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/CLI/config/setup.py | get_api_key | def get_api_key(client, username, secret):
"""Attempts API-Key and password auth to get an API key.
This will also generate an API key if one doesn't exist
"""
# Try to use a client with username/api key
if len(secret) == 64:
try:
client['Account'].getCurrentUser()
return secret
except SoftLayer.SoftLayerAPIError as ex:
if 'invalid api token' not in ex.faultString.lower():
raise
else:
# Try to use a client with username/password
client.authenticate_with_password(username, secret)
user_record = client['Account'].getCurrentUser(mask='id, apiAuthenticationKeys')
api_keys = user_record['apiAuthenticationKeys']
if len(api_keys) == 0:
return client['User_Customer'].addApiAuthenticationKey(id=user_record['id'])
return api_keys[0]['authenticationKey'] | python | def get_api_key(client, username, secret):
"""Attempts API-Key and password auth to get an API key.
This will also generate an API key if one doesn't exist
"""
# Try to use a client with username/api key
if len(secret) == 64:
try:
client['Account'].getCurrentUser()
return secret
except SoftLayer.SoftLayerAPIError as ex:
if 'invalid api token' not in ex.faultString.lower():
raise
else:
# Try to use a client with username/password
client.authenticate_with_password(username, secret)
user_record = client['Account'].getCurrentUser(mask='id, apiAuthenticationKeys')
api_keys = user_record['apiAuthenticationKeys']
if len(api_keys) == 0:
return client['User_Customer'].addApiAuthenticationKey(id=user_record['id'])
return api_keys[0]['authenticationKey'] | [
"def",
"get_api_key",
"(",
"client",
",",
"username",
",",
"secret",
")",
":",
"# Try to use a client with username/api key",
"if",
"len",
"(",
"secret",
")",
"==",
"64",
":",
"try",
":",
"client",
"[",
"'Account'",
"]",
".",
"getCurrentUser",
"(",
")",
"return",
"secret",
"except",
"SoftLayer",
".",
"SoftLayerAPIError",
"as",
"ex",
":",
"if",
"'invalid api token'",
"not",
"in",
"ex",
".",
"faultString",
".",
"lower",
"(",
")",
":",
"raise",
"else",
":",
"# Try to use a client with username/password",
"client",
".",
"authenticate_with_password",
"(",
"username",
",",
"secret",
")",
"user_record",
"=",
"client",
"[",
"'Account'",
"]",
".",
"getCurrentUser",
"(",
"mask",
"=",
"'id, apiAuthenticationKeys'",
")",
"api_keys",
"=",
"user_record",
"[",
"'apiAuthenticationKeys'",
"]",
"if",
"len",
"(",
"api_keys",
")",
"==",
"0",
":",
"return",
"client",
"[",
"'User_Customer'",
"]",
".",
"addApiAuthenticationKey",
"(",
"id",
"=",
"user_record",
"[",
"'id'",
"]",
")",
"return",
"api_keys",
"[",
"0",
"]",
"[",
"'authenticationKey'",
"]"
] | Attempts API-Key and password auth to get an API key.
This will also generate an API key if one doesn't exist | [
"Attempts",
"API",
"-",
"Key",
"and",
"password",
"auth",
"to",
"get",
"an",
"API",
"key",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/config/setup.py#L15-L37 | train | 234,200 |
softlayer/softlayer-python | SoftLayer/CLI/config/setup.py | cli | def cli(env):
"""Edit configuration."""
username, secret, endpoint_url, timeout = get_user_input(env)
new_client = SoftLayer.Client(username=username, api_key=secret, endpoint_url=endpoint_url, timeout=timeout)
api_key = get_api_key(new_client, username, secret)
path = '~/.softlayer'
if env.config_file:
path = env.config_file
config_path = os.path.expanduser(path)
env.out(env.fmt(config.config_table({'username': username,
'api_key': api_key,
'endpoint_url': endpoint_url,
'timeout': timeout})))
if not formatting.confirm('Are you sure you want to write settings '
'to "%s"?' % config_path, default=True):
raise exceptions.CLIAbort('Aborted.')
# Persist the config file. Read the target config file in before
# setting the values to avoid clobbering settings
parsed_config = utils.configparser.RawConfigParser()
parsed_config.read(config_path)
try:
parsed_config.add_section('softlayer')
except utils.configparser.DuplicateSectionError:
pass
parsed_config.set('softlayer', 'username', username)
parsed_config.set('softlayer', 'api_key', api_key)
parsed_config.set('softlayer', 'endpoint_url', endpoint_url)
parsed_config.set('softlayer', 'timeout', timeout)
config_fd = os.fdopen(os.open(config_path,
(os.O_WRONLY | os.O_CREAT | os.O_TRUNC),
0o600),
'w')
try:
parsed_config.write(config_fd)
finally:
config_fd.close()
env.fout("Configuration Updated Successfully") | python | def cli(env):
"""Edit configuration."""
username, secret, endpoint_url, timeout = get_user_input(env)
new_client = SoftLayer.Client(username=username, api_key=secret, endpoint_url=endpoint_url, timeout=timeout)
api_key = get_api_key(new_client, username, secret)
path = '~/.softlayer'
if env.config_file:
path = env.config_file
config_path = os.path.expanduser(path)
env.out(env.fmt(config.config_table({'username': username,
'api_key': api_key,
'endpoint_url': endpoint_url,
'timeout': timeout})))
if not formatting.confirm('Are you sure you want to write settings '
'to "%s"?' % config_path, default=True):
raise exceptions.CLIAbort('Aborted.')
# Persist the config file. Read the target config file in before
# setting the values to avoid clobbering settings
parsed_config = utils.configparser.RawConfigParser()
parsed_config.read(config_path)
try:
parsed_config.add_section('softlayer')
except utils.configparser.DuplicateSectionError:
pass
parsed_config.set('softlayer', 'username', username)
parsed_config.set('softlayer', 'api_key', api_key)
parsed_config.set('softlayer', 'endpoint_url', endpoint_url)
parsed_config.set('softlayer', 'timeout', timeout)
config_fd = os.fdopen(os.open(config_path,
(os.O_WRONLY | os.O_CREAT | os.O_TRUNC),
0o600),
'w')
try:
parsed_config.write(config_fd)
finally:
config_fd.close()
env.fout("Configuration Updated Successfully") | [
"def",
"cli",
"(",
"env",
")",
":",
"username",
",",
"secret",
",",
"endpoint_url",
",",
"timeout",
"=",
"get_user_input",
"(",
"env",
")",
"new_client",
"=",
"SoftLayer",
".",
"Client",
"(",
"username",
"=",
"username",
",",
"api_key",
"=",
"secret",
",",
"endpoint_url",
"=",
"endpoint_url",
",",
"timeout",
"=",
"timeout",
")",
"api_key",
"=",
"get_api_key",
"(",
"new_client",
",",
"username",
",",
"secret",
")",
"path",
"=",
"'~/.softlayer'",
"if",
"env",
".",
"config_file",
":",
"path",
"=",
"env",
".",
"config_file",
"config_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"env",
".",
"out",
"(",
"env",
".",
"fmt",
"(",
"config",
".",
"config_table",
"(",
"{",
"'username'",
":",
"username",
",",
"'api_key'",
":",
"api_key",
",",
"'endpoint_url'",
":",
"endpoint_url",
",",
"'timeout'",
":",
"timeout",
"}",
")",
")",
")",
"if",
"not",
"formatting",
".",
"confirm",
"(",
"'Are you sure you want to write settings '",
"'to \"%s\"?'",
"%",
"config_path",
",",
"default",
"=",
"True",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted.'",
")",
"# Persist the config file. Read the target config file in before",
"# setting the values to avoid clobbering settings",
"parsed_config",
"=",
"utils",
".",
"configparser",
".",
"RawConfigParser",
"(",
")",
"parsed_config",
".",
"read",
"(",
"config_path",
")",
"try",
":",
"parsed_config",
".",
"add_section",
"(",
"'softlayer'",
")",
"except",
"utils",
".",
"configparser",
".",
"DuplicateSectionError",
":",
"pass",
"parsed_config",
".",
"set",
"(",
"'softlayer'",
",",
"'username'",
",",
"username",
")",
"parsed_config",
".",
"set",
"(",
"'softlayer'",
",",
"'api_key'",
",",
"api_key",
")",
"parsed_config",
".",
"set",
"(",
"'softlayer'",
",",
"'endpoint_url'",
",",
"endpoint_url",
")",
"parsed_config",
".",
"set",
"(",
"'softlayer'",
",",
"'timeout'",
",",
"timeout",
")",
"config_fd",
"=",
"os",
".",
"fdopen",
"(",
"os",
".",
"open",
"(",
"config_path",
",",
"(",
"os",
".",
"O_WRONLY",
"|",
"os",
".",
"O_CREAT",
"|",
"os",
".",
"O_TRUNC",
")",
",",
"0o600",
")",
",",
"'w'",
")",
"try",
":",
"parsed_config",
".",
"write",
"(",
"config_fd",
")",
"finally",
":",
"config_fd",
".",
"close",
"(",
")",
"env",
".",
"fout",
"(",
"\"Configuration Updated Successfully\"",
")"
] | Edit configuration. | [
"Edit",
"configuration",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/config/setup.py#L42-L86 | train | 234,201 |
softlayer/softlayer-python | SoftLayer/CLI/dedicatedhost/create_options.py | cli | def cli(env, **kwargs):
"""host order options for a given dedicated host.
To get a list of available backend routers see example:
slcli dh create-options --datacenter dal05 --flavor 56_CORES_X_242_RAM_X_1_4_TB
"""
mgr = SoftLayer.DedicatedHostManager(env.client)
tables = []
if not kwargs['flavor'] and not kwargs['datacenter']:
options = mgr.get_create_options()
# Datacenters
dc_table = formatting.Table(['datacenter', 'value'])
dc_table.sortby = 'value'
for location in options['locations']:
dc_table.add_row([location['name'], location['key']])
tables.append(dc_table)
dh_table = formatting.Table(['Dedicated Virtual Host Flavor(s)', 'value'])
dh_table.sortby = 'value'
for item in options['dedicated_host']:
dh_table.add_row([item['name'], item['key']])
tables.append(dh_table)
else:
if kwargs['flavor'] is None or kwargs['datacenter'] is None:
raise exceptions.ArgumentError('Both a flavor and datacenter need '
'to be passed as arguments '
'ex. slcli dh create-options -d '
'ams01 -f '
'56_CORES_X_242_RAM_X_1_4_TB')
router_opt = mgr.get_router_options(kwargs['datacenter'], kwargs['flavor'])
br_table = formatting.Table(
['Available Backend Routers'])
for router in router_opt:
br_table.add_row([router['hostname']])
tables.append(br_table)
env.fout(formatting.listing(tables, separator='\n')) | python | def cli(env, **kwargs):
"""host order options for a given dedicated host.
To get a list of available backend routers see example:
slcli dh create-options --datacenter dal05 --flavor 56_CORES_X_242_RAM_X_1_4_TB
"""
mgr = SoftLayer.DedicatedHostManager(env.client)
tables = []
if not kwargs['flavor'] and not kwargs['datacenter']:
options = mgr.get_create_options()
# Datacenters
dc_table = formatting.Table(['datacenter', 'value'])
dc_table.sortby = 'value'
for location in options['locations']:
dc_table.add_row([location['name'], location['key']])
tables.append(dc_table)
dh_table = formatting.Table(['Dedicated Virtual Host Flavor(s)', 'value'])
dh_table.sortby = 'value'
for item in options['dedicated_host']:
dh_table.add_row([item['name'], item['key']])
tables.append(dh_table)
else:
if kwargs['flavor'] is None or kwargs['datacenter'] is None:
raise exceptions.ArgumentError('Both a flavor and datacenter need '
'to be passed as arguments '
'ex. slcli dh create-options -d '
'ams01 -f '
'56_CORES_X_242_RAM_X_1_4_TB')
router_opt = mgr.get_router_options(kwargs['datacenter'], kwargs['flavor'])
br_table = formatting.Table(
['Available Backend Routers'])
for router in router_opt:
br_table.add_row([router['hostname']])
tables.append(br_table)
env.fout(formatting.listing(tables, separator='\n')) | [
"def",
"cli",
"(",
"env",
",",
"*",
"*",
"kwargs",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"DedicatedHostManager",
"(",
"env",
".",
"client",
")",
"tables",
"=",
"[",
"]",
"if",
"not",
"kwargs",
"[",
"'flavor'",
"]",
"and",
"not",
"kwargs",
"[",
"'datacenter'",
"]",
":",
"options",
"=",
"mgr",
".",
"get_create_options",
"(",
")",
"# Datacenters",
"dc_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'datacenter'",
",",
"'value'",
"]",
")",
"dc_table",
".",
"sortby",
"=",
"'value'",
"for",
"location",
"in",
"options",
"[",
"'locations'",
"]",
":",
"dc_table",
".",
"add_row",
"(",
"[",
"location",
"[",
"'name'",
"]",
",",
"location",
"[",
"'key'",
"]",
"]",
")",
"tables",
".",
"append",
"(",
"dc_table",
")",
"dh_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Dedicated Virtual Host Flavor(s)'",
",",
"'value'",
"]",
")",
"dh_table",
".",
"sortby",
"=",
"'value'",
"for",
"item",
"in",
"options",
"[",
"'dedicated_host'",
"]",
":",
"dh_table",
".",
"add_row",
"(",
"[",
"item",
"[",
"'name'",
"]",
",",
"item",
"[",
"'key'",
"]",
"]",
")",
"tables",
".",
"append",
"(",
"dh_table",
")",
"else",
":",
"if",
"kwargs",
"[",
"'flavor'",
"]",
"is",
"None",
"or",
"kwargs",
"[",
"'datacenter'",
"]",
"is",
"None",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"'Both a flavor and datacenter need '",
"'to be passed as arguments '",
"'ex. slcli dh create-options -d '",
"'ams01 -f '",
"'56_CORES_X_242_RAM_X_1_4_TB'",
")",
"router_opt",
"=",
"mgr",
".",
"get_router_options",
"(",
"kwargs",
"[",
"'datacenter'",
"]",
",",
"kwargs",
"[",
"'flavor'",
"]",
")",
"br_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Available Backend Routers'",
"]",
")",
"for",
"router",
"in",
"router_opt",
":",
"br_table",
".",
"add_row",
"(",
"[",
"router",
"[",
"'hostname'",
"]",
"]",
")",
"tables",
".",
"append",
"(",
"br_table",
")",
"env",
".",
"fout",
"(",
"formatting",
".",
"listing",
"(",
"tables",
",",
"separator",
"=",
"'\\n'",
")",
")"
] | host order options for a given dedicated host.
To get a list of available backend routers see example:
slcli dh create-options --datacenter dal05 --flavor 56_CORES_X_242_RAM_X_1_4_TB | [
"host",
"order",
"options",
"for",
"a",
"given",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dedicatedhost/create_options.py#L22-L61 | train | 234,202 |
softlayer/softlayer-python | SoftLayer/CLI/hardware/cancel_reasons.py | cli | def cli(env):
"""Display a list of cancellation reasons."""
table = formatting.Table(['Code', 'Reason'])
table.align['Code'] = 'r'
table.align['Reason'] = 'l'
mgr = SoftLayer.HardwareManager(env.client)
for code, reason in mgr.get_cancellation_reasons().items():
table.add_row([code, reason])
env.fout(table) | python | def cli(env):
"""Display a list of cancellation reasons."""
table = formatting.Table(['Code', 'Reason'])
table.align['Code'] = 'r'
table.align['Reason'] = 'l'
mgr = SoftLayer.HardwareManager(env.client)
for code, reason in mgr.get_cancellation_reasons().items():
table.add_row([code, reason])
env.fout(table) | [
"def",
"cli",
"(",
"env",
")",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Code'",
",",
"'Reason'",
"]",
")",
"table",
".",
"align",
"[",
"'Code'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'Reason'",
"]",
"=",
"'l'",
"mgr",
"=",
"SoftLayer",
".",
"HardwareManager",
"(",
"env",
".",
"client",
")",
"for",
"code",
",",
"reason",
"in",
"mgr",
".",
"get_cancellation_reasons",
"(",
")",
".",
"items",
"(",
")",
":",
"table",
".",
"add_row",
"(",
"[",
"code",
",",
"reason",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | Display a list of cancellation reasons. | [
"Display",
"a",
"list",
"of",
"cancellation",
"reasons",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/cancel_reasons.py#L13-L25 | train | 234,203 |
softlayer/softlayer-python | SoftLayer/CLI/vpn/ipsec/list.py | cli | def cli(env):
"""List IPSec VPN tunnel contexts"""
manager = SoftLayer.IPSECManager(env.client)
contexts = manager.get_tunnel_contexts()
table = formatting.Table(['id',
'name',
'friendly name',
'internal peer IP address',
'remote peer IP address',
'created'])
for context in contexts:
table.add_row([context.get('id', ''),
context.get('name', ''),
context.get('friendlyName', ''),
context.get('internalPeerIpAddress', ''),
context.get('customerPeerIpAddress', ''),
context.get('createDate', '')])
env.fout(table) | python | def cli(env):
"""List IPSec VPN tunnel contexts"""
manager = SoftLayer.IPSECManager(env.client)
contexts = manager.get_tunnel_contexts()
table = formatting.Table(['id',
'name',
'friendly name',
'internal peer IP address',
'remote peer IP address',
'created'])
for context in contexts:
table.add_row([context.get('id', ''),
context.get('name', ''),
context.get('friendlyName', ''),
context.get('internalPeerIpAddress', ''),
context.get('customerPeerIpAddress', ''),
context.get('createDate', '')])
env.fout(table) | [
"def",
"cli",
"(",
"env",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"IPSECManager",
"(",
"env",
".",
"client",
")",
"contexts",
"=",
"manager",
".",
"get_tunnel_contexts",
"(",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'name'",
",",
"'friendly name'",
",",
"'internal peer IP address'",
",",
"'remote peer IP address'",
",",
"'created'",
"]",
")",
"for",
"context",
"in",
"contexts",
":",
"table",
".",
"add_row",
"(",
"[",
"context",
".",
"get",
"(",
"'id'",
",",
"''",
")",
",",
"context",
".",
"get",
"(",
"'name'",
",",
"''",
")",
",",
"context",
".",
"get",
"(",
"'friendlyName'",
",",
"''",
")",
",",
"context",
".",
"get",
"(",
"'internalPeerIpAddress'",
",",
"''",
")",
",",
"context",
".",
"get",
"(",
"'customerPeerIpAddress'",
",",
"''",
")",
",",
"context",
".",
"get",
"(",
"'createDate'",
",",
"''",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List IPSec VPN tunnel contexts | [
"List",
"IPSec",
"VPN",
"tunnel",
"contexts"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/list.py#L13-L31 | train | 234,204 |
softlayer/softlayer-python | SoftLayer/CLI/file/replication/locations.py | cli | def cli(env, columns, sortby, volume_id):
"""List suitable replication datacenters for the given volume."""
file_storage_manager = SoftLayer.FileStorageManager(env.client)
legal_centers = file_storage_manager.get_replication_locations(
volume_id
)
if not legal_centers:
click.echo("No data centers compatible for replication.")
else:
table = formatting.KeyValueTable(columns.columns)
table.sortby = sortby
for legal_center in legal_centers:
table.add_row([value or formatting.blank()
for value in columns.row(legal_center)])
env.fout(table) | python | def cli(env, columns, sortby, volume_id):
"""List suitable replication datacenters for the given volume."""
file_storage_manager = SoftLayer.FileStorageManager(env.client)
legal_centers = file_storage_manager.get_replication_locations(
volume_id
)
if not legal_centers:
click.echo("No data centers compatible for replication.")
else:
table = formatting.KeyValueTable(columns.columns)
table.sortby = sortby
for legal_center in legal_centers:
table.add_row([value or formatting.blank()
for value in columns.row(legal_center)])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"columns",
",",
"sortby",
",",
"volume_id",
")",
":",
"file_storage_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"legal_centers",
"=",
"file_storage_manager",
".",
"get_replication_locations",
"(",
"volume_id",
")",
"if",
"not",
"legal_centers",
":",
"click",
".",
"echo",
"(",
"\"No data centers compatible for replication.\"",
")",
"else",
":",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"columns",
".",
"columns",
")",
"table",
".",
"sortby",
"=",
"sortby",
"for",
"legal_center",
"in",
"legal_centers",
":",
"table",
".",
"add_row",
"(",
"[",
"value",
"or",
"formatting",
".",
"blank",
"(",
")",
"for",
"value",
"in",
"columns",
".",
"row",
"(",
"legal_center",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List suitable replication datacenters for the given volume. | [
"List",
"suitable",
"replication",
"datacenters",
"for",
"the",
"given",
"volume",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/replication/locations.py#L32-L49 | train | 234,205 |
softlayer/softlayer-python | SoftLayer/CLI/dedicatedhost/list_guests.py | cli | def cli(env, identifier, sortby, cpu, domain, hostname, memory, tag, columns):
"""List guests which are in a dedicated host server."""
mgr = SoftLayer.DedicatedHostManager(env.client)
guests = mgr.list_guests(host_id=identifier,
cpus=cpu,
hostname=hostname,
domain=domain,
memory=memory,
tags=tag,
mask=columns.mask())
table = formatting.Table(columns.columns)
table.sortby = sortby
for guest in guests:
table.add_row([value or formatting.blank()
for value in columns.row(guest)])
env.fout(table) | python | def cli(env, identifier, sortby, cpu, domain, hostname, memory, tag, columns):
"""List guests which are in a dedicated host server."""
mgr = SoftLayer.DedicatedHostManager(env.client)
guests = mgr.list_guests(host_id=identifier,
cpus=cpu,
hostname=hostname,
domain=domain,
memory=memory,
tags=tag,
mask=columns.mask())
table = formatting.Table(columns.columns)
table.sortby = sortby
for guest in guests:
table.add_row([value or formatting.blank()
for value in columns.row(guest)])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"sortby",
",",
"cpu",
",",
"domain",
",",
"hostname",
",",
"memory",
",",
"tag",
",",
"columns",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"DedicatedHostManager",
"(",
"env",
".",
"client",
")",
"guests",
"=",
"mgr",
".",
"list_guests",
"(",
"host_id",
"=",
"identifier",
",",
"cpus",
"=",
"cpu",
",",
"hostname",
"=",
"hostname",
",",
"domain",
"=",
"domain",
",",
"memory",
"=",
"memory",
",",
"tags",
"=",
"tag",
",",
"mask",
"=",
"columns",
".",
"mask",
"(",
")",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"columns",
".",
"columns",
")",
"table",
".",
"sortby",
"=",
"sortby",
"for",
"guest",
"in",
"guests",
":",
"table",
".",
"add_row",
"(",
"[",
"value",
"or",
"formatting",
".",
"blank",
"(",
")",
"for",
"value",
"in",
"columns",
".",
"row",
"(",
"guest",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List guests which are in a dedicated host server. | [
"List",
"guests",
"which",
"are",
"in",
"a",
"dedicated",
"host",
"server",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dedicatedhost/list_guests.py#L57-L76 | train | 234,206 |
softlayer/softlayer-python | SoftLayer/CLI/ticket/detail.py | cli | def cli(env, identifier, count):
"""Get details for a ticket."""
mgr = SoftLayer.TicketManager(env.client)
ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket')
env.fout(ticket.get_ticket_results(mgr, ticket_id, update_count=count)) | python | def cli(env, identifier, count):
"""Get details for a ticket."""
mgr = SoftLayer.TicketManager(env.client)
ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket')
env.fout(ticket.get_ticket_results(mgr, ticket_id, update_count=count)) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"count",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"TicketManager",
"(",
"env",
".",
"client",
")",
"ticket_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'ticket'",
")",
"env",
".",
"fout",
"(",
"ticket",
".",
"get_ticket_results",
"(",
"mgr",
",",
"ticket_id",
",",
"update_count",
"=",
"count",
")",
")"
] | Get details for a ticket. | [
"Get",
"details",
"for",
"a",
"ticket",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ticket/detail.py#L20-L26 | train | 234,207 |
softlayer/softlayer-python | SoftLayer/transports.py | get_session | def get_session(user_agent):
"""Sets up urllib sessions"""
client = requests.Session()
client.headers.update({
'Content-Type': 'application/json',
'User-Agent': user_agent,
})
retry = Retry(connect=3, backoff_factor=3)
adapter = HTTPAdapter(max_retries=retry)
client.mount('https://', adapter)
return client | python | def get_session(user_agent):
"""Sets up urllib sessions"""
client = requests.Session()
client.headers.update({
'Content-Type': 'application/json',
'User-Agent': user_agent,
})
retry = Retry(connect=3, backoff_factor=3)
adapter = HTTPAdapter(max_retries=retry)
client.mount('https://', adapter)
return client | [
"def",
"get_session",
"(",
"user_agent",
")",
":",
"client",
"=",
"requests",
".",
"Session",
"(",
")",
"client",
".",
"headers",
".",
"update",
"(",
"{",
"'Content-Type'",
":",
"'application/json'",
",",
"'User-Agent'",
":",
"user_agent",
",",
"}",
")",
"retry",
"=",
"Retry",
"(",
"connect",
"=",
"3",
",",
"backoff_factor",
"=",
"3",
")",
"adapter",
"=",
"HTTPAdapter",
"(",
"max_retries",
"=",
"retry",
")",
"client",
".",
"mount",
"(",
"'https://'",
",",
"adapter",
")",
"return",
"client"
] | Sets up urllib sessions | [
"Sets",
"up",
"urllib",
"sessions"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/transports.py#L45-L56 | train | 234,208 |
softlayer/softlayer-python | SoftLayer/transports.py | _format_object_mask | def _format_object_mask(objectmask):
"""Format the new style object mask.
This wraps the user mask with mask[USER_MASK] if it does not already
have one. This makes it slightly easier for users.
:param objectmask: a string-based object mask
"""
objectmask = objectmask.strip()
if (not objectmask.startswith('mask') and
not objectmask.startswith('[')):
objectmask = "mask[%s]" % objectmask
return objectmask | python | def _format_object_mask(objectmask):
"""Format the new style object mask.
This wraps the user mask with mask[USER_MASK] if it does not already
have one. This makes it slightly easier for users.
:param objectmask: a string-based object mask
"""
objectmask = objectmask.strip()
if (not objectmask.startswith('mask') and
not objectmask.startswith('[')):
objectmask = "mask[%s]" % objectmask
return objectmask | [
"def",
"_format_object_mask",
"(",
"objectmask",
")",
":",
"objectmask",
"=",
"objectmask",
".",
"strip",
"(",
")",
"if",
"(",
"not",
"objectmask",
".",
"startswith",
"(",
"'mask'",
")",
"and",
"not",
"objectmask",
".",
"startswith",
"(",
"'['",
")",
")",
":",
"objectmask",
"=",
"\"mask[%s]\"",
"%",
"objectmask",
"return",
"objectmask"
] | Format the new style object mask.
This wraps the user mask with mask[USER_MASK] if it does not already
have one. This makes it slightly easier for users.
:param objectmask: a string-based object mask | [
"Format",
"the",
"new",
"style",
"object",
"mask",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/transports.py#L544-L558 | train | 234,209 |
softlayer/softlayer-python | SoftLayer/transports.py | XmlRpcTransport.client | def client(self):
"""Returns client session object"""
if self._client is None:
self._client = get_session(self.user_agent)
return self._client | python | def client(self):
"""Returns client session object"""
if self._client is None:
self._client = get_session(self.user_agent)
return self._client | [
"def",
"client",
"(",
"self",
")",
":",
"if",
"self",
".",
"_client",
"is",
"None",
":",
"self",
".",
"_client",
"=",
"get_session",
"(",
"self",
".",
"user_agent",
")",
"return",
"self",
".",
"_client"
] | Returns client session object | [
"Returns",
"client",
"session",
"object"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/transports.py#L158-L163 | train | 234,210 |
softlayer/softlayer-python | SoftLayer/CLI/hardware/toggle_ipmi.py | cli | def cli(env, identifier, enable):
"""Toggle the IPMI interface on and off"""
mgr = SoftLayer.HardwareManager(env.client)
hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
result = env.client['Hardware_Server'].toggleManagementInterface(enable, id=hw_id)
env.fout(result) | python | def cli(env, identifier, enable):
"""Toggle the IPMI interface on and off"""
mgr = SoftLayer.HardwareManager(env.client)
hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
result = env.client['Hardware_Server'].toggleManagementInterface(enable, id=hw_id)
env.fout(result) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"enable",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"HardwareManager",
"(",
"env",
".",
"client",
")",
"hw_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'hardware'",
")",
"result",
"=",
"env",
".",
"client",
"[",
"'Hardware_Server'",
"]",
".",
"toggleManagementInterface",
"(",
"enable",
",",
"id",
"=",
"hw_id",
")",
"env",
".",
"fout",
"(",
"result",
")"
] | Toggle the IPMI interface on and off | [
"Toggle",
"the",
"IPMI",
"interface",
"on",
"and",
"off"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/toggle_ipmi.py#L16-L22 | train | 234,211 |
softlayer/softlayer-python | SoftLayer/CLI/dns/record_remove.py | cli | def cli(env, record_id):
"""Remove resource record."""
manager = SoftLayer.DNSManager(env.client)
if not (env.skip_confirmations or formatting.no_going_back('yes')):
raise exceptions.CLIAbort("Aborted.")
manager.delete_record(record_id) | python | def cli(env, record_id):
"""Remove resource record."""
manager = SoftLayer.DNSManager(env.client)
if not (env.skip_confirmations or formatting.no_going_back('yes')):
raise exceptions.CLIAbort("Aborted.")
manager.delete_record(record_id) | [
"def",
"cli",
"(",
"env",
",",
"record_id",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"DNSManager",
"(",
"env",
".",
"client",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"no_going_back",
"(",
"'yes'",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Aborted.\"",
")",
"manager",
".",
"delete_record",
"(",
"record_id",
")"
] | Remove resource record. | [
"Remove",
"resource",
"record",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dns/record_remove.py#L15-L23 | train | 234,212 |
softlayer/softlayer-python | SoftLayer/CLI/block/count.py | cli | def cli(env, sortby, datacenter):
"""List number of block storage volumes per datacenter."""
block_manager = SoftLayer.BlockStorageManager(env.client)
mask = "mask[serviceResource[datacenter[name]],"\
"replicationPartners[serviceResource[datacenter[name]]]]"
block_volumes = block_manager.list_block_volumes(datacenter=datacenter,
mask=mask)
# cycle through all block volumes and count datacenter occurences.
datacenters = dict()
for volume in block_volumes:
service_resource = volume['serviceResource']
if 'datacenter' in service_resource:
datacenter_name = service_resource['datacenter']['name']
if datacenter_name not in datacenters.keys():
datacenters[datacenter_name] = 1
else:
datacenters[datacenter_name] += 1
table = formatting.KeyValueTable(DEFAULT_COLUMNS)
table.sortby = sortby
for datacenter_name in datacenters:
table.add_row([datacenter_name, datacenters[datacenter_name]])
env.fout(table) | python | def cli(env, sortby, datacenter):
"""List number of block storage volumes per datacenter."""
block_manager = SoftLayer.BlockStorageManager(env.client)
mask = "mask[serviceResource[datacenter[name]],"\
"replicationPartners[serviceResource[datacenter[name]]]]"
block_volumes = block_manager.list_block_volumes(datacenter=datacenter,
mask=mask)
# cycle through all block volumes and count datacenter occurences.
datacenters = dict()
for volume in block_volumes:
service_resource = volume['serviceResource']
if 'datacenter' in service_resource:
datacenter_name = service_resource['datacenter']['name']
if datacenter_name not in datacenters.keys():
datacenters[datacenter_name] = 1
else:
datacenters[datacenter_name] += 1
table = formatting.KeyValueTable(DEFAULT_COLUMNS)
table.sortby = sortby
for datacenter_name in datacenters:
table.add_row([datacenter_name, datacenters[datacenter_name]])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"sortby",
",",
"datacenter",
")",
":",
"block_manager",
"=",
"SoftLayer",
".",
"BlockStorageManager",
"(",
"env",
".",
"client",
")",
"mask",
"=",
"\"mask[serviceResource[datacenter[name]],\"",
"\"replicationPartners[serviceResource[datacenter[name]]]]\"",
"block_volumes",
"=",
"block_manager",
".",
"list_block_volumes",
"(",
"datacenter",
"=",
"datacenter",
",",
"mask",
"=",
"mask",
")",
"# cycle through all block volumes and count datacenter occurences.",
"datacenters",
"=",
"dict",
"(",
")",
"for",
"volume",
"in",
"block_volumes",
":",
"service_resource",
"=",
"volume",
"[",
"'serviceResource'",
"]",
"if",
"'datacenter'",
"in",
"service_resource",
":",
"datacenter_name",
"=",
"service_resource",
"[",
"'datacenter'",
"]",
"[",
"'name'",
"]",
"if",
"datacenter_name",
"not",
"in",
"datacenters",
".",
"keys",
"(",
")",
":",
"datacenters",
"[",
"datacenter_name",
"]",
"=",
"1",
"else",
":",
"datacenters",
"[",
"datacenter_name",
"]",
"+=",
"1",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"DEFAULT_COLUMNS",
")",
"table",
".",
"sortby",
"=",
"sortby",
"for",
"datacenter_name",
"in",
"datacenters",
":",
"table",
".",
"add_row",
"(",
"[",
"datacenter_name",
",",
"datacenters",
"[",
"datacenter_name",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List number of block storage volumes per datacenter. | [
"List",
"number",
"of",
"block",
"storage",
"volumes",
"per",
"datacenter",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/count.py#L19-L42 | train | 234,213 |
softlayer/softlayer-python | SoftLayer/CLI/cdn/load.py | cli | def cli(env, account_id, content_url):
"""Cache one or more files on all edge nodes."""
manager = SoftLayer.CDNManager(env.client)
manager.load_content(account_id, content_url) | python | def cli(env, account_id, content_url):
"""Cache one or more files on all edge nodes."""
manager = SoftLayer.CDNManager(env.client)
manager.load_content(account_id, content_url) | [
"def",
"cli",
"(",
"env",
",",
"account_id",
",",
"content_url",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"CDNManager",
"(",
"env",
".",
"client",
")",
"manager",
".",
"load_content",
"(",
"account_id",
",",
"content_url",
")"
] | Cache one or more files on all edge nodes. | [
"Cache",
"one",
"or",
"more",
"files",
"on",
"all",
"edge",
"nodes",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/cdn/load.py#L14-L18 | train | 234,214 |
softlayer/softlayer-python | SoftLayer/CLI/vlan/detail.py | cli | def cli(env, identifier, no_vs, no_hardware):
"""Get details about a VLAN."""
mgr = SoftLayer.NetworkManager(env.client)
vlan_id = helpers.resolve_id(mgr.resolve_vlan_ids, identifier, 'VLAN')
vlan = mgr.get_vlan(vlan_id)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', vlan['id']])
table.add_row(['number', vlan['vlanNumber']])
table.add_row(['datacenter',
vlan['primaryRouter']['datacenter']['longName']])
table.add_row(['primary_router',
vlan['primaryRouter']['fullyQualifiedDomainName']])
table.add_row(['firewall',
'Yes' if vlan['firewallInterfaces'] else 'No'])
subnets = []
for subnet in vlan.get('subnets', []):
subnet_table = formatting.KeyValueTable(['name', 'value'])
subnet_table.align['name'] = 'r'
subnet_table.align['value'] = 'l'
subnet_table.add_row(['id', subnet['id']])
subnet_table.add_row(['identifier', subnet['networkIdentifier']])
subnet_table.add_row(['netmask', subnet['netmask']])
subnet_table.add_row(['gateway', subnet.get('gateway', '-')])
subnet_table.add_row(['type', subnet['subnetType']])
subnet_table.add_row(['usable ips',
subnet['usableIpAddressCount']])
subnets.append(subnet_table)
table.add_row(['subnets', subnets])
server_columns = ['hostname', 'domain', 'public_ip', 'private_ip']
if not no_vs:
if vlan.get('virtualGuests'):
vs_table = formatting.KeyValueTable(server_columns)
for vsi in vlan['virtualGuests']:
vs_table.add_row([vsi.get('hostname'),
vsi.get('domain'),
vsi.get('primaryIpAddress'),
vsi.get('primaryBackendIpAddress')])
table.add_row(['vs', vs_table])
else:
table.add_row(['vs', 'none'])
if not no_hardware:
if vlan.get('hardware'):
hw_table = formatting.Table(server_columns)
for hardware in vlan['hardware']:
hw_table.add_row([hardware.get('hostname'),
hardware.get('domain'),
hardware.get('primaryIpAddress'),
hardware.get('primaryBackendIpAddress')])
table.add_row(['hardware', hw_table])
else:
table.add_row(['hardware', 'none'])
env.fout(table) | python | def cli(env, identifier, no_vs, no_hardware):
"""Get details about a VLAN."""
mgr = SoftLayer.NetworkManager(env.client)
vlan_id = helpers.resolve_id(mgr.resolve_vlan_ids, identifier, 'VLAN')
vlan = mgr.get_vlan(vlan_id)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', vlan['id']])
table.add_row(['number', vlan['vlanNumber']])
table.add_row(['datacenter',
vlan['primaryRouter']['datacenter']['longName']])
table.add_row(['primary_router',
vlan['primaryRouter']['fullyQualifiedDomainName']])
table.add_row(['firewall',
'Yes' if vlan['firewallInterfaces'] else 'No'])
subnets = []
for subnet in vlan.get('subnets', []):
subnet_table = formatting.KeyValueTable(['name', 'value'])
subnet_table.align['name'] = 'r'
subnet_table.align['value'] = 'l'
subnet_table.add_row(['id', subnet['id']])
subnet_table.add_row(['identifier', subnet['networkIdentifier']])
subnet_table.add_row(['netmask', subnet['netmask']])
subnet_table.add_row(['gateway', subnet.get('gateway', '-')])
subnet_table.add_row(['type', subnet['subnetType']])
subnet_table.add_row(['usable ips',
subnet['usableIpAddressCount']])
subnets.append(subnet_table)
table.add_row(['subnets', subnets])
server_columns = ['hostname', 'domain', 'public_ip', 'private_ip']
if not no_vs:
if vlan.get('virtualGuests'):
vs_table = formatting.KeyValueTable(server_columns)
for vsi in vlan['virtualGuests']:
vs_table.add_row([vsi.get('hostname'),
vsi.get('domain'),
vsi.get('primaryIpAddress'),
vsi.get('primaryBackendIpAddress')])
table.add_row(['vs', vs_table])
else:
table.add_row(['vs', 'none'])
if not no_hardware:
if vlan.get('hardware'):
hw_table = formatting.Table(server_columns)
for hardware in vlan['hardware']:
hw_table.add_row([hardware.get('hostname'),
hardware.get('domain'),
hardware.get('primaryIpAddress'),
hardware.get('primaryBackendIpAddress')])
table.add_row(['hardware', hw_table])
else:
table.add_row(['hardware', 'none'])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"no_vs",
",",
"no_hardware",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"vlan_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_vlan_ids",
",",
"identifier",
",",
"'VLAN'",
")",
"vlan",
"=",
"mgr",
".",
"get_vlan",
"(",
"vlan_id",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"vlan",
"[",
"'id'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'number'",
",",
"vlan",
"[",
"'vlanNumber'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'datacenter'",
",",
"vlan",
"[",
"'primaryRouter'",
"]",
"[",
"'datacenter'",
"]",
"[",
"'longName'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'primary_router'",
",",
"vlan",
"[",
"'primaryRouter'",
"]",
"[",
"'fullyQualifiedDomainName'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'firewall'",
",",
"'Yes'",
"if",
"vlan",
"[",
"'firewallInterfaces'",
"]",
"else",
"'No'",
"]",
")",
"subnets",
"=",
"[",
"]",
"for",
"subnet",
"in",
"vlan",
".",
"get",
"(",
"'subnets'",
",",
"[",
"]",
")",
":",
"subnet_table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"subnet_table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"subnet_table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"subnet_table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"subnet",
"[",
"'id'",
"]",
"]",
")",
"subnet_table",
".",
"add_row",
"(",
"[",
"'identifier'",
",",
"subnet",
"[",
"'networkIdentifier'",
"]",
"]",
")",
"subnet_table",
".",
"add_row",
"(",
"[",
"'netmask'",
",",
"subnet",
"[",
"'netmask'",
"]",
"]",
")",
"subnet_table",
".",
"add_row",
"(",
"[",
"'gateway'",
",",
"subnet",
".",
"get",
"(",
"'gateway'",
",",
"'-'",
")",
"]",
")",
"subnet_table",
".",
"add_row",
"(",
"[",
"'type'",
",",
"subnet",
"[",
"'subnetType'",
"]",
"]",
")",
"subnet_table",
".",
"add_row",
"(",
"[",
"'usable ips'",
",",
"subnet",
"[",
"'usableIpAddressCount'",
"]",
"]",
")",
"subnets",
".",
"append",
"(",
"subnet_table",
")",
"table",
".",
"add_row",
"(",
"[",
"'subnets'",
",",
"subnets",
"]",
")",
"server_columns",
"=",
"[",
"'hostname'",
",",
"'domain'",
",",
"'public_ip'",
",",
"'private_ip'",
"]",
"if",
"not",
"no_vs",
":",
"if",
"vlan",
".",
"get",
"(",
"'virtualGuests'",
")",
":",
"vs_table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"server_columns",
")",
"for",
"vsi",
"in",
"vlan",
"[",
"'virtualGuests'",
"]",
":",
"vs_table",
".",
"add_row",
"(",
"[",
"vsi",
".",
"get",
"(",
"'hostname'",
")",
",",
"vsi",
".",
"get",
"(",
"'domain'",
")",
",",
"vsi",
".",
"get",
"(",
"'primaryIpAddress'",
")",
",",
"vsi",
".",
"get",
"(",
"'primaryBackendIpAddress'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'vs'",
",",
"vs_table",
"]",
")",
"else",
":",
"table",
".",
"add_row",
"(",
"[",
"'vs'",
",",
"'none'",
"]",
")",
"if",
"not",
"no_hardware",
":",
"if",
"vlan",
".",
"get",
"(",
"'hardware'",
")",
":",
"hw_table",
"=",
"formatting",
".",
"Table",
"(",
"server_columns",
")",
"for",
"hardware",
"in",
"vlan",
"[",
"'hardware'",
"]",
":",
"hw_table",
".",
"add_row",
"(",
"[",
"hardware",
".",
"get",
"(",
"'hostname'",
")",
",",
"hardware",
".",
"get",
"(",
"'domain'",
")",
",",
"hardware",
".",
"get",
"(",
"'primaryIpAddress'",
")",
",",
"hardware",
".",
"get",
"(",
"'primaryBackendIpAddress'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'hardware'",
",",
"hw_table",
"]",
")",
"else",
":",
"table",
".",
"add_row",
"(",
"[",
"'hardware'",
",",
"'none'",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | Get details about a VLAN. | [
"Get",
"details",
"about",
"a",
"VLAN",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vlan/detail.py#L21-L83 | train | 234,215 |
softlayer/softlayer-python | SoftLayer/CLI/block/lun.py | cli | def cli(env, volume_id, lun_id):
"""Set the LUN ID on an existing block storage volume.
The LUN ID only takes effect during the Host Authorization process. It is
recommended (but not necessary) to de-authorize all hosts before using this
method. See `block access-revoke`.
VOLUME_ID - the volume ID on which to set the LUN ID.
LUN_ID - recommended range is an integer between 0 and 255. Advanced users
can use an integer between 0 and 4095.
"""
block_storage_manager = SoftLayer.BlockStorageManager(env.client)
res = block_storage_manager.create_or_update_lun_id(volume_id, lun_id)
if 'value' in res and lun_id == res['value']:
click.echo(
'Block volume with id %s is reporting LUN ID %s' % (res['volumeId'], res['value']))
else:
click.echo(
'Failed to confirm the new LUN ID on volume %s' % (volume_id)) | python | def cli(env, volume_id, lun_id):
"""Set the LUN ID on an existing block storage volume.
The LUN ID only takes effect during the Host Authorization process. It is
recommended (but not necessary) to de-authorize all hosts before using this
method. See `block access-revoke`.
VOLUME_ID - the volume ID on which to set the LUN ID.
LUN_ID - recommended range is an integer between 0 and 255. Advanced users
can use an integer between 0 and 4095.
"""
block_storage_manager = SoftLayer.BlockStorageManager(env.client)
res = block_storage_manager.create_or_update_lun_id(volume_id, lun_id)
if 'value' in res and lun_id == res['value']:
click.echo(
'Block volume with id %s is reporting LUN ID %s' % (res['volumeId'], res['value']))
else:
click.echo(
'Failed to confirm the new LUN ID on volume %s' % (volume_id)) | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"lun_id",
")",
":",
"block_storage_manager",
"=",
"SoftLayer",
".",
"BlockStorageManager",
"(",
"env",
".",
"client",
")",
"res",
"=",
"block_storage_manager",
".",
"create_or_update_lun_id",
"(",
"volume_id",
",",
"lun_id",
")",
"if",
"'value'",
"in",
"res",
"and",
"lun_id",
"==",
"res",
"[",
"'value'",
"]",
":",
"click",
".",
"echo",
"(",
"'Block volume with id %s is reporting LUN ID %s'",
"%",
"(",
"res",
"[",
"'volumeId'",
"]",
",",
"res",
"[",
"'value'",
"]",
")",
")",
"else",
":",
"click",
".",
"echo",
"(",
"'Failed to confirm the new LUN ID on volume %s'",
"%",
"(",
"volume_id",
")",
")"
] | Set the LUN ID on an existing block storage volume.
The LUN ID only takes effect during the Host Authorization process. It is
recommended (but not necessary) to de-authorize all hosts before using this
method. See `block access-revoke`.
VOLUME_ID - the volume ID on which to set the LUN ID.
LUN_ID - recommended range is an integer between 0 and 255. Advanced users
can use an integer between 0 and 4095. | [
"Set",
"the",
"LUN",
"ID",
"on",
"an",
"existing",
"block",
"storage",
"volume",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/lun.py#L14-L36 | train | 234,216 |
softlayer/softlayer-python | SoftLayer/CLI/loadbal/detail.py | cli | def cli(env, identifier):
"""Get Load balancer details."""
mgr = SoftLayer.LoadBalancerManager(env.client)
_, loadbal_id = loadbal.parse_id(identifier)
load_balancer = mgr.get_local_lb(loadbal_id)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'l'
table.align['value'] = 'l'
table.add_row(['ID', 'local:%s' % load_balancer['id']])
table.add_row(['IP Address', load_balancer['ipAddress']['ipAddress']])
name = load_balancer['loadBalancerHardware'][0]['datacenter']['name']
table.add_row(['Datacenter', name])
table.add_row(['Connections limit', load_balancer['connectionLimit']])
table.add_row(['Dedicated', load_balancer['dedicatedFlag']])
table.add_row(['HA', load_balancer['highAvailabilityFlag']])
table.add_row(['SSL Enabled', load_balancer['sslEnabledFlag']])
table.add_row(['SSL Active', load_balancer['sslActiveFlag']])
index0 = 1
for virtual_server in load_balancer['virtualServers']:
for group in virtual_server['serviceGroups']:
service_group_table = formatting.KeyValueTable(['name', 'value'])
table.add_row(['Service Group %s' % index0, service_group_table])
index0 += 1
service_group_table.add_row(['Guest ID',
virtual_server['id']])
service_group_table.add_row(['Port', virtual_server['port']])
service_group_table.add_row(['Allocation',
'%s %%' %
virtual_server['allocation']])
service_group_table.add_row(['Routing Type',
'%s:%s' %
(group['routingTypeId'],
group['routingType']['name'])])
service_group_table.add_row(['Routing Method',
'%s:%s' %
(group['routingMethodId'],
group['routingMethod']['name'])])
index1 = 1
for service in group['services']:
service_table = formatting.KeyValueTable(['name', 'value'])
service_group_table.add_row(['Service %s' % index1,
service_table])
index1 += 1
health_check = service['healthChecks'][0]
service_table.add_row(['Service ID', service['id']])
service_table.add_row(['IP Address',
service['ipAddress']['ipAddress']])
service_table.add_row(['Port', service['port']])
service_table.add_row(['Health Check',
'%s:%s' %
(health_check['healthCheckTypeId'],
health_check['type']['name'])])
service_table.add_row(
['Weight', service['groupReferences'][0]['weight']])
service_table.add_row(['Enabled', service['enabled']])
service_table.add_row(['Status', service['status']])
env.fout(table) | python | def cli(env, identifier):
"""Get Load balancer details."""
mgr = SoftLayer.LoadBalancerManager(env.client)
_, loadbal_id = loadbal.parse_id(identifier)
load_balancer = mgr.get_local_lb(loadbal_id)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'l'
table.align['value'] = 'l'
table.add_row(['ID', 'local:%s' % load_balancer['id']])
table.add_row(['IP Address', load_balancer['ipAddress']['ipAddress']])
name = load_balancer['loadBalancerHardware'][0]['datacenter']['name']
table.add_row(['Datacenter', name])
table.add_row(['Connections limit', load_balancer['connectionLimit']])
table.add_row(['Dedicated', load_balancer['dedicatedFlag']])
table.add_row(['HA', load_balancer['highAvailabilityFlag']])
table.add_row(['SSL Enabled', load_balancer['sslEnabledFlag']])
table.add_row(['SSL Active', load_balancer['sslActiveFlag']])
index0 = 1
for virtual_server in load_balancer['virtualServers']:
for group in virtual_server['serviceGroups']:
service_group_table = formatting.KeyValueTable(['name', 'value'])
table.add_row(['Service Group %s' % index0, service_group_table])
index0 += 1
service_group_table.add_row(['Guest ID',
virtual_server['id']])
service_group_table.add_row(['Port', virtual_server['port']])
service_group_table.add_row(['Allocation',
'%s %%' %
virtual_server['allocation']])
service_group_table.add_row(['Routing Type',
'%s:%s' %
(group['routingTypeId'],
group['routingType']['name'])])
service_group_table.add_row(['Routing Method',
'%s:%s' %
(group['routingMethodId'],
group['routingMethod']['name'])])
index1 = 1
for service in group['services']:
service_table = formatting.KeyValueTable(['name', 'value'])
service_group_table.add_row(['Service %s' % index1,
service_table])
index1 += 1
health_check = service['healthChecks'][0]
service_table.add_row(['Service ID', service['id']])
service_table.add_row(['IP Address',
service['ipAddress']['ipAddress']])
service_table.add_row(['Port', service['port']])
service_table.add_row(['Health Check',
'%s:%s' %
(health_check['healthCheckTypeId'],
health_check['type']['name'])])
service_table.add_row(
['Weight', service['groupReferences'][0]['weight']])
service_table.add_row(['Enabled', service['enabled']])
service_table.add_row(['Status', service['status']])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"LoadBalancerManager",
"(",
"env",
".",
"client",
")",
"_",
",",
"loadbal_id",
"=",
"loadbal",
".",
"parse_id",
"(",
"identifier",
")",
"load_balancer",
"=",
"mgr",
".",
"get_local_lb",
"(",
"loadbal_id",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'l'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'ID'",
",",
"'local:%s'",
"%",
"load_balancer",
"[",
"'id'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'IP Address'",
",",
"load_balancer",
"[",
"'ipAddress'",
"]",
"[",
"'ipAddress'",
"]",
"]",
")",
"name",
"=",
"load_balancer",
"[",
"'loadBalancerHardware'",
"]",
"[",
"0",
"]",
"[",
"'datacenter'",
"]",
"[",
"'name'",
"]",
"table",
".",
"add_row",
"(",
"[",
"'Datacenter'",
",",
"name",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Connections limit'",
",",
"load_balancer",
"[",
"'connectionLimit'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Dedicated'",
",",
"load_balancer",
"[",
"'dedicatedFlag'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'HA'",
",",
"load_balancer",
"[",
"'highAvailabilityFlag'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'SSL Enabled'",
",",
"load_balancer",
"[",
"'sslEnabledFlag'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'SSL Active'",
",",
"load_balancer",
"[",
"'sslActiveFlag'",
"]",
"]",
")",
"index0",
"=",
"1",
"for",
"virtual_server",
"in",
"load_balancer",
"[",
"'virtualServers'",
"]",
":",
"for",
"group",
"in",
"virtual_server",
"[",
"'serviceGroups'",
"]",
":",
"service_group_table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Service Group %s'",
"%",
"index0",
",",
"service_group_table",
"]",
")",
"index0",
"+=",
"1",
"service_group_table",
".",
"add_row",
"(",
"[",
"'Guest ID'",
",",
"virtual_server",
"[",
"'id'",
"]",
"]",
")",
"service_group_table",
".",
"add_row",
"(",
"[",
"'Port'",
",",
"virtual_server",
"[",
"'port'",
"]",
"]",
")",
"service_group_table",
".",
"add_row",
"(",
"[",
"'Allocation'",
",",
"'%s %%'",
"%",
"virtual_server",
"[",
"'allocation'",
"]",
"]",
")",
"service_group_table",
".",
"add_row",
"(",
"[",
"'Routing Type'",
",",
"'%s:%s'",
"%",
"(",
"group",
"[",
"'routingTypeId'",
"]",
",",
"group",
"[",
"'routingType'",
"]",
"[",
"'name'",
"]",
")",
"]",
")",
"service_group_table",
".",
"add_row",
"(",
"[",
"'Routing Method'",
",",
"'%s:%s'",
"%",
"(",
"group",
"[",
"'routingMethodId'",
"]",
",",
"group",
"[",
"'routingMethod'",
"]",
"[",
"'name'",
"]",
")",
"]",
")",
"index1",
"=",
"1",
"for",
"service",
"in",
"group",
"[",
"'services'",
"]",
":",
"service_table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"service_group_table",
".",
"add_row",
"(",
"[",
"'Service %s'",
"%",
"index1",
",",
"service_table",
"]",
")",
"index1",
"+=",
"1",
"health_check",
"=",
"service",
"[",
"'healthChecks'",
"]",
"[",
"0",
"]",
"service_table",
".",
"add_row",
"(",
"[",
"'Service ID'",
",",
"service",
"[",
"'id'",
"]",
"]",
")",
"service_table",
".",
"add_row",
"(",
"[",
"'IP Address'",
",",
"service",
"[",
"'ipAddress'",
"]",
"[",
"'ipAddress'",
"]",
"]",
")",
"service_table",
".",
"add_row",
"(",
"[",
"'Port'",
",",
"service",
"[",
"'port'",
"]",
"]",
")",
"service_table",
".",
"add_row",
"(",
"[",
"'Health Check'",
",",
"'%s:%s'",
"%",
"(",
"health_check",
"[",
"'healthCheckTypeId'",
"]",
",",
"health_check",
"[",
"'type'",
"]",
"[",
"'name'",
"]",
")",
"]",
")",
"service_table",
".",
"add_row",
"(",
"[",
"'Weight'",
",",
"service",
"[",
"'groupReferences'",
"]",
"[",
"0",
"]",
"[",
"'weight'",
"]",
"]",
")",
"service_table",
".",
"add_row",
"(",
"[",
"'Enabled'",
",",
"service",
"[",
"'enabled'",
"]",
"]",
")",
"service_table",
".",
"add_row",
"(",
"[",
"'Status'",
",",
"service",
"[",
"'status'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | Get Load balancer details. | [
"Get",
"Load",
"balancer",
"details",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/detail.py#L15-L81 | train | 234,217 |
softlayer/softlayer-python | SoftLayer/CLI/core.py | cli | def cli(env,
format='table',
config=None,
verbose=0,
proxy=None,
really=False,
demo=False,
**kwargs):
"""Main click CLI entry-point."""
# Populate environement with client and set it as the context object
env.skip_confirmations = really
env.config_file = config
env.format = format
env.ensure_client(config_file=config, is_demo=demo, proxy=proxy)
env.vars['_start'] = time.time()
logger = logging.getLogger()
if demo is False:
logger.addHandler(logging.StreamHandler())
else:
# This section is for running CLI tests.
logging.getLogger("urllib3").setLevel(logging.WARNING)
logger.addHandler(logging.NullHandler())
logger.setLevel(DEBUG_LOGGING_MAP.get(verbose, logging.DEBUG))
env.vars['_timings'] = SoftLayer.DebugTransport(env.client.transport)
env.client.transport = env.vars['_timings'] | python | def cli(env,
format='table',
config=None,
verbose=0,
proxy=None,
really=False,
demo=False,
**kwargs):
"""Main click CLI entry-point."""
# Populate environement with client and set it as the context object
env.skip_confirmations = really
env.config_file = config
env.format = format
env.ensure_client(config_file=config, is_demo=demo, proxy=proxy)
env.vars['_start'] = time.time()
logger = logging.getLogger()
if demo is False:
logger.addHandler(logging.StreamHandler())
else:
# This section is for running CLI tests.
logging.getLogger("urllib3").setLevel(logging.WARNING)
logger.addHandler(logging.NullHandler())
logger.setLevel(DEBUG_LOGGING_MAP.get(verbose, logging.DEBUG))
env.vars['_timings'] = SoftLayer.DebugTransport(env.client.transport)
env.client.transport = env.vars['_timings'] | [
"def",
"cli",
"(",
"env",
",",
"format",
"=",
"'table'",
",",
"config",
"=",
"None",
",",
"verbose",
"=",
"0",
",",
"proxy",
"=",
"None",
",",
"really",
"=",
"False",
",",
"demo",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# Populate environement with client and set it as the context object",
"env",
".",
"skip_confirmations",
"=",
"really",
"env",
".",
"config_file",
"=",
"config",
"env",
".",
"format",
"=",
"format",
"env",
".",
"ensure_client",
"(",
"config_file",
"=",
"config",
",",
"is_demo",
"=",
"demo",
",",
"proxy",
"=",
"proxy",
")",
"env",
".",
"vars",
"[",
"'_start'",
"]",
"=",
"time",
".",
"time",
"(",
")",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"if",
"demo",
"is",
"False",
":",
"logger",
".",
"addHandler",
"(",
"logging",
".",
"StreamHandler",
"(",
")",
")",
"else",
":",
"# This section is for running CLI tests.",
"logging",
".",
"getLogger",
"(",
"\"urllib3\"",
")",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"logger",
".",
"addHandler",
"(",
"logging",
".",
"NullHandler",
"(",
")",
")",
"logger",
".",
"setLevel",
"(",
"DEBUG_LOGGING_MAP",
".",
"get",
"(",
"verbose",
",",
"logging",
".",
"DEBUG",
")",
")",
"env",
".",
"vars",
"[",
"'_timings'",
"]",
"=",
"SoftLayer",
".",
"DebugTransport",
"(",
"env",
".",
"client",
".",
"transport",
")",
"env",
".",
"client",
".",
"transport",
"=",
"env",
".",
"vars",
"[",
"'_timings'",
"]"
] | Main click CLI entry-point. | [
"Main",
"click",
"CLI",
"entry",
"-",
"point",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/core.py#L108-L135 | train | 234,218 |
softlayer/softlayer-python | SoftLayer/CLI/core.py | output_diagnostics | def output_diagnostics(env, result, verbose=0, **kwargs):
"""Output diagnostic information."""
if verbose > 0:
diagnostic_table = formatting.Table(['name', 'value'])
diagnostic_table.add_row(['execution_time', '%fs' % (time.time() - START_TIME)])
api_call_value = []
for call in env.client.transport.get_last_calls():
api_call_value.append("%s::%s (%fs)" % (call.service, call.method, call.end_time - call.start_time))
diagnostic_table.add_row(['api_calls', api_call_value])
diagnostic_table.add_row(['version', consts.USER_AGENT])
diagnostic_table.add_row(['python_version', sys.version])
diagnostic_table.add_row(['library_location', os.path.dirname(SoftLayer.__file__)])
env.err(env.fmt(diagnostic_table))
if verbose > 1:
for call in env.client.transport.get_last_calls():
call_table = formatting.Table(['', '{}::{}'.format(call.service, call.method)])
nice_mask = ''
if call.mask is not None:
nice_mask = call.mask
call_table.add_row(['id', call.identifier])
call_table.add_row(['mask', nice_mask])
call_table.add_row(['filter', call.filter])
call_table.add_row(['limit', call.limit])
call_table.add_row(['offset', call.offset])
env.err(env.fmt(call_table))
if verbose > 2:
for call in env.client.transport.get_last_calls():
env.err(env.client.transport.print_reproduceable(call)) | python | def output_diagnostics(env, result, verbose=0, **kwargs):
"""Output diagnostic information."""
if verbose > 0:
diagnostic_table = formatting.Table(['name', 'value'])
diagnostic_table.add_row(['execution_time', '%fs' % (time.time() - START_TIME)])
api_call_value = []
for call in env.client.transport.get_last_calls():
api_call_value.append("%s::%s (%fs)" % (call.service, call.method, call.end_time - call.start_time))
diagnostic_table.add_row(['api_calls', api_call_value])
diagnostic_table.add_row(['version', consts.USER_AGENT])
diagnostic_table.add_row(['python_version', sys.version])
diagnostic_table.add_row(['library_location', os.path.dirname(SoftLayer.__file__)])
env.err(env.fmt(diagnostic_table))
if verbose > 1:
for call in env.client.transport.get_last_calls():
call_table = formatting.Table(['', '{}::{}'.format(call.service, call.method)])
nice_mask = ''
if call.mask is not None:
nice_mask = call.mask
call_table.add_row(['id', call.identifier])
call_table.add_row(['mask', nice_mask])
call_table.add_row(['filter', call.filter])
call_table.add_row(['limit', call.limit])
call_table.add_row(['offset', call.offset])
env.err(env.fmt(call_table))
if verbose > 2:
for call in env.client.transport.get_last_calls():
env.err(env.client.transport.print_reproduceable(call)) | [
"def",
"output_diagnostics",
"(",
"env",
",",
"result",
",",
"verbose",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"verbose",
">",
"0",
":",
"diagnostic_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"diagnostic_table",
".",
"add_row",
"(",
"[",
"'execution_time'",
",",
"'%fs'",
"%",
"(",
"time",
".",
"time",
"(",
")",
"-",
"START_TIME",
")",
"]",
")",
"api_call_value",
"=",
"[",
"]",
"for",
"call",
"in",
"env",
".",
"client",
".",
"transport",
".",
"get_last_calls",
"(",
")",
":",
"api_call_value",
".",
"append",
"(",
"\"%s::%s (%fs)\"",
"%",
"(",
"call",
".",
"service",
",",
"call",
".",
"method",
",",
"call",
".",
"end_time",
"-",
"call",
".",
"start_time",
")",
")",
"diagnostic_table",
".",
"add_row",
"(",
"[",
"'api_calls'",
",",
"api_call_value",
"]",
")",
"diagnostic_table",
".",
"add_row",
"(",
"[",
"'version'",
",",
"consts",
".",
"USER_AGENT",
"]",
")",
"diagnostic_table",
".",
"add_row",
"(",
"[",
"'python_version'",
",",
"sys",
".",
"version",
"]",
")",
"diagnostic_table",
".",
"add_row",
"(",
"[",
"'library_location'",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"SoftLayer",
".",
"__file__",
")",
"]",
")",
"env",
".",
"err",
"(",
"env",
".",
"fmt",
"(",
"diagnostic_table",
")",
")",
"if",
"verbose",
">",
"1",
":",
"for",
"call",
"in",
"env",
".",
"client",
".",
"transport",
".",
"get_last_calls",
"(",
")",
":",
"call_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"''",
",",
"'{}::{}'",
".",
"format",
"(",
"call",
".",
"service",
",",
"call",
".",
"method",
")",
"]",
")",
"nice_mask",
"=",
"''",
"if",
"call",
".",
"mask",
"is",
"not",
"None",
":",
"nice_mask",
"=",
"call",
".",
"mask",
"call_table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"call",
".",
"identifier",
"]",
")",
"call_table",
".",
"add_row",
"(",
"[",
"'mask'",
",",
"nice_mask",
"]",
")",
"call_table",
".",
"add_row",
"(",
"[",
"'filter'",
",",
"call",
".",
"filter",
"]",
")",
"call_table",
".",
"add_row",
"(",
"[",
"'limit'",
",",
"call",
".",
"limit",
"]",
")",
"call_table",
".",
"add_row",
"(",
"[",
"'offset'",
",",
"call",
".",
"offset",
"]",
")",
"env",
".",
"err",
"(",
"env",
".",
"fmt",
"(",
"call_table",
")",
")",
"if",
"verbose",
">",
"2",
":",
"for",
"call",
"in",
"env",
".",
"client",
".",
"transport",
".",
"get_last_calls",
"(",
")",
":",
"env",
".",
"err",
"(",
"env",
".",
"client",
".",
"transport",
".",
"print_reproduceable",
"(",
"call",
")",
")"
] | Output diagnostic information. | [
"Output",
"diagnostic",
"information",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/core.py#L140-L174 | train | 234,219 |
softlayer/softlayer-python | SoftLayer/CLI/core.py | main | def main(reraise_exceptions=False, **kwargs):
"""Main program. Catches several common errors and displays them nicely."""
exit_status = 0
try:
cli.main(**kwargs)
except SoftLayer.SoftLayerAPIError as ex:
if 'invalid api token' in ex.faultString.lower():
print("Authentication Failed: To update your credentials, use 'slcli config setup'")
exit_status = 1
else:
print(str(ex))
exit_status = 1
except SoftLayer.SoftLayerError as ex:
print(str(ex))
exit_status = 1
except exceptions.CLIAbort as ex:
print(str(ex.message))
exit_status = ex.code
except Exception:
if reraise_exceptions:
raise
import traceback
print("An unexpected error has occured:")
print(str(traceback.format_exc()))
print("Feel free to report this error as it is likely a bug:")
print(" https://github.com/softlayer/softlayer-python/issues")
print("The following snippet should be able to reproduce the error")
exit_status = 1
sys.exit(exit_status) | python | def main(reraise_exceptions=False, **kwargs):
"""Main program. Catches several common errors and displays them nicely."""
exit_status = 0
try:
cli.main(**kwargs)
except SoftLayer.SoftLayerAPIError as ex:
if 'invalid api token' in ex.faultString.lower():
print("Authentication Failed: To update your credentials, use 'slcli config setup'")
exit_status = 1
else:
print(str(ex))
exit_status = 1
except SoftLayer.SoftLayerError as ex:
print(str(ex))
exit_status = 1
except exceptions.CLIAbort as ex:
print(str(ex.message))
exit_status = ex.code
except Exception:
if reraise_exceptions:
raise
import traceback
print("An unexpected error has occured:")
print(str(traceback.format_exc()))
print("Feel free to report this error as it is likely a bug:")
print(" https://github.com/softlayer/softlayer-python/issues")
print("The following snippet should be able to reproduce the error")
exit_status = 1
sys.exit(exit_status) | [
"def",
"main",
"(",
"reraise_exceptions",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"exit_status",
"=",
"0",
"try",
":",
"cli",
".",
"main",
"(",
"*",
"*",
"kwargs",
")",
"except",
"SoftLayer",
".",
"SoftLayerAPIError",
"as",
"ex",
":",
"if",
"'invalid api token'",
"in",
"ex",
".",
"faultString",
".",
"lower",
"(",
")",
":",
"print",
"(",
"\"Authentication Failed: To update your credentials, use 'slcli config setup'\"",
")",
"exit_status",
"=",
"1",
"else",
":",
"print",
"(",
"str",
"(",
"ex",
")",
")",
"exit_status",
"=",
"1",
"except",
"SoftLayer",
".",
"SoftLayerError",
"as",
"ex",
":",
"print",
"(",
"str",
"(",
"ex",
")",
")",
"exit_status",
"=",
"1",
"except",
"exceptions",
".",
"CLIAbort",
"as",
"ex",
":",
"print",
"(",
"str",
"(",
"ex",
".",
"message",
")",
")",
"exit_status",
"=",
"ex",
".",
"code",
"except",
"Exception",
":",
"if",
"reraise_exceptions",
":",
"raise",
"import",
"traceback",
"print",
"(",
"\"An unexpected error has occured:\"",
")",
"print",
"(",
"str",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
")",
"print",
"(",
"\"Feel free to report this error as it is likely a bug:\"",
")",
"print",
"(",
"\" https://github.com/softlayer/softlayer-python/issues\"",
")",
"print",
"(",
"\"The following snippet should be able to reproduce the error\"",
")",
"exit_status",
"=",
"1",
"sys",
".",
"exit",
"(",
"exit_status",
")"
] | Main program. Catches several common errors and displays them nicely. | [
"Main",
"program",
".",
"Catches",
"several",
"common",
"errors",
"and",
"displays",
"them",
"nicely",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/core.py#L177-L208 | train | 234,220 |
softlayer/softlayer-python | SoftLayer/CLI/block/access/revoke.py | cli | def cli(env, volume_id, hardware_id, virtual_id, ip_address_id, ip_address):
"""Revokes authorization for hosts accessing a given volume"""
block_manager = SoftLayer.BlockStorageManager(env.client)
ip_address_id_list = list(ip_address_id)
# Convert actual IP Addresses to their SoftLayer ids
if ip_address is not None:
network_manager = SoftLayer.NetworkManager(env.client)
for ip_address_value in ip_address:
ip_address_object = network_manager.ip_lookup(ip_address_value)
ip_address_id_list.append(ip_address_object['id'])
block_manager.deauthorize_host_to_volume(volume_id,
hardware_id,
virtual_id,
ip_address_id_list)
# If no exception was raised, the command succeeded
click.echo('Access to %s was revoked for the specified hosts' % volume_id) | python | def cli(env, volume_id, hardware_id, virtual_id, ip_address_id, ip_address):
"""Revokes authorization for hosts accessing a given volume"""
block_manager = SoftLayer.BlockStorageManager(env.client)
ip_address_id_list = list(ip_address_id)
# Convert actual IP Addresses to their SoftLayer ids
if ip_address is not None:
network_manager = SoftLayer.NetworkManager(env.client)
for ip_address_value in ip_address:
ip_address_object = network_manager.ip_lookup(ip_address_value)
ip_address_id_list.append(ip_address_object['id'])
block_manager.deauthorize_host_to_volume(volume_id,
hardware_id,
virtual_id,
ip_address_id_list)
# If no exception was raised, the command succeeded
click.echo('Access to %s was revoked for the specified hosts' % volume_id) | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"hardware_id",
",",
"virtual_id",
",",
"ip_address_id",
",",
"ip_address",
")",
":",
"block_manager",
"=",
"SoftLayer",
".",
"BlockStorageManager",
"(",
"env",
".",
"client",
")",
"ip_address_id_list",
"=",
"list",
"(",
"ip_address_id",
")",
"# Convert actual IP Addresses to their SoftLayer ids",
"if",
"ip_address",
"is",
"not",
"None",
":",
"network_manager",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"for",
"ip_address_value",
"in",
"ip_address",
":",
"ip_address_object",
"=",
"network_manager",
".",
"ip_lookup",
"(",
"ip_address_value",
")",
"ip_address_id_list",
".",
"append",
"(",
"ip_address_object",
"[",
"'id'",
"]",
")",
"block_manager",
".",
"deauthorize_host_to_volume",
"(",
"volume_id",
",",
"hardware_id",
",",
"virtual_id",
",",
"ip_address_id_list",
")",
"# If no exception was raised, the command succeeded",
"click",
".",
"echo",
"(",
"'Access to %s was revoked for the specified hosts'",
"%",
"volume_id",
")"
] | Revokes authorization for hosts accessing a given volume | [
"Revokes",
"authorization",
"for",
"hosts",
"accessing",
"a",
"given",
"volume"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/access/revoke.py#L23-L41 | train | 234,221 |
softlayer/softlayer-python | SoftLayer/CLI/loadbal/group_add.py | cli | def cli(env, identifier, allocation, port, routing_type, routing_method):
"""Adds a new load_balancer service."""
mgr = SoftLayer.LoadBalancerManager(env.client)
_, loadbal_id = loadbal.parse_id(identifier)
mgr.add_service_group(loadbal_id,
allocation=allocation,
port=port,
routing_type=routing_type,
routing_method=routing_method)
env.fout('Load balancer service group is being added!') | python | def cli(env, identifier, allocation, port, routing_type, routing_method):
"""Adds a new load_balancer service."""
mgr = SoftLayer.LoadBalancerManager(env.client)
_, loadbal_id = loadbal.parse_id(identifier)
mgr.add_service_group(loadbal_id,
allocation=allocation,
port=port,
routing_type=routing_type,
routing_method=routing_method)
env.fout('Load balancer service group is being added!') | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"allocation",
",",
"port",
",",
"routing_type",
",",
"routing_method",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"LoadBalancerManager",
"(",
"env",
".",
"client",
")",
"_",
",",
"loadbal_id",
"=",
"loadbal",
".",
"parse_id",
"(",
"identifier",
")",
"mgr",
".",
"add_service_group",
"(",
"loadbal_id",
",",
"allocation",
"=",
"allocation",
",",
"port",
"=",
"port",
",",
"routing_type",
"=",
"routing_type",
",",
"routing_method",
"=",
"routing_method",
")",
"env",
".",
"fout",
"(",
"'Load balancer service group 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/group_add.py#L28-L41 | train | 234,222 |
softlayer/softlayer-python | SoftLayer/CLI/dedicatedhost/cancel_guests.py | cli | def cli(env, identifier):
"""Cancel all virtual guests of the dedicated host immediately.
Use the 'slcli vs cancel' command to cancel an specific guest
"""
dh_mgr = SoftLayer.DedicatedHostManager(env.client)
host_id = helpers.resolve_id(dh_mgr.resolve_ids, identifier, 'dedicated host')
if not (env.skip_confirmations or formatting.no_going_back(host_id)):
raise exceptions.CLIAbort('Aborted')
table = formatting.Table(['id', 'server name', 'status'])
result = dh_mgr.cancel_guests(host_id)
if result:
for status in result:
table.add_row([
status['id'],
status['fqdn'],
status['status']
])
env.fout(table)
else:
click.secho('There is not any guest into the dedicated host %s' % host_id, fg='red') | python | def cli(env, identifier):
"""Cancel all virtual guests of the dedicated host immediately.
Use the 'slcli vs cancel' command to cancel an specific guest
"""
dh_mgr = SoftLayer.DedicatedHostManager(env.client)
host_id = helpers.resolve_id(dh_mgr.resolve_ids, identifier, 'dedicated host')
if not (env.skip_confirmations or formatting.no_going_back(host_id)):
raise exceptions.CLIAbort('Aborted')
table = formatting.Table(['id', 'server name', 'status'])
result = dh_mgr.cancel_guests(host_id)
if result:
for status in result:
table.add_row([
status['id'],
status['fqdn'],
status['status']
])
env.fout(table)
else:
click.secho('There is not any guest into the dedicated host %s' % host_id, fg='red') | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"dh_mgr",
"=",
"SoftLayer",
".",
"DedicatedHostManager",
"(",
"env",
".",
"client",
")",
"host_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"dh_mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'dedicated host'",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"no_going_back",
"(",
"host_id",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted'",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'server name'",
",",
"'status'",
"]",
")",
"result",
"=",
"dh_mgr",
".",
"cancel_guests",
"(",
"host_id",
")",
"if",
"result",
":",
"for",
"status",
"in",
"result",
":",
"table",
".",
"add_row",
"(",
"[",
"status",
"[",
"'id'",
"]",
",",
"status",
"[",
"'fqdn'",
"]",
",",
"status",
"[",
"'status'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")",
"else",
":",
"click",
".",
"secho",
"(",
"'There is not any guest into the dedicated host %s'",
"%",
"host_id",
",",
"fg",
"=",
"'red'",
")"
] | Cancel all virtual guests of the dedicated host immediately.
Use the 'slcli vs cancel' command to cancel an specific guest | [
"Cancel",
"all",
"virtual",
"guests",
"of",
"the",
"dedicated",
"host",
"immediately",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dedicatedhost/cancel_guests.py#L16-L43 | train | 234,223 |
softlayer/softlayer-python | SoftLayer/CLI/file/list.py | cli | def cli(env, sortby, columns, datacenter, username, storage_type):
"""List file storage."""
file_manager = SoftLayer.FileStorageManager(env.client)
file_volumes = file_manager.list_file_volumes(datacenter=datacenter,
username=username,
storage_type=storage_type,
mask=columns.mask())
table = formatting.Table(columns.columns)
table.sortby = sortby
for file_volume in file_volumes:
table.add_row([value or formatting.blank()
for value in columns.row(file_volume)])
env.fout(table) | python | def cli(env, sortby, columns, datacenter, username, storage_type):
"""List file storage."""
file_manager = SoftLayer.FileStorageManager(env.client)
file_volumes = file_manager.list_file_volumes(datacenter=datacenter,
username=username,
storage_type=storage_type,
mask=columns.mask())
table = formatting.Table(columns.columns)
table.sortby = sortby
for file_volume in file_volumes:
table.add_row([value or formatting.blank()
for value in columns.row(file_volume)])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"sortby",
",",
"columns",
",",
"datacenter",
",",
"username",
",",
"storage_type",
")",
":",
"file_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"file_volumes",
"=",
"file_manager",
".",
"list_file_volumes",
"(",
"datacenter",
"=",
"datacenter",
",",
"username",
"=",
"username",
",",
"storage_type",
"=",
"storage_type",
",",
"mask",
"=",
"columns",
".",
"mask",
"(",
")",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"columns",
".",
"columns",
")",
"table",
".",
"sortby",
"=",
"sortby",
"for",
"file_volume",
"in",
"file_volumes",
":",
"table",
".",
"add_row",
"(",
"[",
"value",
"or",
"formatting",
".",
"blank",
"(",
")",
"for",
"value",
"in",
"columns",
".",
"row",
"(",
"file_volume",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List file storage. | [
"List",
"file",
"storage",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/list.py#L66-L81 | train | 234,224 |
softlayer/softlayer-python | SoftLayer/CLI/file/duplicate.py | cli | def cli(env, origin_volume_id, origin_snapshot_id, duplicate_size,
duplicate_iops, duplicate_tier, duplicate_snapshot_size, billing):
"""Order a duplicate file storage volume."""
file_manager = SoftLayer.FileStorageManager(env.client)
hourly_billing_flag = False
if billing.lower() == "hourly":
hourly_billing_flag = True
if duplicate_tier is not None:
duplicate_tier = float(duplicate_tier)
try:
order = file_manager.order_duplicate_volume(
origin_volume_id,
origin_snapshot_id=origin_snapshot_id,
duplicate_size=duplicate_size,
duplicate_iops=duplicate_iops,
duplicate_tier_level=duplicate_tier,
duplicate_snapshot_size=duplicate_snapshot_size,
hourly_billing_flag=hourly_billing_flag
)
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, origin_volume_id, origin_snapshot_id, duplicate_size,
duplicate_iops, duplicate_tier, duplicate_snapshot_size, billing):
"""Order a duplicate file storage volume."""
file_manager = SoftLayer.FileStorageManager(env.client)
hourly_billing_flag = False
if billing.lower() == "hourly":
hourly_billing_flag = True
if duplicate_tier is not None:
duplicate_tier = float(duplicate_tier)
try:
order = file_manager.order_duplicate_volume(
origin_volume_id,
origin_snapshot_id=origin_snapshot_id,
duplicate_size=duplicate_size,
duplicate_iops=duplicate_iops,
duplicate_tier_level=duplicate_tier,
duplicate_snapshot_size=duplicate_snapshot_size,
hourly_billing_flag=hourly_billing_flag
)
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",
",",
"origin_volume_id",
",",
"origin_snapshot_id",
",",
"duplicate_size",
",",
"duplicate_iops",
",",
"duplicate_tier",
",",
"duplicate_snapshot_size",
",",
"billing",
")",
":",
"file_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"hourly_billing_flag",
"=",
"False",
"if",
"billing",
".",
"lower",
"(",
")",
"==",
"\"hourly\"",
":",
"hourly_billing_flag",
"=",
"True",
"if",
"duplicate_tier",
"is",
"not",
"None",
":",
"duplicate_tier",
"=",
"float",
"(",
"duplicate_tier",
")",
"try",
":",
"order",
"=",
"file_manager",
".",
"order_duplicate_volume",
"(",
"origin_volume_id",
",",
"origin_snapshot_id",
"=",
"origin_snapshot_id",
",",
"duplicate_size",
"=",
"duplicate_size",
",",
"duplicate_iops",
"=",
"duplicate_iops",
",",
"duplicate_tier_level",
"=",
"duplicate_tier",
",",
"duplicate_snapshot_size",
"=",
"duplicate_snapshot_size",
",",
"hourly_billing_flag",
"=",
"hourly_billing_flag",
")",
"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 duplicate file storage volume. | [
"Order",
"a",
"duplicate",
"file",
"storage",
"volume",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/duplicate.py#L56-L88 | train | 234,225 |
softlayer/softlayer-python | SoftLayer/CLI/vpn/ipsec/subnet/remove.py | cli | def cli(env, context_id, subnet_id, subnet_type):
"""Remove a subnet from an IPSEC tunnel context.
The subnet id to remove must be specified.
Remote subnets are deleted upon removal from a tunnel context.
A separate configuration request should be made to realize changes on
network devices.
"""
manager = SoftLayer.IPSECManager(env.client)
# ensure context can be retrieved by given id
manager.get_tunnel_context(context_id)
succeeded = False
if subnet_type == 'internal':
succeeded = manager.remove_internal_subnet(context_id, subnet_id)
elif subnet_type == 'remote':
succeeded = manager.remove_remote_subnet(context_id, subnet_id)
elif subnet_type == 'service':
succeeded = manager.remove_service_subnet(context_id, subnet_id)
if succeeded:
env.out('Removed {} subnet #{}'.format(subnet_type, subnet_id))
else:
raise CLIHalt('Failed to remove {} subnet #{}'
.format(subnet_type, subnet_id)) | python | def cli(env, context_id, subnet_id, subnet_type):
"""Remove a subnet from an IPSEC tunnel context.
The subnet id to remove must be specified.
Remote subnets are deleted upon removal from a tunnel context.
A separate configuration request should be made to realize changes on
network devices.
"""
manager = SoftLayer.IPSECManager(env.client)
# ensure context can be retrieved by given id
manager.get_tunnel_context(context_id)
succeeded = False
if subnet_type == 'internal':
succeeded = manager.remove_internal_subnet(context_id, subnet_id)
elif subnet_type == 'remote':
succeeded = manager.remove_remote_subnet(context_id, subnet_id)
elif subnet_type == 'service':
succeeded = manager.remove_service_subnet(context_id, subnet_id)
if succeeded:
env.out('Removed {} subnet #{}'.format(subnet_type, subnet_id))
else:
raise CLIHalt('Failed to remove {} subnet #{}'
.format(subnet_type, subnet_id)) | [
"def",
"cli",
"(",
"env",
",",
"context_id",
",",
"subnet_id",
",",
"subnet_type",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"IPSECManager",
"(",
"env",
".",
"client",
")",
"# ensure context can be retrieved by given id",
"manager",
".",
"get_tunnel_context",
"(",
"context_id",
")",
"succeeded",
"=",
"False",
"if",
"subnet_type",
"==",
"'internal'",
":",
"succeeded",
"=",
"manager",
".",
"remove_internal_subnet",
"(",
"context_id",
",",
"subnet_id",
")",
"elif",
"subnet_type",
"==",
"'remote'",
":",
"succeeded",
"=",
"manager",
".",
"remove_remote_subnet",
"(",
"context_id",
",",
"subnet_id",
")",
"elif",
"subnet_type",
"==",
"'service'",
":",
"succeeded",
"=",
"manager",
".",
"remove_service_subnet",
"(",
"context_id",
",",
"subnet_id",
")",
"if",
"succeeded",
":",
"env",
".",
"out",
"(",
"'Removed {} subnet #{}'",
".",
"format",
"(",
"subnet_type",
",",
"subnet_id",
")",
")",
"else",
":",
"raise",
"CLIHalt",
"(",
"'Failed to remove {} subnet #{}'",
".",
"format",
"(",
"subnet_type",
",",
"subnet_id",
")",
")"
] | Remove a subnet from an IPSEC tunnel context.
The subnet id to remove must be specified.
Remote subnets are deleted upon removal from a tunnel context.
A separate configuration request should be made to realize changes on
network devices. | [
"Remove",
"a",
"subnet",
"from",
"an",
"IPSEC",
"tunnel",
"context",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/subnet/remove.py#L25-L51 | train | 234,226 |
softlayer/softlayer-python | SoftLayer/CLI/ticket/list.py | cli | def cli(env, is_open):
"""List tickets."""
ticket_mgr = SoftLayer.TicketManager(env.client)
table = formatting.Table([
'id', 'assigned_user', 'title', 'last_edited', 'status', 'updates', 'priority'
])
tickets = ticket_mgr.list_tickets(open_status=is_open, closed_status=not is_open)
for ticket in tickets:
user = formatting.blank()
if ticket.get('assignedUser'):
user = "%s %s" % (ticket['assignedUser']['firstName'], ticket['assignedUser']['lastName'])
table.add_row([
ticket['id'],
user,
click.wrap_text(ticket['title']),
ticket['lastEditDate'],
ticket['status']['name'],
ticket.get('updateCount', 0),
ticket.get('priority', 0)
])
env.fout(table) | python | def cli(env, is_open):
"""List tickets."""
ticket_mgr = SoftLayer.TicketManager(env.client)
table = formatting.Table([
'id', 'assigned_user', 'title', 'last_edited', 'status', 'updates', 'priority'
])
tickets = ticket_mgr.list_tickets(open_status=is_open, closed_status=not is_open)
for ticket in tickets:
user = formatting.blank()
if ticket.get('assignedUser'):
user = "%s %s" % (ticket['assignedUser']['firstName'], ticket['assignedUser']['lastName'])
table.add_row([
ticket['id'],
user,
click.wrap_text(ticket['title']),
ticket['lastEditDate'],
ticket['status']['name'],
ticket.get('updateCount', 0),
ticket.get('priority', 0)
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"is_open",
")",
":",
"ticket_mgr",
"=",
"SoftLayer",
".",
"TicketManager",
"(",
"env",
".",
"client",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'assigned_user'",
",",
"'title'",
",",
"'last_edited'",
",",
"'status'",
",",
"'updates'",
",",
"'priority'",
"]",
")",
"tickets",
"=",
"ticket_mgr",
".",
"list_tickets",
"(",
"open_status",
"=",
"is_open",
",",
"closed_status",
"=",
"not",
"is_open",
")",
"for",
"ticket",
"in",
"tickets",
":",
"user",
"=",
"formatting",
".",
"blank",
"(",
")",
"if",
"ticket",
".",
"get",
"(",
"'assignedUser'",
")",
":",
"user",
"=",
"\"%s %s\"",
"%",
"(",
"ticket",
"[",
"'assignedUser'",
"]",
"[",
"'firstName'",
"]",
",",
"ticket",
"[",
"'assignedUser'",
"]",
"[",
"'lastName'",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"ticket",
"[",
"'id'",
"]",
",",
"user",
",",
"click",
".",
"wrap_text",
"(",
"ticket",
"[",
"'title'",
"]",
")",
",",
"ticket",
"[",
"'lastEditDate'",
"]",
",",
"ticket",
"[",
"'status'",
"]",
"[",
"'name'",
"]",
",",
"ticket",
".",
"get",
"(",
"'updateCount'",
",",
"0",
")",
",",
"ticket",
".",
"get",
"(",
"'priority'",
",",
"0",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List tickets. | [
"List",
"tickets",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ticket/list.py#L15-L38 | train | 234,227 |
softlayer/softlayer-python | SoftLayer/CLI/securitygroup/detail.py | cli | def cli(env, identifier):
"""Get details about a security group."""
mgr = SoftLayer.NetworkManager(env.client)
secgroup = mgr.get_securitygroup(identifier)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', secgroup['id']])
table.add_row(['name', secgroup.get('name') or formatting.blank()])
table.add_row(['description',
secgroup.get('description') or formatting.blank()])
rule_table = formatting.Table(['id', 'remoteIp', 'remoteGroupId',
'direction', 'ethertype', 'portRangeMin',
'portRangeMax', 'protocol'])
for rule in secgroup.get('rules', []):
rg_id = rule.get('remoteGroup', {}).get('id') or formatting.blank()
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()
rule_table.add_row([rule['id'],
rule.get('remoteIp') or formatting.blank(),
rule.get('remoteGroupId', rg_id),
rule['direction'],
rule.get('ethertype') or formatting.blank(),
port_min,
port_max,
rule.get('protocol') or formatting.blank()])
table.add_row(['rules', rule_table])
vsi_table = formatting.Table(['id', 'hostname', 'interface', 'ipAddress'])
for binding in secgroup.get('networkComponentBindings', []):
try:
vsi = binding['networkComponent']['guest']
vsi_id = vsi['id']
hostname = vsi['hostname']
interface = ('PRIVATE' if binding['networkComponent']['port'] == 0
else 'PUBLIC')
ip_address = (vsi['primaryBackendIpAddress']
if binding['networkComponent']['port'] == 0
else vsi['primaryIpAddress'])
except KeyError:
vsi_id = "N/A"
hostname = "Not enough permission to view"
interface = "N/A"
ip_address = "N/A"
vsi_table.add_row([vsi_id, hostname, interface, ip_address])
table.add_row(['servers', vsi_table])
env.fout(table) | python | def cli(env, identifier):
"""Get details about a security group."""
mgr = SoftLayer.NetworkManager(env.client)
secgroup = mgr.get_securitygroup(identifier)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', secgroup['id']])
table.add_row(['name', secgroup.get('name') or formatting.blank()])
table.add_row(['description',
secgroup.get('description') or formatting.blank()])
rule_table = formatting.Table(['id', 'remoteIp', 'remoteGroupId',
'direction', 'ethertype', 'portRangeMin',
'portRangeMax', 'protocol'])
for rule in secgroup.get('rules', []):
rg_id = rule.get('remoteGroup', {}).get('id') or formatting.blank()
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()
rule_table.add_row([rule['id'],
rule.get('remoteIp') or formatting.blank(),
rule.get('remoteGroupId', rg_id),
rule['direction'],
rule.get('ethertype') or formatting.blank(),
port_min,
port_max,
rule.get('protocol') or formatting.blank()])
table.add_row(['rules', rule_table])
vsi_table = formatting.Table(['id', 'hostname', 'interface', 'ipAddress'])
for binding in secgroup.get('networkComponentBindings', []):
try:
vsi = binding['networkComponent']['guest']
vsi_id = vsi['id']
hostname = vsi['hostname']
interface = ('PRIVATE' if binding['networkComponent']['port'] == 0
else 'PUBLIC')
ip_address = (vsi['primaryBackendIpAddress']
if binding['networkComponent']['port'] == 0
else vsi['primaryIpAddress'])
except KeyError:
vsi_id = "N/A"
hostname = "Not enough permission to view"
interface = "N/A"
ip_address = "N/A"
vsi_table.add_row([vsi_id, hostname, interface, ip_address])
table.add_row(['servers', vsi_table])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"secgroup",
"=",
"mgr",
".",
"get_securitygroup",
"(",
"identifier",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"secgroup",
"[",
"'id'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'name'",
",",
"secgroup",
".",
"get",
"(",
"'name'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'description'",
",",
"secgroup",
".",
"get",
"(",
"'description'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
"]",
")",
"rule_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'remoteIp'",
",",
"'remoteGroupId'",
",",
"'direction'",
",",
"'ethertype'",
",",
"'portRangeMin'",
",",
"'portRangeMax'",
",",
"'protocol'",
"]",
")",
"for",
"rule",
"in",
"secgroup",
".",
"get",
"(",
"'rules'",
",",
"[",
"]",
")",
":",
"rg_id",
"=",
"rule",
".",
"get",
"(",
"'remoteGroup'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'id'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
"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",
"(",
")",
"rule_table",
".",
"add_row",
"(",
"[",
"rule",
"[",
"'id'",
"]",
",",
"rule",
".",
"get",
"(",
"'remoteIp'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
",",
"rule",
".",
"get",
"(",
"'remoteGroupId'",
",",
"rg_id",
")",
",",
"rule",
"[",
"'direction'",
"]",
",",
"rule",
".",
"get",
"(",
"'ethertype'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
",",
"port_min",
",",
"port_max",
",",
"rule",
".",
"get",
"(",
"'protocol'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'rules'",
",",
"rule_table",
"]",
")",
"vsi_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'hostname'",
",",
"'interface'",
",",
"'ipAddress'",
"]",
")",
"for",
"binding",
"in",
"secgroup",
".",
"get",
"(",
"'networkComponentBindings'",
",",
"[",
"]",
")",
":",
"try",
":",
"vsi",
"=",
"binding",
"[",
"'networkComponent'",
"]",
"[",
"'guest'",
"]",
"vsi_id",
"=",
"vsi",
"[",
"'id'",
"]",
"hostname",
"=",
"vsi",
"[",
"'hostname'",
"]",
"interface",
"=",
"(",
"'PRIVATE'",
"if",
"binding",
"[",
"'networkComponent'",
"]",
"[",
"'port'",
"]",
"==",
"0",
"else",
"'PUBLIC'",
")",
"ip_address",
"=",
"(",
"vsi",
"[",
"'primaryBackendIpAddress'",
"]",
"if",
"binding",
"[",
"'networkComponent'",
"]",
"[",
"'port'",
"]",
"==",
"0",
"else",
"vsi",
"[",
"'primaryIpAddress'",
"]",
")",
"except",
"KeyError",
":",
"vsi_id",
"=",
"\"N/A\"",
"hostname",
"=",
"\"Not enough permission to view\"",
"interface",
"=",
"\"N/A\"",
"ip_address",
"=",
"\"N/A\"",
"vsi_table",
".",
"add_row",
"(",
"[",
"vsi_id",
",",
"hostname",
",",
"interface",
",",
"ip_address",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'servers'",
",",
"vsi_table",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | Get details about a security group. | [
"Get",
"details",
"about",
"a",
"security",
"group",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/detail.py#L14-L73 | train | 234,228 |
softlayer/softlayer-python | SoftLayer/CLI/dns/record_add.py | cli | def cli(env, record, record_type, data, zone, ttl, priority, protocol, port, service, weight):
"""Add resource record.
Each resource record contains a RECORD and DATA property, defining a resource's name and it's target data.
Domains contain multiple types of resource records so it can take one of the following values: A, AAAA, CNAME,
MX, SPF, SRV, and PTR.
About reverse records (PTR), the RECORD value must to be the public Ip Address of device you would like to manage
reverse DNS.
slcli dns record-add 10.10.8.21 PTR myhost.com --ttl=900
Examples:
slcli dns record-add myhost.com A 192.168.1.10 --zone=foobar.com --ttl=900
slcli dns record-add myhost.com AAAA 2001:DB8::1 --zone=foobar.com
slcli dns record-add 192.168.1.2 MX 192.168.1.10 --zone=foobar.com --priority=11 --ttl=1800
slcli dns record-add myhost.com TXT "txt-verification=rXOxyZounZs87oacJSKvbUSIQ" --zone=2223334
slcli dns record-add myhost.com SPF "v=spf1 include:_spf.google.com ~all" --zone=2223334
slcli dns record-add myhost.com SRV 192.168.1.10 --zone=2223334 --service=foobar --port=80 --protocol=TCP
"""
manager = SoftLayer.DNSManager(env.client)
record_type = record_type.upper()
if zone and record_type != 'PTR':
zone_id = helpers.resolve_id(manager.resolve_ids, zone, name='zone')
if record_type == 'MX':
manager.create_record_mx(zone_id, record, data, ttl=ttl, priority=priority)
elif record_type == 'SRV':
manager.create_record_srv(zone_id, record, data, protocol, port, service,
ttl=ttl, priority=priority, weight=weight)
else:
manager.create_record(zone_id, record, record_type, data, ttl=ttl)
elif record_type == 'PTR':
manager.create_record_ptr(record, data, ttl=ttl)
else:
raise exceptions.CLIAbort("%s isn't a valid record type or zone is missing" % record_type)
click.secho("%s record added successfully" % record_type, fg='green') | python | def cli(env, record, record_type, data, zone, ttl, priority, protocol, port, service, weight):
"""Add resource record.
Each resource record contains a RECORD and DATA property, defining a resource's name and it's target data.
Domains contain multiple types of resource records so it can take one of the following values: A, AAAA, CNAME,
MX, SPF, SRV, and PTR.
About reverse records (PTR), the RECORD value must to be the public Ip Address of device you would like to manage
reverse DNS.
slcli dns record-add 10.10.8.21 PTR myhost.com --ttl=900
Examples:
slcli dns record-add myhost.com A 192.168.1.10 --zone=foobar.com --ttl=900
slcli dns record-add myhost.com AAAA 2001:DB8::1 --zone=foobar.com
slcli dns record-add 192.168.1.2 MX 192.168.1.10 --zone=foobar.com --priority=11 --ttl=1800
slcli dns record-add myhost.com TXT "txt-verification=rXOxyZounZs87oacJSKvbUSIQ" --zone=2223334
slcli dns record-add myhost.com SPF "v=spf1 include:_spf.google.com ~all" --zone=2223334
slcli dns record-add myhost.com SRV 192.168.1.10 --zone=2223334 --service=foobar --port=80 --protocol=TCP
"""
manager = SoftLayer.DNSManager(env.client)
record_type = record_type.upper()
if zone and record_type != 'PTR':
zone_id = helpers.resolve_id(manager.resolve_ids, zone, name='zone')
if record_type == 'MX':
manager.create_record_mx(zone_id, record, data, ttl=ttl, priority=priority)
elif record_type == 'SRV':
manager.create_record_srv(zone_id, record, data, protocol, port, service,
ttl=ttl, priority=priority, weight=weight)
else:
manager.create_record(zone_id, record, record_type, data, ttl=ttl)
elif record_type == 'PTR':
manager.create_record_ptr(record, data, ttl=ttl)
else:
raise exceptions.CLIAbort("%s isn't a valid record type or zone is missing" % record_type)
click.secho("%s record added successfully" % record_type, fg='green') | [
"def",
"cli",
"(",
"env",
",",
"record",
",",
"record_type",
",",
"data",
",",
"zone",
",",
"ttl",
",",
"priority",
",",
"protocol",
",",
"port",
",",
"service",
",",
"weight",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"DNSManager",
"(",
"env",
".",
"client",
")",
"record_type",
"=",
"record_type",
".",
"upper",
"(",
")",
"if",
"zone",
"and",
"record_type",
"!=",
"'PTR'",
":",
"zone_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"manager",
".",
"resolve_ids",
",",
"zone",
",",
"name",
"=",
"'zone'",
")",
"if",
"record_type",
"==",
"'MX'",
":",
"manager",
".",
"create_record_mx",
"(",
"zone_id",
",",
"record",
",",
"data",
",",
"ttl",
"=",
"ttl",
",",
"priority",
"=",
"priority",
")",
"elif",
"record_type",
"==",
"'SRV'",
":",
"manager",
".",
"create_record_srv",
"(",
"zone_id",
",",
"record",
",",
"data",
",",
"protocol",
",",
"port",
",",
"service",
",",
"ttl",
"=",
"ttl",
",",
"priority",
"=",
"priority",
",",
"weight",
"=",
"weight",
")",
"else",
":",
"manager",
".",
"create_record",
"(",
"zone_id",
",",
"record",
",",
"record_type",
",",
"data",
",",
"ttl",
"=",
"ttl",
")",
"elif",
"record_type",
"==",
"'PTR'",
":",
"manager",
".",
"create_record_ptr",
"(",
"record",
",",
"data",
",",
"ttl",
"=",
"ttl",
")",
"else",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"%s isn't a valid record type or zone is missing\"",
"%",
"record_type",
")",
"click",
".",
"secho",
"(",
"\"%s record added successfully\"",
"%",
"record_type",
",",
"fg",
"=",
"'green'",
")"
] | Add resource record.
Each resource record contains a RECORD and DATA property, defining a resource's name and it's target data.
Domains contain multiple types of resource records so it can take one of the following values: A, AAAA, CNAME,
MX, SPF, SRV, and PTR.
About reverse records (PTR), the RECORD value must to be the public Ip Address of device you would like to manage
reverse DNS.
slcli dns record-add 10.10.8.21 PTR myhost.com --ttl=900
Examples:
slcli dns record-add myhost.com A 192.168.1.10 --zone=foobar.com --ttl=900
slcli dns record-add myhost.com AAAA 2001:DB8::1 --zone=foobar.com
slcli dns record-add 192.168.1.2 MX 192.168.1.10 --zone=foobar.com --priority=11 --ttl=1800
slcli dns record-add myhost.com TXT "txt-verification=rXOxyZounZs87oacJSKvbUSIQ" --zone=2223334
slcli dns record-add myhost.com SPF "v=spf1 include:_spf.google.com ~all" --zone=2223334
slcli dns record-add myhost.com SRV 192.168.1.10 --zone=2223334 --service=foobar --port=80 --protocol=TCP | [
"Add",
"resource",
"record",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dns/record_add.py#L43-L90 | train | 234,229 |
softlayer/softlayer-python | SoftLayer/CLI/loadbal/cancel.py | cli | def cli(env, identifier):
"""Cancel an existing load balancer."""
mgr = SoftLayer.LoadBalancerManager(env.client)
_, loadbal_id = loadbal.parse_id(identifier)
if not (env.skip_confirmations or
formatting.confirm("This action will cancel a load balancer. "
"Continue?")):
raise exceptions.CLIAbort('Aborted.')
mgr.cancel_lb(loadbal_id)
env.fout('Load Balancer with id %s is being cancelled!' % identifier) | python | def cli(env, identifier):
"""Cancel an existing load balancer."""
mgr = SoftLayer.LoadBalancerManager(env.client)
_, loadbal_id = loadbal.parse_id(identifier)
if not (env.skip_confirmations or
formatting.confirm("This action will cancel a load balancer. "
"Continue?")):
raise exceptions.CLIAbort('Aborted.')
mgr.cancel_lb(loadbal_id)
env.fout('Load Balancer with id %s is being cancelled!' % identifier) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"LoadBalancerManager",
"(",
"env",
".",
"client",
")",
"_",
",",
"loadbal_id",
"=",
"loadbal",
".",
"parse_id",
"(",
"identifier",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"confirm",
"(",
"\"This action will cancel a load balancer. \"",
"\"Continue?\"",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted.'",
")",
"mgr",
".",
"cancel_lb",
"(",
"loadbal_id",
")",
"env",
".",
"fout",
"(",
"'Load Balancer with id %s is being cancelled!'",
"%",
"identifier",
")"
] | Cancel an existing load balancer. | [
"Cancel",
"an",
"existing",
"load",
"balancer",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/cancel.py#L16-L29 | train | 234,230 |
softlayer/softlayer-python | SoftLayer/CLI/order/preset_list.py | cli | def cli(env, package_keyname, keyword):
"""List package presets.
.. Note::
Presets are set CPU / RAM / Disk allotments. You still need to specify required items.
Some packages do not have presets.
::
# List the presets for Bare Metal servers
slcli order preset-list BARE_METAL_SERVER
# List the Bare Metal server presets that include a GPU
slcli order preset-list BARE_METAL_SERVER --keyword gpu
"""
table = formatting.Table(COLUMNS)
manager = ordering.OrderingManager(env.client)
_filter = {}
if keyword:
_filter = {'activePresets': {'name': {'operation': '*= %s' % keyword}}}
presets = manager.list_presets(package_keyname, filter=_filter)
for preset in presets:
table.add_row([
preset['name'],
preset['keyName'],
preset['description']
])
env.fout(table) | python | def cli(env, package_keyname, keyword):
"""List package presets.
.. Note::
Presets are set CPU / RAM / Disk allotments. You still need to specify required items.
Some packages do not have presets.
::
# List the presets for Bare Metal servers
slcli order preset-list BARE_METAL_SERVER
# List the Bare Metal server presets that include a GPU
slcli order preset-list BARE_METAL_SERVER --keyword gpu
"""
table = formatting.Table(COLUMNS)
manager = ordering.OrderingManager(env.client)
_filter = {}
if keyword:
_filter = {'activePresets': {'name': {'operation': '*= %s' % keyword}}}
presets = manager.list_presets(package_keyname, filter=_filter)
for preset in presets:
table.add_row([
preset['name'],
preset['keyName'],
preset['description']
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"package_keyname",
",",
"keyword",
")",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"COLUMNS",
")",
"manager",
"=",
"ordering",
".",
"OrderingManager",
"(",
"env",
".",
"client",
")",
"_filter",
"=",
"{",
"}",
"if",
"keyword",
":",
"_filter",
"=",
"{",
"'activePresets'",
":",
"{",
"'name'",
":",
"{",
"'operation'",
":",
"'*= %s'",
"%",
"keyword",
"}",
"}",
"}",
"presets",
"=",
"manager",
".",
"list_presets",
"(",
"package_keyname",
",",
"filter",
"=",
"_filter",
")",
"for",
"preset",
"in",
"presets",
":",
"table",
".",
"add_row",
"(",
"[",
"preset",
"[",
"'name'",
"]",
",",
"preset",
"[",
"'keyName'",
"]",
",",
"preset",
"[",
"'description'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List package presets.
.. Note::
Presets are set CPU / RAM / Disk allotments. You still need to specify required items.
Some packages do not have presets.
::
# List the presets for Bare Metal servers
slcli order preset-list BARE_METAL_SERVER
# List the Bare Metal server presets that include a GPU
slcli order preset-list BARE_METAL_SERVER --keyword gpu | [
"List",
"package",
"presets",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/preset_list.py#L20-L50 | train | 234,231 |
softlayer/softlayer-python | SoftLayer/CLI/user/permissions.py | permission_table | def permission_table(user_permissions, all_permissions):
"""Creates a table of available permissions"""
table = formatting.Table(['Description', 'KeyName', 'Assigned'])
table.align['KeyName'] = 'l'
table.align['Description'] = 'l'
table.align['Assigned'] = 'l'
for perm in all_permissions:
assigned = user_permissions.get(perm['keyName'], False)
table.add_row([perm['name'], perm['keyName'], assigned])
return table | python | def permission_table(user_permissions, all_permissions):
"""Creates a table of available permissions"""
table = formatting.Table(['Description', 'KeyName', 'Assigned'])
table.align['KeyName'] = 'l'
table.align['Description'] = 'l'
table.align['Assigned'] = 'l'
for perm in all_permissions:
assigned = user_permissions.get(perm['keyName'], False)
table.add_row([perm['name'], perm['keyName'], assigned])
return table | [
"def",
"permission_table",
"(",
"user_permissions",
",",
"all_permissions",
")",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Description'",
",",
"'KeyName'",
",",
"'Assigned'",
"]",
")",
"table",
".",
"align",
"[",
"'KeyName'",
"]",
"=",
"'l'",
"table",
".",
"align",
"[",
"'Description'",
"]",
"=",
"'l'",
"table",
".",
"align",
"[",
"'Assigned'",
"]",
"=",
"'l'",
"for",
"perm",
"in",
"all_permissions",
":",
"assigned",
"=",
"user_permissions",
".",
"get",
"(",
"perm",
"[",
"'keyName'",
"]",
",",
"False",
")",
"table",
".",
"add_row",
"(",
"[",
"perm",
"[",
"'name'",
"]",
",",
"perm",
"[",
"'keyName'",
"]",
",",
"assigned",
"]",
")",
"return",
"table"
] | Creates a table of available permissions | [
"Creates",
"a",
"table",
"of",
"available",
"permissions"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/permissions.py#L39-L49 | train | 234,232 |
softlayer/softlayer-python | SoftLayer/CLI/user/permissions.py | roles_table | def roles_table(user):
"""Creates a table for a users roles"""
table = formatting.Table(['id', 'Role Name', 'Description'])
for role in user['roles']:
table.add_row([role['id'], role['name'], role['description']])
return table | python | def roles_table(user):
"""Creates a table for a users roles"""
table = formatting.Table(['id', 'Role Name', 'Description'])
for role in user['roles']:
table.add_row([role['id'], role['name'], role['description']])
return table | [
"def",
"roles_table",
"(",
"user",
")",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'Role Name'",
",",
"'Description'",
"]",
")",
"for",
"role",
"in",
"user",
"[",
"'roles'",
"]",
":",
"table",
".",
"add_row",
"(",
"[",
"role",
"[",
"'id'",
"]",
",",
"role",
"[",
"'name'",
"]",
",",
"role",
"[",
"'description'",
"]",
"]",
")",
"return",
"table"
] | Creates a table for a users roles | [
"Creates",
"a",
"table",
"for",
"a",
"users",
"roles"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/permissions.py#L52-L57 | train | 234,233 |
softlayer/softlayer-python | SoftLayer/CLI/virt/create.py | _update_with_like_args | def _update_with_like_args(ctx, _, value):
"""Update arguments with options taken from a currently running VS."""
if value is None:
return
env = ctx.ensure_object(environment.Environment)
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, value, 'VS')
like_details = vsi.get_instance(vs_id)
like_args = {
'hostname': like_details['hostname'],
'domain': like_details['domain'],
'hourly': like_details['hourlyBillingFlag'],
'datacenter': like_details['datacenter']['name'],
'network': like_details['networkComponents'][0]['maxSpeed'],
'userdata': like_details['userData'] or None,
'postinstall': like_details.get('postInstallScriptUri'),
'dedicated': like_details['dedicatedAccountHostOnlyFlag'],
'private': like_details['privateNetworkOnlyFlag'],
'placement_id': like_details.get('placementGroupId', None),
}
like_args['flavor'] = utils.lookup(like_details,
'billingItem',
'orderItem',
'preset',
'keyName')
if not like_args['flavor']:
like_args['cpu'] = like_details['maxCpu']
like_args['memory'] = '%smb' % like_details['maxMemory']
tag_refs = like_details.get('tagReferences', None)
if tag_refs is not None and len(tag_refs) > 0:
like_args['tag'] = [t['tag']['name'] for t in tag_refs]
# Handle mutually exclusive options
like_image = utils.lookup(like_details,
'blockDeviceTemplateGroup',
'globalIdentifier')
like_os = utils.lookup(like_details,
'operatingSystem',
'softwareLicense',
'softwareDescription',
'referenceCode')
if like_image:
like_args['image'] = like_image
elif like_os:
like_args['os'] = like_os
if ctx.default_map is None:
ctx.default_map = {}
ctx.default_map.update(like_args) | python | def _update_with_like_args(ctx, _, value):
"""Update arguments with options taken from a currently running VS."""
if value is None:
return
env = ctx.ensure_object(environment.Environment)
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, value, 'VS')
like_details = vsi.get_instance(vs_id)
like_args = {
'hostname': like_details['hostname'],
'domain': like_details['domain'],
'hourly': like_details['hourlyBillingFlag'],
'datacenter': like_details['datacenter']['name'],
'network': like_details['networkComponents'][0]['maxSpeed'],
'userdata': like_details['userData'] or None,
'postinstall': like_details.get('postInstallScriptUri'),
'dedicated': like_details['dedicatedAccountHostOnlyFlag'],
'private': like_details['privateNetworkOnlyFlag'],
'placement_id': like_details.get('placementGroupId', None),
}
like_args['flavor'] = utils.lookup(like_details,
'billingItem',
'orderItem',
'preset',
'keyName')
if not like_args['flavor']:
like_args['cpu'] = like_details['maxCpu']
like_args['memory'] = '%smb' % like_details['maxMemory']
tag_refs = like_details.get('tagReferences', None)
if tag_refs is not None and len(tag_refs) > 0:
like_args['tag'] = [t['tag']['name'] for t in tag_refs]
# Handle mutually exclusive options
like_image = utils.lookup(like_details,
'blockDeviceTemplateGroup',
'globalIdentifier')
like_os = utils.lookup(like_details,
'operatingSystem',
'softwareLicense',
'softwareDescription',
'referenceCode')
if like_image:
like_args['image'] = like_image
elif like_os:
like_args['os'] = like_os
if ctx.default_map is None:
ctx.default_map = {}
ctx.default_map.update(like_args) | [
"def",
"_update_with_like_args",
"(",
"ctx",
",",
"_",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"env",
"=",
"ctx",
".",
"ensure_object",
"(",
"environment",
".",
"Environment",
")",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
"value",
",",
"'VS'",
")",
"like_details",
"=",
"vsi",
".",
"get_instance",
"(",
"vs_id",
")",
"like_args",
"=",
"{",
"'hostname'",
":",
"like_details",
"[",
"'hostname'",
"]",
",",
"'domain'",
":",
"like_details",
"[",
"'domain'",
"]",
",",
"'hourly'",
":",
"like_details",
"[",
"'hourlyBillingFlag'",
"]",
",",
"'datacenter'",
":",
"like_details",
"[",
"'datacenter'",
"]",
"[",
"'name'",
"]",
",",
"'network'",
":",
"like_details",
"[",
"'networkComponents'",
"]",
"[",
"0",
"]",
"[",
"'maxSpeed'",
"]",
",",
"'userdata'",
":",
"like_details",
"[",
"'userData'",
"]",
"or",
"None",
",",
"'postinstall'",
":",
"like_details",
".",
"get",
"(",
"'postInstallScriptUri'",
")",
",",
"'dedicated'",
":",
"like_details",
"[",
"'dedicatedAccountHostOnlyFlag'",
"]",
",",
"'private'",
":",
"like_details",
"[",
"'privateNetworkOnlyFlag'",
"]",
",",
"'placement_id'",
":",
"like_details",
".",
"get",
"(",
"'placementGroupId'",
",",
"None",
")",
",",
"}",
"like_args",
"[",
"'flavor'",
"]",
"=",
"utils",
".",
"lookup",
"(",
"like_details",
",",
"'billingItem'",
",",
"'orderItem'",
",",
"'preset'",
",",
"'keyName'",
")",
"if",
"not",
"like_args",
"[",
"'flavor'",
"]",
":",
"like_args",
"[",
"'cpu'",
"]",
"=",
"like_details",
"[",
"'maxCpu'",
"]",
"like_args",
"[",
"'memory'",
"]",
"=",
"'%smb'",
"%",
"like_details",
"[",
"'maxMemory'",
"]",
"tag_refs",
"=",
"like_details",
".",
"get",
"(",
"'tagReferences'",
",",
"None",
")",
"if",
"tag_refs",
"is",
"not",
"None",
"and",
"len",
"(",
"tag_refs",
")",
">",
"0",
":",
"like_args",
"[",
"'tag'",
"]",
"=",
"[",
"t",
"[",
"'tag'",
"]",
"[",
"'name'",
"]",
"for",
"t",
"in",
"tag_refs",
"]",
"# Handle mutually exclusive options",
"like_image",
"=",
"utils",
".",
"lookup",
"(",
"like_details",
",",
"'blockDeviceTemplateGroup'",
",",
"'globalIdentifier'",
")",
"like_os",
"=",
"utils",
".",
"lookup",
"(",
"like_details",
",",
"'operatingSystem'",
",",
"'softwareLicense'",
",",
"'softwareDescription'",
",",
"'referenceCode'",
")",
"if",
"like_image",
":",
"like_args",
"[",
"'image'",
"]",
"=",
"like_image",
"elif",
"like_os",
":",
"like_args",
"[",
"'os'",
"]",
"=",
"like_os",
"if",
"ctx",
".",
"default_map",
"is",
"None",
":",
"ctx",
".",
"default_map",
"=",
"{",
"}",
"ctx",
".",
"default_map",
".",
"update",
"(",
"like_args",
")"
] | Update arguments with options taken from a currently running VS. | [
"Update",
"arguments",
"with",
"options",
"taken",
"from",
"a",
"currently",
"running",
"VS",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/create.py#L16-L67 | train | 234,234 |
softlayer/softlayer-python | SoftLayer/CLI/virt/create.py | _build_receipt_table | def _build_receipt_table(result, billing="hourly", test=False):
"""Retrieve the total recurring fee of the items prices"""
title = "OrderId: %s" % (result.get('orderId', 'No order placed'))
table = formatting.Table(['Cost', 'Description'], title=title)
table.align['Cost'] = 'r'
table.align['Description'] = 'l'
total = 0.000
if test:
prices = result['prices']
else:
prices = result['orderDetails']['prices']
for item in prices:
rate = 0.000
if billing == "hourly":
rate += float(item.get('hourlyRecurringFee', 0.000))
else:
rate += float(item.get('recurringFee', 0.000))
total += rate
table.add_row([rate, item['item']['description']])
table.add_row(["%.3f" % total, "Total %s cost" % billing])
return table | python | def _build_receipt_table(result, billing="hourly", test=False):
"""Retrieve the total recurring fee of the items prices"""
title = "OrderId: %s" % (result.get('orderId', 'No order placed'))
table = formatting.Table(['Cost', 'Description'], title=title)
table.align['Cost'] = 'r'
table.align['Description'] = 'l'
total = 0.000
if test:
prices = result['prices']
else:
prices = result['orderDetails']['prices']
for item in prices:
rate = 0.000
if billing == "hourly":
rate += float(item.get('hourlyRecurringFee', 0.000))
else:
rate += float(item.get('recurringFee', 0.000))
total += rate
table.add_row([rate, item['item']['description']])
table.add_row(["%.3f" % total, "Total %s cost" % billing])
return table | [
"def",
"_build_receipt_table",
"(",
"result",
",",
"billing",
"=",
"\"hourly\"",
",",
"test",
"=",
"False",
")",
":",
"title",
"=",
"\"OrderId: %s\"",
"%",
"(",
"result",
".",
"get",
"(",
"'orderId'",
",",
"'No order placed'",
")",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Cost'",
",",
"'Description'",
"]",
",",
"title",
"=",
"title",
")",
"table",
".",
"align",
"[",
"'Cost'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'Description'",
"]",
"=",
"'l'",
"total",
"=",
"0.000",
"if",
"test",
":",
"prices",
"=",
"result",
"[",
"'prices'",
"]",
"else",
":",
"prices",
"=",
"result",
"[",
"'orderDetails'",
"]",
"[",
"'prices'",
"]",
"for",
"item",
"in",
"prices",
":",
"rate",
"=",
"0.000",
"if",
"billing",
"==",
"\"hourly\"",
":",
"rate",
"+=",
"float",
"(",
"item",
".",
"get",
"(",
"'hourlyRecurringFee'",
",",
"0.000",
")",
")",
"else",
":",
"rate",
"+=",
"float",
"(",
"item",
".",
"get",
"(",
"'recurringFee'",
",",
"0.000",
")",
")",
"total",
"+=",
"rate",
"table",
".",
"add_row",
"(",
"[",
"rate",
",",
"item",
"[",
"'item'",
"]",
"[",
"'description'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"\"%.3f\"",
"%",
"total",
",",
"\"Total %s cost\"",
"%",
"billing",
"]",
")",
"return",
"table"
] | Retrieve the total recurring fee of the items prices | [
"Retrieve",
"the",
"total",
"recurring",
"fee",
"of",
"the",
"items",
"prices"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/create.py#L239-L260 | train | 234,235 |
softlayer/softlayer-python | SoftLayer/CLI/virt/create.py | _validate_args | def _validate_args(env, args):
"""Raises an ArgumentError if the given arguments are not valid."""
if all([args['cpu'], args['flavor']]):
raise exceptions.ArgumentError(
'[-c | --cpu] not allowed with [-f | --flavor]')
if all([args['memory'], args['flavor']]):
raise exceptions.ArgumentError(
'[-m | --memory] not allowed with [-f | --flavor]')
if all([args['dedicated'], args['flavor']]):
raise exceptions.ArgumentError(
'[-d | --dedicated] not allowed with [-f | --flavor]')
if all([args['host_id'], args['flavor']]):
raise exceptions.ArgumentError(
'[-h | --host-id] not allowed with [-f | --flavor]')
if all([args['userdata'], args['userfile']]):
raise exceptions.ArgumentError(
'[-u | --userdata] not allowed with [-F | --userfile]')
image_args = [args['os'], args['image']]
if all(image_args):
raise exceptions.ArgumentError(
'[-o | --os] not allowed with [--image]')
while not any([args['os'], args['image']]):
args['os'] = env.input("Operating System Code", default="", show_default=False)
if not args['os']:
args['image'] = env.input("Image", default="", show_default=False) | python | def _validate_args(env, args):
"""Raises an ArgumentError if the given arguments are not valid."""
if all([args['cpu'], args['flavor']]):
raise exceptions.ArgumentError(
'[-c | --cpu] not allowed with [-f | --flavor]')
if all([args['memory'], args['flavor']]):
raise exceptions.ArgumentError(
'[-m | --memory] not allowed with [-f | --flavor]')
if all([args['dedicated'], args['flavor']]):
raise exceptions.ArgumentError(
'[-d | --dedicated] not allowed with [-f | --flavor]')
if all([args['host_id'], args['flavor']]):
raise exceptions.ArgumentError(
'[-h | --host-id] not allowed with [-f | --flavor]')
if all([args['userdata'], args['userfile']]):
raise exceptions.ArgumentError(
'[-u | --userdata] not allowed with [-F | --userfile]')
image_args = [args['os'], args['image']]
if all(image_args):
raise exceptions.ArgumentError(
'[-o | --os] not allowed with [--image]')
while not any([args['os'], args['image']]):
args['os'] = env.input("Operating System Code", default="", show_default=False)
if not args['os']:
args['image'] = env.input("Image", default="", show_default=False) | [
"def",
"_validate_args",
"(",
"env",
",",
"args",
")",
":",
"if",
"all",
"(",
"[",
"args",
"[",
"'cpu'",
"]",
",",
"args",
"[",
"'flavor'",
"]",
"]",
")",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"'[-c | --cpu] not allowed with [-f | --flavor]'",
")",
"if",
"all",
"(",
"[",
"args",
"[",
"'memory'",
"]",
",",
"args",
"[",
"'flavor'",
"]",
"]",
")",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"'[-m | --memory] not allowed with [-f | --flavor]'",
")",
"if",
"all",
"(",
"[",
"args",
"[",
"'dedicated'",
"]",
",",
"args",
"[",
"'flavor'",
"]",
"]",
")",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"'[-d | --dedicated] not allowed with [-f | --flavor]'",
")",
"if",
"all",
"(",
"[",
"args",
"[",
"'host_id'",
"]",
",",
"args",
"[",
"'flavor'",
"]",
"]",
")",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"'[-h | --host-id] not allowed with [-f | --flavor]'",
")",
"if",
"all",
"(",
"[",
"args",
"[",
"'userdata'",
"]",
",",
"args",
"[",
"'userfile'",
"]",
"]",
")",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"'[-u | --userdata] not allowed with [-F | --userfile]'",
")",
"image_args",
"=",
"[",
"args",
"[",
"'os'",
"]",
",",
"args",
"[",
"'image'",
"]",
"]",
"if",
"all",
"(",
"image_args",
")",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"'[-o | --os] not allowed with [--image]'",
")",
"while",
"not",
"any",
"(",
"[",
"args",
"[",
"'os'",
"]",
",",
"args",
"[",
"'image'",
"]",
"]",
")",
":",
"args",
"[",
"'os'",
"]",
"=",
"env",
".",
"input",
"(",
"\"Operating System Code\"",
",",
"default",
"=",
"\"\"",
",",
"show_default",
"=",
"False",
")",
"if",
"not",
"args",
"[",
"'os'",
"]",
":",
"args",
"[",
"'image'",
"]",
"=",
"env",
".",
"input",
"(",
"\"Image\"",
",",
"default",
"=",
"\"\"",
",",
"show_default",
"=",
"False",
")"
] | Raises an ArgumentError if the given arguments are not valid. | [
"Raises",
"an",
"ArgumentError",
"if",
"the",
"given",
"arguments",
"are",
"not",
"valid",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/create.py#L273-L304 | train | 234,236 |
softlayer/softlayer-python | SoftLayer/CLI/virt/upgrade.py | cli | def cli(env, identifier, cpu, private, memory, network, flavor):
"""Upgrade a virtual server."""
vsi = SoftLayer.VSManager(env.client)
if not any([cpu, memory, network, flavor]):
raise exceptions.ArgumentError("Must provide [--cpu], [--memory], [--network], or [--flavor] to upgrade")
if private and not cpu:
raise exceptions.ArgumentError("Must specify [--cpu] when using [--private]")
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
if not (env.skip_confirmations or formatting.confirm("This action will incur charges on your account. Continue?")):
raise exceptions.CLIAbort('Aborted')
if memory:
memory = int(memory / 1024)
if not vsi.upgrade(vs_id, cpus=cpu, memory=memory, nic_speed=network, public=not private, preset=flavor):
raise exceptions.CLIAbort('VS Upgrade Failed') | python | def cli(env, identifier, cpu, private, memory, network, flavor):
"""Upgrade a virtual server."""
vsi = SoftLayer.VSManager(env.client)
if not any([cpu, memory, network, flavor]):
raise exceptions.ArgumentError("Must provide [--cpu], [--memory], [--network], or [--flavor] to upgrade")
if private and not cpu:
raise exceptions.ArgumentError("Must specify [--cpu] when using [--private]")
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
if not (env.skip_confirmations or formatting.confirm("This action will incur charges on your account. Continue?")):
raise exceptions.CLIAbort('Aborted')
if memory:
memory = int(memory / 1024)
if not vsi.upgrade(vs_id, cpus=cpu, memory=memory, nic_speed=network, public=not private, preset=flavor):
raise exceptions.CLIAbort('VS Upgrade Failed') | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"cpu",
",",
"private",
",",
"memory",
",",
"network",
",",
"flavor",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"if",
"not",
"any",
"(",
"[",
"cpu",
",",
"memory",
",",
"network",
",",
"flavor",
"]",
")",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"\"Must provide [--cpu], [--memory], [--network], or [--flavor] to upgrade\"",
")",
"if",
"private",
"and",
"not",
"cpu",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"\"Must specify [--cpu] when using [--private]\"",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
"identifier",
",",
"'VS'",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"confirm",
"(",
"\"This action will incur charges on your account. Continue?\"",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted'",
")",
"if",
"memory",
":",
"memory",
"=",
"int",
"(",
"memory",
"/",
"1024",
")",
"if",
"not",
"vsi",
".",
"upgrade",
"(",
"vs_id",
",",
"cpus",
"=",
"cpu",
",",
"memory",
"=",
"memory",
",",
"nic_speed",
"=",
"network",
",",
"public",
"=",
"not",
"private",
",",
"preset",
"=",
"flavor",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'VS Upgrade Failed'",
")"
] | Upgrade a virtual server. | [
"Upgrade",
"a",
"virtual",
"server",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/upgrade.py#L26-L45 | train | 234,237 |
softlayer/softlayer-python | SoftLayer/CLI/hardware/power.py | reboot | def reboot(env, identifier, hard):
"""Reboot an active server."""
hardware_server = env.client['Hardware_Server']
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. '
'Continue?' % hw_id)):
raise exceptions.CLIAbort('Aborted.')
if hard is True:
hardware_server.rebootHard(id=hw_id)
elif hard is False:
hardware_server.rebootSoft(id=hw_id)
else:
hardware_server.rebootDefault(id=hw_id) | python | def reboot(env, identifier, hard):
"""Reboot an active server."""
hardware_server = env.client['Hardware_Server']
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. '
'Continue?' % hw_id)):
raise exceptions.CLIAbort('Aborted.')
if hard is True:
hardware_server.rebootHard(id=hw_id)
elif hard is False:
hardware_server.rebootSoft(id=hw_id)
else:
hardware_server.rebootDefault(id=hw_id) | [
"def",
"reboot",
"(",
"env",
",",
"identifier",
",",
"hard",
")",
":",
"hardware_server",
"=",
"env",
".",
"client",
"[",
"'Hardware_Server'",
"]",
"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. '",
"'Continue?'",
"%",
"hw_id",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted.'",
")",
"if",
"hard",
"is",
"True",
":",
"hardware_server",
".",
"rebootHard",
"(",
"id",
"=",
"hw_id",
")",
"elif",
"hard",
"is",
"False",
":",
"hardware_server",
".",
"rebootSoft",
"(",
"id",
"=",
"hw_id",
")",
"else",
":",
"hardware_server",
".",
"rebootDefault",
"(",
"id",
"=",
"hw_id",
")"
] | Reboot an active server. | [
"Reboot",
"an",
"active",
"server",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/power.py#L35-L51 | train | 234,238 |
softlayer/softlayer-python | SoftLayer/CLI/hardware/power.py | power_on | def power_on(env, identifier):
"""Power on a server."""
mgr = SoftLayer.HardwareManager(env.client)
hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
env.client['Hardware_Server'].powerOn(id=hw_id) | python | def power_on(env, identifier):
"""Power on a server."""
mgr = SoftLayer.HardwareManager(env.client)
hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
env.client['Hardware_Server'].powerOn(id=hw_id) | [
"def",
"power_on",
"(",
"env",
",",
"identifier",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"HardwareManager",
"(",
"env",
".",
"client",
")",
"hw_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'hardware'",
")",
"env",
".",
"client",
"[",
"'Hardware_Server'",
"]",
".",
"powerOn",
"(",
"id",
"=",
"hw_id",
")"
] | Power on a server. | [
"Power",
"on",
"a",
"server",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/power.py#L57-L62 | train | 234,239 |
softlayer/softlayer-python | SoftLayer/CLI/hardware/power.py | power_cycle | def power_cycle(env, identifier):
"""Power cycle a server."""
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. '
'Continue?' % hw_id)):
raise exceptions.CLIAbort('Aborted.')
env.client['Hardware_Server'].powerCycle(id=hw_id) | python | def power_cycle(env, identifier):
"""Power cycle a server."""
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. '
'Continue?' % hw_id)):
raise exceptions.CLIAbort('Aborted.')
env.client['Hardware_Server'].powerCycle(id=hw_id) | [
"def",
"power_cycle",
"(",
"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. '",
"'Continue?'",
"%",
"hw_id",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted.'",
")",
"env",
".",
"client",
"[",
"'Hardware_Server'",
"]",
".",
"powerCycle",
"(",
"id",
"=",
"hw_id",
")"
] | Power cycle a server. | [
"Power",
"cycle",
"a",
"server",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/power.py#L68-L79 | train | 234,240 |
softlayer/softlayer-python | SoftLayer/CLI/securitygroup/edit.py | cli | def cli(env, group_id, name, description):
"""Edit details of a security group."""
mgr = SoftLayer.NetworkManager(env.client)
data = {}
if name:
data['name'] = name
if description:
data['description'] = description
if not mgr.edit_securitygroup(group_id, **data):
raise exceptions.CLIAbort("Failed to edit security group") | python | def cli(env, group_id, name, description):
"""Edit details of a security group."""
mgr = SoftLayer.NetworkManager(env.client)
data = {}
if name:
data['name'] = name
if description:
data['description'] = description
if not mgr.edit_securitygroup(group_id, **data):
raise exceptions.CLIAbort("Failed to edit security group") | [
"def",
"cli",
"(",
"env",
",",
"group_id",
",",
"name",
",",
"description",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"data",
"=",
"{",
"}",
"if",
"name",
":",
"data",
"[",
"'name'",
"]",
"=",
"name",
"if",
"description",
":",
"data",
"[",
"'description'",
"]",
"=",
"description",
"if",
"not",
"mgr",
".",
"edit_securitygroup",
"(",
"group_id",
",",
"*",
"*",
"data",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Failed to edit security group\"",
")"
] | Edit details of a security group. | [
"Edit",
"details",
"of",
"a",
"security",
"group",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/edit.py#L18-L28 | train | 234,241 |
softlayer/softlayer-python | SoftLayer/CLI/event_log/get.py | cli | def cli(env, date_min, date_max, obj_event, obj_id, obj_type, utc_offset, metadata, limit):
"""Get Event Logs
Example:
slcli event-log get -d 01/01/2019 -D 02/01/2019 -t User -l 10
"""
columns = ['Event', 'Object', 'Type', 'Date', 'Username']
event_mgr = SoftLayer.EventLogManager(env.client)
user_mgr = SoftLayer.UserManager(env.client)
request_filter = event_mgr.build_filter(date_min, date_max, obj_event, obj_id, obj_type, utc_offset)
logs = event_mgr.get_event_logs(request_filter)
log_time = "%Y-%m-%dT%H:%M:%S.%f%z"
user_data = {}
if metadata:
columns.append('Metadata')
row_count = 0
click.secho(", ".join(columns))
for log in logs:
if log is None:
click.secho('No logs available for filter %s.' % request_filter, fg='red')
return
user = log['userType']
label = log.get('label', '')
if user == "CUSTOMER":
username = user_data.get(log['userId'])
if username is None:
username = user_mgr.get_user(log['userId'], "mask[username]")['username']
user_data[log['userId']] = username
user = username
if metadata:
metadata_data = log['metaData'].strip("\n\t")
click.secho("'{0}','{1}','{2}','{3}','{4}','{5}'".format(
log['eventName'],
label,
log['objectName'],
utils.clean_time(log['eventCreateDate'], in_format=log_time),
user,
metadata_data))
else:
click.secho("'{0}','{1}','{2}','{3}','{4}'".format(
log['eventName'],
label,
log['objectName'],
utils.clean_time(log['eventCreateDate'], in_format=log_time),
user))
row_count = row_count + 1
if row_count >= limit and limit != -1:
return | python | def cli(env, date_min, date_max, obj_event, obj_id, obj_type, utc_offset, metadata, limit):
"""Get Event Logs
Example:
slcli event-log get -d 01/01/2019 -D 02/01/2019 -t User -l 10
"""
columns = ['Event', 'Object', 'Type', 'Date', 'Username']
event_mgr = SoftLayer.EventLogManager(env.client)
user_mgr = SoftLayer.UserManager(env.client)
request_filter = event_mgr.build_filter(date_min, date_max, obj_event, obj_id, obj_type, utc_offset)
logs = event_mgr.get_event_logs(request_filter)
log_time = "%Y-%m-%dT%H:%M:%S.%f%z"
user_data = {}
if metadata:
columns.append('Metadata')
row_count = 0
click.secho(", ".join(columns))
for log in logs:
if log is None:
click.secho('No logs available for filter %s.' % request_filter, fg='red')
return
user = log['userType']
label = log.get('label', '')
if user == "CUSTOMER":
username = user_data.get(log['userId'])
if username is None:
username = user_mgr.get_user(log['userId'], "mask[username]")['username']
user_data[log['userId']] = username
user = username
if metadata:
metadata_data = log['metaData'].strip("\n\t")
click.secho("'{0}','{1}','{2}','{3}','{4}','{5}'".format(
log['eventName'],
label,
log['objectName'],
utils.clean_time(log['eventCreateDate'], in_format=log_time),
user,
metadata_data))
else:
click.secho("'{0}','{1}','{2}','{3}','{4}'".format(
log['eventName'],
label,
log['objectName'],
utils.clean_time(log['eventCreateDate'], in_format=log_time),
user))
row_count = row_count + 1
if row_count >= limit and limit != -1:
return | [
"def",
"cli",
"(",
"env",
",",
"date_min",
",",
"date_max",
",",
"obj_event",
",",
"obj_id",
",",
"obj_type",
",",
"utc_offset",
",",
"metadata",
",",
"limit",
")",
":",
"columns",
"=",
"[",
"'Event'",
",",
"'Object'",
",",
"'Type'",
",",
"'Date'",
",",
"'Username'",
"]",
"event_mgr",
"=",
"SoftLayer",
".",
"EventLogManager",
"(",
"env",
".",
"client",
")",
"user_mgr",
"=",
"SoftLayer",
".",
"UserManager",
"(",
"env",
".",
"client",
")",
"request_filter",
"=",
"event_mgr",
".",
"build_filter",
"(",
"date_min",
",",
"date_max",
",",
"obj_event",
",",
"obj_id",
",",
"obj_type",
",",
"utc_offset",
")",
"logs",
"=",
"event_mgr",
".",
"get_event_logs",
"(",
"request_filter",
")",
"log_time",
"=",
"\"%Y-%m-%dT%H:%M:%S.%f%z\"",
"user_data",
"=",
"{",
"}",
"if",
"metadata",
":",
"columns",
".",
"append",
"(",
"'Metadata'",
")",
"row_count",
"=",
"0",
"click",
".",
"secho",
"(",
"\", \"",
".",
"join",
"(",
"columns",
")",
")",
"for",
"log",
"in",
"logs",
":",
"if",
"log",
"is",
"None",
":",
"click",
".",
"secho",
"(",
"'No logs available for filter %s.'",
"%",
"request_filter",
",",
"fg",
"=",
"'red'",
")",
"return",
"user",
"=",
"log",
"[",
"'userType'",
"]",
"label",
"=",
"log",
".",
"get",
"(",
"'label'",
",",
"''",
")",
"if",
"user",
"==",
"\"CUSTOMER\"",
":",
"username",
"=",
"user_data",
".",
"get",
"(",
"log",
"[",
"'userId'",
"]",
")",
"if",
"username",
"is",
"None",
":",
"username",
"=",
"user_mgr",
".",
"get_user",
"(",
"log",
"[",
"'userId'",
"]",
",",
"\"mask[username]\"",
")",
"[",
"'username'",
"]",
"user_data",
"[",
"log",
"[",
"'userId'",
"]",
"]",
"=",
"username",
"user",
"=",
"username",
"if",
"metadata",
":",
"metadata_data",
"=",
"log",
"[",
"'metaData'",
"]",
".",
"strip",
"(",
"\"\\n\\t\"",
")",
"click",
".",
"secho",
"(",
"\"'{0}','{1}','{2}','{3}','{4}','{5}'\"",
".",
"format",
"(",
"log",
"[",
"'eventName'",
"]",
",",
"label",
",",
"log",
"[",
"'objectName'",
"]",
",",
"utils",
".",
"clean_time",
"(",
"log",
"[",
"'eventCreateDate'",
"]",
",",
"in_format",
"=",
"log_time",
")",
",",
"user",
",",
"metadata_data",
")",
")",
"else",
":",
"click",
".",
"secho",
"(",
"\"'{0}','{1}','{2}','{3}','{4}'\"",
".",
"format",
"(",
"log",
"[",
"'eventName'",
"]",
",",
"label",
",",
"log",
"[",
"'objectName'",
"]",
",",
"utils",
".",
"clean_time",
"(",
"log",
"[",
"'eventCreateDate'",
"]",
",",
"in_format",
"=",
"log_time",
")",
",",
"user",
")",
")",
"row_count",
"=",
"row_count",
"+",
"1",
"if",
"row_count",
">=",
"limit",
"and",
"limit",
"!=",
"-",
"1",
":",
"return"
] | Get Event Logs
Example:
slcli event-log get -d 01/01/2019 -D 02/01/2019 -t User -l 10 | [
"Get",
"Event",
"Logs"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/event_log/get.py#L29-L83 | train | 234,242 |
softlayer/softlayer-python | SoftLayer/CLI/file/modify.py | cli | def cli(env, volume_id, new_size, new_iops, new_tier):
"""Modify an existing file storage volume."""
file_manager = SoftLayer.FileStorageManager(env.client)
if new_tier is not None:
new_tier = float(new_tier)
try:
order = file_manager.order_modified_volume(
volume_id,
new_size=new_size,
new_iops=new_iops,
new_tier_level=new_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, new_size, new_iops, new_tier):
"""Modify an existing file storage volume."""
file_manager = SoftLayer.FileStorageManager(env.client)
if new_tier is not None:
new_tier = float(new_tier)
try:
order = file_manager.order_modified_volume(
volume_id,
new_size=new_size,
new_iops=new_iops,
new_tier_level=new_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",
",",
"new_size",
",",
"new_iops",
",",
"new_tier",
")",
":",
"file_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"if",
"new_tier",
"is",
"not",
"None",
":",
"new_tier",
"=",
"float",
"(",
"new_tier",
")",
"try",
":",
"order",
"=",
"file_manager",
".",
"order_modified_volume",
"(",
"volume_id",
",",
"new_size",
"=",
"new_size",
",",
"new_iops",
"=",
"new_iops",
",",
"new_tier_level",
"=",
"new_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.\"",
")"
] | Modify an existing file storage volume. | [
"Modify",
"an",
"existing",
"file",
"storage",
"volume",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/modify.py#L35-L57 | train | 234,243 |
softlayer/softlayer-python | SoftLayer/managers/user.py | UserManager.add_permissions | def add_permissions(self, user_id, permissions):
"""Enables a list of permissions for a user
:param int id: user id to set
:param list permissions: List of permissions keynames to enable
:returns: True on success, Exception otherwise
Example::
add_permissions(123, ['BANDWIDTH_MANAGE'])
"""
pretty_permissions = self.format_permission_object(permissions)
LOGGER.warning("Adding the following permissions to %s: %s", user_id, pretty_permissions)
return self.user_service.addBulkPortalPermission(pretty_permissions, id=user_id) | python | def add_permissions(self, user_id, permissions):
"""Enables a list of permissions for a user
:param int id: user id to set
:param list permissions: List of permissions keynames to enable
:returns: True on success, Exception otherwise
Example::
add_permissions(123, ['BANDWIDTH_MANAGE'])
"""
pretty_permissions = self.format_permission_object(permissions)
LOGGER.warning("Adding the following permissions to %s: %s", user_id, pretty_permissions)
return self.user_service.addBulkPortalPermission(pretty_permissions, id=user_id) | [
"def",
"add_permissions",
"(",
"self",
",",
"user_id",
",",
"permissions",
")",
":",
"pretty_permissions",
"=",
"self",
".",
"format_permission_object",
"(",
"permissions",
")",
"LOGGER",
".",
"warning",
"(",
"\"Adding the following permissions to %s: %s\"",
",",
"user_id",
",",
"pretty_permissions",
")",
"return",
"self",
".",
"user_service",
".",
"addBulkPortalPermission",
"(",
"pretty_permissions",
",",
"id",
"=",
"user_id",
")"
] | Enables a list of permissions for a user
:param int id: user id to set
:param list permissions: List of permissions keynames to enable
:returns: True on success, Exception otherwise
Example::
add_permissions(123, ['BANDWIDTH_MANAGE']) | [
"Enables",
"a",
"list",
"of",
"permissions",
"for",
"a",
"user"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/user.py#L87-L99 | train | 234,244 |
softlayer/softlayer-python | SoftLayer/managers/user.py | UserManager.remove_permissions | def remove_permissions(self, user_id, permissions):
"""Disables a list of permissions for a user
:param int id: user id to set
:param list permissions: List of permissions keynames to disable
:returns: True on success, Exception otherwise
Example::
remove_permissions(123, ['BANDWIDTH_MANAGE'])
"""
pretty_permissions = self.format_permission_object(permissions)
LOGGER.warning("Removing the following permissions to %s: %s", user_id, pretty_permissions)
return self.user_service.removeBulkPortalPermission(pretty_permissions, id=user_id) | python | def remove_permissions(self, user_id, permissions):
"""Disables a list of permissions for a user
:param int id: user id to set
:param list permissions: List of permissions keynames to disable
:returns: True on success, Exception otherwise
Example::
remove_permissions(123, ['BANDWIDTH_MANAGE'])
"""
pretty_permissions = self.format_permission_object(permissions)
LOGGER.warning("Removing the following permissions to %s: %s", user_id, pretty_permissions)
return self.user_service.removeBulkPortalPermission(pretty_permissions, id=user_id) | [
"def",
"remove_permissions",
"(",
"self",
",",
"user_id",
",",
"permissions",
")",
":",
"pretty_permissions",
"=",
"self",
".",
"format_permission_object",
"(",
"permissions",
")",
"LOGGER",
".",
"warning",
"(",
"\"Removing the following permissions to %s: %s\"",
",",
"user_id",
",",
"pretty_permissions",
")",
"return",
"self",
".",
"user_service",
".",
"removeBulkPortalPermission",
"(",
"pretty_permissions",
",",
"id",
"=",
"user_id",
")"
] | Disables a list of permissions for a user
:param int id: user id to set
:param list permissions: List of permissions keynames to disable
:returns: True on success, Exception otherwise
Example::
remove_permissions(123, ['BANDWIDTH_MANAGE']) | [
"Disables",
"a",
"list",
"of",
"permissions",
"for",
"a",
"user"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/user.py#L101-L113 | train | 234,245 |
softlayer/softlayer-python | SoftLayer/managers/user.py | UserManager.permissions_from_user | def permissions_from_user(self, user_id, from_user_id):
"""Sets user_id's permission to be the same as from_user_id's
Any permissions from_user_id has will be added to user_id.
Any permissions from_user_id doesn't have will be removed from user_id.
:param int user_id: The user to change permissions.
:param int from_user_id: The use to base permissions from.
:returns: True on success, Exception otherwise.
"""
from_permissions = self.get_user_permissions(from_user_id)
self.add_permissions(user_id, from_permissions)
all_permissions = self.get_all_permissions()
remove_permissions = []
for permission in all_permissions:
# If permission does not exist for from_user_id add it to the list to be removed
if _keyname_search(from_permissions, permission['keyName']):
continue
else:
remove_permissions.append({'keyName': permission['keyName']})
self.remove_permissions(user_id, remove_permissions)
return True | python | def permissions_from_user(self, user_id, from_user_id):
"""Sets user_id's permission to be the same as from_user_id's
Any permissions from_user_id has will be added to user_id.
Any permissions from_user_id doesn't have will be removed from user_id.
:param int user_id: The user to change permissions.
:param int from_user_id: The use to base permissions from.
:returns: True on success, Exception otherwise.
"""
from_permissions = self.get_user_permissions(from_user_id)
self.add_permissions(user_id, from_permissions)
all_permissions = self.get_all_permissions()
remove_permissions = []
for permission in all_permissions:
# If permission does not exist for from_user_id add it to the list to be removed
if _keyname_search(from_permissions, permission['keyName']):
continue
else:
remove_permissions.append({'keyName': permission['keyName']})
self.remove_permissions(user_id, remove_permissions)
return True | [
"def",
"permissions_from_user",
"(",
"self",
",",
"user_id",
",",
"from_user_id",
")",
":",
"from_permissions",
"=",
"self",
".",
"get_user_permissions",
"(",
"from_user_id",
")",
"self",
".",
"add_permissions",
"(",
"user_id",
",",
"from_permissions",
")",
"all_permissions",
"=",
"self",
".",
"get_all_permissions",
"(",
")",
"remove_permissions",
"=",
"[",
"]",
"for",
"permission",
"in",
"all_permissions",
":",
"# If permission does not exist for from_user_id add it to the list to be removed",
"if",
"_keyname_search",
"(",
"from_permissions",
",",
"permission",
"[",
"'keyName'",
"]",
")",
":",
"continue",
"else",
":",
"remove_permissions",
".",
"append",
"(",
"{",
"'keyName'",
":",
"permission",
"[",
"'keyName'",
"]",
"}",
")",
"self",
".",
"remove_permissions",
"(",
"user_id",
",",
"remove_permissions",
")",
"return",
"True"
] | Sets user_id's permission to be the same as from_user_id's
Any permissions from_user_id has will be added to user_id.
Any permissions from_user_id doesn't have will be removed from user_id.
:param int user_id: The user to change permissions.
:param int from_user_id: The use to base permissions from.
:returns: True on success, Exception otherwise. | [
"Sets",
"user_id",
"s",
"permission",
"to",
"be",
"the",
"same",
"as",
"from_user_id",
"s"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/user.py#L115-L139 | train | 234,246 |
softlayer/softlayer-python | SoftLayer/managers/user.py | UserManager.get_user_permissions | def get_user_permissions(self, user_id):
"""Returns a sorted list of a users permissions"""
permissions = self.user_service.getPermissions(id=user_id)
return sorted(permissions, key=itemgetter('keyName')) | python | def get_user_permissions(self, user_id):
"""Returns a sorted list of a users permissions"""
permissions = self.user_service.getPermissions(id=user_id)
return sorted(permissions, key=itemgetter('keyName')) | [
"def",
"get_user_permissions",
"(",
"self",
",",
"user_id",
")",
":",
"permissions",
"=",
"self",
".",
"user_service",
".",
"getPermissions",
"(",
"id",
"=",
"user_id",
")",
"return",
"sorted",
"(",
"permissions",
",",
"key",
"=",
"itemgetter",
"(",
"'keyName'",
")",
")"
] | Returns a sorted list of a users permissions | [
"Returns",
"a",
"sorted",
"list",
"of",
"a",
"users",
"permissions"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/user.py#L141-L144 | train | 234,247 |
softlayer/softlayer-python | SoftLayer/managers/user.py | UserManager.get_logins | def get_logins(self, user_id, start_date=None):
"""Gets the login history for a user, default start_date is 30 days ago
:param int id: User id to get
:param string start_date: "%m/%d/%Y %H:%M:%s" formatted string.
:returns: list https://softlayer.github.io/reference/datatypes/SoftLayer_User_Customer_Access_Authentication/
Example::
get_logins(123, '04/08/2018 0:0:0')
"""
if start_date is None:
date_object = datetime.datetime.today() - datetime.timedelta(days=30)
start_date = date_object.strftime("%m/%d/%Y 0:0:0")
date_filter = {
'loginAttempts': {
'createDate': {
'operation': 'greaterThanDate',
'options': [{'name': 'date', 'value': [start_date]}]
}
}
}
login_log = self.user_service.getLoginAttempts(id=user_id, filter=date_filter)
return login_log | python | def get_logins(self, user_id, start_date=None):
"""Gets the login history for a user, default start_date is 30 days ago
:param int id: User id to get
:param string start_date: "%m/%d/%Y %H:%M:%s" formatted string.
:returns: list https://softlayer.github.io/reference/datatypes/SoftLayer_User_Customer_Access_Authentication/
Example::
get_logins(123, '04/08/2018 0:0:0')
"""
if start_date is None:
date_object = datetime.datetime.today() - datetime.timedelta(days=30)
start_date = date_object.strftime("%m/%d/%Y 0:0:0")
date_filter = {
'loginAttempts': {
'createDate': {
'operation': 'greaterThanDate',
'options': [{'name': 'date', 'value': [start_date]}]
}
}
}
login_log = self.user_service.getLoginAttempts(id=user_id, filter=date_filter)
return login_log | [
"def",
"get_logins",
"(",
"self",
",",
"user_id",
",",
"start_date",
"=",
"None",
")",
":",
"if",
"start_date",
"is",
"None",
":",
"date_object",
"=",
"datetime",
".",
"datetime",
".",
"today",
"(",
")",
"-",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"30",
")",
"start_date",
"=",
"date_object",
".",
"strftime",
"(",
"\"%m/%d/%Y 0:0:0\"",
")",
"date_filter",
"=",
"{",
"'loginAttempts'",
":",
"{",
"'createDate'",
":",
"{",
"'operation'",
":",
"'greaterThanDate'",
",",
"'options'",
":",
"[",
"{",
"'name'",
":",
"'date'",
",",
"'value'",
":",
"[",
"start_date",
"]",
"}",
"]",
"}",
"}",
"}",
"login_log",
"=",
"self",
".",
"user_service",
".",
"getLoginAttempts",
"(",
"id",
"=",
"user_id",
",",
"filter",
"=",
"date_filter",
")",
"return",
"login_log"
] | Gets the login history for a user, default start_date is 30 days ago
:param int id: User id to get
:param string start_date: "%m/%d/%Y %H:%M:%s" formatted string.
:returns: list https://softlayer.github.io/reference/datatypes/SoftLayer_User_Customer_Access_Authentication/
Example::
get_logins(123, '04/08/2018 0:0:0') | [
"Gets",
"the",
"login",
"history",
"for",
"a",
"user",
"default",
"start_date",
"is",
"30",
"days",
"ago"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/user.py#L146-L169 | train | 234,248 |
softlayer/softlayer-python | SoftLayer/managers/user.py | UserManager.get_events | def get_events(self, user_id, start_date=None):
"""Gets the event log for a specific user, default start_date is 30 days ago
:param int id: User id to view
:param string start_date: "%Y-%m-%dT%H:%M:%s.0000-06:00" is the full formatted string.
The Timezone part has to be HH:MM, notice the : there.
:returns: https://softlayer.github.io/reference/datatypes/SoftLayer_Event_Log/
"""
if start_date is None:
date_object = datetime.datetime.today() - datetime.timedelta(days=30)
start_date = date_object.strftime("%Y-%m-%dT00:00:00")
object_filter = {
'userId': {
'operation': user_id
},
'eventCreateDate': {
'operation': 'greaterThanDate',
'options': [{'name': 'date', 'value': [start_date]}]
}
}
events = self.client.call('Event_Log', 'getAllObjects', filter=object_filter)
if events is None:
events = [{'eventName': 'No Events Found'}]
return events | python | def get_events(self, user_id, start_date=None):
"""Gets the event log for a specific user, default start_date is 30 days ago
:param int id: User id to view
:param string start_date: "%Y-%m-%dT%H:%M:%s.0000-06:00" is the full formatted string.
The Timezone part has to be HH:MM, notice the : there.
:returns: https://softlayer.github.io/reference/datatypes/SoftLayer_Event_Log/
"""
if start_date is None:
date_object = datetime.datetime.today() - datetime.timedelta(days=30)
start_date = date_object.strftime("%Y-%m-%dT00:00:00")
object_filter = {
'userId': {
'operation': user_id
},
'eventCreateDate': {
'operation': 'greaterThanDate',
'options': [{'name': 'date', 'value': [start_date]}]
}
}
events = self.client.call('Event_Log', 'getAllObjects', filter=object_filter)
if events is None:
events = [{'eventName': 'No Events Found'}]
return events | [
"def",
"get_events",
"(",
"self",
",",
"user_id",
",",
"start_date",
"=",
"None",
")",
":",
"if",
"start_date",
"is",
"None",
":",
"date_object",
"=",
"datetime",
".",
"datetime",
".",
"today",
"(",
")",
"-",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"30",
")",
"start_date",
"=",
"date_object",
".",
"strftime",
"(",
"\"%Y-%m-%dT00:00:00\"",
")",
"object_filter",
"=",
"{",
"'userId'",
":",
"{",
"'operation'",
":",
"user_id",
"}",
",",
"'eventCreateDate'",
":",
"{",
"'operation'",
":",
"'greaterThanDate'",
",",
"'options'",
":",
"[",
"{",
"'name'",
":",
"'date'",
",",
"'value'",
":",
"[",
"start_date",
"]",
"}",
"]",
"}",
"}",
"events",
"=",
"self",
".",
"client",
".",
"call",
"(",
"'Event_Log'",
",",
"'getAllObjects'",
",",
"filter",
"=",
"object_filter",
")",
"if",
"events",
"is",
"None",
":",
"events",
"=",
"[",
"{",
"'eventName'",
":",
"'No Events Found'",
"}",
"]",
"return",
"events"
] | Gets the event log for a specific user, default start_date is 30 days ago
:param int id: User id to view
:param string start_date: "%Y-%m-%dT%H:%M:%s.0000-06:00" is the full formatted string.
The Timezone part has to be HH:MM, notice the : there.
:returns: https://softlayer.github.io/reference/datatypes/SoftLayer_Event_Log/ | [
"Gets",
"the",
"event",
"log",
"for",
"a",
"specific",
"user",
"default",
"start_date",
"is",
"30",
"days",
"ago"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/user.py#L171-L197 | train | 234,249 |
softlayer/softlayer-python | SoftLayer/managers/user.py | UserManager._get_id_from_username | def _get_id_from_username(self, username):
"""Looks up a username's id
:param string username: Username to lookup
:returns: The id that matches username.
"""
_mask = "mask[id, username]"
_filter = {'users': {'username': utils.query_filter(username)}}
user = self.list_users(_mask, _filter)
if len(user) == 1:
return [user[0]['id']]
elif len(user) > 1:
raise exceptions.SoftLayerError("Multiple users found with the name: %s" % username)
else:
raise exceptions.SoftLayerError("Unable to find user id for %s" % username) | python | def _get_id_from_username(self, username):
"""Looks up a username's id
:param string username: Username to lookup
:returns: The id that matches username.
"""
_mask = "mask[id, username]"
_filter = {'users': {'username': utils.query_filter(username)}}
user = self.list_users(_mask, _filter)
if len(user) == 1:
return [user[0]['id']]
elif len(user) > 1:
raise exceptions.SoftLayerError("Multiple users found with the name: %s" % username)
else:
raise exceptions.SoftLayerError("Unable to find user id for %s" % username) | [
"def",
"_get_id_from_username",
"(",
"self",
",",
"username",
")",
":",
"_mask",
"=",
"\"mask[id, username]\"",
"_filter",
"=",
"{",
"'users'",
":",
"{",
"'username'",
":",
"utils",
".",
"query_filter",
"(",
"username",
")",
"}",
"}",
"user",
"=",
"self",
".",
"list_users",
"(",
"_mask",
",",
"_filter",
")",
"if",
"len",
"(",
"user",
")",
"==",
"1",
":",
"return",
"[",
"user",
"[",
"0",
"]",
"[",
"'id'",
"]",
"]",
"elif",
"len",
"(",
"user",
")",
">",
"1",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"Multiple users found with the name: %s\"",
"%",
"username",
")",
"else",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"Unable to find user id for %s\"",
"%",
"username",
")"
] | Looks up a username's id
:param string username: Username to lookup
:returns: The id that matches username. | [
"Looks",
"up",
"a",
"username",
"s",
"id"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/user.py#L199-L213 | train | 234,250 |
softlayer/softlayer-python | SoftLayer/managers/user.py | UserManager.format_permission_object | def format_permission_object(self, permissions):
"""Formats a list of permission key names into something the SLAPI will respect.
:param list permissions: A list of SLAPI permissions keyNames.
keyName of ALL will return all permissions.
:returns: list of dictionaries that can be sent to the api to add or remove permissions
:throws SoftLayerError: If any permission is invalid this exception will be thrown.
"""
pretty_permissions = []
available_permissions = self.get_all_permissions()
# pp(available_permissions)
for permission in permissions:
# Handle data retrieved directly from the API
if isinstance(permission, dict):
permission = permission['keyName']
permission = permission.upper()
if permission == 'ALL':
return available_permissions
# Search through available_permissions to make sure what the user entered was valid
if _keyname_search(available_permissions, permission):
pretty_permissions.append({'keyName': permission})
else:
raise exceptions.SoftLayerError("'%s' is not a valid permission" % permission)
return pretty_permissions | python | def format_permission_object(self, permissions):
"""Formats a list of permission key names into something the SLAPI will respect.
:param list permissions: A list of SLAPI permissions keyNames.
keyName of ALL will return all permissions.
:returns: list of dictionaries that can be sent to the api to add or remove permissions
:throws SoftLayerError: If any permission is invalid this exception will be thrown.
"""
pretty_permissions = []
available_permissions = self.get_all_permissions()
# pp(available_permissions)
for permission in permissions:
# Handle data retrieved directly from the API
if isinstance(permission, dict):
permission = permission['keyName']
permission = permission.upper()
if permission == 'ALL':
return available_permissions
# Search through available_permissions to make sure what the user entered was valid
if _keyname_search(available_permissions, permission):
pretty_permissions.append({'keyName': permission})
else:
raise exceptions.SoftLayerError("'%s' is not a valid permission" % permission)
return pretty_permissions | [
"def",
"format_permission_object",
"(",
"self",
",",
"permissions",
")",
":",
"pretty_permissions",
"=",
"[",
"]",
"available_permissions",
"=",
"self",
".",
"get_all_permissions",
"(",
")",
"# pp(available_permissions)",
"for",
"permission",
"in",
"permissions",
":",
"# Handle data retrieved directly from the API",
"if",
"isinstance",
"(",
"permission",
",",
"dict",
")",
":",
"permission",
"=",
"permission",
"[",
"'keyName'",
"]",
"permission",
"=",
"permission",
".",
"upper",
"(",
")",
"if",
"permission",
"==",
"'ALL'",
":",
"return",
"available_permissions",
"# Search through available_permissions to make sure what the user entered was valid",
"if",
"_keyname_search",
"(",
"available_permissions",
",",
"permission",
")",
":",
"pretty_permissions",
".",
"append",
"(",
"{",
"'keyName'",
":",
"permission",
"}",
")",
"else",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"'%s' is not a valid permission\"",
"%",
"permission",
")",
"return",
"pretty_permissions"
] | Formats a list of permission key names into something the SLAPI will respect.
:param list permissions: A list of SLAPI permissions keyNames.
keyName of ALL will return all permissions.
:returns: list of dictionaries that can be sent to the api to add or remove permissions
:throws SoftLayerError: If any permission is invalid this exception will be thrown. | [
"Formats",
"a",
"list",
"of",
"permission",
"key",
"names",
"into",
"something",
"the",
"SLAPI",
"will",
"respect",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/user.py#L215-L238 | train | 234,251 |
softlayer/softlayer-python | SoftLayer/CLI/globalip/unassign.py | cli | def cli(env, identifier):
"""Unassigns a global IP from a target."""
mgr = SoftLayer.NetworkManager(env.client)
global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier,
name='global ip')
mgr.unassign_global_ip(global_ip_id) | python | def cli(env, identifier):
"""Unassigns a global IP from a target."""
mgr = SoftLayer.NetworkManager(env.client)
global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier,
name='global ip')
mgr.unassign_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'",
")",
"mgr",
".",
"unassign_global_ip",
"(",
"global_ip_id",
")"
] | Unassigns a global IP from a target. | [
"Unassigns",
"a",
"global",
"IP",
"from",
"a",
"target",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/globalip/unassign.py#L14-L20 | train | 234,252 |
softlayer/softlayer-python | SoftLayer/CLI/vpn/ipsec/configure.py | cli | def cli(env, context_id):
"""Request configuration of a tunnel context.
This action will update the advancedConfigurationFlag on the context
instance and further modifications against the context will be prevented
until all changes can be propgated to network devices.
"""
manager = SoftLayer.IPSECManager(env.client)
# ensure context can be retrieved by given id
manager.get_tunnel_context(context_id)
succeeded = manager.apply_configuration(context_id)
if succeeded:
env.out('Configuration request received for context #{}'
.format(context_id))
else:
raise CLIHalt('Failed to enqueue configuration request for context #{}'
.format(context_id)) | python | def cli(env, context_id):
"""Request configuration of a tunnel context.
This action will update the advancedConfigurationFlag on the context
instance and further modifications against the context will be prevented
until all changes can be propgated to network devices.
"""
manager = SoftLayer.IPSECManager(env.client)
# ensure context can be retrieved by given id
manager.get_tunnel_context(context_id)
succeeded = manager.apply_configuration(context_id)
if succeeded:
env.out('Configuration request received for context #{}'
.format(context_id))
else:
raise CLIHalt('Failed to enqueue configuration request for context #{}'
.format(context_id)) | [
"def",
"cli",
"(",
"env",
",",
"context_id",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"IPSECManager",
"(",
"env",
".",
"client",
")",
"# ensure context can be retrieved by given id",
"manager",
".",
"get_tunnel_context",
"(",
"context_id",
")",
"succeeded",
"=",
"manager",
".",
"apply_configuration",
"(",
"context_id",
")",
"if",
"succeeded",
":",
"env",
".",
"out",
"(",
"'Configuration request received for context #{}'",
".",
"format",
"(",
"context_id",
")",
")",
"else",
":",
"raise",
"CLIHalt",
"(",
"'Failed to enqueue configuration request for context #{}'",
".",
"format",
"(",
"context_id",
")",
")"
] | Request configuration of a tunnel context.
This action will update the advancedConfigurationFlag on the context
instance and further modifications against the context will be prevented
until all changes can be propgated to network devices. | [
"Request",
"configuration",
"of",
"a",
"tunnel",
"context",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/configure.py#L14-L31 | train | 234,253 |
softlayer/softlayer-python | SoftLayer/managers/dns.py | DNSManager._get_zone_id_from_name | def _get_zone_id_from_name(self, name):
"""Return zone ID based on a zone."""
results = self.client['Account'].getDomains(
filter={"domains": {"name": utils.query_filter(name)}})
return [x['id'] for x in results] | python | def _get_zone_id_from_name(self, name):
"""Return zone ID based on a zone."""
results = self.client['Account'].getDomains(
filter={"domains": {"name": utils.query_filter(name)}})
return [x['id'] for x in results] | [
"def",
"_get_zone_id_from_name",
"(",
"self",
",",
"name",
")",
":",
"results",
"=",
"self",
".",
"client",
"[",
"'Account'",
"]",
".",
"getDomains",
"(",
"filter",
"=",
"{",
"\"domains\"",
":",
"{",
"\"name\"",
":",
"utils",
".",
"query_filter",
"(",
"name",
")",
"}",
"}",
")",
"return",
"[",
"x",
"[",
"'id'",
"]",
"for",
"x",
"in",
"results",
"]"
] | Return zone ID based on a zone. | [
"Return",
"zone",
"ID",
"based",
"on",
"a",
"zone",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dns.py#L28-L32 | train | 234,254 |
softlayer/softlayer-python | SoftLayer/managers/dns.py | DNSManager.get_zone | def get_zone(self, zone_id, records=True):
"""Get a zone and its records.
:param zone: the zone name
:returns: A dictionary containing a large amount of information about
the specified zone.
"""
mask = None
if records:
mask = 'resourceRecords'
return self.service.getObject(id=zone_id, mask=mask) | python | def get_zone(self, zone_id, records=True):
"""Get a zone and its records.
:param zone: the zone name
:returns: A dictionary containing a large amount of information about
the specified zone.
"""
mask = None
if records:
mask = 'resourceRecords'
return self.service.getObject(id=zone_id, mask=mask) | [
"def",
"get_zone",
"(",
"self",
",",
"zone_id",
",",
"records",
"=",
"True",
")",
":",
"mask",
"=",
"None",
"if",
"records",
":",
"mask",
"=",
"'resourceRecords'",
"return",
"self",
".",
"service",
".",
"getObject",
"(",
"id",
"=",
"zone_id",
",",
"mask",
"=",
"mask",
")"
] | Get a zone and its records.
:param zone: the zone name
:returns: A dictionary containing a large amount of information about
the specified zone. | [
"Get",
"a",
"zone",
"and",
"its",
"records",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dns.py#L43-L54 | train | 234,255 |
softlayer/softlayer-python | SoftLayer/managers/dns.py | DNSManager.create_zone | def create_zone(self, zone, serial=None):
"""Create a zone for the specified zone.
:param zone: the zone name to create
:param serial: serial value on the zone (default: strftime(%Y%m%d01))
"""
return self.service.createObject({
'name': zone,
'serial': serial or time.strftime('%Y%m%d01'),
"resourceRecords": {}}) | python | def create_zone(self, zone, serial=None):
"""Create a zone for the specified zone.
:param zone: the zone name to create
:param serial: serial value on the zone (default: strftime(%Y%m%d01))
"""
return self.service.createObject({
'name': zone,
'serial': serial or time.strftime('%Y%m%d01'),
"resourceRecords": {}}) | [
"def",
"create_zone",
"(",
"self",
",",
"zone",
",",
"serial",
"=",
"None",
")",
":",
"return",
"self",
".",
"service",
".",
"createObject",
"(",
"{",
"'name'",
":",
"zone",
",",
"'serial'",
":",
"serial",
"or",
"time",
".",
"strftime",
"(",
"'%Y%m%d01'",
")",
",",
"\"resourceRecords\"",
":",
"{",
"}",
"}",
")"
] | Create a zone for the specified zone.
:param zone: the zone name to create
:param serial: serial value on the zone (default: strftime(%Y%m%d01)) | [
"Create",
"a",
"zone",
"for",
"the",
"specified",
"zone",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dns.py#L56-L66 | train | 234,256 |
softlayer/softlayer-python | SoftLayer/managers/dns.py | DNSManager.create_record_mx | def create_record_mx(self, zone_id, record, data, ttl=60, priority=10):
"""Create a mx resource record on a domain.
:param integer id: the zone's ID
:param record: the name of the record to add
:param data: the record's value
:param integer ttl: the TTL or time-to-live value (default: 60)
:param integer priority: the priority of the target host
"""
resource_record = self._generate_create_dict(record, 'MX', data, ttl,
domainId=zone_id, mxPriority=priority)
return self.record.createObject(resource_record) | python | def create_record_mx(self, zone_id, record, data, ttl=60, priority=10):
"""Create a mx resource record on a domain.
:param integer id: the zone's ID
:param record: the name of the record to add
:param data: the record's value
:param integer ttl: the TTL or time-to-live value (default: 60)
:param integer priority: the priority of the target host
"""
resource_record = self._generate_create_dict(record, 'MX', data, ttl,
domainId=zone_id, mxPriority=priority)
return self.record.createObject(resource_record) | [
"def",
"create_record_mx",
"(",
"self",
",",
"zone_id",
",",
"record",
",",
"data",
",",
"ttl",
"=",
"60",
",",
"priority",
"=",
"10",
")",
":",
"resource_record",
"=",
"self",
".",
"_generate_create_dict",
"(",
"record",
",",
"'MX'",
",",
"data",
",",
"ttl",
",",
"domainId",
"=",
"zone_id",
",",
"mxPriority",
"=",
"priority",
")",
"return",
"self",
".",
"record",
".",
"createObject",
"(",
"resource_record",
")"
] | Create a mx resource record on a domain.
:param integer id: the zone's ID
:param record: the name of the record to add
:param data: the record's value
:param integer ttl: the TTL or time-to-live value (default: 60)
:param integer priority: the priority of the target host | [
"Create",
"a",
"mx",
"resource",
"record",
"on",
"a",
"domain",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dns.py#L101-L113 | train | 234,257 |
softlayer/softlayer-python | SoftLayer/managers/dns.py | DNSManager.create_record_ptr | def create_record_ptr(self, record, data, ttl=60):
"""Create a reverse record.
:param record: the public ip address of device for which you would like to manage reverse DNS.
:param data: the record's value
:param integer ttl: the TTL or time-to-live value (default: 60)
"""
resource_record = self._generate_create_dict(record, 'PTR', data, ttl)
return self.record.createObject(resource_record) | python | def create_record_ptr(self, record, data, ttl=60):
"""Create a reverse record.
:param record: the public ip address of device for which you would like to manage reverse DNS.
:param data: the record's value
:param integer ttl: the TTL or time-to-live value (default: 60)
"""
resource_record = self._generate_create_dict(record, 'PTR', data, ttl)
return self.record.createObject(resource_record) | [
"def",
"create_record_ptr",
"(",
"self",
",",
"record",
",",
"data",
",",
"ttl",
"=",
"60",
")",
":",
"resource_record",
"=",
"self",
".",
"_generate_create_dict",
"(",
"record",
",",
"'PTR'",
",",
"data",
",",
"ttl",
")",
"return",
"self",
".",
"record",
".",
"createObject",
"(",
"resource_record",
")"
] | Create a reverse record.
:param record: the public ip address of device for which you would like to manage reverse DNS.
:param data: the record's value
:param integer ttl: the TTL or time-to-live value (default: 60) | [
"Create",
"a",
"reverse",
"record",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dns.py#L139-L149 | train | 234,258 |
softlayer/softlayer-python | SoftLayer/managers/dns.py | DNSManager.get_records | def get_records(self, zone_id, ttl=None, data=None, host=None,
record_type=None):
"""List, and optionally filter, records within a zone.
:param zone: the zone name in which to search.
:param int ttl: time in seconds
:param str data: the records data
:param str host: record's host
:param str record_type: the type of record
:returns: A list of dictionaries representing the matching records
within the specified zone.
"""
_filter = utils.NestedDict()
if ttl:
_filter['resourceRecords']['ttl'] = utils.query_filter(ttl)
if host:
_filter['resourceRecords']['host'] = utils.query_filter(host)
if data:
_filter['resourceRecords']['data'] = utils.query_filter(data)
if record_type:
_filter['resourceRecords']['type'] = utils.query_filter(
record_type.lower())
results = self.service.getResourceRecords(
id=zone_id,
mask='id,expire,domainId,host,minimum,refresh,retry,'
'mxPriority,ttl,type,data,responsiblePerson',
filter=_filter.to_dict(),
)
return results | python | def get_records(self, zone_id, ttl=None, data=None, host=None,
record_type=None):
"""List, and optionally filter, records within a zone.
:param zone: the zone name in which to search.
:param int ttl: time in seconds
:param str data: the records data
:param str host: record's host
:param str record_type: the type of record
:returns: A list of dictionaries representing the matching records
within the specified zone.
"""
_filter = utils.NestedDict()
if ttl:
_filter['resourceRecords']['ttl'] = utils.query_filter(ttl)
if host:
_filter['resourceRecords']['host'] = utils.query_filter(host)
if data:
_filter['resourceRecords']['data'] = utils.query_filter(data)
if record_type:
_filter['resourceRecords']['type'] = utils.query_filter(
record_type.lower())
results = self.service.getResourceRecords(
id=zone_id,
mask='id,expire,domainId,host,minimum,refresh,retry,'
'mxPriority,ttl,type,data,responsiblePerson',
filter=_filter.to_dict(),
)
return results | [
"def",
"get_records",
"(",
"self",
",",
"zone_id",
",",
"ttl",
"=",
"None",
",",
"data",
"=",
"None",
",",
"host",
"=",
"None",
",",
"record_type",
"=",
"None",
")",
":",
"_filter",
"=",
"utils",
".",
"NestedDict",
"(",
")",
"if",
"ttl",
":",
"_filter",
"[",
"'resourceRecords'",
"]",
"[",
"'ttl'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"ttl",
")",
"if",
"host",
":",
"_filter",
"[",
"'resourceRecords'",
"]",
"[",
"'host'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"host",
")",
"if",
"data",
":",
"_filter",
"[",
"'resourceRecords'",
"]",
"[",
"'data'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"data",
")",
"if",
"record_type",
":",
"_filter",
"[",
"'resourceRecords'",
"]",
"[",
"'type'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"record_type",
".",
"lower",
"(",
")",
")",
"results",
"=",
"self",
".",
"service",
".",
"getResourceRecords",
"(",
"id",
"=",
"zone_id",
",",
"mask",
"=",
"'id,expire,domainId,host,minimum,refresh,retry,'",
"'mxPriority,ttl,type,data,responsiblePerson'",
",",
"filter",
"=",
"_filter",
".",
"to_dict",
"(",
")",
",",
")",
"return",
"results"
] | List, and optionally filter, records within a zone.
:param zone: the zone name in which to search.
:param int ttl: time in seconds
:param str data: the records data
:param str host: record's host
:param str record_type: the type of record
:returns: A list of dictionaries representing the matching records
within the specified zone. | [
"List",
"and",
"optionally",
"filter",
"records",
"within",
"a",
"zone",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dns.py#L183-L218 | train | 234,259 |
softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager.cancel_guests | def cancel_guests(self, host_id):
"""Cancel all guests into the dedicated host immediately.
To cancel an specified guest use the method VSManager.cancel_instance()
:param host_id: The ID of the dedicated host.
:return: The id, fqdn and status of all guests into a dictionary. The status
could be 'Cancelled' or an exception message, The dictionary is empty
if there isn't any guest in the dedicated host.
Example::
# Cancel guests of dedicated host id 12345
result = mgr.cancel_guests(12345)
"""
result = []
guests = self.host.getGuests(id=host_id, mask='id,fullyQualifiedDomainName')
if guests:
for vs in guests:
status_info = {
'id': vs['id'],
'fqdn': vs['fullyQualifiedDomainName'],
'status': self._delete_guest(vs['id'])
}
result.append(status_info)
return result | python | def cancel_guests(self, host_id):
"""Cancel all guests into the dedicated host immediately.
To cancel an specified guest use the method VSManager.cancel_instance()
:param host_id: The ID of the dedicated host.
:return: The id, fqdn and status of all guests into a dictionary. The status
could be 'Cancelled' or an exception message, The dictionary is empty
if there isn't any guest in the dedicated host.
Example::
# Cancel guests of dedicated host id 12345
result = mgr.cancel_guests(12345)
"""
result = []
guests = self.host.getGuests(id=host_id, mask='id,fullyQualifiedDomainName')
if guests:
for vs in guests:
status_info = {
'id': vs['id'],
'fqdn': vs['fullyQualifiedDomainName'],
'status': self._delete_guest(vs['id'])
}
result.append(status_info)
return result | [
"def",
"cancel_guests",
"(",
"self",
",",
"host_id",
")",
":",
"result",
"=",
"[",
"]",
"guests",
"=",
"self",
".",
"host",
".",
"getGuests",
"(",
"id",
"=",
"host_id",
",",
"mask",
"=",
"'id,fullyQualifiedDomainName'",
")",
"if",
"guests",
":",
"for",
"vs",
"in",
"guests",
":",
"status_info",
"=",
"{",
"'id'",
":",
"vs",
"[",
"'id'",
"]",
",",
"'fqdn'",
":",
"vs",
"[",
"'fullyQualifiedDomainName'",
"]",
",",
"'status'",
":",
"self",
".",
"_delete_guest",
"(",
"vs",
"[",
"'id'",
"]",
")",
"}",
"result",
".",
"append",
"(",
"status_info",
")",
"return",
"result"
] | Cancel all guests into the dedicated host immediately.
To cancel an specified guest use the method VSManager.cancel_instance()
:param host_id: The ID of the dedicated host.
:return: The id, fqdn and status of all guests into a dictionary. The status
could be 'Cancelled' or an exception message, The dictionary is empty
if there isn't any guest in the dedicated host.
Example::
# Cancel guests of dedicated host id 12345
result = mgr.cancel_guests(12345) | [
"Cancel",
"all",
"guests",
"into",
"the",
"dedicated",
"host",
"immediately",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L54-L81 | train | 234,260 |
softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager.list_guests | def list_guests(self, host_id, tags=None, cpus=None, memory=None, hostname=None,
domain=None, local_disk=None, nic_speed=None, public_ip=None,
private_ip=None, **kwargs):
"""Retrieve a list of all virtual servers on the dedicated host.
Example::
# Print out a list of instances with 4 cpu cores in the host id 12345.
for vsi in mgr.list_guests(host_id=12345, cpus=4):
print vsi['fullyQualifiedDomainName'], vsi['primaryIpAddress']
# Using a custom object-mask. Will get ONLY what is specified
object_mask = "mask[hostname,monitoringRobot[robotStatus]]"
for vsi in mgr.list_guests(mask=object_mask,cpus=4):
print vsi
:param integer host_id: the identifier of dedicated host
:param list tags: filter based on list of tags
:param integer cpus: filter based on number of CPUS
:param integer memory: filter based on amount of memory
:param string hostname: filter based on hostname
:param string domain: filter based on domain
:param string local_disk: filter based on local_disk
:param integer nic_speed: filter based on network speed (in MBPS)
:param string public_ip: filter based on public ip address
:param string private_ip: filter based on private ip address
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
:returns: Returns a list of dictionaries representing the matching
virtual servers
"""
if 'mask' not in kwargs:
items = [
'id',
'globalIdentifier',
'hostname',
'domain',
'fullyQualifiedDomainName',
'primaryBackendIpAddress',
'primaryIpAddress',
'lastKnownPowerState.name',
'hourlyBillingFlag',
'powerState',
'maxCpu',
'maxMemory',
'datacenter',
'activeTransaction.transactionStatus[friendlyName,name]',
'status',
]
kwargs['mask'] = "mask[%s]" % ','.join(items)
_filter = utils.NestedDict(kwargs.get('filter') or {})
if tags:
_filter['guests']['tagReferences']['tag']['name'] = {
'operation': 'in',
'options': [{'name': 'data', 'value': tags}],
}
if cpus:
_filter['guests']['maxCpu'] = utils.query_filter(cpus)
if memory:
_filter['guests']['maxMemory'] = utils.query_filter(memory)
if hostname:
_filter['guests']['hostname'] = utils.query_filter(hostname)
if domain:
_filter['guests']['domain'] = utils.query_filter(domain)
if local_disk is not None:
_filter['guests']['localDiskFlag'] = (
utils.query_filter(bool(local_disk)))
if nic_speed:
_filter['guests']['networkComponents']['maxSpeed'] = (
utils.query_filter(nic_speed))
if public_ip:
_filter['guests']['primaryIpAddress'] = (
utils.query_filter(public_ip))
if private_ip:
_filter['guests']['primaryBackendIpAddress'] = (
utils.query_filter(private_ip))
kwargs['filter'] = _filter.to_dict()
kwargs['iter'] = True
return self.host.getGuests(id=host_id, **kwargs) | python | def list_guests(self, host_id, tags=None, cpus=None, memory=None, hostname=None,
domain=None, local_disk=None, nic_speed=None, public_ip=None,
private_ip=None, **kwargs):
"""Retrieve a list of all virtual servers on the dedicated host.
Example::
# Print out a list of instances with 4 cpu cores in the host id 12345.
for vsi in mgr.list_guests(host_id=12345, cpus=4):
print vsi['fullyQualifiedDomainName'], vsi['primaryIpAddress']
# Using a custom object-mask. Will get ONLY what is specified
object_mask = "mask[hostname,monitoringRobot[robotStatus]]"
for vsi in mgr.list_guests(mask=object_mask,cpus=4):
print vsi
:param integer host_id: the identifier of dedicated host
:param list tags: filter based on list of tags
:param integer cpus: filter based on number of CPUS
:param integer memory: filter based on amount of memory
:param string hostname: filter based on hostname
:param string domain: filter based on domain
:param string local_disk: filter based on local_disk
:param integer nic_speed: filter based on network speed (in MBPS)
:param string public_ip: filter based on public ip address
:param string private_ip: filter based on private ip address
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
:returns: Returns a list of dictionaries representing the matching
virtual servers
"""
if 'mask' not in kwargs:
items = [
'id',
'globalIdentifier',
'hostname',
'domain',
'fullyQualifiedDomainName',
'primaryBackendIpAddress',
'primaryIpAddress',
'lastKnownPowerState.name',
'hourlyBillingFlag',
'powerState',
'maxCpu',
'maxMemory',
'datacenter',
'activeTransaction.transactionStatus[friendlyName,name]',
'status',
]
kwargs['mask'] = "mask[%s]" % ','.join(items)
_filter = utils.NestedDict(kwargs.get('filter') or {})
if tags:
_filter['guests']['tagReferences']['tag']['name'] = {
'operation': 'in',
'options': [{'name': 'data', 'value': tags}],
}
if cpus:
_filter['guests']['maxCpu'] = utils.query_filter(cpus)
if memory:
_filter['guests']['maxMemory'] = utils.query_filter(memory)
if hostname:
_filter['guests']['hostname'] = utils.query_filter(hostname)
if domain:
_filter['guests']['domain'] = utils.query_filter(domain)
if local_disk is not None:
_filter['guests']['localDiskFlag'] = (
utils.query_filter(bool(local_disk)))
if nic_speed:
_filter['guests']['networkComponents']['maxSpeed'] = (
utils.query_filter(nic_speed))
if public_ip:
_filter['guests']['primaryIpAddress'] = (
utils.query_filter(public_ip))
if private_ip:
_filter['guests']['primaryBackendIpAddress'] = (
utils.query_filter(private_ip))
kwargs['filter'] = _filter.to_dict()
kwargs['iter'] = True
return self.host.getGuests(id=host_id, **kwargs) | [
"def",
"list_guests",
"(",
"self",
",",
"host_id",
",",
"tags",
"=",
"None",
",",
"cpus",
"=",
"None",
",",
"memory",
"=",
"None",
",",
"hostname",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"local_disk",
"=",
"None",
",",
"nic_speed",
"=",
"None",
",",
"public_ip",
"=",
"None",
",",
"private_ip",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"items",
"=",
"[",
"'id'",
",",
"'globalIdentifier'",
",",
"'hostname'",
",",
"'domain'",
",",
"'fullyQualifiedDomainName'",
",",
"'primaryBackendIpAddress'",
",",
"'primaryIpAddress'",
",",
"'lastKnownPowerState.name'",
",",
"'hourlyBillingFlag'",
",",
"'powerState'",
",",
"'maxCpu'",
",",
"'maxMemory'",
",",
"'datacenter'",
",",
"'activeTransaction.transactionStatus[friendlyName,name]'",
",",
"'status'",
",",
"]",
"kwargs",
"[",
"'mask'",
"]",
"=",
"\"mask[%s]\"",
"%",
"','",
".",
"join",
"(",
"items",
")",
"_filter",
"=",
"utils",
".",
"NestedDict",
"(",
"kwargs",
".",
"get",
"(",
"'filter'",
")",
"or",
"{",
"}",
")",
"if",
"tags",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'tagReferences'",
"]",
"[",
"'tag'",
"]",
"[",
"'name'",
"]",
"=",
"{",
"'operation'",
":",
"'in'",
",",
"'options'",
":",
"[",
"{",
"'name'",
":",
"'data'",
",",
"'value'",
":",
"tags",
"}",
"]",
",",
"}",
"if",
"cpus",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'maxCpu'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"cpus",
")",
"if",
"memory",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'maxMemory'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"memory",
")",
"if",
"hostname",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'hostname'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"hostname",
")",
"if",
"domain",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'domain'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"domain",
")",
"if",
"local_disk",
"is",
"not",
"None",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'localDiskFlag'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"bool",
"(",
"local_disk",
")",
")",
")",
"if",
"nic_speed",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'networkComponents'",
"]",
"[",
"'maxSpeed'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"nic_speed",
")",
")",
"if",
"public_ip",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'primaryIpAddress'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"public_ip",
")",
")",
"if",
"private_ip",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'primaryBackendIpAddress'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"private_ip",
")",
")",
"kwargs",
"[",
"'filter'",
"]",
"=",
"_filter",
".",
"to_dict",
"(",
")",
"kwargs",
"[",
"'iter'",
"]",
"=",
"True",
"return",
"self",
".",
"host",
".",
"getGuests",
"(",
"id",
"=",
"host_id",
",",
"*",
"*",
"kwargs",
")"
] | Retrieve a list of all virtual servers on the dedicated host.
Example::
# Print out a list of instances with 4 cpu cores in the host id 12345.
for vsi in mgr.list_guests(host_id=12345, cpus=4):
print vsi['fullyQualifiedDomainName'], vsi['primaryIpAddress']
# Using a custom object-mask. Will get ONLY what is specified
object_mask = "mask[hostname,monitoringRobot[robotStatus]]"
for vsi in mgr.list_guests(mask=object_mask,cpus=4):
print vsi
:param integer host_id: the identifier of dedicated host
:param list tags: filter based on list of tags
:param integer cpus: filter based on number of CPUS
:param integer memory: filter based on amount of memory
:param string hostname: filter based on hostname
:param string domain: filter based on domain
:param string local_disk: filter based on local_disk
:param integer nic_speed: filter based on network speed (in MBPS)
:param string public_ip: filter based on public ip address
:param string private_ip: filter based on private ip address
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
:returns: Returns a list of dictionaries representing the matching
virtual servers | [
"Retrieve",
"a",
"list",
"of",
"all",
"virtual",
"servers",
"on",
"the",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L83-L172 | train | 234,261 |
softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager.list_instances | def list_instances(self, tags=None, cpus=None, memory=None, hostname=None,
disk=None, datacenter=None, **kwargs):
"""Retrieve a list of all dedicated hosts on the account
:param list tags: filter based on list of tags
:param integer cpus: filter based on number of CPUS
:param integer memory: filter based on amount of memory
:param string hostname: filter based on hostname
:param string disk: filter based on disk
:param string datacenter: filter based on datacenter
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
:returns: Returns a list of dictionaries representing the matching dedicated host.
"""
if 'mask' not in kwargs:
items = [
'id',
'name',
'cpuCount',
'diskCapacity',
'memoryCapacity',
'datacenter',
'guestCount',
]
kwargs['mask'] = "mask[%s]" % ','.join(items)
_filter = utils.NestedDict(kwargs.get('filter') or {})
if tags:
_filter['dedicatedHosts']['tagReferences']['tag']['name'] = {
'operation': 'in',
'options': [{'name': 'data', 'value': tags}],
}
if hostname:
_filter['dedicatedHosts']['name'] = (
utils.query_filter(hostname)
)
if cpus:
_filter['dedicatedHosts']['cpuCount'] = utils.query_filter(cpus)
if disk:
_filter['dedicatedHosts']['diskCapacity'] = (
utils.query_filter(disk))
if memory:
_filter['dedicatedHosts']['memoryCapacity'] = (
utils.query_filter(memory))
if datacenter:
_filter['dedicatedHosts']['datacenter']['name'] = (
utils.query_filter(datacenter))
kwargs['filter'] = _filter.to_dict()
return self.account.getDedicatedHosts(**kwargs) | python | def list_instances(self, tags=None, cpus=None, memory=None, hostname=None,
disk=None, datacenter=None, **kwargs):
"""Retrieve a list of all dedicated hosts on the account
:param list tags: filter based on list of tags
:param integer cpus: filter based on number of CPUS
:param integer memory: filter based on amount of memory
:param string hostname: filter based on hostname
:param string disk: filter based on disk
:param string datacenter: filter based on datacenter
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
:returns: Returns a list of dictionaries representing the matching dedicated host.
"""
if 'mask' not in kwargs:
items = [
'id',
'name',
'cpuCount',
'diskCapacity',
'memoryCapacity',
'datacenter',
'guestCount',
]
kwargs['mask'] = "mask[%s]" % ','.join(items)
_filter = utils.NestedDict(kwargs.get('filter') or {})
if tags:
_filter['dedicatedHosts']['tagReferences']['tag']['name'] = {
'operation': 'in',
'options': [{'name': 'data', 'value': tags}],
}
if hostname:
_filter['dedicatedHosts']['name'] = (
utils.query_filter(hostname)
)
if cpus:
_filter['dedicatedHosts']['cpuCount'] = utils.query_filter(cpus)
if disk:
_filter['dedicatedHosts']['diskCapacity'] = (
utils.query_filter(disk))
if memory:
_filter['dedicatedHosts']['memoryCapacity'] = (
utils.query_filter(memory))
if datacenter:
_filter['dedicatedHosts']['datacenter']['name'] = (
utils.query_filter(datacenter))
kwargs['filter'] = _filter.to_dict()
return self.account.getDedicatedHosts(**kwargs) | [
"def",
"list_instances",
"(",
"self",
",",
"tags",
"=",
"None",
",",
"cpus",
"=",
"None",
",",
"memory",
"=",
"None",
",",
"hostname",
"=",
"None",
",",
"disk",
"=",
"None",
",",
"datacenter",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"items",
"=",
"[",
"'id'",
",",
"'name'",
",",
"'cpuCount'",
",",
"'diskCapacity'",
",",
"'memoryCapacity'",
",",
"'datacenter'",
",",
"'guestCount'",
",",
"]",
"kwargs",
"[",
"'mask'",
"]",
"=",
"\"mask[%s]\"",
"%",
"','",
".",
"join",
"(",
"items",
")",
"_filter",
"=",
"utils",
".",
"NestedDict",
"(",
"kwargs",
".",
"get",
"(",
"'filter'",
")",
"or",
"{",
"}",
")",
"if",
"tags",
":",
"_filter",
"[",
"'dedicatedHosts'",
"]",
"[",
"'tagReferences'",
"]",
"[",
"'tag'",
"]",
"[",
"'name'",
"]",
"=",
"{",
"'operation'",
":",
"'in'",
",",
"'options'",
":",
"[",
"{",
"'name'",
":",
"'data'",
",",
"'value'",
":",
"tags",
"}",
"]",
",",
"}",
"if",
"hostname",
":",
"_filter",
"[",
"'dedicatedHosts'",
"]",
"[",
"'name'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"hostname",
")",
")",
"if",
"cpus",
":",
"_filter",
"[",
"'dedicatedHosts'",
"]",
"[",
"'cpuCount'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"cpus",
")",
"if",
"disk",
":",
"_filter",
"[",
"'dedicatedHosts'",
"]",
"[",
"'diskCapacity'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"disk",
")",
")",
"if",
"memory",
":",
"_filter",
"[",
"'dedicatedHosts'",
"]",
"[",
"'memoryCapacity'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"memory",
")",
")",
"if",
"datacenter",
":",
"_filter",
"[",
"'dedicatedHosts'",
"]",
"[",
"'datacenter'",
"]",
"[",
"'name'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"datacenter",
")",
")",
"kwargs",
"[",
"'filter'",
"]",
"=",
"_filter",
".",
"to_dict",
"(",
")",
"return",
"self",
".",
"account",
".",
"getDedicatedHosts",
"(",
"*",
"*",
"kwargs",
")"
] | Retrieve a list of all dedicated hosts on the account
:param list tags: filter based on list of tags
:param integer cpus: filter based on number of CPUS
:param integer memory: filter based on amount of memory
:param string hostname: filter based on hostname
:param string disk: filter based on disk
:param string datacenter: filter based on datacenter
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
:returns: Returns a list of dictionaries representing the matching dedicated host. | [
"Retrieve",
"a",
"list",
"of",
"all",
"dedicated",
"hosts",
"on",
"the",
"account"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L174-L228 | train | 234,262 |
softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager.get_host | def get_host(self, host_id, **kwargs):
"""Get details about a dedicated host.
:param integer : the host ID
:returns: A dictionary containing host information.
Example::
# Print out host ID 12345.
dh = mgr.get_host(12345)
print dh
# Print out only name and backendRouter for instance 12345
object_mask = "mask[name,backendRouter[id]]"
dh = mgr.get_host(12345, mask=mask)
print dh
"""
if 'mask' not in kwargs:
kwargs['mask'] = ('''
id,
name,
cpuCount,
memoryCapacity,
diskCapacity,
createDate,
modifyDate,
backendRouter[
id,
hostname,
domain
],
billingItem[
id,
nextInvoiceTotalRecurringAmount,
children[
categoryCode,
nextInvoiceTotalRecurringAmount
],
orderItem[
id,
order.userRecord[
username
]
]
],
datacenter[
id,
name,
longName
],
guests[
id,
hostname,
domain,
uuid
],
guestCount
''')
return self.host.getObject(id=host_id, **kwargs) | python | def get_host(self, host_id, **kwargs):
"""Get details about a dedicated host.
:param integer : the host ID
:returns: A dictionary containing host information.
Example::
# Print out host ID 12345.
dh = mgr.get_host(12345)
print dh
# Print out only name and backendRouter for instance 12345
object_mask = "mask[name,backendRouter[id]]"
dh = mgr.get_host(12345, mask=mask)
print dh
"""
if 'mask' not in kwargs:
kwargs['mask'] = ('''
id,
name,
cpuCount,
memoryCapacity,
diskCapacity,
createDate,
modifyDate,
backendRouter[
id,
hostname,
domain
],
billingItem[
id,
nextInvoiceTotalRecurringAmount,
children[
categoryCode,
nextInvoiceTotalRecurringAmount
],
orderItem[
id,
order.userRecord[
username
]
]
],
datacenter[
id,
name,
longName
],
guests[
id,
hostname,
domain,
uuid
],
guestCount
''')
return self.host.getObject(id=host_id, **kwargs) | [
"def",
"get_host",
"(",
"self",
",",
"host_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'mask'",
"]",
"=",
"(",
"'''\n id,\n name,\n cpuCount,\n memoryCapacity,\n diskCapacity,\n createDate,\n modifyDate,\n backendRouter[\n id,\n hostname,\n domain\n ],\n billingItem[\n id,\n nextInvoiceTotalRecurringAmount,\n children[\n categoryCode,\n nextInvoiceTotalRecurringAmount\n ],\n orderItem[\n id,\n order.userRecord[\n username\n ]\n ]\n ],\n datacenter[\n id,\n name,\n longName\n ],\n guests[\n id,\n hostname,\n domain,\n uuid\n ],\n guestCount\n '''",
")",
"return",
"self",
".",
"host",
".",
"getObject",
"(",
"id",
"=",
"host_id",
",",
"*",
"*",
"kwargs",
")"
] | Get details about a dedicated host.
:param integer : the host ID
:returns: A dictionary containing host information.
Example::
# Print out host ID 12345.
dh = mgr.get_host(12345)
print dh
# Print out only name and backendRouter for instance 12345
object_mask = "mask[name,backendRouter[id]]"
dh = mgr.get_host(12345, mask=mask)
print dh | [
"Get",
"details",
"about",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L230-L290 | train | 234,263 |
softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager.place_order | def place_order(self, hostname, domain, location, flavor, hourly, router=None):
"""Places an order for a dedicated host.
See get_create_options() for valid arguments.
:param string hostname: server hostname
:param string domain: server domain name
:param string location: location (datacenter) name
:param boolean hourly: True if using hourly pricing (default).
False for monthly.
:param int router: an optional value for selecting a backend router
"""
create_options = self._generate_create_dict(hostname=hostname,
router=router,
domain=domain,
flavor=flavor,
datacenter=location,
hourly=hourly)
return self.client['Product_Order'].placeOrder(create_options) | python | def place_order(self, hostname, domain, location, flavor, hourly, router=None):
"""Places an order for a dedicated host.
See get_create_options() for valid arguments.
:param string hostname: server hostname
:param string domain: server domain name
:param string location: location (datacenter) name
:param boolean hourly: True if using hourly pricing (default).
False for monthly.
:param int router: an optional value for selecting a backend router
"""
create_options = self._generate_create_dict(hostname=hostname,
router=router,
domain=domain,
flavor=flavor,
datacenter=location,
hourly=hourly)
return self.client['Product_Order'].placeOrder(create_options) | [
"def",
"place_order",
"(",
"self",
",",
"hostname",
",",
"domain",
",",
"location",
",",
"flavor",
",",
"hourly",
",",
"router",
"=",
"None",
")",
":",
"create_options",
"=",
"self",
".",
"_generate_create_dict",
"(",
"hostname",
"=",
"hostname",
",",
"router",
"=",
"router",
",",
"domain",
"=",
"domain",
",",
"flavor",
"=",
"flavor",
",",
"datacenter",
"=",
"location",
",",
"hourly",
"=",
"hourly",
")",
"return",
"self",
".",
"client",
"[",
"'Product_Order'",
"]",
".",
"placeOrder",
"(",
"create_options",
")"
] | Places an order for a dedicated host.
See get_create_options() for valid arguments.
:param string hostname: server hostname
:param string domain: server domain name
:param string location: location (datacenter) name
:param boolean hourly: True if using hourly pricing (default).
False for monthly.
:param int router: an optional value for selecting a backend router | [
"Places",
"an",
"order",
"for",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L292-L311 | train | 234,264 |
softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager.verify_order | def verify_order(self, hostname, domain, location, hourly, flavor, router=None):
"""Verifies an order for a dedicated host.
See :func:`place_order` for a list of available options.
"""
create_options = self._generate_create_dict(hostname=hostname,
router=router,
domain=domain,
flavor=flavor,
datacenter=location,
hourly=hourly)
return self.client['Product_Order'].verifyOrder(create_options) | python | def verify_order(self, hostname, domain, location, hourly, flavor, router=None):
"""Verifies an order for a dedicated host.
See :func:`place_order` for a list of available options.
"""
create_options = self._generate_create_dict(hostname=hostname,
router=router,
domain=domain,
flavor=flavor,
datacenter=location,
hourly=hourly)
return self.client['Product_Order'].verifyOrder(create_options) | [
"def",
"verify_order",
"(",
"self",
",",
"hostname",
",",
"domain",
",",
"location",
",",
"hourly",
",",
"flavor",
",",
"router",
"=",
"None",
")",
":",
"create_options",
"=",
"self",
".",
"_generate_create_dict",
"(",
"hostname",
"=",
"hostname",
",",
"router",
"=",
"router",
",",
"domain",
"=",
"domain",
",",
"flavor",
"=",
"flavor",
",",
"datacenter",
"=",
"location",
",",
"hourly",
"=",
"hourly",
")",
"return",
"self",
".",
"client",
"[",
"'Product_Order'",
"]",
".",
"verifyOrder",
"(",
"create_options",
")"
] | Verifies an order for a dedicated host.
See :func:`place_order` for a list of available options. | [
"Verifies",
"an",
"order",
"for",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L313-L326 | train | 234,265 |
softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager._generate_create_dict | def _generate_create_dict(self,
hostname=None,
domain=None,
flavor=None,
router=None,
datacenter=None,
hourly=True):
"""Translates args into a dictionary for creating a dedicated host."""
package = self._get_package()
item = self._get_item(package, flavor)
location = self._get_location(package['regions'], datacenter)
price = self._get_price(item)
routers = self._get_backend_router(
location['location']['locationPackageDetails'], item)
router = self._get_default_router(routers, router)
hardware = {
'hostname': hostname,
'domain': domain,
'primaryBackendNetworkComponent': {
'router': {
'id': router
}
}
}
complex_type = "SoftLayer_Container_Product_Order_Virtual_DedicatedHost"
order = {
"complexType": complex_type,
"quantity": 1,
'location': location['keyname'],
'packageId': package['id'],
'prices': [{'id': price}],
'hardware': [hardware],
'useHourlyPricing': hourly,
}
return order | python | def _generate_create_dict(self,
hostname=None,
domain=None,
flavor=None,
router=None,
datacenter=None,
hourly=True):
"""Translates args into a dictionary for creating a dedicated host."""
package = self._get_package()
item = self._get_item(package, flavor)
location = self._get_location(package['regions'], datacenter)
price = self._get_price(item)
routers = self._get_backend_router(
location['location']['locationPackageDetails'], item)
router = self._get_default_router(routers, router)
hardware = {
'hostname': hostname,
'domain': domain,
'primaryBackendNetworkComponent': {
'router': {
'id': router
}
}
}
complex_type = "SoftLayer_Container_Product_Order_Virtual_DedicatedHost"
order = {
"complexType": complex_type,
"quantity": 1,
'location': location['keyname'],
'packageId': package['id'],
'prices': [{'id': price}],
'hardware': [hardware],
'useHourlyPricing': hourly,
}
return order | [
"def",
"_generate_create_dict",
"(",
"self",
",",
"hostname",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"flavor",
"=",
"None",
",",
"router",
"=",
"None",
",",
"datacenter",
"=",
"None",
",",
"hourly",
"=",
"True",
")",
":",
"package",
"=",
"self",
".",
"_get_package",
"(",
")",
"item",
"=",
"self",
".",
"_get_item",
"(",
"package",
",",
"flavor",
")",
"location",
"=",
"self",
".",
"_get_location",
"(",
"package",
"[",
"'regions'",
"]",
",",
"datacenter",
")",
"price",
"=",
"self",
".",
"_get_price",
"(",
"item",
")",
"routers",
"=",
"self",
".",
"_get_backend_router",
"(",
"location",
"[",
"'location'",
"]",
"[",
"'locationPackageDetails'",
"]",
",",
"item",
")",
"router",
"=",
"self",
".",
"_get_default_router",
"(",
"routers",
",",
"router",
")",
"hardware",
"=",
"{",
"'hostname'",
":",
"hostname",
",",
"'domain'",
":",
"domain",
",",
"'primaryBackendNetworkComponent'",
":",
"{",
"'router'",
":",
"{",
"'id'",
":",
"router",
"}",
"}",
"}",
"complex_type",
"=",
"\"SoftLayer_Container_Product_Order_Virtual_DedicatedHost\"",
"order",
"=",
"{",
"\"complexType\"",
":",
"complex_type",
",",
"\"quantity\"",
":",
"1",
",",
"'location'",
":",
"location",
"[",
"'keyname'",
"]",
",",
"'packageId'",
":",
"package",
"[",
"'id'",
"]",
",",
"'prices'",
":",
"[",
"{",
"'id'",
":",
"price",
"}",
"]",
",",
"'hardware'",
":",
"[",
"hardware",
"]",
",",
"'useHourlyPricing'",
":",
"hourly",
",",
"}",
"return",
"order"
] | Translates args into a dictionary for creating a dedicated host. | [
"Translates",
"args",
"into",
"a",
"dictionary",
"for",
"creating",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L328-L368 | train | 234,266 |
softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager.get_create_options | def get_create_options(self):
"""Returns valid options for ordering a dedicated host."""
package = self._get_package()
# Locations
locations = []
for region in package['regions']:
locations.append({
'name': region['location']['location']['longName'],
'key': region['location']['location']['name'],
})
# flavors
dedicated_host = []
for item in package['items']:
if item['itemCategory']['categoryCode'] == \
'dedicated_virtual_hosts':
dedicated_host.append({
'name': item['description'],
'key': item['keyName'],
})
return {'locations': locations, 'dedicated_host': dedicated_host} | python | def get_create_options(self):
"""Returns valid options for ordering a dedicated host."""
package = self._get_package()
# Locations
locations = []
for region in package['regions']:
locations.append({
'name': region['location']['location']['longName'],
'key': region['location']['location']['name'],
})
# flavors
dedicated_host = []
for item in package['items']:
if item['itemCategory']['categoryCode'] == \
'dedicated_virtual_hosts':
dedicated_host.append({
'name': item['description'],
'key': item['keyName'],
})
return {'locations': locations, 'dedicated_host': dedicated_host} | [
"def",
"get_create_options",
"(",
"self",
")",
":",
"package",
"=",
"self",
".",
"_get_package",
"(",
")",
"# Locations",
"locations",
"=",
"[",
"]",
"for",
"region",
"in",
"package",
"[",
"'regions'",
"]",
":",
"locations",
".",
"append",
"(",
"{",
"'name'",
":",
"region",
"[",
"'location'",
"]",
"[",
"'location'",
"]",
"[",
"'longName'",
"]",
",",
"'key'",
":",
"region",
"[",
"'location'",
"]",
"[",
"'location'",
"]",
"[",
"'name'",
"]",
",",
"}",
")",
"# flavors",
"dedicated_host",
"=",
"[",
"]",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"item",
"[",
"'itemCategory'",
"]",
"[",
"'categoryCode'",
"]",
"==",
"'dedicated_virtual_hosts'",
":",
"dedicated_host",
".",
"append",
"(",
"{",
"'name'",
":",
"item",
"[",
"'description'",
"]",
",",
"'key'",
":",
"item",
"[",
"'keyName'",
"]",
",",
"}",
")",
"return",
"{",
"'locations'",
":",
"locations",
",",
"'dedicated_host'",
":",
"dedicated_host",
"}"
] | Returns valid options for ordering a dedicated host. | [
"Returns",
"valid",
"options",
"for",
"ordering",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L400-L420 | train | 234,267 |
softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager._get_price | def _get_price(self, package):
"""Returns valid price for ordering a dedicated host."""
for price in package['prices']:
if not price.get('locationGroupId'):
return price['id']
raise SoftLayer.SoftLayerError("Could not find valid price") | python | def _get_price(self, package):
"""Returns valid price for ordering a dedicated host."""
for price in package['prices']:
if not price.get('locationGroupId'):
return price['id']
raise SoftLayer.SoftLayerError("Could not find valid price") | [
"def",
"_get_price",
"(",
"self",
",",
"package",
")",
":",
"for",
"price",
"in",
"package",
"[",
"'prices'",
"]",
":",
"if",
"not",
"price",
".",
"get",
"(",
"'locationGroupId'",
")",
":",
"return",
"price",
"[",
"'id'",
"]",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Could not find valid price\"",
")"
] | Returns valid price for ordering a dedicated host. | [
"Returns",
"valid",
"price",
"for",
"ordering",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L422-L429 | train | 234,268 |
softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager._get_item | def _get_item(self, package, flavor):
"""Returns the item for ordering a dedicated host."""
for item in package['items']:
if item['keyName'] == flavor:
return item
raise SoftLayer.SoftLayerError("Could not find valid item for: '%s'" % flavor) | python | def _get_item(self, package, flavor):
"""Returns the item for ordering a dedicated host."""
for item in package['items']:
if item['keyName'] == flavor:
return item
raise SoftLayer.SoftLayerError("Could not find valid item for: '%s'" % flavor) | [
"def",
"_get_item",
"(",
"self",
",",
"package",
",",
"flavor",
")",
":",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"item",
"[",
"'keyName'",
"]",
"==",
"flavor",
":",
"return",
"item",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Could not find valid item for: '%s'\"",
"%",
"flavor",
")"
] | Returns the item for ordering a dedicated host. | [
"Returns",
"the",
"item",
"for",
"ordering",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L431-L438 | train | 234,269 |
softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager._get_backend_router | def _get_backend_router(self, locations, item):
"""Returns valid router options for ordering a dedicated host."""
mask = '''
id,
hostname
'''
cpu_count = item['capacity']
for capacity in item['bundleItems']:
for category in capacity['categories']:
if category['categoryCode'] == 'dedicated_host_ram':
mem_capacity = capacity['capacity']
if category['categoryCode'] == 'dedicated_host_disk':
disk_capacity = capacity['capacity']
for hardwareComponent in item['bundleItems']:
if hardwareComponent['keyName'].find("GPU") != -1:
hardwareComponentType = hardwareComponent['hardwareGenericComponentModel']['hardwareComponentType']
gpuComponents = [
{
'hardwareComponentModel': {
'hardwareGenericComponentModel': {
'id': hardwareComponent['hardwareGenericComponentModel']['id'],
'hardwareComponentType': {
'keyName': hardwareComponentType['keyName']
}
}
}
},
{
'hardwareComponentModel': {
'hardwareGenericComponentModel': {
'id': hardwareComponent['hardwareGenericComponentModel']['id'],
'hardwareComponentType': {
'keyName': hardwareComponentType['keyName']
}
}
}
}
]
if locations is not None:
for location in locations:
if location['locationId'] is not None:
loc_id = location['locationId']
host = {
'cpuCount': cpu_count,
'memoryCapacity': mem_capacity,
'diskCapacity': disk_capacity,
'datacenter': {
'id': loc_id
}
}
if item['keyName'].find("GPU") != -1:
host['pciDevices'] = gpuComponents
routers = self.host.getAvailableRouters(host, mask=mask)
return routers
raise SoftLayer.SoftLayerError("Could not find available routers") | python | def _get_backend_router(self, locations, item):
"""Returns valid router options for ordering a dedicated host."""
mask = '''
id,
hostname
'''
cpu_count = item['capacity']
for capacity in item['bundleItems']:
for category in capacity['categories']:
if category['categoryCode'] == 'dedicated_host_ram':
mem_capacity = capacity['capacity']
if category['categoryCode'] == 'dedicated_host_disk':
disk_capacity = capacity['capacity']
for hardwareComponent in item['bundleItems']:
if hardwareComponent['keyName'].find("GPU") != -1:
hardwareComponentType = hardwareComponent['hardwareGenericComponentModel']['hardwareComponentType']
gpuComponents = [
{
'hardwareComponentModel': {
'hardwareGenericComponentModel': {
'id': hardwareComponent['hardwareGenericComponentModel']['id'],
'hardwareComponentType': {
'keyName': hardwareComponentType['keyName']
}
}
}
},
{
'hardwareComponentModel': {
'hardwareGenericComponentModel': {
'id': hardwareComponent['hardwareGenericComponentModel']['id'],
'hardwareComponentType': {
'keyName': hardwareComponentType['keyName']
}
}
}
}
]
if locations is not None:
for location in locations:
if location['locationId'] is not None:
loc_id = location['locationId']
host = {
'cpuCount': cpu_count,
'memoryCapacity': mem_capacity,
'diskCapacity': disk_capacity,
'datacenter': {
'id': loc_id
}
}
if item['keyName'].find("GPU") != -1:
host['pciDevices'] = gpuComponents
routers = self.host.getAvailableRouters(host, mask=mask)
return routers
raise SoftLayer.SoftLayerError("Could not find available routers") | [
"def",
"_get_backend_router",
"(",
"self",
",",
"locations",
",",
"item",
")",
":",
"mask",
"=",
"'''\n id,\n hostname\n '''",
"cpu_count",
"=",
"item",
"[",
"'capacity'",
"]",
"for",
"capacity",
"in",
"item",
"[",
"'bundleItems'",
"]",
":",
"for",
"category",
"in",
"capacity",
"[",
"'categories'",
"]",
":",
"if",
"category",
"[",
"'categoryCode'",
"]",
"==",
"'dedicated_host_ram'",
":",
"mem_capacity",
"=",
"capacity",
"[",
"'capacity'",
"]",
"if",
"category",
"[",
"'categoryCode'",
"]",
"==",
"'dedicated_host_disk'",
":",
"disk_capacity",
"=",
"capacity",
"[",
"'capacity'",
"]",
"for",
"hardwareComponent",
"in",
"item",
"[",
"'bundleItems'",
"]",
":",
"if",
"hardwareComponent",
"[",
"'keyName'",
"]",
".",
"find",
"(",
"\"GPU\"",
")",
"!=",
"-",
"1",
":",
"hardwareComponentType",
"=",
"hardwareComponent",
"[",
"'hardwareGenericComponentModel'",
"]",
"[",
"'hardwareComponentType'",
"]",
"gpuComponents",
"=",
"[",
"{",
"'hardwareComponentModel'",
":",
"{",
"'hardwareGenericComponentModel'",
":",
"{",
"'id'",
":",
"hardwareComponent",
"[",
"'hardwareGenericComponentModel'",
"]",
"[",
"'id'",
"]",
",",
"'hardwareComponentType'",
":",
"{",
"'keyName'",
":",
"hardwareComponentType",
"[",
"'keyName'",
"]",
"}",
"}",
"}",
"}",
",",
"{",
"'hardwareComponentModel'",
":",
"{",
"'hardwareGenericComponentModel'",
":",
"{",
"'id'",
":",
"hardwareComponent",
"[",
"'hardwareGenericComponentModel'",
"]",
"[",
"'id'",
"]",
",",
"'hardwareComponentType'",
":",
"{",
"'keyName'",
":",
"hardwareComponentType",
"[",
"'keyName'",
"]",
"}",
"}",
"}",
"}",
"]",
"if",
"locations",
"is",
"not",
"None",
":",
"for",
"location",
"in",
"locations",
":",
"if",
"location",
"[",
"'locationId'",
"]",
"is",
"not",
"None",
":",
"loc_id",
"=",
"location",
"[",
"'locationId'",
"]",
"host",
"=",
"{",
"'cpuCount'",
":",
"cpu_count",
",",
"'memoryCapacity'",
":",
"mem_capacity",
",",
"'diskCapacity'",
":",
"disk_capacity",
",",
"'datacenter'",
":",
"{",
"'id'",
":",
"loc_id",
"}",
"}",
"if",
"item",
"[",
"'keyName'",
"]",
".",
"find",
"(",
"\"GPU\"",
")",
"!=",
"-",
"1",
":",
"host",
"[",
"'pciDevices'",
"]",
"=",
"gpuComponents",
"routers",
"=",
"self",
".",
"host",
".",
"getAvailableRouters",
"(",
"host",
",",
"mask",
"=",
"mask",
")",
"return",
"routers",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Could not find available routers\"",
")"
] | Returns valid router options for ordering a dedicated host. | [
"Returns",
"valid",
"router",
"options",
"for",
"ordering",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L440-L498 | train | 234,270 |
softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager._get_default_router | def _get_default_router(self, routers, router_name=None):
"""Returns the default router for ordering a dedicated host."""
if router_name is None:
for router in routers:
if router['id'] is not None:
return router['id']
else:
for router in routers:
if router['hostname'] == router_name:
return router['id']
raise SoftLayer.SoftLayerError("Could not find valid default router") | python | def _get_default_router(self, routers, router_name=None):
"""Returns the default router for ordering a dedicated host."""
if router_name is None:
for router in routers:
if router['id'] is not None:
return router['id']
else:
for router in routers:
if router['hostname'] == router_name:
return router['id']
raise SoftLayer.SoftLayerError("Could not find valid default router") | [
"def",
"_get_default_router",
"(",
"self",
",",
"routers",
",",
"router_name",
"=",
"None",
")",
":",
"if",
"router_name",
"is",
"None",
":",
"for",
"router",
"in",
"routers",
":",
"if",
"router",
"[",
"'id'",
"]",
"is",
"not",
"None",
":",
"return",
"router",
"[",
"'id'",
"]",
"else",
":",
"for",
"router",
"in",
"routers",
":",
"if",
"router",
"[",
"'hostname'",
"]",
"==",
"router_name",
":",
"return",
"router",
"[",
"'id'",
"]",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Could not find valid default router\"",
")"
] | Returns the default router for ordering a dedicated host. | [
"Returns",
"the",
"default",
"router",
"for",
"ordering",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L500-L511 | train | 234,271 |
softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager.get_router_options | def get_router_options(self, datacenter=None, flavor=None):
"""Returns available backend routers for the dedicated host."""
package = self._get_package()
location = self._get_location(package['regions'], datacenter)
item = self._get_item(package, flavor)
return self._get_backend_router(location['location']['locationPackageDetails'], item) | python | def get_router_options(self, datacenter=None, flavor=None):
"""Returns available backend routers for the dedicated host."""
package = self._get_package()
location = self._get_location(package['regions'], datacenter)
item = self._get_item(package, flavor)
return self._get_backend_router(location['location']['locationPackageDetails'], item) | [
"def",
"get_router_options",
"(",
"self",
",",
"datacenter",
"=",
"None",
",",
"flavor",
"=",
"None",
")",
":",
"package",
"=",
"self",
".",
"_get_package",
"(",
")",
"location",
"=",
"self",
".",
"_get_location",
"(",
"package",
"[",
"'regions'",
"]",
",",
"datacenter",
")",
"item",
"=",
"self",
".",
"_get_item",
"(",
"package",
",",
"flavor",
")",
"return",
"self",
".",
"_get_backend_router",
"(",
"location",
"[",
"'location'",
"]",
"[",
"'locationPackageDetails'",
"]",
",",
"item",
")"
] | Returns available backend routers for the dedicated host. | [
"Returns",
"available",
"backend",
"routers",
"for",
"the",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L513-L520 | train | 234,272 |
softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager._delete_guest | def _delete_guest(self, guest_id):
"""Deletes a guest and returns 'Cancelled' or and Exception message"""
msg = 'Cancelled'
try:
self.guest.deleteObject(id=guest_id)
except SoftLayer.SoftLayerAPIError as e:
msg = 'Exception: ' + e.faultString
return msg | python | def _delete_guest(self, guest_id):
"""Deletes a guest and returns 'Cancelled' or and Exception message"""
msg = 'Cancelled'
try:
self.guest.deleteObject(id=guest_id)
except SoftLayer.SoftLayerAPIError as e:
msg = 'Exception: ' + e.faultString
return msg | [
"def",
"_delete_guest",
"(",
"self",
",",
"guest_id",
")",
":",
"msg",
"=",
"'Cancelled'",
"try",
":",
"self",
".",
"guest",
".",
"deleteObject",
"(",
"id",
"=",
"guest_id",
")",
"except",
"SoftLayer",
".",
"SoftLayerAPIError",
"as",
"e",
":",
"msg",
"=",
"'Exception: '",
"+",
"e",
".",
"faultString",
"return",
"msg"
] | Deletes a guest and returns 'Cancelled' or and Exception message | [
"Deletes",
"a",
"guest",
"and",
"returns",
"Cancelled",
"or",
"and",
"Exception",
"message"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L522-L530 | train | 234,273 |
softlayer/softlayer-python | SoftLayer/shell/completer.py | _click_autocomplete | def _click_autocomplete(root, text):
"""Completer generator for click applications."""
try:
parts = shlex.split(text)
except ValueError:
raise StopIteration
location, incomplete = _click_resolve_command(root, parts)
if not text.endswith(' ') and not incomplete and text:
raise StopIteration
if incomplete and not incomplete[0:2].isalnum():
for param in location.params:
if not isinstance(param, click.Option):
continue
for opt in itertools.chain(param.opts, param.secondary_opts):
if opt.startswith(incomplete):
yield completion.Completion(opt, -len(incomplete), display_meta=param.help)
elif isinstance(location, (click.MultiCommand, click.core.Group)):
ctx = click.Context(location)
commands = location.list_commands(ctx)
for command in commands:
if command.startswith(incomplete):
cmd = location.get_command(ctx, command)
yield completion.Completion(command, -len(incomplete), display_meta=cmd.short_help) | python | def _click_autocomplete(root, text):
"""Completer generator for click applications."""
try:
parts = shlex.split(text)
except ValueError:
raise StopIteration
location, incomplete = _click_resolve_command(root, parts)
if not text.endswith(' ') and not incomplete and text:
raise StopIteration
if incomplete and not incomplete[0:2].isalnum():
for param in location.params:
if not isinstance(param, click.Option):
continue
for opt in itertools.chain(param.opts, param.secondary_opts):
if opt.startswith(incomplete):
yield completion.Completion(opt, -len(incomplete), display_meta=param.help)
elif isinstance(location, (click.MultiCommand, click.core.Group)):
ctx = click.Context(location)
commands = location.list_commands(ctx)
for command in commands:
if command.startswith(incomplete):
cmd = location.get_command(ctx, command)
yield completion.Completion(command, -len(incomplete), display_meta=cmd.short_help) | [
"def",
"_click_autocomplete",
"(",
"root",
",",
"text",
")",
":",
"try",
":",
"parts",
"=",
"shlex",
".",
"split",
"(",
"text",
")",
"except",
"ValueError",
":",
"raise",
"StopIteration",
"location",
",",
"incomplete",
"=",
"_click_resolve_command",
"(",
"root",
",",
"parts",
")",
"if",
"not",
"text",
".",
"endswith",
"(",
"' '",
")",
"and",
"not",
"incomplete",
"and",
"text",
":",
"raise",
"StopIteration",
"if",
"incomplete",
"and",
"not",
"incomplete",
"[",
"0",
":",
"2",
"]",
".",
"isalnum",
"(",
")",
":",
"for",
"param",
"in",
"location",
".",
"params",
":",
"if",
"not",
"isinstance",
"(",
"param",
",",
"click",
".",
"Option",
")",
":",
"continue",
"for",
"opt",
"in",
"itertools",
".",
"chain",
"(",
"param",
".",
"opts",
",",
"param",
".",
"secondary_opts",
")",
":",
"if",
"opt",
".",
"startswith",
"(",
"incomplete",
")",
":",
"yield",
"completion",
".",
"Completion",
"(",
"opt",
",",
"-",
"len",
"(",
"incomplete",
")",
",",
"display_meta",
"=",
"param",
".",
"help",
")",
"elif",
"isinstance",
"(",
"location",
",",
"(",
"click",
".",
"MultiCommand",
",",
"click",
".",
"core",
".",
"Group",
")",
")",
":",
"ctx",
"=",
"click",
".",
"Context",
"(",
"location",
")",
"commands",
"=",
"location",
".",
"list_commands",
"(",
"ctx",
")",
"for",
"command",
"in",
"commands",
":",
"if",
"command",
".",
"startswith",
"(",
"incomplete",
")",
":",
"cmd",
"=",
"location",
".",
"get_command",
"(",
"ctx",
",",
"command",
")",
"yield",
"completion",
".",
"Completion",
"(",
"command",
",",
"-",
"len",
"(",
"incomplete",
")",
",",
"display_meta",
"=",
"cmd",
".",
"short_help",
")"
] | Completer generator for click applications. | [
"Completer",
"generator",
"for",
"click",
"applications",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/shell/completer.py#L28-L54 | train | 234,274 |
softlayer/softlayer-python | SoftLayer/shell/completer.py | _click_resolve_command | def _click_resolve_command(root, parts):
"""Return the click command and the left over text given some vargs."""
location = root
incomplete = ''
for part in parts:
incomplete = part
if not part[0:2].isalnum():
continue
try:
next_location = location.get_command(click.Context(location),
part)
if next_location is not None:
location = next_location
incomplete = ''
except AttributeError:
break
return location, incomplete | python | def _click_resolve_command(root, parts):
"""Return the click command and the left over text given some vargs."""
location = root
incomplete = ''
for part in parts:
incomplete = part
if not part[0:2].isalnum():
continue
try:
next_location = location.get_command(click.Context(location),
part)
if next_location is not None:
location = next_location
incomplete = ''
except AttributeError:
break
return location, incomplete | [
"def",
"_click_resolve_command",
"(",
"root",
",",
"parts",
")",
":",
"location",
"=",
"root",
"incomplete",
"=",
"''",
"for",
"part",
"in",
"parts",
":",
"incomplete",
"=",
"part",
"if",
"not",
"part",
"[",
"0",
":",
"2",
"]",
".",
"isalnum",
"(",
")",
":",
"continue",
"try",
":",
"next_location",
"=",
"location",
".",
"get_command",
"(",
"click",
".",
"Context",
"(",
"location",
")",
",",
"part",
")",
"if",
"next_location",
"is",
"not",
"None",
":",
"location",
"=",
"next_location",
"incomplete",
"=",
"''",
"except",
"AttributeError",
":",
"break",
"return",
"location",
",",
"incomplete"
] | Return the click command and the left over text given some vargs. | [
"Return",
"the",
"click",
"command",
"and",
"the",
"left",
"over",
"text",
"given",
"some",
"vargs",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/shell/completer.py#L57-L75 | train | 234,275 |
softlayer/softlayer-python | SoftLayer/CLI/user/edit_permissions.py | cli | def cli(env, identifier, enable, permission, from_user):
"""Enable or Disable specific permissions."""
mgr = SoftLayer.UserManager(env.client)
user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
result = False
if from_user:
from_user_id = helpers.resolve_id(mgr.resolve_ids, from_user, 'username')
result = mgr.permissions_from_user(user_id, from_user_id)
elif enable:
result = mgr.add_permissions(user_id, permission)
else:
result = mgr.remove_permissions(user_id, permission)
if result:
click.secho("Permissions updated successfully: %s" % ", ".join(permission), fg='green')
else:
click.secho("Failed to update permissions: %s" % ", ".join(permission), fg='red') | python | def cli(env, identifier, enable, permission, from_user):
"""Enable or Disable specific permissions."""
mgr = SoftLayer.UserManager(env.client)
user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
result = False
if from_user:
from_user_id = helpers.resolve_id(mgr.resolve_ids, from_user, 'username')
result = mgr.permissions_from_user(user_id, from_user_id)
elif enable:
result = mgr.add_permissions(user_id, permission)
else:
result = mgr.remove_permissions(user_id, permission)
if result:
click.secho("Permissions updated successfully: %s" % ", ".join(permission), fg='green')
else:
click.secho("Failed to update permissions: %s" % ", ".join(permission), fg='red') | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"enable",
",",
"permission",
",",
"from_user",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"UserManager",
"(",
"env",
".",
"client",
")",
"user_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'username'",
")",
"result",
"=",
"False",
"if",
"from_user",
":",
"from_user_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"from_user",
",",
"'username'",
")",
"result",
"=",
"mgr",
".",
"permissions_from_user",
"(",
"user_id",
",",
"from_user_id",
")",
"elif",
"enable",
":",
"result",
"=",
"mgr",
".",
"add_permissions",
"(",
"user_id",
",",
"permission",
")",
"else",
":",
"result",
"=",
"mgr",
".",
"remove_permissions",
"(",
"user_id",
",",
"permission",
")",
"if",
"result",
":",
"click",
".",
"secho",
"(",
"\"Permissions updated successfully: %s\"",
"%",
"\", \"",
".",
"join",
"(",
"permission",
")",
",",
"fg",
"=",
"'green'",
")",
"else",
":",
"click",
".",
"secho",
"(",
"\"Failed to update permissions: %s\"",
"%",
"\", \"",
".",
"join",
"(",
"permission",
")",
",",
"fg",
"=",
"'red'",
")"
] | Enable or Disable specific permissions. | [
"Enable",
"or",
"Disable",
"specific",
"permissions",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/edit_permissions.py#L22-L38 | train | 234,276 |
softlayer/softlayer-python | SoftLayer/managers/cdn.py | CDNManager.list_accounts | def list_accounts(self):
"""Lists CDN accounts for the active user."""
account = self.client['Account']
mask = 'cdnAccounts[%s]' % ', '.join(['id',
'createDate',
'cdnAccountName',
'cdnSolutionName',
'cdnAccountNote',
'status'])
return account.getObject(mask=mask).get('cdnAccounts', []) | python | def list_accounts(self):
"""Lists CDN accounts for the active user."""
account = self.client['Account']
mask = 'cdnAccounts[%s]' % ', '.join(['id',
'createDate',
'cdnAccountName',
'cdnSolutionName',
'cdnAccountNote',
'status'])
return account.getObject(mask=mask).get('cdnAccounts', []) | [
"def",
"list_accounts",
"(",
"self",
")",
":",
"account",
"=",
"self",
".",
"client",
"[",
"'Account'",
"]",
"mask",
"=",
"'cdnAccounts[%s]'",
"%",
"', '",
".",
"join",
"(",
"[",
"'id'",
",",
"'createDate'",
",",
"'cdnAccountName'",
",",
"'cdnSolutionName'",
",",
"'cdnAccountNote'",
",",
"'status'",
"]",
")",
"return",
"account",
".",
"getObject",
"(",
"mask",
"=",
"mask",
")",
".",
"get",
"(",
"'cdnAccounts'",
",",
"[",
"]",
")"
] | Lists CDN accounts for the active user. | [
"Lists",
"CDN",
"accounts",
"for",
"the",
"active",
"user",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/cdn.py#L30-L40 | train | 234,277 |
softlayer/softlayer-python | SoftLayer/managers/cdn.py | CDNManager.get_account | def get_account(self, account_id, **kwargs):
"""Retrieves a CDN account with the specified account ID.
:param account_id int: the numeric ID associated with the CDN account.
:param dict \\*\\*kwargs: additional arguments to include in the object
mask.
"""
if 'mask' not in kwargs:
kwargs['mask'] = 'status'
return self.account.getObject(id=account_id, **kwargs) | python | def get_account(self, account_id, **kwargs):
"""Retrieves a CDN account with the specified account ID.
:param account_id int: the numeric ID associated with the CDN account.
:param dict \\*\\*kwargs: additional arguments to include in the object
mask.
"""
if 'mask' not in kwargs:
kwargs['mask'] = 'status'
return self.account.getObject(id=account_id, **kwargs) | [
"def",
"get_account",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'mask'",
"]",
"=",
"'status'",
"return",
"self",
".",
"account",
".",
"getObject",
"(",
"id",
"=",
"account_id",
",",
"*",
"*",
"kwargs",
")"
] | Retrieves a CDN account with the specified account ID.
:param account_id int: the numeric ID associated with the CDN account.
:param dict \\*\\*kwargs: additional arguments to include in the object
mask. | [
"Retrieves",
"a",
"CDN",
"account",
"with",
"the",
"specified",
"account",
"ID",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/cdn.py#L42-L53 | train | 234,278 |
softlayer/softlayer-python | SoftLayer/managers/cdn.py | CDNManager.get_origins | def get_origins(self, account_id, **kwargs):
"""Retrieves list of origin pull mappings for a specified CDN account.
:param account_id int: the numeric ID associated with the CDN account.
:param dict \\*\\*kwargs: additional arguments to include in the object
mask.
"""
return self.account.getOriginPullMappingInformation(id=account_id,
**kwargs) | python | def get_origins(self, account_id, **kwargs):
"""Retrieves list of origin pull mappings for a specified CDN account.
:param account_id int: the numeric ID associated with the CDN account.
:param dict \\*\\*kwargs: additional arguments to include in the object
mask.
"""
return self.account.getOriginPullMappingInformation(id=account_id,
**kwargs) | [
"def",
"get_origins",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"account",
".",
"getOriginPullMappingInformation",
"(",
"id",
"=",
"account_id",
",",
"*",
"*",
"kwargs",
")"
] | Retrieves list of origin pull mappings for a specified CDN account.
:param account_id int: the numeric ID associated with the CDN account.
:param dict \\*\\*kwargs: additional arguments to include in the object
mask. | [
"Retrieves",
"list",
"of",
"origin",
"pull",
"mappings",
"for",
"a",
"specified",
"CDN",
"account",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/cdn.py#L55-L64 | train | 234,279 |
softlayer/softlayer-python | SoftLayer/managers/cdn.py | CDNManager.add_origin | def add_origin(self, account_id, media_type, origin_url, cname=None,
secure=False):
"""Adds an original pull mapping to an origin-pull.
:param int account_id: the numeric ID associated with the CDN account.
:param string media_type: the media type/protocol associated with this
origin pull mapping; valid values are HTTP,
FLASH, and WM.
:param string origin_url: the base URL from which content should be
pulled.
:param string cname: an optional CNAME that should be associated with
this origin pull rule; only the hostname should be
included (i.e., no 'http://', directories, etc.).
:param boolean secure: specifies whether this is an SSL origin pull
rule, if SSL is enabled on your account
(defaults to false).
"""
config = {'mediaType': media_type,
'originUrl': origin_url,
'isSecureContent': secure}
if cname:
config['cname'] = cname
return self.account.createOriginPullMapping(config, id=account_id) | python | def add_origin(self, account_id, media_type, origin_url, cname=None,
secure=False):
"""Adds an original pull mapping to an origin-pull.
:param int account_id: the numeric ID associated with the CDN account.
:param string media_type: the media type/protocol associated with this
origin pull mapping; valid values are HTTP,
FLASH, and WM.
:param string origin_url: the base URL from which content should be
pulled.
:param string cname: an optional CNAME that should be associated with
this origin pull rule; only the hostname should be
included (i.e., no 'http://', directories, etc.).
:param boolean secure: specifies whether this is an SSL origin pull
rule, if SSL is enabled on your account
(defaults to false).
"""
config = {'mediaType': media_type,
'originUrl': origin_url,
'isSecureContent': secure}
if cname:
config['cname'] = cname
return self.account.createOriginPullMapping(config, id=account_id) | [
"def",
"add_origin",
"(",
"self",
",",
"account_id",
",",
"media_type",
",",
"origin_url",
",",
"cname",
"=",
"None",
",",
"secure",
"=",
"False",
")",
":",
"config",
"=",
"{",
"'mediaType'",
":",
"media_type",
",",
"'originUrl'",
":",
"origin_url",
",",
"'isSecureContent'",
":",
"secure",
"}",
"if",
"cname",
":",
"config",
"[",
"'cname'",
"]",
"=",
"cname",
"return",
"self",
".",
"account",
".",
"createOriginPullMapping",
"(",
"config",
",",
"id",
"=",
"account_id",
")"
] | Adds an original pull mapping to an origin-pull.
:param int account_id: the numeric ID associated with the CDN account.
:param string media_type: the media type/protocol associated with this
origin pull mapping; valid values are HTTP,
FLASH, and WM.
:param string origin_url: the base URL from which content should be
pulled.
:param string cname: an optional CNAME that should be associated with
this origin pull rule; only the hostname should be
included (i.e., no 'http://', directories, etc.).
:param boolean secure: specifies whether this is an SSL origin pull
rule, if SSL is enabled on your account
(defaults to false). | [
"Adds",
"an",
"original",
"pull",
"mapping",
"to",
"an",
"origin",
"-",
"pull",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/cdn.py#L66-L91 | train | 234,280 |
softlayer/softlayer-python | SoftLayer/managers/cdn.py | CDNManager.remove_origin | def remove_origin(self, account_id, origin_id):
"""Removes an origin pull mapping with the given origin pull ID.
:param int account_id: the CDN account ID from which the mapping should
be deleted.
:param int origin_id: the origin pull mapping ID to delete.
"""
return self.account.deleteOriginPullRule(origin_id, id=account_id) | python | def remove_origin(self, account_id, origin_id):
"""Removes an origin pull mapping with the given origin pull ID.
:param int account_id: the CDN account ID from which the mapping should
be deleted.
:param int origin_id: the origin pull mapping ID to delete.
"""
return self.account.deleteOriginPullRule(origin_id, id=account_id) | [
"def",
"remove_origin",
"(",
"self",
",",
"account_id",
",",
"origin_id",
")",
":",
"return",
"self",
".",
"account",
".",
"deleteOriginPullRule",
"(",
"origin_id",
",",
"id",
"=",
"account_id",
")"
] | Removes an origin pull mapping with the given origin pull ID.
:param int account_id: the CDN account ID from which the mapping should
be deleted.
:param int origin_id: the origin pull mapping ID to delete. | [
"Removes",
"an",
"origin",
"pull",
"mapping",
"with",
"the",
"given",
"origin",
"pull",
"ID",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/cdn.py#L93-L101 | train | 234,281 |
softlayer/softlayer-python | SoftLayer/managers/cdn.py | CDNManager.load_content | def load_content(self, account_id, urls):
"""Prefetches one or more URLs to the CDN edge nodes.
:param int account_id: the CDN account ID into which content should be
preloaded.
:param urls: a string or a list of strings representing the CDN URLs
that should be pre-loaded.
:returns: true if all load requests were successfully submitted;
otherwise, returns the first error encountered.
"""
if isinstance(urls, six.string_types):
urls = [urls]
for i in range(0, len(urls), MAX_URLS_PER_LOAD):
result = self.account.loadContent(urls[i:i + MAX_URLS_PER_LOAD],
id=account_id)
if not result:
return result
return True | python | def load_content(self, account_id, urls):
"""Prefetches one or more URLs to the CDN edge nodes.
:param int account_id: the CDN account ID into which content should be
preloaded.
:param urls: a string or a list of strings representing the CDN URLs
that should be pre-loaded.
:returns: true if all load requests were successfully submitted;
otherwise, returns the first error encountered.
"""
if isinstance(urls, six.string_types):
urls = [urls]
for i in range(0, len(urls), MAX_URLS_PER_LOAD):
result = self.account.loadContent(urls[i:i + MAX_URLS_PER_LOAD],
id=account_id)
if not result:
return result
return True | [
"def",
"load_content",
"(",
"self",
",",
"account_id",
",",
"urls",
")",
":",
"if",
"isinstance",
"(",
"urls",
",",
"six",
".",
"string_types",
")",
":",
"urls",
"=",
"[",
"urls",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"urls",
")",
",",
"MAX_URLS_PER_LOAD",
")",
":",
"result",
"=",
"self",
".",
"account",
".",
"loadContent",
"(",
"urls",
"[",
"i",
":",
"i",
"+",
"MAX_URLS_PER_LOAD",
"]",
",",
"id",
"=",
"account_id",
")",
"if",
"not",
"result",
":",
"return",
"result",
"return",
"True"
] | Prefetches one or more URLs to the CDN edge nodes.
:param int account_id: the CDN account ID into which content should be
preloaded.
:param urls: a string or a list of strings representing the CDN URLs
that should be pre-loaded.
:returns: true if all load requests were successfully submitted;
otherwise, returns the first error encountered. | [
"Prefetches",
"one",
"or",
"more",
"URLs",
"to",
"the",
"CDN",
"edge",
"nodes",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/cdn.py#L103-L123 | train | 234,282 |
softlayer/softlayer-python | SoftLayer/managers/cdn.py | CDNManager.purge_content | def purge_content(self, account_id, urls):
"""Purges one or more URLs from the CDN edge nodes.
:param int account_id: the CDN account ID from which content should
be purged.
:param urls: a string or a list of strings representing the CDN URLs
that should be purged.
:returns: a list of SoftLayer_Container_Network_ContentDelivery_PurgeService_Response objects
which indicates if the purge for each url was SUCCESS, FAILED or INVALID_URL.
"""
if isinstance(urls, six.string_types):
urls = [urls]
content_list = []
for i in range(0, len(urls), MAX_URLS_PER_PURGE):
content = self.account.purgeCache(urls[i:i + MAX_URLS_PER_PURGE], id=account_id)
content_list.extend(content)
return content_list | python | def purge_content(self, account_id, urls):
"""Purges one or more URLs from the CDN edge nodes.
:param int account_id: the CDN account ID from which content should
be purged.
:param urls: a string or a list of strings representing the CDN URLs
that should be purged.
:returns: a list of SoftLayer_Container_Network_ContentDelivery_PurgeService_Response objects
which indicates if the purge for each url was SUCCESS, FAILED or INVALID_URL.
"""
if isinstance(urls, six.string_types):
urls = [urls]
content_list = []
for i in range(0, len(urls), MAX_URLS_PER_PURGE):
content = self.account.purgeCache(urls[i:i + MAX_URLS_PER_PURGE], id=account_id)
content_list.extend(content)
return content_list | [
"def",
"purge_content",
"(",
"self",
",",
"account_id",
",",
"urls",
")",
":",
"if",
"isinstance",
"(",
"urls",
",",
"six",
".",
"string_types",
")",
":",
"urls",
"=",
"[",
"urls",
"]",
"content_list",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"urls",
")",
",",
"MAX_URLS_PER_PURGE",
")",
":",
"content",
"=",
"self",
".",
"account",
".",
"purgeCache",
"(",
"urls",
"[",
"i",
":",
"i",
"+",
"MAX_URLS_PER_PURGE",
"]",
",",
"id",
"=",
"account_id",
")",
"content_list",
".",
"extend",
"(",
"content",
")",
"return",
"content_list"
] | Purges one or more URLs from the CDN edge nodes.
:param int account_id: the CDN account ID from which content should
be purged.
:param urls: a string or a list of strings representing the CDN URLs
that should be purged.
:returns: a list of SoftLayer_Container_Network_ContentDelivery_PurgeService_Response objects
which indicates if the purge for each url was SUCCESS, FAILED or INVALID_URL. | [
"Purges",
"one",
"or",
"more",
"URLs",
"from",
"the",
"CDN",
"edge",
"nodes",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/cdn.py#L125-L144 | train | 234,283 |
softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.get_lb_pkgs | def get_lb_pkgs(self):
"""Retrieves the local load balancer packages.
:returns: A dictionary containing the load balancer packages
"""
_filter = {'items': {'description':
utils.query_filter('*Load Balancer*')}}
packages = self.prod_pkg.getItems(id=0, filter=_filter)
pkgs = []
for package in packages:
if not package['description'].startswith('Global'):
pkgs.append(package)
return pkgs | python | def get_lb_pkgs(self):
"""Retrieves the local load balancer packages.
:returns: A dictionary containing the load balancer packages
"""
_filter = {'items': {'description':
utils.query_filter('*Load Balancer*')}}
packages = self.prod_pkg.getItems(id=0, filter=_filter)
pkgs = []
for package in packages:
if not package['description'].startswith('Global'):
pkgs.append(package)
return pkgs | [
"def",
"get_lb_pkgs",
"(",
"self",
")",
":",
"_filter",
"=",
"{",
"'items'",
":",
"{",
"'description'",
":",
"utils",
".",
"query_filter",
"(",
"'*Load Balancer*'",
")",
"}",
"}",
"packages",
"=",
"self",
".",
"prod_pkg",
".",
"getItems",
"(",
"id",
"=",
"0",
",",
"filter",
"=",
"_filter",
")",
"pkgs",
"=",
"[",
"]",
"for",
"package",
"in",
"packages",
":",
"if",
"not",
"package",
"[",
"'description'",
"]",
".",
"startswith",
"(",
"'Global'",
")",
":",
"pkgs",
".",
"append",
"(",
"package",
")",
"return",
"pkgs"
] | Retrieves the local load balancer packages.
:returns: A dictionary containing the load balancer packages | [
"Retrieves",
"the",
"local",
"load",
"balancer",
"packages",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L27-L41 | train | 234,284 |
softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager._get_location | def _get_location(self, datacenter_name):
"""Returns the location of the specified datacenter.
:param string datacenter_name: The datacenter to create
the loadbalancer in
:returns: the location id of the given datacenter
"""
datacenters = self.client['Location'].getDataCenters()
for datacenter in datacenters:
if datacenter['name'] == datacenter_name:
return datacenter['id']
return 'FIRST_AVAILABLE' | python | def _get_location(self, datacenter_name):
"""Returns the location of the specified datacenter.
:param string datacenter_name: The datacenter to create
the loadbalancer in
:returns: the location id of the given datacenter
"""
datacenters = self.client['Location'].getDataCenters()
for datacenter in datacenters:
if datacenter['name'] == datacenter_name:
return datacenter['id']
return 'FIRST_AVAILABLE' | [
"def",
"_get_location",
"(",
"self",
",",
"datacenter_name",
")",
":",
"datacenters",
"=",
"self",
".",
"client",
"[",
"'Location'",
"]",
".",
"getDataCenters",
"(",
")",
"for",
"datacenter",
"in",
"datacenters",
":",
"if",
"datacenter",
"[",
"'name'",
"]",
"==",
"datacenter_name",
":",
"return",
"datacenter",
"[",
"'id'",
"]",
"return",
"'FIRST_AVAILABLE'"
] | Returns the location of the specified datacenter.
:param string datacenter_name: The datacenter to create
the loadbalancer in
:returns: the location id of the given datacenter | [
"Returns",
"the",
"location",
"of",
"the",
"specified",
"datacenter",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L73-L86 | train | 234,285 |
softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.cancel_lb | def cancel_lb(self, loadbal_id):
"""Cancels the specified load balancer.
:param int loadbal_id: Load Balancer ID to be cancelled.
"""
lb_billing = self.lb_svc.getBillingItem(id=loadbal_id)
billing_id = lb_billing['id']
billing_item = self.client['Billing_Item']
return billing_item.cancelService(id=billing_id) | python | def cancel_lb(self, loadbal_id):
"""Cancels the specified load balancer.
:param int loadbal_id: Load Balancer ID to be cancelled.
"""
lb_billing = self.lb_svc.getBillingItem(id=loadbal_id)
billing_id = lb_billing['id']
billing_item = self.client['Billing_Item']
return billing_item.cancelService(id=billing_id) | [
"def",
"cancel_lb",
"(",
"self",
",",
"loadbal_id",
")",
":",
"lb_billing",
"=",
"self",
".",
"lb_svc",
".",
"getBillingItem",
"(",
"id",
"=",
"loadbal_id",
")",
"billing_id",
"=",
"lb_billing",
"[",
"'id'",
"]",
"billing_item",
"=",
"self",
".",
"client",
"[",
"'Billing_Item'",
"]",
"return",
"billing_item",
".",
"cancelService",
"(",
"id",
"=",
"billing_id",
")"
] | Cancels the specified load balancer.
:param int loadbal_id: Load Balancer ID to be cancelled. | [
"Cancels",
"the",
"specified",
"load",
"balancer",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L88-L97 | train | 234,286 |
softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.add_local_lb | def add_local_lb(self, price_item_id, datacenter):
"""Creates a local load balancer in the specified data center.
:param int price_item_id: The price item ID for the load balancer
:param string datacenter: The datacenter to create the loadbalancer in
:returns: A dictionary containing the product order
"""
product_order = {
'complexType': 'SoftLayer_Container_Product_Order_Network_'
'LoadBalancer',
'quantity': 1,
'packageId': 0,
"location": self._get_location(datacenter),
'prices': [{'id': price_item_id}]
}
return self.client['Product_Order'].placeOrder(product_order) | python | def add_local_lb(self, price_item_id, datacenter):
"""Creates a local load balancer in the specified data center.
:param int price_item_id: The price item ID for the load balancer
:param string datacenter: The datacenter to create the loadbalancer in
:returns: A dictionary containing the product order
"""
product_order = {
'complexType': 'SoftLayer_Container_Product_Order_Network_'
'LoadBalancer',
'quantity': 1,
'packageId': 0,
"location": self._get_location(datacenter),
'prices': [{'id': price_item_id}]
}
return self.client['Product_Order'].placeOrder(product_order) | [
"def",
"add_local_lb",
"(",
"self",
",",
"price_item_id",
",",
"datacenter",
")",
":",
"product_order",
"=",
"{",
"'complexType'",
":",
"'SoftLayer_Container_Product_Order_Network_'",
"'LoadBalancer'",
",",
"'quantity'",
":",
"1",
",",
"'packageId'",
":",
"0",
",",
"\"location\"",
":",
"self",
".",
"_get_location",
"(",
"datacenter",
")",
",",
"'prices'",
":",
"[",
"{",
"'id'",
":",
"price_item_id",
"}",
"]",
"}",
"return",
"self",
".",
"client",
"[",
"'Product_Order'",
"]",
".",
"placeOrder",
"(",
"product_order",
")"
] | Creates a local load balancer in the specified data center.
:param int price_item_id: The price item ID for the load balancer
:param string datacenter: The datacenter to create the loadbalancer in
:returns: A dictionary containing the product order | [
"Creates",
"a",
"local",
"load",
"balancer",
"in",
"the",
"specified",
"data",
"center",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L99-L115 | train | 234,287 |
softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.get_local_lb | def get_local_lb(self, loadbal_id, **kwargs):
"""Returns a specified local load balancer given the id.
:param int loadbal_id: The id of the load balancer to retrieve
:returns: A dictionary containing the details of the load balancer
"""
if 'mask' not in kwargs:
kwargs['mask'] = ('loadBalancerHardware[datacenter], '
'ipAddress, virtualServers[serviceGroups'
'[routingMethod,routingType,services'
'[healthChecks[type], groupReferences,'
' ipAddress]]]')
return self.lb_svc.getObject(id=loadbal_id, **kwargs) | python | def get_local_lb(self, loadbal_id, **kwargs):
"""Returns a specified local load balancer given the id.
:param int loadbal_id: The id of the load balancer to retrieve
:returns: A dictionary containing the details of the load balancer
"""
if 'mask' not in kwargs:
kwargs['mask'] = ('loadBalancerHardware[datacenter], '
'ipAddress, virtualServers[serviceGroups'
'[routingMethod,routingType,services'
'[healthChecks[type], groupReferences,'
' ipAddress]]]')
return self.lb_svc.getObject(id=loadbal_id, **kwargs) | [
"def",
"get_local_lb",
"(",
"self",
",",
"loadbal_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'mask'",
"]",
"=",
"(",
"'loadBalancerHardware[datacenter], '",
"'ipAddress, virtualServers[serviceGroups'",
"'[routingMethod,routingType,services'",
"'[healthChecks[type], groupReferences,'",
"' ipAddress]]]'",
")",
"return",
"self",
".",
"lb_svc",
".",
"getObject",
"(",
"id",
"=",
"loadbal_id",
",",
"*",
"*",
"kwargs",
")"
] | Returns a specified local load balancer given the id.
:param int loadbal_id: The id of the load balancer to retrieve
:returns: A dictionary containing the details of the load balancer | [
"Returns",
"a",
"specified",
"local",
"load",
"balancer",
"given",
"the",
"id",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L126-L140 | train | 234,288 |
softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.delete_service | def delete_service(self, service_id):
"""Deletes a service from the loadbal_id.
:param int service_id: The id of the service to delete
"""
svc = self.client['Network_Application_Delivery_Controller_'
'LoadBalancer_Service']
return svc.deleteObject(id=service_id) | python | def delete_service(self, service_id):
"""Deletes a service from the loadbal_id.
:param int service_id: The id of the service to delete
"""
svc = self.client['Network_Application_Delivery_Controller_'
'LoadBalancer_Service']
return svc.deleteObject(id=service_id) | [
"def",
"delete_service",
"(",
"self",
",",
"service_id",
")",
":",
"svc",
"=",
"self",
".",
"client",
"[",
"'Network_Application_Delivery_Controller_'",
"'LoadBalancer_Service'",
"]",
"return",
"svc",
".",
"deleteObject",
"(",
"id",
"=",
"service_id",
")"
] | Deletes a service from the loadbal_id.
:param int service_id: The id of the service to delete | [
"Deletes",
"a",
"service",
"from",
"the",
"loadbal_id",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L142-L151 | train | 234,289 |
softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.delete_service_group | def delete_service_group(self, group_id):
"""Deletes a service group from the loadbal_id.
:param int group_id: The id of the service group to delete
"""
svc = self.client['Network_Application_Delivery_Controller_'
'LoadBalancer_VirtualServer']
return svc.deleteObject(id=group_id) | python | def delete_service_group(self, group_id):
"""Deletes a service group from the loadbal_id.
:param int group_id: The id of the service group to delete
"""
svc = self.client['Network_Application_Delivery_Controller_'
'LoadBalancer_VirtualServer']
return svc.deleteObject(id=group_id) | [
"def",
"delete_service_group",
"(",
"self",
",",
"group_id",
")",
":",
"svc",
"=",
"self",
".",
"client",
"[",
"'Network_Application_Delivery_Controller_'",
"'LoadBalancer_VirtualServer'",
"]",
"return",
"svc",
".",
"deleteObject",
"(",
"id",
"=",
"group_id",
")"
] | Deletes a service group from the loadbal_id.
:param int group_id: The id of the service group to delete | [
"Deletes",
"a",
"service",
"group",
"from",
"the",
"loadbal_id",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L153-L162 | train | 234,290 |
softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.toggle_service_status | def toggle_service_status(self, service_id):
"""Toggles the service status.
:param int service_id: The id of the service to delete
"""
svc = self.client['Network_Application_Delivery_Controller_'
'LoadBalancer_Service']
return svc.toggleStatus(id=service_id) | python | def toggle_service_status(self, service_id):
"""Toggles the service status.
:param int service_id: The id of the service to delete
"""
svc = self.client['Network_Application_Delivery_Controller_'
'LoadBalancer_Service']
return svc.toggleStatus(id=service_id) | [
"def",
"toggle_service_status",
"(",
"self",
",",
"service_id",
")",
":",
"svc",
"=",
"self",
".",
"client",
"[",
"'Network_Application_Delivery_Controller_'",
"'LoadBalancer_Service'",
"]",
"return",
"svc",
".",
"toggleStatus",
"(",
"id",
"=",
"service_id",
")"
] | Toggles the service status.
:param int service_id: The id of the service to delete | [
"Toggles",
"the",
"service",
"status",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L164-L172 | train | 234,291 |
softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.edit_service | def edit_service(self, loadbal_id, service_id, ip_address_id=None,
port=None, enabled=None, hc_type=None, weight=None):
"""Edits an existing service properties.
:param int loadbal_id: The id of the loadbal where the service resides
:param int service_id: The id of the service to edit
:param string ip_address: The ip address of the service
:param int port: the port of the service
:param bool enabled: enable or disable the search
:param int hc_type: The health check type
:param int weight: the weight to give to the service
"""
_filter = {
'virtualServers': {
'serviceGroups': {
'services': {'id': utils.query_filter(service_id)}}}}
mask = 'serviceGroups[services[groupReferences,healthChecks]]'
virtual_servers = self.lb_svc.getVirtualServers(id=loadbal_id,
filter=_filter,
mask=mask)
for service in virtual_servers[0]['serviceGroups'][0]['services']:
if service['id'] == service_id:
if enabled is not None:
service['enabled'] = int(enabled)
if port is not None:
service['port'] = port
if weight is not None:
service['groupReferences'][0]['weight'] = weight
if hc_type is not None:
service['healthChecks'][0]['healthCheckTypeId'] = hc_type
if ip_address_id is not None:
service['ipAddressId'] = ip_address_id
template = {'virtualServers': list(virtual_servers)}
load_balancer = self.lb_svc.editObject(template, id=loadbal_id)
return load_balancer | python | def edit_service(self, loadbal_id, service_id, ip_address_id=None,
port=None, enabled=None, hc_type=None, weight=None):
"""Edits an existing service properties.
:param int loadbal_id: The id of the loadbal where the service resides
:param int service_id: The id of the service to edit
:param string ip_address: The ip address of the service
:param int port: the port of the service
:param bool enabled: enable or disable the search
:param int hc_type: The health check type
:param int weight: the weight to give to the service
"""
_filter = {
'virtualServers': {
'serviceGroups': {
'services': {'id': utils.query_filter(service_id)}}}}
mask = 'serviceGroups[services[groupReferences,healthChecks]]'
virtual_servers = self.lb_svc.getVirtualServers(id=loadbal_id,
filter=_filter,
mask=mask)
for service in virtual_servers[0]['serviceGroups'][0]['services']:
if service['id'] == service_id:
if enabled is not None:
service['enabled'] = int(enabled)
if port is not None:
service['port'] = port
if weight is not None:
service['groupReferences'][0]['weight'] = weight
if hc_type is not None:
service['healthChecks'][0]['healthCheckTypeId'] = hc_type
if ip_address_id is not None:
service['ipAddressId'] = ip_address_id
template = {'virtualServers': list(virtual_servers)}
load_balancer = self.lb_svc.editObject(template, id=loadbal_id)
return load_balancer | [
"def",
"edit_service",
"(",
"self",
",",
"loadbal_id",
",",
"service_id",
",",
"ip_address_id",
"=",
"None",
",",
"port",
"=",
"None",
",",
"enabled",
"=",
"None",
",",
"hc_type",
"=",
"None",
",",
"weight",
"=",
"None",
")",
":",
"_filter",
"=",
"{",
"'virtualServers'",
":",
"{",
"'serviceGroups'",
":",
"{",
"'services'",
":",
"{",
"'id'",
":",
"utils",
".",
"query_filter",
"(",
"service_id",
")",
"}",
"}",
"}",
"}",
"mask",
"=",
"'serviceGroups[services[groupReferences,healthChecks]]'",
"virtual_servers",
"=",
"self",
".",
"lb_svc",
".",
"getVirtualServers",
"(",
"id",
"=",
"loadbal_id",
",",
"filter",
"=",
"_filter",
",",
"mask",
"=",
"mask",
")",
"for",
"service",
"in",
"virtual_servers",
"[",
"0",
"]",
"[",
"'serviceGroups'",
"]",
"[",
"0",
"]",
"[",
"'services'",
"]",
":",
"if",
"service",
"[",
"'id'",
"]",
"==",
"service_id",
":",
"if",
"enabled",
"is",
"not",
"None",
":",
"service",
"[",
"'enabled'",
"]",
"=",
"int",
"(",
"enabled",
")",
"if",
"port",
"is",
"not",
"None",
":",
"service",
"[",
"'port'",
"]",
"=",
"port",
"if",
"weight",
"is",
"not",
"None",
":",
"service",
"[",
"'groupReferences'",
"]",
"[",
"0",
"]",
"[",
"'weight'",
"]",
"=",
"weight",
"if",
"hc_type",
"is",
"not",
"None",
":",
"service",
"[",
"'healthChecks'",
"]",
"[",
"0",
"]",
"[",
"'healthCheckTypeId'",
"]",
"=",
"hc_type",
"if",
"ip_address_id",
"is",
"not",
"None",
":",
"service",
"[",
"'ipAddressId'",
"]",
"=",
"ip_address_id",
"template",
"=",
"{",
"'virtualServers'",
":",
"list",
"(",
"virtual_servers",
")",
"}",
"load_balancer",
"=",
"self",
".",
"lb_svc",
".",
"editObject",
"(",
"template",
",",
"id",
"=",
"loadbal_id",
")",
"return",
"load_balancer"
] | Edits an existing service properties.
:param int loadbal_id: The id of the loadbal where the service resides
:param int service_id: The id of the service to edit
:param string ip_address: The ip address of the service
:param int port: the port of the service
:param bool enabled: enable or disable the search
:param int hc_type: The health check type
:param int weight: the weight to give to the service | [
"Edits",
"an",
"existing",
"service",
"properties",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L174-L214 | train | 234,292 |
softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.add_service | def add_service(self, loadbal_id, service_group_id, ip_address_id,
port=80, enabled=True, hc_type=21, weight=1):
"""Adds a new service to the service group.
:param int loadbal_id: The id of the loadbal where the service resides
:param int service_group_id: The group to add the service to
:param int ip_address id: The ip address ID of the service
:param int port: the port of the service
:param bool enabled: Enable or disable the service
:param int hc_type: The health check type
:param int weight: the weight to give to the service
"""
kwargs = utils.NestedDict({})
kwargs['mask'] = ('virtualServers['
'serviceGroups[services[groupReferences]]]')
load_balancer = self.lb_svc.getObject(id=loadbal_id, **kwargs)
virtual_servers = load_balancer['virtualServers']
for virtual_server in virtual_servers:
if virtual_server['id'] == service_group_id:
service_template = {
'enabled': int(enabled),
'port': port,
'ipAddressId': ip_address_id,
'healthChecks': [
{
'healthCheckTypeId': hc_type
}
],
'groupReferences': [
{
'weight': weight
}
]
}
services = virtual_server['serviceGroups'][0]['services']
services.append(service_template)
return self.lb_svc.editObject(load_balancer, id=loadbal_id) | python | def add_service(self, loadbal_id, service_group_id, ip_address_id,
port=80, enabled=True, hc_type=21, weight=1):
"""Adds a new service to the service group.
:param int loadbal_id: The id of the loadbal where the service resides
:param int service_group_id: The group to add the service to
:param int ip_address id: The ip address ID of the service
:param int port: the port of the service
:param bool enabled: Enable or disable the service
:param int hc_type: The health check type
:param int weight: the weight to give to the service
"""
kwargs = utils.NestedDict({})
kwargs['mask'] = ('virtualServers['
'serviceGroups[services[groupReferences]]]')
load_balancer = self.lb_svc.getObject(id=loadbal_id, **kwargs)
virtual_servers = load_balancer['virtualServers']
for virtual_server in virtual_servers:
if virtual_server['id'] == service_group_id:
service_template = {
'enabled': int(enabled),
'port': port,
'ipAddressId': ip_address_id,
'healthChecks': [
{
'healthCheckTypeId': hc_type
}
],
'groupReferences': [
{
'weight': weight
}
]
}
services = virtual_server['serviceGroups'][0]['services']
services.append(service_template)
return self.lb_svc.editObject(load_balancer, id=loadbal_id) | [
"def",
"add_service",
"(",
"self",
",",
"loadbal_id",
",",
"service_group_id",
",",
"ip_address_id",
",",
"port",
"=",
"80",
",",
"enabled",
"=",
"True",
",",
"hc_type",
"=",
"21",
",",
"weight",
"=",
"1",
")",
":",
"kwargs",
"=",
"utils",
".",
"NestedDict",
"(",
"{",
"}",
")",
"kwargs",
"[",
"'mask'",
"]",
"=",
"(",
"'virtualServers['",
"'serviceGroups[services[groupReferences]]]'",
")",
"load_balancer",
"=",
"self",
".",
"lb_svc",
".",
"getObject",
"(",
"id",
"=",
"loadbal_id",
",",
"*",
"*",
"kwargs",
")",
"virtual_servers",
"=",
"load_balancer",
"[",
"'virtualServers'",
"]",
"for",
"virtual_server",
"in",
"virtual_servers",
":",
"if",
"virtual_server",
"[",
"'id'",
"]",
"==",
"service_group_id",
":",
"service_template",
"=",
"{",
"'enabled'",
":",
"int",
"(",
"enabled",
")",
",",
"'port'",
":",
"port",
",",
"'ipAddressId'",
":",
"ip_address_id",
",",
"'healthChecks'",
":",
"[",
"{",
"'healthCheckTypeId'",
":",
"hc_type",
"}",
"]",
",",
"'groupReferences'",
":",
"[",
"{",
"'weight'",
":",
"weight",
"}",
"]",
"}",
"services",
"=",
"virtual_server",
"[",
"'serviceGroups'",
"]",
"[",
"0",
"]",
"[",
"'services'",
"]",
"services",
".",
"append",
"(",
"service_template",
")",
"return",
"self",
".",
"lb_svc",
".",
"editObject",
"(",
"load_balancer",
",",
"id",
"=",
"loadbal_id",
")"
] | Adds a new service to the service group.
:param int loadbal_id: The id of the loadbal where the service resides
:param int service_group_id: The group to add the service to
:param int ip_address id: The ip address ID of the service
:param int port: the port of the service
:param bool enabled: Enable or disable the service
:param int hc_type: The health check type
:param int weight: the weight to give to the service | [
"Adds",
"a",
"new",
"service",
"to",
"the",
"service",
"group",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L216-L254 | train | 234,293 |
softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.add_service_group | def add_service_group(self, lb_id, allocation=100, port=80,
routing_type=2, routing_method=10):
"""Adds a new service group to the load balancer.
:param int loadbal_id: The id of the loadbal where the service resides
:param int allocation: percent of connections to allocate toward the
group
:param int port: the port of the service group
:param int routing_type: the routing type to set on the service group
:param int routing_method: The routing method to set on the group
"""
mask = 'virtualServers[serviceGroups[services[groupReferences]]]'
load_balancer = self.lb_svc.getObject(id=lb_id, mask=mask)
service_template = {
'port': port,
'allocation': allocation,
'serviceGroups': [
{
'routingTypeId': routing_type,
'routingMethodId': routing_method
}
]
}
load_balancer['virtualServers'].append(service_template)
return self.lb_svc.editObject(load_balancer, id=lb_id) | python | def add_service_group(self, lb_id, allocation=100, port=80,
routing_type=2, routing_method=10):
"""Adds a new service group to the load balancer.
:param int loadbal_id: The id of the loadbal where the service resides
:param int allocation: percent of connections to allocate toward the
group
:param int port: the port of the service group
:param int routing_type: the routing type to set on the service group
:param int routing_method: The routing method to set on the group
"""
mask = 'virtualServers[serviceGroups[services[groupReferences]]]'
load_balancer = self.lb_svc.getObject(id=lb_id, mask=mask)
service_template = {
'port': port,
'allocation': allocation,
'serviceGroups': [
{
'routingTypeId': routing_type,
'routingMethodId': routing_method
}
]
}
load_balancer['virtualServers'].append(service_template)
return self.lb_svc.editObject(load_balancer, id=lb_id) | [
"def",
"add_service_group",
"(",
"self",
",",
"lb_id",
",",
"allocation",
"=",
"100",
",",
"port",
"=",
"80",
",",
"routing_type",
"=",
"2",
",",
"routing_method",
"=",
"10",
")",
":",
"mask",
"=",
"'virtualServers[serviceGroups[services[groupReferences]]]'",
"load_balancer",
"=",
"self",
".",
"lb_svc",
".",
"getObject",
"(",
"id",
"=",
"lb_id",
",",
"mask",
"=",
"mask",
")",
"service_template",
"=",
"{",
"'port'",
":",
"port",
",",
"'allocation'",
":",
"allocation",
",",
"'serviceGroups'",
":",
"[",
"{",
"'routingTypeId'",
":",
"routing_type",
",",
"'routingMethodId'",
":",
"routing_method",
"}",
"]",
"}",
"load_balancer",
"[",
"'virtualServers'",
"]",
".",
"append",
"(",
"service_template",
")",
"return",
"self",
".",
"lb_svc",
".",
"editObject",
"(",
"load_balancer",
",",
"id",
"=",
"lb_id",
")"
] | Adds a new service group to the load balancer.
:param int loadbal_id: The id of the loadbal where the service resides
:param int allocation: percent of connections to allocate toward the
group
:param int port: the port of the service group
:param int routing_type: the routing type to set on the service group
:param int routing_method: The routing method to set on the group | [
"Adds",
"a",
"new",
"service",
"group",
"to",
"the",
"load",
"balancer",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L256-L282 | train | 234,294 |
softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.edit_service_group | def edit_service_group(self, loadbal_id, group_id, allocation=None,
port=None, routing_type=None, routing_method=None):
"""Edit an existing service group.
:param int loadbal_id: The id of the loadbal where the service resides
:param int group_id: The id of the service group
:param int allocation: the % of connections to allocate to the group
:param int port: the port of the service group
:param int routing_type: the routing type to set on the service group
:param int routing_method: The routing method to set on the group
"""
mask = 'virtualServers[serviceGroups[services[groupReferences]]]'
load_balancer = self.lb_svc.getObject(id=loadbal_id, mask=mask)
virtual_servers = load_balancer['virtualServers']
for virtual_server in virtual_servers:
if virtual_server['id'] == group_id:
service_group = virtual_server['serviceGroups'][0]
if allocation is not None:
virtual_server['allocation'] = allocation
if port is not None:
virtual_server['port'] = port
if routing_type is not None:
service_group['routingTypeId'] = routing_type
if routing_method is not None:
service_group['routingMethodId'] = routing_method
break
return self.lb_svc.editObject(load_balancer, id=loadbal_id) | python | def edit_service_group(self, loadbal_id, group_id, allocation=None,
port=None, routing_type=None, routing_method=None):
"""Edit an existing service group.
:param int loadbal_id: The id of the loadbal where the service resides
:param int group_id: The id of the service group
:param int allocation: the % of connections to allocate to the group
:param int port: the port of the service group
:param int routing_type: the routing type to set on the service group
:param int routing_method: The routing method to set on the group
"""
mask = 'virtualServers[serviceGroups[services[groupReferences]]]'
load_balancer = self.lb_svc.getObject(id=loadbal_id, mask=mask)
virtual_servers = load_balancer['virtualServers']
for virtual_server in virtual_servers:
if virtual_server['id'] == group_id:
service_group = virtual_server['serviceGroups'][0]
if allocation is not None:
virtual_server['allocation'] = allocation
if port is not None:
virtual_server['port'] = port
if routing_type is not None:
service_group['routingTypeId'] = routing_type
if routing_method is not None:
service_group['routingMethodId'] = routing_method
break
return self.lb_svc.editObject(load_balancer, id=loadbal_id) | [
"def",
"edit_service_group",
"(",
"self",
",",
"loadbal_id",
",",
"group_id",
",",
"allocation",
"=",
"None",
",",
"port",
"=",
"None",
",",
"routing_type",
"=",
"None",
",",
"routing_method",
"=",
"None",
")",
":",
"mask",
"=",
"'virtualServers[serviceGroups[services[groupReferences]]]'",
"load_balancer",
"=",
"self",
".",
"lb_svc",
".",
"getObject",
"(",
"id",
"=",
"loadbal_id",
",",
"mask",
"=",
"mask",
")",
"virtual_servers",
"=",
"load_balancer",
"[",
"'virtualServers'",
"]",
"for",
"virtual_server",
"in",
"virtual_servers",
":",
"if",
"virtual_server",
"[",
"'id'",
"]",
"==",
"group_id",
":",
"service_group",
"=",
"virtual_server",
"[",
"'serviceGroups'",
"]",
"[",
"0",
"]",
"if",
"allocation",
"is",
"not",
"None",
":",
"virtual_server",
"[",
"'allocation'",
"]",
"=",
"allocation",
"if",
"port",
"is",
"not",
"None",
":",
"virtual_server",
"[",
"'port'",
"]",
"=",
"port",
"if",
"routing_type",
"is",
"not",
"None",
":",
"service_group",
"[",
"'routingTypeId'",
"]",
"=",
"routing_type",
"if",
"routing_method",
"is",
"not",
"None",
":",
"service_group",
"[",
"'routingMethodId'",
"]",
"=",
"routing_method",
"break",
"return",
"self",
".",
"lb_svc",
".",
"editObject",
"(",
"load_balancer",
",",
"id",
"=",
"loadbal_id",
")"
] | Edit an existing service group.
:param int loadbal_id: The id of the loadbal where the service resides
:param int group_id: The id of the service group
:param int allocation: the % of connections to allocate to the group
:param int port: the port of the service group
:param int routing_type: the routing type to set on the service group
:param int routing_method: The routing method to set on the group | [
"Edit",
"an",
"existing",
"service",
"group",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L284-L314 | train | 234,295 |
softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.reset_service_group | def reset_service_group(self, loadbal_id, group_id):
"""Resets all the connections on the service group.
:param int loadbal_id: The id of the loadbal
:param int group_id: The id of the service group to reset
"""
_filter = {'virtualServers': {'id': utils.query_filter(group_id)}}
virtual_servers = self.lb_svc.getVirtualServers(id=loadbal_id,
filter=_filter,
mask='serviceGroups')
actual_id = virtual_servers[0]['serviceGroups'][0]['id']
svc = self.client['Network_Application_Delivery_Controller'
'_LoadBalancer_Service_Group']
return svc.kickAllConnections(id=actual_id) | python | def reset_service_group(self, loadbal_id, group_id):
"""Resets all the connections on the service group.
:param int loadbal_id: The id of the loadbal
:param int group_id: The id of the service group to reset
"""
_filter = {'virtualServers': {'id': utils.query_filter(group_id)}}
virtual_servers = self.lb_svc.getVirtualServers(id=loadbal_id,
filter=_filter,
mask='serviceGroups')
actual_id = virtual_servers[0]['serviceGroups'][0]['id']
svc = self.client['Network_Application_Delivery_Controller'
'_LoadBalancer_Service_Group']
return svc.kickAllConnections(id=actual_id) | [
"def",
"reset_service_group",
"(",
"self",
",",
"loadbal_id",
",",
"group_id",
")",
":",
"_filter",
"=",
"{",
"'virtualServers'",
":",
"{",
"'id'",
":",
"utils",
".",
"query_filter",
"(",
"group_id",
")",
"}",
"}",
"virtual_servers",
"=",
"self",
".",
"lb_svc",
".",
"getVirtualServers",
"(",
"id",
"=",
"loadbal_id",
",",
"filter",
"=",
"_filter",
",",
"mask",
"=",
"'serviceGroups'",
")",
"actual_id",
"=",
"virtual_servers",
"[",
"0",
"]",
"[",
"'serviceGroups'",
"]",
"[",
"0",
"]",
"[",
"'id'",
"]",
"svc",
"=",
"self",
".",
"client",
"[",
"'Network_Application_Delivery_Controller'",
"'_LoadBalancer_Service_Group'",
"]",
"return",
"svc",
".",
"kickAllConnections",
"(",
"id",
"=",
"actual_id",
")"
] | Resets all the connections on the service group.
:param int loadbal_id: The id of the loadbal
:param int group_id: The id of the service group to reset | [
"Resets",
"all",
"the",
"connections",
"on",
"the",
"service",
"group",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L316-L331 | train | 234,296 |
softlayer/softlayer-python | SoftLayer/CLI/image/detail.py | cli | def cli(env, identifier):
"""Get details for an image."""
image_mgr = SoftLayer.ImageManager(env.client)
image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')
image = image_mgr.get_image(image_id, mask=image_mod.DETAIL_MASK)
disk_space = 0
datacenters = []
for child in image.get('children'):
disk_space = int(child.get('blockDevicesDiskSpaceTotal', 0))
if child.get('datacenter'):
datacenters.append(utils.lookup(child, 'datacenter', 'name'))
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', image['id']])
table.add_row(['global_identifier',
image.get('globalIdentifier', formatting.blank())])
table.add_row(['name', image['name'].strip()])
table.add_row(['status', formatting.FormattedItem(
utils.lookup(image, 'status', 'keyname'),
utils.lookup(image, 'status', 'name'),
)])
table.add_row([
'active_transaction',
formatting.transaction_status(image.get('transaction')),
])
table.add_row(['account', image.get('accountId', formatting.blank())])
table.add_row(['visibility',
image_mod.PUBLIC_TYPE if image['publicFlag']
else image_mod.PRIVATE_TYPE])
table.add_row(['type',
formatting.FormattedItem(
utils.lookup(image, 'imageType', 'keyName'),
utils.lookup(image, 'imageType', 'name'),
)])
table.add_row(['flex', image.get('flexImageFlag')])
table.add_row(['note', image.get('note')])
table.add_row(['created', image.get('createDate')])
table.add_row(['disk_space', formatting.b_to_gb(disk_space)])
table.add_row(['datacenters', formatting.listing(sorted(datacenters),
separator=',')])
env.fout(table) | python | def cli(env, identifier):
"""Get details for an image."""
image_mgr = SoftLayer.ImageManager(env.client)
image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')
image = image_mgr.get_image(image_id, mask=image_mod.DETAIL_MASK)
disk_space = 0
datacenters = []
for child in image.get('children'):
disk_space = int(child.get('blockDevicesDiskSpaceTotal', 0))
if child.get('datacenter'):
datacenters.append(utils.lookup(child, 'datacenter', 'name'))
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', image['id']])
table.add_row(['global_identifier',
image.get('globalIdentifier', formatting.blank())])
table.add_row(['name', image['name'].strip()])
table.add_row(['status', formatting.FormattedItem(
utils.lookup(image, 'status', 'keyname'),
utils.lookup(image, 'status', 'name'),
)])
table.add_row([
'active_transaction',
formatting.transaction_status(image.get('transaction')),
])
table.add_row(['account', image.get('accountId', formatting.blank())])
table.add_row(['visibility',
image_mod.PUBLIC_TYPE if image['publicFlag']
else image_mod.PRIVATE_TYPE])
table.add_row(['type',
formatting.FormattedItem(
utils.lookup(image, 'imageType', 'keyName'),
utils.lookup(image, 'imageType', 'name'),
)])
table.add_row(['flex', image.get('flexImageFlag')])
table.add_row(['note', image.get('note')])
table.add_row(['created', image.get('createDate')])
table.add_row(['disk_space', formatting.b_to_gb(disk_space)])
table.add_row(['datacenters', formatting.listing(sorted(datacenters),
separator=',')])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"image_mgr",
"=",
"SoftLayer",
".",
"ImageManager",
"(",
"env",
".",
"client",
")",
"image_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"image_mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'image'",
")",
"image",
"=",
"image_mgr",
".",
"get_image",
"(",
"image_id",
",",
"mask",
"=",
"image_mod",
".",
"DETAIL_MASK",
")",
"disk_space",
"=",
"0",
"datacenters",
"=",
"[",
"]",
"for",
"child",
"in",
"image",
".",
"get",
"(",
"'children'",
")",
":",
"disk_space",
"=",
"int",
"(",
"child",
".",
"get",
"(",
"'blockDevicesDiskSpaceTotal'",
",",
"0",
")",
")",
"if",
"child",
".",
"get",
"(",
"'datacenter'",
")",
":",
"datacenters",
".",
"append",
"(",
"utils",
".",
"lookup",
"(",
"child",
",",
"'datacenter'",
",",
"'name'",
")",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"image",
"[",
"'id'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'global_identifier'",
",",
"image",
".",
"get",
"(",
"'globalIdentifier'",
",",
"formatting",
".",
"blank",
"(",
")",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'name'",
",",
"image",
"[",
"'name'",
"]",
".",
"strip",
"(",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'status'",
",",
"formatting",
".",
"FormattedItem",
"(",
"utils",
".",
"lookup",
"(",
"image",
",",
"'status'",
",",
"'keyname'",
")",
",",
"utils",
".",
"lookup",
"(",
"image",
",",
"'status'",
",",
"'name'",
")",
",",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'active_transaction'",
",",
"formatting",
".",
"transaction_status",
"(",
"image",
".",
"get",
"(",
"'transaction'",
")",
")",
",",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'account'",
",",
"image",
".",
"get",
"(",
"'accountId'",
",",
"formatting",
".",
"blank",
"(",
")",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'visibility'",
",",
"image_mod",
".",
"PUBLIC_TYPE",
"if",
"image",
"[",
"'publicFlag'",
"]",
"else",
"image_mod",
".",
"PRIVATE_TYPE",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'type'",
",",
"formatting",
".",
"FormattedItem",
"(",
"utils",
".",
"lookup",
"(",
"image",
",",
"'imageType'",
",",
"'keyName'",
")",
",",
"utils",
".",
"lookup",
"(",
"image",
",",
"'imageType'",
",",
"'name'",
")",
",",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'flex'",
",",
"image",
".",
"get",
"(",
"'flexImageFlag'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'note'",
",",
"image",
".",
"get",
"(",
"'note'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'created'",
",",
"image",
".",
"get",
"(",
"'createDate'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'disk_space'",
",",
"formatting",
".",
"b_to_gb",
"(",
"disk_space",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'datacenters'",
",",
"formatting",
".",
"listing",
"(",
"sorted",
"(",
"datacenters",
")",
",",
"separator",
"=",
"','",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | Get details for an image. | [
"Get",
"details",
"for",
"an",
"image",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/image/detail.py#L17-L63 | train | 234,297 |
softlayer/softlayer-python | SoftLayer/CLI/file/snapshot/enable.py | cli | def cli(env, volume_id, schedule_type, retention_count,
minute, hour, day_of_week):
"""Enables snapshots for a given volume on the specified schedule"""
file_manager = SoftLayer.FileStorageManager(env.client)
valid_schedule_types = {'INTERVAL', 'HOURLY', 'DAILY', 'WEEKLY'}
valid_days = {'SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY',
'FRIDAY', 'SATURDAY'}
if schedule_type not in valid_schedule_types:
raise exceptions.CLIAbort(
'--schedule-type must be INTERVAL, HOURLY, ' +
'DAILY, or WEEKLY, not ' + schedule_type)
if schedule_type == 'INTERVAL' and (minute < 30 or minute > 59):
raise exceptions.CLIAbort(
'--minute value must be between 30 and 59')
if minute < 0 or minute > 59:
raise exceptions.CLIAbort(
'--minute value must be between 0 and 59')
if hour < 0 or hour > 23:
raise exceptions.CLIAbort(
'--hour value must be between 0 and 23')
if day_of_week not in valid_days:
raise exceptions.CLIAbort(
'--day_of_week value must be a valid day (ex: SUNDAY)')
enabled = file_manager.enable_snapshots(volume_id, schedule_type,
retention_count, minute,
hour, day_of_week)
if enabled:
click.echo('%s snapshots have been enabled for volume %s'
% (schedule_type, volume_id)) | python | def cli(env, volume_id, schedule_type, retention_count,
minute, hour, day_of_week):
"""Enables snapshots for a given volume on the specified schedule"""
file_manager = SoftLayer.FileStorageManager(env.client)
valid_schedule_types = {'INTERVAL', 'HOURLY', 'DAILY', 'WEEKLY'}
valid_days = {'SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY',
'FRIDAY', 'SATURDAY'}
if schedule_type not in valid_schedule_types:
raise exceptions.CLIAbort(
'--schedule-type must be INTERVAL, HOURLY, ' +
'DAILY, or WEEKLY, not ' + schedule_type)
if schedule_type == 'INTERVAL' and (minute < 30 or minute > 59):
raise exceptions.CLIAbort(
'--minute value must be between 30 and 59')
if minute < 0 or minute > 59:
raise exceptions.CLIAbort(
'--minute value must be between 0 and 59')
if hour < 0 or hour > 23:
raise exceptions.CLIAbort(
'--hour value must be between 0 and 23')
if day_of_week not in valid_days:
raise exceptions.CLIAbort(
'--day_of_week value must be a valid day (ex: SUNDAY)')
enabled = file_manager.enable_snapshots(volume_id, schedule_type,
retention_count, minute,
hour, day_of_week)
if enabled:
click.echo('%s snapshots have been enabled for volume %s'
% (schedule_type, volume_id)) | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"schedule_type",
",",
"retention_count",
",",
"minute",
",",
"hour",
",",
"day_of_week",
")",
":",
"file_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"valid_schedule_types",
"=",
"{",
"'INTERVAL'",
",",
"'HOURLY'",
",",
"'DAILY'",
",",
"'WEEKLY'",
"}",
"valid_days",
"=",
"{",
"'SUNDAY'",
",",
"'MONDAY'",
",",
"'TUESDAY'",
",",
"'WEDNESDAY'",
",",
"'THURSDAY'",
",",
"'FRIDAY'",
",",
"'SATURDAY'",
"}",
"if",
"schedule_type",
"not",
"in",
"valid_schedule_types",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'--schedule-type must be INTERVAL, HOURLY, '",
"+",
"'DAILY, or WEEKLY, not '",
"+",
"schedule_type",
")",
"if",
"schedule_type",
"==",
"'INTERVAL'",
"and",
"(",
"minute",
"<",
"30",
"or",
"minute",
">",
"59",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'--minute value must be between 30 and 59'",
")",
"if",
"minute",
"<",
"0",
"or",
"minute",
">",
"59",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'--minute value must be between 0 and 59'",
")",
"if",
"hour",
"<",
"0",
"or",
"hour",
">",
"23",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'--hour value must be between 0 and 23'",
")",
"if",
"day_of_week",
"not",
"in",
"valid_days",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'--day_of_week value must be a valid day (ex: SUNDAY)'",
")",
"enabled",
"=",
"file_manager",
".",
"enable_snapshots",
"(",
"volume_id",
",",
"schedule_type",
",",
"retention_count",
",",
"minute",
",",
"hour",
",",
"day_of_week",
")",
"if",
"enabled",
":",
"click",
".",
"echo",
"(",
"'%s snapshots have been enabled for volume %s'",
"%",
"(",
"schedule_type",
",",
"volume_id",
")",
")"
] | Enables snapshots for a given volume on the specified schedule | [
"Enables",
"snapshots",
"for",
"a",
"given",
"volume",
"on",
"the",
"specified",
"schedule"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/snapshot/enable.py#L28-L61 | train | 234,298 |
softlayer/softlayer-python | SoftLayer/managers/account.py | AccountManager.get_upcoming_events | def get_upcoming_events(self):
"""Retreives a list of Notification_Occurrence_Events that have not ended yet
:return: SoftLayer_Notification_Occurrence_Event
"""
mask = "mask[id, subject, startDate, endDate, statusCode, acknowledgedFlag, impactedResourceCount, updateCount]"
_filter = {
'endDate': {
'operation': '> sysdate'
},
'startDate': {
'operation': 'orderBy',
'options': [{
'name': 'sort',
'value': ['ASC']
}]
}
}
return self.client.call('Notification_Occurrence_Event', 'getAllObjects', filter=_filter, mask=mask, iter=True) | python | def get_upcoming_events(self):
"""Retreives a list of Notification_Occurrence_Events that have not ended yet
:return: SoftLayer_Notification_Occurrence_Event
"""
mask = "mask[id, subject, startDate, endDate, statusCode, acknowledgedFlag, impactedResourceCount, updateCount]"
_filter = {
'endDate': {
'operation': '> sysdate'
},
'startDate': {
'operation': 'orderBy',
'options': [{
'name': 'sort',
'value': ['ASC']
}]
}
}
return self.client.call('Notification_Occurrence_Event', 'getAllObjects', filter=_filter, mask=mask, iter=True) | [
"def",
"get_upcoming_events",
"(",
"self",
")",
":",
"mask",
"=",
"\"mask[id, subject, startDate, endDate, statusCode, acknowledgedFlag, impactedResourceCount, updateCount]\"",
"_filter",
"=",
"{",
"'endDate'",
":",
"{",
"'operation'",
":",
"'> sysdate'",
"}",
",",
"'startDate'",
":",
"{",
"'operation'",
":",
"'orderBy'",
",",
"'options'",
":",
"[",
"{",
"'name'",
":",
"'sort'",
",",
"'value'",
":",
"[",
"'ASC'",
"]",
"}",
"]",
"}",
"}",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'Notification_Occurrence_Event'",
",",
"'getAllObjects'",
",",
"filter",
"=",
"_filter",
",",
"mask",
"=",
"mask",
",",
"iter",
"=",
"True",
")"
] | Retreives a list of Notification_Occurrence_Events that have not ended yet
:return: SoftLayer_Notification_Occurrence_Event | [
"Retreives",
"a",
"list",
"of",
"Notification_Occurrence_Events",
"that",
"have",
"not",
"ended",
"yet"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/account.py#L50-L68 | train | 234,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.