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 = utils.NestedDict({}) _value = "%s%s" % (item['primaryNetworkComponent']['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 execute(self, args): iscsi_mgr = SoftLayer.ISCSIManager(self.client) iscsi_list = iscsi_mgr.list_iscsi() iscsi_list = [utils.NestedDict(n) for n in iscsi_list] table = formatting.Table([ 'id', 'datacenter', 'size', 'username', 'password', 'server' ]) for iscsi in iscsi_list: table.add_row([ iscsi['id'], iscsi['serviceResource']['datacenter'].get('name', formatting.blank()), formatting.FormattedItem( iscsi.get('capacityGb', formatting.blank()), "%dGB" % iscsi.get('capacityGb', 0)), iscsi.get('username', formatting.blank()), iscsi.get('password', formatting.blank()), iscsi.get('serviceResourceBackendIpAddress', formatting.blank())]) return table
def execute(self, args): iscsi_mgr = SoftLayer.ISCSIManager(self.client) table = formatting.KeyValueTable(['Name', 'Value']) table.align['Name'] = 'r' table.align['Value'] = 'l' iscsi_id = helpers.resolve_id( iscsi_mgr.resolve_ids, args.get('<identifier>'), 'iSCSI') result = iscsi_mgr.get_iscsi(iscsi_id) result = utils.NestedDict(result) table.add_row(['id', result['id']]) table.add_row(['serviceResourceName', result['serviceResourceName']]) table.add_row(['createDate', result['createDate']]) table.add_row(['nasType', result['nasType']]) table.add_row(['capacityGb', result['capacityGb']]) if result['snapshotCapacityGb']: table.add_row(['snapshotCapacityGb', result['snapshotCapacityGb']]) table.add_row(['mountableFlag', result['mountableFlag']]) table.add_row( ['serviceResourceBackendIpAddress', result['serviceResourceBackendIpAddress']]) table.add_row(['price', result['billingItem']['recurringFee']]) table.add_row(['BillingItemId', result['billingItem']['id']]) if result.get('notes'): table.add_row(['notes', result['notes']]) if args.get('--password'): pass_table = formatting.Table(['username', 'password']) pass_table.add_row([result['username'], result['password']]) table.add_row(['users', pass_table]) return table
def get_ticket_results(mgr, ticket_id, update_count=1): """Get output about a ticket. :param integer id: the ticket ID :param integer update_count: number of entries to retrieve from ticket :returns: a KeyValue table containing the details of the ticket """ result = mgr.get_ticket(ticket_id) result = utils.NestedDict(result) table = formatting.KeyValueTable(['Name', 'Value']) table.align['Name'] = 'r' table.align['Value'] = 'l' table.add_row(['id', result['id']]) table.add_row(['title', result['title']]) if result['assignedUser']: table.add_row([ 'assignedUser', "%s %s" % (result['assignedUser']['firstName'], result['assignedUser']['lastName']) ]) table.add_row(['createDate', result['createDate']]) table.add_row(['lastEditDate', result['lastEditDate']]) total_update_count = result['updateCount'] count = min(total_update_count, update_count) for i, update in enumerate(result['updates'][:count]): # NOTE(kmcdonald): Windows new-line characters need to be stripped out wrapped_entry = click.wrap_text(update['entry'].replace('\r', '')) table.add_row(['Update %s' % (i + 1, ), wrapped_entry]) return table
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 execute(self, args): iscsi_mgr = SoftLayer.ISCSIManager(self.client) iscsi_id = helpers.resolve_id(iscsi_mgr.resolve_ids, args.get('<identifier>'), 'iSCSI') iscsi = self.client['Network_Storage_Iscsi'] snapshots = iscsi.getPartnerships( mask='volumeId,partnerVolumeId,createDate,type', id=iscsi_id) snapshots = [utils.NestedDict(n) for n in snapshots] table = formatting.Table([ 'id', 'createDate', 'name', 'description', ]) for snapshot in snapshots: table.add_row([ snapshot['partnerVolumeId'], snapshot['createDate'], snapshot['type']['name'], snapshot['type']['description'], ]) return table
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_package(manager, category_code): """Returns a product packaged 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_ticket_results(mgr, ticket_id, update_count=1): """ Get output about a ticket :param integer id: the ticket ID :param integer update_count: number of entries to retrieve from ticket :returns: a KeyValue table containing the details of the ticket """ result = mgr.get_ticket(ticket_id) result = utils.NestedDict(result) table = formatting.KeyValueTable(['Name', 'Value']) table.align['Name'] = 'r' table.align['Value'] = 'l' table.add_row(['id', result['id']]) table.add_row(['title', result['title']]) if result['assignedUser']: table.add_row([ 'assignedUser', "%s %s" % (result['assignedUser']['firstName'], result['assignedUser']['lastName']) ]) table.add_row(['createDate', result['createDate']]) table.add_row(['lastEditDate', result['lastEditDate']]) total_update_count = result['updateCount'] count = min(total_update_count, update_count) for i, update in enumerate(result['updates'][:count]): update = wrap_string(update['entry']) table.add_row(['Update %s' % (i + 1, ), update]) return table
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 """ kwargs = utils.NestedDict({}) kwargs['mask'] = ('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'] == group_id: service_group = virtual_server['serviceGroups'][0] if allocation is not None: virtual_server['allocation'] = int(allocation) if port is not None: virtual_server['port'] = int(port) if routing_type is not None: service_group['routingTypeId'] = int(routing_type) if routing_method is not None: service_group['routingMethodId'] = int(routing_method) break return self.lb_svc.editObject(load_balancer, id=loadbal_id)
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: 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 """ kwargs = utils.NestedDict({}) kwargs['mask'] = ('mask[virtualServers[serviceGroups' '[services[groupReferences]]]]') load_balancer = self.lb_svc.getObject(id=lb_id, **kwargs) virtual_servers = load_balancer['virtualServers'] service_template = { 'port': port, 'allocation': allocation, 'serviceGroups': [{ 'routingTypeId': routing_type, 'routingMethodId': routing_method }] } virtual_servers.append(service_template) return self.lb_svc.editObject(load_balancer, id=lb_id)
def cli(env): """List iSCSI targets.""" iscsi_mgr = SoftLayer.ISCSIManager(env.client) iscsi_list = iscsi_mgr.list_iscsi() iscsi_list = [utils.NestedDict(n) for n in iscsi_list] table = formatting.Table([ 'id', 'datacenter', 'size', 'username', 'password', 'server' ]) for iscsi in iscsi_list: table.add_row([ iscsi['id'], iscsi['serviceResource']['datacenter'].get('name', formatting.blank()), formatting.FormattedItem(iscsi.get('capacityGb', formatting.blank()), "%dGB" % iscsi.get('capacityGb', 0)), iscsi.get('username', formatting.blank()), iscsi.get('password', formatting.blank()), iscsi.get('serviceResourceBackendIpAddress', formatting.blank())]) env.fout(table)
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_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 list_file_volumes(self, **kwargs): """Returns a list of file volumes :param datacenter: Datacenter short name `(e.g.: dal09)` :type datacenter: str :param username: Name of volume :type username: str :param storage_type: Type of volume "Endurance|Performance" :type storage_type: str :param order: Volume order ID :type order: int :return: Returns a list of file volumes :rtype: list """ # Build dict of argument and assign default value when needed args = { 'datacenter': kwargs.get('datacenter') or None, 'username': kwargs.get('username') or None, 'storage_type': kwargs.get('storage_type') or None, 'order': kwargs.get('order') or None } _kwargs = {} _filter = sl_utils.NestedDict({}) result = [] _filter['nasNetworkStorage']['serviceResource']['type']['type'] = \ (sl_utils.query_filter('!~ NAS')) _filter['nasNetworkStorage']['storageType']['keyName'] = ( sl_utils.query_filter('*FILE_STORAGE*')) if args['username']: _filter['nasNetworkStorage']['username'] = \ (sl_utils.query_filter(args['username'])) if args['datacenter']: _filter['nasNetworkStorage']['serviceResource']['datacenter'][ 'name'] = (sl_utils.query_filter(args['datacenter'])) if args['storage_type']: _filter['nasNetworkStorage']['storageType']['keyName'] = \ (sl_utils.query_filter( '%s_FILE_STORAGE*' % args['storage_type'].upper())) if args['order']: _filter['nasNetworkStorage']['billingItem']['orderItem'][ 'order']['id'] = (sl_utils.query_filter(args['order'])) _kwargs['filter'] = _filter.to_dict() try: r = self.client.call('Account', 'getNasNetworkStorage', **_kwargs) for fs in r: result.append(fs) return result except sl.SoftLayer.SoftLayerAPIError as error: return resource_error(error.faultCode, error.faultString)
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_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 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 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 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_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 cli(env, sortby, cpu, domain, datacenter, hostname, memory, network, hourly, monthly, tags, columns): """List virtual servers.""" vsi = SoftLayer.VSManager(env.client) columns_clean = [col.strip() for col in columns.split(',')] tag_list = None if tags: tag_list = [tag.strip() for tag in tags.split(',')] guests = vsi.list_instances(hourly=hourly, monthly=monthly, hostname=hostname, domain=domain, cpus=cpu, memory=memory, datacenter=datacenter, nic_speed=network, tags=tag_list) table = formatting.Table(columns_clean) table.sortby = sortby column_map = {} column_map['guid'] = 'globalIdentifier' column_map['primary_ip'] = 'primaryIpAddress' column_map['backend_ip'] = 'primaryBackendIpAddress' column_map['datacenter'] = 'datacenter-name' column_map['action'] = 'formatted-action' column_map['powerState'] = 'powerState-name' for guest in guests: guest = utils.NestedDict(guest) guest['datacenter-name'] = guest['datacenter']['name'] guest['formatted-action'] = formatting.active_txn(guest) guest['powerState-name'] = guest['powerState']['name'] row_column = [] for col in columns_clean: entry = None if col in column_map: entry = guest[column_map[col]] else: entry = guest[col] row_column.append(entry or formatting.blank()) table.add_row(row_column) return table
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() kwargs['iter'] = True return self.client.call('Account', 'getSubnets', **kwargs)
def cli(env, identifier, price=False, guests=False): """Get details for a dedicated host.""" dhost = SoftLayer.DedicatedHostManager(env.client) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' result = dhost.get_host(identifier) result = utils.NestedDict(result) table.add_row(['id', result['id']]) table.add_row(['name', result['name']]) table.add_row(['cpu count', result['cpuCount']]) table.add_row(['memory capacity', result['memoryCapacity']]) table.add_row(['disk capacity', result['diskCapacity']]) table.add_row(['create date', result['createDate']]) table.add_row(['modify date', result['modifyDate']]) table.add_row(['router id', result['backendRouter']['id']]) table.add_row(['router hostname', result['backendRouter']['hostname']]) table.add_row([ 'owner', formatting.FormattedItem( utils.lookup(result, 'billingItem', 'orderItem', 'order', 'userRecord', 'username') or formatting.blank(), ) ]) if price: total_price = utils.lookup(result, 'billingItem', 'nextInvoiceTotalRecurringAmount') or 0 total_price += sum( p['nextInvoiceTotalRecurringAmount'] for p in utils.lookup(result, 'billingItem', 'children') or []) table.add_row(['price_rate', total_price]) table.add_row(['guest count', result['guestCount']]) if guests: guest_table = formatting.Table(['id', 'hostname', 'domain', 'uuid']) for guest in result['guests']: guest_table.add_row([ guest['id'], guest['hostname'], guest['domain'], guest['uuid'] ]) table.add_row(['guests', guest_table]) table.add_row(['datacenter', result['datacenter']['name']]) env.fout(table)
def 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 cli(env, volume_id): """Display details for a specified volume.""" block_manager = SoftLayer.BlockStorageManager(env.client) block_volume = block_manager.get_block_volume_details(volume_id) block_volume = utils.NestedDict(block_volume) table = formatting.KeyValueTable(['Name', 'Value']) table.align['Name'] = 'r' table.align['Value'] = 'l' storage_type = block_volume['storageType']['keyName'].split('_').pop(0) table.add_row(['ID', block_volume['id']]) table.add_row(['Username', block_volume['username']]) table.add_row(['Type', storage_type]) table.add_row(['Capacity (GB)', "%iGB" % block_volume['capacityGb']]) table.add_row(['LUN Id', "%s" % block_volume['lunId']]) if block_volume.get('iops'): table.add_row(['IOPs', block_volume['iops']]) if block_volume.get('storageTierLevel'): table.add_row([ 'Endurance Tier', block_volume['storageTierLevel']['description'], ]) table.add_row([ 'Data Center', block_volume['serviceResource']['datacenter']['name'], ]) table.add_row([ 'Target IP', block_volume['serviceResourceBackendIpAddress'], ]) if block_volume['snapshotCapacityGb']: table.add_row([ 'Snapshot Capacity (GB)', block_volume['snapshotCapacityGb'], ]) table.add_row([ 'Snapshot Used (Bytes)', block_volume['parentVolume']['snapshotSizeBytes'], ]) env.fout(table)
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' ] 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 cli(env, sortby, cpu, domain, datacenter, hostname, memory, network, tag, columns): """List hardware servers.""" manager = SoftLayer.HardwareManager(env.client) columns_clean = [col.strip() for col in columns.split(',')] servers = manager.list_hardware(hostname=hostname, domain=domain, cpus=cpu, memory=memory, datacenter=datacenter, nic_speed=network, tags=tag) table = formatting.Table(columns_clean) table.sortby = sortby column_map = {} column_map['guid'] = 'globalIdentifier' column_map['primary_ip'] = 'primaryIpAddress' column_map['backend_ip'] = 'primaryBackendIpAddress' column_map['datacenter'] = 'datacenter-name' column_map['action'] = 'formatted-action' column_map['powerState'] = 'powerState-name' for server in servers: server = utils.NestedDict(server) server['datacenter-name'] = server['datacenter']['name'] server['formatted-action'] = formatting.active_txn(server) server['powerState-name'] = server['powerState']['name'] row_column = [] for col in columns_clean: entry = None if col in column_map: entry = server[column_map[col]] else: entry = server[col] row_column.append(entry or formatting.blank()) table.add_row(row_column) return table
def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network, hourly, monthly, tags): """List virtual servers.""" vsi = SoftLayer.VSManager(env.client) tag_list = None if tags: tag_list = [tag.strip() for tag in tags.split(',')] guests = vsi.list_instances(hourly=hourly, monthly=monthly, hostname=hostname, domain=domain, cpus=cpu, memory=memory, datacenter=datacenter, nic_speed=network, tags=tag_list) table = formatting.Table([ 'guid', 'hostname', 'primary_ip', 'backend_ip', 'datacenter', 'action', ]) table.sortby = sortby or 'hostname' for guest in guests: guest = utils.NestedDict(guest) table.add_row([ guest['globalIdentifier'] or guest['id'], guest['hostname'], guest['primaryIpAddress'] or formatting.blank(), guest['primaryBackendIpAddress'] or formatting.blank(), guest['datacenter']['name'] or formatting.blank(), formatting.active_txn(guest), ]) return table