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/ipsec.py | IPSECManager.get_translation | def get_translation(self, context_id, translation_id):
"""Retrieves a translation entry for the given id values.
:param int context_id: The id-value representing the context instance.
:param int translation_id: The id-value representing the translation
instance.
:return dict: Mapping of properties for the translation entry.
:raise SoftLayerAPIError: If a translation cannot be found.
"""
translation = next((x for x in self.get_translations(context_id)
if x['id'] == translation_id), None)
if translation is None:
raise SoftLayerAPIError('SoftLayer_Exception_ObjectNotFound',
'Unable to find object with id of \'{}\''
.format(translation_id))
return translation | python | def get_translation(self, context_id, translation_id):
translation = next((x for x in self.get_translations(context_id)
if x['id'] == translation_id), None)
if translation is None:
raise SoftLayerAPIError('SoftLayer_Exception_ObjectNotFound',
'Unable to find object with id of \'{}\''
.format(translation_id))
return translation | [
"def",
"get_translation",
"(",
"self",
",",
"context_id",
",",
"translation_id",
")",
":",
"translation",
"=",
"next",
"(",
"(",
"x",
"for",
"x",
"in",
"self",
".",
"get_translations",
"(",
"context_id",
")",
"if",
"x",
"[",
"'id'",
"]",
"==",
"translation_id",
")",
",",
"None",
")",
"if",
"translation",
"is",
"None",
":",
"raise",
"SoftLayerAPIError",
"(",
"'SoftLayer_Exception_ObjectNotFound'",
",",
"'Unable to find object with id of \\'{}\\''",
".",
"format",
"(",
"translation_id",
")",
")",
"return",
"translation"
]
| Retrieves a translation entry for the given id values.
:param int context_id: The id-value representing the context instance.
:param int translation_id: The id-value representing the translation
instance.
:return dict: Mapping of properties for the translation entry.
:raise SoftLayerAPIError: If a translation cannot be found. | [
"Retrieves",
"a",
"translation",
"entry",
"for",
"the",
"given",
"id",
"values",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/ipsec.py#L126-L141 |
softlayer/softlayer-python | SoftLayer/managers/ipsec.py | IPSECManager.get_translations | def get_translations(self, context_id):
"""Retrieves all translation entries for a tunnel context.
:param int context_id: The id-value representing the context instance.
:return list(dict): Translations associated with the given context
"""
_mask = ('[mask[addressTranslations[customerIpAddressRecord,'
'internalIpAddressRecord]]]')
context = self.get_tunnel_context(context_id, mask=_mask)
# Pull the internal and remote IP addresses into the translation
for translation in context.get('addressTranslations', []):
remote_ip = translation.get('customerIpAddressRecord', {})
internal_ip = translation.get('internalIpAddressRecord', {})
translation['customerIpAddress'] = remote_ip.get('ipAddress', '')
translation['internalIpAddress'] = internal_ip.get('ipAddress', '')
translation.pop('customerIpAddressRecord', None)
translation.pop('internalIpAddressRecord', None)
return context['addressTranslations'] | python | def get_translations(self, context_id):
_mask = ('[mask[addressTranslations[customerIpAddressRecord,'
'internalIpAddressRecord]]]')
context = self.get_tunnel_context(context_id, mask=_mask)
for translation in context.get('addressTranslations', []):
remote_ip = translation.get('customerIpAddressRecord', {})
internal_ip = translation.get('internalIpAddressRecord', {})
translation['customerIpAddress'] = remote_ip.get('ipAddress', '')
translation['internalIpAddress'] = internal_ip.get('ipAddress', '')
translation.pop('customerIpAddressRecord', None)
translation.pop('internalIpAddressRecord', None)
return context['addressTranslations'] | [
"def",
"get_translations",
"(",
"self",
",",
"context_id",
")",
":",
"_mask",
"=",
"(",
"'[mask[addressTranslations[customerIpAddressRecord,'",
"'internalIpAddressRecord]]]'",
")",
"context",
"=",
"self",
".",
"get_tunnel_context",
"(",
"context_id",
",",
"mask",
"=",
"_mask",
")",
"# Pull the internal and remote IP addresses into the translation",
"for",
"translation",
"in",
"context",
".",
"get",
"(",
"'addressTranslations'",
",",
"[",
"]",
")",
":",
"remote_ip",
"=",
"translation",
".",
"get",
"(",
"'customerIpAddressRecord'",
",",
"{",
"}",
")",
"internal_ip",
"=",
"translation",
".",
"get",
"(",
"'internalIpAddressRecord'",
",",
"{",
"}",
")",
"translation",
"[",
"'customerIpAddress'",
"]",
"=",
"remote_ip",
".",
"get",
"(",
"'ipAddress'",
",",
"''",
")",
"translation",
"[",
"'internalIpAddress'",
"]",
"=",
"internal_ip",
".",
"get",
"(",
"'ipAddress'",
",",
"''",
")",
"translation",
".",
"pop",
"(",
"'customerIpAddressRecord'",
",",
"None",
")",
"translation",
".",
"pop",
"(",
"'internalIpAddressRecord'",
",",
"None",
")",
"return",
"context",
"[",
"'addressTranslations'",
"]"
]
| Retrieves all translation entries for a tunnel context.
:param int context_id: The id-value representing the context instance.
:return list(dict): Translations associated with the given context | [
"Retrieves",
"all",
"translation",
"entries",
"for",
"a",
"tunnel",
"context",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/ipsec.py#L143-L160 |
softlayer/softlayer-python | SoftLayer/managers/ipsec.py | IPSECManager.remove_internal_subnet | def remove_internal_subnet(self, context_id, subnet_id):
"""Remove an internal subnet from 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 removal was successful.
"""
return self.context.removePrivateSubnetFromNetworkTunnel(subnet_id,
id=context_id) | python | def remove_internal_subnet(self, context_id, subnet_id):
return self.context.removePrivateSubnetFromNetworkTunnel(subnet_id,
id=context_id) | [
"def",
"remove_internal_subnet",
"(",
"self",
",",
"context_id",
",",
"subnet_id",
")",
":",
"return",
"self",
".",
"context",
".",
"removePrivateSubnetFromNetworkTunnel",
"(",
"subnet_id",
",",
"id",
"=",
"context_id",
")"
]
| Remove an internal subnet from 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 removal was successful. | [
"Remove",
"an",
"internal",
"subnet",
"from",
"a",
"tunnel",
"context",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/ipsec.py#L169-L177 |
softlayer/softlayer-python | SoftLayer/managers/ipsec.py | IPSECManager.remove_remote_subnet | def remove_remote_subnet(self, context_id, subnet_id):
"""Removes a remote subnet from 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 removal was successful.
"""
return self.context.removeCustomerSubnetFromNetworkTunnel(subnet_id,
id=context_id) | python | def remove_remote_subnet(self, context_id, subnet_id):
return self.context.removeCustomerSubnetFromNetworkTunnel(subnet_id,
id=context_id) | [
"def",
"remove_remote_subnet",
"(",
"self",
",",
"context_id",
",",
"subnet_id",
")",
":",
"return",
"self",
".",
"context",
".",
"removeCustomerSubnetFromNetworkTunnel",
"(",
"subnet_id",
",",
"id",
"=",
"context_id",
")"
]
| Removes a remote subnet from 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 removal was successful. | [
"Removes",
"a",
"remote",
"subnet",
"from",
"a",
"tunnel",
"context",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/ipsec.py#L179-L187 |
softlayer/softlayer-python | SoftLayer/managers/ipsec.py | IPSECManager.remove_service_subnet | def remove_service_subnet(self, context_id, subnet_id):
"""Removes a service subnet from 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 removal was successful.
"""
return self.context.removeServiceSubnetFromNetworkTunnel(subnet_id,
id=context_id) | python | def remove_service_subnet(self, context_id, subnet_id):
return self.context.removeServiceSubnetFromNetworkTunnel(subnet_id,
id=context_id) | [
"def",
"remove_service_subnet",
"(",
"self",
",",
"context_id",
",",
"subnet_id",
")",
":",
"return",
"self",
".",
"context",
".",
"removeServiceSubnetFromNetworkTunnel",
"(",
"subnet_id",
",",
"id",
"=",
"context_id",
")"
]
| Removes a service subnet from 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 removal was successful. | [
"Removes",
"a",
"service",
"subnet",
"from",
"a",
"tunnel",
"context",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/ipsec.py#L189-L197 |
softlayer/softlayer-python | SoftLayer/managers/ipsec.py | IPSECManager.remove_translation | def remove_translation(self, context_id, translation_id):
"""Removes a translation entry from a tunnel context.
:param int context_id: The id-value representing the context instance.
:param int translation_id: The id-value representing the translation.
:return bool: True if translation entry removal was successful.
"""
return self.context.deleteAddressTranslation(translation_id,
id=context_id) | python | def remove_translation(self, context_id, translation_id):
return self.context.deleteAddressTranslation(translation_id,
id=context_id) | [
"def",
"remove_translation",
"(",
"self",
",",
"context_id",
",",
"translation_id",
")",
":",
"return",
"self",
".",
"context",
".",
"deleteAddressTranslation",
"(",
"translation_id",
",",
"id",
"=",
"context_id",
")"
]
| Removes a translation entry from a tunnel context.
:param int context_id: The id-value representing the context instance.
:param int translation_id: The id-value representing the translation.
:return bool: True if translation entry removal was successful. | [
"Removes",
"a",
"translation",
"entry",
"from",
"a",
"tunnel",
"context",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/ipsec.py#L199-L207 |
softlayer/softlayer-python | SoftLayer/managers/ipsec.py | IPSECManager.update_translation | def update_translation(self, context_id, translation_id, static_ip=None,
remote_ip=None, notes=None):
"""Updates an address translation entry using the given values.
:param int context_id: The id-value representing the context instance.
:param dict template: A key-value mapping of translation properties.
:param string static_ip: The static IP address value to update.
:param string remote_ip: The remote IP address value to update.
:param string notes: The notes value to update.
:return bool: True if the update was successful.
"""
translation = self.get_translation(context_id, translation_id)
if static_ip is not None:
translation['internalIpAddress'] = static_ip
translation.pop('internalIpAddressId', None)
if remote_ip is not None:
translation['customerIpAddress'] = remote_ip
translation.pop('customerIpAddressId', None)
if notes is not None:
translation['notes'] = notes
self.context.editAddressTranslation(translation, id=context_id)
return True | python | def update_translation(self, context_id, translation_id, static_ip=None,
remote_ip=None, notes=None):
translation = self.get_translation(context_id, translation_id)
if static_ip is not None:
translation['internalIpAddress'] = static_ip
translation.pop('internalIpAddressId', None)
if remote_ip is not None:
translation['customerIpAddress'] = remote_ip
translation.pop('customerIpAddressId', None)
if notes is not None:
translation['notes'] = notes
self.context.editAddressTranslation(translation, id=context_id)
return True | [
"def",
"update_translation",
"(",
"self",
",",
"context_id",
",",
"translation_id",
",",
"static_ip",
"=",
"None",
",",
"remote_ip",
"=",
"None",
",",
"notes",
"=",
"None",
")",
":",
"translation",
"=",
"self",
".",
"get_translation",
"(",
"context_id",
",",
"translation_id",
")",
"if",
"static_ip",
"is",
"not",
"None",
":",
"translation",
"[",
"'internalIpAddress'",
"]",
"=",
"static_ip",
"translation",
".",
"pop",
"(",
"'internalIpAddressId'",
",",
"None",
")",
"if",
"remote_ip",
"is",
"not",
"None",
":",
"translation",
"[",
"'customerIpAddress'",
"]",
"=",
"remote_ip",
"translation",
".",
"pop",
"(",
"'customerIpAddressId'",
",",
"None",
")",
"if",
"notes",
"is",
"not",
"None",
":",
"translation",
"[",
"'notes'",
"]",
"=",
"notes",
"self",
".",
"context",
".",
"editAddressTranslation",
"(",
"translation",
",",
"id",
"=",
"context_id",
")",
"return",
"True"
]
| Updates an address translation entry using the given values.
:param int context_id: The id-value representing the context instance.
:param dict template: A key-value mapping of translation properties.
:param string static_ip: The static IP address value to update.
:param string remote_ip: The remote IP address value to update.
:param string notes: The notes value to update.
:return bool: True if the update was successful. | [
"Updates",
"an",
"address",
"translation",
"entry",
"using",
"the",
"given",
"values",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/ipsec.py#L209-L231 |
softlayer/softlayer-python | SoftLayer/managers/ipsec.py | IPSECManager.update_tunnel_context | def update_tunnel_context(self, context_id, friendly_name=None,
remote_peer=None, preshared_key=None,
phase1_auth=None, phase1_crypto=None,
phase1_dh=None, phase1_key_ttl=None,
phase2_auth=None, phase2_crypto=None,
phase2_dh=None, phase2_forward_secrecy=None,
phase2_key_ttl=None):
"""Updates a tunnel context using the given values.
:param string context_id: The id-value representing the context.
:param string friendly_name: The friendly name value to update.
:param string remote_peer: The remote peer IP address value to update.
:param string preshared_key: The preshared key value to update.
:param string phase1_auth: The phase 1 authentication value to update.
:param string phase1_crypto: The phase 1 encryption value to update.
:param string phase1_dh: The phase 1 diffie hellman group value
to update.
:param string phase1_key_ttl: The phase 1 key life value to update.
:param string phase2_auth: The phase 2 authentication value to update.
:param string phase2_crypto: The phase 2 encryption value to update.
:param string phase2_df: The phase 2 diffie hellman group value
to update.
:param string phase2_forward_secriecy: The phase 2 perfect forward
secrecy value to update.
:param string phase2_key_ttl: The phase 2 key life value to update.
:return bool: True if the update was successful.
"""
context = self.get_tunnel_context(context_id)
if friendly_name is not None:
context['friendlyName'] = friendly_name
if remote_peer is not None:
context['customerPeerIpAddress'] = remote_peer
if preshared_key is not None:
context['presharedKey'] = preshared_key
if phase1_auth is not None:
context['phaseOneAuthentication'] = phase1_auth
if phase1_crypto is not None:
context['phaseOneEncryption'] = phase1_crypto
if phase1_dh is not None:
context['phaseOneDiffieHellmanGroup'] = phase1_dh
if phase1_key_ttl is not None:
context['phaseOneKeylife'] = phase1_key_ttl
if phase2_auth is not None:
context['phaseTwoAuthentication'] = phase2_auth
if phase2_crypto is not None:
context['phaseTwoEncryption'] = phase2_crypto
if phase2_dh is not None:
context['phaseTwoDiffieHellmanGroup'] = phase2_dh
if phase2_forward_secrecy is not None:
context['phaseTwoPerfectForwardSecrecy'] = phase2_forward_secrecy
if phase2_key_ttl is not None:
context['phaseTwoKeylife'] = phase2_key_ttl
return self.context.editObject(context, id=context_id) | python | def update_tunnel_context(self, context_id, friendly_name=None,
remote_peer=None, preshared_key=None,
phase1_auth=None, phase1_crypto=None,
phase1_dh=None, phase1_key_ttl=None,
phase2_auth=None, phase2_crypto=None,
phase2_dh=None, phase2_forward_secrecy=None,
phase2_key_ttl=None):
context = self.get_tunnel_context(context_id)
if friendly_name is not None:
context['friendlyName'] = friendly_name
if remote_peer is not None:
context['customerPeerIpAddress'] = remote_peer
if preshared_key is not None:
context['presharedKey'] = preshared_key
if phase1_auth is not None:
context['phaseOneAuthentication'] = phase1_auth
if phase1_crypto is not None:
context['phaseOneEncryption'] = phase1_crypto
if phase1_dh is not None:
context['phaseOneDiffieHellmanGroup'] = phase1_dh
if phase1_key_ttl is not None:
context['phaseOneKeylife'] = phase1_key_ttl
if phase2_auth is not None:
context['phaseTwoAuthentication'] = phase2_auth
if phase2_crypto is not None:
context['phaseTwoEncryption'] = phase2_crypto
if phase2_dh is not None:
context['phaseTwoDiffieHellmanGroup'] = phase2_dh
if phase2_forward_secrecy is not None:
context['phaseTwoPerfectForwardSecrecy'] = phase2_forward_secrecy
if phase2_key_ttl is not None:
context['phaseTwoKeylife'] = phase2_key_ttl
return self.context.editObject(context, id=context_id) | [
"def",
"update_tunnel_context",
"(",
"self",
",",
"context_id",
",",
"friendly_name",
"=",
"None",
",",
"remote_peer",
"=",
"None",
",",
"preshared_key",
"=",
"None",
",",
"phase1_auth",
"=",
"None",
",",
"phase1_crypto",
"=",
"None",
",",
"phase1_dh",
"=",
"None",
",",
"phase1_key_ttl",
"=",
"None",
",",
"phase2_auth",
"=",
"None",
",",
"phase2_crypto",
"=",
"None",
",",
"phase2_dh",
"=",
"None",
",",
"phase2_forward_secrecy",
"=",
"None",
",",
"phase2_key_ttl",
"=",
"None",
")",
":",
"context",
"=",
"self",
".",
"get_tunnel_context",
"(",
"context_id",
")",
"if",
"friendly_name",
"is",
"not",
"None",
":",
"context",
"[",
"'friendlyName'",
"]",
"=",
"friendly_name",
"if",
"remote_peer",
"is",
"not",
"None",
":",
"context",
"[",
"'customerPeerIpAddress'",
"]",
"=",
"remote_peer",
"if",
"preshared_key",
"is",
"not",
"None",
":",
"context",
"[",
"'presharedKey'",
"]",
"=",
"preshared_key",
"if",
"phase1_auth",
"is",
"not",
"None",
":",
"context",
"[",
"'phaseOneAuthentication'",
"]",
"=",
"phase1_auth",
"if",
"phase1_crypto",
"is",
"not",
"None",
":",
"context",
"[",
"'phaseOneEncryption'",
"]",
"=",
"phase1_crypto",
"if",
"phase1_dh",
"is",
"not",
"None",
":",
"context",
"[",
"'phaseOneDiffieHellmanGroup'",
"]",
"=",
"phase1_dh",
"if",
"phase1_key_ttl",
"is",
"not",
"None",
":",
"context",
"[",
"'phaseOneKeylife'",
"]",
"=",
"phase1_key_ttl",
"if",
"phase2_auth",
"is",
"not",
"None",
":",
"context",
"[",
"'phaseTwoAuthentication'",
"]",
"=",
"phase2_auth",
"if",
"phase2_crypto",
"is",
"not",
"None",
":",
"context",
"[",
"'phaseTwoEncryption'",
"]",
"=",
"phase2_crypto",
"if",
"phase2_dh",
"is",
"not",
"None",
":",
"context",
"[",
"'phaseTwoDiffieHellmanGroup'",
"]",
"=",
"phase2_dh",
"if",
"phase2_forward_secrecy",
"is",
"not",
"None",
":",
"context",
"[",
"'phaseTwoPerfectForwardSecrecy'",
"]",
"=",
"phase2_forward_secrecy",
"if",
"phase2_key_ttl",
"is",
"not",
"None",
":",
"context",
"[",
"'phaseTwoKeylife'",
"]",
"=",
"phase2_key_ttl",
"return",
"self",
".",
"context",
".",
"editObject",
"(",
"context",
",",
"id",
"=",
"context_id",
")"
]
| Updates a tunnel context using the given values.
:param string context_id: The id-value representing the context.
:param string friendly_name: The friendly name value to update.
:param string remote_peer: The remote peer IP address value to update.
:param string preshared_key: The preshared key value to update.
:param string phase1_auth: The phase 1 authentication value to update.
:param string phase1_crypto: The phase 1 encryption value to update.
:param string phase1_dh: The phase 1 diffie hellman group value
to update.
:param string phase1_key_ttl: The phase 1 key life value to update.
:param string phase2_auth: The phase 2 authentication value to update.
:param string phase2_crypto: The phase 2 encryption value to update.
:param string phase2_df: The phase 2 diffie hellman group value
to update.
:param string phase2_forward_secriecy: The phase 2 perfect forward
secrecy value to update.
:param string phase2_key_ttl: The phase 2 key life value to update.
:return bool: True if the update was successful. | [
"Updates",
"a",
"tunnel",
"context",
"using",
"the",
"given",
"values",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/ipsec.py#L233-L286 |
softlayer/softlayer-python | SoftLayer/CLI/object_storage/credential/create.py | cli | def cli(env, identifier):
"""Create credentials for an IBM Cloud Object Storage Account"""
mgr = SoftLayer.ObjectStorageManager(env.client)
credential = mgr.create_credential(identifier)
table = formatting.Table(['id', 'password', 'username', 'type_name'])
table.sortby = 'id'
table.add_row([
credential['id'],
credential['password'],
credential['username'],
credential['type']['name']
])
env.fout(table) | python | def cli(env, identifier):
mgr = SoftLayer.ObjectStorageManager(env.client)
credential = mgr.create_credential(identifier)
table = formatting.Table(['id', 'password', 'username', 'type_name'])
table.sortby = 'id'
table.add_row([
credential['id'],
credential['password'],
credential['username'],
credential['type']['name']
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"ObjectStorageManager",
"(",
"env",
".",
"client",
")",
"credential",
"=",
"mgr",
".",
"create_credential",
"(",
"identifier",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'password'",
",",
"'username'",
",",
"'type_name'",
"]",
")",
"table",
".",
"sortby",
"=",
"'id'",
"table",
".",
"add_row",
"(",
"[",
"credential",
"[",
"'id'",
"]",
",",
"credential",
"[",
"'password'",
"]",
",",
"credential",
"[",
"'username'",
"]",
",",
"credential",
"[",
"'type'",
"]",
"[",
"'name'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Create credentials for an IBM Cloud Object Storage Account | [
"Create",
"credentials",
"for",
"an",
"IBM",
"Cloud",
"Object",
"Storage",
"Account"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/object_storage/credential/create.py#L14-L28 |
softlayer/softlayer-python | SoftLayer/CLI/image/list.py | cli | def cli(env, name, public):
"""List images."""
image_mgr = SoftLayer.ImageManager(env.client)
images = []
if public in [False, None]:
for image in image_mgr.list_private_images(name=name,
mask=image_mod.MASK):
images.append(image)
if public in [True, None]:
for image in image_mgr.list_public_images(name=name,
mask=image_mod.MASK):
images.append(image)
table = formatting.Table(['id',
'name',
'type',
'visibility',
'account'])
images = [image for image in images if image['parentId'] == '']
for image in images:
visibility = (image_mod.PUBLIC_TYPE if image['publicFlag']
else image_mod.PRIVATE_TYPE)
table.add_row([
image.get('id', formatting.blank()),
formatting.FormattedItem(image['name'],
click.wrap_text(image['name'], width=50)),
formatting.FormattedItem(
utils.lookup(image, 'imageType', 'keyName'),
utils.lookup(image, 'imageType', 'name')),
visibility,
image.get('accountId', formatting.blank()),
])
env.fout(table) | python | def cli(env, name, public):
image_mgr = SoftLayer.ImageManager(env.client)
images = []
if public in [False, None]:
for image in image_mgr.list_private_images(name=name,
mask=image_mod.MASK):
images.append(image)
if public in [True, None]:
for image in image_mgr.list_public_images(name=name,
mask=image_mod.MASK):
images.append(image)
table = formatting.Table(['id',
'name',
'type',
'visibility',
'account'])
images = [image for image in images if image['parentId'] == '']
for image in images:
visibility = (image_mod.PUBLIC_TYPE if image['publicFlag']
else image_mod.PRIVATE_TYPE)
table.add_row([
image.get('id', formatting.blank()),
formatting.FormattedItem(image['name'],
click.wrap_text(image['name'], width=50)),
formatting.FormattedItem(
utils.lookup(image, 'imageType', 'keyName'),
utils.lookup(image, 'imageType', 'name')),
visibility,
image.get('accountId', formatting.blank()),
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"name",
",",
"public",
")",
":",
"image_mgr",
"=",
"SoftLayer",
".",
"ImageManager",
"(",
"env",
".",
"client",
")",
"images",
"=",
"[",
"]",
"if",
"public",
"in",
"[",
"False",
",",
"None",
"]",
":",
"for",
"image",
"in",
"image_mgr",
".",
"list_private_images",
"(",
"name",
"=",
"name",
",",
"mask",
"=",
"image_mod",
".",
"MASK",
")",
":",
"images",
".",
"append",
"(",
"image",
")",
"if",
"public",
"in",
"[",
"True",
",",
"None",
"]",
":",
"for",
"image",
"in",
"image_mgr",
".",
"list_public_images",
"(",
"name",
"=",
"name",
",",
"mask",
"=",
"image_mod",
".",
"MASK",
")",
":",
"images",
".",
"append",
"(",
"image",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'name'",
",",
"'type'",
",",
"'visibility'",
",",
"'account'",
"]",
")",
"images",
"=",
"[",
"image",
"for",
"image",
"in",
"images",
"if",
"image",
"[",
"'parentId'",
"]",
"==",
"''",
"]",
"for",
"image",
"in",
"images",
":",
"visibility",
"=",
"(",
"image_mod",
".",
"PUBLIC_TYPE",
"if",
"image",
"[",
"'publicFlag'",
"]",
"else",
"image_mod",
".",
"PRIVATE_TYPE",
")",
"table",
".",
"add_row",
"(",
"[",
"image",
".",
"get",
"(",
"'id'",
",",
"formatting",
".",
"blank",
"(",
")",
")",
",",
"formatting",
".",
"FormattedItem",
"(",
"image",
"[",
"'name'",
"]",
",",
"click",
".",
"wrap_text",
"(",
"image",
"[",
"'name'",
"]",
",",
"width",
"=",
"50",
")",
")",
",",
"formatting",
".",
"FormattedItem",
"(",
"utils",
".",
"lookup",
"(",
"image",
",",
"'imageType'",
",",
"'keyName'",
")",
",",
"utils",
".",
"lookup",
"(",
"image",
",",
"'imageType'",
",",
"'name'",
")",
")",
",",
"visibility",
",",
"image",
".",
"get",
"(",
"'accountId'",
",",
"formatting",
".",
"blank",
"(",
")",
")",
",",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| List images. | [
"List",
"images",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/image/list.py#L20-L58 |
softlayer/softlayer-python | SoftLayer/CLI/vpn/ipsec/subnet/add.py | cli | def cli(env, context_id, subnet_id, subnet_type, network_identifier):
"""Add a subnet to an IPSEC tunnel context.
A subnet id may be specified to link to the existing tunnel context.
Otherwise, a network identifier in CIDR notation should be specified,
indicating that a subnet resource should first be created before associating
it with the tunnel context. Note that this is only supported for remote
subnets, which are also deleted upon failure to attach to a context.
A separate configuration request should be made to realize changes on
network devices.
"""
create_remote = False
if subnet_id is None:
if network_identifier is None:
raise ArgumentError('Either a network identifier or subnet id '
'must be provided.')
if subnet_type != 'remote':
raise ArgumentError('Unable to create {} subnets'
.format(subnet_type))
create_remote = True
manager = SoftLayer.IPSECManager(env.client)
context = manager.get_tunnel_context(context_id)
if create_remote:
subnet = manager.create_remote_subnet(context['accountId'],
identifier=network_identifier[0],
cidr=network_identifier[1])
subnet_id = subnet['id']
env.out('Created subnet {}/{} #{}'
.format(network_identifier[0],
network_identifier[1],
subnet_id))
succeeded = False
if subnet_type == 'internal':
succeeded = manager.add_internal_subnet(context_id, subnet_id)
elif subnet_type == 'remote':
succeeded = manager.add_remote_subnet(context_id, subnet_id)
elif subnet_type == 'service':
succeeded = manager.add_service_subnet(context_id, subnet_id)
if succeeded:
env.out('Added {} subnet #{}'.format(subnet_type, subnet_id))
else:
raise CLIHalt('Failed to add {} subnet #{}'
.format(subnet_type, subnet_id)) | python | def cli(env, context_id, subnet_id, subnet_type, network_identifier):
create_remote = False
if subnet_id is None:
if network_identifier is None:
raise ArgumentError('Either a network identifier or subnet id '
'must be provided.')
if subnet_type != 'remote':
raise ArgumentError('Unable to create {} subnets'
.format(subnet_type))
create_remote = True
manager = SoftLayer.IPSECManager(env.client)
context = manager.get_tunnel_context(context_id)
if create_remote:
subnet = manager.create_remote_subnet(context['accountId'],
identifier=network_identifier[0],
cidr=network_identifier[1])
subnet_id = subnet['id']
env.out('Created subnet {}/{}
.format(network_identifier[0],
network_identifier[1],
subnet_id))
succeeded = False
if subnet_type == 'internal':
succeeded = manager.add_internal_subnet(context_id, subnet_id)
elif subnet_type == 'remote':
succeeded = manager.add_remote_subnet(context_id, subnet_id)
elif subnet_type == 'service':
succeeded = manager.add_service_subnet(context_id, subnet_id)
if succeeded:
env.out('Added {} subnet
else:
raise CLIHalt('Failed to add {} subnet
.format(subnet_type, subnet_id)) | [
"def",
"cli",
"(",
"env",
",",
"context_id",
",",
"subnet_id",
",",
"subnet_type",
",",
"network_identifier",
")",
":",
"create_remote",
"=",
"False",
"if",
"subnet_id",
"is",
"None",
":",
"if",
"network_identifier",
"is",
"None",
":",
"raise",
"ArgumentError",
"(",
"'Either a network identifier or subnet id '",
"'must be provided.'",
")",
"if",
"subnet_type",
"!=",
"'remote'",
":",
"raise",
"ArgumentError",
"(",
"'Unable to create {} subnets'",
".",
"format",
"(",
"subnet_type",
")",
")",
"create_remote",
"=",
"True",
"manager",
"=",
"SoftLayer",
".",
"IPSECManager",
"(",
"env",
".",
"client",
")",
"context",
"=",
"manager",
".",
"get_tunnel_context",
"(",
"context_id",
")",
"if",
"create_remote",
":",
"subnet",
"=",
"manager",
".",
"create_remote_subnet",
"(",
"context",
"[",
"'accountId'",
"]",
",",
"identifier",
"=",
"network_identifier",
"[",
"0",
"]",
",",
"cidr",
"=",
"network_identifier",
"[",
"1",
"]",
")",
"subnet_id",
"=",
"subnet",
"[",
"'id'",
"]",
"env",
".",
"out",
"(",
"'Created subnet {}/{} #{}'",
".",
"format",
"(",
"network_identifier",
"[",
"0",
"]",
",",
"network_identifier",
"[",
"1",
"]",
",",
"subnet_id",
")",
")",
"succeeded",
"=",
"False",
"if",
"subnet_type",
"==",
"'internal'",
":",
"succeeded",
"=",
"manager",
".",
"add_internal_subnet",
"(",
"context_id",
",",
"subnet_id",
")",
"elif",
"subnet_type",
"==",
"'remote'",
":",
"succeeded",
"=",
"manager",
".",
"add_remote_subnet",
"(",
"context_id",
",",
"subnet_id",
")",
"elif",
"subnet_type",
"==",
"'service'",
":",
"succeeded",
"=",
"manager",
".",
"add_service_subnet",
"(",
"context_id",
",",
"subnet_id",
")",
"if",
"succeeded",
":",
"env",
".",
"out",
"(",
"'Added {} subnet #{}'",
".",
"format",
"(",
"subnet_type",
",",
"subnet_id",
")",
")",
"else",
":",
"raise",
"CLIHalt",
"(",
"'Failed to add {} subnet #{}'",
".",
"format",
"(",
"subnet_type",
",",
"subnet_id",
")",
")"
]
| Add a subnet to an IPSEC tunnel context.
A subnet id may be specified to link to the existing tunnel context.
Otherwise, a network identifier in CIDR notation should be specified,
indicating that a subnet resource should first be created before associating
it with the tunnel context. Note that this is only supported for remote
subnets, which are also deleted upon failure to attach to a context.
A separate configuration request should be made to realize changes on
network devices. | [
"Add",
"a",
"subnet",
"to",
"an",
"IPSEC",
"tunnel",
"context",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/subnet/add.py#L33-L81 |
softlayer/softlayer-python | SoftLayer/CLI/virt/placementgroup/list.py | cli | def cli(env):
"""List placement groups."""
manager = PlacementManager(env.client)
result = manager.list()
table = formatting.Table(
["Id", "Name", "Backend Router", "Rule", "Guests", "Created"],
title="Placement Groups"
)
for group in result:
table.add_row([
group['id'],
group['name'],
group['backendRouter']['hostname'],
group['rule']['name'],
group['guestCount'],
group['createDate']
])
env.fout(table) | python | def cli(env):
manager = PlacementManager(env.client)
result = manager.list()
table = formatting.Table(
["Id", "Name", "Backend Router", "Rule", "Guests", "Created"],
title="Placement Groups"
)
for group in result:
table.add_row([
group['id'],
group['name'],
group['backendRouter']['hostname'],
group['rule']['name'],
group['guestCount'],
group['createDate']
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
")",
":",
"manager",
"=",
"PlacementManager",
"(",
"env",
".",
"client",
")",
"result",
"=",
"manager",
".",
"list",
"(",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"\"Id\"",
",",
"\"Name\"",
",",
"\"Backend Router\"",
",",
"\"Rule\"",
",",
"\"Guests\"",
",",
"\"Created\"",
"]",
",",
"title",
"=",
"\"Placement Groups\"",
")",
"for",
"group",
"in",
"result",
":",
"table",
".",
"add_row",
"(",
"[",
"group",
"[",
"'id'",
"]",
",",
"group",
"[",
"'name'",
"]",
",",
"group",
"[",
"'backendRouter'",
"]",
"[",
"'hostname'",
"]",
",",
"group",
"[",
"'rule'",
"]",
"[",
"'name'",
"]",
",",
"group",
"[",
"'guestCount'",
"]",
",",
"group",
"[",
"'createDate'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| List placement groups. | [
"List",
"placement",
"groups",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/placementgroup/list.py#L12-L30 |
softlayer/softlayer-python | SoftLayer/CLI/account/events.py | cli | def cli(env, ack_all):
"""Summary and acknowledgement of upcoming and ongoing maintenance events"""
manager = AccountManager(env.client)
events = manager.get_upcoming_events()
if ack_all:
for event in events:
result = manager.ack_event(event['id'])
event['acknowledgedFlag'] = result
env.fout(event_table(events)) | python | def cli(env, ack_all):
manager = AccountManager(env.client)
events = manager.get_upcoming_events()
if ack_all:
for event in events:
result = manager.ack_event(event['id'])
event['acknowledgedFlag'] = result
env.fout(event_table(events)) | [
"def",
"cli",
"(",
"env",
",",
"ack_all",
")",
":",
"manager",
"=",
"AccountManager",
"(",
"env",
".",
"client",
")",
"events",
"=",
"manager",
".",
"get_upcoming_events",
"(",
")",
"if",
"ack_all",
":",
"for",
"event",
"in",
"events",
":",
"result",
"=",
"manager",
".",
"ack_event",
"(",
"event",
"[",
"'id'",
"]",
")",
"event",
"[",
"'acknowledgedFlag'",
"]",
"=",
"result",
"env",
".",
"fout",
"(",
"event_table",
"(",
"events",
")",
")"
]
| Summary and acknowledgement of upcoming and ongoing maintenance events | [
"Summary",
"and",
"acknowledgement",
"of",
"upcoming",
"and",
"ongoing",
"maintenance",
"events"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/events.py#L15-L25 |
softlayer/softlayer-python | SoftLayer/CLI/account/events.py | event_table | def event_table(events):
"""Formats a table for events"""
table = formatting.Table([
"Id",
"Start Date",
"End Date",
"Subject",
"Status",
"Acknowledged",
"Updates",
"Impacted Resources"
], title="Upcoming Events")
table.align['Subject'] = 'l'
table.align['Impacted Resources'] = 'l'
for event in events:
table.add_row([
event.get('id'),
utils.clean_time(event.get('startDate')),
utils.clean_time(event.get('endDate')),
# Some subjects can have \r\n for some reason.
utils.clean_splitlines(event.get('subject')),
utils.lookup(event, 'statusCode', 'name'),
event.get('acknowledgedFlag'),
event.get('updateCount'),
event.get('impactedResourceCount')
])
return table | python | def event_table(events):
table = formatting.Table([
"Id",
"Start Date",
"End Date",
"Subject",
"Status",
"Acknowledged",
"Updates",
"Impacted Resources"
], title="Upcoming Events")
table.align['Subject'] = 'l'
table.align['Impacted Resources'] = 'l'
for event in events:
table.add_row([
event.get('id'),
utils.clean_time(event.get('startDate')),
utils.clean_time(event.get('endDate')),
utils.clean_splitlines(event.get('subject')),
utils.lookup(event, 'statusCode', 'name'),
event.get('acknowledgedFlag'),
event.get('updateCount'),
event.get('impactedResourceCount')
])
return table | [
"def",
"event_table",
"(",
"events",
")",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"\"Id\"",
",",
"\"Start Date\"",
",",
"\"End Date\"",
",",
"\"Subject\"",
",",
"\"Status\"",
",",
"\"Acknowledged\"",
",",
"\"Updates\"",
",",
"\"Impacted Resources\"",
"]",
",",
"title",
"=",
"\"Upcoming Events\"",
")",
"table",
".",
"align",
"[",
"'Subject'",
"]",
"=",
"'l'",
"table",
".",
"align",
"[",
"'Impacted Resources'",
"]",
"=",
"'l'",
"for",
"event",
"in",
"events",
":",
"table",
".",
"add_row",
"(",
"[",
"event",
".",
"get",
"(",
"'id'",
")",
",",
"utils",
".",
"clean_time",
"(",
"event",
".",
"get",
"(",
"'startDate'",
")",
")",
",",
"utils",
".",
"clean_time",
"(",
"event",
".",
"get",
"(",
"'endDate'",
")",
")",
",",
"# Some subjects can have \\r\\n for some reason.",
"utils",
".",
"clean_splitlines",
"(",
"event",
".",
"get",
"(",
"'subject'",
")",
")",
",",
"utils",
".",
"lookup",
"(",
"event",
",",
"'statusCode'",
",",
"'name'",
")",
",",
"event",
".",
"get",
"(",
"'acknowledgedFlag'",
")",
",",
"event",
".",
"get",
"(",
"'updateCount'",
")",
",",
"event",
".",
"get",
"(",
"'impactedResourceCount'",
")",
"]",
")",
"return",
"table"
]
| Formats a table for events | [
"Formats",
"a",
"table",
"for",
"events"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/events.py#L28-L54 |
softlayer/softlayer-python | SoftLayer/CLI/block/access/password.py | cli | def cli(env, access_id, password):
"""Changes a password for a volume's access.
access id is the allowed_host_id from slcli block access-list
"""
block_manager = SoftLayer.BlockStorageManager(env.client)
result = block_manager.set_credential_password(access_id=access_id, password=password)
if result:
click.echo('Password updated for %s' % access_id)
else:
click.echo('FAILED updating password for %s' % access_id) | python | def cli(env, access_id, password):
block_manager = SoftLayer.BlockStorageManager(env.client)
result = block_manager.set_credential_password(access_id=access_id, password=password)
if result:
click.echo('Password updated for %s' % access_id)
else:
click.echo('FAILED updating password for %s' % access_id) | [
"def",
"cli",
"(",
"env",
",",
"access_id",
",",
"password",
")",
":",
"block_manager",
"=",
"SoftLayer",
".",
"BlockStorageManager",
"(",
"env",
".",
"client",
")",
"result",
"=",
"block_manager",
".",
"set_credential_password",
"(",
"access_id",
"=",
"access_id",
",",
"password",
"=",
"password",
")",
"if",
"result",
":",
"click",
".",
"echo",
"(",
"'Password updated for %s'",
"%",
"access_id",
")",
"else",
":",
"click",
".",
"echo",
"(",
"'FAILED updating password for %s'",
"%",
"access_id",
")"
]
| Changes a password for a volume's access.
access id is the allowed_host_id from slcli block access-list | [
"Changes",
"a",
"password",
"for",
"a",
"volume",
"s",
"access",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/access/password.py#L14-L27 |
softlayer/softlayer-python | SoftLayer/CLI/cdn/detail.py | cli | def cli(env, account_id):
"""Detail a CDN Account."""
manager = SoftLayer.CDNManager(env.client)
account = manager.get_account(account_id)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', account['id']])
table.add_row(['account_name', account['cdnAccountName']])
table.add_row(['type', account['cdnSolutionName']])
table.add_row(['status', account['status']['name']])
table.add_row(['created', account['createDate']])
table.add_row(['notes',
account.get('cdnAccountNote', formatting.blank())])
env.fout(table) | python | def cli(env, account_id):
manager = SoftLayer.CDNManager(env.client)
account = manager.get_account(account_id)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', account['id']])
table.add_row(['account_name', account['cdnAccountName']])
table.add_row(['type', account['cdnSolutionName']])
table.add_row(['status', account['status']['name']])
table.add_row(['created', account['createDate']])
table.add_row(['notes',
account.get('cdnAccountNote', formatting.blank())])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"account_id",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"CDNManager",
"(",
"env",
".",
"client",
")",
"account",
"=",
"manager",
".",
"get_account",
"(",
"account_id",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"account",
"[",
"'id'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'account_name'",
",",
"account",
"[",
"'cdnAccountName'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'type'",
",",
"account",
"[",
"'cdnSolutionName'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'status'",
",",
"account",
"[",
"'status'",
"]",
"[",
"'name'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'created'",
",",
"account",
"[",
"'createDate'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'notes'",
",",
"account",
".",
"get",
"(",
"'cdnAccountNote'",
",",
"formatting",
".",
"blank",
"(",
")",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Detail a CDN Account. | [
"Detail",
"a",
"CDN",
"Account",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/cdn/detail.py#L14-L32 |
softlayer/softlayer-python | SoftLayer/utils.py | lookup | def lookup(dic, key, *keys):
"""A generic dictionary access helper.
This helps simplify code that uses heavily nested dictionaries. It will
return None if any of the keys in *keys do not exist.
::
>>> lookup({'this': {'is': 'nested'}}, 'this', 'is')
nested
>>> lookup({}, 'this', 'is')
None
"""
if keys:
return lookup(dic.get(key, {}), keys[0], *keys[1:])
return dic.get(key) | python | def lookup(dic, key, *keys):
if keys:
return lookup(dic.get(key, {}), keys[0], *keys[1:])
return dic.get(key) | [
"def",
"lookup",
"(",
"dic",
",",
"key",
",",
"*",
"keys",
")",
":",
"if",
"keys",
":",
"return",
"lookup",
"(",
"dic",
".",
"get",
"(",
"key",
",",
"{",
"}",
")",
",",
"keys",
"[",
"0",
"]",
",",
"*",
"keys",
"[",
"1",
":",
"]",
")",
"return",
"dic",
".",
"get",
"(",
"key",
")"
]
| A generic dictionary access helper.
This helps simplify code that uses heavily nested dictionaries. It will
return None if any of the keys in *keys do not exist.
::
>>> lookup({'this': {'is': 'nested'}}, 'this', 'is')
nested
>>> lookup({}, 'this', 'is')
None | [
"A",
"generic",
"dictionary",
"access",
"helper",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/utils.py#L24-L41 |
softlayer/softlayer-python | SoftLayer/utils.py | query_filter | def query_filter(query):
"""Translate a query-style string to a 'filter'.
Query can be the following formats:
Case Insensitive
'value' OR '*= value' Contains
'value*' OR '^= value' Begins with value
'*value' OR '$= value' Ends with value
'*value*' OR '_= value' Contains value
Case Sensitive
'~ value' Contains
'!~ value' Does not contain
'> value' Greater than value
'< value' Less than value
'>= value' Greater than or equal to value
'<= value' Less than or equal to value
:param string query: query string
"""
try:
return {'operation': int(query)}
except ValueError:
pass
if isinstance(query, string_types):
query = query.strip()
for operation in KNOWN_OPERATIONS:
if query.startswith(operation):
query = "%s %s" % (operation, query[len(operation):].strip())
return {'operation': query}
if query.startswith('*') and query.endswith('*'):
query = "*= %s" % query.strip('*')
elif query.startswith('*'):
query = "$= %s" % query.strip('*')
elif query.endswith('*'):
query = "^= %s" % query.strip('*')
else:
query = "_= %s" % query
return {'operation': query} | python | def query_filter(query):
try:
return {'operation': int(query)}
except ValueError:
pass
if isinstance(query, string_types):
query = query.strip()
for operation in KNOWN_OPERATIONS:
if query.startswith(operation):
query = "%s %s" % (operation, query[len(operation):].strip())
return {'operation': query}
if query.startswith('*') and query.endswith('*'):
query = "*= %s" % query.strip('*')
elif query.startswith('*'):
query = "$= %s" % query.strip('*')
elif query.endswith('*'):
query = "^= %s" % query.strip('*')
else:
query = "_= %s" % query
return {'operation': query} | [
"def",
"query_filter",
"(",
"query",
")",
":",
"try",
":",
"return",
"{",
"'operation'",
":",
"int",
"(",
"query",
")",
"}",
"except",
"ValueError",
":",
"pass",
"if",
"isinstance",
"(",
"query",
",",
"string_types",
")",
":",
"query",
"=",
"query",
".",
"strip",
"(",
")",
"for",
"operation",
"in",
"KNOWN_OPERATIONS",
":",
"if",
"query",
".",
"startswith",
"(",
"operation",
")",
":",
"query",
"=",
"\"%s %s\"",
"%",
"(",
"operation",
",",
"query",
"[",
"len",
"(",
"operation",
")",
":",
"]",
".",
"strip",
"(",
")",
")",
"return",
"{",
"'operation'",
":",
"query",
"}",
"if",
"query",
".",
"startswith",
"(",
"'*'",
")",
"and",
"query",
".",
"endswith",
"(",
"'*'",
")",
":",
"query",
"=",
"\"*= %s\"",
"%",
"query",
".",
"strip",
"(",
"'*'",
")",
"elif",
"query",
".",
"startswith",
"(",
"'*'",
")",
":",
"query",
"=",
"\"$= %s\"",
"%",
"query",
".",
"strip",
"(",
"'*'",
")",
"elif",
"query",
".",
"endswith",
"(",
"'*'",
")",
":",
"query",
"=",
"\"^= %s\"",
"%",
"query",
".",
"strip",
"(",
"'*'",
")",
"else",
":",
"query",
"=",
"\"_= %s\"",
"%",
"query",
"return",
"{",
"'operation'",
":",
"query",
"}"
]
| Translate a query-style string to a 'filter'.
Query can be the following formats:
Case Insensitive
'value' OR '*= value' Contains
'value*' OR '^= value' Begins with value
'*value' OR '$= value' Ends with value
'*value*' OR '_= value' Contains value
Case Sensitive
'~ value' Contains
'!~ value' Does not contain
'> value' Greater than value
'< value' Less than value
'>= value' Greater than or equal to value
'<= value' Less than or equal to value
:param string query: query string | [
"Translate",
"a",
"query",
"-",
"style",
"string",
"to",
"a",
"filter",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/utils.py#L66-L108 |
softlayer/softlayer-python | SoftLayer/utils.py | query_filter_date | def query_filter_date(start, end):
"""Query filters given start and end date.
:param start:YY-MM-DD
:param end: YY-MM-DD
"""
sdate = datetime.datetime.strptime(start, "%Y-%m-%d")
edate = datetime.datetime.strptime(end, "%Y-%m-%d")
startdate = "%s/%s/%s" % (sdate.month, sdate.day, sdate.year)
enddate = "%s/%s/%s" % (edate.month, edate.day, edate.year)
return {
'operation': 'betweenDate',
'options': [
{'name': 'startDate', 'value': [startdate + ' 0:0:0']},
{'name': 'endDate', 'value': [enddate + ' 0:0:0']}
]
} | python | def query_filter_date(start, end):
sdate = datetime.datetime.strptime(start, "%Y-%m-%d")
edate = datetime.datetime.strptime(end, "%Y-%m-%d")
startdate = "%s/%s/%s" % (sdate.month, sdate.day, sdate.year)
enddate = "%s/%s/%s" % (edate.month, edate.day, edate.year)
return {
'operation': 'betweenDate',
'options': [
{'name': 'startDate', 'value': [startdate + ' 0:0:0']},
{'name': 'endDate', 'value': [enddate + ' 0:0:0']}
]
} | [
"def",
"query_filter_date",
"(",
"start",
",",
"end",
")",
":",
"sdate",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"start",
",",
"\"%Y-%m-%d\"",
")",
"edate",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"end",
",",
"\"%Y-%m-%d\"",
")",
"startdate",
"=",
"\"%s/%s/%s\"",
"%",
"(",
"sdate",
".",
"month",
",",
"sdate",
".",
"day",
",",
"sdate",
".",
"year",
")",
"enddate",
"=",
"\"%s/%s/%s\"",
"%",
"(",
"edate",
".",
"month",
",",
"edate",
".",
"day",
",",
"edate",
".",
"year",
")",
"return",
"{",
"'operation'",
":",
"'betweenDate'",
",",
"'options'",
":",
"[",
"{",
"'name'",
":",
"'startDate'",
",",
"'value'",
":",
"[",
"startdate",
"+",
"' 0:0:0'",
"]",
"}",
",",
"{",
"'name'",
":",
"'endDate'",
",",
"'value'",
":",
"[",
"enddate",
"+",
"' 0:0:0'",
"]",
"}",
"]",
"}"
]
| Query filters given start and end date.
:param start:YY-MM-DD
:param end: YY-MM-DD | [
"Query",
"filters",
"given",
"start",
"and",
"end",
"date",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/utils.py#L111-L127 |
softlayer/softlayer-python | SoftLayer/utils.py | format_event_log_date | def format_event_log_date(date_string, utc):
"""Gets a date in the format that the SoftLayer_EventLog object likes.
:param string date_string: date in mm/dd/yyyy format
:param string utc: utc offset. Defaults to '+0000'
"""
user_date_format = "%m/%d/%Y"
user_date = datetime.datetime.strptime(date_string, user_date_format)
dirty_time = user_date.isoformat()
if utc is None:
utc = "+0000"
iso_time_zone = utc[:3] + ':' + utc[3:]
cleaned_time = "{}.000000{}".format(dirty_time, iso_time_zone)
return cleaned_time | python | def format_event_log_date(date_string, utc):
user_date_format = "%m/%d/%Y"
user_date = datetime.datetime.strptime(date_string, user_date_format)
dirty_time = user_date.isoformat()
if utc is None:
utc = "+0000"
iso_time_zone = utc[:3] + ':' + utc[3:]
cleaned_time = "{}.000000{}".format(dirty_time, iso_time_zone)
return cleaned_time | [
"def",
"format_event_log_date",
"(",
"date_string",
",",
"utc",
")",
":",
"user_date_format",
"=",
"\"%m/%d/%Y\"",
"user_date",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"date_string",
",",
"user_date_format",
")",
"dirty_time",
"=",
"user_date",
".",
"isoformat",
"(",
")",
"if",
"utc",
"is",
"None",
":",
"utc",
"=",
"\"+0000\"",
"iso_time_zone",
"=",
"utc",
"[",
":",
"3",
"]",
"+",
"':'",
"+",
"utc",
"[",
"3",
":",
"]",
"cleaned_time",
"=",
"\"{}.000000{}\"",
".",
"format",
"(",
"dirty_time",
",",
"iso_time_zone",
")",
"return",
"cleaned_time"
]
| Gets a date in the format that the SoftLayer_EventLog object likes.
:param string date_string: date in mm/dd/yyyy format
:param string utc: utc offset. Defaults to '+0000' | [
"Gets",
"a",
"date",
"in",
"the",
"format",
"that",
"the",
"SoftLayer_EventLog",
"object",
"likes",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/utils.py#L130-L147 |
softlayer/softlayer-python | SoftLayer/utils.py | event_log_filter_between_date | def event_log_filter_between_date(start, end, utc):
"""betweenDate Query filter that SoftLayer_EventLog likes
:param string start: lower bound date in mm/dd/yyyy format
:param string end: upper bound date in mm/dd/yyyy format
:param string utc: utc offset. Defaults to '+0000'
"""
return {
'operation': 'betweenDate',
'options': [
{'name': 'startDate', 'value': [format_event_log_date(start, utc)]},
{'name': 'endDate', 'value': [format_event_log_date(end, utc)]}
]
} | python | def event_log_filter_between_date(start, end, utc):
return {
'operation': 'betweenDate',
'options': [
{'name': 'startDate', 'value': [format_event_log_date(start, utc)]},
{'name': 'endDate', 'value': [format_event_log_date(end, utc)]}
]
} | [
"def",
"event_log_filter_between_date",
"(",
"start",
",",
"end",
",",
"utc",
")",
":",
"return",
"{",
"'operation'",
":",
"'betweenDate'",
",",
"'options'",
":",
"[",
"{",
"'name'",
":",
"'startDate'",
",",
"'value'",
":",
"[",
"format_event_log_date",
"(",
"start",
",",
"utc",
")",
"]",
"}",
",",
"{",
"'name'",
":",
"'endDate'",
",",
"'value'",
":",
"[",
"format_event_log_date",
"(",
"end",
",",
"utc",
")",
"]",
"}",
"]",
"}"
]
| betweenDate Query filter that SoftLayer_EventLog likes
:param string start: lower bound date in mm/dd/yyyy format
:param string end: upper bound date in mm/dd/yyyy format
:param string utc: utc offset. Defaults to '+0000' | [
"betweenDate",
"Query",
"filter",
"that",
"SoftLayer_EventLog",
"likes"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/utils.py#L150-L163 |
softlayer/softlayer-python | SoftLayer/utils.py | resolve_ids | def resolve_ids(identifier, resolvers):
"""Resolves IDs given a list of functions.
:param string identifier: identifier string
:param list resolvers: a list of functions
:returns list:
"""
# Before doing anything, let's see if this is an integer
try:
return [int(identifier)]
except ValueError:
pass # It was worth a shot
# This looks like a globalIdentifier (UUID)
if len(identifier) == 36 and UUID_RE.match(identifier):
return [identifier]
for resolver in resolvers:
ids = resolver(identifier)
if ids:
return ids
return [] | python | def resolve_ids(identifier, resolvers):
try:
return [int(identifier)]
except ValueError:
pass
if len(identifier) == 36 and UUID_RE.match(identifier):
return [identifier]
for resolver in resolvers:
ids = resolver(identifier)
if ids:
return ids
return [] | [
"def",
"resolve_ids",
"(",
"identifier",
",",
"resolvers",
")",
":",
"# Before doing anything, let's see if this is an integer",
"try",
":",
"return",
"[",
"int",
"(",
"identifier",
")",
"]",
"except",
"ValueError",
":",
"pass",
"# It was worth a shot",
"# This looks like a globalIdentifier (UUID)",
"if",
"len",
"(",
"identifier",
")",
"==",
"36",
"and",
"UUID_RE",
".",
"match",
"(",
"identifier",
")",
":",
"return",
"[",
"identifier",
"]",
"for",
"resolver",
"in",
"resolvers",
":",
"ids",
"=",
"resolver",
"(",
"identifier",
")",
"if",
"ids",
":",
"return",
"ids",
"return",
"[",
"]"
]
| Resolves IDs given a list of functions.
:param string identifier: identifier string
:param list resolvers: a list of functions
:returns list: | [
"Resolves",
"IDs",
"given",
"a",
"list",
"of",
"functions",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/utils.py#L215-L238 |
softlayer/softlayer-python | SoftLayer/utils.py | is_ready | def is_ready(instance, pending=False):
"""Returns True if instance is ready to be used
:param Object instance: Hardware or Virt with transaction data retrieved from the API
:param bool pending: Wait for ALL transactions to finish?
:returns bool:
"""
last_reload = lookup(instance, 'lastOperatingSystemReload', 'id')
active_transaction = lookup(instance, 'activeTransaction', 'id')
reloading = all((
active_transaction,
last_reload,
last_reload == active_transaction,
))
outstanding = False
if pending:
outstanding = active_transaction
if instance.get('provisionDate') and not reloading and not outstanding:
return True
return False | python | def is_ready(instance, pending=False):
last_reload = lookup(instance, 'lastOperatingSystemReload', 'id')
active_transaction = lookup(instance, 'activeTransaction', 'id')
reloading = all((
active_transaction,
last_reload,
last_reload == active_transaction,
))
outstanding = False
if pending:
outstanding = active_transaction
if instance.get('provisionDate') and not reloading and not outstanding:
return True
return False | [
"def",
"is_ready",
"(",
"instance",
",",
"pending",
"=",
"False",
")",
":",
"last_reload",
"=",
"lookup",
"(",
"instance",
",",
"'lastOperatingSystemReload'",
",",
"'id'",
")",
"active_transaction",
"=",
"lookup",
"(",
"instance",
",",
"'activeTransaction'",
",",
"'id'",
")",
"reloading",
"=",
"all",
"(",
"(",
"active_transaction",
",",
"last_reload",
",",
"last_reload",
"==",
"active_transaction",
",",
")",
")",
"outstanding",
"=",
"False",
"if",
"pending",
":",
"outstanding",
"=",
"active_transaction",
"if",
"instance",
".",
"get",
"(",
"'provisionDate'",
")",
"and",
"not",
"reloading",
"and",
"not",
"outstanding",
":",
"return",
"True",
"return",
"False"
]
| Returns True if instance is ready to be used
:param Object instance: Hardware or Virt with transaction data retrieved from the API
:param bool pending: Wait for ALL transactions to finish?
:returns bool: | [
"Returns",
"True",
"if",
"instance",
"is",
"ready",
"to",
"be",
"used"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/utils.py#L254-L275 |
softlayer/softlayer-python | SoftLayer/utils.py | clean_time | def clean_time(sltime, in_format='%Y-%m-%dT%H:%M:%S%z', out_format='%Y-%m-%d %H:%M'):
"""Easy way to format time strings
:param string sltime: A softlayer formatted time string
:param string in_format: Datetime format for strptime
:param string out_format: Datetime format for strftime
"""
try:
clean = datetime.datetime.strptime(sltime, in_format)
return clean.strftime(out_format)
# The %z option only exists with py3.6+
except ValueError:
return sltime | python | def clean_time(sltime, in_format='%Y-%m-%dT%H:%M:%S%z', out_format='%Y-%m-%d %H:%M'):
try:
clean = datetime.datetime.strptime(sltime, in_format)
return clean.strftime(out_format)
except ValueError:
return sltime | [
"def",
"clean_time",
"(",
"sltime",
",",
"in_format",
"=",
"'%Y-%m-%dT%H:%M:%S%z'",
",",
"out_format",
"=",
"'%Y-%m-%d %H:%M'",
")",
":",
"try",
":",
"clean",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"sltime",
",",
"in_format",
")",
"return",
"clean",
".",
"strftime",
"(",
"out_format",
")",
"# The %z option only exists with py3.6+",
"except",
"ValueError",
":",
"return",
"sltime"
]
| Easy way to format time strings
:param string sltime: A softlayer formatted time string
:param string in_format: Datetime format for strptime
:param string out_format: Datetime format for strftime | [
"Easy",
"way",
"to",
"format",
"time",
"strings"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/utils.py#L301-L313 |
softlayer/softlayer-python | SoftLayer/utils.py | NestedDict.to_dict | def to_dict(self):
"""Converts a NestedDict instance into a real dictionary.
This is needed for places where strict type checking is done.
"""
return {key: val.to_dict() if isinstance(val, NestedDict) else val
for key, val in self.items()} | python | def to_dict(self):
return {key: val.to_dict() if isinstance(val, NestedDict) else val
for key, val in self.items()} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"key",
":",
"val",
".",
"to_dict",
"(",
")",
"if",
"isinstance",
"(",
"val",
",",
"NestedDict",
")",
"else",
"val",
"for",
"key",
",",
"val",
"in",
"self",
".",
"items",
"(",
")",
"}"
]
| Converts a NestedDict instance into a real dictionary.
This is needed for places where strict type checking is done. | [
"Converts",
"a",
"NestedDict",
"instance",
"into",
"a",
"real",
"dictionary",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/utils.py#L57-L63 |
softlayer/softlayer-python | SoftLayer/CLI/firewall/cancel.py | cli | def cli(env, identifier):
"""Cancels a firewall."""
mgr = SoftLayer.FirewallManager(env.client)
firewall_type, firewall_id = firewall.parse_id(identifier)
if not (env.skip_confirmations or
formatting.confirm("This action will cancel a firewall from your "
"account. Continue?")):
raise exceptions.CLIAbort('Aborted.')
if firewall_type in ['vs', 'server']:
mgr.cancel_firewall(firewall_id, dedicated=False)
elif firewall_type == 'vlan':
mgr.cancel_firewall(firewall_id, dedicated=True)
else:
raise exceptions.CLIAbort('Unknown firewall type: %s' % firewall_type)
env.fout('Firewall with id %s is being cancelled!' % identifier) | python | def cli(env, identifier):
mgr = SoftLayer.FirewallManager(env.client)
firewall_type, firewall_id = firewall.parse_id(identifier)
if not (env.skip_confirmations or
formatting.confirm("This action will cancel a firewall from your "
"account. Continue?")):
raise exceptions.CLIAbort('Aborted.')
if firewall_type in ['vs', 'server']:
mgr.cancel_firewall(firewall_id, dedicated=False)
elif firewall_type == 'vlan':
mgr.cancel_firewall(firewall_id, dedicated=True)
else:
raise exceptions.CLIAbort('Unknown firewall type: %s' % firewall_type)
env.fout('Firewall with id %s is being cancelled!' % identifier) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"FirewallManager",
"(",
"env",
".",
"client",
")",
"firewall_type",
",",
"firewall_id",
"=",
"firewall",
".",
"parse_id",
"(",
"identifier",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"confirm",
"(",
"\"This action will cancel a firewall from your \"",
"\"account. Continue?\"",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted.'",
")",
"if",
"firewall_type",
"in",
"[",
"'vs'",
",",
"'server'",
"]",
":",
"mgr",
".",
"cancel_firewall",
"(",
"firewall_id",
",",
"dedicated",
"=",
"False",
")",
"elif",
"firewall_type",
"==",
"'vlan'",
":",
"mgr",
".",
"cancel_firewall",
"(",
"firewall_id",
",",
"dedicated",
"=",
"True",
")",
"else",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Unknown firewall type: %s'",
"%",
"firewall_type",
")",
"env",
".",
"fout",
"(",
"'Firewall with id %s is being cancelled!'",
"%",
"identifier",
")"
]
| Cancels a firewall. | [
"Cancels",
"a",
"firewall",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/cancel.py#L16-L34 |
softlayer/softlayer-python | SoftLayer/CLI/sshkey/add.py | cli | def cli(env, label, in_file, key, note):
"""Add a new SSH key."""
if in_file is None and key is None:
raise exceptions.ArgumentError(
'Either [-f | --in-file] or [-k | --key] arguments are required to add a key'
)
if in_file and key:
raise exceptions.ArgumentError(
'[-f | --in-file] is not allowed with [-k | --key]'
)
if key:
key_text = key
else:
key_file = open(path.expanduser(in_file), 'rU')
key_text = key_file.read().strip()
key_file.close()
mgr = SoftLayer.SshKeyManager(env.client)
result = mgr.add_key(key_text, label, note)
env.fout("SSH key added: %s" % result.get('fingerprint')) | python | def cli(env, label, in_file, key, note):
if in_file is None and key is None:
raise exceptions.ArgumentError(
'Either [-f | --in-file] or [-k | --key] arguments are required to add a key'
)
if in_file and key:
raise exceptions.ArgumentError(
'[-f | --in-file] is not allowed with [-k | --key]'
)
if key:
key_text = key
else:
key_file = open(path.expanduser(in_file), 'rU')
key_text = key_file.read().strip()
key_file.close()
mgr = SoftLayer.SshKeyManager(env.client)
result = mgr.add_key(key_text, label, note)
env.fout("SSH key added: %s" % result.get('fingerprint')) | [
"def",
"cli",
"(",
"env",
",",
"label",
",",
"in_file",
",",
"key",
",",
"note",
")",
":",
"if",
"in_file",
"is",
"None",
"and",
"key",
"is",
"None",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"'Either [-f | --in-file] or [-k | --key] arguments are required to add a key'",
")",
"if",
"in_file",
"and",
"key",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"'[-f | --in-file] is not allowed with [-k | --key]'",
")",
"if",
"key",
":",
"key_text",
"=",
"key",
"else",
":",
"key_file",
"=",
"open",
"(",
"path",
".",
"expanduser",
"(",
"in_file",
")",
",",
"'rU'",
")",
"key_text",
"=",
"key_file",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"key_file",
".",
"close",
"(",
")",
"mgr",
"=",
"SoftLayer",
".",
"SshKeyManager",
"(",
"env",
".",
"client",
")",
"result",
"=",
"mgr",
".",
"add_key",
"(",
"key_text",
",",
"label",
",",
"note",
")",
"env",
".",
"fout",
"(",
"\"SSH key added: %s\"",
"%",
"result",
".",
"get",
"(",
"'fingerprint'",
")",
")"
]
| Add a new SSH key. | [
"Add",
"a",
"new",
"SSH",
"key",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/sshkey/add.py#L20-L43 |
softlayer/softlayer-python | SoftLayer/CLI/rwhois/show.py | cli | def cli(env):
"""Display the RWhois information for your account."""
mgr = SoftLayer.NetworkManager(env.client)
result = mgr.get_rwhois()
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['Name', result['firstName'] + ' ' + result['lastName']])
table.add_row(['Company', result['companyName']])
table.add_row(['Abuse Email', result['abuseEmail']])
table.add_row(['Address 1', result['address1']])
if result.get('address2'):
table.add_row(['Address 2', result['address2']])
table.add_row(['City', result['city']])
table.add_row(['State', result.get('state', '-')])
table.add_row(['Postal Code', result.get('postalCode', '-')])
table.add_row(['Country', result['country']])
table.add_row(['Private Residence', result['privateResidenceFlag']])
env.fout(table) | python | def cli(env):
mgr = SoftLayer.NetworkManager(env.client)
result = mgr.get_rwhois()
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['Name', result['firstName'] + ' ' + result['lastName']])
table.add_row(['Company', result['companyName']])
table.add_row(['Abuse Email', result['abuseEmail']])
table.add_row(['Address 1', result['address1']])
if result.get('address2'):
table.add_row(['Address 2', result['address2']])
table.add_row(['City', result['city']])
table.add_row(['State', result.get('state', '-')])
table.add_row(['Postal Code', result.get('postalCode', '-')])
table.add_row(['Country', result['country']])
table.add_row(['Private Residence', result['privateResidenceFlag']])
env.fout(table) | [
"def",
"cli",
"(",
"env",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"result",
"=",
"mgr",
".",
"get_rwhois",
"(",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'Name'",
",",
"result",
"[",
"'firstName'",
"]",
"+",
"' '",
"+",
"result",
"[",
"'lastName'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Company'",
",",
"result",
"[",
"'companyName'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Abuse Email'",
",",
"result",
"[",
"'abuseEmail'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Address 1'",
",",
"result",
"[",
"'address1'",
"]",
"]",
")",
"if",
"result",
".",
"get",
"(",
"'address2'",
")",
":",
"table",
".",
"add_row",
"(",
"[",
"'Address 2'",
",",
"result",
"[",
"'address2'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'City'",
",",
"result",
"[",
"'city'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'State'",
",",
"result",
".",
"get",
"(",
"'state'",
",",
"'-'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Postal Code'",
",",
"result",
".",
"get",
"(",
"'postalCode'",
",",
"'-'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Country'",
",",
"result",
"[",
"'country'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Private Residence'",
",",
"result",
"[",
"'privateResidenceFlag'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Display the RWhois information for your account. | [
"Display",
"the",
"RWhois",
"information",
"for",
"your",
"account",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/rwhois/show.py#L13-L34 |
softlayer/softlayer-python | SoftLayer/CLI/vpn/ipsec/translation/add.py | cli | def cli(env, context_id, static_ip, remote_ip, note):
"""Add an address translation to an IPSEC tunnel context.
A separate configuration request should be made to realize changes on
network devices.
"""
manager = SoftLayer.IPSECManager(env.client)
# ensure context can be retrieved by given id
manager.get_tunnel_context(context_id)
translation = manager.create_translation(context_id,
static_ip=static_ip,
remote_ip=remote_ip,
notes=note)
env.out('Created translation from {} to {} #{}'
.format(static_ip, remote_ip, translation['id'])) | python | def cli(env, context_id, static_ip, remote_ip, note):
manager = SoftLayer.IPSECManager(env.client)
manager.get_tunnel_context(context_id)
translation = manager.create_translation(context_id,
static_ip=static_ip,
remote_ip=remote_ip,
notes=note)
env.out('Created translation from {} to {}
.format(static_ip, remote_ip, translation['id'])) | [
"def",
"cli",
"(",
"env",
",",
"context_id",
",",
"static_ip",
",",
"remote_ip",
",",
"note",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"IPSECManager",
"(",
"env",
".",
"client",
")",
"# ensure context can be retrieved by given id",
"manager",
".",
"get_tunnel_context",
"(",
"context_id",
")",
"translation",
"=",
"manager",
".",
"create_translation",
"(",
"context_id",
",",
"static_ip",
"=",
"static_ip",
",",
"remote_ip",
"=",
"remote_ip",
",",
"notes",
"=",
"note",
")",
"env",
".",
"out",
"(",
"'Created translation from {} to {} #{}'",
".",
"format",
"(",
"static_ip",
",",
"remote_ip",
",",
"translation",
"[",
"'id'",
"]",
")",
")"
]
| Add an address translation to an IPSEC tunnel context.
A separate configuration request should be made to realize changes on
network devices. | [
"Add",
"an",
"address",
"translation",
"to",
"an",
"IPSEC",
"tunnel",
"context",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/translation/add.py#L27-L42 |
softlayer/softlayer-python | SoftLayer/CLI/virt/dns.py | cli | def cli(env, identifier, a_record, aaaa_record, ptr, ttl):
"""Sync DNS records."""
items = ['id',
'globalIdentifier',
'fullyQualifiedDomainName',
'hostname',
'domain',
'primaryBackendIpAddress',
'primaryIpAddress',
'''primaryNetworkComponent[
id, primaryIpAddress,
primaryVersion6IpAddressRecord[ipAddress]
]''']
mask = "mask[%s]" % ','.join(items)
dns = SoftLayer.DNSManager(env.client)
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
instance = vsi.get_instance(vs_id, mask=mask)
zone_id = helpers.resolve_id(dns.resolve_ids,
instance['domain'],
name='zone')
def sync_a_record():
"""Sync A record."""
records = dns.get_records(zone_id,
host=instance['hostname'],
record_type='a')
if not records:
# don't have a record, lets add one to the base zone
dns.create_record(zone['id'],
instance['hostname'],
'a',
instance['primaryIpAddress'],
ttl=ttl)
else:
if len(records) != 1:
raise exceptions.CLIAbort("Aborting A record sync, found "
"%d A record exists!" % len(records))
rec = records[0]
rec['data'] = instance['primaryIpAddress']
rec['ttl'] = ttl
dns.edit_record(rec)
def sync_aaaa_record():
"""Sync AAAA record."""
records = dns.get_records(zone_id,
host=instance['hostname'],
record_type='aaaa')
try:
# done this way to stay within 80 character lines
component = instance['primaryNetworkComponent']
record = component['primaryVersion6IpAddressRecord']
ip_address = record['ipAddress']
except KeyError:
raise exceptions.CLIAbort("%s does not have an ipv6 address"
% instance['fullyQualifiedDomainName'])
if not records:
# don't have a record, lets add one to the base zone
dns.create_record(zone['id'],
instance['hostname'],
'aaaa',
ip_address,
ttl=ttl)
else:
if len(records) != 1:
raise exceptions.CLIAbort("Aborting A record sync, found "
"%d A record exists!" % len(records))
rec = records[0]
rec['data'] = ip_address
rec['ttl'] = ttl
dns.edit_record(rec)
def sync_ptr_record():
"""Sync PTR record."""
host_rec = instance['primaryIpAddress'].split('.')[-1]
ptr_domains = (env.client['Virtual_Guest']
.getReverseDomainRecords(id=instance['id'])[0])
edit_ptr = None
for ptr in ptr_domains['resourceRecords']:
if ptr['host'] == host_rec:
ptr['ttl'] = ttl
edit_ptr = ptr
break
if edit_ptr:
edit_ptr['data'] = instance['fullyQualifiedDomainName']
dns.edit_record(edit_ptr)
else:
dns.create_record(ptr_domains['id'],
host_rec,
'ptr',
instance['fullyQualifiedDomainName'],
ttl=ttl)
if not instance['primaryIpAddress']:
raise exceptions.CLIAbort('No primary IP address associated with '
'this VS')
zone = dns.get_zone(zone_id)
go_for_it = env.skip_confirmations or formatting.confirm(
"Attempt to update DNS records for %s"
% instance['fullyQualifiedDomainName'])
if not go_for_it:
raise exceptions.CLIAbort("Aborting DNS sync")
both = False
if not ptr and not a_record and not aaaa_record:
both = True
if both or a_record:
sync_a_record()
if both or ptr:
sync_ptr_record()
if aaaa_record:
sync_aaaa_record() | python | def cli(env, identifier, a_record, aaaa_record, ptr, ttl):
items = ['id',
'globalIdentifier',
'fullyQualifiedDomainName',
'hostname',
'domain',
'primaryBackendIpAddress',
'primaryIpAddress',
]
mask = "mask[%s]" % ','.join(items)
dns = SoftLayer.DNSManager(env.client)
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
instance = vsi.get_instance(vs_id, mask=mask)
zone_id = helpers.resolve_id(dns.resolve_ids,
instance['domain'],
name='zone')
def sync_a_record():
records = dns.get_records(zone_id,
host=instance['hostname'],
record_type='a')
if not records:
dns.create_record(zone['id'],
instance['hostname'],
'a',
instance['primaryIpAddress'],
ttl=ttl)
else:
if len(records) != 1:
raise exceptions.CLIAbort("Aborting A record sync, found "
"%d A record exists!" % len(records))
rec = records[0]
rec['data'] = instance['primaryIpAddress']
rec['ttl'] = ttl
dns.edit_record(rec)
def sync_aaaa_record():
records = dns.get_records(zone_id,
host=instance['hostname'],
record_type='aaaa')
try:
component = instance['primaryNetworkComponent']
record = component['primaryVersion6IpAddressRecord']
ip_address = record['ipAddress']
except KeyError:
raise exceptions.CLIAbort("%s does not have an ipv6 address"
% instance['fullyQualifiedDomainName'])
if not records:
dns.create_record(zone['id'],
instance['hostname'],
'aaaa',
ip_address,
ttl=ttl)
else:
if len(records) != 1:
raise exceptions.CLIAbort("Aborting A record sync, found "
"%d A record exists!" % len(records))
rec = records[0]
rec['data'] = ip_address
rec['ttl'] = ttl
dns.edit_record(rec)
def sync_ptr_record():
host_rec = instance['primaryIpAddress'].split('.')[-1]
ptr_domains = (env.client['Virtual_Guest']
.getReverseDomainRecords(id=instance['id'])[0])
edit_ptr = None
for ptr in ptr_domains['resourceRecords']:
if ptr['host'] == host_rec:
ptr['ttl'] = ttl
edit_ptr = ptr
break
if edit_ptr:
edit_ptr['data'] = instance['fullyQualifiedDomainName']
dns.edit_record(edit_ptr)
else:
dns.create_record(ptr_domains['id'],
host_rec,
'ptr',
instance['fullyQualifiedDomainName'],
ttl=ttl)
if not instance['primaryIpAddress']:
raise exceptions.CLIAbort('No primary IP address associated with '
'this VS')
zone = dns.get_zone(zone_id)
go_for_it = env.skip_confirmations or formatting.confirm(
"Attempt to update DNS records for %s"
% instance['fullyQualifiedDomainName'])
if not go_for_it:
raise exceptions.CLIAbort("Aborting DNS sync")
both = False
if not ptr and not a_record and not aaaa_record:
both = True
if both or a_record:
sync_a_record()
if both or ptr:
sync_ptr_record()
if aaaa_record:
sync_aaaa_record() | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"a_record",
",",
"aaaa_record",
",",
"ptr",
",",
"ttl",
")",
":",
"items",
"=",
"[",
"'id'",
",",
"'globalIdentifier'",
",",
"'fullyQualifiedDomainName'",
",",
"'hostname'",
",",
"'domain'",
",",
"'primaryBackendIpAddress'",
",",
"'primaryIpAddress'",
",",
"'''primaryNetworkComponent[\n id, primaryIpAddress,\n primaryVersion6IpAddressRecord[ipAddress]\n ]'''",
"]",
"mask",
"=",
"\"mask[%s]\"",
"%",
"','",
".",
"join",
"(",
"items",
")",
"dns",
"=",
"SoftLayer",
".",
"DNSManager",
"(",
"env",
".",
"client",
")",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
"identifier",
",",
"'VS'",
")",
"instance",
"=",
"vsi",
".",
"get_instance",
"(",
"vs_id",
",",
"mask",
"=",
"mask",
")",
"zone_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"dns",
".",
"resolve_ids",
",",
"instance",
"[",
"'domain'",
"]",
",",
"name",
"=",
"'zone'",
")",
"def",
"sync_a_record",
"(",
")",
":",
"\"\"\"Sync A record.\"\"\"",
"records",
"=",
"dns",
".",
"get_records",
"(",
"zone_id",
",",
"host",
"=",
"instance",
"[",
"'hostname'",
"]",
",",
"record_type",
"=",
"'a'",
")",
"if",
"not",
"records",
":",
"# don't have a record, lets add one to the base zone",
"dns",
".",
"create_record",
"(",
"zone",
"[",
"'id'",
"]",
",",
"instance",
"[",
"'hostname'",
"]",
",",
"'a'",
",",
"instance",
"[",
"'primaryIpAddress'",
"]",
",",
"ttl",
"=",
"ttl",
")",
"else",
":",
"if",
"len",
"(",
"records",
")",
"!=",
"1",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Aborting A record sync, found \"",
"\"%d A record exists!\"",
"%",
"len",
"(",
"records",
")",
")",
"rec",
"=",
"records",
"[",
"0",
"]",
"rec",
"[",
"'data'",
"]",
"=",
"instance",
"[",
"'primaryIpAddress'",
"]",
"rec",
"[",
"'ttl'",
"]",
"=",
"ttl",
"dns",
".",
"edit_record",
"(",
"rec",
")",
"def",
"sync_aaaa_record",
"(",
")",
":",
"\"\"\"Sync AAAA record.\"\"\"",
"records",
"=",
"dns",
".",
"get_records",
"(",
"zone_id",
",",
"host",
"=",
"instance",
"[",
"'hostname'",
"]",
",",
"record_type",
"=",
"'aaaa'",
")",
"try",
":",
"# done this way to stay within 80 character lines",
"component",
"=",
"instance",
"[",
"'primaryNetworkComponent'",
"]",
"record",
"=",
"component",
"[",
"'primaryVersion6IpAddressRecord'",
"]",
"ip_address",
"=",
"record",
"[",
"'ipAddress'",
"]",
"except",
"KeyError",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"%s does not have an ipv6 address\"",
"%",
"instance",
"[",
"'fullyQualifiedDomainName'",
"]",
")",
"if",
"not",
"records",
":",
"# don't have a record, lets add one to the base zone",
"dns",
".",
"create_record",
"(",
"zone",
"[",
"'id'",
"]",
",",
"instance",
"[",
"'hostname'",
"]",
",",
"'aaaa'",
",",
"ip_address",
",",
"ttl",
"=",
"ttl",
")",
"else",
":",
"if",
"len",
"(",
"records",
")",
"!=",
"1",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Aborting A record sync, found \"",
"\"%d A record exists!\"",
"%",
"len",
"(",
"records",
")",
")",
"rec",
"=",
"records",
"[",
"0",
"]",
"rec",
"[",
"'data'",
"]",
"=",
"ip_address",
"rec",
"[",
"'ttl'",
"]",
"=",
"ttl",
"dns",
".",
"edit_record",
"(",
"rec",
")",
"def",
"sync_ptr_record",
"(",
")",
":",
"\"\"\"Sync PTR record.\"\"\"",
"host_rec",
"=",
"instance",
"[",
"'primaryIpAddress'",
"]",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"ptr_domains",
"=",
"(",
"env",
".",
"client",
"[",
"'Virtual_Guest'",
"]",
".",
"getReverseDomainRecords",
"(",
"id",
"=",
"instance",
"[",
"'id'",
"]",
")",
"[",
"0",
"]",
")",
"edit_ptr",
"=",
"None",
"for",
"ptr",
"in",
"ptr_domains",
"[",
"'resourceRecords'",
"]",
":",
"if",
"ptr",
"[",
"'host'",
"]",
"==",
"host_rec",
":",
"ptr",
"[",
"'ttl'",
"]",
"=",
"ttl",
"edit_ptr",
"=",
"ptr",
"break",
"if",
"edit_ptr",
":",
"edit_ptr",
"[",
"'data'",
"]",
"=",
"instance",
"[",
"'fullyQualifiedDomainName'",
"]",
"dns",
".",
"edit_record",
"(",
"edit_ptr",
")",
"else",
":",
"dns",
".",
"create_record",
"(",
"ptr_domains",
"[",
"'id'",
"]",
",",
"host_rec",
",",
"'ptr'",
",",
"instance",
"[",
"'fullyQualifiedDomainName'",
"]",
",",
"ttl",
"=",
"ttl",
")",
"if",
"not",
"instance",
"[",
"'primaryIpAddress'",
"]",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'No primary IP address associated with '",
"'this VS'",
")",
"zone",
"=",
"dns",
".",
"get_zone",
"(",
"zone_id",
")",
"go_for_it",
"=",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"confirm",
"(",
"\"Attempt to update DNS records for %s\"",
"%",
"instance",
"[",
"'fullyQualifiedDomainName'",
"]",
")",
"if",
"not",
"go_for_it",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Aborting DNS sync\"",
")",
"both",
"=",
"False",
"if",
"not",
"ptr",
"and",
"not",
"a_record",
"and",
"not",
"aaaa_record",
":",
"both",
"=",
"True",
"if",
"both",
"or",
"a_record",
":",
"sync_a_record",
"(",
")",
"if",
"both",
"or",
"ptr",
":",
"sync_ptr_record",
"(",
")",
"if",
"aaaa_record",
":",
"sync_aaaa_record",
"(",
")"
]
| Sync DNS records. | [
"Sync",
"DNS",
"records",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/dns.py#L31-L152 |
softlayer/softlayer-python | SoftLayer/CLI/block/snapshot/disable.py | cli | def cli(env, volume_id, schedule_type):
"""Disables snapshots on the specified schedule for a given volume"""
if (schedule_type not in ['INTERVAL', 'HOURLY', 'DAILY', 'WEEKLY']):
raise exceptions.CLIAbort(
'--schedule-type must be INTERVAL, HOURLY, DAILY, or WEEKLY')
block_manager = SoftLayer.BlockStorageManager(env.client)
disabled = block_manager.disable_snapshots(volume_id, schedule_type)
if disabled:
click.echo('%s snapshots have been disabled for volume %s'
% (schedule_type, volume_id)) | python | def cli(env, volume_id, schedule_type):
if (schedule_type not in ['INTERVAL', 'HOURLY', 'DAILY', 'WEEKLY']):
raise exceptions.CLIAbort(
'--schedule-type must be INTERVAL, HOURLY, DAILY, or WEEKLY')
block_manager = SoftLayer.BlockStorageManager(env.client)
disabled = block_manager.disable_snapshots(volume_id, schedule_type)
if disabled:
click.echo('%s snapshots have been disabled for volume %s'
% (schedule_type, volume_id)) | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"schedule_type",
")",
":",
"if",
"(",
"schedule_type",
"not",
"in",
"[",
"'INTERVAL'",
",",
"'HOURLY'",
",",
"'DAILY'",
",",
"'WEEKLY'",
"]",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'--schedule-type must be INTERVAL, HOURLY, DAILY, or WEEKLY'",
")",
"block_manager",
"=",
"SoftLayer",
".",
"BlockStorageManager",
"(",
"env",
".",
"client",
")",
"disabled",
"=",
"block_manager",
".",
"disable_snapshots",
"(",
"volume_id",
",",
"schedule_type",
")",
"if",
"disabled",
":",
"click",
".",
"echo",
"(",
"'%s snapshots have been disabled for volume %s'",
"%",
"(",
"schedule_type",
",",
"volume_id",
")",
")"
]
| Disables snapshots on the specified schedule for a given volume | [
"Disables",
"snapshots",
"on",
"the",
"specified",
"schedule",
"for",
"a",
"given",
"volume"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/snapshot/disable.py#L16-L28 |
softlayer/softlayer-python | SoftLayer/CLI/ssl/list.py | cli | def cli(env, status, sortby):
"""List SSL certificates."""
manager = SoftLayer.SSLManager(env.client)
certificates = manager.list_certs(status)
table = formatting.Table(['id',
'common_name',
'days_until_expire',
'notes'])
for certificate in certificates:
table.add_row([
certificate['id'],
certificate['commonName'],
certificate['validityDays'],
certificate.get('notes', formatting.blank())
])
table.sortby = sortby
env.fout(table) | python | def cli(env, status, sortby):
manager = SoftLayer.SSLManager(env.client)
certificates = manager.list_certs(status)
table = formatting.Table(['id',
'common_name',
'days_until_expire',
'notes'])
for certificate in certificates:
table.add_row([
certificate['id'],
certificate['commonName'],
certificate['validityDays'],
certificate.get('notes', formatting.blank())
])
table.sortby = sortby
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"status",
",",
"sortby",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"SSLManager",
"(",
"env",
".",
"client",
")",
"certificates",
"=",
"manager",
".",
"list_certs",
"(",
"status",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'common_name'",
",",
"'days_until_expire'",
",",
"'notes'",
"]",
")",
"for",
"certificate",
"in",
"certificates",
":",
"table",
".",
"add_row",
"(",
"[",
"certificate",
"[",
"'id'",
"]",
",",
"certificate",
"[",
"'commonName'",
"]",
",",
"certificate",
"[",
"'validityDays'",
"]",
",",
"certificate",
".",
"get",
"(",
"'notes'",
",",
"formatting",
".",
"blank",
"(",
")",
")",
"]",
")",
"table",
".",
"sortby",
"=",
"sortby",
"env",
".",
"fout",
"(",
"table",
")"
]
| List SSL certificates. | [
"List",
"SSL",
"certificates",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ssl/list.py#L24-L42 |
softlayer/softlayer-python | SoftLayer/CLI/loadbal/health_checks.py | cli | def cli(env):
"""List health check types."""
mgr = SoftLayer.LoadBalancerManager(env.client)
hc_types = mgr.get_hc_types()
table = formatting.KeyValueTable(['ID', 'Name'])
table.align['ID'] = 'l'
table.align['Name'] = 'l'
table.sortby = 'ID'
for hc_type in hc_types:
table.add_row([hc_type['id'], hc_type['name']])
env.fout(table) | python | def cli(env):
mgr = SoftLayer.LoadBalancerManager(env.client)
hc_types = mgr.get_hc_types()
table = formatting.KeyValueTable(['ID', 'Name'])
table.align['ID'] = 'l'
table.align['Name'] = 'l'
table.sortby = 'ID'
for hc_type in hc_types:
table.add_row([hc_type['id'], hc_type['name']])
env.fout(table) | [
"def",
"cli",
"(",
"env",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"LoadBalancerManager",
"(",
"env",
".",
"client",
")",
"hc_types",
"=",
"mgr",
".",
"get_hc_types",
"(",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'ID'",
",",
"'Name'",
"]",
")",
"table",
".",
"align",
"[",
"'ID'",
"]",
"=",
"'l'",
"table",
".",
"align",
"[",
"'Name'",
"]",
"=",
"'l'",
"table",
".",
"sortby",
"=",
"'ID'",
"for",
"hc_type",
"in",
"hc_types",
":",
"table",
".",
"add_row",
"(",
"[",
"hc_type",
"[",
"'id'",
"]",
",",
"hc_type",
"[",
"'name'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| List health check types. | [
"List",
"health",
"check",
"types",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/health_checks.py#L13-L26 |
softlayer/softlayer-python | SoftLayer/CLI/object_storage/credential/limit.py | cli | def cli(env, identifier):
"""Credential limits for this IBM Cloud Object Storage account."""
mgr = SoftLayer.ObjectStorageManager(env.client)
credential_limit = mgr.limit_credential(identifier)
table = formatting.Table(['limit'])
table.add_row([
credential_limit,
])
env.fout(table) | python | def cli(env, identifier):
mgr = SoftLayer.ObjectStorageManager(env.client)
credential_limit = mgr.limit_credential(identifier)
table = formatting.Table(['limit'])
table.add_row([
credential_limit,
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"ObjectStorageManager",
"(",
"env",
".",
"client",
")",
"credential_limit",
"=",
"mgr",
".",
"limit_credential",
"(",
"identifier",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'limit'",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"credential_limit",
",",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Credential limits for this IBM Cloud Object Storage account. | [
"Credential",
"limits",
"for",
"this",
"IBM",
"Cloud",
"Object",
"Storage",
"account",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/object_storage/credential/limit.py#L14-L24 |
softlayer/softlayer-python | SoftLayer/CLI/vpn/ipsec/detail.py | cli | def cli(env, context_id, include):
"""List IPSEC VPN tunnel context details.
Additional resources can be joined using multiple instances of the
include option, for which the following choices are available.
\b
at: address translations
is: internal subnets
rs: remote subnets
sr: statically routed subnets
ss: service subnets
"""
mask = _get_tunnel_context_mask(('at' in include),
('is' in include),
('rs' in include),
('sr' in include),
('ss' in include))
manager = SoftLayer.IPSECManager(env.client)
context = manager.get_tunnel_context(context_id, mask=mask)
env.out('Context Details:')
env.fout(_get_context_table(context))
for relation in include:
if relation == 'at':
env.out('Address Translations:')
env.fout(_get_address_translations_table(
context.get('addressTranslations', [])))
elif relation == 'is':
env.out('Internal Subnets:')
env.fout(_get_subnets_table(context.get('internalSubnets', [])))
elif relation == 'rs':
env.out('Remote Subnets:')
env.fout(_get_subnets_table(context.get('customerSubnets', [])))
elif relation == 'sr':
env.out('Static Subnets:')
env.fout(_get_subnets_table(context.get('staticRouteSubnets', [])))
elif relation == 'ss':
env.out('Service Subnets:')
env.fout(_get_subnets_table(context.get('serviceSubnets', []))) | python | def cli(env, context_id, include):
mask = _get_tunnel_context_mask(('at' in include),
('is' in include),
('rs' in include),
('sr' in include),
('ss' in include))
manager = SoftLayer.IPSECManager(env.client)
context = manager.get_tunnel_context(context_id, mask=mask)
env.out('Context Details:')
env.fout(_get_context_table(context))
for relation in include:
if relation == 'at':
env.out('Address Translations:')
env.fout(_get_address_translations_table(
context.get('addressTranslations', [])))
elif relation == 'is':
env.out('Internal Subnets:')
env.fout(_get_subnets_table(context.get('internalSubnets', [])))
elif relation == 'rs':
env.out('Remote Subnets:')
env.fout(_get_subnets_table(context.get('customerSubnets', [])))
elif relation == 'sr':
env.out('Static Subnets:')
env.fout(_get_subnets_table(context.get('staticRouteSubnets', [])))
elif relation == 'ss':
env.out('Service Subnets:')
env.fout(_get_subnets_table(context.get('serviceSubnets', []))) | [
"def",
"cli",
"(",
"env",
",",
"context_id",
",",
"include",
")",
":",
"mask",
"=",
"_get_tunnel_context_mask",
"(",
"(",
"'at'",
"in",
"include",
")",
",",
"(",
"'is'",
"in",
"include",
")",
",",
"(",
"'rs'",
"in",
"include",
")",
",",
"(",
"'sr'",
"in",
"include",
")",
",",
"(",
"'ss'",
"in",
"include",
")",
")",
"manager",
"=",
"SoftLayer",
".",
"IPSECManager",
"(",
"env",
".",
"client",
")",
"context",
"=",
"manager",
".",
"get_tunnel_context",
"(",
"context_id",
",",
"mask",
"=",
"mask",
")",
"env",
".",
"out",
"(",
"'Context Details:'",
")",
"env",
".",
"fout",
"(",
"_get_context_table",
"(",
"context",
")",
")",
"for",
"relation",
"in",
"include",
":",
"if",
"relation",
"==",
"'at'",
":",
"env",
".",
"out",
"(",
"'Address Translations:'",
")",
"env",
".",
"fout",
"(",
"_get_address_translations_table",
"(",
"context",
".",
"get",
"(",
"'addressTranslations'",
",",
"[",
"]",
")",
")",
")",
"elif",
"relation",
"==",
"'is'",
":",
"env",
".",
"out",
"(",
"'Internal Subnets:'",
")",
"env",
".",
"fout",
"(",
"_get_subnets_table",
"(",
"context",
".",
"get",
"(",
"'internalSubnets'",
",",
"[",
"]",
")",
")",
")",
"elif",
"relation",
"==",
"'rs'",
":",
"env",
".",
"out",
"(",
"'Remote Subnets:'",
")",
"env",
".",
"fout",
"(",
"_get_subnets_table",
"(",
"context",
".",
"get",
"(",
"'customerSubnets'",
",",
"[",
"]",
")",
")",
")",
"elif",
"relation",
"==",
"'sr'",
":",
"env",
".",
"out",
"(",
"'Static Subnets:'",
")",
"env",
".",
"fout",
"(",
"_get_subnets_table",
"(",
"context",
".",
"get",
"(",
"'staticRouteSubnets'",
",",
"[",
"]",
")",
")",
")",
"elif",
"relation",
"==",
"'ss'",
":",
"env",
".",
"out",
"(",
"'Service Subnets:'",
")",
"env",
".",
"fout",
"(",
"_get_subnets_table",
"(",
"context",
".",
"get",
"(",
"'serviceSubnets'",
",",
"[",
"]",
")",
")",
")"
]
| List IPSEC VPN tunnel context details.
Additional resources can be joined using multiple instances of the
include option, for which the following choices are available.
\b
at: address translations
is: internal subnets
rs: remote subnets
sr: statically routed subnets
ss: service subnets | [
"List",
"IPSEC",
"VPN",
"tunnel",
"context",
"details",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/detail.py#L20-L60 |
softlayer/softlayer-python | SoftLayer/CLI/vpn/ipsec/detail.py | _get_address_translations_table | def _get_address_translations_table(address_translations):
"""Yields a formatted table to print address translations.
:param List[dict] address_translations: List of address translations.
:return Table: Formatted for address translation output.
"""
table = formatting.Table(['id',
'static IP address',
'static IP address id',
'remote IP address',
'remote IP address id',
'note'])
for address_translation in address_translations:
table.add_row([address_translation.get('id', ''),
address_translation.get('internalIpAddressRecord', {})
.get('ipAddress', ''),
address_translation.get('internalIpAddressId', ''),
address_translation.get('customerIpAddressRecord', {})
.get('ipAddress', ''),
address_translation.get('customerIpAddressId', ''),
address_translation.get('notes', '')])
return table | python | def _get_address_translations_table(address_translations):
table = formatting.Table(['id',
'static IP address',
'static IP address id',
'remote IP address',
'remote IP address id',
'note'])
for address_translation in address_translations:
table.add_row([address_translation.get('id', ''),
address_translation.get('internalIpAddressRecord', {})
.get('ipAddress', ''),
address_translation.get('internalIpAddressId', ''),
address_translation.get('customerIpAddressRecord', {})
.get('ipAddress', ''),
address_translation.get('customerIpAddressId', ''),
address_translation.get('notes', '')])
return table | [
"def",
"_get_address_translations_table",
"(",
"address_translations",
")",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'static IP address'",
",",
"'static IP address id'",
",",
"'remote IP address'",
",",
"'remote IP address id'",
",",
"'note'",
"]",
")",
"for",
"address_translation",
"in",
"address_translations",
":",
"table",
".",
"add_row",
"(",
"[",
"address_translation",
".",
"get",
"(",
"'id'",
",",
"''",
")",
",",
"address_translation",
".",
"get",
"(",
"'internalIpAddressRecord'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'ipAddress'",
",",
"''",
")",
",",
"address_translation",
".",
"get",
"(",
"'internalIpAddressId'",
",",
"''",
")",
",",
"address_translation",
".",
"get",
"(",
"'customerIpAddressRecord'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'ipAddress'",
",",
"''",
")",
",",
"address_translation",
".",
"get",
"(",
"'customerIpAddressId'",
",",
"''",
")",
",",
"address_translation",
".",
"get",
"(",
"'notes'",
",",
"''",
")",
"]",
")",
"return",
"table"
]
| Yields a formatted table to print address translations.
:param List[dict] address_translations: List of address translations.
:return Table: Formatted for address translation output. | [
"Yields",
"a",
"formatted",
"table",
"to",
"print",
"address",
"translations",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/detail.py#L63-L84 |
softlayer/softlayer-python | SoftLayer/CLI/vpn/ipsec/detail.py | _get_subnets_table | def _get_subnets_table(subnets):
"""Yields a formatted table to print subnet details.
:param List[dict] subnets: List of subnets.
:return Table: Formatted for subnet output.
"""
table = formatting.Table(['id',
'network identifier',
'cidr',
'note'])
for subnet in subnets:
table.add_row([subnet.get('id', ''),
subnet.get('networkIdentifier', ''),
subnet.get('cidr', ''),
subnet.get('note', '')])
return table | python | def _get_subnets_table(subnets):
table = formatting.Table(['id',
'network identifier',
'cidr',
'note'])
for subnet in subnets:
table.add_row([subnet.get('id', ''),
subnet.get('networkIdentifier', ''),
subnet.get('cidr', ''),
subnet.get('note', '')])
return table | [
"def",
"_get_subnets_table",
"(",
"subnets",
")",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'network identifier'",
",",
"'cidr'",
",",
"'note'",
"]",
")",
"for",
"subnet",
"in",
"subnets",
":",
"table",
".",
"add_row",
"(",
"[",
"subnet",
".",
"get",
"(",
"'id'",
",",
"''",
")",
",",
"subnet",
".",
"get",
"(",
"'networkIdentifier'",
",",
"''",
")",
",",
"subnet",
".",
"get",
"(",
"'cidr'",
",",
"''",
")",
",",
"subnet",
".",
"get",
"(",
"'note'",
",",
"''",
")",
"]",
")",
"return",
"table"
]
| Yields a formatted table to print subnet details.
:param List[dict] subnets: List of subnets.
:return Table: Formatted for subnet output. | [
"Yields",
"a",
"formatted",
"table",
"to",
"print",
"subnet",
"details",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/detail.py#L87-L102 |
softlayer/softlayer-python | SoftLayer/CLI/vpn/ipsec/detail.py | _get_tunnel_context_mask | def _get_tunnel_context_mask(address_translations=False,
internal_subnets=False,
remote_subnets=False,
static_subnets=False,
service_subnets=False):
"""Yields a mask object for a tunnel context.
All exposed properties on the tunnel context service are included in
the constructed mask. Additional joins may be requested.
:param bool address_translations: Whether to join the context's address
translation entries.
:param bool internal_subnets: Whether to join the context's internal
subnet associations.
:param bool remote_subnets: Whether to join the context's remote subnet
associations.
:param bool static_subnets: Whether to join the context's statically
routed subnet associations.
:param bool service_subnets: Whether to join the SoftLayer service
network subnets.
:return string: Encoding for the requested mask object.
"""
entries = ['id',
'accountId',
'advancedConfigurationFlag',
'createDate',
'customerPeerIpAddress',
'modifyDate',
'name',
'friendlyName',
'internalPeerIpAddress',
'phaseOneAuthentication',
'phaseOneDiffieHellmanGroup',
'phaseOneEncryption',
'phaseOneKeylife',
'phaseTwoAuthentication',
'phaseTwoDiffieHellmanGroup',
'phaseTwoEncryption',
'phaseTwoKeylife',
'phaseTwoPerfectForwardSecrecy',
'presharedKey']
if address_translations:
entries.append('addressTranslations[internalIpAddressRecord[ipAddress],'
'customerIpAddressRecord[ipAddress]]')
if internal_subnets:
entries.append('internalSubnets')
if remote_subnets:
entries.append('customerSubnets')
if static_subnets:
entries.append('staticRouteSubnets')
if service_subnets:
entries.append('serviceSubnets')
return '[mask[{}]]'.format(','.join(entries)) | python | def _get_tunnel_context_mask(address_translations=False,
internal_subnets=False,
remote_subnets=False,
static_subnets=False,
service_subnets=False):
entries = ['id',
'accountId',
'advancedConfigurationFlag',
'createDate',
'customerPeerIpAddress',
'modifyDate',
'name',
'friendlyName',
'internalPeerIpAddress',
'phaseOneAuthentication',
'phaseOneDiffieHellmanGroup',
'phaseOneEncryption',
'phaseOneKeylife',
'phaseTwoAuthentication',
'phaseTwoDiffieHellmanGroup',
'phaseTwoEncryption',
'phaseTwoKeylife',
'phaseTwoPerfectForwardSecrecy',
'presharedKey']
if address_translations:
entries.append('addressTranslations[internalIpAddressRecord[ipAddress],'
'customerIpAddressRecord[ipAddress]]')
if internal_subnets:
entries.append('internalSubnets')
if remote_subnets:
entries.append('customerSubnets')
if static_subnets:
entries.append('staticRouteSubnets')
if service_subnets:
entries.append('serviceSubnets')
return '[mask[{}]]'.format(','.join(entries)) | [
"def",
"_get_tunnel_context_mask",
"(",
"address_translations",
"=",
"False",
",",
"internal_subnets",
"=",
"False",
",",
"remote_subnets",
"=",
"False",
",",
"static_subnets",
"=",
"False",
",",
"service_subnets",
"=",
"False",
")",
":",
"entries",
"=",
"[",
"'id'",
",",
"'accountId'",
",",
"'advancedConfigurationFlag'",
",",
"'createDate'",
",",
"'customerPeerIpAddress'",
",",
"'modifyDate'",
",",
"'name'",
",",
"'friendlyName'",
",",
"'internalPeerIpAddress'",
",",
"'phaseOneAuthentication'",
",",
"'phaseOneDiffieHellmanGroup'",
",",
"'phaseOneEncryption'",
",",
"'phaseOneKeylife'",
",",
"'phaseTwoAuthentication'",
",",
"'phaseTwoDiffieHellmanGroup'",
",",
"'phaseTwoEncryption'",
",",
"'phaseTwoKeylife'",
",",
"'phaseTwoPerfectForwardSecrecy'",
",",
"'presharedKey'",
"]",
"if",
"address_translations",
":",
"entries",
".",
"append",
"(",
"'addressTranslations[internalIpAddressRecord[ipAddress],'",
"'customerIpAddressRecord[ipAddress]]'",
")",
"if",
"internal_subnets",
":",
"entries",
".",
"append",
"(",
"'internalSubnets'",
")",
"if",
"remote_subnets",
":",
"entries",
".",
"append",
"(",
"'customerSubnets'",
")",
"if",
"static_subnets",
":",
"entries",
".",
"append",
"(",
"'staticRouteSubnets'",
")",
"if",
"service_subnets",
":",
"entries",
".",
"append",
"(",
"'serviceSubnets'",
")",
"return",
"'[mask[{}]]'",
".",
"format",
"(",
"','",
".",
"join",
"(",
"entries",
")",
")"
]
| Yields a mask object for a tunnel context.
All exposed properties on the tunnel context service are included in
the constructed mask. Additional joins may be requested.
:param bool address_translations: Whether to join the context's address
translation entries.
:param bool internal_subnets: Whether to join the context's internal
subnet associations.
:param bool remote_subnets: Whether to join the context's remote subnet
associations.
:param bool static_subnets: Whether to join the context's statically
routed subnet associations.
:param bool service_subnets: Whether to join the SoftLayer service
network subnets.
:return string: Encoding for the requested mask object. | [
"Yields",
"a",
"mask",
"object",
"for",
"a",
"tunnel",
"context",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/detail.py#L105-L157 |
softlayer/softlayer-python | SoftLayer/CLI/vpn/ipsec/detail.py | _get_context_table | def _get_context_table(context):
"""Yields a formatted table to print context details.
:param dict context: The tunnel context
:return Table: Formatted for tunnel context output
"""
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', context.get('id', '')])
table.add_row(['name', context.get('name', '')])
table.add_row(['friendly name', context.get('friendlyName', '')])
table.add_row(['internal peer IP address',
context.get('internalPeerIpAddress', '')])
table.add_row(['remote peer IP address',
context.get('customerPeerIpAddress', '')])
table.add_row(['advanced configuration flag',
context.get('advancedConfigurationFlag', '')])
table.add_row(['preshared key', context.get('presharedKey', '')])
table.add_row(['phase 1 authentication',
context.get('phaseOneAuthentication', '')])
table.add_row(['phase 1 diffie hellman group',
context.get('phaseOneDiffieHellmanGroup', '')])
table.add_row(['phase 1 encryption', context.get('phaseOneEncryption', '')])
table.add_row(['phase 1 key life', context.get('phaseOneKeylife', '')])
table.add_row(['phase 2 authentication',
context.get('phaseTwoAuthentication', '')])
table.add_row(['phase 2 diffie hellman group',
context.get('phaseTwoDiffieHellmanGroup', '')])
table.add_row(['phase 2 encryption', context.get('phaseTwoEncryption', '')])
table.add_row(['phase 2 key life', context.get('phaseTwoKeylife', '')])
table.add_row(['phase 2 perfect forward secrecy',
context.get('phaseTwoPerfectForwardSecrecy', '')])
table.add_row(['created', context.get('createDate')])
table.add_row(['modified', context.get('modifyDate')])
return table | python | def _get_context_table(context):
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', context.get('id', '')])
table.add_row(['name', context.get('name', '')])
table.add_row(['friendly name', context.get('friendlyName', '')])
table.add_row(['internal peer IP address',
context.get('internalPeerIpAddress', '')])
table.add_row(['remote peer IP address',
context.get('customerPeerIpAddress', '')])
table.add_row(['advanced configuration flag',
context.get('advancedConfigurationFlag', '')])
table.add_row(['preshared key', context.get('presharedKey', '')])
table.add_row(['phase 1 authentication',
context.get('phaseOneAuthentication', '')])
table.add_row(['phase 1 diffie hellman group',
context.get('phaseOneDiffieHellmanGroup', '')])
table.add_row(['phase 1 encryption', context.get('phaseOneEncryption', '')])
table.add_row(['phase 1 key life', context.get('phaseOneKeylife', '')])
table.add_row(['phase 2 authentication',
context.get('phaseTwoAuthentication', '')])
table.add_row(['phase 2 diffie hellman group',
context.get('phaseTwoDiffieHellmanGroup', '')])
table.add_row(['phase 2 encryption', context.get('phaseTwoEncryption', '')])
table.add_row(['phase 2 key life', context.get('phaseTwoKeylife', '')])
table.add_row(['phase 2 perfect forward secrecy',
context.get('phaseTwoPerfectForwardSecrecy', '')])
table.add_row(['created', context.get('createDate')])
table.add_row(['modified', context.get('modifyDate')])
return table | [
"def",
"_get_context_table",
"(",
"context",
")",
":",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"context",
".",
"get",
"(",
"'id'",
",",
"''",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'name'",
",",
"context",
".",
"get",
"(",
"'name'",
",",
"''",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'friendly name'",
",",
"context",
".",
"get",
"(",
"'friendlyName'",
",",
"''",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'internal peer IP address'",
",",
"context",
".",
"get",
"(",
"'internalPeerIpAddress'",
",",
"''",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'remote peer IP address'",
",",
"context",
".",
"get",
"(",
"'customerPeerIpAddress'",
",",
"''",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'advanced configuration flag'",
",",
"context",
".",
"get",
"(",
"'advancedConfigurationFlag'",
",",
"''",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'preshared key'",
",",
"context",
".",
"get",
"(",
"'presharedKey'",
",",
"''",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'phase 1 authentication'",
",",
"context",
".",
"get",
"(",
"'phaseOneAuthentication'",
",",
"''",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'phase 1 diffie hellman group'",
",",
"context",
".",
"get",
"(",
"'phaseOneDiffieHellmanGroup'",
",",
"''",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'phase 1 encryption'",
",",
"context",
".",
"get",
"(",
"'phaseOneEncryption'",
",",
"''",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'phase 1 key life'",
",",
"context",
".",
"get",
"(",
"'phaseOneKeylife'",
",",
"''",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'phase 2 authentication'",
",",
"context",
".",
"get",
"(",
"'phaseTwoAuthentication'",
",",
"''",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'phase 2 diffie hellman group'",
",",
"context",
".",
"get",
"(",
"'phaseTwoDiffieHellmanGroup'",
",",
"''",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'phase 2 encryption'",
",",
"context",
".",
"get",
"(",
"'phaseTwoEncryption'",
",",
"''",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'phase 2 key life'",
",",
"context",
".",
"get",
"(",
"'phaseTwoKeylife'",
",",
"''",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'phase 2 perfect forward secrecy'",
",",
"context",
".",
"get",
"(",
"'phaseTwoPerfectForwardSecrecy'",
",",
"''",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'created'",
",",
"context",
".",
"get",
"(",
"'createDate'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'modified'",
",",
"context",
".",
"get",
"(",
"'modifyDate'",
")",
"]",
")",
"return",
"table"
]
| Yields a formatted table to print context details.
:param dict context: The tunnel context
:return Table: Formatted for tunnel context output | [
"Yields",
"a",
"formatted",
"table",
"to",
"print",
"context",
"details",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/detail.py#L160-L196 |
softlayer/softlayer-python | SoftLayer/CLI/file/replication/failover.py | cli | def cli(env, volume_id, replicant_id, immediate):
"""Failover a file volume to the given replicant volume."""
file_storage_manager = SoftLayer.FileStorageManager(env.client)
success = file_storage_manager.failover_to_replicant(
volume_id,
replicant_id,
immediate
)
if success:
click.echo("Failover to replicant is now in progress.")
else:
click.echo("Failover operation could not be initiated.") | python | def cli(env, volume_id, replicant_id, immediate):
file_storage_manager = SoftLayer.FileStorageManager(env.client)
success = file_storage_manager.failover_to_replicant(
volume_id,
replicant_id,
immediate
)
if success:
click.echo("Failover to replicant is now in progress.")
else:
click.echo("Failover operation could not be initiated.") | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"replicant_id",
",",
"immediate",
")",
":",
"file_storage_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"success",
"=",
"file_storage_manager",
".",
"failover_to_replicant",
"(",
"volume_id",
",",
"replicant_id",
",",
"immediate",
")",
"if",
"success",
":",
"click",
".",
"echo",
"(",
"\"Failover to replicant is now in progress.\"",
")",
"else",
":",
"click",
".",
"echo",
"(",
"\"Failover operation could not be initiated.\"",
")"
]
| Failover a file volume to the given replicant volume. | [
"Failover",
"a",
"file",
"volume",
"to",
"the",
"given",
"replicant",
"volume",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/replication/failover.py#L17-L30 |
softlayer/softlayer-python | SoftLayer/CLI/file/count.py | cli | def cli(env, sortby, datacenter):
"""List number of file storage volumes per datacenter."""
file_manager = SoftLayer.FileStorageManager(env.client)
mask = "mask[serviceResource[datacenter[name]],"\
"replicationPartners[serviceResource[datacenter[name]]]]"
file_volumes = file_manager.list_file_volumes(datacenter=datacenter,
mask=mask)
datacenters = dict()
for volume in file_volumes:
service_resource = volume['serviceResource']
if 'datacenter' in service_resource:
datacenter_name = service_resource['datacenter']['name']
if datacenter_name not in datacenters.keys():
datacenters[datacenter_name] = 1
else:
datacenters[datacenter_name] += 1
table = formatting.KeyValueTable(DEFAULT_COLUMNS)
table.sortby = sortby
for datacenter_name in datacenters:
table.add_row([datacenter_name, datacenters[datacenter_name]])
env.fout(table) | python | def cli(env, sortby, datacenter):
file_manager = SoftLayer.FileStorageManager(env.client)
mask = "mask[serviceResource[datacenter[name]],"\
"replicationPartners[serviceResource[datacenter[name]]]]"
file_volumes = file_manager.list_file_volumes(datacenter=datacenter,
mask=mask)
datacenters = dict()
for volume in file_volumes:
service_resource = volume['serviceResource']
if 'datacenter' in service_resource:
datacenter_name = service_resource['datacenter']['name']
if datacenter_name not in datacenters.keys():
datacenters[datacenter_name] = 1
else:
datacenters[datacenter_name] += 1
table = formatting.KeyValueTable(DEFAULT_COLUMNS)
table.sortby = sortby
for datacenter_name in datacenters:
table.add_row([datacenter_name, datacenters[datacenter_name]])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"sortby",
",",
"datacenter",
")",
":",
"file_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"mask",
"=",
"\"mask[serviceResource[datacenter[name]],\"",
"\"replicationPartners[serviceResource[datacenter[name]]]]\"",
"file_volumes",
"=",
"file_manager",
".",
"list_file_volumes",
"(",
"datacenter",
"=",
"datacenter",
",",
"mask",
"=",
"mask",
")",
"datacenters",
"=",
"dict",
"(",
")",
"for",
"volume",
"in",
"file_volumes",
":",
"service_resource",
"=",
"volume",
"[",
"'serviceResource'",
"]",
"if",
"'datacenter'",
"in",
"service_resource",
":",
"datacenter_name",
"=",
"service_resource",
"[",
"'datacenter'",
"]",
"[",
"'name'",
"]",
"if",
"datacenter_name",
"not",
"in",
"datacenters",
".",
"keys",
"(",
")",
":",
"datacenters",
"[",
"datacenter_name",
"]",
"=",
"1",
"else",
":",
"datacenters",
"[",
"datacenter_name",
"]",
"+=",
"1",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"DEFAULT_COLUMNS",
")",
"table",
".",
"sortby",
"=",
"sortby",
"for",
"datacenter_name",
"in",
"datacenters",
":",
"table",
".",
"add_row",
"(",
"[",
"datacenter_name",
",",
"datacenters",
"[",
"datacenter_name",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| List number of file storage volumes per datacenter. | [
"List",
"number",
"of",
"file",
"storage",
"volumes",
"per",
"datacenter",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/count.py#L19-L41 |
softlayer/softlayer-python | SoftLayer/CLI/hardware/create_options.py | cli | def cli(env):
"""Server order options for a given chassis."""
hardware_manager = hardware.HardwareManager(env.client)
options = hardware_manager.get_create_options()
tables = []
# Datacenters
dc_table = formatting.Table(['datacenter', 'value'])
dc_table.sortby = 'value'
for location in options['locations']:
dc_table.add_row([location['name'], location['key']])
tables.append(dc_table)
# Presets
preset_table = formatting.Table(['size', 'value'])
preset_table.sortby = 'value'
for size in options['sizes']:
preset_table.add_row([size['name'], size['key']])
tables.append(preset_table)
# Operating systems
os_table = formatting.Table(['operating_system', 'value'])
os_table.sortby = 'value'
for operating_system in options['operating_systems']:
os_table.add_row([operating_system['name'], operating_system['key']])
tables.append(os_table)
# Port speed
port_speed_table = formatting.Table(['port_speed', 'value'])
port_speed_table.sortby = 'value'
for speed in options['port_speeds']:
port_speed_table.add_row([speed['name'], speed['key']])
tables.append(port_speed_table)
# Extras
extras_table = formatting.Table(['extras', 'value'])
extras_table.sortby = 'value'
for extra in options['extras']:
extras_table.add_row([extra['name'], extra['key']])
tables.append(extras_table)
env.fout(formatting.listing(tables, separator='\n')) | python | def cli(env):
hardware_manager = hardware.HardwareManager(env.client)
options = hardware_manager.get_create_options()
tables = []
dc_table = formatting.Table(['datacenter', 'value'])
dc_table.sortby = 'value'
for location in options['locations']:
dc_table.add_row([location['name'], location['key']])
tables.append(dc_table)
preset_table = formatting.Table(['size', 'value'])
preset_table.sortby = 'value'
for size in options['sizes']:
preset_table.add_row([size['name'], size['key']])
tables.append(preset_table)
os_table = formatting.Table(['operating_system', 'value'])
os_table.sortby = 'value'
for operating_system in options['operating_systems']:
os_table.add_row([operating_system['name'], operating_system['key']])
tables.append(os_table)
port_speed_table = formatting.Table(['port_speed', 'value'])
port_speed_table.sortby = 'value'
for speed in options['port_speeds']:
port_speed_table.add_row([speed['name'], speed['key']])
tables.append(port_speed_table)
extras_table = formatting.Table(['extras', 'value'])
extras_table.sortby = 'value'
for extra in options['extras']:
extras_table.add_row([extra['name'], extra['key']])
tables.append(extras_table)
env.fout(formatting.listing(tables, separator='\n')) | [
"def",
"cli",
"(",
"env",
")",
":",
"hardware_manager",
"=",
"hardware",
".",
"HardwareManager",
"(",
"env",
".",
"client",
")",
"options",
"=",
"hardware_manager",
".",
"get_create_options",
"(",
")",
"tables",
"=",
"[",
"]",
"# Datacenters",
"dc_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'datacenter'",
",",
"'value'",
"]",
")",
"dc_table",
".",
"sortby",
"=",
"'value'",
"for",
"location",
"in",
"options",
"[",
"'locations'",
"]",
":",
"dc_table",
".",
"add_row",
"(",
"[",
"location",
"[",
"'name'",
"]",
",",
"location",
"[",
"'key'",
"]",
"]",
")",
"tables",
".",
"append",
"(",
"dc_table",
")",
"# Presets",
"preset_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'size'",
",",
"'value'",
"]",
")",
"preset_table",
".",
"sortby",
"=",
"'value'",
"for",
"size",
"in",
"options",
"[",
"'sizes'",
"]",
":",
"preset_table",
".",
"add_row",
"(",
"[",
"size",
"[",
"'name'",
"]",
",",
"size",
"[",
"'key'",
"]",
"]",
")",
"tables",
".",
"append",
"(",
"preset_table",
")",
"# Operating systems",
"os_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'operating_system'",
",",
"'value'",
"]",
")",
"os_table",
".",
"sortby",
"=",
"'value'",
"for",
"operating_system",
"in",
"options",
"[",
"'operating_systems'",
"]",
":",
"os_table",
".",
"add_row",
"(",
"[",
"operating_system",
"[",
"'name'",
"]",
",",
"operating_system",
"[",
"'key'",
"]",
"]",
")",
"tables",
".",
"append",
"(",
"os_table",
")",
"# Port speed",
"port_speed_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'port_speed'",
",",
"'value'",
"]",
")",
"port_speed_table",
".",
"sortby",
"=",
"'value'",
"for",
"speed",
"in",
"options",
"[",
"'port_speeds'",
"]",
":",
"port_speed_table",
".",
"add_row",
"(",
"[",
"speed",
"[",
"'name'",
"]",
",",
"speed",
"[",
"'key'",
"]",
"]",
")",
"tables",
".",
"append",
"(",
"port_speed_table",
")",
"# Extras",
"extras_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'extras'",
",",
"'value'",
"]",
")",
"extras_table",
".",
"sortby",
"=",
"'value'",
"for",
"extra",
"in",
"options",
"[",
"'extras'",
"]",
":",
"extras_table",
".",
"add_row",
"(",
"[",
"extra",
"[",
"'name'",
"]",
",",
"extra",
"[",
"'key'",
"]",
"]",
")",
"tables",
".",
"append",
"(",
"extras_table",
")",
"env",
".",
"fout",
"(",
"formatting",
".",
"listing",
"(",
"tables",
",",
"separator",
"=",
"'\\n'",
")",
")"
]
| Server order options for a given chassis. | [
"Server",
"order",
"options",
"for",
"a",
"given",
"chassis",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/create_options.py#L13-L56 |
softlayer/softlayer-python | SoftLayer/CLI/firewall/__init__.py | parse_id | def parse_id(input_id):
"""Helper package to retrieve the actual IDs.
:param input_id: the ID provided by the user
:returns: A list of valid IDs
"""
key_value = input_id.split(':')
if len(key_value) != 2:
raise exceptions.CLIAbort(
'Invalid ID %s: ID should be of the form xxx:yyy' % input_id)
return key_value[0], int(key_value[1]) | python | def parse_id(input_id):
key_value = input_id.split(':')
if len(key_value) != 2:
raise exceptions.CLIAbort(
'Invalid ID %s: ID should be of the form xxx:yyy' % input_id)
return key_value[0], int(key_value[1]) | [
"def",
"parse_id",
"(",
"input_id",
")",
":",
"key_value",
"=",
"input_id",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"key_value",
")",
"!=",
"2",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Invalid ID %s: ID should be of the form xxx:yyy'",
"%",
"input_id",
")",
"return",
"key_value",
"[",
"0",
"]",
",",
"int",
"(",
"key_value",
"[",
"1",
"]",
")"
]
| Helper package to retrieve the actual IDs.
:param input_id: the ID provided by the user
:returns: A list of valid IDs | [
"Helper",
"package",
"to",
"retrieve",
"the",
"actual",
"IDs",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/__init__.py#L7-L18 |
softlayer/softlayer-python | SoftLayer/CLI/call_api.py | _build_filters | def _build_filters(_filters):
"""Builds filters using the filter options passed into the CLI.
This only supports the equals keyword at the moment.
"""
root = utils.NestedDict({})
for _filter in _filters:
operation = None
for operation, token in SPLIT_TOKENS:
# split "some.key=value" into ["some.key", "value"]
top_parts = _filter.split(token, 1)
if len(top_parts) == 2:
break
else:
raise exceptions.CLIAbort('Failed to find valid operation for: %s'
% _filter)
key, value = top_parts
current = root
# split "some.key" into ["some", "key"]
parts = [part.strip() for part in key.split('.')]
# Actually drill down and add the filter
for part in parts[:-1]:
current = current[part]
if operation == 'eq':
current[parts[-1]] = utils.query_filter(value.strip())
elif operation == 'in':
current[parts[-1]] = {
'operation': 'in',
'options': [{
'name': 'data',
'value': [p.strip() for p in value.split(',')],
}],
}
return root.to_dict() | python | def _build_filters(_filters):
root = utils.NestedDict({})
for _filter in _filters:
operation = None
for operation, token in SPLIT_TOKENS:
top_parts = _filter.split(token, 1)
if len(top_parts) == 2:
break
else:
raise exceptions.CLIAbort('Failed to find valid operation for: %s'
% _filter)
key, value = top_parts
current = root
parts = [part.strip() for part in key.split('.')]
for part in parts[:-1]:
current = current[part]
if operation == 'eq':
current[parts[-1]] = utils.query_filter(value.strip())
elif operation == 'in':
current[parts[-1]] = {
'operation': 'in',
'options': [{
'name': 'data',
'value': [p.strip() for p in value.split(',')],
}],
}
return root.to_dict() | [
"def",
"_build_filters",
"(",
"_filters",
")",
":",
"root",
"=",
"utils",
".",
"NestedDict",
"(",
"{",
"}",
")",
"for",
"_filter",
"in",
"_filters",
":",
"operation",
"=",
"None",
"for",
"operation",
",",
"token",
"in",
"SPLIT_TOKENS",
":",
"# split \"some.key=value\" into [\"some.key\", \"value\"]",
"top_parts",
"=",
"_filter",
".",
"split",
"(",
"token",
",",
"1",
")",
"if",
"len",
"(",
"top_parts",
")",
"==",
"2",
":",
"break",
"else",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Failed to find valid operation for: %s'",
"%",
"_filter",
")",
"key",
",",
"value",
"=",
"top_parts",
"current",
"=",
"root",
"# split \"some.key\" into [\"some\", \"key\"]",
"parts",
"=",
"[",
"part",
".",
"strip",
"(",
")",
"for",
"part",
"in",
"key",
".",
"split",
"(",
"'.'",
")",
"]",
"# Actually drill down and add the filter",
"for",
"part",
"in",
"parts",
"[",
":",
"-",
"1",
"]",
":",
"current",
"=",
"current",
"[",
"part",
"]",
"if",
"operation",
"==",
"'eq'",
":",
"current",
"[",
"parts",
"[",
"-",
"1",
"]",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"value",
".",
"strip",
"(",
")",
")",
"elif",
"operation",
"==",
"'in'",
":",
"current",
"[",
"parts",
"[",
"-",
"1",
"]",
"]",
"=",
"{",
"'operation'",
":",
"'in'",
",",
"'options'",
":",
"[",
"{",
"'name'",
":",
"'data'",
",",
"'value'",
":",
"[",
"p",
".",
"strip",
"(",
")",
"for",
"p",
"in",
"value",
".",
"split",
"(",
"','",
")",
"]",
",",
"}",
"]",
",",
"}",
"return",
"root",
".",
"to_dict",
"(",
")"
]
| Builds filters using the filter options passed into the CLI.
This only supports the equals keyword at the moment. | [
"Builds",
"filters",
"using",
"the",
"filter",
"options",
"passed",
"into",
"the",
"CLI",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/call_api.py#L16-L53 |
softlayer/softlayer-python | SoftLayer/CLI/call_api.py | cli | def cli(env, service, method, parameters, _id, _filters, mask, limit, offset,
output_python=False):
"""Call arbitrary API endpoints with the given SERVICE and METHOD.
Example::
slcli call-api Account getObject
slcli call-api Account getVirtualGuests --limit=10 --mask=id,hostname
slcli call-api Virtual_Guest getObject --id=12345
slcli call-api Metric_Tracking_Object getBandwidthData --id=1234 \\
"2015-01-01 00:00:00" "2015-01-1 12:00:00" public
slcli call-api Account getVirtualGuests \\
-f 'virtualGuests.datacenter.name=dal05' \\
-f 'virtualGuests.maxCpu=4' \\
--mask=id,hostname,datacenter.name,maxCpu
slcli call-api Account getVirtualGuests \\
-f 'virtualGuests.datacenter.name IN dal05,sng01'
"""
args = [service, method] + list(parameters)
kwargs = {
'id': _id,
'filter': _build_filters(_filters),
'mask': mask,
'limit': limit,
'offset': offset,
}
if output_python:
env.out(_build_python_example(args, kwargs))
else:
result = env.client.call(*args, **kwargs)
env.fout(formatting.iter_to_table(result)) | python | def cli(env, service, method, parameters, _id, _filters, mask, limit, offset,
output_python=False):
args = [service, method] + list(parameters)
kwargs = {
'id': _id,
'filter': _build_filters(_filters),
'mask': mask,
'limit': limit,
'offset': offset,
}
if output_python:
env.out(_build_python_example(args, kwargs))
else:
result = env.client.call(*args, **kwargs)
env.fout(formatting.iter_to_table(result)) | [
"def",
"cli",
"(",
"env",
",",
"service",
",",
"method",
",",
"parameters",
",",
"_id",
",",
"_filters",
",",
"mask",
",",
"limit",
",",
"offset",
",",
"output_python",
"=",
"False",
")",
":",
"args",
"=",
"[",
"service",
",",
"method",
"]",
"+",
"list",
"(",
"parameters",
")",
"kwargs",
"=",
"{",
"'id'",
":",
"_id",
",",
"'filter'",
":",
"_build_filters",
"(",
"_filters",
")",
",",
"'mask'",
":",
"mask",
",",
"'limit'",
":",
"limit",
",",
"'offset'",
":",
"offset",
",",
"}",
"if",
"output_python",
":",
"env",
".",
"out",
"(",
"_build_python_example",
"(",
"args",
",",
"kwargs",
")",
")",
"else",
":",
"result",
"=",
"env",
".",
"client",
".",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"env",
".",
"fout",
"(",
"formatting",
".",
"iter_to_table",
"(",
"result",
")",
")"
]
| Call arbitrary API endpoints with the given SERVICE and METHOD.
Example::
slcli call-api Account getObject
slcli call-api Account getVirtualGuests --limit=10 --mask=id,hostname
slcli call-api Virtual_Guest getObject --id=12345
slcli call-api Metric_Tracking_Object getBandwidthData --id=1234 \\
"2015-01-01 00:00:00" "2015-01-1 12:00:00" public
slcli call-api Account getVirtualGuests \\
-f 'virtualGuests.datacenter.name=dal05' \\
-f 'virtualGuests.maxCpu=4' \\
--mask=id,hostname,datacenter.name,maxCpu
slcli call-api Account getVirtualGuests \\
-f 'virtualGuests.datacenter.name IN dal05,sng01' | [
"Call",
"arbitrary",
"API",
"endpoints",
"with",
"the",
"given",
"SERVICE",
"and",
"METHOD",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/call_api.py#L86-L118 |
softlayer/softlayer-python | SoftLayer/CLI/block/snapshot/list.py | cli | def cli(env, volume_id, sortby, columns):
"""List block storage snapshots."""
block_manager = SoftLayer.BlockStorageManager(env.client)
snapshots = block_manager.get_block_volume_snapshot_list(
volume_id,
mask=columns.mask()
)
table = formatting.Table(columns.columns)
table.sortby = sortby
for snapshot in snapshots:
table.add_row([value or formatting.blank()
for value in columns.row(snapshot)])
env.fout(table) | python | def cli(env, volume_id, sortby, columns):
block_manager = SoftLayer.BlockStorageManager(env.client)
snapshots = block_manager.get_block_volume_snapshot_list(
volume_id,
mask=columns.mask()
)
table = formatting.Table(columns.columns)
table.sortby = sortby
for snapshot in snapshots:
table.add_row([value or formatting.blank()
for value in columns.row(snapshot)])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"sortby",
",",
"columns",
")",
":",
"block_manager",
"=",
"SoftLayer",
".",
"BlockStorageManager",
"(",
"env",
".",
"client",
")",
"snapshots",
"=",
"block_manager",
".",
"get_block_volume_snapshot_list",
"(",
"volume_id",
",",
"mask",
"=",
"columns",
".",
"mask",
"(",
")",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"columns",
".",
"columns",
")",
"table",
".",
"sortby",
"=",
"sortby",
"for",
"snapshot",
"in",
"snapshots",
":",
"table",
".",
"add_row",
"(",
"[",
"value",
"or",
"formatting",
".",
"blank",
"(",
")",
"for",
"value",
"in",
"columns",
".",
"row",
"(",
"snapshot",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| List block storage snapshots. | [
"List",
"block",
"storage",
"snapshots",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/snapshot/list.py#L38-L53 |
softlayer/softlayer-python | SoftLayer/CLI/hardware/detail.py | cli | def cli(env, identifier, passwords, price):
"""Get details for a hardware device."""
hardware = SoftLayer.HardwareManager(env.client)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
hardware_id = helpers.resolve_id(hardware.resolve_ids, identifier, 'hardware')
result = hardware.get_hardware(hardware_id)
result = utils.NestedDict(result)
operating_system = utils.lookup(result, 'operatingSystem', 'softwareLicense', 'softwareDescription') or {}
memory = formatting.gb(result.get('memoryCapacity', 0))
owner = None
if utils.lookup(result, 'billingItem') != []:
owner = utils.lookup(result, 'billingItem', 'orderItem', 'order', 'userRecord', 'username')
table.add_row(['id', result['id']])
table.add_row(['guid', result['globalIdentifier'] or formatting.blank()])
table.add_row(['hostname', result['hostname']])
table.add_row(['domain', result['domain']])
table.add_row(['fqdn', result['fullyQualifiedDomainName']])
table.add_row(['status', result['hardwareStatus']['status']])
table.add_row(['datacenter', result['datacenter']['name'] or formatting.blank()])
table.add_row(['cores', result['processorPhysicalCoreAmount']])
table.add_row(['memory', memory])
table.add_row(['public_ip', result['primaryIpAddress'] or formatting.blank()])
table.add_row(['private_ip', result['primaryBackendIpAddress'] or formatting.blank()])
table.add_row(['ipmi_ip', result['networkManagementIpAddress'] or formatting.blank()])
table.add_row(['os', operating_system.get('name') or formatting.blank()])
table.add_row(['os_version', operating_system.get('version') or formatting.blank()])
table.add_row(['created', result['provisionDate'] or formatting.blank()])
table.add_row(['owner', owner or formatting.blank()])
vlan_table = formatting.Table(['type', 'number', 'id'])
for vlan in result['networkVlans']:
vlan_table.add_row([vlan['networkSpace'], vlan['vlanNumber'], vlan['id']])
table.add_row(['vlans', vlan_table])
if result.get('notes'):
table.add_row(['notes', result['notes']])
if price:
total_price = utils.lookup(result, 'billingItem', 'nextInvoiceTotalRecurringAmount') or 0
price_table = formatting.Table(['Item', 'Recurring Price'])
price_table.add_row(['Total', total_price])
for item in utils.lookup(result, 'billingItem', 'children') or []:
price_table.add_row([item['description'], item['nextInvoiceTotalRecurringAmount']])
table.add_row(['prices', price_table])
if passwords:
pass_table = formatting.Table(['username', 'password'])
for item in result['operatingSystem']['passwords']:
pass_table.add_row([item['username'], item['password']])
table.add_row(['users', pass_table])
pass_table = formatting.Table(['ipmi_username', 'password'])
for item in result['remoteManagementAccounts']:
pass_table.add_row([item['username'], item['password']])
table.add_row(['remote users', pass_table])
table.add_row(['tags', formatting.tags(result['tagReferences'])])
env.fout(table) | python | def cli(env, identifier, passwords, price):
hardware = SoftLayer.HardwareManager(env.client)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
hardware_id = helpers.resolve_id(hardware.resolve_ids, identifier, 'hardware')
result = hardware.get_hardware(hardware_id)
result = utils.NestedDict(result)
operating_system = utils.lookup(result, 'operatingSystem', 'softwareLicense', 'softwareDescription') or {}
memory = formatting.gb(result.get('memoryCapacity', 0))
owner = None
if utils.lookup(result, 'billingItem') != []:
owner = utils.lookup(result, 'billingItem', 'orderItem', 'order', 'userRecord', 'username')
table.add_row(['id', result['id']])
table.add_row(['guid', result['globalIdentifier'] or formatting.blank()])
table.add_row(['hostname', result['hostname']])
table.add_row(['domain', result['domain']])
table.add_row(['fqdn', result['fullyQualifiedDomainName']])
table.add_row(['status', result['hardwareStatus']['status']])
table.add_row(['datacenter', result['datacenter']['name'] or formatting.blank()])
table.add_row(['cores', result['processorPhysicalCoreAmount']])
table.add_row(['memory', memory])
table.add_row(['public_ip', result['primaryIpAddress'] or formatting.blank()])
table.add_row(['private_ip', result['primaryBackendIpAddress'] or formatting.blank()])
table.add_row(['ipmi_ip', result['networkManagementIpAddress'] or formatting.blank()])
table.add_row(['os', operating_system.get('name') or formatting.blank()])
table.add_row(['os_version', operating_system.get('version') or formatting.blank()])
table.add_row(['created', result['provisionDate'] or formatting.blank()])
table.add_row(['owner', owner or formatting.blank()])
vlan_table = formatting.Table(['type', 'number', 'id'])
for vlan in result['networkVlans']:
vlan_table.add_row([vlan['networkSpace'], vlan['vlanNumber'], vlan['id']])
table.add_row(['vlans', vlan_table])
if result.get('notes'):
table.add_row(['notes', result['notes']])
if price:
total_price = utils.lookup(result, 'billingItem', 'nextInvoiceTotalRecurringAmount') or 0
price_table = formatting.Table(['Item', 'Recurring Price'])
price_table.add_row(['Total', total_price])
for item in utils.lookup(result, 'billingItem', 'children') or []:
price_table.add_row([item['description'], item['nextInvoiceTotalRecurringAmount']])
table.add_row(['prices', price_table])
if passwords:
pass_table = formatting.Table(['username', 'password'])
for item in result['operatingSystem']['passwords']:
pass_table.add_row([item['username'], item['password']])
table.add_row(['users', pass_table])
pass_table = formatting.Table(['ipmi_username', 'password'])
for item in result['remoteManagementAccounts']:
pass_table.add_row([item['username'], item['password']])
table.add_row(['remote users', pass_table])
table.add_row(['tags', formatting.tags(result['tagReferences'])])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"passwords",
",",
"price",
")",
":",
"hardware",
"=",
"SoftLayer",
".",
"HardwareManager",
"(",
"env",
".",
"client",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"hardware_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"hardware",
".",
"resolve_ids",
",",
"identifier",
",",
"'hardware'",
")",
"result",
"=",
"hardware",
".",
"get_hardware",
"(",
"hardware_id",
")",
"result",
"=",
"utils",
".",
"NestedDict",
"(",
"result",
")",
"operating_system",
"=",
"utils",
".",
"lookup",
"(",
"result",
",",
"'operatingSystem'",
",",
"'softwareLicense'",
",",
"'softwareDescription'",
")",
"or",
"{",
"}",
"memory",
"=",
"formatting",
".",
"gb",
"(",
"result",
".",
"get",
"(",
"'memoryCapacity'",
",",
"0",
")",
")",
"owner",
"=",
"None",
"if",
"utils",
".",
"lookup",
"(",
"result",
",",
"'billingItem'",
")",
"!=",
"[",
"]",
":",
"owner",
"=",
"utils",
".",
"lookup",
"(",
"result",
",",
"'billingItem'",
",",
"'orderItem'",
",",
"'order'",
",",
"'userRecord'",
",",
"'username'",
")",
"table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"result",
"[",
"'id'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'guid'",
",",
"result",
"[",
"'globalIdentifier'",
"]",
"or",
"formatting",
".",
"blank",
"(",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'hostname'",
",",
"result",
"[",
"'hostname'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'domain'",
",",
"result",
"[",
"'domain'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'fqdn'",
",",
"result",
"[",
"'fullyQualifiedDomainName'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'status'",
",",
"result",
"[",
"'hardwareStatus'",
"]",
"[",
"'status'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'datacenter'",
",",
"result",
"[",
"'datacenter'",
"]",
"[",
"'name'",
"]",
"or",
"formatting",
".",
"blank",
"(",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'cores'",
",",
"result",
"[",
"'processorPhysicalCoreAmount'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'memory'",
",",
"memory",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'public_ip'",
",",
"result",
"[",
"'primaryIpAddress'",
"]",
"or",
"formatting",
".",
"blank",
"(",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'private_ip'",
",",
"result",
"[",
"'primaryBackendIpAddress'",
"]",
"or",
"formatting",
".",
"blank",
"(",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'ipmi_ip'",
",",
"result",
"[",
"'networkManagementIpAddress'",
"]",
"or",
"formatting",
".",
"blank",
"(",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'os'",
",",
"operating_system",
".",
"get",
"(",
"'name'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'os_version'",
",",
"operating_system",
".",
"get",
"(",
"'version'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'created'",
",",
"result",
"[",
"'provisionDate'",
"]",
"or",
"formatting",
".",
"blank",
"(",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'owner'",
",",
"owner",
"or",
"formatting",
".",
"blank",
"(",
")",
"]",
")",
"vlan_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'type'",
",",
"'number'",
",",
"'id'",
"]",
")",
"for",
"vlan",
"in",
"result",
"[",
"'networkVlans'",
"]",
":",
"vlan_table",
".",
"add_row",
"(",
"[",
"vlan",
"[",
"'networkSpace'",
"]",
",",
"vlan",
"[",
"'vlanNumber'",
"]",
",",
"vlan",
"[",
"'id'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'vlans'",
",",
"vlan_table",
"]",
")",
"if",
"result",
".",
"get",
"(",
"'notes'",
")",
":",
"table",
".",
"add_row",
"(",
"[",
"'notes'",
",",
"result",
"[",
"'notes'",
"]",
"]",
")",
"if",
"price",
":",
"total_price",
"=",
"utils",
".",
"lookup",
"(",
"result",
",",
"'billingItem'",
",",
"'nextInvoiceTotalRecurringAmount'",
")",
"or",
"0",
"price_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Item'",
",",
"'Recurring Price'",
"]",
")",
"price_table",
".",
"add_row",
"(",
"[",
"'Total'",
",",
"total_price",
"]",
")",
"for",
"item",
"in",
"utils",
".",
"lookup",
"(",
"result",
",",
"'billingItem'",
",",
"'children'",
")",
"or",
"[",
"]",
":",
"price_table",
".",
"add_row",
"(",
"[",
"item",
"[",
"'description'",
"]",
",",
"item",
"[",
"'nextInvoiceTotalRecurringAmount'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'prices'",
",",
"price_table",
"]",
")",
"if",
"passwords",
":",
"pass_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'username'",
",",
"'password'",
"]",
")",
"for",
"item",
"in",
"result",
"[",
"'operatingSystem'",
"]",
"[",
"'passwords'",
"]",
":",
"pass_table",
".",
"add_row",
"(",
"[",
"item",
"[",
"'username'",
"]",
",",
"item",
"[",
"'password'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'users'",
",",
"pass_table",
"]",
")",
"pass_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'ipmi_username'",
",",
"'password'",
"]",
")",
"for",
"item",
"in",
"result",
"[",
"'remoteManagementAccounts'",
"]",
":",
"pass_table",
".",
"add_row",
"(",
"[",
"item",
"[",
"'username'",
"]",
",",
"item",
"[",
"'password'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'remote users'",
",",
"pass_table",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'tags'",
",",
"formatting",
".",
"tags",
"(",
"result",
"[",
"'tagReferences'",
"]",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Get details for a hardware device. | [
"Get",
"details",
"for",
"a",
"hardware",
"device",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/detail.py#L18-L87 |
softlayer/softlayer-python | SoftLayer/CLI/virt/create_options.py | cli | def cli(env):
"""Virtual server order options."""
vsi = SoftLayer.VSManager(env.client)
result = vsi.get_create_options()
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
# Datacenters
datacenters = [dc['template']['datacenter']['name']
for dc in result['datacenters']]
datacenters = sorted(datacenters)
table.add_row(['datacenter',
formatting.listing(datacenters, separator='\n')])
def _add_flavor_rows(flavor_key, flavor_label, flavor_options):
flavors = []
for flavor_option in flavor_options:
flavor_key_name = utils.lookup(flavor_option, 'flavor', 'keyName')
if not flavor_key_name.startswith(flavor_key):
continue
flavors.append(flavor_key_name)
if len(flavors) > 0:
table.add_row(['flavors (%s)' % flavor_label,
formatting.listing(flavors, separator='\n')])
if result.get('flavors', None):
_add_flavor_rows('B1', 'balanced', result['flavors'])
_add_flavor_rows('BL1', 'balanced local - hdd', result['flavors'])
_add_flavor_rows('BL2', 'balanced local - ssd', result['flavors'])
_add_flavor_rows('C1', 'compute', result['flavors'])
_add_flavor_rows('M1', 'memory', result['flavors'])
_add_flavor_rows('AC', 'GPU', result['flavors'])
# CPUs
standard_cpus = [int(x['template']['startCpus']) for x in result['processors']
if not x['template'].get('dedicatedAccountHostOnlyFlag',
False)
and not x['template'].get('dedicatedHost', None)]
ded_cpus = [int(x['template']['startCpus']) for x in result['processors']
if x['template'].get('dedicatedAccountHostOnlyFlag', False)]
ded_host_cpus = [int(x['template']['startCpus']) for x in result['processors']
if x['template'].get('dedicatedHost', None)]
standard_cpus = sorted(standard_cpus)
table.add_row(['cpus (standard)', formatting.listing(standard_cpus, separator=',')])
ded_cpus = sorted(ded_cpus)
table.add_row(['cpus (dedicated)', formatting.listing(ded_cpus, separator=',')])
ded_host_cpus = sorted(ded_host_cpus)
table.add_row(['cpus (dedicated host)', formatting.listing(ded_host_cpus, separator=',')])
# Memory
memory = [int(m['template']['maxMemory']) for m in result['memory']
if not m['itemPrice'].get('dedicatedHostInstanceFlag', False)]
ded_host_memory = [int(m['template']['maxMemory']) for m in result['memory']
if m['itemPrice'].get('dedicatedHostInstanceFlag', False)]
memory = sorted(memory)
table.add_row(['memory',
formatting.listing(memory, separator=',')])
ded_host_memory = sorted(ded_host_memory)
table.add_row(['memory (dedicated host)',
formatting.listing(ded_host_memory, separator=',')])
# Operating Systems
op_sys = [o['template']['operatingSystemReferenceCode'] for o in
result['operatingSystems']]
op_sys = sorted(op_sys)
os_summary = set()
for operating_system in op_sys:
os_summary.add(operating_system[0:operating_system.find('_')])
for summary in sorted(os_summary):
table.add_row([
'os (%s)' % summary,
os.linesep.join(sorted([x for x in op_sys
if x[0:len(summary)] == summary]))
])
# Disk
local_disks = [x for x in result['blockDevices']
if x['template'].get('localDiskFlag', False)
and not x['itemPrice'].get('dedicatedHostInstanceFlag',
False)]
ded_host_local_disks = [x for x in result['blockDevices']
if x['template'].get('localDiskFlag', False)
and x['itemPrice'].get('dedicatedHostInstanceFlag',
False)]
san_disks = [x for x in result['blockDevices']
if not x['template'].get('localDiskFlag', False)]
def add_block_rows(disks, name):
"""Add block rows to the table."""
simple = {}
for disk in disks:
block = disk['template']['blockDevices'][0]
bid = block['device']
if bid not in simple:
simple[bid] = []
simple[bid].append(str(block['diskImage']['capacity']))
for label in sorted(simple):
table.add_row(['%s disk(%s)' % (name, label),
formatting.listing(simple[label],
separator=',')])
add_block_rows(san_disks, 'san')
add_block_rows(local_disks, 'local')
add_block_rows(ded_host_local_disks, 'local (dedicated host)')
# Network
speeds = []
ded_host_speeds = []
for option in result['networkComponents']:
template = option.get('template', None)
price = option.get('itemPrice', None)
if not template or not price \
or not template.get('networkComponents', None):
continue
if not template['networkComponents'][0] \
or not template['networkComponents'][0].get('maxSpeed', None):
continue
max_speed = str(template['networkComponents'][0]['maxSpeed'])
if price.get('dedicatedHostInstanceFlag', False) \
and max_speed not in ded_host_speeds:
ded_host_speeds.append(max_speed)
elif max_speed not in speeds:
speeds.append(max_speed)
speeds = sorted(speeds)
table.add_row(['nic', formatting.listing(speeds, separator=',')])
ded_host_speeds = sorted(ded_host_speeds)
table.add_row(['nic (dedicated host)',
formatting.listing(ded_host_speeds, separator=',')])
env.fout(table) | python | def cli(env):
vsi = SoftLayer.VSManager(env.client)
result = vsi.get_create_options()
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
datacenters = [dc['template']['datacenter']['name']
for dc in result['datacenters']]
datacenters = sorted(datacenters)
table.add_row(['datacenter',
formatting.listing(datacenters, separator='\n')])
def _add_flavor_rows(flavor_key, flavor_label, flavor_options):
flavors = []
for flavor_option in flavor_options:
flavor_key_name = utils.lookup(flavor_option, 'flavor', 'keyName')
if not flavor_key_name.startswith(flavor_key):
continue
flavors.append(flavor_key_name)
if len(flavors) > 0:
table.add_row(['flavors (%s)' % flavor_label,
formatting.listing(flavors, separator='\n')])
if result.get('flavors', None):
_add_flavor_rows('B1', 'balanced', result['flavors'])
_add_flavor_rows('BL1', 'balanced local - hdd', result['flavors'])
_add_flavor_rows('BL2', 'balanced local - ssd', result['flavors'])
_add_flavor_rows('C1', 'compute', result['flavors'])
_add_flavor_rows('M1', 'memory', result['flavors'])
_add_flavor_rows('AC', 'GPU', result['flavors'])
standard_cpus = [int(x['template']['startCpus']) for x in result['processors']
if not x['template'].get('dedicatedAccountHostOnlyFlag',
False)
and not x['template'].get('dedicatedHost', None)]
ded_cpus = [int(x['template']['startCpus']) for x in result['processors']
if x['template'].get('dedicatedAccountHostOnlyFlag', False)]
ded_host_cpus = [int(x['template']['startCpus']) for x in result['processors']
if x['template'].get('dedicatedHost', None)]
standard_cpus = sorted(standard_cpus)
table.add_row(['cpus (standard)', formatting.listing(standard_cpus, separator=',')])
ded_cpus = sorted(ded_cpus)
table.add_row(['cpus (dedicated)', formatting.listing(ded_cpus, separator=',')])
ded_host_cpus = sorted(ded_host_cpus)
table.add_row(['cpus (dedicated host)', formatting.listing(ded_host_cpus, separator=',')])
memory = [int(m['template']['maxMemory']) for m in result['memory']
if not m['itemPrice'].get('dedicatedHostInstanceFlag', False)]
ded_host_memory = [int(m['template']['maxMemory']) for m in result['memory']
if m['itemPrice'].get('dedicatedHostInstanceFlag', False)]
memory = sorted(memory)
table.add_row(['memory',
formatting.listing(memory, separator=',')])
ded_host_memory = sorted(ded_host_memory)
table.add_row(['memory (dedicated host)',
formatting.listing(ded_host_memory, separator=',')])
op_sys = [o['template']['operatingSystemReferenceCode'] for o in
result['operatingSystems']]
op_sys = sorted(op_sys)
os_summary = set()
for operating_system in op_sys:
os_summary.add(operating_system[0:operating_system.find('_')])
for summary in sorted(os_summary):
table.add_row([
'os (%s)' % summary,
os.linesep.join(sorted([x for x in op_sys
if x[0:len(summary)] == summary]))
])
local_disks = [x for x in result['blockDevices']
if x['template'].get('localDiskFlag', False)
and not x['itemPrice'].get('dedicatedHostInstanceFlag',
False)]
ded_host_local_disks = [x for x in result['blockDevices']
if x['template'].get('localDiskFlag', False)
and x['itemPrice'].get('dedicatedHostInstanceFlag',
False)]
san_disks = [x for x in result['blockDevices']
if not x['template'].get('localDiskFlag', False)]
def add_block_rows(disks, name):
simple = {}
for disk in disks:
block = disk['template']['blockDevices'][0]
bid = block['device']
if bid not in simple:
simple[bid] = []
simple[bid].append(str(block['diskImage']['capacity']))
for label in sorted(simple):
table.add_row(['%s disk(%s)' % (name, label),
formatting.listing(simple[label],
separator=',')])
add_block_rows(san_disks, 'san')
add_block_rows(local_disks, 'local')
add_block_rows(ded_host_local_disks, 'local (dedicated host)')
speeds = []
ded_host_speeds = []
for option in result['networkComponents']:
template = option.get('template', None)
price = option.get('itemPrice', None)
if not template or not price \
or not template.get('networkComponents', None):
continue
if not template['networkComponents'][0] \
or not template['networkComponents'][0].get('maxSpeed', None):
continue
max_speed = str(template['networkComponents'][0]['maxSpeed'])
if price.get('dedicatedHostInstanceFlag', False) \
and max_speed not in ded_host_speeds:
ded_host_speeds.append(max_speed)
elif max_speed not in speeds:
speeds.append(max_speed)
speeds = sorted(speeds)
table.add_row(['nic', formatting.listing(speeds, separator=',')])
ded_host_speeds = sorted(ded_host_speeds)
table.add_row(['nic (dedicated host)',
formatting.listing(ded_host_speeds, separator=',')])
env.fout(table) | [
"def",
"cli",
"(",
"env",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"result",
"=",
"vsi",
".",
"get_create_options",
"(",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"# Datacenters",
"datacenters",
"=",
"[",
"dc",
"[",
"'template'",
"]",
"[",
"'datacenter'",
"]",
"[",
"'name'",
"]",
"for",
"dc",
"in",
"result",
"[",
"'datacenters'",
"]",
"]",
"datacenters",
"=",
"sorted",
"(",
"datacenters",
")",
"table",
".",
"add_row",
"(",
"[",
"'datacenter'",
",",
"formatting",
".",
"listing",
"(",
"datacenters",
",",
"separator",
"=",
"'\\n'",
")",
"]",
")",
"def",
"_add_flavor_rows",
"(",
"flavor_key",
",",
"flavor_label",
",",
"flavor_options",
")",
":",
"flavors",
"=",
"[",
"]",
"for",
"flavor_option",
"in",
"flavor_options",
":",
"flavor_key_name",
"=",
"utils",
".",
"lookup",
"(",
"flavor_option",
",",
"'flavor'",
",",
"'keyName'",
")",
"if",
"not",
"flavor_key_name",
".",
"startswith",
"(",
"flavor_key",
")",
":",
"continue",
"flavors",
".",
"append",
"(",
"flavor_key_name",
")",
"if",
"len",
"(",
"flavors",
")",
">",
"0",
":",
"table",
".",
"add_row",
"(",
"[",
"'flavors (%s)'",
"%",
"flavor_label",
",",
"formatting",
".",
"listing",
"(",
"flavors",
",",
"separator",
"=",
"'\\n'",
")",
"]",
")",
"if",
"result",
".",
"get",
"(",
"'flavors'",
",",
"None",
")",
":",
"_add_flavor_rows",
"(",
"'B1'",
",",
"'balanced'",
",",
"result",
"[",
"'flavors'",
"]",
")",
"_add_flavor_rows",
"(",
"'BL1'",
",",
"'balanced local - hdd'",
",",
"result",
"[",
"'flavors'",
"]",
")",
"_add_flavor_rows",
"(",
"'BL2'",
",",
"'balanced local - ssd'",
",",
"result",
"[",
"'flavors'",
"]",
")",
"_add_flavor_rows",
"(",
"'C1'",
",",
"'compute'",
",",
"result",
"[",
"'flavors'",
"]",
")",
"_add_flavor_rows",
"(",
"'M1'",
",",
"'memory'",
",",
"result",
"[",
"'flavors'",
"]",
")",
"_add_flavor_rows",
"(",
"'AC'",
",",
"'GPU'",
",",
"result",
"[",
"'flavors'",
"]",
")",
"# CPUs",
"standard_cpus",
"=",
"[",
"int",
"(",
"x",
"[",
"'template'",
"]",
"[",
"'startCpus'",
"]",
")",
"for",
"x",
"in",
"result",
"[",
"'processors'",
"]",
"if",
"not",
"x",
"[",
"'template'",
"]",
".",
"get",
"(",
"'dedicatedAccountHostOnlyFlag'",
",",
"False",
")",
"and",
"not",
"x",
"[",
"'template'",
"]",
".",
"get",
"(",
"'dedicatedHost'",
",",
"None",
")",
"]",
"ded_cpus",
"=",
"[",
"int",
"(",
"x",
"[",
"'template'",
"]",
"[",
"'startCpus'",
"]",
")",
"for",
"x",
"in",
"result",
"[",
"'processors'",
"]",
"if",
"x",
"[",
"'template'",
"]",
".",
"get",
"(",
"'dedicatedAccountHostOnlyFlag'",
",",
"False",
")",
"]",
"ded_host_cpus",
"=",
"[",
"int",
"(",
"x",
"[",
"'template'",
"]",
"[",
"'startCpus'",
"]",
")",
"for",
"x",
"in",
"result",
"[",
"'processors'",
"]",
"if",
"x",
"[",
"'template'",
"]",
".",
"get",
"(",
"'dedicatedHost'",
",",
"None",
")",
"]",
"standard_cpus",
"=",
"sorted",
"(",
"standard_cpus",
")",
"table",
".",
"add_row",
"(",
"[",
"'cpus (standard)'",
",",
"formatting",
".",
"listing",
"(",
"standard_cpus",
",",
"separator",
"=",
"','",
")",
"]",
")",
"ded_cpus",
"=",
"sorted",
"(",
"ded_cpus",
")",
"table",
".",
"add_row",
"(",
"[",
"'cpus (dedicated)'",
",",
"formatting",
".",
"listing",
"(",
"ded_cpus",
",",
"separator",
"=",
"','",
")",
"]",
")",
"ded_host_cpus",
"=",
"sorted",
"(",
"ded_host_cpus",
")",
"table",
".",
"add_row",
"(",
"[",
"'cpus (dedicated host)'",
",",
"formatting",
".",
"listing",
"(",
"ded_host_cpus",
",",
"separator",
"=",
"','",
")",
"]",
")",
"# Memory",
"memory",
"=",
"[",
"int",
"(",
"m",
"[",
"'template'",
"]",
"[",
"'maxMemory'",
"]",
")",
"for",
"m",
"in",
"result",
"[",
"'memory'",
"]",
"if",
"not",
"m",
"[",
"'itemPrice'",
"]",
".",
"get",
"(",
"'dedicatedHostInstanceFlag'",
",",
"False",
")",
"]",
"ded_host_memory",
"=",
"[",
"int",
"(",
"m",
"[",
"'template'",
"]",
"[",
"'maxMemory'",
"]",
")",
"for",
"m",
"in",
"result",
"[",
"'memory'",
"]",
"if",
"m",
"[",
"'itemPrice'",
"]",
".",
"get",
"(",
"'dedicatedHostInstanceFlag'",
",",
"False",
")",
"]",
"memory",
"=",
"sorted",
"(",
"memory",
")",
"table",
".",
"add_row",
"(",
"[",
"'memory'",
",",
"formatting",
".",
"listing",
"(",
"memory",
",",
"separator",
"=",
"','",
")",
"]",
")",
"ded_host_memory",
"=",
"sorted",
"(",
"ded_host_memory",
")",
"table",
".",
"add_row",
"(",
"[",
"'memory (dedicated host)'",
",",
"formatting",
".",
"listing",
"(",
"ded_host_memory",
",",
"separator",
"=",
"','",
")",
"]",
")",
"# Operating Systems",
"op_sys",
"=",
"[",
"o",
"[",
"'template'",
"]",
"[",
"'operatingSystemReferenceCode'",
"]",
"for",
"o",
"in",
"result",
"[",
"'operatingSystems'",
"]",
"]",
"op_sys",
"=",
"sorted",
"(",
"op_sys",
")",
"os_summary",
"=",
"set",
"(",
")",
"for",
"operating_system",
"in",
"op_sys",
":",
"os_summary",
".",
"add",
"(",
"operating_system",
"[",
"0",
":",
"operating_system",
".",
"find",
"(",
"'_'",
")",
"]",
")",
"for",
"summary",
"in",
"sorted",
"(",
"os_summary",
")",
":",
"table",
".",
"add_row",
"(",
"[",
"'os (%s)'",
"%",
"summary",
",",
"os",
".",
"linesep",
".",
"join",
"(",
"sorted",
"(",
"[",
"x",
"for",
"x",
"in",
"op_sys",
"if",
"x",
"[",
"0",
":",
"len",
"(",
"summary",
")",
"]",
"==",
"summary",
"]",
")",
")",
"]",
")",
"# Disk",
"local_disks",
"=",
"[",
"x",
"for",
"x",
"in",
"result",
"[",
"'blockDevices'",
"]",
"if",
"x",
"[",
"'template'",
"]",
".",
"get",
"(",
"'localDiskFlag'",
",",
"False",
")",
"and",
"not",
"x",
"[",
"'itemPrice'",
"]",
".",
"get",
"(",
"'dedicatedHostInstanceFlag'",
",",
"False",
")",
"]",
"ded_host_local_disks",
"=",
"[",
"x",
"for",
"x",
"in",
"result",
"[",
"'blockDevices'",
"]",
"if",
"x",
"[",
"'template'",
"]",
".",
"get",
"(",
"'localDiskFlag'",
",",
"False",
")",
"and",
"x",
"[",
"'itemPrice'",
"]",
".",
"get",
"(",
"'dedicatedHostInstanceFlag'",
",",
"False",
")",
"]",
"san_disks",
"=",
"[",
"x",
"for",
"x",
"in",
"result",
"[",
"'blockDevices'",
"]",
"if",
"not",
"x",
"[",
"'template'",
"]",
".",
"get",
"(",
"'localDiskFlag'",
",",
"False",
")",
"]",
"def",
"add_block_rows",
"(",
"disks",
",",
"name",
")",
":",
"\"\"\"Add block rows to the table.\"\"\"",
"simple",
"=",
"{",
"}",
"for",
"disk",
"in",
"disks",
":",
"block",
"=",
"disk",
"[",
"'template'",
"]",
"[",
"'blockDevices'",
"]",
"[",
"0",
"]",
"bid",
"=",
"block",
"[",
"'device'",
"]",
"if",
"bid",
"not",
"in",
"simple",
":",
"simple",
"[",
"bid",
"]",
"=",
"[",
"]",
"simple",
"[",
"bid",
"]",
".",
"append",
"(",
"str",
"(",
"block",
"[",
"'diskImage'",
"]",
"[",
"'capacity'",
"]",
")",
")",
"for",
"label",
"in",
"sorted",
"(",
"simple",
")",
":",
"table",
".",
"add_row",
"(",
"[",
"'%s disk(%s)'",
"%",
"(",
"name",
",",
"label",
")",
",",
"formatting",
".",
"listing",
"(",
"simple",
"[",
"label",
"]",
",",
"separator",
"=",
"','",
")",
"]",
")",
"add_block_rows",
"(",
"san_disks",
",",
"'san'",
")",
"add_block_rows",
"(",
"local_disks",
",",
"'local'",
")",
"add_block_rows",
"(",
"ded_host_local_disks",
",",
"'local (dedicated host)'",
")",
"# Network",
"speeds",
"=",
"[",
"]",
"ded_host_speeds",
"=",
"[",
"]",
"for",
"option",
"in",
"result",
"[",
"'networkComponents'",
"]",
":",
"template",
"=",
"option",
".",
"get",
"(",
"'template'",
",",
"None",
")",
"price",
"=",
"option",
".",
"get",
"(",
"'itemPrice'",
",",
"None",
")",
"if",
"not",
"template",
"or",
"not",
"price",
"or",
"not",
"template",
".",
"get",
"(",
"'networkComponents'",
",",
"None",
")",
":",
"continue",
"if",
"not",
"template",
"[",
"'networkComponents'",
"]",
"[",
"0",
"]",
"or",
"not",
"template",
"[",
"'networkComponents'",
"]",
"[",
"0",
"]",
".",
"get",
"(",
"'maxSpeed'",
",",
"None",
")",
":",
"continue",
"max_speed",
"=",
"str",
"(",
"template",
"[",
"'networkComponents'",
"]",
"[",
"0",
"]",
"[",
"'maxSpeed'",
"]",
")",
"if",
"price",
".",
"get",
"(",
"'dedicatedHostInstanceFlag'",
",",
"False",
")",
"and",
"max_speed",
"not",
"in",
"ded_host_speeds",
":",
"ded_host_speeds",
".",
"append",
"(",
"max_speed",
")",
"elif",
"max_speed",
"not",
"in",
"speeds",
":",
"speeds",
".",
"append",
"(",
"max_speed",
")",
"speeds",
"=",
"sorted",
"(",
"speeds",
")",
"table",
".",
"add_row",
"(",
"[",
"'nic'",
",",
"formatting",
".",
"listing",
"(",
"speeds",
",",
"separator",
"=",
"','",
")",
"]",
")",
"ded_host_speeds",
"=",
"sorted",
"(",
"ded_host_speeds",
")",
"table",
".",
"add_row",
"(",
"[",
"'nic (dedicated host)'",
",",
"formatting",
".",
"listing",
"(",
"ded_host_speeds",
",",
"separator",
"=",
"','",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Virtual server order options. | [
"Virtual",
"server",
"order",
"options",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/create_options.py#L17-L169 |
softlayer/softlayer-python | SoftLayer/CLI/order/place.py | cli | def cli(env, package_keyname, location, preset, verify, billing, complex_type,
quantity, extras, order_items):
"""Place or verify an order.
This CLI command is used for placing/verifying an order of the specified package in
the given location (denoted by a datacenter's long name). Orders made via the CLI
can then be converted to be made programmatically by calling
SoftLayer.OrderingManager.place_order() with the same keynames.
Packages for ordering can be retrieved from `slcli order package-list`
Presets for ordering can be retrieved from `slcli order preset-list` (not all packages
have presets)
Items can be retrieved from `slcli order item-list`. In order to find required
items for the order, use `slcli order category-list`, and then provide the
--category option for each category code in `slcli order item-list`.
Example::
# Order an hourly VSI with 4 CPU, 16 GB RAM, 100 GB SAN disk,
# Ubuntu 16.04, and 1 Gbps public & private uplink in dal13
slcli order place --billing hourly CLOUD_SERVER DALLAS13 \\
GUEST_CORES_4 \\
RAM_16_GB \\
REBOOT_REMOTE_CONSOLE \\
1_GBPS_PUBLIC_PRIVATE_NETWORK_UPLINKS \\
BANDWIDTH_0_GB_2 \\
1_IP_ADDRESS \\
GUEST_DISK_100_GB_SAN \\
OS_UBUNTU_16_04_LTS_XENIAL_XERUS_MINIMAL_64_BIT_FOR_VSI \\
MONITORING_HOST_PING \\
NOTIFICATION_EMAIL_AND_TICKET \\
AUTOMATED_NOTIFICATION \\
UNLIMITED_SSL_VPN_USERS_1_PPTP_VPN_USER_PER_ACCOUNT \\
NESSUS_VULNERABILITY_ASSESSMENT_REPORTING \\
--extras '{"virtualGuests": [{"hostname": "test", "domain": "softlayer.com"}]}' \\
--complex-type SoftLayer_Container_Product_Order_Virtual_Guest
"""
manager = ordering.OrderingManager(env.client)
if extras:
try:
extras = json.loads(extras)
except ValueError as err:
raise exceptions.CLIAbort("There was an error when parsing the --extras value: {}".format(err))
args = (package_keyname, location, order_items)
kwargs = {'preset_keyname': preset,
'extras': extras,
'quantity': quantity,
'complex_type': complex_type,
'hourly': bool(billing == 'hourly')}
if verify:
table = formatting.Table(COLUMNS)
order_to_place = manager.verify_order(*args, **kwargs)
for price in order_to_place['orderContainers'][0]['prices']:
cost_key = 'hourlyRecurringFee' if billing == 'hourly' else 'recurringFee'
table.add_row([
price['item']['keyName'],
price['item']['description'],
price[cost_key] if cost_key in price else formatting.blank()
])
else:
if not (env.skip_confirmations or formatting.confirm(
"This action will incur charges on your account. Continue?")):
raise exceptions.CLIAbort("Aborting order.")
order = manager.place_order(*args, **kwargs)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', order['orderId']])
table.add_row(['created', order['orderDate']])
table.add_row(['status', order['placedOrder']['status']])
env.fout(table) | python | def cli(env, package_keyname, location, preset, verify, billing, complex_type,
quantity, extras, order_items):
manager = ordering.OrderingManager(env.client)
if extras:
try:
extras = json.loads(extras)
except ValueError as err:
raise exceptions.CLIAbort("There was an error when parsing the --extras value: {}".format(err))
args = (package_keyname, location, order_items)
kwargs = {'preset_keyname': preset,
'extras': extras,
'quantity': quantity,
'complex_type': complex_type,
'hourly': bool(billing == 'hourly')}
if verify:
table = formatting.Table(COLUMNS)
order_to_place = manager.verify_order(*args, **kwargs)
for price in order_to_place['orderContainers'][0]['prices']:
cost_key = 'hourlyRecurringFee' if billing == 'hourly' else 'recurringFee'
table.add_row([
price['item']['keyName'],
price['item']['description'],
price[cost_key] if cost_key in price else formatting.blank()
])
else:
if not (env.skip_confirmations or formatting.confirm(
"This action will incur charges on your account. Continue?")):
raise exceptions.CLIAbort("Aborting order.")
order = manager.place_order(*args, **kwargs)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', order['orderId']])
table.add_row(['created', order['orderDate']])
table.add_row(['status', order['placedOrder']['status']])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"package_keyname",
",",
"location",
",",
"preset",
",",
"verify",
",",
"billing",
",",
"complex_type",
",",
"quantity",
",",
"extras",
",",
"order_items",
")",
":",
"manager",
"=",
"ordering",
".",
"OrderingManager",
"(",
"env",
".",
"client",
")",
"if",
"extras",
":",
"try",
":",
"extras",
"=",
"json",
".",
"loads",
"(",
"extras",
")",
"except",
"ValueError",
"as",
"err",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"There was an error when parsing the --extras value: {}\"",
".",
"format",
"(",
"err",
")",
")",
"args",
"=",
"(",
"package_keyname",
",",
"location",
",",
"order_items",
")",
"kwargs",
"=",
"{",
"'preset_keyname'",
":",
"preset",
",",
"'extras'",
":",
"extras",
",",
"'quantity'",
":",
"quantity",
",",
"'complex_type'",
":",
"complex_type",
",",
"'hourly'",
":",
"bool",
"(",
"billing",
"==",
"'hourly'",
")",
"}",
"if",
"verify",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"COLUMNS",
")",
"order_to_place",
"=",
"manager",
".",
"verify_order",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"price",
"in",
"order_to_place",
"[",
"'orderContainers'",
"]",
"[",
"0",
"]",
"[",
"'prices'",
"]",
":",
"cost_key",
"=",
"'hourlyRecurringFee'",
"if",
"billing",
"==",
"'hourly'",
"else",
"'recurringFee'",
"table",
".",
"add_row",
"(",
"[",
"price",
"[",
"'item'",
"]",
"[",
"'keyName'",
"]",
",",
"price",
"[",
"'item'",
"]",
"[",
"'description'",
"]",
",",
"price",
"[",
"cost_key",
"]",
"if",
"cost_key",
"in",
"price",
"else",
"formatting",
".",
"blank",
"(",
")",
"]",
")",
"else",
":",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"confirm",
"(",
"\"This action will incur charges on your account. Continue?\"",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Aborting order.\"",
")",
"order",
"=",
"manager",
".",
"place_order",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"order",
"[",
"'orderId'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'created'",
",",
"order",
"[",
"'orderDate'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'status'",
",",
"order",
"[",
"'placedOrder'",
"]",
"[",
"'status'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Place or verify an order.
This CLI command is used for placing/verifying an order of the specified package in
the given location (denoted by a datacenter's long name). Orders made via the CLI
can then be converted to be made programmatically by calling
SoftLayer.OrderingManager.place_order() with the same keynames.
Packages for ordering can be retrieved from `slcli order package-list`
Presets for ordering can be retrieved from `slcli order preset-list` (not all packages
have presets)
Items can be retrieved from `slcli order item-list`. In order to find required
items for the order, use `slcli order category-list`, and then provide the
--category option for each category code in `slcli order item-list`.
Example::
# Order an hourly VSI with 4 CPU, 16 GB RAM, 100 GB SAN disk,
# Ubuntu 16.04, and 1 Gbps public & private uplink in dal13
slcli order place --billing hourly CLOUD_SERVER DALLAS13 \\
GUEST_CORES_4 \\
RAM_16_GB \\
REBOOT_REMOTE_CONSOLE \\
1_GBPS_PUBLIC_PRIVATE_NETWORK_UPLINKS \\
BANDWIDTH_0_GB_2 \\
1_IP_ADDRESS \\
GUEST_DISK_100_GB_SAN \\
OS_UBUNTU_16_04_LTS_XENIAL_XERUS_MINIMAL_64_BIT_FOR_VSI \\
MONITORING_HOST_PING \\
NOTIFICATION_EMAIL_AND_TICKET \\
AUTOMATED_NOTIFICATION \\
UNLIMITED_SSL_VPN_USERS_1_PPTP_VPN_USER_PER_ACCOUNT \\
NESSUS_VULNERABILITY_ASSESSMENT_REPORTING \\
--extras '{"virtualGuests": [{"hostname": "test", "domain": "softlayer.com"}]}' \\
--complex-type SoftLayer_Container_Product_Order_Virtual_Guest | [
"Place",
"or",
"verify",
"an",
"order",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/place.py#L41-L120 |
softlayer/softlayer-python | SoftLayer/CLI/sshkey/edit.py | cli | def cli(env, identifier, label, note):
"""Edits an SSH key."""
mgr = SoftLayer.SshKeyManager(env.client)
key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey')
if not mgr.edit_key(key_id, label=label, notes=note):
raise exceptions.CLIAbort('Failed to edit SSH key') | python | def cli(env, identifier, label, note):
mgr = SoftLayer.SshKeyManager(env.client)
key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey')
if not mgr.edit_key(key_id, label=label, notes=note):
raise exceptions.CLIAbort('Failed to edit SSH key') | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"label",
",",
"note",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"SshKeyManager",
"(",
"env",
".",
"client",
")",
"key_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'SshKey'",
")",
"if",
"not",
"mgr",
".",
"edit_key",
"(",
"key_id",
",",
"label",
"=",
"label",
",",
"notes",
"=",
"note",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Failed to edit SSH key'",
")"
]
| Edits an SSH key. | [
"Edits",
"an",
"SSH",
"key",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/sshkey/edit.py#L17-L25 |
softlayer/softlayer-python | SoftLayer/CLI/securitygroup/delete.py | cli | def cli(env, securitygroup_id):
"""Deletes the given security group"""
mgr = SoftLayer.NetworkManager(env.client)
if not mgr.delete_securitygroup(securitygroup_id):
raise exceptions.CLIAbort("Failed to delete security group") | python | def cli(env, securitygroup_id):
mgr = SoftLayer.NetworkManager(env.client)
if not mgr.delete_securitygroup(securitygroup_id):
raise exceptions.CLIAbort("Failed to delete security group") | [
"def",
"cli",
"(",
"env",
",",
"securitygroup_id",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"if",
"not",
"mgr",
".",
"delete_securitygroup",
"(",
"securitygroup_id",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Failed to delete security group\"",
")"
]
| Deletes the given security group | [
"Deletes",
"the",
"given",
"security",
"group"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/delete.py#L13-L17 |
softlayer/softlayer-python | SoftLayer/CLI/globalip/create.py | cli | def cli(env, ipv6, test):
"""Creates a global IP."""
mgr = SoftLayer.NetworkManager(env.client)
version = 4
if ipv6:
version = 6
if not (test or env.skip_confirmations):
if not formatting.confirm("This action will incur charges on your "
"account. Continue?"):
raise exceptions.CLIAbort('Cancelling order.')
result = mgr.add_global_ip(version=version, test_order=test)
table = formatting.Table(['item', 'cost'])
table.align['Item'] = 'r'
table.align['cost'] = 'r'
total = 0.0
for price in result['orderDetails']['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])
env.fout(table) | python | def cli(env, ipv6, test):
mgr = SoftLayer.NetworkManager(env.client)
version = 4
if ipv6:
version = 6
if not (test or env.skip_confirmations):
if not formatting.confirm("This action will incur charges on your "
"account. Continue?"):
raise exceptions.CLIAbort('Cancelling order.')
result = mgr.add_global_ip(version=version, test_order=test)
table = formatting.Table(['item', 'cost'])
table.align['Item'] = 'r'
table.align['cost'] = 'r'
total = 0.0
for price in result['orderDetails']['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])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"ipv6",
",",
"test",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"version",
"=",
"4",
"if",
"ipv6",
":",
"version",
"=",
"6",
"if",
"not",
"(",
"test",
"or",
"env",
".",
"skip_confirmations",
")",
":",
"if",
"not",
"formatting",
".",
"confirm",
"(",
"\"This action will incur charges on your \"",
"\"account. Continue?\"",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Cancelling order.'",
")",
"result",
"=",
"mgr",
".",
"add_global_ip",
"(",
"version",
"=",
"version",
",",
"test_order",
"=",
"test",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'item'",
",",
"'cost'",
"]",
")",
"table",
".",
"align",
"[",
"'Item'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'cost'",
"]",
"=",
"'r'",
"total",
"=",
"0.0",
"for",
"price",
"in",
"result",
"[",
"'orderDetails'",
"]",
"[",
"'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",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Creates a global IP. | [
"Creates",
"a",
"global",
"IP",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/globalip/create.py#L16-L44 |
softlayer/softlayer-python | SoftLayer/CLI/vpn/ipsec/translation/remove.py | cli | def cli(env, context_id, translation_id):
"""Remove a translation entry from an IPSEC tunnel context.
A separate configuration request should be made to realize changes on
network devices.
"""
manager = SoftLayer.IPSECManager(env.client)
# ensure translation can be retrieved by given id
manager.get_translation(context_id, translation_id)
succeeded = manager.remove_translation(context_id, translation_id)
if succeeded:
env.out('Removed translation #{}'.format(translation_id))
else:
raise CLIHalt('Failed to remove translation #{}'.format(translation_id)) | python | def cli(env, context_id, translation_id):
manager = SoftLayer.IPSECManager(env.client)
manager.get_translation(context_id, translation_id)
succeeded = manager.remove_translation(context_id, translation_id)
if succeeded:
env.out('Removed translation
else:
raise CLIHalt('Failed to remove translation | [
"def",
"cli",
"(",
"env",
",",
"context_id",
",",
"translation_id",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"IPSECManager",
"(",
"env",
".",
"client",
")",
"# ensure translation can be retrieved by given id",
"manager",
".",
"get_translation",
"(",
"context_id",
",",
"translation_id",
")",
"succeeded",
"=",
"manager",
".",
"remove_translation",
"(",
"context_id",
",",
"translation_id",
")",
"if",
"succeeded",
":",
"env",
".",
"out",
"(",
"'Removed translation #{}'",
".",
"format",
"(",
"translation_id",
")",
")",
"else",
":",
"raise",
"CLIHalt",
"(",
"'Failed to remove translation #{}'",
".",
"format",
"(",
"translation_id",
")",
")"
]
| Remove a translation entry from an IPSEC tunnel context.
A separate configuration request should be made to realize changes on
network devices. | [
"Remove",
"a",
"translation",
"entry",
"from",
"an",
"IPSEC",
"tunnel",
"context",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/translation/remove.py#L19-L33 |
softlayer/softlayer-python | SoftLayer/CLI/virt/list.py | cli | def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network,
hourly, monthly, tag, columns, limit):
"""List virtual servers."""
vsi = SoftLayer.VSManager(env.client)
guests = vsi.list_instances(hourly=hourly,
monthly=monthly,
hostname=hostname,
domain=domain,
cpus=cpu,
memory=memory,
datacenter=datacenter,
nic_speed=network,
tags=tag,
mask=columns.mask(),
limit=limit)
table = formatting.Table(columns.columns)
table.sortby = sortby
for guest in guests:
table.add_row([value or formatting.blank()
for value in columns.row(guest)])
env.fout(table) | python | def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network,
hourly, monthly, tag, columns, limit):
vsi = SoftLayer.VSManager(env.client)
guests = vsi.list_instances(hourly=hourly,
monthly=monthly,
hostname=hostname,
domain=domain,
cpus=cpu,
memory=memory,
datacenter=datacenter,
nic_speed=network,
tags=tag,
mask=columns.mask(),
limit=limit)
table = formatting.Table(columns.columns)
table.sortby = sortby
for guest in guests:
table.add_row([value or formatting.blank()
for value in columns.row(guest)])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"sortby",
",",
"cpu",
",",
"domain",
",",
"datacenter",
",",
"hostname",
",",
"memory",
",",
"network",
",",
"hourly",
",",
"monthly",
",",
"tag",
",",
"columns",
",",
"limit",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"guests",
"=",
"vsi",
".",
"list_instances",
"(",
"hourly",
"=",
"hourly",
",",
"monthly",
"=",
"monthly",
",",
"hostname",
"=",
"hostname",
",",
"domain",
"=",
"domain",
",",
"cpus",
"=",
"cpu",
",",
"memory",
"=",
"memory",
",",
"datacenter",
"=",
"datacenter",
",",
"nic_speed",
"=",
"network",
",",
"tags",
"=",
"tag",
",",
"mask",
"=",
"columns",
".",
"mask",
"(",
")",
",",
"limit",
"=",
"limit",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"columns",
".",
"columns",
")",
"table",
".",
"sortby",
"=",
"sortby",
"for",
"guest",
"in",
"guests",
":",
"table",
".",
"add_row",
"(",
"[",
"value",
"or",
"formatting",
".",
"blank",
"(",
")",
"for",
"value",
"in",
"columns",
".",
"row",
"(",
"guest",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| List virtual servers. | [
"List",
"virtual",
"servers",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/list.py#L70-L93 |
softlayer/softlayer-python | SoftLayer/CLI/file/snapshot/disable.py | cli | def cli(env, volume_id, schedule_type):
"""Disables snapshots on the specified schedule for a given volume"""
if (schedule_type not in ['INTERVAL', 'HOURLY', 'DAILY', 'WEEKLY']):
raise exceptions.CLIAbort(
'--schedule_type must be INTERVAL, HOURLY, DAILY, or WEEKLY')
file_manager = SoftLayer.FileStorageManager(env.client)
disabled = file_manager.disable_snapshots(volume_id, schedule_type)
if disabled:
click.echo('%s snapshots have been disabled for volume %s'
% (schedule_type, volume_id)) | python | def cli(env, volume_id, schedule_type):
if (schedule_type not in ['INTERVAL', 'HOURLY', 'DAILY', 'WEEKLY']):
raise exceptions.CLIAbort(
'--schedule_type must be INTERVAL, HOURLY, DAILY, or WEEKLY')
file_manager = SoftLayer.FileStorageManager(env.client)
disabled = file_manager.disable_snapshots(volume_id, schedule_type)
if disabled:
click.echo('%s snapshots have been disabled for volume %s'
% (schedule_type, volume_id)) | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"schedule_type",
")",
":",
"if",
"(",
"schedule_type",
"not",
"in",
"[",
"'INTERVAL'",
",",
"'HOURLY'",
",",
"'DAILY'",
",",
"'WEEKLY'",
"]",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'--schedule_type must be INTERVAL, HOURLY, DAILY, or WEEKLY'",
")",
"file_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"disabled",
"=",
"file_manager",
".",
"disable_snapshots",
"(",
"volume_id",
",",
"schedule_type",
")",
"if",
"disabled",
":",
"click",
".",
"echo",
"(",
"'%s snapshots have been disabled for volume %s'",
"%",
"(",
"schedule_type",
",",
"volume_id",
")",
")"
]
| Disables snapshots on the specified schedule for a given volume | [
"Disables",
"snapshots",
"on",
"the",
"specified",
"schedule",
"for",
"a",
"given",
"volume"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/snapshot/disable.py#L16-L28 |
softlayer/softlayer-python | SoftLayer/CLI/securitygroup/create.py | cli | def cli(env, name, description):
"""Create a security group."""
mgr = SoftLayer.NetworkManager(env.client)
result = mgr.create_securitygroup(name, description)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', result['id']])
table.add_row(['name',
result.get('name') or formatting.blank()])
table.add_row(['description',
result.get('description') or formatting.blank()])
table.add_row(['created', result['createDate']])
env.fout(table) | python | def cli(env, name, description):
mgr = SoftLayer.NetworkManager(env.client)
result = mgr.create_securitygroup(name, description)
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', result['id']])
table.add_row(['name',
result.get('name') or formatting.blank()])
table.add_row(['description',
result.get('description') or formatting.blank()])
table.add_row(['created', result['createDate']])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"name",
",",
"description",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"result",
"=",
"mgr",
".",
"create_securitygroup",
"(",
"name",
",",
"description",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"result",
"[",
"'id'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'name'",
",",
"result",
".",
"get",
"(",
"'name'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'description'",
",",
"result",
".",
"get",
"(",
"'description'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'created'",
",",
"result",
"[",
"'createDate'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Create a security group. | [
"Create",
"a",
"security",
"group",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/create.py#L17-L32 |
softlayer/softlayer-python | SoftLayer/CLI/sshkey/remove.py | cli | def cli(env, identifier):
"""Permanently removes an SSH key."""
mgr = SoftLayer.SshKeyManager(env.client)
key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey')
if not (env.skip_confirmations or formatting.no_going_back(key_id)):
raise exceptions.CLIAbort('Aborted')
mgr.delete_key(key_id) | python | def cli(env, identifier):
mgr = SoftLayer.SshKeyManager(env.client)
key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey')
if not (env.skip_confirmations or formatting.no_going_back(key_id)):
raise exceptions.CLIAbort('Aborted')
mgr.delete_key(key_id) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"SshKeyManager",
"(",
"env",
".",
"client",
")",
"key_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'SshKey'",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"no_going_back",
"(",
"key_id",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted'",
")",
"mgr",
".",
"delete_key",
"(",
"key_id",
")"
]
| Permanently removes an SSH key. | [
"Permanently",
"removes",
"an",
"SSH",
"key",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/sshkey/remove.py#L16-L24 |
softlayer/softlayer-python | SoftLayer/CLI/formatting.py | format_output | def format_output(data, fmt='table'): # pylint: disable=R0911,R0912
"""Given some data, will format it for console output.
:param data: One of: String, Table, FormattedItem, List, Tuple,
SequentialOutput
:param string fmt (optional): One of: table, raw, json, python
"""
if isinstance(data, utils.string_types):
if fmt in ('json', 'jsonraw'):
return json.dumps(data)
return data
# responds to .prettytable()
if hasattr(data, 'prettytable'):
if fmt == 'table':
return str(format_prettytable(data))
elif fmt == 'raw':
return str(format_no_tty(data))
# responds to .to_python()
if hasattr(data, 'to_python'):
if fmt == 'json':
return json.dumps(
format_output(data, fmt='python'),
indent=4,
cls=CLIJSONEncoder)
elif fmt == 'jsonraw':
return json.dumps(format_output(data, fmt='python'),
cls=CLIJSONEncoder)
elif fmt == 'python':
return data.to_python()
# responds to .formatted
if hasattr(data, 'formatted'):
if fmt == 'table':
return data.formatted
# responds to .separator
if hasattr(data, 'separator'):
output = [format_output(d, fmt=fmt) for d in data if d]
return str(SequentialOutput(data.separator, output))
# is iterable
if isinstance(data, list) or isinstance(data, tuple):
output = [format_output(d, fmt=fmt) for d in data]
if fmt == 'python':
return output
return format_output(listing(output, separator=os.linesep))
# fallback, convert this odd object to a string
return data | python | def format_output(data, fmt='table'):
if isinstance(data, utils.string_types):
if fmt in ('json', 'jsonraw'):
return json.dumps(data)
return data
if hasattr(data, 'prettytable'):
if fmt == 'table':
return str(format_prettytable(data))
elif fmt == 'raw':
return str(format_no_tty(data))
if hasattr(data, 'to_python'):
if fmt == 'json':
return json.dumps(
format_output(data, fmt='python'),
indent=4,
cls=CLIJSONEncoder)
elif fmt == 'jsonraw':
return json.dumps(format_output(data, fmt='python'),
cls=CLIJSONEncoder)
elif fmt == 'python':
return data.to_python()
if hasattr(data, 'formatted'):
if fmt == 'table':
return data.formatted
if hasattr(data, 'separator'):
output = [format_output(d, fmt=fmt) for d in data if d]
return str(SequentialOutput(data.separator, output))
if isinstance(data, list) or isinstance(data, tuple):
output = [format_output(d, fmt=fmt) for d in data]
if fmt == 'python':
return output
return format_output(listing(output, separator=os.linesep))
return data | [
"def",
"format_output",
"(",
"data",
",",
"fmt",
"=",
"'table'",
")",
":",
"# pylint: disable=R0911,R0912",
"if",
"isinstance",
"(",
"data",
",",
"utils",
".",
"string_types",
")",
":",
"if",
"fmt",
"in",
"(",
"'json'",
",",
"'jsonraw'",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"data",
")",
"return",
"data",
"# responds to .prettytable()",
"if",
"hasattr",
"(",
"data",
",",
"'prettytable'",
")",
":",
"if",
"fmt",
"==",
"'table'",
":",
"return",
"str",
"(",
"format_prettytable",
"(",
"data",
")",
")",
"elif",
"fmt",
"==",
"'raw'",
":",
"return",
"str",
"(",
"format_no_tty",
"(",
"data",
")",
")",
"# responds to .to_python()",
"if",
"hasattr",
"(",
"data",
",",
"'to_python'",
")",
":",
"if",
"fmt",
"==",
"'json'",
":",
"return",
"json",
".",
"dumps",
"(",
"format_output",
"(",
"data",
",",
"fmt",
"=",
"'python'",
")",
",",
"indent",
"=",
"4",
",",
"cls",
"=",
"CLIJSONEncoder",
")",
"elif",
"fmt",
"==",
"'jsonraw'",
":",
"return",
"json",
".",
"dumps",
"(",
"format_output",
"(",
"data",
",",
"fmt",
"=",
"'python'",
")",
",",
"cls",
"=",
"CLIJSONEncoder",
")",
"elif",
"fmt",
"==",
"'python'",
":",
"return",
"data",
".",
"to_python",
"(",
")",
"# responds to .formatted",
"if",
"hasattr",
"(",
"data",
",",
"'formatted'",
")",
":",
"if",
"fmt",
"==",
"'table'",
":",
"return",
"data",
".",
"formatted",
"# responds to .separator",
"if",
"hasattr",
"(",
"data",
",",
"'separator'",
")",
":",
"output",
"=",
"[",
"format_output",
"(",
"d",
",",
"fmt",
"=",
"fmt",
")",
"for",
"d",
"in",
"data",
"if",
"d",
"]",
"return",
"str",
"(",
"SequentialOutput",
"(",
"data",
".",
"separator",
",",
"output",
")",
")",
"# is iterable",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
"or",
"isinstance",
"(",
"data",
",",
"tuple",
")",
":",
"output",
"=",
"[",
"format_output",
"(",
"d",
",",
"fmt",
"=",
"fmt",
")",
"for",
"d",
"in",
"data",
"]",
"if",
"fmt",
"==",
"'python'",
":",
"return",
"output",
"return",
"format_output",
"(",
"listing",
"(",
"output",
",",
"separator",
"=",
"os",
".",
"linesep",
")",
")",
"# fallback, convert this odd object to a string",
"return",
"data"
]
| Given some data, will format it for console output.
:param data: One of: String, Table, FormattedItem, List, Tuple,
SequentialOutput
:param string fmt (optional): One of: table, raw, json, python | [
"Given",
"some",
"data",
"will",
"format",
"it",
"for",
"console",
"output",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/formatting.py#L26-L76 |
softlayer/softlayer-python | SoftLayer/CLI/formatting.py | format_prettytable | def format_prettytable(table):
"""Converts SoftLayer.CLI.formatting.Table instance to a prettytable."""
for i, row in enumerate(table.rows):
for j, item in enumerate(row):
table.rows[i][j] = format_output(item)
ptable = table.prettytable()
ptable.hrules = prettytable.FRAME
ptable.horizontal_char = '.'
ptable.vertical_char = ':'
ptable.junction_char = ':'
return ptable | python | def format_prettytable(table):
for i, row in enumerate(table.rows):
for j, item in enumerate(row):
table.rows[i][j] = format_output(item)
ptable = table.prettytable()
ptable.hrules = prettytable.FRAME
ptable.horizontal_char = '.'
ptable.vertical_char = ':'
ptable.junction_char = ':'
return ptable | [
"def",
"format_prettytable",
"(",
"table",
")",
":",
"for",
"i",
",",
"row",
"in",
"enumerate",
"(",
"table",
".",
"rows",
")",
":",
"for",
"j",
",",
"item",
"in",
"enumerate",
"(",
"row",
")",
":",
"table",
".",
"rows",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"format_output",
"(",
"item",
")",
"ptable",
"=",
"table",
".",
"prettytable",
"(",
")",
"ptable",
".",
"hrules",
"=",
"prettytable",
".",
"FRAME",
"ptable",
".",
"horizontal_char",
"=",
"'.'",
"ptable",
".",
"vertical_char",
"=",
"':'",
"ptable",
".",
"junction_char",
"=",
"':'",
"return",
"ptable"
]
| Converts SoftLayer.CLI.formatting.Table instance to a prettytable. | [
"Converts",
"SoftLayer",
".",
"CLI",
".",
"formatting",
".",
"Table",
"instance",
"to",
"a",
"prettytable",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/formatting.py#L79-L90 |
softlayer/softlayer-python | SoftLayer/CLI/formatting.py | format_no_tty | def format_no_tty(table):
"""Converts SoftLayer.CLI.formatting.Table instance to a prettytable."""
for i, row in enumerate(table.rows):
for j, item in enumerate(row):
table.rows[i][j] = format_output(item, fmt='raw')
ptable = table.prettytable()
for col in table.columns:
ptable.align[col] = 'l'
ptable.hrules = prettytable.NONE
ptable.border = False
ptable.header = False
ptable.left_padding_width = 0
ptable.right_padding_width = 2
return ptable | python | def format_no_tty(table):
for i, row in enumerate(table.rows):
for j, item in enumerate(row):
table.rows[i][j] = format_output(item, fmt='raw')
ptable = table.prettytable()
for col in table.columns:
ptable.align[col] = 'l'
ptable.hrules = prettytable.NONE
ptable.border = False
ptable.header = False
ptable.left_padding_width = 0
ptable.right_padding_width = 2
return ptable | [
"def",
"format_no_tty",
"(",
"table",
")",
":",
"for",
"i",
",",
"row",
"in",
"enumerate",
"(",
"table",
".",
"rows",
")",
":",
"for",
"j",
",",
"item",
"in",
"enumerate",
"(",
"row",
")",
":",
"table",
".",
"rows",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"format_output",
"(",
"item",
",",
"fmt",
"=",
"'raw'",
")",
"ptable",
"=",
"table",
".",
"prettytable",
"(",
")",
"for",
"col",
"in",
"table",
".",
"columns",
":",
"ptable",
".",
"align",
"[",
"col",
"]",
"=",
"'l'",
"ptable",
".",
"hrules",
"=",
"prettytable",
".",
"NONE",
"ptable",
".",
"border",
"=",
"False",
"ptable",
".",
"header",
"=",
"False",
"ptable",
".",
"left_padding_width",
"=",
"0",
"ptable",
".",
"right_padding_width",
"=",
"2",
"return",
"ptable"
]
| Converts SoftLayer.CLI.formatting.Table instance to a prettytable. | [
"Converts",
"SoftLayer",
".",
"CLI",
".",
"formatting",
".",
"Table",
"instance",
"to",
"a",
"prettytable",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/formatting.py#L93-L109 |
softlayer/softlayer-python | SoftLayer/CLI/formatting.py | transaction_status | def transaction_status(transaction):
"""Returns a FormattedItem describing the given transaction.
:param item: An object capable of having an active transaction
"""
if not transaction or not transaction.get('transactionStatus'):
return blank()
return FormattedItem(
transaction['transactionStatus'].get('name'),
transaction['transactionStatus'].get('friendlyName')) | python | def transaction_status(transaction):
if not transaction or not transaction.get('transactionStatus'):
return blank()
return FormattedItem(
transaction['transactionStatus'].get('name'),
transaction['transactionStatus'].get('friendlyName')) | [
"def",
"transaction_status",
"(",
"transaction",
")",
":",
"if",
"not",
"transaction",
"or",
"not",
"transaction",
".",
"get",
"(",
"'transactionStatus'",
")",
":",
"return",
"blank",
"(",
")",
"return",
"FormattedItem",
"(",
"transaction",
"[",
"'transactionStatus'",
"]",
".",
"get",
"(",
"'name'",
")",
",",
"transaction",
"[",
"'transactionStatus'",
"]",
".",
"get",
"(",
"'friendlyName'",
")",
")"
]
| Returns a FormattedItem describing the given transaction.
:param item: An object capable of having an active transaction | [
"Returns",
"a",
"FormattedItem",
"describing",
"the",
"given",
"transaction",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/formatting.py#L162-L172 |
softlayer/softlayer-python | SoftLayer/CLI/formatting.py | tags | def tags(tag_references):
"""Returns a formatted list of tags."""
if not tag_references:
return blank()
tag_row = []
for tag_detail in tag_references:
tag = utils.lookup(tag_detail, 'tag', 'name')
if tag is not None:
tag_row.append(tag)
return listing(tag_row, separator=', ') | python | def tags(tag_references):
if not tag_references:
return blank()
tag_row = []
for tag_detail in tag_references:
tag = utils.lookup(tag_detail, 'tag', 'name')
if tag is not None:
tag_row.append(tag)
return listing(tag_row, separator=', ') | [
"def",
"tags",
"(",
"tag_references",
")",
":",
"if",
"not",
"tag_references",
":",
"return",
"blank",
"(",
")",
"tag_row",
"=",
"[",
"]",
"for",
"tag_detail",
"in",
"tag_references",
":",
"tag",
"=",
"utils",
".",
"lookup",
"(",
"tag_detail",
",",
"'tag'",
",",
"'name'",
")",
"if",
"tag",
"is",
"not",
"None",
":",
"tag_row",
".",
"append",
"(",
"tag",
")",
"return",
"listing",
"(",
"tag_row",
",",
"separator",
"=",
"', '",
")"
]
| Returns a formatted list of tags. | [
"Returns",
"a",
"formatted",
"list",
"of",
"tags",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/formatting.py#L175-L186 |
softlayer/softlayer-python | SoftLayer/CLI/formatting.py | confirm | def confirm(prompt_str, default=False):
"""Show a confirmation prompt to a command-line user.
:param string prompt_str: prompt to give to the user
:param bool default: Default value to True or False
"""
if default:
default_str = 'y'
prompt = '%s [Y/n]' % prompt_str
else:
default_str = 'n'
prompt = '%s [y/N]' % prompt_str
ans = click.prompt(prompt, default=default_str, show_default=False)
if ans.lower() in ('y', 'yes', 'yeah', 'yup', 'yolo'):
return True
return False | python | def confirm(prompt_str, default=False):
if default:
default_str = 'y'
prompt = '%s [Y/n]' % prompt_str
else:
default_str = 'n'
prompt = '%s [y/N]' % prompt_str
ans = click.prompt(prompt, default=default_str, show_default=False)
if ans.lower() in ('y', 'yes', 'yeah', 'yup', 'yolo'):
return True
return False | [
"def",
"confirm",
"(",
"prompt_str",
",",
"default",
"=",
"False",
")",
":",
"if",
"default",
":",
"default_str",
"=",
"'y'",
"prompt",
"=",
"'%s [Y/n]'",
"%",
"prompt_str",
"else",
":",
"default_str",
"=",
"'n'",
"prompt",
"=",
"'%s [y/N]'",
"%",
"prompt_str",
"ans",
"=",
"click",
".",
"prompt",
"(",
"prompt",
",",
"default",
"=",
"default_str",
",",
"show_default",
"=",
"False",
")",
"if",
"ans",
".",
"lower",
"(",
")",
"in",
"(",
"'y'",
",",
"'yes'",
",",
"'yeah'",
",",
"'yup'",
",",
"'yolo'",
")",
":",
"return",
"True",
"return",
"False"
]
| Show a confirmation prompt to a command-line user.
:param string prompt_str: prompt to give to the user
:param bool default: Default value to True or False | [
"Show",
"a",
"confirmation",
"prompt",
"to",
"a",
"command",
"-",
"line",
"user",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/formatting.py#L189-L206 |
softlayer/softlayer-python | SoftLayer/CLI/formatting.py | no_going_back | def no_going_back(confirmation):
"""Show a confirmation to a user.
:param confirmation str: the string the user has to enter in order to
confirm their action.
"""
if not confirmation:
confirmation = 'yes'
prompt = ('This action cannot be undone! Type "%s" or press Enter '
'to abort' % confirmation)
ans = click.prompt(prompt, default='', show_default=False)
if ans.lower() == str(confirmation):
return True
return False | python | def no_going_back(confirmation):
if not confirmation:
confirmation = 'yes'
prompt = ('This action cannot be undone! Type "%s" or press Enter '
'to abort' % confirmation)
ans = click.prompt(prompt, default='', show_default=False)
if ans.lower() == str(confirmation):
return True
return False | [
"def",
"no_going_back",
"(",
"confirmation",
")",
":",
"if",
"not",
"confirmation",
":",
"confirmation",
"=",
"'yes'",
"prompt",
"=",
"(",
"'This action cannot be undone! Type \"%s\" or press Enter '",
"'to abort'",
"%",
"confirmation",
")",
"ans",
"=",
"click",
".",
"prompt",
"(",
"prompt",
",",
"default",
"=",
"''",
",",
"show_default",
"=",
"False",
")",
"if",
"ans",
".",
"lower",
"(",
")",
"==",
"str",
"(",
"confirmation",
")",
":",
"return",
"True",
"return",
"False"
]
| Show a confirmation to a user.
:param confirmation str: the string the user has to enter in order to
confirm their action. | [
"Show",
"a",
"confirmation",
"to",
"a",
"user",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/formatting.py#L209-L225 |
softlayer/softlayer-python | SoftLayer/CLI/formatting.py | iter_to_table | def iter_to_table(value):
"""Convert raw API responses to response tables."""
if isinstance(value, list):
return _format_list(value)
if isinstance(value, dict):
return _format_dict(value)
return value | python | def iter_to_table(value):
if isinstance(value, list):
return _format_list(value)
if isinstance(value, dict):
return _format_dict(value)
return value | [
"def",
"iter_to_table",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"_format_list",
"(",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"return",
"_format_dict",
"(",
"value",
")",
"return",
"value"
]
| Convert raw API responses to response tables. | [
"Convert",
"raw",
"API",
"responses",
"to",
"response",
"tables",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/formatting.py#L390-L396 |
softlayer/softlayer-python | SoftLayer/CLI/formatting.py | _format_dict | def _format_dict(result):
"""Format dictionary responses into key-value table."""
table = KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
for key, value in result.items():
value = iter_to_table(value)
table.add_row([key, value])
return table | python | def _format_dict(result):
table = KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
for key, value in result.items():
value = iter_to_table(value)
table.add_row([key, value])
return table | [
"def",
"_format_dict",
"(",
"result",
")",
":",
"table",
"=",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"for",
"key",
",",
"value",
"in",
"result",
".",
"items",
"(",
")",
":",
"value",
"=",
"iter_to_table",
"(",
"value",
")",
"table",
".",
"add_row",
"(",
"[",
"key",
",",
"value",
"]",
")",
"return",
"table"
]
| Format dictionary responses into key-value table. | [
"Format",
"dictionary",
"responses",
"into",
"key",
"-",
"value",
"table",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/formatting.py#L399-L410 |
softlayer/softlayer-python | SoftLayer/CLI/formatting.py | _format_list | def _format_list(result):
"""Format list responses into a table."""
if not result:
return result
if isinstance(result[0], dict):
return _format_list_objects(result)
table = Table(['value'])
for item in result:
table.add_row([iter_to_table(item)])
return table | python | def _format_list(result):
if not result:
return result
if isinstance(result[0], dict):
return _format_list_objects(result)
table = Table(['value'])
for item in result:
table.add_row([iter_to_table(item)])
return table | [
"def",
"_format_list",
"(",
"result",
")",
":",
"if",
"not",
"result",
":",
"return",
"result",
"if",
"isinstance",
"(",
"result",
"[",
"0",
"]",
",",
"dict",
")",
":",
"return",
"_format_list_objects",
"(",
"result",
")",
"table",
"=",
"Table",
"(",
"[",
"'value'",
"]",
")",
"for",
"item",
"in",
"result",
":",
"table",
".",
"add_row",
"(",
"[",
"iter_to_table",
"(",
"item",
")",
"]",
")",
"return",
"table"
]
| Format list responses into a table. | [
"Format",
"list",
"responses",
"into",
"a",
"table",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/formatting.py#L413-L425 |
softlayer/softlayer-python | SoftLayer/CLI/formatting.py | _format_list_objects | def _format_list_objects(result):
"""Format list of objects into a table."""
all_keys = set()
for item in result:
all_keys = all_keys.union(item.keys())
all_keys = sorted(all_keys)
table = Table(all_keys)
for item in result:
values = []
for key in all_keys:
value = iter_to_table(item.get(key))
values.append(value)
table.add_row(values)
return table | python | def _format_list_objects(result):
all_keys = set()
for item in result:
all_keys = all_keys.union(item.keys())
all_keys = sorted(all_keys)
table = Table(all_keys)
for item in result:
values = []
for key in all_keys:
value = iter_to_table(item.get(key))
values.append(value)
table.add_row(values)
return table | [
"def",
"_format_list_objects",
"(",
"result",
")",
":",
"all_keys",
"=",
"set",
"(",
")",
"for",
"item",
"in",
"result",
":",
"all_keys",
"=",
"all_keys",
".",
"union",
"(",
"item",
".",
"keys",
"(",
")",
")",
"all_keys",
"=",
"sorted",
"(",
"all_keys",
")",
"table",
"=",
"Table",
"(",
"all_keys",
")",
"for",
"item",
"in",
"result",
":",
"values",
"=",
"[",
"]",
"for",
"key",
"in",
"all_keys",
":",
"value",
"=",
"iter_to_table",
"(",
"item",
".",
"get",
"(",
"key",
")",
")",
"values",
".",
"append",
"(",
"value",
")",
"table",
".",
"add_row",
"(",
"values",
")",
"return",
"table"
]
| Format list of objects into a table. | [
"Format",
"list",
"of",
"objects",
"into",
"a",
"table",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/formatting.py#L428-L446 |
softlayer/softlayer-python | SoftLayer/CLI/formatting.py | CLIJSONEncoder.default | def default(self, obj):
"""Encode object if it implements to_python()."""
if hasattr(obj, 'to_python'):
return obj.to_python()
return super(CLIJSONEncoder, self).default(obj) | python | def default(self, obj):
if hasattr(obj, 'to_python'):
return obj.to_python()
return super(CLIJSONEncoder, self).default(obj) | [
"def",
"default",
"(",
"self",
",",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'to_python'",
")",
":",
"return",
"obj",
".",
"to_python",
"(",
")",
"return",
"super",
"(",
"CLIJSONEncoder",
",",
"self",
")",
".",
"default",
"(",
"obj",
")"
]
| Encode object if it implements to_python(). | [
"Encode",
"object",
"if",
"it",
"implements",
"to_python",
"()",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/formatting.py#L251-L255 |
softlayer/softlayer-python | SoftLayer/CLI/formatting.py | Table.to_python | def to_python(self):
"""Decode this Table object to standard Python types."""
# Adding rows
items = []
for row in self.rows:
formatted_row = [_format_python_value(v) for v in row]
items.append(dict(zip(self.columns, formatted_row)))
return items | python | def to_python(self):
items = []
for row in self.rows:
formatted_row = [_format_python_value(v) for v in row]
items.append(dict(zip(self.columns, formatted_row)))
return items | [
"def",
"to_python",
"(",
"self",
")",
":",
"# Adding rows",
"items",
"=",
"[",
"]",
"for",
"row",
"in",
"self",
".",
"rows",
":",
"formatted_row",
"=",
"[",
"_format_python_value",
"(",
"v",
")",
"for",
"v",
"in",
"row",
"]",
"items",
".",
"append",
"(",
"dict",
"(",
"zip",
"(",
"self",
".",
"columns",
",",
"formatted_row",
")",
")",
")",
"return",
"items"
]
| Decode this Table object to standard Python types. | [
"Decode",
"this",
"Table",
"object",
"to",
"standard",
"Python",
"types",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/formatting.py#L285-L292 |
softlayer/softlayer-python | SoftLayer/CLI/formatting.py | Table.prettytable | def prettytable(self):
"""Returns a new prettytable instance."""
table = prettytable.PrettyTable(self.columns)
if self.sortby:
if self.sortby in self.columns:
table.sortby = self.sortby
else:
msg = "Column (%s) doesn't exist to sort by" % self.sortby
raise exceptions.CLIAbort(msg)
for a_col, alignment in self.align.items():
table.align[a_col] = alignment
if self.title:
table.title = self.title
# Adding rows
for row in self.rows:
table.add_row(row)
return table | python | def prettytable(self):
table = prettytable.PrettyTable(self.columns)
if self.sortby:
if self.sortby in self.columns:
table.sortby = self.sortby
else:
msg = "Column (%s) doesn't exist to sort by" % self.sortby
raise exceptions.CLIAbort(msg)
for a_col, alignment in self.align.items():
table.align[a_col] = alignment
if self.title:
table.title = self.title
for row in self.rows:
table.add_row(row)
return table | [
"def",
"prettytable",
"(",
"self",
")",
":",
"table",
"=",
"prettytable",
".",
"PrettyTable",
"(",
"self",
".",
"columns",
")",
"if",
"self",
".",
"sortby",
":",
"if",
"self",
".",
"sortby",
"in",
"self",
".",
"columns",
":",
"table",
".",
"sortby",
"=",
"self",
".",
"sortby",
"else",
":",
"msg",
"=",
"\"Column (%s) doesn't exist to sort by\"",
"%",
"self",
".",
"sortby",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"msg",
")",
"for",
"a_col",
",",
"alignment",
"in",
"self",
".",
"align",
".",
"items",
"(",
")",
":",
"table",
".",
"align",
"[",
"a_col",
"]",
"=",
"alignment",
"if",
"self",
".",
"title",
":",
"table",
".",
"title",
"=",
"self",
".",
"title",
"# Adding rows",
"for",
"row",
"in",
"self",
".",
"rows",
":",
"table",
".",
"add_row",
"(",
"row",
")",
"return",
"table"
]
| Returns a new prettytable instance. | [
"Returns",
"a",
"new",
"prettytable",
"instance",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/formatting.py#L294-L312 |
softlayer/softlayer-python | SoftLayer/CLI/formatting.py | KeyValueTable.to_python | def to_python(self):
"""Decode this KeyValueTable object to standard Python types."""
mapping = {}
for row in self.rows:
mapping[row[0]] = _format_python_value(row[1])
return mapping | python | def to_python(self):
mapping = {}
for row in self.rows:
mapping[row[0]] = _format_python_value(row[1])
return mapping | [
"def",
"to_python",
"(",
"self",
")",
":",
"mapping",
"=",
"{",
"}",
"for",
"row",
"in",
"self",
".",
"rows",
":",
"mapping",
"[",
"row",
"[",
"0",
"]",
"]",
"=",
"_format_python_value",
"(",
"row",
"[",
"1",
"]",
")",
"return",
"mapping"
]
| Decode this KeyValueTable object to standard Python types. | [
"Decode",
"this",
"KeyValueTable",
"object",
"to",
"standard",
"Python",
"types",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/formatting.py#L318-L323 |
softlayer/softlayer-python | SoftLayer/CLI/user/create.py | cli | def cli(env, username, email, password, from_user, template, api_key):
"""Creates a user Users.
:Example: slcli user create [email protected] -e [email protected] -p generate -a
-t '{"firstName": "Test", "lastName": "Testerson"}'
Remember to set the permissions and access for this new user.
"""
mgr = SoftLayer.UserManager(env.client)
user_mask = ("mask[id, firstName, lastName, email, companyName, address1, city, country, postalCode, "
"state, userStatusId, timezoneId]")
from_user_id = None
if from_user is None:
user_template = mgr.get_current_user(objectmask=user_mask)
from_user_id = user_template['id']
else:
from_user_id = helpers.resolve_id(mgr.resolve_ids, from_user, 'username')
user_template = mgr.get_user(from_user_id, objectmask=user_mask)
# If we send the ID back to the API, an exception will be thrown
del user_template['id']
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)
user_template['username'] = username
if password == 'generate':
password = generate_password()
user_template['email'] = email
if not env.skip_confirmations:
table = formatting.KeyValueTable(['name', 'value'])
for key in user_template:
table.add_row([key, user_template[key]])
table.add_row(['password', password])
click.secho("You are about to create the following user...", fg='green')
env.fout(table)
if not formatting.confirm("Do you wish to continue?"):
raise exceptions.CLIAbort("Canceling creation!")
result = mgr.create_user(user_template, password)
new_api_key = None
if api_key:
click.secho("Adding API key...", fg='green')
new_api_key = mgr.add_api_authentication_key(result['id'])
table = formatting.Table(['Username', 'Email', 'Password', 'API Key'])
table.add_row([result['username'], result['email'], password, new_api_key])
env.fout(table) | python | def cli(env, username, email, password, from_user, template, api_key):
mgr = SoftLayer.UserManager(env.client)
user_mask = ("mask[id, firstName, lastName, email, companyName, address1, city, country, postalCode, "
"state, userStatusId, timezoneId]")
from_user_id = None
if from_user is None:
user_template = mgr.get_current_user(objectmask=user_mask)
from_user_id = user_template['id']
else:
from_user_id = helpers.resolve_id(mgr.resolve_ids, from_user, 'username')
user_template = mgr.get_user(from_user_id, objectmask=user_mask)
del user_template['id']
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)
user_template['username'] = username
if password == 'generate':
password = generate_password()
user_template['email'] = email
if not env.skip_confirmations:
table = formatting.KeyValueTable(['name', 'value'])
for key in user_template:
table.add_row([key, user_template[key]])
table.add_row(['password', password])
click.secho("You are about to create the following user...", fg='green')
env.fout(table)
if not formatting.confirm("Do you wish to continue?"):
raise exceptions.CLIAbort("Canceling creation!")
result = mgr.create_user(user_template, password)
new_api_key = None
if api_key:
click.secho("Adding API key...", fg='green')
new_api_key = mgr.add_api_authentication_key(result['id'])
table = formatting.Table(['Username', 'Email', 'Password', 'API Key'])
table.add_row([result['username'], result['email'], password, new_api_key])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"username",
",",
"email",
",",
"password",
",",
"from_user",
",",
"template",
",",
"api_key",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"UserManager",
"(",
"env",
".",
"client",
")",
"user_mask",
"=",
"(",
"\"mask[id, firstName, lastName, email, companyName, address1, city, country, postalCode, \"",
"\"state, userStatusId, timezoneId]\"",
")",
"from_user_id",
"=",
"None",
"if",
"from_user",
"is",
"None",
":",
"user_template",
"=",
"mgr",
".",
"get_current_user",
"(",
"objectmask",
"=",
"user_mask",
")",
"from_user_id",
"=",
"user_template",
"[",
"'id'",
"]",
"else",
":",
"from_user_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"from_user",
",",
"'username'",
")",
"user_template",
"=",
"mgr",
".",
"get_user",
"(",
"from_user_id",
",",
"objectmask",
"=",
"user_mask",
")",
"# If we send the ID back to the API, an exception will be thrown",
"del",
"user_template",
"[",
"'id'",
"]",
"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",
")",
"user_template",
"[",
"'username'",
"]",
"=",
"username",
"if",
"password",
"==",
"'generate'",
":",
"password",
"=",
"generate_password",
"(",
")",
"user_template",
"[",
"'email'",
"]",
"=",
"email",
"if",
"not",
"env",
".",
"skip_confirmations",
":",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"for",
"key",
"in",
"user_template",
":",
"table",
".",
"add_row",
"(",
"[",
"key",
",",
"user_template",
"[",
"key",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'password'",
",",
"password",
"]",
")",
"click",
".",
"secho",
"(",
"\"You are about to create the following user...\"",
",",
"fg",
"=",
"'green'",
")",
"env",
".",
"fout",
"(",
"table",
")",
"if",
"not",
"formatting",
".",
"confirm",
"(",
"\"Do you wish to continue?\"",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Canceling creation!\"",
")",
"result",
"=",
"mgr",
".",
"create_user",
"(",
"user_template",
",",
"password",
")",
"new_api_key",
"=",
"None",
"if",
"api_key",
":",
"click",
".",
"secho",
"(",
"\"Adding API key...\"",
",",
"fg",
"=",
"'green'",
")",
"new_api_key",
"=",
"mgr",
".",
"add_api_authentication_key",
"(",
"result",
"[",
"'id'",
"]",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Username'",
",",
"'Email'",
",",
"'Password'",
",",
"'API Key'",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"result",
"[",
"'username'",
"]",
",",
"result",
"[",
"'email'",
"]",
",",
"password",
",",
"new_api_key",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Creates a user Users.
:Example: slcli user create [email protected] -e [email protected] -p generate -a
-t '{"firstName": "Test", "lastName": "Testerson"}'
Remember to set the permissions and access for this new user. | [
"Creates",
"a",
"user",
"Users",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/create.py#L34-L88 |
softlayer/softlayer-python | SoftLayer/CLI/user/create.py | generate_password | def generate_password():
"""Returns a 23 character random string, with 3 special characters at the end"""
if sys.version_info > (3, 6):
import secrets # pylint: disable=import-error
alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for i in range(20))
special = ''.join(secrets.choice(string.punctuation) for i in range(3))
return password + special
else:
raise ImportError("Generating passwords require python 3.6 or higher") | python | def generate_password():
if sys.version_info > (3, 6):
import secrets
alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for i in range(20))
special = ''.join(secrets.choice(string.punctuation) for i in range(3))
return password + special
else:
raise ImportError("Generating passwords require python 3.6 or higher") | [
"def",
"generate_password",
"(",
")",
":",
"if",
"sys",
".",
"version_info",
">",
"(",
"3",
",",
"6",
")",
":",
"import",
"secrets",
"# pylint: disable=import-error",
"alphabet",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"password",
"=",
"''",
".",
"join",
"(",
"secrets",
".",
"choice",
"(",
"alphabet",
")",
"for",
"i",
"in",
"range",
"(",
"20",
")",
")",
"special",
"=",
"''",
".",
"join",
"(",
"secrets",
".",
"choice",
"(",
"string",
".",
"punctuation",
")",
"for",
"i",
"in",
"range",
"(",
"3",
")",
")",
"return",
"password",
"+",
"special",
"else",
":",
"raise",
"ImportError",
"(",
"\"Generating passwords require python 3.6 or higher\"",
")"
]
| Returns a 23 character random string, with 3 special characters at the end | [
"Returns",
"a",
"23",
"character",
"random",
"string",
"with",
"3",
"special",
"characters",
"at",
"the",
"end"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/create.py#L91-L100 |
softlayer/softlayer-python | SoftLayer/CLI/block/snapshot/create.py | cli | def cli(env, volume_id, notes):
"""Creates a snapshot on a given volume"""
block_manager = SoftLayer.BlockStorageManager(env.client)
snapshot = block_manager.create_snapshot(volume_id, notes=notes)
if 'id' in snapshot:
click.echo('New snapshot created with id: %s' % snapshot['id'])
else:
click.echo('Error occurred while creating snapshot.\n'
'Ensure volume is not failed over or in another '
'state which prevents taking snapshots.') | python | def cli(env, volume_id, notes):
block_manager = SoftLayer.BlockStorageManager(env.client)
snapshot = block_manager.create_snapshot(volume_id, notes=notes)
if 'id' in snapshot:
click.echo('New snapshot created with id: %s' % snapshot['id'])
else:
click.echo('Error occurred while creating snapshot.\n'
'Ensure volume is not failed over or in another '
'state which prevents taking snapshots.') | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"notes",
")",
":",
"block_manager",
"=",
"SoftLayer",
".",
"BlockStorageManager",
"(",
"env",
".",
"client",
")",
"snapshot",
"=",
"block_manager",
".",
"create_snapshot",
"(",
"volume_id",
",",
"notes",
"=",
"notes",
")",
"if",
"'id'",
"in",
"snapshot",
":",
"click",
".",
"echo",
"(",
"'New snapshot created with id: %s'",
"%",
"snapshot",
"[",
"'id'",
"]",
")",
"else",
":",
"click",
".",
"echo",
"(",
"'Error occurred while creating snapshot.\\n'",
"'Ensure volume is not failed over or in another '",
"'state which prevents taking snapshots.'",
")"
]
| Creates a snapshot on a given volume | [
"Creates",
"a",
"snapshot",
"on",
"a",
"given",
"volume"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/snapshot/create.py#L14-L24 |
softlayer/softlayer-python | SoftLayer/CLI/event_log/types.py | cli | def cli(env):
"""Get Event Log Types"""
mgr = SoftLayer.EventLogManager(env.client)
event_log_types = mgr.get_event_log_types()
table = formatting.Table(COLUMNS)
for event_log_type in event_log_types:
table.add_row([event_log_type])
env.fout(table) | python | def cli(env):
mgr = SoftLayer.EventLogManager(env.client)
event_log_types = mgr.get_event_log_types()
table = formatting.Table(COLUMNS)
for event_log_type in event_log_types:
table.add_row([event_log_type])
env.fout(table) | [
"def",
"cli",
"(",
"env",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"EventLogManager",
"(",
"env",
".",
"client",
")",
"event_log_types",
"=",
"mgr",
".",
"get_event_log_types",
"(",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"COLUMNS",
")",
"for",
"event_log_type",
"in",
"event_log_types",
":",
"table",
".",
"add_row",
"(",
"[",
"event_log_type",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
]
| Get Event Log Types | [
"Get",
"Event",
"Log",
"Types"
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/event_log/types.py#L15-L26 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | _get_extra_price_id | def _get_extra_price_id(items, key_name, hourly, location):
"""Returns a price id attached to item with the given key_name."""
for item in items:
if utils.lookup(item, 'keyName') != key_name:
continue
for price in item['prices']:
if not _matches_billing(price, hourly):
continue
if not _matches_location(price, location):
continue
return price['id']
raise SoftLayer.SoftLayerError(
"Could not find valid price for extra option, '%s'" % key_name) | python | def _get_extra_price_id(items, key_name, hourly, location):
for item in items:
if utils.lookup(item, 'keyName') != key_name:
continue
for price in item['prices']:
if not _matches_billing(price, hourly):
continue
if not _matches_location(price, location):
continue
return price['id']
raise SoftLayer.SoftLayerError(
"Could not find valid price for extra option, '%s'" % key_name) | [
"def",
"_get_extra_price_id",
"(",
"items",
",",
"key_name",
",",
"hourly",
",",
"location",
")",
":",
"for",
"item",
"in",
"items",
":",
"if",
"utils",
".",
"lookup",
"(",
"item",
",",
"'keyName'",
")",
"!=",
"key_name",
":",
"continue",
"for",
"price",
"in",
"item",
"[",
"'prices'",
"]",
":",
"if",
"not",
"_matches_billing",
"(",
"price",
",",
"hourly",
")",
":",
"continue",
"if",
"not",
"_matches_location",
"(",
"price",
",",
"location",
")",
":",
"continue",
"return",
"price",
"[",
"'id'",
"]",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Could not find valid price for extra option, '%s'\"",
"%",
"key_name",
")"
]
| Returns a price id attached to item with the given key_name. | [
"Returns",
"a",
"price",
"id",
"attached",
"to",
"item",
"with",
"the",
"given",
"key_name",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L668-L685 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | _get_default_price_id | def _get_default_price_id(items, option, hourly, location):
"""Returns a 'free' price id given an option."""
for item in items:
if utils.lookup(item, 'itemCategory', 'categoryCode') != option:
continue
for price in item['prices']:
if all([float(price.get('hourlyRecurringFee', 0)) == 0.0,
float(price.get('recurringFee', 0)) == 0.0,
_matches_billing(price, hourly),
_matches_location(price, location)]):
return price['id']
raise SoftLayer.SoftLayerError(
"Could not find valid price for '%s' option" % option) | python | def _get_default_price_id(items, option, hourly, location):
for item in items:
if utils.lookup(item, 'itemCategory', 'categoryCode') != option:
continue
for price in item['prices']:
if all([float(price.get('hourlyRecurringFee', 0)) == 0.0,
float(price.get('recurringFee', 0)) == 0.0,
_matches_billing(price, hourly),
_matches_location(price, location)]):
return price['id']
raise SoftLayer.SoftLayerError(
"Could not find valid price for '%s' option" % option) | [
"def",
"_get_default_price_id",
"(",
"items",
",",
"option",
",",
"hourly",
",",
"location",
")",
":",
"for",
"item",
"in",
"items",
":",
"if",
"utils",
".",
"lookup",
"(",
"item",
",",
"'itemCategory'",
",",
"'categoryCode'",
")",
"!=",
"option",
":",
"continue",
"for",
"price",
"in",
"item",
"[",
"'prices'",
"]",
":",
"if",
"all",
"(",
"[",
"float",
"(",
"price",
".",
"get",
"(",
"'hourlyRecurringFee'",
",",
"0",
")",
")",
"==",
"0.0",
",",
"float",
"(",
"price",
".",
"get",
"(",
"'recurringFee'",
",",
"0",
")",
")",
"==",
"0.0",
",",
"_matches_billing",
"(",
"price",
",",
"hourly",
")",
",",
"_matches_location",
"(",
"price",
",",
"location",
")",
"]",
")",
":",
"return",
"price",
"[",
"'id'",
"]",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Could not find valid price for '%s' option\"",
"%",
"option",
")"
]
| Returns a 'free' price id given an option. | [
"Returns",
"a",
"free",
"price",
"id",
"given",
"an",
"option",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L688-L703 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | _get_bandwidth_price_id | def _get_bandwidth_price_id(items,
hourly=True,
no_public=False,
location=None):
"""Choose a valid price id for bandwidth."""
# Prefer pay-for-use data transfer with hourly
for item in items:
capacity = float(item.get('capacity', 0))
# Hourly and private only do pay-as-you-go bandwidth
if any([utils.lookup(item,
'itemCategory',
'categoryCode') != 'bandwidth',
(hourly or no_public) and capacity != 0.0,
not (hourly or no_public) and capacity == 0.0]):
continue
for price in item['prices']:
if not _matches_billing(price, hourly):
continue
if not _matches_location(price, location):
continue
return price['id']
raise SoftLayer.SoftLayerError(
"Could not find valid price for bandwidth option") | python | def _get_bandwidth_price_id(items,
hourly=True,
no_public=False,
location=None):
for item in items:
capacity = float(item.get('capacity', 0))
if any([utils.lookup(item,
'itemCategory',
'categoryCode') != 'bandwidth',
(hourly or no_public) and capacity != 0.0,
not (hourly or no_public) and capacity == 0.0]):
continue
for price in item['prices']:
if not _matches_billing(price, hourly):
continue
if not _matches_location(price, location):
continue
return price['id']
raise SoftLayer.SoftLayerError(
"Could not find valid price for bandwidth option") | [
"def",
"_get_bandwidth_price_id",
"(",
"items",
",",
"hourly",
"=",
"True",
",",
"no_public",
"=",
"False",
",",
"location",
"=",
"None",
")",
":",
"# Prefer pay-for-use data transfer with hourly",
"for",
"item",
"in",
"items",
":",
"capacity",
"=",
"float",
"(",
"item",
".",
"get",
"(",
"'capacity'",
",",
"0",
")",
")",
"# Hourly and private only do pay-as-you-go bandwidth",
"if",
"any",
"(",
"[",
"utils",
".",
"lookup",
"(",
"item",
",",
"'itemCategory'",
",",
"'categoryCode'",
")",
"!=",
"'bandwidth'",
",",
"(",
"hourly",
"or",
"no_public",
")",
"and",
"capacity",
"!=",
"0.0",
",",
"not",
"(",
"hourly",
"or",
"no_public",
")",
"and",
"capacity",
"==",
"0.0",
"]",
")",
":",
"continue",
"for",
"price",
"in",
"item",
"[",
"'prices'",
"]",
":",
"if",
"not",
"_matches_billing",
"(",
"price",
",",
"hourly",
")",
":",
"continue",
"if",
"not",
"_matches_location",
"(",
"price",
",",
"location",
")",
":",
"continue",
"return",
"price",
"[",
"'id'",
"]",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Could not find valid price for bandwidth option\"",
")"
]
| Choose a valid price id for bandwidth. | [
"Choose",
"a",
"valid",
"price",
"id",
"for",
"bandwidth",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L706-L733 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | _get_os_price_id | def _get_os_price_id(items, os, location):
"""Returns the price id matching."""
for item in items:
if any([utils.lookup(item,
'itemCategory',
'categoryCode') != 'os',
utils.lookup(item,
'softwareDescription',
'referenceCode') != os]):
continue
for price in item['prices']:
if not _matches_location(price, location):
continue
return price['id']
raise SoftLayer.SoftLayerError("Could not find valid price for os: '%s'" %
os) | python | def _get_os_price_id(items, os, location):
for item in items:
if any([utils.lookup(item,
'itemCategory',
'categoryCode') != 'os',
utils.lookup(item,
'softwareDescription',
'referenceCode') != os]):
continue
for price in item['prices']:
if not _matches_location(price, location):
continue
return price['id']
raise SoftLayer.SoftLayerError("Could not find valid price for os: '%s'" %
os) | [
"def",
"_get_os_price_id",
"(",
"items",
",",
"os",
",",
"location",
")",
":",
"for",
"item",
"in",
"items",
":",
"if",
"any",
"(",
"[",
"utils",
".",
"lookup",
"(",
"item",
",",
"'itemCategory'",
",",
"'categoryCode'",
")",
"!=",
"'os'",
",",
"utils",
".",
"lookup",
"(",
"item",
",",
"'softwareDescription'",
",",
"'referenceCode'",
")",
"!=",
"os",
"]",
")",
":",
"continue",
"for",
"price",
"in",
"item",
"[",
"'prices'",
"]",
":",
"if",
"not",
"_matches_location",
"(",
"price",
",",
"location",
")",
":",
"continue",
"return",
"price",
"[",
"'id'",
"]",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Could not find valid price for os: '%s'\"",
"%",
"os",
")"
]
| Returns the price id matching. | [
"Returns",
"the",
"price",
"id",
"matching",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L736-L755 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | _get_port_speed_price_id | def _get_port_speed_price_id(items, port_speed, no_public, location):
"""Choose a valid price id for port speed."""
for item in items:
if utils.lookup(item,
'itemCategory',
'categoryCode') != 'port_speed':
continue
# Check for correct capacity and if the item matches private only
if any([int(utils.lookup(item, 'capacity')) != port_speed,
_is_private_port_speed_item(item) != no_public,
not _is_bonded(item)]):
continue
for price in item['prices']:
if not _matches_location(price, location):
continue
return price['id']
raise SoftLayer.SoftLayerError(
"Could not find valid price for port speed: '%s'" % port_speed) | python | def _get_port_speed_price_id(items, port_speed, no_public, location):
for item in items:
if utils.lookup(item,
'itemCategory',
'categoryCode') != 'port_speed':
continue
if any([int(utils.lookup(item, 'capacity')) != port_speed,
_is_private_port_speed_item(item) != no_public,
not _is_bonded(item)]):
continue
for price in item['prices']:
if not _matches_location(price, location):
continue
return price['id']
raise SoftLayer.SoftLayerError(
"Could not find valid price for port speed: '%s'" % port_speed) | [
"def",
"_get_port_speed_price_id",
"(",
"items",
",",
"port_speed",
",",
"no_public",
",",
"location",
")",
":",
"for",
"item",
"in",
"items",
":",
"if",
"utils",
".",
"lookup",
"(",
"item",
",",
"'itemCategory'",
",",
"'categoryCode'",
")",
"!=",
"'port_speed'",
":",
"continue",
"# Check for correct capacity and if the item matches private only",
"if",
"any",
"(",
"[",
"int",
"(",
"utils",
".",
"lookup",
"(",
"item",
",",
"'capacity'",
")",
")",
"!=",
"port_speed",
",",
"_is_private_port_speed_item",
"(",
"item",
")",
"!=",
"no_public",
",",
"not",
"_is_bonded",
"(",
"item",
")",
"]",
")",
":",
"continue",
"for",
"price",
"in",
"item",
"[",
"'prices'",
"]",
":",
"if",
"not",
"_matches_location",
"(",
"price",
",",
"location",
")",
":",
"continue",
"return",
"price",
"[",
"'id'",
"]",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Could not find valid price for port speed: '%s'\"",
"%",
"port_speed",
")"
]
| Choose a valid price id for port speed. | [
"Choose",
"a",
"valid",
"price",
"id",
"for",
"port",
"speed",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L758-L780 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | _matches_billing | def _matches_billing(price, hourly):
"""Return True if the price object is hourly and/or monthly."""
return any([hourly and price.get('hourlyRecurringFee') is not None,
not hourly and price.get('recurringFee') is not None]) | python | def _matches_billing(price, hourly):
return any([hourly and price.get('hourlyRecurringFee') is not None,
not hourly and price.get('recurringFee') is not None]) | [
"def",
"_matches_billing",
"(",
"price",
",",
"hourly",
")",
":",
"return",
"any",
"(",
"[",
"hourly",
"and",
"price",
".",
"get",
"(",
"'hourlyRecurringFee'",
")",
"is",
"not",
"None",
",",
"not",
"hourly",
"and",
"price",
".",
"get",
"(",
"'recurringFee'",
")",
"is",
"not",
"None",
"]",
")"
]
| Return True if the price object is hourly and/or monthly. | [
"Return",
"True",
"if",
"the",
"price",
"object",
"is",
"hourly",
"and",
"/",
"or",
"monthly",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L783-L786 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | _matches_location | def _matches_location(price, location):
"""Return True if the price object matches the location."""
# the price has no location restriction
if not price.get('locationGroupId'):
return True
# Check to see if any of the location groups match the location group
# of this price object
for group in location['location']['location']['priceGroups']:
if group['id'] == price['locationGroupId']:
return True
return False | python | def _matches_location(price, location):
if not price.get('locationGroupId'):
return True
for group in location['location']['location']['priceGroups']:
if group['id'] == price['locationGroupId']:
return True
return False | [
"def",
"_matches_location",
"(",
"price",
",",
"location",
")",
":",
"# the price has no location restriction",
"if",
"not",
"price",
".",
"get",
"(",
"'locationGroupId'",
")",
":",
"return",
"True",
"# Check to see if any of the location groups match the location group",
"# of this price object",
"for",
"group",
"in",
"location",
"[",
"'location'",
"]",
"[",
"'location'",
"]",
"[",
"'priceGroups'",
"]",
":",
"if",
"group",
"[",
"'id'",
"]",
"==",
"price",
"[",
"'locationGroupId'",
"]",
":",
"return",
"True",
"return",
"False"
]
| Return True if the price object matches the location. | [
"Return",
"True",
"if",
"the",
"price",
"object",
"matches",
"the",
"location",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L789-L801 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | _get_location | def _get_location(package, location):
"""Get the longer key with a short location name."""
for region in package['regions']:
if region['location']['location']['name'] == location:
return region
raise SoftLayer.SoftLayerError("Could not find valid location for: '%s'" % location) | python | def _get_location(package, location):
for region in package['regions']:
if region['location']['location']['name'] == location:
return region
raise SoftLayer.SoftLayerError("Could not find valid location for: '%s'" % location) | [
"def",
"_get_location",
"(",
"package",
",",
"location",
")",
":",
"for",
"region",
"in",
"package",
"[",
"'regions'",
"]",
":",
"if",
"region",
"[",
"'location'",
"]",
"[",
"'location'",
"]",
"[",
"'name'",
"]",
"==",
"location",
":",
"return",
"region",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Could not find valid location for: '%s'\"",
"%",
"location",
")"
]
| Get the longer key with a short location name. | [
"Get",
"the",
"longer",
"key",
"with",
"a",
"short",
"location",
"name",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L822-L828 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | _get_preset_id | def _get_preset_id(package, size):
"""Get the preset id given the keyName of the preset."""
for preset in package['activePresets'] + package['accountRestrictedActivePresets']:
if preset['keyName'] == size or preset['id'] == size:
return preset['id']
raise SoftLayer.SoftLayerError("Could not find valid size for: '%s'" % size) | python | def _get_preset_id(package, size):
for preset in package['activePresets'] + package['accountRestrictedActivePresets']:
if preset['keyName'] == size or preset['id'] == size:
return preset['id']
raise SoftLayer.SoftLayerError("Could not find valid size for: '%s'" % size) | [
"def",
"_get_preset_id",
"(",
"package",
",",
"size",
")",
":",
"for",
"preset",
"in",
"package",
"[",
"'activePresets'",
"]",
"+",
"package",
"[",
"'accountRestrictedActivePresets'",
"]",
":",
"if",
"preset",
"[",
"'keyName'",
"]",
"==",
"size",
"or",
"preset",
"[",
"'id'",
"]",
"==",
"size",
":",
"return",
"preset",
"[",
"'id'",
"]",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Could not find valid size for: '%s'\"",
"%",
"size",
")"
]
| Get the preset id given the keyName of the preset. | [
"Get",
"the",
"preset",
"id",
"given",
"the",
"keyName",
"of",
"the",
"preset",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L831-L837 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager.cancel_hardware | def cancel_hardware(self, hardware_id, reason='unneeded', comment='', immediate=False):
"""Cancels the specified dedicated server.
Example::
# Cancels hardware id 1234
result = mgr.cancel_hardware(hardware_id=1234)
:param int hardware_id: The ID of the hardware to be cancelled.
:param string reason: The reason code for the cancellation. This should come from
:func:`get_cancellation_reasons`.
:param string comment: An optional comment to include with the cancellation.
:param bool immediate: If set to True, will automatically update the cancelation ticket to request
the resource be reclaimed asap. This request still has to be reviewed by a human
:returns: True on success or an exception
"""
# Get cancel reason
reasons = self.get_cancellation_reasons()
cancel_reason = reasons.get(reason, reasons['unneeded'])
ticket_mgr = SoftLayer.TicketManager(self.client)
mask = 'mask[id, hourlyBillingFlag, billingItem[id], openCancellationTicket[id], activeTransaction]'
hw_billing = self.get_hardware(hardware_id, mask=mask)
if 'activeTransaction' in hw_billing:
raise SoftLayer.SoftLayerError("Unable to cancel hardware with running transaction")
if 'billingItem' not in hw_billing:
raise SoftLayer.SoftLayerError("Ticket #%s already exists for this server" %
hw_billing['openCancellationTicket']['id'])
billing_id = hw_billing['billingItem']['id']
if immediate and not hw_billing['hourlyBillingFlag']:
LOGGER.warning("Immediate cancelation of montly servers is not guaranteed."
"Please check the cancelation ticket for updates.")
result = self.client.call('Billing_Item', 'cancelItem',
False, False, cancel_reason, comment, id=billing_id)
hw_billing = self.get_hardware(hardware_id, mask=mask)
ticket_number = hw_billing['openCancellationTicket']['id']
cancel_message = "Please reclaim this server ASAP, it is no longer needed. Thankyou."
ticket_mgr.update_ticket(ticket_number, cancel_message)
LOGGER.info("Cancelation ticket #%s has been updated requesting immediate reclaim", ticket_number)
else:
result = self.client.call('Billing_Item', 'cancelItem',
immediate, False, cancel_reason, comment, id=billing_id)
hw_billing = self.get_hardware(hardware_id, mask=mask)
ticket_number = hw_billing['openCancellationTicket']['id']
LOGGER.info("Cancelation ticket #%s has been created", ticket_number)
return result | python | def cancel_hardware(self, hardware_id, reason='unneeded', comment='', immediate=False):
reasons = self.get_cancellation_reasons()
cancel_reason = reasons.get(reason, reasons['unneeded'])
ticket_mgr = SoftLayer.TicketManager(self.client)
mask = 'mask[id, hourlyBillingFlag, billingItem[id], openCancellationTicket[id], activeTransaction]'
hw_billing = self.get_hardware(hardware_id, mask=mask)
if 'activeTransaction' in hw_billing:
raise SoftLayer.SoftLayerError("Unable to cancel hardware with running transaction")
if 'billingItem' not in hw_billing:
raise SoftLayer.SoftLayerError("Ticket
hw_billing['openCancellationTicket']['id'])
billing_id = hw_billing['billingItem']['id']
if immediate and not hw_billing['hourlyBillingFlag']:
LOGGER.warning("Immediate cancelation of montly servers is not guaranteed."
"Please check the cancelation ticket for updates.")
result = self.client.call('Billing_Item', 'cancelItem',
False, False, cancel_reason, comment, id=billing_id)
hw_billing = self.get_hardware(hardware_id, mask=mask)
ticket_number = hw_billing['openCancellationTicket']['id']
cancel_message = "Please reclaim this server ASAP, it is no longer needed. Thankyou."
ticket_mgr.update_ticket(ticket_number, cancel_message)
LOGGER.info("Cancelation ticket
else:
result = self.client.call('Billing_Item', 'cancelItem',
immediate, False, cancel_reason, comment, id=billing_id)
hw_billing = self.get_hardware(hardware_id, mask=mask)
ticket_number = hw_billing['openCancellationTicket']['id']
LOGGER.info("Cancelation ticket
return result | [
"def",
"cancel_hardware",
"(",
"self",
",",
"hardware_id",
",",
"reason",
"=",
"'unneeded'",
",",
"comment",
"=",
"''",
",",
"immediate",
"=",
"False",
")",
":",
"# Get cancel reason",
"reasons",
"=",
"self",
".",
"get_cancellation_reasons",
"(",
")",
"cancel_reason",
"=",
"reasons",
".",
"get",
"(",
"reason",
",",
"reasons",
"[",
"'unneeded'",
"]",
")",
"ticket_mgr",
"=",
"SoftLayer",
".",
"TicketManager",
"(",
"self",
".",
"client",
")",
"mask",
"=",
"'mask[id, hourlyBillingFlag, billingItem[id], openCancellationTicket[id], activeTransaction]'",
"hw_billing",
"=",
"self",
".",
"get_hardware",
"(",
"hardware_id",
",",
"mask",
"=",
"mask",
")",
"if",
"'activeTransaction'",
"in",
"hw_billing",
":",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Unable to cancel hardware with running transaction\"",
")",
"if",
"'billingItem'",
"not",
"in",
"hw_billing",
":",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Ticket #%s already exists for this server\"",
"%",
"hw_billing",
"[",
"'openCancellationTicket'",
"]",
"[",
"'id'",
"]",
")",
"billing_id",
"=",
"hw_billing",
"[",
"'billingItem'",
"]",
"[",
"'id'",
"]",
"if",
"immediate",
"and",
"not",
"hw_billing",
"[",
"'hourlyBillingFlag'",
"]",
":",
"LOGGER",
".",
"warning",
"(",
"\"Immediate cancelation of montly servers is not guaranteed.\"",
"\"Please check the cancelation ticket for updates.\"",
")",
"result",
"=",
"self",
".",
"client",
".",
"call",
"(",
"'Billing_Item'",
",",
"'cancelItem'",
",",
"False",
",",
"False",
",",
"cancel_reason",
",",
"comment",
",",
"id",
"=",
"billing_id",
")",
"hw_billing",
"=",
"self",
".",
"get_hardware",
"(",
"hardware_id",
",",
"mask",
"=",
"mask",
")",
"ticket_number",
"=",
"hw_billing",
"[",
"'openCancellationTicket'",
"]",
"[",
"'id'",
"]",
"cancel_message",
"=",
"\"Please reclaim this server ASAP, it is no longer needed. Thankyou.\"",
"ticket_mgr",
".",
"update_ticket",
"(",
"ticket_number",
",",
"cancel_message",
")",
"LOGGER",
".",
"info",
"(",
"\"Cancelation ticket #%s has been updated requesting immediate reclaim\"",
",",
"ticket_number",
")",
"else",
":",
"result",
"=",
"self",
".",
"client",
".",
"call",
"(",
"'Billing_Item'",
",",
"'cancelItem'",
",",
"immediate",
",",
"False",
",",
"cancel_reason",
",",
"comment",
",",
"id",
"=",
"billing_id",
")",
"hw_billing",
"=",
"self",
".",
"get_hardware",
"(",
"hardware_id",
",",
"mask",
"=",
"mask",
")",
"ticket_number",
"=",
"hw_billing",
"[",
"'openCancellationTicket'",
"]",
"[",
"'id'",
"]",
"LOGGER",
".",
"info",
"(",
"\"Cancelation ticket #%s has been created\"",
",",
"ticket_number",
")",
"return",
"result"
]
| Cancels the specified dedicated server.
Example::
# Cancels hardware id 1234
result = mgr.cancel_hardware(hardware_id=1234)
:param int hardware_id: The ID of the hardware to be cancelled.
:param string reason: The reason code for the cancellation. This should come from
:func:`get_cancellation_reasons`.
:param string comment: An optional comment to include with the cancellation.
:param bool immediate: If set to True, will automatically update the cancelation ticket to request
the resource be reclaimed asap. This request still has to be reviewed by a human
:returns: True on success or an exception | [
"Cancels",
"the",
"specified",
"dedicated",
"server",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L61-L112 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager.list_hardware | def list_hardware(self, tags=None, cpus=None, memory=None, hostname=None,
domain=None, datacenter=None, nic_speed=None,
public_ip=None, private_ip=None, **kwargs):
"""List all hardware (servers and bare metal computing instances).
:param list tags: filter based on tags
:param integer cpus: filter based on number of CPUS
:param integer memory: filter based on amount of memory in gigabytes
:param string hostname: filter based on hostname
:param string domain: filter based on domain
:param string datacenter: filter based on datacenter
:param integer nic_speed: filter based on network speed (in MBPS)
:param string public_ip: filter based on public ip address
:param string private_ip: filter based on private ip address
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
:returns: Returns a list of dictionaries representing the matching
hardware. This list will contain both dedicated servers and
bare metal computing instances
Example::
# Using a custom object-mask. Will get ONLY what is specified
# These will stem from the SoftLayer_Hardware_Server datatype
object_mask = "mask[hostname,monitoringRobot[robotStatus]]"
result = mgr.list_hardware(mask=object_mask)
"""
if 'mask' not in kwargs:
hw_items = [
'id',
'hostname',
'domain',
'hardwareStatusId',
'globalIdentifier',
'fullyQualifiedDomainName',
'processorPhysicalCoreAmount',
'memoryCapacity',
'primaryBackendIpAddress',
'primaryIpAddress',
'datacenter',
]
server_items = [
'activeTransaction[id, transactionStatus[friendlyName,name]]',
]
kwargs['mask'] = ('[mask[%s],'
' mask(SoftLayer_Hardware_Server)[%s]]'
% (','.join(hw_items), ','.join(server_items)))
_filter = utils.NestedDict(kwargs.get('filter') or {})
if tags:
_filter['hardware']['tagReferences']['tag']['name'] = {
'operation': 'in',
'options': [{'name': 'data', 'value': tags}],
}
if cpus:
_filter['hardware']['processorPhysicalCoreAmount'] = (
utils.query_filter(cpus))
if memory:
_filter['hardware']['memoryCapacity'] = utils.query_filter(memory)
if hostname:
_filter['hardware']['hostname'] = utils.query_filter(hostname)
if domain:
_filter['hardware']['domain'] = utils.query_filter(domain)
if datacenter:
_filter['hardware']['datacenter']['name'] = (
utils.query_filter(datacenter))
if nic_speed:
_filter['hardware']['networkComponents']['maxSpeed'] = (
utils.query_filter(nic_speed))
if public_ip:
_filter['hardware']['primaryIpAddress'] = (
utils.query_filter(public_ip))
if private_ip:
_filter['hardware']['primaryBackendIpAddress'] = (
utils.query_filter(private_ip))
kwargs['filter'] = _filter.to_dict()
kwargs['iter'] = True
return self.client.call('Account', 'getHardware', **kwargs) | python | def list_hardware(self, tags=None, cpus=None, memory=None, hostname=None,
domain=None, datacenter=None, nic_speed=None,
public_ip=None, private_ip=None, **kwargs):
if 'mask' not in kwargs:
hw_items = [
'id',
'hostname',
'domain',
'hardwareStatusId',
'globalIdentifier',
'fullyQualifiedDomainName',
'processorPhysicalCoreAmount',
'memoryCapacity',
'primaryBackendIpAddress',
'primaryIpAddress',
'datacenter',
]
server_items = [
'activeTransaction[id, transactionStatus[friendlyName,name]]',
]
kwargs['mask'] = ('[mask[%s],'
' mask(SoftLayer_Hardware_Server)[%s]]'
% (','.join(hw_items), ','.join(server_items)))
_filter = utils.NestedDict(kwargs.get('filter') or {})
if tags:
_filter['hardware']['tagReferences']['tag']['name'] = {
'operation': 'in',
'options': [{'name': 'data', 'value': tags}],
}
if cpus:
_filter['hardware']['processorPhysicalCoreAmount'] = (
utils.query_filter(cpus))
if memory:
_filter['hardware']['memoryCapacity'] = utils.query_filter(memory)
if hostname:
_filter['hardware']['hostname'] = utils.query_filter(hostname)
if domain:
_filter['hardware']['domain'] = utils.query_filter(domain)
if datacenter:
_filter['hardware']['datacenter']['name'] = (
utils.query_filter(datacenter))
if nic_speed:
_filter['hardware']['networkComponents']['maxSpeed'] = (
utils.query_filter(nic_speed))
if public_ip:
_filter['hardware']['primaryIpAddress'] = (
utils.query_filter(public_ip))
if private_ip:
_filter['hardware']['primaryBackendIpAddress'] = (
utils.query_filter(private_ip))
kwargs['filter'] = _filter.to_dict()
kwargs['iter'] = True
return self.client.call('Account', 'getHardware', **kwargs) | [
"def",
"list_hardware",
"(",
"self",
",",
"tags",
"=",
"None",
",",
"cpus",
"=",
"None",
",",
"memory",
"=",
"None",
",",
"hostname",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"datacenter",
"=",
"None",
",",
"nic_speed",
"=",
"None",
",",
"public_ip",
"=",
"None",
",",
"private_ip",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"hw_items",
"=",
"[",
"'id'",
",",
"'hostname'",
",",
"'domain'",
",",
"'hardwareStatusId'",
",",
"'globalIdentifier'",
",",
"'fullyQualifiedDomainName'",
",",
"'processorPhysicalCoreAmount'",
",",
"'memoryCapacity'",
",",
"'primaryBackendIpAddress'",
",",
"'primaryIpAddress'",
",",
"'datacenter'",
",",
"]",
"server_items",
"=",
"[",
"'activeTransaction[id, transactionStatus[friendlyName,name]]'",
",",
"]",
"kwargs",
"[",
"'mask'",
"]",
"=",
"(",
"'[mask[%s],'",
"' mask(SoftLayer_Hardware_Server)[%s]]'",
"%",
"(",
"','",
".",
"join",
"(",
"hw_items",
")",
",",
"','",
".",
"join",
"(",
"server_items",
")",
")",
")",
"_filter",
"=",
"utils",
".",
"NestedDict",
"(",
"kwargs",
".",
"get",
"(",
"'filter'",
")",
"or",
"{",
"}",
")",
"if",
"tags",
":",
"_filter",
"[",
"'hardware'",
"]",
"[",
"'tagReferences'",
"]",
"[",
"'tag'",
"]",
"[",
"'name'",
"]",
"=",
"{",
"'operation'",
":",
"'in'",
",",
"'options'",
":",
"[",
"{",
"'name'",
":",
"'data'",
",",
"'value'",
":",
"tags",
"}",
"]",
",",
"}",
"if",
"cpus",
":",
"_filter",
"[",
"'hardware'",
"]",
"[",
"'processorPhysicalCoreAmount'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"cpus",
")",
")",
"if",
"memory",
":",
"_filter",
"[",
"'hardware'",
"]",
"[",
"'memoryCapacity'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"memory",
")",
"if",
"hostname",
":",
"_filter",
"[",
"'hardware'",
"]",
"[",
"'hostname'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"hostname",
")",
"if",
"domain",
":",
"_filter",
"[",
"'hardware'",
"]",
"[",
"'domain'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"domain",
")",
"if",
"datacenter",
":",
"_filter",
"[",
"'hardware'",
"]",
"[",
"'datacenter'",
"]",
"[",
"'name'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"datacenter",
")",
")",
"if",
"nic_speed",
":",
"_filter",
"[",
"'hardware'",
"]",
"[",
"'networkComponents'",
"]",
"[",
"'maxSpeed'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"nic_speed",
")",
")",
"if",
"public_ip",
":",
"_filter",
"[",
"'hardware'",
"]",
"[",
"'primaryIpAddress'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"public_ip",
")",
")",
"if",
"private_ip",
":",
"_filter",
"[",
"'hardware'",
"]",
"[",
"'primaryBackendIpAddress'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"private_ip",
")",
")",
"kwargs",
"[",
"'filter'",
"]",
"=",
"_filter",
".",
"to_dict",
"(",
")",
"kwargs",
"[",
"'iter'",
"]",
"=",
"True",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'Account'",
",",
"'getHardware'",
",",
"*",
"*",
"kwargs",
")"
]
| List all hardware (servers and bare metal computing instances).
:param list tags: filter based on tags
:param integer cpus: filter based on number of CPUS
:param integer memory: filter based on amount of memory in gigabytes
:param string hostname: filter based on hostname
:param string domain: filter based on domain
:param string datacenter: filter based on datacenter
:param integer nic_speed: filter based on network speed (in MBPS)
:param string public_ip: filter based on public ip address
:param string private_ip: filter based on private ip address
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
:returns: Returns a list of dictionaries representing the matching
hardware. This list will contain both dedicated servers and
bare metal computing instances
Example::
# Using a custom object-mask. Will get ONLY what is specified
# These will stem from the SoftLayer_Hardware_Server datatype
object_mask = "mask[hostname,monitoringRobot[robotStatus]]"
result = mgr.list_hardware(mask=object_mask) | [
"List",
"all",
"hardware",
"(",
"servers",
"and",
"bare",
"metal",
"computing",
"instances",
")",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L115-L201 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager.get_hardware | def get_hardware(self, hardware_id, **kwargs):
"""Get details about a hardware device.
:param integer id: the hardware ID
:returns: A dictionary containing a large amount of information about
the specified server.
Example::
object_mask = "mask[id,networkVlans[vlanNumber]]"
# Object masks are optional
result = mgr.get_hardware(hardware_id=1234,mask=object_mask)
"""
if 'mask' not in kwargs:
kwargs['mask'] = (
'id,'
'globalIdentifier,'
'fullyQualifiedDomainName,'
'hostname,'
'domain,'
'provisionDate,'
'hardwareStatus,'
'processorPhysicalCoreAmount,'
'memoryCapacity,'
'notes,'
'privateNetworkOnlyFlag,'
'primaryBackendIpAddress,'
'primaryIpAddress,'
'networkManagementIpAddress,'
'userData,'
'datacenter,'
'''networkComponents[id, status, speed, maxSpeed, name,
ipmiMacAddress, ipmiIpAddress, macAddress, primaryIpAddress,
port, primarySubnet[id, netmask, broadcastAddress,
networkIdentifier, gateway]],'''
'hardwareChassis[id,name],'
'activeTransaction[id, transactionStatus[friendlyName,name]],'
'''operatingSystem[
softwareLicense[softwareDescription[manufacturer,
name,
version,
referenceCode]],
passwords[username,password]],'''
'''softwareComponents[
softwareLicense[softwareDescription[manufacturer,
name,
version,
referenceCode]],
passwords[username,password]],'''
'billingItem['
'id,nextInvoiceTotalRecurringAmount,'
'children[nextInvoiceTotalRecurringAmount],'
'orderItem.order.userRecord[username]'
'],'
'hourlyBillingFlag,'
'tagReferences[id,tag[name,id]],'
'networkVlans[id,vlanNumber,networkSpace],'
'remoteManagementAccounts[username,password]'
)
return self.hardware.getObject(id=hardware_id, **kwargs) | python | def get_hardware(self, hardware_id, **kwargs):
if 'mask' not in kwargs:
kwargs['mask'] = (
'id,'
'globalIdentifier,'
'fullyQualifiedDomainName,'
'hostname,'
'domain,'
'provisionDate,'
'hardwareStatus,'
'processorPhysicalCoreAmount,'
'memoryCapacity,'
'notes,'
'privateNetworkOnlyFlag,'
'primaryBackendIpAddress,'
'primaryIpAddress,'
'networkManagementIpAddress,'
'userData,'
'datacenter,'
'hardwareChassis[id,name],'
'activeTransaction[id, transactionStatus[friendlyName,name]],'
'billingItem['
'id,nextInvoiceTotalRecurringAmount,'
'children[nextInvoiceTotalRecurringAmount],'
'orderItem.order.userRecord[username]'
'],'
'hourlyBillingFlag,'
'tagReferences[id,tag[name,id]],'
'networkVlans[id,vlanNumber,networkSpace],'
'remoteManagementAccounts[username,password]'
)
return self.hardware.getObject(id=hardware_id, **kwargs) | [
"def",
"get_hardware",
"(",
"self",
",",
"hardware_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'mask'",
"]",
"=",
"(",
"'id,'",
"'globalIdentifier,'",
"'fullyQualifiedDomainName,'",
"'hostname,'",
"'domain,'",
"'provisionDate,'",
"'hardwareStatus,'",
"'processorPhysicalCoreAmount,'",
"'memoryCapacity,'",
"'notes,'",
"'privateNetworkOnlyFlag,'",
"'primaryBackendIpAddress,'",
"'primaryIpAddress,'",
"'networkManagementIpAddress,'",
"'userData,'",
"'datacenter,'",
"'''networkComponents[id, status, speed, maxSpeed, name,\n ipmiMacAddress, ipmiIpAddress, macAddress, primaryIpAddress,\n port, primarySubnet[id, netmask, broadcastAddress,\n networkIdentifier, gateway]],'''",
"'hardwareChassis[id,name],'",
"'activeTransaction[id, transactionStatus[friendlyName,name]],'",
"'''operatingSystem[\n softwareLicense[softwareDescription[manufacturer,\n name,\n version,\n referenceCode]],\n passwords[username,password]],'''",
"'''softwareComponents[\n softwareLicense[softwareDescription[manufacturer,\n name,\n version,\n referenceCode]],\n passwords[username,password]],'''",
"'billingItem['",
"'id,nextInvoiceTotalRecurringAmount,'",
"'children[nextInvoiceTotalRecurringAmount],'",
"'orderItem.order.userRecord[username]'",
"'],'",
"'hourlyBillingFlag,'",
"'tagReferences[id,tag[name,id]],'",
"'networkVlans[id,vlanNumber,networkSpace],'",
"'remoteManagementAccounts[username,password]'",
")",
"return",
"self",
".",
"hardware",
".",
"getObject",
"(",
"id",
"=",
"hardware_id",
",",
"*",
"*",
"kwargs",
")"
]
| Get details about a hardware device.
:param integer id: the hardware ID
:returns: A dictionary containing a large amount of information about
the specified server.
Example::
object_mask = "mask[id,networkVlans[vlanNumber]]"
# Object masks are optional
result = mgr.get_hardware(hardware_id=1234,mask=object_mask) | [
"Get",
"details",
"about",
"a",
"hardware",
"device",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L204-L265 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager.reload | def reload(self, hardware_id, post_uri=None, ssh_keys=None):
"""Perform an OS reload of a server with its current configuration.
:param integer hardware_id: the instance ID to reload
:param string post_uri: The URI of the post-install script to run
after reload
:param list ssh_keys: The SSH keys to add to the root user
"""
config = {}
if post_uri:
config['customProvisionScriptUri'] = post_uri
if ssh_keys:
config['sshKeyIds'] = [key_id for key_id in ssh_keys]
return self.hardware.reloadOperatingSystem('FORCE', config,
id=hardware_id) | python | def reload(self, hardware_id, post_uri=None, ssh_keys=None):
config = {}
if post_uri:
config['customProvisionScriptUri'] = post_uri
if ssh_keys:
config['sshKeyIds'] = [key_id for key_id in ssh_keys]
return self.hardware.reloadOperatingSystem('FORCE', config,
id=hardware_id) | [
"def",
"reload",
"(",
"self",
",",
"hardware_id",
",",
"post_uri",
"=",
"None",
",",
"ssh_keys",
"=",
"None",
")",
":",
"config",
"=",
"{",
"}",
"if",
"post_uri",
":",
"config",
"[",
"'customProvisionScriptUri'",
"]",
"=",
"post_uri",
"if",
"ssh_keys",
":",
"config",
"[",
"'sshKeyIds'",
"]",
"=",
"[",
"key_id",
"for",
"key_id",
"in",
"ssh_keys",
"]",
"return",
"self",
".",
"hardware",
".",
"reloadOperatingSystem",
"(",
"'FORCE'",
",",
"config",
",",
"id",
"=",
"hardware_id",
")"
]
| Perform an OS reload of a server with its current configuration.
:param integer hardware_id: the instance ID to reload
:param string post_uri: The URI of the post-install script to run
after reload
:param list ssh_keys: The SSH keys to add to the root user | [
"Perform",
"an",
"OS",
"reload",
"of",
"a",
"server",
"with",
"its",
"current",
"configuration",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L267-L285 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager.change_port_speed | def change_port_speed(self, hardware_id, public, speed):
"""Allows you to change the port speed of a server's NICs.
:param int hardware_id: The ID of the server
:param bool public: Flag to indicate which interface to change.
True (default) means the public interface.
False indicates the private interface.
:param int speed: The port speed to set.
.. warning::
A port speed of 0 will disable the interface.
Example::
#change the Public interface to 10Mbps on instance 12345
result = mgr.change_port_speed(hardware_id=12345,
public=True, speed=10)
# result will be True or an Exception
"""
if public:
return self.client.call('Hardware_Server',
'setPublicNetworkInterfaceSpeed',
speed, id=hardware_id)
else:
return self.client.call('Hardware_Server',
'setPrivateNetworkInterfaceSpeed',
speed, id=hardware_id) | python | def change_port_speed(self, hardware_id, public, speed):
if public:
return self.client.call('Hardware_Server',
'setPublicNetworkInterfaceSpeed',
speed, id=hardware_id)
else:
return self.client.call('Hardware_Server',
'setPrivateNetworkInterfaceSpeed',
speed, id=hardware_id) | [
"def",
"change_port_speed",
"(",
"self",
",",
"hardware_id",
",",
"public",
",",
"speed",
")",
":",
"if",
"public",
":",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'Hardware_Server'",
",",
"'setPublicNetworkInterfaceSpeed'",
",",
"speed",
",",
"id",
"=",
"hardware_id",
")",
"else",
":",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'Hardware_Server'",
",",
"'setPrivateNetworkInterfaceSpeed'",
",",
"speed",
",",
"id",
"=",
"hardware_id",
")"
]
| Allows you to change the port speed of a server's NICs.
:param int hardware_id: The ID of the server
:param bool public: Flag to indicate which interface to change.
True (default) means the public interface.
False indicates the private interface.
:param int speed: The port speed to set.
.. warning::
A port speed of 0 will disable the interface.
Example::
#change the Public interface to 10Mbps on instance 12345
result = mgr.change_port_speed(hardware_id=12345,
public=True, speed=10)
# result will be True or an Exception | [
"Allows",
"you",
"to",
"change",
"the",
"port",
"speed",
"of",
"a",
"server",
"s",
"NICs",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L298-L324 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager.place_order | def place_order(self, **kwargs):
"""Places an order for a piece of hardware.
See get_create_options() for valid arguments.
:param string size: server size name or presetId
:param string hostname: server hostname
:param string domain: server domain name
:param string location: location (datacenter) name
:param string os: operating system name
:param int port_speed: Port speed in Mbps
:param list ssh_keys: list of ssh key ids
:param string post_uri: The URI of the post-install script to run
after reload
:param boolean hourly: True if using hourly pricing (default).
False for monthly.
:param boolean no_public: True if this server should only have private
interfaces
:param list extras: List of extra feature names
"""
create_options = self._generate_create_dict(**kwargs)
return self.client['Product_Order'].placeOrder(create_options) | python | def place_order(self, **kwargs):
create_options = self._generate_create_dict(**kwargs)
return self.client['Product_Order'].placeOrder(create_options) | [
"def",
"place_order",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"create_options",
"=",
"self",
".",
"_generate_create_dict",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"client",
"[",
"'Product_Order'",
"]",
".",
"placeOrder",
"(",
"create_options",
")"
]
| Places an order for a piece of hardware.
See get_create_options() for valid arguments.
:param string size: server size name or presetId
:param string hostname: server hostname
:param string domain: server domain name
:param string location: location (datacenter) name
:param string os: operating system name
:param int port_speed: Port speed in Mbps
:param list ssh_keys: list of ssh key ids
:param string post_uri: The URI of the post-install script to run
after reload
:param boolean hourly: True if using hourly pricing (default).
False for monthly.
:param boolean no_public: True if this server should only have private
interfaces
:param list extras: List of extra feature names | [
"Places",
"an",
"order",
"for",
"a",
"piece",
"of",
"hardware",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L326-L347 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager.verify_order | def verify_order(self, **kwargs):
"""Verifies an order for a piece of hardware.
See :func:`place_order` for a list of available options.
"""
create_options = self._generate_create_dict(**kwargs)
return self.client['Product_Order'].verifyOrder(create_options) | python | def verify_order(self, **kwargs):
create_options = self._generate_create_dict(**kwargs)
return self.client['Product_Order'].verifyOrder(create_options) | [
"def",
"verify_order",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"create_options",
"=",
"self",
".",
"_generate_create_dict",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"client",
"[",
"'Product_Order'",
"]",
".",
"verifyOrder",
"(",
"create_options",
")"
]
| Verifies an order for a piece of hardware.
See :func:`place_order` for a list of available options. | [
"Verifies",
"an",
"order",
"for",
"a",
"piece",
"of",
"hardware",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L349-L355 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager.get_create_options | def get_create_options(self):
"""Returns valid options for ordering hardware."""
package = self._get_package()
# Locations
locations = []
for region in package['regions']:
locations.append({
'name': region['location']['location']['longName'],
'key': region['location']['location']['name'],
})
# Sizes
sizes = []
for preset in package['activePresets'] + package['accountRestrictedActivePresets']:
sizes.append({
'name': preset['description'],
'key': preset['keyName']
})
# Operating systems
operating_systems = []
for item in package['items']:
if item['itemCategory']['categoryCode'] == 'os':
operating_systems.append({
'name': item['softwareDescription']['longDescription'],
'key': item['softwareDescription']['referenceCode'],
})
# Port speeds
port_speeds = []
for item in package['items']:
if all([item['itemCategory']['categoryCode'] == 'port_speed',
# Hide private options
not _is_private_port_speed_item(item),
# Hide unbonded options
_is_bonded(item)]):
port_speeds.append({
'name': item['description'],
'key': item['capacity'],
})
# Extras
extras = []
for item in package['items']:
if item['itemCategory']['categoryCode'] in EXTRA_CATEGORIES:
extras.append({
'name': item['description'],
'key': item['keyName']
})
return {
'locations': locations,
'sizes': sizes,
'operating_systems': operating_systems,
'port_speeds': port_speeds,
'extras': extras,
} | python | def get_create_options(self):
package = self._get_package()
locations = []
for region in package['regions']:
locations.append({
'name': region['location']['location']['longName'],
'key': region['location']['location']['name'],
})
sizes = []
for preset in package['activePresets'] + package['accountRestrictedActivePresets']:
sizes.append({
'name': preset['description'],
'key': preset['keyName']
})
operating_systems = []
for item in package['items']:
if item['itemCategory']['categoryCode'] == 'os':
operating_systems.append({
'name': item['softwareDescription']['longDescription'],
'key': item['softwareDescription']['referenceCode'],
})
port_speeds = []
for item in package['items']:
if all([item['itemCategory']['categoryCode'] == 'port_speed',
not _is_private_port_speed_item(item),
_is_bonded(item)]):
port_speeds.append({
'name': item['description'],
'key': item['capacity'],
})
extras = []
for item in package['items']:
if item['itemCategory']['categoryCode'] in EXTRA_CATEGORIES:
extras.append({
'name': item['description'],
'key': item['keyName']
})
return {
'locations': locations,
'sizes': sizes,
'operating_systems': operating_systems,
'port_speeds': port_speeds,
'extras': extras,
} | [
"def",
"get_create_options",
"(",
"self",
")",
":",
"package",
"=",
"self",
".",
"_get_package",
"(",
")",
"# Locations",
"locations",
"=",
"[",
"]",
"for",
"region",
"in",
"package",
"[",
"'regions'",
"]",
":",
"locations",
".",
"append",
"(",
"{",
"'name'",
":",
"region",
"[",
"'location'",
"]",
"[",
"'location'",
"]",
"[",
"'longName'",
"]",
",",
"'key'",
":",
"region",
"[",
"'location'",
"]",
"[",
"'location'",
"]",
"[",
"'name'",
"]",
",",
"}",
")",
"# Sizes",
"sizes",
"=",
"[",
"]",
"for",
"preset",
"in",
"package",
"[",
"'activePresets'",
"]",
"+",
"package",
"[",
"'accountRestrictedActivePresets'",
"]",
":",
"sizes",
".",
"append",
"(",
"{",
"'name'",
":",
"preset",
"[",
"'description'",
"]",
",",
"'key'",
":",
"preset",
"[",
"'keyName'",
"]",
"}",
")",
"# Operating systems",
"operating_systems",
"=",
"[",
"]",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"item",
"[",
"'itemCategory'",
"]",
"[",
"'categoryCode'",
"]",
"==",
"'os'",
":",
"operating_systems",
".",
"append",
"(",
"{",
"'name'",
":",
"item",
"[",
"'softwareDescription'",
"]",
"[",
"'longDescription'",
"]",
",",
"'key'",
":",
"item",
"[",
"'softwareDescription'",
"]",
"[",
"'referenceCode'",
"]",
",",
"}",
")",
"# Port speeds",
"port_speeds",
"=",
"[",
"]",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"all",
"(",
"[",
"item",
"[",
"'itemCategory'",
"]",
"[",
"'categoryCode'",
"]",
"==",
"'port_speed'",
",",
"# Hide private options",
"not",
"_is_private_port_speed_item",
"(",
"item",
")",
",",
"# Hide unbonded options",
"_is_bonded",
"(",
"item",
")",
"]",
")",
":",
"port_speeds",
".",
"append",
"(",
"{",
"'name'",
":",
"item",
"[",
"'description'",
"]",
",",
"'key'",
":",
"item",
"[",
"'capacity'",
"]",
",",
"}",
")",
"# Extras",
"extras",
"=",
"[",
"]",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"item",
"[",
"'itemCategory'",
"]",
"[",
"'categoryCode'",
"]",
"in",
"EXTRA_CATEGORIES",
":",
"extras",
".",
"append",
"(",
"{",
"'name'",
":",
"item",
"[",
"'description'",
"]",
",",
"'key'",
":",
"item",
"[",
"'keyName'",
"]",
"}",
")",
"return",
"{",
"'locations'",
":",
"locations",
",",
"'sizes'",
":",
"sizes",
",",
"'operating_systems'",
":",
"operating_systems",
",",
"'port_speeds'",
":",
"port_speeds",
",",
"'extras'",
":",
"extras",
",",
"}"
]
| Returns valid options for ordering hardware. | [
"Returns",
"valid",
"options",
"for",
"ordering",
"hardware",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L377-L435 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager._get_package | def _get_package(self):
"""Get the package related to simple hardware ordering."""
mask = '''
items[
keyName,
capacity,
description,
attributes[id,attributeTypeKeyName],
itemCategory[id,categoryCode],
softwareDescription[id,referenceCode,longDescription],
prices
],
activePresets,
accountRestrictedActivePresets,
regions[location[location[priceGroups]]]
'''
package_keyname = 'BARE_METAL_SERVER'
package = self.ordering_manager.get_package_by_key(package_keyname, mask=mask)
return package | python | def _get_package(self):
mask =
package_keyname = 'BARE_METAL_SERVER'
package = self.ordering_manager.get_package_by_key(package_keyname, mask=mask)
return package | [
"def",
"_get_package",
"(",
"self",
")",
":",
"mask",
"=",
"'''\n items[\n keyName,\n capacity,\n description,\n attributes[id,attributeTypeKeyName],\n itemCategory[id,categoryCode],\n softwareDescription[id,referenceCode,longDescription],\n prices\n ],\n activePresets,\n accountRestrictedActivePresets,\n regions[location[location[priceGroups]]]\n '''",
"package_keyname",
"=",
"'BARE_METAL_SERVER'",
"package",
"=",
"self",
".",
"ordering_manager",
".",
"get_package_by_key",
"(",
"package_keyname",
",",
"mask",
"=",
"mask",
")",
"return",
"package"
]
| Get the package related to simple hardware ordering. | [
"Get",
"the",
"package",
"related",
"to",
"simple",
"hardware",
"ordering",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L438-L457 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager._generate_create_dict | def _generate_create_dict(self,
size=None,
hostname=None,
domain=None,
location=None,
os=None,
port_speed=None,
ssh_keys=None,
post_uri=None,
hourly=True,
no_public=False,
extras=None):
"""Translates arguments into a dictionary for creating a server."""
extras = extras or []
package = self._get_package()
location = _get_location(package, location)
prices = []
for category in ['pri_ip_addresses',
'vpn_management',
'remote_management']:
prices.append(_get_default_price_id(package['items'],
option=category,
hourly=hourly,
location=location))
prices.append(_get_os_price_id(package['items'], os,
location=location))
prices.append(_get_bandwidth_price_id(package['items'],
hourly=hourly,
no_public=no_public,
location=location))
prices.append(_get_port_speed_price_id(package['items'],
port_speed,
no_public,
location=location))
for extra in extras:
prices.append(_get_extra_price_id(package['items'],
extra, hourly,
location=location))
hardware = {
'hostname': hostname,
'domain': domain,
}
order = {
'hardware': [hardware],
'location': location['keyname'],
'prices': [{'id': price} for price in prices],
'packageId': package['id'],
'presetId': _get_preset_id(package, size),
'useHourlyPricing': hourly,
}
if post_uri:
order['provisionScripts'] = [post_uri]
if ssh_keys:
order['sshKeys'] = [{'sshKeyIds': ssh_keys}]
return order | python | def _generate_create_dict(self,
size=None,
hostname=None,
domain=None,
location=None,
os=None,
port_speed=None,
ssh_keys=None,
post_uri=None,
hourly=True,
no_public=False,
extras=None):
extras = extras or []
package = self._get_package()
location = _get_location(package, location)
prices = []
for category in ['pri_ip_addresses',
'vpn_management',
'remote_management']:
prices.append(_get_default_price_id(package['items'],
option=category,
hourly=hourly,
location=location))
prices.append(_get_os_price_id(package['items'], os,
location=location))
prices.append(_get_bandwidth_price_id(package['items'],
hourly=hourly,
no_public=no_public,
location=location))
prices.append(_get_port_speed_price_id(package['items'],
port_speed,
no_public,
location=location))
for extra in extras:
prices.append(_get_extra_price_id(package['items'],
extra, hourly,
location=location))
hardware = {
'hostname': hostname,
'domain': domain,
}
order = {
'hardware': [hardware],
'location': location['keyname'],
'prices': [{'id': price} for price in prices],
'packageId': package['id'],
'presetId': _get_preset_id(package, size),
'useHourlyPricing': hourly,
}
if post_uri:
order['provisionScripts'] = [post_uri]
if ssh_keys:
order['sshKeys'] = [{'sshKeyIds': ssh_keys}]
return order | [
"def",
"_generate_create_dict",
"(",
"self",
",",
"size",
"=",
"None",
",",
"hostname",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"location",
"=",
"None",
",",
"os",
"=",
"None",
",",
"port_speed",
"=",
"None",
",",
"ssh_keys",
"=",
"None",
",",
"post_uri",
"=",
"None",
",",
"hourly",
"=",
"True",
",",
"no_public",
"=",
"False",
",",
"extras",
"=",
"None",
")",
":",
"extras",
"=",
"extras",
"or",
"[",
"]",
"package",
"=",
"self",
".",
"_get_package",
"(",
")",
"location",
"=",
"_get_location",
"(",
"package",
",",
"location",
")",
"prices",
"=",
"[",
"]",
"for",
"category",
"in",
"[",
"'pri_ip_addresses'",
",",
"'vpn_management'",
",",
"'remote_management'",
"]",
":",
"prices",
".",
"append",
"(",
"_get_default_price_id",
"(",
"package",
"[",
"'items'",
"]",
",",
"option",
"=",
"category",
",",
"hourly",
"=",
"hourly",
",",
"location",
"=",
"location",
")",
")",
"prices",
".",
"append",
"(",
"_get_os_price_id",
"(",
"package",
"[",
"'items'",
"]",
",",
"os",
",",
"location",
"=",
"location",
")",
")",
"prices",
".",
"append",
"(",
"_get_bandwidth_price_id",
"(",
"package",
"[",
"'items'",
"]",
",",
"hourly",
"=",
"hourly",
",",
"no_public",
"=",
"no_public",
",",
"location",
"=",
"location",
")",
")",
"prices",
".",
"append",
"(",
"_get_port_speed_price_id",
"(",
"package",
"[",
"'items'",
"]",
",",
"port_speed",
",",
"no_public",
",",
"location",
"=",
"location",
")",
")",
"for",
"extra",
"in",
"extras",
":",
"prices",
".",
"append",
"(",
"_get_extra_price_id",
"(",
"package",
"[",
"'items'",
"]",
",",
"extra",
",",
"hourly",
",",
"location",
"=",
"location",
")",
")",
"hardware",
"=",
"{",
"'hostname'",
":",
"hostname",
",",
"'domain'",
":",
"domain",
",",
"}",
"order",
"=",
"{",
"'hardware'",
":",
"[",
"hardware",
"]",
",",
"'location'",
":",
"location",
"[",
"'keyname'",
"]",
",",
"'prices'",
":",
"[",
"{",
"'id'",
":",
"price",
"}",
"for",
"price",
"in",
"prices",
"]",
",",
"'packageId'",
":",
"package",
"[",
"'id'",
"]",
",",
"'presetId'",
":",
"_get_preset_id",
"(",
"package",
",",
"size",
")",
",",
"'useHourlyPricing'",
":",
"hourly",
",",
"}",
"if",
"post_uri",
":",
"order",
"[",
"'provisionScripts'",
"]",
"=",
"[",
"post_uri",
"]",
"if",
"ssh_keys",
":",
"order",
"[",
"'sshKeys'",
"]",
"=",
"[",
"{",
"'sshKeyIds'",
":",
"ssh_keys",
"}",
"]",
"return",
"order"
]
| Translates arguments into a dictionary for creating a server. | [
"Translates",
"arguments",
"into",
"a",
"dictionary",
"for",
"creating",
"a",
"server",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L459-L523 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager._get_ids_from_hostname | def _get_ids_from_hostname(self, hostname):
"""Returns list of matching hardware IDs for a given hostname."""
results = self.list_hardware(hostname=hostname, mask="id")
return [result['id'] for result in results] | python | def _get_ids_from_hostname(self, hostname):
results = self.list_hardware(hostname=hostname, mask="id")
return [result['id'] for result in results] | [
"def",
"_get_ids_from_hostname",
"(",
"self",
",",
"hostname",
")",
":",
"results",
"=",
"self",
".",
"list_hardware",
"(",
"hostname",
"=",
"hostname",
",",
"mask",
"=",
"\"id\"",
")",
"return",
"[",
"result",
"[",
"'id'",
"]",
"for",
"result",
"in",
"results",
"]"
]
| Returns list of matching hardware IDs for a given hostname. | [
"Returns",
"list",
"of",
"matching",
"hardware",
"IDs",
"for",
"a",
"given",
"hostname",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L525-L528 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager._get_ids_from_ip | def _get_ids_from_ip(self, ip): # pylint: disable=inconsistent-return-statements
"""Returns list of matching hardware IDs for a given ip address."""
try:
# Does it look like an ip address?
socket.inet_aton(ip)
except socket.error:
return []
# Find the server via ip address. First try public ip, then private
results = self.list_hardware(public_ip=ip, mask="id")
if results:
return [result['id'] for result in results]
results = self.list_hardware(private_ip=ip, mask="id")
if results:
return [result['id'] for result in results] | python | def _get_ids_from_ip(self, ip):
try:
socket.inet_aton(ip)
except socket.error:
return []
results = self.list_hardware(public_ip=ip, mask="id")
if results:
return [result['id'] for result in results]
results = self.list_hardware(private_ip=ip, mask="id")
if results:
return [result['id'] for result in results] | [
"def",
"_get_ids_from_ip",
"(",
"self",
",",
"ip",
")",
":",
"# pylint: disable=inconsistent-return-statements",
"try",
":",
"# Does it look like an ip address?",
"socket",
".",
"inet_aton",
"(",
"ip",
")",
"except",
"socket",
".",
"error",
":",
"return",
"[",
"]",
"# Find the server via ip address. First try public ip, then private",
"results",
"=",
"self",
".",
"list_hardware",
"(",
"public_ip",
"=",
"ip",
",",
"mask",
"=",
"\"id\"",
")",
"if",
"results",
":",
"return",
"[",
"result",
"[",
"'id'",
"]",
"for",
"result",
"in",
"results",
"]",
"results",
"=",
"self",
".",
"list_hardware",
"(",
"private_ip",
"=",
"ip",
",",
"mask",
"=",
"\"id\"",
")",
"if",
"results",
":",
"return",
"[",
"result",
"[",
"'id'",
"]",
"for",
"result",
"in",
"results",
"]"
]
| Returns list of matching hardware IDs for a given ip address. | [
"Returns",
"list",
"of",
"matching",
"hardware",
"IDs",
"for",
"a",
"given",
"ip",
"address",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L530-L545 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager.edit | def edit(self, hardware_id, userdata=None, hostname=None, domain=None,
notes=None, tags=None):
"""Edit hostname, domain name, notes, user data of the hardware.
Parameters set to None will be ignored and not attempted to be updated.
:param integer hardware_id: the instance ID to edit
:param string userdata: user data on the hardware to edit.
If none exist it will be created
:param string hostname: valid hostname
:param string domain: valid domain name
:param string notes: notes about this particular hardware
:param string tags: tags to set on the hardware as a comma separated
list. Use the empty string to remove all tags.
Example::
# Change the hostname on instance 12345 to 'something'
result = mgr.edit(hardware_id=12345 , hostname="something")
#result will be True or an Exception
"""
obj = {}
if userdata:
self.hardware.setUserMetadata([userdata], id=hardware_id)
if tags is not None:
self.hardware.setTags(tags, id=hardware_id)
if hostname:
obj['hostname'] = hostname
if domain:
obj['domain'] = domain
if notes:
obj['notes'] = notes
if not obj:
return True
return self.hardware.editObject(obj, id=hardware_id) | python | def edit(self, hardware_id, userdata=None, hostname=None, domain=None,
notes=None, tags=None):
obj = {}
if userdata:
self.hardware.setUserMetadata([userdata], id=hardware_id)
if tags is not None:
self.hardware.setTags(tags, id=hardware_id)
if hostname:
obj['hostname'] = hostname
if domain:
obj['domain'] = domain
if notes:
obj['notes'] = notes
if not obj:
return True
return self.hardware.editObject(obj, id=hardware_id) | [
"def",
"edit",
"(",
"self",
",",
"hardware_id",
",",
"userdata",
"=",
"None",
",",
"hostname",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"notes",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"obj",
"=",
"{",
"}",
"if",
"userdata",
":",
"self",
".",
"hardware",
".",
"setUserMetadata",
"(",
"[",
"userdata",
"]",
",",
"id",
"=",
"hardware_id",
")",
"if",
"tags",
"is",
"not",
"None",
":",
"self",
".",
"hardware",
".",
"setTags",
"(",
"tags",
",",
"id",
"=",
"hardware_id",
")",
"if",
"hostname",
":",
"obj",
"[",
"'hostname'",
"]",
"=",
"hostname",
"if",
"domain",
":",
"obj",
"[",
"'domain'",
"]",
"=",
"domain",
"if",
"notes",
":",
"obj",
"[",
"'notes'",
"]",
"=",
"notes",
"if",
"not",
"obj",
":",
"return",
"True",
"return",
"self",
".",
"hardware",
".",
"editObject",
"(",
"obj",
",",
"id",
"=",
"hardware_id",
")"
]
| Edit hostname, domain name, notes, user data of the hardware.
Parameters set to None will be ignored and not attempted to be updated.
:param integer hardware_id: the instance ID to edit
:param string userdata: user data on the hardware to edit.
If none exist it will be created
:param string hostname: valid hostname
:param string domain: valid domain name
:param string notes: notes about this particular hardware
:param string tags: tags to set on the hardware as a comma separated
list. Use the empty string to remove all tags.
Example::
# Change the hostname on instance 12345 to 'something'
result = mgr.edit(hardware_id=12345 , hostname="something")
#result will be True or an Exception | [
"Edit",
"hostname",
"domain",
"name",
"notes",
"user",
"data",
"of",
"the",
"hardware",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L547-L588 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager.update_firmware | def update_firmware(self,
hardware_id,
ipmi=True,
raid_controller=True,
bios=True,
hard_drive=True):
"""Update hardware firmware.
This will cause the server to be unavailable for ~20 minutes.
:param int hardware_id: The ID of the hardware to have its firmware
updated.
:param bool ipmi: Update the ipmi firmware.
:param bool raid_controller: Update the raid controller firmware.
:param bool bios: Update the bios firmware.
:param bool hard_drive: Update the hard drive firmware.
Example::
# Check the servers active transactions to see progress
result = mgr.update_firmware(hardware_id=1234)
"""
return self.hardware.createFirmwareUpdateTransaction(
bool(ipmi), bool(raid_controller), bool(bios), bool(hard_drive), id=hardware_id) | python | def update_firmware(self,
hardware_id,
ipmi=True,
raid_controller=True,
bios=True,
hard_drive=True):
return self.hardware.createFirmwareUpdateTransaction(
bool(ipmi), bool(raid_controller), bool(bios), bool(hard_drive), id=hardware_id) | [
"def",
"update_firmware",
"(",
"self",
",",
"hardware_id",
",",
"ipmi",
"=",
"True",
",",
"raid_controller",
"=",
"True",
",",
"bios",
"=",
"True",
",",
"hard_drive",
"=",
"True",
")",
":",
"return",
"self",
".",
"hardware",
".",
"createFirmwareUpdateTransaction",
"(",
"bool",
"(",
"ipmi",
")",
",",
"bool",
"(",
"raid_controller",
")",
",",
"bool",
"(",
"bios",
")",
",",
"bool",
"(",
"hard_drive",
")",
",",
"id",
"=",
"hardware_id",
")"
]
| Update hardware firmware.
This will cause the server to be unavailable for ~20 minutes.
:param int hardware_id: The ID of the hardware to have its firmware
updated.
:param bool ipmi: Update the ipmi firmware.
:param bool raid_controller: Update the raid controller firmware.
:param bool bios: Update the bios firmware.
:param bool hard_drive: Update the hard drive firmware.
Example::
# Check the servers active transactions to see progress
result = mgr.update_firmware(hardware_id=1234) | [
"Update",
"hardware",
"firmware",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L590-L614 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager.reflash_firmware | def reflash_firmware(self,
hardware_id,
ipmi=True,
raid_controller=True,
bios=True):
"""Reflash hardware firmware.
This will cause the server to be unavailable for ~60 minutes.
The firmware will not be upgraded but rather reflashed to the version installed.
:param int hardware_id: The ID of the hardware to have its firmware
reflashed.
:param bool ipmi: Reflash the ipmi firmware.
:param bool raid_controller: Reflash the raid controller firmware.
:param bool bios: Reflash the bios firmware.
Example::
# Check the servers active transactions to see progress
result = mgr.reflash_firmware(hardware_id=1234)
"""
return self.hardware.createFirmwareReflashTransaction(
bool(ipmi), bool(raid_controller), bool(bios), id=hardware_id) | python | def reflash_firmware(self,
hardware_id,
ipmi=True,
raid_controller=True,
bios=True):
return self.hardware.createFirmwareReflashTransaction(
bool(ipmi), bool(raid_controller), bool(bios), id=hardware_id) | [
"def",
"reflash_firmware",
"(",
"self",
",",
"hardware_id",
",",
"ipmi",
"=",
"True",
",",
"raid_controller",
"=",
"True",
",",
"bios",
"=",
"True",
")",
":",
"return",
"self",
".",
"hardware",
".",
"createFirmwareReflashTransaction",
"(",
"bool",
"(",
"ipmi",
")",
",",
"bool",
"(",
"raid_controller",
")",
",",
"bool",
"(",
"bios",
")",
",",
"id",
"=",
"hardware_id",
")"
]
| Reflash hardware firmware.
This will cause the server to be unavailable for ~60 minutes.
The firmware will not be upgraded but rather reflashed to the version installed.
:param int hardware_id: The ID of the hardware to have its firmware
reflashed.
:param bool ipmi: Reflash the ipmi firmware.
:param bool raid_controller: Reflash the raid controller firmware.
:param bool bios: Reflash the bios firmware.
Example::
# Check the servers active transactions to see progress
result = mgr.reflash_firmware(hardware_id=1234) | [
"Reflash",
"hardware",
"firmware",
"."
]
| train | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L616-L639 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.