repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 39
1.84M
| func_code_tokens
listlengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
listlengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
softlayer/softlayer-python | SoftLayer/managers/firewall.py | FirewallManager.edit_dedicated_fwl_rules | def edit_dedicated_fwl_rules(self, firewall_id, rules):
"""Edit the rules for dedicated firewall.
:param integer firewall_id: the instance ID of the dedicated firewall
:param list rules: the rules to be pushed on the firewall as defined by
SoftLayer_Network_Firewall_Update_Request_Rule
"""
mask = ('mask[networkVlan[firewallInterfaces'
'[firewallContextAccessControlLists]]]')
svc = self.client['Network_Vlan_Firewall']
fwl = svc.getObject(id=firewall_id, mask=mask)
network_vlan = fwl['networkVlan']
for fwl1 in network_vlan['firewallInterfaces']:
if fwl1['name'] == 'inside':
continue
for control_list in fwl1['firewallContextAccessControlLists']:
if control_list['direction'] == 'out':
continue
fwl_ctx_acl_id = control_list['id']
template = {'firewallContextAccessControlListId': fwl_ctx_acl_id,
'rules': rules}
svc = self.client['Network_Firewall_Update_Request']
return svc.createObject(template) | python | def edit_dedicated_fwl_rules(self, firewall_id, rules):
mask = ('mask[networkVlan[firewallInterfaces'
'[firewallContextAccessControlLists]]]')
svc = self.client['Network_Vlan_Firewall']
fwl = svc.getObject(id=firewall_id, mask=mask)
network_vlan = fwl['networkVlan']
for fwl1 in network_vlan['firewallInterfaces']:
if fwl1['name'] == 'inside':
continue
for control_list in fwl1['firewallContextAccessControlLists']:
if control_list['direction'] == 'out':
continue
fwl_ctx_acl_id = control_list['id']
template = {'firewallContextAccessControlListId': fwl_ctx_acl_id,
'rules': rules}
svc = self.client['Network_Firewall_Update_Request']
return svc.createObject(template) | [
"def",
"edit_dedicated_fwl_rules",
"(",
"self",
",",
"firewall_id",
",",
"rules",
")",
":",
"mask",
"=",
"(",
"'mask[networkVlan[firewallInterfaces'",
"'[firewallContextAccessControlLists]]]'",
")",
"svc",
"=",
"self",
".",
"client",
"[",
"'Network_Vlan_Firewall'",
"]",
"fwl",
"=",
"svc",
".",
"getObject",
"(",
"id",
"=",
"firewall_id",
",",
"mask",
"=",
"mask",
")",
"network_vlan",
"=",
"fwl",
"[",
"'networkVlan'",
"]",
"for",
"fwl1",
"in",
"network_vlan",
"[",
"'firewallInterfaces'",
"]",
":",
"if",
"fwl1",
"[",
"'name'",
"]",
"==",
"'inside'",
":",
"continue",
"for",
"control_list",
"in",
"fwl1",
"[",
"'firewallContextAccessControlLists'",
"]",
":",
"if",
"control_list",
"[",
"'direction'",
"]",
"==",
"'out'",
":",
"continue",
"fwl_ctx_acl_id",
"=",
"control_list",
"[",
"'id'",
"]",
"template",
"=",
"{",
"'firewallContextAccessControlListId'",
":",
"fwl_ctx_acl_id",
",",
"'rules'",
":",
"rules",
"}",
"svc",
"=",
"self",
".",
"client",
"[",
"'Network_Firewall_Update_Request'",
"]",
"return",
"svc",
".",
"createObject",
"(",
"template",
")"
]
| Edit the rules for dedicated firewall.
:param integer firewall_id: the instance ID of the dedicated firewall
:param list rules: the rules to be pushed on the firewall as defined by
SoftLayer_Network_Firewall_Update_Request_Rule | [
"Edit",
"the",
"rules",
"for",
"dedicated",
"firewall",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/firewall.py#L252-L279 |
softlayer/softlayer-python | SoftLayer/managers/firewall.py | FirewallManager.edit_standard_fwl_rules | def edit_standard_fwl_rules(self, firewall_id, rules):
"""Edit the rules for standard firewall.
:param integer firewall_id: the instance ID of the standard firewall
:param dict rules: the rules to be pushed on the firewall
"""
rule_svc = self.client['Network_Firewall_Update_Request']
template = {'networkComponentFirewallId': firewall_id, 'rules': rules}
return rule_svc.createObject(template) | python | def edit_standard_fwl_rules(self, firewall_id, rules):
rule_svc = self.client['Network_Firewall_Update_Request']
template = {'networkComponentFirewallId': firewall_id, 'rules': rules}
return rule_svc.createObject(template) | [
"def",
"edit_standard_fwl_rules",
"(",
"self",
",",
"firewall_id",
",",
"rules",
")",
":",
"rule_svc",
"=",
"self",
".",
"client",
"[",
"'Network_Firewall_Update_Request'",
"]",
"template",
"=",
"{",
"'networkComponentFirewallId'",
":",
"firewall_id",
",",
"'rules'",
":",
"rules",
"}",
"return",
"rule_svc",
".",
"createObject",
"(",
"template",
")"
]
| Edit the rules for standard firewall.
:param integer firewall_id: the instance ID of the standard firewall
:param dict rules: the rules to be pushed on the firewall | [
"Edit",
"the",
"rules",
"for",
"standard",
"firewall",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/firewall.py#L281-L291 |
softlayer/softlayer-python | SoftLayer/auth.py | TokenAuthentication.get_request | def get_request(self, request):
"""Sets token-based auth headers."""
request.headers['authenticate'] = {
'complexType': 'PortalLoginToken',
'userId': self.user_id,
'authToken': self.auth_token,
}
return request | python | def get_request(self, request):
request.headers['authenticate'] = {
'complexType': 'PortalLoginToken',
'userId': self.user_id,
'authToken': self.auth_token,
}
return request | [
"def",
"get_request",
"(",
"self",
",",
"request",
")",
":",
"request",
".",
"headers",
"[",
"'authenticate'",
"]",
"=",
"{",
"'complexType'",
":",
"'PortalLoginToken'",
",",
"'userId'",
":",
"self",
".",
"user_id",
",",
"'authToken'",
":",
"self",
".",
"auth_token",
",",
"}",
"return",
"request"
]
| Sets token-based auth headers. | [
"Sets",
"token",
"-",
"based",
"auth",
"headers",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/auth.py#L50-L57 |
softlayer/softlayer-python | SoftLayer/auth.py | BasicAuthentication.get_request | def get_request(self, request):
"""Sets token-based auth headers."""
request.headers['authenticate'] = {
'username': self.username,
'apiKey': self.api_key,
}
return request | python | def get_request(self, request):
request.headers['authenticate'] = {
'username': self.username,
'apiKey': self.api_key,
}
return request | [
"def",
"get_request",
"(",
"self",
",",
"request",
")",
":",
"request",
".",
"headers",
"[",
"'authenticate'",
"]",
"=",
"{",
"'username'",
":",
"self",
".",
"username",
",",
"'apiKey'",
":",
"self",
".",
"api_key",
",",
"}",
"return",
"request"
]
| Sets token-based auth headers. | [
"Sets",
"token",
"-",
"based",
"auth",
"headers",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/auth.py#L74-L80 |
softlayer/softlayer-python | SoftLayer/auth.py | BasicHTTPAuthentication.get_request | def get_request(self, request):
"""Sets token-based auth headers."""
request.transport_user = self.username
request.transport_password = self.api_key
return request | python | def get_request(self, request):
request.transport_user = self.username
request.transport_password = self.api_key
return request | [
"def",
"get_request",
"(",
"self",
",",
"request",
")",
":",
"request",
".",
"transport_user",
"=",
"self",
".",
"username",
"request",
".",
"transport_password",
"=",
"self",
".",
"api_key",
"return",
"request"
]
| Sets token-based auth headers. | [
"Sets",
"token",
"-",
"based",
"auth",
"headers",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/auth.py#L97-L101 |
softlayer/softlayer-python | SoftLayer/CLI/image/edit.py | cli | def cli(env, identifier, name, note, tag):
"""Edit details of an image."""
image_mgr = SoftLayer.ImageManager(env.client)
data = {}
if name:
data['name'] = name
if note:
data['note'] = note
if tag:
data['tag'] = tag
image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')
if not image_mgr.edit(image_id, **data):
raise exceptions.CLIAbort("Failed to Edit Image") | python | def cli(env, identifier, name, note, tag):
image_mgr = SoftLayer.ImageManager(env.client)
data = {}
if name:
data['name'] = name
if note:
data['note'] = note
if tag:
data['tag'] = tag
image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')
if not image_mgr.edit(image_id, **data):
raise exceptions.CLIAbort("Failed to Edit Image") | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"name",
",",
"note",
",",
"tag",
")",
":",
"image_mgr",
"=",
"SoftLayer",
".",
"ImageManager",
"(",
"env",
".",
"client",
")",
"data",
"=",
"{",
"}",
"if",
"name",
":",
"data",
"[",
"'name'",
"]",
"=",
"name",
"if",
"note",
":",
"data",
"[",
"'note'",
"]",
"=",
"note",
"if",
"tag",
":",
"data",
"[",
"'tag'",
"]",
"=",
"tag",
"image_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"image_mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'image'",
")",
"if",
"not",
"image_mgr",
".",
"edit",
"(",
"image_id",
",",
"*",
"*",
"data",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Failed to Edit Image\"",
")"
]
| Edit details of an image. | [
"Edit",
"details",
"of",
"an",
"image",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/image/edit.py#L18-L31 |
softlayer/softlayer-python | SoftLayer/CLI/ticket/attach.py | cli | def cli(env, identifier, hardware_identifier, virtual_identifier):
"""Attach devices to a ticket."""
ticket_mgr = SoftLayer.TicketManager(env.client)
if hardware_identifier and virtual_identifier:
raise exceptions.ArgumentError("Cannot attach hardware and a virtual server at the same time")
if hardware_identifier:
hardware_mgr = SoftLayer.HardwareManager(env.client)
hardware_id = helpers.resolve_id(hardware_mgr.resolve_ids, hardware_identifier, 'hardware')
ticket_mgr.attach_hardware(identifier, hardware_id)
elif virtual_identifier:
vs_mgr = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vs_mgr.resolve_ids, virtual_identifier, 'VS')
ticket_mgr.attach_virtual_server(identifier, vs_id)
else:
raise exceptions.ArgumentError("Must have a hardware or virtual server identifier to attach") | python | def cli(env, identifier, hardware_identifier, virtual_identifier):
ticket_mgr = SoftLayer.TicketManager(env.client)
if hardware_identifier and virtual_identifier:
raise exceptions.ArgumentError("Cannot attach hardware and a virtual server at the same time")
if hardware_identifier:
hardware_mgr = SoftLayer.HardwareManager(env.client)
hardware_id = helpers.resolve_id(hardware_mgr.resolve_ids, hardware_identifier, 'hardware')
ticket_mgr.attach_hardware(identifier, hardware_id)
elif virtual_identifier:
vs_mgr = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vs_mgr.resolve_ids, virtual_identifier, 'VS')
ticket_mgr.attach_virtual_server(identifier, vs_id)
else:
raise exceptions.ArgumentError("Must have a hardware or virtual server identifier to attach") | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"hardware_identifier",
",",
"virtual_identifier",
")",
":",
"ticket_mgr",
"=",
"SoftLayer",
".",
"TicketManager",
"(",
"env",
".",
"client",
")",
"if",
"hardware_identifier",
"and",
"virtual_identifier",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"\"Cannot attach hardware and a virtual server at the same time\"",
")",
"if",
"hardware_identifier",
":",
"hardware_mgr",
"=",
"SoftLayer",
".",
"HardwareManager",
"(",
"env",
".",
"client",
")",
"hardware_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"hardware_mgr",
".",
"resolve_ids",
",",
"hardware_identifier",
",",
"'hardware'",
")",
"ticket_mgr",
".",
"attach_hardware",
"(",
"identifier",
",",
"hardware_id",
")",
"elif",
"virtual_identifier",
":",
"vs_mgr",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vs_mgr",
".",
"resolve_ids",
",",
"virtual_identifier",
",",
"'VS'",
")",
"ticket_mgr",
".",
"attach_virtual_server",
"(",
"identifier",
",",
"vs_id",
")",
"else",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"\"Must have a hardware or virtual server identifier to attach\"",
")"
]
| Attach devices to a ticket. | [
"Attach",
"devices",
"to",
"a",
"ticket",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ticket/attach.py#L19-L35 |
softlayer/softlayer-python | SoftLayer/managers/metadata.py | MetadataManager.get | def get(self, name, param=None):
"""Retreive a metadata attribute.
:param string name: name of the attribute to retrieve. See `attribs`
:param param: Required parameter for some attributes
"""
if name not in self.attribs:
raise exceptions.SoftLayerError('Unknown metadata attribute.')
call_details = self.attribs[name]
if call_details.get('param_req'):
if not param:
raise exceptions.SoftLayerError(
'Parameter required to get this attribute.')
params = tuple()
if param is not None:
params = (param,)
try:
return self.client.call('Resource_Metadata',
self.attribs[name]['call'],
*params)
except exceptions.SoftLayerAPIError as ex:
if ex.faultCode == 404:
return None
raise ex | python | def get(self, name, param=None):
if name not in self.attribs:
raise exceptions.SoftLayerError('Unknown metadata attribute.')
call_details = self.attribs[name]
if call_details.get('param_req'):
if not param:
raise exceptions.SoftLayerError(
'Parameter required to get this attribute.')
params = tuple()
if param is not None:
params = (param,)
try:
return self.client.call('Resource_Metadata',
self.attribs[name]['call'],
*params)
except exceptions.SoftLayerAPIError as ex:
if ex.faultCode == 404:
return None
raise ex | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"param",
"=",
"None",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"attribs",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"'Unknown metadata attribute.'",
")",
"call_details",
"=",
"self",
".",
"attribs",
"[",
"name",
"]",
"if",
"call_details",
".",
"get",
"(",
"'param_req'",
")",
":",
"if",
"not",
"param",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"'Parameter required to get this attribute.'",
")",
"params",
"=",
"tuple",
"(",
")",
"if",
"param",
"is",
"not",
"None",
":",
"params",
"=",
"(",
"param",
",",
")",
"try",
":",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'Resource_Metadata'",
",",
"self",
".",
"attribs",
"[",
"name",
"]",
"[",
"'call'",
"]",
",",
"*",
"params",
")",
"except",
"exceptions",
".",
"SoftLayerAPIError",
"as",
"ex",
":",
"if",
"ex",
".",
"faultCode",
"==",
"404",
":",
"return",
"None",
"raise",
"ex"
]
| Retreive a metadata attribute.
:param string name: name of the attribute to retrieve. See `attribs`
:param param: Required parameter for some attributes | [
"Retreive",
"a",
"metadata",
"attribute",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/metadata.py#L73-L100 |
softlayer/softlayer-python | SoftLayer/managers/metadata.py | MetadataManager._get_network | def _get_network(self, kind, router=True, vlans=True, vlan_ids=True):
"""Wrapper for getting details about networks.
:param string kind: network kind. Typically 'public' or 'private'
:param boolean router: flag to include router information
:param boolean vlans: flag to include vlan information
:param boolean vlan_ids: flag to include vlan_ids
"""
network = {}
macs = self.get('%s_mac' % kind)
network['mac_addresses'] = macs
if len(macs) == 0:
return network
if router:
network['router'] = self.get('router', macs[0])
if vlans:
network['vlans'] = self.get('vlans', macs[0])
if vlan_ids:
network['vlan_ids'] = self.get('vlan_ids', macs[0])
return network | python | def _get_network(self, kind, router=True, vlans=True, vlan_ids=True):
network = {}
macs = self.get('%s_mac' % kind)
network['mac_addresses'] = macs
if len(macs) == 0:
return network
if router:
network['router'] = self.get('router', macs[0])
if vlans:
network['vlans'] = self.get('vlans', macs[0])
if vlan_ids:
network['vlan_ids'] = self.get('vlan_ids', macs[0])
return network | [
"def",
"_get_network",
"(",
"self",
",",
"kind",
",",
"router",
"=",
"True",
",",
"vlans",
"=",
"True",
",",
"vlan_ids",
"=",
"True",
")",
":",
"network",
"=",
"{",
"}",
"macs",
"=",
"self",
".",
"get",
"(",
"'%s_mac'",
"%",
"kind",
")",
"network",
"[",
"'mac_addresses'",
"]",
"=",
"macs",
"if",
"len",
"(",
"macs",
")",
"==",
"0",
":",
"return",
"network",
"if",
"router",
":",
"network",
"[",
"'router'",
"]",
"=",
"self",
".",
"get",
"(",
"'router'",
",",
"macs",
"[",
"0",
"]",
")",
"if",
"vlans",
":",
"network",
"[",
"'vlans'",
"]",
"=",
"self",
".",
"get",
"(",
"'vlans'",
",",
"macs",
"[",
"0",
"]",
")",
"if",
"vlan_ids",
":",
"network",
"[",
"'vlan_ids'",
"]",
"=",
"self",
".",
"get",
"(",
"'vlan_ids'",
",",
"macs",
"[",
"0",
"]",
")",
"return",
"network"
]
| Wrapper for getting details about networks.
:param string kind: network kind. Typically 'public' or 'private'
:param boolean router: flag to include router information
:param boolean vlans: flag to include vlan information
:param boolean vlan_ids: flag to include vlan_ids | [
"Wrapper",
"for",
"getting",
"details",
"about",
"networks",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/metadata.py#L102-L127 |
softlayer/softlayer-python | SoftLayer/shell/cmd_env.py | cli | def cli(env):
"""Print environment variables."""
filtered_vars = dict([(k, v)
for k, v in env.vars.items()
if not k.startswith('_')])
env.fout(formatting.iter_to_table(filtered_vars)) | python | def cli(env):
filtered_vars = dict([(k, v)
for k, v in env.vars.items()
if not k.startswith('_')])
env.fout(formatting.iter_to_table(filtered_vars)) | [
"def",
"cli",
"(",
"env",
")",
":",
"filtered_vars",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"env",
".",
"vars",
".",
"items",
"(",
")",
"if",
"not",
"k",
".",
"startswith",
"(",
"'_'",
")",
"]",
")",
"env",
".",
"fout",
"(",
"formatting",
".",
"iter_to_table",
"(",
"filtered_vars",
")",
")"
]
| Print environment variables. | [
"Print",
"environment",
"variables",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/shell/cmd_env.py#L12-L17 |
softlayer/softlayer-python | SoftLayer/CLI/block/snapshot/restore.py | cli | def cli(env, volume_id, snapshot_id):
"""Restore block volume using a given snapshot"""
block_manager = SoftLayer.BlockStorageManager(env.client)
success = block_manager.restore_from_snapshot(volume_id, snapshot_id)
if success:
click.echo('Block volume %s is being restored using snapshot %s'
% (volume_id, snapshot_id)) | python | def cli(env, volume_id, snapshot_id):
block_manager = SoftLayer.BlockStorageManager(env.client)
success = block_manager.restore_from_snapshot(volume_id, snapshot_id)
if success:
click.echo('Block volume %s is being restored using snapshot %s'
% (volume_id, snapshot_id)) | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"snapshot_id",
")",
":",
"block_manager",
"=",
"SoftLayer",
".",
"BlockStorageManager",
"(",
"env",
".",
"client",
")",
"success",
"=",
"block_manager",
".",
"restore_from_snapshot",
"(",
"volume_id",
",",
"snapshot_id",
")",
"if",
"success",
":",
"click",
".",
"echo",
"(",
"'Block volume %s is being restored using snapshot %s'",
"%",
"(",
"volume_id",
",",
"snapshot_id",
")",
")"
]
| Restore block volume using a given snapshot | [
"Restore",
"block",
"volume",
"using",
"a",
"given",
"snapshot"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/snapshot/restore.py#L15-L22 |
softlayer/softlayer-python | SoftLayer/CLI/ssl/add.py | cli | def cli(env, crt, csr, icc, key, notes):
"""Add and upload SSL certificate details."""
template = {
'intermediateCertificate': '',
'certificateSigningRequest': '',
'notes': notes,
}
template['certificate'] = open(crt).read()
template['privateKey'] = open(key).read()
if csr:
body = open(csr).read()
template['certificateSigningRequest'] = body
if icc:
body = open(icc).read()
template['intermediateCertificate'] = body
manager = SoftLayer.SSLManager(env.client)
manager.add_certificate(template) | python | def cli(env, crt, csr, icc, key, notes):
template = {
'intermediateCertificate': '',
'certificateSigningRequest': '',
'notes': notes,
}
template['certificate'] = open(crt).read()
template['privateKey'] = open(key).read()
if csr:
body = open(csr).read()
template['certificateSigningRequest'] = body
if icc:
body = open(icc).read()
template['intermediateCertificate'] = body
manager = SoftLayer.SSLManager(env.client)
manager.add_certificate(template) | [
"def",
"cli",
"(",
"env",
",",
"crt",
",",
"csr",
",",
"icc",
",",
"key",
",",
"notes",
")",
":",
"template",
"=",
"{",
"'intermediateCertificate'",
":",
"''",
",",
"'certificateSigningRequest'",
":",
"''",
",",
"'notes'",
":",
"notes",
",",
"}",
"template",
"[",
"'certificate'",
"]",
"=",
"open",
"(",
"crt",
")",
".",
"read",
"(",
")",
"template",
"[",
"'privateKey'",
"]",
"=",
"open",
"(",
"key",
")",
".",
"read",
"(",
")",
"if",
"csr",
":",
"body",
"=",
"open",
"(",
"csr",
")",
".",
"read",
"(",
")",
"template",
"[",
"'certificateSigningRequest'",
"]",
"=",
"body",
"if",
"icc",
":",
"body",
"=",
"open",
"(",
"icc",
")",
".",
"read",
"(",
")",
"template",
"[",
"'intermediateCertificate'",
"]",
"=",
"body",
"manager",
"=",
"SoftLayer",
".",
"SSLManager",
"(",
"env",
".",
"client",
")",
"manager",
".",
"add_certificate",
"(",
"template",
")"
]
| Add and upload SSL certificate details. | [
"Add",
"and",
"upload",
"SSL",
"certificate",
"details",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ssl/add.py#L23-L42 |
softlayer/softlayer-python | SoftLayer/CLI/dedicatedhost/detail.py | cli | def cli(env, identifier, price=False, guests=False):
"""Get details for a virtual server."""
dhost = SoftLayer.DedicatedHostManager(env.client)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
result = dhost.get_host(identifier)
result = utils.NestedDict(result)
table.add_row(['id', result['id']])
table.add_row(['name', result['name']])
table.add_row(['cpu count', result['cpuCount']])
table.add_row(['memory capacity', result['memoryCapacity']])
table.add_row(['disk capacity', result['diskCapacity']])
table.add_row(['create date', result['createDate']])
table.add_row(['modify date', result['modifyDate']])
table.add_row(['router id', result['backendRouter']['id']])
table.add_row(['router hostname', result['backendRouter']['hostname']])
table.add_row(['owner', formatting.FormattedItem(
utils.lookup(result, 'billingItem', 'orderItem', 'order', 'userRecord', 'username') or formatting.blank(),)])
if price:
total_price = utils.lookup(result,
'billingItem',
'nextInvoiceTotalRecurringAmount') or 0
total_price += sum(p['nextInvoiceTotalRecurringAmount']
for p
in utils.lookup(result,
'billingItem',
'children') or [])
table.add_row(['price_rate', total_price])
table.add_row(['guest count', result['guestCount']])
if guests:
guest_table = formatting.Table(['id', 'hostname', 'domain', 'uuid'])
for guest in result['guests']:
guest_table.add_row([
guest['id'], guest['hostname'], guest['domain'], guest['uuid']])
table.add_row(['guests', guest_table])
table.add_row(['datacenter', result['datacenter']['name']])
env.fout(table) | python | def cli(env, identifier, price=False, guests=False):
dhost = SoftLayer.DedicatedHostManager(env.client)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
result = dhost.get_host(identifier)
result = utils.NestedDict(result)
table.add_row(['id', result['id']])
table.add_row(['name', result['name']])
table.add_row(['cpu count', result['cpuCount']])
table.add_row(['memory capacity', result['memoryCapacity']])
table.add_row(['disk capacity', result['diskCapacity']])
table.add_row(['create date', result['createDate']])
table.add_row(['modify date', result['modifyDate']])
table.add_row(['router id', result['backendRouter']['id']])
table.add_row(['router hostname', result['backendRouter']['hostname']])
table.add_row(['owner', formatting.FormattedItem(
utils.lookup(result, 'billingItem', 'orderItem', 'order', 'userRecord', 'username') or formatting.blank(),)])
if price:
total_price = utils.lookup(result,
'billingItem',
'nextInvoiceTotalRecurringAmount') or 0
total_price += sum(p['nextInvoiceTotalRecurringAmount']
for p
in utils.lookup(result,
'billingItem',
'children') or [])
table.add_row(['price_rate', total_price])
table.add_row(['guest count', result['guestCount']])
if guests:
guest_table = formatting.Table(['id', 'hostname', 'domain', 'uuid'])
for guest in result['guests']:
guest_table.add_row([
guest['id'], guest['hostname'], guest['domain'], guest['uuid']])
table.add_row(['guests', guest_table])
table.add_row(['datacenter', result['datacenter']['name']])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"price",
"=",
"False",
",",
"guests",
"=",
"False",
")",
":",
"dhost",
"=",
"SoftLayer",
".",
"DedicatedHostManager",
"(",
"env",
".",
"client",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"result",
"=",
"dhost",
".",
"get_host",
"(",
"identifier",
")",
"result",
"=",
"utils",
".",
"NestedDict",
"(",
"result",
")",
"table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"result",
"[",
"'id'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'name'",
",",
"result",
"[",
"'name'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'cpu count'",
",",
"result",
"[",
"'cpuCount'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'memory capacity'",
",",
"result",
"[",
"'memoryCapacity'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'disk capacity'",
",",
"result",
"[",
"'diskCapacity'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'create date'",
",",
"result",
"[",
"'createDate'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'modify date'",
",",
"result",
"[",
"'modifyDate'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'router id'",
",",
"result",
"[",
"'backendRouter'",
"]",
"[",
"'id'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'router hostname'",
",",
"result",
"[",
"'backendRouter'",
"]",
"[",
"'hostname'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'owner'",
",",
"formatting",
".",
"FormattedItem",
"(",
"utils",
".",
"lookup",
"(",
"result",
",",
"'billingItem'",
",",
"'orderItem'",
",",
"'order'",
",",
"'userRecord'",
",",
"'username'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
",",
")",
"]",
")",
"if",
"price",
":",
"total_price",
"=",
"utils",
".",
"lookup",
"(",
"result",
",",
"'billingItem'",
",",
"'nextInvoiceTotalRecurringAmount'",
")",
"or",
"0",
"total_price",
"+=",
"sum",
"(",
"p",
"[",
"'nextInvoiceTotalRecurringAmount'",
"]",
"for",
"p",
"in",
"utils",
".",
"lookup",
"(",
"result",
",",
"'billingItem'",
",",
"'children'",
")",
"or",
"[",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'price_rate'",
",",
"total_price",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'guest count'",
",",
"result",
"[",
"'guestCount'",
"]",
"]",
")",
"if",
"guests",
":",
"guest_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'hostname'",
",",
"'domain'",
",",
"'uuid'",
"]",
")",
"for",
"guest",
"in",
"result",
"[",
"'guests'",
"]",
":",
"guest_table",
".",
"add_row",
"(",
"[",
"guest",
"[",
"'id'",
"]",
",",
"guest",
"[",
"'hostname'",
"]",
",",
"guest",
"[",
"'domain'",
"]",
",",
"guest",
"[",
"'uuid'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'guests'",
",",
"guest_table",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'datacenter'",
",",
"result",
"[",
"'datacenter'",
"]",
"[",
"'name'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Get details for a virtual server. | [
"Get",
"details",
"for",
"a",
"virtual",
"server",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dedicatedhost/detail.py#L21-L65 |
softlayer/softlayer-python | SoftLayer/CLI/image/export.py | cli | def cli(env, identifier, uri, ibm_api_key):
"""Export an image to object storage.
The URI for an object storage object (.vhd/.iso file) of the format:
swift://<objectStorageAccount>@<cluster>/<container>/<objectPath>
or cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud
Object Storage
"""
image_mgr = SoftLayer.ImageManager(env.client)
image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')
result = image_mgr.export_image_to_uri(image_id, uri, ibm_api_key)
if not result:
raise exceptions.CLIAbort("Failed to export Image") | python | def cli(env, identifier, uri, ibm_api_key):
image_mgr = SoftLayer.ImageManager(env.client)
image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')
result = image_mgr.export_image_to_uri(image_id, uri, ibm_api_key)
if not result:
raise exceptions.CLIAbort("Failed to export Image") | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"uri",
",",
"ibm_api_key",
")",
":",
"image_mgr",
"=",
"SoftLayer",
".",
"ImageManager",
"(",
"env",
".",
"client",
")",
"image_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"image_mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'image'",
")",
"result",
"=",
"image_mgr",
".",
"export_image_to_uri",
"(",
"image_id",
",",
"uri",
",",
"ibm_api_key",
")",
"if",
"not",
"result",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Failed to export Image\"",
")"
]
| Export an image to object storage.
The URI for an object storage object (.vhd/.iso file) of the format:
swift://<objectStorageAccount>@<cluster>/<container>/<objectPath>
or cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud
Object Storage | [
"Export",
"an",
"image",
"to",
"object",
"storage",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/image/export.py#L22-L36 |
softlayer/softlayer-python | SoftLayer/CLI/account/invoices.py | cli | def cli(env, limit, closed=False, get_all=False):
"""Invoices and all that mess"""
manager = AccountManager(env.client)
invoices = manager.get_invoices(limit, closed, get_all)
table = formatting.Table([
"Id", "Created", "Type", "Status", "Starting Balance", "Ending Balance", "Invoice Amount", "Items"
])
table.align['Starting Balance'] = 'l'
table.align['Ending Balance'] = 'l'
table.align['Invoice Amount'] = 'l'
table.align['Items'] = 'l'
if isinstance(invoices, dict):
invoices = [invoices]
for invoice in invoices:
table.add_row([
invoice.get('id'),
utils.clean_time(invoice.get('createDate'), out_format="%Y-%m-%d"),
invoice.get('typeCode'),
invoice.get('statusCode'),
invoice.get('startingBalance'),
invoice.get('endingBalance'),
invoice.get('invoiceTotalAmount'),
invoice.get('itemCount')
])
env.fout(table) | python | def cli(env, limit, closed=False, get_all=False):
manager = AccountManager(env.client)
invoices = manager.get_invoices(limit, closed, get_all)
table = formatting.Table([
"Id", "Created", "Type", "Status", "Starting Balance", "Ending Balance", "Invoice Amount", "Items"
])
table.align['Starting Balance'] = 'l'
table.align['Ending Balance'] = 'l'
table.align['Invoice Amount'] = 'l'
table.align['Items'] = 'l'
if isinstance(invoices, dict):
invoices = [invoices]
for invoice in invoices:
table.add_row([
invoice.get('id'),
utils.clean_time(invoice.get('createDate'), out_format="%Y-%m-%d"),
invoice.get('typeCode'),
invoice.get('statusCode'),
invoice.get('startingBalance'),
invoice.get('endingBalance'),
invoice.get('invoiceTotalAmount'),
invoice.get('itemCount')
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"limit",
",",
"closed",
"=",
"False",
",",
"get_all",
"=",
"False",
")",
":",
"manager",
"=",
"AccountManager",
"(",
"env",
".",
"client",
")",
"invoices",
"=",
"manager",
".",
"get_invoices",
"(",
"limit",
",",
"closed",
",",
"get_all",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"\"Id\"",
",",
"\"Created\"",
",",
"\"Type\"",
",",
"\"Status\"",
",",
"\"Starting Balance\"",
",",
"\"Ending Balance\"",
",",
"\"Invoice Amount\"",
",",
"\"Items\"",
"]",
")",
"table",
".",
"align",
"[",
"'Starting Balance'",
"]",
"=",
"'l'",
"table",
".",
"align",
"[",
"'Ending Balance'",
"]",
"=",
"'l'",
"table",
".",
"align",
"[",
"'Invoice Amount'",
"]",
"=",
"'l'",
"table",
".",
"align",
"[",
"'Items'",
"]",
"=",
"'l'",
"if",
"isinstance",
"(",
"invoices",
",",
"dict",
")",
":",
"invoices",
"=",
"[",
"invoices",
"]",
"for",
"invoice",
"in",
"invoices",
":",
"table",
".",
"add_row",
"(",
"[",
"invoice",
".",
"get",
"(",
"'id'",
")",
",",
"utils",
".",
"clean_time",
"(",
"invoice",
".",
"get",
"(",
"'createDate'",
")",
",",
"out_format",
"=",
"\"%Y-%m-%d\"",
")",
",",
"invoice",
".",
"get",
"(",
"'typeCode'",
")",
",",
"invoice",
".",
"get",
"(",
"'statusCode'",
")",
",",
"invoice",
".",
"get",
"(",
"'startingBalance'",
")",
",",
"invoice",
".",
"get",
"(",
"'endingBalance'",
")",
",",
"invoice",
".",
"get",
"(",
"'invoiceTotalAmount'",
")",
",",
"invoice",
".",
"get",
"(",
"'itemCount'",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Invoices and all that mess | [
"Invoices",
"and",
"all",
"that",
"mess"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/invoices.py#L20-L46 |
softlayer/softlayer-python | SoftLayer/CLI/virt/__init__.py | MemoryType.convert | def convert(self, value, param, ctx): # pylint: disable=inconsistent-return-statements
"""Validate memory argument. Returns the memory value in megabytes."""
matches = MEMORY_RE.match(value.lower())
if matches is None:
self.fail('%s is not a valid value for memory amount' % value, param, ctx)
amount_str, unit = matches.groups()
amount = int(amount_str)
if unit in [None, 'm', 'mb']:
# Assume the user intends gigabytes if they specify a number < 1024
if amount < 1024:
return amount * 1024
else:
if amount % 1024 != 0:
self.fail('%s is not an integer that is divisable by 1024' % value, param, ctx)
return amount
elif unit in ['g', 'gb']:
return amount * 1024 | python | def convert(self, value, param, ctx):
matches = MEMORY_RE.match(value.lower())
if matches is None:
self.fail('%s is not a valid value for memory amount' % value, param, ctx)
amount_str, unit = matches.groups()
amount = int(amount_str)
if unit in [None, 'm', 'mb']:
if amount < 1024:
return amount * 1024
else:
if amount % 1024 != 0:
self.fail('%s is not an integer that is divisable by 1024' % value, param, ctx)
return amount
elif unit in ['g', 'gb']:
return amount * 1024 | [
"def",
"convert",
"(",
"self",
",",
"value",
",",
"param",
",",
"ctx",
")",
":",
"# pylint: disable=inconsistent-return-statements",
"matches",
"=",
"MEMORY_RE",
".",
"match",
"(",
"value",
".",
"lower",
"(",
")",
")",
"if",
"matches",
"is",
"None",
":",
"self",
".",
"fail",
"(",
"'%s is not a valid value for memory amount'",
"%",
"value",
",",
"param",
",",
"ctx",
")",
"amount_str",
",",
"unit",
"=",
"matches",
".",
"groups",
"(",
")",
"amount",
"=",
"int",
"(",
"amount_str",
")",
"if",
"unit",
"in",
"[",
"None",
",",
"'m'",
",",
"'mb'",
"]",
":",
"# Assume the user intends gigabytes if they specify a number < 1024",
"if",
"amount",
"<",
"1024",
":",
"return",
"amount",
"*",
"1024",
"else",
":",
"if",
"amount",
"%",
"1024",
"!=",
"0",
":",
"self",
".",
"fail",
"(",
"'%s is not an integer that is divisable by 1024'",
"%",
"value",
",",
"param",
",",
"ctx",
")",
"return",
"amount",
"elif",
"unit",
"in",
"[",
"'g'",
",",
"'gb'",
"]",
":",
"return",
"amount",
"*",
"1024"
]
| Validate memory argument. Returns the memory value in megabytes. | [
"Validate",
"memory",
"argument",
".",
"Returns",
"the",
"memory",
"value",
"in",
"megabytes",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/__init__.py#L15-L31 |
softlayer/softlayer-python | SoftLayer/CLI/nas/credentials.py | cli | def cli(env, identifier):
"""List NAS account credentials."""
nw_mgr = SoftLayer.NetworkManager(env.client)
result = nw_mgr.get_nas_credentials(identifier)
table = formatting.Table(['username', 'password'])
table.add_row([result.get('username', 'None'),
result.get('password', 'None')])
env.fout(table) | python | def cli(env, identifier):
nw_mgr = SoftLayer.NetworkManager(env.client)
result = nw_mgr.get_nas_credentials(identifier)
table = formatting.Table(['username', 'password'])
table.add_row([result.get('username', 'None'),
result.get('password', 'None')])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"nw_mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"result",
"=",
"nw_mgr",
".",
"get_nas_credentials",
"(",
"identifier",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'username'",
",",
"'password'",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"result",
".",
"get",
"(",
"'username'",
",",
"'None'",
")",
",",
"result",
".",
"get",
"(",
"'password'",
",",
"'None'",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| List NAS account credentials. | [
"List",
"NAS",
"account",
"credentials",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/nas/credentials.py#L14-L22 |
softlayer/softlayer-python | SoftLayer/CLI/firewall/detail.py | cli | def cli(env, identifier):
"""Detail firewall."""
mgr = SoftLayer.FirewallManager(env.client)
firewall_type, firewall_id = firewall.parse_id(identifier)
if firewall_type == 'vlan':
rules = mgr.get_dedicated_fwl_rules(firewall_id)
else:
rules = mgr.get_standard_fwl_rules(firewall_id)
env.fout(get_rules_table(rules)) | python | def cli(env, identifier):
mgr = SoftLayer.FirewallManager(env.client)
firewall_type, firewall_id = firewall.parse_id(identifier)
if firewall_type == 'vlan':
rules = mgr.get_dedicated_fwl_rules(firewall_id)
else:
rules = mgr.get_standard_fwl_rules(firewall_id)
env.fout(get_rules_table(rules)) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"FirewallManager",
"(",
"env",
".",
"client",
")",
"firewall_type",
",",
"firewall_id",
"=",
"firewall",
".",
"parse_id",
"(",
"identifier",
")",
"if",
"firewall_type",
"==",
"'vlan'",
":",
"rules",
"=",
"mgr",
".",
"get_dedicated_fwl_rules",
"(",
"firewall_id",
")",
"else",
":",
"rules",
"=",
"mgr",
".",
"get_standard_fwl_rules",
"(",
"firewall_id",
")",
"env",
".",
"fout",
"(",
"get_rules_table",
"(",
"rules",
")",
")"
]
| Detail firewall. | [
"Detail",
"firewall",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/detail.py#L16-L27 |
softlayer/softlayer-python | SoftLayer/CLI/firewall/detail.py | get_rules_table | def get_rules_table(rules):
"""Helper to format the rules into a table.
:param list rules: A list containing the rules of the firewall
:returns: a formatted table of the firewall rules
"""
table = formatting.Table(['#', 'action', 'protocol', 'src_ip', 'src_mask',
'dest', 'dest_mask'])
table.sortby = '#'
for rule in rules:
table.add_row([
rule['orderValue'],
rule['action'],
rule['protocol'],
rule['sourceIpAddress'],
utils.lookup(rule, 'sourceIpSubnetMask'),
'%s:%s-%s' % (rule['destinationIpAddress'],
rule['destinationPortRangeStart'],
rule['destinationPortRangeEnd']),
utils.lookup(rule, 'destinationIpSubnetMask')])
return table | python | def get_rules_table(rules):
table = formatting.Table(['
'dest', 'dest_mask'])
table.sortby = '
for rule in rules:
table.add_row([
rule['orderValue'],
rule['action'],
rule['protocol'],
rule['sourceIpAddress'],
utils.lookup(rule, 'sourceIpSubnetMask'),
'%s:%s-%s' % (rule['destinationIpAddress'],
rule['destinationPortRangeStart'],
rule['destinationPortRangeEnd']),
utils.lookup(rule, 'destinationIpSubnetMask')])
return table | [
"def",
"get_rules_table",
"(",
"rules",
")",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'#'",
",",
"'action'",
",",
"'protocol'",
",",
"'src_ip'",
",",
"'src_mask'",
",",
"'dest'",
",",
"'dest_mask'",
"]",
")",
"table",
".",
"sortby",
"=",
"'#'",
"for",
"rule",
"in",
"rules",
":",
"table",
".",
"add_row",
"(",
"[",
"rule",
"[",
"'orderValue'",
"]",
",",
"rule",
"[",
"'action'",
"]",
",",
"rule",
"[",
"'protocol'",
"]",
",",
"rule",
"[",
"'sourceIpAddress'",
"]",
",",
"utils",
".",
"lookup",
"(",
"rule",
",",
"'sourceIpSubnetMask'",
")",
",",
"'%s:%s-%s'",
"%",
"(",
"rule",
"[",
"'destinationIpAddress'",
"]",
",",
"rule",
"[",
"'destinationPortRangeStart'",
"]",
",",
"rule",
"[",
"'destinationPortRangeEnd'",
"]",
")",
",",
"utils",
".",
"lookup",
"(",
"rule",
",",
"'destinationIpSubnetMask'",
")",
"]",
")",
"return",
"table"
]
| Helper to format the rules into a table.
:param list rules: A list containing the rules of the firewall
:returns: a formatted table of the firewall rules | [
"Helper",
"to",
"format",
"the",
"rules",
"into",
"a",
"table",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/detail.py#L30-L50 |
softlayer/softlayer-python | SoftLayer/managers/sshkey.py | SshKeyManager.add_key | def add_key(self, key, label, notes=None):
"""Adds a new SSH key to the account.
:param string key: The SSH key to add
:param string label: The label for the key
:param string notes: Additional notes for the key
:returns: A dictionary of the new key's information.
"""
order = {
'key': key,
'label': label,
'notes': notes,
}
return self.sshkey.createObject(order) | python | def add_key(self, key, label, notes=None):
order = {
'key': key,
'label': label,
'notes': notes,
}
return self.sshkey.createObject(order) | [
"def",
"add_key",
"(",
"self",
",",
"key",
",",
"label",
",",
"notes",
"=",
"None",
")",
":",
"order",
"=",
"{",
"'key'",
":",
"key",
",",
"'label'",
":",
"label",
",",
"'notes'",
":",
"notes",
",",
"}",
"return",
"self",
".",
"sshkey",
".",
"createObject",
"(",
"order",
")"
]
| Adds a new SSH key to the account.
:param string key: The SSH key to add
:param string label: The label for the key
:param string notes: Additional notes for the key
:returns: A dictionary of the new key's information. | [
"Adds",
"a",
"new",
"SSH",
"key",
"to",
"the",
"account",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/sshkey.py#L26-L40 |
softlayer/softlayer-python | SoftLayer/managers/sshkey.py | SshKeyManager.edit_key | def edit_key(self, key_id, label=None, notes=None):
"""Edits information about an SSH key.
:param int key_id: The ID of the key to edit
:param string label: The new label for the key
:param string notes: Notes to set or change on the key
:returns: A Boolean indicating success or failure
"""
data = {}
if label:
data['label'] = label
if notes:
data['notes'] = notes
return self.sshkey.editObject(data, id=key_id) | python | def edit_key(self, key_id, label=None, notes=None):
data = {}
if label:
data['label'] = label
if notes:
data['notes'] = notes
return self.sshkey.editObject(data, id=key_id) | [
"def",
"edit_key",
"(",
"self",
",",
"key_id",
",",
"label",
"=",
"None",
",",
"notes",
"=",
"None",
")",
":",
"data",
"=",
"{",
"}",
"if",
"label",
":",
"data",
"[",
"'label'",
"]",
"=",
"label",
"if",
"notes",
":",
"data",
"[",
"'notes'",
"]",
"=",
"notes",
"return",
"self",
".",
"sshkey",
".",
"editObject",
"(",
"data",
",",
"id",
"=",
"key_id",
")"
]
| Edits information about an SSH key.
:param int key_id: The ID of the key to edit
:param string label: The new label for the key
:param string notes: Notes to set or change on the key
:returns: A Boolean indicating success or failure | [
"Edits",
"information",
"about",
"an",
"SSH",
"key",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/sshkey.py#L50-L66 |
softlayer/softlayer-python | SoftLayer/managers/sshkey.py | SshKeyManager.list_keys | def list_keys(self, label=None):
"""Lists all SSH keys on the account.
:param string label: Filter list based on SSH key label
:returns: A list of dictionaries with information about each key
"""
_filter = utils.NestedDict({})
if label:
_filter['sshKeys']['label'] = utils.query_filter(label)
return self.client['Account'].getSshKeys(filter=_filter.to_dict()) | python | def list_keys(self, label=None):
_filter = utils.NestedDict({})
if label:
_filter['sshKeys']['label'] = utils.query_filter(label)
return self.client['Account'].getSshKeys(filter=_filter.to_dict()) | [
"def",
"list_keys",
"(",
"self",
",",
"label",
"=",
"None",
")",
":",
"_filter",
"=",
"utils",
".",
"NestedDict",
"(",
"{",
"}",
")",
"if",
"label",
":",
"_filter",
"[",
"'sshKeys'",
"]",
"[",
"'label'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"label",
")",
"return",
"self",
".",
"client",
"[",
"'Account'",
"]",
".",
"getSshKeys",
"(",
"filter",
"=",
"_filter",
".",
"to_dict",
"(",
")",
")"
]
| Lists all SSH keys on the account.
:param string label: Filter list based on SSH key label
:returns: A list of dictionaries with information about each key | [
"Lists",
"all",
"SSH",
"keys",
"on",
"the",
"account",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/sshkey.py#L76-L86 |
softlayer/softlayer-python | SoftLayer/managers/sshkey.py | SshKeyManager._get_ids_from_label | def _get_ids_from_label(self, label):
"""Return sshkey IDs which match the given label."""
keys = self.list_keys()
results = []
for key in keys:
if key['label'] == label:
results.append(key['id'])
return results | python | def _get_ids_from_label(self, label):
keys = self.list_keys()
results = []
for key in keys:
if key['label'] == label:
results.append(key['id'])
return results | [
"def",
"_get_ids_from_label",
"(",
"self",
",",
"label",
")",
":",
"keys",
"=",
"self",
".",
"list_keys",
"(",
")",
"results",
"=",
"[",
"]",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
"[",
"'label'",
"]",
"==",
"label",
":",
"results",
".",
"append",
"(",
"key",
"[",
"'id'",
"]",
")",
"return",
"results"
]
| Return sshkey IDs which match the given label. | [
"Return",
"sshkey",
"IDs",
"which",
"match",
"the",
"given",
"label",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/sshkey.py#L88-L95 |
softlayer/softlayer-python | SoftLayer/CLI/ssl/download.py | cli | def cli(env, identifier):
"""Download SSL certificate and key file."""
manager = SoftLayer.SSLManager(env.client)
certificate = manager.get_certificate(identifier)
write_cert(certificate['commonName'] + '.crt', certificate['certificate'])
write_cert(certificate['commonName'] + '.key', certificate['privateKey'])
if 'intermediateCertificate' in certificate:
write_cert(certificate['commonName'] + '.icc',
certificate['intermediateCertificate'])
if 'certificateSigningRequest' in certificate:
write_cert(certificate['commonName'] + '.csr',
certificate['certificateSigningRequest']) | python | def cli(env, identifier):
manager = SoftLayer.SSLManager(env.client)
certificate = manager.get_certificate(identifier)
write_cert(certificate['commonName'] + '.crt', certificate['certificate'])
write_cert(certificate['commonName'] + '.key', certificate['privateKey'])
if 'intermediateCertificate' in certificate:
write_cert(certificate['commonName'] + '.icc',
certificate['intermediateCertificate'])
if 'certificateSigningRequest' in certificate:
write_cert(certificate['commonName'] + '.csr',
certificate['certificateSigningRequest']) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"SSLManager",
"(",
"env",
".",
"client",
")",
"certificate",
"=",
"manager",
".",
"get_certificate",
"(",
"identifier",
")",
"write_cert",
"(",
"certificate",
"[",
"'commonName'",
"]",
"+",
"'.crt'",
",",
"certificate",
"[",
"'certificate'",
"]",
")",
"write_cert",
"(",
"certificate",
"[",
"'commonName'",
"]",
"+",
"'.key'",
",",
"certificate",
"[",
"'privateKey'",
"]",
")",
"if",
"'intermediateCertificate'",
"in",
"certificate",
":",
"write_cert",
"(",
"certificate",
"[",
"'commonName'",
"]",
"+",
"'.icc'",
",",
"certificate",
"[",
"'intermediateCertificate'",
"]",
")",
"if",
"'certificateSigningRequest'",
"in",
"certificate",
":",
"write_cert",
"(",
"certificate",
"[",
"'commonName'",
"]",
"+",
"'.csr'",
",",
"certificate",
"[",
"'certificateSigningRequest'",
"]",
")"
]
| Download SSL certificate and key file. | [
"Download",
"SSL",
"certificate",
"and",
"key",
"file",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ssl/download.py#L13-L28 |
softlayer/softlayer-python | SoftLayer/CLI/virt/capture.py | cli | def cli(env, identifier, name, all, note):
"""Capture one or all disks from a virtual server to a SoftLayer image."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
capture = vsi.capture(vs_id, name, all, note)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['vs_id', capture['guestId']])
table.add_row(['date', capture['createDate'][:10]])
table.add_row(['time', capture['createDate'][11:19]])
table.add_row(['transaction', formatting.transaction_status(capture)])
table.add_row(['transaction_id', capture['id']])
table.add_row(['all_disks', all])
env.fout(table) | python | def cli(env, identifier, name, all, note):
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
capture = vsi.capture(vs_id, name, all, note)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['vs_id', capture['guestId']])
table.add_row(['date', capture['createDate'][:10]])
table.add_row(['time', capture['createDate'][11:19]])
table.add_row(['transaction', formatting.transaction_status(capture)])
table.add_row(['transaction_id', capture['id']])
table.add_row(['all_disks', all])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"name",
",",
"all",
",",
"note",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
"identifier",
",",
"'VS'",
")",
"capture",
"=",
"vsi",
".",
"capture",
"(",
"vs_id",
",",
"name",
",",
"all",
",",
"note",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'vs_id'",
",",
"capture",
"[",
"'guestId'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'date'",
",",
"capture",
"[",
"'createDate'",
"]",
"[",
":",
"10",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'time'",
",",
"capture",
"[",
"'createDate'",
"]",
"[",
"11",
":",
"19",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'transaction'",
",",
"formatting",
".",
"transaction_status",
"(",
"capture",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'transaction_id'",
",",
"capture",
"[",
"'id'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'all_disks'",
",",
"all",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Capture one or all disks from a virtual server to a SoftLayer image. | [
"Capture",
"one",
"or",
"all",
"disks",
"from",
"a",
"virtual",
"server",
"to",
"a",
"SoftLayer",
"image",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/capture.py#L20-L38 |
softlayer/softlayer-python | SoftLayer/managers/event_log.py | EventLogManager.get_event_logs | def get_event_logs(self, request_filter=None, log_limit=20, iterator=True):
"""Returns a list of event logs
Example::
event_mgr = SoftLayer.EventLogManager(env.client)
request_filter = event_mgr.build_filter(date_min="01/01/2019", date_max="02/01/2019")
logs = event_mgr.get_event_logs(request_filter)
for log in logs:
print("Event Name: {}".format(log['eventName']))
:param dict request_filter: filter dict
:param int log_limit: number of results to get in one API call
:param bool iterator: False will only make one API call for log_limit results.
True will keep making API calls until all logs have been retreived. There may be a lot of these.
:returns: List of event logs. If iterator=True, will return a python generator object instead.
"""
if iterator:
# Call iter_call directly as this returns the actual generator
return self.client.iter_call('Event_Log', 'getAllObjects', filter=request_filter, limit=log_limit)
return self.client.call('Event_Log', 'getAllObjects', filter=request_filter, limit=log_limit) | python | def get_event_logs(self, request_filter=None, log_limit=20, iterator=True):
if iterator:
return self.client.iter_call('Event_Log', 'getAllObjects', filter=request_filter, limit=log_limit)
return self.client.call('Event_Log', 'getAllObjects', filter=request_filter, limit=log_limit) | [
"def",
"get_event_logs",
"(",
"self",
",",
"request_filter",
"=",
"None",
",",
"log_limit",
"=",
"20",
",",
"iterator",
"=",
"True",
")",
":",
"if",
"iterator",
":",
"# Call iter_call directly as this returns the actual generator",
"return",
"self",
".",
"client",
".",
"iter_call",
"(",
"'Event_Log'",
",",
"'getAllObjects'",
",",
"filter",
"=",
"request_filter",
",",
"limit",
"=",
"log_limit",
")",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'Event_Log'",
",",
"'getAllObjects'",
",",
"filter",
"=",
"request_filter",
",",
"limit",
"=",
"log_limit",
")"
]
| Returns a list of event logs
Example::
event_mgr = SoftLayer.EventLogManager(env.client)
request_filter = event_mgr.build_filter(date_min="01/01/2019", date_max="02/01/2019")
logs = event_mgr.get_event_logs(request_filter)
for log in logs:
print("Event Name: {}".format(log['eventName']))
:param dict request_filter: filter dict
:param int log_limit: number of results to get in one API call
:param bool iterator: False will only make one API call for log_limit results.
True will keep making API calls until all logs have been retreived. There may be a lot of these.
:returns: List of event logs. If iterator=True, will return a python generator object instead. | [
"Returns",
"a",
"list",
"of",
"event",
"logs"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/event_log.py#L23-L44 |
softlayer/softlayer-python | SoftLayer/managers/event_log.py | EventLogManager.build_filter | def build_filter(date_min=None, date_max=None, obj_event=None, obj_id=None, obj_type=None, utc_offset=None):
"""Returns a query filter that can be passed into EventLogManager.get_event_logs
:param string date_min: Lower bound date in MM/DD/YYYY format
:param string date_max: Upper bound date in MM/DD/YYYY format
:param string obj_event: The name of the events we want to filter by
:param int obj_id: The id of the event we want to filter by
:param string obj_type: The type of event we want to filter by
:param string utc_offset: The UTC offset we want to use when converting date_min and date_max.
(default '+0000')
:returns: dict: The generated query filter
"""
if not any([date_min, date_max, obj_event, obj_id, obj_type]):
return {}
request_filter = {}
if date_min and date_max:
request_filter['eventCreateDate'] = utils.event_log_filter_between_date(date_min, date_max, utc_offset)
else:
if date_min:
request_filter['eventCreateDate'] = utils.event_log_filter_greater_than_date(date_min, utc_offset)
elif date_max:
request_filter['eventCreateDate'] = utils.event_log_filter_less_than_date(date_max, utc_offset)
if obj_event:
request_filter['eventName'] = {'operation': obj_event}
if obj_id:
request_filter['objectId'] = {'operation': obj_id}
if obj_type:
request_filter['objectName'] = {'operation': obj_type}
return request_filter | python | def build_filter(date_min=None, date_max=None, obj_event=None, obj_id=None, obj_type=None, utc_offset=None):
if not any([date_min, date_max, obj_event, obj_id, obj_type]):
return {}
request_filter = {}
if date_min and date_max:
request_filter['eventCreateDate'] = utils.event_log_filter_between_date(date_min, date_max, utc_offset)
else:
if date_min:
request_filter['eventCreateDate'] = utils.event_log_filter_greater_than_date(date_min, utc_offset)
elif date_max:
request_filter['eventCreateDate'] = utils.event_log_filter_less_than_date(date_max, utc_offset)
if obj_event:
request_filter['eventName'] = {'operation': obj_event}
if obj_id:
request_filter['objectId'] = {'operation': obj_id}
if obj_type:
request_filter['objectName'] = {'operation': obj_type}
return request_filter | [
"def",
"build_filter",
"(",
"date_min",
"=",
"None",
",",
"date_max",
"=",
"None",
",",
"obj_event",
"=",
"None",
",",
"obj_id",
"=",
"None",
",",
"obj_type",
"=",
"None",
",",
"utc_offset",
"=",
"None",
")",
":",
"if",
"not",
"any",
"(",
"[",
"date_min",
",",
"date_max",
",",
"obj_event",
",",
"obj_id",
",",
"obj_type",
"]",
")",
":",
"return",
"{",
"}",
"request_filter",
"=",
"{",
"}",
"if",
"date_min",
"and",
"date_max",
":",
"request_filter",
"[",
"'eventCreateDate'",
"]",
"=",
"utils",
".",
"event_log_filter_between_date",
"(",
"date_min",
",",
"date_max",
",",
"utc_offset",
")",
"else",
":",
"if",
"date_min",
":",
"request_filter",
"[",
"'eventCreateDate'",
"]",
"=",
"utils",
".",
"event_log_filter_greater_than_date",
"(",
"date_min",
",",
"utc_offset",
")",
"elif",
"date_max",
":",
"request_filter",
"[",
"'eventCreateDate'",
"]",
"=",
"utils",
".",
"event_log_filter_less_than_date",
"(",
"date_max",
",",
"utc_offset",
")",
"if",
"obj_event",
":",
"request_filter",
"[",
"'eventName'",
"]",
"=",
"{",
"'operation'",
":",
"obj_event",
"}",
"if",
"obj_id",
":",
"request_filter",
"[",
"'objectId'",
"]",
"=",
"{",
"'operation'",
":",
"obj_id",
"}",
"if",
"obj_type",
":",
"request_filter",
"[",
"'objectName'",
"]",
"=",
"{",
"'operation'",
":",
"obj_type",
"}",
"return",
"request_filter"
]
| Returns a query filter that can be passed into EventLogManager.get_event_logs
:param string date_min: Lower bound date in MM/DD/YYYY format
:param string date_max: Upper bound date in MM/DD/YYYY format
:param string obj_event: The name of the events we want to filter by
:param int obj_id: The id of the event we want to filter by
:param string obj_type: The type of event we want to filter by
:param string utc_offset: The UTC offset we want to use when converting date_min and date_max.
(default '+0000')
:returns: dict: The generated query filter | [
"Returns",
"a",
"query",
"filter",
"that",
"can",
"be",
"passed",
"into",
"EventLogManager",
".",
"get_event_logs"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/event_log.py#L55-L91 |
softlayer/softlayer-python | SoftLayer/CLI/dns/record_list.py | cli | def cli(env, zone, data, record, ttl, type):
"""List all records in a zone."""
manager = SoftLayer.DNSManager(env.client)
table = formatting.Table(['id', 'record', 'type', 'ttl', 'data'])
table.align['ttl'] = 'l'
table.align['record'] = 'r'
table.align['data'] = 'l'
zone_id = helpers.resolve_id(manager.resolve_ids, zone, name='zone')
records = manager.get_records(zone_id,
record_type=type,
host=record,
ttl=ttl,
data=data)
for the_record in records:
table.add_row([
the_record['id'],
the_record['host'],
the_record['type'].upper(),
the_record['ttl'],
the_record['data']
])
env.fout(table) | python | def cli(env, zone, data, record, ttl, type):
manager = SoftLayer.DNSManager(env.client)
table = formatting.Table(['id', 'record', 'type', 'ttl', 'data'])
table.align['ttl'] = 'l'
table.align['record'] = 'r'
table.align['data'] = 'l'
zone_id = helpers.resolve_id(manager.resolve_ids, zone, name='zone')
records = manager.get_records(zone_id,
record_type=type,
host=record,
ttl=ttl,
data=data)
for the_record in records:
table.add_row([
the_record['id'],
the_record['host'],
the_record['type'].upper(),
the_record['ttl'],
the_record['data']
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"zone",
",",
"data",
",",
"record",
",",
"ttl",
",",
"type",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"DNSManager",
"(",
"env",
".",
"client",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'record'",
",",
"'type'",
",",
"'ttl'",
",",
"'data'",
"]",
")",
"table",
".",
"align",
"[",
"'ttl'",
"]",
"=",
"'l'",
"table",
".",
"align",
"[",
"'record'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'data'",
"]",
"=",
"'l'",
"zone_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"manager",
".",
"resolve_ids",
",",
"zone",
",",
"name",
"=",
"'zone'",
")",
"records",
"=",
"manager",
".",
"get_records",
"(",
"zone_id",
",",
"record_type",
"=",
"type",
",",
"host",
"=",
"record",
",",
"ttl",
"=",
"ttl",
",",
"data",
"=",
"data",
")",
"for",
"the_record",
"in",
"records",
":",
"table",
".",
"add_row",
"(",
"[",
"the_record",
"[",
"'id'",
"]",
",",
"the_record",
"[",
"'host'",
"]",
",",
"the_record",
"[",
"'type'",
"]",
".",
"upper",
"(",
")",
",",
"the_record",
"[",
"'ttl'",
"]",
",",
"the_record",
"[",
"'data'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| List all records in a zone. | [
"List",
"all",
"records",
"in",
"a",
"zone",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dns/record_list.py#L22-L49 |
softlayer/softlayer-python | SoftLayer/CLI/ticket/subjects.py | cli | def cli(env):
"""List Subject IDs for ticket creation."""
ticket_mgr = SoftLayer.TicketManager(env.client)
table = formatting.Table(['id', 'subject'])
for subject in ticket_mgr.list_subjects():
table.add_row([subject['id'], subject['name']])
env.fout(table) | python | def cli(env):
ticket_mgr = SoftLayer.TicketManager(env.client)
table = formatting.Table(['id', 'subject'])
for subject in ticket_mgr.list_subjects():
table.add_row([subject['id'], subject['name']])
env.fout(table) | [
"def",
"cli",
"(",
"env",
")",
":",
"ticket_mgr",
"=",
"SoftLayer",
".",
"TicketManager",
"(",
"env",
".",
"client",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'subject'",
"]",
")",
"for",
"subject",
"in",
"ticket_mgr",
".",
"list_subjects",
"(",
")",
":",
"table",
".",
"add_row",
"(",
"[",
"subject",
"[",
"'id'",
"]",
",",
"subject",
"[",
"'name'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| List Subject IDs for ticket creation. | [
"List",
"Subject",
"IDs",
"for",
"ticket",
"creation",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ticket/subjects.py#L13-L21 |
softlayer/softlayer-python | SoftLayer/CLI/virt/placementgroup/create.py | cli | def cli(env, **args):
"""Create a placement group."""
manager = PlacementManager(env.client)
backend_router_id = helpers.resolve_id(manager.get_backend_router_id_from_hostname,
args.get('backend_router'),
'backendRouter')
rule_id = helpers.resolve_id(manager.get_rule_id_from_name, args.get('rule'), 'Rule')
placement_object = {
'name': args.get('name'),
'backendRouterId': backend_router_id,
'ruleId': rule_id
}
result = manager.create(placement_object)
click.secho("Successfully created placement group: ID: %s, Name: %s" % (result['id'], result['name']), fg='green') | python | def cli(env, **args):
manager = PlacementManager(env.client)
backend_router_id = helpers.resolve_id(manager.get_backend_router_id_from_hostname,
args.get('backend_router'),
'backendRouter')
rule_id = helpers.resolve_id(manager.get_rule_id_from_name, args.get('rule'), 'Rule')
placement_object = {
'name': args.get('name'),
'backendRouterId': backend_router_id,
'ruleId': rule_id
}
result = manager.create(placement_object)
click.secho("Successfully created placement group: ID: %s, Name: %s" % (result['id'], result['name']), fg='green') | [
"def",
"cli",
"(",
"env",
",",
"*",
"*",
"args",
")",
":",
"manager",
"=",
"PlacementManager",
"(",
"env",
".",
"client",
")",
"backend_router_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"manager",
".",
"get_backend_router_id_from_hostname",
",",
"args",
".",
"get",
"(",
"'backend_router'",
")",
",",
"'backendRouter'",
")",
"rule_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"manager",
".",
"get_rule_id_from_name",
",",
"args",
".",
"get",
"(",
"'rule'",
")",
",",
"'Rule'",
")",
"placement_object",
"=",
"{",
"'name'",
":",
"args",
".",
"get",
"(",
"'name'",
")",
",",
"'backendRouterId'",
":",
"backend_router_id",
",",
"'ruleId'",
":",
"rule_id",
"}",
"result",
"=",
"manager",
".",
"create",
"(",
"placement_object",
")",
"click",
".",
"secho",
"(",
"\"Successfully created placement group: ID: %s, Name: %s\"",
"%",
"(",
"result",
"[",
"'id'",
"]",
",",
"result",
"[",
"'name'",
"]",
")",
",",
"fg",
"=",
"'green'",
")"
]
| Create a placement group. | [
"Create",
"a",
"placement",
"group",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/placementgroup/create.py#L17-L31 |
softlayer/softlayer-python | SoftLayer/CLI/user/detail.py | cli | def cli(env, identifier, keys, permissions, hardware, virtual, logins, events):
"""User details."""
mgr = SoftLayer.UserManager(env.client)
user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
object_mask = "userStatus[name], parent[id, username], apiAuthenticationKeys[authenticationKey], "\
"unsuccessfulLogins, successfulLogins"
user = mgr.get_user(user_id, object_mask)
env.fout(basic_info(user, keys))
if permissions:
perms = mgr.get_user_permissions(user_id)
env.fout(print_permissions(perms))
if hardware:
mask = "id, hardware, dedicatedHosts"
access = mgr.get_user(user_id, mask)
env.fout(print_dedicated_access(access.get('dedicatedHosts', [])))
env.fout(print_access(access.get('hardware', []), 'Hardware'))
if virtual:
mask = "id, virtualGuests"
access = mgr.get_user(user_id, mask)
env.fout(print_access(access.get('virtualGuests', []), 'Virtual Guests'))
if logins:
login_log = mgr.get_logins(user_id)
env.fout(print_logins(login_log))
if events:
event_log = mgr.get_events(user_id)
env.fout(print_events(event_log)) | python | def cli(env, identifier, keys, permissions, hardware, virtual, logins, events):
mgr = SoftLayer.UserManager(env.client)
user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
object_mask = "userStatus[name], parent[id, username], apiAuthenticationKeys[authenticationKey], "\
"unsuccessfulLogins, successfulLogins"
user = mgr.get_user(user_id, object_mask)
env.fout(basic_info(user, keys))
if permissions:
perms = mgr.get_user_permissions(user_id)
env.fout(print_permissions(perms))
if hardware:
mask = "id, hardware, dedicatedHosts"
access = mgr.get_user(user_id, mask)
env.fout(print_dedicated_access(access.get('dedicatedHosts', [])))
env.fout(print_access(access.get('hardware', []), 'Hardware'))
if virtual:
mask = "id, virtualGuests"
access = mgr.get_user(user_id, mask)
env.fout(print_access(access.get('virtualGuests', []), 'Virtual Guests'))
if logins:
login_log = mgr.get_logins(user_id)
env.fout(print_logins(login_log))
if events:
event_log = mgr.get_events(user_id)
env.fout(print_events(event_log)) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"keys",
",",
"permissions",
",",
"hardware",
",",
"virtual",
",",
"logins",
",",
"events",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"UserManager",
"(",
"env",
".",
"client",
")",
"user_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'username'",
")",
"object_mask",
"=",
"\"userStatus[name], parent[id, username], apiAuthenticationKeys[authenticationKey], \"",
"\"unsuccessfulLogins, successfulLogins\"",
"user",
"=",
"mgr",
".",
"get_user",
"(",
"user_id",
",",
"object_mask",
")",
"env",
".",
"fout",
"(",
"basic_info",
"(",
"user",
",",
"keys",
")",
")",
"if",
"permissions",
":",
"perms",
"=",
"mgr",
".",
"get_user_permissions",
"(",
"user_id",
")",
"env",
".",
"fout",
"(",
"print_permissions",
"(",
"perms",
")",
")",
"if",
"hardware",
":",
"mask",
"=",
"\"id, hardware, dedicatedHosts\"",
"access",
"=",
"mgr",
".",
"get_user",
"(",
"user_id",
",",
"mask",
")",
"env",
".",
"fout",
"(",
"print_dedicated_access",
"(",
"access",
".",
"get",
"(",
"'dedicatedHosts'",
",",
"[",
"]",
")",
")",
")",
"env",
".",
"fout",
"(",
"print_access",
"(",
"access",
".",
"get",
"(",
"'hardware'",
",",
"[",
"]",
")",
",",
"'Hardware'",
")",
")",
"if",
"virtual",
":",
"mask",
"=",
"\"id, virtualGuests\"",
"access",
"=",
"mgr",
".",
"get_user",
"(",
"user_id",
",",
"mask",
")",
"env",
".",
"fout",
"(",
"print_access",
"(",
"access",
".",
"get",
"(",
"'virtualGuests'",
",",
"[",
"]",
")",
",",
"'Virtual Guests'",
")",
")",
"if",
"logins",
":",
"login_log",
"=",
"mgr",
".",
"get_logins",
"(",
"user_id",
")",
"env",
".",
"fout",
"(",
"print_logins",
"(",
"login_log",
")",
")",
"if",
"events",
":",
"event_log",
"=",
"mgr",
".",
"get_events",
"(",
"user_id",
")",
"env",
".",
"fout",
"(",
"print_events",
"(",
"event_log",
")",
")"
]
| User details. | [
"User",
"details",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/detail.py#L28-L56 |
softlayer/softlayer-python | SoftLayer/CLI/user/detail.py | basic_info | def basic_info(user, keys):
"""Prints a table of basic user information"""
table = formatting.KeyValueTable(['Title', 'Basic Information'])
table.align['Title'] = 'r'
table.align['Basic Information'] = 'l'
table.add_row(['Id', user.get('id', '-')])
table.add_row(['Username', user.get('username', '-')])
if keys:
for key in user.get('apiAuthenticationKeys'):
table.add_row(['APIKEY', key.get('authenticationKey')])
table.add_row(['Name', "%s %s" % (user.get('firstName', '-'), user.get('lastName', '-'))])
table.add_row(['Email', user.get('email')])
table.add_row(['OpenID', user.get('openIdConnectUserName')])
address = "%s %s %s %s %s %s" % (
user.get('address1'), user.get('address2'), user.get('city'), user.get('state'),
user.get('country'), user.get('postalCode'))
table.add_row(['Address', address])
table.add_row(['Company', user.get('companyName')])
table.add_row(['Created', user.get('createDate')])
table.add_row(['Phone Number', user.get('officePhone')])
if user.get('parentId', False):
table.add_row(['Parent User', utils.lookup(user, 'parent', 'username')])
table.add_row(['Status', utils.lookup(user, 'userStatus', 'name')])
table.add_row(['PPTP VPN', user.get('pptpVpnAllowedFlag', 'No')])
table.add_row(['SSL VPN', user.get('sslVpnAllowedFlag', 'No')])
for login in user.get('unsuccessfulLogins', {}):
login_string = "%s From: %s" % (login.get('createDate'), login.get('ipAddress'))
table.add_row(['Last Failed Login', login_string])
break
for login in user.get('successfulLogins', {}):
login_string = "%s From: %s" % (login.get('createDate'), login.get('ipAddress'))
table.add_row(['Last Login', login_string])
break
return table | python | def basic_info(user, keys):
table = formatting.KeyValueTable(['Title', 'Basic Information'])
table.align['Title'] = 'r'
table.align['Basic Information'] = 'l'
table.add_row(['Id', user.get('id', '-')])
table.add_row(['Username', user.get('username', '-')])
if keys:
for key in user.get('apiAuthenticationKeys'):
table.add_row(['APIKEY', key.get('authenticationKey')])
table.add_row(['Name', "%s %s" % (user.get('firstName', '-'), user.get('lastName', '-'))])
table.add_row(['Email', user.get('email')])
table.add_row(['OpenID', user.get('openIdConnectUserName')])
address = "%s %s %s %s %s %s" % (
user.get('address1'), user.get('address2'), user.get('city'), user.get('state'),
user.get('country'), user.get('postalCode'))
table.add_row(['Address', address])
table.add_row(['Company', user.get('companyName')])
table.add_row(['Created', user.get('createDate')])
table.add_row(['Phone Number', user.get('officePhone')])
if user.get('parentId', False):
table.add_row(['Parent User', utils.lookup(user, 'parent', 'username')])
table.add_row(['Status', utils.lookup(user, 'userStatus', 'name')])
table.add_row(['PPTP VPN', user.get('pptpVpnAllowedFlag', 'No')])
table.add_row(['SSL VPN', user.get('sslVpnAllowedFlag', 'No')])
for login in user.get('unsuccessfulLogins', {}):
login_string = "%s From: %s" % (login.get('createDate'), login.get('ipAddress'))
table.add_row(['Last Failed Login', login_string])
break
for login in user.get('successfulLogins', {}):
login_string = "%s From: %s" % (login.get('createDate'), login.get('ipAddress'))
table.add_row(['Last Login', login_string])
break
return table | [
"def",
"basic_info",
"(",
"user",
",",
"keys",
")",
":",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'Title'",
",",
"'Basic Information'",
"]",
")",
"table",
".",
"align",
"[",
"'Title'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'Basic Information'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'Id'",
",",
"user",
".",
"get",
"(",
"'id'",
",",
"'-'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Username'",
",",
"user",
".",
"get",
"(",
"'username'",
",",
"'-'",
")",
"]",
")",
"if",
"keys",
":",
"for",
"key",
"in",
"user",
".",
"get",
"(",
"'apiAuthenticationKeys'",
")",
":",
"table",
".",
"add_row",
"(",
"[",
"'APIKEY'",
",",
"key",
".",
"get",
"(",
"'authenticationKey'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Name'",
",",
"\"%s %s\"",
"%",
"(",
"user",
".",
"get",
"(",
"'firstName'",
",",
"'-'",
")",
",",
"user",
".",
"get",
"(",
"'lastName'",
",",
"'-'",
")",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Email'",
",",
"user",
".",
"get",
"(",
"'email'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'OpenID'",
",",
"user",
".",
"get",
"(",
"'openIdConnectUserName'",
")",
"]",
")",
"address",
"=",
"\"%s %s %s %s %s %s\"",
"%",
"(",
"user",
".",
"get",
"(",
"'address1'",
")",
",",
"user",
".",
"get",
"(",
"'address2'",
")",
",",
"user",
".",
"get",
"(",
"'city'",
")",
",",
"user",
".",
"get",
"(",
"'state'",
")",
",",
"user",
".",
"get",
"(",
"'country'",
")",
",",
"user",
".",
"get",
"(",
"'postalCode'",
")",
")",
"table",
".",
"add_row",
"(",
"[",
"'Address'",
",",
"address",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Company'",
",",
"user",
".",
"get",
"(",
"'companyName'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Created'",
",",
"user",
".",
"get",
"(",
"'createDate'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Phone Number'",
",",
"user",
".",
"get",
"(",
"'officePhone'",
")",
"]",
")",
"if",
"user",
".",
"get",
"(",
"'parentId'",
",",
"False",
")",
":",
"table",
".",
"add_row",
"(",
"[",
"'Parent User'",
",",
"utils",
".",
"lookup",
"(",
"user",
",",
"'parent'",
",",
"'username'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Status'",
",",
"utils",
".",
"lookup",
"(",
"user",
",",
"'userStatus'",
",",
"'name'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'PPTP VPN'",
",",
"user",
".",
"get",
"(",
"'pptpVpnAllowedFlag'",
",",
"'No'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'SSL VPN'",
",",
"user",
".",
"get",
"(",
"'sslVpnAllowedFlag'",
",",
"'No'",
")",
"]",
")",
"for",
"login",
"in",
"user",
".",
"get",
"(",
"'unsuccessfulLogins'",
",",
"{",
"}",
")",
":",
"login_string",
"=",
"\"%s From: %s\"",
"%",
"(",
"login",
".",
"get",
"(",
"'createDate'",
")",
",",
"login",
".",
"get",
"(",
"'ipAddress'",
")",
")",
"table",
".",
"add_row",
"(",
"[",
"'Last Failed Login'",
",",
"login_string",
"]",
")",
"break",
"for",
"login",
"in",
"user",
".",
"get",
"(",
"'successfulLogins'",
",",
"{",
"}",
")",
":",
"login_string",
"=",
"\"%s From: %s\"",
"%",
"(",
"login",
".",
"get",
"(",
"'createDate'",
")",
",",
"login",
".",
"get",
"(",
"'ipAddress'",
")",
")",
"table",
".",
"add_row",
"(",
"[",
"'Last Login'",
",",
"login_string",
"]",
")",
"break",
"return",
"table"
]
| Prints a table of basic user information | [
"Prints",
"a",
"table",
"of",
"basic",
"user",
"information"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/detail.py#L59-L95 |
softlayer/softlayer-python | SoftLayer/CLI/user/detail.py | print_permissions | def print_permissions(permissions):
"""Prints out a users permissions"""
table = formatting.Table(['keyName', 'Description'])
for perm in permissions:
table.add_row([perm['keyName'], perm['name']])
return table | python | def print_permissions(permissions):
table = formatting.Table(['keyName', 'Description'])
for perm in permissions:
table.add_row([perm['keyName'], perm['name']])
return table | [
"def",
"print_permissions",
"(",
"permissions",
")",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'keyName'",
",",
"'Description'",
"]",
")",
"for",
"perm",
"in",
"permissions",
":",
"table",
".",
"add_row",
"(",
"[",
"perm",
"[",
"'keyName'",
"]",
",",
"perm",
"[",
"'name'",
"]",
"]",
")",
"return",
"table"
]
| Prints out a users permissions | [
"Prints",
"out",
"a",
"users",
"permissions"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/detail.py#L98-L104 |
softlayer/softlayer-python | SoftLayer/CLI/user/detail.py | print_access | def print_access(access, title):
"""Prints out the hardware or virtual guests a user can access"""
columns = ['id', 'hostname', 'Primary Public IP', 'Primary Private IP', 'Created']
table = formatting.Table(columns, title)
for host in access:
host_id = host.get('id')
host_fqdn = host.get('fullyQualifiedDomainName', '-')
host_primary = host.get('primaryIpAddress')
host_private = host.get('primaryBackendIpAddress')
host_created = host.get('provisionDate')
table.add_row([host_id, host_fqdn, host_primary, host_private, host_created])
return table | python | def print_access(access, title):
columns = ['id', 'hostname', 'Primary Public IP', 'Primary Private IP', 'Created']
table = formatting.Table(columns, title)
for host in access:
host_id = host.get('id')
host_fqdn = host.get('fullyQualifiedDomainName', '-')
host_primary = host.get('primaryIpAddress')
host_private = host.get('primaryBackendIpAddress')
host_created = host.get('provisionDate')
table.add_row([host_id, host_fqdn, host_primary, host_private, host_created])
return table | [
"def",
"print_access",
"(",
"access",
",",
"title",
")",
":",
"columns",
"=",
"[",
"'id'",
",",
"'hostname'",
",",
"'Primary Public IP'",
",",
"'Primary Private IP'",
",",
"'Created'",
"]",
"table",
"=",
"formatting",
".",
"Table",
"(",
"columns",
",",
"title",
")",
"for",
"host",
"in",
"access",
":",
"host_id",
"=",
"host",
".",
"get",
"(",
"'id'",
")",
"host_fqdn",
"=",
"host",
".",
"get",
"(",
"'fullyQualifiedDomainName'",
",",
"'-'",
")",
"host_primary",
"=",
"host",
".",
"get",
"(",
"'primaryIpAddress'",
")",
"host_private",
"=",
"host",
".",
"get",
"(",
"'primaryBackendIpAddress'",
")",
"host_created",
"=",
"host",
".",
"get",
"(",
"'provisionDate'",
")",
"table",
".",
"add_row",
"(",
"[",
"host_id",
",",
"host_fqdn",
",",
"host_primary",
",",
"host_private",
",",
"host_created",
"]",
")",
"return",
"table"
]
| Prints out the hardware or virtual guests a user can access | [
"Prints",
"out",
"the",
"hardware",
"or",
"virtual",
"guests",
"a",
"user",
"can",
"access"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/detail.py#L107-L120 |
softlayer/softlayer-python | SoftLayer/CLI/user/detail.py | print_dedicated_access | def print_dedicated_access(access):
"""Prints out the dedicated hosts a user can access"""
table = formatting.Table(['id', 'Name', 'Cpus', 'Memory', 'Disk', 'Created'], 'Dedicated Access')
for host in access:
host_id = host.get('id')
host_fqdn = host.get('name')
host_cpu = host.get('cpuCount')
host_mem = host.get('memoryCapacity')
host_disk = host.get('diskCapacity')
host_created = host.get('createDate')
table.add_row([host_id, host_fqdn, host_cpu, host_mem, host_disk, host_created])
return table | python | def print_dedicated_access(access):
table = formatting.Table(['id', 'Name', 'Cpus', 'Memory', 'Disk', 'Created'], 'Dedicated Access')
for host in access:
host_id = host.get('id')
host_fqdn = host.get('name')
host_cpu = host.get('cpuCount')
host_mem = host.get('memoryCapacity')
host_disk = host.get('diskCapacity')
host_created = host.get('createDate')
table.add_row([host_id, host_fqdn, host_cpu, host_mem, host_disk, host_created])
return table | [
"def",
"print_dedicated_access",
"(",
"access",
")",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'Name'",
",",
"'Cpus'",
",",
"'Memory'",
",",
"'Disk'",
",",
"'Created'",
"]",
",",
"'Dedicated Access'",
")",
"for",
"host",
"in",
"access",
":",
"host_id",
"=",
"host",
".",
"get",
"(",
"'id'",
")",
"host_fqdn",
"=",
"host",
".",
"get",
"(",
"'name'",
")",
"host_cpu",
"=",
"host",
".",
"get",
"(",
"'cpuCount'",
")",
"host_mem",
"=",
"host",
".",
"get",
"(",
"'memoryCapacity'",
")",
"host_disk",
"=",
"host",
".",
"get",
"(",
"'diskCapacity'",
")",
"host_created",
"=",
"host",
".",
"get",
"(",
"'createDate'",
")",
"table",
".",
"add_row",
"(",
"[",
"host_id",
",",
"host_fqdn",
",",
"host_cpu",
",",
"host_mem",
",",
"host_disk",
",",
"host_created",
"]",
")",
"return",
"table"
]
| Prints out the dedicated hosts a user can access | [
"Prints",
"out",
"the",
"dedicated",
"hosts",
"a",
"user",
"can",
"access"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/detail.py#L123-L135 |
softlayer/softlayer-python | SoftLayer/CLI/user/detail.py | print_logins | def print_logins(logins):
"""Prints out the login history for a user"""
table = formatting.Table(['Date', 'IP Address', 'Successufl Login?'])
for login in logins:
table.add_row([login.get('createDate'), login.get('ipAddress'), login.get('successFlag')])
return table | python | def print_logins(logins):
table = formatting.Table(['Date', 'IP Address', 'Successufl Login?'])
for login in logins:
table.add_row([login.get('createDate'), login.get('ipAddress'), login.get('successFlag')])
return table | [
"def",
"print_logins",
"(",
"logins",
")",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Date'",
",",
"'IP Address'",
",",
"'Successufl Login?'",
"]",
")",
"for",
"login",
"in",
"logins",
":",
"table",
".",
"add_row",
"(",
"[",
"login",
".",
"get",
"(",
"'createDate'",
")",
",",
"login",
".",
"get",
"(",
"'ipAddress'",
")",
",",
"login",
".",
"get",
"(",
"'successFlag'",
")",
"]",
")",
"return",
"table"
]
| Prints out the login history for a user | [
"Prints",
"out",
"the",
"login",
"history",
"for",
"a",
"user"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/detail.py#L138-L143 |
softlayer/softlayer-python | SoftLayer/CLI/user/detail.py | print_events | def print_events(events):
"""Prints out the event log for a user"""
columns = ['Date', 'Type', 'IP Address', 'label', 'username']
table = formatting.Table(columns)
for event in events:
table.add_row([event.get('eventCreateDate'), event.get('eventName'),
event.get('ipAddress'), event.get('label'), event.get('username')])
return table | python | def print_events(events):
columns = ['Date', 'Type', 'IP Address', 'label', 'username']
table = formatting.Table(columns)
for event in events:
table.add_row([event.get('eventCreateDate'), event.get('eventName'),
event.get('ipAddress'), event.get('label'), event.get('username')])
return table | [
"def",
"print_events",
"(",
"events",
")",
":",
"columns",
"=",
"[",
"'Date'",
",",
"'Type'",
",",
"'IP Address'",
",",
"'label'",
",",
"'username'",
"]",
"table",
"=",
"formatting",
".",
"Table",
"(",
"columns",
")",
"for",
"event",
"in",
"events",
":",
"table",
".",
"add_row",
"(",
"[",
"event",
".",
"get",
"(",
"'eventCreateDate'",
")",
",",
"event",
".",
"get",
"(",
"'eventName'",
")",
",",
"event",
".",
"get",
"(",
"'ipAddress'",
")",
",",
"event",
".",
"get",
"(",
"'label'",
")",
",",
"event",
".",
"get",
"(",
"'username'",
")",
"]",
")",
"return",
"table"
]
| Prints out the event log for a user | [
"Prints",
"out",
"the",
"event",
"log",
"for",
"a",
"user"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/detail.py#L146-L153 |
softlayer/softlayer-python | SoftLayer/CLI/block/access/list.py | cli | def cli(env, columns, sortby, volume_id):
"""List ACLs."""
block_manager = SoftLayer.BlockStorageManager(env.client)
access_list = block_manager.get_block_volume_access_list(
volume_id=volume_id)
table = formatting.Table(columns.columns)
table.sortby = sortby
for key, type_name in [('allowedVirtualGuests', 'VIRTUAL'),
('allowedHardware', 'HARDWARE'),
('allowedSubnets', 'SUBNET'),
('allowedIpAddresses', 'IP')]:
for obj in access_list.get(key, []):
obj['type'] = type_name
table.add_row([value or formatting.blank()
for value in columns.row(obj)])
env.fout(table) | python | def cli(env, columns, sortby, volume_id):
block_manager = SoftLayer.BlockStorageManager(env.client)
access_list = block_manager.get_block_volume_access_list(
volume_id=volume_id)
table = formatting.Table(columns.columns)
table.sortby = sortby
for key, type_name in [('allowedVirtualGuests', 'VIRTUAL'),
('allowedHardware', 'HARDWARE'),
('allowedSubnets', 'SUBNET'),
('allowedIpAddresses', 'IP')]:
for obj in access_list.get(key, []):
obj['type'] = type_name
table.add_row([value or formatting.blank()
for value in columns.row(obj)])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"columns",
",",
"sortby",
",",
"volume_id",
")",
":",
"block_manager",
"=",
"SoftLayer",
".",
"BlockStorageManager",
"(",
"env",
".",
"client",
")",
"access_list",
"=",
"block_manager",
".",
"get_block_volume_access_list",
"(",
"volume_id",
"=",
"volume_id",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"columns",
".",
"columns",
")",
"table",
".",
"sortby",
"=",
"sortby",
"for",
"key",
",",
"type_name",
"in",
"[",
"(",
"'allowedVirtualGuests'",
",",
"'VIRTUAL'",
")",
",",
"(",
"'allowedHardware'",
",",
"'HARDWARE'",
")",
",",
"(",
"'allowedSubnets'",
",",
"'SUBNET'",
")",
",",
"(",
"'allowedIpAddresses'",
",",
"'IP'",
")",
"]",
":",
"for",
"obj",
"in",
"access_list",
".",
"get",
"(",
"key",
",",
"[",
"]",
")",
":",
"obj",
"[",
"'type'",
"]",
"=",
"type_name",
"table",
".",
"add_row",
"(",
"[",
"value",
"or",
"formatting",
".",
"blank",
"(",
")",
"for",
"value",
"in",
"columns",
".",
"row",
"(",
"obj",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| List ACLs. | [
"List",
"ACLs",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/access/list.py#L21-L38 |
softlayer/softlayer-python | SoftLayer/CLI/user/delete.py | cli | def cli(env, identifier):
"""Sets a user's status to CANCEL_PENDING, which will immediately disable the account,
and will eventually be fully removed from the account by an automated internal process.
Example: slcli user delete userId
"""
mgr = SoftLayer.UserManager(env.client)
user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
user_template = {'userStatusId': 1021}
result = mgr.edit_user(user_id, user_template)
if result:
click.secho("%s deleted successfully" % identifier, fg='green')
else:
click.secho("Failed to delete %s" % identifier, fg='red') | python | def cli(env, identifier):
mgr = SoftLayer.UserManager(env.client)
user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
user_template = {'userStatusId': 1021}
result = mgr.edit_user(user_id, user_template)
if result:
click.secho("%s deleted successfully" % identifier, fg='green')
else:
click.secho("Failed to delete %s" % identifier, fg='red') | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"UserManager",
"(",
"env",
".",
"client",
")",
"user_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'username'",
")",
"user_template",
"=",
"{",
"'userStatusId'",
":",
"1021",
"}",
"result",
"=",
"mgr",
".",
"edit_user",
"(",
"user_id",
",",
"user_template",
")",
"if",
"result",
":",
"click",
".",
"secho",
"(",
"\"%s deleted successfully\"",
"%",
"identifier",
",",
"fg",
"=",
"'green'",
")",
"else",
":",
"click",
".",
"secho",
"(",
"\"Failed to delete %s\"",
"%",
"identifier",
",",
"fg",
"=",
"'red'",
")"
]
| Sets a user's status to CANCEL_PENDING, which will immediately disable the account,
and will eventually be fully removed from the account by an automated internal process.
Example: slcli user delete userId | [
"Sets",
"a",
"user",
"s",
"status",
"to",
"CANCEL_PENDING",
"which",
"will",
"immediately",
"disable",
"the",
"account"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/delete.py#L14-L32 |
softlayer/softlayer-python | SoftLayer/CLI/ssl/edit.py | cli | def cli(env, identifier, crt, csr, icc, key, notes):
"""Edit SSL certificate."""
template = {'id': identifier}
if crt:
template['certificate'] = open(crt).read()
if key:
template['privateKey'] = open(key).read()
if csr:
template['certificateSigningRequest'] = open(csr).read()
if icc:
template['intermediateCertificate'] = open(icc).read()
if notes:
template['notes'] = notes
manager = SoftLayer.SSLManager(env.client)
manager.edit_certificate(template) | python | def cli(env, identifier, crt, csr, icc, key, notes):
template = {'id': identifier}
if crt:
template['certificate'] = open(crt).read()
if key:
template['privateKey'] = open(key).read()
if csr:
template['certificateSigningRequest'] = open(csr).read()
if icc:
template['intermediateCertificate'] = open(icc).read()
if notes:
template['notes'] = notes
manager = SoftLayer.SSLManager(env.client)
manager.edit_certificate(template) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"crt",
",",
"csr",
",",
"icc",
",",
"key",
",",
"notes",
")",
":",
"template",
"=",
"{",
"'id'",
":",
"identifier",
"}",
"if",
"crt",
":",
"template",
"[",
"'certificate'",
"]",
"=",
"open",
"(",
"crt",
")",
".",
"read",
"(",
")",
"if",
"key",
":",
"template",
"[",
"'privateKey'",
"]",
"=",
"open",
"(",
"key",
")",
".",
"read",
"(",
")",
"if",
"csr",
":",
"template",
"[",
"'certificateSigningRequest'",
"]",
"=",
"open",
"(",
"csr",
")",
".",
"read",
"(",
")",
"if",
"icc",
":",
"template",
"[",
"'intermediateCertificate'",
"]",
"=",
"open",
"(",
"icc",
")",
".",
"read",
"(",
")",
"if",
"notes",
":",
"template",
"[",
"'notes'",
"]",
"=",
"notes",
"manager",
"=",
"SoftLayer",
".",
"SSLManager",
"(",
"env",
".",
"client",
")",
"manager",
".",
"edit_certificate",
"(",
"template",
")"
]
| Edit SSL certificate. | [
"Edit",
"SSL",
"certificate",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ssl/edit.py#L24-L39 |
softlayer/softlayer-python | SoftLayer/CLI/cdn/origin_add.py | cli | def cli(env, account_id, content_url, type, cname):
"""Create an origin pull mapping."""
manager = SoftLayer.CDNManager(env.client)
manager.add_origin(account_id, type, content_url, cname) | python | def cli(env, account_id, content_url, type, cname):
manager = SoftLayer.CDNManager(env.client)
manager.add_origin(account_id, type, content_url, cname) | [
"def",
"cli",
"(",
"env",
",",
"account_id",
",",
"content_url",
",",
"type",
",",
"cname",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"CDNManager",
"(",
"env",
".",
"client",
")",
"manager",
".",
"add_origin",
"(",
"account_id",
",",
"type",
",",
"content_url",
",",
"cname",
")"
]
| Create an origin pull mapping. | [
"Create",
"an",
"origin",
"pull",
"mapping",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/cdn/origin_add.py#L22-L26 |
softlayer/softlayer-python | SoftLayer/CLI/template.py | export_to_template | def export_to_template(filename, args, exclude=None):
"""Exports given options to the given filename in INI format.
:param filename: Filename to save options to
:param dict args: Arguments to export
:param list exclude (optional): Exclusion list for options that should not
be exported
"""
exclude = exclude or []
exclude.append('config')
exclude.append('really')
exclude.append('format')
exclude.append('debug')
with open(filename, "w") as template_file:
for k, val in args.items():
if val and k not in exclude:
if isinstance(val, tuple):
val = ','.join(val)
if isinstance(val, list):
val = ','.join(val)
template_file.write('%s=%s\n' % (k, val)) | python | def export_to_template(filename, args, exclude=None):
exclude = exclude or []
exclude.append('config')
exclude.append('really')
exclude.append('format')
exclude.append('debug')
with open(filename, "w") as template_file:
for k, val in args.items():
if val and k not in exclude:
if isinstance(val, tuple):
val = ','.join(val)
if isinstance(val, list):
val = ','.join(val)
template_file.write('%s=%s\n' % (k, val)) | [
"def",
"export_to_template",
"(",
"filename",
",",
"args",
",",
"exclude",
"=",
"None",
")",
":",
"exclude",
"=",
"exclude",
"or",
"[",
"]",
"exclude",
".",
"append",
"(",
"'config'",
")",
"exclude",
".",
"append",
"(",
"'really'",
")",
"exclude",
".",
"append",
"(",
"'format'",
")",
"exclude",
".",
"append",
"(",
"'debug'",
")",
"with",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"as",
"template_file",
":",
"for",
"k",
",",
"val",
"in",
"args",
".",
"items",
"(",
")",
":",
"if",
"val",
"and",
"k",
"not",
"in",
"exclude",
":",
"if",
"isinstance",
"(",
"val",
",",
"tuple",
")",
":",
"val",
"=",
"','",
".",
"join",
"(",
"val",
")",
"if",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"val",
"=",
"','",
".",
"join",
"(",
"val",
")",
"template_file",
".",
"write",
"(",
"'%s=%s\\n'",
"%",
"(",
"k",
",",
"val",
")",
")"
]
| Exports given options to the given filename in INI format.
:param filename: Filename to save options to
:param dict args: Arguments to export
:param list exclude (optional): Exclusion list for options that should not
be exported | [
"Exports",
"given",
"options",
"to",
"the",
"given",
"filename",
"in",
"INI",
"format",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/template.py#L47-L68 |
softlayer/softlayer-python | SoftLayer/managers/vs_placement.py | PlacementManager.list | def list(self, mask=None):
"""List existing placement groups
Calls SoftLayer_Account::getPlacementGroups
"""
if mask is None:
mask = "mask[id, name, createDate, rule, guestCount, backendRouter[id, hostname]]"
groups = self.client.call('Account', 'getPlacementGroups', mask=mask, iter=True)
return groups | python | def list(self, mask=None):
if mask is None:
mask = "mask[id, name, createDate, rule, guestCount, backendRouter[id, hostname]]"
groups = self.client.call('Account', 'getPlacementGroups', mask=mask, iter=True)
return groups | [
"def",
"list",
"(",
"self",
",",
"mask",
"=",
"None",
")",
":",
"if",
"mask",
"is",
"None",
":",
"mask",
"=",
"\"mask[id, name, createDate, rule, guestCount, backendRouter[id, hostname]]\"",
"groups",
"=",
"self",
".",
"client",
".",
"call",
"(",
"'Account'",
",",
"'getPlacementGroups'",
",",
"mask",
"=",
"mask",
",",
"iter",
"=",
"True",
")",
"return",
"groups"
]
| List existing placement groups
Calls SoftLayer_Account::getPlacementGroups | [
"List",
"existing",
"placement",
"groups"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs_placement.py#L40-L48 |
softlayer/softlayer-python | SoftLayer/managers/vs_placement.py | PlacementManager.get_object | def get_object(self, group_id, mask=None):
"""Returns a PlacementGroup Object
https://softlayer.github.io/reference/services/SoftLayer_Virtual_PlacementGroup/getObject
"""
if mask is None:
mask = "mask[id, name, createDate, rule, backendRouter[id, hostname]," \
"guests[activeTransaction[id,transactionStatus[name,friendlyName]]]]"
return self.client.call('SoftLayer_Virtual_PlacementGroup', 'getObject', id=group_id, mask=mask) | python | def get_object(self, group_id, mask=None):
if mask is None:
mask = "mask[id, name, createDate, rule, backendRouter[id, hostname]," \
"guests[activeTransaction[id,transactionStatus[name,friendlyName]]]]"
return self.client.call('SoftLayer_Virtual_PlacementGroup', 'getObject', id=group_id, mask=mask) | [
"def",
"get_object",
"(",
"self",
",",
"group_id",
",",
"mask",
"=",
"None",
")",
":",
"if",
"mask",
"is",
"None",
":",
"mask",
"=",
"\"mask[id, name, createDate, rule, backendRouter[id, hostname],\"",
"\"guests[activeTransaction[id,transactionStatus[name,friendlyName]]]]\"",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'SoftLayer_Virtual_PlacementGroup'",
",",
"'getObject'",
",",
"id",
"=",
"group_id",
",",
"mask",
"=",
"mask",
")"
]
| Returns a PlacementGroup Object
https://softlayer.github.io/reference/services/SoftLayer_Virtual_PlacementGroup/getObject | [
"Returns",
"a",
"PlacementGroup",
"Object"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs_placement.py#L72-L80 |
softlayer/softlayer-python | SoftLayer/managers/vs_placement.py | PlacementManager.get_rule_id_from_name | def get_rule_id_from_name(self, name):
"""Finds the rule that matches name.
SoftLayer_Virtual_PlacementGroup_Rule.getAllObjects doesn't support objectFilters.
"""
results = self.client.call('SoftLayer_Virtual_PlacementGroup_Rule', 'getAllObjects')
return [result['id'] for result in results if result['keyName'] == name.upper()] | python | def get_rule_id_from_name(self, name):
results = self.client.call('SoftLayer_Virtual_PlacementGroup_Rule', 'getAllObjects')
return [result['id'] for result in results if result['keyName'] == name.upper()] | [
"def",
"get_rule_id_from_name",
"(",
"self",
",",
"name",
")",
":",
"results",
"=",
"self",
".",
"client",
".",
"call",
"(",
"'SoftLayer_Virtual_PlacementGroup_Rule'",
",",
"'getAllObjects'",
")",
"return",
"[",
"result",
"[",
"'id'",
"]",
"for",
"result",
"in",
"results",
"if",
"result",
"[",
"'keyName'",
"]",
"==",
"name",
".",
"upper",
"(",
")",
"]"
]
| Finds the rule that matches name.
SoftLayer_Virtual_PlacementGroup_Rule.getAllObjects doesn't support objectFilters. | [
"Finds",
"the",
"rule",
"that",
"matches",
"name",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs_placement.py#L94-L100 |
softlayer/softlayer-python | SoftLayer/managers/vs_placement.py | PlacementManager.get_backend_router_id_from_hostname | def get_backend_router_id_from_hostname(self, hostname):
"""Finds the backend router Id that matches the hostname given
No way to use an objectFilter to find a backendRouter, so we have to search the hard way.
"""
results = self.client.call('SoftLayer_Network_Pod', 'getAllObjects')
return [result['backendRouterId'] for result in results if result['backendRouterName'] == hostname.lower()] | python | def get_backend_router_id_from_hostname(self, hostname):
results = self.client.call('SoftLayer_Network_Pod', 'getAllObjects')
return [result['backendRouterId'] for result in results if result['backendRouterName'] == hostname.lower()] | [
"def",
"get_backend_router_id_from_hostname",
"(",
"self",
",",
"hostname",
")",
":",
"results",
"=",
"self",
".",
"client",
".",
"call",
"(",
"'SoftLayer_Network_Pod'",
",",
"'getAllObjects'",
")",
"return",
"[",
"result",
"[",
"'backendRouterId'",
"]",
"for",
"result",
"in",
"results",
"if",
"result",
"[",
"'backendRouterName'",
"]",
"==",
"hostname",
".",
"lower",
"(",
")",
"]"
]
| Finds the backend router Id that matches the hostname given
No way to use an objectFilter to find a backendRouter, so we have to search the hard way. | [
"Finds",
"the",
"backend",
"router",
"Id",
"that",
"matches",
"the",
"hostname",
"given"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs_placement.py#L102-L108 |
softlayer/softlayer-python | SoftLayer/managers/vs_placement.py | PlacementManager._get_id_from_name | def _get_id_from_name(self, name):
"""List placement group ids which match the given name."""
_filter = {
'placementGroups': {
'name': {'operation': name}
}
}
mask = "mask[id, name]"
results = self.client.call('Account', 'getPlacementGroups', filter=_filter, mask=mask)
return [result['id'] for result in results] | python | def _get_id_from_name(self, name):
_filter = {
'placementGroups': {
'name': {'operation': name}
}
}
mask = "mask[id, name]"
results = self.client.call('Account', 'getPlacementGroups', filter=_filter, mask=mask)
return [result['id'] for result in results] | [
"def",
"_get_id_from_name",
"(",
"self",
",",
"name",
")",
":",
"_filter",
"=",
"{",
"'placementGroups'",
":",
"{",
"'name'",
":",
"{",
"'operation'",
":",
"name",
"}",
"}",
"}",
"mask",
"=",
"\"mask[id, name]\"",
"results",
"=",
"self",
".",
"client",
".",
"call",
"(",
"'Account'",
",",
"'getPlacementGroups'",
",",
"filter",
"=",
"_filter",
",",
"mask",
"=",
"mask",
")",
"return",
"[",
"result",
"[",
"'id'",
"]",
"for",
"result",
"in",
"results",
"]"
]
| List placement group ids which match the given name. | [
"List",
"placement",
"group",
"ids",
"which",
"match",
"the",
"given",
"name",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs_placement.py#L110-L119 |
softlayer/softlayer-python | SoftLayer/CLI/virt/capacity/create_options.py | cli | def cli(env):
"""List options for creating Reserved Capacity"""
manager = CapacityManager(env.client)
items = manager.get_create_options()
items.sort(key=lambda term: int(term['capacity']))
table = formatting.Table(["KeyName", "Description", "Term", "Default Hourly Price Per Instance"],
title="Reserved Capacity Options")
table.align["Hourly Price"] = "l"
table.align["Description"] = "l"
table.align["KeyName"] = "l"
for item in items:
table.add_row([
item['keyName'], item['description'], item['capacity'], get_price(item)
])
env.fout(table)
regions = manager.get_available_routers()
location_table = formatting.Table(['Location', 'POD', 'BackendRouterId'], 'Orderable Locations')
for region in regions:
for location in region['locations']:
for pod in location['location']['pods']:
location_table.add_row([region['keyname'], pod['backendRouterName'], pod['backendRouterId']])
env.fout(location_table) | python | def cli(env):
manager = CapacityManager(env.client)
items = manager.get_create_options()
items.sort(key=lambda term: int(term['capacity']))
table = formatting.Table(["KeyName", "Description", "Term", "Default Hourly Price Per Instance"],
title="Reserved Capacity Options")
table.align["Hourly Price"] = "l"
table.align["Description"] = "l"
table.align["KeyName"] = "l"
for item in items:
table.add_row([
item['keyName'], item['description'], item['capacity'], get_price(item)
])
env.fout(table)
regions = manager.get_available_routers()
location_table = formatting.Table(['Location', 'POD', 'BackendRouterId'], 'Orderable Locations')
for region in regions:
for location in region['locations']:
for pod in location['location']['pods']:
location_table.add_row([region['keyname'], pod['backendRouterName'], pod['backendRouterId']])
env.fout(location_table) | [
"def",
"cli",
"(",
"env",
")",
":",
"manager",
"=",
"CapacityManager",
"(",
"env",
".",
"client",
")",
"items",
"=",
"manager",
".",
"get_create_options",
"(",
")",
"items",
".",
"sort",
"(",
"key",
"=",
"lambda",
"term",
":",
"int",
"(",
"term",
"[",
"'capacity'",
"]",
")",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"\"KeyName\"",
",",
"\"Description\"",
",",
"\"Term\"",
",",
"\"Default Hourly Price Per Instance\"",
"]",
",",
"title",
"=",
"\"Reserved Capacity Options\"",
")",
"table",
".",
"align",
"[",
"\"Hourly Price\"",
"]",
"=",
"\"l\"",
"table",
".",
"align",
"[",
"\"Description\"",
"]",
"=",
"\"l\"",
"table",
".",
"align",
"[",
"\"KeyName\"",
"]",
"=",
"\"l\"",
"for",
"item",
"in",
"items",
":",
"table",
".",
"add_row",
"(",
"[",
"item",
"[",
"'keyName'",
"]",
",",
"item",
"[",
"'description'",
"]",
",",
"item",
"[",
"'capacity'",
"]",
",",
"get_price",
"(",
"item",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")",
"regions",
"=",
"manager",
".",
"get_available_routers",
"(",
")",
"location_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Location'",
",",
"'POD'",
",",
"'BackendRouterId'",
"]",
",",
"'Orderable Locations'",
")",
"for",
"region",
"in",
"regions",
":",
"for",
"location",
"in",
"region",
"[",
"'locations'",
"]",
":",
"for",
"pod",
"in",
"location",
"[",
"'location'",
"]",
"[",
"'pods'",
"]",
":",
"location_table",
".",
"add_row",
"(",
"[",
"region",
"[",
"'keyname'",
"]",
",",
"pod",
"[",
"'backendRouterName'",
"]",
",",
"pod",
"[",
"'backendRouterId'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"location_table",
")"
]
| List options for creating Reserved Capacity | [
"List",
"options",
"for",
"creating",
"Reserved",
"Capacity"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/capacity/create_options.py#L13-L36 |
softlayer/softlayer-python | SoftLayer/CLI/virt/capacity/create_options.py | get_price | def get_price(item):
"""Finds the price with the default locationGroupId"""
the_price = "No Default Pricing"
for price in item.get('prices', []):
if not price.get('locationGroupId'):
the_price = "%0.4f" % float(price['hourlyRecurringFee'])
return the_price | python | def get_price(item):
the_price = "No Default Pricing"
for price in item.get('prices', []):
if not price.get('locationGroupId'):
the_price = "%0.4f" % float(price['hourlyRecurringFee'])
return the_price | [
"def",
"get_price",
"(",
"item",
")",
":",
"the_price",
"=",
"\"No Default Pricing\"",
"for",
"price",
"in",
"item",
".",
"get",
"(",
"'prices'",
",",
"[",
"]",
")",
":",
"if",
"not",
"price",
".",
"get",
"(",
"'locationGroupId'",
")",
":",
"the_price",
"=",
"\"%0.4f\"",
"%",
"float",
"(",
"price",
"[",
"'hourlyRecurringFee'",
"]",
")",
"return",
"the_price"
]
| Finds the price with the default locationGroupId | [
"Finds",
"the",
"price",
"with",
"the",
"default",
"locationGroupId"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/capacity/create_options.py#L39-L45 |
softlayer/softlayer-python | SoftLayer/CLI/order/package_list.py | cli | def cli(env, keyword, package_type):
"""List packages that can be ordered via the placeOrder API.
::
# List out all packages for ordering
slcli order package-list
# List out all packages with "server" in the name
slcli order package-list --keyword server
# Select only specifict package types
slcli order package-list --package_type BARE_METAL_CPU
"""
manager = ordering.OrderingManager(env.client)
table = formatting.Table(COLUMNS)
_filter = {'type': {'keyName': {'operation': '!= BLUEMIX_SERVICE'}}}
if keyword:
_filter['name'] = {'operation': '*= %s' % keyword}
if package_type:
_filter['type'] = {'keyName': {'operation': package_type}}
packages = manager.list_packages(filter=_filter)
for package in packages:
table.add_row([
package['id'],
package['name'],
package['keyName'],
package['type']['keyName']
])
env.fout(table) | python | def cli(env, keyword, package_type):
manager = ordering.OrderingManager(env.client)
table = formatting.Table(COLUMNS)
_filter = {'type': {'keyName': {'operation': '!= BLUEMIX_SERVICE'}}}
if keyword:
_filter['name'] = {'operation': '*= %s' % keyword}
if package_type:
_filter['type'] = {'keyName': {'operation': package_type}}
packages = manager.list_packages(filter=_filter)
for package in packages:
table.add_row([
package['id'],
package['name'],
package['keyName'],
package['type']['keyName']
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"keyword",
",",
"package_type",
")",
":",
"manager",
"=",
"ordering",
".",
"OrderingManager",
"(",
"env",
".",
"client",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"COLUMNS",
")",
"_filter",
"=",
"{",
"'type'",
":",
"{",
"'keyName'",
":",
"{",
"'operation'",
":",
"'!= BLUEMIX_SERVICE'",
"}",
"}",
"}",
"if",
"keyword",
":",
"_filter",
"[",
"'name'",
"]",
"=",
"{",
"'operation'",
":",
"'*= %s'",
"%",
"keyword",
"}",
"if",
"package_type",
":",
"_filter",
"[",
"'type'",
"]",
"=",
"{",
"'keyName'",
":",
"{",
"'operation'",
":",
"package_type",
"}",
"}",
"packages",
"=",
"manager",
".",
"list_packages",
"(",
"filter",
"=",
"_filter",
")",
"for",
"package",
"in",
"packages",
":",
"table",
".",
"add_row",
"(",
"[",
"package",
"[",
"'id'",
"]",
",",
"package",
"[",
"'name'",
"]",
",",
"package",
"[",
"'keyName'",
"]",
",",
"package",
"[",
"'type'",
"]",
"[",
"'keyName'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| List packages that can be ordered via the placeOrder API.
::
# List out all packages for ordering
slcli order package-list
# List out all packages with "server" in the name
slcli order package-list --keyword server
# Select only specifict package types
slcli order package-list --package_type BARE_METAL_CPU | [
"List",
"packages",
"that",
"can",
"be",
"ordered",
"via",
"the",
"placeOrder",
"API",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/package_list.py#L20-L53 |
softlayer/softlayer-python | SoftLayer/CLI/hardware/create.py | cli | def cli(env, **args):
"""Order/create a dedicated server."""
mgr = SoftLayer.HardwareManager(env.client)
# Get the SSH keys
ssh_keys = []
for key in args.get('key'):
resolver = SoftLayer.SshKeyManager(env.client).resolve_ids
key_id = helpers.resolve_id(resolver, key, 'SshKey')
ssh_keys.append(key_id)
order = {
'hostname': args['hostname'],
'domain': args['domain'],
'size': args['size'],
'location': args.get('datacenter'),
'ssh_keys': ssh_keys,
'post_uri': args.get('postinstall'),
'os': args['os'],
'hourly': args.get('billing') == 'hourly',
'port_speed': args.get('port_speed'),
'no_public': args.get('no_public') or False,
'extras': args.get('extra'),
}
# Do not create hardware server with --test or --export
do_create = not (args['export'] or args['test'])
output = None
if args.get('test'):
result = mgr.verify_order(**order)
table = formatting.Table(['Item', 'cost'])
table.align['Item'] = 'r'
table.align['cost'] = 'r'
total = 0.0
for price in result['prices']:
total += float(price.get('recurringFee', 0.0))
rate = "%.2f" % float(price['recurringFee'])
table.add_row([price['item']['description'], rate])
table.add_row(['Total monthly cost', "%.2f" % total])
output = []
output.append(table)
output.append(formatting.FormattedItem(
'',
' -- ! Prices reflected here are retail and do not '
'take account level discounts and are not guaranteed.'))
if args['export']:
export_file = args.pop('export')
template.export_to_template(export_file, args,
exclude=['wait', 'test'])
env.fout('Successfully exported options to a template file.')
return
if do_create:
if not (env.skip_confirmations or formatting.confirm(
"This action will incur charges on your account. "
"Continue?")):
raise exceptions.CLIAbort('Aborting dedicated server order.')
result = mgr.place_order(**order)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', result['orderId']])
table.add_row(['created', result['orderDate']])
output = table
env.fout(output) | python | def cli(env, **args):
mgr = SoftLayer.HardwareManager(env.client)
ssh_keys = []
for key in args.get('key'):
resolver = SoftLayer.SshKeyManager(env.client).resolve_ids
key_id = helpers.resolve_id(resolver, key, 'SshKey')
ssh_keys.append(key_id)
order = {
'hostname': args['hostname'],
'domain': args['domain'],
'size': args['size'],
'location': args.get('datacenter'),
'ssh_keys': ssh_keys,
'post_uri': args.get('postinstall'),
'os': args['os'],
'hourly': args.get('billing') == 'hourly',
'port_speed': args.get('port_speed'),
'no_public': args.get('no_public') or False,
'extras': args.get('extra'),
}
do_create = not (args['export'] or args['test'])
output = None
if args.get('test'):
result = mgr.verify_order(**order)
table = formatting.Table(['Item', 'cost'])
table.align['Item'] = 'r'
table.align['cost'] = 'r'
total = 0.0
for price in result['prices']:
total += float(price.get('recurringFee', 0.0))
rate = "%.2f" % float(price['recurringFee'])
table.add_row([price['item']['description'], rate])
table.add_row(['Total monthly cost', "%.2f" % total])
output = []
output.append(table)
output.append(formatting.FormattedItem(
'',
' -- ! Prices reflected here are retail and do not '
'take account level discounts and are not guaranteed.'))
if args['export']:
export_file = args.pop('export')
template.export_to_template(export_file, args,
exclude=['wait', 'test'])
env.fout('Successfully exported options to a template file.')
return
if do_create:
if not (env.skip_confirmations or formatting.confirm(
"This action will incur charges on your account. "
"Continue?")):
raise exceptions.CLIAbort('Aborting dedicated server order.')
result = mgr.place_order(**order)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', result['orderId']])
table.add_row(['created', result['orderDate']])
output = table
env.fout(output) | [
"def",
"cli",
"(",
"env",
",",
"*",
"*",
"args",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"HardwareManager",
"(",
"env",
".",
"client",
")",
"# Get the SSH keys",
"ssh_keys",
"=",
"[",
"]",
"for",
"key",
"in",
"args",
".",
"get",
"(",
"'key'",
")",
":",
"resolver",
"=",
"SoftLayer",
".",
"SshKeyManager",
"(",
"env",
".",
"client",
")",
".",
"resolve_ids",
"key_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"resolver",
",",
"key",
",",
"'SshKey'",
")",
"ssh_keys",
".",
"append",
"(",
"key_id",
")",
"order",
"=",
"{",
"'hostname'",
":",
"args",
"[",
"'hostname'",
"]",
",",
"'domain'",
":",
"args",
"[",
"'domain'",
"]",
",",
"'size'",
":",
"args",
"[",
"'size'",
"]",
",",
"'location'",
":",
"args",
".",
"get",
"(",
"'datacenter'",
")",
",",
"'ssh_keys'",
":",
"ssh_keys",
",",
"'post_uri'",
":",
"args",
".",
"get",
"(",
"'postinstall'",
")",
",",
"'os'",
":",
"args",
"[",
"'os'",
"]",
",",
"'hourly'",
":",
"args",
".",
"get",
"(",
"'billing'",
")",
"==",
"'hourly'",
",",
"'port_speed'",
":",
"args",
".",
"get",
"(",
"'port_speed'",
")",
",",
"'no_public'",
":",
"args",
".",
"get",
"(",
"'no_public'",
")",
"or",
"False",
",",
"'extras'",
":",
"args",
".",
"get",
"(",
"'extra'",
")",
",",
"}",
"# Do not create hardware server with --test or --export",
"do_create",
"=",
"not",
"(",
"args",
"[",
"'export'",
"]",
"or",
"args",
"[",
"'test'",
"]",
")",
"output",
"=",
"None",
"if",
"args",
".",
"get",
"(",
"'test'",
")",
":",
"result",
"=",
"mgr",
".",
"verify_order",
"(",
"*",
"*",
"order",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Item'",
",",
"'cost'",
"]",
")",
"table",
".",
"align",
"[",
"'Item'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'cost'",
"]",
"=",
"'r'",
"total",
"=",
"0.0",
"for",
"price",
"in",
"result",
"[",
"'prices'",
"]",
":",
"total",
"+=",
"float",
"(",
"price",
".",
"get",
"(",
"'recurringFee'",
",",
"0.0",
")",
")",
"rate",
"=",
"\"%.2f\"",
"%",
"float",
"(",
"price",
"[",
"'recurringFee'",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"price",
"[",
"'item'",
"]",
"[",
"'description'",
"]",
",",
"rate",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Total monthly cost'",
",",
"\"%.2f\"",
"%",
"total",
"]",
")",
"output",
"=",
"[",
"]",
"output",
".",
"append",
"(",
"table",
")",
"output",
".",
"append",
"(",
"formatting",
".",
"FormattedItem",
"(",
"''",
",",
"' -- ! Prices reflected here are retail and do not '",
"'take account level discounts and are not guaranteed.'",
")",
")",
"if",
"args",
"[",
"'export'",
"]",
":",
"export_file",
"=",
"args",
".",
"pop",
"(",
"'export'",
")",
"template",
".",
"export_to_template",
"(",
"export_file",
",",
"args",
",",
"exclude",
"=",
"[",
"'wait'",
",",
"'test'",
"]",
")",
"env",
".",
"fout",
"(",
"'Successfully exported options to a template file.'",
")",
"return",
"if",
"do_create",
":",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"confirm",
"(",
"\"This action will incur charges on your account. \"",
"\"Continue?\"",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborting dedicated server order.'",
")",
"result",
"=",
"mgr",
".",
"place_order",
"(",
"*",
"*",
"order",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"result",
"[",
"'orderId'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'created'",
",",
"result",
"[",
"'orderDate'",
"]",
"]",
")",
"output",
"=",
"table",
"env",
".",
"fout",
"(",
"output",
")"
]
| Order/create a dedicated server. | [
"Order",
"/",
"create",
"a",
"dedicated",
"server",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/create.py#L66-L139 |
softlayer/softlayer-python | SoftLayer/CLI/loadbal/list.py | cli | def cli(env):
"""List active load balancers."""
mgr = SoftLayer.LoadBalancerManager(env.client)
load_balancers = mgr.get_local_lbs()
table = formatting.Table(['ID',
'VIP Address',
'Location',
'SSL Offload',
'Connections/second',
'Type'])
table.align['Connections/second'] = 'r'
for load_balancer in load_balancers:
ssl_support = 'Not Supported'
if load_balancer['sslEnabledFlag']:
if load_balancer['sslActiveFlag']:
ssl_support = 'On'
else:
ssl_support = 'Off'
lb_type = 'Standard'
if load_balancer['dedicatedFlag']:
lb_type = 'Dedicated'
elif load_balancer['highAvailabilityFlag']:
lb_type = 'HA'
table.add_row([
'local:%s' % load_balancer['id'],
load_balancer['ipAddress']['ipAddress'],
load_balancer['loadBalancerHardware'][0]['datacenter']['name'],
ssl_support,
load_balancer['connectionLimit'],
lb_type
])
env.fout(table) | python | def cli(env):
mgr = SoftLayer.LoadBalancerManager(env.client)
load_balancers = mgr.get_local_lbs()
table = formatting.Table(['ID',
'VIP Address',
'Location',
'SSL Offload',
'Connections/second',
'Type'])
table.align['Connections/second'] = 'r'
for load_balancer in load_balancers:
ssl_support = 'Not Supported'
if load_balancer['sslEnabledFlag']:
if load_balancer['sslActiveFlag']:
ssl_support = 'On'
else:
ssl_support = 'Off'
lb_type = 'Standard'
if load_balancer['dedicatedFlag']:
lb_type = 'Dedicated'
elif load_balancer['highAvailabilityFlag']:
lb_type = 'HA'
table.add_row([
'local:%s' % load_balancer['id'],
load_balancer['ipAddress']['ipAddress'],
load_balancer['loadBalancerHardware'][0]['datacenter']['name'],
ssl_support,
load_balancer['connectionLimit'],
lb_type
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"LoadBalancerManager",
"(",
"env",
".",
"client",
")",
"load_balancers",
"=",
"mgr",
".",
"get_local_lbs",
"(",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'ID'",
",",
"'VIP Address'",
",",
"'Location'",
",",
"'SSL Offload'",
",",
"'Connections/second'",
",",
"'Type'",
"]",
")",
"table",
".",
"align",
"[",
"'Connections/second'",
"]",
"=",
"'r'",
"for",
"load_balancer",
"in",
"load_balancers",
":",
"ssl_support",
"=",
"'Not Supported'",
"if",
"load_balancer",
"[",
"'sslEnabledFlag'",
"]",
":",
"if",
"load_balancer",
"[",
"'sslActiveFlag'",
"]",
":",
"ssl_support",
"=",
"'On'",
"else",
":",
"ssl_support",
"=",
"'Off'",
"lb_type",
"=",
"'Standard'",
"if",
"load_balancer",
"[",
"'dedicatedFlag'",
"]",
":",
"lb_type",
"=",
"'Dedicated'",
"elif",
"load_balancer",
"[",
"'highAvailabilityFlag'",
"]",
":",
"lb_type",
"=",
"'HA'",
"table",
".",
"add_row",
"(",
"[",
"'local:%s'",
"%",
"load_balancer",
"[",
"'id'",
"]",
",",
"load_balancer",
"[",
"'ipAddress'",
"]",
"[",
"'ipAddress'",
"]",
",",
"load_balancer",
"[",
"'loadBalancerHardware'",
"]",
"[",
"0",
"]",
"[",
"'datacenter'",
"]",
"[",
"'name'",
"]",
",",
"ssl_support",
",",
"load_balancer",
"[",
"'connectionLimit'",
"]",
",",
"lb_type",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| List active load balancers. | [
"List",
"active",
"load",
"balancers",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/list.py#L13-L49 |
softlayer/softlayer-python | SoftLayer/CLI/hardware/credentials.py | cli | def cli(env, identifier):
"""List server credentials."""
manager = SoftLayer.HardwareManager(env.client)
hardware_id = helpers.resolve_id(manager.resolve_ids,
identifier,
'hardware')
instance = manager.get_hardware(hardware_id)
table = formatting.Table(['username', 'password'])
for item in instance['softwareComponents']:
if 'passwords' not in item:
raise exceptions.SoftLayerError("No passwords found in softwareComponents")
for credentials in item['passwords']:
table.add_row([credentials.get('username', 'None'), credentials.get('password', 'None')])
env.fout(table) | python | def cli(env, identifier):
manager = SoftLayer.HardwareManager(env.client)
hardware_id = helpers.resolve_id(manager.resolve_ids,
identifier,
'hardware')
instance = manager.get_hardware(hardware_id)
table = formatting.Table(['username', 'password'])
for item in instance['softwareComponents']:
if 'passwords' not in item:
raise exceptions.SoftLayerError("No passwords found in softwareComponents")
for credentials in item['passwords']:
table.add_row([credentials.get('username', 'None'), credentials.get('password', 'None')])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"HardwareManager",
"(",
"env",
".",
"client",
")",
"hardware_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"manager",
".",
"resolve_ids",
",",
"identifier",
",",
"'hardware'",
")",
"instance",
"=",
"manager",
".",
"get_hardware",
"(",
"hardware_id",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'username'",
",",
"'password'",
"]",
")",
"for",
"item",
"in",
"instance",
"[",
"'softwareComponents'",
"]",
":",
"if",
"'passwords'",
"not",
"in",
"item",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"No passwords found in softwareComponents\"",
")",
"for",
"credentials",
"in",
"item",
"[",
"'passwords'",
"]",
":",
"table",
".",
"add_row",
"(",
"[",
"credentials",
".",
"get",
"(",
"'username'",
",",
"'None'",
")",
",",
"credentials",
".",
"get",
"(",
"'password'",
",",
"'None'",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| List server credentials. | [
"List",
"server",
"credentials",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/credentials.py#L16-L31 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | populate_host_templates | def populate_host_templates(host_templates,
hardware_ids=None,
virtual_guest_ids=None,
ip_address_ids=None,
subnet_ids=None):
"""Populate the given host_templates array with the IDs provided
:param host_templates: The array to which host templates will be added
:param hardware_ids: A List of SoftLayer_Hardware ids
:param virtual_guest_ids: A List of SoftLayer_Virtual_Guest ids
:param ip_address_ids: A List of SoftLayer_Network_Subnet_IpAddress ids
:param subnet_ids: A List of SoftLayer_Network_Subnet ids
"""
if hardware_ids is not None:
for hardware_id in hardware_ids:
host_templates.append({
'objectType': 'SoftLayer_Hardware',
'id': hardware_id
})
if virtual_guest_ids is not None:
for virtual_guest_id in virtual_guest_ids:
host_templates.append({
'objectType': 'SoftLayer_Virtual_Guest',
'id': virtual_guest_id
})
if ip_address_ids is not None:
for ip_address_id in ip_address_ids:
host_templates.append({
'objectType': 'SoftLayer_Network_Subnet_IpAddress',
'id': ip_address_id
})
if subnet_ids is not None:
for subnet_id in subnet_ids:
host_templates.append({
'objectType': 'SoftLayer_Network_Subnet',
'id': subnet_id
}) | python | def populate_host_templates(host_templates,
hardware_ids=None,
virtual_guest_ids=None,
ip_address_ids=None,
subnet_ids=None):
if hardware_ids is not None:
for hardware_id in hardware_ids:
host_templates.append({
'objectType': 'SoftLayer_Hardware',
'id': hardware_id
})
if virtual_guest_ids is not None:
for virtual_guest_id in virtual_guest_ids:
host_templates.append({
'objectType': 'SoftLayer_Virtual_Guest',
'id': virtual_guest_id
})
if ip_address_ids is not None:
for ip_address_id in ip_address_ids:
host_templates.append({
'objectType': 'SoftLayer_Network_Subnet_IpAddress',
'id': ip_address_id
})
if subnet_ids is not None:
for subnet_id in subnet_ids:
host_templates.append({
'objectType': 'SoftLayer_Network_Subnet',
'id': subnet_id
}) | [
"def",
"populate_host_templates",
"(",
"host_templates",
",",
"hardware_ids",
"=",
"None",
",",
"virtual_guest_ids",
"=",
"None",
",",
"ip_address_ids",
"=",
"None",
",",
"subnet_ids",
"=",
"None",
")",
":",
"if",
"hardware_ids",
"is",
"not",
"None",
":",
"for",
"hardware_id",
"in",
"hardware_ids",
":",
"host_templates",
".",
"append",
"(",
"{",
"'objectType'",
":",
"'SoftLayer_Hardware'",
",",
"'id'",
":",
"hardware_id",
"}",
")",
"if",
"virtual_guest_ids",
"is",
"not",
"None",
":",
"for",
"virtual_guest_id",
"in",
"virtual_guest_ids",
":",
"host_templates",
".",
"append",
"(",
"{",
"'objectType'",
":",
"'SoftLayer_Virtual_Guest'",
",",
"'id'",
":",
"virtual_guest_id",
"}",
")",
"if",
"ip_address_ids",
"is",
"not",
"None",
":",
"for",
"ip_address_id",
"in",
"ip_address_ids",
":",
"host_templates",
".",
"append",
"(",
"{",
"'objectType'",
":",
"'SoftLayer_Network_Subnet_IpAddress'",
",",
"'id'",
":",
"ip_address_id",
"}",
")",
"if",
"subnet_ids",
"is",
"not",
"None",
":",
"for",
"subnet_id",
"in",
"subnet_ids",
":",
"host_templates",
".",
"append",
"(",
"{",
"'objectType'",
":",
"'SoftLayer_Network_Subnet'",
",",
"'id'",
":",
"subnet_id",
"}",
")"
]
| Populate the given host_templates array with the IDs provided
:param host_templates: The array to which host templates will be added
:param hardware_ids: A List of SoftLayer_Hardware ids
:param virtual_guest_ids: A List of SoftLayer_Virtual_Guest ids
:param ip_address_ids: A List of SoftLayer_Network_Subnet_IpAddress ids
:param subnet_ids: A List of SoftLayer_Network_Subnet ids | [
"Populate",
"the",
"given",
"host_templates",
"array",
"with",
"the",
"IDs",
"provided"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L22-L61 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | get_package | def get_package(manager, category_code):
"""Returns a product package based on type of storage.
:param manager: The storage manager which calls this function.
:param category_code: Category code of product package.
:return: Returns a packaged based on type of storage.
"""
_filter = utils.NestedDict({})
_filter['categories']['categoryCode'] = (
utils.query_filter(category_code))
_filter['statusCode'] = (utils.query_filter('ACTIVE'))
packages = manager.client.call(
'Product_Package', 'getAllObjects',
filter=_filter.to_dict(),
mask='id,name,items[prices[categories],attributes]'
)
if len(packages) == 0:
raise ValueError('No packages were found for %s' % category_code)
if len(packages) > 1:
raise ValueError('More than one package was found for %s'
% category_code)
return packages[0] | python | def get_package(manager, category_code):
_filter = utils.NestedDict({})
_filter['categories']['categoryCode'] = (
utils.query_filter(category_code))
_filter['statusCode'] = (utils.query_filter('ACTIVE'))
packages = manager.client.call(
'Product_Package', 'getAllObjects',
filter=_filter.to_dict(),
mask='id,name,items[prices[categories],attributes]'
)
if len(packages) == 0:
raise ValueError('No packages were found for %s' % category_code)
if len(packages) > 1:
raise ValueError('More than one package was found for %s'
% category_code)
return packages[0] | [
"def",
"get_package",
"(",
"manager",
",",
"category_code",
")",
":",
"_filter",
"=",
"utils",
".",
"NestedDict",
"(",
"{",
"}",
")",
"_filter",
"[",
"'categories'",
"]",
"[",
"'categoryCode'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"category_code",
")",
")",
"_filter",
"[",
"'statusCode'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"'ACTIVE'",
")",
")",
"packages",
"=",
"manager",
".",
"client",
".",
"call",
"(",
"'Product_Package'",
",",
"'getAllObjects'",
",",
"filter",
"=",
"_filter",
".",
"to_dict",
"(",
")",
",",
"mask",
"=",
"'id,name,items[prices[categories],attributes]'",
")",
"if",
"len",
"(",
"packages",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'No packages were found for %s'",
"%",
"category_code",
")",
"if",
"len",
"(",
"packages",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"'More than one package was found for %s'",
"%",
"category_code",
")",
"return",
"packages",
"[",
"0",
"]"
]
| Returns a product package based on type of storage.
:param manager: The storage manager which calls this function.
:param category_code: Category code of product package.
:return: Returns a packaged based on type of storage. | [
"Returns",
"a",
"product",
"package",
"based",
"on",
"type",
"of",
"storage",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L64-L88 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | get_location_id | def get_location_id(manager, location):
"""Returns location id
:param manager: The storage manager which calls this function.
:param location: Datacenter short name
:return: Returns location id
"""
loc_svc = manager.client['Location_Datacenter']
datacenters = loc_svc.getDatacenters(mask='mask[longName,id,name]')
for datacenter in datacenters:
if datacenter['name'] == location:
location = datacenter['id']
return location
raise ValueError('Invalid datacenter name specified.') | python | def get_location_id(manager, location):
loc_svc = manager.client['Location_Datacenter']
datacenters = loc_svc.getDatacenters(mask='mask[longName,id,name]')
for datacenter in datacenters:
if datacenter['name'] == location:
location = datacenter['id']
return location
raise ValueError('Invalid datacenter name specified.') | [
"def",
"get_location_id",
"(",
"manager",
",",
"location",
")",
":",
"loc_svc",
"=",
"manager",
".",
"client",
"[",
"'Location_Datacenter'",
"]",
"datacenters",
"=",
"loc_svc",
".",
"getDatacenters",
"(",
"mask",
"=",
"'mask[longName,id,name]'",
")",
"for",
"datacenter",
"in",
"datacenters",
":",
"if",
"datacenter",
"[",
"'name'",
"]",
"==",
"location",
":",
"location",
"=",
"datacenter",
"[",
"'id'",
"]",
"return",
"location",
"raise",
"ValueError",
"(",
"'Invalid datacenter name specified.'",
")"
]
| Returns location id
:param manager: The storage manager which calls this function.
:param location: Datacenter short name
:return: Returns location id | [
"Returns",
"location",
"id"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L91-L104 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | find_price_by_category | def find_price_by_category(package, price_category):
"""Find the price in the given package that has the specified category
:param package: The AsAService, Enterprise, or Performance product package
:param price_category: The price category code to search for
:return: Returns the price for the given category, or an error if not found
"""
for item in package['items']:
price_id = _find_price_id(item['prices'], price_category)
if price_id:
return price_id
raise ValueError("Could not find price with the category, %s" % price_category) | python | def find_price_by_category(package, price_category):
for item in package['items']:
price_id = _find_price_id(item['prices'], price_category)
if price_id:
return price_id
raise ValueError("Could not find price with the category, %s" % price_category) | [
"def",
"find_price_by_category",
"(",
"package",
",",
"price_category",
")",
":",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"price_id",
"=",
"_find_price_id",
"(",
"item",
"[",
"'prices'",
"]",
",",
"price_category",
")",
"if",
"price_id",
":",
"return",
"price_id",
"raise",
"ValueError",
"(",
"\"Could not find price with the category, %s\"",
"%",
"price_category",
")"
]
| Find the price in the given package that has the specified category
:param package: The AsAService, Enterprise, or Performance product package
:param price_category: The price category code to search for
:return: Returns the price for the given category, or an error if not found | [
"Find",
"the",
"price",
"in",
"the",
"given",
"package",
"that",
"has",
"the",
"specified",
"category"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L107-L119 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | find_ent_space_price | def find_ent_space_price(package, category, size, tier_level):
"""Find the space price for the given category, size, and tier
:param package: The Enterprise (Endurance) product package
:param category: The category of space (endurance, replication, snapshot)
:param size: The size for which a price is desired
:param tier_level: The endurance tier for which a price is desired
:return: Returns the matching price, or an error if not found
"""
if category == 'snapshot':
category_code = 'storage_snapshot_space'
elif category == 'replication':
category_code = 'performance_storage_replication'
else: # category == 'endurance'
category_code = 'performance_storage_space'
level = ENDURANCE_TIERS.get(tier_level)
for item in package['items']:
if int(item['capacity']) != size:
continue
price_id = _find_price_id(item['prices'], category_code, 'STORAGE_TIER_LEVEL', level)
if price_id:
return price_id
raise ValueError("Could not find price for %s storage space" % category) | python | def find_ent_space_price(package, category, size, tier_level):
if category == 'snapshot':
category_code = 'storage_snapshot_space'
elif category == 'replication':
category_code = 'performance_storage_replication'
else:
category_code = 'performance_storage_space'
level = ENDURANCE_TIERS.get(tier_level)
for item in package['items']:
if int(item['capacity']) != size:
continue
price_id = _find_price_id(item['prices'], category_code, 'STORAGE_TIER_LEVEL', level)
if price_id:
return price_id
raise ValueError("Could not find price for %s storage space" % category) | [
"def",
"find_ent_space_price",
"(",
"package",
",",
"category",
",",
"size",
",",
"tier_level",
")",
":",
"if",
"category",
"==",
"'snapshot'",
":",
"category_code",
"=",
"'storage_snapshot_space'",
"elif",
"category",
"==",
"'replication'",
":",
"category_code",
"=",
"'performance_storage_replication'",
"else",
":",
"# category == 'endurance'",
"category_code",
"=",
"'performance_storage_space'",
"level",
"=",
"ENDURANCE_TIERS",
".",
"get",
"(",
"tier_level",
")",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"int",
"(",
"item",
"[",
"'capacity'",
"]",
")",
"!=",
"size",
":",
"continue",
"price_id",
"=",
"_find_price_id",
"(",
"item",
"[",
"'prices'",
"]",
",",
"category_code",
",",
"'STORAGE_TIER_LEVEL'",
",",
"level",
")",
"if",
"price_id",
":",
"return",
"price_id",
"raise",
"ValueError",
"(",
"\"Could not find price for %s storage space\"",
"%",
"category",
")"
]
| Find the space price for the given category, size, and tier
:param package: The Enterprise (Endurance) product package
:param category: The category of space (endurance, replication, snapshot)
:param size: The size for which a price is desired
:param tier_level: The endurance tier for which a price is desired
:return: Returns the matching price, or an error if not found | [
"Find",
"the",
"space",
"price",
"for",
"the",
"given",
"category",
"size",
"and",
"tier"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L122-L147 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | find_ent_endurance_tier_price | def find_ent_endurance_tier_price(package, tier_level):
"""Find the price in the given package with the specified tier level
:param package: The Enterprise (Endurance) product package
:param tier_level: The endurance tier for which a price is desired
:return: Returns the price for the given tier, or an error if not found
"""
for item in package['items']:
for attribute in item.get('attributes', []):
if int(attribute['value']) == ENDURANCE_TIERS.get(tier_level):
break
else:
continue
price_id = _find_price_id(item['prices'], 'storage_tier_level')
if price_id:
return price_id
raise ValueError("Could not find price for endurance tier level") | python | def find_ent_endurance_tier_price(package, tier_level):
for item in package['items']:
for attribute in item.get('attributes', []):
if int(attribute['value']) == ENDURANCE_TIERS.get(tier_level):
break
else:
continue
price_id = _find_price_id(item['prices'], 'storage_tier_level')
if price_id:
return price_id
raise ValueError("Could not find price for endurance tier level") | [
"def",
"find_ent_endurance_tier_price",
"(",
"package",
",",
"tier_level",
")",
":",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"for",
"attribute",
"in",
"item",
".",
"get",
"(",
"'attributes'",
",",
"[",
"]",
")",
":",
"if",
"int",
"(",
"attribute",
"[",
"'value'",
"]",
")",
"==",
"ENDURANCE_TIERS",
".",
"get",
"(",
"tier_level",
")",
":",
"break",
"else",
":",
"continue",
"price_id",
"=",
"_find_price_id",
"(",
"item",
"[",
"'prices'",
"]",
",",
"'storage_tier_level'",
")",
"if",
"price_id",
":",
"return",
"price_id",
"raise",
"ValueError",
"(",
"\"Could not find price for endurance tier level\"",
")"
]
| Find the price in the given package with the specified tier level
:param package: The Enterprise (Endurance) product package
:param tier_level: The endurance tier for which a price is desired
:return: Returns the price for the given tier, or an error if not found | [
"Find",
"the",
"price",
"in",
"the",
"given",
"package",
"with",
"the",
"specified",
"tier",
"level"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L150-L168 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | find_endurance_tier_iops_per_gb | def find_endurance_tier_iops_per_gb(volume):
"""Find the tier for the given endurance volume (IOPS per GB)
:param volume: The volume for which the tier level is desired
:return: Returns a float value indicating the IOPS per GB for the volume
"""
tier = volume['storageTierLevel']
iops_per_gb = 0.25
if tier == "LOW_INTENSITY_TIER":
iops_per_gb = 0.25
elif tier == "READHEAVY_TIER":
iops_per_gb = 2
elif tier == "WRITEHEAVY_TIER":
iops_per_gb = 4
elif tier == "10_IOPS_PER_GB":
iops_per_gb = 10
else:
raise ValueError("Could not find tier IOPS per GB for this volume")
return iops_per_gb | python | def find_endurance_tier_iops_per_gb(volume):
tier = volume['storageTierLevel']
iops_per_gb = 0.25
if tier == "LOW_INTENSITY_TIER":
iops_per_gb = 0.25
elif tier == "READHEAVY_TIER":
iops_per_gb = 2
elif tier == "WRITEHEAVY_TIER":
iops_per_gb = 4
elif tier == "10_IOPS_PER_GB":
iops_per_gb = 10
else:
raise ValueError("Could not find tier IOPS per GB for this volume")
return iops_per_gb | [
"def",
"find_endurance_tier_iops_per_gb",
"(",
"volume",
")",
":",
"tier",
"=",
"volume",
"[",
"'storageTierLevel'",
"]",
"iops_per_gb",
"=",
"0.25",
"if",
"tier",
"==",
"\"LOW_INTENSITY_TIER\"",
":",
"iops_per_gb",
"=",
"0.25",
"elif",
"tier",
"==",
"\"READHEAVY_TIER\"",
":",
"iops_per_gb",
"=",
"2",
"elif",
"tier",
"==",
"\"WRITEHEAVY_TIER\"",
":",
"iops_per_gb",
"=",
"4",
"elif",
"tier",
"==",
"\"10_IOPS_PER_GB\"",
":",
"iops_per_gb",
"=",
"10",
"else",
":",
"raise",
"ValueError",
"(",
"\"Could not find tier IOPS per GB for this volume\"",
")",
"return",
"iops_per_gb"
]
| Find the tier for the given endurance volume (IOPS per GB)
:param volume: The volume for which the tier level is desired
:return: Returns a float value indicating the IOPS per GB for the volume | [
"Find",
"the",
"tier",
"for",
"the",
"given",
"endurance",
"volume",
"(",
"IOPS",
"per",
"GB",
")"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L171-L191 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | find_perf_space_price | def find_perf_space_price(package, size):
"""Find the price in the given package with the specified size
:param package: The Performance product package
:param size: The storage space size for which a price is desired
:return: Returns the price for the given size, or an error if not found
"""
for item in package['items']:
if int(item['capacity']) != size:
continue
price_id = _find_price_id(item['prices'], 'performance_storage_space')
if price_id:
return price_id
raise ValueError("Could not find performance space price for this volume") | python | def find_perf_space_price(package, size):
for item in package['items']:
if int(item['capacity']) != size:
continue
price_id = _find_price_id(item['prices'], 'performance_storage_space')
if price_id:
return price_id
raise ValueError("Could not find performance space price for this volume") | [
"def",
"find_perf_space_price",
"(",
"package",
",",
"size",
")",
":",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"int",
"(",
"item",
"[",
"'capacity'",
"]",
")",
"!=",
"size",
":",
"continue",
"price_id",
"=",
"_find_price_id",
"(",
"item",
"[",
"'prices'",
"]",
",",
"'performance_storage_space'",
")",
"if",
"price_id",
":",
"return",
"price_id",
"raise",
"ValueError",
"(",
"\"Could not find performance space price for this volume\"",
")"
]
| Find the price in the given package with the specified size
:param package: The Performance product package
:param size: The storage space size for which a price is desired
:return: Returns the price for the given size, or an error if not found | [
"Find",
"the",
"price",
"in",
"the",
"given",
"package",
"with",
"the",
"specified",
"size"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L194-L209 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | find_perf_iops_price | def find_perf_iops_price(package, size, iops):
"""Find the price in the given package with the specified size and iops
:param package: The Performance product package
:param size: The size of storage space for which an IOPS price is desired
:param iops: The number of IOPS for which a price is desired
:return: Returns the price for the size and IOPS, or an error if not found
"""
for item in package['items']:
if int(item['capacity']) != int(iops):
continue
price_id = _find_price_id(item['prices'], 'performance_storage_iops', 'STORAGE_SPACE', size)
if price_id:
return price_id
raise ValueError("Could not find price for iops for the given volume") | python | def find_perf_iops_price(package, size, iops):
for item in package['items']:
if int(item['capacity']) != int(iops):
continue
price_id = _find_price_id(item['prices'], 'performance_storage_iops', 'STORAGE_SPACE', size)
if price_id:
return price_id
raise ValueError("Could not find price for iops for the given volume") | [
"def",
"find_perf_iops_price",
"(",
"package",
",",
"size",
",",
"iops",
")",
":",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"int",
"(",
"item",
"[",
"'capacity'",
"]",
")",
"!=",
"int",
"(",
"iops",
")",
":",
"continue",
"price_id",
"=",
"_find_price_id",
"(",
"item",
"[",
"'prices'",
"]",
",",
"'performance_storage_iops'",
",",
"'STORAGE_SPACE'",
",",
"size",
")",
"if",
"price_id",
":",
"return",
"price_id",
"raise",
"ValueError",
"(",
"\"Could not find price for iops for the given volume\"",
")"
]
| Find the price in the given package with the specified size and iops
:param package: The Performance product package
:param size: The size of storage space for which an IOPS price is desired
:param iops: The number of IOPS for which a price is desired
:return: Returns the price for the size and IOPS, or an error if not found | [
"Find",
"the",
"price",
"in",
"the",
"given",
"package",
"with",
"the",
"specified",
"size",
"and",
"iops"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L212-L228 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | find_saas_endurance_space_price | def find_saas_endurance_space_price(package, size, tier_level):
"""Find the SaaS endurance storage space price for the size and tier
:param package: The Storage As A Service product package
:param size: The volume size for which a price is desired
:param tier_level: The endurance tier for which a price is desired
:return: Returns the price for the size and tier, or an error if not found
"""
if tier_level != 0.25:
tier_level = int(tier_level)
key_name = 'STORAGE_SPACE_FOR_{0}_IOPS_PER_GB'.format(tier_level)
key_name = key_name.replace(".", "_")
for item in package['items']:
if key_name not in item['keyName']:
continue
if 'capacityMinimum' not in item or 'capacityMaximum' not in item:
continue
capacity_minimum = int(item['capacityMinimum'])
capacity_maximum = int(item['capacityMaximum'])
if size < capacity_minimum or size > capacity_maximum:
continue
price_id = _find_price_id(item['prices'], 'performance_storage_space')
if price_id:
return price_id
raise ValueError("Could not find price for endurance storage space") | python | def find_saas_endurance_space_price(package, size, tier_level):
if tier_level != 0.25:
tier_level = int(tier_level)
key_name = 'STORAGE_SPACE_FOR_{0}_IOPS_PER_GB'.format(tier_level)
key_name = key_name.replace(".", "_")
for item in package['items']:
if key_name not in item['keyName']:
continue
if 'capacityMinimum' not in item or 'capacityMaximum' not in item:
continue
capacity_minimum = int(item['capacityMinimum'])
capacity_maximum = int(item['capacityMaximum'])
if size < capacity_minimum or size > capacity_maximum:
continue
price_id = _find_price_id(item['prices'], 'performance_storage_space')
if price_id:
return price_id
raise ValueError("Could not find price for endurance storage space") | [
"def",
"find_saas_endurance_space_price",
"(",
"package",
",",
"size",
",",
"tier_level",
")",
":",
"if",
"tier_level",
"!=",
"0.25",
":",
"tier_level",
"=",
"int",
"(",
"tier_level",
")",
"key_name",
"=",
"'STORAGE_SPACE_FOR_{0}_IOPS_PER_GB'",
".",
"format",
"(",
"tier_level",
")",
"key_name",
"=",
"key_name",
".",
"replace",
"(",
"\".\"",
",",
"\"_\"",
")",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"key_name",
"not",
"in",
"item",
"[",
"'keyName'",
"]",
":",
"continue",
"if",
"'capacityMinimum'",
"not",
"in",
"item",
"or",
"'capacityMaximum'",
"not",
"in",
"item",
":",
"continue",
"capacity_minimum",
"=",
"int",
"(",
"item",
"[",
"'capacityMinimum'",
"]",
")",
"capacity_maximum",
"=",
"int",
"(",
"item",
"[",
"'capacityMaximum'",
"]",
")",
"if",
"size",
"<",
"capacity_minimum",
"or",
"size",
">",
"capacity_maximum",
":",
"continue",
"price_id",
"=",
"_find_price_id",
"(",
"item",
"[",
"'prices'",
"]",
",",
"'performance_storage_space'",
")",
"if",
"price_id",
":",
"return",
"price_id",
"raise",
"ValueError",
"(",
"\"Could not find price for endurance storage space\"",
")"
]
| Find the SaaS endurance storage space price for the size and tier
:param package: The Storage As A Service product package
:param size: The volume size for which a price is desired
:param tier_level: The endurance tier for which a price is desired
:return: Returns the price for the size and tier, or an error if not found | [
"Find",
"the",
"SaaS",
"endurance",
"storage",
"space",
"price",
"for",
"the",
"size",
"and",
"tier"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L231-L259 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | find_saas_endurance_tier_price | def find_saas_endurance_tier_price(package, tier_level):
"""Find the SaaS storage tier level price for the specified tier level
:param package: The Storage As A Service product package
:param tier_level: The endurance tier for which a price is desired
:return: Returns the price for the given tier, or an error if not found
"""
target_capacity = ENDURANCE_TIERS.get(tier_level)
for item in package['items']:
if 'itemCategory' not in item\
or 'categoryCode' not in item['itemCategory']\
or item['itemCategory']['categoryCode']\
!= 'storage_tier_level':
continue
if int(item['capacity']) != target_capacity:
continue
price_id = _find_price_id(item['prices'], 'storage_tier_level')
if price_id:
return price_id
raise ValueError("Could not find price for endurance tier level") | python | def find_saas_endurance_tier_price(package, tier_level):
target_capacity = ENDURANCE_TIERS.get(tier_level)
for item in package['items']:
if 'itemCategory' not in item\
or 'categoryCode' not in item['itemCategory']\
or item['itemCategory']['categoryCode']\
!= 'storage_tier_level':
continue
if int(item['capacity']) != target_capacity:
continue
price_id = _find_price_id(item['prices'], 'storage_tier_level')
if price_id:
return price_id
raise ValueError("Could not find price for endurance tier level") | [
"def",
"find_saas_endurance_tier_price",
"(",
"package",
",",
"tier_level",
")",
":",
"target_capacity",
"=",
"ENDURANCE_TIERS",
".",
"get",
"(",
"tier_level",
")",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"'itemCategory'",
"not",
"in",
"item",
"or",
"'categoryCode'",
"not",
"in",
"item",
"[",
"'itemCategory'",
"]",
"or",
"item",
"[",
"'itemCategory'",
"]",
"[",
"'categoryCode'",
"]",
"!=",
"'storage_tier_level'",
":",
"continue",
"if",
"int",
"(",
"item",
"[",
"'capacity'",
"]",
")",
"!=",
"target_capacity",
":",
"continue",
"price_id",
"=",
"_find_price_id",
"(",
"item",
"[",
"'prices'",
"]",
",",
"'storage_tier_level'",
")",
"if",
"price_id",
":",
"return",
"price_id",
"raise",
"ValueError",
"(",
"\"Could not find price for endurance tier level\"",
")"
]
| Find the SaaS storage tier level price for the specified tier level
:param package: The Storage As A Service product package
:param tier_level: The endurance tier for which a price is desired
:return: Returns the price for the given tier, or an error if not found | [
"Find",
"the",
"SaaS",
"storage",
"tier",
"level",
"price",
"for",
"the",
"specified",
"tier",
"level"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L262-L284 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | find_saas_perform_space_price | def find_saas_perform_space_price(package, size):
"""Find the SaaS performance storage space price for the given size
:param package: The Storage As A Service product package
:param size: The volume size for which a price is desired
:return: Returns the price for the size and tier, or an error if not found
"""
for item in package['items']:
if 'itemCategory' not in item\
or 'categoryCode' not in item['itemCategory']\
or item['itemCategory']['categoryCode']\
!= 'performance_storage_space':
continue
if 'capacityMinimum' not in item or 'capacityMaximum' not in item:
continue
capacity_minimum = int(item['capacityMinimum'])
capacity_maximum = int(item['capacityMaximum'])
if size < capacity_minimum or size > capacity_maximum:
continue
key_name = '{0}_{1}_GBS'.format(capacity_minimum, capacity_maximum)
if item['keyName'] != key_name:
continue
price_id = _find_price_id(item['prices'], 'performance_storage_space')
if price_id:
return price_id
raise ValueError("Could not find price for performance storage space") | python | def find_saas_perform_space_price(package, size):
for item in package['items']:
if 'itemCategory' not in item\
or 'categoryCode' not in item['itemCategory']\
or item['itemCategory']['categoryCode']\
!= 'performance_storage_space':
continue
if 'capacityMinimum' not in item or 'capacityMaximum' not in item:
continue
capacity_minimum = int(item['capacityMinimum'])
capacity_maximum = int(item['capacityMaximum'])
if size < capacity_minimum or size > capacity_maximum:
continue
key_name = '{0}_{1}_GBS'.format(capacity_minimum, capacity_maximum)
if item['keyName'] != key_name:
continue
price_id = _find_price_id(item['prices'], 'performance_storage_space')
if price_id:
return price_id
raise ValueError("Could not find price for performance storage space") | [
"def",
"find_saas_perform_space_price",
"(",
"package",
",",
"size",
")",
":",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"'itemCategory'",
"not",
"in",
"item",
"or",
"'categoryCode'",
"not",
"in",
"item",
"[",
"'itemCategory'",
"]",
"or",
"item",
"[",
"'itemCategory'",
"]",
"[",
"'categoryCode'",
"]",
"!=",
"'performance_storage_space'",
":",
"continue",
"if",
"'capacityMinimum'",
"not",
"in",
"item",
"or",
"'capacityMaximum'",
"not",
"in",
"item",
":",
"continue",
"capacity_minimum",
"=",
"int",
"(",
"item",
"[",
"'capacityMinimum'",
"]",
")",
"capacity_maximum",
"=",
"int",
"(",
"item",
"[",
"'capacityMaximum'",
"]",
")",
"if",
"size",
"<",
"capacity_minimum",
"or",
"size",
">",
"capacity_maximum",
":",
"continue",
"key_name",
"=",
"'{0}_{1}_GBS'",
".",
"format",
"(",
"capacity_minimum",
",",
"capacity_maximum",
")",
"if",
"item",
"[",
"'keyName'",
"]",
"!=",
"key_name",
":",
"continue",
"price_id",
"=",
"_find_price_id",
"(",
"item",
"[",
"'prices'",
"]",
",",
"'performance_storage_space'",
")",
"if",
"price_id",
":",
"return",
"price_id",
"raise",
"ValueError",
"(",
"\"Could not find price for performance storage space\"",
")"
]
| Find the SaaS performance storage space price for the given size
:param package: The Storage As A Service product package
:param size: The volume size for which a price is desired
:return: Returns the price for the size and tier, or an error if not found | [
"Find",
"the",
"SaaS",
"performance",
"storage",
"space",
"price",
"for",
"the",
"given",
"size"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L287-L316 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | find_saas_perform_iops_price | def find_saas_perform_iops_price(package, size, iops):
"""Find the SaaS IOPS price for the specified size and iops
:param package: The Storage As A Service product package
:param size: The volume size for which a price is desired
:param iops: The number of IOPS for which a price is desired
:return: Returns the price for the size and IOPS, or an error if not found
"""
for item in package['items']:
if 'itemCategory' not in item\
or 'categoryCode' not in item['itemCategory']\
or item['itemCategory']['categoryCode']\
!= 'performance_storage_iops':
continue
if 'capacityMinimum' not in item or 'capacityMaximum' not in item:
continue
capacity_minimum = int(item['capacityMinimum'])
capacity_maximum = int(item['capacityMaximum'])
if iops < capacity_minimum or iops > capacity_maximum:
continue
price_id = _find_price_id(item['prices'], 'performance_storage_iops', 'STORAGE_SPACE', size)
if price_id:
return price_id
raise ValueError("Could not find price for iops for the given volume") | python | def find_saas_perform_iops_price(package, size, iops):
for item in package['items']:
if 'itemCategory' not in item\
or 'categoryCode' not in item['itemCategory']\
or item['itemCategory']['categoryCode']\
!= 'performance_storage_iops':
continue
if 'capacityMinimum' not in item or 'capacityMaximum' not in item:
continue
capacity_minimum = int(item['capacityMinimum'])
capacity_maximum = int(item['capacityMaximum'])
if iops < capacity_minimum or iops > capacity_maximum:
continue
price_id = _find_price_id(item['prices'], 'performance_storage_iops', 'STORAGE_SPACE', size)
if price_id:
return price_id
raise ValueError("Could not find price for iops for the given volume") | [
"def",
"find_saas_perform_iops_price",
"(",
"package",
",",
"size",
",",
"iops",
")",
":",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"'itemCategory'",
"not",
"in",
"item",
"or",
"'categoryCode'",
"not",
"in",
"item",
"[",
"'itemCategory'",
"]",
"or",
"item",
"[",
"'itemCategory'",
"]",
"[",
"'categoryCode'",
"]",
"!=",
"'performance_storage_iops'",
":",
"continue",
"if",
"'capacityMinimum'",
"not",
"in",
"item",
"or",
"'capacityMaximum'",
"not",
"in",
"item",
":",
"continue",
"capacity_minimum",
"=",
"int",
"(",
"item",
"[",
"'capacityMinimum'",
"]",
")",
"capacity_maximum",
"=",
"int",
"(",
"item",
"[",
"'capacityMaximum'",
"]",
")",
"if",
"iops",
"<",
"capacity_minimum",
"or",
"iops",
">",
"capacity_maximum",
":",
"continue",
"price_id",
"=",
"_find_price_id",
"(",
"item",
"[",
"'prices'",
"]",
",",
"'performance_storage_iops'",
",",
"'STORAGE_SPACE'",
",",
"size",
")",
"if",
"price_id",
":",
"return",
"price_id",
"raise",
"ValueError",
"(",
"\"Could not find price for iops for the given volume\"",
")"
]
| Find the SaaS IOPS price for the specified size and iops
:param package: The Storage As A Service product package
:param size: The volume size for which a price is desired
:param iops: The number of IOPS for which a price is desired
:return: Returns the price for the size and IOPS, or an error if not found | [
"Find",
"the",
"SaaS",
"IOPS",
"price",
"for",
"the",
"specified",
"size",
"and",
"iops"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L319-L346 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | find_saas_snapshot_space_price | def find_saas_snapshot_space_price(package, size, tier=None, iops=None):
"""Find the price in the SaaS package for the desired snapshot space size
:param package: The product package of the endurance storage type
:param size: The snapshot space size for which a price is desired
:param tier: The tier of the volume for which space is being ordered
:param iops: The IOPS of the volume for which space is being ordered
:return: Returns the price for the given size, or an error if not found
"""
if tier is not None:
target_value = ENDURANCE_TIERS.get(tier)
target_restriction_type = 'STORAGE_TIER_LEVEL'
else:
target_value = iops
target_restriction_type = 'IOPS'
for item in package['items']:
if int(item['capacity']) != size:
continue
price_id = _find_price_id(item['prices'], 'storage_snapshot_space', target_restriction_type, target_value)
if price_id:
return price_id
raise ValueError("Could not find price for snapshot space") | python | def find_saas_snapshot_space_price(package, size, tier=None, iops=None):
if tier is not None:
target_value = ENDURANCE_TIERS.get(tier)
target_restriction_type = 'STORAGE_TIER_LEVEL'
else:
target_value = iops
target_restriction_type = 'IOPS'
for item in package['items']:
if int(item['capacity']) != size:
continue
price_id = _find_price_id(item['prices'], 'storage_snapshot_space', target_restriction_type, target_value)
if price_id:
return price_id
raise ValueError("Could not find price for snapshot space") | [
"def",
"find_saas_snapshot_space_price",
"(",
"package",
",",
"size",
",",
"tier",
"=",
"None",
",",
"iops",
"=",
"None",
")",
":",
"if",
"tier",
"is",
"not",
"None",
":",
"target_value",
"=",
"ENDURANCE_TIERS",
".",
"get",
"(",
"tier",
")",
"target_restriction_type",
"=",
"'STORAGE_TIER_LEVEL'",
"else",
":",
"target_value",
"=",
"iops",
"target_restriction_type",
"=",
"'IOPS'",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"int",
"(",
"item",
"[",
"'capacity'",
"]",
")",
"!=",
"size",
":",
"continue",
"price_id",
"=",
"_find_price_id",
"(",
"item",
"[",
"'prices'",
"]",
",",
"'storage_snapshot_space'",
",",
"target_restriction_type",
",",
"target_value",
")",
"if",
"price_id",
":",
"return",
"price_id",
"raise",
"ValueError",
"(",
"\"Could not find price for snapshot space\"",
")"
]
| Find the price in the SaaS package for the desired snapshot space size
:param package: The product package of the endurance storage type
:param size: The snapshot space size for which a price is desired
:param tier: The tier of the volume for which space is being ordered
:param iops: The IOPS of the volume for which space is being ordered
:return: Returns the price for the given size, or an error if not found | [
"Find",
"the",
"price",
"in",
"the",
"SaaS",
"package",
"for",
"the",
"desired",
"snapshot",
"space",
"size"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L349-L373 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | find_saas_replication_price | def find_saas_replication_price(package, tier=None, iops=None):
"""Find the price in the given package for the desired replicant volume
:param package: The product package of the endurance storage type
:param tier: The tier of the primary storage volume
:param iops: The IOPS of the primary storage volume
:return: Returns the replication price, or an error if not found
"""
if tier is not None:
target_value = ENDURANCE_TIERS.get(tier)
target_item_keyname = 'REPLICATION_FOR_TIERBASED_PERFORMANCE'
target_restriction_type = 'STORAGE_TIER_LEVEL'
else:
target_value = iops
target_item_keyname = 'REPLICATION_FOR_IOPSBASED_PERFORMANCE'
target_restriction_type = 'IOPS'
for item in package['items']:
if item['keyName'] != target_item_keyname:
continue
price_id = _find_price_id(
item['prices'],
'performance_storage_replication',
target_restriction_type,
target_value
)
if price_id:
return price_id
raise ValueError("Could not find price for replicant volume") | python | def find_saas_replication_price(package, tier=None, iops=None):
if tier is not None:
target_value = ENDURANCE_TIERS.get(tier)
target_item_keyname = 'REPLICATION_FOR_TIERBASED_PERFORMANCE'
target_restriction_type = 'STORAGE_TIER_LEVEL'
else:
target_value = iops
target_item_keyname = 'REPLICATION_FOR_IOPSBASED_PERFORMANCE'
target_restriction_type = 'IOPS'
for item in package['items']:
if item['keyName'] != target_item_keyname:
continue
price_id = _find_price_id(
item['prices'],
'performance_storage_replication',
target_restriction_type,
target_value
)
if price_id:
return price_id
raise ValueError("Could not find price for replicant volume") | [
"def",
"find_saas_replication_price",
"(",
"package",
",",
"tier",
"=",
"None",
",",
"iops",
"=",
"None",
")",
":",
"if",
"tier",
"is",
"not",
"None",
":",
"target_value",
"=",
"ENDURANCE_TIERS",
".",
"get",
"(",
"tier",
")",
"target_item_keyname",
"=",
"'REPLICATION_FOR_TIERBASED_PERFORMANCE'",
"target_restriction_type",
"=",
"'STORAGE_TIER_LEVEL'",
"else",
":",
"target_value",
"=",
"iops",
"target_item_keyname",
"=",
"'REPLICATION_FOR_IOPSBASED_PERFORMANCE'",
"target_restriction_type",
"=",
"'IOPS'",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"item",
"[",
"'keyName'",
"]",
"!=",
"target_item_keyname",
":",
"continue",
"price_id",
"=",
"_find_price_id",
"(",
"item",
"[",
"'prices'",
"]",
",",
"'performance_storage_replication'",
",",
"target_restriction_type",
",",
"target_value",
")",
"if",
"price_id",
":",
"return",
"price_id",
"raise",
"ValueError",
"(",
"\"Could not find price for replicant volume\"",
")"
]
| Find the price in the given package for the desired replicant volume
:param package: The product package of the endurance storage type
:param tier: The tier of the primary storage volume
:param iops: The IOPS of the primary storage volume
:return: Returns the replication price, or an error if not found | [
"Find",
"the",
"price",
"in",
"the",
"given",
"package",
"for",
"the",
"desired",
"replicant",
"volume"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L376-L406 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | find_snapshot_schedule_id | def find_snapshot_schedule_id(volume, snapshot_schedule_keyname):
"""Find the snapshot schedule ID for the given volume and keyname
:param volume: The volume for which the snapshot ID is desired
:param snapshot_schedule_keyname: The keyname of the snapshot schedule
:return: Returns an int value indicating the volume's snapshot schedule ID
"""
for schedule in volume['schedules']:
if 'type' in schedule and 'keyname' in schedule['type']:
if schedule['type']['keyname'] == snapshot_schedule_keyname:
return schedule['id']
raise ValueError("The given snapshot schedule ID was not found for "
"the given storage volume") | python | def find_snapshot_schedule_id(volume, snapshot_schedule_keyname):
for schedule in volume['schedules']:
if 'type' in schedule and 'keyname' in schedule['type']:
if schedule['type']['keyname'] == snapshot_schedule_keyname:
return schedule['id']
raise ValueError("The given snapshot schedule ID was not found for "
"the given storage volume") | [
"def",
"find_snapshot_schedule_id",
"(",
"volume",
",",
"snapshot_schedule_keyname",
")",
":",
"for",
"schedule",
"in",
"volume",
"[",
"'schedules'",
"]",
":",
"if",
"'type'",
"in",
"schedule",
"and",
"'keyname'",
"in",
"schedule",
"[",
"'type'",
"]",
":",
"if",
"schedule",
"[",
"'type'",
"]",
"[",
"'keyname'",
"]",
"==",
"snapshot_schedule_keyname",
":",
"return",
"schedule",
"[",
"'id'",
"]",
"raise",
"ValueError",
"(",
"\"The given snapshot schedule ID was not found for \"",
"\"the given storage volume\"",
")"
]
| Find the snapshot schedule ID for the given volume and keyname
:param volume: The volume for which the snapshot ID is desired
:param snapshot_schedule_keyname: The keyname of the snapshot schedule
:return: Returns an int value indicating the volume's snapshot schedule ID | [
"Find",
"the",
"snapshot",
"schedule",
"ID",
"for",
"the",
"given",
"volume",
"and",
"keyname"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L409-L422 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | prepare_snapshot_order_object | def prepare_snapshot_order_object(manager, volume, capacity, tier, upgrade):
"""Prepare the snapshot space order object for the placeOrder() method
:param manager: The File or Block manager calling this function
:param integer volume: The volume for which snapshot space is ordered
:param integer capacity: The snapshot space size to order, in GB
:param float tier: The tier level of the volume, in IOPS per GB (optional)
:param boolean upgrade: Flag to indicate if this order is an upgrade
:return: Returns the order object for the
Product_Order service's placeOrder() method
"""
# Ensure the storage volume has not been cancelled
if 'billingItem' not in volume:
raise exceptions.SoftLayerError(
'This volume has been cancelled; unable to order snapshot space')
# Determine and validate the storage volume's billing item category
billing_item_category_code = volume['billingItem']['categoryCode']
if billing_item_category_code == 'storage_as_a_service':
order_type_is_saas = True
elif billing_item_category_code == 'storage_service_enterprise':
order_type_is_saas = False
else:
raise exceptions.SoftLayerError(
"Snapshot space cannot be ordered for a primary volume with a "
"billing item category code of '%s'" % billing_item_category_code)
# Use the volume's billing item category code to get the product package
package = get_package(manager, billing_item_category_code)
# Find prices based on the volume's type and billing item category
if order_type_is_saas: # 'storage_as_a_service' package
volume_storage_type = volume['storageType']['keyName']
if 'ENDURANCE' in volume_storage_type:
if tier is None:
tier = find_endurance_tier_iops_per_gb(volume)
prices = [find_saas_snapshot_space_price(
package, capacity, tier=tier)]
elif 'PERFORMANCE' in volume_storage_type:
if not _staas_version_is_v2_or_above(volume):
raise exceptions.SoftLayerError(
"Snapshot space cannot be ordered for this performance "
"volume since it does not support Encryption at Rest.")
iops = int(volume['provisionedIops'])
prices = [find_saas_snapshot_space_price(
package, capacity, iops=iops)]
else:
raise exceptions.SoftLayerError(
"Storage volume does not have a valid storage type "
"(with an appropriate keyName to indicate the "
"volume is a PERFORMANCE or an ENDURANCE volume)")
else: # 'storage_service_enterprise' package
if tier is None:
tier = find_endurance_tier_iops_per_gb(volume)
prices = [find_ent_space_price(package, 'snapshot', capacity, tier)]
# Currently, these types are valid for snapshot space orders, whether
# the base volume's order container was Enterprise or AsAService
if upgrade:
complex_type = 'SoftLayer_Container_Product_Order_'\
'Network_Storage_Enterprise_SnapshotSpace_Upgrade'
else:
complex_type = 'SoftLayer_Container_Product_Order_'\
'Network_Storage_Enterprise_SnapshotSpace'
# Determine if hourly billing should be used
hourly_billing_flag = utils.lookup(volume, 'billingItem', 'hourlyFlag')
if hourly_billing_flag is None:
hourly_billing_flag = False
# Build and return the order object
snapshot_space_order = {
'complexType': complex_type,
'packageId': package['id'],
'prices': prices,
'quantity': 1,
'location': volume['billingItem']['location']['id'],
'volumeId': volume['id'],
'useHourlyPricing': hourly_billing_flag
}
return snapshot_space_order | python | def prepare_snapshot_order_object(manager, volume, capacity, tier, upgrade):
if 'billingItem' not in volume:
raise exceptions.SoftLayerError(
'This volume has been cancelled; unable to order snapshot space')
billing_item_category_code = volume['billingItem']['categoryCode']
if billing_item_category_code == 'storage_as_a_service':
order_type_is_saas = True
elif billing_item_category_code == 'storage_service_enterprise':
order_type_is_saas = False
else:
raise exceptions.SoftLayerError(
"Snapshot space cannot be ordered for a primary volume with a "
"billing item category code of '%s'" % billing_item_category_code)
package = get_package(manager, billing_item_category_code)
if order_type_is_saas:
volume_storage_type = volume['storageType']['keyName']
if 'ENDURANCE' in volume_storage_type:
if tier is None:
tier = find_endurance_tier_iops_per_gb(volume)
prices = [find_saas_snapshot_space_price(
package, capacity, tier=tier)]
elif 'PERFORMANCE' in volume_storage_type:
if not _staas_version_is_v2_or_above(volume):
raise exceptions.SoftLayerError(
"Snapshot space cannot be ordered for this performance "
"volume since it does not support Encryption at Rest.")
iops = int(volume['provisionedIops'])
prices = [find_saas_snapshot_space_price(
package, capacity, iops=iops)]
else:
raise exceptions.SoftLayerError(
"Storage volume does not have a valid storage type "
"(with an appropriate keyName to indicate the "
"volume is a PERFORMANCE or an ENDURANCE volume)")
else:
if tier is None:
tier = find_endurance_tier_iops_per_gb(volume)
prices = [find_ent_space_price(package, 'snapshot', capacity, tier)]
if upgrade:
complex_type = 'SoftLayer_Container_Product_Order_'\
'Network_Storage_Enterprise_SnapshotSpace_Upgrade'
else:
complex_type = 'SoftLayer_Container_Product_Order_'\
'Network_Storage_Enterprise_SnapshotSpace'
hourly_billing_flag = utils.lookup(volume, 'billingItem', 'hourlyFlag')
if hourly_billing_flag is None:
hourly_billing_flag = False
snapshot_space_order = {
'complexType': complex_type,
'packageId': package['id'],
'prices': prices,
'quantity': 1,
'location': volume['billingItem']['location']['id'],
'volumeId': volume['id'],
'useHourlyPricing': hourly_billing_flag
}
return snapshot_space_order | [
"def",
"prepare_snapshot_order_object",
"(",
"manager",
",",
"volume",
",",
"capacity",
",",
"tier",
",",
"upgrade",
")",
":",
"# Ensure the storage volume has not been cancelled",
"if",
"'billingItem'",
"not",
"in",
"volume",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"'This volume has been cancelled; unable to order snapshot space'",
")",
"# Determine and validate the storage volume's billing item category",
"billing_item_category_code",
"=",
"volume",
"[",
"'billingItem'",
"]",
"[",
"'categoryCode'",
"]",
"if",
"billing_item_category_code",
"==",
"'storage_as_a_service'",
":",
"order_type_is_saas",
"=",
"True",
"elif",
"billing_item_category_code",
"==",
"'storage_service_enterprise'",
":",
"order_type_is_saas",
"=",
"False",
"else",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"Snapshot space cannot be ordered for a primary volume with a \"",
"\"billing item category code of '%s'\"",
"%",
"billing_item_category_code",
")",
"# Use the volume's billing item category code to get the product package",
"package",
"=",
"get_package",
"(",
"manager",
",",
"billing_item_category_code",
")",
"# Find prices based on the volume's type and billing item category",
"if",
"order_type_is_saas",
":",
"# 'storage_as_a_service' package",
"volume_storage_type",
"=",
"volume",
"[",
"'storageType'",
"]",
"[",
"'keyName'",
"]",
"if",
"'ENDURANCE'",
"in",
"volume_storage_type",
":",
"if",
"tier",
"is",
"None",
":",
"tier",
"=",
"find_endurance_tier_iops_per_gb",
"(",
"volume",
")",
"prices",
"=",
"[",
"find_saas_snapshot_space_price",
"(",
"package",
",",
"capacity",
",",
"tier",
"=",
"tier",
")",
"]",
"elif",
"'PERFORMANCE'",
"in",
"volume_storage_type",
":",
"if",
"not",
"_staas_version_is_v2_or_above",
"(",
"volume",
")",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"Snapshot space cannot be ordered for this performance \"",
"\"volume since it does not support Encryption at Rest.\"",
")",
"iops",
"=",
"int",
"(",
"volume",
"[",
"'provisionedIops'",
"]",
")",
"prices",
"=",
"[",
"find_saas_snapshot_space_price",
"(",
"package",
",",
"capacity",
",",
"iops",
"=",
"iops",
")",
"]",
"else",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"Storage volume does not have a valid storage type \"",
"\"(with an appropriate keyName to indicate the \"",
"\"volume is a PERFORMANCE or an ENDURANCE volume)\"",
")",
"else",
":",
"# 'storage_service_enterprise' package",
"if",
"tier",
"is",
"None",
":",
"tier",
"=",
"find_endurance_tier_iops_per_gb",
"(",
"volume",
")",
"prices",
"=",
"[",
"find_ent_space_price",
"(",
"package",
",",
"'snapshot'",
",",
"capacity",
",",
"tier",
")",
"]",
"# Currently, these types are valid for snapshot space orders, whether",
"# the base volume's order container was Enterprise or AsAService",
"if",
"upgrade",
":",
"complex_type",
"=",
"'SoftLayer_Container_Product_Order_'",
"'Network_Storage_Enterprise_SnapshotSpace_Upgrade'",
"else",
":",
"complex_type",
"=",
"'SoftLayer_Container_Product_Order_'",
"'Network_Storage_Enterprise_SnapshotSpace'",
"# Determine if hourly billing should be used",
"hourly_billing_flag",
"=",
"utils",
".",
"lookup",
"(",
"volume",
",",
"'billingItem'",
",",
"'hourlyFlag'",
")",
"if",
"hourly_billing_flag",
"is",
"None",
":",
"hourly_billing_flag",
"=",
"False",
"# Build and return the order object",
"snapshot_space_order",
"=",
"{",
"'complexType'",
":",
"complex_type",
",",
"'packageId'",
":",
"package",
"[",
"'id'",
"]",
",",
"'prices'",
":",
"prices",
",",
"'quantity'",
":",
"1",
",",
"'location'",
":",
"volume",
"[",
"'billingItem'",
"]",
"[",
"'location'",
"]",
"[",
"'id'",
"]",
",",
"'volumeId'",
":",
"volume",
"[",
"'id'",
"]",
",",
"'useHourlyPricing'",
":",
"hourly_billing_flag",
"}",
"return",
"snapshot_space_order"
]
| Prepare the snapshot space order object for the placeOrder() method
:param manager: The File or Block manager calling this function
:param integer volume: The volume for which snapshot space is ordered
:param integer capacity: The snapshot space size to order, in GB
:param float tier: The tier level of the volume, in IOPS per GB (optional)
:param boolean upgrade: Flag to indicate if this order is an upgrade
:return: Returns the order object for the
Product_Order service's placeOrder() method | [
"Prepare",
"the",
"snapshot",
"space",
"order",
"object",
"for",
"the",
"placeOrder",
"()",
"method"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L425-L506 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | prepare_volume_order_object | def prepare_volume_order_object(manager, storage_type, location, size,
iops, tier, snapshot_size, service_offering,
volume_type, hourly_billing_flag=False):
"""Prepare the order object which is submitted to the placeOrder() method
:param manager: The File or Block manager calling this function
:param storage_type: "performance" or "endurance"
:param location: Requested datacenter location name for the ordered volume
:param size: Desired size of the volume, in GB
:param iops: Number of IOPs for a "Performance" volume order
:param tier: Tier level to use for an "Endurance" volume order
:param snapshot_size: The size of snapshot space for the volume (optional)
:param service_offering: Requested offering package to use for the order
:param volume_type: The type of the volume to order ('file' or 'block')
:param hourly_billing_flag: Billing type, monthly (False) or hourly (True)
:return: Returns the order object for the
Product_Order service's placeOrder() method
"""
# Ensure the volume storage type is valid
if storage_type != 'performance' and storage_type != 'endurance':
raise exceptions.SoftLayerError(
"Volume storage type must be either performance or endurance")
# Find the ID for the requested location
try:
location_id = get_location_id(manager, location)
except ValueError:
raise exceptions.SoftLayerError(
"Invalid datacenter name specified. "
"Please provide the lower case short name (e.g.: dal09)")
# Determine the category code to use for the order (and product package)
order_type_is_saas, order_category_code = _get_order_type_and_category(
service_offering,
storage_type,
volume_type
)
# Get the product package for the given category code
package = get_package(manager, order_category_code)
# Based on the storage type and product package, build up the complex type
# and array of price codes to include in the order object
base_type_name = 'SoftLayer_Container_Product_Order_Network_'
if order_type_is_saas:
complex_type = base_type_name + 'Storage_AsAService'
if storage_type == 'performance':
prices = [
find_price_by_category(package, order_category_code),
find_price_by_category(package, 'storage_' + volume_type),
find_saas_perform_space_price(package, size),
find_saas_perform_iops_price(package, size, iops)
]
if snapshot_size is not None:
prices.append(find_saas_snapshot_space_price(
package, snapshot_size, iops=iops))
else: # storage_type == 'endurance'
prices = [
find_price_by_category(package, order_category_code),
find_price_by_category(package, 'storage_' + volume_type),
find_saas_endurance_space_price(package, size, tier),
find_saas_endurance_tier_price(package, tier)
]
if snapshot_size is not None:
prices.append(find_saas_snapshot_space_price(
package, snapshot_size, tier=tier))
else: # offering package is enterprise or performance
if storage_type == 'performance':
if volume_type == 'block':
complex_type = base_type_name + 'PerformanceStorage_Iscsi'
else:
complex_type = base_type_name + 'PerformanceStorage_Nfs'
prices = [
find_price_by_category(package, order_category_code),
find_perf_space_price(package, size),
find_perf_iops_price(package, size, iops),
]
else: # storage_type == 'endurance'
complex_type = base_type_name + 'Storage_Enterprise'
prices = [
find_price_by_category(package, order_category_code),
find_price_by_category(package, 'storage_' + volume_type),
find_ent_space_price(package, 'endurance', size, tier),
find_ent_endurance_tier_price(package, tier),
]
if snapshot_size is not None:
prices.append(find_ent_space_price(
package, 'snapshot', snapshot_size, tier))
# Build and return the order object
order = {
'complexType': complex_type,
'packageId': package['id'],
'prices': prices,
'quantity': 1,
'location': location_id,
'useHourlyPricing': hourly_billing_flag
}
if order_type_is_saas:
order['volumeSize'] = size
if storage_type == 'performance':
order['iops'] = iops
return order | python | def prepare_volume_order_object(manager, storage_type, location, size,
iops, tier, snapshot_size, service_offering,
volume_type, hourly_billing_flag=False):
if storage_type != 'performance' and storage_type != 'endurance':
raise exceptions.SoftLayerError(
"Volume storage type must be either performance or endurance")
try:
location_id = get_location_id(manager, location)
except ValueError:
raise exceptions.SoftLayerError(
"Invalid datacenter name specified. "
"Please provide the lower case short name (e.g.: dal09)")
order_type_is_saas, order_category_code = _get_order_type_and_category(
service_offering,
storage_type,
volume_type
)
package = get_package(manager, order_category_code)
base_type_name = 'SoftLayer_Container_Product_Order_Network_'
if order_type_is_saas:
complex_type = base_type_name + 'Storage_AsAService'
if storage_type == 'performance':
prices = [
find_price_by_category(package, order_category_code),
find_price_by_category(package, 'storage_' + volume_type),
find_saas_perform_space_price(package, size),
find_saas_perform_iops_price(package, size, iops)
]
if snapshot_size is not None:
prices.append(find_saas_snapshot_space_price(
package, snapshot_size, iops=iops))
else:
prices = [
find_price_by_category(package, order_category_code),
find_price_by_category(package, 'storage_' + volume_type),
find_saas_endurance_space_price(package, size, tier),
find_saas_endurance_tier_price(package, tier)
]
if snapshot_size is not None:
prices.append(find_saas_snapshot_space_price(
package, snapshot_size, tier=tier))
else:
if storage_type == 'performance':
if volume_type == 'block':
complex_type = base_type_name + 'PerformanceStorage_Iscsi'
else:
complex_type = base_type_name + 'PerformanceStorage_Nfs'
prices = [
find_price_by_category(package, order_category_code),
find_perf_space_price(package, size),
find_perf_iops_price(package, size, iops),
]
else:
complex_type = base_type_name + 'Storage_Enterprise'
prices = [
find_price_by_category(package, order_category_code),
find_price_by_category(package, 'storage_' + volume_type),
find_ent_space_price(package, 'endurance', size, tier),
find_ent_endurance_tier_price(package, tier),
]
if snapshot_size is not None:
prices.append(find_ent_space_price(
package, 'snapshot', snapshot_size, tier))
order = {
'complexType': complex_type,
'packageId': package['id'],
'prices': prices,
'quantity': 1,
'location': location_id,
'useHourlyPricing': hourly_billing_flag
}
if order_type_is_saas:
order['volumeSize'] = size
if storage_type == 'performance':
order['iops'] = iops
return order | [
"def",
"prepare_volume_order_object",
"(",
"manager",
",",
"storage_type",
",",
"location",
",",
"size",
",",
"iops",
",",
"tier",
",",
"snapshot_size",
",",
"service_offering",
",",
"volume_type",
",",
"hourly_billing_flag",
"=",
"False",
")",
":",
"# Ensure the volume storage type is valid",
"if",
"storage_type",
"!=",
"'performance'",
"and",
"storage_type",
"!=",
"'endurance'",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"Volume storage type must be either performance or endurance\"",
")",
"# Find the ID for the requested location",
"try",
":",
"location_id",
"=",
"get_location_id",
"(",
"manager",
",",
"location",
")",
"except",
"ValueError",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"Invalid datacenter name specified. \"",
"\"Please provide the lower case short name (e.g.: dal09)\"",
")",
"# Determine the category code to use for the order (and product package)",
"order_type_is_saas",
",",
"order_category_code",
"=",
"_get_order_type_and_category",
"(",
"service_offering",
",",
"storage_type",
",",
"volume_type",
")",
"# Get the product package for the given category code",
"package",
"=",
"get_package",
"(",
"manager",
",",
"order_category_code",
")",
"# Based on the storage type and product package, build up the complex type",
"# and array of price codes to include in the order object",
"base_type_name",
"=",
"'SoftLayer_Container_Product_Order_Network_'",
"if",
"order_type_is_saas",
":",
"complex_type",
"=",
"base_type_name",
"+",
"'Storage_AsAService'",
"if",
"storage_type",
"==",
"'performance'",
":",
"prices",
"=",
"[",
"find_price_by_category",
"(",
"package",
",",
"order_category_code",
")",
",",
"find_price_by_category",
"(",
"package",
",",
"'storage_'",
"+",
"volume_type",
")",
",",
"find_saas_perform_space_price",
"(",
"package",
",",
"size",
")",
",",
"find_saas_perform_iops_price",
"(",
"package",
",",
"size",
",",
"iops",
")",
"]",
"if",
"snapshot_size",
"is",
"not",
"None",
":",
"prices",
".",
"append",
"(",
"find_saas_snapshot_space_price",
"(",
"package",
",",
"snapshot_size",
",",
"iops",
"=",
"iops",
")",
")",
"else",
":",
"# storage_type == 'endurance'",
"prices",
"=",
"[",
"find_price_by_category",
"(",
"package",
",",
"order_category_code",
")",
",",
"find_price_by_category",
"(",
"package",
",",
"'storage_'",
"+",
"volume_type",
")",
",",
"find_saas_endurance_space_price",
"(",
"package",
",",
"size",
",",
"tier",
")",
",",
"find_saas_endurance_tier_price",
"(",
"package",
",",
"tier",
")",
"]",
"if",
"snapshot_size",
"is",
"not",
"None",
":",
"prices",
".",
"append",
"(",
"find_saas_snapshot_space_price",
"(",
"package",
",",
"snapshot_size",
",",
"tier",
"=",
"tier",
")",
")",
"else",
":",
"# offering package is enterprise or performance",
"if",
"storage_type",
"==",
"'performance'",
":",
"if",
"volume_type",
"==",
"'block'",
":",
"complex_type",
"=",
"base_type_name",
"+",
"'PerformanceStorage_Iscsi'",
"else",
":",
"complex_type",
"=",
"base_type_name",
"+",
"'PerformanceStorage_Nfs'",
"prices",
"=",
"[",
"find_price_by_category",
"(",
"package",
",",
"order_category_code",
")",
",",
"find_perf_space_price",
"(",
"package",
",",
"size",
")",
",",
"find_perf_iops_price",
"(",
"package",
",",
"size",
",",
"iops",
")",
",",
"]",
"else",
":",
"# storage_type == 'endurance'",
"complex_type",
"=",
"base_type_name",
"+",
"'Storage_Enterprise'",
"prices",
"=",
"[",
"find_price_by_category",
"(",
"package",
",",
"order_category_code",
")",
",",
"find_price_by_category",
"(",
"package",
",",
"'storage_'",
"+",
"volume_type",
")",
",",
"find_ent_space_price",
"(",
"package",
",",
"'endurance'",
",",
"size",
",",
"tier",
")",
",",
"find_ent_endurance_tier_price",
"(",
"package",
",",
"tier",
")",
",",
"]",
"if",
"snapshot_size",
"is",
"not",
"None",
":",
"prices",
".",
"append",
"(",
"find_ent_space_price",
"(",
"package",
",",
"'snapshot'",
",",
"snapshot_size",
",",
"tier",
")",
")",
"# Build and return the order object",
"order",
"=",
"{",
"'complexType'",
":",
"complex_type",
",",
"'packageId'",
":",
"package",
"[",
"'id'",
"]",
",",
"'prices'",
":",
"prices",
",",
"'quantity'",
":",
"1",
",",
"'location'",
":",
"location_id",
",",
"'useHourlyPricing'",
":",
"hourly_billing_flag",
"}",
"if",
"order_type_is_saas",
":",
"order",
"[",
"'volumeSize'",
"]",
"=",
"size",
"if",
"storage_type",
"==",
"'performance'",
":",
"order",
"[",
"'iops'",
"]",
"=",
"iops",
"return",
"order"
]
| Prepare the order object which is submitted to the placeOrder() method
:param manager: The File or Block manager calling this function
:param storage_type: "performance" or "endurance"
:param location: Requested datacenter location name for the ordered volume
:param size: Desired size of the volume, in GB
:param iops: Number of IOPs for a "Performance" volume order
:param tier: Tier level to use for an "Endurance" volume order
:param snapshot_size: The size of snapshot space for the volume (optional)
:param service_offering: Requested offering package to use for the order
:param volume_type: The type of the volume to order ('file' or 'block')
:param hourly_billing_flag: Billing type, monthly (False) or hourly (True)
:return: Returns the order object for the
Product_Order service's placeOrder() method | [
"Prepare",
"the",
"order",
"object",
"which",
"is",
"submitted",
"to",
"the",
"placeOrder",
"()",
"method"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L509-L613 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | prepare_replicant_order_object | def prepare_replicant_order_object(manager, snapshot_schedule, location,
tier, volume, volume_type):
"""Prepare the order object which is submitted to the placeOrder() method
:param manager: The File or Block manager calling this function
:param snapshot_schedule: The primary volume's snapshot
schedule to use for replication
:param location: The location for the ordered replicant volume
:param tier: The tier (IOPS per GB) of the primary volume
:param volume: The primary volume as a SoftLayer_Network_Storage object
:param volume_type: The type of the primary volume ('file' or 'block')
:return: Returns the order object for the
Product_Order service's placeOrder() method
"""
# Ensure the primary volume and snapshot space are not set for cancellation
if 'billingItem' not in volume\
or volume['billingItem']['cancellationDate'] != '':
raise exceptions.SoftLayerError(
'This volume is set for cancellation; '
'unable to order replicant volume')
for child in volume['billingItem']['activeChildren']:
if child['categoryCode'] == 'storage_snapshot_space'\
and child['cancellationDate'] != '':
raise exceptions.SoftLayerError(
'The snapshot space for this volume is set for '
'cancellation; unable to order replicant volume')
# Find the ID for the requested location
try:
location_id = get_location_id(manager, location)
except ValueError:
raise exceptions.SoftLayerError(
"Invalid datacenter name specified. "
"Please provide the lower case short name (e.g.: dal09)")
# Get sizes and properties needed for the order
volume_size = int(volume['capacityGb'])
billing_item_category_code = volume['billingItem']['categoryCode']
if billing_item_category_code == 'storage_as_a_service':
order_type_is_saas = True
elif billing_item_category_code == 'storage_service_enterprise':
order_type_is_saas = False
else:
raise exceptions.SoftLayerError(
"A replicant volume cannot be ordered for a primary volume with a "
"billing item category code of '%s'" % billing_item_category_code)
if 'snapshotCapacityGb' in volume:
snapshot_size = int(volume['snapshotCapacityGb'])
else:
raise exceptions.SoftLayerError(
"Snapshot capacity not found for the given primary volume")
snapshot_schedule_id = find_snapshot_schedule_id(
volume,
'SNAPSHOT_' + snapshot_schedule
)
# Use the volume's billing item category code to get the product package
package = get_package(manager, billing_item_category_code)
# Find prices based on the primary volume's type and billing item category
if order_type_is_saas: # 'storage_as_a_service' package
complex_type = 'SoftLayer_Container_Product_Order_'\
'Network_Storage_AsAService'
volume_storage_type = volume['storageType']['keyName']
if 'ENDURANCE' in volume_storage_type:
volume_is_performance = False
if tier is None:
tier = find_endurance_tier_iops_per_gb(volume)
prices = [
find_price_by_category(package, billing_item_category_code),
find_price_by_category(package, 'storage_' + volume_type),
find_saas_endurance_space_price(package, volume_size, tier),
find_saas_endurance_tier_price(package, tier),
find_saas_snapshot_space_price(
package, snapshot_size, tier=tier),
find_saas_replication_price(package, tier=tier)
]
elif 'PERFORMANCE' in volume_storage_type:
if not _staas_version_is_v2_or_above(volume):
raise exceptions.SoftLayerError(
"A replica volume cannot be ordered for this performance "
"volume since it does not support Encryption at Rest.")
volume_is_performance = True
iops = int(volume['provisionedIops'])
prices = [
find_price_by_category(package, billing_item_category_code),
find_price_by_category(package, 'storage_' + volume_type),
find_saas_perform_space_price(package, volume_size),
find_saas_perform_iops_price(package, volume_size, iops),
find_saas_snapshot_space_price(
package, snapshot_size, iops=iops),
find_saas_replication_price(package, iops=iops)
]
else:
raise exceptions.SoftLayerError(
"Storage volume does not have a valid storage type "
"(with an appropriate keyName to indicate the "
"volume is a PERFORMANCE or an ENDURANCE volume)")
else: # 'storage_service_enterprise' package
complex_type = 'SoftLayer_Container_Product_Order_'\
'Network_Storage_Enterprise'
volume_is_performance = False
if tier is None:
tier = find_endurance_tier_iops_per_gb(volume)
prices = [
find_price_by_category(package, billing_item_category_code),
find_price_by_category(package, 'storage_' + volume_type),
find_ent_space_price(package, 'endurance', volume_size, tier),
find_ent_endurance_tier_price(package, tier),
find_ent_space_price(package, 'snapshot', snapshot_size, tier),
find_ent_space_price(package, 'replication', volume_size, tier)
]
# Determine if hourly billing should be used
hourly_billing_flag = utils.lookup(volume, 'billingItem', 'hourlyFlag')
if hourly_billing_flag is None:
hourly_billing_flag = False
# Build and return the order object
replicant_order = {
'complexType': complex_type,
'packageId': package['id'],
'prices': prices,
'quantity': 1,
'location': location_id,
'originVolumeId': volume['id'],
'originVolumeScheduleId': snapshot_schedule_id,
'useHourlyPricing': hourly_billing_flag
}
if order_type_is_saas:
replicant_order['volumeSize'] = volume_size
if volume_is_performance:
replicant_order['iops'] = iops
return replicant_order | python | def prepare_replicant_order_object(manager, snapshot_schedule, location,
tier, volume, volume_type):
if 'billingItem' not in volume\
or volume['billingItem']['cancellationDate'] != '':
raise exceptions.SoftLayerError(
'This volume is set for cancellation; '
'unable to order replicant volume')
for child in volume['billingItem']['activeChildren']:
if child['categoryCode'] == 'storage_snapshot_space'\
and child['cancellationDate'] != '':
raise exceptions.SoftLayerError(
'The snapshot space for this volume is set for '
'cancellation; unable to order replicant volume')
try:
location_id = get_location_id(manager, location)
except ValueError:
raise exceptions.SoftLayerError(
"Invalid datacenter name specified. "
"Please provide the lower case short name (e.g.: dal09)")
volume_size = int(volume['capacityGb'])
billing_item_category_code = volume['billingItem']['categoryCode']
if billing_item_category_code == 'storage_as_a_service':
order_type_is_saas = True
elif billing_item_category_code == 'storage_service_enterprise':
order_type_is_saas = False
else:
raise exceptions.SoftLayerError(
"A replicant volume cannot be ordered for a primary volume with a "
"billing item category code of '%s'" % billing_item_category_code)
if 'snapshotCapacityGb' in volume:
snapshot_size = int(volume['snapshotCapacityGb'])
else:
raise exceptions.SoftLayerError(
"Snapshot capacity not found for the given primary volume")
snapshot_schedule_id = find_snapshot_schedule_id(
volume,
'SNAPSHOT_' + snapshot_schedule
)
package = get_package(manager, billing_item_category_code)
if order_type_is_saas:
complex_type = 'SoftLayer_Container_Product_Order_'\
'Network_Storage_AsAService'
volume_storage_type = volume['storageType']['keyName']
if 'ENDURANCE' in volume_storage_type:
volume_is_performance = False
if tier is None:
tier = find_endurance_tier_iops_per_gb(volume)
prices = [
find_price_by_category(package, billing_item_category_code),
find_price_by_category(package, 'storage_' + volume_type),
find_saas_endurance_space_price(package, volume_size, tier),
find_saas_endurance_tier_price(package, tier),
find_saas_snapshot_space_price(
package, snapshot_size, tier=tier),
find_saas_replication_price(package, tier=tier)
]
elif 'PERFORMANCE' in volume_storage_type:
if not _staas_version_is_v2_or_above(volume):
raise exceptions.SoftLayerError(
"A replica volume cannot be ordered for this performance "
"volume since it does not support Encryption at Rest.")
volume_is_performance = True
iops = int(volume['provisionedIops'])
prices = [
find_price_by_category(package, billing_item_category_code),
find_price_by_category(package, 'storage_' + volume_type),
find_saas_perform_space_price(package, volume_size),
find_saas_perform_iops_price(package, volume_size, iops),
find_saas_snapshot_space_price(
package, snapshot_size, iops=iops),
find_saas_replication_price(package, iops=iops)
]
else:
raise exceptions.SoftLayerError(
"Storage volume does not have a valid storage type "
"(with an appropriate keyName to indicate the "
"volume is a PERFORMANCE or an ENDURANCE volume)")
else:
complex_type = 'SoftLayer_Container_Product_Order_'\
'Network_Storage_Enterprise'
volume_is_performance = False
if tier is None:
tier = find_endurance_tier_iops_per_gb(volume)
prices = [
find_price_by_category(package, billing_item_category_code),
find_price_by_category(package, 'storage_' + volume_type),
find_ent_space_price(package, 'endurance', volume_size, tier),
find_ent_endurance_tier_price(package, tier),
find_ent_space_price(package, 'snapshot', snapshot_size, tier),
find_ent_space_price(package, 'replication', volume_size, tier)
]
hourly_billing_flag = utils.lookup(volume, 'billingItem', 'hourlyFlag')
if hourly_billing_flag is None:
hourly_billing_flag = False
replicant_order = {
'complexType': complex_type,
'packageId': package['id'],
'prices': prices,
'quantity': 1,
'location': location_id,
'originVolumeId': volume['id'],
'originVolumeScheduleId': snapshot_schedule_id,
'useHourlyPricing': hourly_billing_flag
}
if order_type_is_saas:
replicant_order['volumeSize'] = volume_size
if volume_is_performance:
replicant_order['iops'] = iops
return replicant_order | [
"def",
"prepare_replicant_order_object",
"(",
"manager",
",",
"snapshot_schedule",
",",
"location",
",",
"tier",
",",
"volume",
",",
"volume_type",
")",
":",
"# Ensure the primary volume and snapshot space are not set for cancellation",
"if",
"'billingItem'",
"not",
"in",
"volume",
"or",
"volume",
"[",
"'billingItem'",
"]",
"[",
"'cancellationDate'",
"]",
"!=",
"''",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"'This volume is set for cancellation; '",
"'unable to order replicant volume'",
")",
"for",
"child",
"in",
"volume",
"[",
"'billingItem'",
"]",
"[",
"'activeChildren'",
"]",
":",
"if",
"child",
"[",
"'categoryCode'",
"]",
"==",
"'storage_snapshot_space'",
"and",
"child",
"[",
"'cancellationDate'",
"]",
"!=",
"''",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"'The snapshot space for this volume is set for '",
"'cancellation; unable to order replicant volume'",
")",
"# Find the ID for the requested location",
"try",
":",
"location_id",
"=",
"get_location_id",
"(",
"manager",
",",
"location",
")",
"except",
"ValueError",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"Invalid datacenter name specified. \"",
"\"Please provide the lower case short name (e.g.: dal09)\"",
")",
"# Get sizes and properties needed for the order",
"volume_size",
"=",
"int",
"(",
"volume",
"[",
"'capacityGb'",
"]",
")",
"billing_item_category_code",
"=",
"volume",
"[",
"'billingItem'",
"]",
"[",
"'categoryCode'",
"]",
"if",
"billing_item_category_code",
"==",
"'storage_as_a_service'",
":",
"order_type_is_saas",
"=",
"True",
"elif",
"billing_item_category_code",
"==",
"'storage_service_enterprise'",
":",
"order_type_is_saas",
"=",
"False",
"else",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"A replicant volume cannot be ordered for a primary volume with a \"",
"\"billing item category code of '%s'\"",
"%",
"billing_item_category_code",
")",
"if",
"'snapshotCapacityGb'",
"in",
"volume",
":",
"snapshot_size",
"=",
"int",
"(",
"volume",
"[",
"'snapshotCapacityGb'",
"]",
")",
"else",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"Snapshot capacity not found for the given primary volume\"",
")",
"snapshot_schedule_id",
"=",
"find_snapshot_schedule_id",
"(",
"volume",
",",
"'SNAPSHOT_'",
"+",
"snapshot_schedule",
")",
"# Use the volume's billing item category code to get the product package",
"package",
"=",
"get_package",
"(",
"manager",
",",
"billing_item_category_code",
")",
"# Find prices based on the primary volume's type and billing item category",
"if",
"order_type_is_saas",
":",
"# 'storage_as_a_service' package",
"complex_type",
"=",
"'SoftLayer_Container_Product_Order_'",
"'Network_Storage_AsAService'",
"volume_storage_type",
"=",
"volume",
"[",
"'storageType'",
"]",
"[",
"'keyName'",
"]",
"if",
"'ENDURANCE'",
"in",
"volume_storage_type",
":",
"volume_is_performance",
"=",
"False",
"if",
"tier",
"is",
"None",
":",
"tier",
"=",
"find_endurance_tier_iops_per_gb",
"(",
"volume",
")",
"prices",
"=",
"[",
"find_price_by_category",
"(",
"package",
",",
"billing_item_category_code",
")",
",",
"find_price_by_category",
"(",
"package",
",",
"'storage_'",
"+",
"volume_type",
")",
",",
"find_saas_endurance_space_price",
"(",
"package",
",",
"volume_size",
",",
"tier",
")",
",",
"find_saas_endurance_tier_price",
"(",
"package",
",",
"tier",
")",
",",
"find_saas_snapshot_space_price",
"(",
"package",
",",
"snapshot_size",
",",
"tier",
"=",
"tier",
")",
",",
"find_saas_replication_price",
"(",
"package",
",",
"tier",
"=",
"tier",
")",
"]",
"elif",
"'PERFORMANCE'",
"in",
"volume_storage_type",
":",
"if",
"not",
"_staas_version_is_v2_or_above",
"(",
"volume",
")",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"A replica volume cannot be ordered for this performance \"",
"\"volume since it does not support Encryption at Rest.\"",
")",
"volume_is_performance",
"=",
"True",
"iops",
"=",
"int",
"(",
"volume",
"[",
"'provisionedIops'",
"]",
")",
"prices",
"=",
"[",
"find_price_by_category",
"(",
"package",
",",
"billing_item_category_code",
")",
",",
"find_price_by_category",
"(",
"package",
",",
"'storage_'",
"+",
"volume_type",
")",
",",
"find_saas_perform_space_price",
"(",
"package",
",",
"volume_size",
")",
",",
"find_saas_perform_iops_price",
"(",
"package",
",",
"volume_size",
",",
"iops",
")",
",",
"find_saas_snapshot_space_price",
"(",
"package",
",",
"snapshot_size",
",",
"iops",
"=",
"iops",
")",
",",
"find_saas_replication_price",
"(",
"package",
",",
"iops",
"=",
"iops",
")",
"]",
"else",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"Storage volume does not have a valid storage type \"",
"\"(with an appropriate keyName to indicate the \"",
"\"volume is a PERFORMANCE or an ENDURANCE volume)\"",
")",
"else",
":",
"# 'storage_service_enterprise' package",
"complex_type",
"=",
"'SoftLayer_Container_Product_Order_'",
"'Network_Storage_Enterprise'",
"volume_is_performance",
"=",
"False",
"if",
"tier",
"is",
"None",
":",
"tier",
"=",
"find_endurance_tier_iops_per_gb",
"(",
"volume",
")",
"prices",
"=",
"[",
"find_price_by_category",
"(",
"package",
",",
"billing_item_category_code",
")",
",",
"find_price_by_category",
"(",
"package",
",",
"'storage_'",
"+",
"volume_type",
")",
",",
"find_ent_space_price",
"(",
"package",
",",
"'endurance'",
",",
"volume_size",
",",
"tier",
")",
",",
"find_ent_endurance_tier_price",
"(",
"package",
",",
"tier",
")",
",",
"find_ent_space_price",
"(",
"package",
",",
"'snapshot'",
",",
"snapshot_size",
",",
"tier",
")",
",",
"find_ent_space_price",
"(",
"package",
",",
"'replication'",
",",
"volume_size",
",",
"tier",
")",
"]",
"# Determine if hourly billing should be used",
"hourly_billing_flag",
"=",
"utils",
".",
"lookup",
"(",
"volume",
",",
"'billingItem'",
",",
"'hourlyFlag'",
")",
"if",
"hourly_billing_flag",
"is",
"None",
":",
"hourly_billing_flag",
"=",
"False",
"# Build and return the order object",
"replicant_order",
"=",
"{",
"'complexType'",
":",
"complex_type",
",",
"'packageId'",
":",
"package",
"[",
"'id'",
"]",
",",
"'prices'",
":",
"prices",
",",
"'quantity'",
":",
"1",
",",
"'location'",
":",
"location_id",
",",
"'originVolumeId'",
":",
"volume",
"[",
"'id'",
"]",
",",
"'originVolumeScheduleId'",
":",
"snapshot_schedule_id",
",",
"'useHourlyPricing'",
":",
"hourly_billing_flag",
"}",
"if",
"order_type_is_saas",
":",
"replicant_order",
"[",
"'volumeSize'",
"]",
"=",
"volume_size",
"if",
"volume_is_performance",
":",
"replicant_order",
"[",
"'iops'",
"]",
"=",
"iops",
"return",
"replicant_order"
]
| Prepare the order object which is submitted to the placeOrder() method
:param manager: The File or Block manager calling this function
:param snapshot_schedule: The primary volume's snapshot
schedule to use for replication
:param location: The location for the ordered replicant volume
:param tier: The tier (IOPS per GB) of the primary volume
:param volume: The primary volume as a SoftLayer_Network_Storage object
:param volume_type: The type of the primary volume ('file' or 'block')
:return: Returns the order object for the
Product_Order service's placeOrder() method | [
"Prepare",
"the",
"order",
"object",
"which",
"is",
"submitted",
"to",
"the",
"placeOrder",
"()",
"method"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L647-L786 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | prepare_duplicate_order_object | def prepare_duplicate_order_object(manager, origin_volume, iops, tier,
duplicate_size, duplicate_snapshot_size,
volume_type, hourly_billing_flag=False):
"""Prepare the duplicate order to submit to SoftLayer_Product::placeOrder()
:param manager: The File or Block manager calling this function
:param origin_volume: The origin volume which is being duplicated
:param iops: The IOPS for the duplicate volume (performance)
:param tier: The tier level for the duplicate volume (endurance)
:param duplicate_size: The requested size for the duplicate volume
:param duplicate_snapshot_size: The size for the duplicate snapshot space
:param volume_type: The type of the origin volume ('file' or 'block')
:param hourly_billing_flag: Billing type, monthly (False) or hourly (True)
:return: Returns the order object to be passed to the
placeOrder() method of the Product_Order service
"""
# Verify that the origin volume has not been cancelled
if 'billingItem' not in origin_volume:
raise exceptions.SoftLayerError(
"The origin volume has been cancelled; "
"unable to order duplicate volume")
# Verify that the origin volume has snapshot space (needed for duplication)
if isinstance(utils.lookup(origin_volume, 'snapshotCapacityGb'), str):
origin_snapshot_size = int(origin_volume['snapshotCapacityGb'])
else:
raise exceptions.SoftLayerError(
"Snapshot space not found for the origin volume. "
"Origin snapshot space is needed for duplication.")
# Obtain the datacenter location ID for the duplicate
if isinstance(utils.lookup(origin_volume, 'billingItem',
'location', 'id'), int):
location_id = origin_volume['billingItem']['location']['id']
else:
raise exceptions.SoftLayerError(
"Cannot find origin volume's location")
# Ensure the origin volume is STaaS v2 or higher
# and supports Encryption at Rest
if not _staas_version_is_v2_or_above(origin_volume):
raise exceptions.SoftLayerError(
"This volume cannot be duplicated since it "
"does not support Encryption at Rest.")
# If no specific snapshot space was requested for the duplicate,
# use the origin snapshot space size
if duplicate_snapshot_size is None:
duplicate_snapshot_size = origin_snapshot_size
# Use the origin volume size if no size was specified for the duplicate
if duplicate_size is None:
duplicate_size = origin_volume['capacityGb']
# Get the appropriate package for the order
# ('storage_as_a_service' is currently used for duplicate volumes)
package = get_package(manager, 'storage_as_a_service')
# Determine the IOPS or tier level for the duplicate volume, along with
# the type and prices for the order
origin_storage_type = origin_volume['storageType']['keyName']
if 'PERFORMANCE' in origin_storage_type:
volume_is_performance = True
if iops is None:
iops = int(origin_volume.get('provisionedIops', 0))
if iops <= 0:
raise exceptions.SoftLayerError("Cannot find origin volume's provisioned IOPS")
# Set up the price array for the order
prices = [
find_price_by_category(package, 'storage_as_a_service'),
find_price_by_category(package, 'storage_' + volume_type),
find_saas_perform_space_price(package, duplicate_size),
find_saas_perform_iops_price(package, duplicate_size, iops),
]
# Add the price code for snapshot space as well, unless 0 GB was given
if duplicate_snapshot_size > 0:
prices.append(find_saas_snapshot_space_price(
package, duplicate_snapshot_size, iops=iops))
elif 'ENDURANCE' in origin_storage_type:
volume_is_performance = False
if tier is None:
tier = find_endurance_tier_iops_per_gb(origin_volume)
# Set up the price array for the order
prices = [
find_price_by_category(package, 'storage_as_a_service'),
find_price_by_category(package, 'storage_' + volume_type),
find_saas_endurance_space_price(package, duplicate_size, tier),
find_saas_endurance_tier_price(package, tier),
]
# Add the price code for snapshot space as well, unless 0 GB was given
if duplicate_snapshot_size > 0:
prices.append(find_saas_snapshot_space_price(
package, duplicate_snapshot_size, tier=tier))
else:
raise exceptions.SoftLayerError(
"Origin volume does not have a valid storage type "
"(with an appropriate keyName to indicate the "
"volume is a PERFORMANCE or an ENDURANCE volume)")
duplicate_order = {
'complexType': 'SoftLayer_Container_Product_Order_'
'Network_Storage_AsAService',
'packageId': package['id'],
'prices': prices,
'volumeSize': duplicate_size,
'quantity': 1,
'location': location_id,
'duplicateOriginVolumeId': origin_volume['id'],
'useHourlyPricing': hourly_billing_flag
}
if volume_is_performance:
duplicate_order['iops'] = iops
return duplicate_order | python | def prepare_duplicate_order_object(manager, origin_volume, iops, tier,
duplicate_size, duplicate_snapshot_size,
volume_type, hourly_billing_flag=False):
if 'billingItem' not in origin_volume:
raise exceptions.SoftLayerError(
"The origin volume has been cancelled; "
"unable to order duplicate volume")
if isinstance(utils.lookup(origin_volume, 'snapshotCapacityGb'), str):
origin_snapshot_size = int(origin_volume['snapshotCapacityGb'])
else:
raise exceptions.SoftLayerError(
"Snapshot space not found for the origin volume. "
"Origin snapshot space is needed for duplication.")
if isinstance(utils.lookup(origin_volume, 'billingItem',
'location', 'id'), int):
location_id = origin_volume['billingItem']['location']['id']
else:
raise exceptions.SoftLayerError(
"Cannot find origin volume's location")
if not _staas_version_is_v2_or_above(origin_volume):
raise exceptions.SoftLayerError(
"This volume cannot be duplicated since it "
"does not support Encryption at Rest.")
if duplicate_snapshot_size is None:
duplicate_snapshot_size = origin_snapshot_size
if duplicate_size is None:
duplicate_size = origin_volume['capacityGb']
package = get_package(manager, 'storage_as_a_service')
origin_storage_type = origin_volume['storageType']['keyName']
if 'PERFORMANCE' in origin_storage_type:
volume_is_performance = True
if iops is None:
iops = int(origin_volume.get('provisionedIops', 0))
if iops <= 0:
raise exceptions.SoftLayerError("Cannot find origin volume's provisioned IOPS")
prices = [
find_price_by_category(package, 'storage_as_a_service'),
find_price_by_category(package, 'storage_' + volume_type),
find_saas_perform_space_price(package, duplicate_size),
find_saas_perform_iops_price(package, duplicate_size, iops),
]
if duplicate_snapshot_size > 0:
prices.append(find_saas_snapshot_space_price(
package, duplicate_snapshot_size, iops=iops))
elif 'ENDURANCE' in origin_storage_type:
volume_is_performance = False
if tier is None:
tier = find_endurance_tier_iops_per_gb(origin_volume)
prices = [
find_price_by_category(package, 'storage_as_a_service'),
find_price_by_category(package, 'storage_' + volume_type),
find_saas_endurance_space_price(package, duplicate_size, tier),
find_saas_endurance_tier_price(package, tier),
]
if duplicate_snapshot_size > 0:
prices.append(find_saas_snapshot_space_price(
package, duplicate_snapshot_size, tier=tier))
else:
raise exceptions.SoftLayerError(
"Origin volume does not have a valid storage type "
"(with an appropriate keyName to indicate the "
"volume is a PERFORMANCE or an ENDURANCE volume)")
duplicate_order = {
'complexType': 'SoftLayer_Container_Product_Order_'
'Network_Storage_AsAService',
'packageId': package['id'],
'prices': prices,
'volumeSize': duplicate_size,
'quantity': 1,
'location': location_id,
'duplicateOriginVolumeId': origin_volume['id'],
'useHourlyPricing': hourly_billing_flag
}
if volume_is_performance:
duplicate_order['iops'] = iops
return duplicate_order | [
"def",
"prepare_duplicate_order_object",
"(",
"manager",
",",
"origin_volume",
",",
"iops",
",",
"tier",
",",
"duplicate_size",
",",
"duplicate_snapshot_size",
",",
"volume_type",
",",
"hourly_billing_flag",
"=",
"False",
")",
":",
"# Verify that the origin volume has not been cancelled",
"if",
"'billingItem'",
"not",
"in",
"origin_volume",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"The origin volume has been cancelled; \"",
"\"unable to order duplicate volume\"",
")",
"# Verify that the origin volume has snapshot space (needed for duplication)",
"if",
"isinstance",
"(",
"utils",
".",
"lookup",
"(",
"origin_volume",
",",
"'snapshotCapacityGb'",
")",
",",
"str",
")",
":",
"origin_snapshot_size",
"=",
"int",
"(",
"origin_volume",
"[",
"'snapshotCapacityGb'",
"]",
")",
"else",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"Snapshot space not found for the origin volume. \"",
"\"Origin snapshot space is needed for duplication.\"",
")",
"# Obtain the datacenter location ID for the duplicate",
"if",
"isinstance",
"(",
"utils",
".",
"lookup",
"(",
"origin_volume",
",",
"'billingItem'",
",",
"'location'",
",",
"'id'",
")",
",",
"int",
")",
":",
"location_id",
"=",
"origin_volume",
"[",
"'billingItem'",
"]",
"[",
"'location'",
"]",
"[",
"'id'",
"]",
"else",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"Cannot find origin volume's location\"",
")",
"# Ensure the origin volume is STaaS v2 or higher",
"# and supports Encryption at Rest",
"if",
"not",
"_staas_version_is_v2_or_above",
"(",
"origin_volume",
")",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"This volume cannot be duplicated since it \"",
"\"does not support Encryption at Rest.\"",
")",
"# If no specific snapshot space was requested for the duplicate,",
"# use the origin snapshot space size",
"if",
"duplicate_snapshot_size",
"is",
"None",
":",
"duplicate_snapshot_size",
"=",
"origin_snapshot_size",
"# Use the origin volume size if no size was specified for the duplicate",
"if",
"duplicate_size",
"is",
"None",
":",
"duplicate_size",
"=",
"origin_volume",
"[",
"'capacityGb'",
"]",
"# Get the appropriate package for the order",
"# ('storage_as_a_service' is currently used for duplicate volumes)",
"package",
"=",
"get_package",
"(",
"manager",
",",
"'storage_as_a_service'",
")",
"# Determine the IOPS or tier level for the duplicate volume, along with",
"# the type and prices for the order",
"origin_storage_type",
"=",
"origin_volume",
"[",
"'storageType'",
"]",
"[",
"'keyName'",
"]",
"if",
"'PERFORMANCE'",
"in",
"origin_storage_type",
":",
"volume_is_performance",
"=",
"True",
"if",
"iops",
"is",
"None",
":",
"iops",
"=",
"int",
"(",
"origin_volume",
".",
"get",
"(",
"'provisionedIops'",
",",
"0",
")",
")",
"if",
"iops",
"<=",
"0",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"Cannot find origin volume's provisioned IOPS\"",
")",
"# Set up the price array for the order",
"prices",
"=",
"[",
"find_price_by_category",
"(",
"package",
",",
"'storage_as_a_service'",
")",
",",
"find_price_by_category",
"(",
"package",
",",
"'storage_'",
"+",
"volume_type",
")",
",",
"find_saas_perform_space_price",
"(",
"package",
",",
"duplicate_size",
")",
",",
"find_saas_perform_iops_price",
"(",
"package",
",",
"duplicate_size",
",",
"iops",
")",
",",
"]",
"# Add the price code for snapshot space as well, unless 0 GB was given",
"if",
"duplicate_snapshot_size",
">",
"0",
":",
"prices",
".",
"append",
"(",
"find_saas_snapshot_space_price",
"(",
"package",
",",
"duplicate_snapshot_size",
",",
"iops",
"=",
"iops",
")",
")",
"elif",
"'ENDURANCE'",
"in",
"origin_storage_type",
":",
"volume_is_performance",
"=",
"False",
"if",
"tier",
"is",
"None",
":",
"tier",
"=",
"find_endurance_tier_iops_per_gb",
"(",
"origin_volume",
")",
"# Set up the price array for the order",
"prices",
"=",
"[",
"find_price_by_category",
"(",
"package",
",",
"'storage_as_a_service'",
")",
",",
"find_price_by_category",
"(",
"package",
",",
"'storage_'",
"+",
"volume_type",
")",
",",
"find_saas_endurance_space_price",
"(",
"package",
",",
"duplicate_size",
",",
"tier",
")",
",",
"find_saas_endurance_tier_price",
"(",
"package",
",",
"tier",
")",
",",
"]",
"# Add the price code for snapshot space as well, unless 0 GB was given",
"if",
"duplicate_snapshot_size",
">",
"0",
":",
"prices",
".",
"append",
"(",
"find_saas_snapshot_space_price",
"(",
"package",
",",
"duplicate_snapshot_size",
",",
"tier",
"=",
"tier",
")",
")",
"else",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"Origin volume does not have a valid storage type \"",
"\"(with an appropriate keyName to indicate the \"",
"\"volume is a PERFORMANCE or an ENDURANCE volume)\"",
")",
"duplicate_order",
"=",
"{",
"'complexType'",
":",
"'SoftLayer_Container_Product_Order_'",
"'Network_Storage_AsAService'",
",",
"'packageId'",
":",
"package",
"[",
"'id'",
"]",
",",
"'prices'",
":",
"prices",
",",
"'volumeSize'",
":",
"duplicate_size",
",",
"'quantity'",
":",
"1",
",",
"'location'",
":",
"location_id",
",",
"'duplicateOriginVolumeId'",
":",
"origin_volume",
"[",
"'id'",
"]",
",",
"'useHourlyPricing'",
":",
"hourly_billing_flag",
"}",
"if",
"volume_is_performance",
":",
"duplicate_order",
"[",
"'iops'",
"]",
"=",
"iops",
"return",
"duplicate_order"
]
| Prepare the duplicate order to submit to SoftLayer_Product::placeOrder()
:param manager: The File or Block manager calling this function
:param origin_volume: The origin volume which is being duplicated
:param iops: The IOPS for the duplicate volume (performance)
:param tier: The tier level for the duplicate volume (endurance)
:param duplicate_size: The requested size for the duplicate volume
:param duplicate_snapshot_size: The size for the duplicate snapshot space
:param volume_type: The type of the origin volume ('file' or 'block')
:param hourly_billing_flag: Billing type, monthly (False) or hourly (True)
:return: Returns the order object to be passed to the
placeOrder() method of the Product_Order service | [
"Prepare",
"the",
"duplicate",
"order",
"to",
"submit",
"to",
"SoftLayer_Product",
"::",
"placeOrder",
"()"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L789-L906 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | prepare_modify_order_object | def prepare_modify_order_object(manager, volume, new_iops, new_tier, new_size):
"""Prepare the modification order to submit to SoftLayer_Product::placeOrder()
:param manager: The File or Block manager calling this function
:param volume: The volume which is being modified
:param new_iops: The new IOPS for the volume (performance)
:param new_tier: The new tier level for the volume (endurance)
:param new_size: The requested new size for the volume
:return: Returns the order object to be passed to the placeOrder() method of the Product_Order service
"""
# Verify that the origin volume has not been cancelled
if 'billingItem' not in volume:
raise exceptions.SoftLayerError("The volume has been cancelled; unable to modify volume.")
# Ensure the origin volume is STaaS v2 or higher and supports Encryption at Rest
if not _staas_version_is_v2_or_above(volume):
raise exceptions.SoftLayerError("This volume cannot be modified since it does not support Encryption at Rest.")
# Get the appropriate package for the order ('storage_as_a_service' is currently used for modifying volumes)
package = get_package(manager, 'storage_as_a_service')
# Based on volume storage type, ensure at least one volume property is being modified,
# use current values if some are not specified, and lookup price codes for the order
volume_storage_type = volume['storageType']['keyName']
if 'PERFORMANCE' in volume_storage_type:
volume_is_performance = True
if new_size is None and new_iops is None:
raise exceptions.SoftLayerError("A size or IOPS value must be given to modify this performance volume.")
if new_size is None:
new_size = volume['capacityGb']
elif new_iops is None:
new_iops = int(volume.get('provisionedIops', 0))
if new_iops <= 0:
raise exceptions.SoftLayerError("Cannot find volume's provisioned IOPS.")
# Set up the prices array for the order
prices = [
find_price_by_category(package, 'storage_as_a_service'),
find_saas_perform_space_price(package, new_size),
find_saas_perform_iops_price(package, new_size, new_iops),
]
elif 'ENDURANCE' in volume_storage_type:
volume_is_performance = False
if new_size is None and new_tier is None:
raise exceptions.SoftLayerError("A size or tier value must be given to modify this endurance volume.")
if new_size is None:
new_size = volume['capacityGb']
elif new_tier is None:
new_tier = find_endurance_tier_iops_per_gb(volume)
# Set up the prices array for the order
prices = [
find_price_by_category(package, 'storage_as_a_service'),
find_saas_endurance_space_price(package, new_size, new_tier),
find_saas_endurance_tier_price(package, new_tier),
]
else:
raise exceptions.SoftLayerError("Volume does not have a valid storage type (with an appropriate "
"keyName to indicate the volume is a PERFORMANCE or an ENDURANCE volume).")
modify_order = {
'complexType': 'SoftLayer_Container_Product_Order_Network_Storage_AsAService_Upgrade',
'packageId': package['id'],
'prices': prices,
'volume': {'id': volume['id']},
'volumeSize': new_size
}
if volume_is_performance:
modify_order['iops'] = new_iops
return modify_order | python | def prepare_modify_order_object(manager, volume, new_iops, new_tier, new_size):
if 'billingItem' not in volume:
raise exceptions.SoftLayerError("The volume has been cancelled; unable to modify volume.")
if not _staas_version_is_v2_or_above(volume):
raise exceptions.SoftLayerError("This volume cannot be modified since it does not support Encryption at Rest.")
package = get_package(manager, 'storage_as_a_service')
volume_storage_type = volume['storageType']['keyName']
if 'PERFORMANCE' in volume_storage_type:
volume_is_performance = True
if new_size is None and new_iops is None:
raise exceptions.SoftLayerError("A size or IOPS value must be given to modify this performance volume.")
if new_size is None:
new_size = volume['capacityGb']
elif new_iops is None:
new_iops = int(volume.get('provisionedIops', 0))
if new_iops <= 0:
raise exceptions.SoftLayerError("Cannot find volume's provisioned IOPS.")
prices = [
find_price_by_category(package, 'storage_as_a_service'),
find_saas_perform_space_price(package, new_size),
find_saas_perform_iops_price(package, new_size, new_iops),
]
elif 'ENDURANCE' in volume_storage_type:
volume_is_performance = False
if new_size is None and new_tier is None:
raise exceptions.SoftLayerError("A size or tier value must be given to modify this endurance volume.")
if new_size is None:
new_size = volume['capacityGb']
elif new_tier is None:
new_tier = find_endurance_tier_iops_per_gb(volume)
prices = [
find_price_by_category(package, 'storage_as_a_service'),
find_saas_endurance_space_price(package, new_size, new_tier),
find_saas_endurance_tier_price(package, new_tier),
]
else:
raise exceptions.SoftLayerError("Volume does not have a valid storage type (with an appropriate "
"keyName to indicate the volume is a PERFORMANCE or an ENDURANCE volume).")
modify_order = {
'complexType': 'SoftLayer_Container_Product_Order_Network_Storage_AsAService_Upgrade',
'packageId': package['id'],
'prices': prices,
'volume': {'id': volume['id']},
'volumeSize': new_size
}
if volume_is_performance:
modify_order['iops'] = new_iops
return modify_order | [
"def",
"prepare_modify_order_object",
"(",
"manager",
",",
"volume",
",",
"new_iops",
",",
"new_tier",
",",
"new_size",
")",
":",
"# Verify that the origin volume has not been cancelled",
"if",
"'billingItem'",
"not",
"in",
"volume",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"The volume has been cancelled; unable to modify volume.\"",
")",
"# Ensure the origin volume is STaaS v2 or higher and supports Encryption at Rest",
"if",
"not",
"_staas_version_is_v2_or_above",
"(",
"volume",
")",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"This volume cannot be modified since it does not support Encryption at Rest.\"",
")",
"# Get the appropriate package for the order ('storage_as_a_service' is currently used for modifying volumes)",
"package",
"=",
"get_package",
"(",
"manager",
",",
"'storage_as_a_service'",
")",
"# Based on volume storage type, ensure at least one volume property is being modified,",
"# use current values if some are not specified, and lookup price codes for the order",
"volume_storage_type",
"=",
"volume",
"[",
"'storageType'",
"]",
"[",
"'keyName'",
"]",
"if",
"'PERFORMANCE'",
"in",
"volume_storage_type",
":",
"volume_is_performance",
"=",
"True",
"if",
"new_size",
"is",
"None",
"and",
"new_iops",
"is",
"None",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"A size or IOPS value must be given to modify this performance volume.\"",
")",
"if",
"new_size",
"is",
"None",
":",
"new_size",
"=",
"volume",
"[",
"'capacityGb'",
"]",
"elif",
"new_iops",
"is",
"None",
":",
"new_iops",
"=",
"int",
"(",
"volume",
".",
"get",
"(",
"'provisionedIops'",
",",
"0",
")",
")",
"if",
"new_iops",
"<=",
"0",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"Cannot find volume's provisioned IOPS.\"",
")",
"# Set up the prices array for the order",
"prices",
"=",
"[",
"find_price_by_category",
"(",
"package",
",",
"'storage_as_a_service'",
")",
",",
"find_saas_perform_space_price",
"(",
"package",
",",
"new_size",
")",
",",
"find_saas_perform_iops_price",
"(",
"package",
",",
"new_size",
",",
"new_iops",
")",
",",
"]",
"elif",
"'ENDURANCE'",
"in",
"volume_storage_type",
":",
"volume_is_performance",
"=",
"False",
"if",
"new_size",
"is",
"None",
"and",
"new_tier",
"is",
"None",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"A size or tier value must be given to modify this endurance volume.\"",
")",
"if",
"new_size",
"is",
"None",
":",
"new_size",
"=",
"volume",
"[",
"'capacityGb'",
"]",
"elif",
"new_tier",
"is",
"None",
":",
"new_tier",
"=",
"find_endurance_tier_iops_per_gb",
"(",
"volume",
")",
"# Set up the prices array for the order",
"prices",
"=",
"[",
"find_price_by_category",
"(",
"package",
",",
"'storage_as_a_service'",
")",
",",
"find_saas_endurance_space_price",
"(",
"package",
",",
"new_size",
",",
"new_tier",
")",
",",
"find_saas_endurance_tier_price",
"(",
"package",
",",
"new_tier",
")",
",",
"]",
"else",
":",
"raise",
"exceptions",
".",
"SoftLayerError",
"(",
"\"Volume does not have a valid storage type (with an appropriate \"",
"\"keyName to indicate the volume is a PERFORMANCE or an ENDURANCE volume).\"",
")",
"modify_order",
"=",
"{",
"'complexType'",
":",
"'SoftLayer_Container_Product_Order_Network_Storage_AsAService_Upgrade'",
",",
"'packageId'",
":",
"package",
"[",
"'id'",
"]",
",",
"'prices'",
":",
"prices",
",",
"'volume'",
":",
"{",
"'id'",
":",
"volume",
"[",
"'id'",
"]",
"}",
",",
"'volumeSize'",
":",
"new_size",
"}",
"if",
"volume_is_performance",
":",
"modify_order",
"[",
"'iops'",
"]",
"=",
"new_iops",
"return",
"modify_order"
]
| Prepare the modification order to submit to SoftLayer_Product::placeOrder()
:param manager: The File or Block manager calling this function
:param volume: The volume which is being modified
:param new_iops: The new IOPS for the volume (performance)
:param new_tier: The new tier level for the volume (endurance)
:param new_size: The requested new size for the volume
:return: Returns the order object to be passed to the placeOrder() method of the Product_Order service | [
"Prepare",
"the",
"modification",
"order",
"to",
"submit",
"to",
"SoftLayer_Product",
"::",
"placeOrder",
"()"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L909-L985 |
softlayer/softlayer-python | SoftLayer/CLI/block/snapshot/delete.py | cli | def cli(env, snapshot_id):
"""Deletes a snapshot on a given volume"""
block_manager = SoftLayer.BlockStorageManager(env.client)
deleted = block_manager.delete_snapshot(snapshot_id)
if deleted:
click.echo('Snapshot %s deleted' % snapshot_id) | python | def cli(env, snapshot_id):
block_manager = SoftLayer.BlockStorageManager(env.client)
deleted = block_manager.delete_snapshot(snapshot_id)
if deleted:
click.echo('Snapshot %s deleted' % snapshot_id) | [
"def",
"cli",
"(",
"env",
",",
"snapshot_id",
")",
":",
"block_manager",
"=",
"SoftLayer",
".",
"BlockStorageManager",
"(",
"env",
".",
"client",
")",
"deleted",
"=",
"block_manager",
".",
"delete_snapshot",
"(",
"snapshot_id",
")",
"if",
"deleted",
":",
"click",
".",
"echo",
"(",
"'Snapshot %s deleted'",
"%",
"snapshot_id",
")"
]
| Deletes a snapshot on a given volume | [
"Deletes",
"a",
"snapshot",
"on",
"a",
"given",
"volume"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/snapshot/delete.py#L12-L18 |
softlayer/softlayer-python | fabfile.py | release | def release(version, force=False):
"""Perform a release. Example:
$ fab release:3.0.0
"""
if version.startswith("v"):
abort("Version should not start with 'v'")
version_str = "v%s" % version
clean()
local("pip install wheel")
puts(" * Uploading to PyPI")
upload()
puts(" * Tagging Version %s" % version_str)
force_option = 'f' if force else ''
local("git tag -%sam \"%s\" %s" % (force_option, version_str, version_str))
puts(" * Pushing Tag to upstream")
local("git push upstream %s" % version_str) | python | def release(version, force=False):
if version.startswith("v"):
abort("Version should not start with 'v'")
version_str = "v%s" % version
clean()
local("pip install wheel")
puts(" * Uploading to PyPI")
upload()
puts(" * Tagging Version %s" % version_str)
force_option = 'f' if force else ''
local("git tag -%sam \"%s\" %s" % (force_option, version_str, version_str))
puts(" * Pushing Tag to upstream")
local("git push upstream %s" % version_str) | [
"def",
"release",
"(",
"version",
",",
"force",
"=",
"False",
")",
":",
"if",
"version",
".",
"startswith",
"(",
"\"v\"",
")",
":",
"abort",
"(",
"\"Version should not start with 'v'\"",
")",
"version_str",
"=",
"\"v%s\"",
"%",
"version",
"clean",
"(",
")",
"local",
"(",
"\"pip install wheel\"",
")",
"puts",
"(",
"\" * Uploading to PyPI\"",
")",
"upload",
"(",
")",
"puts",
"(",
"\" * Tagging Version %s\"",
"%",
"version_str",
")",
"force_option",
"=",
"'f'",
"if",
"force",
"else",
"''",
"local",
"(",
"\"git tag -%sam \\\"%s\\\" %s\"",
"%",
"(",
"force_option",
",",
"version_str",
",",
"version_str",
")",
")",
"puts",
"(",
"\" * Pushing Tag to upstream\"",
")",
"local",
"(",
"\"git push upstream %s\"",
"%",
"version_str",
")"
]
| Perform a release. Example:
$ fab release:3.0.0 | [
"Perform",
"a",
"release",
".",
"Example",
":"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/fabfile.py#L27-L49 |
softlayer/softlayer-python | SoftLayer/CLI/file/snapshot/cancel.py | cli | def cli(env, volume_id, reason, immediate):
"""Cancel existing snapshot space for a given volume."""
file_storage_manager = SoftLayer.FileStorageManager(env.client)
if not (env.skip_confirmations or formatting.no_going_back(volume_id)):
raise exceptions.CLIAbort('Aborted')
cancelled = file_storage_manager.cancel_snapshot_space(
volume_id, reason, immediate)
if cancelled:
if immediate:
click.echo('File volume with id %s has been marked'
' for immediate snapshot cancellation' % volume_id)
else:
click.echo('File volume with id %s has been marked'
' for snapshot cancellation' % volume_id)
else:
click.echo('Unable to cancel snapshot space for file volume %s'
% volume_id) | python | def cli(env, volume_id, reason, immediate):
file_storage_manager = SoftLayer.FileStorageManager(env.client)
if not (env.skip_confirmations or formatting.no_going_back(volume_id)):
raise exceptions.CLIAbort('Aborted')
cancelled = file_storage_manager.cancel_snapshot_space(
volume_id, reason, immediate)
if cancelled:
if immediate:
click.echo('File volume with id %s has been marked'
' for immediate snapshot cancellation' % volume_id)
else:
click.echo('File volume with id %s has been marked'
' for snapshot cancellation' % volume_id)
else:
click.echo('Unable to cancel snapshot space for file volume %s'
% volume_id) | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"reason",
",",
"immediate",
")",
":",
"file_storage_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"no_going_back",
"(",
"volume_id",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted'",
")",
"cancelled",
"=",
"file_storage_manager",
".",
"cancel_snapshot_space",
"(",
"volume_id",
",",
"reason",
",",
"immediate",
")",
"if",
"cancelled",
":",
"if",
"immediate",
":",
"click",
".",
"echo",
"(",
"'File volume with id %s has been marked'",
"' for immediate snapshot cancellation'",
"%",
"volume_id",
")",
"else",
":",
"click",
".",
"echo",
"(",
"'File volume with id %s has been marked'",
"' for snapshot cancellation'",
"%",
"volume_id",
")",
"else",
":",
"click",
".",
"echo",
"(",
"'Unable to cancel snapshot space for file volume %s'",
"%",
"volume_id",
")"
]
| Cancel existing snapshot space for a given volume. | [
"Cancel",
"existing",
"snapshot",
"space",
"for",
"a",
"given",
"volume",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/snapshot/cancel.py#L20-L40 |
softlayer/softlayer-python | SoftLayer/CLI/block/detail.py | cli | def cli(env, volume_id):
"""Display details for a specified volume."""
block_manager = SoftLayer.BlockStorageManager(env.client)
block_volume = block_manager.get_block_volume_details(volume_id)
block_volume = utils.NestedDict(block_volume)
table = formatting.KeyValueTable(['Name', 'Value'])
table.align['Name'] = 'r'
table.align['Value'] = 'l'
storage_type = block_volume['storageType']['keyName'].split('_').pop(0)
table.add_row(['ID', block_volume['id']])
table.add_row(['Username', block_volume['username']])
table.add_row(['Type', storage_type])
table.add_row(['Capacity (GB)', "%iGB" % block_volume['capacityGb']])
table.add_row(['LUN Id', "%s" % block_volume['lunId']])
if block_volume.get('provisionedIops'):
table.add_row(['IOPs', float(block_volume['provisionedIops'])])
if block_volume.get('storageTierLevel'):
table.add_row([
'Endurance Tier',
block_volume['storageTierLevel'],
])
table.add_row([
'Data Center',
block_volume['serviceResource']['datacenter']['name'],
])
table.add_row([
'Target IP',
block_volume['serviceResourceBackendIpAddress'],
])
if block_volume['snapshotCapacityGb']:
table.add_row([
'Snapshot Capacity (GB)',
block_volume['snapshotCapacityGb'],
])
if 'snapshotSizeBytes' in block_volume['parentVolume']:
table.add_row([
'Snapshot Used (Bytes)',
block_volume['parentVolume']['snapshotSizeBytes'],
])
table.add_row(['# of Active Transactions', "%i"
% block_volume['activeTransactionCount']])
if block_volume['activeTransactions']:
for trans in block_volume['activeTransactions']:
if 'transactionStatus' in trans and 'friendlyName' in trans['transactionStatus']:
table.add_row(['Ongoing Transaction', trans['transactionStatus']['friendlyName']])
table.add_row(['Replicant Count', "%u" % block_volume.get('replicationPartnerCount', 0)])
if block_volume['replicationPartnerCount'] > 0:
# This if/else temporarily handles a bug in which the SL API
# returns a string or object for 'replicationStatus'; it seems that
# the type is string for File volumes and object for Block volumes
if 'message' in block_volume['replicationStatus']:
table.add_row(['Replication Status', "%s"
% block_volume['replicationStatus']['message']])
else:
table.add_row(['Replication Status', "%s"
% block_volume['replicationStatus']])
replicant_list = []
for replicant in block_volume['replicationPartners']:
replicant_table = formatting.Table(['Replicant ID',
replicant['id']])
replicant_table.add_row([
'Volume Name',
utils.lookup(replicant, 'username')])
replicant_table.add_row([
'Target IP',
utils.lookup(replicant, 'serviceResourceBackendIpAddress')])
replicant_table.add_row([
'Data Center',
utils.lookup(replicant,
'serviceResource', 'datacenter', 'name')])
replicant_table.add_row([
'Schedule',
utils.lookup(replicant,
'replicationSchedule', 'type', 'keyname')])
replicant_list.append(replicant_table)
table.add_row(['Replicant Volumes', replicant_list])
if block_volume.get('originalVolumeSize'):
original_volume_info = formatting.Table(['Property', 'Value'])
original_volume_info.add_row(['Original Volume Size', block_volume['originalVolumeSize']])
if block_volume.get('originalVolumeName'):
original_volume_info.add_row(['Original Volume Name', block_volume['originalVolumeName']])
if block_volume.get('originalSnapshotName'):
original_volume_info.add_row(['Original Snapshot Name', block_volume['originalSnapshotName']])
table.add_row(['Original Volume Properties', original_volume_info])
env.fout(table) | python | def cli(env, volume_id):
block_manager = SoftLayer.BlockStorageManager(env.client)
block_volume = block_manager.get_block_volume_details(volume_id)
block_volume = utils.NestedDict(block_volume)
table = formatting.KeyValueTable(['Name', 'Value'])
table.align['Name'] = 'r'
table.align['Value'] = 'l'
storage_type = block_volume['storageType']['keyName'].split('_').pop(0)
table.add_row(['ID', block_volume['id']])
table.add_row(['Username', block_volume['username']])
table.add_row(['Type', storage_type])
table.add_row(['Capacity (GB)', "%iGB" % block_volume['capacityGb']])
table.add_row(['LUN Id', "%s" % block_volume['lunId']])
if block_volume.get('provisionedIops'):
table.add_row(['IOPs', float(block_volume['provisionedIops'])])
if block_volume.get('storageTierLevel'):
table.add_row([
'Endurance Tier',
block_volume['storageTierLevel'],
])
table.add_row([
'Data Center',
block_volume['serviceResource']['datacenter']['name'],
])
table.add_row([
'Target IP',
block_volume['serviceResourceBackendIpAddress'],
])
if block_volume['snapshotCapacityGb']:
table.add_row([
'Snapshot Capacity (GB)',
block_volume['snapshotCapacityGb'],
])
if 'snapshotSizeBytes' in block_volume['parentVolume']:
table.add_row([
'Snapshot Used (Bytes)',
block_volume['parentVolume']['snapshotSizeBytes'],
])
table.add_row(['
% block_volume['activeTransactionCount']])
if block_volume['activeTransactions']:
for trans in block_volume['activeTransactions']:
if 'transactionStatus' in trans and 'friendlyName' in trans['transactionStatus']:
table.add_row(['Ongoing Transaction', trans['transactionStatus']['friendlyName']])
table.add_row(['Replicant Count', "%u" % block_volume.get('replicationPartnerCount', 0)])
if block_volume['replicationPartnerCount'] > 0:
if 'message' in block_volume['replicationStatus']:
table.add_row(['Replication Status', "%s"
% block_volume['replicationStatus']['message']])
else:
table.add_row(['Replication Status', "%s"
% block_volume['replicationStatus']])
replicant_list = []
for replicant in block_volume['replicationPartners']:
replicant_table = formatting.Table(['Replicant ID',
replicant['id']])
replicant_table.add_row([
'Volume Name',
utils.lookup(replicant, 'username')])
replicant_table.add_row([
'Target IP',
utils.lookup(replicant, 'serviceResourceBackendIpAddress')])
replicant_table.add_row([
'Data Center',
utils.lookup(replicant,
'serviceResource', 'datacenter', 'name')])
replicant_table.add_row([
'Schedule',
utils.lookup(replicant,
'replicationSchedule', 'type', 'keyname')])
replicant_list.append(replicant_table)
table.add_row(['Replicant Volumes', replicant_list])
if block_volume.get('originalVolumeSize'):
original_volume_info = formatting.Table(['Property', 'Value'])
original_volume_info.add_row(['Original Volume Size', block_volume['originalVolumeSize']])
if block_volume.get('originalVolumeName'):
original_volume_info.add_row(['Original Volume Name', block_volume['originalVolumeName']])
if block_volume.get('originalSnapshotName'):
original_volume_info.add_row(['Original Snapshot Name', block_volume['originalSnapshotName']])
table.add_row(['Original Volume Properties', original_volume_info])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
")",
":",
"block_manager",
"=",
"SoftLayer",
".",
"BlockStorageManager",
"(",
"env",
".",
"client",
")",
"block_volume",
"=",
"block_manager",
".",
"get_block_volume_details",
"(",
"volume_id",
")",
"block_volume",
"=",
"utils",
".",
"NestedDict",
"(",
"block_volume",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'Name'",
",",
"'Value'",
"]",
")",
"table",
".",
"align",
"[",
"'Name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'Value'",
"]",
"=",
"'l'",
"storage_type",
"=",
"block_volume",
"[",
"'storageType'",
"]",
"[",
"'keyName'",
"]",
".",
"split",
"(",
"'_'",
")",
".",
"pop",
"(",
"0",
")",
"table",
".",
"add_row",
"(",
"[",
"'ID'",
",",
"block_volume",
"[",
"'id'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Username'",
",",
"block_volume",
"[",
"'username'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Type'",
",",
"storage_type",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Capacity (GB)'",
",",
"\"%iGB\"",
"%",
"block_volume",
"[",
"'capacityGb'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'LUN Id'",
",",
"\"%s\"",
"%",
"block_volume",
"[",
"'lunId'",
"]",
"]",
")",
"if",
"block_volume",
".",
"get",
"(",
"'provisionedIops'",
")",
":",
"table",
".",
"add_row",
"(",
"[",
"'IOPs'",
",",
"float",
"(",
"block_volume",
"[",
"'provisionedIops'",
"]",
")",
"]",
")",
"if",
"block_volume",
".",
"get",
"(",
"'storageTierLevel'",
")",
":",
"table",
".",
"add_row",
"(",
"[",
"'Endurance Tier'",
",",
"block_volume",
"[",
"'storageTierLevel'",
"]",
",",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Data Center'",
",",
"block_volume",
"[",
"'serviceResource'",
"]",
"[",
"'datacenter'",
"]",
"[",
"'name'",
"]",
",",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Target IP'",
",",
"block_volume",
"[",
"'serviceResourceBackendIpAddress'",
"]",
",",
"]",
")",
"if",
"block_volume",
"[",
"'snapshotCapacityGb'",
"]",
":",
"table",
".",
"add_row",
"(",
"[",
"'Snapshot Capacity (GB)'",
",",
"block_volume",
"[",
"'snapshotCapacityGb'",
"]",
",",
"]",
")",
"if",
"'snapshotSizeBytes'",
"in",
"block_volume",
"[",
"'parentVolume'",
"]",
":",
"table",
".",
"add_row",
"(",
"[",
"'Snapshot Used (Bytes)'",
",",
"block_volume",
"[",
"'parentVolume'",
"]",
"[",
"'snapshotSizeBytes'",
"]",
",",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'# of Active Transactions'",
",",
"\"%i\"",
"%",
"block_volume",
"[",
"'activeTransactionCount'",
"]",
"]",
")",
"if",
"block_volume",
"[",
"'activeTransactions'",
"]",
":",
"for",
"trans",
"in",
"block_volume",
"[",
"'activeTransactions'",
"]",
":",
"if",
"'transactionStatus'",
"in",
"trans",
"and",
"'friendlyName'",
"in",
"trans",
"[",
"'transactionStatus'",
"]",
":",
"table",
".",
"add_row",
"(",
"[",
"'Ongoing Transaction'",
",",
"trans",
"[",
"'transactionStatus'",
"]",
"[",
"'friendlyName'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Replicant Count'",
",",
"\"%u\"",
"%",
"block_volume",
".",
"get",
"(",
"'replicationPartnerCount'",
",",
"0",
")",
"]",
")",
"if",
"block_volume",
"[",
"'replicationPartnerCount'",
"]",
">",
"0",
":",
"# This if/else temporarily handles a bug in which the SL API",
"# returns a string or object for 'replicationStatus'; it seems that",
"# the type is string for File volumes and object for Block volumes",
"if",
"'message'",
"in",
"block_volume",
"[",
"'replicationStatus'",
"]",
":",
"table",
".",
"add_row",
"(",
"[",
"'Replication Status'",
",",
"\"%s\"",
"%",
"block_volume",
"[",
"'replicationStatus'",
"]",
"[",
"'message'",
"]",
"]",
")",
"else",
":",
"table",
".",
"add_row",
"(",
"[",
"'Replication Status'",
",",
"\"%s\"",
"%",
"block_volume",
"[",
"'replicationStatus'",
"]",
"]",
")",
"replicant_list",
"=",
"[",
"]",
"for",
"replicant",
"in",
"block_volume",
"[",
"'replicationPartners'",
"]",
":",
"replicant_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Replicant ID'",
",",
"replicant",
"[",
"'id'",
"]",
"]",
")",
"replicant_table",
".",
"add_row",
"(",
"[",
"'Volume Name'",
",",
"utils",
".",
"lookup",
"(",
"replicant",
",",
"'username'",
")",
"]",
")",
"replicant_table",
".",
"add_row",
"(",
"[",
"'Target IP'",
",",
"utils",
".",
"lookup",
"(",
"replicant",
",",
"'serviceResourceBackendIpAddress'",
")",
"]",
")",
"replicant_table",
".",
"add_row",
"(",
"[",
"'Data Center'",
",",
"utils",
".",
"lookup",
"(",
"replicant",
",",
"'serviceResource'",
",",
"'datacenter'",
",",
"'name'",
")",
"]",
")",
"replicant_table",
".",
"add_row",
"(",
"[",
"'Schedule'",
",",
"utils",
".",
"lookup",
"(",
"replicant",
",",
"'replicationSchedule'",
",",
"'type'",
",",
"'keyname'",
")",
"]",
")",
"replicant_list",
".",
"append",
"(",
"replicant_table",
")",
"table",
".",
"add_row",
"(",
"[",
"'Replicant Volumes'",
",",
"replicant_list",
"]",
")",
"if",
"block_volume",
".",
"get",
"(",
"'originalVolumeSize'",
")",
":",
"original_volume_info",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Property'",
",",
"'Value'",
"]",
")",
"original_volume_info",
".",
"add_row",
"(",
"[",
"'Original Volume Size'",
",",
"block_volume",
"[",
"'originalVolumeSize'",
"]",
"]",
")",
"if",
"block_volume",
".",
"get",
"(",
"'originalVolumeName'",
")",
":",
"original_volume_info",
".",
"add_row",
"(",
"[",
"'Original Volume Name'",
",",
"block_volume",
"[",
"'originalVolumeName'",
"]",
"]",
")",
"if",
"block_volume",
".",
"get",
"(",
"'originalSnapshotName'",
")",
":",
"original_volume_info",
".",
"add_row",
"(",
"[",
"'Original Snapshot Name'",
",",
"block_volume",
"[",
"'originalSnapshotName'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Original Volume Properties'",
",",
"original_volume_info",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Display details for a specified volume. | [
"Display",
"details",
"for",
"a",
"specified",
"volume",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/detail.py#L14-L111 |
softlayer/softlayer-python | SoftLayer/CLI/securitygroup/event_log.py | get_by_request_id | def get_by_request_id(env, request_id):
"""Search for event logs by request id"""
mgr = SoftLayer.NetworkManager(env.client)
logs = mgr.get_event_logs_by_request_id(request_id)
table = formatting.Table(COLUMNS)
table.align['metadata'] = "l"
for log in logs:
metadata = json.dumps(json.loads(log['metaData']), indent=4, sort_keys=True)
table.add_row([log['eventName'], log['label'], log['eventCreateDate'], metadata])
env.fout(table) | python | def get_by_request_id(env, request_id):
mgr = SoftLayer.NetworkManager(env.client)
logs = mgr.get_event_logs_by_request_id(request_id)
table = formatting.Table(COLUMNS)
table.align['metadata'] = "l"
for log in logs:
metadata = json.dumps(json.loads(log['metaData']), indent=4, sort_keys=True)
table.add_row([log['eventName'], log['label'], log['eventCreateDate'], metadata])
env.fout(table) | [
"def",
"get_by_request_id",
"(",
"env",
",",
"request_id",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"logs",
"=",
"mgr",
".",
"get_event_logs_by_request_id",
"(",
"request_id",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"COLUMNS",
")",
"table",
".",
"align",
"[",
"'metadata'",
"]",
"=",
"\"l\"",
"for",
"log",
"in",
"logs",
":",
"metadata",
"=",
"json",
".",
"dumps",
"(",
"json",
".",
"loads",
"(",
"log",
"[",
"'metaData'",
"]",
")",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")",
"table",
".",
"add_row",
"(",
"[",
"log",
"[",
"'eventName'",
"]",
",",
"log",
"[",
"'label'",
"]",
",",
"log",
"[",
"'eventCreateDate'",
"]",
",",
"metadata",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Search for event logs by request id | [
"Search",
"for",
"event",
"logs",
"by",
"request",
"id"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/event_log.py#L18-L32 |
softlayer/softlayer-python | SoftLayer/CLI/ticket/create.py | cli | def cli(env, title, subject_id, body, hardware_identifier, virtual_identifier, priority):
"""Create a support ticket."""
ticket_mgr = SoftLayer.TicketManager(env.client)
if body is None:
body = click.edit('\n\n' + ticket.TEMPLATE_MSG)
created_ticket = ticket_mgr.create_ticket(
title=title,
body=body,
subject=subject_id,
priority=priority)
if hardware_identifier:
hardware_mgr = SoftLayer.HardwareManager(env.client)
hardware_id = helpers.resolve_id(hardware_mgr.resolve_ids, hardware_identifier, 'hardware')
ticket_mgr.attach_hardware(created_ticket['id'], hardware_id)
if virtual_identifier:
vs_mgr = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vs_mgr.resolve_ids, virtual_identifier, 'VS')
ticket_mgr.attach_virtual_server(created_ticket['id'], vs_id)
env.fout(ticket.get_ticket_results(ticket_mgr, created_ticket['id'])) | python | def cli(env, title, subject_id, body, hardware_identifier, virtual_identifier, priority):
ticket_mgr = SoftLayer.TicketManager(env.client)
if body is None:
body = click.edit('\n\n' + ticket.TEMPLATE_MSG)
created_ticket = ticket_mgr.create_ticket(
title=title,
body=body,
subject=subject_id,
priority=priority)
if hardware_identifier:
hardware_mgr = SoftLayer.HardwareManager(env.client)
hardware_id = helpers.resolve_id(hardware_mgr.resolve_ids, hardware_identifier, 'hardware')
ticket_mgr.attach_hardware(created_ticket['id'], hardware_id)
if virtual_identifier:
vs_mgr = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vs_mgr.resolve_ids, virtual_identifier, 'VS')
ticket_mgr.attach_virtual_server(created_ticket['id'], vs_id)
env.fout(ticket.get_ticket_results(ticket_mgr, created_ticket['id'])) | [
"def",
"cli",
"(",
"env",
",",
"title",
",",
"subject_id",
",",
"body",
",",
"hardware_identifier",
",",
"virtual_identifier",
",",
"priority",
")",
":",
"ticket_mgr",
"=",
"SoftLayer",
".",
"TicketManager",
"(",
"env",
".",
"client",
")",
"if",
"body",
"is",
"None",
":",
"body",
"=",
"click",
".",
"edit",
"(",
"'\\n\\n'",
"+",
"ticket",
".",
"TEMPLATE_MSG",
")",
"created_ticket",
"=",
"ticket_mgr",
".",
"create_ticket",
"(",
"title",
"=",
"title",
",",
"body",
"=",
"body",
",",
"subject",
"=",
"subject_id",
",",
"priority",
"=",
"priority",
")",
"if",
"hardware_identifier",
":",
"hardware_mgr",
"=",
"SoftLayer",
".",
"HardwareManager",
"(",
"env",
".",
"client",
")",
"hardware_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"hardware_mgr",
".",
"resolve_ids",
",",
"hardware_identifier",
",",
"'hardware'",
")",
"ticket_mgr",
".",
"attach_hardware",
"(",
"created_ticket",
"[",
"'id'",
"]",
",",
"hardware_id",
")",
"if",
"virtual_identifier",
":",
"vs_mgr",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vs_mgr",
".",
"resolve_ids",
",",
"virtual_identifier",
",",
"'VS'",
")",
"ticket_mgr",
".",
"attach_virtual_server",
"(",
"created_ticket",
"[",
"'id'",
"]",
",",
"vs_id",
")",
"env",
".",
"fout",
"(",
"ticket",
".",
"get_ticket_results",
"(",
"ticket_mgr",
",",
"created_ticket",
"[",
"'id'",
"]",
")",
")"
]
| Create a support ticket. | [
"Create",
"a",
"support",
"ticket",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ticket/create.py#L26-L48 |
softlayer/softlayer-python | SoftLayer/CLI/file/detail.py | cli | def cli(env, volume_id):
"""Display details for a specified volume."""
file_manager = SoftLayer.FileStorageManager(env.client)
file_volume = file_manager.get_file_volume_details(volume_id)
file_volume = utils.NestedDict(file_volume)
table = formatting.KeyValueTable(['Name', 'Value'])
table.align['Name'] = 'r'
table.align['Value'] = 'l'
storage_type = file_volume['storageType']['keyName'].split('_').pop(0)
table.add_row(['ID', file_volume['id']])
table.add_row(['Username', file_volume['username']])
table.add_row(['Type', storage_type])
table.add_row(['Capacity (GB)', "%iGB" % file_volume['capacityGb']])
used_space = int(file_volume['bytesUsed'])\
if file_volume['bytesUsed'] else 0
if used_space < (1 << 10):
table.add_row(['Used Space', "%dB" % used_space])
elif used_space < (1 << 20):
table.add_row(['Used Space', "%dKB" % (used_space / (1 << 10))])
elif used_space < (1 << 30):
table.add_row(['Used Space', "%dMB" % (used_space / (1 << 20))])
else:
table.add_row(['Used Space', "%dGB" % (used_space / (1 << 30))])
if file_volume.get('provisionedIops'):
table.add_row(['IOPs', float(file_volume['provisionedIops'])])
if file_volume.get('storageTierLevel'):
table.add_row([
'Endurance Tier',
file_volume['storageTierLevel'],
])
table.add_row([
'Data Center',
file_volume['serviceResource']['datacenter']['name'],
])
table.add_row([
'Target IP',
file_volume['serviceResourceBackendIpAddress'],
])
if file_volume['fileNetworkMountAddress']:
table.add_row([
'Mount Address',
file_volume['fileNetworkMountAddress'],
])
if file_volume['snapshotCapacityGb']:
table.add_row([
'Snapshot Capacity (GB)',
file_volume['snapshotCapacityGb'],
])
if 'snapshotSizeBytes' in file_volume['parentVolume']:
table.add_row([
'Snapshot Used (Bytes)',
file_volume['parentVolume']['snapshotSizeBytes'],
])
table.add_row(['# of Active Transactions', "%i"
% file_volume['activeTransactionCount']])
if file_volume['activeTransactions']:
for trans in file_volume['activeTransactions']:
if 'transactionStatus' in trans and 'friendlyName' in trans['transactionStatus']:
table.add_row(['Ongoing Transaction', trans['transactionStatus']['friendlyName']])
table.add_row(['Replicant Count', "%u" % file_volume.get('replicationPartnerCount', 0)])
if file_volume['replicationPartnerCount'] > 0:
# This if/else temporarily handles a bug in which the SL API
# returns a string or object for 'replicationStatus'; it seems that
# the type is string for File volumes and object for Block volumes
if 'message' in file_volume['replicationStatus']:
table.add_row(['Replication Status', "%s"
% file_volume['replicationStatus']['message']])
else:
table.add_row(['Replication Status', "%s"
% file_volume['replicationStatus']])
replicant_list = []
for replicant in file_volume['replicationPartners']:
replicant_table = formatting.Table(['Replicant ID',
replicant['id']])
replicant_table.add_row([
'Volume Name',
utils.lookup(replicant, 'username')])
replicant_table.add_row([
'Target IP',
utils.lookup(replicant, 'serviceResourceBackendIpAddress')])
replicant_table.add_row([
'Data Center',
utils.lookup(replicant,
'serviceResource', 'datacenter', 'name')])
replicant_table.add_row([
'Schedule',
utils.lookup(replicant,
'replicationSchedule', 'type', 'keyname')])
replicant_list.append(replicant_table)
table.add_row(['Replicant Volumes', replicant_list])
if file_volume.get('originalVolumeSize'):
original_volume_info = formatting.Table(['Property', 'Value'])
original_volume_info.add_row(['Original Volume Size', file_volume['originalVolumeSize']])
if file_volume.get('originalVolumeName'):
original_volume_info.add_row(['Original Volume Name', file_volume['originalVolumeName']])
if file_volume.get('originalSnapshotName'):
original_volume_info.add_row(['Original Snapshot Name', file_volume['originalSnapshotName']])
table.add_row(['Original Volume Properties', original_volume_info])
env.fout(table) | python | def cli(env, volume_id):
file_manager = SoftLayer.FileStorageManager(env.client)
file_volume = file_manager.get_file_volume_details(volume_id)
file_volume = utils.NestedDict(file_volume)
table = formatting.KeyValueTable(['Name', 'Value'])
table.align['Name'] = 'r'
table.align['Value'] = 'l'
storage_type = file_volume['storageType']['keyName'].split('_').pop(0)
table.add_row(['ID', file_volume['id']])
table.add_row(['Username', file_volume['username']])
table.add_row(['Type', storage_type])
table.add_row(['Capacity (GB)', "%iGB" % file_volume['capacityGb']])
used_space = int(file_volume['bytesUsed'])\
if file_volume['bytesUsed'] else 0
if used_space < (1 << 10):
table.add_row(['Used Space', "%dB" % used_space])
elif used_space < (1 << 20):
table.add_row(['Used Space', "%dKB" % (used_space / (1 << 10))])
elif used_space < (1 << 30):
table.add_row(['Used Space', "%dMB" % (used_space / (1 << 20))])
else:
table.add_row(['Used Space', "%dGB" % (used_space / (1 << 30))])
if file_volume.get('provisionedIops'):
table.add_row(['IOPs', float(file_volume['provisionedIops'])])
if file_volume.get('storageTierLevel'):
table.add_row([
'Endurance Tier',
file_volume['storageTierLevel'],
])
table.add_row([
'Data Center',
file_volume['serviceResource']['datacenter']['name'],
])
table.add_row([
'Target IP',
file_volume['serviceResourceBackendIpAddress'],
])
if file_volume['fileNetworkMountAddress']:
table.add_row([
'Mount Address',
file_volume['fileNetworkMountAddress'],
])
if file_volume['snapshotCapacityGb']:
table.add_row([
'Snapshot Capacity (GB)',
file_volume['snapshotCapacityGb'],
])
if 'snapshotSizeBytes' in file_volume['parentVolume']:
table.add_row([
'Snapshot Used (Bytes)',
file_volume['parentVolume']['snapshotSizeBytes'],
])
table.add_row(['
% file_volume['activeTransactionCount']])
if file_volume['activeTransactions']:
for trans in file_volume['activeTransactions']:
if 'transactionStatus' in trans and 'friendlyName' in trans['transactionStatus']:
table.add_row(['Ongoing Transaction', trans['transactionStatus']['friendlyName']])
table.add_row(['Replicant Count', "%u" % file_volume.get('replicationPartnerCount', 0)])
if file_volume['replicationPartnerCount'] > 0:
if 'message' in file_volume['replicationStatus']:
table.add_row(['Replication Status', "%s"
% file_volume['replicationStatus']['message']])
else:
table.add_row(['Replication Status', "%s"
% file_volume['replicationStatus']])
replicant_list = []
for replicant in file_volume['replicationPartners']:
replicant_table = formatting.Table(['Replicant ID',
replicant['id']])
replicant_table.add_row([
'Volume Name',
utils.lookup(replicant, 'username')])
replicant_table.add_row([
'Target IP',
utils.lookup(replicant, 'serviceResourceBackendIpAddress')])
replicant_table.add_row([
'Data Center',
utils.lookup(replicant,
'serviceResource', 'datacenter', 'name')])
replicant_table.add_row([
'Schedule',
utils.lookup(replicant,
'replicationSchedule', 'type', 'keyname')])
replicant_list.append(replicant_table)
table.add_row(['Replicant Volumes', replicant_list])
if file_volume.get('originalVolumeSize'):
original_volume_info = formatting.Table(['Property', 'Value'])
original_volume_info.add_row(['Original Volume Size', file_volume['originalVolumeSize']])
if file_volume.get('originalVolumeName'):
original_volume_info.add_row(['Original Volume Name', file_volume['originalVolumeName']])
if file_volume.get('originalSnapshotName'):
original_volume_info.add_row(['Original Snapshot Name', file_volume['originalSnapshotName']])
table.add_row(['Original Volume Properties', original_volume_info])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
")",
":",
"file_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"file_volume",
"=",
"file_manager",
".",
"get_file_volume_details",
"(",
"volume_id",
")",
"file_volume",
"=",
"utils",
".",
"NestedDict",
"(",
"file_volume",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'Name'",
",",
"'Value'",
"]",
")",
"table",
".",
"align",
"[",
"'Name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'Value'",
"]",
"=",
"'l'",
"storage_type",
"=",
"file_volume",
"[",
"'storageType'",
"]",
"[",
"'keyName'",
"]",
".",
"split",
"(",
"'_'",
")",
".",
"pop",
"(",
"0",
")",
"table",
".",
"add_row",
"(",
"[",
"'ID'",
",",
"file_volume",
"[",
"'id'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Username'",
",",
"file_volume",
"[",
"'username'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Type'",
",",
"storage_type",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Capacity (GB)'",
",",
"\"%iGB\"",
"%",
"file_volume",
"[",
"'capacityGb'",
"]",
"]",
")",
"used_space",
"=",
"int",
"(",
"file_volume",
"[",
"'bytesUsed'",
"]",
")",
"if",
"file_volume",
"[",
"'bytesUsed'",
"]",
"else",
"0",
"if",
"used_space",
"<",
"(",
"1",
"<<",
"10",
")",
":",
"table",
".",
"add_row",
"(",
"[",
"'Used Space'",
",",
"\"%dB\"",
"%",
"used_space",
"]",
")",
"elif",
"used_space",
"<",
"(",
"1",
"<<",
"20",
")",
":",
"table",
".",
"add_row",
"(",
"[",
"'Used Space'",
",",
"\"%dKB\"",
"%",
"(",
"used_space",
"/",
"(",
"1",
"<<",
"10",
")",
")",
"]",
")",
"elif",
"used_space",
"<",
"(",
"1",
"<<",
"30",
")",
":",
"table",
".",
"add_row",
"(",
"[",
"'Used Space'",
",",
"\"%dMB\"",
"%",
"(",
"used_space",
"/",
"(",
"1",
"<<",
"20",
")",
")",
"]",
")",
"else",
":",
"table",
".",
"add_row",
"(",
"[",
"'Used Space'",
",",
"\"%dGB\"",
"%",
"(",
"used_space",
"/",
"(",
"1",
"<<",
"30",
")",
")",
"]",
")",
"if",
"file_volume",
".",
"get",
"(",
"'provisionedIops'",
")",
":",
"table",
".",
"add_row",
"(",
"[",
"'IOPs'",
",",
"float",
"(",
"file_volume",
"[",
"'provisionedIops'",
"]",
")",
"]",
")",
"if",
"file_volume",
".",
"get",
"(",
"'storageTierLevel'",
")",
":",
"table",
".",
"add_row",
"(",
"[",
"'Endurance Tier'",
",",
"file_volume",
"[",
"'storageTierLevel'",
"]",
",",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Data Center'",
",",
"file_volume",
"[",
"'serviceResource'",
"]",
"[",
"'datacenter'",
"]",
"[",
"'name'",
"]",
",",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Target IP'",
",",
"file_volume",
"[",
"'serviceResourceBackendIpAddress'",
"]",
",",
"]",
")",
"if",
"file_volume",
"[",
"'fileNetworkMountAddress'",
"]",
":",
"table",
".",
"add_row",
"(",
"[",
"'Mount Address'",
",",
"file_volume",
"[",
"'fileNetworkMountAddress'",
"]",
",",
"]",
")",
"if",
"file_volume",
"[",
"'snapshotCapacityGb'",
"]",
":",
"table",
".",
"add_row",
"(",
"[",
"'Snapshot Capacity (GB)'",
",",
"file_volume",
"[",
"'snapshotCapacityGb'",
"]",
",",
"]",
")",
"if",
"'snapshotSizeBytes'",
"in",
"file_volume",
"[",
"'parentVolume'",
"]",
":",
"table",
".",
"add_row",
"(",
"[",
"'Snapshot Used (Bytes)'",
",",
"file_volume",
"[",
"'parentVolume'",
"]",
"[",
"'snapshotSizeBytes'",
"]",
",",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'# of Active Transactions'",
",",
"\"%i\"",
"%",
"file_volume",
"[",
"'activeTransactionCount'",
"]",
"]",
")",
"if",
"file_volume",
"[",
"'activeTransactions'",
"]",
":",
"for",
"trans",
"in",
"file_volume",
"[",
"'activeTransactions'",
"]",
":",
"if",
"'transactionStatus'",
"in",
"trans",
"and",
"'friendlyName'",
"in",
"trans",
"[",
"'transactionStatus'",
"]",
":",
"table",
".",
"add_row",
"(",
"[",
"'Ongoing Transaction'",
",",
"trans",
"[",
"'transactionStatus'",
"]",
"[",
"'friendlyName'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Replicant Count'",
",",
"\"%u\"",
"%",
"file_volume",
".",
"get",
"(",
"'replicationPartnerCount'",
",",
"0",
")",
"]",
")",
"if",
"file_volume",
"[",
"'replicationPartnerCount'",
"]",
">",
"0",
":",
"# This if/else temporarily handles a bug in which the SL API",
"# returns a string or object for 'replicationStatus'; it seems that",
"# the type is string for File volumes and object for Block volumes",
"if",
"'message'",
"in",
"file_volume",
"[",
"'replicationStatus'",
"]",
":",
"table",
".",
"add_row",
"(",
"[",
"'Replication Status'",
",",
"\"%s\"",
"%",
"file_volume",
"[",
"'replicationStatus'",
"]",
"[",
"'message'",
"]",
"]",
")",
"else",
":",
"table",
".",
"add_row",
"(",
"[",
"'Replication Status'",
",",
"\"%s\"",
"%",
"file_volume",
"[",
"'replicationStatus'",
"]",
"]",
")",
"replicant_list",
"=",
"[",
"]",
"for",
"replicant",
"in",
"file_volume",
"[",
"'replicationPartners'",
"]",
":",
"replicant_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Replicant ID'",
",",
"replicant",
"[",
"'id'",
"]",
"]",
")",
"replicant_table",
".",
"add_row",
"(",
"[",
"'Volume Name'",
",",
"utils",
".",
"lookup",
"(",
"replicant",
",",
"'username'",
")",
"]",
")",
"replicant_table",
".",
"add_row",
"(",
"[",
"'Target IP'",
",",
"utils",
".",
"lookup",
"(",
"replicant",
",",
"'serviceResourceBackendIpAddress'",
")",
"]",
")",
"replicant_table",
".",
"add_row",
"(",
"[",
"'Data Center'",
",",
"utils",
".",
"lookup",
"(",
"replicant",
",",
"'serviceResource'",
",",
"'datacenter'",
",",
"'name'",
")",
"]",
")",
"replicant_table",
".",
"add_row",
"(",
"[",
"'Schedule'",
",",
"utils",
".",
"lookup",
"(",
"replicant",
",",
"'replicationSchedule'",
",",
"'type'",
",",
"'keyname'",
")",
"]",
")",
"replicant_list",
".",
"append",
"(",
"replicant_table",
")",
"table",
".",
"add_row",
"(",
"[",
"'Replicant Volumes'",
",",
"replicant_list",
"]",
")",
"if",
"file_volume",
".",
"get",
"(",
"'originalVolumeSize'",
")",
":",
"original_volume_info",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Property'",
",",
"'Value'",
"]",
")",
"original_volume_info",
".",
"add_row",
"(",
"[",
"'Original Volume Size'",
",",
"file_volume",
"[",
"'originalVolumeSize'",
"]",
"]",
")",
"if",
"file_volume",
".",
"get",
"(",
"'originalVolumeName'",
")",
":",
"original_volume_info",
".",
"add_row",
"(",
"[",
"'Original Volume Name'",
",",
"file_volume",
"[",
"'originalVolumeName'",
"]",
"]",
")",
"if",
"file_volume",
".",
"get",
"(",
"'originalSnapshotName'",
")",
":",
"original_volume_info",
".",
"add_row",
"(",
"[",
"'Original Snapshot Name'",
",",
"file_volume",
"[",
"'originalSnapshotName'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Original Volume Properties'",
",",
"original_volume_info",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Display details for a specified volume. | [
"Display",
"details",
"for",
"a",
"specified",
"volume",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/detail.py#L14-L127 |
softlayer/softlayer-python | SoftLayer/CLI/file/replication/failback.py | cli | def cli(env, volume_id, replicant_id):
"""Failback a file volume from the given replicant volume."""
file_storage_manager = SoftLayer.FileStorageManager(env.client)
success = file_storage_manager.failback_from_replicant(
volume_id,
replicant_id
)
if success:
click.echo("Failback from replicant is now in progress.")
else:
click.echo("Failback operation could not be initiated.") | python | def cli(env, volume_id, replicant_id):
file_storage_manager = SoftLayer.FileStorageManager(env.client)
success = file_storage_manager.failback_from_replicant(
volume_id,
replicant_id
)
if success:
click.echo("Failback from replicant is now in progress.")
else:
click.echo("Failback operation could not be initiated.") | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"replicant_id",
")",
":",
"file_storage_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"success",
"=",
"file_storage_manager",
".",
"failback_from_replicant",
"(",
"volume_id",
",",
"replicant_id",
")",
"if",
"success",
":",
"click",
".",
"echo",
"(",
"\"Failback from replicant is now in progress.\"",
")",
"else",
":",
"click",
".",
"echo",
"(",
"\"Failback operation could not be initiated.\"",
")"
]
| Failback a file volume from the given replicant volume. | [
"Failback",
"a",
"file",
"volume",
"from",
"the",
"given",
"replicant",
"volume",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/replication/failback.py#L14-L26 |
softlayer/softlayer-python | SoftLayer/CLI/file/snapshot/restore.py | cli | def cli(env, volume_id, snapshot_id):
"""Restore file volume using a given snapshot"""
file_manager = SoftLayer.FileStorageManager(env.client)
success = file_manager.restore_from_snapshot(volume_id, snapshot_id)
if success:
click.echo('File volume %s is being restored using snapshot %s'
% (volume_id, snapshot_id)) | python | def cli(env, volume_id, snapshot_id):
file_manager = SoftLayer.FileStorageManager(env.client)
success = file_manager.restore_from_snapshot(volume_id, snapshot_id)
if success:
click.echo('File volume %s is being restored using snapshot %s'
% (volume_id, snapshot_id)) | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"snapshot_id",
")",
":",
"file_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"success",
"=",
"file_manager",
".",
"restore_from_snapshot",
"(",
"volume_id",
",",
"snapshot_id",
")",
"if",
"success",
":",
"click",
".",
"echo",
"(",
"'File volume %s is being restored using snapshot %s'",
"%",
"(",
"volume_id",
",",
"snapshot_id",
")",
")"
]
| Restore file volume using a given snapshot | [
"Restore",
"file",
"volume",
"using",
"a",
"given",
"snapshot"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/snapshot/restore.py#L15-L22 |
softlayer/softlayer-python | SoftLayer/CLI/config/show.py | cli | def cli(env):
"""Show current configuration."""
settings = config.get_settings_from_client(env.client)
env.fout(config.config_table(settings)) | python | def cli(env):
settings = config.get_settings_from_client(env.client)
env.fout(config.config_table(settings)) | [
"def",
"cli",
"(",
"env",
")",
":",
"settings",
"=",
"config",
".",
"get_settings_from_client",
"(",
"env",
".",
"client",
")",
"env",
".",
"fout",
"(",
"config",
".",
"config_table",
"(",
"settings",
")",
")"
]
| Show current configuration. | [
"Show",
"current",
"configuration",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/config/show.py#L12-L16 |
softlayer/softlayer-python | SoftLayer/CLI/file/order.py | cli | def cli(env, storage_type, size, iops, tier,
location, snapshot_size, service_offering, billing):
"""Order a file storage volume.
Valid size and iops options can be found here:
https://console.bluemix.net/docs/infrastructure/FileStorage/index.html#provisioning
"""
file_manager = SoftLayer.FileStorageManager(env.client)
storage_type = storage_type.lower()
hourly_billing_flag = False
if billing.lower() == "hourly":
hourly_billing_flag = True
if service_offering != 'storage_as_a_service':
click.secho('{} is a legacy storage offering'.format(service_offering), fg='red')
if hourly_billing_flag:
raise exceptions.CLIAbort(
'Hourly billing is only available for the storage_as_a_service service offering'
)
if storage_type == 'performance':
if iops is None:
raise exceptions.CLIAbort('Option --iops required with Performance')
if service_offering == 'performance' and snapshot_size is not None:
raise exceptions.CLIAbort(
'--snapshot-size is not available for performance service offerings. '
'Use --service-offering storage_as_a_service'
)
try:
order = file_manager.order_file_volume(
storage_type=storage_type,
location=location,
size=size,
iops=iops,
snapshot_size=snapshot_size,
service_offering=service_offering,
hourly_billing_flag=hourly_billing_flag
)
except ValueError as ex:
raise exceptions.ArgumentError(str(ex))
if storage_type == 'endurance':
if tier is None:
raise exceptions.CLIAbort(
'Option --tier required with Endurance in IOPS/GB [0.25,2,4,10]'
)
try:
order = file_manager.order_file_volume(
storage_type=storage_type,
location=location,
size=size,
tier_level=float(tier),
snapshot_size=snapshot_size,
service_offering=service_offering,
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, storage_type, size, iops, tier,
location, snapshot_size, service_offering, billing):
file_manager = SoftLayer.FileStorageManager(env.client)
storage_type = storage_type.lower()
hourly_billing_flag = False
if billing.lower() == "hourly":
hourly_billing_flag = True
if service_offering != 'storage_as_a_service':
click.secho('{} is a legacy storage offering'.format(service_offering), fg='red')
if hourly_billing_flag:
raise exceptions.CLIAbort(
'Hourly billing is only available for the storage_as_a_service service offering'
)
if storage_type == 'performance':
if iops is None:
raise exceptions.CLIAbort('Option --iops required with Performance')
if service_offering == 'performance' and snapshot_size is not None:
raise exceptions.CLIAbort(
'--snapshot-size is not available for performance service offerings. '
'Use --service-offering storage_as_a_service'
)
try:
order = file_manager.order_file_volume(
storage_type=storage_type,
location=location,
size=size,
iops=iops,
snapshot_size=snapshot_size,
service_offering=service_offering,
hourly_billing_flag=hourly_billing_flag
)
except ValueError as ex:
raise exceptions.ArgumentError(str(ex))
if storage_type == 'endurance':
if tier is None:
raise exceptions.CLIAbort(
'Option --tier required with Endurance in IOPS/GB [0.25,2,4,10]'
)
try:
order = file_manager.order_file_volume(
storage_type=storage_type,
location=location,
size=size,
tier_level=float(tier),
snapshot_size=snapshot_size,
service_offering=service_offering,
hourly_billing_flag=hourly_billing_flag
)
except ValueError as ex:
raise exceptions.ArgumentError(str(ex))
if 'placedOrder' in order.keys():
click.echo("Order
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",
",",
"storage_type",
",",
"size",
",",
"iops",
",",
"tier",
",",
"location",
",",
"snapshot_size",
",",
"service_offering",
",",
"billing",
")",
":",
"file_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"storage_type",
"=",
"storage_type",
".",
"lower",
"(",
")",
"hourly_billing_flag",
"=",
"False",
"if",
"billing",
".",
"lower",
"(",
")",
"==",
"\"hourly\"",
":",
"hourly_billing_flag",
"=",
"True",
"if",
"service_offering",
"!=",
"'storage_as_a_service'",
":",
"click",
".",
"secho",
"(",
"'{} is a legacy storage offering'",
".",
"format",
"(",
"service_offering",
")",
",",
"fg",
"=",
"'red'",
")",
"if",
"hourly_billing_flag",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Hourly billing is only available for the storage_as_a_service service offering'",
")",
"if",
"storage_type",
"==",
"'performance'",
":",
"if",
"iops",
"is",
"None",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Option --iops required with Performance'",
")",
"if",
"service_offering",
"==",
"'performance'",
"and",
"snapshot_size",
"is",
"not",
"None",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'--snapshot-size is not available for performance service offerings. '",
"'Use --service-offering storage_as_a_service'",
")",
"try",
":",
"order",
"=",
"file_manager",
".",
"order_file_volume",
"(",
"storage_type",
"=",
"storage_type",
",",
"location",
"=",
"location",
",",
"size",
"=",
"size",
",",
"iops",
"=",
"iops",
",",
"snapshot_size",
"=",
"snapshot_size",
",",
"service_offering",
"=",
"service_offering",
",",
"hourly_billing_flag",
"=",
"hourly_billing_flag",
")",
"except",
"ValueError",
"as",
"ex",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"str",
"(",
"ex",
")",
")",
"if",
"storage_type",
"==",
"'endurance'",
":",
"if",
"tier",
"is",
"None",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Option --tier required with Endurance in IOPS/GB [0.25,2,4,10]'",
")",
"try",
":",
"order",
"=",
"file_manager",
".",
"order_file_volume",
"(",
"storage_type",
"=",
"storage_type",
",",
"location",
"=",
"location",
",",
"size",
"=",
"size",
",",
"tier_level",
"=",
"float",
"(",
"tier",
")",
",",
"snapshot_size",
"=",
"snapshot_size",
",",
"service_offering",
"=",
"service_offering",
",",
"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 file storage volume.
Valid size and iops options can be found here:
https://console.bluemix.net/docs/infrastructure/FileStorage/index.html#provisioning | [
"Order",
"a",
"file",
"storage",
"volume",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/order.py#L50-L119 |
softlayer/softlayer-python | SoftLayer/CLI/virt/capacity/create_guest.py | cli | def cli(env, **args):
"""Allows for creating a virtual guest in a reserved capacity."""
create_args = _parse_create_args(env.client, args)
create_args['primary_disk'] = args.get('primary_disk')
manager = CapacityManager(env.client)
capacity_id = args.get('capacity_id')
test = args.get('test')
result = manager.create_guest(capacity_id, test, create_args)
env.fout(_build_receipt(result, test)) | python | def cli(env, **args):
create_args = _parse_create_args(env.client, args)
create_args['primary_disk'] = args.get('primary_disk')
manager = CapacityManager(env.client)
capacity_id = args.get('capacity_id')
test = args.get('test')
result = manager.create_guest(capacity_id, test, create_args)
env.fout(_build_receipt(result, test)) | [
"def",
"cli",
"(",
"env",
",",
"*",
"*",
"args",
")",
":",
"create_args",
"=",
"_parse_create_args",
"(",
"env",
".",
"client",
",",
"args",
")",
"create_args",
"[",
"'primary_disk'",
"]",
"=",
"args",
".",
"get",
"(",
"'primary_disk'",
")",
"manager",
"=",
"CapacityManager",
"(",
"env",
".",
"client",
")",
"capacity_id",
"=",
"args",
".",
"get",
"(",
"'capacity_id'",
")",
"test",
"=",
"args",
".",
"get",
"(",
"'test'",
")",
"result",
"=",
"manager",
".",
"create_guest",
"(",
"capacity_id",
",",
"test",
",",
"create_args",
")",
"env",
".",
"fout",
"(",
"_build_receipt",
"(",
"result",
",",
"test",
")",
")"
]
| Allows for creating a virtual guest in a reserved capacity. | [
"Allows",
"for",
"creating",
"a",
"virtual",
"guest",
"in",
"a",
"reserved",
"capacity",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/capacity/create_guest.py#L36-L47 |
softlayer/softlayer-python | SoftLayer/CLI/sshkey/print.py | cli | def cli(env, identifier, out_file):
"""Prints out an SSH key to the screen."""
mgr = SoftLayer.SshKeyManager(env.client)
key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey')
key = mgr.get_key(key_id)
if out_file:
with open(path.expanduser(out_file), 'w') as pub_file:
pub_file.write(key['key'])
table = formatting.KeyValueTable(['name', 'value'])
table.add_row(['id', key['id']])
table.add_row(['label', key.get('label')])
table.add_row(['notes', key.get('notes', '-')])
env.fout(table) | python | def cli(env, identifier, out_file):
mgr = SoftLayer.SshKeyManager(env.client)
key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey')
key = mgr.get_key(key_id)
if out_file:
with open(path.expanduser(out_file), 'w') as pub_file:
pub_file.write(key['key'])
table = formatting.KeyValueTable(['name', 'value'])
table.add_row(['id', key['id']])
table.add_row(['label', key.get('label')])
table.add_row(['notes', key.get('notes', '-')])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"out_file",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"SshKeyManager",
"(",
"env",
".",
"client",
")",
"key_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'SshKey'",
")",
"key",
"=",
"mgr",
".",
"get_key",
"(",
"key_id",
")",
"if",
"out_file",
":",
"with",
"open",
"(",
"path",
".",
"expanduser",
"(",
"out_file",
")",
",",
"'w'",
")",
"as",
"pub_file",
":",
"pub_file",
".",
"write",
"(",
"key",
"[",
"'key'",
"]",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"key",
"[",
"'id'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'label'",
",",
"key",
".",
"get",
"(",
"'label'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'notes'",
",",
"key",
".",
"get",
"(",
"'notes'",
",",
"'-'",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Prints out an SSH key to the screen. | [
"Prints",
"out",
"an",
"SSH",
"key",
"to",
"the",
"screen",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/sshkey/print.py#L19-L36 |
softlayer/softlayer-python | SoftLayer/managers/object_storage.py | ObjectStorageManager.list_endpoints | def list_endpoints(self):
"""Lists the known object storage endpoints."""
_filter = {
'hubNetworkStorage': {'vendorName': {'operation': 'Swift'}},
}
endpoints = []
network_storage = self.client.call('Account',
'getHubNetworkStorage',
mask=ENDPOINT_MASK,
limit=1,
filter=_filter)
if network_storage:
for node in network_storage['storageNodes']:
endpoints.append({
'datacenter': node['datacenter'],
'public': node['frontendIpAddress'],
'private': node['backendIpAddress'],
})
return endpoints | python | def list_endpoints(self):
_filter = {
'hubNetworkStorage': {'vendorName': {'operation': 'Swift'}},
}
endpoints = []
network_storage = self.client.call('Account',
'getHubNetworkStorage',
mask=ENDPOINT_MASK,
limit=1,
filter=_filter)
if network_storage:
for node in network_storage['storageNodes']:
endpoints.append({
'datacenter': node['datacenter'],
'public': node['frontendIpAddress'],
'private': node['backendIpAddress'],
})
return endpoints | [
"def",
"list_endpoints",
"(",
"self",
")",
":",
"_filter",
"=",
"{",
"'hubNetworkStorage'",
":",
"{",
"'vendorName'",
":",
"{",
"'operation'",
":",
"'Swift'",
"}",
"}",
",",
"}",
"endpoints",
"=",
"[",
"]",
"network_storage",
"=",
"self",
".",
"client",
".",
"call",
"(",
"'Account'",
",",
"'getHubNetworkStorage'",
",",
"mask",
"=",
"ENDPOINT_MASK",
",",
"limit",
"=",
"1",
",",
"filter",
"=",
"_filter",
")",
"if",
"network_storage",
":",
"for",
"node",
"in",
"network_storage",
"[",
"'storageNodes'",
"]",
":",
"endpoints",
".",
"append",
"(",
"{",
"'datacenter'",
":",
"node",
"[",
"'datacenter'",
"]",
",",
"'public'",
":",
"node",
"[",
"'frontendIpAddress'",
"]",
",",
"'private'",
":",
"node",
"[",
"'backendIpAddress'",
"]",
",",
"}",
")",
"return",
"endpoints"
]
| Lists the known object storage endpoints. | [
"Lists",
"the",
"known",
"object",
"storage",
"endpoints",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/object_storage.py#L35-L54 |
softlayer/softlayer-python | SoftLayer/managers/object_storage.py | ObjectStorageManager.delete_credential | def delete_credential(self, identifier, credential_id=None):
"""Delete the object storage credential.
:param int id: The object storage account identifier.
:param int credential_id: The credential id to be deleted.
"""
credential = {
'id': credential_id
}
return self.client.call('SoftLayer_Network_Storage_Hub_Cleversafe_Account', 'credentialDelete',
credential, id=identifier) | python | def delete_credential(self, identifier, credential_id=None):
credential = {
'id': credential_id
}
return self.client.call('SoftLayer_Network_Storage_Hub_Cleversafe_Account', 'credentialDelete',
credential, id=identifier) | [
"def",
"delete_credential",
"(",
"self",
",",
"identifier",
",",
"credential_id",
"=",
"None",
")",
":",
"credential",
"=",
"{",
"'id'",
":",
"credential_id",
"}",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'SoftLayer_Network_Storage_Hub_Cleversafe_Account'",
",",
"'credentialDelete'",
",",
"credential",
",",
"id",
"=",
"identifier",
")"
]
| Delete the object storage credential.
:param int id: The object storage account identifier.
:param int credential_id: The credential id to be deleted. | [
"Delete",
"the",
"object",
"storage",
"credential",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/object_storage.py#L66-L78 |
softlayer/softlayer-python | SoftLayer/CLI/hardware/list.py | cli | def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network, tag, columns, limit):
"""List hardware servers."""
manager = SoftLayer.HardwareManager(env.client)
servers = manager.list_hardware(hostname=hostname,
domain=domain,
cpus=cpu,
memory=memory,
datacenter=datacenter,
nic_speed=network,
tags=tag,
mask="mask(SoftLayer_Hardware_Server)[%s]" % columns.mask(),
limit=limit)
table = formatting.Table(columns.columns)
table.sortby = sortby
for server in servers:
table.add_row([value or formatting.blank()
for value in columns.row(server)])
env.fout(table) | python | def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network, tag, columns, limit):
manager = SoftLayer.HardwareManager(env.client)
servers = manager.list_hardware(hostname=hostname,
domain=domain,
cpus=cpu,
memory=memory,
datacenter=datacenter,
nic_speed=network,
tags=tag,
mask="mask(SoftLayer_Hardware_Server)[%s]" % columns.mask(),
limit=limit)
table = formatting.Table(columns.columns)
table.sortby = sortby
for server in servers:
table.add_row([value or formatting.blank()
for value in columns.row(server)])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"sortby",
",",
"cpu",
",",
"domain",
",",
"datacenter",
",",
"hostname",
",",
"memory",
",",
"network",
",",
"tag",
",",
"columns",
",",
"limit",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"HardwareManager",
"(",
"env",
".",
"client",
")",
"servers",
"=",
"manager",
".",
"list_hardware",
"(",
"hostname",
"=",
"hostname",
",",
"domain",
"=",
"domain",
",",
"cpus",
"=",
"cpu",
",",
"memory",
"=",
"memory",
",",
"datacenter",
"=",
"datacenter",
",",
"nic_speed",
"=",
"network",
",",
"tags",
"=",
"tag",
",",
"mask",
"=",
"\"mask(SoftLayer_Hardware_Server)[%s]\"",
"%",
"columns",
".",
"mask",
"(",
")",
",",
"limit",
"=",
"limit",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"columns",
".",
"columns",
")",
"table",
".",
"sortby",
"=",
"sortby",
"for",
"server",
"in",
"servers",
":",
"table",
".",
"add_row",
"(",
"[",
"value",
"or",
"formatting",
".",
"blank",
"(",
")",
"for",
"value",
"in",
"columns",
".",
"row",
"(",
"server",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| List hardware servers. | [
"List",
"hardware",
"servers",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/list.py#L62-L83 |
softlayer/softlayer-python | SoftLayer/CLI/user/edit_details.py | cli | def cli(env, user, template):
"""Edit a Users details
JSON strings should be enclosed in '' and each item should be enclosed in ""
:Example: slcli user edit-details testUser -t '{"firstName": "Test", "lastName": "Testerson"}'
"""
mgr = SoftLayer.UserManager(env.client)
user_id = helpers.resolve_id(mgr.resolve_ids, user, 'username')
user_template = {}
if template is not None:
try:
template_object = json.loads(template)
for key in template_object:
user_template[key] = template_object[key]
except ValueError as ex:
raise exceptions.ArgumentError("Unable to parse --template. %s" % ex)
result = mgr.edit_user(user_id, user_template)
if result:
click.secho("%s updated successfully" % (user), fg='green')
else:
click.secho("Failed to update %s" % (user), fg='red') | python | def cli(env, user, template):
mgr = SoftLayer.UserManager(env.client)
user_id = helpers.resolve_id(mgr.resolve_ids, user, 'username')
user_template = {}
if template is not None:
try:
template_object = json.loads(template)
for key in template_object:
user_template[key] = template_object[key]
except ValueError as ex:
raise exceptions.ArgumentError("Unable to parse --template. %s" % ex)
result = mgr.edit_user(user_id, user_template)
if result:
click.secho("%s updated successfully" % (user), fg='green')
else:
click.secho("Failed to update %s" % (user), fg='red') | [
"def",
"cli",
"(",
"env",
",",
"user",
",",
"template",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"UserManager",
"(",
"env",
".",
"client",
")",
"user_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"user",
",",
"'username'",
")",
"user_template",
"=",
"{",
"}",
"if",
"template",
"is",
"not",
"None",
":",
"try",
":",
"template_object",
"=",
"json",
".",
"loads",
"(",
"template",
")",
"for",
"key",
"in",
"template_object",
":",
"user_template",
"[",
"key",
"]",
"=",
"template_object",
"[",
"key",
"]",
"except",
"ValueError",
"as",
"ex",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"\"Unable to parse --template. %s\"",
"%",
"ex",
")",
"result",
"=",
"mgr",
".",
"edit_user",
"(",
"user_id",
",",
"user_template",
")",
"if",
"result",
":",
"click",
".",
"secho",
"(",
"\"%s updated successfully\"",
"%",
"(",
"user",
")",
",",
"fg",
"=",
"'green'",
")",
"else",
":",
"click",
".",
"secho",
"(",
"\"Failed to update %s\"",
"%",
"(",
"user",
")",
",",
"fg",
"=",
"'red'",
")"
]
| Edit a Users details
JSON strings should be enclosed in '' and each item should be enclosed in ""
:Example: slcli user edit-details testUser -t '{"firstName": "Test", "lastName": "Testerson"}' | [
"Edit",
"a",
"Users",
"details"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/edit_details.py#L20-L43 |
softlayer/softlayer-python | SoftLayer/CLI/subnet/lookup.py | cli | def cli(env, ip_address):
"""Find an IP address and display its subnet and device info."""
mgr = SoftLayer.NetworkManager(env.client)
addr_info = mgr.ip_lookup(ip_address)
if not addr_info:
raise exceptions.CLIAbort('Not found')
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', addr_info['id']])
table.add_row(['ip', addr_info['ipAddress']])
subnet_table = formatting.KeyValueTable(['name', 'value'])
subnet_table.align['name'] = 'r'
subnet_table.align['value'] = 'l'
subnet_table.add_row(['id', addr_info['subnet']['id']])
subnet_table.add_row(['identifier',
'%s/%s' % (addr_info['subnet']['networkIdentifier'],
str(addr_info['subnet']['cidr']))])
subnet_table.add_row(['netmask', addr_info['subnet']['netmask']])
if addr_info['subnet'].get('gateway'):
subnet_table.add_row(['gateway', addr_info['subnet']['gateway']])
subnet_table.add_row(['type', addr_info['subnet'].get('subnetType')])
table.add_row(['subnet', subnet_table])
if addr_info.get('virtualGuest') or addr_info.get('hardware'):
device_table = formatting.KeyValueTable(['name', 'value'])
device_table.align['name'] = 'r'
device_table.align['value'] = 'l'
if addr_info.get('virtualGuest'):
device = addr_info['virtualGuest']
device_type = 'vs'
else:
device = addr_info['hardware']
device_type = 'server'
device_table.add_row(['id', device['id']])
device_table.add_row(['name', device['fullyQualifiedDomainName']])
device_table.add_row(['type', device_type])
table.add_row(['device', device_table])
env.fout(table) | python | def cli(env, ip_address):
mgr = SoftLayer.NetworkManager(env.client)
addr_info = mgr.ip_lookup(ip_address)
if not addr_info:
raise exceptions.CLIAbort('Not found')
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', addr_info['id']])
table.add_row(['ip', addr_info['ipAddress']])
subnet_table = formatting.KeyValueTable(['name', 'value'])
subnet_table.align['name'] = 'r'
subnet_table.align['value'] = 'l'
subnet_table.add_row(['id', addr_info['subnet']['id']])
subnet_table.add_row(['identifier',
'%s/%s' % (addr_info['subnet']['networkIdentifier'],
str(addr_info['subnet']['cidr']))])
subnet_table.add_row(['netmask', addr_info['subnet']['netmask']])
if addr_info['subnet'].get('gateway'):
subnet_table.add_row(['gateway', addr_info['subnet']['gateway']])
subnet_table.add_row(['type', addr_info['subnet'].get('subnetType')])
table.add_row(['subnet', subnet_table])
if addr_info.get('virtualGuest') or addr_info.get('hardware'):
device_table = formatting.KeyValueTable(['name', 'value'])
device_table.align['name'] = 'r'
device_table.align['value'] = 'l'
if addr_info.get('virtualGuest'):
device = addr_info['virtualGuest']
device_type = 'vs'
else:
device = addr_info['hardware']
device_type = 'server'
device_table.add_row(['id', device['id']])
device_table.add_row(['name', device['fullyQualifiedDomainName']])
device_table.add_row(['type', device_type])
table.add_row(['device', device_table])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"ip_address",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"addr_info",
"=",
"mgr",
".",
"ip_lookup",
"(",
"ip_address",
")",
"if",
"not",
"addr_info",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Not found'",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"addr_info",
"[",
"'id'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'ip'",
",",
"addr_info",
"[",
"'ipAddress'",
"]",
"]",
")",
"subnet_table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"subnet_table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"subnet_table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"subnet_table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"addr_info",
"[",
"'subnet'",
"]",
"[",
"'id'",
"]",
"]",
")",
"subnet_table",
".",
"add_row",
"(",
"[",
"'identifier'",
",",
"'%s/%s'",
"%",
"(",
"addr_info",
"[",
"'subnet'",
"]",
"[",
"'networkIdentifier'",
"]",
",",
"str",
"(",
"addr_info",
"[",
"'subnet'",
"]",
"[",
"'cidr'",
"]",
")",
")",
"]",
")",
"subnet_table",
".",
"add_row",
"(",
"[",
"'netmask'",
",",
"addr_info",
"[",
"'subnet'",
"]",
"[",
"'netmask'",
"]",
"]",
")",
"if",
"addr_info",
"[",
"'subnet'",
"]",
".",
"get",
"(",
"'gateway'",
")",
":",
"subnet_table",
".",
"add_row",
"(",
"[",
"'gateway'",
",",
"addr_info",
"[",
"'subnet'",
"]",
"[",
"'gateway'",
"]",
"]",
")",
"subnet_table",
".",
"add_row",
"(",
"[",
"'type'",
",",
"addr_info",
"[",
"'subnet'",
"]",
".",
"get",
"(",
"'subnetType'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'subnet'",
",",
"subnet_table",
"]",
")",
"if",
"addr_info",
".",
"get",
"(",
"'virtualGuest'",
")",
"or",
"addr_info",
".",
"get",
"(",
"'hardware'",
")",
":",
"device_table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"device_table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"device_table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"if",
"addr_info",
".",
"get",
"(",
"'virtualGuest'",
")",
":",
"device",
"=",
"addr_info",
"[",
"'virtualGuest'",
"]",
"device_type",
"=",
"'vs'",
"else",
":",
"device",
"=",
"addr_info",
"[",
"'hardware'",
"]",
"device_type",
"=",
"'server'",
"device_table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"device",
"[",
"'id'",
"]",
"]",
")",
"device_table",
".",
"add_row",
"(",
"[",
"'name'",
",",
"device",
"[",
"'fullyQualifiedDomainName'",
"]",
"]",
")",
"device_table",
".",
"add_row",
"(",
"[",
"'type'",
",",
"device_type",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'device'",
",",
"device_table",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Find an IP address and display its subnet and device info. | [
"Find",
"an",
"IP",
"address",
"and",
"display",
"its",
"subnet",
"and",
"device",
"info",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/subnet/lookup.py#L15-L60 |
softlayer/softlayer-python | SoftLayer/CLI/image/import.py | cli | def cli(env, name, note, os_code, uri, ibm_api_key, root_key_crn, wrapped_dek,
cloud_init, byol, is_encrypted):
"""Import an image.
The URI for an object storage object (.vhd/.iso file) of the format:
swift://<objectStorageAccount>@<cluster>/<container>/<objectPath>
or cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud
Object Storage
"""
image_mgr = SoftLayer.ImageManager(env.client)
result = image_mgr.import_image_from_uri(
name=name,
note=note,
os_code=os_code,
uri=uri,
ibm_api_key=ibm_api_key,
root_key_crn=root_key_crn,
wrapped_dek=wrapped_dek,
cloud_init=cloud_init,
byol=byol,
is_encrypted=is_encrypted
)
if not result:
raise exceptions.CLIAbort("Failed to import Image")
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['name', result['name']])
table.add_row(['id', result['id']])
table.add_row(['created', result['createDate']])
table.add_row(['guid', result['globalIdentifier']])
env.fout(table) | python | def cli(env, name, note, os_code, uri, ibm_api_key, root_key_crn, wrapped_dek,
cloud_init, byol, is_encrypted):
image_mgr = SoftLayer.ImageManager(env.client)
result = image_mgr.import_image_from_uri(
name=name,
note=note,
os_code=os_code,
uri=uri,
ibm_api_key=ibm_api_key,
root_key_crn=root_key_crn,
wrapped_dek=wrapped_dek,
cloud_init=cloud_init,
byol=byol,
is_encrypted=is_encrypted
)
if not result:
raise exceptions.CLIAbort("Failed to import Image")
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['name', result['name']])
table.add_row(['id', result['id']])
table.add_row(['created', result['createDate']])
table.add_row(['guid', result['globalIdentifier']])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"name",
",",
"note",
",",
"os_code",
",",
"uri",
",",
"ibm_api_key",
",",
"root_key_crn",
",",
"wrapped_dek",
",",
"cloud_init",
",",
"byol",
",",
"is_encrypted",
")",
":",
"image_mgr",
"=",
"SoftLayer",
".",
"ImageManager",
"(",
"env",
".",
"client",
")",
"result",
"=",
"image_mgr",
".",
"import_image_from_uri",
"(",
"name",
"=",
"name",
",",
"note",
"=",
"note",
",",
"os_code",
"=",
"os_code",
",",
"uri",
"=",
"uri",
",",
"ibm_api_key",
"=",
"ibm_api_key",
",",
"root_key_crn",
"=",
"root_key_crn",
",",
"wrapped_dek",
"=",
"wrapped_dek",
",",
"cloud_init",
"=",
"cloud_init",
",",
"byol",
"=",
"byol",
",",
"is_encrypted",
"=",
"is_encrypted",
")",
"if",
"not",
"result",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Failed to import Image\"",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'name'",
",",
"result",
"[",
"'name'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"result",
"[",
"'id'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'created'",
",",
"result",
"[",
"'createDate'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'guid'",
",",
"result",
"[",
"'globalIdentifier'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Import an image.
The URI for an object storage object (.vhd/.iso file) of the format:
swift://<objectStorageAccount>@<cluster>/<container>/<objectPath>
or cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud
Object Storage | [
"Import",
"an",
"image",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/image/import.py#L46-L80 |
softlayer/softlayer-python | SoftLayer/CLI/vpn/ipsec/update.py | cli | def cli(env, context_id, friendly_name, remote_peer, preshared_key,
phase1_auth, phase1_crypto, phase1_dh, phase1_key_ttl, phase2_auth,
phase2_crypto, phase2_dh, phase2_forward_secrecy, phase2_key_ttl):
"""Update tunnel context properties.
Updates are made atomically, so either all are accepted or none are.
Key life values must be in the range 120-172800.
Phase 2 perfect forward secrecy must be in the range 0-1.
A separate configuration request should be made to realize changes on
network devices.
"""
manager = SoftLayer.IPSECManager(env.client)
succeeded = manager.update_tunnel_context(
context_id,
friendly_name=friendly_name,
remote_peer=remote_peer,
preshared_key=preshared_key,
phase1_auth=phase1_auth,
phase1_crypto=phase1_crypto,
phase1_dh=phase1_dh,
phase1_key_ttl=phase1_key_ttl,
phase2_auth=phase2_auth,
phase2_crypto=phase2_crypto,
phase2_dh=phase2_dh,
phase2_forward_secrecy=phase2_forward_secrecy,
phase2_key_ttl=phase2_key_ttl
)
if succeeded:
env.out('Updated context #{}'.format(context_id))
else:
raise CLIHalt('Failed to update context #{}'.format(context_id)) | python | def cli(env, context_id, friendly_name, remote_peer, preshared_key,
phase1_auth, phase1_crypto, phase1_dh, phase1_key_ttl, phase2_auth,
phase2_crypto, phase2_dh, phase2_forward_secrecy, phase2_key_ttl):
manager = SoftLayer.IPSECManager(env.client)
succeeded = manager.update_tunnel_context(
context_id,
friendly_name=friendly_name,
remote_peer=remote_peer,
preshared_key=preshared_key,
phase1_auth=phase1_auth,
phase1_crypto=phase1_crypto,
phase1_dh=phase1_dh,
phase1_key_ttl=phase1_key_ttl,
phase2_auth=phase2_auth,
phase2_crypto=phase2_crypto,
phase2_dh=phase2_dh,
phase2_forward_secrecy=phase2_forward_secrecy,
phase2_key_ttl=phase2_key_ttl
)
if succeeded:
env.out('Updated context
else:
raise CLIHalt('Failed to update context | [
"def",
"cli",
"(",
"env",
",",
"context_id",
",",
"friendly_name",
",",
"remote_peer",
",",
"preshared_key",
",",
"phase1_auth",
",",
"phase1_crypto",
",",
"phase1_dh",
",",
"phase1_key_ttl",
",",
"phase2_auth",
",",
"phase2_crypto",
",",
"phase2_dh",
",",
"phase2_forward_secrecy",
",",
"phase2_key_ttl",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"IPSECManager",
"(",
"env",
".",
"client",
")",
"succeeded",
"=",
"manager",
".",
"update_tunnel_context",
"(",
"context_id",
",",
"friendly_name",
"=",
"friendly_name",
",",
"remote_peer",
"=",
"remote_peer",
",",
"preshared_key",
"=",
"preshared_key",
",",
"phase1_auth",
"=",
"phase1_auth",
",",
"phase1_crypto",
"=",
"phase1_crypto",
",",
"phase1_dh",
"=",
"phase1_dh",
",",
"phase1_key_ttl",
"=",
"phase1_key_ttl",
",",
"phase2_auth",
"=",
"phase2_auth",
",",
"phase2_crypto",
"=",
"phase2_crypto",
",",
"phase2_dh",
"=",
"phase2_dh",
",",
"phase2_forward_secrecy",
"=",
"phase2_forward_secrecy",
",",
"phase2_key_ttl",
"=",
"phase2_key_ttl",
")",
"if",
"succeeded",
":",
"env",
".",
"out",
"(",
"'Updated context #{}'",
".",
"format",
"(",
"context_id",
")",
")",
"else",
":",
"raise",
"CLIHalt",
"(",
"'Failed to update context #{}'",
".",
"format",
"(",
"context_id",
")",
")"
]
| Update tunnel context properties.
Updates are made atomically, so either all are accepted or none are.
Key life values must be in the range 120-172800.
Phase 2 perfect forward secrecy must be in the range 0-1.
A separate configuration request should be made to realize changes on
network devices. | [
"Update",
"tunnel",
"context",
"properties",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/update.py#L68-L101 |
softlayer/softlayer-python | SoftLayer/managers/ipsec.py | IPSECManager.add_internal_subnet | def add_internal_subnet(self, context_id, subnet_id):
"""Add an internal subnet to a tunnel context.
:param int context_id: The id-value representing the context instance.
:param int subnet_id: The id-value representing the internal subnet.
:return bool: True if internal subnet addition was successful.
"""
return self.context.addPrivateSubnetToNetworkTunnel(subnet_id,
id=context_id) | python | def add_internal_subnet(self, context_id, subnet_id):
return self.context.addPrivateSubnetToNetworkTunnel(subnet_id,
id=context_id) | [
"def",
"add_internal_subnet",
"(",
"self",
",",
"context_id",
",",
"subnet_id",
")",
":",
"return",
"self",
".",
"context",
".",
"addPrivateSubnetToNetworkTunnel",
"(",
"subnet_id",
",",
"id",
"=",
"context_id",
")"
]
| Add an internal subnet to a tunnel context.
:param int context_id: The id-value representing the context instance.
:param int subnet_id: The id-value representing the internal subnet.
:return bool: True if internal subnet addition was successful. | [
"Add",
"an",
"internal",
"subnet",
"to",
"a",
"tunnel",
"context",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/ipsec.py#L31-L39 |
softlayer/softlayer-python | SoftLayer/managers/ipsec.py | IPSECManager.add_remote_subnet | def add_remote_subnet(self, context_id, subnet_id):
"""Adds a remote subnet to a tunnel context.
:param int context_id: The id-value representing the context instance.
:param int subnet_id: The id-value representing the remote subnet.
:return bool: True if remote subnet addition was successful.
"""
return self.context.addCustomerSubnetToNetworkTunnel(subnet_id,
id=context_id) | python | def add_remote_subnet(self, context_id, subnet_id):
return self.context.addCustomerSubnetToNetworkTunnel(subnet_id,
id=context_id) | [
"def",
"add_remote_subnet",
"(",
"self",
",",
"context_id",
",",
"subnet_id",
")",
":",
"return",
"self",
".",
"context",
".",
"addCustomerSubnetToNetworkTunnel",
"(",
"subnet_id",
",",
"id",
"=",
"context_id",
")"
]
| Adds a remote subnet to a tunnel context.
:param int context_id: The id-value representing the context instance.
:param int subnet_id: The id-value representing the remote subnet.
:return bool: True if remote subnet addition was successful. | [
"Adds",
"a",
"remote",
"subnet",
"to",
"a",
"tunnel",
"context",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/ipsec.py#L41-L49 |
softlayer/softlayer-python | SoftLayer/managers/ipsec.py | IPSECManager.add_service_subnet | def add_service_subnet(self, context_id, subnet_id):
"""Adds a service subnet to a tunnel context.
:param int context_id: The id-value representing the context instance.
:param int subnet_id: The id-value representing the service subnet.
:return bool: True if service subnet addition was successful.
"""
return self.context.addServiceSubnetToNetworkTunnel(subnet_id,
id=context_id) | python | def add_service_subnet(self, context_id, subnet_id):
return self.context.addServiceSubnetToNetworkTunnel(subnet_id,
id=context_id) | [
"def",
"add_service_subnet",
"(",
"self",
",",
"context_id",
",",
"subnet_id",
")",
":",
"return",
"self",
".",
"context",
".",
"addServiceSubnetToNetworkTunnel",
"(",
"subnet_id",
",",
"id",
"=",
"context_id",
")"
]
| Adds a service subnet to a tunnel context.
:param int context_id: The id-value representing the context instance.
:param int subnet_id: The id-value representing the service subnet.
:return bool: True if service subnet addition was successful. | [
"Adds",
"a",
"service",
"subnet",
"to",
"a",
"tunnel",
"context",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/ipsec.py#L51-L59 |
softlayer/softlayer-python | SoftLayer/managers/ipsec.py | IPSECManager.create_remote_subnet | def create_remote_subnet(self, account_id, identifier, cidr):
"""Creates a remote subnet on the given account.
:param string account_id: The account identifier.
:param string identifier: The network identifier of the remote subnet.
:param string cidr: The CIDR value of the remote subnet.
:return dict: Mapping of properties for the new remote subnet.
"""
return self.remote_subnet.createObject({
'accountId': account_id,
'cidr': cidr,
'networkIdentifier': identifier
}) | python | def create_remote_subnet(self, account_id, identifier, cidr):
return self.remote_subnet.createObject({
'accountId': account_id,
'cidr': cidr,
'networkIdentifier': identifier
}) | [
"def",
"create_remote_subnet",
"(",
"self",
",",
"account_id",
",",
"identifier",
",",
"cidr",
")",
":",
"return",
"self",
".",
"remote_subnet",
".",
"createObject",
"(",
"{",
"'accountId'",
":",
"account_id",
",",
"'cidr'",
":",
"cidr",
",",
"'networkIdentifier'",
":",
"identifier",
"}",
")"
]
| Creates a remote subnet on the given account.
:param string account_id: The account identifier.
:param string identifier: The network identifier of the remote subnet.
:param string cidr: The CIDR value of the remote subnet.
:return dict: Mapping of properties for the new remote subnet. | [
"Creates",
"a",
"remote",
"subnet",
"on",
"the",
"given",
"account",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/ipsec.py#L69-L81 |
softlayer/softlayer-python | SoftLayer/managers/ipsec.py | IPSECManager.create_translation | def create_translation(self, context_id, static_ip, remote_ip, notes):
"""Creates an address translation on a tunnel context/
:param int context_id: The id-value representing the context instance.
:param string static_ip: The IP address value representing the
internal side of the translation entry,
:param string remote_ip: The IP address value representing the remote
side of the translation entry,
:param string notes: The notes to supply with the translation entry,
:return dict: Mapping of properties for the new translation entry.
"""
return self.context.createAddressTranslation({
'customerIpAddress': remote_ip,
'internalIpAddress': static_ip,
'notes': notes
}, id=context_id) | python | def create_translation(self, context_id, static_ip, remote_ip, notes):
return self.context.createAddressTranslation({
'customerIpAddress': remote_ip,
'internalIpAddress': static_ip,
'notes': notes
}, id=context_id) | [
"def",
"create_translation",
"(",
"self",
",",
"context_id",
",",
"static_ip",
",",
"remote_ip",
",",
"notes",
")",
":",
"return",
"self",
".",
"context",
".",
"createAddressTranslation",
"(",
"{",
"'customerIpAddress'",
":",
"remote_ip",
",",
"'internalIpAddress'",
":",
"static_ip",
",",
"'notes'",
":",
"notes",
"}",
",",
"id",
"=",
"context_id",
")"
]
| Creates an address translation on a tunnel context/
:param int context_id: The id-value representing the context instance.
:param string static_ip: The IP address value representing the
internal side of the translation entry,
:param string remote_ip: The IP address value representing the remote
side of the translation entry,
:param string notes: The notes to supply with the translation entry,
:return dict: Mapping of properties for the new translation entry. | [
"Creates",
"an",
"address",
"translation",
"on",
"a",
"tunnel",
"context",
"/"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/ipsec.py#L83-L98 |
softlayer/softlayer-python | SoftLayer/managers/ipsec.py | IPSECManager.get_tunnel_context | def get_tunnel_context(self, context_id, **kwargs):
"""Retrieves the network tunnel context instance.
:param int context_id: The id-value representing the context instance.
:return dict: Mapping of properties for the tunnel context.
:raise SoftLayerAPIError: If a context cannot be found.
"""
_filter = utils.NestedDict(kwargs.get('filter') or {})
_filter['networkTunnelContexts']['id'] = utils.query_filter(context_id)
kwargs['filter'] = _filter.to_dict()
contexts = self.account.getNetworkTunnelContexts(**kwargs)
if len(contexts) == 0:
raise SoftLayerAPIError('SoftLayer_Exception_ObjectNotFound',
'Unable to find object with id of \'{}\''
.format(context_id))
return contexts[0] | python | def get_tunnel_context(self, context_id, **kwargs):
_filter = utils.NestedDict(kwargs.get('filter') or {})
_filter['networkTunnelContexts']['id'] = utils.query_filter(context_id)
kwargs['filter'] = _filter.to_dict()
contexts = self.account.getNetworkTunnelContexts(**kwargs)
if len(contexts) == 0:
raise SoftLayerAPIError('SoftLayer_Exception_ObjectNotFound',
'Unable to find object with id of \'{}\''
.format(context_id))
return contexts[0] | [
"def",
"get_tunnel_context",
"(",
"self",
",",
"context_id",
",",
"*",
"*",
"kwargs",
")",
":",
"_filter",
"=",
"utils",
".",
"NestedDict",
"(",
"kwargs",
".",
"get",
"(",
"'filter'",
")",
"or",
"{",
"}",
")",
"_filter",
"[",
"'networkTunnelContexts'",
"]",
"[",
"'id'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"context_id",
")",
"kwargs",
"[",
"'filter'",
"]",
"=",
"_filter",
".",
"to_dict",
"(",
")",
"contexts",
"=",
"self",
".",
"account",
".",
"getNetworkTunnelContexts",
"(",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"contexts",
")",
"==",
"0",
":",
"raise",
"SoftLayerAPIError",
"(",
"'SoftLayer_Exception_ObjectNotFound'",
",",
"'Unable to find object with id of \\'{}\\''",
".",
"format",
"(",
"context_id",
")",
")",
"return",
"contexts",
"[",
"0",
"]"
]
| Retrieves the network tunnel context instance.
:param int context_id: The id-value representing the context instance.
:return dict: Mapping of properties for the tunnel context.
:raise SoftLayerAPIError: If a context cannot be found. | [
"Retrieves",
"the",
"network",
"tunnel",
"context",
"instance",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/ipsec.py#L108-L124 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.