def get_private_images(self, guid=None, name=None, limit=None, marker=None): _filter = sl_utils.NestedDict() if name: _filter['privateBlockDeviceTemplateGroups']['name'] = ( sl_utils.query_filter(name)) if marker is not None: _filter['privateBlockDeviceTemplateGroups']['globalIdentifier'] = ( sl_utils.query_filter('> %s' % marker)) if guid: _filter['privateBlockDeviceTemplateGroups'] = { 'globalIdentifier': sl_utils.query_filter(guid)} params = {} params['mask'] = self.image_mask if _filter: params['filter'] = _filter.to_dict() if limit: params['limit'] = limit account = self.client['Account'] return account.getPrivateBlockDeviceTemplateGroups(**params)
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_package(self, category_code): """Returns a product packaged based on type of storage. :param category_code: Category code of product package. :return: Returns a packaged based on type of storage. """ _filter = utils.NestedDict({}) _filter['categories']['categoryCode'] = ( utils.query_filter(category_code)) _filter['statusCode'] = (utils.query_filter('ACTIVE')) packages = self.client.call('Product_Package', 'getAllObjects', filter=_filter.to_dict(), mask=""" id, name, items[prices[categories],attributes] """) if len(packages) == 0: raise ValueError('No packages were found for %s' % category_code) if len(packages) > 1: raise ValueError('More than one package was found for %s' % category_code) return packages[0]
def list_vlans(self, datacenter=None, vlan_number=None, name=None, **kwargs): """ Display a list of all VLANs on the account. This provides a quick overview of all VLANs including information about data center residence and the number of devices attached. :param string datacenter: If specified, the list will only contain VLANs in the specified data center. :param int vlan_number: If specified, the list will only contain the VLAN matching this VLAN number. :param int name: If specified, the list will only contain the VLAN matching this VLAN name. :param dict \*\*kwargs: response-level arguments (limit, offset, etc.) """ _filter = NestedDict(kwargs.get("filter") or {}) if vlan_number: _filter["networkVlans"]["vlanNumber"] = query_filter(vlan_number) if name: _filter["networkVlans"]["name"] = query_filter(name) if datacenter: _filter["networkVlans"]["primaryRouter"]["datacenter"]["name"] = query_filter(datacenter) kwargs["filter"] = _filter.to_dict() if "mask" not in kwargs: kwargs["mask"] = self._get_vlan_mask() return self.account.getNetworkVlans(**kwargs)
def get_records(self, zone_id, ttl=None, data=None, host=None, type=None, **kwargs): """ List, and optionally filter, records within a zone. :param zone: the zone name in which to search. :param int ttl: optionally, time in seconds: :param data: optionally, the records data :param host: optionally, record's host :param type: optionally, the type of record: :returns: A list of dictionaries representing the matching records within the specified zone. """ _filter = NestedDict() if ttl: _filter['resourceRecords']['ttl'] = query_filter(ttl) if host: _filter['resourceRecords']['host'] = query_filter(host) if data: _filter['resourceRecords']['data'] = query_filter(data) if type: _filter['resourceRecords']['type'] = query_filter(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 list_subnets(self, identifier=None, datacenter=None, version=0, subnet_type=None, **kwargs): """ Display a list of all subnets on the account. This provides a quick overview of all subnets including information about data center residence and the number of devices attached. :param string identifier: If specified, the list will only contain the subnet matching this network identifier. :param string datacenter: If specified, the list will only contain subnets in the specified data center. :param int version: Only returns subnets of this version (4 or 6). :param string subnet_type: If specified, it will only returns subnets of this type. :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if "mask" not in kwargs: kwargs["mask"] = DEFAULT_SUBNET_MASK _filter = NestedDict(kwargs.get("filter") or {}) if identifier: _filter["subnets"]["networkIdentifier"] = query_filter(identifier) if datacenter: _filter["subnets"]["datacenter"]["name"] = query_filter(datacenter) if version: _filter["subnets"]["version"] = query_filter(version) if subnet_type: _filter["subnets"]["subnetType"] = query_filter(subnet_type) else: # This filters out global IPs from the subnet listing. _filter["subnets"]["subnetType"] = {"operation": "!= GLOBAL_IP"} kwargs["filter"] = _filter.to_dict() return self.account.getSubnets(**kwargs)
def list_vlans(self, datacenter=None, vlan_number=None, **kwargs): """ Display a list of all VLANs on the account. This provides a quick overview of all VLANs including information about data center residence and the number of devices attached. :param string datacenter: If specified, the list will only contain VLANs in the specified data center. :param int vlan_number: If specified, the list will only contain the VLAN matching this VLAN number. :param dict \*\*kwargs: response-level arguments (limit, offset, etc.) """ _filter = NestedDict(kwargs.get('filter') or {}) if vlan_number: _filter['networkVlans']['vlanNumber'] = query_filter(vlan_number) if datacenter: _filter['networkVlans']['primaryRouter']['datacenter']['name'] = \ query_filter(datacenter) kwargs['filter'] = _filter.to_dict() return self._get_vlans(**kwargs)
def list_vlans(self, datacenter=None, vlan_number=None, name=None, **kwargs): """Display a list of all VLANs on the account. This provides a quick overview of all VLANs including information about data center residence and the number of devices attached. :param string datacenter: If specified, the list will only contain VLANs in the specified data center. :param int vlan_number: If specified, the list will only contain the VLAN matching this VLAN number. :param int name: If specified, the list will only contain the VLAN matching this VLAN name. :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ _filter = utils.NestedDict(kwargs.get('filter') or {}) if vlan_number: _filter['networkVlans']['vlanNumber'] = ( utils.query_filter(vlan_number)) if name: _filter['networkVlans']['name'] = utils.query_filter(name) if datacenter: _filter['networkVlans']['primaryRouter']['datacenter']['name'] = ( utils.query_filter(datacenter)) kwargs['filter'] = _filter.to_dict() if 'mask' not in kwargs: kwargs['mask'] = DEFAULT_VLAN_MASK return self.account.getNetworkVlans(**kwargs)
def find_free_volume(self, size, imported): """ Find a volume in the pool of the given size. :param size: size to search for. :param imported: list of imported volumes :returns: sl_vol: SoftLayer iSCSI volume representation """ _filter = NestedDict({}) if self.configuration.sl_vol_order_ceil: _filter['iscsiNetworkStorage'][ 'capacityGb'] = query_filter('>=%s' % size) else: _filter['iscsiNetworkStorage']['capacityGb'] = query_filter(size) _filter['iscsiNetworkStorage'][ 'billingItem'][ 'location'][ 'id'] = query_filter(self.location) sl_volumes = self.client['Account'].getIscsiNetworkStorage( mask='mask[id,capacityGb,' 'username,password,billingItem[id]]', filter=_filter.to_dict()) if len(sl_volumes) == 0: return None sl_volumes = sorted(sl_volumes, key=lambda x: int(x['capacityGb'])) for sl_vol in sl_volumes: if sl_vol['id'] in imported: continue return self._get_vol(sl_vol['id']) LOG.warn(_("No free volume found of size %s" % size)) return None
def _find_item(self, size, category_code, ceil): """ Find the item_price IDs for the iSCSIs of given size :param int size: iSCSI volume size :returns: Returns a list of item price IDs matching the given volume size or first large enough size, if the `sl_vol_order_ceil` configuration value is se """ _filter = NestedDict({}) _filter[ 'items'][ 'categories'][ 'categoryCode'] = query_filter(category_code) if ceil: _filter['items'][ 'capacity'] = query_filter('>=%s' % size) else: _filter['items']['capacity'] = query_filter(size) iscsi_item_prices = self.client['Product_Package'].getItems( id=0, mask=','.join(('id', 'prices', 'capacity')), filter=_filter.to_dict()) if len(iscsi_item_prices) == 0: return None iscsi_item_prices = sorted( iscsi_item_prices, key=lambda x: float(x['capacity'])) return iscsi_item_prices[0]['prices'][0]['id']
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 get_standard_package(self, server_id, is_cci=True): """ Retrieves the standard firewall package for the CCI. :param int server_id: The ID of the server to create the firewall for :param bool is_cci: True if the id provided is for a CCI, False for a server :returns: A dictionary containing the standard CCI firewall package """ mask = ('mask[primaryNetworkComponent[speed]]') if is_cci: svc = self.client['Virtual_Guest'] else: svc = self.client['Hardware_Server'] item = svc.getObject(mask=mask, id=server_id) _filter = NestedDict({}) _value = "%s%s" % (item['primaryNetworkComponent']['speed'], "Mbps Hardware Firewall") _filter['items']['description'] = query_filter(_value) kwargs = NestedDict({}) kwargs['id'] = 0 # look at package id 0 kwargs['filter'] = _filter.to_dict() return self.prod_pkg.getItems(**kwargs)
def list_subnets(self, identifier=None, datacenter=None, version=0, subnet_type=None, **kwargs): """ Display a list of all subnets on the account. This provides a quick overview of all subnets including information about data center residence and the number of devices attached. :param string identifier: If specified, the list will only contain the subnet matching this network identifier. :param string datacenter: If specified, the list will only contain subnets in the specified data center. :param int version: Only returns subnets of this version (4 or 6). :param string subnet_type: If specified, it will only returns subnets of this type. :param dict \*\*kwargs: response-level arguments (limit, offset, etc.) """ if 'mask' not in kwargs: mask = self._get_subnet_mask() kwargs['mask'] = 'mask[%s]' % ','.join(mask) _filter = NestedDict(kwargs.get('filter') or {}) if identifier: _filter['subnets']['networkIdentifier'] = query_filter(identifier) if datacenter: _filter['subnets']['datacenter']['name'] = \ query_filter(datacenter) if version: _filter['subnets']['version'] = query_filter(version) if subnet_type: _filter['subnets']['subnetType'] = query_filter(subnet_type) else: # This filters out global IPs from the subnet listing. _filter['subnets']['subnetType'] = {'operation': 'not null'} kwargs['filter'] = _filter.to_dict() results = [] # Filtering out routed global IPs here. This is being done in code # because of complications getting the object filter syntax working. for subnet in self.account.getSubnets(**kwargs): if 'GLOBAL_IP' not in subnet['subnetType']: results.append(subnet) return results
def get_dedicated_package(self, ha_enabled=False): """Retrieves the dedicated firewall package. :param bool ha_enabled: True if HA is to be enabled on the firewall False for No HA :returns: A dictionary containing the dedicated CCI firewall package """ fwl_filter = 'Hardware Firewall (Dedicated)' ha_fwl_filter = 'Hardware Firewall (High Availability)' _filter = utils.NestedDict({}) if ha_enabled: _filter['items']['description'] = utils.query_filter(ha_fwl_filter) else: _filter['items']['description'] = utils.query_filter(fwl_filter) return self.prod_pkg.getItems(id=0, filter=_filter.to_dict())
def list_block_volumes(self, datacenter=None, username=None, storage_type=None, **kwargs): """Returns a list of block volumes. :param datacenter: Datacenter short name (e.g.: dal09) :param username: Name of volume. :param storage_type: Type of volume: Endurance or Performance :param kwargs: :return: Returns a list of block volumes. """ if 'mask' not in kwargs: items = [ 'id', 'username', 'lunId', 'capacityGb', 'bytesUsed', 'serviceResource.datacenter[name]', 'serviceResourceBackendIpAddress', 'activeTransactionCount', 'replicationPartnerCount' ] kwargs['mask'] = ','.join(items) _filter = utils.NestedDict(kwargs.get('filter') or {}) _filter['iscsiNetworkStorage']['serviceResource']['type']['type'] = \ (utils.query_filter('!~ ISCSI')) _filter['iscsiNetworkStorage']['storageType']['keyName'] = ( utils.query_filter('*BLOCK_STORAGE*')) if storage_type: _filter['iscsiNetworkStorage']['storageType']['keyName'] = ( utils.query_filter('%s_BLOCK_STORAGE*' % storage_type.upper())) if datacenter: _filter['iscsiNetworkStorage']['serviceResource']['datacenter'][ 'name'] = (utils.query_filter(datacenter)) if username: _filter['iscsiNetworkStorage']['username'] = \ (utils.query_filter(username)) kwargs['filter'] = _filter.to_dict() return self.client.call('Account', 'getIscsiNetworkStorage', **kwargs)
def list_subnets(self, identifier=None, datacenter=None, version=0, subnet_type=None, network_space=None, **kwargs): """Display a list of all subnets on the account. This provides a quick overview of all subnets including information about data center residence and the number of devices attached. :param string identifier: If specified, the list will only contain the subnet matching this network identifier. :param string datacenter: If specified, the list will only contain subnets in the specified data center. :param int version: Only returns subnets of this version (4 or 6). :param string subnet_type: If specified, it will only returns subnets of this type. :param string network_space: If specified, it will only returns subnets with the given address space label. :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if 'mask' not in kwargs: kwargs['mask'] = DEFAULT_SUBNET_MASK _filter = utils.NestedDict(kwargs.get('filter') or {}) if identifier: _filter['subnets']['networkIdentifier'] = ( utils.query_filter(identifier)) if datacenter: _filter['subnets']['datacenter']['name'] = ( utils.query_filter(datacenter)) if version: _filter['subnets']['version'] = utils.query_filter(version) if subnet_type: _filter['subnets']['subnetType'] = utils.query_filter(subnet_type) else: # This filters out global IPs from the subnet listing. _filter['subnets']['subnetType'] = {'operation': '!= GLOBAL_IP'} if network_space: _filter['subnets']['networkVlan']['networkSpace'] = ( utils.query_filter(network_space)) kwargs['filter'] = _filter.to_dict() return self.account.getSubnets(**kwargs)
def get_public_images(self, guid=None, name=None, limit=None): _filter = {} if name: _filter['name'] = query_filter(name) if guid: _filter['globalIdentifier'] = query_filter(guid) params = {} params['mask'] = self.image_mask if _filter: params['filter'] = _filter if limit: params['limit'] = limit vgbdtg = self.client['Virtual_Guest_Block_Device_Template_Group'] return vgbdtg.getPublicImages(**params)
def list_keys(self, label=None): """ Lists all SSH keys on the account. :param string label: Filter list based on SSH key label :returns: A list of dictionaries with information about each key """ _filter = utils.NestedDict({}) if label: _filter['sshKeys']['label'] = utils.query_filter(label) return self.client['Account'].getSshKeys(filter=_filter.to_dict())
def get_dedicated_package(self, ha_enabled=False): """ Retrieves the dedicated firewall package. :param bool ha_enabled: True if HA is to be enabled on the firewall False for No HA :returns: A dictionary containing the dedicated CCI firewall package """ fwl_filter = "Hardware Firewall (Dedicated)" ha_fwl_filter = "Hardware Firewall (High Availability)" _filter = utils.NestedDict({}) if ha_enabled: _filter["items"]["description"] = utils.query_filter(ha_fwl_filter) else: _filter["items"]["description"] = utils.query_filter(fwl_filter) kwargs = utils.NestedDict({}) kwargs["id"] = 0 # look at package id 0 kwargs["filter"] = _filter.to_dict() return self.prod_pkg.getItems(**kwargs)
def list_public_images(self, guid=None, name=None, **kwargs): """ List all public images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if 'mask' not in kwargs: kwargs['mask'] = IMAGE_MASK _filter = utils.NestedDict(kwargs.get('filter') or {}) if name: _filter['name'] = utils.query_filter(name) if guid: _filter['globalIdentifier'] = utils.query_filter(guid) kwargs['filter'] = _filter.to_dict() return self.vgbdtg.getPublicImages(**kwargs)
def _get_bare_metal_package_id(self): packages = self.client['Product_Package'].getAllObjects( mask='mask[id, name]', filter={'name': query_filter('Bare Metal Instance')}) hw_id = 0 for package in packages: if 'Bare Metal Instance' == package['name']: hw_id = package['id'] break return hw_id
def get_private_images(self, guid=None, name=None, limit=None): _filter = {} if name: _filter['privateBlockDeviceTemplateGroups'] = { 'name': query_filter(name)} if guid: _filter['privateBlockDeviceTemplateGroups'] = { 'globalIdentifier': query_filter(guid)} params = {} params['mask'] = self.image_mask if _filter: params['filter'] = _filter if limit: params['limit'] = limit account = self.client['Account'] return account.getPrivateBlockDeviceTemplateGroups(**params)
def list_global_ips(self, version=0): """ Returns a list of all global IP address records on the account. :param int version: Only returns IPs of this version (4 or 6). """ mask = ['destinationIpAddress[hardware, virtualGuest]', 'ipAddress'] mask = 'mask[%s]' % ','.join(mask) _filter = NestedDict({}) if version: v = query_filter(version) _filter['globalIpRecords']['ipAddress']['subnet']['version'] = v _filter = _filter.to_dict() return self.account.getGlobalIpRecords(filter=_filter, mask=mask)
def list_vlans(self, datacenter=None, vlan_number=None, name=None, **kwargs): """Display a list of all VLANs on the account. This provides a quick overview of all VLANs including information about data center residence and the number of devices attached. :param string datacenter: If specified, the list will only contain VLANs in the specified data center. :param int vlan_number: If specified, the list will only contain the VLAN matching this VLAN number. :param int name: If specified, the list will only contain the VLAN matching this VLAN name. :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ _filter = utils.NestedDict(kwargs.get('filter') or {}) if vlan_number: _filter['networkVlans']['vlanNumber'] = ( utils.query_filter(vlan_number)) if name: _filter['networkVlans']['name'] = utils.query_filter(name) if datacenter: _filter['networkVlans']['primaryRouter']['datacenter']['name'] = ( utils.query_filter(datacenter)) kwargs['filter'] = _filter.to_dict() if 'mask' not in kwargs: kwargs['mask'] = DEFAULT_VLAN_MASK kwargs['iter'] = True return self.account.getNetworkVlans(**kwargs)
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 list_subnets(self, identifier=None, datacenter=None, version=0, subnet_type=None, **kwargs): """ Display a list of all subnets on the account. This provides a quick overview of all subnets including information about data center residence and the number of devices attached. :param string identifier: If specified, the list will only contain the subnet matching this network identifier. :param string datacenter: If specified, the list will only contain subnets in the specified data center. :param int version: Only returns subnets of this version (4 or 6). :param string subnet_type: If specified, it will only returns subnets of this type. :param dict \*\*kwargs: response-level arguments (limit, offset, etc.) """ if 'mask' not in kwargs: kwargs['mask'] = ','.join(self._get_subnet_mask()) _filter = NestedDict(kwargs.get('filter') or {}) if identifier: _filter['subnets']['networkIdentifier'] = query_filter(identifier) if datacenter: _filter['subnets']['datacenter']['name'] = \ query_filter(datacenter) if version: _filter['subnets']['version'] = query_filter(version) if subnet_type: _filter['subnets']['subnetType'] = query_filter(subnet_type) else: # This filters out global IPs from the subnet listing. _filter['subnets']['subnetType'] = {'operation': '!= GLOBAL_IP'} kwargs['filter'] = _filter.to_dict() return self.account.getSubnets(**kwargs)
def list_subnets(self, identifier=None, datacenter=None, version=0, subnet_type=None, **kwargs): """Display a list of all subnets on the account. This provides a quick overview of all subnets including information about data center residence and the number of devices attached. :param string identifier: If specified, the list will only contain the subnet matching this network identifier. :param string datacenter: If specified, the list will only contain subnets in the specified data center. :param int version: Only returns subnets of this version (4 or 6). :param string subnet_type: If specified, it will only returns subnets of this type. :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if 'mask' not in kwargs: kwargs['mask'] = DEFAULT_SUBNET_MASK _filter = utils.NestedDict(kwargs.get('filter') or {}) if identifier: _filter['subnets']['networkIdentifier'] = ( utils.query_filter(identifier)) if datacenter: _filter['subnets']['datacenter']['name'] = ( utils.query_filter(datacenter)) if version: _filter['subnets']['version'] = utils.query_filter(version) if subnet_type: _filter['subnets']['subnetType'] = utils.query_filter(subnet_type) else: # This filters out global IPs from the subnet listing. _filter['subnets']['subnetType'] = {'operation': '!= GLOBAL_IP'} kwargs['filter'] = _filter.to_dict() return self.account.getSubnets(**kwargs)
def get_public_images(self, guid=None, name=None, limit=None, marker=None): _filter = sl_utils.NestedDict() if name: _filter['name'] = sl_utils.query_filter(name) if guid: _filter['globalIdentifier'] = sl_utils.query_filter(guid) if marker is not None: _filter['globalIdentifier'] = sl_utils.query_filter('> %s' % marker) params = {} params['mask'] = self.image_mask if _filter: params['filter'] = _filter.to_dict() if limit: params['limit'] = limit vgbdtg = self.client['Virtual_Guest_Block_Device_Template_Group'] return vgbdtg.getPublicImages(**params)
def get_private_images(self, guid=None, name=None, limit=None): _filter = {} if name: _filter['privateBlockDeviceTemplateGroups'] = { 'name': query_filter(name) } if guid: _filter['privateBlockDeviceTemplateGroups'] = { 'globalIdentifier': query_filter(guid) } params = {} params['mask'] = self.image_mask if _filter: params['filter'] = _filter if limit: params['limit'] = limit account = self.client['Account'] return account.getPrivateBlockDeviceTemplateGroups(**params)
def list_global_ips(self, version=None, identifier=None, **kwargs): """ Returns a list of all global IP address records on the account. :param int version: Only returns IPs of this version (4 or 6) :param string identifier: If specified, the list will only contain the global ips matching this network identifier. """ if "mask" not in kwargs: mask = ["destinationIpAddress[hardware, virtualGuest]", "ipAddress"] kwargs["mask"] = ",".join(mask) _filter = NestedDict({}) if version: ver = query_filter(version) _filter["globalIpRecords"]["ipAddress"]["subnet"]["version"] = ver if identifier: subnet_filter = _filter["globalIpRecords"]["ipAddress"]["subnet"] subnet_filter["networkIdentifier"] = query_filter(identifier) kwargs["filter"] = _filter.to_dict() return self.account.getGlobalIpRecords(**kwargs)
def list_private_images(self, guid=None, name=None, **kwargs): """List all private images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if 'mask' not in kwargs: kwargs['mask'] = IMAGE_MASK _filter = utils.NestedDict(kwargs.get('filter') or {}) if name: _filter['privateBlockDeviceTemplateGroups']['name'] = ( utils.query_filter(name)) if guid: _filter['privateBlockDeviceTemplateGroups']['globalIdentifier'] = ( utils.query_filter(guid)) kwargs['filter'] = _filter.to_dict() account = self.client['Account'] return account.getPrivateBlockDeviceTemplateGroups(**kwargs)
def list_private_images(self, guid=None, name=None, **kwargs): """ List all private images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if 'mask' not in kwargs: kwargs['mask'] = IMAGE_MASK _filter = utils.NestedDict(kwargs.get('filter') or {}) if name: _filter['privateBlockDeviceTemplateGroups']['name'] = ( utils.query_filter(name)) if guid: _filter['privateBlockDeviceTemplateGroups']['globalIdentifier'] = ( utils.query_filter(guid)) kwargs['filter'] = _filter.to_dict() account = self.client['Account'] return account.getPrivateBlockDeviceTemplateGroups(**kwargs)
def 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_standard_package(self, server_id, is_cci=True): """Retrieves the standard firewall package for the CCI. :param int server_id: The ID of the server to create the firewall for :param bool is_cci: True if the id provided is for a CCI, False for a server :returns: A dictionary containing the standard CCI firewall package """ firewall_port_speed = self._get_fwl_port_speed(server_id, is_cci) _value = "%s%s" % (firewall_port_speed, "Mbps Hardware Firewall") _filter = {'items': {'description': utils.query_filter(_value)}} return self.prod_pkg.getItems(id=0, filter=_filter)
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 list_global_ips(self, version=None, identifier=None, **kwargs): """Returns a list of all global IP address records on the account. :param int version: Only returns IPs of this version (4 or 6) :param string identifier: If specified, the list will only contain the global ips matching this network identifier. """ if 'mask' not in kwargs: mask = ['destinationIpAddress[hardware, virtualGuest]', 'ipAddress'] kwargs['mask'] = ','.join(mask) _filter = utils.NestedDict({}) if version: ver = utils.query_filter(version) _filter['globalIpRecords']['ipAddress']['subnet']['version'] = ver if identifier: subnet_filter = _filter['globalIpRecords']['ipAddress']['subnet'] subnet_filter['networkIdentifier'] = utils.query_filter(identifier) kwargs['filter'] = _filter.to_dict() return self.account.getGlobalIpRecords(**kwargs)
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_package(manager, category_code): """Returns a product package based on type of storage. :param manager: The storage manager which calls this function. :param category_code: Category code of product package. :return: Returns a packaged based on type of storage. """ _filter = utils.NestedDict({}) _filter['categories']['categoryCode'] = (utils.query_filter(category_code)) _filter['statusCode'] = (utils.query_filter('ACTIVE')) packages = manager.client.call( 'Product_Package', 'getAllObjects', filter=_filter.to_dict(), mask='id,name,items[prices[categories],attributes]') if len(packages) == 0: raise ValueError('No packages were found for %s' % category_code) if len(packages) > 1: raise ValueError('More than one package was found for %s' % category_code) return packages[0]
def _get_id_from_username(self, username): """Looks up a username's id :param string username: Username to lookup :returns: The id that matches username. """ _mask = "mask[id, username]" _filter = {'users': {'username': utils.query_filter(username)}} user = self.list_users(_mask, _filter) if len(user) == 1: return [user[0]['id']] elif len(user) > 1: raise exceptions.SoftLayerError("Multiple users found with the name: %s" % username) else: raise exceptions.SoftLayerError("Unable to find user id for %s" % username)
def 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 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 int enabled: 1 to enable the service, 0 to disable it :param int hc_type: The health check type :param int weight: the weight to give to the service """ _filter = utils.NestedDict({}) _filter['virtualServers']['serviceGroups']['services']['id'] = ( utils.query_filter(service_id)) kwargs = utils.NestedDict({}) kwargs['filter'] = _filter.to_dict() kwargs['mask'] = ('mask[serviceGroups[services[groupReferences,' 'healthChecks]]]') virtual_servers = self.lb_svc.getVirtualServers(id=loadbal_id, **kwargs) 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'] = int(port) if weight is not None: service['groupReferences'][0]['weight'] = int(weight) if hc_type is not None: service['healthChecks'][0]['healthCheckTypeId'] = ( int(hc_type)) if ip_address_id is not None: service['ipAddressId'] = ip_address_id template = {'virtualServers': virtual_servers} load_balancer = self.lb_svc.editObject(template, id=loadbal_id) return load_balancer
def get_tunnel_context(self, context_id, **kwargs): """Retrieves the network tunnel context instance. :param int context_id: The id-value representing the context instance. :return dict: Mapping of properties for the tunnel context. :raise SoftLayerAPIError: If a context cannot be found. """ _filter = utils.NestedDict(kwargs.get('filter') or {}) _filter['networkTunnelContexts']['id'] = utils.query_filter(context_id) kwargs['filter'] = _filter.to_dict() contexts = self.account.getNetworkTunnelContexts(**kwargs) if len(contexts) == 0: raise SoftLayerAPIError('SoftLayer_Exception_ObjectNotFound', 'Unable to find object with id of \'{}\'' .format(context_id)) return contexts[0]
def list_file_volumes(self, datacenter=None, username=None, storage_type=None, order=None, **kwargs): """Returns a list of file volumes. :param datacenter: Datacenter short name (e.g.: dal09) :param username: Name of volume. :param storage_type: Type of volume: Endurance or Performance :param order: Volume order id. :param kwargs: :return: Returns a list of file volumes. """ if 'mask' not in kwargs: items = [ 'id', 'username', 'capacityGb', 'bytesUsed', 'serviceResource.datacenter[name]', 'serviceResourceBackendIpAddress', 'activeTransactionCount', 'fileNetworkMountAddress', 'replicationPartnerCount' ] kwargs['mask'] = ','.join(items) _filter = utils.NestedDict(kwargs.get('filter') or {}) _filter['nasNetworkStorage']['serviceResource']['type']['type'] = \ (utils.query_filter('!~ NAS')) _filter['nasNetworkStorage']['storageType']['keyName'] = ( utils.query_filter('*FILE_STORAGE*')) if storage_type: _filter['nasNetworkStorage']['storageType']['keyName'] = ( utils.query_filter('%s_FILE_STORAGE*' % storage_type.upper())) if datacenter: _filter['nasNetworkStorage']['serviceResource']['datacenter'][ 'name'] = (utils.query_filter(datacenter)) if username: _filter['nasNetworkStorage']['username'] = \ (utils.query_filter(username)) if order: _filter['nasNetworkStorage']['billingItem']['orderItem']['order'][ 'id'] = (utils.query_filter(order)) kwargs['filter'] = _filter.to_dict() return self.client.call('Account', 'getNasNetworkStorage', iter=True, **kwargs)
def get_standard_package(self, server_id, is_cci=True): """ Retrieves the standard firewall package for the CCI. :param int server_id: The ID of the server to create the firewall for :param bool is_cci: True if the id provided is for a CCI, False for a server :returns: A dictionary containing the standard CCI firewall package """ firewall_port_speed = self._get_fwl_port_speed(server_id, is_cci) _filter = utils.NestedDict({}) _value = "%s%s" % (firewall_port_speed, "Mbps Hardware Firewall") _filter['items']['description'] = utils.query_filter(_value) kwargs = utils.NestedDict({}) kwargs['id'] = 0 # look at package id 0 kwargs['filter'] = _filter.to_dict() return self.prod_pkg.getItems(**kwargs)
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 = utils.NestedDict({}) _filter['virtualServers']['id'] = utils.query_filter(group_id) kwargs = utils.NestedDict({}) kwargs['filter'] = _filter.to_dict() kwargs['mask'] = 'mask[serviceGroups]' virtual_servers = self.lb_svc.getVirtualServers(id=loadbal_id, **kwargs) 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 get_lb_pkgs(self): """ Retrieves the local load balancer packages. :returns: A dictionary containing the load balancer packages """ lb_filter = '*Load Balancer*' _filter = utils.NestedDict({}) _filter['items']['description'] = utils.query_filter(lb_filter) kwargs = utils.NestedDict({}) kwargs['id'] = 0 # look at package id 0 kwargs['filter'] = _filter.to_dict() packages = self.prod_pkg.getItems(**kwargs) pkgs = [] for package in packages: if not package['description'].startswith('Global'): pkgs.append(package) return pkgs
def _build_filters(_filters): """Builds filters using the filter options passed into the CLI. This only supports the equals keyword at the moment. """ root = utils.NestedDict({}) for _filter in _filters: # split "some.key=value" into ["some.key", "value"] key, value = _filter.split('=', 1) current = root # split "some.key" into ["some", "key"] parts = [part.strip() for part in key.split('.')] # Actually drill down and add the filter for part in parts[:-1]: current = current[part] current[parts[-1]] = utils.query_filter(value.strip()) return root.to_dict()
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 _build_filters(_filters): """Builds filters using the filter options passed into the CLI. This only supports the equals keyword at the moment. """ root = utils.NestedDict({}) for _filter in _filters: operation = None for operation, token in SPLIT_TOKENS: # split "some.key=value" into ["some.key", "value"] top_parts = _filter.split(token, 1) if len(top_parts) == 2: break else: raise exceptions.CLIAbort( 'Failed to find valid operation for: %s' % _filter) key, value = top_parts current = root # split "some.key" into ["some", "key"] parts = [part.strip() for part in key.split('.')] # Actually drill down and add the filter for part in parts[:-1]: current = current[part] if operation == 'eq': current[parts[-1]] = utils.query_filter(value.strip()) elif operation == 'in': current[parts[-1]] = { 'operation': 'in', 'options': [{ 'name': 'data', 'value': [p.strip() for p in value.split(',')], }], } return root.to_dict()
def _get_id_from_username(self, username): """Looks up a username's id :param string username: Username to lookup :returns: The id that matches username. """ _mask = "mask[id,username]" _filter = { 'hubNetworkStorage': { 'username': utils.query_filter(username) } } account = self.list_accounts(_mask, _filter) if len(account) == 1: return [account[0]['id']] elif len(account) > 1: raise SoftLayerError( "Multiple object storage accounts found with the name: {}". format(username)) else: raise SoftLayerError( "Unable to find object storage account id for: {}".format( username))
def list_instances(self, hourly=True, monthly=True, tags=None, cpus=None, memory=None, hostname=None, domain=None, local_disk=None, datacenter=None, nic_speed=None, public_ip=None, private_ip=None, **kwargs): """Retrieve a list of all virtual servers on the account. Example:: # Print out a list of hourly instances in the DAL05 data center. for vsi in mgr.list_instances(hourly=True, datacenter='dal05'): 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_instances(mask=object_mask,hourly=True): print vsi :param boolean hourly: include hourly instances :param boolean monthly: include monthly instances :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 string datacenter: filter based on datacenter :param integer nic_speed: filter based on network speed (in MBPS) :param string public_ip: filter based on public ip address :param string private_ip: filter based on private ip address :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) :returns: Returns a list of dictionaries representing the matching virtual servers """ if 'mask' not in kwargs: items = [ 'id', 'globalIdentifier', 'hostname', 'domain', 'fullyQualifiedDomainName', 'primaryBackendIpAddress', 'primaryIpAddress', 'lastKnownPowerState.name', 'powerState', 'maxCpu', 'maxMemory', 'datacenter', 'activeTransaction.transactionStatus[friendlyName,name]', 'status', ] kwargs['mask'] = "mask[%s]" % ','.join(items) call = 'getVirtualGuests' if not all([hourly, monthly]): if hourly: call = 'getHourlyVirtualGuests' elif monthly: call = 'getMonthlyVirtualGuests' _filter = utils.NestedDict(kwargs.get('filter') or {}) if tags: _filter['virtualGuests']['tagReferences']['tag']['name'] = { 'operation': 'in', 'options': [{ 'name': 'data', 'value': tags }], } if cpus: _filter['virtualGuests']['maxCpu'] = utils.query_filter(cpus) if memory: _filter['virtualGuests']['maxMemory'] = utils.query_filter(memory) if hostname: _filter['virtualGuests']['hostname'] = utils.query_filter(hostname) if domain: _filter['virtualGuests']['domain'] = utils.query_filter(domain) if local_disk is not None: _filter['virtualGuests']['localDiskFlag'] = (utils.query_filter( bool(local_disk))) if datacenter: _filter['virtualGuests']['datacenter']['name'] = ( utils.query_filter(datacenter)) if nic_speed: _filter['virtualGuests']['networkComponents']['maxSpeed'] = ( utils.query_filter(nic_speed)) if public_ip: _filter['virtualGuests']['primaryIpAddress'] = ( utils.query_filter(public_ip)) if private_ip: _filter['virtualGuests']['primaryBackendIpAddress'] = ( utils.query_filter(private_ip)) kwargs['filter'] = _filter.to_dict() func = getattr(self.account, call) return func(**kwargs)
def list_hardware(self, tags=None, cpus=None, memory=None, hostname=None, domain=None, datacenter=None, nic_speed=None, public_ip=None, private_ip=None, **kwargs): """List all hardware (servers and bare metal computing instances). :param list tags: filter based on tags :param integer cpus: filter based on number of CPUS :param integer memory: filter based on amount of memory in gigabytes :param string hostname: filter based on hostname :param string domain: filter based on domain :param string datacenter: filter based on datacenter :param integer nic_speed: filter based on network speed (in MBPS) :param string public_ip: filter based on public ip address :param string private_ip: filter based on private ip address :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) :returns: Returns a list of dictionaries representing the matching hardware. This list will contain both dedicated servers and bare metal computing instances Example:: # Using a custom object-mask. Will get ONLY what is specified # These will stem from the SoftLayer_Hardware_Server datatype object_mask = "mask[hostname,monitoringRobot[robotStatus]]" result = mgr.list_hardware(mask=object_mask) """ if 'mask' not in kwargs: hw_items = [ 'id', 'hostname', 'domain', 'hardwareStatusId', 'globalIdentifier', 'fullyQualifiedDomainName', 'processorPhysicalCoreAmount', 'memoryCapacity', 'primaryBackendIpAddress', 'primaryIpAddress', 'datacenter', ] server_items = [ 'activeTransaction[id, transactionStatus[friendlyName,name]]', ] kwargs['mask'] = ('[mask[%s],' ' mask(SoftLayer_Hardware_Server)[%s]]' % (','.join(hw_items), ','.join(server_items))) _filter = utils.NestedDict(kwargs.get('filter') or {}) if tags: _filter['hardware']['tagReferences']['tag']['name'] = { 'operation': 'in', 'options': [{ 'name': 'data', 'value': tags }], } if cpus: _filter['hardware']['processorPhysicalCoreAmount'] = ( utils.query_filter(cpus)) if memory: _filter['hardware']['memoryCapacity'] = utils.query_filter(memory) if hostname: _filter['hardware']['hostname'] = utils.query_filter(hostname) if domain: _filter['hardware']['domain'] = utils.query_filter(domain) if datacenter: _filter['hardware']['datacenter']['name'] = ( utils.query_filter(datacenter)) if nic_speed: _filter['hardware']['networkComponents']['maxSpeed'] = ( utils.query_filter(nic_speed)) if public_ip: _filter['hardware']['primaryIpAddress'] = ( utils.query_filter(public_ip)) if private_ip: _filter['hardware']['primaryBackendIpAddress'] = ( utils.query_filter(private_ip)) kwargs['filter'] = _filter.to_dict() kwargs['iter'] = True return self.client.call('Account', 'getHardware', **kwargs)
def _get_zone_id_from_name(self, name): """Return zone ID based on a zone.""" results = self.client['Account'].getDomains( filter={"domains": {"name": utils.query_filter(name)}}) return [x['id'] for x in results]
def 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 Example:: :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)