id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
1,400 | softlayer/softlayer-python | SoftLayer/managers/dns.py | DNSManager.create_record_ptr | def create_record_ptr(self, record, data, ttl=60):
"""Create a reverse record.
:param record: the public ip address of device for which you would like to manage reverse DNS.
:param data: the record's value
:param integer ttl: the TTL or time-to-live value (default: 60)
"""
resource_record = self._generate_create_dict(record, 'PTR', data, ttl)
return self.record.createObject(resource_record) | python | def create_record_ptr(self, record, data, ttl=60):
"""Create a reverse record.
:param record: the public ip address of device for which you would like to manage reverse DNS.
:param data: the record's value
:param integer ttl: the TTL or time-to-live value (default: 60)
"""
resource_record = self._generate_create_dict(record, 'PTR', data, ttl)
return self.record.createObject(resource_record) | [
"def",
"create_record_ptr",
"(",
"self",
",",
"record",
",",
"data",
",",
"ttl",
"=",
"60",
")",
":",
"resource_record",
"=",
"self",
".",
"_generate_create_dict",
"(",
"record",
",",
"'PTR'",
",",
"data",
",",
"ttl",
")",
"return",
"self",
".",
"record",
".",
"createObject",
"(",
"resource_record",
")"
] | Create a reverse record.
:param record: the public ip address of device for which you would like to manage reverse DNS.
:param data: the record's value
:param integer ttl: the TTL or time-to-live value (default: 60) | [
"Create",
"a",
"reverse",
"record",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dns.py#L139-L149 |
1,401 | softlayer/softlayer-python | SoftLayer/managers/dns.py | DNSManager.get_records | def get_records(self, zone_id, ttl=None, data=None, host=None,
record_type=None):
"""List, and optionally filter, records within a zone.
:param zone: the zone name in which to search.
:param int ttl: time in seconds
:param str data: the records data
:param str host: record's host
:param str record_type: the type of record
:returns: A list of dictionaries representing the matching records
within the specified zone.
"""
_filter = utils.NestedDict()
if ttl:
_filter['resourceRecords']['ttl'] = utils.query_filter(ttl)
if host:
_filter['resourceRecords']['host'] = utils.query_filter(host)
if data:
_filter['resourceRecords']['data'] = utils.query_filter(data)
if record_type:
_filter['resourceRecords']['type'] = utils.query_filter(
record_type.lower())
results = self.service.getResourceRecords(
id=zone_id,
mask='id,expire,domainId,host,minimum,refresh,retry,'
'mxPriority,ttl,type,data,responsiblePerson',
filter=_filter.to_dict(),
)
return results | python | def get_records(self, zone_id, ttl=None, data=None, host=None,
record_type=None):
"""List, and optionally filter, records within a zone.
:param zone: the zone name in which to search.
:param int ttl: time in seconds
:param str data: the records data
:param str host: record's host
:param str record_type: the type of record
:returns: A list of dictionaries representing the matching records
within the specified zone.
"""
_filter = utils.NestedDict()
if ttl:
_filter['resourceRecords']['ttl'] = utils.query_filter(ttl)
if host:
_filter['resourceRecords']['host'] = utils.query_filter(host)
if data:
_filter['resourceRecords']['data'] = utils.query_filter(data)
if record_type:
_filter['resourceRecords']['type'] = utils.query_filter(
record_type.lower())
results = self.service.getResourceRecords(
id=zone_id,
mask='id,expire,domainId,host,minimum,refresh,retry,'
'mxPriority,ttl,type,data,responsiblePerson',
filter=_filter.to_dict(),
)
return results | [
"def",
"get_records",
"(",
"self",
",",
"zone_id",
",",
"ttl",
"=",
"None",
",",
"data",
"=",
"None",
",",
"host",
"=",
"None",
",",
"record_type",
"=",
"None",
")",
":",
"_filter",
"=",
"utils",
".",
"NestedDict",
"(",
")",
"if",
"ttl",
":",
"_filter",
"[",
"'resourceRecords'",
"]",
"[",
"'ttl'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"ttl",
")",
"if",
"host",
":",
"_filter",
"[",
"'resourceRecords'",
"]",
"[",
"'host'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"host",
")",
"if",
"data",
":",
"_filter",
"[",
"'resourceRecords'",
"]",
"[",
"'data'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"data",
")",
"if",
"record_type",
":",
"_filter",
"[",
"'resourceRecords'",
"]",
"[",
"'type'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"record_type",
".",
"lower",
"(",
")",
")",
"results",
"=",
"self",
".",
"service",
".",
"getResourceRecords",
"(",
"id",
"=",
"zone_id",
",",
"mask",
"=",
"'id,expire,domainId,host,minimum,refresh,retry,'",
"'mxPriority,ttl,type,data,responsiblePerson'",
",",
"filter",
"=",
"_filter",
".",
"to_dict",
"(",
")",
",",
")",
"return",
"results"
] | List, and optionally filter, records within a zone.
:param zone: the zone name in which to search.
:param int ttl: time in seconds
:param str data: the records data
:param str host: record's host
:param str record_type: the type of record
:returns: A list of dictionaries representing the matching records
within the specified zone. | [
"List",
"and",
"optionally",
"filter",
"records",
"within",
"a",
"zone",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dns.py#L183-L218 |
1,402 | softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager.cancel_guests | def cancel_guests(self, host_id):
"""Cancel all guests into the dedicated host immediately.
To cancel an specified guest use the method VSManager.cancel_instance()
:param host_id: The ID of the dedicated host.
:return: The id, fqdn and status of all guests into a dictionary. The status
could be 'Cancelled' or an exception message, The dictionary is empty
if there isn't any guest in the dedicated host.
Example::
# Cancel guests of dedicated host id 12345
result = mgr.cancel_guests(12345)
"""
result = []
guests = self.host.getGuests(id=host_id, mask='id,fullyQualifiedDomainName')
if guests:
for vs in guests:
status_info = {
'id': vs['id'],
'fqdn': vs['fullyQualifiedDomainName'],
'status': self._delete_guest(vs['id'])
}
result.append(status_info)
return result | python | def cancel_guests(self, host_id):
"""Cancel all guests into the dedicated host immediately.
To cancel an specified guest use the method VSManager.cancel_instance()
:param host_id: The ID of the dedicated host.
:return: The id, fqdn and status of all guests into a dictionary. The status
could be 'Cancelled' or an exception message, The dictionary is empty
if there isn't any guest in the dedicated host.
Example::
# Cancel guests of dedicated host id 12345
result = mgr.cancel_guests(12345)
"""
result = []
guests = self.host.getGuests(id=host_id, mask='id,fullyQualifiedDomainName')
if guests:
for vs in guests:
status_info = {
'id': vs['id'],
'fqdn': vs['fullyQualifiedDomainName'],
'status': self._delete_guest(vs['id'])
}
result.append(status_info)
return result | [
"def",
"cancel_guests",
"(",
"self",
",",
"host_id",
")",
":",
"result",
"=",
"[",
"]",
"guests",
"=",
"self",
".",
"host",
".",
"getGuests",
"(",
"id",
"=",
"host_id",
",",
"mask",
"=",
"'id,fullyQualifiedDomainName'",
")",
"if",
"guests",
":",
"for",
"vs",
"in",
"guests",
":",
"status_info",
"=",
"{",
"'id'",
":",
"vs",
"[",
"'id'",
"]",
",",
"'fqdn'",
":",
"vs",
"[",
"'fullyQualifiedDomainName'",
"]",
",",
"'status'",
":",
"self",
".",
"_delete_guest",
"(",
"vs",
"[",
"'id'",
"]",
")",
"}",
"result",
".",
"append",
"(",
"status_info",
")",
"return",
"result"
] | Cancel all guests into the dedicated host immediately.
To cancel an specified guest use the method VSManager.cancel_instance()
:param host_id: The ID of the dedicated host.
:return: The id, fqdn and status of all guests into a dictionary. The status
could be 'Cancelled' or an exception message, The dictionary is empty
if there isn't any guest in the dedicated host.
Example::
# Cancel guests of dedicated host id 12345
result = mgr.cancel_guests(12345) | [
"Cancel",
"all",
"guests",
"into",
"the",
"dedicated",
"host",
"immediately",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L54-L81 |
1,403 | softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager.list_guests | def list_guests(self, host_id, tags=None, cpus=None, memory=None, hostname=None,
domain=None, local_disk=None, nic_speed=None, public_ip=None,
private_ip=None, **kwargs):
"""Retrieve a list of all virtual servers on the dedicated host.
Example::
# Print out a list of instances with 4 cpu cores in the host id 12345.
for vsi in mgr.list_guests(host_id=12345, cpus=4):
print vsi['fullyQualifiedDomainName'], vsi['primaryIpAddress']
# Using a custom object-mask. Will get ONLY what is specified
object_mask = "mask[hostname,monitoringRobot[robotStatus]]"
for vsi in mgr.list_guests(mask=object_mask,cpus=4):
print vsi
:param integer host_id: the identifier of dedicated host
:param list tags: filter based on list of tags
:param integer cpus: filter based on number of CPUS
:param integer memory: filter based on amount of memory
:param string hostname: filter based on hostname
:param string domain: filter based on domain
:param string local_disk: filter based on local_disk
:param integer nic_speed: filter based on network speed (in MBPS)
:param string public_ip: filter based on public ip address
:param string private_ip: filter based on private ip address
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
:returns: Returns a list of dictionaries representing the matching
virtual servers
"""
if 'mask' not in kwargs:
items = [
'id',
'globalIdentifier',
'hostname',
'domain',
'fullyQualifiedDomainName',
'primaryBackendIpAddress',
'primaryIpAddress',
'lastKnownPowerState.name',
'hourlyBillingFlag',
'powerState',
'maxCpu',
'maxMemory',
'datacenter',
'activeTransaction.transactionStatus[friendlyName,name]',
'status',
]
kwargs['mask'] = "mask[%s]" % ','.join(items)
_filter = utils.NestedDict(kwargs.get('filter') or {})
if tags:
_filter['guests']['tagReferences']['tag']['name'] = {
'operation': 'in',
'options': [{'name': 'data', 'value': tags}],
}
if cpus:
_filter['guests']['maxCpu'] = utils.query_filter(cpus)
if memory:
_filter['guests']['maxMemory'] = utils.query_filter(memory)
if hostname:
_filter['guests']['hostname'] = utils.query_filter(hostname)
if domain:
_filter['guests']['domain'] = utils.query_filter(domain)
if local_disk is not None:
_filter['guests']['localDiskFlag'] = (
utils.query_filter(bool(local_disk)))
if nic_speed:
_filter['guests']['networkComponents']['maxSpeed'] = (
utils.query_filter(nic_speed))
if public_ip:
_filter['guests']['primaryIpAddress'] = (
utils.query_filter(public_ip))
if private_ip:
_filter['guests']['primaryBackendIpAddress'] = (
utils.query_filter(private_ip))
kwargs['filter'] = _filter.to_dict()
kwargs['iter'] = True
return self.host.getGuests(id=host_id, **kwargs) | python | def list_guests(self, host_id, tags=None, cpus=None, memory=None, hostname=None,
domain=None, local_disk=None, nic_speed=None, public_ip=None,
private_ip=None, **kwargs):
"""Retrieve a list of all virtual servers on the dedicated host.
Example::
# Print out a list of instances with 4 cpu cores in the host id 12345.
for vsi in mgr.list_guests(host_id=12345, cpus=4):
print vsi['fullyQualifiedDomainName'], vsi['primaryIpAddress']
# Using a custom object-mask. Will get ONLY what is specified
object_mask = "mask[hostname,monitoringRobot[robotStatus]]"
for vsi in mgr.list_guests(mask=object_mask,cpus=4):
print vsi
:param integer host_id: the identifier of dedicated host
:param list tags: filter based on list of tags
:param integer cpus: filter based on number of CPUS
:param integer memory: filter based on amount of memory
:param string hostname: filter based on hostname
:param string domain: filter based on domain
:param string local_disk: filter based on local_disk
:param integer nic_speed: filter based on network speed (in MBPS)
:param string public_ip: filter based on public ip address
:param string private_ip: filter based on private ip address
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
:returns: Returns a list of dictionaries representing the matching
virtual servers
"""
if 'mask' not in kwargs:
items = [
'id',
'globalIdentifier',
'hostname',
'domain',
'fullyQualifiedDomainName',
'primaryBackendIpAddress',
'primaryIpAddress',
'lastKnownPowerState.name',
'hourlyBillingFlag',
'powerState',
'maxCpu',
'maxMemory',
'datacenter',
'activeTransaction.transactionStatus[friendlyName,name]',
'status',
]
kwargs['mask'] = "mask[%s]" % ','.join(items)
_filter = utils.NestedDict(kwargs.get('filter') or {})
if tags:
_filter['guests']['tagReferences']['tag']['name'] = {
'operation': 'in',
'options': [{'name': 'data', 'value': tags}],
}
if cpus:
_filter['guests']['maxCpu'] = utils.query_filter(cpus)
if memory:
_filter['guests']['maxMemory'] = utils.query_filter(memory)
if hostname:
_filter['guests']['hostname'] = utils.query_filter(hostname)
if domain:
_filter['guests']['domain'] = utils.query_filter(domain)
if local_disk is not None:
_filter['guests']['localDiskFlag'] = (
utils.query_filter(bool(local_disk)))
if nic_speed:
_filter['guests']['networkComponents']['maxSpeed'] = (
utils.query_filter(nic_speed))
if public_ip:
_filter['guests']['primaryIpAddress'] = (
utils.query_filter(public_ip))
if private_ip:
_filter['guests']['primaryBackendIpAddress'] = (
utils.query_filter(private_ip))
kwargs['filter'] = _filter.to_dict()
kwargs['iter'] = True
return self.host.getGuests(id=host_id, **kwargs) | [
"def",
"list_guests",
"(",
"self",
",",
"host_id",
",",
"tags",
"=",
"None",
",",
"cpus",
"=",
"None",
",",
"memory",
"=",
"None",
",",
"hostname",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"local_disk",
"=",
"None",
",",
"nic_speed",
"=",
"None",
",",
"public_ip",
"=",
"None",
",",
"private_ip",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"items",
"=",
"[",
"'id'",
",",
"'globalIdentifier'",
",",
"'hostname'",
",",
"'domain'",
",",
"'fullyQualifiedDomainName'",
",",
"'primaryBackendIpAddress'",
",",
"'primaryIpAddress'",
",",
"'lastKnownPowerState.name'",
",",
"'hourlyBillingFlag'",
",",
"'powerState'",
",",
"'maxCpu'",
",",
"'maxMemory'",
",",
"'datacenter'",
",",
"'activeTransaction.transactionStatus[friendlyName,name]'",
",",
"'status'",
",",
"]",
"kwargs",
"[",
"'mask'",
"]",
"=",
"\"mask[%s]\"",
"%",
"','",
".",
"join",
"(",
"items",
")",
"_filter",
"=",
"utils",
".",
"NestedDict",
"(",
"kwargs",
".",
"get",
"(",
"'filter'",
")",
"or",
"{",
"}",
")",
"if",
"tags",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'tagReferences'",
"]",
"[",
"'tag'",
"]",
"[",
"'name'",
"]",
"=",
"{",
"'operation'",
":",
"'in'",
",",
"'options'",
":",
"[",
"{",
"'name'",
":",
"'data'",
",",
"'value'",
":",
"tags",
"}",
"]",
",",
"}",
"if",
"cpus",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'maxCpu'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"cpus",
")",
"if",
"memory",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'maxMemory'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"memory",
")",
"if",
"hostname",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'hostname'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"hostname",
")",
"if",
"domain",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'domain'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"domain",
")",
"if",
"local_disk",
"is",
"not",
"None",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'localDiskFlag'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"bool",
"(",
"local_disk",
")",
")",
")",
"if",
"nic_speed",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'networkComponents'",
"]",
"[",
"'maxSpeed'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"nic_speed",
")",
")",
"if",
"public_ip",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'primaryIpAddress'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"public_ip",
")",
")",
"if",
"private_ip",
":",
"_filter",
"[",
"'guests'",
"]",
"[",
"'primaryBackendIpAddress'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"private_ip",
")",
")",
"kwargs",
"[",
"'filter'",
"]",
"=",
"_filter",
".",
"to_dict",
"(",
")",
"kwargs",
"[",
"'iter'",
"]",
"=",
"True",
"return",
"self",
".",
"host",
".",
"getGuests",
"(",
"id",
"=",
"host_id",
",",
"*",
"*",
"kwargs",
")"
] | Retrieve a list of all virtual servers on the dedicated host.
Example::
# Print out a list of instances with 4 cpu cores in the host id 12345.
for vsi in mgr.list_guests(host_id=12345, cpus=4):
print vsi['fullyQualifiedDomainName'], vsi['primaryIpAddress']
# Using a custom object-mask. Will get ONLY what is specified
object_mask = "mask[hostname,monitoringRobot[robotStatus]]"
for vsi in mgr.list_guests(mask=object_mask,cpus=4):
print vsi
:param integer host_id: the identifier of dedicated host
:param list tags: filter based on list of tags
:param integer cpus: filter based on number of CPUS
:param integer memory: filter based on amount of memory
:param string hostname: filter based on hostname
:param string domain: filter based on domain
:param string local_disk: filter based on local_disk
:param integer nic_speed: filter based on network speed (in MBPS)
:param string public_ip: filter based on public ip address
:param string private_ip: filter based on private ip address
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
:returns: Returns a list of dictionaries representing the matching
virtual servers | [
"Retrieve",
"a",
"list",
"of",
"all",
"virtual",
"servers",
"on",
"the",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L83-L172 |
1,404 | softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager.list_instances | def list_instances(self, tags=None, cpus=None, memory=None, hostname=None,
disk=None, datacenter=None, **kwargs):
"""Retrieve a list of all dedicated hosts on the account
:param list tags: filter based on list of tags
:param integer cpus: filter based on number of CPUS
:param integer memory: filter based on amount of memory
:param string hostname: filter based on hostname
:param string disk: filter based on disk
:param string datacenter: filter based on datacenter
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
:returns: Returns a list of dictionaries representing the matching dedicated host.
"""
if 'mask' not in kwargs:
items = [
'id',
'name',
'cpuCount',
'diskCapacity',
'memoryCapacity',
'datacenter',
'guestCount',
]
kwargs['mask'] = "mask[%s]" % ','.join(items)
_filter = utils.NestedDict(kwargs.get('filter') or {})
if tags:
_filter['dedicatedHosts']['tagReferences']['tag']['name'] = {
'operation': 'in',
'options': [{'name': 'data', 'value': tags}],
}
if hostname:
_filter['dedicatedHosts']['name'] = (
utils.query_filter(hostname)
)
if cpus:
_filter['dedicatedHosts']['cpuCount'] = utils.query_filter(cpus)
if disk:
_filter['dedicatedHosts']['diskCapacity'] = (
utils.query_filter(disk))
if memory:
_filter['dedicatedHosts']['memoryCapacity'] = (
utils.query_filter(memory))
if datacenter:
_filter['dedicatedHosts']['datacenter']['name'] = (
utils.query_filter(datacenter))
kwargs['filter'] = _filter.to_dict()
return self.account.getDedicatedHosts(**kwargs) | python | def list_instances(self, tags=None, cpus=None, memory=None, hostname=None,
disk=None, datacenter=None, **kwargs):
"""Retrieve a list of all dedicated hosts on the account
:param list tags: filter based on list of tags
:param integer cpus: filter based on number of CPUS
:param integer memory: filter based on amount of memory
:param string hostname: filter based on hostname
:param string disk: filter based on disk
:param string datacenter: filter based on datacenter
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
:returns: Returns a list of dictionaries representing the matching dedicated host.
"""
if 'mask' not in kwargs:
items = [
'id',
'name',
'cpuCount',
'diskCapacity',
'memoryCapacity',
'datacenter',
'guestCount',
]
kwargs['mask'] = "mask[%s]" % ','.join(items)
_filter = utils.NestedDict(kwargs.get('filter') or {})
if tags:
_filter['dedicatedHosts']['tagReferences']['tag']['name'] = {
'operation': 'in',
'options': [{'name': 'data', 'value': tags}],
}
if hostname:
_filter['dedicatedHosts']['name'] = (
utils.query_filter(hostname)
)
if cpus:
_filter['dedicatedHosts']['cpuCount'] = utils.query_filter(cpus)
if disk:
_filter['dedicatedHosts']['diskCapacity'] = (
utils.query_filter(disk))
if memory:
_filter['dedicatedHosts']['memoryCapacity'] = (
utils.query_filter(memory))
if datacenter:
_filter['dedicatedHosts']['datacenter']['name'] = (
utils.query_filter(datacenter))
kwargs['filter'] = _filter.to_dict()
return self.account.getDedicatedHosts(**kwargs) | [
"def",
"list_instances",
"(",
"self",
",",
"tags",
"=",
"None",
",",
"cpus",
"=",
"None",
",",
"memory",
"=",
"None",
",",
"hostname",
"=",
"None",
",",
"disk",
"=",
"None",
",",
"datacenter",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"items",
"=",
"[",
"'id'",
",",
"'name'",
",",
"'cpuCount'",
",",
"'diskCapacity'",
",",
"'memoryCapacity'",
",",
"'datacenter'",
",",
"'guestCount'",
",",
"]",
"kwargs",
"[",
"'mask'",
"]",
"=",
"\"mask[%s]\"",
"%",
"','",
".",
"join",
"(",
"items",
")",
"_filter",
"=",
"utils",
".",
"NestedDict",
"(",
"kwargs",
".",
"get",
"(",
"'filter'",
")",
"or",
"{",
"}",
")",
"if",
"tags",
":",
"_filter",
"[",
"'dedicatedHosts'",
"]",
"[",
"'tagReferences'",
"]",
"[",
"'tag'",
"]",
"[",
"'name'",
"]",
"=",
"{",
"'operation'",
":",
"'in'",
",",
"'options'",
":",
"[",
"{",
"'name'",
":",
"'data'",
",",
"'value'",
":",
"tags",
"}",
"]",
",",
"}",
"if",
"hostname",
":",
"_filter",
"[",
"'dedicatedHosts'",
"]",
"[",
"'name'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"hostname",
")",
")",
"if",
"cpus",
":",
"_filter",
"[",
"'dedicatedHosts'",
"]",
"[",
"'cpuCount'",
"]",
"=",
"utils",
".",
"query_filter",
"(",
"cpus",
")",
"if",
"disk",
":",
"_filter",
"[",
"'dedicatedHosts'",
"]",
"[",
"'diskCapacity'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"disk",
")",
")",
"if",
"memory",
":",
"_filter",
"[",
"'dedicatedHosts'",
"]",
"[",
"'memoryCapacity'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"memory",
")",
")",
"if",
"datacenter",
":",
"_filter",
"[",
"'dedicatedHosts'",
"]",
"[",
"'datacenter'",
"]",
"[",
"'name'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"datacenter",
")",
")",
"kwargs",
"[",
"'filter'",
"]",
"=",
"_filter",
".",
"to_dict",
"(",
")",
"return",
"self",
".",
"account",
".",
"getDedicatedHosts",
"(",
"*",
"*",
"kwargs",
")"
] | Retrieve a list of all dedicated hosts on the account
:param list tags: filter based on list of tags
:param integer cpus: filter based on number of CPUS
:param integer memory: filter based on amount of memory
:param string hostname: filter based on hostname
:param string disk: filter based on disk
:param string datacenter: filter based on datacenter
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
:returns: Returns a list of dictionaries representing the matching dedicated host. | [
"Retrieve",
"a",
"list",
"of",
"all",
"dedicated",
"hosts",
"on",
"the",
"account"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L174-L228 |
1,405 | softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager.get_host | def get_host(self, host_id, **kwargs):
"""Get details about a dedicated host.
:param integer : the host ID
:returns: A dictionary containing host information.
Example::
# Print out host ID 12345.
dh = mgr.get_host(12345)
print dh
# Print out only name and backendRouter for instance 12345
object_mask = "mask[name,backendRouter[id]]"
dh = mgr.get_host(12345, mask=mask)
print dh
"""
if 'mask' not in kwargs:
kwargs['mask'] = ('''
id,
name,
cpuCount,
memoryCapacity,
diskCapacity,
createDate,
modifyDate,
backendRouter[
id,
hostname,
domain
],
billingItem[
id,
nextInvoiceTotalRecurringAmount,
children[
categoryCode,
nextInvoiceTotalRecurringAmount
],
orderItem[
id,
order.userRecord[
username
]
]
],
datacenter[
id,
name,
longName
],
guests[
id,
hostname,
domain,
uuid
],
guestCount
''')
return self.host.getObject(id=host_id, **kwargs) | python | def get_host(self, host_id, **kwargs):
"""Get details about a dedicated host.
:param integer : the host ID
:returns: A dictionary containing host information.
Example::
# Print out host ID 12345.
dh = mgr.get_host(12345)
print dh
# Print out only name and backendRouter for instance 12345
object_mask = "mask[name,backendRouter[id]]"
dh = mgr.get_host(12345, mask=mask)
print dh
"""
if 'mask' not in kwargs:
kwargs['mask'] = ('''
id,
name,
cpuCount,
memoryCapacity,
diskCapacity,
createDate,
modifyDate,
backendRouter[
id,
hostname,
domain
],
billingItem[
id,
nextInvoiceTotalRecurringAmount,
children[
categoryCode,
nextInvoiceTotalRecurringAmount
],
orderItem[
id,
order.userRecord[
username
]
]
],
datacenter[
id,
name,
longName
],
guests[
id,
hostname,
domain,
uuid
],
guestCount
''')
return self.host.getObject(id=host_id, **kwargs) | [
"def",
"get_host",
"(",
"self",
",",
"host_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'mask'",
"]",
"=",
"(",
"'''\n id,\n name,\n cpuCount,\n memoryCapacity,\n diskCapacity,\n createDate,\n modifyDate,\n backendRouter[\n id,\n hostname,\n domain\n ],\n billingItem[\n id,\n nextInvoiceTotalRecurringAmount,\n children[\n categoryCode,\n nextInvoiceTotalRecurringAmount\n ],\n orderItem[\n id,\n order.userRecord[\n username\n ]\n ]\n ],\n datacenter[\n id,\n name,\n longName\n ],\n guests[\n id,\n hostname,\n domain,\n uuid\n ],\n guestCount\n '''",
")",
"return",
"self",
".",
"host",
".",
"getObject",
"(",
"id",
"=",
"host_id",
",",
"*",
"*",
"kwargs",
")"
] | Get details about a dedicated host.
:param integer : the host ID
:returns: A dictionary containing host information.
Example::
# Print out host ID 12345.
dh = mgr.get_host(12345)
print dh
# Print out only name and backendRouter for instance 12345
object_mask = "mask[name,backendRouter[id]]"
dh = mgr.get_host(12345, mask=mask)
print dh | [
"Get",
"details",
"about",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L230-L290 |
1,406 | softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager.place_order | def place_order(self, hostname, domain, location, flavor, hourly, router=None):
"""Places an order for a dedicated host.
See get_create_options() for valid arguments.
:param string hostname: server hostname
:param string domain: server domain name
:param string location: location (datacenter) name
:param boolean hourly: True if using hourly pricing (default).
False for monthly.
:param int router: an optional value for selecting a backend router
"""
create_options = self._generate_create_dict(hostname=hostname,
router=router,
domain=domain,
flavor=flavor,
datacenter=location,
hourly=hourly)
return self.client['Product_Order'].placeOrder(create_options) | python | def place_order(self, hostname, domain, location, flavor, hourly, router=None):
"""Places an order for a dedicated host.
See get_create_options() for valid arguments.
:param string hostname: server hostname
:param string domain: server domain name
:param string location: location (datacenter) name
:param boolean hourly: True if using hourly pricing (default).
False for monthly.
:param int router: an optional value for selecting a backend router
"""
create_options = self._generate_create_dict(hostname=hostname,
router=router,
domain=domain,
flavor=flavor,
datacenter=location,
hourly=hourly)
return self.client['Product_Order'].placeOrder(create_options) | [
"def",
"place_order",
"(",
"self",
",",
"hostname",
",",
"domain",
",",
"location",
",",
"flavor",
",",
"hourly",
",",
"router",
"=",
"None",
")",
":",
"create_options",
"=",
"self",
".",
"_generate_create_dict",
"(",
"hostname",
"=",
"hostname",
",",
"router",
"=",
"router",
",",
"domain",
"=",
"domain",
",",
"flavor",
"=",
"flavor",
",",
"datacenter",
"=",
"location",
",",
"hourly",
"=",
"hourly",
")",
"return",
"self",
".",
"client",
"[",
"'Product_Order'",
"]",
".",
"placeOrder",
"(",
"create_options",
")"
] | Places an order for a dedicated host.
See get_create_options() for valid arguments.
:param string hostname: server hostname
:param string domain: server domain name
:param string location: location (datacenter) name
:param boolean hourly: True if using hourly pricing (default).
False for monthly.
:param int router: an optional value for selecting a backend router | [
"Places",
"an",
"order",
"for",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L292-L311 |
1,407 | softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager.verify_order | def verify_order(self, hostname, domain, location, hourly, flavor, router=None):
"""Verifies an order for a dedicated host.
See :func:`place_order` for a list of available options.
"""
create_options = self._generate_create_dict(hostname=hostname,
router=router,
domain=domain,
flavor=flavor,
datacenter=location,
hourly=hourly)
return self.client['Product_Order'].verifyOrder(create_options) | python | def verify_order(self, hostname, domain, location, hourly, flavor, router=None):
"""Verifies an order for a dedicated host.
See :func:`place_order` for a list of available options.
"""
create_options = self._generate_create_dict(hostname=hostname,
router=router,
domain=domain,
flavor=flavor,
datacenter=location,
hourly=hourly)
return self.client['Product_Order'].verifyOrder(create_options) | [
"def",
"verify_order",
"(",
"self",
",",
"hostname",
",",
"domain",
",",
"location",
",",
"hourly",
",",
"flavor",
",",
"router",
"=",
"None",
")",
":",
"create_options",
"=",
"self",
".",
"_generate_create_dict",
"(",
"hostname",
"=",
"hostname",
",",
"router",
"=",
"router",
",",
"domain",
"=",
"domain",
",",
"flavor",
"=",
"flavor",
",",
"datacenter",
"=",
"location",
",",
"hourly",
"=",
"hourly",
")",
"return",
"self",
".",
"client",
"[",
"'Product_Order'",
"]",
".",
"verifyOrder",
"(",
"create_options",
")"
] | Verifies an order for a dedicated host.
See :func:`place_order` for a list of available options. | [
"Verifies",
"an",
"order",
"for",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L313-L326 |
1,408 | softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager._generate_create_dict | def _generate_create_dict(self,
hostname=None,
domain=None,
flavor=None,
router=None,
datacenter=None,
hourly=True):
"""Translates args into a dictionary for creating a dedicated host."""
package = self._get_package()
item = self._get_item(package, flavor)
location = self._get_location(package['regions'], datacenter)
price = self._get_price(item)
routers = self._get_backend_router(
location['location']['locationPackageDetails'], item)
router = self._get_default_router(routers, router)
hardware = {
'hostname': hostname,
'domain': domain,
'primaryBackendNetworkComponent': {
'router': {
'id': router
}
}
}
complex_type = "SoftLayer_Container_Product_Order_Virtual_DedicatedHost"
order = {
"complexType": complex_type,
"quantity": 1,
'location': location['keyname'],
'packageId': package['id'],
'prices': [{'id': price}],
'hardware': [hardware],
'useHourlyPricing': hourly,
}
return order | python | def _generate_create_dict(self,
hostname=None,
domain=None,
flavor=None,
router=None,
datacenter=None,
hourly=True):
"""Translates args into a dictionary for creating a dedicated host."""
package = self._get_package()
item = self._get_item(package, flavor)
location = self._get_location(package['regions'], datacenter)
price = self._get_price(item)
routers = self._get_backend_router(
location['location']['locationPackageDetails'], item)
router = self._get_default_router(routers, router)
hardware = {
'hostname': hostname,
'domain': domain,
'primaryBackendNetworkComponent': {
'router': {
'id': router
}
}
}
complex_type = "SoftLayer_Container_Product_Order_Virtual_DedicatedHost"
order = {
"complexType": complex_type,
"quantity": 1,
'location': location['keyname'],
'packageId': package['id'],
'prices': [{'id': price}],
'hardware': [hardware],
'useHourlyPricing': hourly,
}
return order | [
"def",
"_generate_create_dict",
"(",
"self",
",",
"hostname",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"flavor",
"=",
"None",
",",
"router",
"=",
"None",
",",
"datacenter",
"=",
"None",
",",
"hourly",
"=",
"True",
")",
":",
"package",
"=",
"self",
".",
"_get_package",
"(",
")",
"item",
"=",
"self",
".",
"_get_item",
"(",
"package",
",",
"flavor",
")",
"location",
"=",
"self",
".",
"_get_location",
"(",
"package",
"[",
"'regions'",
"]",
",",
"datacenter",
")",
"price",
"=",
"self",
".",
"_get_price",
"(",
"item",
")",
"routers",
"=",
"self",
".",
"_get_backend_router",
"(",
"location",
"[",
"'location'",
"]",
"[",
"'locationPackageDetails'",
"]",
",",
"item",
")",
"router",
"=",
"self",
".",
"_get_default_router",
"(",
"routers",
",",
"router",
")",
"hardware",
"=",
"{",
"'hostname'",
":",
"hostname",
",",
"'domain'",
":",
"domain",
",",
"'primaryBackendNetworkComponent'",
":",
"{",
"'router'",
":",
"{",
"'id'",
":",
"router",
"}",
"}",
"}",
"complex_type",
"=",
"\"SoftLayer_Container_Product_Order_Virtual_DedicatedHost\"",
"order",
"=",
"{",
"\"complexType\"",
":",
"complex_type",
",",
"\"quantity\"",
":",
"1",
",",
"'location'",
":",
"location",
"[",
"'keyname'",
"]",
",",
"'packageId'",
":",
"package",
"[",
"'id'",
"]",
",",
"'prices'",
":",
"[",
"{",
"'id'",
":",
"price",
"}",
"]",
",",
"'hardware'",
":",
"[",
"hardware",
"]",
",",
"'useHourlyPricing'",
":",
"hourly",
",",
"}",
"return",
"order"
] | Translates args into a dictionary for creating a dedicated host. | [
"Translates",
"args",
"into",
"a",
"dictionary",
"for",
"creating",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L328-L368 |
1,409 | softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager.get_create_options | def get_create_options(self):
"""Returns valid options for ordering a dedicated host."""
package = self._get_package()
# Locations
locations = []
for region in package['regions']:
locations.append({
'name': region['location']['location']['longName'],
'key': region['location']['location']['name'],
})
# flavors
dedicated_host = []
for item in package['items']:
if item['itemCategory']['categoryCode'] == \
'dedicated_virtual_hosts':
dedicated_host.append({
'name': item['description'],
'key': item['keyName'],
})
return {'locations': locations, 'dedicated_host': dedicated_host} | python | def get_create_options(self):
"""Returns valid options for ordering a dedicated host."""
package = self._get_package()
# Locations
locations = []
for region in package['regions']:
locations.append({
'name': region['location']['location']['longName'],
'key': region['location']['location']['name'],
})
# flavors
dedicated_host = []
for item in package['items']:
if item['itemCategory']['categoryCode'] == \
'dedicated_virtual_hosts':
dedicated_host.append({
'name': item['description'],
'key': item['keyName'],
})
return {'locations': locations, 'dedicated_host': dedicated_host} | [
"def",
"get_create_options",
"(",
"self",
")",
":",
"package",
"=",
"self",
".",
"_get_package",
"(",
")",
"# Locations",
"locations",
"=",
"[",
"]",
"for",
"region",
"in",
"package",
"[",
"'regions'",
"]",
":",
"locations",
".",
"append",
"(",
"{",
"'name'",
":",
"region",
"[",
"'location'",
"]",
"[",
"'location'",
"]",
"[",
"'longName'",
"]",
",",
"'key'",
":",
"region",
"[",
"'location'",
"]",
"[",
"'location'",
"]",
"[",
"'name'",
"]",
",",
"}",
")",
"# flavors",
"dedicated_host",
"=",
"[",
"]",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"item",
"[",
"'itemCategory'",
"]",
"[",
"'categoryCode'",
"]",
"==",
"'dedicated_virtual_hosts'",
":",
"dedicated_host",
".",
"append",
"(",
"{",
"'name'",
":",
"item",
"[",
"'description'",
"]",
",",
"'key'",
":",
"item",
"[",
"'keyName'",
"]",
",",
"}",
")",
"return",
"{",
"'locations'",
":",
"locations",
",",
"'dedicated_host'",
":",
"dedicated_host",
"}"
] | Returns valid options for ordering a dedicated host. | [
"Returns",
"valid",
"options",
"for",
"ordering",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L400-L420 |
1,410 | softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager._get_price | def _get_price(self, package):
"""Returns valid price for ordering a dedicated host."""
for price in package['prices']:
if not price.get('locationGroupId'):
return price['id']
raise SoftLayer.SoftLayerError("Could not find valid price") | python | def _get_price(self, package):
"""Returns valid price for ordering a dedicated host."""
for price in package['prices']:
if not price.get('locationGroupId'):
return price['id']
raise SoftLayer.SoftLayerError("Could not find valid price") | [
"def",
"_get_price",
"(",
"self",
",",
"package",
")",
":",
"for",
"price",
"in",
"package",
"[",
"'prices'",
"]",
":",
"if",
"not",
"price",
".",
"get",
"(",
"'locationGroupId'",
")",
":",
"return",
"price",
"[",
"'id'",
"]",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Could not find valid price\"",
")"
] | Returns valid price for ordering a dedicated host. | [
"Returns",
"valid",
"price",
"for",
"ordering",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L422-L429 |
1,411 | softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager._get_item | def _get_item(self, package, flavor):
"""Returns the item for ordering a dedicated host."""
for item in package['items']:
if item['keyName'] == flavor:
return item
raise SoftLayer.SoftLayerError("Could not find valid item for: '%s'" % flavor) | python | def _get_item(self, package, flavor):
"""Returns the item for ordering a dedicated host."""
for item in package['items']:
if item['keyName'] == flavor:
return item
raise SoftLayer.SoftLayerError("Could not find valid item for: '%s'" % flavor) | [
"def",
"_get_item",
"(",
"self",
",",
"package",
",",
"flavor",
")",
":",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"item",
"[",
"'keyName'",
"]",
"==",
"flavor",
":",
"return",
"item",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Could not find valid item for: '%s'\"",
"%",
"flavor",
")"
] | Returns the item for ordering a dedicated host. | [
"Returns",
"the",
"item",
"for",
"ordering",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L431-L438 |
1,412 | softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager._get_backend_router | def _get_backend_router(self, locations, item):
"""Returns valid router options for ordering a dedicated host."""
mask = '''
id,
hostname
'''
cpu_count = item['capacity']
for capacity in item['bundleItems']:
for category in capacity['categories']:
if category['categoryCode'] == 'dedicated_host_ram':
mem_capacity = capacity['capacity']
if category['categoryCode'] == 'dedicated_host_disk':
disk_capacity = capacity['capacity']
for hardwareComponent in item['bundleItems']:
if hardwareComponent['keyName'].find("GPU") != -1:
hardwareComponentType = hardwareComponent['hardwareGenericComponentModel']['hardwareComponentType']
gpuComponents = [
{
'hardwareComponentModel': {
'hardwareGenericComponentModel': {
'id': hardwareComponent['hardwareGenericComponentModel']['id'],
'hardwareComponentType': {
'keyName': hardwareComponentType['keyName']
}
}
}
},
{
'hardwareComponentModel': {
'hardwareGenericComponentModel': {
'id': hardwareComponent['hardwareGenericComponentModel']['id'],
'hardwareComponentType': {
'keyName': hardwareComponentType['keyName']
}
}
}
}
]
if locations is not None:
for location in locations:
if location['locationId'] is not None:
loc_id = location['locationId']
host = {
'cpuCount': cpu_count,
'memoryCapacity': mem_capacity,
'diskCapacity': disk_capacity,
'datacenter': {
'id': loc_id
}
}
if item['keyName'].find("GPU") != -1:
host['pciDevices'] = gpuComponents
routers = self.host.getAvailableRouters(host, mask=mask)
return routers
raise SoftLayer.SoftLayerError("Could not find available routers") | python | def _get_backend_router(self, locations, item):
"""Returns valid router options for ordering a dedicated host."""
mask = '''
id,
hostname
'''
cpu_count = item['capacity']
for capacity in item['bundleItems']:
for category in capacity['categories']:
if category['categoryCode'] == 'dedicated_host_ram':
mem_capacity = capacity['capacity']
if category['categoryCode'] == 'dedicated_host_disk':
disk_capacity = capacity['capacity']
for hardwareComponent in item['bundleItems']:
if hardwareComponent['keyName'].find("GPU") != -1:
hardwareComponentType = hardwareComponent['hardwareGenericComponentModel']['hardwareComponentType']
gpuComponents = [
{
'hardwareComponentModel': {
'hardwareGenericComponentModel': {
'id': hardwareComponent['hardwareGenericComponentModel']['id'],
'hardwareComponentType': {
'keyName': hardwareComponentType['keyName']
}
}
}
},
{
'hardwareComponentModel': {
'hardwareGenericComponentModel': {
'id': hardwareComponent['hardwareGenericComponentModel']['id'],
'hardwareComponentType': {
'keyName': hardwareComponentType['keyName']
}
}
}
}
]
if locations is not None:
for location in locations:
if location['locationId'] is not None:
loc_id = location['locationId']
host = {
'cpuCount': cpu_count,
'memoryCapacity': mem_capacity,
'diskCapacity': disk_capacity,
'datacenter': {
'id': loc_id
}
}
if item['keyName'].find("GPU") != -1:
host['pciDevices'] = gpuComponents
routers = self.host.getAvailableRouters(host, mask=mask)
return routers
raise SoftLayer.SoftLayerError("Could not find available routers") | [
"def",
"_get_backend_router",
"(",
"self",
",",
"locations",
",",
"item",
")",
":",
"mask",
"=",
"'''\n id,\n hostname\n '''",
"cpu_count",
"=",
"item",
"[",
"'capacity'",
"]",
"for",
"capacity",
"in",
"item",
"[",
"'bundleItems'",
"]",
":",
"for",
"category",
"in",
"capacity",
"[",
"'categories'",
"]",
":",
"if",
"category",
"[",
"'categoryCode'",
"]",
"==",
"'dedicated_host_ram'",
":",
"mem_capacity",
"=",
"capacity",
"[",
"'capacity'",
"]",
"if",
"category",
"[",
"'categoryCode'",
"]",
"==",
"'dedicated_host_disk'",
":",
"disk_capacity",
"=",
"capacity",
"[",
"'capacity'",
"]",
"for",
"hardwareComponent",
"in",
"item",
"[",
"'bundleItems'",
"]",
":",
"if",
"hardwareComponent",
"[",
"'keyName'",
"]",
".",
"find",
"(",
"\"GPU\"",
")",
"!=",
"-",
"1",
":",
"hardwareComponentType",
"=",
"hardwareComponent",
"[",
"'hardwareGenericComponentModel'",
"]",
"[",
"'hardwareComponentType'",
"]",
"gpuComponents",
"=",
"[",
"{",
"'hardwareComponentModel'",
":",
"{",
"'hardwareGenericComponentModel'",
":",
"{",
"'id'",
":",
"hardwareComponent",
"[",
"'hardwareGenericComponentModel'",
"]",
"[",
"'id'",
"]",
",",
"'hardwareComponentType'",
":",
"{",
"'keyName'",
":",
"hardwareComponentType",
"[",
"'keyName'",
"]",
"}",
"}",
"}",
"}",
",",
"{",
"'hardwareComponentModel'",
":",
"{",
"'hardwareGenericComponentModel'",
":",
"{",
"'id'",
":",
"hardwareComponent",
"[",
"'hardwareGenericComponentModel'",
"]",
"[",
"'id'",
"]",
",",
"'hardwareComponentType'",
":",
"{",
"'keyName'",
":",
"hardwareComponentType",
"[",
"'keyName'",
"]",
"}",
"}",
"}",
"}",
"]",
"if",
"locations",
"is",
"not",
"None",
":",
"for",
"location",
"in",
"locations",
":",
"if",
"location",
"[",
"'locationId'",
"]",
"is",
"not",
"None",
":",
"loc_id",
"=",
"location",
"[",
"'locationId'",
"]",
"host",
"=",
"{",
"'cpuCount'",
":",
"cpu_count",
",",
"'memoryCapacity'",
":",
"mem_capacity",
",",
"'diskCapacity'",
":",
"disk_capacity",
",",
"'datacenter'",
":",
"{",
"'id'",
":",
"loc_id",
"}",
"}",
"if",
"item",
"[",
"'keyName'",
"]",
".",
"find",
"(",
"\"GPU\"",
")",
"!=",
"-",
"1",
":",
"host",
"[",
"'pciDevices'",
"]",
"=",
"gpuComponents",
"routers",
"=",
"self",
".",
"host",
".",
"getAvailableRouters",
"(",
"host",
",",
"mask",
"=",
"mask",
")",
"return",
"routers",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Could not find available routers\"",
")"
] | Returns valid router options for ordering a dedicated host. | [
"Returns",
"valid",
"router",
"options",
"for",
"ordering",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L440-L498 |
1,413 | softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager._get_default_router | def _get_default_router(self, routers, router_name=None):
"""Returns the default router for ordering a dedicated host."""
if router_name is None:
for router in routers:
if router['id'] is not None:
return router['id']
else:
for router in routers:
if router['hostname'] == router_name:
return router['id']
raise SoftLayer.SoftLayerError("Could not find valid default router") | python | def _get_default_router(self, routers, router_name=None):
"""Returns the default router for ordering a dedicated host."""
if router_name is None:
for router in routers:
if router['id'] is not None:
return router['id']
else:
for router in routers:
if router['hostname'] == router_name:
return router['id']
raise SoftLayer.SoftLayerError("Could not find valid default router") | [
"def",
"_get_default_router",
"(",
"self",
",",
"routers",
",",
"router_name",
"=",
"None",
")",
":",
"if",
"router_name",
"is",
"None",
":",
"for",
"router",
"in",
"routers",
":",
"if",
"router",
"[",
"'id'",
"]",
"is",
"not",
"None",
":",
"return",
"router",
"[",
"'id'",
"]",
"else",
":",
"for",
"router",
"in",
"routers",
":",
"if",
"router",
"[",
"'hostname'",
"]",
"==",
"router_name",
":",
"return",
"router",
"[",
"'id'",
"]",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Could not find valid default router\"",
")"
] | Returns the default router for ordering a dedicated host. | [
"Returns",
"the",
"default",
"router",
"for",
"ordering",
"a",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L500-L511 |
1,414 | softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager.get_router_options | def get_router_options(self, datacenter=None, flavor=None):
"""Returns available backend routers for the dedicated host."""
package = self._get_package()
location = self._get_location(package['regions'], datacenter)
item = self._get_item(package, flavor)
return self._get_backend_router(location['location']['locationPackageDetails'], item) | python | def get_router_options(self, datacenter=None, flavor=None):
"""Returns available backend routers for the dedicated host."""
package = self._get_package()
location = self._get_location(package['regions'], datacenter)
item = self._get_item(package, flavor)
return self._get_backend_router(location['location']['locationPackageDetails'], item) | [
"def",
"get_router_options",
"(",
"self",
",",
"datacenter",
"=",
"None",
",",
"flavor",
"=",
"None",
")",
":",
"package",
"=",
"self",
".",
"_get_package",
"(",
")",
"location",
"=",
"self",
".",
"_get_location",
"(",
"package",
"[",
"'regions'",
"]",
",",
"datacenter",
")",
"item",
"=",
"self",
".",
"_get_item",
"(",
"package",
",",
"flavor",
")",
"return",
"self",
".",
"_get_backend_router",
"(",
"location",
"[",
"'location'",
"]",
"[",
"'locationPackageDetails'",
"]",
",",
"item",
")"
] | Returns available backend routers for the dedicated host. | [
"Returns",
"available",
"backend",
"routers",
"for",
"the",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L513-L520 |
1,415 | softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | DedicatedHostManager._delete_guest | def _delete_guest(self, guest_id):
"""Deletes a guest and returns 'Cancelled' or and Exception message"""
msg = 'Cancelled'
try:
self.guest.deleteObject(id=guest_id)
except SoftLayer.SoftLayerAPIError as e:
msg = 'Exception: ' + e.faultString
return msg | python | def _delete_guest(self, guest_id):
"""Deletes a guest and returns 'Cancelled' or and Exception message"""
msg = 'Cancelled'
try:
self.guest.deleteObject(id=guest_id)
except SoftLayer.SoftLayerAPIError as e:
msg = 'Exception: ' + e.faultString
return msg | [
"def",
"_delete_guest",
"(",
"self",
",",
"guest_id",
")",
":",
"msg",
"=",
"'Cancelled'",
"try",
":",
"self",
".",
"guest",
".",
"deleteObject",
"(",
"id",
"=",
"guest_id",
")",
"except",
"SoftLayer",
".",
"SoftLayerAPIError",
"as",
"e",
":",
"msg",
"=",
"'Exception: '",
"+",
"e",
".",
"faultString",
"return",
"msg"
] | Deletes a guest and returns 'Cancelled' or and Exception message | [
"Deletes",
"a",
"guest",
"and",
"returns",
"Cancelled",
"or",
"and",
"Exception",
"message"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L522-L530 |
1,416 | softlayer/softlayer-python | SoftLayer/shell/completer.py | _click_autocomplete | def _click_autocomplete(root, text):
"""Completer generator for click applications."""
try:
parts = shlex.split(text)
except ValueError:
raise StopIteration
location, incomplete = _click_resolve_command(root, parts)
if not text.endswith(' ') and not incomplete and text:
raise StopIteration
if incomplete and not incomplete[0:2].isalnum():
for param in location.params:
if not isinstance(param, click.Option):
continue
for opt in itertools.chain(param.opts, param.secondary_opts):
if opt.startswith(incomplete):
yield completion.Completion(opt, -len(incomplete), display_meta=param.help)
elif isinstance(location, (click.MultiCommand, click.core.Group)):
ctx = click.Context(location)
commands = location.list_commands(ctx)
for command in commands:
if command.startswith(incomplete):
cmd = location.get_command(ctx, command)
yield completion.Completion(command, -len(incomplete), display_meta=cmd.short_help) | python | def _click_autocomplete(root, text):
"""Completer generator for click applications."""
try:
parts = shlex.split(text)
except ValueError:
raise StopIteration
location, incomplete = _click_resolve_command(root, parts)
if not text.endswith(' ') and not incomplete and text:
raise StopIteration
if incomplete and not incomplete[0:2].isalnum():
for param in location.params:
if not isinstance(param, click.Option):
continue
for opt in itertools.chain(param.opts, param.secondary_opts):
if opt.startswith(incomplete):
yield completion.Completion(opt, -len(incomplete), display_meta=param.help)
elif isinstance(location, (click.MultiCommand, click.core.Group)):
ctx = click.Context(location)
commands = location.list_commands(ctx)
for command in commands:
if command.startswith(incomplete):
cmd = location.get_command(ctx, command)
yield completion.Completion(command, -len(incomplete), display_meta=cmd.short_help) | [
"def",
"_click_autocomplete",
"(",
"root",
",",
"text",
")",
":",
"try",
":",
"parts",
"=",
"shlex",
".",
"split",
"(",
"text",
")",
"except",
"ValueError",
":",
"raise",
"StopIteration",
"location",
",",
"incomplete",
"=",
"_click_resolve_command",
"(",
"root",
",",
"parts",
")",
"if",
"not",
"text",
".",
"endswith",
"(",
"' '",
")",
"and",
"not",
"incomplete",
"and",
"text",
":",
"raise",
"StopIteration",
"if",
"incomplete",
"and",
"not",
"incomplete",
"[",
"0",
":",
"2",
"]",
".",
"isalnum",
"(",
")",
":",
"for",
"param",
"in",
"location",
".",
"params",
":",
"if",
"not",
"isinstance",
"(",
"param",
",",
"click",
".",
"Option",
")",
":",
"continue",
"for",
"opt",
"in",
"itertools",
".",
"chain",
"(",
"param",
".",
"opts",
",",
"param",
".",
"secondary_opts",
")",
":",
"if",
"opt",
".",
"startswith",
"(",
"incomplete",
")",
":",
"yield",
"completion",
".",
"Completion",
"(",
"opt",
",",
"-",
"len",
"(",
"incomplete",
")",
",",
"display_meta",
"=",
"param",
".",
"help",
")",
"elif",
"isinstance",
"(",
"location",
",",
"(",
"click",
".",
"MultiCommand",
",",
"click",
".",
"core",
".",
"Group",
")",
")",
":",
"ctx",
"=",
"click",
".",
"Context",
"(",
"location",
")",
"commands",
"=",
"location",
".",
"list_commands",
"(",
"ctx",
")",
"for",
"command",
"in",
"commands",
":",
"if",
"command",
".",
"startswith",
"(",
"incomplete",
")",
":",
"cmd",
"=",
"location",
".",
"get_command",
"(",
"ctx",
",",
"command",
")",
"yield",
"completion",
".",
"Completion",
"(",
"command",
",",
"-",
"len",
"(",
"incomplete",
")",
",",
"display_meta",
"=",
"cmd",
".",
"short_help",
")"
] | Completer generator for click applications. | [
"Completer",
"generator",
"for",
"click",
"applications",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/shell/completer.py#L28-L54 |
1,417 | softlayer/softlayer-python | SoftLayer/shell/completer.py | _click_resolve_command | def _click_resolve_command(root, parts):
"""Return the click command and the left over text given some vargs."""
location = root
incomplete = ''
for part in parts:
incomplete = part
if not part[0:2].isalnum():
continue
try:
next_location = location.get_command(click.Context(location),
part)
if next_location is not None:
location = next_location
incomplete = ''
except AttributeError:
break
return location, incomplete | python | def _click_resolve_command(root, parts):
"""Return the click command and the left over text given some vargs."""
location = root
incomplete = ''
for part in parts:
incomplete = part
if not part[0:2].isalnum():
continue
try:
next_location = location.get_command(click.Context(location),
part)
if next_location is not None:
location = next_location
incomplete = ''
except AttributeError:
break
return location, incomplete | [
"def",
"_click_resolve_command",
"(",
"root",
",",
"parts",
")",
":",
"location",
"=",
"root",
"incomplete",
"=",
"''",
"for",
"part",
"in",
"parts",
":",
"incomplete",
"=",
"part",
"if",
"not",
"part",
"[",
"0",
":",
"2",
"]",
".",
"isalnum",
"(",
")",
":",
"continue",
"try",
":",
"next_location",
"=",
"location",
".",
"get_command",
"(",
"click",
".",
"Context",
"(",
"location",
")",
",",
"part",
")",
"if",
"next_location",
"is",
"not",
"None",
":",
"location",
"=",
"next_location",
"incomplete",
"=",
"''",
"except",
"AttributeError",
":",
"break",
"return",
"location",
",",
"incomplete"
] | Return the click command and the left over text given some vargs. | [
"Return",
"the",
"click",
"command",
"and",
"the",
"left",
"over",
"text",
"given",
"some",
"vargs",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/shell/completer.py#L57-L75 |
1,418 | softlayer/softlayer-python | SoftLayer/CLI/user/edit_permissions.py | cli | def cli(env, identifier, enable, permission, from_user):
"""Enable or Disable specific permissions."""
mgr = SoftLayer.UserManager(env.client)
user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
result = False
if from_user:
from_user_id = helpers.resolve_id(mgr.resolve_ids, from_user, 'username')
result = mgr.permissions_from_user(user_id, from_user_id)
elif enable:
result = mgr.add_permissions(user_id, permission)
else:
result = mgr.remove_permissions(user_id, permission)
if result:
click.secho("Permissions updated successfully: %s" % ", ".join(permission), fg='green')
else:
click.secho("Failed to update permissions: %s" % ", ".join(permission), fg='red') | python | def cli(env, identifier, enable, permission, from_user):
"""Enable or Disable specific permissions."""
mgr = SoftLayer.UserManager(env.client)
user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
result = False
if from_user:
from_user_id = helpers.resolve_id(mgr.resolve_ids, from_user, 'username')
result = mgr.permissions_from_user(user_id, from_user_id)
elif enable:
result = mgr.add_permissions(user_id, permission)
else:
result = mgr.remove_permissions(user_id, permission)
if result:
click.secho("Permissions updated successfully: %s" % ", ".join(permission), fg='green')
else:
click.secho("Failed to update permissions: %s" % ", ".join(permission), fg='red') | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"enable",
",",
"permission",
",",
"from_user",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"UserManager",
"(",
"env",
".",
"client",
")",
"user_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'username'",
")",
"result",
"=",
"False",
"if",
"from_user",
":",
"from_user_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"from_user",
",",
"'username'",
")",
"result",
"=",
"mgr",
".",
"permissions_from_user",
"(",
"user_id",
",",
"from_user_id",
")",
"elif",
"enable",
":",
"result",
"=",
"mgr",
".",
"add_permissions",
"(",
"user_id",
",",
"permission",
")",
"else",
":",
"result",
"=",
"mgr",
".",
"remove_permissions",
"(",
"user_id",
",",
"permission",
")",
"if",
"result",
":",
"click",
".",
"secho",
"(",
"\"Permissions updated successfully: %s\"",
"%",
"\", \"",
".",
"join",
"(",
"permission",
")",
",",
"fg",
"=",
"'green'",
")",
"else",
":",
"click",
".",
"secho",
"(",
"\"Failed to update permissions: %s\"",
"%",
"\", \"",
".",
"join",
"(",
"permission",
")",
",",
"fg",
"=",
"'red'",
")"
] | Enable or Disable specific permissions. | [
"Enable",
"or",
"Disable",
"specific",
"permissions",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/edit_permissions.py#L22-L38 |
1,419 | softlayer/softlayer-python | SoftLayer/managers/cdn.py | CDNManager.list_accounts | def list_accounts(self):
"""Lists CDN accounts for the active user."""
account = self.client['Account']
mask = 'cdnAccounts[%s]' % ', '.join(['id',
'createDate',
'cdnAccountName',
'cdnSolutionName',
'cdnAccountNote',
'status'])
return account.getObject(mask=mask).get('cdnAccounts', []) | python | def list_accounts(self):
"""Lists CDN accounts for the active user."""
account = self.client['Account']
mask = 'cdnAccounts[%s]' % ', '.join(['id',
'createDate',
'cdnAccountName',
'cdnSolutionName',
'cdnAccountNote',
'status'])
return account.getObject(mask=mask).get('cdnAccounts', []) | [
"def",
"list_accounts",
"(",
"self",
")",
":",
"account",
"=",
"self",
".",
"client",
"[",
"'Account'",
"]",
"mask",
"=",
"'cdnAccounts[%s]'",
"%",
"', '",
".",
"join",
"(",
"[",
"'id'",
",",
"'createDate'",
",",
"'cdnAccountName'",
",",
"'cdnSolutionName'",
",",
"'cdnAccountNote'",
",",
"'status'",
"]",
")",
"return",
"account",
".",
"getObject",
"(",
"mask",
"=",
"mask",
")",
".",
"get",
"(",
"'cdnAccounts'",
",",
"[",
"]",
")"
] | Lists CDN accounts for the active user. | [
"Lists",
"CDN",
"accounts",
"for",
"the",
"active",
"user",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/cdn.py#L30-L40 |
1,420 | softlayer/softlayer-python | SoftLayer/managers/cdn.py | CDNManager.get_account | def get_account(self, account_id, **kwargs):
"""Retrieves a CDN account with the specified account ID.
:param account_id int: the numeric ID associated with the CDN account.
:param dict \\*\\*kwargs: additional arguments to include in the object
mask.
"""
if 'mask' not in kwargs:
kwargs['mask'] = 'status'
return self.account.getObject(id=account_id, **kwargs) | python | def get_account(self, account_id, **kwargs):
"""Retrieves a CDN account with the specified account ID.
:param account_id int: the numeric ID associated with the CDN account.
:param dict \\*\\*kwargs: additional arguments to include in the object
mask.
"""
if 'mask' not in kwargs:
kwargs['mask'] = 'status'
return self.account.getObject(id=account_id, **kwargs) | [
"def",
"get_account",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'mask'",
"]",
"=",
"'status'",
"return",
"self",
".",
"account",
".",
"getObject",
"(",
"id",
"=",
"account_id",
",",
"*",
"*",
"kwargs",
")"
] | Retrieves a CDN account with the specified account ID.
:param account_id int: the numeric ID associated with the CDN account.
:param dict \\*\\*kwargs: additional arguments to include in the object
mask. | [
"Retrieves",
"a",
"CDN",
"account",
"with",
"the",
"specified",
"account",
"ID",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/cdn.py#L42-L53 |
1,421 | softlayer/softlayer-python | SoftLayer/managers/cdn.py | CDNManager.get_origins | def get_origins(self, account_id, **kwargs):
"""Retrieves list of origin pull mappings for a specified CDN account.
:param account_id int: the numeric ID associated with the CDN account.
:param dict \\*\\*kwargs: additional arguments to include in the object
mask.
"""
return self.account.getOriginPullMappingInformation(id=account_id,
**kwargs) | python | def get_origins(self, account_id, **kwargs):
"""Retrieves list of origin pull mappings for a specified CDN account.
:param account_id int: the numeric ID associated with the CDN account.
:param dict \\*\\*kwargs: additional arguments to include in the object
mask.
"""
return self.account.getOriginPullMappingInformation(id=account_id,
**kwargs) | [
"def",
"get_origins",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"account",
".",
"getOriginPullMappingInformation",
"(",
"id",
"=",
"account_id",
",",
"*",
"*",
"kwargs",
")"
] | Retrieves list of origin pull mappings for a specified CDN account.
:param account_id int: the numeric ID associated with the CDN account.
:param dict \\*\\*kwargs: additional arguments to include in the object
mask. | [
"Retrieves",
"list",
"of",
"origin",
"pull",
"mappings",
"for",
"a",
"specified",
"CDN",
"account",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/cdn.py#L55-L64 |
1,422 | softlayer/softlayer-python | SoftLayer/managers/cdn.py | CDNManager.add_origin | def add_origin(self, account_id, media_type, origin_url, cname=None,
secure=False):
"""Adds an original pull mapping to an origin-pull.
:param int account_id: the numeric ID associated with the CDN account.
:param string media_type: the media type/protocol associated with this
origin pull mapping; valid values are HTTP,
FLASH, and WM.
:param string origin_url: the base URL from which content should be
pulled.
:param string cname: an optional CNAME that should be associated with
this origin pull rule; only the hostname should be
included (i.e., no 'http://', directories, etc.).
:param boolean secure: specifies whether this is an SSL origin pull
rule, if SSL is enabled on your account
(defaults to false).
"""
config = {'mediaType': media_type,
'originUrl': origin_url,
'isSecureContent': secure}
if cname:
config['cname'] = cname
return self.account.createOriginPullMapping(config, id=account_id) | python | def add_origin(self, account_id, media_type, origin_url, cname=None,
secure=False):
"""Adds an original pull mapping to an origin-pull.
:param int account_id: the numeric ID associated with the CDN account.
:param string media_type: the media type/protocol associated with this
origin pull mapping; valid values are HTTP,
FLASH, and WM.
:param string origin_url: the base URL from which content should be
pulled.
:param string cname: an optional CNAME that should be associated with
this origin pull rule; only the hostname should be
included (i.e., no 'http://', directories, etc.).
:param boolean secure: specifies whether this is an SSL origin pull
rule, if SSL is enabled on your account
(defaults to false).
"""
config = {'mediaType': media_type,
'originUrl': origin_url,
'isSecureContent': secure}
if cname:
config['cname'] = cname
return self.account.createOriginPullMapping(config, id=account_id) | [
"def",
"add_origin",
"(",
"self",
",",
"account_id",
",",
"media_type",
",",
"origin_url",
",",
"cname",
"=",
"None",
",",
"secure",
"=",
"False",
")",
":",
"config",
"=",
"{",
"'mediaType'",
":",
"media_type",
",",
"'originUrl'",
":",
"origin_url",
",",
"'isSecureContent'",
":",
"secure",
"}",
"if",
"cname",
":",
"config",
"[",
"'cname'",
"]",
"=",
"cname",
"return",
"self",
".",
"account",
".",
"createOriginPullMapping",
"(",
"config",
",",
"id",
"=",
"account_id",
")"
] | Adds an original pull mapping to an origin-pull.
:param int account_id: the numeric ID associated with the CDN account.
:param string media_type: the media type/protocol associated with this
origin pull mapping; valid values are HTTP,
FLASH, and WM.
:param string origin_url: the base URL from which content should be
pulled.
:param string cname: an optional CNAME that should be associated with
this origin pull rule; only the hostname should be
included (i.e., no 'http://', directories, etc.).
:param boolean secure: specifies whether this is an SSL origin pull
rule, if SSL is enabled on your account
(defaults to false). | [
"Adds",
"an",
"original",
"pull",
"mapping",
"to",
"an",
"origin",
"-",
"pull",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/cdn.py#L66-L91 |
1,423 | softlayer/softlayer-python | SoftLayer/managers/cdn.py | CDNManager.remove_origin | def remove_origin(self, account_id, origin_id):
"""Removes an origin pull mapping with the given origin pull ID.
:param int account_id: the CDN account ID from which the mapping should
be deleted.
:param int origin_id: the origin pull mapping ID to delete.
"""
return self.account.deleteOriginPullRule(origin_id, id=account_id) | python | def remove_origin(self, account_id, origin_id):
"""Removes an origin pull mapping with the given origin pull ID.
:param int account_id: the CDN account ID from which the mapping should
be deleted.
:param int origin_id: the origin pull mapping ID to delete.
"""
return self.account.deleteOriginPullRule(origin_id, id=account_id) | [
"def",
"remove_origin",
"(",
"self",
",",
"account_id",
",",
"origin_id",
")",
":",
"return",
"self",
".",
"account",
".",
"deleteOriginPullRule",
"(",
"origin_id",
",",
"id",
"=",
"account_id",
")"
] | Removes an origin pull mapping with the given origin pull ID.
:param int account_id: the CDN account ID from which the mapping should
be deleted.
:param int origin_id: the origin pull mapping ID to delete. | [
"Removes",
"an",
"origin",
"pull",
"mapping",
"with",
"the",
"given",
"origin",
"pull",
"ID",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/cdn.py#L93-L101 |
1,424 | softlayer/softlayer-python | SoftLayer/managers/cdn.py | CDNManager.load_content | def load_content(self, account_id, urls):
"""Prefetches one or more URLs to the CDN edge nodes.
:param int account_id: the CDN account ID into which content should be
preloaded.
:param urls: a string or a list of strings representing the CDN URLs
that should be pre-loaded.
:returns: true if all load requests were successfully submitted;
otherwise, returns the first error encountered.
"""
if isinstance(urls, six.string_types):
urls = [urls]
for i in range(0, len(urls), MAX_URLS_PER_LOAD):
result = self.account.loadContent(urls[i:i + MAX_URLS_PER_LOAD],
id=account_id)
if not result:
return result
return True | python | def load_content(self, account_id, urls):
"""Prefetches one or more URLs to the CDN edge nodes.
:param int account_id: the CDN account ID into which content should be
preloaded.
:param urls: a string or a list of strings representing the CDN URLs
that should be pre-loaded.
:returns: true if all load requests were successfully submitted;
otherwise, returns the first error encountered.
"""
if isinstance(urls, six.string_types):
urls = [urls]
for i in range(0, len(urls), MAX_URLS_PER_LOAD):
result = self.account.loadContent(urls[i:i + MAX_URLS_PER_LOAD],
id=account_id)
if not result:
return result
return True | [
"def",
"load_content",
"(",
"self",
",",
"account_id",
",",
"urls",
")",
":",
"if",
"isinstance",
"(",
"urls",
",",
"six",
".",
"string_types",
")",
":",
"urls",
"=",
"[",
"urls",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"urls",
")",
",",
"MAX_URLS_PER_LOAD",
")",
":",
"result",
"=",
"self",
".",
"account",
".",
"loadContent",
"(",
"urls",
"[",
"i",
":",
"i",
"+",
"MAX_URLS_PER_LOAD",
"]",
",",
"id",
"=",
"account_id",
")",
"if",
"not",
"result",
":",
"return",
"result",
"return",
"True"
] | Prefetches one or more URLs to the CDN edge nodes.
:param int account_id: the CDN account ID into which content should be
preloaded.
:param urls: a string or a list of strings representing the CDN URLs
that should be pre-loaded.
:returns: true if all load requests were successfully submitted;
otherwise, returns the first error encountered. | [
"Prefetches",
"one",
"or",
"more",
"URLs",
"to",
"the",
"CDN",
"edge",
"nodes",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/cdn.py#L103-L123 |
1,425 | softlayer/softlayer-python | SoftLayer/managers/cdn.py | CDNManager.purge_content | def purge_content(self, account_id, urls):
"""Purges one or more URLs from the CDN edge nodes.
:param int account_id: the CDN account ID from which content should
be purged.
:param urls: a string or a list of strings representing the CDN URLs
that should be purged.
:returns: a list of SoftLayer_Container_Network_ContentDelivery_PurgeService_Response objects
which indicates if the purge for each url was SUCCESS, FAILED or INVALID_URL.
"""
if isinstance(urls, six.string_types):
urls = [urls]
content_list = []
for i in range(0, len(urls), MAX_URLS_PER_PURGE):
content = self.account.purgeCache(urls[i:i + MAX_URLS_PER_PURGE], id=account_id)
content_list.extend(content)
return content_list | python | def purge_content(self, account_id, urls):
"""Purges one or more URLs from the CDN edge nodes.
:param int account_id: the CDN account ID from which content should
be purged.
:param urls: a string or a list of strings representing the CDN URLs
that should be purged.
:returns: a list of SoftLayer_Container_Network_ContentDelivery_PurgeService_Response objects
which indicates if the purge for each url was SUCCESS, FAILED or INVALID_URL.
"""
if isinstance(urls, six.string_types):
urls = [urls]
content_list = []
for i in range(0, len(urls), MAX_URLS_PER_PURGE):
content = self.account.purgeCache(urls[i:i + MAX_URLS_PER_PURGE], id=account_id)
content_list.extend(content)
return content_list | [
"def",
"purge_content",
"(",
"self",
",",
"account_id",
",",
"urls",
")",
":",
"if",
"isinstance",
"(",
"urls",
",",
"six",
".",
"string_types",
")",
":",
"urls",
"=",
"[",
"urls",
"]",
"content_list",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"urls",
")",
",",
"MAX_URLS_PER_PURGE",
")",
":",
"content",
"=",
"self",
".",
"account",
".",
"purgeCache",
"(",
"urls",
"[",
"i",
":",
"i",
"+",
"MAX_URLS_PER_PURGE",
"]",
",",
"id",
"=",
"account_id",
")",
"content_list",
".",
"extend",
"(",
"content",
")",
"return",
"content_list"
] | Purges one or more URLs from the CDN edge nodes.
:param int account_id: the CDN account ID from which content should
be purged.
:param urls: a string or a list of strings representing the CDN URLs
that should be purged.
:returns: a list of SoftLayer_Container_Network_ContentDelivery_PurgeService_Response objects
which indicates if the purge for each url was SUCCESS, FAILED or INVALID_URL. | [
"Purges",
"one",
"or",
"more",
"URLs",
"from",
"the",
"CDN",
"edge",
"nodes",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/cdn.py#L125-L144 |
1,426 | softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.get_lb_pkgs | def get_lb_pkgs(self):
"""Retrieves the local load balancer packages.
:returns: A dictionary containing the load balancer packages
"""
_filter = {'items': {'description':
utils.query_filter('*Load Balancer*')}}
packages = self.prod_pkg.getItems(id=0, filter=_filter)
pkgs = []
for package in packages:
if not package['description'].startswith('Global'):
pkgs.append(package)
return pkgs | python | def get_lb_pkgs(self):
"""Retrieves the local load balancer packages.
:returns: A dictionary containing the load balancer packages
"""
_filter = {'items': {'description':
utils.query_filter('*Load Balancer*')}}
packages = self.prod_pkg.getItems(id=0, filter=_filter)
pkgs = []
for package in packages:
if not package['description'].startswith('Global'):
pkgs.append(package)
return pkgs | [
"def",
"get_lb_pkgs",
"(",
"self",
")",
":",
"_filter",
"=",
"{",
"'items'",
":",
"{",
"'description'",
":",
"utils",
".",
"query_filter",
"(",
"'*Load Balancer*'",
")",
"}",
"}",
"packages",
"=",
"self",
".",
"prod_pkg",
".",
"getItems",
"(",
"id",
"=",
"0",
",",
"filter",
"=",
"_filter",
")",
"pkgs",
"=",
"[",
"]",
"for",
"package",
"in",
"packages",
":",
"if",
"not",
"package",
"[",
"'description'",
"]",
".",
"startswith",
"(",
"'Global'",
")",
":",
"pkgs",
".",
"append",
"(",
"package",
")",
"return",
"pkgs"
] | Retrieves the local load balancer packages.
:returns: A dictionary containing the load balancer packages | [
"Retrieves",
"the",
"local",
"load",
"balancer",
"packages",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L27-L41 |
1,427 | softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager._get_location | def _get_location(self, datacenter_name):
"""Returns the location of the specified datacenter.
:param string datacenter_name: The datacenter to create
the loadbalancer in
:returns: the location id of the given datacenter
"""
datacenters = self.client['Location'].getDataCenters()
for datacenter in datacenters:
if datacenter['name'] == datacenter_name:
return datacenter['id']
return 'FIRST_AVAILABLE' | python | def _get_location(self, datacenter_name):
"""Returns the location of the specified datacenter.
:param string datacenter_name: The datacenter to create
the loadbalancer in
:returns: the location id of the given datacenter
"""
datacenters = self.client['Location'].getDataCenters()
for datacenter in datacenters:
if datacenter['name'] == datacenter_name:
return datacenter['id']
return 'FIRST_AVAILABLE' | [
"def",
"_get_location",
"(",
"self",
",",
"datacenter_name",
")",
":",
"datacenters",
"=",
"self",
".",
"client",
"[",
"'Location'",
"]",
".",
"getDataCenters",
"(",
")",
"for",
"datacenter",
"in",
"datacenters",
":",
"if",
"datacenter",
"[",
"'name'",
"]",
"==",
"datacenter_name",
":",
"return",
"datacenter",
"[",
"'id'",
"]",
"return",
"'FIRST_AVAILABLE'"
] | Returns the location of the specified datacenter.
:param string datacenter_name: The datacenter to create
the loadbalancer in
:returns: the location id of the given datacenter | [
"Returns",
"the",
"location",
"of",
"the",
"specified",
"datacenter",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L73-L86 |
1,428 | softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.cancel_lb | def cancel_lb(self, loadbal_id):
"""Cancels the specified load balancer.
:param int loadbal_id: Load Balancer ID to be cancelled.
"""
lb_billing = self.lb_svc.getBillingItem(id=loadbal_id)
billing_id = lb_billing['id']
billing_item = self.client['Billing_Item']
return billing_item.cancelService(id=billing_id) | python | def cancel_lb(self, loadbal_id):
"""Cancels the specified load balancer.
:param int loadbal_id: Load Balancer ID to be cancelled.
"""
lb_billing = self.lb_svc.getBillingItem(id=loadbal_id)
billing_id = lb_billing['id']
billing_item = self.client['Billing_Item']
return billing_item.cancelService(id=billing_id) | [
"def",
"cancel_lb",
"(",
"self",
",",
"loadbal_id",
")",
":",
"lb_billing",
"=",
"self",
".",
"lb_svc",
".",
"getBillingItem",
"(",
"id",
"=",
"loadbal_id",
")",
"billing_id",
"=",
"lb_billing",
"[",
"'id'",
"]",
"billing_item",
"=",
"self",
".",
"client",
"[",
"'Billing_Item'",
"]",
"return",
"billing_item",
".",
"cancelService",
"(",
"id",
"=",
"billing_id",
")"
] | Cancels the specified load balancer.
:param int loadbal_id: Load Balancer ID to be cancelled. | [
"Cancels",
"the",
"specified",
"load",
"balancer",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L88-L97 |
1,429 | softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.add_local_lb | def add_local_lb(self, price_item_id, datacenter):
"""Creates a local load balancer in the specified data center.
:param int price_item_id: The price item ID for the load balancer
:param string datacenter: The datacenter to create the loadbalancer in
:returns: A dictionary containing the product order
"""
product_order = {
'complexType': 'SoftLayer_Container_Product_Order_Network_'
'LoadBalancer',
'quantity': 1,
'packageId': 0,
"location": self._get_location(datacenter),
'prices': [{'id': price_item_id}]
}
return self.client['Product_Order'].placeOrder(product_order) | python | def add_local_lb(self, price_item_id, datacenter):
"""Creates a local load balancer in the specified data center.
:param int price_item_id: The price item ID for the load balancer
:param string datacenter: The datacenter to create the loadbalancer in
:returns: A dictionary containing the product order
"""
product_order = {
'complexType': 'SoftLayer_Container_Product_Order_Network_'
'LoadBalancer',
'quantity': 1,
'packageId': 0,
"location": self._get_location(datacenter),
'prices': [{'id': price_item_id}]
}
return self.client['Product_Order'].placeOrder(product_order) | [
"def",
"add_local_lb",
"(",
"self",
",",
"price_item_id",
",",
"datacenter",
")",
":",
"product_order",
"=",
"{",
"'complexType'",
":",
"'SoftLayer_Container_Product_Order_Network_'",
"'LoadBalancer'",
",",
"'quantity'",
":",
"1",
",",
"'packageId'",
":",
"0",
",",
"\"location\"",
":",
"self",
".",
"_get_location",
"(",
"datacenter",
")",
",",
"'prices'",
":",
"[",
"{",
"'id'",
":",
"price_item_id",
"}",
"]",
"}",
"return",
"self",
".",
"client",
"[",
"'Product_Order'",
"]",
".",
"placeOrder",
"(",
"product_order",
")"
] | Creates a local load balancer in the specified data center.
:param int price_item_id: The price item ID for the load balancer
:param string datacenter: The datacenter to create the loadbalancer in
:returns: A dictionary containing the product order | [
"Creates",
"a",
"local",
"load",
"balancer",
"in",
"the",
"specified",
"data",
"center",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L99-L115 |
1,430 | softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.get_local_lb | def get_local_lb(self, loadbal_id, **kwargs):
"""Returns a specified local load balancer given the id.
:param int loadbal_id: The id of the load balancer to retrieve
:returns: A dictionary containing the details of the load balancer
"""
if 'mask' not in kwargs:
kwargs['mask'] = ('loadBalancerHardware[datacenter], '
'ipAddress, virtualServers[serviceGroups'
'[routingMethod,routingType,services'
'[healthChecks[type], groupReferences,'
' ipAddress]]]')
return self.lb_svc.getObject(id=loadbal_id, **kwargs) | python | def get_local_lb(self, loadbal_id, **kwargs):
"""Returns a specified local load balancer given the id.
:param int loadbal_id: The id of the load balancer to retrieve
:returns: A dictionary containing the details of the load balancer
"""
if 'mask' not in kwargs:
kwargs['mask'] = ('loadBalancerHardware[datacenter], '
'ipAddress, virtualServers[serviceGroups'
'[routingMethod,routingType,services'
'[healthChecks[type], groupReferences,'
' ipAddress]]]')
return self.lb_svc.getObject(id=loadbal_id, **kwargs) | [
"def",
"get_local_lb",
"(",
"self",
",",
"loadbal_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'mask'",
"]",
"=",
"(",
"'loadBalancerHardware[datacenter], '",
"'ipAddress, virtualServers[serviceGroups'",
"'[routingMethod,routingType,services'",
"'[healthChecks[type], groupReferences,'",
"' ipAddress]]]'",
")",
"return",
"self",
".",
"lb_svc",
".",
"getObject",
"(",
"id",
"=",
"loadbal_id",
",",
"*",
"*",
"kwargs",
")"
] | Returns a specified local load balancer given the id.
:param int loadbal_id: The id of the load balancer to retrieve
:returns: A dictionary containing the details of the load balancer | [
"Returns",
"a",
"specified",
"local",
"load",
"balancer",
"given",
"the",
"id",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L126-L140 |
1,431 | softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.delete_service | def delete_service(self, service_id):
"""Deletes a service from the loadbal_id.
:param int service_id: The id of the service to delete
"""
svc = self.client['Network_Application_Delivery_Controller_'
'LoadBalancer_Service']
return svc.deleteObject(id=service_id) | python | def delete_service(self, service_id):
"""Deletes a service from the loadbal_id.
:param int service_id: The id of the service to delete
"""
svc = self.client['Network_Application_Delivery_Controller_'
'LoadBalancer_Service']
return svc.deleteObject(id=service_id) | [
"def",
"delete_service",
"(",
"self",
",",
"service_id",
")",
":",
"svc",
"=",
"self",
".",
"client",
"[",
"'Network_Application_Delivery_Controller_'",
"'LoadBalancer_Service'",
"]",
"return",
"svc",
".",
"deleteObject",
"(",
"id",
"=",
"service_id",
")"
] | Deletes a service from the loadbal_id.
:param int service_id: The id of the service to delete | [
"Deletes",
"a",
"service",
"from",
"the",
"loadbal_id",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L142-L151 |
1,432 | softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.delete_service_group | def delete_service_group(self, group_id):
"""Deletes a service group from the loadbal_id.
:param int group_id: The id of the service group to delete
"""
svc = self.client['Network_Application_Delivery_Controller_'
'LoadBalancer_VirtualServer']
return svc.deleteObject(id=group_id) | python | def delete_service_group(self, group_id):
"""Deletes a service group from the loadbal_id.
:param int group_id: The id of the service group to delete
"""
svc = self.client['Network_Application_Delivery_Controller_'
'LoadBalancer_VirtualServer']
return svc.deleteObject(id=group_id) | [
"def",
"delete_service_group",
"(",
"self",
",",
"group_id",
")",
":",
"svc",
"=",
"self",
".",
"client",
"[",
"'Network_Application_Delivery_Controller_'",
"'LoadBalancer_VirtualServer'",
"]",
"return",
"svc",
".",
"deleteObject",
"(",
"id",
"=",
"group_id",
")"
] | Deletes a service group from the loadbal_id.
:param int group_id: The id of the service group to delete | [
"Deletes",
"a",
"service",
"group",
"from",
"the",
"loadbal_id",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L153-L162 |
1,433 | softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.toggle_service_status | def toggle_service_status(self, service_id):
"""Toggles the service status.
:param int service_id: The id of the service to delete
"""
svc = self.client['Network_Application_Delivery_Controller_'
'LoadBalancer_Service']
return svc.toggleStatus(id=service_id) | python | def toggle_service_status(self, service_id):
"""Toggles the service status.
:param int service_id: The id of the service to delete
"""
svc = self.client['Network_Application_Delivery_Controller_'
'LoadBalancer_Service']
return svc.toggleStatus(id=service_id) | [
"def",
"toggle_service_status",
"(",
"self",
",",
"service_id",
")",
":",
"svc",
"=",
"self",
".",
"client",
"[",
"'Network_Application_Delivery_Controller_'",
"'LoadBalancer_Service'",
"]",
"return",
"svc",
".",
"toggleStatus",
"(",
"id",
"=",
"service_id",
")"
] | Toggles the service status.
:param int service_id: The id of the service to delete | [
"Toggles",
"the",
"service",
"status",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L164-L172 |
1,434 | softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.edit_service | def edit_service(self, loadbal_id, service_id, ip_address_id=None,
port=None, enabled=None, hc_type=None, weight=None):
"""Edits an existing service properties.
:param int loadbal_id: The id of the loadbal where the service resides
:param int service_id: The id of the service to edit
:param string ip_address: The ip address of the service
:param int port: the port of the service
:param bool enabled: enable or disable the search
:param int hc_type: The health check type
:param int weight: the weight to give to the service
"""
_filter = {
'virtualServers': {
'serviceGroups': {
'services': {'id': utils.query_filter(service_id)}}}}
mask = 'serviceGroups[services[groupReferences,healthChecks]]'
virtual_servers = self.lb_svc.getVirtualServers(id=loadbal_id,
filter=_filter,
mask=mask)
for service in virtual_servers[0]['serviceGroups'][0]['services']:
if service['id'] == service_id:
if enabled is not None:
service['enabled'] = int(enabled)
if port is not None:
service['port'] = port
if weight is not None:
service['groupReferences'][0]['weight'] = weight
if hc_type is not None:
service['healthChecks'][0]['healthCheckTypeId'] = hc_type
if ip_address_id is not None:
service['ipAddressId'] = ip_address_id
template = {'virtualServers': list(virtual_servers)}
load_balancer = self.lb_svc.editObject(template, id=loadbal_id)
return load_balancer | python | def edit_service(self, loadbal_id, service_id, ip_address_id=None,
port=None, enabled=None, hc_type=None, weight=None):
"""Edits an existing service properties.
:param int loadbal_id: The id of the loadbal where the service resides
:param int service_id: The id of the service to edit
:param string ip_address: The ip address of the service
:param int port: the port of the service
:param bool enabled: enable or disable the search
:param int hc_type: The health check type
:param int weight: the weight to give to the service
"""
_filter = {
'virtualServers': {
'serviceGroups': {
'services': {'id': utils.query_filter(service_id)}}}}
mask = 'serviceGroups[services[groupReferences,healthChecks]]'
virtual_servers = self.lb_svc.getVirtualServers(id=loadbal_id,
filter=_filter,
mask=mask)
for service in virtual_servers[0]['serviceGroups'][0]['services']:
if service['id'] == service_id:
if enabled is not None:
service['enabled'] = int(enabled)
if port is not None:
service['port'] = port
if weight is not None:
service['groupReferences'][0]['weight'] = weight
if hc_type is not None:
service['healthChecks'][0]['healthCheckTypeId'] = hc_type
if ip_address_id is not None:
service['ipAddressId'] = ip_address_id
template = {'virtualServers': list(virtual_servers)}
load_balancer = self.lb_svc.editObject(template, id=loadbal_id)
return load_balancer | [
"def",
"edit_service",
"(",
"self",
",",
"loadbal_id",
",",
"service_id",
",",
"ip_address_id",
"=",
"None",
",",
"port",
"=",
"None",
",",
"enabled",
"=",
"None",
",",
"hc_type",
"=",
"None",
",",
"weight",
"=",
"None",
")",
":",
"_filter",
"=",
"{",
"'virtualServers'",
":",
"{",
"'serviceGroups'",
":",
"{",
"'services'",
":",
"{",
"'id'",
":",
"utils",
".",
"query_filter",
"(",
"service_id",
")",
"}",
"}",
"}",
"}",
"mask",
"=",
"'serviceGroups[services[groupReferences,healthChecks]]'",
"virtual_servers",
"=",
"self",
".",
"lb_svc",
".",
"getVirtualServers",
"(",
"id",
"=",
"loadbal_id",
",",
"filter",
"=",
"_filter",
",",
"mask",
"=",
"mask",
")",
"for",
"service",
"in",
"virtual_servers",
"[",
"0",
"]",
"[",
"'serviceGroups'",
"]",
"[",
"0",
"]",
"[",
"'services'",
"]",
":",
"if",
"service",
"[",
"'id'",
"]",
"==",
"service_id",
":",
"if",
"enabled",
"is",
"not",
"None",
":",
"service",
"[",
"'enabled'",
"]",
"=",
"int",
"(",
"enabled",
")",
"if",
"port",
"is",
"not",
"None",
":",
"service",
"[",
"'port'",
"]",
"=",
"port",
"if",
"weight",
"is",
"not",
"None",
":",
"service",
"[",
"'groupReferences'",
"]",
"[",
"0",
"]",
"[",
"'weight'",
"]",
"=",
"weight",
"if",
"hc_type",
"is",
"not",
"None",
":",
"service",
"[",
"'healthChecks'",
"]",
"[",
"0",
"]",
"[",
"'healthCheckTypeId'",
"]",
"=",
"hc_type",
"if",
"ip_address_id",
"is",
"not",
"None",
":",
"service",
"[",
"'ipAddressId'",
"]",
"=",
"ip_address_id",
"template",
"=",
"{",
"'virtualServers'",
":",
"list",
"(",
"virtual_servers",
")",
"}",
"load_balancer",
"=",
"self",
".",
"lb_svc",
".",
"editObject",
"(",
"template",
",",
"id",
"=",
"loadbal_id",
")",
"return",
"load_balancer"
] | Edits an existing service properties.
:param int loadbal_id: The id of the loadbal where the service resides
:param int service_id: The id of the service to edit
:param string ip_address: The ip address of the service
:param int port: the port of the service
:param bool enabled: enable or disable the search
:param int hc_type: The health check type
:param int weight: the weight to give to the service | [
"Edits",
"an",
"existing",
"service",
"properties",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L174-L214 |
1,435 | softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.add_service | def add_service(self, loadbal_id, service_group_id, ip_address_id,
port=80, enabled=True, hc_type=21, weight=1):
"""Adds a new service to the service group.
:param int loadbal_id: The id of the loadbal where the service resides
:param int service_group_id: The group to add the service to
:param int ip_address id: The ip address ID of the service
:param int port: the port of the service
:param bool enabled: Enable or disable the service
:param int hc_type: The health check type
:param int weight: the weight to give to the service
"""
kwargs = utils.NestedDict({})
kwargs['mask'] = ('virtualServers['
'serviceGroups[services[groupReferences]]]')
load_balancer = self.lb_svc.getObject(id=loadbal_id, **kwargs)
virtual_servers = load_balancer['virtualServers']
for virtual_server in virtual_servers:
if virtual_server['id'] == service_group_id:
service_template = {
'enabled': int(enabled),
'port': port,
'ipAddressId': ip_address_id,
'healthChecks': [
{
'healthCheckTypeId': hc_type
}
],
'groupReferences': [
{
'weight': weight
}
]
}
services = virtual_server['serviceGroups'][0]['services']
services.append(service_template)
return self.lb_svc.editObject(load_balancer, id=loadbal_id) | python | def add_service(self, loadbal_id, service_group_id, ip_address_id,
port=80, enabled=True, hc_type=21, weight=1):
"""Adds a new service to the service group.
:param int loadbal_id: The id of the loadbal where the service resides
:param int service_group_id: The group to add the service to
:param int ip_address id: The ip address ID of the service
:param int port: the port of the service
:param bool enabled: Enable or disable the service
:param int hc_type: The health check type
:param int weight: the weight to give to the service
"""
kwargs = utils.NestedDict({})
kwargs['mask'] = ('virtualServers['
'serviceGroups[services[groupReferences]]]')
load_balancer = self.lb_svc.getObject(id=loadbal_id, **kwargs)
virtual_servers = load_balancer['virtualServers']
for virtual_server in virtual_servers:
if virtual_server['id'] == service_group_id:
service_template = {
'enabled': int(enabled),
'port': port,
'ipAddressId': ip_address_id,
'healthChecks': [
{
'healthCheckTypeId': hc_type
}
],
'groupReferences': [
{
'weight': weight
}
]
}
services = virtual_server['serviceGroups'][0]['services']
services.append(service_template)
return self.lb_svc.editObject(load_balancer, id=loadbal_id) | [
"def",
"add_service",
"(",
"self",
",",
"loadbal_id",
",",
"service_group_id",
",",
"ip_address_id",
",",
"port",
"=",
"80",
",",
"enabled",
"=",
"True",
",",
"hc_type",
"=",
"21",
",",
"weight",
"=",
"1",
")",
":",
"kwargs",
"=",
"utils",
".",
"NestedDict",
"(",
"{",
"}",
")",
"kwargs",
"[",
"'mask'",
"]",
"=",
"(",
"'virtualServers['",
"'serviceGroups[services[groupReferences]]]'",
")",
"load_balancer",
"=",
"self",
".",
"lb_svc",
".",
"getObject",
"(",
"id",
"=",
"loadbal_id",
",",
"*",
"*",
"kwargs",
")",
"virtual_servers",
"=",
"load_balancer",
"[",
"'virtualServers'",
"]",
"for",
"virtual_server",
"in",
"virtual_servers",
":",
"if",
"virtual_server",
"[",
"'id'",
"]",
"==",
"service_group_id",
":",
"service_template",
"=",
"{",
"'enabled'",
":",
"int",
"(",
"enabled",
")",
",",
"'port'",
":",
"port",
",",
"'ipAddressId'",
":",
"ip_address_id",
",",
"'healthChecks'",
":",
"[",
"{",
"'healthCheckTypeId'",
":",
"hc_type",
"}",
"]",
",",
"'groupReferences'",
":",
"[",
"{",
"'weight'",
":",
"weight",
"}",
"]",
"}",
"services",
"=",
"virtual_server",
"[",
"'serviceGroups'",
"]",
"[",
"0",
"]",
"[",
"'services'",
"]",
"services",
".",
"append",
"(",
"service_template",
")",
"return",
"self",
".",
"lb_svc",
".",
"editObject",
"(",
"load_balancer",
",",
"id",
"=",
"loadbal_id",
")"
] | Adds a new service to the service group.
:param int loadbal_id: The id of the loadbal where the service resides
:param int service_group_id: The group to add the service to
:param int ip_address id: The ip address ID of the service
:param int port: the port of the service
:param bool enabled: Enable or disable the service
:param int hc_type: The health check type
:param int weight: the weight to give to the service | [
"Adds",
"a",
"new",
"service",
"to",
"the",
"service",
"group",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L216-L254 |
1,436 | softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.add_service_group | def add_service_group(self, lb_id, allocation=100, port=80,
routing_type=2, routing_method=10):
"""Adds a new service group to the load balancer.
:param int loadbal_id: The id of the loadbal where the service resides
:param int allocation: percent of connections to allocate toward the
group
:param int port: the port of the service group
:param int routing_type: the routing type to set on the service group
:param int routing_method: The routing method to set on the group
"""
mask = 'virtualServers[serviceGroups[services[groupReferences]]]'
load_balancer = self.lb_svc.getObject(id=lb_id, mask=mask)
service_template = {
'port': port,
'allocation': allocation,
'serviceGroups': [
{
'routingTypeId': routing_type,
'routingMethodId': routing_method
}
]
}
load_balancer['virtualServers'].append(service_template)
return self.lb_svc.editObject(load_balancer, id=lb_id) | python | def add_service_group(self, lb_id, allocation=100, port=80,
routing_type=2, routing_method=10):
"""Adds a new service group to the load balancer.
:param int loadbal_id: The id of the loadbal where the service resides
:param int allocation: percent of connections to allocate toward the
group
:param int port: the port of the service group
:param int routing_type: the routing type to set on the service group
:param int routing_method: The routing method to set on the group
"""
mask = 'virtualServers[serviceGroups[services[groupReferences]]]'
load_balancer = self.lb_svc.getObject(id=lb_id, mask=mask)
service_template = {
'port': port,
'allocation': allocation,
'serviceGroups': [
{
'routingTypeId': routing_type,
'routingMethodId': routing_method
}
]
}
load_balancer['virtualServers'].append(service_template)
return self.lb_svc.editObject(load_balancer, id=lb_id) | [
"def",
"add_service_group",
"(",
"self",
",",
"lb_id",
",",
"allocation",
"=",
"100",
",",
"port",
"=",
"80",
",",
"routing_type",
"=",
"2",
",",
"routing_method",
"=",
"10",
")",
":",
"mask",
"=",
"'virtualServers[serviceGroups[services[groupReferences]]]'",
"load_balancer",
"=",
"self",
".",
"lb_svc",
".",
"getObject",
"(",
"id",
"=",
"lb_id",
",",
"mask",
"=",
"mask",
")",
"service_template",
"=",
"{",
"'port'",
":",
"port",
",",
"'allocation'",
":",
"allocation",
",",
"'serviceGroups'",
":",
"[",
"{",
"'routingTypeId'",
":",
"routing_type",
",",
"'routingMethodId'",
":",
"routing_method",
"}",
"]",
"}",
"load_balancer",
"[",
"'virtualServers'",
"]",
".",
"append",
"(",
"service_template",
")",
"return",
"self",
".",
"lb_svc",
".",
"editObject",
"(",
"load_balancer",
",",
"id",
"=",
"lb_id",
")"
] | Adds a new service group to the load balancer.
:param int loadbal_id: The id of the loadbal where the service resides
:param int allocation: percent of connections to allocate toward the
group
:param int port: the port of the service group
:param int routing_type: the routing type to set on the service group
:param int routing_method: The routing method to set on the group | [
"Adds",
"a",
"new",
"service",
"group",
"to",
"the",
"load",
"balancer",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L256-L282 |
1,437 | softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.edit_service_group | def edit_service_group(self, loadbal_id, group_id, allocation=None,
port=None, routing_type=None, routing_method=None):
"""Edit an existing service group.
:param int loadbal_id: The id of the loadbal where the service resides
:param int group_id: The id of the service group
:param int allocation: the % of connections to allocate to the group
:param int port: the port of the service group
:param int routing_type: the routing type to set on the service group
:param int routing_method: The routing method to set on the group
"""
mask = 'virtualServers[serviceGroups[services[groupReferences]]]'
load_balancer = self.lb_svc.getObject(id=loadbal_id, mask=mask)
virtual_servers = load_balancer['virtualServers']
for virtual_server in virtual_servers:
if virtual_server['id'] == group_id:
service_group = virtual_server['serviceGroups'][0]
if allocation is not None:
virtual_server['allocation'] = allocation
if port is not None:
virtual_server['port'] = port
if routing_type is not None:
service_group['routingTypeId'] = routing_type
if routing_method is not None:
service_group['routingMethodId'] = routing_method
break
return self.lb_svc.editObject(load_balancer, id=loadbal_id) | python | def edit_service_group(self, loadbal_id, group_id, allocation=None,
port=None, routing_type=None, routing_method=None):
"""Edit an existing service group.
:param int loadbal_id: The id of the loadbal where the service resides
:param int group_id: The id of the service group
:param int allocation: the % of connections to allocate to the group
:param int port: the port of the service group
:param int routing_type: the routing type to set on the service group
:param int routing_method: The routing method to set on the group
"""
mask = 'virtualServers[serviceGroups[services[groupReferences]]]'
load_balancer = self.lb_svc.getObject(id=loadbal_id, mask=mask)
virtual_servers = load_balancer['virtualServers']
for virtual_server in virtual_servers:
if virtual_server['id'] == group_id:
service_group = virtual_server['serviceGroups'][0]
if allocation is not None:
virtual_server['allocation'] = allocation
if port is not None:
virtual_server['port'] = port
if routing_type is not None:
service_group['routingTypeId'] = routing_type
if routing_method is not None:
service_group['routingMethodId'] = routing_method
break
return self.lb_svc.editObject(load_balancer, id=loadbal_id) | [
"def",
"edit_service_group",
"(",
"self",
",",
"loadbal_id",
",",
"group_id",
",",
"allocation",
"=",
"None",
",",
"port",
"=",
"None",
",",
"routing_type",
"=",
"None",
",",
"routing_method",
"=",
"None",
")",
":",
"mask",
"=",
"'virtualServers[serviceGroups[services[groupReferences]]]'",
"load_balancer",
"=",
"self",
".",
"lb_svc",
".",
"getObject",
"(",
"id",
"=",
"loadbal_id",
",",
"mask",
"=",
"mask",
")",
"virtual_servers",
"=",
"load_balancer",
"[",
"'virtualServers'",
"]",
"for",
"virtual_server",
"in",
"virtual_servers",
":",
"if",
"virtual_server",
"[",
"'id'",
"]",
"==",
"group_id",
":",
"service_group",
"=",
"virtual_server",
"[",
"'serviceGroups'",
"]",
"[",
"0",
"]",
"if",
"allocation",
"is",
"not",
"None",
":",
"virtual_server",
"[",
"'allocation'",
"]",
"=",
"allocation",
"if",
"port",
"is",
"not",
"None",
":",
"virtual_server",
"[",
"'port'",
"]",
"=",
"port",
"if",
"routing_type",
"is",
"not",
"None",
":",
"service_group",
"[",
"'routingTypeId'",
"]",
"=",
"routing_type",
"if",
"routing_method",
"is",
"not",
"None",
":",
"service_group",
"[",
"'routingMethodId'",
"]",
"=",
"routing_method",
"break",
"return",
"self",
".",
"lb_svc",
".",
"editObject",
"(",
"load_balancer",
",",
"id",
"=",
"loadbal_id",
")"
] | Edit an existing service group.
:param int loadbal_id: The id of the loadbal where the service resides
:param int group_id: The id of the service group
:param int allocation: the % of connections to allocate to the group
:param int port: the port of the service group
:param int routing_type: the routing type to set on the service group
:param int routing_method: The routing method to set on the group | [
"Edit",
"an",
"existing",
"service",
"group",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L284-L314 |
1,438 | softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | LoadBalancerManager.reset_service_group | def reset_service_group(self, loadbal_id, group_id):
"""Resets all the connections on the service group.
:param int loadbal_id: The id of the loadbal
:param int group_id: The id of the service group to reset
"""
_filter = {'virtualServers': {'id': utils.query_filter(group_id)}}
virtual_servers = self.lb_svc.getVirtualServers(id=loadbal_id,
filter=_filter,
mask='serviceGroups')
actual_id = virtual_servers[0]['serviceGroups'][0]['id']
svc = self.client['Network_Application_Delivery_Controller'
'_LoadBalancer_Service_Group']
return svc.kickAllConnections(id=actual_id) | python | def reset_service_group(self, loadbal_id, group_id):
"""Resets all the connections on the service group.
:param int loadbal_id: The id of the loadbal
:param int group_id: The id of the service group to reset
"""
_filter = {'virtualServers': {'id': utils.query_filter(group_id)}}
virtual_servers = self.lb_svc.getVirtualServers(id=loadbal_id,
filter=_filter,
mask='serviceGroups')
actual_id = virtual_servers[0]['serviceGroups'][0]['id']
svc = self.client['Network_Application_Delivery_Controller'
'_LoadBalancer_Service_Group']
return svc.kickAllConnections(id=actual_id) | [
"def",
"reset_service_group",
"(",
"self",
",",
"loadbal_id",
",",
"group_id",
")",
":",
"_filter",
"=",
"{",
"'virtualServers'",
":",
"{",
"'id'",
":",
"utils",
".",
"query_filter",
"(",
"group_id",
")",
"}",
"}",
"virtual_servers",
"=",
"self",
".",
"lb_svc",
".",
"getVirtualServers",
"(",
"id",
"=",
"loadbal_id",
",",
"filter",
"=",
"_filter",
",",
"mask",
"=",
"'serviceGroups'",
")",
"actual_id",
"=",
"virtual_servers",
"[",
"0",
"]",
"[",
"'serviceGroups'",
"]",
"[",
"0",
"]",
"[",
"'id'",
"]",
"svc",
"=",
"self",
".",
"client",
"[",
"'Network_Application_Delivery_Controller'",
"'_LoadBalancer_Service_Group'",
"]",
"return",
"svc",
".",
"kickAllConnections",
"(",
"id",
"=",
"actual_id",
")"
] | Resets all the connections on the service group.
:param int loadbal_id: The id of the loadbal
:param int group_id: The id of the service group to reset | [
"Resets",
"all",
"the",
"connections",
"on",
"the",
"service",
"group",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L316-L331 |
1,439 | softlayer/softlayer-python | SoftLayer/CLI/image/detail.py | cli | def cli(env, identifier):
"""Get details for an image."""
image_mgr = SoftLayer.ImageManager(env.client)
image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')
image = image_mgr.get_image(image_id, mask=image_mod.DETAIL_MASK)
disk_space = 0
datacenters = []
for child in image.get('children'):
disk_space = int(child.get('blockDevicesDiskSpaceTotal', 0))
if child.get('datacenter'):
datacenters.append(utils.lookup(child, 'datacenter', 'name'))
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', image['id']])
table.add_row(['global_identifier',
image.get('globalIdentifier', formatting.blank())])
table.add_row(['name', image['name'].strip()])
table.add_row(['status', formatting.FormattedItem(
utils.lookup(image, 'status', 'keyname'),
utils.lookup(image, 'status', 'name'),
)])
table.add_row([
'active_transaction',
formatting.transaction_status(image.get('transaction')),
])
table.add_row(['account', image.get('accountId', formatting.blank())])
table.add_row(['visibility',
image_mod.PUBLIC_TYPE if image['publicFlag']
else image_mod.PRIVATE_TYPE])
table.add_row(['type',
formatting.FormattedItem(
utils.lookup(image, 'imageType', 'keyName'),
utils.lookup(image, 'imageType', 'name'),
)])
table.add_row(['flex', image.get('flexImageFlag')])
table.add_row(['note', image.get('note')])
table.add_row(['created', image.get('createDate')])
table.add_row(['disk_space', formatting.b_to_gb(disk_space)])
table.add_row(['datacenters', formatting.listing(sorted(datacenters),
separator=',')])
env.fout(table) | python | def cli(env, identifier):
"""Get details for an image."""
image_mgr = SoftLayer.ImageManager(env.client)
image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')
image = image_mgr.get_image(image_id, mask=image_mod.DETAIL_MASK)
disk_space = 0
datacenters = []
for child in image.get('children'):
disk_space = int(child.get('blockDevicesDiskSpaceTotal', 0))
if child.get('datacenter'):
datacenters.append(utils.lookup(child, 'datacenter', 'name'))
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['id', image['id']])
table.add_row(['global_identifier',
image.get('globalIdentifier', formatting.blank())])
table.add_row(['name', image['name'].strip()])
table.add_row(['status', formatting.FormattedItem(
utils.lookup(image, 'status', 'keyname'),
utils.lookup(image, 'status', 'name'),
)])
table.add_row([
'active_transaction',
formatting.transaction_status(image.get('transaction')),
])
table.add_row(['account', image.get('accountId', formatting.blank())])
table.add_row(['visibility',
image_mod.PUBLIC_TYPE if image['publicFlag']
else image_mod.PRIVATE_TYPE])
table.add_row(['type',
formatting.FormattedItem(
utils.lookup(image, 'imageType', 'keyName'),
utils.lookup(image, 'imageType', 'name'),
)])
table.add_row(['flex', image.get('flexImageFlag')])
table.add_row(['note', image.get('note')])
table.add_row(['created', image.get('createDate')])
table.add_row(['disk_space', formatting.b_to_gb(disk_space)])
table.add_row(['datacenters', formatting.listing(sorted(datacenters),
separator=',')])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"image_mgr",
"=",
"SoftLayer",
".",
"ImageManager",
"(",
"env",
".",
"client",
")",
"image_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"image_mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'image'",
")",
"image",
"=",
"image_mgr",
".",
"get_image",
"(",
"image_id",
",",
"mask",
"=",
"image_mod",
".",
"DETAIL_MASK",
")",
"disk_space",
"=",
"0",
"datacenters",
"=",
"[",
"]",
"for",
"child",
"in",
"image",
".",
"get",
"(",
"'children'",
")",
":",
"disk_space",
"=",
"int",
"(",
"child",
".",
"get",
"(",
"'blockDevicesDiskSpaceTotal'",
",",
"0",
")",
")",
"if",
"child",
".",
"get",
"(",
"'datacenter'",
")",
":",
"datacenters",
".",
"append",
"(",
"utils",
".",
"lookup",
"(",
"child",
",",
"'datacenter'",
",",
"'name'",
")",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'id'",
",",
"image",
"[",
"'id'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'global_identifier'",
",",
"image",
".",
"get",
"(",
"'globalIdentifier'",
",",
"formatting",
".",
"blank",
"(",
")",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'name'",
",",
"image",
"[",
"'name'",
"]",
".",
"strip",
"(",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'status'",
",",
"formatting",
".",
"FormattedItem",
"(",
"utils",
".",
"lookup",
"(",
"image",
",",
"'status'",
",",
"'keyname'",
")",
",",
"utils",
".",
"lookup",
"(",
"image",
",",
"'status'",
",",
"'name'",
")",
",",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'active_transaction'",
",",
"formatting",
".",
"transaction_status",
"(",
"image",
".",
"get",
"(",
"'transaction'",
")",
")",
",",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'account'",
",",
"image",
".",
"get",
"(",
"'accountId'",
",",
"formatting",
".",
"blank",
"(",
")",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'visibility'",
",",
"image_mod",
".",
"PUBLIC_TYPE",
"if",
"image",
"[",
"'publicFlag'",
"]",
"else",
"image_mod",
".",
"PRIVATE_TYPE",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'type'",
",",
"formatting",
".",
"FormattedItem",
"(",
"utils",
".",
"lookup",
"(",
"image",
",",
"'imageType'",
",",
"'keyName'",
")",
",",
"utils",
".",
"lookup",
"(",
"image",
",",
"'imageType'",
",",
"'name'",
")",
",",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'flex'",
",",
"image",
".",
"get",
"(",
"'flexImageFlag'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'note'",
",",
"image",
".",
"get",
"(",
"'note'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'created'",
",",
"image",
".",
"get",
"(",
"'createDate'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'disk_space'",
",",
"formatting",
".",
"b_to_gb",
"(",
"disk_space",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'datacenters'",
",",
"formatting",
".",
"listing",
"(",
"sorted",
"(",
"datacenters",
")",
",",
"separator",
"=",
"','",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | Get details for an image. | [
"Get",
"details",
"for",
"an",
"image",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/image/detail.py#L17-L63 |
1,440 | softlayer/softlayer-python | SoftLayer/CLI/file/snapshot/enable.py | cli | def cli(env, volume_id, schedule_type, retention_count,
minute, hour, day_of_week):
"""Enables snapshots for a given volume on the specified schedule"""
file_manager = SoftLayer.FileStorageManager(env.client)
valid_schedule_types = {'INTERVAL', 'HOURLY', 'DAILY', 'WEEKLY'}
valid_days = {'SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY',
'FRIDAY', 'SATURDAY'}
if schedule_type not in valid_schedule_types:
raise exceptions.CLIAbort(
'--schedule-type must be INTERVAL, HOURLY, ' +
'DAILY, or WEEKLY, not ' + schedule_type)
if schedule_type == 'INTERVAL' and (minute < 30 or minute > 59):
raise exceptions.CLIAbort(
'--minute value must be between 30 and 59')
if minute < 0 or minute > 59:
raise exceptions.CLIAbort(
'--minute value must be between 0 and 59')
if hour < 0 or hour > 23:
raise exceptions.CLIAbort(
'--hour value must be between 0 and 23')
if day_of_week not in valid_days:
raise exceptions.CLIAbort(
'--day_of_week value must be a valid day (ex: SUNDAY)')
enabled = file_manager.enable_snapshots(volume_id, schedule_type,
retention_count, minute,
hour, day_of_week)
if enabled:
click.echo('%s snapshots have been enabled for volume %s'
% (schedule_type, volume_id)) | python | def cli(env, volume_id, schedule_type, retention_count,
minute, hour, day_of_week):
"""Enables snapshots for a given volume on the specified schedule"""
file_manager = SoftLayer.FileStorageManager(env.client)
valid_schedule_types = {'INTERVAL', 'HOURLY', 'DAILY', 'WEEKLY'}
valid_days = {'SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY',
'FRIDAY', 'SATURDAY'}
if schedule_type not in valid_schedule_types:
raise exceptions.CLIAbort(
'--schedule-type must be INTERVAL, HOURLY, ' +
'DAILY, or WEEKLY, not ' + schedule_type)
if schedule_type == 'INTERVAL' and (minute < 30 or minute > 59):
raise exceptions.CLIAbort(
'--minute value must be between 30 and 59')
if minute < 0 or minute > 59:
raise exceptions.CLIAbort(
'--minute value must be between 0 and 59')
if hour < 0 or hour > 23:
raise exceptions.CLIAbort(
'--hour value must be between 0 and 23')
if day_of_week not in valid_days:
raise exceptions.CLIAbort(
'--day_of_week value must be a valid day (ex: SUNDAY)')
enabled = file_manager.enable_snapshots(volume_id, schedule_type,
retention_count, minute,
hour, day_of_week)
if enabled:
click.echo('%s snapshots have been enabled for volume %s'
% (schedule_type, volume_id)) | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"schedule_type",
",",
"retention_count",
",",
"minute",
",",
"hour",
",",
"day_of_week",
")",
":",
"file_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"valid_schedule_types",
"=",
"{",
"'INTERVAL'",
",",
"'HOURLY'",
",",
"'DAILY'",
",",
"'WEEKLY'",
"}",
"valid_days",
"=",
"{",
"'SUNDAY'",
",",
"'MONDAY'",
",",
"'TUESDAY'",
",",
"'WEDNESDAY'",
",",
"'THURSDAY'",
",",
"'FRIDAY'",
",",
"'SATURDAY'",
"}",
"if",
"schedule_type",
"not",
"in",
"valid_schedule_types",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'--schedule-type must be INTERVAL, HOURLY, '",
"+",
"'DAILY, or WEEKLY, not '",
"+",
"schedule_type",
")",
"if",
"schedule_type",
"==",
"'INTERVAL'",
"and",
"(",
"minute",
"<",
"30",
"or",
"minute",
">",
"59",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'--minute value must be between 30 and 59'",
")",
"if",
"minute",
"<",
"0",
"or",
"minute",
">",
"59",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'--minute value must be between 0 and 59'",
")",
"if",
"hour",
"<",
"0",
"or",
"hour",
">",
"23",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'--hour value must be between 0 and 23'",
")",
"if",
"day_of_week",
"not",
"in",
"valid_days",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'--day_of_week value must be a valid day (ex: SUNDAY)'",
")",
"enabled",
"=",
"file_manager",
".",
"enable_snapshots",
"(",
"volume_id",
",",
"schedule_type",
",",
"retention_count",
",",
"minute",
",",
"hour",
",",
"day_of_week",
")",
"if",
"enabled",
":",
"click",
".",
"echo",
"(",
"'%s snapshots have been enabled for volume %s'",
"%",
"(",
"schedule_type",
",",
"volume_id",
")",
")"
] | Enables snapshots for a given volume on the specified schedule | [
"Enables",
"snapshots",
"for",
"a",
"given",
"volume",
"on",
"the",
"specified",
"schedule"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/snapshot/enable.py#L28-L61 |
1,441 | softlayer/softlayer-python | SoftLayer/managers/account.py | AccountManager.get_upcoming_events | def get_upcoming_events(self):
"""Retreives a list of Notification_Occurrence_Events that have not ended yet
:return: SoftLayer_Notification_Occurrence_Event
"""
mask = "mask[id, subject, startDate, endDate, statusCode, acknowledgedFlag, impactedResourceCount, updateCount]"
_filter = {
'endDate': {
'operation': '> sysdate'
},
'startDate': {
'operation': 'orderBy',
'options': [{
'name': 'sort',
'value': ['ASC']
}]
}
}
return self.client.call('Notification_Occurrence_Event', 'getAllObjects', filter=_filter, mask=mask, iter=True) | python | def get_upcoming_events(self):
"""Retreives a list of Notification_Occurrence_Events that have not ended yet
:return: SoftLayer_Notification_Occurrence_Event
"""
mask = "mask[id, subject, startDate, endDate, statusCode, acknowledgedFlag, impactedResourceCount, updateCount]"
_filter = {
'endDate': {
'operation': '> sysdate'
},
'startDate': {
'operation': 'orderBy',
'options': [{
'name': 'sort',
'value': ['ASC']
}]
}
}
return self.client.call('Notification_Occurrence_Event', 'getAllObjects', filter=_filter, mask=mask, iter=True) | [
"def",
"get_upcoming_events",
"(",
"self",
")",
":",
"mask",
"=",
"\"mask[id, subject, startDate, endDate, statusCode, acknowledgedFlag, impactedResourceCount, updateCount]\"",
"_filter",
"=",
"{",
"'endDate'",
":",
"{",
"'operation'",
":",
"'> sysdate'",
"}",
",",
"'startDate'",
":",
"{",
"'operation'",
":",
"'orderBy'",
",",
"'options'",
":",
"[",
"{",
"'name'",
":",
"'sort'",
",",
"'value'",
":",
"[",
"'ASC'",
"]",
"}",
"]",
"}",
"}",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'Notification_Occurrence_Event'",
",",
"'getAllObjects'",
",",
"filter",
"=",
"_filter",
",",
"mask",
"=",
"mask",
",",
"iter",
"=",
"True",
")"
] | Retreives a list of Notification_Occurrence_Events that have not ended yet
:return: SoftLayer_Notification_Occurrence_Event | [
"Retreives",
"a",
"list",
"of",
"Notification_Occurrence_Events",
"that",
"have",
"not",
"ended",
"yet"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/account.py#L50-L68 |
1,442 | softlayer/softlayer-python | SoftLayer/managers/account.py | AccountManager.get_invoices | def get_invoices(self, limit=50, closed=False, get_all=False):
"""Gets an accounts invoices.
:param int limit: Number of invoices to get back in a single call.
:param bool closed: If True, will also get CLOSED invoices
:param bool get_all: If True, will paginate through invoices until all have been retrieved.
:return: Billing_Invoice
"""
mask = "mask[invoiceTotalAmount, itemCount]"
_filter = {
'invoices': {
'createDate': {
'operation': 'orderBy',
'options': [{
'name': 'sort',
'value': ['DESC']
}]
},
'statusCode': {'operation': 'OPEN'},
}
}
if closed:
del _filter['invoices']['statusCode']
return self.client.call('Account', 'getInvoices', mask=mask, filter=_filter, iter=get_all, limit=limit) | python | def get_invoices(self, limit=50, closed=False, get_all=False):
"""Gets an accounts invoices.
:param int limit: Number of invoices to get back in a single call.
:param bool closed: If True, will also get CLOSED invoices
:param bool get_all: If True, will paginate through invoices until all have been retrieved.
:return: Billing_Invoice
"""
mask = "mask[invoiceTotalAmount, itemCount]"
_filter = {
'invoices': {
'createDate': {
'operation': 'orderBy',
'options': [{
'name': 'sort',
'value': ['DESC']
}]
},
'statusCode': {'operation': 'OPEN'},
}
}
if closed:
del _filter['invoices']['statusCode']
return self.client.call('Account', 'getInvoices', mask=mask, filter=_filter, iter=get_all, limit=limit) | [
"def",
"get_invoices",
"(",
"self",
",",
"limit",
"=",
"50",
",",
"closed",
"=",
"False",
",",
"get_all",
"=",
"False",
")",
":",
"mask",
"=",
"\"mask[invoiceTotalAmount, itemCount]\"",
"_filter",
"=",
"{",
"'invoices'",
":",
"{",
"'createDate'",
":",
"{",
"'operation'",
":",
"'orderBy'",
",",
"'options'",
":",
"[",
"{",
"'name'",
":",
"'sort'",
",",
"'value'",
":",
"[",
"'DESC'",
"]",
"}",
"]",
"}",
",",
"'statusCode'",
":",
"{",
"'operation'",
":",
"'OPEN'",
"}",
",",
"}",
"}",
"if",
"closed",
":",
"del",
"_filter",
"[",
"'invoices'",
"]",
"[",
"'statusCode'",
"]",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'Account'",
",",
"'getInvoices'",
",",
"mask",
"=",
"mask",
",",
"filter",
"=",
"_filter",
",",
"iter",
"=",
"get_all",
",",
"limit",
"=",
"limit",
")"
] | Gets an accounts invoices.
:param int limit: Number of invoices to get back in a single call.
:param bool closed: If True, will also get CLOSED invoices
:param bool get_all: If True, will paginate through invoices until all have been retrieved.
:return: Billing_Invoice | [
"Gets",
"an",
"accounts",
"invoices",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/account.py#L94-L118 |
1,443 | softlayer/softlayer-python | SoftLayer/CLI/loadbal/create_options.py | cli | def cli(env):
"""Get price options to create a load balancer with."""
mgr = SoftLayer.LoadBalancerManager(env.client)
table = formatting.Table(['price_id', 'capacity', 'description', 'price'])
table.sortby = 'price'
table.align['price'] = 'r'
table.align['capacity'] = 'r'
table.align['id'] = 'r'
packages = mgr.get_lb_pkgs()
for package in packages:
table.add_row([
package['prices'][0]['id'],
package.get('capacity'),
package['description'],
'%.2f' % float(package['prices'][0]['recurringFee'])
])
env.fout(table) | python | def cli(env):
"""Get price options to create a load balancer with."""
mgr = SoftLayer.LoadBalancerManager(env.client)
table = formatting.Table(['price_id', 'capacity', 'description', 'price'])
table.sortby = 'price'
table.align['price'] = 'r'
table.align['capacity'] = 'r'
table.align['id'] = 'r'
packages = mgr.get_lb_pkgs()
for package in packages:
table.add_row([
package['prices'][0]['id'],
package.get('capacity'),
package['description'],
'%.2f' % float(package['prices'][0]['recurringFee'])
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"LoadBalancerManager",
"(",
"env",
".",
"client",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'price_id'",
",",
"'capacity'",
",",
"'description'",
",",
"'price'",
"]",
")",
"table",
".",
"sortby",
"=",
"'price'",
"table",
".",
"align",
"[",
"'price'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'capacity'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'id'",
"]",
"=",
"'r'",
"packages",
"=",
"mgr",
".",
"get_lb_pkgs",
"(",
")",
"for",
"package",
"in",
"packages",
":",
"table",
".",
"add_row",
"(",
"[",
"package",
"[",
"'prices'",
"]",
"[",
"0",
"]",
"[",
"'id'",
"]",
",",
"package",
".",
"get",
"(",
"'capacity'",
")",
",",
"package",
"[",
"'description'",
"]",
",",
"'%.2f'",
"%",
"float",
"(",
"package",
"[",
"'prices'",
"]",
"[",
"0",
"]",
"[",
"'recurringFee'",
"]",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | Get price options to create a load balancer with. | [
"Get",
"price",
"options",
"to",
"create",
"a",
"load",
"balancer",
"with",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/create_options.py#L13-L35 |
1,444 | softlayer/softlayer-python | SoftLayer/CLI/virt/credentials.py | cli | def cli(env, identifier):
"""List virtual server credentials."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
instance = vsi.get_instance(vs_id)
table = formatting.Table(['username', 'password'])
for item in instance['operatingSystem']['passwords']:
table.add_row([item['username'], item['password']])
env.fout(table) | python | def cli(env, identifier):
"""List virtual server credentials."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
instance = vsi.get_instance(vs_id)
table = formatting.Table(['username', 'password'])
for item in instance['operatingSystem']['passwords']:
table.add_row([item['username'], item['password']])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
"identifier",
",",
"'VS'",
")",
"instance",
"=",
"vsi",
".",
"get_instance",
"(",
"vs_id",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'username'",
",",
"'password'",
"]",
")",
"for",
"item",
"in",
"instance",
"[",
"'operatingSystem'",
"]",
"[",
"'passwords'",
"]",
":",
"table",
".",
"add_row",
"(",
"[",
"item",
"[",
"'username'",
"]",
",",
"item",
"[",
"'password'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List virtual server credentials. | [
"List",
"virtual",
"server",
"credentials",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/credentials.py#L15-L25 |
1,445 | softlayer/softlayer-python | SoftLayer/CLI/dns/record_edit.py | cli | def cli(env, zone_id, by_record, by_id, data, ttl):
"""Update DNS record."""
manager = SoftLayer.DNSManager(env.client)
zone_id = helpers.resolve_id(manager.resolve_ids, zone_id, name='zone')
results = manager.get_records(zone_id, host=by_record)
for result in results:
if by_id and str(result['id']) != by_id:
continue
result['data'] = data or result['data']
result['ttl'] = ttl or result['ttl']
manager.edit_record(result) | python | def cli(env, zone_id, by_record, by_id, data, ttl):
"""Update DNS record."""
manager = SoftLayer.DNSManager(env.client)
zone_id = helpers.resolve_id(manager.resolve_ids, zone_id, name='zone')
results = manager.get_records(zone_id, host=by_record)
for result in results:
if by_id and str(result['id']) != by_id:
continue
result['data'] = data or result['data']
result['ttl'] = ttl or result['ttl']
manager.edit_record(result) | [
"def",
"cli",
"(",
"env",
",",
"zone_id",
",",
"by_record",
",",
"by_id",
",",
"data",
",",
"ttl",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"DNSManager",
"(",
"env",
".",
"client",
")",
"zone_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"manager",
".",
"resolve_ids",
",",
"zone_id",
",",
"name",
"=",
"'zone'",
")",
"results",
"=",
"manager",
".",
"get_records",
"(",
"zone_id",
",",
"host",
"=",
"by_record",
")",
"for",
"result",
"in",
"results",
":",
"if",
"by_id",
"and",
"str",
"(",
"result",
"[",
"'id'",
"]",
")",
"!=",
"by_id",
":",
"continue",
"result",
"[",
"'data'",
"]",
"=",
"data",
"or",
"result",
"[",
"'data'",
"]",
"result",
"[",
"'ttl'",
"]",
"=",
"ttl",
"or",
"result",
"[",
"'ttl'",
"]",
"manager",
".",
"edit_record",
"(",
"result",
")"
] | Update DNS record. | [
"Update",
"DNS",
"record",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dns/record_edit.py#L21-L33 |
1,446 | softlayer/softlayer-python | SoftLayer/CLI/hardware/ready.py | cli | def cli(env, identifier, wait):
"""Check if a server is ready."""
compute = SoftLayer.HardwareManager(env.client)
compute_id = helpers.resolve_id(compute.resolve_ids, identifier,
'hardware')
ready = compute.wait_for_ready(compute_id, wait)
if ready:
env.fout("READY")
else:
raise exceptions.CLIAbort("Server %s not ready" % compute_id) | python | def cli(env, identifier, wait):
"""Check if a server is ready."""
compute = SoftLayer.HardwareManager(env.client)
compute_id = helpers.resolve_id(compute.resolve_ids, identifier,
'hardware')
ready = compute.wait_for_ready(compute_id, wait)
if ready:
env.fout("READY")
else:
raise exceptions.CLIAbort("Server %s not ready" % compute_id) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"wait",
")",
":",
"compute",
"=",
"SoftLayer",
".",
"HardwareManager",
"(",
"env",
".",
"client",
")",
"compute_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"compute",
".",
"resolve_ids",
",",
"identifier",
",",
"'hardware'",
")",
"ready",
"=",
"compute",
".",
"wait_for_ready",
"(",
"compute_id",
",",
"wait",
")",
"if",
"ready",
":",
"env",
".",
"fout",
"(",
"\"READY\"",
")",
"else",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Server %s not ready\"",
"%",
"compute_id",
")"
] | Check if a server is ready. | [
"Check",
"if",
"a",
"server",
"is",
"ready",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/ready.py#L17-L27 |
1,447 | softlayer/softlayer-python | SoftLayer/CLI/ticket/summary.py | cli | def cli(env):
"""Summary info about tickets."""
mask = ('openTicketCount, closedTicketCount, '
'openBillingTicketCount, openOtherTicketCount, '
'openSalesTicketCount, openSupportTicketCount, '
'openAccountingTicketCount')
account = env.client['Account'].getObject(mask=mask)
table = formatting.Table(['Status', 'count'])
nested = formatting.Table(['Type', 'count'])
nested.add_row(['Accounting',
account['openAccountingTicketCount']])
nested.add_row(['Billing', account['openBillingTicketCount']])
nested.add_row(['Sales', account['openSalesTicketCount']])
nested.add_row(['Support', account['openSupportTicketCount']])
nested.add_row(['Other', account['openOtherTicketCount']])
nested.add_row(['Total', account['openTicketCount']])
table.add_row(['Open', nested])
table.add_row(['Closed', account['closedTicketCount']])
env.fout(table) | python | def cli(env):
"""Summary info about tickets."""
mask = ('openTicketCount, closedTicketCount, '
'openBillingTicketCount, openOtherTicketCount, '
'openSalesTicketCount, openSupportTicketCount, '
'openAccountingTicketCount')
account = env.client['Account'].getObject(mask=mask)
table = formatting.Table(['Status', 'count'])
nested = formatting.Table(['Type', 'count'])
nested.add_row(['Accounting',
account['openAccountingTicketCount']])
nested.add_row(['Billing', account['openBillingTicketCount']])
nested.add_row(['Sales', account['openSalesTicketCount']])
nested.add_row(['Support', account['openSupportTicketCount']])
nested.add_row(['Other', account['openOtherTicketCount']])
nested.add_row(['Total', account['openTicketCount']])
table.add_row(['Open', nested])
table.add_row(['Closed', account['closedTicketCount']])
env.fout(table) | [
"def",
"cli",
"(",
"env",
")",
":",
"mask",
"=",
"(",
"'openTicketCount, closedTicketCount, '",
"'openBillingTicketCount, openOtherTicketCount, '",
"'openSalesTicketCount, openSupportTicketCount, '",
"'openAccountingTicketCount'",
")",
"account",
"=",
"env",
".",
"client",
"[",
"'Account'",
"]",
".",
"getObject",
"(",
"mask",
"=",
"mask",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Status'",
",",
"'count'",
"]",
")",
"nested",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Type'",
",",
"'count'",
"]",
")",
"nested",
".",
"add_row",
"(",
"[",
"'Accounting'",
",",
"account",
"[",
"'openAccountingTicketCount'",
"]",
"]",
")",
"nested",
".",
"add_row",
"(",
"[",
"'Billing'",
",",
"account",
"[",
"'openBillingTicketCount'",
"]",
"]",
")",
"nested",
".",
"add_row",
"(",
"[",
"'Sales'",
",",
"account",
"[",
"'openSalesTicketCount'",
"]",
"]",
")",
"nested",
".",
"add_row",
"(",
"[",
"'Support'",
",",
"account",
"[",
"'openSupportTicketCount'",
"]",
"]",
")",
"nested",
".",
"add_row",
"(",
"[",
"'Other'",
",",
"account",
"[",
"'openOtherTicketCount'",
"]",
"]",
")",
"nested",
".",
"add_row",
"(",
"[",
"'Total'",
",",
"account",
"[",
"'openTicketCount'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Open'",
",",
"nested",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Closed'",
",",
"account",
"[",
"'closedTicketCount'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | Summary info about tickets. | [
"Summary",
"info",
"about",
"tickets",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ticket/summary.py#L12-L33 |
1,448 | softlayer/softlayer-python | SoftLayer/CLI/globalip/list.py | cli | def cli(env, ip_version):
"""List all global IPs."""
mgr = SoftLayer.NetworkManager(env.client)
table = formatting.Table(['id', 'ip', 'assigned', 'target'])
version = None
if ip_version == 'v4':
version = 4
elif ip_version == 'v6':
version = 6
ips = mgr.list_global_ips(version=version)
for ip_address in ips:
assigned = 'No'
target = 'None'
if ip_address.get('destinationIpAddress'):
dest = ip_address['destinationIpAddress']
assigned = 'Yes'
target = dest['ipAddress']
virtual_guest = dest.get('virtualGuest')
if virtual_guest:
target += (' (%s)'
% virtual_guest['fullyQualifiedDomainName'])
elif ip_address['destinationIpAddress'].get('hardware'):
target += (' (%s)'
% dest['hardware']['fullyQualifiedDomainName'])
table.add_row([ip_address['id'],
ip_address['ipAddress']['ipAddress'],
assigned,
target])
env.fout(table) | python | def cli(env, ip_version):
"""List all global IPs."""
mgr = SoftLayer.NetworkManager(env.client)
table = formatting.Table(['id', 'ip', 'assigned', 'target'])
version = None
if ip_version == 'v4':
version = 4
elif ip_version == 'v6':
version = 6
ips = mgr.list_global_ips(version=version)
for ip_address in ips:
assigned = 'No'
target = 'None'
if ip_address.get('destinationIpAddress'):
dest = ip_address['destinationIpAddress']
assigned = 'Yes'
target = dest['ipAddress']
virtual_guest = dest.get('virtualGuest')
if virtual_guest:
target += (' (%s)'
% virtual_guest['fullyQualifiedDomainName'])
elif ip_address['destinationIpAddress'].get('hardware'):
target += (' (%s)'
% dest['hardware']['fullyQualifiedDomainName'])
table.add_row([ip_address['id'],
ip_address['ipAddress']['ipAddress'],
assigned,
target])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"ip_version",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'ip'",
",",
"'assigned'",
",",
"'target'",
"]",
")",
"version",
"=",
"None",
"if",
"ip_version",
"==",
"'v4'",
":",
"version",
"=",
"4",
"elif",
"ip_version",
"==",
"'v6'",
":",
"version",
"=",
"6",
"ips",
"=",
"mgr",
".",
"list_global_ips",
"(",
"version",
"=",
"version",
")",
"for",
"ip_address",
"in",
"ips",
":",
"assigned",
"=",
"'No'",
"target",
"=",
"'None'",
"if",
"ip_address",
".",
"get",
"(",
"'destinationIpAddress'",
")",
":",
"dest",
"=",
"ip_address",
"[",
"'destinationIpAddress'",
"]",
"assigned",
"=",
"'Yes'",
"target",
"=",
"dest",
"[",
"'ipAddress'",
"]",
"virtual_guest",
"=",
"dest",
".",
"get",
"(",
"'virtualGuest'",
")",
"if",
"virtual_guest",
":",
"target",
"+=",
"(",
"' (%s)'",
"%",
"virtual_guest",
"[",
"'fullyQualifiedDomainName'",
"]",
")",
"elif",
"ip_address",
"[",
"'destinationIpAddress'",
"]",
".",
"get",
"(",
"'hardware'",
")",
":",
"target",
"+=",
"(",
"' (%s)'",
"%",
"dest",
"[",
"'hardware'",
"]",
"[",
"'fullyQualifiedDomainName'",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"ip_address",
"[",
"'id'",
"]",
",",
"ip_address",
"[",
"'ipAddress'",
"]",
"[",
"'ipAddress'",
"]",
",",
"assigned",
",",
"target",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List all global IPs. | [
"List",
"all",
"global",
"IPs",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/globalip/list.py#L16-L50 |
1,449 | softlayer/softlayer-python | SoftLayer/CLI/globalip/cancel.py | cli | def cli(env, identifier):
"""Cancel global IP."""
mgr = SoftLayer.NetworkManager(env.client)
global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier,
name='global ip')
if not (env.skip_confirmations or formatting.no_going_back(global_ip_id)):
raise exceptions.CLIAbort('Aborted')
mgr.cancel_global_ip(global_ip_id) | python | def cli(env, identifier):
"""Cancel global IP."""
mgr = SoftLayer.NetworkManager(env.client)
global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier,
name='global ip')
if not (env.skip_confirmations or formatting.no_going_back(global_ip_id)):
raise exceptions.CLIAbort('Aborted')
mgr.cancel_global_ip(global_ip_id) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"global_ip_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_global_ip_ids",
",",
"identifier",
",",
"name",
"=",
"'global ip'",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"no_going_back",
"(",
"global_ip_id",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted'",
")",
"mgr",
".",
"cancel_global_ip",
"(",
"global_ip_id",
")"
] | Cancel global IP. | [
"Cancel",
"global",
"IP",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/globalip/cancel.py#L16-L26 |
1,450 | softlayer/softlayer-python | SoftLayer/API.py | create_client_from_env | def create_client_from_env(username=None,
api_key=None,
endpoint_url=None,
timeout=None,
auth=None,
config_file=None,
proxy=None,
user_agent=None,
transport=None,
verify=True):
"""Creates a SoftLayer API client using your environment.
Settings are loaded via keyword arguments, environemtal variables and
config file.
:param username: an optional API username if you wish to bypass the
package's built-in username
:param api_key: an optional API key if you wish to bypass the package's
built in API key
:param endpoint_url: the API endpoint base URL you wish to connect to.
Set this to API_PRIVATE_ENDPOINT to connect via SoftLayer's private
network.
:param proxy: proxy to be used to make API calls
:param integer timeout: timeout for API requests
:param auth: an object which responds to get_headers() to be inserted into
the xml-rpc headers. Example: `BasicAuthentication`
:param config_file: A path to a configuration file used to load settings
:param user_agent: an optional User Agent to report when making API
calls if you wish to bypass the packages built in User Agent string
:param transport: An object that's callable with this signature:
transport(SoftLayer.transports.Request)
:param bool verify: decide to verify the server's SSL/TLS cert. DO NOT SET
TO FALSE WITHOUT UNDERSTANDING THE IMPLICATIONS.
Usage:
>>> import SoftLayer
>>> client = SoftLayer.create_client_from_env()
>>> resp = client.call('Account', 'getObject')
>>> resp['companyName']
'Your Company'
"""
settings = config.get_client_settings(username=username,
api_key=api_key,
endpoint_url=endpoint_url,
timeout=timeout,
proxy=proxy,
verify=verify,
config_file=config_file)
if transport is None:
url = settings.get('endpoint_url')
if url is not None and '/rest' in url:
# If this looks like a rest endpoint, use the rest transport
transport = transports.RestTransport(
endpoint_url=settings.get('endpoint_url'),
proxy=settings.get('proxy'),
timeout=settings.get('timeout'),
user_agent=user_agent,
verify=verify,
)
else:
# Default the transport to use XMLRPC
transport = transports.XmlRpcTransport(
endpoint_url=settings.get('endpoint_url'),
proxy=settings.get('proxy'),
timeout=settings.get('timeout'),
user_agent=user_agent,
verify=verify,
)
# If we have enough information to make an auth driver, let's do it
if auth is None and settings.get('username') and settings.get('api_key'):
# NOTE(kmcdonald): some transports mask other transports, so this is
# a way to find the 'real' one
real_transport = getattr(transport, 'transport', transport)
if isinstance(real_transport, transports.XmlRpcTransport):
auth = slauth.BasicAuthentication(
settings.get('username'),
settings.get('api_key'),
)
elif isinstance(real_transport, transports.RestTransport):
auth = slauth.BasicHTTPAuthentication(
settings.get('username'),
settings.get('api_key'),
)
return BaseClient(auth=auth, transport=transport) | python | def create_client_from_env(username=None,
api_key=None,
endpoint_url=None,
timeout=None,
auth=None,
config_file=None,
proxy=None,
user_agent=None,
transport=None,
verify=True):
"""Creates a SoftLayer API client using your environment.
Settings are loaded via keyword arguments, environemtal variables and
config file.
:param username: an optional API username if you wish to bypass the
package's built-in username
:param api_key: an optional API key if you wish to bypass the package's
built in API key
:param endpoint_url: the API endpoint base URL you wish to connect to.
Set this to API_PRIVATE_ENDPOINT to connect via SoftLayer's private
network.
:param proxy: proxy to be used to make API calls
:param integer timeout: timeout for API requests
:param auth: an object which responds to get_headers() to be inserted into
the xml-rpc headers. Example: `BasicAuthentication`
:param config_file: A path to a configuration file used to load settings
:param user_agent: an optional User Agent to report when making API
calls if you wish to bypass the packages built in User Agent string
:param transport: An object that's callable with this signature:
transport(SoftLayer.transports.Request)
:param bool verify: decide to verify the server's SSL/TLS cert. DO NOT SET
TO FALSE WITHOUT UNDERSTANDING THE IMPLICATIONS.
Usage:
>>> import SoftLayer
>>> client = SoftLayer.create_client_from_env()
>>> resp = client.call('Account', 'getObject')
>>> resp['companyName']
'Your Company'
"""
settings = config.get_client_settings(username=username,
api_key=api_key,
endpoint_url=endpoint_url,
timeout=timeout,
proxy=proxy,
verify=verify,
config_file=config_file)
if transport is None:
url = settings.get('endpoint_url')
if url is not None and '/rest' in url:
# If this looks like a rest endpoint, use the rest transport
transport = transports.RestTransport(
endpoint_url=settings.get('endpoint_url'),
proxy=settings.get('proxy'),
timeout=settings.get('timeout'),
user_agent=user_agent,
verify=verify,
)
else:
# Default the transport to use XMLRPC
transport = transports.XmlRpcTransport(
endpoint_url=settings.get('endpoint_url'),
proxy=settings.get('proxy'),
timeout=settings.get('timeout'),
user_agent=user_agent,
verify=verify,
)
# If we have enough information to make an auth driver, let's do it
if auth is None and settings.get('username') and settings.get('api_key'):
# NOTE(kmcdonald): some transports mask other transports, so this is
# a way to find the 'real' one
real_transport = getattr(transport, 'transport', transport)
if isinstance(real_transport, transports.XmlRpcTransport):
auth = slauth.BasicAuthentication(
settings.get('username'),
settings.get('api_key'),
)
elif isinstance(real_transport, transports.RestTransport):
auth = slauth.BasicHTTPAuthentication(
settings.get('username'),
settings.get('api_key'),
)
return BaseClient(auth=auth, transport=transport) | [
"def",
"create_client_from_env",
"(",
"username",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"endpoint_url",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"config_file",
"=",
"None",
",",
"proxy",
"=",
"None",
",",
"user_agent",
"=",
"None",
",",
"transport",
"=",
"None",
",",
"verify",
"=",
"True",
")",
":",
"settings",
"=",
"config",
".",
"get_client_settings",
"(",
"username",
"=",
"username",
",",
"api_key",
"=",
"api_key",
",",
"endpoint_url",
"=",
"endpoint_url",
",",
"timeout",
"=",
"timeout",
",",
"proxy",
"=",
"proxy",
",",
"verify",
"=",
"verify",
",",
"config_file",
"=",
"config_file",
")",
"if",
"transport",
"is",
"None",
":",
"url",
"=",
"settings",
".",
"get",
"(",
"'endpoint_url'",
")",
"if",
"url",
"is",
"not",
"None",
"and",
"'/rest'",
"in",
"url",
":",
"# If this looks like a rest endpoint, use the rest transport",
"transport",
"=",
"transports",
".",
"RestTransport",
"(",
"endpoint_url",
"=",
"settings",
".",
"get",
"(",
"'endpoint_url'",
")",
",",
"proxy",
"=",
"settings",
".",
"get",
"(",
"'proxy'",
")",
",",
"timeout",
"=",
"settings",
".",
"get",
"(",
"'timeout'",
")",
",",
"user_agent",
"=",
"user_agent",
",",
"verify",
"=",
"verify",
",",
")",
"else",
":",
"# Default the transport to use XMLRPC",
"transport",
"=",
"transports",
".",
"XmlRpcTransport",
"(",
"endpoint_url",
"=",
"settings",
".",
"get",
"(",
"'endpoint_url'",
")",
",",
"proxy",
"=",
"settings",
".",
"get",
"(",
"'proxy'",
")",
",",
"timeout",
"=",
"settings",
".",
"get",
"(",
"'timeout'",
")",
",",
"user_agent",
"=",
"user_agent",
",",
"verify",
"=",
"verify",
",",
")",
"# If we have enough information to make an auth driver, let's do it",
"if",
"auth",
"is",
"None",
"and",
"settings",
".",
"get",
"(",
"'username'",
")",
"and",
"settings",
".",
"get",
"(",
"'api_key'",
")",
":",
"# NOTE(kmcdonald): some transports mask other transports, so this is",
"# a way to find the 'real' one",
"real_transport",
"=",
"getattr",
"(",
"transport",
",",
"'transport'",
",",
"transport",
")",
"if",
"isinstance",
"(",
"real_transport",
",",
"transports",
".",
"XmlRpcTransport",
")",
":",
"auth",
"=",
"slauth",
".",
"BasicAuthentication",
"(",
"settings",
".",
"get",
"(",
"'username'",
")",
",",
"settings",
".",
"get",
"(",
"'api_key'",
")",
",",
")",
"elif",
"isinstance",
"(",
"real_transport",
",",
"transports",
".",
"RestTransport",
")",
":",
"auth",
"=",
"slauth",
".",
"BasicHTTPAuthentication",
"(",
"settings",
".",
"get",
"(",
"'username'",
")",
",",
"settings",
".",
"get",
"(",
"'api_key'",
")",
",",
")",
"return",
"BaseClient",
"(",
"auth",
"=",
"auth",
",",
"transport",
"=",
"transport",
")"
] | Creates a SoftLayer API client using your environment.
Settings are loaded via keyword arguments, environemtal variables and
config file.
:param username: an optional API username if you wish to bypass the
package's built-in username
:param api_key: an optional API key if you wish to bypass the package's
built in API key
:param endpoint_url: the API endpoint base URL you wish to connect to.
Set this to API_PRIVATE_ENDPOINT to connect via SoftLayer's private
network.
:param proxy: proxy to be used to make API calls
:param integer timeout: timeout for API requests
:param auth: an object which responds to get_headers() to be inserted into
the xml-rpc headers. Example: `BasicAuthentication`
:param config_file: A path to a configuration file used to load settings
:param user_agent: an optional User Agent to report when making API
calls if you wish to bypass the packages built in User Agent string
:param transport: An object that's callable with this signature:
transport(SoftLayer.transports.Request)
:param bool verify: decide to verify the server's SSL/TLS cert. DO NOT SET
TO FALSE WITHOUT UNDERSTANDING THE IMPLICATIONS.
Usage:
>>> import SoftLayer
>>> client = SoftLayer.create_client_from_env()
>>> resp = client.call('Account', 'getObject')
>>> resp['companyName']
'Your Company' | [
"Creates",
"a",
"SoftLayer",
"API",
"client",
"using",
"your",
"environment",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/API.py#L41-L131 |
1,451 | softlayer/softlayer-python | SoftLayer/API.py | BaseClient.call | def call(self, service, method, *args, **kwargs):
"""Make a SoftLayer API call.
:param method: the method to call on the service
:param \\*args: (optional) arguments for the remote call
:param id: (optional) id for the resource
:param mask: (optional) object mask
:param dict filter: (optional) filter dict
:param dict headers: (optional) optional XML-RPC headers
:param boolean compress: (optional) Enable/Disable HTTP compression
:param dict raw_headers: (optional) HTTP transport headers
:param int limit: (optional) return at most this many results
:param int offset: (optional) offset results by this many
:param boolean iter: (optional) if True, returns a generator with the
results
:param bool verify: verify SSL cert
:param cert: client certificate path
Usage:
>>> import SoftLayer
>>> client = SoftLayer.create_client_from_env()
>>> client.call('Account', 'getVirtualGuests', mask="id", limit=10)
[...]
"""
if kwargs.pop('iter', False):
# Most of the codebase assumes a non-generator will be returned, so casting to list
# keeps those sections working
return list(self.iter_call(service, method, *args, **kwargs))
invalid_kwargs = set(kwargs.keys()) - VALID_CALL_ARGS
if invalid_kwargs:
raise TypeError(
'Invalid keyword arguments: %s' % ','.join(invalid_kwargs))
if self._prefix and not service.startswith(self._prefix):
service = self._prefix + service
http_headers = {'Accept': '*/*'}
if kwargs.get('compress', True):
http_headers['Accept-Encoding'] = 'gzip, deflate, compress'
else:
http_headers['Accept-Encoding'] = None
if kwargs.get('raw_headers'):
http_headers.update(kwargs.get('raw_headers'))
request = transports.Request()
request.service = service
request.method = method
request.args = args
request.transport_headers = http_headers
request.identifier = kwargs.get('id')
request.mask = kwargs.get('mask')
request.filter = kwargs.get('filter')
request.limit = kwargs.get('limit')
request.offset = kwargs.get('offset')
if kwargs.get('verify') is not None:
request.verify = kwargs.get('verify')
if self.auth:
extra_headers = self.auth.get_headers()
if extra_headers:
warnings.warn("auth.get_headers() is deprecated and will be "
"removed in the next major version",
DeprecationWarning)
request.headers.update(extra_headers)
request = self.auth.get_request(request)
request.headers.update(kwargs.get('headers', {}))
return self.transport(request) | python | def call(self, service, method, *args, **kwargs):
"""Make a SoftLayer API call.
:param method: the method to call on the service
:param \\*args: (optional) arguments for the remote call
:param id: (optional) id for the resource
:param mask: (optional) object mask
:param dict filter: (optional) filter dict
:param dict headers: (optional) optional XML-RPC headers
:param boolean compress: (optional) Enable/Disable HTTP compression
:param dict raw_headers: (optional) HTTP transport headers
:param int limit: (optional) return at most this many results
:param int offset: (optional) offset results by this many
:param boolean iter: (optional) if True, returns a generator with the
results
:param bool verify: verify SSL cert
:param cert: client certificate path
Usage:
>>> import SoftLayer
>>> client = SoftLayer.create_client_from_env()
>>> client.call('Account', 'getVirtualGuests', mask="id", limit=10)
[...]
"""
if kwargs.pop('iter', False):
# Most of the codebase assumes a non-generator will be returned, so casting to list
# keeps those sections working
return list(self.iter_call(service, method, *args, **kwargs))
invalid_kwargs = set(kwargs.keys()) - VALID_CALL_ARGS
if invalid_kwargs:
raise TypeError(
'Invalid keyword arguments: %s' % ','.join(invalid_kwargs))
if self._prefix and not service.startswith(self._prefix):
service = self._prefix + service
http_headers = {'Accept': '*/*'}
if kwargs.get('compress', True):
http_headers['Accept-Encoding'] = 'gzip, deflate, compress'
else:
http_headers['Accept-Encoding'] = None
if kwargs.get('raw_headers'):
http_headers.update(kwargs.get('raw_headers'))
request = transports.Request()
request.service = service
request.method = method
request.args = args
request.transport_headers = http_headers
request.identifier = kwargs.get('id')
request.mask = kwargs.get('mask')
request.filter = kwargs.get('filter')
request.limit = kwargs.get('limit')
request.offset = kwargs.get('offset')
if kwargs.get('verify') is not None:
request.verify = kwargs.get('verify')
if self.auth:
extra_headers = self.auth.get_headers()
if extra_headers:
warnings.warn("auth.get_headers() is deprecated and will be "
"removed in the next major version",
DeprecationWarning)
request.headers.update(extra_headers)
request = self.auth.get_request(request)
request.headers.update(kwargs.get('headers', {}))
return self.transport(request) | [
"def",
"call",
"(",
"self",
",",
"service",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"pop",
"(",
"'iter'",
",",
"False",
")",
":",
"# Most of the codebase assumes a non-generator will be returned, so casting to list",
"# keeps those sections working",
"return",
"list",
"(",
"self",
".",
"iter_call",
"(",
"service",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"invalid_kwargs",
"=",
"set",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
"-",
"VALID_CALL_ARGS",
"if",
"invalid_kwargs",
":",
"raise",
"TypeError",
"(",
"'Invalid keyword arguments: %s'",
"%",
"','",
".",
"join",
"(",
"invalid_kwargs",
")",
")",
"if",
"self",
".",
"_prefix",
"and",
"not",
"service",
".",
"startswith",
"(",
"self",
".",
"_prefix",
")",
":",
"service",
"=",
"self",
".",
"_prefix",
"+",
"service",
"http_headers",
"=",
"{",
"'Accept'",
":",
"'*/*'",
"}",
"if",
"kwargs",
".",
"get",
"(",
"'compress'",
",",
"True",
")",
":",
"http_headers",
"[",
"'Accept-Encoding'",
"]",
"=",
"'gzip, deflate, compress'",
"else",
":",
"http_headers",
"[",
"'Accept-Encoding'",
"]",
"=",
"None",
"if",
"kwargs",
".",
"get",
"(",
"'raw_headers'",
")",
":",
"http_headers",
".",
"update",
"(",
"kwargs",
".",
"get",
"(",
"'raw_headers'",
")",
")",
"request",
"=",
"transports",
".",
"Request",
"(",
")",
"request",
".",
"service",
"=",
"service",
"request",
".",
"method",
"=",
"method",
"request",
".",
"args",
"=",
"args",
"request",
".",
"transport_headers",
"=",
"http_headers",
"request",
".",
"identifier",
"=",
"kwargs",
".",
"get",
"(",
"'id'",
")",
"request",
".",
"mask",
"=",
"kwargs",
".",
"get",
"(",
"'mask'",
")",
"request",
".",
"filter",
"=",
"kwargs",
".",
"get",
"(",
"'filter'",
")",
"request",
".",
"limit",
"=",
"kwargs",
".",
"get",
"(",
"'limit'",
")",
"request",
".",
"offset",
"=",
"kwargs",
".",
"get",
"(",
"'offset'",
")",
"if",
"kwargs",
".",
"get",
"(",
"'verify'",
")",
"is",
"not",
"None",
":",
"request",
".",
"verify",
"=",
"kwargs",
".",
"get",
"(",
"'verify'",
")",
"if",
"self",
".",
"auth",
":",
"extra_headers",
"=",
"self",
".",
"auth",
".",
"get_headers",
"(",
")",
"if",
"extra_headers",
":",
"warnings",
".",
"warn",
"(",
"\"auth.get_headers() is deprecated and will be \"",
"\"removed in the next major version\"",
",",
"DeprecationWarning",
")",
"request",
".",
"headers",
".",
"update",
"(",
"extra_headers",
")",
"request",
"=",
"self",
".",
"auth",
".",
"get_request",
"(",
"request",
")",
"request",
".",
"headers",
".",
"update",
"(",
"kwargs",
".",
"get",
"(",
"'headers'",
",",
"{",
"}",
")",
")",
"return",
"self",
".",
"transport",
"(",
"request",
")"
] | Make a SoftLayer API call.
:param method: the method to call on the service
:param \\*args: (optional) arguments for the remote call
:param id: (optional) id for the resource
:param mask: (optional) object mask
:param dict filter: (optional) filter dict
:param dict headers: (optional) optional XML-RPC headers
:param boolean compress: (optional) Enable/Disable HTTP compression
:param dict raw_headers: (optional) HTTP transport headers
:param int limit: (optional) return at most this many results
:param int offset: (optional) offset results by this many
:param boolean iter: (optional) if True, returns a generator with the
results
:param bool verify: verify SSL cert
:param cert: client certificate path
Usage:
>>> import SoftLayer
>>> client = SoftLayer.create_client_from_env()
>>> client.call('Account', 'getVirtualGuests', mask="id", limit=10)
[...] | [
"Make",
"a",
"SoftLayer",
"API",
"call",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/API.py#L193-L265 |
1,452 | softlayer/softlayer-python | SoftLayer/API.py | Service.call | def call(self, name, *args, **kwargs):
"""Make a SoftLayer API call
:param service: the name of the SoftLayer API service
:param method: the method to call on the service
:param \\*args: same optional arguments that ``BaseClient.call`` takes
:param \\*\\*kwargs: same optional keyword arguments that
``BaseClient.call`` takes
:param service: the name of the SoftLayer API service
Usage:
>>> import SoftLayer
>>> client = SoftLayer.create_client_from_env()
>>> client['Account'].getVirtualGuests(mask="id", limit=10)
[...]
"""
return self.client.call(self.name, name, *args, **kwargs) | python | def call(self, name, *args, **kwargs):
"""Make a SoftLayer API call
:param service: the name of the SoftLayer API service
:param method: the method to call on the service
:param \\*args: same optional arguments that ``BaseClient.call`` takes
:param \\*\\*kwargs: same optional keyword arguments that
``BaseClient.call`` takes
:param service: the name of the SoftLayer API service
Usage:
>>> import SoftLayer
>>> client = SoftLayer.create_client_from_env()
>>> client['Account'].getVirtualGuests(mask="id", limit=10)
[...]
"""
return self.client.call(self.name, name, *args, **kwargs) | [
"def",
"call",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"client",
".",
"call",
"(",
"self",
".",
"name",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Make a SoftLayer API call
:param service: the name of the SoftLayer API service
:param method: the method to call on the service
:param \\*args: same optional arguments that ``BaseClient.call`` takes
:param \\*\\*kwargs: same optional keyword arguments that
``BaseClient.call`` takes
:param service: the name of the SoftLayer API service
Usage:
>>> import SoftLayer
>>> client = SoftLayer.create_client_from_env()
>>> client['Account'].getVirtualGuests(mask="id", limit=10)
[...] | [
"Make",
"a",
"SoftLayer",
"API",
"call"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/API.py#L339-L357 |
1,453 | softlayer/softlayer-python | SoftLayer/CLI/object_storage/credential/list.py | cli | def cli(env, identifier):
"""Retrieve credentials used for generating an AWS signature. Max of 2."""
mgr = SoftLayer.ObjectStorageManager(env.client)
credential_list = mgr.list_credential(identifier)
table = formatting.Table(['id', 'password', 'username', 'type_name'])
for credential in credential_list:
table.add_row([
credential['id'],
credential['password'],
credential['username'],
credential['type']['name']
])
env.fout(table) | python | def cli(env, identifier):
"""Retrieve credentials used for generating an AWS signature. Max of 2."""
mgr = SoftLayer.ObjectStorageManager(env.client)
credential_list = mgr.list_credential(identifier)
table = formatting.Table(['id', 'password', 'username', 'type_name'])
for credential in credential_list:
table.add_row([
credential['id'],
credential['password'],
credential['username'],
credential['type']['name']
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"ObjectStorageManager",
"(",
"env",
".",
"client",
")",
"credential_list",
"=",
"mgr",
".",
"list_credential",
"(",
"identifier",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'password'",
",",
"'username'",
",",
"'type_name'",
"]",
")",
"for",
"credential",
"in",
"credential_list",
":",
"table",
".",
"add_row",
"(",
"[",
"credential",
"[",
"'id'",
"]",
",",
"credential",
"[",
"'password'",
"]",
",",
"credential",
"[",
"'username'",
"]",
",",
"credential",
"[",
"'type'",
"]",
"[",
"'name'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | Retrieve credentials used for generating an AWS signature. Max of 2. | [
"Retrieve",
"credentials",
"used",
"for",
"generating",
"an",
"AWS",
"signature",
".",
"Max",
"of",
"2",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/object_storage/credential/list.py#L14-L29 |
1,454 | softlayer/softlayer-python | SoftLayer/CLI/dedicatedhost/list.py | cli | def cli(env, sortby, cpu, columns, datacenter, name, memory, disk, tag):
"""List dedicated host."""
mgr = SoftLayer.DedicatedHostManager(env.client)
hosts = mgr.list_instances(cpus=cpu,
datacenter=datacenter,
hostname=name,
memory=memory,
disk=disk,
tags=tag,
mask=columns.mask())
table = formatting.Table(columns.columns)
table.sortby = sortby
for host in hosts:
table.add_row([value or formatting.blank()
for value in columns.row(host)])
env.fout(table) | python | def cli(env, sortby, cpu, columns, datacenter, name, memory, disk, tag):
"""List dedicated host."""
mgr = SoftLayer.DedicatedHostManager(env.client)
hosts = mgr.list_instances(cpus=cpu,
datacenter=datacenter,
hostname=name,
memory=memory,
disk=disk,
tags=tag,
mask=columns.mask())
table = formatting.Table(columns.columns)
table.sortby = sortby
for host in hosts:
table.add_row([value or formatting.blank()
for value in columns.row(host)])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"sortby",
",",
"cpu",
",",
"columns",
",",
"datacenter",
",",
"name",
",",
"memory",
",",
"disk",
",",
"tag",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"DedicatedHostManager",
"(",
"env",
".",
"client",
")",
"hosts",
"=",
"mgr",
".",
"list_instances",
"(",
"cpus",
"=",
"cpu",
",",
"datacenter",
"=",
"datacenter",
",",
"hostname",
"=",
"name",
",",
"memory",
"=",
"memory",
",",
"disk",
"=",
"disk",
",",
"tags",
"=",
"tag",
",",
"mask",
"=",
"columns",
".",
"mask",
"(",
")",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"columns",
".",
"columns",
")",
"table",
".",
"sortby",
"=",
"sortby",
"for",
"host",
"in",
"hosts",
":",
"table",
".",
"add_row",
"(",
"[",
"value",
"or",
"formatting",
".",
"blank",
"(",
")",
"for",
"value",
"in",
"columns",
".",
"row",
"(",
"host",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List dedicated host. | [
"List",
"dedicated",
"host",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dedicatedhost/list.py#L52-L70 |
1,455 | softlayer/softlayer-python | SoftLayer/CLI/environment.py | Environment.input | def input(self, prompt, default=None, show_default=True):
"""Provide a command prompt."""
return click.prompt(prompt, default=default, show_default=show_default) | python | def input(self, prompt, default=None, show_default=True):
"""Provide a command prompt."""
return click.prompt(prompt, default=default, show_default=show_default) | [
"def",
"input",
"(",
"self",
",",
"prompt",
",",
"default",
"=",
"None",
",",
"show_default",
"=",
"True",
")",
":",
"return",
"click",
".",
"prompt",
"(",
"prompt",
",",
"default",
"=",
"default",
",",
"show_default",
"=",
"show_default",
")"
] | Provide a command prompt. | [
"Provide",
"a",
"command",
"prompt",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L58-L60 |
1,456 | softlayer/softlayer-python | SoftLayer/CLI/environment.py | Environment.getpass | def getpass(self, prompt, default=None):
"""Provide a password prompt."""
return click.prompt(prompt, hide_input=True, default=default) | python | def getpass(self, prompt, default=None):
"""Provide a password prompt."""
return click.prompt(prompt, hide_input=True, default=default) | [
"def",
"getpass",
"(",
"self",
",",
"prompt",
",",
"default",
"=",
"None",
")",
":",
"return",
"click",
".",
"prompt",
"(",
"prompt",
",",
"hide_input",
"=",
"True",
",",
"default",
"=",
"default",
")"
] | Provide a password prompt. | [
"Provide",
"a",
"password",
"prompt",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L62-L64 |
1,457 | softlayer/softlayer-python | SoftLayer/CLI/environment.py | Environment.list_commands | def list_commands(self, *path):
"""Command listing."""
path_str = ':'.join(path)
commands = []
for command in self.commands:
# Filter based on prefix and the segment length
if all([command.startswith(path_str),
len(path) == command.count(":")]):
# offset is used to exclude the path that the caller requested.
offset = len(path_str) + 1 if path_str else 0
commands.append(command[offset:])
return sorted(commands) | python | def list_commands(self, *path):
"""Command listing."""
path_str = ':'.join(path)
commands = []
for command in self.commands:
# Filter based on prefix and the segment length
if all([command.startswith(path_str),
len(path) == command.count(":")]):
# offset is used to exclude the path that the caller requested.
offset = len(path_str) + 1 if path_str else 0
commands.append(command[offset:])
return sorted(commands) | [
"def",
"list_commands",
"(",
"self",
",",
"*",
"path",
")",
":",
"path_str",
"=",
"':'",
".",
"join",
"(",
"path",
")",
"commands",
"=",
"[",
"]",
"for",
"command",
"in",
"self",
".",
"commands",
":",
"# Filter based on prefix and the segment length",
"if",
"all",
"(",
"[",
"command",
".",
"startswith",
"(",
"path_str",
")",
",",
"len",
"(",
"path",
")",
"==",
"command",
".",
"count",
"(",
"\":\"",
")",
"]",
")",
":",
"# offset is used to exclude the path that the caller requested.",
"offset",
"=",
"len",
"(",
"path_str",
")",
"+",
"1",
"if",
"path_str",
"else",
"0",
"commands",
".",
"append",
"(",
"command",
"[",
"offset",
":",
"]",
")",
"return",
"sorted",
"(",
"commands",
")"
] | Command listing. | [
"Command",
"listing",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L67-L82 |
1,458 | softlayer/softlayer-python | SoftLayer/CLI/environment.py | Environment.get_command | def get_command(self, *path):
"""Return command at the given path or raise error."""
path_str = ':'.join(path)
if path_str in self.commands:
return self.commands[path_str].load()
return None | python | def get_command(self, *path):
"""Return command at the given path or raise error."""
path_str = ':'.join(path)
if path_str in self.commands:
return self.commands[path_str].load()
return None | [
"def",
"get_command",
"(",
"self",
",",
"*",
"path",
")",
":",
"path_str",
"=",
"':'",
".",
"join",
"(",
"path",
")",
"if",
"path_str",
"in",
"self",
".",
"commands",
":",
"return",
"self",
".",
"commands",
"[",
"path_str",
"]",
".",
"load",
"(",
")",
"return",
"None"
] | Return command at the given path or raise error. | [
"Return",
"command",
"at",
"the",
"given",
"path",
"or",
"raise",
"error",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L84-L91 |
1,459 | softlayer/softlayer-python | SoftLayer/CLI/environment.py | Environment.resolve_alias | def resolve_alias(self, path_str):
"""Returns the actual command name. Uses the alias mapping."""
if path_str in self.aliases:
return self.aliases[path_str]
return path_str | python | def resolve_alias(self, path_str):
"""Returns the actual command name. Uses the alias mapping."""
if path_str in self.aliases:
return self.aliases[path_str]
return path_str | [
"def",
"resolve_alias",
"(",
"self",
",",
"path_str",
")",
":",
"if",
"path_str",
"in",
"self",
".",
"aliases",
":",
"return",
"self",
".",
"aliases",
"[",
"path_str",
"]",
"return",
"path_str"
] | Returns the actual command name. Uses the alias mapping. | [
"Returns",
"the",
"actual",
"command",
"name",
".",
"Uses",
"the",
"alias",
"mapping",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L93-L97 |
1,460 | softlayer/softlayer-python | SoftLayer/CLI/environment.py | Environment.load | def load(self):
"""Loads all modules."""
if self._modules_loaded is True:
return
self.load_modules_from_python(routes.ALL_ROUTES)
self.aliases.update(routes.ALL_ALIASES)
self._load_modules_from_entry_points('softlayer.cli')
self._modules_loaded = True | python | def load(self):
"""Loads all modules."""
if self._modules_loaded is True:
return
self.load_modules_from_python(routes.ALL_ROUTES)
self.aliases.update(routes.ALL_ALIASES)
self._load_modules_from_entry_points('softlayer.cli')
self._modules_loaded = True | [
"def",
"load",
"(",
"self",
")",
":",
"if",
"self",
".",
"_modules_loaded",
"is",
"True",
":",
"return",
"self",
".",
"load_modules_from_python",
"(",
"routes",
".",
"ALL_ROUTES",
")",
"self",
".",
"aliases",
".",
"update",
"(",
"routes",
".",
"ALL_ALIASES",
")",
"self",
".",
"_load_modules_from_entry_points",
"(",
"'softlayer.cli'",
")",
"self",
".",
"_modules_loaded",
"=",
"True"
] | Loads all modules. | [
"Loads",
"all",
"modules",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L99-L108 |
1,461 | softlayer/softlayer-python | SoftLayer/CLI/environment.py | Environment.load_modules_from_python | def load_modules_from_python(self, route_list):
"""Load modules from the native python source."""
for name, modpath in route_list:
if ':' in modpath:
path, attr = modpath.split(':', 1)
else:
path, attr = modpath, None
self.commands[name] = ModuleLoader(path, attr=attr) | python | def load_modules_from_python(self, route_list):
"""Load modules from the native python source."""
for name, modpath in route_list:
if ':' in modpath:
path, attr = modpath.split(':', 1)
else:
path, attr = modpath, None
self.commands[name] = ModuleLoader(path, attr=attr) | [
"def",
"load_modules_from_python",
"(",
"self",
",",
"route_list",
")",
":",
"for",
"name",
",",
"modpath",
"in",
"route_list",
":",
"if",
"':'",
"in",
"modpath",
":",
"path",
",",
"attr",
"=",
"modpath",
".",
"split",
"(",
"':'",
",",
"1",
")",
"else",
":",
"path",
",",
"attr",
"=",
"modpath",
",",
"None",
"self",
".",
"commands",
"[",
"name",
"]",
"=",
"ModuleLoader",
"(",
"path",
",",
"attr",
"=",
"attr",
")"
] | Load modules from the native python source. | [
"Load",
"modules",
"from",
"the",
"native",
"python",
"source",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L110-L117 |
1,462 | softlayer/softlayer-python | SoftLayer/CLI/environment.py | Environment.ensure_client | def ensure_client(self, config_file=None, is_demo=False, proxy=None):
"""Create a new SLAPI client to the environment.
This will be a no-op if there is already a client in this environment.
"""
if self.client is not None:
return
# Environment can be passed in explicitly. This is used for testing
if is_demo:
client = SoftLayer.BaseClient(
transport=SoftLayer.FixtureTransport(),
auth=None,
)
else:
# Create SL Client
client = SoftLayer.create_client_from_env(
proxy=proxy,
config_file=config_file,
)
self.client = client | python | def ensure_client(self, config_file=None, is_demo=False, proxy=None):
"""Create a new SLAPI client to the environment.
This will be a no-op if there is already a client in this environment.
"""
if self.client is not None:
return
# Environment can be passed in explicitly. This is used for testing
if is_demo:
client = SoftLayer.BaseClient(
transport=SoftLayer.FixtureTransport(),
auth=None,
)
else:
# Create SL Client
client = SoftLayer.create_client_from_env(
proxy=proxy,
config_file=config_file,
)
self.client = client | [
"def",
"ensure_client",
"(",
"self",
",",
"config_file",
"=",
"None",
",",
"is_demo",
"=",
"False",
",",
"proxy",
"=",
"None",
")",
":",
"if",
"self",
".",
"client",
"is",
"not",
"None",
":",
"return",
"# Environment can be passed in explicitly. This is used for testing",
"if",
"is_demo",
":",
"client",
"=",
"SoftLayer",
".",
"BaseClient",
"(",
"transport",
"=",
"SoftLayer",
".",
"FixtureTransport",
"(",
")",
",",
"auth",
"=",
"None",
",",
")",
"else",
":",
"# Create SL Client",
"client",
"=",
"SoftLayer",
".",
"create_client_from_env",
"(",
"proxy",
"=",
"proxy",
",",
"config_file",
"=",
"config_file",
",",
")",
"self",
".",
"client",
"=",
"client"
] | Create a new SLAPI client to the environment.
This will be a no-op if there is already a client in this environment. | [
"Create",
"a",
"new",
"SLAPI",
"client",
"to",
"the",
"environment",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L133-L153 |
1,463 | softlayer/softlayer-python | SoftLayer/CLI/helpers.py | multi_option | def multi_option(*param_decls, **attrs):
"""modify help text and indicate option is permitted multiple times
:param param_decls:
:param attrs:
:return:
"""
attrhelp = attrs.get('help', None)
if attrhelp is not None:
newhelp = attrhelp + " (multiple occurrence permitted)"
attrs['help'] = newhelp
attrs['multiple'] = True
return click.option(*param_decls, **attrs) | python | def multi_option(*param_decls, **attrs):
"""modify help text and indicate option is permitted multiple times
:param param_decls:
:param attrs:
:return:
"""
attrhelp = attrs.get('help', None)
if attrhelp is not None:
newhelp = attrhelp + " (multiple occurrence permitted)"
attrs['help'] = newhelp
attrs['multiple'] = True
return click.option(*param_decls, **attrs) | [
"def",
"multi_option",
"(",
"*",
"param_decls",
",",
"*",
"*",
"attrs",
")",
":",
"attrhelp",
"=",
"attrs",
".",
"get",
"(",
"'help'",
",",
"None",
")",
"if",
"attrhelp",
"is",
"not",
"None",
":",
"newhelp",
"=",
"attrhelp",
"+",
"\" (multiple occurrence permitted)\"",
"attrs",
"[",
"'help'",
"]",
"=",
"newhelp",
"attrs",
"[",
"'multiple'",
"]",
"=",
"True",
"return",
"click",
".",
"option",
"(",
"*",
"param_decls",
",",
"*",
"*",
"attrs",
")"
] | modify help text and indicate option is permitted multiple times
:param param_decls:
:param attrs:
:return: | [
"modify",
"help",
"text",
"and",
"indicate",
"option",
"is",
"permitted",
"multiple",
"times"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/helpers.py#L14-L27 |
1,464 | softlayer/softlayer-python | SoftLayer/CLI/helpers.py | resolve_id | def resolve_id(resolver, identifier, name='object'):
"""Resolves a single id using a resolver function.
:param resolver: function that resolves ids. Should return None or a list of ids.
:param string identifier: a string identifier used to resolve ids
:param string name: the object type, to be used in error messages
"""
try:
return int(identifier)
except ValueError:
pass # It was worth a shot
ids = resolver(identifier)
if len(ids) == 0:
raise exceptions.CLIAbort("Error: Unable to find %s '%s'" % (name, identifier))
if len(ids) > 1:
raise exceptions.CLIAbort(
"Error: Multiple %s found for '%s': %s" %
(name, identifier, ', '.join([str(_id) for _id in ids])))
return ids[0] | python | def resolve_id(resolver, identifier, name='object'):
"""Resolves a single id using a resolver function.
:param resolver: function that resolves ids. Should return None or a list of ids.
:param string identifier: a string identifier used to resolve ids
:param string name: the object type, to be used in error messages
"""
try:
return int(identifier)
except ValueError:
pass # It was worth a shot
ids = resolver(identifier)
if len(ids) == 0:
raise exceptions.CLIAbort("Error: Unable to find %s '%s'" % (name, identifier))
if len(ids) > 1:
raise exceptions.CLIAbort(
"Error: Multiple %s found for '%s': %s" %
(name, identifier, ', '.join([str(_id) for _id in ids])))
return ids[0] | [
"def",
"resolve_id",
"(",
"resolver",
",",
"identifier",
",",
"name",
"=",
"'object'",
")",
":",
"try",
":",
"return",
"int",
"(",
"identifier",
")",
"except",
"ValueError",
":",
"pass",
"# It was worth a shot",
"ids",
"=",
"resolver",
"(",
"identifier",
")",
"if",
"len",
"(",
"ids",
")",
"==",
"0",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Error: Unable to find %s '%s'\"",
"%",
"(",
"name",
",",
"identifier",
")",
")",
"if",
"len",
"(",
"ids",
")",
">",
"1",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Error: Multiple %s found for '%s': %s\"",
"%",
"(",
"name",
",",
"identifier",
",",
"', '",
".",
"join",
"(",
"[",
"str",
"(",
"_id",
")",
"for",
"_id",
"in",
"ids",
"]",
")",
")",
")",
"return",
"ids",
"[",
"0",
"]"
] | Resolves a single id using a resolver function.
:param resolver: function that resolves ids. Should return None or a list of ids.
:param string identifier: a string identifier used to resolve ids
:param string name: the object type, to be used in error messages | [
"Resolves",
"a",
"single",
"id",
"using",
"a",
"resolver",
"function",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/helpers.py#L30-L53 |
1,465 | softlayer/softlayer-python | SoftLayer/CLI/ssl/remove.py | cli | def cli(env, identifier):
"""Remove SSL certificate."""
manager = SoftLayer.SSLManager(env.client)
if not (env.skip_confirmations or formatting.no_going_back('yes')):
raise exceptions.CLIAbort("Aborted.")
manager.remove_certificate(identifier) | python | def cli(env, identifier):
"""Remove SSL certificate."""
manager = SoftLayer.SSLManager(env.client)
if not (env.skip_confirmations or formatting.no_going_back('yes')):
raise exceptions.CLIAbort("Aborted.")
manager.remove_certificate(identifier) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"SSLManager",
"(",
"env",
".",
"client",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"no_going_back",
"(",
"'yes'",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Aborted.\"",
")",
"manager",
".",
"remove_certificate",
"(",
"identifier",
")"
] | Remove SSL certificate. | [
"Remove",
"SSL",
"certificate",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ssl/remove.py#L15-L22 |
1,466 | softlayer/softlayer-python | SoftLayer/CLI/file/snapshot/order.py | cli | def cli(env, volume_id, capacity, tier, upgrade):
"""Order snapshot space for a file storage volume."""
file_manager = SoftLayer.FileStorageManager(env.client)
if tier is not None:
tier = float(tier)
try:
order = file_manager.order_snapshot_space(
volume_id,
capacity=capacity,
tier=tier,
upgrade=upgrade
)
except ValueError as ex:
raise exceptions.ArgumentError(str(ex))
if 'placedOrder' in order.keys():
click.echo("Order #{0} placed successfully!".format(
order['placedOrder']['id']))
for item in order['placedOrder']['items']:
click.echo(" > %s" % item['description'])
if 'status' in order['placedOrder'].keys():
click.echo(" > Order status: %s" % order['placedOrder']['status'])
else:
click.echo("Order could not be placed! Please verify your options " +
"and try again.") | python | def cli(env, volume_id, capacity, tier, upgrade):
"""Order snapshot space for a file storage volume."""
file_manager = SoftLayer.FileStorageManager(env.client)
if tier is not None:
tier = float(tier)
try:
order = file_manager.order_snapshot_space(
volume_id,
capacity=capacity,
tier=tier,
upgrade=upgrade
)
except ValueError as ex:
raise exceptions.ArgumentError(str(ex))
if 'placedOrder' in order.keys():
click.echo("Order #{0} placed successfully!".format(
order['placedOrder']['id']))
for item in order['placedOrder']['items']:
click.echo(" > %s" % item['description'])
if 'status' in order['placedOrder'].keys():
click.echo(" > Order status: %s" % order['placedOrder']['status'])
else:
click.echo("Order could not be placed! Please verify your options " +
"and try again.") | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"capacity",
",",
"tier",
",",
"upgrade",
")",
":",
"file_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"if",
"tier",
"is",
"not",
"None",
":",
"tier",
"=",
"float",
"(",
"tier",
")",
"try",
":",
"order",
"=",
"file_manager",
".",
"order_snapshot_space",
"(",
"volume_id",
",",
"capacity",
"=",
"capacity",
",",
"tier",
"=",
"tier",
",",
"upgrade",
"=",
"upgrade",
")",
"except",
"ValueError",
"as",
"ex",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"str",
"(",
"ex",
")",
")",
"if",
"'placedOrder'",
"in",
"order",
".",
"keys",
"(",
")",
":",
"click",
".",
"echo",
"(",
"\"Order #{0} placed successfully!\"",
".",
"format",
"(",
"order",
"[",
"'placedOrder'",
"]",
"[",
"'id'",
"]",
")",
")",
"for",
"item",
"in",
"order",
"[",
"'placedOrder'",
"]",
"[",
"'items'",
"]",
":",
"click",
".",
"echo",
"(",
"\" > %s\"",
"%",
"item",
"[",
"'description'",
"]",
")",
"if",
"'status'",
"in",
"order",
"[",
"'placedOrder'",
"]",
".",
"keys",
"(",
")",
":",
"click",
".",
"echo",
"(",
"\" > Order status: %s\"",
"%",
"order",
"[",
"'placedOrder'",
"]",
"[",
"'status'",
"]",
")",
"else",
":",
"click",
".",
"echo",
"(",
"\"Order could not be placed! Please verify your options \"",
"+",
"\"and try again.\"",
")"
] | Order snapshot space for a file storage volume. | [
"Order",
"snapshot",
"space",
"for",
"a",
"file",
"storage",
"volume",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/snapshot/order.py#L27-L53 |
1,467 | softlayer/softlayer-python | SoftLayer/CLI/virt/edit.py | cli | def cli(env, identifier, domain, userfile, tag, hostname, userdata,
public_speed, private_speed):
"""Edit a virtual server's details."""
if userdata and userfile:
raise exceptions.ArgumentError(
'[-u | --userdata] not allowed with [-F | --userfile]')
data = {}
if userdata:
data['userdata'] = userdata
elif userfile:
with open(userfile, 'r') as userfile_obj:
data['userdata'] = userfile_obj.read()
data['hostname'] = hostname
data['domain'] = domain
if tag:
data['tags'] = ','.join(tag)
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
if not vsi.edit(vs_id, **data):
raise exceptions.CLIAbort("Failed to update virtual server")
if public_speed is not None:
vsi.change_port_speed(vs_id, True, int(public_speed))
if private_speed is not None:
vsi.change_port_speed(vs_id, False, int(private_speed)) | python | def cli(env, identifier, domain, userfile, tag, hostname, userdata,
public_speed, private_speed):
"""Edit a virtual server's details."""
if userdata and userfile:
raise exceptions.ArgumentError(
'[-u | --userdata] not allowed with [-F | --userfile]')
data = {}
if userdata:
data['userdata'] = userdata
elif userfile:
with open(userfile, 'r') as userfile_obj:
data['userdata'] = userfile_obj.read()
data['hostname'] = hostname
data['domain'] = domain
if tag:
data['tags'] = ','.join(tag)
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
if not vsi.edit(vs_id, **data):
raise exceptions.CLIAbort("Failed to update virtual server")
if public_speed is not None:
vsi.change_port_speed(vs_id, True, int(public_speed))
if private_speed is not None:
vsi.change_port_speed(vs_id, False, int(private_speed)) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"domain",
",",
"userfile",
",",
"tag",
",",
"hostname",
",",
"userdata",
",",
"public_speed",
",",
"private_speed",
")",
":",
"if",
"userdata",
"and",
"userfile",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"'[-u | --userdata] not allowed with [-F | --userfile]'",
")",
"data",
"=",
"{",
"}",
"if",
"userdata",
":",
"data",
"[",
"'userdata'",
"]",
"=",
"userdata",
"elif",
"userfile",
":",
"with",
"open",
"(",
"userfile",
",",
"'r'",
")",
"as",
"userfile_obj",
":",
"data",
"[",
"'userdata'",
"]",
"=",
"userfile_obj",
".",
"read",
"(",
")",
"data",
"[",
"'hostname'",
"]",
"=",
"hostname",
"data",
"[",
"'domain'",
"]",
"=",
"domain",
"if",
"tag",
":",
"data",
"[",
"'tags'",
"]",
"=",
"','",
".",
"join",
"(",
"tag",
")",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
"identifier",
",",
"'VS'",
")",
"if",
"not",
"vsi",
".",
"edit",
"(",
"vs_id",
",",
"*",
"*",
"data",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Failed to update virtual server\"",
")",
"if",
"public_speed",
"is",
"not",
"None",
":",
"vsi",
".",
"change_port_speed",
"(",
"vs_id",
",",
"True",
",",
"int",
"(",
"public_speed",
")",
")",
"if",
"private_speed",
"is",
"not",
"None",
":",
"vsi",
".",
"change_port_speed",
"(",
"vs_id",
",",
"False",
",",
"int",
"(",
"private_speed",
")",
")"
] | Edit a virtual server's details. | [
"Edit",
"a",
"virtual",
"server",
"s",
"details",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/edit.py#L33-L64 |
1,468 | softlayer/softlayer-python | SoftLayer/CLI/file/replication/order.py | cli | def cli(env, volume_id, snapshot_schedule, location, tier):
"""Order a file storage replica volume."""
file_manager = SoftLayer.FileStorageManager(env.client)
if tier is not None:
tier = float(tier)
try:
order = file_manager.order_replicant_volume(
volume_id,
snapshot_schedule=snapshot_schedule,
location=location,
tier=tier,
)
except ValueError as ex:
raise exceptions.ArgumentError(str(ex))
if 'placedOrder' in order.keys():
click.echo("Order #{0} placed successfully!".format(
order['placedOrder']['id']))
for item in order['placedOrder']['items']:
click.echo(" > %s" % item['description'])
else:
click.echo("Order could not be placed! Please verify your options " +
"and try again.") | python | def cli(env, volume_id, snapshot_schedule, location, tier):
"""Order a file storage replica volume."""
file_manager = SoftLayer.FileStorageManager(env.client)
if tier is not None:
tier = float(tier)
try:
order = file_manager.order_replicant_volume(
volume_id,
snapshot_schedule=snapshot_schedule,
location=location,
tier=tier,
)
except ValueError as ex:
raise exceptions.ArgumentError(str(ex))
if 'placedOrder' in order.keys():
click.echo("Order #{0} placed successfully!".format(
order['placedOrder']['id']))
for item in order['placedOrder']['items']:
click.echo(" > %s" % item['description'])
else:
click.echo("Order could not be placed! Please verify your options " +
"and try again.") | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"snapshot_schedule",
",",
"location",
",",
"tier",
")",
":",
"file_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"if",
"tier",
"is",
"not",
"None",
":",
"tier",
"=",
"float",
"(",
"tier",
")",
"try",
":",
"order",
"=",
"file_manager",
".",
"order_replicant_volume",
"(",
"volume_id",
",",
"snapshot_schedule",
"=",
"snapshot_schedule",
",",
"location",
"=",
"location",
",",
"tier",
"=",
"tier",
",",
")",
"except",
"ValueError",
"as",
"ex",
":",
"raise",
"exceptions",
".",
"ArgumentError",
"(",
"str",
"(",
"ex",
")",
")",
"if",
"'placedOrder'",
"in",
"order",
".",
"keys",
"(",
")",
":",
"click",
".",
"echo",
"(",
"\"Order #{0} placed successfully!\"",
".",
"format",
"(",
"order",
"[",
"'placedOrder'",
"]",
"[",
"'id'",
"]",
")",
")",
"for",
"item",
"in",
"order",
"[",
"'placedOrder'",
"]",
"[",
"'items'",
"]",
":",
"click",
".",
"echo",
"(",
"\" > %s\"",
"%",
"item",
"[",
"'description'",
"]",
")",
"else",
":",
"click",
".",
"echo",
"(",
"\"Order could not be placed! Please verify your options \"",
"+",
"\"and try again.\"",
")"
] | Order a file storage replica volume. | [
"Order",
"a",
"file",
"storage",
"replica",
"volume",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/replication/order.py#L29-L53 |
1,469 | softlayer/softlayer-python | SoftLayer/CLI/block/replication/failback.py | cli | def cli(env, volume_id, replicant_id):
"""Failback a block volume from the given replicant volume."""
block_storage_manager = SoftLayer.BlockStorageManager(env.client)
success = block_storage_manager.failback_from_replicant(
volume_id,
replicant_id
)
if success:
click.echo("Failback from replicant is now in progress.")
else:
click.echo("Failback operation could not be initiated.") | python | def cli(env, volume_id, replicant_id):
"""Failback a block volume from the given replicant volume."""
block_storage_manager = SoftLayer.BlockStorageManager(env.client)
success = block_storage_manager.failback_from_replicant(
volume_id,
replicant_id
)
if success:
click.echo("Failback from replicant is now in progress.")
else:
click.echo("Failback operation could not be initiated.") | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"replicant_id",
")",
":",
"block_storage_manager",
"=",
"SoftLayer",
".",
"BlockStorageManager",
"(",
"env",
".",
"client",
")",
"success",
"=",
"block_storage_manager",
".",
"failback_from_replicant",
"(",
"volume_id",
",",
"replicant_id",
")",
"if",
"success",
":",
"click",
".",
"echo",
"(",
"\"Failback from replicant is now in progress.\"",
")",
"else",
":",
"click",
".",
"echo",
"(",
"\"Failback operation could not be initiated.\"",
")"
] | Failback a block volume from the given replicant volume. | [
"Failback",
"a",
"block",
"volume",
"from",
"the",
"given",
"replicant",
"volume",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/replication/failback.py#L13-L25 |
1,470 | softlayer/softlayer-python | SoftLayer/CLI/virt/placementgroup/detail.py | cli | def cli(env, identifier):
"""View details of a placement group.
IDENTIFIER can be either the Name or Id of the placement group you want to view
"""
manager = PlacementManager(env.client)
group_id = helpers.resolve_id(manager.resolve_ids, identifier, 'placement_group')
result = manager.get_object(group_id)
table = formatting.Table(["Id", "Name", "Backend Router", "Rule", "Created"])
table.add_row([
result['id'],
result['name'],
result['backendRouter']['hostname'],
result['rule']['name'],
result['createDate']
])
guest_table = formatting.Table([
"Id",
"FQDN",
"Primary IP",
"Backend IP",
"CPU",
"Memory",
"Provisioned",
"Transaction"
])
for guest in result['guests']:
guest_table.add_row([
guest.get('id'),
guest.get('fullyQualifiedDomainName'),
guest.get('primaryIpAddress'),
guest.get('primaryBackendIpAddress'),
guest.get('maxCpu'),
guest.get('maxMemory'),
guest.get('provisionDate'),
formatting.active_txn(guest)
])
env.fout(table)
env.fout(guest_table) | python | def cli(env, identifier):
"""View details of a placement group.
IDENTIFIER can be either the Name or Id of the placement group you want to view
"""
manager = PlacementManager(env.client)
group_id = helpers.resolve_id(manager.resolve_ids, identifier, 'placement_group')
result = manager.get_object(group_id)
table = formatting.Table(["Id", "Name", "Backend Router", "Rule", "Created"])
table.add_row([
result['id'],
result['name'],
result['backendRouter']['hostname'],
result['rule']['name'],
result['createDate']
])
guest_table = formatting.Table([
"Id",
"FQDN",
"Primary IP",
"Backend IP",
"CPU",
"Memory",
"Provisioned",
"Transaction"
])
for guest in result['guests']:
guest_table.add_row([
guest.get('id'),
guest.get('fullyQualifiedDomainName'),
guest.get('primaryIpAddress'),
guest.get('primaryBackendIpAddress'),
guest.get('maxCpu'),
guest.get('maxMemory'),
guest.get('provisionDate'),
formatting.active_txn(guest)
])
env.fout(table)
env.fout(guest_table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"manager",
"=",
"PlacementManager",
"(",
"env",
".",
"client",
")",
"group_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"manager",
".",
"resolve_ids",
",",
"identifier",
",",
"'placement_group'",
")",
"result",
"=",
"manager",
".",
"get_object",
"(",
"group_id",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"\"Id\"",
",",
"\"Name\"",
",",
"\"Backend Router\"",
",",
"\"Rule\"",
",",
"\"Created\"",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"result",
"[",
"'id'",
"]",
",",
"result",
"[",
"'name'",
"]",
",",
"result",
"[",
"'backendRouter'",
"]",
"[",
"'hostname'",
"]",
",",
"result",
"[",
"'rule'",
"]",
"[",
"'name'",
"]",
",",
"result",
"[",
"'createDate'",
"]",
"]",
")",
"guest_table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"\"Id\"",
",",
"\"FQDN\"",
",",
"\"Primary IP\"",
",",
"\"Backend IP\"",
",",
"\"CPU\"",
",",
"\"Memory\"",
",",
"\"Provisioned\"",
",",
"\"Transaction\"",
"]",
")",
"for",
"guest",
"in",
"result",
"[",
"'guests'",
"]",
":",
"guest_table",
".",
"add_row",
"(",
"[",
"guest",
".",
"get",
"(",
"'id'",
")",
",",
"guest",
".",
"get",
"(",
"'fullyQualifiedDomainName'",
")",
",",
"guest",
".",
"get",
"(",
"'primaryIpAddress'",
")",
",",
"guest",
".",
"get",
"(",
"'primaryBackendIpAddress'",
")",
",",
"guest",
".",
"get",
"(",
"'maxCpu'",
")",
",",
"guest",
".",
"get",
"(",
"'maxMemory'",
")",
",",
"guest",
".",
"get",
"(",
"'provisionDate'",
")",
",",
"formatting",
".",
"active_txn",
"(",
"guest",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")",
"env",
".",
"fout",
"(",
"guest_table",
")"
] | View details of a placement group.
IDENTIFIER can be either the Name or Id of the placement group you want to view | [
"View",
"details",
"of",
"a",
"placement",
"group",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/placementgroup/detail.py#L14-L54 |
1,471 | softlayer/softlayer-python | SoftLayer/CLI/user/list.py | cli | def cli(env, columns):
"""List Users."""
mgr = SoftLayer.UserManager(env.client)
users = mgr.list_users()
table = formatting.Table(columns.columns)
for user in users:
table.add_row([value or formatting.blank()
for value in columns.row(user)])
env.fout(table) | python | def cli(env, columns):
"""List Users."""
mgr = SoftLayer.UserManager(env.client)
users = mgr.list_users()
table = formatting.Table(columns.columns)
for user in users:
table.add_row([value or formatting.blank()
for value in columns.row(user)])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"columns",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"UserManager",
"(",
"env",
".",
"client",
")",
"users",
"=",
"mgr",
".",
"list_users",
"(",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"columns",
".",
"columns",
")",
"for",
"user",
"in",
"users",
":",
"table",
".",
"add_row",
"(",
"[",
"value",
"or",
"formatting",
".",
"blank",
"(",
")",
"for",
"value",
"in",
"columns",
".",
"row",
"(",
"user",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List Users. | [
"List",
"Users",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/list.py#L37-L48 |
1,472 | softlayer/softlayer-python | SoftLayer/CLI/ticket/update.py | cli | def cli(env, identifier, body):
"""Adds an update to an existing ticket."""
mgr = SoftLayer.TicketManager(env.client)
ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket')
if body is None:
body = click.edit('\n\n' + ticket.TEMPLATE_MSG)
mgr.update_ticket(ticket_id=ticket_id, body=body)
env.fout("Ticket Updated!") | python | def cli(env, identifier, body):
"""Adds an update to an existing ticket."""
mgr = SoftLayer.TicketManager(env.client)
ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket')
if body is None:
body = click.edit('\n\n' + ticket.TEMPLATE_MSG)
mgr.update_ticket(ticket_id=ticket_id, body=body)
env.fout("Ticket Updated!") | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"body",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"TicketManager",
"(",
"env",
".",
"client",
")",
"ticket_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'ticket'",
")",
"if",
"body",
"is",
"None",
":",
"body",
"=",
"click",
".",
"edit",
"(",
"'\\n\\n'",
"+",
"ticket",
".",
"TEMPLATE_MSG",
")",
"mgr",
".",
"update_ticket",
"(",
"ticket_id",
"=",
"ticket_id",
",",
"body",
"=",
"body",
")",
"env",
".",
"fout",
"(",
"\"Ticket Updated!\"",
")"
] | Adds an update to an existing ticket. | [
"Adds",
"an",
"update",
"to",
"an",
"existing",
"ticket",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ticket/update.py#L16-L26 |
1,473 | softlayer/softlayer-python | SoftLayer/CLI/order/quote_detail.py | cli | def cli(env, quote):
"""View a quote"""
manager = ordering.OrderingManager(env.client)
result = manager.get_quote_details(quote)
package = result['order']['items'][0]['package']
title = "{} - Package: {}, Id {}".format(result.get('name'), package['keyName'], package['id'])
table = formatting.Table([
'Category', 'Description', 'Quantity', 'Recurring', 'One Time'
], title=title)
table.align['Category'] = 'l'
table.align['Description'] = 'l'
items = lookup(result, 'order', 'items')
for item in items:
table.add_row([
item.get('categoryCode'),
item.get('description'),
item.get('quantity'),
item.get('recurringFee'),
item.get('oneTimeFee')
])
env.fout(table) | python | def cli(env, quote):
"""View a quote"""
manager = ordering.OrderingManager(env.client)
result = manager.get_quote_details(quote)
package = result['order']['items'][0]['package']
title = "{} - Package: {}, Id {}".format(result.get('name'), package['keyName'], package['id'])
table = formatting.Table([
'Category', 'Description', 'Quantity', 'Recurring', 'One Time'
], title=title)
table.align['Category'] = 'l'
table.align['Description'] = 'l'
items = lookup(result, 'order', 'items')
for item in items:
table.add_row([
item.get('categoryCode'),
item.get('description'),
item.get('quantity'),
item.get('recurringFee'),
item.get('oneTimeFee')
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"quote",
")",
":",
"manager",
"=",
"ordering",
".",
"OrderingManager",
"(",
"env",
".",
"client",
")",
"result",
"=",
"manager",
".",
"get_quote_details",
"(",
"quote",
")",
"package",
"=",
"result",
"[",
"'order'",
"]",
"[",
"'items'",
"]",
"[",
"0",
"]",
"[",
"'package'",
"]",
"title",
"=",
"\"{} - Package: {}, Id {}\"",
".",
"format",
"(",
"result",
".",
"get",
"(",
"'name'",
")",
",",
"package",
"[",
"'keyName'",
"]",
",",
"package",
"[",
"'id'",
"]",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Category'",
",",
"'Description'",
",",
"'Quantity'",
",",
"'Recurring'",
",",
"'One Time'",
"]",
",",
"title",
"=",
"title",
")",
"table",
".",
"align",
"[",
"'Category'",
"]",
"=",
"'l'",
"table",
".",
"align",
"[",
"'Description'",
"]",
"=",
"'l'",
"items",
"=",
"lookup",
"(",
"result",
",",
"'order'",
",",
"'items'",
")",
"for",
"item",
"in",
"items",
":",
"table",
".",
"add_row",
"(",
"[",
"item",
".",
"get",
"(",
"'categoryCode'",
")",
",",
"item",
".",
"get",
"(",
"'description'",
")",
",",
"item",
".",
"get",
"(",
"'quantity'",
")",
",",
"item",
".",
"get",
"(",
"'recurringFee'",
")",
",",
"item",
".",
"get",
"(",
"'oneTimeFee'",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | View a quote | [
"View",
"a",
"quote"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/quote_detail.py#L14-L38 |
1,474 | softlayer/softlayer-python | SoftLayer/CLI/securitygroup/list.py | cli | def cli(env, sortby, limit):
"""List security groups."""
mgr = SoftLayer.NetworkManager(env.client)
table = formatting.Table(COLUMNS)
table.sortby = sortby
sgs = mgr.list_securitygroups(limit=limit)
for secgroup in sgs:
table.add_row([
secgroup['id'],
secgroup.get('name') or formatting.blank(),
secgroup.get('description') or formatting.blank(),
])
env.fout(table) | python | def cli(env, sortby, limit):
"""List security groups."""
mgr = SoftLayer.NetworkManager(env.client)
table = formatting.Table(COLUMNS)
table.sortby = sortby
sgs = mgr.list_securitygroups(limit=limit)
for secgroup in sgs:
table.add_row([
secgroup['id'],
secgroup.get('name') or formatting.blank(),
secgroup.get('description') or formatting.blank(),
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"sortby",
",",
"limit",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"COLUMNS",
")",
"table",
".",
"sortby",
"=",
"sortby",
"sgs",
"=",
"mgr",
".",
"list_securitygroups",
"(",
"limit",
"=",
"limit",
")",
"for",
"secgroup",
"in",
"sgs",
":",
"table",
".",
"add_row",
"(",
"[",
"secgroup",
"[",
"'id'",
"]",
",",
"secgroup",
".",
"get",
"(",
"'name'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
",",
"secgroup",
".",
"get",
"(",
"'description'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
",",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List security groups. | [
"List",
"security",
"groups",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/list.py#L24-L40 |
1,475 | softlayer/softlayer-python | SoftLayer/CLI/firewall/edit.py | parse_rules | def parse_rules(content=None):
"""Helper to parse the input from the user into a list of rules.
:param string content: the content of the editor
:returns: a list of rules
"""
rules = content.split(DELIMITER)
parsed_rules = list()
order = 1
for rule in rules:
if rule.strip() == '':
continue
parsed_rule = {}
lines = rule.split("\n")
parsed_rule['orderValue'] = order
order += 1
for line in lines:
if line.strip() == '':
continue
key_value = line.strip().split(':')
key = key_value[0].strip()
value = key_value[1].strip()
if key == 'action':
parsed_rule['action'] = value
elif key == 'protocol':
parsed_rule['protocol'] = value
elif key == 'source_ip_address':
parsed_rule['sourceIpAddress'] = value
elif key == 'source_ip_subnet_mask':
parsed_rule['sourceIpSubnetMask'] = value
elif key == 'destination_ip_address':
parsed_rule['destinationIpAddress'] = value
elif key == 'destination_ip_subnet_mask':
parsed_rule['destinationIpSubnetMask'] = value
elif key == 'destination_port_range_start':
parsed_rule['destinationPortRangeStart'] = int(value)
elif key == 'destination_port_range_end':
parsed_rule['destinationPortRangeEnd'] = int(value)
elif key == 'version':
parsed_rule['version'] = int(value)
parsed_rules.append(parsed_rule)
return parsed_rules | python | def parse_rules(content=None):
"""Helper to parse the input from the user into a list of rules.
:param string content: the content of the editor
:returns: a list of rules
"""
rules = content.split(DELIMITER)
parsed_rules = list()
order = 1
for rule in rules:
if rule.strip() == '':
continue
parsed_rule = {}
lines = rule.split("\n")
parsed_rule['orderValue'] = order
order += 1
for line in lines:
if line.strip() == '':
continue
key_value = line.strip().split(':')
key = key_value[0].strip()
value = key_value[1].strip()
if key == 'action':
parsed_rule['action'] = value
elif key == 'protocol':
parsed_rule['protocol'] = value
elif key == 'source_ip_address':
parsed_rule['sourceIpAddress'] = value
elif key == 'source_ip_subnet_mask':
parsed_rule['sourceIpSubnetMask'] = value
elif key == 'destination_ip_address':
parsed_rule['destinationIpAddress'] = value
elif key == 'destination_ip_subnet_mask':
parsed_rule['destinationIpSubnetMask'] = value
elif key == 'destination_port_range_start':
parsed_rule['destinationPortRangeStart'] = int(value)
elif key == 'destination_port_range_end':
parsed_rule['destinationPortRangeEnd'] = int(value)
elif key == 'version':
parsed_rule['version'] = int(value)
parsed_rules.append(parsed_rule)
return parsed_rules | [
"def",
"parse_rules",
"(",
"content",
"=",
"None",
")",
":",
"rules",
"=",
"content",
".",
"split",
"(",
"DELIMITER",
")",
"parsed_rules",
"=",
"list",
"(",
")",
"order",
"=",
"1",
"for",
"rule",
"in",
"rules",
":",
"if",
"rule",
".",
"strip",
"(",
")",
"==",
"''",
":",
"continue",
"parsed_rule",
"=",
"{",
"}",
"lines",
"=",
"rule",
".",
"split",
"(",
"\"\\n\"",
")",
"parsed_rule",
"[",
"'orderValue'",
"]",
"=",
"order",
"order",
"+=",
"1",
"for",
"line",
"in",
"lines",
":",
"if",
"line",
".",
"strip",
"(",
")",
"==",
"''",
":",
"continue",
"key_value",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"':'",
")",
"key",
"=",
"key_value",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"value",
"=",
"key_value",
"[",
"1",
"]",
".",
"strip",
"(",
")",
"if",
"key",
"==",
"'action'",
":",
"parsed_rule",
"[",
"'action'",
"]",
"=",
"value",
"elif",
"key",
"==",
"'protocol'",
":",
"parsed_rule",
"[",
"'protocol'",
"]",
"=",
"value",
"elif",
"key",
"==",
"'source_ip_address'",
":",
"parsed_rule",
"[",
"'sourceIpAddress'",
"]",
"=",
"value",
"elif",
"key",
"==",
"'source_ip_subnet_mask'",
":",
"parsed_rule",
"[",
"'sourceIpSubnetMask'",
"]",
"=",
"value",
"elif",
"key",
"==",
"'destination_ip_address'",
":",
"parsed_rule",
"[",
"'destinationIpAddress'",
"]",
"=",
"value",
"elif",
"key",
"==",
"'destination_ip_subnet_mask'",
":",
"parsed_rule",
"[",
"'destinationIpSubnetMask'",
"]",
"=",
"value",
"elif",
"key",
"==",
"'destination_port_range_start'",
":",
"parsed_rule",
"[",
"'destinationPortRangeStart'",
"]",
"=",
"int",
"(",
"value",
")",
"elif",
"key",
"==",
"'destination_port_range_end'",
":",
"parsed_rule",
"[",
"'destinationPortRangeEnd'",
"]",
"=",
"int",
"(",
"value",
")",
"elif",
"key",
"==",
"'version'",
":",
"parsed_rule",
"[",
"'version'",
"]",
"=",
"int",
"(",
"value",
")",
"parsed_rules",
".",
"append",
"(",
"parsed_rule",
")",
"return",
"parsed_rules"
] | Helper to parse the input from the user into a list of rules.
:param string content: the content of the editor
:returns: a list of rules | [
"Helper",
"to",
"parse",
"the",
"input",
"from",
"the",
"user",
"into",
"a",
"list",
"of",
"rules",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/edit.py#L19-L60 |
1,476 | softlayer/softlayer-python | SoftLayer/CLI/firewall/edit.py | open_editor | def open_editor(rules=None, content=None):
"""Helper to open an editor for editing the firewall rules.
This method takes two parameters, if content is provided,
that means that submitting the rules failed and we are allowing
the user to re-edit what they provided. If content is not provided, the
rules retrieved from the firewall will be displayed to the user.
:param list rules: A list containing the rules of the firewall
:param string content: the content that the user provided in the editor
:returns: a formatted string that get be pushed into the editor
"""
# Let's get the default EDITOR of the environment,
# use nano if none is specified
editor = os.environ.get('EDITOR', 'nano')
with tempfile.NamedTemporaryFile(suffix=".tmp") as tfile:
if content:
# if content is provided, just display it as is
tfile.write(content)
tfile.flush()
subprocess.call([editor, tfile.name])
tfile.seek(0)
data = tfile.read()
return data
if not rules:
# if the firewall has no rules, provide a template
tfile.write(DELIMITER)
tfile.write(get_formatted_rule())
else:
# if the firewall has rules, display those to the user
for rule in rules:
tfile.write(DELIMITER)
tfile.write(get_formatted_rule(rule))
tfile.write(DELIMITER)
tfile.flush()
subprocess.call([editor, tfile.name])
tfile.seek(0)
data = tfile.read()
return data | python | def open_editor(rules=None, content=None):
"""Helper to open an editor for editing the firewall rules.
This method takes two parameters, if content is provided,
that means that submitting the rules failed and we are allowing
the user to re-edit what they provided. If content is not provided, the
rules retrieved from the firewall will be displayed to the user.
:param list rules: A list containing the rules of the firewall
:param string content: the content that the user provided in the editor
:returns: a formatted string that get be pushed into the editor
"""
# Let's get the default EDITOR of the environment,
# use nano if none is specified
editor = os.environ.get('EDITOR', 'nano')
with tempfile.NamedTemporaryFile(suffix=".tmp") as tfile:
if content:
# if content is provided, just display it as is
tfile.write(content)
tfile.flush()
subprocess.call([editor, tfile.name])
tfile.seek(0)
data = tfile.read()
return data
if not rules:
# if the firewall has no rules, provide a template
tfile.write(DELIMITER)
tfile.write(get_formatted_rule())
else:
# if the firewall has rules, display those to the user
for rule in rules:
tfile.write(DELIMITER)
tfile.write(get_formatted_rule(rule))
tfile.write(DELIMITER)
tfile.flush()
subprocess.call([editor, tfile.name])
tfile.seek(0)
data = tfile.read()
return data | [
"def",
"open_editor",
"(",
"rules",
"=",
"None",
",",
"content",
"=",
"None",
")",
":",
"# Let's get the default EDITOR of the environment,",
"# use nano if none is specified",
"editor",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'EDITOR'",
",",
"'nano'",
")",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"\".tmp\"",
")",
"as",
"tfile",
":",
"if",
"content",
":",
"# if content is provided, just display it as is",
"tfile",
".",
"write",
"(",
"content",
")",
"tfile",
".",
"flush",
"(",
")",
"subprocess",
".",
"call",
"(",
"[",
"editor",
",",
"tfile",
".",
"name",
"]",
")",
"tfile",
".",
"seek",
"(",
"0",
")",
"data",
"=",
"tfile",
".",
"read",
"(",
")",
"return",
"data",
"if",
"not",
"rules",
":",
"# if the firewall has no rules, provide a template",
"tfile",
".",
"write",
"(",
"DELIMITER",
")",
"tfile",
".",
"write",
"(",
"get_formatted_rule",
"(",
")",
")",
"else",
":",
"# if the firewall has rules, display those to the user",
"for",
"rule",
"in",
"rules",
":",
"tfile",
".",
"write",
"(",
"DELIMITER",
")",
"tfile",
".",
"write",
"(",
"get_formatted_rule",
"(",
"rule",
")",
")",
"tfile",
".",
"write",
"(",
"DELIMITER",
")",
"tfile",
".",
"flush",
"(",
")",
"subprocess",
".",
"call",
"(",
"[",
"editor",
",",
"tfile",
".",
"name",
"]",
")",
"tfile",
".",
"seek",
"(",
"0",
")",
"data",
"=",
"tfile",
".",
"read",
"(",
")",
"return",
"data"
] | Helper to open an editor for editing the firewall rules.
This method takes two parameters, if content is provided,
that means that submitting the rules failed and we are allowing
the user to re-edit what they provided. If content is not provided, the
rules retrieved from the firewall will be displayed to the user.
:param list rules: A list containing the rules of the firewall
:param string content: the content that the user provided in the editor
:returns: a formatted string that get be pushed into the editor | [
"Helper",
"to",
"open",
"an",
"editor",
"for",
"editing",
"the",
"firewall",
"rules",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/edit.py#L63-L105 |
1,477 | softlayer/softlayer-python | SoftLayer/CLI/firewall/edit.py | get_formatted_rule | def get_formatted_rule(rule=None):
"""Helper to format the rule into a user friendly format.
:param dict rule: A dict containing one rule of the firewall
:returns: a formatted string that get be pushed into the editor
"""
rule = rule or {}
return ('action: %s\n'
'protocol: %s\n'
'source_ip_address: %s\n'
'source_ip_subnet_mask: %s\n'
'destination_ip_address: %s\n'
'destination_ip_subnet_mask: %s\n'
'destination_port_range_start: %s\n'
'destination_port_range_end: %s\n'
'version: %s\n'
% (rule.get('action', 'permit'),
rule.get('protocol', 'tcp'),
rule.get('sourceIpAddress', 'any'),
rule.get('sourceIpSubnetMask', '255.255.255.255'),
rule.get('destinationIpAddress', 'any'),
rule.get('destinationIpSubnetMask', '255.255.255.255'),
rule.get('destinationPortRangeStart', 1),
rule.get('destinationPortRangeEnd', 1),
rule.get('version', 4))) | python | def get_formatted_rule(rule=None):
"""Helper to format the rule into a user friendly format.
:param dict rule: A dict containing one rule of the firewall
:returns: a formatted string that get be pushed into the editor
"""
rule = rule or {}
return ('action: %s\n'
'protocol: %s\n'
'source_ip_address: %s\n'
'source_ip_subnet_mask: %s\n'
'destination_ip_address: %s\n'
'destination_ip_subnet_mask: %s\n'
'destination_port_range_start: %s\n'
'destination_port_range_end: %s\n'
'version: %s\n'
% (rule.get('action', 'permit'),
rule.get('protocol', 'tcp'),
rule.get('sourceIpAddress', 'any'),
rule.get('sourceIpSubnetMask', '255.255.255.255'),
rule.get('destinationIpAddress', 'any'),
rule.get('destinationIpSubnetMask', '255.255.255.255'),
rule.get('destinationPortRangeStart', 1),
rule.get('destinationPortRangeEnd', 1),
rule.get('version', 4))) | [
"def",
"get_formatted_rule",
"(",
"rule",
"=",
"None",
")",
":",
"rule",
"=",
"rule",
"or",
"{",
"}",
"return",
"(",
"'action: %s\\n'",
"'protocol: %s\\n'",
"'source_ip_address: %s\\n'",
"'source_ip_subnet_mask: %s\\n'",
"'destination_ip_address: %s\\n'",
"'destination_ip_subnet_mask: %s\\n'",
"'destination_port_range_start: %s\\n'",
"'destination_port_range_end: %s\\n'",
"'version: %s\\n'",
"%",
"(",
"rule",
".",
"get",
"(",
"'action'",
",",
"'permit'",
")",
",",
"rule",
".",
"get",
"(",
"'protocol'",
",",
"'tcp'",
")",
",",
"rule",
".",
"get",
"(",
"'sourceIpAddress'",
",",
"'any'",
")",
",",
"rule",
".",
"get",
"(",
"'sourceIpSubnetMask'",
",",
"'255.255.255.255'",
")",
",",
"rule",
".",
"get",
"(",
"'destinationIpAddress'",
",",
"'any'",
")",
",",
"rule",
".",
"get",
"(",
"'destinationIpSubnetMask'",
",",
"'255.255.255.255'",
")",
",",
"rule",
".",
"get",
"(",
"'destinationPortRangeStart'",
",",
"1",
")",
",",
"rule",
".",
"get",
"(",
"'destinationPortRangeEnd'",
",",
"1",
")",
",",
"rule",
".",
"get",
"(",
"'version'",
",",
"4",
")",
")",
")"
] | Helper to format the rule into a user friendly format.
:param dict rule: A dict containing one rule of the firewall
:returns: a formatted string that get be pushed into the editor | [
"Helper",
"to",
"format",
"the",
"rule",
"into",
"a",
"user",
"friendly",
"format",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/edit.py#L108-L132 |
1,478 | softlayer/softlayer-python | SoftLayer/CLI/firewall/edit.py | cli | def cli(env, identifier):
"""Edit firewall rules."""
mgr = SoftLayer.FirewallManager(env.client)
firewall_type, firewall_id = firewall.parse_id(identifier)
if firewall_type == 'vlan':
orig_rules = mgr.get_dedicated_fwl_rules(firewall_id)
else:
orig_rules = mgr.get_standard_fwl_rules(firewall_id)
# open an editor for the user to enter their rules
edited_rules = open_editor(rules=orig_rules)
env.out(edited_rules)
if formatting.confirm("Would you like to submit the rules. "
"Continue?"):
while True:
try:
rules = parse_rules(edited_rules)
if firewall_type == 'vlan':
rules = mgr.edit_dedicated_fwl_rules(firewall_id,
rules)
else:
rules = mgr.edit_standard_fwl_rules(firewall_id,
rules)
break
except (SoftLayer.SoftLayerError, ValueError) as error:
env.out("Unexpected error({%s})" % (error))
if formatting.confirm("Would you like to continue editing "
"the rules. Continue?"):
edited_rules = open_editor(content=edited_rules)
env.out(edited_rules)
if formatting.confirm("Would you like to submit the "
"rules. Continue?"):
continue
else:
raise exceptions.CLIAbort('Aborted.')
else:
raise exceptions.CLIAbort('Aborted.')
env.fout('Firewall updated!')
else:
raise exceptions.CLIAbort('Aborted.') | python | def cli(env, identifier):
"""Edit firewall rules."""
mgr = SoftLayer.FirewallManager(env.client)
firewall_type, firewall_id = firewall.parse_id(identifier)
if firewall_type == 'vlan':
orig_rules = mgr.get_dedicated_fwl_rules(firewall_id)
else:
orig_rules = mgr.get_standard_fwl_rules(firewall_id)
# open an editor for the user to enter their rules
edited_rules = open_editor(rules=orig_rules)
env.out(edited_rules)
if formatting.confirm("Would you like to submit the rules. "
"Continue?"):
while True:
try:
rules = parse_rules(edited_rules)
if firewall_type == 'vlan':
rules = mgr.edit_dedicated_fwl_rules(firewall_id,
rules)
else:
rules = mgr.edit_standard_fwl_rules(firewall_id,
rules)
break
except (SoftLayer.SoftLayerError, ValueError) as error:
env.out("Unexpected error({%s})" % (error))
if formatting.confirm("Would you like to continue editing "
"the rules. Continue?"):
edited_rules = open_editor(content=edited_rules)
env.out(edited_rules)
if formatting.confirm("Would you like to submit the "
"rules. Continue?"):
continue
else:
raise exceptions.CLIAbort('Aborted.')
else:
raise exceptions.CLIAbort('Aborted.')
env.fout('Firewall updated!')
else:
raise exceptions.CLIAbort('Aborted.') | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"FirewallManager",
"(",
"env",
".",
"client",
")",
"firewall_type",
",",
"firewall_id",
"=",
"firewall",
".",
"parse_id",
"(",
"identifier",
")",
"if",
"firewall_type",
"==",
"'vlan'",
":",
"orig_rules",
"=",
"mgr",
".",
"get_dedicated_fwl_rules",
"(",
"firewall_id",
")",
"else",
":",
"orig_rules",
"=",
"mgr",
".",
"get_standard_fwl_rules",
"(",
"firewall_id",
")",
"# open an editor for the user to enter their rules",
"edited_rules",
"=",
"open_editor",
"(",
"rules",
"=",
"orig_rules",
")",
"env",
".",
"out",
"(",
"edited_rules",
")",
"if",
"formatting",
".",
"confirm",
"(",
"\"Would you like to submit the rules. \"",
"\"Continue?\"",
")",
":",
"while",
"True",
":",
"try",
":",
"rules",
"=",
"parse_rules",
"(",
"edited_rules",
")",
"if",
"firewall_type",
"==",
"'vlan'",
":",
"rules",
"=",
"mgr",
".",
"edit_dedicated_fwl_rules",
"(",
"firewall_id",
",",
"rules",
")",
"else",
":",
"rules",
"=",
"mgr",
".",
"edit_standard_fwl_rules",
"(",
"firewall_id",
",",
"rules",
")",
"break",
"except",
"(",
"SoftLayer",
".",
"SoftLayerError",
",",
"ValueError",
")",
"as",
"error",
":",
"env",
".",
"out",
"(",
"\"Unexpected error({%s})\"",
"%",
"(",
"error",
")",
")",
"if",
"formatting",
".",
"confirm",
"(",
"\"Would you like to continue editing \"",
"\"the rules. Continue?\"",
")",
":",
"edited_rules",
"=",
"open_editor",
"(",
"content",
"=",
"edited_rules",
")",
"env",
".",
"out",
"(",
"edited_rules",
")",
"if",
"formatting",
".",
"confirm",
"(",
"\"Would you like to submit the \"",
"\"rules. Continue?\"",
")",
":",
"continue",
"else",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted.'",
")",
"else",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted.'",
")",
"env",
".",
"fout",
"(",
"'Firewall updated!'",
")",
"else",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted.'",
")"
] | Edit firewall rules. | [
"Edit",
"firewall",
"rules",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/edit.py#L138-L178 |
1,479 | softlayer/softlayer-python | SoftLayer/CLI/securitygroup/rule.py | rule_list | def rule_list(env, securitygroup_id, sortby):
"""List security group rules."""
mgr = SoftLayer.NetworkManager(env.client)
table = formatting.Table(COLUMNS)
table.sortby = sortby
rules = mgr.list_securitygroup_rules(securitygroup_id)
for rule in rules:
port_min = rule.get('portRangeMin')
port_max = rule.get('portRangeMax')
if port_min is None:
port_min = formatting.blank()
if port_max is None:
port_max = formatting.blank()
table.add_row([
rule['id'],
rule.get('remoteIp') or formatting.blank(),
rule.get('remoteGroupId') or formatting.blank(),
rule['direction'],
rule.get('ethertype') or formatting.blank(),
port_min,
port_max,
rule.get('protocol') or formatting.blank(),
rule.get('createDate') or formatting.blank(),
rule.get('modifyDate') or formatting.blank()
])
env.fout(table) | python | def rule_list(env, securitygroup_id, sortby):
"""List security group rules."""
mgr = SoftLayer.NetworkManager(env.client)
table = formatting.Table(COLUMNS)
table.sortby = sortby
rules = mgr.list_securitygroup_rules(securitygroup_id)
for rule in rules:
port_min = rule.get('portRangeMin')
port_max = rule.get('portRangeMax')
if port_min is None:
port_min = formatting.blank()
if port_max is None:
port_max = formatting.blank()
table.add_row([
rule['id'],
rule.get('remoteIp') or formatting.blank(),
rule.get('remoteGroupId') or formatting.blank(),
rule['direction'],
rule.get('ethertype') or formatting.blank(),
port_min,
port_max,
rule.get('protocol') or formatting.blank(),
rule.get('createDate') or formatting.blank(),
rule.get('modifyDate') or formatting.blank()
])
env.fout(table) | [
"def",
"rule_list",
"(",
"env",
",",
"securitygroup_id",
",",
"sortby",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"COLUMNS",
")",
"table",
".",
"sortby",
"=",
"sortby",
"rules",
"=",
"mgr",
".",
"list_securitygroup_rules",
"(",
"securitygroup_id",
")",
"for",
"rule",
"in",
"rules",
":",
"port_min",
"=",
"rule",
".",
"get",
"(",
"'portRangeMin'",
")",
"port_max",
"=",
"rule",
".",
"get",
"(",
"'portRangeMax'",
")",
"if",
"port_min",
"is",
"None",
":",
"port_min",
"=",
"formatting",
".",
"blank",
"(",
")",
"if",
"port_max",
"is",
"None",
":",
"port_max",
"=",
"formatting",
".",
"blank",
"(",
")",
"table",
".",
"add_row",
"(",
"[",
"rule",
"[",
"'id'",
"]",
",",
"rule",
".",
"get",
"(",
"'remoteIp'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
",",
"rule",
".",
"get",
"(",
"'remoteGroupId'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
",",
"rule",
"[",
"'direction'",
"]",
",",
"rule",
".",
"get",
"(",
"'ethertype'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
",",
"port_min",
",",
"port_max",
",",
"rule",
".",
"get",
"(",
"'protocol'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
",",
"rule",
".",
"get",
"(",
"'createDate'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
",",
"rule",
".",
"get",
"(",
"'modifyDate'",
")",
"or",
"formatting",
".",
"blank",
"(",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List security group rules. | [
"List",
"security",
"group",
"rules",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/rule.py#L32-L62 |
1,480 | softlayer/softlayer-python | SoftLayer/CLI/securitygroup/rule.py | add | def add(env, securitygroup_id, remote_ip, remote_group,
direction, ethertype, port_max, port_min, protocol):
"""Add a security group rule to a security group.
\b
Examples:
# Add an SSH rule (TCP port 22) to a security group
slcli sg rule-add 384727 \\
--direction ingress \\
--protocol tcp \\
--port-min 22 \\
--port-max 22
\b
# Add a ping rule (ICMP type 8 code 0) to a security group
slcli sg rule-add 384727 \\
--direction ingress \\
--protocol icmp \\
--port-min 8 \\
--port-max 0
"""
mgr = SoftLayer.NetworkManager(env.client)
ret = mgr.add_securitygroup_rule(securitygroup_id, remote_ip, remote_group,
direction, ethertype, port_max,
port_min, protocol)
if not ret:
raise exceptions.CLIAbort("Failed to add security group rule")
table = formatting.Table(REQUEST_RULES_COLUMNS)
table.add_row([ret['requestId'], str(ret['rules'])])
env.fout(table) | python | def add(env, securitygroup_id, remote_ip, remote_group,
direction, ethertype, port_max, port_min, protocol):
"""Add a security group rule to a security group.
\b
Examples:
# Add an SSH rule (TCP port 22) to a security group
slcli sg rule-add 384727 \\
--direction ingress \\
--protocol tcp \\
--port-min 22 \\
--port-max 22
\b
# Add a ping rule (ICMP type 8 code 0) to a security group
slcli sg rule-add 384727 \\
--direction ingress \\
--protocol icmp \\
--port-min 8 \\
--port-max 0
"""
mgr = SoftLayer.NetworkManager(env.client)
ret = mgr.add_securitygroup_rule(securitygroup_id, remote_ip, remote_group,
direction, ethertype, port_max,
port_min, protocol)
if not ret:
raise exceptions.CLIAbort("Failed to add security group rule")
table = formatting.Table(REQUEST_RULES_COLUMNS)
table.add_row([ret['requestId'], str(ret['rules'])])
env.fout(table) | [
"def",
"add",
"(",
"env",
",",
"securitygroup_id",
",",
"remote_ip",
",",
"remote_group",
",",
"direction",
",",
"ethertype",
",",
"port_max",
",",
"port_min",
",",
"protocol",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"ret",
"=",
"mgr",
".",
"add_securitygroup_rule",
"(",
"securitygroup_id",
",",
"remote_ip",
",",
"remote_group",
",",
"direction",
",",
"ethertype",
",",
"port_max",
",",
"port_min",
",",
"protocol",
")",
"if",
"not",
"ret",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Failed to add security group rule\"",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"REQUEST_RULES_COLUMNS",
")",
"table",
".",
"add_row",
"(",
"[",
"ret",
"[",
"'requestId'",
"]",
",",
"str",
"(",
"ret",
"[",
"'rules'",
"]",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | Add a security group rule to a security group.
\b
Examples:
# Add an SSH rule (TCP port 22) to a security group
slcli sg rule-add 384727 \\
--direction ingress \\
--protocol tcp \\
--port-min 22 \\
--port-max 22
\b
# Add a ping rule (ICMP type 8 code 0) to a security group
slcli sg rule-add 384727 \\
--direction ingress \\
--protocol icmp \\
--port-min 8 \\
--port-max 0 | [
"Add",
"a",
"security",
"group",
"rule",
"to",
"a",
"security",
"group",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/rule.py#L85-L118 |
1,481 | softlayer/softlayer-python | SoftLayer/CLI/securitygroup/rule.py | edit | def edit(env, securitygroup_id, rule_id, remote_ip, remote_group,
direction, ethertype, port_max, port_min, protocol):
"""Edit a security group rule in a security group."""
mgr = SoftLayer.NetworkManager(env.client)
data = {}
if remote_ip:
data['remote_ip'] = remote_ip
if remote_group:
data['remote_group'] = remote_group
if direction:
data['direction'] = direction
if ethertype:
data['ethertype'] = ethertype
if port_max is not None:
data['port_max'] = port_max
if port_min is not None:
data['port_min'] = port_min
if protocol:
data['protocol'] = protocol
ret = mgr.edit_securitygroup_rule(securitygroup_id, rule_id, **data)
if not ret:
raise exceptions.CLIAbort("Failed to edit security group rule")
table = formatting.Table(REQUEST_BOOL_COLUMNS)
table.add_row([ret['requestId']])
env.fout(table) | python | def edit(env, securitygroup_id, rule_id, remote_ip, remote_group,
direction, ethertype, port_max, port_min, protocol):
"""Edit a security group rule in a security group."""
mgr = SoftLayer.NetworkManager(env.client)
data = {}
if remote_ip:
data['remote_ip'] = remote_ip
if remote_group:
data['remote_group'] = remote_group
if direction:
data['direction'] = direction
if ethertype:
data['ethertype'] = ethertype
if port_max is not None:
data['port_max'] = port_max
if port_min is not None:
data['port_min'] = port_min
if protocol:
data['protocol'] = protocol
ret = mgr.edit_securitygroup_rule(securitygroup_id, rule_id, **data)
if not ret:
raise exceptions.CLIAbort("Failed to edit security group rule")
table = formatting.Table(REQUEST_BOOL_COLUMNS)
table.add_row([ret['requestId']])
env.fout(table) | [
"def",
"edit",
"(",
"env",
",",
"securitygroup_id",
",",
"rule_id",
",",
"remote_ip",
",",
"remote_group",
",",
"direction",
",",
"ethertype",
",",
"port_max",
",",
"port_min",
",",
"protocol",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"data",
"=",
"{",
"}",
"if",
"remote_ip",
":",
"data",
"[",
"'remote_ip'",
"]",
"=",
"remote_ip",
"if",
"remote_group",
":",
"data",
"[",
"'remote_group'",
"]",
"=",
"remote_group",
"if",
"direction",
":",
"data",
"[",
"'direction'",
"]",
"=",
"direction",
"if",
"ethertype",
":",
"data",
"[",
"'ethertype'",
"]",
"=",
"ethertype",
"if",
"port_max",
"is",
"not",
"None",
":",
"data",
"[",
"'port_max'",
"]",
"=",
"port_max",
"if",
"port_min",
"is",
"not",
"None",
":",
"data",
"[",
"'port_min'",
"]",
"=",
"port_min",
"if",
"protocol",
":",
"data",
"[",
"'protocol'",
"]",
"=",
"protocol",
"ret",
"=",
"mgr",
".",
"edit_securitygroup_rule",
"(",
"securitygroup_id",
",",
"rule_id",
",",
"*",
"*",
"data",
")",
"if",
"not",
"ret",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Failed to edit security group rule\"",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"REQUEST_BOOL_COLUMNS",
")",
"table",
".",
"add_row",
"(",
"[",
"ret",
"[",
"'requestId'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | Edit a security group rule in a security group. | [
"Edit",
"a",
"security",
"group",
"rule",
"in",
"a",
"security",
"group",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/rule.py#L139-L168 |
1,482 | softlayer/softlayer-python | SoftLayer/CLI/securitygroup/rule.py | remove | def remove(env, securitygroup_id, rule_id):
"""Remove a rule from a security group."""
mgr = SoftLayer.NetworkManager(env.client)
ret = mgr.remove_securitygroup_rule(securitygroup_id, rule_id)
if not ret:
raise exceptions.CLIAbort("Failed to remove security group rule")
table = formatting.Table(REQUEST_BOOL_COLUMNS)
table.add_row([ret['requestId']])
env.fout(table) | python | def remove(env, securitygroup_id, rule_id):
"""Remove a rule from a security group."""
mgr = SoftLayer.NetworkManager(env.client)
ret = mgr.remove_securitygroup_rule(securitygroup_id, rule_id)
if not ret:
raise exceptions.CLIAbort("Failed to remove security group rule")
table = formatting.Table(REQUEST_BOOL_COLUMNS)
table.add_row([ret['requestId']])
env.fout(table) | [
"def",
"remove",
"(",
"env",
",",
"securitygroup_id",
",",
"rule_id",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"ret",
"=",
"mgr",
".",
"remove_securitygroup_rule",
"(",
"securitygroup_id",
",",
"rule_id",
")",
"if",
"not",
"ret",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"\"Failed to remove security group rule\"",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"REQUEST_BOOL_COLUMNS",
")",
"table",
".",
"add_row",
"(",
"[",
"ret",
"[",
"'requestId'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | Remove a rule from a security group. | [
"Remove",
"a",
"rule",
"from",
"a",
"security",
"group",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/rule.py#L175-L187 |
1,483 | softlayer/softlayer-python | SoftLayer/CLI/deprecated.py | main | def main():
"""Main function for the deprecated 'sl' command."""
print("ERROR: Use the 'slcli' command instead.", file=sys.stderr)
print("> slcli %s" % ' '.join(sys.argv[1:]), file=sys.stderr)
exit(-1) | python | def main():
"""Main function for the deprecated 'sl' command."""
print("ERROR: Use the 'slcli' command instead.", file=sys.stderr)
print("> slcli %s" % ' '.join(sys.argv[1:]), file=sys.stderr)
exit(-1) | [
"def",
"main",
"(",
")",
":",
"print",
"(",
"\"ERROR: Use the 'slcli' command instead.\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"\"> slcli %s\"",
"%",
"' '",
".",
"join",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"exit",
"(",
"-",
"1",
")"
] | Main function for the deprecated 'sl' command. | [
"Main",
"function",
"for",
"the",
"deprecated",
"sl",
"command",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/deprecated.py#L11-L15 |
1,484 | softlayer/softlayer-python | SoftLayer/CLI/loadbal/group_edit.py | cli | def cli(env, identifier, allocation, port, routing_type, routing_method):
"""Edit an existing load balancer service group."""
mgr = SoftLayer.LoadBalancerManager(env.client)
loadbal_id, group_id = loadbal.parse_id(identifier)
# check if any input is provided
if not any([allocation, port, routing_type, routing_method]):
raise exceptions.CLIAbort(
'At least one property is required to be changed!')
mgr.edit_service_group(loadbal_id,
group_id,
allocation=allocation,
port=port,
routing_type=routing_type,
routing_method=routing_method)
env.fout('Load balancer service group %s is being updated!' % identifier) | python | def cli(env, identifier, allocation, port, routing_type, routing_method):
"""Edit an existing load balancer service group."""
mgr = SoftLayer.LoadBalancerManager(env.client)
loadbal_id, group_id = loadbal.parse_id(identifier)
# check if any input is provided
if not any([allocation, port, routing_type, routing_method]):
raise exceptions.CLIAbort(
'At least one property is required to be changed!')
mgr.edit_service_group(loadbal_id,
group_id,
allocation=allocation,
port=port,
routing_type=routing_type,
routing_method=routing_method)
env.fout('Load balancer service group %s is being updated!' % identifier) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"allocation",
",",
"port",
",",
"routing_type",
",",
"routing_method",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"LoadBalancerManager",
"(",
"env",
".",
"client",
")",
"loadbal_id",
",",
"group_id",
"=",
"loadbal",
".",
"parse_id",
"(",
"identifier",
")",
"# check if any input is provided",
"if",
"not",
"any",
"(",
"[",
"allocation",
",",
"port",
",",
"routing_type",
",",
"routing_method",
"]",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'At least one property is required to be changed!'",
")",
"mgr",
".",
"edit_service_group",
"(",
"loadbal_id",
",",
"group_id",
",",
"allocation",
"=",
"allocation",
",",
"port",
"=",
"port",
",",
"routing_type",
"=",
"routing_type",
",",
"routing_method",
"=",
"routing_method",
")",
"env",
".",
"fout",
"(",
"'Load balancer service group %s is being updated!'",
"%",
"identifier",
")"
] | Edit an existing load balancer service group. | [
"Edit",
"an",
"existing",
"load",
"balancer",
"service",
"group",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/group_edit.py#L25-L43 |
1,485 | softlayer/softlayer-python | SoftLayer/CLI/account/event_detail.py | cli | def cli(env, identifier, ack):
"""Details of a specific event, and ability to acknowledge event."""
# Print a list of all on going maintenance
manager = AccountManager(env.client)
event = manager.get_event(identifier)
if ack:
manager.ack_event(identifier)
env.fout(basic_event_table(event))
env.fout(impacted_table(event))
env.fout(update_table(event)) | python | def cli(env, identifier, ack):
"""Details of a specific event, and ability to acknowledge event."""
# Print a list of all on going maintenance
manager = AccountManager(env.client)
event = manager.get_event(identifier)
if ack:
manager.ack_event(identifier)
env.fout(basic_event_table(event))
env.fout(impacted_table(event))
env.fout(update_table(event)) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"ack",
")",
":",
"# Print a list of all on going maintenance",
"manager",
"=",
"AccountManager",
"(",
"env",
".",
"client",
")",
"event",
"=",
"manager",
".",
"get_event",
"(",
"identifier",
")",
"if",
"ack",
":",
"manager",
".",
"ack_event",
"(",
"identifier",
")",
"env",
".",
"fout",
"(",
"basic_event_table",
"(",
"event",
")",
")",
"env",
".",
"fout",
"(",
"impacted_table",
"(",
"event",
")",
")",
"env",
".",
"fout",
"(",
"update_table",
"(",
"event",
")",
")"
] | Details of a specific event, and ability to acknowledge event. | [
"Details",
"of",
"a",
"specific",
"event",
"and",
"ability",
"to",
"acknowledge",
"event",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/event_detail.py#L17-L29 |
1,486 | softlayer/softlayer-python | SoftLayer/CLI/account/event_detail.py | basic_event_table | def basic_event_table(event):
"""Formats a basic event table"""
table = formatting.Table(["Id", "Status", "Type", "Start", "End"],
title=utils.clean_splitlines(event.get('subject')))
table.add_row([
event.get('id'),
utils.lookup(event, 'statusCode', 'name'),
utils.lookup(event, 'notificationOccurrenceEventType', 'keyName'),
utils.clean_time(event.get('startDate')),
utils.clean_time(event.get('endDate'))
])
return table | python | def basic_event_table(event):
"""Formats a basic event table"""
table = formatting.Table(["Id", "Status", "Type", "Start", "End"],
title=utils.clean_splitlines(event.get('subject')))
table.add_row([
event.get('id'),
utils.lookup(event, 'statusCode', 'name'),
utils.lookup(event, 'notificationOccurrenceEventType', 'keyName'),
utils.clean_time(event.get('startDate')),
utils.clean_time(event.get('endDate'))
])
return table | [
"def",
"basic_event_table",
"(",
"event",
")",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"\"Id\"",
",",
"\"Status\"",
",",
"\"Type\"",
",",
"\"Start\"",
",",
"\"End\"",
"]",
",",
"title",
"=",
"utils",
".",
"clean_splitlines",
"(",
"event",
".",
"get",
"(",
"'subject'",
")",
")",
")",
"table",
".",
"add_row",
"(",
"[",
"event",
".",
"get",
"(",
"'id'",
")",
",",
"utils",
".",
"lookup",
"(",
"event",
",",
"'statusCode'",
",",
"'name'",
")",
",",
"utils",
".",
"lookup",
"(",
"event",
",",
"'notificationOccurrenceEventType'",
",",
"'keyName'",
")",
",",
"utils",
".",
"clean_time",
"(",
"event",
".",
"get",
"(",
"'startDate'",
")",
")",
",",
"utils",
".",
"clean_time",
"(",
"event",
".",
"get",
"(",
"'endDate'",
")",
")",
"]",
")",
"return",
"table"
] | Formats a basic event table | [
"Formats",
"a",
"basic",
"event",
"table"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/event_detail.py#L32-L45 |
1,487 | softlayer/softlayer-python | SoftLayer/CLI/account/event_detail.py | impacted_table | def impacted_table(event):
"""Formats a basic impacted resources table"""
table = formatting.Table([
"Type", "Id", "Hostname", "PrivateIp", "Label"
])
for item in event.get('impactedResources', []):
table.add_row([
item.get('resourceType'),
item.get('resourceTableId'),
item.get('hostname'),
item.get('privateIp'),
item.get('filterLabel')
])
return table | python | def impacted_table(event):
"""Formats a basic impacted resources table"""
table = formatting.Table([
"Type", "Id", "Hostname", "PrivateIp", "Label"
])
for item in event.get('impactedResources', []):
table.add_row([
item.get('resourceType'),
item.get('resourceTableId'),
item.get('hostname'),
item.get('privateIp'),
item.get('filterLabel')
])
return table | [
"def",
"impacted_table",
"(",
"event",
")",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"\"Type\"",
",",
"\"Id\"",
",",
"\"Hostname\"",
",",
"\"PrivateIp\"",
",",
"\"Label\"",
"]",
")",
"for",
"item",
"in",
"event",
".",
"get",
"(",
"'impactedResources'",
",",
"[",
"]",
")",
":",
"table",
".",
"add_row",
"(",
"[",
"item",
".",
"get",
"(",
"'resourceType'",
")",
",",
"item",
".",
"get",
"(",
"'resourceTableId'",
")",
",",
"item",
".",
"get",
"(",
"'hostname'",
")",
",",
"item",
".",
"get",
"(",
"'privateIp'",
")",
",",
"item",
".",
"get",
"(",
"'filterLabel'",
")",
"]",
")",
"return",
"table"
] | Formats a basic impacted resources table | [
"Formats",
"a",
"basic",
"impacted",
"resources",
"table"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/event_detail.py#L48-L61 |
1,488 | softlayer/softlayer-python | SoftLayer/CLI/account/event_detail.py | update_table | def update_table(event):
"""Formats a basic event update table"""
update_number = 0
for update in event.get('updates', []):
header = "======= Update #%s on %s =======" % (update_number, utils.clean_time(update.get('startDate')))
click.secho(header, fg='green')
update_number = update_number + 1
text = update.get('contents')
# deals with all the \r\n from the API
click.secho(utils.clean_splitlines(text)) | python | def update_table(event):
"""Formats a basic event update table"""
update_number = 0
for update in event.get('updates', []):
header = "======= Update #%s on %s =======" % (update_number, utils.clean_time(update.get('startDate')))
click.secho(header, fg='green')
update_number = update_number + 1
text = update.get('contents')
# deals with all the \r\n from the API
click.secho(utils.clean_splitlines(text)) | [
"def",
"update_table",
"(",
"event",
")",
":",
"update_number",
"=",
"0",
"for",
"update",
"in",
"event",
".",
"get",
"(",
"'updates'",
",",
"[",
"]",
")",
":",
"header",
"=",
"\"======= Update #%s on %s =======\"",
"%",
"(",
"update_number",
",",
"utils",
".",
"clean_time",
"(",
"update",
".",
"get",
"(",
"'startDate'",
")",
")",
")",
"click",
".",
"secho",
"(",
"header",
",",
"fg",
"=",
"'green'",
")",
"update_number",
"=",
"update_number",
"+",
"1",
"text",
"=",
"update",
".",
"get",
"(",
"'contents'",
")",
"# deals with all the \\r\\n from the API",
"click",
".",
"secho",
"(",
"utils",
".",
"clean_splitlines",
"(",
"text",
")",
")"
] | Formats a basic event update table | [
"Formats",
"a",
"basic",
"event",
"update",
"table"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/event_detail.py#L64-L73 |
1,489 | softlayer/softlayer-python | SoftLayer/CLI/block/list.py | cli | def cli(env, sortby, columns, datacenter, username, storage_type):
"""List block storage."""
block_manager = SoftLayer.BlockStorageManager(env.client)
block_volumes = block_manager.list_block_volumes(datacenter=datacenter,
username=username,
storage_type=storage_type,
mask=columns.mask())
table = formatting.Table(columns.columns)
table.sortby = sortby
for block_volume in block_volumes:
table.add_row([value or formatting.blank()
for value in columns.row(block_volume)])
env.fout(table) | python | def cli(env, sortby, columns, datacenter, username, storage_type):
"""List block storage."""
block_manager = SoftLayer.BlockStorageManager(env.client)
block_volumes = block_manager.list_block_volumes(datacenter=datacenter,
username=username,
storage_type=storage_type,
mask=columns.mask())
table = formatting.Table(columns.columns)
table.sortby = sortby
for block_volume in block_volumes:
table.add_row([value or formatting.blank()
for value in columns.row(block_volume)])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"sortby",
",",
"columns",
",",
"datacenter",
",",
"username",
",",
"storage_type",
")",
":",
"block_manager",
"=",
"SoftLayer",
".",
"BlockStorageManager",
"(",
"env",
".",
"client",
")",
"block_volumes",
"=",
"block_manager",
".",
"list_block_volumes",
"(",
"datacenter",
"=",
"datacenter",
",",
"username",
"=",
"username",
",",
"storage_type",
"=",
"storage_type",
",",
"mask",
"=",
"columns",
".",
"mask",
"(",
")",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"columns",
".",
"columns",
")",
"table",
".",
"sortby",
"=",
"sortby",
"for",
"block_volume",
"in",
"block_volumes",
":",
"table",
".",
"add_row",
"(",
"[",
"value",
"or",
"formatting",
".",
"blank",
"(",
")",
"for",
"value",
"in",
"columns",
".",
"row",
"(",
"block_volume",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List block storage. | [
"List",
"block",
"storage",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/list.py#L67-L82 |
1,490 | softlayer/softlayer-python | SoftLayer/CLI/object_storage/list_endpoints.py | cli | def cli(env):
"""List object storage endpoints."""
mgr = SoftLayer.ObjectStorageManager(env.client)
endpoints = mgr.list_endpoints()
table = formatting.Table(['datacenter', 'public', 'private'])
for endpoint in endpoints:
table.add_row([
endpoint['datacenter']['name'],
endpoint['public'],
endpoint['private'],
])
env.fout(table) | python | def cli(env):
"""List object storage endpoints."""
mgr = SoftLayer.ObjectStorageManager(env.client)
endpoints = mgr.list_endpoints()
table = formatting.Table(['datacenter', 'public', 'private'])
for endpoint in endpoints:
table.add_row([
endpoint['datacenter']['name'],
endpoint['public'],
endpoint['private'],
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"ObjectStorageManager",
"(",
"env",
".",
"client",
")",
"endpoints",
"=",
"mgr",
".",
"list_endpoints",
"(",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'datacenter'",
",",
"'public'",
",",
"'private'",
"]",
")",
"for",
"endpoint",
"in",
"endpoints",
":",
"table",
".",
"add_row",
"(",
"[",
"endpoint",
"[",
"'datacenter'",
"]",
"[",
"'name'",
"]",
",",
"endpoint",
"[",
"'public'",
"]",
",",
"endpoint",
"[",
"'private'",
"]",
",",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List object storage endpoints. | [
"List",
"object",
"storage",
"endpoints",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/object_storage/list_endpoints.py#L13-L27 |
1,491 | softlayer/softlayer-python | SoftLayer/CLI/virt/cancel.py | cli | def cli(env, identifier):
"""Cancel virtual servers."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
if not (env.skip_confirmations or formatting.no_going_back(vs_id)):
raise exceptions.CLIAbort('Aborted')
vsi.cancel_instance(vs_id) | python | def cli(env, identifier):
"""Cancel virtual servers."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
if not (env.skip_confirmations or formatting.no_going_back(vs_id)):
raise exceptions.CLIAbort('Aborted')
vsi.cancel_instance(vs_id) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
"identifier",
",",
"'VS'",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"no_going_back",
"(",
"vs_id",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted'",
")",
"vsi",
".",
"cancel_instance",
"(",
"vs_id",
")"
] | Cancel virtual servers. | [
"Cancel",
"virtual",
"servers",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/cancel.py#L16-L24 |
1,492 | softlayer/softlayer-python | SoftLayer/CLI/hardware/reflash_firmware.py | cli | def cli(env, identifier):
"""Reflash server firmware."""
mgr = SoftLayer.HardwareManager(env.client)
hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
if not (env.skip_confirmations or
formatting.confirm('This will power off the server with id %s and '
'reflash device firmware. Continue?' % hw_id)):
raise exceptions.CLIAbort('Aborted.')
mgr.reflash_firmware(hw_id) | python | def cli(env, identifier):
"""Reflash server firmware."""
mgr = SoftLayer.HardwareManager(env.client)
hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
if not (env.skip_confirmations or
formatting.confirm('This will power off the server with id %s and '
'reflash device firmware. Continue?' % hw_id)):
raise exceptions.CLIAbort('Aborted.')
mgr.reflash_firmware(hw_id) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"HardwareManager",
"(",
"env",
".",
"client",
")",
"hw_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'hardware'",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"confirm",
"(",
"'This will power off the server with id %s and '",
"'reflash device firmware. Continue?'",
"%",
"hw_id",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted.'",
")",
"mgr",
".",
"reflash_firmware",
"(",
"hw_id",
")"
] | Reflash server firmware. | [
"Reflash",
"server",
"firmware",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/reflash_firmware.py#L16-L26 |
1,493 | softlayer/softlayer-python | SoftLayer/CLI/file/snapshot/schedule_list.py | cli | def cli(env, volume_id):
"""Lists snapshot schedules for a given volume"""
file_manager = SoftLayer.FileStorageManager(env.client)
snapshot_schedules = file_manager.list_volume_schedules(volume_id)
table = formatting.Table(['id',
'active',
'type',
'replication',
'date_created',
'minute',
'hour',
'day',
'week',
'day_of_week',
'date_of_month',
'month_of_year',
'maximum_snapshots'])
for schedule in snapshot_schedules:
if 'REPLICATION' in schedule['type']['keyname']:
replication = '*'
else:
replication = formatting.blank()
file_schedule_type = schedule['type']['keyname'].replace('REPLICATION_', '')
file_schedule_type = file_schedule_type.replace('SNAPSHOT_', '')
property_list = ['MINUTE', 'HOUR', 'DAY', 'WEEK',
'DAY_OF_WEEK', 'DAY_OF_MONTH',
'MONTH_OF_YEAR', 'SNAPSHOT_LIMIT']
schedule_properties = []
for prop_key in property_list:
item = formatting.blank()
for schedule_property in schedule.get('properties', []):
if schedule_property['type']['keyname'] == prop_key:
if schedule_property['value'] == '-1':
item = '*'
else:
item = schedule_property['value']
break
schedule_properties.append(item)
table_row = [
schedule['id'],
'*' if schedule.get('active', '') else '',
file_schedule_type,
replication,
schedule.get('createDate', '')
]
table_row.extend(schedule_properties)
table.add_row(table_row)
env.fout(table) | python | def cli(env, volume_id):
"""Lists snapshot schedules for a given volume"""
file_manager = SoftLayer.FileStorageManager(env.client)
snapshot_schedules = file_manager.list_volume_schedules(volume_id)
table = formatting.Table(['id',
'active',
'type',
'replication',
'date_created',
'minute',
'hour',
'day',
'week',
'day_of_week',
'date_of_month',
'month_of_year',
'maximum_snapshots'])
for schedule in snapshot_schedules:
if 'REPLICATION' in schedule['type']['keyname']:
replication = '*'
else:
replication = formatting.blank()
file_schedule_type = schedule['type']['keyname'].replace('REPLICATION_', '')
file_schedule_type = file_schedule_type.replace('SNAPSHOT_', '')
property_list = ['MINUTE', 'HOUR', 'DAY', 'WEEK',
'DAY_OF_WEEK', 'DAY_OF_MONTH',
'MONTH_OF_YEAR', 'SNAPSHOT_LIMIT']
schedule_properties = []
for prop_key in property_list:
item = formatting.blank()
for schedule_property in schedule.get('properties', []):
if schedule_property['type']['keyname'] == prop_key:
if schedule_property['value'] == '-1':
item = '*'
else:
item = schedule_property['value']
break
schedule_properties.append(item)
table_row = [
schedule['id'],
'*' if schedule.get('active', '') else '',
file_schedule_type,
replication,
schedule.get('createDate', '')
]
table_row.extend(schedule_properties)
table.add_row(table_row)
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
")",
":",
"file_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"snapshot_schedules",
"=",
"file_manager",
".",
"list_volume_schedules",
"(",
"volume_id",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'active'",
",",
"'type'",
",",
"'replication'",
",",
"'date_created'",
",",
"'minute'",
",",
"'hour'",
",",
"'day'",
",",
"'week'",
",",
"'day_of_week'",
",",
"'date_of_month'",
",",
"'month_of_year'",
",",
"'maximum_snapshots'",
"]",
")",
"for",
"schedule",
"in",
"snapshot_schedules",
":",
"if",
"'REPLICATION'",
"in",
"schedule",
"[",
"'type'",
"]",
"[",
"'keyname'",
"]",
":",
"replication",
"=",
"'*'",
"else",
":",
"replication",
"=",
"formatting",
".",
"blank",
"(",
")",
"file_schedule_type",
"=",
"schedule",
"[",
"'type'",
"]",
"[",
"'keyname'",
"]",
".",
"replace",
"(",
"'REPLICATION_'",
",",
"''",
")",
"file_schedule_type",
"=",
"file_schedule_type",
".",
"replace",
"(",
"'SNAPSHOT_'",
",",
"''",
")",
"property_list",
"=",
"[",
"'MINUTE'",
",",
"'HOUR'",
",",
"'DAY'",
",",
"'WEEK'",
",",
"'DAY_OF_WEEK'",
",",
"'DAY_OF_MONTH'",
",",
"'MONTH_OF_YEAR'",
",",
"'SNAPSHOT_LIMIT'",
"]",
"schedule_properties",
"=",
"[",
"]",
"for",
"prop_key",
"in",
"property_list",
":",
"item",
"=",
"formatting",
".",
"blank",
"(",
")",
"for",
"schedule_property",
"in",
"schedule",
".",
"get",
"(",
"'properties'",
",",
"[",
"]",
")",
":",
"if",
"schedule_property",
"[",
"'type'",
"]",
"[",
"'keyname'",
"]",
"==",
"prop_key",
":",
"if",
"schedule_property",
"[",
"'value'",
"]",
"==",
"'-1'",
":",
"item",
"=",
"'*'",
"else",
":",
"item",
"=",
"schedule_property",
"[",
"'value'",
"]",
"break",
"schedule_properties",
".",
"append",
"(",
"item",
")",
"table_row",
"=",
"[",
"schedule",
"[",
"'id'",
"]",
",",
"'*'",
"if",
"schedule",
".",
"get",
"(",
"'active'",
",",
"''",
")",
"else",
"''",
",",
"file_schedule_type",
",",
"replication",
",",
"schedule",
".",
"get",
"(",
"'createDate'",
",",
"''",
")",
"]",
"table_row",
".",
"extend",
"(",
"schedule_properties",
")",
"table",
".",
"add_row",
"(",
"table_row",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | Lists snapshot schedules for a given volume | [
"Lists",
"snapshot",
"schedules",
"for",
"a",
"given",
"volume"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/snapshot/schedule_list.py#L13-L70 |
1,494 | softlayer/softlayer-python | SoftLayer/CLI/firewall/list.py | cli | def cli(env):
"""List firewalls."""
mgr = SoftLayer.FirewallManager(env.client)
table = formatting.Table(['firewall id',
'type',
'features',
'server/vlan id'])
fwvlans = mgr.get_firewalls()
dedicated_firewalls = [firewall for firewall in fwvlans
if firewall['dedicatedFirewallFlag']]
for vlan in dedicated_firewalls:
features = []
if vlan['highAvailabilityFirewallFlag']:
features.append('HA')
if features:
feature_list = formatting.listing(features, separator=',')
else:
feature_list = formatting.blank()
table.add_row([
'vlan:%s' % vlan['networkVlanFirewall']['id'],
'VLAN - dedicated',
feature_list,
vlan['id']
])
shared_vlan = [firewall for firewall in fwvlans
if not firewall['dedicatedFirewallFlag']]
for vlan in shared_vlan:
vs_firewalls = [guest
for guest in vlan['firewallGuestNetworkComponents']
if has_firewall_component(guest)]
for firewall in vs_firewalls:
table.add_row([
'vs:%s' % firewall['id'],
'Virtual Server - standard',
'-',
firewall['guestNetworkComponent']['guest']['id']
])
server_firewalls = [server
for server in vlan['firewallNetworkComponents']
if has_firewall_component(server)]
for firewall in server_firewalls:
table.add_row([
'server:%s' % firewall['id'],
'Server - standard',
'-',
utils.lookup(firewall,
'networkComponent',
'downlinkComponent',
'hardwareId')
])
env.fout(table) | python | def cli(env):
"""List firewalls."""
mgr = SoftLayer.FirewallManager(env.client)
table = formatting.Table(['firewall id',
'type',
'features',
'server/vlan id'])
fwvlans = mgr.get_firewalls()
dedicated_firewalls = [firewall for firewall in fwvlans
if firewall['dedicatedFirewallFlag']]
for vlan in dedicated_firewalls:
features = []
if vlan['highAvailabilityFirewallFlag']:
features.append('HA')
if features:
feature_list = formatting.listing(features, separator=',')
else:
feature_list = formatting.blank()
table.add_row([
'vlan:%s' % vlan['networkVlanFirewall']['id'],
'VLAN - dedicated',
feature_list,
vlan['id']
])
shared_vlan = [firewall for firewall in fwvlans
if not firewall['dedicatedFirewallFlag']]
for vlan in shared_vlan:
vs_firewalls = [guest
for guest in vlan['firewallGuestNetworkComponents']
if has_firewall_component(guest)]
for firewall in vs_firewalls:
table.add_row([
'vs:%s' % firewall['id'],
'Virtual Server - standard',
'-',
firewall['guestNetworkComponent']['guest']['id']
])
server_firewalls = [server
for server in vlan['firewallNetworkComponents']
if has_firewall_component(server)]
for firewall in server_firewalls:
table.add_row([
'server:%s' % firewall['id'],
'Server - standard',
'-',
utils.lookup(firewall,
'networkComponent',
'downlinkComponent',
'hardwareId')
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"FirewallManager",
"(",
"env",
".",
"client",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'firewall id'",
",",
"'type'",
",",
"'features'",
",",
"'server/vlan id'",
"]",
")",
"fwvlans",
"=",
"mgr",
".",
"get_firewalls",
"(",
")",
"dedicated_firewalls",
"=",
"[",
"firewall",
"for",
"firewall",
"in",
"fwvlans",
"if",
"firewall",
"[",
"'dedicatedFirewallFlag'",
"]",
"]",
"for",
"vlan",
"in",
"dedicated_firewalls",
":",
"features",
"=",
"[",
"]",
"if",
"vlan",
"[",
"'highAvailabilityFirewallFlag'",
"]",
":",
"features",
".",
"append",
"(",
"'HA'",
")",
"if",
"features",
":",
"feature_list",
"=",
"formatting",
".",
"listing",
"(",
"features",
",",
"separator",
"=",
"','",
")",
"else",
":",
"feature_list",
"=",
"formatting",
".",
"blank",
"(",
")",
"table",
".",
"add_row",
"(",
"[",
"'vlan:%s'",
"%",
"vlan",
"[",
"'networkVlanFirewall'",
"]",
"[",
"'id'",
"]",
",",
"'VLAN - dedicated'",
",",
"feature_list",
",",
"vlan",
"[",
"'id'",
"]",
"]",
")",
"shared_vlan",
"=",
"[",
"firewall",
"for",
"firewall",
"in",
"fwvlans",
"if",
"not",
"firewall",
"[",
"'dedicatedFirewallFlag'",
"]",
"]",
"for",
"vlan",
"in",
"shared_vlan",
":",
"vs_firewalls",
"=",
"[",
"guest",
"for",
"guest",
"in",
"vlan",
"[",
"'firewallGuestNetworkComponents'",
"]",
"if",
"has_firewall_component",
"(",
"guest",
")",
"]",
"for",
"firewall",
"in",
"vs_firewalls",
":",
"table",
".",
"add_row",
"(",
"[",
"'vs:%s'",
"%",
"firewall",
"[",
"'id'",
"]",
",",
"'Virtual Server - standard'",
",",
"'-'",
",",
"firewall",
"[",
"'guestNetworkComponent'",
"]",
"[",
"'guest'",
"]",
"[",
"'id'",
"]",
"]",
")",
"server_firewalls",
"=",
"[",
"server",
"for",
"server",
"in",
"vlan",
"[",
"'firewallNetworkComponents'",
"]",
"if",
"has_firewall_component",
"(",
"server",
")",
"]",
"for",
"firewall",
"in",
"server_firewalls",
":",
"table",
".",
"add_row",
"(",
"[",
"'server:%s'",
"%",
"firewall",
"[",
"'id'",
"]",
",",
"'Server - standard'",
",",
"'-'",
",",
"utils",
".",
"lookup",
"(",
"firewall",
",",
"'networkComponent'",
",",
"'downlinkComponent'",
",",
"'hardwareId'",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List firewalls. | [
"List",
"firewalls",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/list.py#L14-L73 |
1,495 | softlayer/softlayer-python | SoftLayer/CLI/subnet/cancel.py | cli | def cli(env, identifier):
"""Cancel a subnet."""
mgr = SoftLayer.NetworkManager(env.client)
subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier,
name='subnet')
if not (env.skip_confirmations or formatting.no_going_back(subnet_id)):
raise exceptions.CLIAbort('Aborted')
mgr.cancel_subnet(subnet_id) | python | def cli(env, identifier):
"""Cancel a subnet."""
mgr = SoftLayer.NetworkManager(env.client)
subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier,
name='subnet')
if not (env.skip_confirmations or formatting.no_going_back(subnet_id)):
raise exceptions.CLIAbort('Aborted')
mgr.cancel_subnet(subnet_id) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"subnet_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_subnet_ids",
",",
"identifier",
",",
"name",
"=",
"'subnet'",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"no_going_back",
"(",
"subnet_id",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted'",
")",
"mgr",
".",
"cancel_subnet",
"(",
"subnet_id",
")"
] | Cancel a subnet. | [
"Cancel",
"a",
"subnet",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/subnet/cancel.py#L16-L26 |
1,496 | softlayer/softlayer-python | SoftLayer/CLI/config/__init__.py | get_settings_from_client | def get_settings_from_client(client):
"""Pull out settings from a SoftLayer.BaseClient instance.
:param client: SoftLayer.BaseClient instance
"""
settings = {
'username': '',
'api_key': '',
'timeout': '',
'endpoint_url': '',
}
try:
settings['username'] = client.auth.username
settings['api_key'] = client.auth.api_key
except AttributeError:
pass
transport = _resolve_transport(client.transport)
try:
settings['timeout'] = transport.timeout
settings['endpoint_url'] = transport.endpoint_url
except AttributeError:
pass
return settings | python | def get_settings_from_client(client):
"""Pull out settings from a SoftLayer.BaseClient instance.
:param client: SoftLayer.BaseClient instance
"""
settings = {
'username': '',
'api_key': '',
'timeout': '',
'endpoint_url': '',
}
try:
settings['username'] = client.auth.username
settings['api_key'] = client.auth.api_key
except AttributeError:
pass
transport = _resolve_transport(client.transport)
try:
settings['timeout'] = transport.timeout
settings['endpoint_url'] = transport.endpoint_url
except AttributeError:
pass
return settings | [
"def",
"get_settings_from_client",
"(",
"client",
")",
":",
"settings",
"=",
"{",
"'username'",
":",
"''",
",",
"'api_key'",
":",
"''",
",",
"'timeout'",
":",
"''",
",",
"'endpoint_url'",
":",
"''",
",",
"}",
"try",
":",
"settings",
"[",
"'username'",
"]",
"=",
"client",
".",
"auth",
".",
"username",
"settings",
"[",
"'api_key'",
"]",
"=",
"client",
".",
"auth",
".",
"api_key",
"except",
"AttributeError",
":",
"pass",
"transport",
"=",
"_resolve_transport",
"(",
"client",
".",
"transport",
")",
"try",
":",
"settings",
"[",
"'timeout'",
"]",
"=",
"transport",
".",
"timeout",
"settings",
"[",
"'endpoint_url'",
"]",
"=",
"transport",
".",
"endpoint_url",
"except",
"AttributeError",
":",
"pass",
"return",
"settings"
] | Pull out settings from a SoftLayer.BaseClient instance.
:param client: SoftLayer.BaseClient instance | [
"Pull",
"out",
"settings",
"from",
"a",
"SoftLayer",
".",
"BaseClient",
"instance",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/config/__init__.py#L16-L40 |
1,497 | softlayer/softlayer-python | SoftLayer/CLI/config/__init__.py | config_table | def config_table(settings):
"""Returns a config table."""
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['Username', settings['username'] or 'not set'])
table.add_row(['API Key', settings['api_key'] or 'not set'])
table.add_row(['Endpoint URL', settings['endpoint_url'] or 'not set'])
table.add_row(['Timeout', settings['timeout'] or 'not set'])
return table | python | def config_table(settings):
"""Returns a config table."""
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['Username', settings['username'] or 'not set'])
table.add_row(['API Key', settings['api_key'] or 'not set'])
table.add_row(['Endpoint URL', settings['endpoint_url'] or 'not set'])
table.add_row(['Timeout', settings['timeout'] or 'not set'])
return table | [
"def",
"config_table",
"(",
"settings",
")",
":",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'Username'",
",",
"settings",
"[",
"'username'",
"]",
"or",
"'not set'",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'API Key'",
",",
"settings",
"[",
"'api_key'",
"]",
"or",
"'not set'",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Endpoint URL'",
",",
"settings",
"[",
"'endpoint_url'",
"]",
"or",
"'not set'",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Timeout'",
",",
"settings",
"[",
"'timeout'",
"]",
"or",
"'not set'",
"]",
")",
"return",
"table"
] | Returns a config table. | [
"Returns",
"a",
"config",
"table",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/config/__init__.py#L43-L52 |
1,498 | softlayer/softlayer-python | SoftLayer/CLI/virt/capacity/create.py | cli | def cli(env, name, backend_router_id, flavor, instances, test=False):
"""Create a Reserved Capacity instance.
*WARNING*: Reserved Capacity is on a yearly contract and not cancelable until the contract is expired.
"""
manager = CapacityManager(env.client)
result = manager.create(
name=name,
backend_router_id=backend_router_id,
flavor=flavor,
instances=instances,
test=test)
if test:
table = formatting.Table(['Name', 'Value'], "Test Order")
container = result['orderContainers'][0]
table.add_row(['Name', container['name']])
table.add_row(['Location', container['locationObject']['longName']])
for price in container['prices']:
table.add_row(['Contract', price['item']['description']])
table.add_row(['Hourly Total', result['postTaxRecurring']])
else:
table = formatting.Table(['Name', 'Value'], "Reciept")
table.add_row(['Order Date', result['orderDate']])
table.add_row(['Order ID', result['orderId']])
table.add_row(['status', result['placedOrder']['status']])
table.add_row(['Hourly Total', result['orderDetails']['postTaxRecurring']])
env.fout(table) | python | def cli(env, name, backend_router_id, flavor, instances, test=False):
"""Create a Reserved Capacity instance.
*WARNING*: Reserved Capacity is on a yearly contract and not cancelable until the contract is expired.
"""
manager = CapacityManager(env.client)
result = manager.create(
name=name,
backend_router_id=backend_router_id,
flavor=flavor,
instances=instances,
test=test)
if test:
table = formatting.Table(['Name', 'Value'], "Test Order")
container = result['orderContainers'][0]
table.add_row(['Name', container['name']])
table.add_row(['Location', container['locationObject']['longName']])
for price in container['prices']:
table.add_row(['Contract', price['item']['description']])
table.add_row(['Hourly Total', result['postTaxRecurring']])
else:
table = formatting.Table(['Name', 'Value'], "Reciept")
table.add_row(['Order Date', result['orderDate']])
table.add_row(['Order ID', result['orderId']])
table.add_row(['status', result['placedOrder']['status']])
table.add_row(['Hourly Total', result['orderDetails']['postTaxRecurring']])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"name",
",",
"backend_router_id",
",",
"flavor",
",",
"instances",
",",
"test",
"=",
"False",
")",
":",
"manager",
"=",
"CapacityManager",
"(",
"env",
".",
"client",
")",
"result",
"=",
"manager",
".",
"create",
"(",
"name",
"=",
"name",
",",
"backend_router_id",
"=",
"backend_router_id",
",",
"flavor",
"=",
"flavor",
",",
"instances",
"=",
"instances",
",",
"test",
"=",
"test",
")",
"if",
"test",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Name'",
",",
"'Value'",
"]",
",",
"\"Test Order\"",
")",
"container",
"=",
"result",
"[",
"'orderContainers'",
"]",
"[",
"0",
"]",
"table",
".",
"add_row",
"(",
"[",
"'Name'",
",",
"container",
"[",
"'name'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Location'",
",",
"container",
"[",
"'locationObject'",
"]",
"[",
"'longName'",
"]",
"]",
")",
"for",
"price",
"in",
"container",
"[",
"'prices'",
"]",
":",
"table",
".",
"add_row",
"(",
"[",
"'Contract'",
",",
"price",
"[",
"'item'",
"]",
"[",
"'description'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Hourly Total'",
",",
"result",
"[",
"'postTaxRecurring'",
"]",
"]",
")",
"else",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'Name'",
",",
"'Value'",
"]",
",",
"\"Reciept\"",
")",
"table",
".",
"add_row",
"(",
"[",
"'Order Date'",
",",
"result",
"[",
"'orderDate'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Order ID'",
",",
"result",
"[",
"'orderId'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'status'",
",",
"result",
"[",
"'placedOrder'",
"]",
"[",
"'status'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Hourly Total'",
",",
"result",
"[",
"'orderDetails'",
"]",
"[",
"'postTaxRecurring'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | Create a Reserved Capacity instance.
*WARNING*: Reserved Capacity is on a yearly contract and not cancelable until the contract is expired. | [
"Create",
"a",
"Reserved",
"Capacity",
"instance",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/capacity/create.py#L24-L51 |
1,499 | softlayer/softlayer-python | SoftLayer/CLI/cdn/origin_list.py | cli | def cli(env, account_id):
"""List origin pull mappings."""
manager = SoftLayer.CDNManager(env.client)
origins = manager.get_origins(account_id)
table = formatting.Table(['id', 'media_type', 'cname', 'origin_url'])
for origin in origins:
table.add_row([origin['id'],
origin['mediaType'],
origin.get('cname', formatting.blank()),
origin['originUrl']])
env.fout(table) | python | def cli(env, account_id):
"""List origin pull mappings."""
manager = SoftLayer.CDNManager(env.client)
origins = manager.get_origins(account_id)
table = formatting.Table(['id', 'media_type', 'cname', 'origin_url'])
for origin in origins:
table.add_row([origin['id'],
origin['mediaType'],
origin.get('cname', formatting.blank()),
origin['originUrl']])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"account_id",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"CDNManager",
"(",
"env",
".",
"client",
")",
"origins",
"=",
"manager",
".",
"get_origins",
"(",
"account_id",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'media_type'",
",",
"'cname'",
",",
"'origin_url'",
"]",
")",
"for",
"origin",
"in",
"origins",
":",
"table",
".",
"add_row",
"(",
"[",
"origin",
"[",
"'id'",
"]",
",",
"origin",
"[",
"'mediaType'",
"]",
",",
"origin",
".",
"get",
"(",
"'cname'",
",",
"formatting",
".",
"blank",
"(",
")",
")",
",",
"origin",
"[",
"'originUrl'",
"]",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List origin pull mappings. | [
"List",
"origin",
"pull",
"mappings",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/cdn/origin_list.py#L14-L28 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.