repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
softlayer/softlayer-python
SoftLayer/managers/account.py
AccountManager.get_invoices
def get_invoices(self, limit=50, closed=False, get_all=False): """Gets an accounts invoices. :param int limit: Number of invoices to get back in a single call. :param bool closed: If True, will also get CLOSED invoices :param bool get_all: If True, will paginate through invoices until all have been retrieved. :return: Billing_Invoice """ mask = "mask[invoiceTotalAmount, itemCount]" _filter = { 'invoices': { 'createDate': { 'operation': 'orderBy', 'options': [{ 'name': 'sort', 'value': ['DESC'] }] }, 'statusCode': {'operation': 'OPEN'}, } } if closed: del _filter['invoices']['statusCode'] return self.client.call('Account', 'getInvoices', mask=mask, filter=_filter, iter=get_all, limit=limit)
python
def get_invoices(self, limit=50, closed=False, get_all=False): """Gets an accounts invoices. :param int limit: Number of invoices to get back in a single call. :param bool closed: If True, will also get CLOSED invoices :param bool get_all: If True, will paginate through invoices until all have been retrieved. :return: Billing_Invoice """ mask = "mask[invoiceTotalAmount, itemCount]" _filter = { 'invoices': { 'createDate': { 'operation': 'orderBy', 'options': [{ 'name': 'sort', 'value': ['DESC'] }] }, 'statusCode': {'operation': 'OPEN'}, } } if closed: del _filter['invoices']['statusCode'] return self.client.call('Account', 'getInvoices', mask=mask, filter=_filter, iter=get_all, limit=limit)
[ "def", "get_invoices", "(", "self", ",", "limit", "=", "50", ",", "closed", "=", "False", ",", "get_all", "=", "False", ")", ":", "mask", "=", "\"mask[invoiceTotalAmount, itemCount]\"", "_filter", "=", "{", "'invoices'", ":", "{", "'createDate'", ":", "{", "'operation'", ":", "'orderBy'", ",", "'options'", ":", "[", "{", "'name'", ":", "'sort'", ",", "'value'", ":", "[", "'DESC'", "]", "}", "]", "}", ",", "'statusCode'", ":", "{", "'operation'", ":", "'OPEN'", "}", ",", "}", "}", "if", "closed", ":", "del", "_filter", "[", "'invoices'", "]", "[", "'statusCode'", "]", "return", "self", ".", "client", ".", "call", "(", "'Account'", ",", "'getInvoices'", ",", "mask", "=", "mask", ",", "filter", "=", "_filter", ",", "iter", "=", "get_all", ",", "limit", "=", "limit", ")" ]
Gets an accounts invoices. :param int limit: Number of invoices to get back in a single call. :param bool closed: If True, will also get CLOSED invoices :param bool get_all: If True, will paginate through invoices until all have been retrieved. :return: Billing_Invoice
[ "Gets", "an", "accounts", "invoices", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/account.py#L94-L118
train
234,300
softlayer/softlayer-python
SoftLayer/CLI/loadbal/create_options.py
cli
def cli(env): """Get price options to create a load balancer with.""" mgr = SoftLayer.LoadBalancerManager(env.client) table = formatting.Table(['price_id', 'capacity', 'description', 'price']) table.sortby = 'price' table.align['price'] = 'r' table.align['capacity'] = 'r' table.align['id'] = 'r' packages = mgr.get_lb_pkgs() for package in packages: table.add_row([ package['prices'][0]['id'], package.get('capacity'), package['description'], '%.2f' % float(package['prices'][0]['recurringFee']) ]) env.fout(table)
python
def cli(env): """Get price options to create a load balancer with.""" mgr = SoftLayer.LoadBalancerManager(env.client) table = formatting.Table(['price_id', 'capacity', 'description', 'price']) table.sortby = 'price' table.align['price'] = 'r' table.align['capacity'] = 'r' table.align['id'] = 'r' packages = mgr.get_lb_pkgs() for package in packages: table.add_row([ package['prices'][0]['id'], package.get('capacity'), package['description'], '%.2f' % float(package['prices'][0]['recurringFee']) ]) env.fout(table)
[ "def", "cli", "(", "env", ")", ":", "mgr", "=", "SoftLayer", ".", "LoadBalancerManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'price_id'", ",", "'capacity'", ",", "'description'", ",", "'price'", "]", ")", "table", ".", "sortby", "=", "'price'", "table", ".", "align", "[", "'price'", "]", "=", "'r'", "table", ".", "align", "[", "'capacity'", "]", "=", "'r'", "table", ".", "align", "[", "'id'", "]", "=", "'r'", "packages", "=", "mgr", ".", "get_lb_pkgs", "(", ")", "for", "package", "in", "packages", ":", "table", ".", "add_row", "(", "[", "package", "[", "'prices'", "]", "[", "0", "]", "[", "'id'", "]", ",", "package", ".", "get", "(", "'capacity'", ")", ",", "package", "[", "'description'", "]", ",", "'%.2f'", "%", "float", "(", "package", "[", "'prices'", "]", "[", "0", "]", "[", "'recurringFee'", "]", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Get price options to create a load balancer with.
[ "Get", "price", "options", "to", "create", "a", "load", "balancer", "with", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/create_options.py#L13-L35
train
234,301
softlayer/softlayer-python
SoftLayer/CLI/virt/credentials.py
cli
def cli(env, identifier): """List virtual server credentials.""" vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') instance = vsi.get_instance(vs_id) table = formatting.Table(['username', 'password']) for item in instance['operatingSystem']['passwords']: table.add_row([item['username'], item['password']]) env.fout(table)
python
def cli(env, identifier): """List virtual server credentials.""" vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') instance = vsi.get_instance(vs_id) table = formatting.Table(['username', 'password']) for item in instance['operatingSystem']['passwords']: table.add_row([item['username'], item['password']]) env.fout(table)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "vsi", "=", "SoftLayer", ".", "VSManager", "(", "env", ".", "client", ")", "vs_id", "=", "helpers", ".", "resolve_id", "(", "vsi", ".", "resolve_ids", ",", "identifier", ",", "'VS'", ")", "instance", "=", "vsi", ".", "get_instance", "(", "vs_id", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'username'", ",", "'password'", "]", ")", "for", "item", "in", "instance", "[", "'operatingSystem'", "]", "[", "'passwords'", "]", ":", "table", ".", "add_row", "(", "[", "item", "[", "'username'", "]", ",", "item", "[", "'password'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List virtual server credentials.
[ "List", "virtual", "server", "credentials", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/credentials.py#L15-L25
train
234,302
softlayer/softlayer-python
SoftLayer/CLI/dns/record_edit.py
cli
def cli(env, zone_id, by_record, by_id, data, ttl): """Update DNS record.""" manager = SoftLayer.DNSManager(env.client) zone_id = helpers.resolve_id(manager.resolve_ids, zone_id, name='zone') results = manager.get_records(zone_id, host=by_record) for result in results: if by_id and str(result['id']) != by_id: continue result['data'] = data or result['data'] result['ttl'] = ttl or result['ttl'] manager.edit_record(result)
python
def cli(env, zone_id, by_record, by_id, data, ttl): """Update DNS record.""" manager = SoftLayer.DNSManager(env.client) zone_id = helpers.resolve_id(manager.resolve_ids, zone_id, name='zone') results = manager.get_records(zone_id, host=by_record) for result in results: if by_id and str(result['id']) != by_id: continue result['data'] = data or result['data'] result['ttl'] = ttl or result['ttl'] manager.edit_record(result)
[ "def", "cli", "(", "env", ",", "zone_id", ",", "by_record", ",", "by_id", ",", "data", ",", "ttl", ")", ":", "manager", "=", "SoftLayer", ".", "DNSManager", "(", "env", ".", "client", ")", "zone_id", "=", "helpers", ".", "resolve_id", "(", "manager", ".", "resolve_ids", ",", "zone_id", ",", "name", "=", "'zone'", ")", "results", "=", "manager", ".", "get_records", "(", "zone_id", ",", "host", "=", "by_record", ")", "for", "result", "in", "results", ":", "if", "by_id", "and", "str", "(", "result", "[", "'id'", "]", ")", "!=", "by_id", ":", "continue", "result", "[", "'data'", "]", "=", "data", "or", "result", "[", "'data'", "]", "result", "[", "'ttl'", "]", "=", "ttl", "or", "result", "[", "'ttl'", "]", "manager", ".", "edit_record", "(", "result", ")" ]
Update DNS record.
[ "Update", "DNS", "record", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dns/record_edit.py#L21-L33
train
234,303
softlayer/softlayer-python
SoftLayer/CLI/hardware/ready.py
cli
def cli(env, identifier, wait): """Check if a server is ready.""" compute = SoftLayer.HardwareManager(env.client) compute_id = helpers.resolve_id(compute.resolve_ids, identifier, 'hardware') ready = compute.wait_for_ready(compute_id, wait) if ready: env.fout("READY") else: raise exceptions.CLIAbort("Server %s not ready" % compute_id)
python
def cli(env, identifier, wait): """Check if a server is ready.""" compute = SoftLayer.HardwareManager(env.client) compute_id = helpers.resolve_id(compute.resolve_ids, identifier, 'hardware') ready = compute.wait_for_ready(compute_id, wait) if ready: env.fout("READY") else: raise exceptions.CLIAbort("Server %s not ready" % compute_id)
[ "def", "cli", "(", "env", ",", "identifier", ",", "wait", ")", ":", "compute", "=", "SoftLayer", ".", "HardwareManager", "(", "env", ".", "client", ")", "compute_id", "=", "helpers", ".", "resolve_id", "(", "compute", ".", "resolve_ids", ",", "identifier", ",", "'hardware'", ")", "ready", "=", "compute", ".", "wait_for_ready", "(", "compute_id", ",", "wait", ")", "if", "ready", ":", "env", ".", "fout", "(", "\"READY\"", ")", "else", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Server %s not ready\"", "%", "compute_id", ")" ]
Check if a server is ready.
[ "Check", "if", "a", "server", "is", "ready", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/ready.py#L17-L27
train
234,304
softlayer/softlayer-python
SoftLayer/CLI/ticket/summary.py
cli
def cli(env): """Summary info about tickets.""" mask = ('openTicketCount, closedTicketCount, ' 'openBillingTicketCount, openOtherTicketCount, ' 'openSalesTicketCount, openSupportTicketCount, ' 'openAccountingTicketCount') account = env.client['Account'].getObject(mask=mask) table = formatting.Table(['Status', 'count']) nested = formatting.Table(['Type', 'count']) nested.add_row(['Accounting', account['openAccountingTicketCount']]) nested.add_row(['Billing', account['openBillingTicketCount']]) nested.add_row(['Sales', account['openSalesTicketCount']]) nested.add_row(['Support', account['openSupportTicketCount']]) nested.add_row(['Other', account['openOtherTicketCount']]) nested.add_row(['Total', account['openTicketCount']]) table.add_row(['Open', nested]) table.add_row(['Closed', account['closedTicketCount']]) env.fout(table)
python
def cli(env): """Summary info about tickets.""" mask = ('openTicketCount, closedTicketCount, ' 'openBillingTicketCount, openOtherTicketCount, ' 'openSalesTicketCount, openSupportTicketCount, ' 'openAccountingTicketCount') account = env.client['Account'].getObject(mask=mask) table = formatting.Table(['Status', 'count']) nested = formatting.Table(['Type', 'count']) nested.add_row(['Accounting', account['openAccountingTicketCount']]) nested.add_row(['Billing', account['openBillingTicketCount']]) nested.add_row(['Sales', account['openSalesTicketCount']]) nested.add_row(['Support', account['openSupportTicketCount']]) nested.add_row(['Other', account['openOtherTicketCount']]) nested.add_row(['Total', account['openTicketCount']]) table.add_row(['Open', nested]) table.add_row(['Closed', account['closedTicketCount']]) env.fout(table)
[ "def", "cli", "(", "env", ")", ":", "mask", "=", "(", "'openTicketCount, closedTicketCount, '", "'openBillingTicketCount, openOtherTicketCount, '", "'openSalesTicketCount, openSupportTicketCount, '", "'openAccountingTicketCount'", ")", "account", "=", "env", ".", "client", "[", "'Account'", "]", ".", "getObject", "(", "mask", "=", "mask", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'Status'", ",", "'count'", "]", ")", "nested", "=", "formatting", ".", "Table", "(", "[", "'Type'", ",", "'count'", "]", ")", "nested", ".", "add_row", "(", "[", "'Accounting'", ",", "account", "[", "'openAccountingTicketCount'", "]", "]", ")", "nested", ".", "add_row", "(", "[", "'Billing'", ",", "account", "[", "'openBillingTicketCount'", "]", "]", ")", "nested", ".", "add_row", "(", "[", "'Sales'", ",", "account", "[", "'openSalesTicketCount'", "]", "]", ")", "nested", ".", "add_row", "(", "[", "'Support'", ",", "account", "[", "'openSupportTicketCount'", "]", "]", ")", "nested", ".", "add_row", "(", "[", "'Other'", ",", "account", "[", "'openOtherTicketCount'", "]", "]", ")", "nested", ".", "add_row", "(", "[", "'Total'", ",", "account", "[", "'openTicketCount'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'Open'", ",", "nested", "]", ")", "table", ".", "add_row", "(", "[", "'Closed'", ",", "account", "[", "'closedTicketCount'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Summary info about tickets.
[ "Summary", "info", "about", "tickets", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ticket/summary.py#L12-L33
train
234,305
softlayer/softlayer-python
SoftLayer/CLI/globalip/list.py
cli
def cli(env, ip_version): """List all global IPs.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table(['id', 'ip', 'assigned', 'target']) version = None if ip_version == 'v4': version = 4 elif ip_version == 'v6': version = 6 ips = mgr.list_global_ips(version=version) for ip_address in ips: assigned = 'No' target = 'None' if ip_address.get('destinationIpAddress'): dest = ip_address['destinationIpAddress'] assigned = 'Yes' target = dest['ipAddress'] virtual_guest = dest.get('virtualGuest') if virtual_guest: target += (' (%s)' % virtual_guest['fullyQualifiedDomainName']) elif ip_address['destinationIpAddress'].get('hardware'): target += (' (%s)' % dest['hardware']['fullyQualifiedDomainName']) table.add_row([ip_address['id'], ip_address['ipAddress']['ipAddress'], assigned, target]) env.fout(table)
python
def cli(env, ip_version): """List all global IPs.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table(['id', 'ip', 'assigned', 'target']) version = None if ip_version == 'v4': version = 4 elif ip_version == 'v6': version = 6 ips = mgr.list_global_ips(version=version) for ip_address in ips: assigned = 'No' target = 'None' if ip_address.get('destinationIpAddress'): dest = ip_address['destinationIpAddress'] assigned = 'Yes' target = dest['ipAddress'] virtual_guest = dest.get('virtualGuest') if virtual_guest: target += (' (%s)' % virtual_guest['fullyQualifiedDomainName']) elif ip_address['destinationIpAddress'].get('hardware'): target += (' (%s)' % dest['hardware']['fullyQualifiedDomainName']) table.add_row([ip_address['id'], ip_address['ipAddress']['ipAddress'], assigned, target]) env.fout(table)
[ "def", "cli", "(", "env", ",", "ip_version", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'ip'", ",", "'assigned'", ",", "'target'", "]", ")", "version", "=", "None", "if", "ip_version", "==", "'v4'", ":", "version", "=", "4", "elif", "ip_version", "==", "'v6'", ":", "version", "=", "6", "ips", "=", "mgr", ".", "list_global_ips", "(", "version", "=", "version", ")", "for", "ip_address", "in", "ips", ":", "assigned", "=", "'No'", "target", "=", "'None'", "if", "ip_address", ".", "get", "(", "'destinationIpAddress'", ")", ":", "dest", "=", "ip_address", "[", "'destinationIpAddress'", "]", "assigned", "=", "'Yes'", "target", "=", "dest", "[", "'ipAddress'", "]", "virtual_guest", "=", "dest", ".", "get", "(", "'virtualGuest'", ")", "if", "virtual_guest", ":", "target", "+=", "(", "' (%s)'", "%", "virtual_guest", "[", "'fullyQualifiedDomainName'", "]", ")", "elif", "ip_address", "[", "'destinationIpAddress'", "]", ".", "get", "(", "'hardware'", ")", ":", "target", "+=", "(", "' (%s)'", "%", "dest", "[", "'hardware'", "]", "[", "'fullyQualifiedDomainName'", "]", ")", "table", ".", "add_row", "(", "[", "ip_address", "[", "'id'", "]", ",", "ip_address", "[", "'ipAddress'", "]", "[", "'ipAddress'", "]", ",", "assigned", ",", "target", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List all global IPs.
[ "List", "all", "global", "IPs", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/globalip/list.py#L16-L50
train
234,306
softlayer/softlayer-python
SoftLayer/CLI/globalip/cancel.py
cli
def cli(env, identifier): """Cancel global IP.""" mgr = SoftLayer.NetworkManager(env.client) global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier, name='global ip') if not (env.skip_confirmations or formatting.no_going_back(global_ip_id)): raise exceptions.CLIAbort('Aborted') mgr.cancel_global_ip(global_ip_id)
python
def cli(env, identifier): """Cancel global IP.""" mgr = SoftLayer.NetworkManager(env.client) global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier, name='global ip') if not (env.skip_confirmations or formatting.no_going_back(global_ip_id)): raise exceptions.CLIAbort('Aborted') mgr.cancel_global_ip(global_ip_id)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "global_ip_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_global_ip_ids", ",", "identifier", ",", "name", "=", "'global ip'", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "no_going_back", "(", "global_ip_id", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted'", ")", "mgr", ".", "cancel_global_ip", "(", "global_ip_id", ")" ]
Cancel global IP.
[ "Cancel", "global", "IP", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/globalip/cancel.py#L16-L26
train
234,307
softlayer/softlayer-python
SoftLayer/API.py
create_client_from_env
def create_client_from_env(username=None, api_key=None, endpoint_url=None, timeout=None, auth=None, config_file=None, proxy=None, user_agent=None, transport=None, verify=True): """Creates a SoftLayer API client using your environment. Settings are loaded via keyword arguments, environemtal variables and config file. :param username: an optional API username if you wish to bypass the package's built-in username :param api_key: an optional API key if you wish to bypass the package's built in API key :param endpoint_url: the API endpoint base URL you wish to connect to. Set this to API_PRIVATE_ENDPOINT to connect via SoftLayer's private network. :param proxy: proxy to be used to make API calls :param integer timeout: timeout for API requests :param auth: an object which responds to get_headers() to be inserted into the xml-rpc headers. Example: `BasicAuthentication` :param config_file: A path to a configuration file used to load settings :param user_agent: an optional User Agent to report when making API calls if you wish to bypass the packages built in User Agent string :param transport: An object that's callable with this signature: transport(SoftLayer.transports.Request) :param bool verify: decide to verify the server's SSL/TLS cert. DO NOT SET TO FALSE WITHOUT UNDERSTANDING THE IMPLICATIONS. Usage: >>> import SoftLayer >>> client = SoftLayer.create_client_from_env() >>> resp = client.call('Account', 'getObject') >>> resp['companyName'] 'Your Company' """ settings = config.get_client_settings(username=username, api_key=api_key, endpoint_url=endpoint_url, timeout=timeout, proxy=proxy, verify=verify, config_file=config_file) if transport is None: url = settings.get('endpoint_url') if url is not None and '/rest' in url: # If this looks like a rest endpoint, use the rest transport transport = transports.RestTransport( endpoint_url=settings.get('endpoint_url'), proxy=settings.get('proxy'), timeout=settings.get('timeout'), user_agent=user_agent, verify=verify, ) else: # Default the transport to use XMLRPC transport = transports.XmlRpcTransport( endpoint_url=settings.get('endpoint_url'), proxy=settings.get('proxy'), timeout=settings.get('timeout'), user_agent=user_agent, verify=verify, ) # If we have enough information to make an auth driver, let's do it if auth is None and settings.get('username') and settings.get('api_key'): # NOTE(kmcdonald): some transports mask other transports, so this is # a way to find the 'real' one real_transport = getattr(transport, 'transport', transport) if isinstance(real_transport, transports.XmlRpcTransport): auth = slauth.BasicAuthentication( settings.get('username'), settings.get('api_key'), ) elif isinstance(real_transport, transports.RestTransport): auth = slauth.BasicHTTPAuthentication( settings.get('username'), settings.get('api_key'), ) return BaseClient(auth=auth, transport=transport)
python
def create_client_from_env(username=None, api_key=None, endpoint_url=None, timeout=None, auth=None, config_file=None, proxy=None, user_agent=None, transport=None, verify=True): """Creates a SoftLayer API client using your environment. Settings are loaded via keyword arguments, environemtal variables and config file. :param username: an optional API username if you wish to bypass the package's built-in username :param api_key: an optional API key if you wish to bypass the package's built in API key :param endpoint_url: the API endpoint base URL you wish to connect to. Set this to API_PRIVATE_ENDPOINT to connect via SoftLayer's private network. :param proxy: proxy to be used to make API calls :param integer timeout: timeout for API requests :param auth: an object which responds to get_headers() to be inserted into the xml-rpc headers. Example: `BasicAuthentication` :param config_file: A path to a configuration file used to load settings :param user_agent: an optional User Agent to report when making API calls if you wish to bypass the packages built in User Agent string :param transport: An object that's callable with this signature: transport(SoftLayer.transports.Request) :param bool verify: decide to verify the server's SSL/TLS cert. DO NOT SET TO FALSE WITHOUT UNDERSTANDING THE IMPLICATIONS. Usage: >>> import SoftLayer >>> client = SoftLayer.create_client_from_env() >>> resp = client.call('Account', 'getObject') >>> resp['companyName'] 'Your Company' """ settings = config.get_client_settings(username=username, api_key=api_key, endpoint_url=endpoint_url, timeout=timeout, proxy=proxy, verify=verify, config_file=config_file) if transport is None: url = settings.get('endpoint_url') if url is not None and '/rest' in url: # If this looks like a rest endpoint, use the rest transport transport = transports.RestTransport( endpoint_url=settings.get('endpoint_url'), proxy=settings.get('proxy'), timeout=settings.get('timeout'), user_agent=user_agent, verify=verify, ) else: # Default the transport to use XMLRPC transport = transports.XmlRpcTransport( endpoint_url=settings.get('endpoint_url'), proxy=settings.get('proxy'), timeout=settings.get('timeout'), user_agent=user_agent, verify=verify, ) # If we have enough information to make an auth driver, let's do it if auth is None and settings.get('username') and settings.get('api_key'): # NOTE(kmcdonald): some transports mask other transports, so this is # a way to find the 'real' one real_transport = getattr(transport, 'transport', transport) if isinstance(real_transport, transports.XmlRpcTransport): auth = slauth.BasicAuthentication( settings.get('username'), settings.get('api_key'), ) elif isinstance(real_transport, transports.RestTransport): auth = slauth.BasicHTTPAuthentication( settings.get('username'), settings.get('api_key'), ) return BaseClient(auth=auth, transport=transport)
[ "def", "create_client_from_env", "(", "username", "=", "None", ",", "api_key", "=", "None", ",", "endpoint_url", "=", "None", ",", "timeout", "=", "None", ",", "auth", "=", "None", ",", "config_file", "=", "None", ",", "proxy", "=", "None", ",", "user_agent", "=", "None", ",", "transport", "=", "None", ",", "verify", "=", "True", ")", ":", "settings", "=", "config", ".", "get_client_settings", "(", "username", "=", "username", ",", "api_key", "=", "api_key", ",", "endpoint_url", "=", "endpoint_url", ",", "timeout", "=", "timeout", ",", "proxy", "=", "proxy", ",", "verify", "=", "verify", ",", "config_file", "=", "config_file", ")", "if", "transport", "is", "None", ":", "url", "=", "settings", ".", "get", "(", "'endpoint_url'", ")", "if", "url", "is", "not", "None", "and", "'/rest'", "in", "url", ":", "# If this looks like a rest endpoint, use the rest transport", "transport", "=", "transports", ".", "RestTransport", "(", "endpoint_url", "=", "settings", ".", "get", "(", "'endpoint_url'", ")", ",", "proxy", "=", "settings", ".", "get", "(", "'proxy'", ")", ",", "timeout", "=", "settings", ".", "get", "(", "'timeout'", ")", ",", "user_agent", "=", "user_agent", ",", "verify", "=", "verify", ",", ")", "else", ":", "# Default the transport to use XMLRPC", "transport", "=", "transports", ".", "XmlRpcTransport", "(", "endpoint_url", "=", "settings", ".", "get", "(", "'endpoint_url'", ")", ",", "proxy", "=", "settings", ".", "get", "(", "'proxy'", ")", ",", "timeout", "=", "settings", ".", "get", "(", "'timeout'", ")", ",", "user_agent", "=", "user_agent", ",", "verify", "=", "verify", ",", ")", "# If we have enough information to make an auth driver, let's do it", "if", "auth", "is", "None", "and", "settings", ".", "get", "(", "'username'", ")", "and", "settings", ".", "get", "(", "'api_key'", ")", ":", "# NOTE(kmcdonald): some transports mask other transports, so this is", "# a way to find the 'real' one", "real_transport", "=", "getattr", "(", "transport", ",", "'transport'", ",", "transport", ")", "if", "isinstance", "(", "real_transport", ",", "transports", ".", "XmlRpcTransport", ")", ":", "auth", "=", "slauth", ".", "BasicAuthentication", "(", "settings", ".", "get", "(", "'username'", ")", ",", "settings", ".", "get", "(", "'api_key'", ")", ",", ")", "elif", "isinstance", "(", "real_transport", ",", "transports", ".", "RestTransport", ")", ":", "auth", "=", "slauth", ".", "BasicHTTPAuthentication", "(", "settings", ".", "get", "(", "'username'", ")", ",", "settings", ".", "get", "(", "'api_key'", ")", ",", ")", "return", "BaseClient", "(", "auth", "=", "auth", ",", "transport", "=", "transport", ")" ]
Creates a SoftLayer API client using your environment. Settings are loaded via keyword arguments, environemtal variables and config file. :param username: an optional API username if you wish to bypass the package's built-in username :param api_key: an optional API key if you wish to bypass the package's built in API key :param endpoint_url: the API endpoint base URL you wish to connect to. Set this to API_PRIVATE_ENDPOINT to connect via SoftLayer's private network. :param proxy: proxy to be used to make API calls :param integer timeout: timeout for API requests :param auth: an object which responds to get_headers() to be inserted into the xml-rpc headers. Example: `BasicAuthentication` :param config_file: A path to a configuration file used to load settings :param user_agent: an optional User Agent to report when making API calls if you wish to bypass the packages built in User Agent string :param transport: An object that's callable with this signature: transport(SoftLayer.transports.Request) :param bool verify: decide to verify the server's SSL/TLS cert. DO NOT SET TO FALSE WITHOUT UNDERSTANDING THE IMPLICATIONS. Usage: >>> import SoftLayer >>> client = SoftLayer.create_client_from_env() >>> resp = client.call('Account', 'getObject') >>> resp['companyName'] 'Your Company'
[ "Creates", "a", "SoftLayer", "API", "client", "using", "your", "environment", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/API.py#L41-L131
train
234,308
softlayer/softlayer-python
SoftLayer/API.py
BaseClient.call
def call(self, service, method, *args, **kwargs): """Make a SoftLayer API call. :param method: the method to call on the service :param \\*args: (optional) arguments for the remote call :param id: (optional) id for the resource :param mask: (optional) object mask :param dict filter: (optional) filter dict :param dict headers: (optional) optional XML-RPC headers :param boolean compress: (optional) Enable/Disable HTTP compression :param dict raw_headers: (optional) HTTP transport headers :param int limit: (optional) return at most this many results :param int offset: (optional) offset results by this many :param boolean iter: (optional) if True, returns a generator with the results :param bool verify: verify SSL cert :param cert: client certificate path Usage: >>> import SoftLayer >>> client = SoftLayer.create_client_from_env() >>> client.call('Account', 'getVirtualGuests', mask="id", limit=10) [...] """ if kwargs.pop('iter', False): # Most of the codebase assumes a non-generator will be returned, so casting to list # keeps those sections working return list(self.iter_call(service, method, *args, **kwargs)) invalid_kwargs = set(kwargs.keys()) - VALID_CALL_ARGS if invalid_kwargs: raise TypeError( 'Invalid keyword arguments: %s' % ','.join(invalid_kwargs)) if self._prefix and not service.startswith(self._prefix): service = self._prefix + service http_headers = {'Accept': '*/*'} if kwargs.get('compress', True): http_headers['Accept-Encoding'] = 'gzip, deflate, compress' else: http_headers['Accept-Encoding'] = None if kwargs.get('raw_headers'): http_headers.update(kwargs.get('raw_headers')) request = transports.Request() request.service = service request.method = method request.args = args request.transport_headers = http_headers request.identifier = kwargs.get('id') request.mask = kwargs.get('mask') request.filter = kwargs.get('filter') request.limit = kwargs.get('limit') request.offset = kwargs.get('offset') if kwargs.get('verify') is not None: request.verify = kwargs.get('verify') if self.auth: extra_headers = self.auth.get_headers() if extra_headers: warnings.warn("auth.get_headers() is deprecated and will be " "removed in the next major version", DeprecationWarning) request.headers.update(extra_headers) request = self.auth.get_request(request) request.headers.update(kwargs.get('headers', {})) return self.transport(request)
python
def call(self, service, method, *args, **kwargs): """Make a SoftLayer API call. :param method: the method to call on the service :param \\*args: (optional) arguments for the remote call :param id: (optional) id for the resource :param mask: (optional) object mask :param dict filter: (optional) filter dict :param dict headers: (optional) optional XML-RPC headers :param boolean compress: (optional) Enable/Disable HTTP compression :param dict raw_headers: (optional) HTTP transport headers :param int limit: (optional) return at most this many results :param int offset: (optional) offset results by this many :param boolean iter: (optional) if True, returns a generator with the results :param bool verify: verify SSL cert :param cert: client certificate path Usage: >>> import SoftLayer >>> client = SoftLayer.create_client_from_env() >>> client.call('Account', 'getVirtualGuests', mask="id", limit=10) [...] """ if kwargs.pop('iter', False): # Most of the codebase assumes a non-generator will be returned, so casting to list # keeps those sections working return list(self.iter_call(service, method, *args, **kwargs)) invalid_kwargs = set(kwargs.keys()) - VALID_CALL_ARGS if invalid_kwargs: raise TypeError( 'Invalid keyword arguments: %s' % ','.join(invalid_kwargs)) if self._prefix and not service.startswith(self._prefix): service = self._prefix + service http_headers = {'Accept': '*/*'} if kwargs.get('compress', True): http_headers['Accept-Encoding'] = 'gzip, deflate, compress' else: http_headers['Accept-Encoding'] = None if kwargs.get('raw_headers'): http_headers.update(kwargs.get('raw_headers')) request = transports.Request() request.service = service request.method = method request.args = args request.transport_headers = http_headers request.identifier = kwargs.get('id') request.mask = kwargs.get('mask') request.filter = kwargs.get('filter') request.limit = kwargs.get('limit') request.offset = kwargs.get('offset') if kwargs.get('verify') is not None: request.verify = kwargs.get('verify') if self.auth: extra_headers = self.auth.get_headers() if extra_headers: warnings.warn("auth.get_headers() is deprecated and will be " "removed in the next major version", DeprecationWarning) request.headers.update(extra_headers) request = self.auth.get_request(request) request.headers.update(kwargs.get('headers', {})) return self.transport(request)
[ "def", "call", "(", "self", ",", "service", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "pop", "(", "'iter'", ",", "False", ")", ":", "# Most of the codebase assumes a non-generator will be returned, so casting to list", "# keeps those sections working", "return", "list", "(", "self", ".", "iter_call", "(", "service", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ")", "invalid_kwargs", "=", "set", "(", "kwargs", ".", "keys", "(", ")", ")", "-", "VALID_CALL_ARGS", "if", "invalid_kwargs", ":", "raise", "TypeError", "(", "'Invalid keyword arguments: %s'", "%", "','", ".", "join", "(", "invalid_kwargs", ")", ")", "if", "self", ".", "_prefix", "and", "not", "service", ".", "startswith", "(", "self", ".", "_prefix", ")", ":", "service", "=", "self", ".", "_prefix", "+", "service", "http_headers", "=", "{", "'Accept'", ":", "'*/*'", "}", "if", "kwargs", ".", "get", "(", "'compress'", ",", "True", ")", ":", "http_headers", "[", "'Accept-Encoding'", "]", "=", "'gzip, deflate, compress'", "else", ":", "http_headers", "[", "'Accept-Encoding'", "]", "=", "None", "if", "kwargs", ".", "get", "(", "'raw_headers'", ")", ":", "http_headers", ".", "update", "(", "kwargs", ".", "get", "(", "'raw_headers'", ")", ")", "request", "=", "transports", ".", "Request", "(", ")", "request", ".", "service", "=", "service", "request", ".", "method", "=", "method", "request", ".", "args", "=", "args", "request", ".", "transport_headers", "=", "http_headers", "request", ".", "identifier", "=", "kwargs", ".", "get", "(", "'id'", ")", "request", ".", "mask", "=", "kwargs", ".", "get", "(", "'mask'", ")", "request", ".", "filter", "=", "kwargs", ".", "get", "(", "'filter'", ")", "request", ".", "limit", "=", "kwargs", ".", "get", "(", "'limit'", ")", "request", ".", "offset", "=", "kwargs", ".", "get", "(", "'offset'", ")", "if", "kwargs", ".", "get", "(", "'verify'", ")", "is", "not", "None", ":", "request", ".", "verify", "=", "kwargs", ".", "get", "(", "'verify'", ")", "if", "self", ".", "auth", ":", "extra_headers", "=", "self", ".", "auth", ".", "get_headers", "(", ")", "if", "extra_headers", ":", "warnings", ".", "warn", "(", "\"auth.get_headers() is deprecated and will be \"", "\"removed in the next major version\"", ",", "DeprecationWarning", ")", "request", ".", "headers", ".", "update", "(", "extra_headers", ")", "request", "=", "self", ".", "auth", ".", "get_request", "(", "request", ")", "request", ".", "headers", ".", "update", "(", "kwargs", ".", "get", "(", "'headers'", ",", "{", "}", ")", ")", "return", "self", ".", "transport", "(", "request", ")" ]
Make a SoftLayer API call. :param method: the method to call on the service :param \\*args: (optional) arguments for the remote call :param id: (optional) id for the resource :param mask: (optional) object mask :param dict filter: (optional) filter dict :param dict headers: (optional) optional XML-RPC headers :param boolean compress: (optional) Enable/Disable HTTP compression :param dict raw_headers: (optional) HTTP transport headers :param int limit: (optional) return at most this many results :param int offset: (optional) offset results by this many :param boolean iter: (optional) if True, returns a generator with the results :param bool verify: verify SSL cert :param cert: client certificate path Usage: >>> import SoftLayer >>> client = SoftLayer.create_client_from_env() >>> client.call('Account', 'getVirtualGuests', mask="id", limit=10) [...]
[ "Make", "a", "SoftLayer", "API", "call", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/API.py#L193-L265
train
234,309
softlayer/softlayer-python
SoftLayer/API.py
Service.call
def call(self, name, *args, **kwargs): """Make a SoftLayer API call :param service: the name of the SoftLayer API service :param method: the method to call on the service :param \\*args: same optional arguments that ``BaseClient.call`` takes :param \\*\\*kwargs: same optional keyword arguments that ``BaseClient.call`` takes :param service: the name of the SoftLayer API service Usage: >>> import SoftLayer >>> client = SoftLayer.create_client_from_env() >>> client['Account'].getVirtualGuests(mask="id", limit=10) [...] """ return self.client.call(self.name, name, *args, **kwargs)
python
def call(self, name, *args, **kwargs): """Make a SoftLayer API call :param service: the name of the SoftLayer API service :param method: the method to call on the service :param \\*args: same optional arguments that ``BaseClient.call`` takes :param \\*\\*kwargs: same optional keyword arguments that ``BaseClient.call`` takes :param service: the name of the SoftLayer API service Usage: >>> import SoftLayer >>> client = SoftLayer.create_client_from_env() >>> client['Account'].getVirtualGuests(mask="id", limit=10) [...] """ return self.client.call(self.name, name, *args, **kwargs)
[ "def", "call", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "client", ".", "call", "(", "self", ".", "name", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Make a SoftLayer API call :param service: the name of the SoftLayer API service :param method: the method to call on the service :param \\*args: same optional arguments that ``BaseClient.call`` takes :param \\*\\*kwargs: same optional keyword arguments that ``BaseClient.call`` takes :param service: the name of the SoftLayer API service Usage: >>> import SoftLayer >>> client = SoftLayer.create_client_from_env() >>> client['Account'].getVirtualGuests(mask="id", limit=10) [...]
[ "Make", "a", "SoftLayer", "API", "call" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/API.py#L339-L357
train
234,310
softlayer/softlayer-python
SoftLayer/CLI/object_storage/credential/list.py
cli
def cli(env, identifier): """Retrieve credentials used for generating an AWS signature. Max of 2.""" mgr = SoftLayer.ObjectStorageManager(env.client) credential_list = mgr.list_credential(identifier) table = formatting.Table(['id', 'password', 'username', 'type_name']) for credential in credential_list: table.add_row([ credential['id'], credential['password'], credential['username'], credential['type']['name'] ]) env.fout(table)
python
def cli(env, identifier): """Retrieve credentials used for generating an AWS signature. Max of 2.""" mgr = SoftLayer.ObjectStorageManager(env.client) credential_list = mgr.list_credential(identifier) table = formatting.Table(['id', 'password', 'username', 'type_name']) for credential in credential_list: table.add_row([ credential['id'], credential['password'], credential['username'], credential['type']['name'] ]) env.fout(table)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "ObjectStorageManager", "(", "env", ".", "client", ")", "credential_list", "=", "mgr", ".", "list_credential", "(", "identifier", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'password'", ",", "'username'", ",", "'type_name'", "]", ")", "for", "credential", "in", "credential_list", ":", "table", ".", "add_row", "(", "[", "credential", "[", "'id'", "]", ",", "credential", "[", "'password'", "]", ",", "credential", "[", "'username'", "]", ",", "credential", "[", "'type'", "]", "[", "'name'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Retrieve credentials used for generating an AWS signature. Max of 2.
[ "Retrieve", "credentials", "used", "for", "generating", "an", "AWS", "signature", ".", "Max", "of", "2", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/object_storage/credential/list.py#L14-L29
train
234,311
softlayer/softlayer-python
SoftLayer/CLI/dedicatedhost/list.py
cli
def cli(env, sortby, cpu, columns, datacenter, name, memory, disk, tag): """List dedicated host.""" mgr = SoftLayer.DedicatedHostManager(env.client) hosts = mgr.list_instances(cpus=cpu, datacenter=datacenter, hostname=name, memory=memory, disk=disk, tags=tag, mask=columns.mask()) table = formatting.Table(columns.columns) table.sortby = sortby for host in hosts: table.add_row([value or formatting.blank() for value in columns.row(host)]) env.fout(table)
python
def cli(env, sortby, cpu, columns, datacenter, name, memory, disk, tag): """List dedicated host.""" mgr = SoftLayer.DedicatedHostManager(env.client) hosts = mgr.list_instances(cpus=cpu, datacenter=datacenter, hostname=name, memory=memory, disk=disk, tags=tag, mask=columns.mask()) table = formatting.Table(columns.columns) table.sortby = sortby for host in hosts: table.add_row([value or formatting.blank() for value in columns.row(host)]) env.fout(table)
[ "def", "cli", "(", "env", ",", "sortby", ",", "cpu", ",", "columns", ",", "datacenter", ",", "name", ",", "memory", ",", "disk", ",", "tag", ")", ":", "mgr", "=", "SoftLayer", ".", "DedicatedHostManager", "(", "env", ".", "client", ")", "hosts", "=", "mgr", ".", "list_instances", "(", "cpus", "=", "cpu", ",", "datacenter", "=", "datacenter", ",", "hostname", "=", "name", ",", "memory", "=", "memory", ",", "disk", "=", "disk", ",", "tags", "=", "tag", ",", "mask", "=", "columns", ".", "mask", "(", ")", ")", "table", "=", "formatting", ".", "Table", "(", "columns", ".", "columns", ")", "table", ".", "sortby", "=", "sortby", "for", "host", "in", "hosts", ":", "table", ".", "add_row", "(", "[", "value", "or", "formatting", ".", "blank", "(", ")", "for", "value", "in", "columns", ".", "row", "(", "host", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List dedicated host.
[ "List", "dedicated", "host", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dedicatedhost/list.py#L52-L70
train
234,312
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.input
def input(self, prompt, default=None, show_default=True): """Provide a command prompt.""" return click.prompt(prompt, default=default, show_default=show_default)
python
def input(self, prompt, default=None, show_default=True): """Provide a command prompt.""" return click.prompt(prompt, default=default, show_default=show_default)
[ "def", "input", "(", "self", ",", "prompt", ",", "default", "=", "None", ",", "show_default", "=", "True", ")", ":", "return", "click", ".", "prompt", "(", "prompt", ",", "default", "=", "default", ",", "show_default", "=", "show_default", ")" ]
Provide a command prompt.
[ "Provide", "a", "command", "prompt", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L58-L60
train
234,313
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.getpass
def getpass(self, prompt, default=None): """Provide a password prompt.""" return click.prompt(prompt, hide_input=True, default=default)
python
def getpass(self, prompt, default=None): """Provide a password prompt.""" return click.prompt(prompt, hide_input=True, default=default)
[ "def", "getpass", "(", "self", ",", "prompt", ",", "default", "=", "None", ")", ":", "return", "click", ".", "prompt", "(", "prompt", ",", "hide_input", "=", "True", ",", "default", "=", "default", ")" ]
Provide a password prompt.
[ "Provide", "a", "password", "prompt", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L62-L64
train
234,314
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.list_commands
def list_commands(self, *path): """Command listing.""" path_str = ':'.join(path) commands = [] for command in self.commands: # Filter based on prefix and the segment length if all([command.startswith(path_str), len(path) == command.count(":")]): # offset is used to exclude the path that the caller requested. offset = len(path_str) + 1 if path_str else 0 commands.append(command[offset:]) return sorted(commands)
python
def list_commands(self, *path): """Command listing.""" path_str = ':'.join(path) commands = [] for command in self.commands: # Filter based on prefix and the segment length if all([command.startswith(path_str), len(path) == command.count(":")]): # offset is used to exclude the path that the caller requested. offset = len(path_str) + 1 if path_str else 0 commands.append(command[offset:]) return sorted(commands)
[ "def", "list_commands", "(", "self", ",", "*", "path", ")", ":", "path_str", "=", "':'", ".", "join", "(", "path", ")", "commands", "=", "[", "]", "for", "command", "in", "self", ".", "commands", ":", "# Filter based on prefix and the segment length", "if", "all", "(", "[", "command", ".", "startswith", "(", "path_str", ")", ",", "len", "(", "path", ")", "==", "command", ".", "count", "(", "\":\"", ")", "]", ")", ":", "# offset is used to exclude the path that the caller requested.", "offset", "=", "len", "(", "path_str", ")", "+", "1", "if", "path_str", "else", "0", "commands", ".", "append", "(", "command", "[", "offset", ":", "]", ")", "return", "sorted", "(", "commands", ")" ]
Command listing.
[ "Command", "listing", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L67-L82
train
234,315
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.get_command
def get_command(self, *path): """Return command at the given path or raise error.""" path_str = ':'.join(path) if path_str in self.commands: return self.commands[path_str].load() return None
python
def get_command(self, *path): """Return command at the given path or raise error.""" path_str = ':'.join(path) if path_str in self.commands: return self.commands[path_str].load() return None
[ "def", "get_command", "(", "self", ",", "*", "path", ")", ":", "path_str", "=", "':'", ".", "join", "(", "path", ")", "if", "path_str", "in", "self", ".", "commands", ":", "return", "self", ".", "commands", "[", "path_str", "]", ".", "load", "(", ")", "return", "None" ]
Return command at the given path or raise error.
[ "Return", "command", "at", "the", "given", "path", "or", "raise", "error", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L84-L91
train
234,316
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.resolve_alias
def resolve_alias(self, path_str): """Returns the actual command name. Uses the alias mapping.""" if path_str in self.aliases: return self.aliases[path_str] return path_str
python
def resolve_alias(self, path_str): """Returns the actual command name. Uses the alias mapping.""" if path_str in self.aliases: return self.aliases[path_str] return path_str
[ "def", "resolve_alias", "(", "self", ",", "path_str", ")", ":", "if", "path_str", "in", "self", ".", "aliases", ":", "return", "self", ".", "aliases", "[", "path_str", "]", "return", "path_str" ]
Returns the actual command name. Uses the alias mapping.
[ "Returns", "the", "actual", "command", "name", ".", "Uses", "the", "alias", "mapping", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L93-L97
train
234,317
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.load
def load(self): """Loads all modules.""" if self._modules_loaded is True: return self.load_modules_from_python(routes.ALL_ROUTES) self.aliases.update(routes.ALL_ALIASES) self._load_modules_from_entry_points('softlayer.cli') self._modules_loaded = True
python
def load(self): """Loads all modules.""" if self._modules_loaded is True: return self.load_modules_from_python(routes.ALL_ROUTES) self.aliases.update(routes.ALL_ALIASES) self._load_modules_from_entry_points('softlayer.cli') self._modules_loaded = True
[ "def", "load", "(", "self", ")", ":", "if", "self", ".", "_modules_loaded", "is", "True", ":", "return", "self", ".", "load_modules_from_python", "(", "routes", ".", "ALL_ROUTES", ")", "self", ".", "aliases", ".", "update", "(", "routes", ".", "ALL_ALIASES", ")", "self", ".", "_load_modules_from_entry_points", "(", "'softlayer.cli'", ")", "self", ".", "_modules_loaded", "=", "True" ]
Loads all modules.
[ "Loads", "all", "modules", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L99-L108
train
234,318
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.load_modules_from_python
def load_modules_from_python(self, route_list): """Load modules from the native python source.""" for name, modpath in route_list: if ':' in modpath: path, attr = modpath.split(':', 1) else: path, attr = modpath, None self.commands[name] = ModuleLoader(path, attr=attr)
python
def load_modules_from_python(self, route_list): """Load modules from the native python source.""" for name, modpath in route_list: if ':' in modpath: path, attr = modpath.split(':', 1) else: path, attr = modpath, None self.commands[name] = ModuleLoader(path, attr=attr)
[ "def", "load_modules_from_python", "(", "self", ",", "route_list", ")", ":", "for", "name", ",", "modpath", "in", "route_list", ":", "if", "':'", "in", "modpath", ":", "path", ",", "attr", "=", "modpath", ".", "split", "(", "':'", ",", "1", ")", "else", ":", "path", ",", "attr", "=", "modpath", ",", "None", "self", ".", "commands", "[", "name", "]", "=", "ModuleLoader", "(", "path", ",", "attr", "=", "attr", ")" ]
Load modules from the native python source.
[ "Load", "modules", "from", "the", "native", "python", "source", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L110-L117
train
234,319
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.ensure_client
def ensure_client(self, config_file=None, is_demo=False, proxy=None): """Create a new SLAPI client to the environment. This will be a no-op if there is already a client in this environment. """ if self.client is not None: return # Environment can be passed in explicitly. This is used for testing if is_demo: client = SoftLayer.BaseClient( transport=SoftLayer.FixtureTransport(), auth=None, ) else: # Create SL Client client = SoftLayer.create_client_from_env( proxy=proxy, config_file=config_file, ) self.client = client
python
def ensure_client(self, config_file=None, is_demo=False, proxy=None): """Create a new SLAPI client to the environment. This will be a no-op if there is already a client in this environment. """ if self.client is not None: return # Environment can be passed in explicitly. This is used for testing if is_demo: client = SoftLayer.BaseClient( transport=SoftLayer.FixtureTransport(), auth=None, ) else: # Create SL Client client = SoftLayer.create_client_from_env( proxy=proxy, config_file=config_file, ) self.client = client
[ "def", "ensure_client", "(", "self", ",", "config_file", "=", "None", ",", "is_demo", "=", "False", ",", "proxy", "=", "None", ")", ":", "if", "self", ".", "client", "is", "not", "None", ":", "return", "# Environment can be passed in explicitly. This is used for testing", "if", "is_demo", ":", "client", "=", "SoftLayer", ".", "BaseClient", "(", "transport", "=", "SoftLayer", ".", "FixtureTransport", "(", ")", ",", "auth", "=", "None", ",", ")", "else", ":", "# Create SL Client", "client", "=", "SoftLayer", ".", "create_client_from_env", "(", "proxy", "=", "proxy", ",", "config_file", "=", "config_file", ",", ")", "self", ".", "client", "=", "client" ]
Create a new SLAPI client to the environment. This will be a no-op if there is already a client in this environment.
[ "Create", "a", "new", "SLAPI", "client", "to", "the", "environment", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L133-L153
train
234,320
softlayer/softlayer-python
SoftLayer/CLI/helpers.py
multi_option
def multi_option(*param_decls, **attrs): """modify help text and indicate option is permitted multiple times :param param_decls: :param attrs: :return: """ attrhelp = attrs.get('help', None) if attrhelp is not None: newhelp = attrhelp + " (multiple occurrence permitted)" attrs['help'] = newhelp attrs['multiple'] = True return click.option(*param_decls, **attrs)
python
def multi_option(*param_decls, **attrs): """modify help text and indicate option is permitted multiple times :param param_decls: :param attrs: :return: """ attrhelp = attrs.get('help', None) if attrhelp is not None: newhelp = attrhelp + " (multiple occurrence permitted)" attrs['help'] = newhelp attrs['multiple'] = True return click.option(*param_decls, **attrs)
[ "def", "multi_option", "(", "*", "param_decls", ",", "*", "*", "attrs", ")", ":", "attrhelp", "=", "attrs", ".", "get", "(", "'help'", ",", "None", ")", "if", "attrhelp", "is", "not", "None", ":", "newhelp", "=", "attrhelp", "+", "\" (multiple occurrence permitted)\"", "attrs", "[", "'help'", "]", "=", "newhelp", "attrs", "[", "'multiple'", "]", "=", "True", "return", "click", ".", "option", "(", "*", "param_decls", ",", "*", "*", "attrs", ")" ]
modify help text and indicate option is permitted multiple times :param param_decls: :param attrs: :return:
[ "modify", "help", "text", "and", "indicate", "option", "is", "permitted", "multiple", "times" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/helpers.py#L14-L27
train
234,321
softlayer/softlayer-python
SoftLayer/CLI/helpers.py
resolve_id
def resolve_id(resolver, identifier, name='object'): """Resolves a single id using a resolver function. :param resolver: function that resolves ids. Should return None or a list of ids. :param string identifier: a string identifier used to resolve ids :param string name: the object type, to be used in error messages """ try: return int(identifier) except ValueError: pass # It was worth a shot ids = resolver(identifier) if len(ids) == 0: raise exceptions.CLIAbort("Error: Unable to find %s '%s'" % (name, identifier)) if len(ids) > 1: raise exceptions.CLIAbort( "Error: Multiple %s found for '%s': %s" % (name, identifier, ', '.join([str(_id) for _id in ids]))) return ids[0]
python
def resolve_id(resolver, identifier, name='object'): """Resolves a single id using a resolver function. :param resolver: function that resolves ids. Should return None or a list of ids. :param string identifier: a string identifier used to resolve ids :param string name: the object type, to be used in error messages """ try: return int(identifier) except ValueError: pass # It was worth a shot ids = resolver(identifier) if len(ids) == 0: raise exceptions.CLIAbort("Error: Unable to find %s '%s'" % (name, identifier)) if len(ids) > 1: raise exceptions.CLIAbort( "Error: Multiple %s found for '%s': %s" % (name, identifier, ', '.join([str(_id) for _id in ids]))) return ids[0]
[ "def", "resolve_id", "(", "resolver", ",", "identifier", ",", "name", "=", "'object'", ")", ":", "try", ":", "return", "int", "(", "identifier", ")", "except", "ValueError", ":", "pass", "# It was worth a shot", "ids", "=", "resolver", "(", "identifier", ")", "if", "len", "(", "ids", ")", "==", "0", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Error: Unable to find %s '%s'\"", "%", "(", "name", ",", "identifier", ")", ")", "if", "len", "(", "ids", ")", ">", "1", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Error: Multiple %s found for '%s': %s\"", "%", "(", "name", ",", "identifier", ",", "', '", ".", "join", "(", "[", "str", "(", "_id", ")", "for", "_id", "in", "ids", "]", ")", ")", ")", "return", "ids", "[", "0", "]" ]
Resolves a single id using a resolver function. :param resolver: function that resolves ids. Should return None or a list of ids. :param string identifier: a string identifier used to resolve ids :param string name: the object type, to be used in error messages
[ "Resolves", "a", "single", "id", "using", "a", "resolver", "function", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/helpers.py#L30-L53
train
234,322
softlayer/softlayer-python
SoftLayer/CLI/ssl/remove.py
cli
def cli(env, identifier): """Remove SSL certificate.""" manager = SoftLayer.SSLManager(env.client) if not (env.skip_confirmations or formatting.no_going_back('yes')): raise exceptions.CLIAbort("Aborted.") manager.remove_certificate(identifier)
python
def cli(env, identifier): """Remove SSL certificate.""" manager = SoftLayer.SSLManager(env.client) if not (env.skip_confirmations or formatting.no_going_back('yes')): raise exceptions.CLIAbort("Aborted.") manager.remove_certificate(identifier)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "manager", "=", "SoftLayer", ".", "SSLManager", "(", "env", ".", "client", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "no_going_back", "(", "'yes'", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Aborted.\"", ")", "manager", ".", "remove_certificate", "(", "identifier", ")" ]
Remove SSL certificate.
[ "Remove", "SSL", "certificate", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ssl/remove.py#L15-L22
train
234,323
softlayer/softlayer-python
SoftLayer/CLI/file/snapshot/order.py
cli
def cli(env, volume_id, capacity, tier, upgrade): """Order snapshot space for a file storage volume.""" file_manager = SoftLayer.FileStorageManager(env.client) if tier is not None: tier = float(tier) try: order = file_manager.order_snapshot_space( volume_id, capacity=capacity, tier=tier, upgrade=upgrade ) except ValueError as ex: raise exceptions.ArgumentError(str(ex)) if 'placedOrder' in order.keys(): click.echo("Order #{0} placed successfully!".format( order['placedOrder']['id'])) for item in order['placedOrder']['items']: click.echo(" > %s" % item['description']) if 'status' in order['placedOrder'].keys(): click.echo(" > Order status: %s" % order['placedOrder']['status']) else: click.echo("Order could not be placed! Please verify your options " + "and try again.")
python
def cli(env, volume_id, capacity, tier, upgrade): """Order snapshot space for a file storage volume.""" file_manager = SoftLayer.FileStorageManager(env.client) if tier is not None: tier = float(tier) try: order = file_manager.order_snapshot_space( volume_id, capacity=capacity, tier=tier, upgrade=upgrade ) except ValueError as ex: raise exceptions.ArgumentError(str(ex)) if 'placedOrder' in order.keys(): click.echo("Order #{0} placed successfully!".format( order['placedOrder']['id'])) for item in order['placedOrder']['items']: click.echo(" > %s" % item['description']) if 'status' in order['placedOrder'].keys(): click.echo(" > Order status: %s" % order['placedOrder']['status']) else: click.echo("Order could not be placed! Please verify your options " + "and try again.")
[ "def", "cli", "(", "env", ",", "volume_id", ",", "capacity", ",", "tier", ",", "upgrade", ")", ":", "file_manager", "=", "SoftLayer", ".", "FileStorageManager", "(", "env", ".", "client", ")", "if", "tier", "is", "not", "None", ":", "tier", "=", "float", "(", "tier", ")", "try", ":", "order", "=", "file_manager", ".", "order_snapshot_space", "(", "volume_id", ",", "capacity", "=", "capacity", ",", "tier", "=", "tier", ",", "upgrade", "=", "upgrade", ")", "except", "ValueError", "as", "ex", ":", "raise", "exceptions", ".", "ArgumentError", "(", "str", "(", "ex", ")", ")", "if", "'placedOrder'", "in", "order", ".", "keys", "(", ")", ":", "click", ".", "echo", "(", "\"Order #{0} placed successfully!\"", ".", "format", "(", "order", "[", "'placedOrder'", "]", "[", "'id'", "]", ")", ")", "for", "item", "in", "order", "[", "'placedOrder'", "]", "[", "'items'", "]", ":", "click", ".", "echo", "(", "\" > %s\"", "%", "item", "[", "'description'", "]", ")", "if", "'status'", "in", "order", "[", "'placedOrder'", "]", ".", "keys", "(", ")", ":", "click", ".", "echo", "(", "\" > Order status: %s\"", "%", "order", "[", "'placedOrder'", "]", "[", "'status'", "]", ")", "else", ":", "click", ".", "echo", "(", "\"Order could not be placed! Please verify your options \"", "+", "\"and try again.\"", ")" ]
Order snapshot space for a file storage volume.
[ "Order", "snapshot", "space", "for", "a", "file", "storage", "volume", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/snapshot/order.py#L27-L53
train
234,324
softlayer/softlayer-python
SoftLayer/CLI/virt/edit.py
cli
def cli(env, identifier, domain, userfile, tag, hostname, userdata, public_speed, private_speed): """Edit a virtual server's details.""" if userdata and userfile: raise exceptions.ArgumentError( '[-u | --userdata] not allowed with [-F | --userfile]') data = {} if userdata: data['userdata'] = userdata elif userfile: with open(userfile, 'r') as userfile_obj: data['userdata'] = userfile_obj.read() data['hostname'] = hostname data['domain'] = domain if tag: data['tags'] = ','.join(tag) vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') if not vsi.edit(vs_id, **data): raise exceptions.CLIAbort("Failed to update virtual server") if public_speed is not None: vsi.change_port_speed(vs_id, True, int(public_speed)) if private_speed is not None: vsi.change_port_speed(vs_id, False, int(private_speed))
python
def cli(env, identifier, domain, userfile, tag, hostname, userdata, public_speed, private_speed): """Edit a virtual server's details.""" if userdata and userfile: raise exceptions.ArgumentError( '[-u | --userdata] not allowed with [-F | --userfile]') data = {} if userdata: data['userdata'] = userdata elif userfile: with open(userfile, 'r') as userfile_obj: data['userdata'] = userfile_obj.read() data['hostname'] = hostname data['domain'] = domain if tag: data['tags'] = ','.join(tag) vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') if not vsi.edit(vs_id, **data): raise exceptions.CLIAbort("Failed to update virtual server") if public_speed is not None: vsi.change_port_speed(vs_id, True, int(public_speed)) if private_speed is not None: vsi.change_port_speed(vs_id, False, int(private_speed))
[ "def", "cli", "(", "env", ",", "identifier", ",", "domain", ",", "userfile", ",", "tag", ",", "hostname", ",", "userdata", ",", "public_speed", ",", "private_speed", ")", ":", "if", "userdata", "and", "userfile", ":", "raise", "exceptions", ".", "ArgumentError", "(", "'[-u | --userdata] not allowed with [-F | --userfile]'", ")", "data", "=", "{", "}", "if", "userdata", ":", "data", "[", "'userdata'", "]", "=", "userdata", "elif", "userfile", ":", "with", "open", "(", "userfile", ",", "'r'", ")", "as", "userfile_obj", ":", "data", "[", "'userdata'", "]", "=", "userfile_obj", ".", "read", "(", ")", "data", "[", "'hostname'", "]", "=", "hostname", "data", "[", "'domain'", "]", "=", "domain", "if", "tag", ":", "data", "[", "'tags'", "]", "=", "','", ".", "join", "(", "tag", ")", "vsi", "=", "SoftLayer", ".", "VSManager", "(", "env", ".", "client", ")", "vs_id", "=", "helpers", ".", "resolve_id", "(", "vsi", ".", "resolve_ids", ",", "identifier", ",", "'VS'", ")", "if", "not", "vsi", ".", "edit", "(", "vs_id", ",", "*", "*", "data", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Failed to update virtual server\"", ")", "if", "public_speed", "is", "not", "None", ":", "vsi", ".", "change_port_speed", "(", "vs_id", ",", "True", ",", "int", "(", "public_speed", ")", ")", "if", "private_speed", "is", "not", "None", ":", "vsi", ".", "change_port_speed", "(", "vs_id", ",", "False", ",", "int", "(", "private_speed", ")", ")" ]
Edit a virtual server's details.
[ "Edit", "a", "virtual", "server", "s", "details", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/edit.py#L33-L64
train
234,325
softlayer/softlayer-python
SoftLayer/CLI/file/replication/order.py
cli
def cli(env, volume_id, snapshot_schedule, location, tier): """Order a file storage replica volume.""" file_manager = SoftLayer.FileStorageManager(env.client) if tier is not None: tier = float(tier) try: order = file_manager.order_replicant_volume( volume_id, snapshot_schedule=snapshot_schedule, location=location, tier=tier, ) except ValueError as ex: raise exceptions.ArgumentError(str(ex)) if 'placedOrder' in order.keys(): click.echo("Order #{0} placed successfully!".format( order['placedOrder']['id'])) for item in order['placedOrder']['items']: click.echo(" > %s" % item['description']) else: click.echo("Order could not be placed! Please verify your options " + "and try again.")
python
def cli(env, volume_id, snapshot_schedule, location, tier): """Order a file storage replica volume.""" file_manager = SoftLayer.FileStorageManager(env.client) if tier is not None: tier = float(tier) try: order = file_manager.order_replicant_volume( volume_id, snapshot_schedule=snapshot_schedule, location=location, tier=tier, ) except ValueError as ex: raise exceptions.ArgumentError(str(ex)) if 'placedOrder' in order.keys(): click.echo("Order #{0} placed successfully!".format( order['placedOrder']['id'])) for item in order['placedOrder']['items']: click.echo(" > %s" % item['description']) else: click.echo("Order could not be placed! Please verify your options " + "and try again.")
[ "def", "cli", "(", "env", ",", "volume_id", ",", "snapshot_schedule", ",", "location", ",", "tier", ")", ":", "file_manager", "=", "SoftLayer", ".", "FileStorageManager", "(", "env", ".", "client", ")", "if", "tier", "is", "not", "None", ":", "tier", "=", "float", "(", "tier", ")", "try", ":", "order", "=", "file_manager", ".", "order_replicant_volume", "(", "volume_id", ",", "snapshot_schedule", "=", "snapshot_schedule", ",", "location", "=", "location", ",", "tier", "=", "tier", ",", ")", "except", "ValueError", "as", "ex", ":", "raise", "exceptions", ".", "ArgumentError", "(", "str", "(", "ex", ")", ")", "if", "'placedOrder'", "in", "order", ".", "keys", "(", ")", ":", "click", ".", "echo", "(", "\"Order #{0} placed successfully!\"", ".", "format", "(", "order", "[", "'placedOrder'", "]", "[", "'id'", "]", ")", ")", "for", "item", "in", "order", "[", "'placedOrder'", "]", "[", "'items'", "]", ":", "click", ".", "echo", "(", "\" > %s\"", "%", "item", "[", "'description'", "]", ")", "else", ":", "click", ".", "echo", "(", "\"Order could not be placed! Please verify your options \"", "+", "\"and try again.\"", ")" ]
Order a file storage replica volume.
[ "Order", "a", "file", "storage", "replica", "volume", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/replication/order.py#L29-L53
train
234,326
softlayer/softlayer-python
SoftLayer/CLI/block/replication/failback.py
cli
def cli(env, volume_id, replicant_id): """Failback a block volume from the given replicant volume.""" block_storage_manager = SoftLayer.BlockStorageManager(env.client) success = block_storage_manager.failback_from_replicant( volume_id, replicant_id ) if success: click.echo("Failback from replicant is now in progress.") else: click.echo("Failback operation could not be initiated.")
python
def cli(env, volume_id, replicant_id): """Failback a block volume from the given replicant volume.""" block_storage_manager = SoftLayer.BlockStorageManager(env.client) success = block_storage_manager.failback_from_replicant( volume_id, replicant_id ) if success: click.echo("Failback from replicant is now in progress.") else: click.echo("Failback operation could not be initiated.")
[ "def", "cli", "(", "env", ",", "volume_id", ",", "replicant_id", ")", ":", "block_storage_manager", "=", "SoftLayer", ".", "BlockStorageManager", "(", "env", ".", "client", ")", "success", "=", "block_storage_manager", ".", "failback_from_replicant", "(", "volume_id", ",", "replicant_id", ")", "if", "success", ":", "click", ".", "echo", "(", "\"Failback from replicant is now in progress.\"", ")", "else", ":", "click", ".", "echo", "(", "\"Failback operation could not be initiated.\"", ")" ]
Failback a block volume from the given replicant volume.
[ "Failback", "a", "block", "volume", "from", "the", "given", "replicant", "volume", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/replication/failback.py#L13-L25
train
234,327
softlayer/softlayer-python
SoftLayer/CLI/virt/placementgroup/detail.py
cli
def cli(env, identifier): """View details of a placement group. IDENTIFIER can be either the Name or Id of the placement group you want to view """ manager = PlacementManager(env.client) group_id = helpers.resolve_id(manager.resolve_ids, identifier, 'placement_group') result = manager.get_object(group_id) table = formatting.Table(["Id", "Name", "Backend Router", "Rule", "Created"]) table.add_row([ result['id'], result['name'], result['backendRouter']['hostname'], result['rule']['name'], result['createDate'] ]) guest_table = formatting.Table([ "Id", "FQDN", "Primary IP", "Backend IP", "CPU", "Memory", "Provisioned", "Transaction" ]) for guest in result['guests']: guest_table.add_row([ guest.get('id'), guest.get('fullyQualifiedDomainName'), guest.get('primaryIpAddress'), guest.get('primaryBackendIpAddress'), guest.get('maxCpu'), guest.get('maxMemory'), guest.get('provisionDate'), formatting.active_txn(guest) ]) env.fout(table) env.fout(guest_table)
python
def cli(env, identifier): """View details of a placement group. IDENTIFIER can be either the Name or Id of the placement group you want to view """ manager = PlacementManager(env.client) group_id = helpers.resolve_id(manager.resolve_ids, identifier, 'placement_group') result = manager.get_object(group_id) table = formatting.Table(["Id", "Name", "Backend Router", "Rule", "Created"]) table.add_row([ result['id'], result['name'], result['backendRouter']['hostname'], result['rule']['name'], result['createDate'] ]) guest_table = formatting.Table([ "Id", "FQDN", "Primary IP", "Backend IP", "CPU", "Memory", "Provisioned", "Transaction" ]) for guest in result['guests']: guest_table.add_row([ guest.get('id'), guest.get('fullyQualifiedDomainName'), guest.get('primaryIpAddress'), guest.get('primaryBackendIpAddress'), guest.get('maxCpu'), guest.get('maxMemory'), guest.get('provisionDate'), formatting.active_txn(guest) ]) env.fout(table) env.fout(guest_table)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "manager", "=", "PlacementManager", "(", "env", ".", "client", ")", "group_id", "=", "helpers", ".", "resolve_id", "(", "manager", ".", "resolve_ids", ",", "identifier", ",", "'placement_group'", ")", "result", "=", "manager", ".", "get_object", "(", "group_id", ")", "table", "=", "formatting", ".", "Table", "(", "[", "\"Id\"", ",", "\"Name\"", ",", "\"Backend Router\"", ",", "\"Rule\"", ",", "\"Created\"", "]", ")", "table", ".", "add_row", "(", "[", "result", "[", "'id'", "]", ",", "result", "[", "'name'", "]", ",", "result", "[", "'backendRouter'", "]", "[", "'hostname'", "]", ",", "result", "[", "'rule'", "]", "[", "'name'", "]", ",", "result", "[", "'createDate'", "]", "]", ")", "guest_table", "=", "formatting", ".", "Table", "(", "[", "\"Id\"", ",", "\"FQDN\"", ",", "\"Primary IP\"", ",", "\"Backend IP\"", ",", "\"CPU\"", ",", "\"Memory\"", ",", "\"Provisioned\"", ",", "\"Transaction\"", "]", ")", "for", "guest", "in", "result", "[", "'guests'", "]", ":", "guest_table", ".", "add_row", "(", "[", "guest", ".", "get", "(", "'id'", ")", ",", "guest", ".", "get", "(", "'fullyQualifiedDomainName'", ")", ",", "guest", ".", "get", "(", "'primaryIpAddress'", ")", ",", "guest", ".", "get", "(", "'primaryBackendIpAddress'", ")", ",", "guest", ".", "get", "(", "'maxCpu'", ")", ",", "guest", ".", "get", "(", "'maxMemory'", ")", ",", "guest", ".", "get", "(", "'provisionDate'", ")", ",", "formatting", ".", "active_txn", "(", "guest", ")", "]", ")", "env", ".", "fout", "(", "table", ")", "env", ".", "fout", "(", "guest_table", ")" ]
View details of a placement group. IDENTIFIER can be either the Name or Id of the placement group you want to view
[ "View", "details", "of", "a", "placement", "group", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/placementgroup/detail.py#L14-L54
train
234,328
softlayer/softlayer-python
SoftLayer/CLI/user/list.py
cli
def cli(env, columns): """List Users.""" mgr = SoftLayer.UserManager(env.client) users = mgr.list_users() table = formatting.Table(columns.columns) for user in users: table.add_row([value or formatting.blank() for value in columns.row(user)]) env.fout(table)
python
def cli(env, columns): """List Users.""" mgr = SoftLayer.UserManager(env.client) users = mgr.list_users() table = formatting.Table(columns.columns) for user in users: table.add_row([value or formatting.blank() for value in columns.row(user)]) env.fout(table)
[ "def", "cli", "(", "env", ",", "columns", ")", ":", "mgr", "=", "SoftLayer", ".", "UserManager", "(", "env", ".", "client", ")", "users", "=", "mgr", ".", "list_users", "(", ")", "table", "=", "formatting", ".", "Table", "(", "columns", ".", "columns", ")", "for", "user", "in", "users", ":", "table", ".", "add_row", "(", "[", "value", "or", "formatting", ".", "blank", "(", ")", "for", "value", "in", "columns", ".", "row", "(", "user", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List Users.
[ "List", "Users", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/list.py#L37-L48
train
234,329
softlayer/softlayer-python
SoftLayer/CLI/ticket/update.py
cli
def cli(env, identifier, body): """Adds an update to an existing ticket.""" mgr = SoftLayer.TicketManager(env.client) ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket') if body is None: body = click.edit('\n\n' + ticket.TEMPLATE_MSG) mgr.update_ticket(ticket_id=ticket_id, body=body) env.fout("Ticket Updated!")
python
def cli(env, identifier, body): """Adds an update to an existing ticket.""" mgr = SoftLayer.TicketManager(env.client) ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket') if body is None: body = click.edit('\n\n' + ticket.TEMPLATE_MSG) mgr.update_ticket(ticket_id=ticket_id, body=body) env.fout("Ticket Updated!")
[ "def", "cli", "(", "env", ",", "identifier", ",", "body", ")", ":", "mgr", "=", "SoftLayer", ".", "TicketManager", "(", "env", ".", "client", ")", "ticket_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_ids", ",", "identifier", ",", "'ticket'", ")", "if", "body", "is", "None", ":", "body", "=", "click", ".", "edit", "(", "'\\n\\n'", "+", "ticket", ".", "TEMPLATE_MSG", ")", "mgr", ".", "update_ticket", "(", "ticket_id", "=", "ticket_id", ",", "body", "=", "body", ")", "env", ".", "fout", "(", "\"Ticket Updated!\"", ")" ]
Adds an update to an existing ticket.
[ "Adds", "an", "update", "to", "an", "existing", "ticket", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ticket/update.py#L16-L26
train
234,330
softlayer/softlayer-python
SoftLayer/CLI/order/quote_detail.py
cli
def cli(env, quote): """View a quote""" manager = ordering.OrderingManager(env.client) result = manager.get_quote_details(quote) package = result['order']['items'][0]['package'] title = "{} - Package: {}, Id {}".format(result.get('name'), package['keyName'], package['id']) table = formatting.Table([ 'Category', 'Description', 'Quantity', 'Recurring', 'One Time' ], title=title) table.align['Category'] = 'l' table.align['Description'] = 'l' items = lookup(result, 'order', 'items') for item in items: table.add_row([ item.get('categoryCode'), item.get('description'), item.get('quantity'), item.get('recurringFee'), item.get('oneTimeFee') ]) env.fout(table)
python
def cli(env, quote): """View a quote""" manager = ordering.OrderingManager(env.client) result = manager.get_quote_details(quote) package = result['order']['items'][0]['package'] title = "{} - Package: {}, Id {}".format(result.get('name'), package['keyName'], package['id']) table = formatting.Table([ 'Category', 'Description', 'Quantity', 'Recurring', 'One Time' ], title=title) table.align['Category'] = 'l' table.align['Description'] = 'l' items = lookup(result, 'order', 'items') for item in items: table.add_row([ item.get('categoryCode'), item.get('description'), item.get('quantity'), item.get('recurringFee'), item.get('oneTimeFee') ]) env.fout(table)
[ "def", "cli", "(", "env", ",", "quote", ")", ":", "manager", "=", "ordering", ".", "OrderingManager", "(", "env", ".", "client", ")", "result", "=", "manager", ".", "get_quote_details", "(", "quote", ")", "package", "=", "result", "[", "'order'", "]", "[", "'items'", "]", "[", "0", "]", "[", "'package'", "]", "title", "=", "\"{} - Package: {}, Id {}\"", ".", "format", "(", "result", ".", "get", "(", "'name'", ")", ",", "package", "[", "'keyName'", "]", ",", "package", "[", "'id'", "]", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'Category'", ",", "'Description'", ",", "'Quantity'", ",", "'Recurring'", ",", "'One Time'", "]", ",", "title", "=", "title", ")", "table", ".", "align", "[", "'Category'", "]", "=", "'l'", "table", ".", "align", "[", "'Description'", "]", "=", "'l'", "items", "=", "lookup", "(", "result", ",", "'order'", ",", "'items'", ")", "for", "item", "in", "items", ":", "table", ".", "add_row", "(", "[", "item", ".", "get", "(", "'categoryCode'", ")", ",", "item", ".", "get", "(", "'description'", ")", ",", "item", ".", "get", "(", "'quantity'", ")", ",", "item", ".", "get", "(", "'recurringFee'", ")", ",", "item", ".", "get", "(", "'oneTimeFee'", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
View a quote
[ "View", "a", "quote" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/quote_detail.py#L14-L38
train
234,331
softlayer/softlayer-python
SoftLayer/CLI/securitygroup/list.py
cli
def cli(env, sortby, limit): """List security groups.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table(COLUMNS) table.sortby = sortby sgs = mgr.list_securitygroups(limit=limit) for secgroup in sgs: table.add_row([ secgroup['id'], secgroup.get('name') or formatting.blank(), secgroup.get('description') or formatting.blank(), ]) env.fout(table)
python
def cli(env, sortby, limit): """List security groups.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table(COLUMNS) table.sortby = sortby sgs = mgr.list_securitygroups(limit=limit) for secgroup in sgs: table.add_row([ secgroup['id'], secgroup.get('name') or formatting.blank(), secgroup.get('description') or formatting.blank(), ]) env.fout(table)
[ "def", "cli", "(", "env", ",", "sortby", ",", "limit", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "COLUMNS", ")", "table", ".", "sortby", "=", "sortby", "sgs", "=", "mgr", ".", "list_securitygroups", "(", "limit", "=", "limit", ")", "for", "secgroup", "in", "sgs", ":", "table", ".", "add_row", "(", "[", "secgroup", "[", "'id'", "]", ",", "secgroup", ".", "get", "(", "'name'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "secgroup", ".", "get", "(", "'description'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List security groups.
[ "List", "security", "groups", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/list.py#L24-L40
train
234,332
softlayer/softlayer-python
SoftLayer/CLI/firewall/edit.py
parse_rules
def parse_rules(content=None): """Helper to parse the input from the user into a list of rules. :param string content: the content of the editor :returns: a list of rules """ rules = content.split(DELIMITER) parsed_rules = list() order = 1 for rule in rules: if rule.strip() == '': continue parsed_rule = {} lines = rule.split("\n") parsed_rule['orderValue'] = order order += 1 for line in lines: if line.strip() == '': continue key_value = line.strip().split(':') key = key_value[0].strip() value = key_value[1].strip() if key == 'action': parsed_rule['action'] = value elif key == 'protocol': parsed_rule['protocol'] = value elif key == 'source_ip_address': parsed_rule['sourceIpAddress'] = value elif key == 'source_ip_subnet_mask': parsed_rule['sourceIpSubnetMask'] = value elif key == 'destination_ip_address': parsed_rule['destinationIpAddress'] = value elif key == 'destination_ip_subnet_mask': parsed_rule['destinationIpSubnetMask'] = value elif key == 'destination_port_range_start': parsed_rule['destinationPortRangeStart'] = int(value) elif key == 'destination_port_range_end': parsed_rule['destinationPortRangeEnd'] = int(value) elif key == 'version': parsed_rule['version'] = int(value) parsed_rules.append(parsed_rule) return parsed_rules
python
def parse_rules(content=None): """Helper to parse the input from the user into a list of rules. :param string content: the content of the editor :returns: a list of rules """ rules = content.split(DELIMITER) parsed_rules = list() order = 1 for rule in rules: if rule.strip() == '': continue parsed_rule = {} lines = rule.split("\n") parsed_rule['orderValue'] = order order += 1 for line in lines: if line.strip() == '': continue key_value = line.strip().split(':') key = key_value[0].strip() value = key_value[1].strip() if key == 'action': parsed_rule['action'] = value elif key == 'protocol': parsed_rule['protocol'] = value elif key == 'source_ip_address': parsed_rule['sourceIpAddress'] = value elif key == 'source_ip_subnet_mask': parsed_rule['sourceIpSubnetMask'] = value elif key == 'destination_ip_address': parsed_rule['destinationIpAddress'] = value elif key == 'destination_ip_subnet_mask': parsed_rule['destinationIpSubnetMask'] = value elif key == 'destination_port_range_start': parsed_rule['destinationPortRangeStart'] = int(value) elif key == 'destination_port_range_end': parsed_rule['destinationPortRangeEnd'] = int(value) elif key == 'version': parsed_rule['version'] = int(value) parsed_rules.append(parsed_rule) return parsed_rules
[ "def", "parse_rules", "(", "content", "=", "None", ")", ":", "rules", "=", "content", ".", "split", "(", "DELIMITER", ")", "parsed_rules", "=", "list", "(", ")", "order", "=", "1", "for", "rule", "in", "rules", ":", "if", "rule", ".", "strip", "(", ")", "==", "''", ":", "continue", "parsed_rule", "=", "{", "}", "lines", "=", "rule", ".", "split", "(", "\"\\n\"", ")", "parsed_rule", "[", "'orderValue'", "]", "=", "order", "order", "+=", "1", "for", "line", "in", "lines", ":", "if", "line", ".", "strip", "(", ")", "==", "''", ":", "continue", "key_value", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "':'", ")", "key", "=", "key_value", "[", "0", "]", ".", "strip", "(", ")", "value", "=", "key_value", "[", "1", "]", ".", "strip", "(", ")", "if", "key", "==", "'action'", ":", "parsed_rule", "[", "'action'", "]", "=", "value", "elif", "key", "==", "'protocol'", ":", "parsed_rule", "[", "'protocol'", "]", "=", "value", "elif", "key", "==", "'source_ip_address'", ":", "parsed_rule", "[", "'sourceIpAddress'", "]", "=", "value", "elif", "key", "==", "'source_ip_subnet_mask'", ":", "parsed_rule", "[", "'sourceIpSubnetMask'", "]", "=", "value", "elif", "key", "==", "'destination_ip_address'", ":", "parsed_rule", "[", "'destinationIpAddress'", "]", "=", "value", "elif", "key", "==", "'destination_ip_subnet_mask'", ":", "parsed_rule", "[", "'destinationIpSubnetMask'", "]", "=", "value", "elif", "key", "==", "'destination_port_range_start'", ":", "parsed_rule", "[", "'destinationPortRangeStart'", "]", "=", "int", "(", "value", ")", "elif", "key", "==", "'destination_port_range_end'", ":", "parsed_rule", "[", "'destinationPortRangeEnd'", "]", "=", "int", "(", "value", ")", "elif", "key", "==", "'version'", ":", "parsed_rule", "[", "'version'", "]", "=", "int", "(", "value", ")", "parsed_rules", ".", "append", "(", "parsed_rule", ")", "return", "parsed_rules" ]
Helper to parse the input from the user into a list of rules. :param string content: the content of the editor :returns: a list of rules
[ "Helper", "to", "parse", "the", "input", "from", "the", "user", "into", "a", "list", "of", "rules", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/edit.py#L19-L60
train
234,333
softlayer/softlayer-python
SoftLayer/CLI/firewall/edit.py
open_editor
def open_editor(rules=None, content=None): """Helper to open an editor for editing the firewall rules. This method takes two parameters, if content is provided, that means that submitting the rules failed and we are allowing the user to re-edit what they provided. If content is not provided, the rules retrieved from the firewall will be displayed to the user. :param list rules: A list containing the rules of the firewall :param string content: the content that the user provided in the editor :returns: a formatted string that get be pushed into the editor """ # Let's get the default EDITOR of the environment, # use nano if none is specified editor = os.environ.get('EDITOR', 'nano') with tempfile.NamedTemporaryFile(suffix=".tmp") as tfile: if content: # if content is provided, just display it as is tfile.write(content) tfile.flush() subprocess.call([editor, tfile.name]) tfile.seek(0) data = tfile.read() return data if not rules: # if the firewall has no rules, provide a template tfile.write(DELIMITER) tfile.write(get_formatted_rule()) else: # if the firewall has rules, display those to the user for rule in rules: tfile.write(DELIMITER) tfile.write(get_formatted_rule(rule)) tfile.write(DELIMITER) tfile.flush() subprocess.call([editor, tfile.name]) tfile.seek(0) data = tfile.read() return data
python
def open_editor(rules=None, content=None): """Helper to open an editor for editing the firewall rules. This method takes two parameters, if content is provided, that means that submitting the rules failed and we are allowing the user to re-edit what they provided. If content is not provided, the rules retrieved from the firewall will be displayed to the user. :param list rules: A list containing the rules of the firewall :param string content: the content that the user provided in the editor :returns: a formatted string that get be pushed into the editor """ # Let's get the default EDITOR of the environment, # use nano if none is specified editor = os.environ.get('EDITOR', 'nano') with tempfile.NamedTemporaryFile(suffix=".tmp") as tfile: if content: # if content is provided, just display it as is tfile.write(content) tfile.flush() subprocess.call([editor, tfile.name]) tfile.seek(0) data = tfile.read() return data if not rules: # if the firewall has no rules, provide a template tfile.write(DELIMITER) tfile.write(get_formatted_rule()) else: # if the firewall has rules, display those to the user for rule in rules: tfile.write(DELIMITER) tfile.write(get_formatted_rule(rule)) tfile.write(DELIMITER) tfile.flush() subprocess.call([editor, tfile.name]) tfile.seek(0) data = tfile.read() return data
[ "def", "open_editor", "(", "rules", "=", "None", ",", "content", "=", "None", ")", ":", "# Let's get the default EDITOR of the environment,", "# use nano if none is specified", "editor", "=", "os", ".", "environ", ".", "get", "(", "'EDITOR'", ",", "'nano'", ")", "with", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "\".tmp\"", ")", "as", "tfile", ":", "if", "content", ":", "# if content is provided, just display it as is", "tfile", ".", "write", "(", "content", ")", "tfile", ".", "flush", "(", ")", "subprocess", ".", "call", "(", "[", "editor", ",", "tfile", ".", "name", "]", ")", "tfile", ".", "seek", "(", "0", ")", "data", "=", "tfile", ".", "read", "(", ")", "return", "data", "if", "not", "rules", ":", "# if the firewall has no rules, provide a template", "tfile", ".", "write", "(", "DELIMITER", ")", "tfile", ".", "write", "(", "get_formatted_rule", "(", ")", ")", "else", ":", "# if the firewall has rules, display those to the user", "for", "rule", "in", "rules", ":", "tfile", ".", "write", "(", "DELIMITER", ")", "tfile", ".", "write", "(", "get_formatted_rule", "(", "rule", ")", ")", "tfile", ".", "write", "(", "DELIMITER", ")", "tfile", ".", "flush", "(", ")", "subprocess", ".", "call", "(", "[", "editor", ",", "tfile", ".", "name", "]", ")", "tfile", ".", "seek", "(", "0", ")", "data", "=", "tfile", ".", "read", "(", ")", "return", "data" ]
Helper to open an editor for editing the firewall rules. This method takes two parameters, if content is provided, that means that submitting the rules failed and we are allowing the user to re-edit what they provided. If content is not provided, the rules retrieved from the firewall will be displayed to the user. :param list rules: A list containing the rules of the firewall :param string content: the content that the user provided in the editor :returns: a formatted string that get be pushed into the editor
[ "Helper", "to", "open", "an", "editor", "for", "editing", "the", "firewall", "rules", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/edit.py#L63-L105
train
234,334
softlayer/softlayer-python
SoftLayer/CLI/firewall/edit.py
get_formatted_rule
def get_formatted_rule(rule=None): """Helper to format the rule into a user friendly format. :param dict rule: A dict containing one rule of the firewall :returns: a formatted string that get be pushed into the editor """ rule = rule or {} return ('action: %s\n' 'protocol: %s\n' 'source_ip_address: %s\n' 'source_ip_subnet_mask: %s\n' 'destination_ip_address: %s\n' 'destination_ip_subnet_mask: %s\n' 'destination_port_range_start: %s\n' 'destination_port_range_end: %s\n' 'version: %s\n' % (rule.get('action', 'permit'), rule.get('protocol', 'tcp'), rule.get('sourceIpAddress', 'any'), rule.get('sourceIpSubnetMask', '255.255.255.255'), rule.get('destinationIpAddress', 'any'), rule.get('destinationIpSubnetMask', '255.255.255.255'), rule.get('destinationPortRangeStart', 1), rule.get('destinationPortRangeEnd', 1), rule.get('version', 4)))
python
def get_formatted_rule(rule=None): """Helper to format the rule into a user friendly format. :param dict rule: A dict containing one rule of the firewall :returns: a formatted string that get be pushed into the editor """ rule = rule or {} return ('action: %s\n' 'protocol: %s\n' 'source_ip_address: %s\n' 'source_ip_subnet_mask: %s\n' 'destination_ip_address: %s\n' 'destination_ip_subnet_mask: %s\n' 'destination_port_range_start: %s\n' 'destination_port_range_end: %s\n' 'version: %s\n' % (rule.get('action', 'permit'), rule.get('protocol', 'tcp'), rule.get('sourceIpAddress', 'any'), rule.get('sourceIpSubnetMask', '255.255.255.255'), rule.get('destinationIpAddress', 'any'), rule.get('destinationIpSubnetMask', '255.255.255.255'), rule.get('destinationPortRangeStart', 1), rule.get('destinationPortRangeEnd', 1), rule.get('version', 4)))
[ "def", "get_formatted_rule", "(", "rule", "=", "None", ")", ":", "rule", "=", "rule", "or", "{", "}", "return", "(", "'action: %s\\n'", "'protocol: %s\\n'", "'source_ip_address: %s\\n'", "'source_ip_subnet_mask: %s\\n'", "'destination_ip_address: %s\\n'", "'destination_ip_subnet_mask: %s\\n'", "'destination_port_range_start: %s\\n'", "'destination_port_range_end: %s\\n'", "'version: %s\\n'", "%", "(", "rule", ".", "get", "(", "'action'", ",", "'permit'", ")", ",", "rule", ".", "get", "(", "'protocol'", ",", "'tcp'", ")", ",", "rule", ".", "get", "(", "'sourceIpAddress'", ",", "'any'", ")", ",", "rule", ".", "get", "(", "'sourceIpSubnetMask'", ",", "'255.255.255.255'", ")", ",", "rule", ".", "get", "(", "'destinationIpAddress'", ",", "'any'", ")", ",", "rule", ".", "get", "(", "'destinationIpSubnetMask'", ",", "'255.255.255.255'", ")", ",", "rule", ".", "get", "(", "'destinationPortRangeStart'", ",", "1", ")", ",", "rule", ".", "get", "(", "'destinationPortRangeEnd'", ",", "1", ")", ",", "rule", ".", "get", "(", "'version'", ",", "4", ")", ")", ")" ]
Helper to format the rule into a user friendly format. :param dict rule: A dict containing one rule of the firewall :returns: a formatted string that get be pushed into the editor
[ "Helper", "to", "format", "the", "rule", "into", "a", "user", "friendly", "format", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/edit.py#L108-L132
train
234,335
softlayer/softlayer-python
SoftLayer/CLI/firewall/edit.py
cli
def cli(env, identifier): """Edit firewall rules.""" mgr = SoftLayer.FirewallManager(env.client) firewall_type, firewall_id = firewall.parse_id(identifier) if firewall_type == 'vlan': orig_rules = mgr.get_dedicated_fwl_rules(firewall_id) else: orig_rules = mgr.get_standard_fwl_rules(firewall_id) # open an editor for the user to enter their rules edited_rules = open_editor(rules=orig_rules) env.out(edited_rules) if formatting.confirm("Would you like to submit the rules. " "Continue?"): while True: try: rules = parse_rules(edited_rules) if firewall_type == 'vlan': rules = mgr.edit_dedicated_fwl_rules(firewall_id, rules) else: rules = mgr.edit_standard_fwl_rules(firewall_id, rules) break except (SoftLayer.SoftLayerError, ValueError) as error: env.out("Unexpected error({%s})" % (error)) if formatting.confirm("Would you like to continue editing " "the rules. Continue?"): edited_rules = open_editor(content=edited_rules) env.out(edited_rules) if formatting.confirm("Would you like to submit the " "rules. Continue?"): continue else: raise exceptions.CLIAbort('Aborted.') else: raise exceptions.CLIAbort('Aborted.') env.fout('Firewall updated!') else: raise exceptions.CLIAbort('Aborted.')
python
def cli(env, identifier): """Edit firewall rules.""" mgr = SoftLayer.FirewallManager(env.client) firewall_type, firewall_id = firewall.parse_id(identifier) if firewall_type == 'vlan': orig_rules = mgr.get_dedicated_fwl_rules(firewall_id) else: orig_rules = mgr.get_standard_fwl_rules(firewall_id) # open an editor for the user to enter their rules edited_rules = open_editor(rules=orig_rules) env.out(edited_rules) if formatting.confirm("Would you like to submit the rules. " "Continue?"): while True: try: rules = parse_rules(edited_rules) if firewall_type == 'vlan': rules = mgr.edit_dedicated_fwl_rules(firewall_id, rules) else: rules = mgr.edit_standard_fwl_rules(firewall_id, rules) break except (SoftLayer.SoftLayerError, ValueError) as error: env.out("Unexpected error({%s})" % (error)) if formatting.confirm("Would you like to continue editing " "the rules. Continue?"): edited_rules = open_editor(content=edited_rules) env.out(edited_rules) if formatting.confirm("Would you like to submit the " "rules. Continue?"): continue else: raise exceptions.CLIAbort('Aborted.') else: raise exceptions.CLIAbort('Aborted.') env.fout('Firewall updated!') else: raise exceptions.CLIAbort('Aborted.')
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "FirewallManager", "(", "env", ".", "client", ")", "firewall_type", ",", "firewall_id", "=", "firewall", ".", "parse_id", "(", "identifier", ")", "if", "firewall_type", "==", "'vlan'", ":", "orig_rules", "=", "mgr", ".", "get_dedicated_fwl_rules", "(", "firewall_id", ")", "else", ":", "orig_rules", "=", "mgr", ".", "get_standard_fwl_rules", "(", "firewall_id", ")", "# open an editor for the user to enter their rules", "edited_rules", "=", "open_editor", "(", "rules", "=", "orig_rules", ")", "env", ".", "out", "(", "edited_rules", ")", "if", "formatting", ".", "confirm", "(", "\"Would you like to submit the rules. \"", "\"Continue?\"", ")", ":", "while", "True", ":", "try", ":", "rules", "=", "parse_rules", "(", "edited_rules", ")", "if", "firewall_type", "==", "'vlan'", ":", "rules", "=", "mgr", ".", "edit_dedicated_fwl_rules", "(", "firewall_id", ",", "rules", ")", "else", ":", "rules", "=", "mgr", ".", "edit_standard_fwl_rules", "(", "firewall_id", ",", "rules", ")", "break", "except", "(", "SoftLayer", ".", "SoftLayerError", ",", "ValueError", ")", "as", "error", ":", "env", ".", "out", "(", "\"Unexpected error({%s})\"", "%", "(", "error", ")", ")", "if", "formatting", ".", "confirm", "(", "\"Would you like to continue editing \"", "\"the rules. Continue?\"", ")", ":", "edited_rules", "=", "open_editor", "(", "content", "=", "edited_rules", ")", "env", ".", "out", "(", "edited_rules", ")", "if", "formatting", ".", "confirm", "(", "\"Would you like to submit the \"", "\"rules. Continue?\"", ")", ":", "continue", "else", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted.'", ")", "else", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted.'", ")", "env", ".", "fout", "(", "'Firewall updated!'", ")", "else", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted.'", ")" ]
Edit firewall rules.
[ "Edit", "firewall", "rules", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/edit.py#L138-L178
train
234,336
softlayer/softlayer-python
SoftLayer/CLI/securitygroup/rule.py
rule_list
def rule_list(env, securitygroup_id, sortby): """List security group rules.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table(COLUMNS) table.sortby = sortby rules = mgr.list_securitygroup_rules(securitygroup_id) for rule in rules: port_min = rule.get('portRangeMin') port_max = rule.get('portRangeMax') if port_min is None: port_min = formatting.blank() if port_max is None: port_max = formatting.blank() table.add_row([ rule['id'], rule.get('remoteIp') or formatting.blank(), rule.get('remoteGroupId') or formatting.blank(), rule['direction'], rule.get('ethertype') or formatting.blank(), port_min, port_max, rule.get('protocol') or formatting.blank(), rule.get('createDate') or formatting.blank(), rule.get('modifyDate') or formatting.blank() ]) env.fout(table)
python
def rule_list(env, securitygroup_id, sortby): """List security group rules.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table(COLUMNS) table.sortby = sortby rules = mgr.list_securitygroup_rules(securitygroup_id) for rule in rules: port_min = rule.get('portRangeMin') port_max = rule.get('portRangeMax') if port_min is None: port_min = formatting.blank() if port_max is None: port_max = formatting.blank() table.add_row([ rule['id'], rule.get('remoteIp') or formatting.blank(), rule.get('remoteGroupId') or formatting.blank(), rule['direction'], rule.get('ethertype') or formatting.blank(), port_min, port_max, rule.get('protocol') or formatting.blank(), rule.get('createDate') or formatting.blank(), rule.get('modifyDate') or formatting.blank() ]) env.fout(table)
[ "def", "rule_list", "(", "env", ",", "securitygroup_id", ",", "sortby", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "COLUMNS", ")", "table", ".", "sortby", "=", "sortby", "rules", "=", "mgr", ".", "list_securitygroup_rules", "(", "securitygroup_id", ")", "for", "rule", "in", "rules", ":", "port_min", "=", "rule", ".", "get", "(", "'portRangeMin'", ")", "port_max", "=", "rule", ".", "get", "(", "'portRangeMax'", ")", "if", "port_min", "is", "None", ":", "port_min", "=", "formatting", ".", "blank", "(", ")", "if", "port_max", "is", "None", ":", "port_max", "=", "formatting", ".", "blank", "(", ")", "table", ".", "add_row", "(", "[", "rule", "[", "'id'", "]", ",", "rule", ".", "get", "(", "'remoteIp'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "rule", ".", "get", "(", "'remoteGroupId'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "rule", "[", "'direction'", "]", ",", "rule", ".", "get", "(", "'ethertype'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "port_min", ",", "port_max", ",", "rule", ".", "get", "(", "'protocol'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "rule", ".", "get", "(", "'createDate'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "rule", ".", "get", "(", "'modifyDate'", ")", "or", "formatting", ".", "blank", "(", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List security group rules.
[ "List", "security", "group", "rules", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/rule.py#L32-L62
train
234,337
softlayer/softlayer-python
SoftLayer/CLI/securitygroup/rule.py
add
def add(env, securitygroup_id, remote_ip, remote_group, direction, ethertype, port_max, port_min, protocol): """Add a security group rule to a security group. \b Examples: # Add an SSH rule (TCP port 22) to a security group slcli sg rule-add 384727 \\ --direction ingress \\ --protocol tcp \\ --port-min 22 \\ --port-max 22 \b # Add a ping rule (ICMP type 8 code 0) to a security group slcli sg rule-add 384727 \\ --direction ingress \\ --protocol icmp \\ --port-min 8 \\ --port-max 0 """ mgr = SoftLayer.NetworkManager(env.client) ret = mgr.add_securitygroup_rule(securitygroup_id, remote_ip, remote_group, direction, ethertype, port_max, port_min, protocol) if not ret: raise exceptions.CLIAbort("Failed to add security group rule") table = formatting.Table(REQUEST_RULES_COLUMNS) table.add_row([ret['requestId'], str(ret['rules'])]) env.fout(table)
python
def add(env, securitygroup_id, remote_ip, remote_group, direction, ethertype, port_max, port_min, protocol): """Add a security group rule to a security group. \b Examples: # Add an SSH rule (TCP port 22) to a security group slcli sg rule-add 384727 \\ --direction ingress \\ --protocol tcp \\ --port-min 22 \\ --port-max 22 \b # Add a ping rule (ICMP type 8 code 0) to a security group slcli sg rule-add 384727 \\ --direction ingress \\ --protocol icmp \\ --port-min 8 \\ --port-max 0 """ mgr = SoftLayer.NetworkManager(env.client) ret = mgr.add_securitygroup_rule(securitygroup_id, remote_ip, remote_group, direction, ethertype, port_max, port_min, protocol) if not ret: raise exceptions.CLIAbort("Failed to add security group rule") table = formatting.Table(REQUEST_RULES_COLUMNS) table.add_row([ret['requestId'], str(ret['rules'])]) env.fout(table)
[ "def", "add", "(", "env", ",", "securitygroup_id", ",", "remote_ip", ",", "remote_group", ",", "direction", ",", "ethertype", ",", "port_max", ",", "port_min", ",", "protocol", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "ret", "=", "mgr", ".", "add_securitygroup_rule", "(", "securitygroup_id", ",", "remote_ip", ",", "remote_group", ",", "direction", ",", "ethertype", ",", "port_max", ",", "port_min", ",", "protocol", ")", "if", "not", "ret", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Failed to add security group rule\"", ")", "table", "=", "formatting", ".", "Table", "(", "REQUEST_RULES_COLUMNS", ")", "table", ".", "add_row", "(", "[", "ret", "[", "'requestId'", "]", ",", "str", "(", "ret", "[", "'rules'", "]", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Add a security group rule to a security group. \b Examples: # Add an SSH rule (TCP port 22) to a security group slcli sg rule-add 384727 \\ --direction ingress \\ --protocol tcp \\ --port-min 22 \\ --port-max 22 \b # Add a ping rule (ICMP type 8 code 0) to a security group slcli sg rule-add 384727 \\ --direction ingress \\ --protocol icmp \\ --port-min 8 \\ --port-max 0
[ "Add", "a", "security", "group", "rule", "to", "a", "security", "group", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/rule.py#L85-L118
train
234,338
softlayer/softlayer-python
SoftLayer/CLI/securitygroup/rule.py
edit
def edit(env, securitygroup_id, rule_id, remote_ip, remote_group, direction, ethertype, port_max, port_min, protocol): """Edit a security group rule in a security group.""" mgr = SoftLayer.NetworkManager(env.client) data = {} if remote_ip: data['remote_ip'] = remote_ip if remote_group: data['remote_group'] = remote_group if direction: data['direction'] = direction if ethertype: data['ethertype'] = ethertype if port_max is not None: data['port_max'] = port_max if port_min is not None: data['port_min'] = port_min if protocol: data['protocol'] = protocol ret = mgr.edit_securitygroup_rule(securitygroup_id, rule_id, **data) if not ret: raise exceptions.CLIAbort("Failed to edit security group rule") table = formatting.Table(REQUEST_BOOL_COLUMNS) table.add_row([ret['requestId']]) env.fout(table)
python
def edit(env, securitygroup_id, rule_id, remote_ip, remote_group, direction, ethertype, port_max, port_min, protocol): """Edit a security group rule in a security group.""" mgr = SoftLayer.NetworkManager(env.client) data = {} if remote_ip: data['remote_ip'] = remote_ip if remote_group: data['remote_group'] = remote_group if direction: data['direction'] = direction if ethertype: data['ethertype'] = ethertype if port_max is not None: data['port_max'] = port_max if port_min is not None: data['port_min'] = port_min if protocol: data['protocol'] = protocol ret = mgr.edit_securitygroup_rule(securitygroup_id, rule_id, **data) if not ret: raise exceptions.CLIAbort("Failed to edit security group rule") table = formatting.Table(REQUEST_BOOL_COLUMNS) table.add_row([ret['requestId']]) env.fout(table)
[ "def", "edit", "(", "env", ",", "securitygroup_id", ",", "rule_id", ",", "remote_ip", ",", "remote_group", ",", "direction", ",", "ethertype", ",", "port_max", ",", "port_min", ",", "protocol", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "data", "=", "{", "}", "if", "remote_ip", ":", "data", "[", "'remote_ip'", "]", "=", "remote_ip", "if", "remote_group", ":", "data", "[", "'remote_group'", "]", "=", "remote_group", "if", "direction", ":", "data", "[", "'direction'", "]", "=", "direction", "if", "ethertype", ":", "data", "[", "'ethertype'", "]", "=", "ethertype", "if", "port_max", "is", "not", "None", ":", "data", "[", "'port_max'", "]", "=", "port_max", "if", "port_min", "is", "not", "None", ":", "data", "[", "'port_min'", "]", "=", "port_min", "if", "protocol", ":", "data", "[", "'protocol'", "]", "=", "protocol", "ret", "=", "mgr", ".", "edit_securitygroup_rule", "(", "securitygroup_id", ",", "rule_id", ",", "*", "*", "data", ")", "if", "not", "ret", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Failed to edit security group rule\"", ")", "table", "=", "formatting", ".", "Table", "(", "REQUEST_BOOL_COLUMNS", ")", "table", ".", "add_row", "(", "[", "ret", "[", "'requestId'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Edit a security group rule in a security group.
[ "Edit", "a", "security", "group", "rule", "in", "a", "security", "group", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/rule.py#L139-L168
train
234,339
softlayer/softlayer-python
SoftLayer/CLI/securitygroup/rule.py
remove
def remove(env, securitygroup_id, rule_id): """Remove a rule from a security group.""" mgr = SoftLayer.NetworkManager(env.client) ret = mgr.remove_securitygroup_rule(securitygroup_id, rule_id) if not ret: raise exceptions.CLIAbort("Failed to remove security group rule") table = formatting.Table(REQUEST_BOOL_COLUMNS) table.add_row([ret['requestId']]) env.fout(table)
python
def remove(env, securitygroup_id, rule_id): """Remove a rule from a security group.""" mgr = SoftLayer.NetworkManager(env.client) ret = mgr.remove_securitygroup_rule(securitygroup_id, rule_id) if not ret: raise exceptions.CLIAbort("Failed to remove security group rule") table = formatting.Table(REQUEST_BOOL_COLUMNS) table.add_row([ret['requestId']]) env.fout(table)
[ "def", "remove", "(", "env", ",", "securitygroup_id", ",", "rule_id", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "ret", "=", "mgr", ".", "remove_securitygroup_rule", "(", "securitygroup_id", ",", "rule_id", ")", "if", "not", "ret", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Failed to remove security group rule\"", ")", "table", "=", "formatting", ".", "Table", "(", "REQUEST_BOOL_COLUMNS", ")", "table", ".", "add_row", "(", "[", "ret", "[", "'requestId'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Remove a rule from a security group.
[ "Remove", "a", "rule", "from", "a", "security", "group", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/rule.py#L175-L187
train
234,340
softlayer/softlayer-python
SoftLayer/CLI/deprecated.py
main
def main(): """Main function for the deprecated 'sl' command.""" print("ERROR: Use the 'slcli' command instead.", file=sys.stderr) print("> slcli %s" % ' '.join(sys.argv[1:]), file=sys.stderr) exit(-1)
python
def main(): """Main function for the deprecated 'sl' command.""" print("ERROR: Use the 'slcli' command instead.", file=sys.stderr) print("> slcli %s" % ' '.join(sys.argv[1:]), file=sys.stderr) exit(-1)
[ "def", "main", "(", ")", ":", "print", "(", "\"ERROR: Use the 'slcli' command instead.\"", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "\"> slcli %s\"", "%", "' '", ".", "join", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", ",", "file", "=", "sys", ".", "stderr", ")", "exit", "(", "-", "1", ")" ]
Main function for the deprecated 'sl' command.
[ "Main", "function", "for", "the", "deprecated", "sl", "command", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/deprecated.py#L11-L15
train
234,341
softlayer/softlayer-python
SoftLayer/CLI/loadbal/group_edit.py
cli
def cli(env, identifier, allocation, port, routing_type, routing_method): """Edit an existing load balancer service group.""" mgr = SoftLayer.LoadBalancerManager(env.client) loadbal_id, group_id = loadbal.parse_id(identifier) # check if any input is provided if not any([allocation, port, routing_type, routing_method]): raise exceptions.CLIAbort( 'At least one property is required to be changed!') mgr.edit_service_group(loadbal_id, group_id, allocation=allocation, port=port, routing_type=routing_type, routing_method=routing_method) env.fout('Load balancer service group %s is being updated!' % identifier)
python
def cli(env, identifier, allocation, port, routing_type, routing_method): """Edit an existing load balancer service group.""" mgr = SoftLayer.LoadBalancerManager(env.client) loadbal_id, group_id = loadbal.parse_id(identifier) # check if any input is provided if not any([allocation, port, routing_type, routing_method]): raise exceptions.CLIAbort( 'At least one property is required to be changed!') mgr.edit_service_group(loadbal_id, group_id, allocation=allocation, port=port, routing_type=routing_type, routing_method=routing_method) env.fout('Load balancer service group %s is being updated!' % identifier)
[ "def", "cli", "(", "env", ",", "identifier", ",", "allocation", ",", "port", ",", "routing_type", ",", "routing_method", ")", ":", "mgr", "=", "SoftLayer", ".", "LoadBalancerManager", "(", "env", ".", "client", ")", "loadbal_id", ",", "group_id", "=", "loadbal", ".", "parse_id", "(", "identifier", ")", "# check if any input is provided", "if", "not", "any", "(", "[", "allocation", ",", "port", ",", "routing_type", ",", "routing_method", "]", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'At least one property is required to be changed!'", ")", "mgr", ".", "edit_service_group", "(", "loadbal_id", ",", "group_id", ",", "allocation", "=", "allocation", ",", "port", "=", "port", ",", "routing_type", "=", "routing_type", ",", "routing_method", "=", "routing_method", ")", "env", ".", "fout", "(", "'Load balancer service group %s is being updated!'", "%", "identifier", ")" ]
Edit an existing load balancer service group.
[ "Edit", "an", "existing", "load", "balancer", "service", "group", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/group_edit.py#L25-L43
train
234,342
softlayer/softlayer-python
SoftLayer/CLI/account/event_detail.py
cli
def cli(env, identifier, ack): """Details of a specific event, and ability to acknowledge event.""" # Print a list of all on going maintenance manager = AccountManager(env.client) event = manager.get_event(identifier) if ack: manager.ack_event(identifier) env.fout(basic_event_table(event)) env.fout(impacted_table(event)) env.fout(update_table(event))
python
def cli(env, identifier, ack): """Details of a specific event, and ability to acknowledge event.""" # Print a list of all on going maintenance manager = AccountManager(env.client) event = manager.get_event(identifier) if ack: manager.ack_event(identifier) env.fout(basic_event_table(event)) env.fout(impacted_table(event)) env.fout(update_table(event))
[ "def", "cli", "(", "env", ",", "identifier", ",", "ack", ")", ":", "# Print a list of all on going maintenance", "manager", "=", "AccountManager", "(", "env", ".", "client", ")", "event", "=", "manager", ".", "get_event", "(", "identifier", ")", "if", "ack", ":", "manager", ".", "ack_event", "(", "identifier", ")", "env", ".", "fout", "(", "basic_event_table", "(", "event", ")", ")", "env", ".", "fout", "(", "impacted_table", "(", "event", ")", ")", "env", ".", "fout", "(", "update_table", "(", "event", ")", ")" ]
Details of a specific event, and ability to acknowledge event.
[ "Details", "of", "a", "specific", "event", "and", "ability", "to", "acknowledge", "event", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/event_detail.py#L17-L29
train
234,343
softlayer/softlayer-python
SoftLayer/CLI/account/event_detail.py
basic_event_table
def basic_event_table(event): """Formats a basic event table""" table = formatting.Table(["Id", "Status", "Type", "Start", "End"], title=utils.clean_splitlines(event.get('subject'))) table.add_row([ event.get('id'), utils.lookup(event, 'statusCode', 'name'), utils.lookup(event, 'notificationOccurrenceEventType', 'keyName'), utils.clean_time(event.get('startDate')), utils.clean_time(event.get('endDate')) ]) return table
python
def basic_event_table(event): """Formats a basic event table""" table = formatting.Table(["Id", "Status", "Type", "Start", "End"], title=utils.clean_splitlines(event.get('subject'))) table.add_row([ event.get('id'), utils.lookup(event, 'statusCode', 'name'), utils.lookup(event, 'notificationOccurrenceEventType', 'keyName'), utils.clean_time(event.get('startDate')), utils.clean_time(event.get('endDate')) ]) return table
[ "def", "basic_event_table", "(", "event", ")", ":", "table", "=", "formatting", ".", "Table", "(", "[", "\"Id\"", ",", "\"Status\"", ",", "\"Type\"", ",", "\"Start\"", ",", "\"End\"", "]", ",", "title", "=", "utils", ".", "clean_splitlines", "(", "event", ".", "get", "(", "'subject'", ")", ")", ")", "table", ".", "add_row", "(", "[", "event", ".", "get", "(", "'id'", ")", ",", "utils", ".", "lookup", "(", "event", ",", "'statusCode'", ",", "'name'", ")", ",", "utils", ".", "lookup", "(", "event", ",", "'notificationOccurrenceEventType'", ",", "'keyName'", ")", ",", "utils", ".", "clean_time", "(", "event", ".", "get", "(", "'startDate'", ")", ")", ",", "utils", ".", "clean_time", "(", "event", ".", "get", "(", "'endDate'", ")", ")", "]", ")", "return", "table" ]
Formats a basic event table
[ "Formats", "a", "basic", "event", "table" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/event_detail.py#L32-L45
train
234,344
softlayer/softlayer-python
SoftLayer/CLI/account/event_detail.py
impacted_table
def impacted_table(event): """Formats a basic impacted resources table""" table = formatting.Table([ "Type", "Id", "Hostname", "PrivateIp", "Label" ]) for item in event.get('impactedResources', []): table.add_row([ item.get('resourceType'), item.get('resourceTableId'), item.get('hostname'), item.get('privateIp'), item.get('filterLabel') ]) return table
python
def impacted_table(event): """Formats a basic impacted resources table""" table = formatting.Table([ "Type", "Id", "Hostname", "PrivateIp", "Label" ]) for item in event.get('impactedResources', []): table.add_row([ item.get('resourceType'), item.get('resourceTableId'), item.get('hostname'), item.get('privateIp'), item.get('filterLabel') ]) return table
[ "def", "impacted_table", "(", "event", ")", ":", "table", "=", "formatting", ".", "Table", "(", "[", "\"Type\"", ",", "\"Id\"", ",", "\"Hostname\"", ",", "\"PrivateIp\"", ",", "\"Label\"", "]", ")", "for", "item", "in", "event", ".", "get", "(", "'impactedResources'", ",", "[", "]", ")", ":", "table", ".", "add_row", "(", "[", "item", ".", "get", "(", "'resourceType'", ")", ",", "item", ".", "get", "(", "'resourceTableId'", ")", ",", "item", ".", "get", "(", "'hostname'", ")", ",", "item", ".", "get", "(", "'privateIp'", ")", ",", "item", ".", "get", "(", "'filterLabel'", ")", "]", ")", "return", "table" ]
Formats a basic impacted resources table
[ "Formats", "a", "basic", "impacted", "resources", "table" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/event_detail.py#L48-L61
train
234,345
softlayer/softlayer-python
SoftLayer/CLI/account/event_detail.py
update_table
def update_table(event): """Formats a basic event update table""" update_number = 0 for update in event.get('updates', []): header = "======= Update #%s on %s =======" % (update_number, utils.clean_time(update.get('startDate'))) click.secho(header, fg='green') update_number = update_number + 1 text = update.get('contents') # deals with all the \r\n from the API click.secho(utils.clean_splitlines(text))
python
def update_table(event): """Formats a basic event update table""" update_number = 0 for update in event.get('updates', []): header = "======= Update #%s on %s =======" % (update_number, utils.clean_time(update.get('startDate'))) click.secho(header, fg='green') update_number = update_number + 1 text = update.get('contents') # deals with all the \r\n from the API click.secho(utils.clean_splitlines(text))
[ "def", "update_table", "(", "event", ")", ":", "update_number", "=", "0", "for", "update", "in", "event", ".", "get", "(", "'updates'", ",", "[", "]", ")", ":", "header", "=", "\"======= Update #%s on %s =======\"", "%", "(", "update_number", ",", "utils", ".", "clean_time", "(", "update", ".", "get", "(", "'startDate'", ")", ")", ")", "click", ".", "secho", "(", "header", ",", "fg", "=", "'green'", ")", "update_number", "=", "update_number", "+", "1", "text", "=", "update", ".", "get", "(", "'contents'", ")", "# deals with all the \\r\\n from the API", "click", ".", "secho", "(", "utils", ".", "clean_splitlines", "(", "text", ")", ")" ]
Formats a basic event update table
[ "Formats", "a", "basic", "event", "update", "table" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/event_detail.py#L64-L73
train
234,346
softlayer/softlayer-python
SoftLayer/CLI/block/list.py
cli
def cli(env, sortby, columns, datacenter, username, storage_type): """List block storage.""" block_manager = SoftLayer.BlockStorageManager(env.client) block_volumes = block_manager.list_block_volumes(datacenter=datacenter, username=username, storage_type=storage_type, mask=columns.mask()) table = formatting.Table(columns.columns) table.sortby = sortby for block_volume in block_volumes: table.add_row([value or formatting.blank() for value in columns.row(block_volume)]) env.fout(table)
python
def cli(env, sortby, columns, datacenter, username, storage_type): """List block storage.""" block_manager = SoftLayer.BlockStorageManager(env.client) block_volumes = block_manager.list_block_volumes(datacenter=datacenter, username=username, storage_type=storage_type, mask=columns.mask()) table = formatting.Table(columns.columns) table.sortby = sortby for block_volume in block_volumes: table.add_row([value or formatting.blank() for value in columns.row(block_volume)]) env.fout(table)
[ "def", "cli", "(", "env", ",", "sortby", ",", "columns", ",", "datacenter", ",", "username", ",", "storage_type", ")", ":", "block_manager", "=", "SoftLayer", ".", "BlockStorageManager", "(", "env", ".", "client", ")", "block_volumes", "=", "block_manager", ".", "list_block_volumes", "(", "datacenter", "=", "datacenter", ",", "username", "=", "username", ",", "storage_type", "=", "storage_type", ",", "mask", "=", "columns", ".", "mask", "(", ")", ")", "table", "=", "formatting", ".", "Table", "(", "columns", ".", "columns", ")", "table", ".", "sortby", "=", "sortby", "for", "block_volume", "in", "block_volumes", ":", "table", ".", "add_row", "(", "[", "value", "or", "formatting", ".", "blank", "(", ")", "for", "value", "in", "columns", ".", "row", "(", "block_volume", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List block storage.
[ "List", "block", "storage", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/list.py#L67-L82
train
234,347
softlayer/softlayer-python
SoftLayer/CLI/object_storage/list_endpoints.py
cli
def cli(env): """List object storage endpoints.""" mgr = SoftLayer.ObjectStorageManager(env.client) endpoints = mgr.list_endpoints() table = formatting.Table(['datacenter', 'public', 'private']) for endpoint in endpoints: table.add_row([ endpoint['datacenter']['name'], endpoint['public'], endpoint['private'], ]) env.fout(table)
python
def cli(env): """List object storage endpoints.""" mgr = SoftLayer.ObjectStorageManager(env.client) endpoints = mgr.list_endpoints() table = formatting.Table(['datacenter', 'public', 'private']) for endpoint in endpoints: table.add_row([ endpoint['datacenter']['name'], endpoint['public'], endpoint['private'], ]) env.fout(table)
[ "def", "cli", "(", "env", ")", ":", "mgr", "=", "SoftLayer", ".", "ObjectStorageManager", "(", "env", ".", "client", ")", "endpoints", "=", "mgr", ".", "list_endpoints", "(", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'datacenter'", ",", "'public'", ",", "'private'", "]", ")", "for", "endpoint", "in", "endpoints", ":", "table", ".", "add_row", "(", "[", "endpoint", "[", "'datacenter'", "]", "[", "'name'", "]", ",", "endpoint", "[", "'public'", "]", ",", "endpoint", "[", "'private'", "]", ",", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List object storage endpoints.
[ "List", "object", "storage", "endpoints", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/object_storage/list_endpoints.py#L13-L27
train
234,348
softlayer/softlayer-python
SoftLayer/CLI/virt/cancel.py
cli
def cli(env, identifier): """Cancel virtual servers.""" vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') if not (env.skip_confirmations or formatting.no_going_back(vs_id)): raise exceptions.CLIAbort('Aborted') vsi.cancel_instance(vs_id)
python
def cli(env, identifier): """Cancel virtual servers.""" vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') if not (env.skip_confirmations or formatting.no_going_back(vs_id)): raise exceptions.CLIAbort('Aborted') vsi.cancel_instance(vs_id)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "vsi", "=", "SoftLayer", ".", "VSManager", "(", "env", ".", "client", ")", "vs_id", "=", "helpers", ".", "resolve_id", "(", "vsi", ".", "resolve_ids", ",", "identifier", ",", "'VS'", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "no_going_back", "(", "vs_id", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted'", ")", "vsi", ".", "cancel_instance", "(", "vs_id", ")" ]
Cancel virtual servers.
[ "Cancel", "virtual", "servers", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/cancel.py#L16-L24
train
234,349
softlayer/softlayer-python
SoftLayer/CLI/hardware/reflash_firmware.py
cli
def cli(env, identifier): """Reflash server firmware.""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.confirm('This will power off the server with id %s and ' 'reflash device firmware. Continue?' % hw_id)): raise exceptions.CLIAbort('Aborted.') mgr.reflash_firmware(hw_id)
python
def cli(env, identifier): """Reflash server firmware.""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.confirm('This will power off the server with id %s and ' 'reflash device firmware. Continue?' % hw_id)): raise exceptions.CLIAbort('Aborted.') mgr.reflash_firmware(hw_id)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "HardwareManager", "(", "env", ".", "client", ")", "hw_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_ids", ",", "identifier", ",", "'hardware'", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "confirm", "(", "'This will power off the server with id %s and '", "'reflash device firmware. Continue?'", "%", "hw_id", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted.'", ")", "mgr", ".", "reflash_firmware", "(", "hw_id", ")" ]
Reflash server firmware.
[ "Reflash", "server", "firmware", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/reflash_firmware.py#L16-L26
train
234,350
softlayer/softlayer-python
SoftLayer/CLI/file/snapshot/schedule_list.py
cli
def cli(env, volume_id): """Lists snapshot schedules for a given volume""" file_manager = SoftLayer.FileStorageManager(env.client) snapshot_schedules = file_manager.list_volume_schedules(volume_id) table = formatting.Table(['id', 'active', 'type', 'replication', 'date_created', 'minute', 'hour', 'day', 'week', 'day_of_week', 'date_of_month', 'month_of_year', 'maximum_snapshots']) for schedule in snapshot_schedules: if 'REPLICATION' in schedule['type']['keyname']: replication = '*' else: replication = formatting.blank() file_schedule_type = schedule['type']['keyname'].replace('REPLICATION_', '') file_schedule_type = file_schedule_type.replace('SNAPSHOT_', '') property_list = ['MINUTE', 'HOUR', 'DAY', 'WEEK', 'DAY_OF_WEEK', 'DAY_OF_MONTH', 'MONTH_OF_YEAR', 'SNAPSHOT_LIMIT'] schedule_properties = [] for prop_key in property_list: item = formatting.blank() for schedule_property in schedule.get('properties', []): if schedule_property['type']['keyname'] == prop_key: if schedule_property['value'] == '-1': item = '*' else: item = schedule_property['value'] break schedule_properties.append(item) table_row = [ schedule['id'], '*' if schedule.get('active', '') else '', file_schedule_type, replication, schedule.get('createDate', '') ] table_row.extend(schedule_properties) table.add_row(table_row) env.fout(table)
python
def cli(env, volume_id): """Lists snapshot schedules for a given volume""" file_manager = SoftLayer.FileStorageManager(env.client) snapshot_schedules = file_manager.list_volume_schedules(volume_id) table = formatting.Table(['id', 'active', 'type', 'replication', 'date_created', 'minute', 'hour', 'day', 'week', 'day_of_week', 'date_of_month', 'month_of_year', 'maximum_snapshots']) for schedule in snapshot_schedules: if 'REPLICATION' in schedule['type']['keyname']: replication = '*' else: replication = formatting.blank() file_schedule_type = schedule['type']['keyname'].replace('REPLICATION_', '') file_schedule_type = file_schedule_type.replace('SNAPSHOT_', '') property_list = ['MINUTE', 'HOUR', 'DAY', 'WEEK', 'DAY_OF_WEEK', 'DAY_OF_MONTH', 'MONTH_OF_YEAR', 'SNAPSHOT_LIMIT'] schedule_properties = [] for prop_key in property_list: item = formatting.blank() for schedule_property in schedule.get('properties', []): if schedule_property['type']['keyname'] == prop_key: if schedule_property['value'] == '-1': item = '*' else: item = schedule_property['value'] break schedule_properties.append(item) table_row = [ schedule['id'], '*' if schedule.get('active', '') else '', file_schedule_type, replication, schedule.get('createDate', '') ] table_row.extend(schedule_properties) table.add_row(table_row) env.fout(table)
[ "def", "cli", "(", "env", ",", "volume_id", ")", ":", "file_manager", "=", "SoftLayer", ".", "FileStorageManager", "(", "env", ".", "client", ")", "snapshot_schedules", "=", "file_manager", ".", "list_volume_schedules", "(", "volume_id", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'active'", ",", "'type'", ",", "'replication'", ",", "'date_created'", ",", "'minute'", ",", "'hour'", ",", "'day'", ",", "'week'", ",", "'day_of_week'", ",", "'date_of_month'", ",", "'month_of_year'", ",", "'maximum_snapshots'", "]", ")", "for", "schedule", "in", "snapshot_schedules", ":", "if", "'REPLICATION'", "in", "schedule", "[", "'type'", "]", "[", "'keyname'", "]", ":", "replication", "=", "'*'", "else", ":", "replication", "=", "formatting", ".", "blank", "(", ")", "file_schedule_type", "=", "schedule", "[", "'type'", "]", "[", "'keyname'", "]", ".", "replace", "(", "'REPLICATION_'", ",", "''", ")", "file_schedule_type", "=", "file_schedule_type", ".", "replace", "(", "'SNAPSHOT_'", ",", "''", ")", "property_list", "=", "[", "'MINUTE'", ",", "'HOUR'", ",", "'DAY'", ",", "'WEEK'", ",", "'DAY_OF_WEEK'", ",", "'DAY_OF_MONTH'", ",", "'MONTH_OF_YEAR'", ",", "'SNAPSHOT_LIMIT'", "]", "schedule_properties", "=", "[", "]", "for", "prop_key", "in", "property_list", ":", "item", "=", "formatting", ".", "blank", "(", ")", "for", "schedule_property", "in", "schedule", ".", "get", "(", "'properties'", ",", "[", "]", ")", ":", "if", "schedule_property", "[", "'type'", "]", "[", "'keyname'", "]", "==", "prop_key", ":", "if", "schedule_property", "[", "'value'", "]", "==", "'-1'", ":", "item", "=", "'*'", "else", ":", "item", "=", "schedule_property", "[", "'value'", "]", "break", "schedule_properties", ".", "append", "(", "item", ")", "table_row", "=", "[", "schedule", "[", "'id'", "]", ",", "'*'", "if", "schedule", ".", "get", "(", "'active'", ",", "''", ")", "else", "''", ",", "file_schedule_type", ",", "replication", ",", "schedule", ".", "get", "(", "'createDate'", ",", "''", ")", "]", "table_row", ".", "extend", "(", "schedule_properties", ")", "table", ".", "add_row", "(", "table_row", ")", "env", ".", "fout", "(", "table", ")" ]
Lists snapshot schedules for a given volume
[ "Lists", "snapshot", "schedules", "for", "a", "given", "volume" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/snapshot/schedule_list.py#L13-L70
train
234,351
softlayer/softlayer-python
SoftLayer/CLI/firewall/list.py
cli
def cli(env): """List firewalls.""" mgr = SoftLayer.FirewallManager(env.client) table = formatting.Table(['firewall id', 'type', 'features', 'server/vlan id']) fwvlans = mgr.get_firewalls() dedicated_firewalls = [firewall for firewall in fwvlans if firewall['dedicatedFirewallFlag']] for vlan in dedicated_firewalls: features = [] if vlan['highAvailabilityFirewallFlag']: features.append('HA') if features: feature_list = formatting.listing(features, separator=',') else: feature_list = formatting.blank() table.add_row([ 'vlan:%s' % vlan['networkVlanFirewall']['id'], 'VLAN - dedicated', feature_list, vlan['id'] ]) shared_vlan = [firewall for firewall in fwvlans if not firewall['dedicatedFirewallFlag']] for vlan in shared_vlan: vs_firewalls = [guest for guest in vlan['firewallGuestNetworkComponents'] if has_firewall_component(guest)] for firewall in vs_firewalls: table.add_row([ 'vs:%s' % firewall['id'], 'Virtual Server - standard', '-', firewall['guestNetworkComponent']['guest']['id'] ]) server_firewalls = [server for server in vlan['firewallNetworkComponents'] if has_firewall_component(server)] for firewall in server_firewalls: table.add_row([ 'server:%s' % firewall['id'], 'Server - standard', '-', utils.lookup(firewall, 'networkComponent', 'downlinkComponent', 'hardwareId') ]) env.fout(table)
python
def cli(env): """List firewalls.""" mgr = SoftLayer.FirewallManager(env.client) table = formatting.Table(['firewall id', 'type', 'features', 'server/vlan id']) fwvlans = mgr.get_firewalls() dedicated_firewalls = [firewall for firewall in fwvlans if firewall['dedicatedFirewallFlag']] for vlan in dedicated_firewalls: features = [] if vlan['highAvailabilityFirewallFlag']: features.append('HA') if features: feature_list = formatting.listing(features, separator=',') else: feature_list = formatting.blank() table.add_row([ 'vlan:%s' % vlan['networkVlanFirewall']['id'], 'VLAN - dedicated', feature_list, vlan['id'] ]) shared_vlan = [firewall for firewall in fwvlans if not firewall['dedicatedFirewallFlag']] for vlan in shared_vlan: vs_firewalls = [guest for guest in vlan['firewallGuestNetworkComponents'] if has_firewall_component(guest)] for firewall in vs_firewalls: table.add_row([ 'vs:%s' % firewall['id'], 'Virtual Server - standard', '-', firewall['guestNetworkComponent']['guest']['id'] ]) server_firewalls = [server for server in vlan['firewallNetworkComponents'] if has_firewall_component(server)] for firewall in server_firewalls: table.add_row([ 'server:%s' % firewall['id'], 'Server - standard', '-', utils.lookup(firewall, 'networkComponent', 'downlinkComponent', 'hardwareId') ]) env.fout(table)
[ "def", "cli", "(", "env", ")", ":", "mgr", "=", "SoftLayer", ".", "FirewallManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'firewall id'", ",", "'type'", ",", "'features'", ",", "'server/vlan id'", "]", ")", "fwvlans", "=", "mgr", ".", "get_firewalls", "(", ")", "dedicated_firewalls", "=", "[", "firewall", "for", "firewall", "in", "fwvlans", "if", "firewall", "[", "'dedicatedFirewallFlag'", "]", "]", "for", "vlan", "in", "dedicated_firewalls", ":", "features", "=", "[", "]", "if", "vlan", "[", "'highAvailabilityFirewallFlag'", "]", ":", "features", ".", "append", "(", "'HA'", ")", "if", "features", ":", "feature_list", "=", "formatting", ".", "listing", "(", "features", ",", "separator", "=", "','", ")", "else", ":", "feature_list", "=", "formatting", ".", "blank", "(", ")", "table", ".", "add_row", "(", "[", "'vlan:%s'", "%", "vlan", "[", "'networkVlanFirewall'", "]", "[", "'id'", "]", ",", "'VLAN - dedicated'", ",", "feature_list", ",", "vlan", "[", "'id'", "]", "]", ")", "shared_vlan", "=", "[", "firewall", "for", "firewall", "in", "fwvlans", "if", "not", "firewall", "[", "'dedicatedFirewallFlag'", "]", "]", "for", "vlan", "in", "shared_vlan", ":", "vs_firewalls", "=", "[", "guest", "for", "guest", "in", "vlan", "[", "'firewallGuestNetworkComponents'", "]", "if", "has_firewall_component", "(", "guest", ")", "]", "for", "firewall", "in", "vs_firewalls", ":", "table", ".", "add_row", "(", "[", "'vs:%s'", "%", "firewall", "[", "'id'", "]", ",", "'Virtual Server - standard'", ",", "'-'", ",", "firewall", "[", "'guestNetworkComponent'", "]", "[", "'guest'", "]", "[", "'id'", "]", "]", ")", "server_firewalls", "=", "[", "server", "for", "server", "in", "vlan", "[", "'firewallNetworkComponents'", "]", "if", "has_firewall_component", "(", "server", ")", "]", "for", "firewall", "in", "server_firewalls", ":", "table", ".", "add_row", "(", "[", "'server:%s'", "%", "firewall", "[", "'id'", "]", ",", "'Server - standard'", ",", "'-'", ",", "utils", ".", "lookup", "(", "firewall", ",", "'networkComponent'", ",", "'downlinkComponent'", ",", "'hardwareId'", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List firewalls.
[ "List", "firewalls", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/list.py#L14-L73
train
234,352
softlayer/softlayer-python
SoftLayer/CLI/subnet/cancel.py
cli
def cli(env, identifier): """Cancel a subnet.""" mgr = SoftLayer.NetworkManager(env.client) subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier, name='subnet') if not (env.skip_confirmations or formatting.no_going_back(subnet_id)): raise exceptions.CLIAbort('Aborted') mgr.cancel_subnet(subnet_id)
python
def cli(env, identifier): """Cancel a subnet.""" mgr = SoftLayer.NetworkManager(env.client) subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier, name='subnet') if not (env.skip_confirmations or formatting.no_going_back(subnet_id)): raise exceptions.CLIAbort('Aborted') mgr.cancel_subnet(subnet_id)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "subnet_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_subnet_ids", ",", "identifier", ",", "name", "=", "'subnet'", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "no_going_back", "(", "subnet_id", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted'", ")", "mgr", ".", "cancel_subnet", "(", "subnet_id", ")" ]
Cancel a subnet.
[ "Cancel", "a", "subnet", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/subnet/cancel.py#L16-L26
train
234,353
softlayer/softlayer-python
SoftLayer/CLI/config/__init__.py
get_settings_from_client
def get_settings_from_client(client): """Pull out settings from a SoftLayer.BaseClient instance. :param client: SoftLayer.BaseClient instance """ settings = { 'username': '', 'api_key': '', 'timeout': '', 'endpoint_url': '', } try: settings['username'] = client.auth.username settings['api_key'] = client.auth.api_key except AttributeError: pass transport = _resolve_transport(client.transport) try: settings['timeout'] = transport.timeout settings['endpoint_url'] = transport.endpoint_url except AttributeError: pass return settings
python
def get_settings_from_client(client): """Pull out settings from a SoftLayer.BaseClient instance. :param client: SoftLayer.BaseClient instance """ settings = { 'username': '', 'api_key': '', 'timeout': '', 'endpoint_url': '', } try: settings['username'] = client.auth.username settings['api_key'] = client.auth.api_key except AttributeError: pass transport = _resolve_transport(client.transport) try: settings['timeout'] = transport.timeout settings['endpoint_url'] = transport.endpoint_url except AttributeError: pass return settings
[ "def", "get_settings_from_client", "(", "client", ")", ":", "settings", "=", "{", "'username'", ":", "''", ",", "'api_key'", ":", "''", ",", "'timeout'", ":", "''", ",", "'endpoint_url'", ":", "''", ",", "}", "try", ":", "settings", "[", "'username'", "]", "=", "client", ".", "auth", ".", "username", "settings", "[", "'api_key'", "]", "=", "client", ".", "auth", ".", "api_key", "except", "AttributeError", ":", "pass", "transport", "=", "_resolve_transport", "(", "client", ".", "transport", ")", "try", ":", "settings", "[", "'timeout'", "]", "=", "transport", ".", "timeout", "settings", "[", "'endpoint_url'", "]", "=", "transport", ".", "endpoint_url", "except", "AttributeError", ":", "pass", "return", "settings" ]
Pull out settings from a SoftLayer.BaseClient instance. :param client: SoftLayer.BaseClient instance
[ "Pull", "out", "settings", "from", "a", "SoftLayer", ".", "BaseClient", "instance", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/config/__init__.py#L16-L40
train
234,354
softlayer/softlayer-python
SoftLayer/CLI/config/__init__.py
config_table
def config_table(settings): """Returns a config table.""" table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['Username', settings['username'] or 'not set']) table.add_row(['API Key', settings['api_key'] or 'not set']) table.add_row(['Endpoint URL', settings['endpoint_url'] or 'not set']) table.add_row(['Timeout', settings['timeout'] or 'not set']) return table
python
def config_table(settings): """Returns a config table.""" table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['Username', settings['username'] or 'not set']) table.add_row(['API Key', settings['api_key'] or 'not set']) table.add_row(['Endpoint URL', settings['endpoint_url'] or 'not set']) table.add_row(['Timeout', settings['timeout'] or 'not set']) return table
[ "def", "config_table", "(", "settings", ")", ":", "table", "=", "formatting", ".", "KeyValueTable", "(", "[", "'name'", ",", "'value'", "]", ")", "table", ".", "align", "[", "'name'", "]", "=", "'r'", "table", ".", "align", "[", "'value'", "]", "=", "'l'", "table", ".", "add_row", "(", "[", "'Username'", ",", "settings", "[", "'username'", "]", "or", "'not set'", "]", ")", "table", ".", "add_row", "(", "[", "'API Key'", ",", "settings", "[", "'api_key'", "]", "or", "'not set'", "]", ")", "table", ".", "add_row", "(", "[", "'Endpoint URL'", ",", "settings", "[", "'endpoint_url'", "]", "or", "'not set'", "]", ")", "table", ".", "add_row", "(", "[", "'Timeout'", ",", "settings", "[", "'timeout'", "]", "or", "'not set'", "]", ")", "return", "table" ]
Returns a config table.
[ "Returns", "a", "config", "table", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/config/__init__.py#L43-L52
train
234,355
softlayer/softlayer-python
SoftLayer/CLI/virt/capacity/create.py
cli
def cli(env, name, backend_router_id, flavor, instances, test=False): """Create a Reserved Capacity instance. *WARNING*: Reserved Capacity is on a yearly contract and not cancelable until the contract is expired. """ manager = CapacityManager(env.client) result = manager.create( name=name, backend_router_id=backend_router_id, flavor=flavor, instances=instances, test=test) if test: table = formatting.Table(['Name', 'Value'], "Test Order") container = result['orderContainers'][0] table.add_row(['Name', container['name']]) table.add_row(['Location', container['locationObject']['longName']]) for price in container['prices']: table.add_row(['Contract', price['item']['description']]) table.add_row(['Hourly Total', result['postTaxRecurring']]) else: table = formatting.Table(['Name', 'Value'], "Reciept") table.add_row(['Order Date', result['orderDate']]) table.add_row(['Order ID', result['orderId']]) table.add_row(['status', result['placedOrder']['status']]) table.add_row(['Hourly Total', result['orderDetails']['postTaxRecurring']]) env.fout(table)
python
def cli(env, name, backend_router_id, flavor, instances, test=False): """Create a Reserved Capacity instance. *WARNING*: Reserved Capacity is on a yearly contract and not cancelable until the contract is expired. """ manager = CapacityManager(env.client) result = manager.create( name=name, backend_router_id=backend_router_id, flavor=flavor, instances=instances, test=test) if test: table = formatting.Table(['Name', 'Value'], "Test Order") container = result['orderContainers'][0] table.add_row(['Name', container['name']]) table.add_row(['Location', container['locationObject']['longName']]) for price in container['prices']: table.add_row(['Contract', price['item']['description']]) table.add_row(['Hourly Total', result['postTaxRecurring']]) else: table = formatting.Table(['Name', 'Value'], "Reciept") table.add_row(['Order Date', result['orderDate']]) table.add_row(['Order ID', result['orderId']]) table.add_row(['status', result['placedOrder']['status']]) table.add_row(['Hourly Total', result['orderDetails']['postTaxRecurring']]) env.fout(table)
[ "def", "cli", "(", "env", ",", "name", ",", "backend_router_id", ",", "flavor", ",", "instances", ",", "test", "=", "False", ")", ":", "manager", "=", "CapacityManager", "(", "env", ".", "client", ")", "result", "=", "manager", ".", "create", "(", "name", "=", "name", ",", "backend_router_id", "=", "backend_router_id", ",", "flavor", "=", "flavor", ",", "instances", "=", "instances", ",", "test", "=", "test", ")", "if", "test", ":", "table", "=", "formatting", ".", "Table", "(", "[", "'Name'", ",", "'Value'", "]", ",", "\"Test Order\"", ")", "container", "=", "result", "[", "'orderContainers'", "]", "[", "0", "]", "table", ".", "add_row", "(", "[", "'Name'", ",", "container", "[", "'name'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'Location'", ",", "container", "[", "'locationObject'", "]", "[", "'longName'", "]", "]", ")", "for", "price", "in", "container", "[", "'prices'", "]", ":", "table", ".", "add_row", "(", "[", "'Contract'", ",", "price", "[", "'item'", "]", "[", "'description'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'Hourly Total'", ",", "result", "[", "'postTaxRecurring'", "]", "]", ")", "else", ":", "table", "=", "formatting", ".", "Table", "(", "[", "'Name'", ",", "'Value'", "]", ",", "\"Reciept\"", ")", "table", ".", "add_row", "(", "[", "'Order Date'", ",", "result", "[", "'orderDate'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'Order ID'", ",", "result", "[", "'orderId'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'status'", ",", "result", "[", "'placedOrder'", "]", "[", "'status'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'Hourly Total'", ",", "result", "[", "'orderDetails'", "]", "[", "'postTaxRecurring'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Create a Reserved Capacity instance. *WARNING*: Reserved Capacity is on a yearly contract and not cancelable until the contract is expired.
[ "Create", "a", "Reserved", "Capacity", "instance", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/capacity/create.py#L24-L51
train
234,356
softlayer/softlayer-python
SoftLayer/CLI/cdn/origin_list.py
cli
def cli(env, account_id): """List origin pull mappings.""" manager = SoftLayer.CDNManager(env.client) origins = manager.get_origins(account_id) table = formatting.Table(['id', 'media_type', 'cname', 'origin_url']) for origin in origins: table.add_row([origin['id'], origin['mediaType'], origin.get('cname', formatting.blank()), origin['originUrl']]) env.fout(table)
python
def cli(env, account_id): """List origin pull mappings.""" manager = SoftLayer.CDNManager(env.client) origins = manager.get_origins(account_id) table = formatting.Table(['id', 'media_type', 'cname', 'origin_url']) for origin in origins: table.add_row([origin['id'], origin['mediaType'], origin.get('cname', formatting.blank()), origin['originUrl']]) env.fout(table)
[ "def", "cli", "(", "env", ",", "account_id", ")", ":", "manager", "=", "SoftLayer", ".", "CDNManager", "(", "env", ".", "client", ")", "origins", "=", "manager", ".", "get_origins", "(", "account_id", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'media_type'", ",", "'cname'", ",", "'origin_url'", "]", ")", "for", "origin", "in", "origins", ":", "table", ".", "add_row", "(", "[", "origin", "[", "'id'", "]", ",", "origin", "[", "'mediaType'", "]", ",", "origin", ".", "get", "(", "'cname'", ",", "formatting", ".", "blank", "(", ")", ")", ",", "origin", "[", "'originUrl'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List origin pull mappings.
[ "List", "origin", "pull", "mappings", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/cdn/origin_list.py#L14-L28
train
234,357
softlayer/softlayer-python
SoftLayer/CLI/virt/placementgroup/create_options.py
cli
def cli(env): """List options for creating a placement group.""" manager = PlacementManager(env.client) routers = manager.get_routers() env.fout(get_router_table(routers)) rules = manager.get_all_rules() env.fout(get_rule_table(rules))
python
def cli(env): """List options for creating a placement group.""" manager = PlacementManager(env.client) routers = manager.get_routers() env.fout(get_router_table(routers)) rules = manager.get_all_rules() env.fout(get_rule_table(rules))
[ "def", "cli", "(", "env", ")", ":", "manager", "=", "PlacementManager", "(", "env", ".", "client", ")", "routers", "=", "manager", ".", "get_routers", "(", ")", "env", ".", "fout", "(", "get_router_table", "(", "routers", ")", ")", "rules", "=", "manager", ".", "get_all_rules", "(", ")", "env", ".", "fout", "(", "get_rule_table", "(", "rules", ")", ")" ]
List options for creating a placement group.
[ "List", "options", "for", "creating", "a", "placement", "group", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/placementgroup/create_options.py#L13-L21
train
234,358
softlayer/softlayer-python
SoftLayer/CLI/virt/placementgroup/create_options.py
get_router_table
def get_router_table(routers): """Formats output from _get_routers and returns a table. """ table = formatting.Table(['Datacenter', 'Hostname', 'Backend Router Id'], "Available Routers") for router in routers: datacenter = router['topLevelLocation']['longName'] table.add_row([datacenter, router['hostname'], router['id']]) return table
python
def get_router_table(routers): """Formats output from _get_routers and returns a table. """ table = formatting.Table(['Datacenter', 'Hostname', 'Backend Router Id'], "Available Routers") for router in routers: datacenter = router['topLevelLocation']['longName'] table.add_row([datacenter, router['hostname'], router['id']]) return table
[ "def", "get_router_table", "(", "routers", ")", ":", "table", "=", "formatting", ".", "Table", "(", "[", "'Datacenter'", ",", "'Hostname'", ",", "'Backend Router Id'", "]", ",", "\"Available Routers\"", ")", "for", "router", "in", "routers", ":", "datacenter", "=", "router", "[", "'topLevelLocation'", "]", "[", "'longName'", "]", "table", ".", "add_row", "(", "[", "datacenter", ",", "router", "[", "'hostname'", "]", ",", "router", "[", "'id'", "]", "]", ")", "return", "table" ]
Formats output from _get_routers and returns a table.
[ "Formats", "output", "from", "_get_routers", "and", "returns", "a", "table", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/placementgroup/create_options.py#L24-L30
train
234,359
softlayer/softlayer-python
SoftLayer/CLI/virt/placementgroup/create_options.py
get_rule_table
def get_rule_table(rules): """Formats output from get_all_rules and returns a table. """ table = formatting.Table(['Id', 'KeyName'], "Rules") for rule in rules: table.add_row([rule['id'], rule['keyName']]) return table
python
def get_rule_table(rules): """Formats output from get_all_rules and returns a table. """ table = formatting.Table(['Id', 'KeyName'], "Rules") for rule in rules: table.add_row([rule['id'], rule['keyName']]) return table
[ "def", "get_rule_table", "(", "rules", ")", ":", "table", "=", "formatting", ".", "Table", "(", "[", "'Id'", ",", "'KeyName'", "]", ",", "\"Rules\"", ")", "for", "rule", "in", "rules", ":", "table", ".", "add_row", "(", "[", "rule", "[", "'id'", "]", ",", "rule", "[", "'keyName'", "]", "]", ")", "return", "table" ]
Formats output from get_all_rules and returns a table.
[ "Formats", "output", "from", "get_all_rules", "and", "returns", "a", "table", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/placementgroup/create_options.py#L33-L38
train
234,360
softlayer/softlayer-python
SoftLayer/CLI/virt/detail.py
_cli_helper_dedicated_host
def _cli_helper_dedicated_host(env, result, table): """Get details on dedicated host for a virtual server.""" dedicated_host_id = utils.lookup(result, 'dedicatedHost', 'id') if dedicated_host_id: table.add_row(['dedicated_host_id', dedicated_host_id]) # Try to find name of dedicated host try: dedicated_host = env.client.call('Virtual_DedicatedHost', 'getObject', id=dedicated_host_id) except SoftLayer.SoftLayerAPIError: LOGGER.error('Unable to get dedicated host id %s', dedicated_host_id) dedicated_host = {} table.add_row(['dedicated_host', dedicated_host.get('name') or formatting.blank()])
python
def _cli_helper_dedicated_host(env, result, table): """Get details on dedicated host for a virtual server.""" dedicated_host_id = utils.lookup(result, 'dedicatedHost', 'id') if dedicated_host_id: table.add_row(['dedicated_host_id', dedicated_host_id]) # Try to find name of dedicated host try: dedicated_host = env.client.call('Virtual_DedicatedHost', 'getObject', id=dedicated_host_id) except SoftLayer.SoftLayerAPIError: LOGGER.error('Unable to get dedicated host id %s', dedicated_host_id) dedicated_host = {} table.add_row(['dedicated_host', dedicated_host.get('name') or formatting.blank()])
[ "def", "_cli_helper_dedicated_host", "(", "env", ",", "result", ",", "table", ")", ":", "dedicated_host_id", "=", "utils", ".", "lookup", "(", "result", ",", "'dedicatedHost'", ",", "'id'", ")", "if", "dedicated_host_id", ":", "table", ".", "add_row", "(", "[", "'dedicated_host_id'", ",", "dedicated_host_id", "]", ")", "# Try to find name of dedicated host", "try", ":", "dedicated_host", "=", "env", ".", "client", ".", "call", "(", "'Virtual_DedicatedHost'", ",", "'getObject'", ",", "id", "=", "dedicated_host_id", ")", "except", "SoftLayer", ".", "SoftLayerAPIError", ":", "LOGGER", ".", "error", "(", "'Unable to get dedicated host id %s'", ",", "dedicated_host_id", ")", "dedicated_host", "=", "{", "}", "table", ".", "add_row", "(", "[", "'dedicated_host'", ",", "dedicated_host", ".", "get", "(", "'name'", ")", "or", "formatting", ".", "blank", "(", ")", "]", ")" ]
Get details on dedicated host for a virtual server.
[ "Get", "details", "on", "dedicated", "host", "for", "a", "virtual", "server", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/detail.py#L148-L162
train
234,361
softlayer/softlayer-python
SoftLayer/CLI/virt/ready.py
cli
def cli(env, identifier, wait): """Check if a virtual server is ready.""" vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') ready = vsi.wait_for_ready(vs_id, wait) if ready: env.fout("READY") else: raise exceptions.CLIAbort("Instance %s not ready" % vs_id)
python
def cli(env, identifier, wait): """Check if a virtual server is ready.""" vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') ready = vsi.wait_for_ready(vs_id, wait) if ready: env.fout("READY") else: raise exceptions.CLIAbort("Instance %s not ready" % vs_id)
[ "def", "cli", "(", "env", ",", "identifier", ",", "wait", ")", ":", "vsi", "=", "SoftLayer", ".", "VSManager", "(", "env", ".", "client", ")", "vs_id", "=", "helpers", ".", "resolve_id", "(", "vsi", ".", "resolve_ids", ",", "identifier", ",", "'VS'", ")", "ready", "=", "vsi", ".", "wait_for_ready", "(", "vs_id", ",", "wait", ")", "if", "ready", ":", "env", ".", "fout", "(", "\"READY\"", ")", "else", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Instance %s not ready\"", "%", "vs_id", ")" ]
Check if a virtual server is ready.
[ "Check", "if", "a", "virtual", "server", "is", "ready", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/ready.py#L16-L25
train
234,362
softlayer/softlayer-python
SoftLayer/CLI/block/replication/failover.py
cli
def cli(env, volume_id, replicant_id, immediate): """Failover a block volume to the given replicant volume.""" block_storage_manager = SoftLayer.BlockStorageManager(env.client) success = block_storage_manager.failover_to_replicant( volume_id, replicant_id, immediate ) if success: click.echo("Failover to replicant is now in progress.") else: click.echo("Failover operation could not be initiated.")
python
def cli(env, volume_id, replicant_id, immediate): """Failover a block volume to the given replicant volume.""" block_storage_manager = SoftLayer.BlockStorageManager(env.client) success = block_storage_manager.failover_to_replicant( volume_id, replicant_id, immediate ) if success: click.echo("Failover to replicant is now in progress.") else: click.echo("Failover operation could not be initiated.")
[ "def", "cli", "(", "env", ",", "volume_id", ",", "replicant_id", ",", "immediate", ")", ":", "block_storage_manager", "=", "SoftLayer", ".", "BlockStorageManager", "(", "env", ".", "client", ")", "success", "=", "block_storage_manager", ".", "failover_to_replicant", "(", "volume_id", ",", "replicant_id", ",", "immediate", ")", "if", "success", ":", "click", ".", "echo", "(", "\"Failover to replicant is now in progress.\"", ")", "else", ":", "click", ".", "echo", "(", "\"Failover operation could not be initiated.\"", ")" ]
Failover a block volume to the given replicant volume.
[ "Failover", "a", "block", "volume", "to", "the", "given", "replicant", "volume", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/replication/failover.py#L17-L30
train
234,363
softlayer/softlayer-python
SoftLayer/CLI/dedicatedhost/cancel.py
cli
def cli(env, identifier): """Cancel a dedicated host server immediately""" mgr = SoftLayer.DedicatedHostManager(env.client) host_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'dedicated host') if not (env.skip_confirmations or formatting.no_going_back(host_id)): raise exceptions.CLIAbort('Aborted') mgr.cancel_host(host_id) click.secho('Dedicated Host %s was cancelled' % host_id, fg='green')
python
def cli(env, identifier): """Cancel a dedicated host server immediately""" mgr = SoftLayer.DedicatedHostManager(env.client) host_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'dedicated host') if not (env.skip_confirmations or formatting.no_going_back(host_id)): raise exceptions.CLIAbort('Aborted') mgr.cancel_host(host_id) click.secho('Dedicated Host %s was cancelled' % host_id, fg='green')
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "DedicatedHostManager", "(", "env", ".", "client", ")", "host_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_ids", ",", "identifier", ",", "'dedicated host'", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "no_going_back", "(", "host_id", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted'", ")", "mgr", ".", "cancel_host", "(", "host_id", ")", "click", ".", "secho", "(", "'Dedicated Host %s was cancelled'", "%", "host_id", ",", "fg", "=", "'green'", ")" ]
Cancel a dedicated host server immediately
[ "Cancel", "a", "dedicated", "host", "server", "immediately" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dedicatedhost/cancel.py#L16-L28
train
234,364
softlayer/softlayer-python
SoftLayer/managers/image.py
ImageManager.get_image
def get_image(self, image_id, **kwargs): """Get details about an image. :param int image: The ID of the image. :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if 'mask' not in kwargs: kwargs['mask'] = IMAGE_MASK return self.vgbdtg.getObject(id=image_id, **kwargs)
python
def get_image(self, image_id, **kwargs): """Get details about an image. :param int image: The ID of the image. :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if 'mask' not in kwargs: kwargs['mask'] = IMAGE_MASK return self.vgbdtg.getObject(id=image_id, **kwargs)
[ "def", "get_image", "(", "self", ",", "image_id", ",", "*", "*", "kwargs", ")", ":", "if", "'mask'", "not", "in", "kwargs", ":", "kwargs", "[", "'mask'", "]", "=", "IMAGE_MASK", "return", "self", ".", "vgbdtg", ".", "getObject", "(", "id", "=", "image_id", ",", "*", "*", "kwargs", ")" ]
Get details about an image. :param int image: The ID of the image. :param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
[ "Get", "details", "about", "an", "image", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/image.py#L30-L39
train
234,365
softlayer/softlayer-python
SoftLayer/managers/image.py
ImageManager.list_private_images
def list_private_images(self, guid=None, name=None, **kwargs): """List all private images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if 'mask' not in kwargs: kwargs['mask'] = IMAGE_MASK _filter = utils.NestedDict(kwargs.get('filter') or {}) if name: _filter['privateBlockDeviceTemplateGroups']['name'] = ( utils.query_filter(name)) if guid: _filter['privateBlockDeviceTemplateGroups']['globalIdentifier'] = ( utils.query_filter(guid)) kwargs['filter'] = _filter.to_dict() account = self.client['Account'] return account.getPrivateBlockDeviceTemplateGroups(**kwargs)
python
def list_private_images(self, guid=None, name=None, **kwargs): """List all private images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if 'mask' not in kwargs: kwargs['mask'] = IMAGE_MASK _filter = utils.NestedDict(kwargs.get('filter') or {}) if name: _filter['privateBlockDeviceTemplateGroups']['name'] = ( utils.query_filter(name)) if guid: _filter['privateBlockDeviceTemplateGroups']['globalIdentifier'] = ( utils.query_filter(guid)) kwargs['filter'] = _filter.to_dict() account = self.client['Account'] return account.getPrivateBlockDeviceTemplateGroups(**kwargs)
[ "def", "list_private_images", "(", "self", ",", "guid", "=", "None", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'mask'", "not", "in", "kwargs", ":", "kwargs", "[", "'mask'", "]", "=", "IMAGE_MASK", "_filter", "=", "utils", ".", "NestedDict", "(", "kwargs", ".", "get", "(", "'filter'", ")", "or", "{", "}", ")", "if", "name", ":", "_filter", "[", "'privateBlockDeviceTemplateGroups'", "]", "[", "'name'", "]", "=", "(", "utils", ".", "query_filter", "(", "name", ")", ")", "if", "guid", ":", "_filter", "[", "'privateBlockDeviceTemplateGroups'", "]", "[", "'globalIdentifier'", "]", "=", "(", "utils", ".", "query_filter", "(", "guid", ")", ")", "kwargs", "[", "'filter'", "]", "=", "_filter", ".", "to_dict", "(", ")", "account", "=", "self", ".", "client", "[", "'Account'", "]", "return", "account", ".", "getPrivateBlockDeviceTemplateGroups", "(", "*", "*", "kwargs", ")" ]
List all private images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
[ "List", "all", "private", "images", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/image.py#L48-L70
train
234,366
softlayer/softlayer-python
SoftLayer/managers/image.py
ImageManager.list_public_images
def list_public_images(self, guid=None, name=None, **kwargs): """List all public images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if 'mask' not in kwargs: kwargs['mask'] = IMAGE_MASK _filter = utils.NestedDict(kwargs.get('filter') or {}) if name: _filter['name'] = utils.query_filter(name) if guid: _filter['globalIdentifier'] = utils.query_filter(guid) kwargs['filter'] = _filter.to_dict() return self.vgbdtg.getPublicImages(**kwargs)
python
def list_public_images(self, guid=None, name=None, **kwargs): """List all public images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if 'mask' not in kwargs: kwargs['mask'] = IMAGE_MASK _filter = utils.NestedDict(kwargs.get('filter') or {}) if name: _filter['name'] = utils.query_filter(name) if guid: _filter['globalIdentifier'] = utils.query_filter(guid) kwargs['filter'] = _filter.to_dict() return self.vgbdtg.getPublicImages(**kwargs)
[ "def", "list_public_images", "(", "self", ",", "guid", "=", "None", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'mask'", "not", "in", "kwargs", ":", "kwargs", "[", "'mask'", "]", "=", "IMAGE_MASK", "_filter", "=", "utils", ".", "NestedDict", "(", "kwargs", ".", "get", "(", "'filter'", ")", "or", "{", "}", ")", "if", "name", ":", "_filter", "[", "'name'", "]", "=", "utils", ".", "query_filter", "(", "name", ")", "if", "guid", ":", "_filter", "[", "'globalIdentifier'", "]", "=", "utils", ".", "query_filter", "(", "guid", ")", "kwargs", "[", "'filter'", "]", "=", "_filter", ".", "to_dict", "(", ")", "return", "self", ".", "vgbdtg", ".", "getPublicImages", "(", "*", "*", "kwargs", ")" ]
List all public images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
[ "List", "all", "public", "images", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/image.py#L72-L91
train
234,367
softlayer/softlayer-python
SoftLayer/managers/image.py
ImageManager._get_ids_from_name_public
def _get_ids_from_name_public(self, name): """Get public images which match the given name.""" results = self.list_public_images(name=name) return [result['id'] for result in results]
python
def _get_ids_from_name_public(self, name): """Get public images which match the given name.""" results = self.list_public_images(name=name) return [result['id'] for result in results]
[ "def", "_get_ids_from_name_public", "(", "self", ",", "name", ")", ":", "results", "=", "self", ".", "list_public_images", "(", "name", "=", "name", ")", "return", "[", "result", "[", "'id'", "]", "for", "result", "in", "results", "]" ]
Get public images which match the given name.
[ "Get", "public", "images", "which", "match", "the", "given", "name", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/image.py#L93-L96
train
234,368
softlayer/softlayer-python
SoftLayer/managers/image.py
ImageManager._get_ids_from_name_private
def _get_ids_from_name_private(self, name): """Get private images which match the given name.""" results = self.list_private_images(name=name) return [result['id'] for result in results]
python
def _get_ids_from_name_private(self, name): """Get private images which match the given name.""" results = self.list_private_images(name=name) return [result['id'] for result in results]
[ "def", "_get_ids_from_name_private", "(", "self", ",", "name", ")", ":", "results", "=", "self", ".", "list_private_images", "(", "name", "=", "name", ")", "return", "[", "result", "[", "'id'", "]", "for", "result", "in", "results", "]" ]
Get private images which match the given name.
[ "Get", "private", "images", "which", "match", "the", "given", "name", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/image.py#L98-L101
train
234,369
softlayer/softlayer-python
SoftLayer/managers/image.py
ImageManager.edit
def edit(self, image_id, name=None, note=None, tag=None): """Edit image related details. :param int image_id: The ID of the image :param string name: Name of the Image. :param string note: Note of the image. :param string tag: Tags of the image to be updated to. """ obj = {} if name: obj['name'] = name if note: obj['note'] = note if obj: self.vgbdtg.editObject(obj, id=image_id) if tag: self.vgbdtg.setTags(str(tag), id=image_id) return bool(name or note or tag)
python
def edit(self, image_id, name=None, note=None, tag=None): """Edit image related details. :param int image_id: The ID of the image :param string name: Name of the Image. :param string note: Note of the image. :param string tag: Tags of the image to be updated to. """ obj = {} if name: obj['name'] = name if note: obj['note'] = note if obj: self.vgbdtg.editObject(obj, id=image_id) if tag: self.vgbdtg.setTags(str(tag), id=image_id) return bool(name or note or tag)
[ "def", "edit", "(", "self", ",", "image_id", ",", "name", "=", "None", ",", "note", "=", "None", ",", "tag", "=", "None", ")", ":", "obj", "=", "{", "}", "if", "name", ":", "obj", "[", "'name'", "]", "=", "name", "if", "note", ":", "obj", "[", "'note'", "]", "=", "note", "if", "obj", ":", "self", ".", "vgbdtg", ".", "editObject", "(", "obj", ",", "id", "=", "image_id", ")", "if", "tag", ":", "self", ".", "vgbdtg", ".", "setTags", "(", "str", "(", "tag", ")", ",", "id", "=", "image_id", ")", "return", "bool", "(", "name", "or", "note", "or", "tag", ")" ]
Edit image related details. :param int image_id: The ID of the image :param string name: Name of the Image. :param string note: Note of the image. :param string tag: Tags of the image to be updated to.
[ "Edit", "image", "related", "details", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/image.py#L103-L121
train
234,370
softlayer/softlayer-python
SoftLayer/managers/image.py
ImageManager.import_image_from_uri
def import_image_from_uri(self, name, uri, os_code=None, note=None, ibm_api_key=None, root_key_crn=None, wrapped_dek=None, cloud_init=False, byol=False, is_encrypted=False): """Import a new image from object storage. :param string name: Name of the new image :param string uri: The URI for an object storage object (.vhd/.iso file) of the format: swift://<objectStorageAccount>@<cluster>/<container>/<objectPath> or (.vhd/.iso/.raw file) of the format: cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud Object Storage :param string os_code: The reference code of the operating system :param string note: Note to add to the image :param string ibm_api_key: Ibm Api Key needed to communicate with ICOS and your KMS :param string root_key_crn: CRN of the root key in your KMS. Go to your KMS (Key Protect or Hyper Protect) provider to get the CRN for your root key. An example CRN: crn:v1:bluemix:public:hs-crypto:us-south:acctID:serviceID:key:keyID' Used only when is_encrypted is True. :param string wrapped_dek: Wrapped Data Encryption Key provided by your KMS. Used only when is_encrypted is True. :param boolean cloud_init: Specifies if image is cloud-init :param boolean byol: Specifies if image is bring your own license :param boolean is_encrypted: Specifies if image is encrypted """ if 'cos://' in uri: return self.vgbdtg.createFromIcos({ 'name': name, 'note': note, 'operatingSystemReferenceCode': os_code, 'uri': uri, 'ibmApiKey': ibm_api_key, 'crkCrn': root_key_crn, 'wrappedDek': wrapped_dek, 'cloudInit': cloud_init, 'byol': byol, 'isEncrypted': is_encrypted }) else: return self.vgbdtg.createFromExternalSource({ 'name': name, 'note': note, 'operatingSystemReferenceCode': os_code, 'uri': uri, })
python
def import_image_from_uri(self, name, uri, os_code=None, note=None, ibm_api_key=None, root_key_crn=None, wrapped_dek=None, cloud_init=False, byol=False, is_encrypted=False): """Import a new image from object storage. :param string name: Name of the new image :param string uri: The URI for an object storage object (.vhd/.iso file) of the format: swift://<objectStorageAccount>@<cluster>/<container>/<objectPath> or (.vhd/.iso/.raw file) of the format: cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud Object Storage :param string os_code: The reference code of the operating system :param string note: Note to add to the image :param string ibm_api_key: Ibm Api Key needed to communicate with ICOS and your KMS :param string root_key_crn: CRN of the root key in your KMS. Go to your KMS (Key Protect or Hyper Protect) provider to get the CRN for your root key. An example CRN: crn:v1:bluemix:public:hs-crypto:us-south:acctID:serviceID:key:keyID' Used only when is_encrypted is True. :param string wrapped_dek: Wrapped Data Encryption Key provided by your KMS. Used only when is_encrypted is True. :param boolean cloud_init: Specifies if image is cloud-init :param boolean byol: Specifies if image is bring your own license :param boolean is_encrypted: Specifies if image is encrypted """ if 'cos://' in uri: return self.vgbdtg.createFromIcos({ 'name': name, 'note': note, 'operatingSystemReferenceCode': os_code, 'uri': uri, 'ibmApiKey': ibm_api_key, 'crkCrn': root_key_crn, 'wrappedDek': wrapped_dek, 'cloudInit': cloud_init, 'byol': byol, 'isEncrypted': is_encrypted }) else: return self.vgbdtg.createFromExternalSource({ 'name': name, 'note': note, 'operatingSystemReferenceCode': os_code, 'uri': uri, })
[ "def", "import_image_from_uri", "(", "self", ",", "name", ",", "uri", ",", "os_code", "=", "None", ",", "note", "=", "None", ",", "ibm_api_key", "=", "None", ",", "root_key_crn", "=", "None", ",", "wrapped_dek", "=", "None", ",", "cloud_init", "=", "False", ",", "byol", "=", "False", ",", "is_encrypted", "=", "False", ")", ":", "if", "'cos://'", "in", "uri", ":", "return", "self", ".", "vgbdtg", ".", "createFromIcos", "(", "{", "'name'", ":", "name", ",", "'note'", ":", "note", ",", "'operatingSystemReferenceCode'", ":", "os_code", ",", "'uri'", ":", "uri", ",", "'ibmApiKey'", ":", "ibm_api_key", ",", "'crkCrn'", ":", "root_key_crn", ",", "'wrappedDek'", ":", "wrapped_dek", ",", "'cloudInit'", ":", "cloud_init", ",", "'byol'", ":", "byol", ",", "'isEncrypted'", ":", "is_encrypted", "}", ")", "else", ":", "return", "self", ".", "vgbdtg", ".", "createFromExternalSource", "(", "{", "'name'", ":", "name", ",", "'note'", ":", "note", ",", "'operatingSystemReferenceCode'", ":", "os_code", ",", "'uri'", ":", "uri", ",", "}", ")" ]
Import a new image from object storage. :param string name: Name of the new image :param string uri: The URI for an object storage object (.vhd/.iso file) of the format: swift://<objectStorageAccount>@<cluster>/<container>/<objectPath> or (.vhd/.iso/.raw file) of the format: cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud Object Storage :param string os_code: The reference code of the operating system :param string note: Note to add to the image :param string ibm_api_key: Ibm Api Key needed to communicate with ICOS and your KMS :param string root_key_crn: CRN of the root key in your KMS. Go to your KMS (Key Protect or Hyper Protect) provider to get the CRN for your root key. An example CRN: crn:v1:bluemix:public:hs-crypto:us-south:acctID:serviceID:key:keyID' Used only when is_encrypted is True. :param string wrapped_dek: Wrapped Data Encryption Key provided by your KMS. Used only when is_encrypted is True. :param boolean cloud_init: Specifies if image is cloud-init :param boolean byol: Specifies if image is bring your own license :param boolean is_encrypted: Specifies if image is encrypted
[ "Import", "a", "new", "image", "from", "object", "storage", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/image.py#L123-L170
train
234,371
softlayer/softlayer-python
SoftLayer/managers/image.py
ImageManager.export_image_to_uri
def export_image_to_uri(self, image_id, uri, ibm_api_key=None): """Export image into the given object storage :param int image_id: The ID of the image :param string uri: The URI for object storage of the format swift://<objectStorageAccount>@<cluster>/<container>/<objectPath> or cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud Object Storage :param string ibm_api_key: Ibm Api Key needed to communicate with IBM Cloud Object Storage """ if 'cos://' in uri: return self.vgbdtg.copyToIcos({ 'uri': uri, 'ibmApiKey': ibm_api_key }, id=image_id) else: return self.vgbdtg.copyToExternalSource({'uri': uri}, id=image_id)
python
def export_image_to_uri(self, image_id, uri, ibm_api_key=None): """Export image into the given object storage :param int image_id: The ID of the image :param string uri: The URI for object storage of the format swift://<objectStorageAccount>@<cluster>/<container>/<objectPath> or cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud Object Storage :param string ibm_api_key: Ibm Api Key needed to communicate with IBM Cloud Object Storage """ if 'cos://' in uri: return self.vgbdtg.copyToIcos({ 'uri': uri, 'ibmApiKey': ibm_api_key }, id=image_id) else: return self.vgbdtg.copyToExternalSource({'uri': uri}, id=image_id)
[ "def", "export_image_to_uri", "(", "self", ",", "image_id", ",", "uri", ",", "ibm_api_key", "=", "None", ")", ":", "if", "'cos://'", "in", "uri", ":", "return", "self", ".", "vgbdtg", ".", "copyToIcos", "(", "{", "'uri'", ":", "uri", ",", "'ibmApiKey'", ":", "ibm_api_key", "}", ",", "id", "=", "image_id", ")", "else", ":", "return", "self", ".", "vgbdtg", ".", "copyToExternalSource", "(", "{", "'uri'", ":", "uri", "}", ",", "id", "=", "image_id", ")" ]
Export image into the given object storage :param int image_id: The ID of the image :param string uri: The URI for object storage of the format swift://<objectStorageAccount>@<cluster>/<container>/<objectPath> or cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud Object Storage :param string ibm_api_key: Ibm Api Key needed to communicate with IBM Cloud Object Storage
[ "Export", "image", "into", "the", "given", "object", "storage" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/image.py#L172-L189
train
234,372
softlayer/softlayer-python
SoftLayer/CLI/object_storage/credential/delete.py
cli
def cli(env, identifier, credential_id): """Delete the credential of an Object Storage Account.""" mgr = SoftLayer.ObjectStorageManager(env.client) credential = mgr.delete_credential(identifier, credential_id=credential_id) env.fout(credential)
python
def cli(env, identifier, credential_id): """Delete the credential of an Object Storage Account.""" mgr = SoftLayer.ObjectStorageManager(env.client) credential = mgr.delete_credential(identifier, credential_id=credential_id) env.fout(credential)
[ "def", "cli", "(", "env", ",", "identifier", ",", "credential_id", ")", ":", "mgr", "=", "SoftLayer", ".", "ObjectStorageManager", "(", "env", ".", "client", ")", "credential", "=", "mgr", ".", "delete_credential", "(", "identifier", ",", "credential_id", "=", "credential_id", ")", "env", ".", "fout", "(", "credential", ")" ]
Delete the credential of an Object Storage Account.
[ "Delete", "the", "credential", "of", "an", "Object", "Storage", "Account", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/object_storage/credential/delete.py#L15-L21
train
234,373
softlayer/softlayer-python
SoftLayer/managers/vs_capacity.py
CapacityManager.list
def list(self): """List Reserved Capacities""" mask = """mask[availableInstanceCount, occupiedInstanceCount, instances[id, billingItem[description, hourlyRecurringFee]], instanceCount, backendRouter[datacenter]]""" results = self.client.call('Account', 'getReservedCapacityGroups', mask=mask) return results
python
def list(self): """List Reserved Capacities""" mask = """mask[availableInstanceCount, occupiedInstanceCount, instances[id, billingItem[description, hourlyRecurringFee]], instanceCount, backendRouter[datacenter]]""" results = self.client.call('Account', 'getReservedCapacityGroups', mask=mask) return results
[ "def", "list", "(", "self", ")", ":", "mask", "=", "\"\"\"mask[availableInstanceCount, occupiedInstanceCount,\ninstances[id, billingItem[description, hourlyRecurringFee]], instanceCount, backendRouter[datacenter]]\"\"\"", "results", "=", "self", ".", "client", ".", "call", "(", "'Account'", ",", "'getReservedCapacityGroups'", ",", "mask", "=", "mask", ")", "return", "results" ]
List Reserved Capacities
[ "List", "Reserved", "Capacities" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs_capacity.py#L46-L51
train
234,374
softlayer/softlayer-python
SoftLayer/managers/vs_capacity.py
CapacityManager.get_object
def get_object(self, identifier, mask=None): """Get a Reserved Capacity Group :param int identifier: Id of the SoftLayer_Virtual_ReservedCapacityGroup :param string mask: override default object Mask """ if mask is None: mask = "mask[instances[billingItem[item[keyName],category], guest], backendRouter[datacenter]]" result = self.client.call(self.rcg_service, 'getObject', id=identifier, mask=mask) return result
python
def get_object(self, identifier, mask=None): """Get a Reserved Capacity Group :param int identifier: Id of the SoftLayer_Virtual_ReservedCapacityGroup :param string mask: override default object Mask """ if mask is None: mask = "mask[instances[billingItem[item[keyName],category], guest], backendRouter[datacenter]]" result = self.client.call(self.rcg_service, 'getObject', id=identifier, mask=mask) return result
[ "def", "get_object", "(", "self", ",", "identifier", ",", "mask", "=", "None", ")", ":", "if", "mask", "is", "None", ":", "mask", "=", "\"mask[instances[billingItem[item[keyName],category], guest], backendRouter[datacenter]]\"", "result", "=", "self", ".", "client", ".", "call", "(", "self", ".", "rcg_service", ",", "'getObject'", ",", "id", "=", "identifier", ",", "mask", "=", "mask", ")", "return", "result" ]
Get a Reserved Capacity Group :param int identifier: Id of the SoftLayer_Virtual_ReservedCapacityGroup :param string mask: override default object Mask
[ "Get", "a", "Reserved", "Capacity", "Group" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs_capacity.py#L53-L62
train
234,375
softlayer/softlayer-python
SoftLayer/managers/vs_capacity.py
CapacityManager.get_create_options
def get_create_options(self): """List available reserved capacity plans""" mask = "mask[attributes,prices[pricingLocationGroup]]" results = self.ordering_manager.list_items(self.capacity_package, mask=mask) return results
python
def get_create_options(self): """List available reserved capacity plans""" mask = "mask[attributes,prices[pricingLocationGroup]]" results = self.ordering_manager.list_items(self.capacity_package, mask=mask) return results
[ "def", "get_create_options", "(", "self", ")", ":", "mask", "=", "\"mask[attributes,prices[pricingLocationGroup]]\"", "results", "=", "self", ".", "ordering_manager", ".", "list_items", "(", "self", ".", "capacity_package", ",", "mask", "=", "mask", ")", "return", "results" ]
List available reserved capacity plans
[ "List", "available", "reserved", "capacity", "plans" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs_capacity.py#L64-L68
train
234,376
softlayer/softlayer-python
SoftLayer/managers/vs_capacity.py
CapacityManager.get_available_routers
def get_available_routers(self, dc=None): """Pulls down all backendRouterIds that are available :param string dc: A specific location to get routers for, like 'dal13'. :returns list: A list of locations where RESERVED_CAPACITY can be ordered. """ mask = "mask[locations]" # Step 1, get the package id package = self.ordering_manager.get_package_by_key(self.capacity_package, mask="id") # Step 2, get the regions this package is orderable in regions = self.client.call('Product_Package', 'getRegions', id=package['id'], mask=mask, iter=True) _filter = None routers = {} if dc is not None: _filter = {'datacenterName': {'operation': dc}} # Step 3, for each location in each region, get the pod details, which contains the router id pods = self.client.call('Network_Pod', 'getAllObjects', filter=_filter, iter=True) for region in regions: routers[region['keyname']] = [] for location in region['locations']: location['location']['pods'] = list() for pod in pods: if pod['datacenterName'] == location['location']['name']: location['location']['pods'].append(pod) # Step 4, return the data. return regions
python
def get_available_routers(self, dc=None): """Pulls down all backendRouterIds that are available :param string dc: A specific location to get routers for, like 'dal13'. :returns list: A list of locations where RESERVED_CAPACITY can be ordered. """ mask = "mask[locations]" # Step 1, get the package id package = self.ordering_manager.get_package_by_key(self.capacity_package, mask="id") # Step 2, get the regions this package is orderable in regions = self.client.call('Product_Package', 'getRegions', id=package['id'], mask=mask, iter=True) _filter = None routers = {} if dc is not None: _filter = {'datacenterName': {'operation': dc}} # Step 3, for each location in each region, get the pod details, which contains the router id pods = self.client.call('Network_Pod', 'getAllObjects', filter=_filter, iter=True) for region in regions: routers[region['keyname']] = [] for location in region['locations']: location['location']['pods'] = list() for pod in pods: if pod['datacenterName'] == location['location']['name']: location['location']['pods'].append(pod) # Step 4, return the data. return regions
[ "def", "get_available_routers", "(", "self", ",", "dc", "=", "None", ")", ":", "mask", "=", "\"mask[locations]\"", "# Step 1, get the package id", "package", "=", "self", ".", "ordering_manager", ".", "get_package_by_key", "(", "self", ".", "capacity_package", ",", "mask", "=", "\"id\"", ")", "# Step 2, get the regions this package is orderable in", "regions", "=", "self", ".", "client", ".", "call", "(", "'Product_Package'", ",", "'getRegions'", ",", "id", "=", "package", "[", "'id'", "]", ",", "mask", "=", "mask", ",", "iter", "=", "True", ")", "_filter", "=", "None", "routers", "=", "{", "}", "if", "dc", "is", "not", "None", ":", "_filter", "=", "{", "'datacenterName'", ":", "{", "'operation'", ":", "dc", "}", "}", "# Step 3, for each location in each region, get the pod details, which contains the router id", "pods", "=", "self", ".", "client", ".", "call", "(", "'Network_Pod'", ",", "'getAllObjects'", ",", "filter", "=", "_filter", ",", "iter", "=", "True", ")", "for", "region", "in", "regions", ":", "routers", "[", "region", "[", "'keyname'", "]", "]", "=", "[", "]", "for", "location", "in", "region", "[", "'locations'", "]", ":", "location", "[", "'location'", "]", "[", "'pods'", "]", "=", "list", "(", ")", "for", "pod", "in", "pods", ":", "if", "pod", "[", "'datacenterName'", "]", "==", "location", "[", "'location'", "]", "[", "'name'", "]", ":", "location", "[", "'location'", "]", "[", "'pods'", "]", ".", "append", "(", "pod", ")", "# Step 4, return the data.", "return", "regions" ]
Pulls down all backendRouterIds that are available :param string dc: A specific location to get routers for, like 'dal13'. :returns list: A list of locations where RESERVED_CAPACITY can be ordered.
[ "Pulls", "down", "all", "backendRouterIds", "that", "are", "available" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs_capacity.py#L70-L98
train
234,377
softlayer/softlayer-python
SoftLayer/managers/vs_capacity.py
CapacityManager.create
def create(self, name, backend_router_id, flavor, instances, test=False): """Orders a Virtual_ReservedCapacityGroup :param string name: Name for the new reserved capacity :param int backend_router_id: This selects the pod. See create_options for a list :param string flavor: Capacity KeyName, see create_options for a list :param int instances: Number of guest this capacity can support :param bool test: If True, don't actually order, just test. """ # Since orderManger needs a DC id, just send in 0, the API will ignore it args = (self.capacity_package, 0, [flavor]) extras = {"backendRouterId": backend_router_id, "name": name} kwargs = { 'extras': extras, 'quantity': instances, 'complex_type': 'SoftLayer_Container_Product_Order_Virtual_ReservedCapacity', 'hourly': True } if test: receipt = self.ordering_manager.verify_order(*args, **kwargs) else: receipt = self.ordering_manager.place_order(*args, **kwargs) return receipt
python
def create(self, name, backend_router_id, flavor, instances, test=False): """Orders a Virtual_ReservedCapacityGroup :param string name: Name for the new reserved capacity :param int backend_router_id: This selects the pod. See create_options for a list :param string flavor: Capacity KeyName, see create_options for a list :param int instances: Number of guest this capacity can support :param bool test: If True, don't actually order, just test. """ # Since orderManger needs a DC id, just send in 0, the API will ignore it args = (self.capacity_package, 0, [flavor]) extras = {"backendRouterId": backend_router_id, "name": name} kwargs = { 'extras': extras, 'quantity': instances, 'complex_type': 'SoftLayer_Container_Product_Order_Virtual_ReservedCapacity', 'hourly': True } if test: receipt = self.ordering_manager.verify_order(*args, **kwargs) else: receipt = self.ordering_manager.place_order(*args, **kwargs) return receipt
[ "def", "create", "(", "self", ",", "name", ",", "backend_router_id", ",", "flavor", ",", "instances", ",", "test", "=", "False", ")", ":", "# Since orderManger needs a DC id, just send in 0, the API will ignore it", "args", "=", "(", "self", ".", "capacity_package", ",", "0", ",", "[", "flavor", "]", ")", "extras", "=", "{", "\"backendRouterId\"", ":", "backend_router_id", ",", "\"name\"", ":", "name", "}", "kwargs", "=", "{", "'extras'", ":", "extras", ",", "'quantity'", ":", "instances", ",", "'complex_type'", ":", "'SoftLayer_Container_Product_Order_Virtual_ReservedCapacity'", ",", "'hourly'", ":", "True", "}", "if", "test", ":", "receipt", "=", "self", ".", "ordering_manager", ".", "verify_order", "(", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "receipt", "=", "self", ".", "ordering_manager", ".", "place_order", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "receipt" ]
Orders a Virtual_ReservedCapacityGroup :param string name: Name for the new reserved capacity :param int backend_router_id: This selects the pod. See create_options for a list :param string flavor: Capacity KeyName, see create_options for a list :param int instances: Number of guest this capacity can support :param bool test: If True, don't actually order, just test.
[ "Orders", "a", "Virtual_ReservedCapacityGroup" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs_capacity.py#L100-L123
train
234,378
softlayer/softlayer-python
SoftLayer/managers/vs_capacity.py
CapacityManager.create_guest
def create_guest(self, capacity_id, test, guest_object): """Turns an empty Reserve Capacity into a real Virtual Guest :param int capacity_id: ID of the RESERVED_CAPACITY_GROUP to create this guest into :param bool test: True will use verifyOrder, False will use placeOrder :param dictionary guest_object: Below is the minimum info you need to send in guest_object = { 'domain': 'test.com', 'hostname': 'A1538172419', 'os_code': 'UBUNTU_LATEST_64', 'primary_disk': '25', } """ vs_manager = VSManager(self.client) mask = "mask[instances[id, billingItem[id, item[id,keyName]]], backendRouter[id, datacenter[name]]]" capacity = self.get_object(capacity_id, mask=mask) try: capacity_flavor = capacity['instances'][0]['billingItem']['item']['keyName'] flavor = _flavor_string(capacity_flavor, guest_object['primary_disk']) except KeyError: raise SoftLayer.SoftLayerError("Unable to find capacity Flavor.") guest_object['flavor'] = flavor guest_object['datacenter'] = capacity['backendRouter']['datacenter']['name'] # Reserved capacity only supports SAN as of 20181008 guest_object['local_disk'] = False template = vs_manager.verify_create_instance(**guest_object) template['reservedCapacityId'] = capacity_id if guest_object.get('ipv6'): ipv6_price = self.ordering_manager.get_price_id_list('PUBLIC_CLOUD_SERVER', ['1_IPV6_ADDRESS']) template['prices'].append({'id': ipv6_price[0]}) if test: result = self.client.call('Product_Order', 'verifyOrder', template) else: result = self.client.call('Product_Order', 'placeOrder', template) return result
python
def create_guest(self, capacity_id, test, guest_object): """Turns an empty Reserve Capacity into a real Virtual Guest :param int capacity_id: ID of the RESERVED_CAPACITY_GROUP to create this guest into :param bool test: True will use verifyOrder, False will use placeOrder :param dictionary guest_object: Below is the minimum info you need to send in guest_object = { 'domain': 'test.com', 'hostname': 'A1538172419', 'os_code': 'UBUNTU_LATEST_64', 'primary_disk': '25', } """ vs_manager = VSManager(self.client) mask = "mask[instances[id, billingItem[id, item[id,keyName]]], backendRouter[id, datacenter[name]]]" capacity = self.get_object(capacity_id, mask=mask) try: capacity_flavor = capacity['instances'][0]['billingItem']['item']['keyName'] flavor = _flavor_string(capacity_flavor, guest_object['primary_disk']) except KeyError: raise SoftLayer.SoftLayerError("Unable to find capacity Flavor.") guest_object['flavor'] = flavor guest_object['datacenter'] = capacity['backendRouter']['datacenter']['name'] # Reserved capacity only supports SAN as of 20181008 guest_object['local_disk'] = False template = vs_manager.verify_create_instance(**guest_object) template['reservedCapacityId'] = capacity_id if guest_object.get('ipv6'): ipv6_price = self.ordering_manager.get_price_id_list('PUBLIC_CLOUD_SERVER', ['1_IPV6_ADDRESS']) template['prices'].append({'id': ipv6_price[0]}) if test: result = self.client.call('Product_Order', 'verifyOrder', template) else: result = self.client.call('Product_Order', 'placeOrder', template) return result
[ "def", "create_guest", "(", "self", ",", "capacity_id", ",", "test", ",", "guest_object", ")", ":", "vs_manager", "=", "VSManager", "(", "self", ".", "client", ")", "mask", "=", "\"mask[instances[id, billingItem[id, item[id,keyName]]], backendRouter[id, datacenter[name]]]\"", "capacity", "=", "self", ".", "get_object", "(", "capacity_id", ",", "mask", "=", "mask", ")", "try", ":", "capacity_flavor", "=", "capacity", "[", "'instances'", "]", "[", "0", "]", "[", "'billingItem'", "]", "[", "'item'", "]", "[", "'keyName'", "]", "flavor", "=", "_flavor_string", "(", "capacity_flavor", ",", "guest_object", "[", "'primary_disk'", "]", ")", "except", "KeyError", ":", "raise", "SoftLayer", ".", "SoftLayerError", "(", "\"Unable to find capacity Flavor.\"", ")", "guest_object", "[", "'flavor'", "]", "=", "flavor", "guest_object", "[", "'datacenter'", "]", "=", "capacity", "[", "'backendRouter'", "]", "[", "'datacenter'", "]", "[", "'name'", "]", "# Reserved capacity only supports SAN as of 20181008", "guest_object", "[", "'local_disk'", "]", "=", "False", "template", "=", "vs_manager", ".", "verify_create_instance", "(", "*", "*", "guest_object", ")", "template", "[", "'reservedCapacityId'", "]", "=", "capacity_id", "if", "guest_object", ".", "get", "(", "'ipv6'", ")", ":", "ipv6_price", "=", "self", ".", "ordering_manager", ".", "get_price_id_list", "(", "'PUBLIC_CLOUD_SERVER'", ",", "[", "'1_IPV6_ADDRESS'", "]", ")", "template", "[", "'prices'", "]", ".", "append", "(", "{", "'id'", ":", "ipv6_price", "[", "0", "]", "}", ")", "if", "test", ":", "result", "=", "self", ".", "client", ".", "call", "(", "'Product_Order'", ",", "'verifyOrder'", ",", "template", ")", "else", ":", "result", "=", "self", ".", "client", ".", "call", "(", "'Product_Order'", ",", "'placeOrder'", ",", "template", ")", "return", "result" ]
Turns an empty Reserve Capacity into a real Virtual Guest :param int capacity_id: ID of the RESERVED_CAPACITY_GROUP to create this guest into :param bool test: True will use verifyOrder, False will use placeOrder :param dictionary guest_object: Below is the minimum info you need to send in guest_object = { 'domain': 'test.com', 'hostname': 'A1538172419', 'os_code': 'UBUNTU_LATEST_64', 'primary_disk': '25', }
[ "Turns", "an", "empty", "Reserve", "Capacity", "into", "a", "real", "Virtual", "Guest" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs_capacity.py#L125-L165
train
234,379
softlayer/softlayer-python
SoftLayer/CLI/virt/capacity/list.py
cli
def cli(env): """List Reserved Capacity groups.""" manager = CapacityManager(env.client) result = manager.list() table = formatting.Table( ["ID", "Name", "Capacity", "Flavor", "Location", "Created"], title="Reserved Capacity" ) for r_c in result: occupied_string = "#" * int(r_c.get('occupiedInstanceCount', 0)) available_string = "-" * int(r_c.get('availableInstanceCount', 0)) try: flavor = r_c['instances'][0]['billingItem']['description'] # cost = float(r_c['instances'][0]['billingItem']['hourlyRecurringFee']) except KeyError: flavor = "Unknown Billing Item" location = r_c['backendRouter']['hostname'] capacity = "%s%s" % (occupied_string, available_string) table.add_row([r_c['id'], r_c['name'], capacity, flavor, location, r_c['createDate']]) env.fout(table)
python
def cli(env): """List Reserved Capacity groups.""" manager = CapacityManager(env.client) result = manager.list() table = formatting.Table( ["ID", "Name", "Capacity", "Flavor", "Location", "Created"], title="Reserved Capacity" ) for r_c in result: occupied_string = "#" * int(r_c.get('occupiedInstanceCount', 0)) available_string = "-" * int(r_c.get('availableInstanceCount', 0)) try: flavor = r_c['instances'][0]['billingItem']['description'] # cost = float(r_c['instances'][0]['billingItem']['hourlyRecurringFee']) except KeyError: flavor = "Unknown Billing Item" location = r_c['backendRouter']['hostname'] capacity = "%s%s" % (occupied_string, available_string) table.add_row([r_c['id'], r_c['name'], capacity, flavor, location, r_c['createDate']]) env.fout(table)
[ "def", "cli", "(", "env", ")", ":", "manager", "=", "CapacityManager", "(", "env", ".", "client", ")", "result", "=", "manager", ".", "list", "(", ")", "table", "=", "formatting", ".", "Table", "(", "[", "\"ID\"", ",", "\"Name\"", ",", "\"Capacity\"", ",", "\"Flavor\"", ",", "\"Location\"", ",", "\"Created\"", "]", ",", "title", "=", "\"Reserved Capacity\"", ")", "for", "r_c", "in", "result", ":", "occupied_string", "=", "\"#\"", "*", "int", "(", "r_c", ".", "get", "(", "'occupiedInstanceCount'", ",", "0", ")", ")", "available_string", "=", "\"-\"", "*", "int", "(", "r_c", ".", "get", "(", "'availableInstanceCount'", ",", "0", ")", ")", "try", ":", "flavor", "=", "r_c", "[", "'instances'", "]", "[", "0", "]", "[", "'billingItem'", "]", "[", "'description'", "]", "# cost = float(r_c['instances'][0]['billingItem']['hourlyRecurringFee'])", "except", "KeyError", ":", "flavor", "=", "\"Unknown Billing Item\"", "location", "=", "r_c", "[", "'backendRouter'", "]", "[", "'hostname'", "]", "capacity", "=", "\"%s%s\"", "%", "(", "occupied_string", ",", "available_string", ")", "table", ".", "add_row", "(", "[", "r_c", "[", "'id'", "]", ",", "r_c", "[", "'name'", "]", ",", "capacity", ",", "flavor", ",", "location", ",", "r_c", "[", "'createDate'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List Reserved Capacity groups.
[ "List", "Reserved", "Capacity", "groups", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/capacity/list.py#L12-L32
train
234,380
softlayer/softlayer-python
SoftLayer/CLI/order/place_quote.py
cli
def cli(env, package_keyname, location, preset, name, send_email, complex_type, extras, order_items): """Place a quote. This CLI command is used for creating a quote of the specified package in the given location (denoted by a datacenter's long name). Orders made via the CLI can then be converted to be made programmatically by calling SoftLayer.OrderingManager.place_quote() with the same keynames. Packages for ordering can be retrieved from `slcli order package-list` Presets for ordering can be retrieved from `slcli order preset-list` (not all packages have presets) Items can be retrieved from `slcli order item-list`. In order to find required items for the order, use `slcli order category-list`, and then provide the --category option for each category code in `slcli order item-list`. Example:: # Place quote a VSI with 4 CPU, 16 GB RAM, 100 GB SAN disk, # Ubuntu 16.04, and 1 Gbps public & private uplink in dal13 slcli order place-quote --name "foobar" --send-email CLOUD_SERVER DALLAS13 \\ GUEST_CORES_4 \\ RAM_16_GB \\ REBOOT_REMOTE_CONSOLE \\ 1_GBPS_PUBLIC_PRIVATE_NETWORK_UPLINKS \\ BANDWIDTH_0_GB_2 \\ 1_IP_ADDRESS \\ GUEST_DISK_100_GB_SAN \\ OS_UBUNTU_16_04_LTS_XENIAL_XERUS_MINIMAL_64_BIT_FOR_VSI \\ MONITORING_HOST_PING \\ NOTIFICATION_EMAIL_AND_TICKET \\ AUTOMATED_NOTIFICATION \\ UNLIMITED_SSL_VPN_USERS_1_PPTP_VPN_USER_PER_ACCOUNT \\ NESSUS_VULNERABILITY_ASSESSMENT_REPORTING \\ --extras '{"virtualGuests": [{"hostname": "test", "domain": "softlayer.com"}]}' \\ --complex-type SoftLayer_Container_Product_Order_Virtual_Guest """ manager = ordering.OrderingManager(env.client) if extras: try: extras = json.loads(extras) except ValueError as err: raise exceptions.CLIAbort("There was an error when parsing the --extras value: {}".format(err)) args = (package_keyname, location, order_items) kwargs = {'preset_keyname': preset, 'extras': extras, 'quantity': 1, 'quote_name': name, 'send_email': send_email, 'complex_type': complex_type} order = manager.place_quote(*args, **kwargs) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', order['quote']['id']]) table.add_row(['name', order['quote']['name']]) table.add_row(['created', order['orderDate']]) table.add_row(['expires', order['quote']['expirationDate']]) table.add_row(['status', order['quote']['status']]) env.fout(table)
python
def cli(env, package_keyname, location, preset, name, send_email, complex_type, extras, order_items): """Place a quote. This CLI command is used for creating a quote of the specified package in the given location (denoted by a datacenter's long name). Orders made via the CLI can then be converted to be made programmatically by calling SoftLayer.OrderingManager.place_quote() with the same keynames. Packages for ordering can be retrieved from `slcli order package-list` Presets for ordering can be retrieved from `slcli order preset-list` (not all packages have presets) Items can be retrieved from `slcli order item-list`. In order to find required items for the order, use `slcli order category-list`, and then provide the --category option for each category code in `slcli order item-list`. Example:: # Place quote a VSI with 4 CPU, 16 GB RAM, 100 GB SAN disk, # Ubuntu 16.04, and 1 Gbps public & private uplink in dal13 slcli order place-quote --name "foobar" --send-email CLOUD_SERVER DALLAS13 \\ GUEST_CORES_4 \\ RAM_16_GB \\ REBOOT_REMOTE_CONSOLE \\ 1_GBPS_PUBLIC_PRIVATE_NETWORK_UPLINKS \\ BANDWIDTH_0_GB_2 \\ 1_IP_ADDRESS \\ GUEST_DISK_100_GB_SAN \\ OS_UBUNTU_16_04_LTS_XENIAL_XERUS_MINIMAL_64_BIT_FOR_VSI \\ MONITORING_HOST_PING \\ NOTIFICATION_EMAIL_AND_TICKET \\ AUTOMATED_NOTIFICATION \\ UNLIMITED_SSL_VPN_USERS_1_PPTP_VPN_USER_PER_ACCOUNT \\ NESSUS_VULNERABILITY_ASSESSMENT_REPORTING \\ --extras '{"virtualGuests": [{"hostname": "test", "domain": "softlayer.com"}]}' \\ --complex-type SoftLayer_Container_Product_Order_Virtual_Guest """ manager = ordering.OrderingManager(env.client) if extras: try: extras = json.loads(extras) except ValueError as err: raise exceptions.CLIAbort("There was an error when parsing the --extras value: {}".format(err)) args = (package_keyname, location, order_items) kwargs = {'preset_keyname': preset, 'extras': extras, 'quantity': 1, 'quote_name': name, 'send_email': send_email, 'complex_type': complex_type} order = manager.place_quote(*args, **kwargs) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', order['quote']['id']]) table.add_row(['name', order['quote']['name']]) table.add_row(['created', order['orderDate']]) table.add_row(['expires', order['quote']['expirationDate']]) table.add_row(['status', order['quote']['status']]) env.fout(table)
[ "def", "cli", "(", "env", ",", "package_keyname", ",", "location", ",", "preset", ",", "name", ",", "send_email", ",", "complex_type", ",", "extras", ",", "order_items", ")", ":", "manager", "=", "ordering", ".", "OrderingManager", "(", "env", ".", "client", ")", "if", "extras", ":", "try", ":", "extras", "=", "json", ".", "loads", "(", "extras", ")", "except", "ValueError", "as", "err", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"There was an error when parsing the --extras value: {}\"", ".", "format", "(", "err", ")", ")", "args", "=", "(", "package_keyname", ",", "location", ",", "order_items", ")", "kwargs", "=", "{", "'preset_keyname'", ":", "preset", ",", "'extras'", ":", "extras", ",", "'quantity'", ":", "1", ",", "'quote_name'", ":", "name", ",", "'send_email'", ":", "send_email", ",", "'complex_type'", ":", "complex_type", "}", "order", "=", "manager", ".", "place_quote", "(", "*", "args", ",", "*", "*", "kwargs", ")", "table", "=", "formatting", ".", "KeyValueTable", "(", "[", "'name'", ",", "'value'", "]", ")", "table", ".", "align", "[", "'name'", "]", "=", "'r'", "table", ".", "align", "[", "'value'", "]", "=", "'l'", "table", ".", "add_row", "(", "[", "'id'", ",", "order", "[", "'quote'", "]", "[", "'id'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'name'", ",", "order", "[", "'quote'", "]", "[", "'name'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'created'", ",", "order", "[", "'orderDate'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'expires'", ",", "order", "[", "'quote'", "]", "[", "'expirationDate'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'status'", ",", "order", "[", "'quote'", "]", "[", "'status'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Place a quote. This CLI command is used for creating a quote of the specified package in the given location (denoted by a datacenter's long name). Orders made via the CLI can then be converted to be made programmatically by calling SoftLayer.OrderingManager.place_quote() with the same keynames. Packages for ordering can be retrieved from `slcli order package-list` Presets for ordering can be retrieved from `slcli order preset-list` (not all packages have presets) Items can be retrieved from `slcli order item-list`. In order to find required items for the order, use `slcli order category-list`, and then provide the --category option for each category code in `slcli order item-list`. Example:: # Place quote a VSI with 4 CPU, 16 GB RAM, 100 GB SAN disk, # Ubuntu 16.04, and 1 Gbps public & private uplink in dal13 slcli order place-quote --name "foobar" --send-email CLOUD_SERVER DALLAS13 \\ GUEST_CORES_4 \\ RAM_16_GB \\ REBOOT_REMOTE_CONSOLE \\ 1_GBPS_PUBLIC_PRIVATE_NETWORK_UPLINKS \\ BANDWIDTH_0_GB_2 \\ 1_IP_ADDRESS \\ GUEST_DISK_100_GB_SAN \\ OS_UBUNTU_16_04_LTS_XENIAL_XERUS_MINIMAL_64_BIT_FOR_VSI \\ MONITORING_HOST_PING \\ NOTIFICATION_EMAIL_AND_TICKET \\ AUTOMATED_NOTIFICATION \\ UNLIMITED_SSL_VPN_USERS_1_PPTP_VPN_USER_PER_ACCOUNT \\ NESSUS_VULNERABILITY_ASSESSMENT_REPORTING \\ --extras '{"virtualGuests": [{"hostname": "test", "domain": "softlayer.com"}]}' \\ --complex-type SoftLayer_Container_Product_Order_Virtual_Guest
[ "Place", "a", "quote", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/place_quote.py#L30-L96
train
234,381
softlayer/softlayer-python
SoftLayer/CLI/order/quote_list.py
cli
def cli(env): """List all active quotes on an account""" table = formatting.Table([ 'Id', 'Name', 'Created', 'Expiration', 'Status', 'Package Name', 'Package Id' ]) table.align['Name'] = 'l' table.align['Package Name'] = 'r' table.align['Package Id'] = 'l' manager = ordering.OrderingManager(env.client) items = manager.get_quotes() for item in items: package = item['order']['items'][0]['package'] table.add_row([ item.get('id'), item.get('name'), clean_time(item.get('createDate')), clean_time(item.get('modifyDate')), item.get('status'), package.get('keyName'), package.get('id') ]) env.fout(table)
python
def cli(env): """List all active quotes on an account""" table = formatting.Table([ 'Id', 'Name', 'Created', 'Expiration', 'Status', 'Package Name', 'Package Id' ]) table.align['Name'] = 'l' table.align['Package Name'] = 'r' table.align['Package Id'] = 'l' manager = ordering.OrderingManager(env.client) items = manager.get_quotes() for item in items: package = item['order']['items'][0]['package'] table.add_row([ item.get('id'), item.get('name'), clean_time(item.get('createDate')), clean_time(item.get('modifyDate')), item.get('status'), package.get('keyName'), package.get('id') ]) env.fout(table)
[ "def", "cli", "(", "env", ")", ":", "table", "=", "formatting", ".", "Table", "(", "[", "'Id'", ",", "'Name'", ",", "'Created'", ",", "'Expiration'", ",", "'Status'", ",", "'Package Name'", ",", "'Package Id'", "]", ")", "table", ".", "align", "[", "'Name'", "]", "=", "'l'", "table", ".", "align", "[", "'Package Name'", "]", "=", "'r'", "table", ".", "align", "[", "'Package Id'", "]", "=", "'l'", "manager", "=", "ordering", ".", "OrderingManager", "(", "env", ".", "client", ")", "items", "=", "manager", ".", "get_quotes", "(", ")", "for", "item", "in", "items", ":", "package", "=", "item", "[", "'order'", "]", "[", "'items'", "]", "[", "0", "]", "[", "'package'", "]", "table", ".", "add_row", "(", "[", "item", ".", "get", "(", "'id'", ")", ",", "item", ".", "get", "(", "'name'", ")", ",", "clean_time", "(", "item", ".", "get", "(", "'createDate'", ")", ")", ",", "clean_time", "(", "item", ".", "get", "(", "'modifyDate'", ")", ")", ",", "item", ".", "get", "(", "'status'", ")", ",", "package", ".", "get", "(", "'keyName'", ")", ",", "package", ".", "get", "(", "'id'", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List all active quotes on an account
[ "List", "all", "active", "quotes", "on", "an", "account" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/quote_list.py#L13-L36
train
234,382
softlayer/softlayer-python
SoftLayer/CLI/image/delete.py
cli
def cli(env, identifier): """Delete an image.""" image_mgr = SoftLayer.ImageManager(env.client) image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image') image_mgr.delete_image(image_id)
python
def cli(env, identifier): """Delete an image.""" image_mgr = SoftLayer.ImageManager(env.client) image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image') image_mgr.delete_image(image_id)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "image_mgr", "=", "SoftLayer", ".", "ImageManager", "(", "env", ".", "client", ")", "image_id", "=", "helpers", ".", "resolve_id", "(", "image_mgr", ".", "resolve_ids", ",", "identifier", ",", "'image'", ")", "image_mgr", ".", "delete_image", "(", "image_id", ")" ]
Delete an image.
[ "Delete", "an", "image", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/image/delete.py#L14-L20
train
234,383
softlayer/softlayer-python
SoftLayer/CLI/loadbal/service_add.py
cli
def cli(env, identifier, enabled, port, weight, healthcheck_type, ip_address): """Adds a new load balancer service.""" mgr = SoftLayer.LoadBalancerManager(env.client) loadbal_id, group_id = loadbal.parse_id(identifier) # check if the IP is valid ip_address_id = None if ip_address: ip_service = env.client['Network_Subnet_IpAddress'] ip_record = ip_service.getByIpAddress(ip_address) if len(ip_record) > 0: ip_address_id = ip_record['id'] mgr.add_service(loadbal_id, group_id, ip_address_id=ip_address_id, enabled=enabled, port=port, weight=weight, hc_type=healthcheck_type) env.fout('Load balancer service is being added!')
python
def cli(env, identifier, enabled, port, weight, healthcheck_type, ip_address): """Adds a new load balancer service.""" mgr = SoftLayer.LoadBalancerManager(env.client) loadbal_id, group_id = loadbal.parse_id(identifier) # check if the IP is valid ip_address_id = None if ip_address: ip_service = env.client['Network_Subnet_IpAddress'] ip_record = ip_service.getByIpAddress(ip_address) if len(ip_record) > 0: ip_address_id = ip_record['id'] mgr.add_service(loadbal_id, group_id, ip_address_id=ip_address_id, enabled=enabled, port=port, weight=weight, hc_type=healthcheck_type) env.fout('Load balancer service is being added!')
[ "def", "cli", "(", "env", ",", "identifier", ",", "enabled", ",", "port", ",", "weight", ",", "healthcheck_type", ",", "ip_address", ")", ":", "mgr", "=", "SoftLayer", ".", "LoadBalancerManager", "(", "env", ".", "client", ")", "loadbal_id", ",", "group_id", "=", "loadbal", ".", "parse_id", "(", "identifier", ")", "# check if the IP is valid", "ip_address_id", "=", "None", "if", "ip_address", ":", "ip_service", "=", "env", ".", "client", "[", "'Network_Subnet_IpAddress'", "]", "ip_record", "=", "ip_service", ".", "getByIpAddress", "(", "ip_address", ")", "if", "len", "(", "ip_record", ")", ">", "0", ":", "ip_address_id", "=", "ip_record", "[", "'id'", "]", "mgr", ".", "add_service", "(", "loadbal_id", ",", "group_id", ",", "ip_address_id", "=", "ip_address_id", ",", "enabled", "=", "enabled", ",", "port", "=", "port", ",", "weight", "=", "weight", ",", "hc_type", "=", "healthcheck_type", ")", "env", ".", "fout", "(", "'Load balancer service is being added!'", ")" ]
Adds a new load balancer service.
[ "Adds", "a", "new", "load", "balancer", "service", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/service_add.py#L31-L53
train
234,384
softlayer/softlayer-python
SoftLayer/shell/core.py
cli
def cli(ctx, env): """Enters a shell for slcli.""" # Set up the environment env = copy.deepcopy(env) env.load_modules_from_python(routes.ALL_ROUTES) env.aliases.update(routes.ALL_ALIASES) env.vars['global_args'] = ctx.parent.params env.vars['is_shell'] = True env.vars['last_exit_code'] = 0 # Set up prompt_toolkit settings app_path = click.get_app_dir('softlayer_shell') if not os.path.exists(app_path): os.makedirs(app_path) complete = completer.ShellCompleter(core.cli) while True: try: line = p_shortcuts.prompt( completer=complete, complete_while_typing=True, auto_suggest=p_auto_suggest.AutoSuggestFromHistory(), ) # Parse arguments try: args = shlex.split(line) except ValueError as ex: print("Invalid Command: %s" % ex) continue if not args: continue # Run Command try: # Reset client so that the client gets refreshed env.client = None core.main(args=list(get_env_args(env)) + args, obj=env, prog_name="", reraise_exceptions=True) except SystemExit as ex: env.vars['last_exit_code'] = ex.code except EOFError: return except ShellExit: return except Exception as ex: env.vars['last_exit_code'] = 1 traceback.print_exc(file=sys.stderr) except KeyboardInterrupt: env.vars['last_exit_code'] = 130
python
def cli(ctx, env): """Enters a shell for slcli.""" # Set up the environment env = copy.deepcopy(env) env.load_modules_from_python(routes.ALL_ROUTES) env.aliases.update(routes.ALL_ALIASES) env.vars['global_args'] = ctx.parent.params env.vars['is_shell'] = True env.vars['last_exit_code'] = 0 # Set up prompt_toolkit settings app_path = click.get_app_dir('softlayer_shell') if not os.path.exists(app_path): os.makedirs(app_path) complete = completer.ShellCompleter(core.cli) while True: try: line = p_shortcuts.prompt( completer=complete, complete_while_typing=True, auto_suggest=p_auto_suggest.AutoSuggestFromHistory(), ) # Parse arguments try: args = shlex.split(line) except ValueError as ex: print("Invalid Command: %s" % ex) continue if not args: continue # Run Command try: # Reset client so that the client gets refreshed env.client = None core.main(args=list(get_env_args(env)) + args, obj=env, prog_name="", reraise_exceptions=True) except SystemExit as ex: env.vars['last_exit_code'] = ex.code except EOFError: return except ShellExit: return except Exception as ex: env.vars['last_exit_code'] = 1 traceback.print_exc(file=sys.stderr) except KeyboardInterrupt: env.vars['last_exit_code'] = 130
[ "def", "cli", "(", "ctx", ",", "env", ")", ":", "# Set up the environment", "env", "=", "copy", ".", "deepcopy", "(", "env", ")", "env", ".", "load_modules_from_python", "(", "routes", ".", "ALL_ROUTES", ")", "env", ".", "aliases", ".", "update", "(", "routes", ".", "ALL_ALIASES", ")", "env", ".", "vars", "[", "'global_args'", "]", "=", "ctx", ".", "parent", ".", "params", "env", ".", "vars", "[", "'is_shell'", "]", "=", "True", "env", ".", "vars", "[", "'last_exit_code'", "]", "=", "0", "# Set up prompt_toolkit settings", "app_path", "=", "click", ".", "get_app_dir", "(", "'softlayer_shell'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "app_path", ")", ":", "os", ".", "makedirs", "(", "app_path", ")", "complete", "=", "completer", ".", "ShellCompleter", "(", "core", ".", "cli", ")", "while", "True", ":", "try", ":", "line", "=", "p_shortcuts", ".", "prompt", "(", "completer", "=", "complete", ",", "complete_while_typing", "=", "True", ",", "auto_suggest", "=", "p_auto_suggest", ".", "AutoSuggestFromHistory", "(", ")", ",", ")", "# Parse arguments", "try", ":", "args", "=", "shlex", ".", "split", "(", "line", ")", "except", "ValueError", "as", "ex", ":", "print", "(", "\"Invalid Command: %s\"", "%", "ex", ")", "continue", "if", "not", "args", ":", "continue", "# Run Command", "try", ":", "# Reset client so that the client gets refreshed", "env", ".", "client", "=", "None", "core", ".", "main", "(", "args", "=", "list", "(", "get_env_args", "(", "env", ")", ")", "+", "args", ",", "obj", "=", "env", ",", "prog_name", "=", "\"\"", ",", "reraise_exceptions", "=", "True", ")", "except", "SystemExit", "as", "ex", ":", "env", ".", "vars", "[", "'last_exit_code'", "]", "=", "ex", ".", "code", "except", "EOFError", ":", "return", "except", "ShellExit", ":", "return", "except", "Exception", "as", "ex", ":", "env", ".", "vars", "[", "'last_exit_code'", "]", "=", "1", "traceback", ".", "print_exc", "(", "file", "=", "sys", ".", "stderr", ")", "except", "KeyboardInterrupt", ":", "env", ".", "vars", "[", "'last_exit_code'", "]", "=", "130" ]
Enters a shell for slcli.
[ "Enters", "a", "shell", "for", "slcli", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/shell/core.py#L34-L88
train
234,385
softlayer/softlayer-python
SoftLayer/shell/core.py
get_env_args
def get_env_args(env): """Yield options to inject into the slcli command from the environment.""" for arg, val in env.vars.get('global_args', {}).items(): if val is True: yield '--%s' % arg elif isinstance(val, int): for _ in range(val): yield '--%s' % arg elif val is None: continue else: yield '--%s=%s' % (arg, val)
python
def get_env_args(env): """Yield options to inject into the slcli command from the environment.""" for arg, val in env.vars.get('global_args', {}).items(): if val is True: yield '--%s' % arg elif isinstance(val, int): for _ in range(val): yield '--%s' % arg elif val is None: continue else: yield '--%s=%s' % (arg, val)
[ "def", "get_env_args", "(", "env", ")", ":", "for", "arg", ",", "val", "in", "env", ".", "vars", ".", "get", "(", "'global_args'", ",", "{", "}", ")", ".", "items", "(", ")", ":", "if", "val", "is", "True", ":", "yield", "'--%s'", "%", "arg", "elif", "isinstance", "(", "val", ",", "int", ")", ":", "for", "_", "in", "range", "(", "val", ")", ":", "yield", "'--%s'", "%", "arg", "elif", "val", "is", "None", ":", "continue", "else", ":", "yield", "'--%s=%s'", "%", "(", "arg", ",", "val", ")" ]
Yield options to inject into the slcli command from the environment.
[ "Yield", "options", "to", "inject", "into", "the", "slcli", "command", "from", "the", "environment", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/shell/core.py#L91-L102
train
234,386
softlayer/softlayer-python
SoftLayer/CLI/virt/placementgroup/delete.py
cli
def cli(env, identifier, purge): """Delete a placement group. Placement Group MUST be empty before you can delete it. IDENTIFIER can be either the Name or Id of the placement group you want to view """ manager = PlacementManager(env.client) group_id = helpers.resolve_id(manager.resolve_ids, identifier, 'placement_group') if purge: placement_group = manager.get_object(group_id) guest_list = ', '.join([guest['fullyQualifiedDomainName'] for guest in placement_group['guests']]) if len(placement_group['guests']) < 1: raise exceptions.CLIAbort('No virtual servers were found in placement group %s' % identifier) click.secho("You are about to delete the following guests!\n%s" % guest_list, fg='red') if not (env.skip_confirmations or formatting.confirm("This action will cancel all guests! Continue?")): raise exceptions.CLIAbort('Aborting virtual server order.') vm_manager = VSManager(env.client) for guest in placement_group['guests']: click.secho("Deleting %s..." % guest['fullyQualifiedDomainName']) vm_manager.cancel_instance(guest['id']) return click.secho("You are about to delete the following placement group! %s" % identifier, fg='red') if not (env.skip_confirmations or formatting.confirm("This action will cancel the placement group! Continue?")): raise exceptions.CLIAbort('Aborting virtual server order.') cancel_result = manager.delete(group_id) if cancel_result: click.secho("Placement Group %s has been canceld." % identifier, fg='green')
python
def cli(env, identifier, purge): """Delete a placement group. Placement Group MUST be empty before you can delete it. IDENTIFIER can be either the Name or Id of the placement group you want to view """ manager = PlacementManager(env.client) group_id = helpers.resolve_id(manager.resolve_ids, identifier, 'placement_group') if purge: placement_group = manager.get_object(group_id) guest_list = ', '.join([guest['fullyQualifiedDomainName'] for guest in placement_group['guests']]) if len(placement_group['guests']) < 1: raise exceptions.CLIAbort('No virtual servers were found in placement group %s' % identifier) click.secho("You are about to delete the following guests!\n%s" % guest_list, fg='red') if not (env.skip_confirmations or formatting.confirm("This action will cancel all guests! Continue?")): raise exceptions.CLIAbort('Aborting virtual server order.') vm_manager = VSManager(env.client) for guest in placement_group['guests']: click.secho("Deleting %s..." % guest['fullyQualifiedDomainName']) vm_manager.cancel_instance(guest['id']) return click.secho("You are about to delete the following placement group! %s" % identifier, fg='red') if not (env.skip_confirmations or formatting.confirm("This action will cancel the placement group! Continue?")): raise exceptions.CLIAbort('Aborting virtual server order.') cancel_result = manager.delete(group_id) if cancel_result: click.secho("Placement Group %s has been canceld." % identifier, fg='green')
[ "def", "cli", "(", "env", ",", "identifier", ",", "purge", ")", ":", "manager", "=", "PlacementManager", "(", "env", ".", "client", ")", "group_id", "=", "helpers", ".", "resolve_id", "(", "manager", ".", "resolve_ids", ",", "identifier", ",", "'placement_group'", ")", "if", "purge", ":", "placement_group", "=", "manager", ".", "get_object", "(", "group_id", ")", "guest_list", "=", "', '", ".", "join", "(", "[", "guest", "[", "'fullyQualifiedDomainName'", "]", "for", "guest", "in", "placement_group", "[", "'guests'", "]", "]", ")", "if", "len", "(", "placement_group", "[", "'guests'", "]", ")", "<", "1", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'No virtual servers were found in placement group %s'", "%", "identifier", ")", "click", ".", "secho", "(", "\"You are about to delete the following guests!\\n%s\"", "%", "guest_list", ",", "fg", "=", "'red'", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "confirm", "(", "\"This action will cancel all guests! Continue?\"", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborting virtual server order.'", ")", "vm_manager", "=", "VSManager", "(", "env", ".", "client", ")", "for", "guest", "in", "placement_group", "[", "'guests'", "]", ":", "click", ".", "secho", "(", "\"Deleting %s...\"", "%", "guest", "[", "'fullyQualifiedDomainName'", "]", ")", "vm_manager", ".", "cancel_instance", "(", "guest", "[", "'id'", "]", ")", "return", "click", ".", "secho", "(", "\"You are about to delete the following placement group! %s\"", "%", "identifier", ",", "fg", "=", "'red'", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "confirm", "(", "\"This action will cancel the placement group! Continue?\"", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborting virtual server order.'", ")", "cancel_result", "=", "manager", ".", "delete", "(", "group_id", ")", "if", "cancel_result", ":", "click", ".", "secho", "(", "\"Placement Group %s has been canceld.\"", "%", "identifier", ",", "fg", "=", "'green'", ")" ]
Delete a placement group. Placement Group MUST be empty before you can delete it. IDENTIFIER can be either the Name or Id of the placement group you want to view
[ "Delete", "a", "placement", "group", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/placementgroup/delete.py#L19-L49
train
234,387
softlayer/softlayer-python
SoftLayer/CLI/vpn/ipsec/translation/update.py
cli
def cli(env, context_id, translation_id, static_ip, remote_ip, note): """Update an address translation for an IPSEC tunnel context. A separate configuration request should be made to realize changes on network devices. """ manager = SoftLayer.IPSECManager(env.client) succeeded = manager.update_translation(context_id, translation_id, static_ip=static_ip, remote_ip=remote_ip, notes=note) if succeeded: env.out('Updated translation #{}'.format(translation_id)) else: raise CLIHalt('Failed to update translation #{}'.format(translation_id))
python
def cli(env, context_id, translation_id, static_ip, remote_ip, note): """Update an address translation for an IPSEC tunnel context. A separate configuration request should be made to realize changes on network devices. """ manager = SoftLayer.IPSECManager(env.client) succeeded = manager.update_translation(context_id, translation_id, static_ip=static_ip, remote_ip=remote_ip, notes=note) if succeeded: env.out('Updated translation #{}'.format(translation_id)) else: raise CLIHalt('Failed to update translation #{}'.format(translation_id))
[ "def", "cli", "(", "env", ",", "context_id", ",", "translation_id", ",", "static_ip", ",", "remote_ip", ",", "note", ")", ":", "manager", "=", "SoftLayer", ".", "IPSECManager", "(", "env", ".", "client", ")", "succeeded", "=", "manager", ".", "update_translation", "(", "context_id", ",", "translation_id", ",", "static_ip", "=", "static_ip", ",", "remote_ip", "=", "remote_ip", ",", "notes", "=", "note", ")", "if", "succeeded", ":", "env", ".", "out", "(", "'Updated translation #{}'", ".", "format", "(", "translation_id", ")", ")", "else", ":", "raise", "CLIHalt", "(", "'Failed to update translation #{}'", ".", "format", "(", "translation_id", ")", ")" ]
Update an address translation for an IPSEC tunnel context. A separate configuration request should be made to realize changes on network devices.
[ "Update", "an", "address", "translation", "for", "an", "IPSEC", "tunnel", "context", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/translation/update.py#L31-L46
train
234,388
softlayer/softlayer-python
SoftLayer/shell/cmd_help.py
cli
def cli(ctx, env): """Print shell help text.""" env.out("Welcome to the SoftLayer shell.") env.out("") formatter = formatting.HelpFormatter() commands = [] shell_commands = [] for name in cli_core.cli.list_commands(ctx): command = cli_core.cli.get_command(ctx, name) if command.short_help is None: command.short_help = command.help details = (name, command.short_help) if name in dict(routes.ALL_ROUTES): shell_commands.append(details) else: commands.append(details) with formatter.section('Shell Commands'): formatter.write_dl(shell_commands) with formatter.section('Commands'): formatter.write_dl(commands) for line in formatter.buffer: env.out(line, newline=False)
python
def cli(ctx, env): """Print shell help text.""" env.out("Welcome to the SoftLayer shell.") env.out("") formatter = formatting.HelpFormatter() commands = [] shell_commands = [] for name in cli_core.cli.list_commands(ctx): command = cli_core.cli.get_command(ctx, name) if command.short_help is None: command.short_help = command.help details = (name, command.short_help) if name in dict(routes.ALL_ROUTES): shell_commands.append(details) else: commands.append(details) with formatter.section('Shell Commands'): formatter.write_dl(shell_commands) with formatter.section('Commands'): formatter.write_dl(commands) for line in formatter.buffer: env.out(line, newline=False)
[ "def", "cli", "(", "ctx", ",", "env", ")", ":", "env", ".", "out", "(", "\"Welcome to the SoftLayer shell.\"", ")", "env", ".", "out", "(", "\"\"", ")", "formatter", "=", "formatting", ".", "HelpFormatter", "(", ")", "commands", "=", "[", "]", "shell_commands", "=", "[", "]", "for", "name", "in", "cli_core", ".", "cli", ".", "list_commands", "(", "ctx", ")", ":", "command", "=", "cli_core", ".", "cli", ".", "get_command", "(", "ctx", ",", "name", ")", "if", "command", ".", "short_help", "is", "None", ":", "command", ".", "short_help", "=", "command", ".", "help", "details", "=", "(", "name", ",", "command", ".", "short_help", ")", "if", "name", "in", "dict", "(", "routes", ".", "ALL_ROUTES", ")", ":", "shell_commands", ".", "append", "(", "details", ")", "else", ":", "commands", ".", "append", "(", "details", ")", "with", "formatter", ".", "section", "(", "'Shell Commands'", ")", ":", "formatter", ".", "write_dl", "(", "shell_commands", ")", "with", "formatter", ".", "section", "(", "'Commands'", ")", ":", "formatter", ".", "write_dl", "(", "commands", ")", "for", "line", "in", "formatter", ".", "buffer", ":", "env", ".", "out", "(", "line", ",", "newline", "=", "False", ")" ]
Print shell help text.
[ "Print", "shell", "help", "text", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/shell/cmd_help.py#L15-L40
train
234,389
softlayer/softlayer-python
SoftLayer/CLI/hardware/reload.py
cli
def cli(env, identifier, postinstall, key): """Reload operating system on a server.""" hardware = SoftLayer.HardwareManager(env.client) hardware_id = helpers.resolve_id(hardware.resolve_ids, identifier, 'hardware') key_list = [] if key: for single_key in key: resolver = SoftLayer.SshKeyManager(env.client).resolve_ids key_id = helpers.resolve_id(resolver, single_key, 'SshKey') key_list.append(key_id) if not (env.skip_confirmations or formatting.no_going_back(hardware_id)): raise exceptions.CLIAbort('Aborted') hardware.reload(hardware_id, postinstall, key_list)
python
def cli(env, identifier, postinstall, key): """Reload operating system on a server.""" hardware = SoftLayer.HardwareManager(env.client) hardware_id = helpers.resolve_id(hardware.resolve_ids, identifier, 'hardware') key_list = [] if key: for single_key in key: resolver = SoftLayer.SshKeyManager(env.client).resolve_ids key_id = helpers.resolve_id(resolver, single_key, 'SshKey') key_list.append(key_id) if not (env.skip_confirmations or formatting.no_going_back(hardware_id)): raise exceptions.CLIAbort('Aborted') hardware.reload(hardware_id, postinstall, key_list)
[ "def", "cli", "(", "env", ",", "identifier", ",", "postinstall", ",", "key", ")", ":", "hardware", "=", "SoftLayer", ".", "HardwareManager", "(", "env", ".", "client", ")", "hardware_id", "=", "helpers", ".", "resolve_id", "(", "hardware", ".", "resolve_ids", ",", "identifier", ",", "'hardware'", ")", "key_list", "=", "[", "]", "if", "key", ":", "for", "single_key", "in", "key", ":", "resolver", "=", "SoftLayer", ".", "SshKeyManager", "(", "env", ".", "client", ")", ".", "resolve_ids", "key_id", "=", "helpers", ".", "resolve_id", "(", "resolver", ",", "single_key", ",", "'SshKey'", ")", "key_list", ".", "append", "(", "key_id", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "no_going_back", "(", "hardware_id", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted'", ")", "hardware", ".", "reload", "(", "hardware_id", ",", "postinstall", ",", "key_list", ")" ]
Reload operating system on a server.
[ "Reload", "operating", "system", "on", "a", "server", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/reload.py#L20-L36
train
234,390
softlayer/softlayer-python
SoftLayer/CLI/loadbal/service_edit.py
cli
def cli(env, identifier, enabled, port, weight, healthcheck_type, ip_address): """Edit the properties of a service group.""" mgr = SoftLayer.LoadBalancerManager(env.client) loadbal_id, service_id = loadbal.parse_id(identifier) # check if any input is provided if ((not any([ip_address, weight, port, healthcheck_type])) and enabled is None): raise exceptions.CLIAbort( 'At least one property is required to be changed!') # check if the IP is valid ip_address_id = None if ip_address: ip_service = env.client['Network_Subnet_IpAddress'] ip_record = ip_service.getByIpAddress(ip_address) ip_address_id = ip_record['id'] mgr.edit_service(loadbal_id, service_id, ip_address_id=ip_address_id, enabled=enabled, port=port, weight=weight, hc_type=healthcheck_type) env.fout('Load balancer service %s is being modified!' % identifier)
python
def cli(env, identifier, enabled, port, weight, healthcheck_type, ip_address): """Edit the properties of a service group.""" mgr = SoftLayer.LoadBalancerManager(env.client) loadbal_id, service_id = loadbal.parse_id(identifier) # check if any input is provided if ((not any([ip_address, weight, port, healthcheck_type])) and enabled is None): raise exceptions.CLIAbort( 'At least one property is required to be changed!') # check if the IP is valid ip_address_id = None if ip_address: ip_service = env.client['Network_Subnet_IpAddress'] ip_record = ip_service.getByIpAddress(ip_address) ip_address_id = ip_record['id'] mgr.edit_service(loadbal_id, service_id, ip_address_id=ip_address_id, enabled=enabled, port=port, weight=weight, hc_type=healthcheck_type) env.fout('Load balancer service %s is being modified!' % identifier)
[ "def", "cli", "(", "env", ",", "identifier", ",", "enabled", ",", "port", ",", "weight", ",", "healthcheck_type", ",", "ip_address", ")", ":", "mgr", "=", "SoftLayer", ".", "LoadBalancerManager", "(", "env", ".", "client", ")", "loadbal_id", ",", "service_id", "=", "loadbal", ".", "parse_id", "(", "identifier", ")", "# check if any input is provided", "if", "(", "(", "not", "any", "(", "[", "ip_address", ",", "weight", ",", "port", ",", "healthcheck_type", "]", ")", ")", "and", "enabled", "is", "None", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'At least one property is required to be changed!'", ")", "# check if the IP is valid", "ip_address_id", "=", "None", "if", "ip_address", ":", "ip_service", "=", "env", ".", "client", "[", "'Network_Subnet_IpAddress'", "]", "ip_record", "=", "ip_service", ".", "getByIpAddress", "(", "ip_address", ")", "ip_address_id", "=", "ip_record", "[", "'id'", "]", "mgr", ".", "edit_service", "(", "loadbal_id", ",", "service_id", ",", "ip_address_id", "=", "ip_address_id", ",", "enabled", "=", "enabled", ",", "port", "=", "port", ",", "weight", "=", "weight", ",", "hc_type", "=", "healthcheck_type", ")", "env", ".", "fout", "(", "'Load balancer service %s is being modified!'", "%", "identifier", ")" ]
Edit the properties of a service group.
[ "Edit", "the", "properties", "of", "a", "service", "group", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/service_edit.py#L25-L52
train
234,391
softlayer/softlayer-python
SoftLayer/CLI/subnet/list.py
cli
def cli(env, sortby, datacenter, identifier, subnet_type, network_space, ipv4, ipv6): """List subnets.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table([ 'id', 'identifier', 'type', 'network_space', 'datacenter', 'vlan_id', 'IPs', 'hardware', 'vs', ]) table.sortby = sortby version = 0 if ipv4: version = 4 elif ipv6: version = 6 subnets = mgr.list_subnets( datacenter=datacenter, version=version, identifier=identifier, subnet_type=subnet_type, network_space=network_space, ) for subnet in subnets: table.add_row([ subnet['id'], '%s/%s' % (subnet['networkIdentifier'], str(subnet['cidr'])), subnet.get('subnetType', formatting.blank()), utils.lookup(subnet, 'networkVlan', 'networkSpace') or formatting.blank(), utils.lookup(subnet, 'datacenter', 'name',) or formatting.blank(), subnet['networkVlanId'], subnet['ipAddressCount'], len(subnet['hardware']), len(subnet['virtualGuests']), ]) env.fout(table)
python
def cli(env, sortby, datacenter, identifier, subnet_type, network_space, ipv4, ipv6): """List subnets.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table([ 'id', 'identifier', 'type', 'network_space', 'datacenter', 'vlan_id', 'IPs', 'hardware', 'vs', ]) table.sortby = sortby version = 0 if ipv4: version = 4 elif ipv6: version = 6 subnets = mgr.list_subnets( datacenter=datacenter, version=version, identifier=identifier, subnet_type=subnet_type, network_space=network_space, ) for subnet in subnets: table.add_row([ subnet['id'], '%s/%s' % (subnet['networkIdentifier'], str(subnet['cidr'])), subnet.get('subnetType', formatting.blank()), utils.lookup(subnet, 'networkVlan', 'networkSpace') or formatting.blank(), utils.lookup(subnet, 'datacenter', 'name',) or formatting.blank(), subnet['networkVlanId'], subnet['ipAddressCount'], len(subnet['hardware']), len(subnet['virtualGuests']), ]) env.fout(table)
[ "def", "cli", "(", "env", ",", "sortby", ",", "datacenter", ",", "identifier", ",", "subnet_type", ",", "network_space", ",", "ipv4", ",", "ipv6", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'identifier'", ",", "'type'", ",", "'network_space'", ",", "'datacenter'", ",", "'vlan_id'", ",", "'IPs'", ",", "'hardware'", ",", "'vs'", ",", "]", ")", "table", ".", "sortby", "=", "sortby", "version", "=", "0", "if", "ipv4", ":", "version", "=", "4", "elif", "ipv6", ":", "version", "=", "6", "subnets", "=", "mgr", ".", "list_subnets", "(", "datacenter", "=", "datacenter", ",", "version", "=", "version", ",", "identifier", "=", "identifier", ",", "subnet_type", "=", "subnet_type", ",", "network_space", "=", "network_space", ",", ")", "for", "subnet", "in", "subnets", ":", "table", ".", "add_row", "(", "[", "subnet", "[", "'id'", "]", ",", "'%s/%s'", "%", "(", "subnet", "[", "'networkIdentifier'", "]", ",", "str", "(", "subnet", "[", "'cidr'", "]", ")", ")", ",", "subnet", ".", "get", "(", "'subnetType'", ",", "formatting", ".", "blank", "(", ")", ")", ",", "utils", ".", "lookup", "(", "subnet", ",", "'networkVlan'", ",", "'networkSpace'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "utils", ".", "lookup", "(", "subnet", ",", "'datacenter'", ",", "'name'", ",", ")", "or", "formatting", ".", "blank", "(", ")", ",", "subnet", "[", "'networkVlanId'", "]", ",", "subnet", "[", "'ipAddressCount'", "]", ",", "len", "(", "subnet", "[", "'hardware'", "]", ")", ",", "len", "(", "subnet", "[", "'virtualGuests'", "]", ")", ",", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List subnets.
[ "List", "subnets", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/subnet/list.py#L32-L72
train
234,392
softlayer/softlayer-python
SoftLayer/CLI/firewall/add.py
cli
def cli(env, target, firewall_type, high_availability): """Create new firewall. TARGET: Id of the server the firewall will protect """ mgr = SoftLayer.FirewallManager(env.client) if not env.skip_confirmations: if firewall_type == 'vlan': pkg = mgr.get_dedicated_package(ha_enabled=high_availability) elif firewall_type == 'vs': pkg = mgr.get_standard_package(target, is_virt=True) elif firewall_type == 'server': pkg = mgr.get_standard_package(target, is_virt=False) if not pkg: exceptions.CLIAbort( "Unable to add firewall - Is network public enabled?") env.out("******************") env.out("Product: %s" % pkg[0]['description']) env.out("Price: $%s monthly" % pkg[0]['prices'][0]['recurringFee']) env.out("******************") if not formatting.confirm("This action will incur charges on your " "account. Continue?"): raise exceptions.CLIAbort('Aborted.') if firewall_type == 'vlan': mgr.add_vlan_firewall(target, ha_enabled=high_availability) elif firewall_type == 'vs': mgr.add_standard_firewall(target, is_virt=True) elif firewall_type == 'server': mgr.add_standard_firewall(target, is_virt=False) env.fout("Firewall is being created!")
python
def cli(env, target, firewall_type, high_availability): """Create new firewall. TARGET: Id of the server the firewall will protect """ mgr = SoftLayer.FirewallManager(env.client) if not env.skip_confirmations: if firewall_type == 'vlan': pkg = mgr.get_dedicated_package(ha_enabled=high_availability) elif firewall_type == 'vs': pkg = mgr.get_standard_package(target, is_virt=True) elif firewall_type == 'server': pkg = mgr.get_standard_package(target, is_virt=False) if not pkg: exceptions.CLIAbort( "Unable to add firewall - Is network public enabled?") env.out("******************") env.out("Product: %s" % pkg[0]['description']) env.out("Price: $%s monthly" % pkg[0]['prices'][0]['recurringFee']) env.out("******************") if not formatting.confirm("This action will incur charges on your " "account. Continue?"): raise exceptions.CLIAbort('Aborted.') if firewall_type == 'vlan': mgr.add_vlan_firewall(target, ha_enabled=high_availability) elif firewall_type == 'vs': mgr.add_standard_firewall(target, is_virt=True) elif firewall_type == 'server': mgr.add_standard_firewall(target, is_virt=False) env.fout("Firewall is being created!")
[ "def", "cli", "(", "env", ",", "target", ",", "firewall_type", ",", "high_availability", ")", ":", "mgr", "=", "SoftLayer", ".", "FirewallManager", "(", "env", ".", "client", ")", "if", "not", "env", ".", "skip_confirmations", ":", "if", "firewall_type", "==", "'vlan'", ":", "pkg", "=", "mgr", ".", "get_dedicated_package", "(", "ha_enabled", "=", "high_availability", ")", "elif", "firewall_type", "==", "'vs'", ":", "pkg", "=", "mgr", ".", "get_standard_package", "(", "target", ",", "is_virt", "=", "True", ")", "elif", "firewall_type", "==", "'server'", ":", "pkg", "=", "mgr", ".", "get_standard_package", "(", "target", ",", "is_virt", "=", "False", ")", "if", "not", "pkg", ":", "exceptions", ".", "CLIAbort", "(", "\"Unable to add firewall - Is network public enabled?\"", ")", "env", ".", "out", "(", "\"******************\"", ")", "env", ".", "out", "(", "\"Product: %s\"", "%", "pkg", "[", "0", "]", "[", "'description'", "]", ")", "env", ".", "out", "(", "\"Price: $%s monthly\"", "%", "pkg", "[", "0", "]", "[", "'prices'", "]", "[", "0", "]", "[", "'recurringFee'", "]", ")", "env", ".", "out", "(", "\"******************\"", ")", "if", "not", "formatting", ".", "confirm", "(", "\"This action will incur charges on your \"", "\"account. Continue?\"", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted.'", ")", "if", "firewall_type", "==", "'vlan'", ":", "mgr", ".", "add_vlan_firewall", "(", "target", ",", "ha_enabled", "=", "high_availability", ")", "elif", "firewall_type", "==", "'vs'", ":", "mgr", ".", "add_standard_firewall", "(", "target", ",", "is_virt", "=", "True", ")", "elif", "firewall_type", "==", "'server'", ":", "mgr", ".", "add_standard_firewall", "(", "target", ",", "is_virt", "=", "False", ")", "env", ".", "fout", "(", "\"Firewall is being created!\"", ")" ]
Create new firewall. TARGET: Id of the server the firewall will protect
[ "Create", "new", "firewall", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/add.py#L22-L58
train
234,393
softlayer/softlayer-python
SoftLayer/CLI/cdn/purge.py
cli
def cli(env, account_id, content_url): """Purge cached files from all edge nodes. Examples: slcli cdn purge 97794 http://example.com/cdn/file.txt slcli cdn purge 97794 http://example.com/cdn/file.txt https://dal01.example.softlayer.net/image.png """ manager = SoftLayer.CDNManager(env.client) content_list = manager.purge_content(account_id, content_url) table = formatting.Table(['url', 'status']) for content in content_list: table.add_row([ content['url'], content['statusCode'] ]) env.fout(table)
python
def cli(env, account_id, content_url): """Purge cached files from all edge nodes. Examples: slcli cdn purge 97794 http://example.com/cdn/file.txt slcli cdn purge 97794 http://example.com/cdn/file.txt https://dal01.example.softlayer.net/image.png """ manager = SoftLayer.CDNManager(env.client) content_list = manager.purge_content(account_id, content_url) table = formatting.Table(['url', 'status']) for content in content_list: table.add_row([ content['url'], content['statusCode'] ]) env.fout(table)
[ "def", "cli", "(", "env", ",", "account_id", ",", "content_url", ")", ":", "manager", "=", "SoftLayer", ".", "CDNManager", "(", "env", ".", "client", ")", "content_list", "=", "manager", ".", "purge_content", "(", "account_id", ",", "content_url", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'url'", ",", "'status'", "]", ")", "for", "content", "in", "content_list", ":", "table", ".", "add_row", "(", "[", "content", "[", "'url'", "]", ",", "content", "[", "'statusCode'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Purge cached files from all edge nodes. Examples: slcli cdn purge 97794 http://example.com/cdn/file.txt slcli cdn purge 97794 http://example.com/cdn/file.txt https://dal01.example.softlayer.net/image.png
[ "Purge", "cached", "files", "from", "all", "edge", "nodes", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/cdn/purge.py#L15-L34
train
234,394
softlayer/softlayer-python
SoftLayer/CLI/order/package_locations.py
cli
def cli(env, package_keyname): """List Datacenters a package can be ordered in. Use the location Key Name to place orders """ manager = ordering.OrderingManager(env.client) table = formatting.Table(COLUMNS) locations = manager.package_locations(package_keyname) for region in locations: for datacenter in region['locations']: table.add_row([ datacenter['location']['id'], datacenter['location']['name'], region['description'], region['keyname'] ]) env.fout(table)
python
def cli(env, package_keyname): """List Datacenters a package can be ordered in. Use the location Key Name to place orders """ manager = ordering.OrderingManager(env.client) table = formatting.Table(COLUMNS) locations = manager.package_locations(package_keyname) for region in locations: for datacenter in region['locations']: table.add_row([ datacenter['location']['id'], datacenter['location']['name'], region['description'], region['keyname'] ]) env.fout(table)
[ "def", "cli", "(", "env", ",", "package_keyname", ")", ":", "manager", "=", "ordering", ".", "OrderingManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "COLUMNS", ")", "locations", "=", "manager", ".", "package_locations", "(", "package_keyname", ")", "for", "region", "in", "locations", ":", "for", "datacenter", "in", "region", "[", "'locations'", "]", ":", "table", ".", "add_row", "(", "[", "datacenter", "[", "'location'", "]", "[", "'id'", "]", ",", "datacenter", "[", "'location'", "]", "[", "'name'", "]", ",", "region", "[", "'description'", "]", ",", "region", "[", "'keyname'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List Datacenters a package can be ordered in. Use the location Key Name to place orders
[ "List", "Datacenters", "a", "package", "can", "be", "ordered", "in", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/package_locations.py#L15-L32
train
234,395
softlayer/softlayer-python
SoftLayer/CLI/rwhois/edit.py
cli
def cli(env, abuse, address1, address2, city, company, country, firstname, lastname, postal, public, state): """Edit the RWhois data on the account.""" mgr = SoftLayer.NetworkManager(env.client) update = { 'abuse_email': abuse, 'address1': address1, 'address2': address2, 'company_name': company, 'city': city, 'country': country, 'first_name': firstname, 'last_name': lastname, 'postal_code': postal, 'state': state, 'private_residence': public, } if public is True: update['private_residence'] = False elif public is False: update['private_residence'] = True check = [x for x in update.values() if x is not None] if not check: raise exceptions.CLIAbort( "You must specify at least one field to update.") mgr.edit_rwhois(**update)
python
def cli(env, abuse, address1, address2, city, company, country, firstname, lastname, postal, public, state): """Edit the RWhois data on the account.""" mgr = SoftLayer.NetworkManager(env.client) update = { 'abuse_email': abuse, 'address1': address1, 'address2': address2, 'company_name': company, 'city': city, 'country': country, 'first_name': firstname, 'last_name': lastname, 'postal_code': postal, 'state': state, 'private_residence': public, } if public is True: update['private_residence'] = False elif public is False: update['private_residence'] = True check = [x for x in update.values() if x is not None] if not check: raise exceptions.CLIAbort( "You must specify at least one field to update.") mgr.edit_rwhois(**update)
[ "def", "cli", "(", "env", ",", "abuse", ",", "address1", ",", "address2", ",", "city", ",", "company", ",", "country", ",", "firstname", ",", "lastname", ",", "postal", ",", "public", ",", "state", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "update", "=", "{", "'abuse_email'", ":", "abuse", ",", "'address1'", ":", "address1", ",", "'address2'", ":", "address2", ",", "'company_name'", ":", "company", ",", "'city'", ":", "city", ",", "'country'", ":", "country", ",", "'first_name'", ":", "firstname", ",", "'last_name'", ":", "lastname", ",", "'postal_code'", ":", "postal", ",", "'state'", ":", "state", ",", "'private_residence'", ":", "public", ",", "}", "if", "public", "is", "True", ":", "update", "[", "'private_residence'", "]", "=", "False", "elif", "public", "is", "False", ":", "update", "[", "'private_residence'", "]", "=", "True", "check", "=", "[", "x", "for", "x", "in", "update", ".", "values", "(", ")", "if", "x", "is", "not", "None", "]", "if", "not", "check", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"You must specify at least one field to update.\"", ")", "mgr", ".", "edit_rwhois", "(", "*", "*", "update", ")" ]
Edit the RWhois data on the account.
[ "Edit", "the", "RWhois", "data", "on", "the", "account", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/rwhois/edit.py#L26-L55
train
234,396
softlayer/softlayer-python
SoftLayer/CLI/order/quote.py
cli
def cli(env, quote, **args): """View and Order a quote \f :note: The hostname and domain are split out from the fully qualified domain name. If you want to order multiple servers, you need to specify each FQDN. Postinstall, userdata, and sshkeys are applied to all servers in an order. :: slcli order quote 12345 --fqdn testing.tester.com \\ --complex-type SoftLayer_Container_Product_Order_Virtual_Guest -k sshKeyNameLabel\\ -i https://domain.com/runthis.sh --userdata DataGoesHere """ table = formatting.Table([ 'Id', 'Name', 'Created', 'Expiration', 'Status' ]) create_args = _parse_create_args(env.client, args) manager = ordering.OrderingManager(env.client) quote_details = manager.get_quote_details(quote) package = quote_details['order']['items'][0]['package'] create_args['packageId'] = package['id'] if args.get('verify'): result = manager.verify_quote(quote, create_args) verify_table = formatting.Table(['keyName', 'description', 'cost']) verify_table.align['keyName'] = 'l' verify_table.align['description'] = 'l' for price in result['prices']: cost_key = 'hourlyRecurringFee' if result['useHourlyPricing'] is True else 'recurringFee' verify_table.add_row([ price['item']['keyName'], price['item']['description'], price[cost_key] if cost_key in price else formatting.blank() ]) env.fout(verify_table) else: result = manager.order_quote(quote, create_args) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', result['orderId']]) table.add_row(['created', result['orderDate']]) table.add_row(['status', result['placedOrder']['status']]) env.fout(table)
python
def cli(env, quote, **args): """View and Order a quote \f :note: The hostname and domain are split out from the fully qualified domain name. If you want to order multiple servers, you need to specify each FQDN. Postinstall, userdata, and sshkeys are applied to all servers in an order. :: slcli order quote 12345 --fqdn testing.tester.com \\ --complex-type SoftLayer_Container_Product_Order_Virtual_Guest -k sshKeyNameLabel\\ -i https://domain.com/runthis.sh --userdata DataGoesHere """ table = formatting.Table([ 'Id', 'Name', 'Created', 'Expiration', 'Status' ]) create_args = _parse_create_args(env.client, args) manager = ordering.OrderingManager(env.client) quote_details = manager.get_quote_details(quote) package = quote_details['order']['items'][0]['package'] create_args['packageId'] = package['id'] if args.get('verify'): result = manager.verify_quote(quote, create_args) verify_table = formatting.Table(['keyName', 'description', 'cost']) verify_table.align['keyName'] = 'l' verify_table.align['description'] = 'l' for price in result['prices']: cost_key = 'hourlyRecurringFee' if result['useHourlyPricing'] is True else 'recurringFee' verify_table.add_row([ price['item']['keyName'], price['item']['description'], price[cost_key] if cost_key in price else formatting.blank() ]) env.fout(verify_table) else: result = manager.order_quote(quote, create_args) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', result['orderId']]) table.add_row(['created', result['orderDate']]) table.add_row(['status', result['placedOrder']['status']]) env.fout(table)
[ "def", "cli", "(", "env", ",", "quote", ",", "*", "*", "args", ")", ":", "table", "=", "formatting", ".", "Table", "(", "[", "'Id'", ",", "'Name'", ",", "'Created'", ",", "'Expiration'", ",", "'Status'", "]", ")", "create_args", "=", "_parse_create_args", "(", "env", ".", "client", ",", "args", ")", "manager", "=", "ordering", ".", "OrderingManager", "(", "env", ".", "client", ")", "quote_details", "=", "manager", ".", "get_quote_details", "(", "quote", ")", "package", "=", "quote_details", "[", "'order'", "]", "[", "'items'", "]", "[", "0", "]", "[", "'package'", "]", "create_args", "[", "'packageId'", "]", "=", "package", "[", "'id'", "]", "if", "args", ".", "get", "(", "'verify'", ")", ":", "result", "=", "manager", ".", "verify_quote", "(", "quote", ",", "create_args", ")", "verify_table", "=", "formatting", ".", "Table", "(", "[", "'keyName'", ",", "'description'", ",", "'cost'", "]", ")", "verify_table", ".", "align", "[", "'keyName'", "]", "=", "'l'", "verify_table", ".", "align", "[", "'description'", "]", "=", "'l'", "for", "price", "in", "result", "[", "'prices'", "]", ":", "cost_key", "=", "'hourlyRecurringFee'", "if", "result", "[", "'useHourlyPricing'", "]", "is", "True", "else", "'recurringFee'", "verify_table", ".", "add_row", "(", "[", "price", "[", "'item'", "]", "[", "'keyName'", "]", ",", "price", "[", "'item'", "]", "[", "'description'", "]", ",", "price", "[", "cost_key", "]", "if", "cost_key", "in", "price", "else", "formatting", ".", "blank", "(", ")", "]", ")", "env", ".", "fout", "(", "verify_table", ")", "else", ":", "result", "=", "manager", ".", "order_quote", "(", "quote", ",", "create_args", ")", "table", "=", "formatting", ".", "KeyValueTable", "(", "[", "'name'", ",", "'value'", "]", ")", "table", ".", "align", "[", "'name'", "]", "=", "'r'", "table", ".", "align", "[", "'value'", "]", "=", "'l'", "table", ".", "add_row", "(", "[", "'id'", ",", "result", "[", "'orderId'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'created'", ",", "result", "[", "'orderDate'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'status'", ",", "result", "[", "'placedOrder'", "]", "[", "'status'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
View and Order a quote \f :note: The hostname and domain are split out from the fully qualified domain name. If you want to order multiple servers, you need to specify each FQDN. Postinstall, userdata, and sshkeys are applied to all servers in an order. :: slcli order quote 12345 --fqdn testing.tester.com \\ --complex-type SoftLayer_Container_Product_Order_Virtual_Guest -k sshKeyNameLabel\\ -i https://domain.com/runthis.sh --userdata DataGoesHere
[ "View", "and", "Order", "a", "quote" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/quote.py#L81-L130
train
234,397
softlayer/softlayer-python
SoftLayer/managers/block.py
BlockStorageManager.authorize_host_to_volume
def authorize_host_to_volume(self, volume_id, hardware_ids=None, virtual_guest_ids=None, ip_address_ids=None, **kwargs): """Authorizes hosts to Block Storage Volumes :param volume_id: The Block volume to authorize hosts to :param hardware_ids: A List of SoftLayer_Hardware ids :param virtual_guest_ids: A List of SoftLayer_Virtual_Guest ids :param ip_address_ids: A List of SoftLayer_Network_Subnet_IpAddress ids :return: Returns an array of SoftLayer_Network_Storage_Allowed_Host objects which now have access to the given Block volume """ host_templates = [] storage_utils.populate_host_templates(host_templates, hardware_ids, virtual_guest_ids, ip_address_ids, None) return self.client.call('Network_Storage', 'allowAccessFromHostList', host_templates, id=volume_id, **kwargs)
python
def authorize_host_to_volume(self, volume_id, hardware_ids=None, virtual_guest_ids=None, ip_address_ids=None, **kwargs): """Authorizes hosts to Block Storage Volumes :param volume_id: The Block volume to authorize hosts to :param hardware_ids: A List of SoftLayer_Hardware ids :param virtual_guest_ids: A List of SoftLayer_Virtual_Guest ids :param ip_address_ids: A List of SoftLayer_Network_Subnet_IpAddress ids :return: Returns an array of SoftLayer_Network_Storage_Allowed_Host objects which now have access to the given Block volume """ host_templates = [] storage_utils.populate_host_templates(host_templates, hardware_ids, virtual_guest_ids, ip_address_ids, None) return self.client.call('Network_Storage', 'allowAccessFromHostList', host_templates, id=volume_id, **kwargs)
[ "def", "authorize_host_to_volume", "(", "self", ",", "volume_id", ",", "hardware_ids", "=", "None", ",", "virtual_guest_ids", "=", "None", ",", "ip_address_ids", "=", "None", ",", "*", "*", "kwargs", ")", ":", "host_templates", "=", "[", "]", "storage_utils", ".", "populate_host_templates", "(", "host_templates", ",", "hardware_ids", ",", "virtual_guest_ids", ",", "ip_address_ids", ",", "None", ")", "return", "self", ".", "client", ".", "call", "(", "'Network_Storage'", ",", "'allowAccessFromHostList'", ",", "host_templates", ",", "id", "=", "volume_id", ",", "*", "*", "kwargs", ")" ]
Authorizes hosts to Block Storage Volumes :param volume_id: The Block volume to authorize hosts to :param hardware_ids: A List of SoftLayer_Hardware ids :param virtual_guest_ids: A List of SoftLayer_Virtual_Guest ids :param ip_address_ids: A List of SoftLayer_Network_Subnet_IpAddress ids :return: Returns an array of SoftLayer_Network_Storage_Allowed_Host objects which now have access to the given Block volume
[ "Authorizes", "hosts", "to", "Block", "Storage", "Volumes" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/block.py#L154-L177
train
234,398
softlayer/softlayer-python
SoftLayer/managers/block.py
BlockStorageManager.order_replicant_volume
def order_replicant_volume(self, volume_id, snapshot_schedule, location, tier=None, os_type=None): """Places an order for a replicant block volume. :param volume_id: The ID of the primary volume to be replicated :param snapshot_schedule: The primary volume's snapshot schedule to use for replication :param location: The location for the ordered replicant volume :param tier: The tier (IOPS per GB) of the primary volume :param os_type: The OS type of the primary volume :return: Returns a SoftLayer_Container_Product_Order_Receipt """ block_mask = 'billingItem[activeChildren,hourlyFlag],'\ 'storageTierLevel,osType,staasVersion,'\ 'hasEncryptionAtRest,snapshotCapacityGb,schedules,'\ 'intervalSchedule,hourlySchedule,dailySchedule,'\ 'weeklySchedule,storageType[keyName],provisionedIops' block_volume = self.get_block_volume_details(volume_id, mask=block_mask) if os_type is None: if isinstance(utils.lookup(block_volume, 'osType', 'keyName'), str): os_type = block_volume['osType']['keyName'] else: raise exceptions.SoftLayerError( "Cannot find primary volume's os-type " "automatically; must specify manually") order = storage_utils.prepare_replicant_order_object( self, snapshot_schedule, location, tier, block_volume, 'block' ) order['osFormatType'] = {'keyName': os_type} return self.client.call('Product_Order', 'placeOrder', order)
python
def order_replicant_volume(self, volume_id, snapshot_schedule, location, tier=None, os_type=None): """Places an order for a replicant block volume. :param volume_id: The ID of the primary volume to be replicated :param snapshot_schedule: The primary volume's snapshot schedule to use for replication :param location: The location for the ordered replicant volume :param tier: The tier (IOPS per GB) of the primary volume :param os_type: The OS type of the primary volume :return: Returns a SoftLayer_Container_Product_Order_Receipt """ block_mask = 'billingItem[activeChildren,hourlyFlag],'\ 'storageTierLevel,osType,staasVersion,'\ 'hasEncryptionAtRest,snapshotCapacityGb,schedules,'\ 'intervalSchedule,hourlySchedule,dailySchedule,'\ 'weeklySchedule,storageType[keyName],provisionedIops' block_volume = self.get_block_volume_details(volume_id, mask=block_mask) if os_type is None: if isinstance(utils.lookup(block_volume, 'osType', 'keyName'), str): os_type = block_volume['osType']['keyName'] else: raise exceptions.SoftLayerError( "Cannot find primary volume's os-type " "automatically; must specify manually") order = storage_utils.prepare_replicant_order_object( self, snapshot_schedule, location, tier, block_volume, 'block' ) order['osFormatType'] = {'keyName': os_type} return self.client.call('Product_Order', 'placeOrder', order)
[ "def", "order_replicant_volume", "(", "self", ",", "volume_id", ",", "snapshot_schedule", ",", "location", ",", "tier", "=", "None", ",", "os_type", "=", "None", ")", ":", "block_mask", "=", "'billingItem[activeChildren,hourlyFlag],'", "'storageTierLevel,osType,staasVersion,'", "'hasEncryptionAtRest,snapshotCapacityGb,schedules,'", "'intervalSchedule,hourlySchedule,dailySchedule,'", "'weeklySchedule,storageType[keyName],provisionedIops'", "block_volume", "=", "self", ".", "get_block_volume_details", "(", "volume_id", ",", "mask", "=", "block_mask", ")", "if", "os_type", "is", "None", ":", "if", "isinstance", "(", "utils", ".", "lookup", "(", "block_volume", ",", "'osType'", ",", "'keyName'", ")", ",", "str", ")", ":", "os_type", "=", "block_volume", "[", "'osType'", "]", "[", "'keyName'", "]", "else", ":", "raise", "exceptions", ".", "SoftLayerError", "(", "\"Cannot find primary volume's os-type \"", "\"automatically; must specify manually\"", ")", "order", "=", "storage_utils", ".", "prepare_replicant_order_object", "(", "self", ",", "snapshot_schedule", ",", "location", ",", "tier", ",", "block_volume", ",", "'block'", ")", "order", "[", "'osFormatType'", "]", "=", "{", "'keyName'", ":", "os_type", "}", "return", "self", ".", "client", ".", "call", "(", "'Product_Order'", ",", "'placeOrder'", ",", "order", ")" ]
Places an order for a replicant block volume. :param volume_id: The ID of the primary volume to be replicated :param snapshot_schedule: The primary volume's snapshot schedule to use for replication :param location: The location for the ordered replicant volume :param tier: The tier (IOPS per GB) of the primary volume :param os_type: The OS type of the primary volume :return: Returns a SoftLayer_Container_Product_Order_Receipt
[ "Places", "an", "order", "for", "a", "replicant", "block", "volume", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/block.py#L224-L260
train
234,399