def cli(env): """Lists Email Delivery Service """ manager = AccountManager(env.client) email_manager = EmailManager(env.client) result = manager.get_network_message_delivery_accounts() table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table_information = formatting.KeyValueTable( ['id', 'username', 'hostname', 'description', 'vendor']) table_information.align['id'] = 'r' table_information.align['username'] = '******' for email in result: table_information.add_row([ email.get('id'), email.get('username'), email.get('emailAddress'), utils.lookup(email, 'type', 'description'), utils.lookup(email, 'vendor', 'keyName') ]) overview_table = _build_overview_table( email_manager.get_account_overview(email.get('id'))) statistics = email_manager.get_statistics(email.get('id')) table.add_row(['email_information', table_information]) table.add_row(['email_overview', overview_table]) for statistic in statistics: table.add_row(['statistics', build_statistics_table(statistic)]) env.fout(table)
def _execute(self, args): meta = SoftLayer.MetadataManager() if args['<public>']: table = formatting.KeyValueTable(['Name', 'Value']) table.align['Name'] = 'r' table.align['Value'] = 'l' network = meta.public_network() table.add_row([ 'mac addresses', formatting.listing(network['mac_addresses'], separator=',')]) table.add_row([ 'router', network['router']]) table.add_row([ 'vlans', formatting.listing(network['vlans'], separator=',')]) table.add_row([ 'vlan ids', formatting.listing(network['vlan_ids'], separator=',')]) return table if args['<private>']: table = formatting.KeyValueTable(['Name', 'Value']) table.align['Name'] = 'r' table.align['Value'] = 'l' network = meta.private_network() table.add_row([ 'mac addresses', formatting.listing(network['mac_addresses'], separator=',')]) table.add_row([ 'router', network['router']]) table.add_row([ 'vlans', formatting.listing(network['vlans'], separator=',')]) table.add_row([ 'vlan ids', formatting.listing(network['vlan_ids'], separator=',')]) return table
def cli(env, ip_address): """Find an IP address and display its subnet and device info.""" mgr = SoftLayer.NetworkManager(env.client) addr_info = mgr.ip_lookup(ip_address) if not addr_info: return 'Not found' table = formatting.KeyValueTable(['Name', 'Value']) table.align['Name'] = 'r' table.align['Value'] = 'l' table.add_row(['id', addr_info['id']]) table.add_row(['ip', addr_info['ipAddress']]) subnet_table = formatting.KeyValueTable(['Name', 'Value']) subnet_table.align['Name'] = 'r' subnet_table.align['Value'] = 'l' subnet_table.add_row(['id', addr_info['subnet']['id']]) subnet_table.add_row([ 'identifier', '%s/%s' % (addr_info['subnet']['networkIdentifier'], str(addr_info['subnet']['cidr'])) ]) subnet_table.add_row(['netmask', addr_info['subnet']['netmask']]) if addr_info['subnet'].get('gateway'): subnet_table.add_row(['gateway', addr_info['subnet']['gateway']]) subnet_table.add_row(['type', addr_info['subnet'].get('subnetType')]) table.add_row(['subnet', subnet_table]) if addr_info.get('virtualGuest') or addr_info.get('hardware'): device_table = formatting.KeyValueTable(['Name', 'Value']) device_table.align['Name'] = 'r' device_table.align['Value'] = 'l' if addr_info.get('virtualGuest'): device = addr_info['virtualGuest'] device_type = 'vs' else: device = addr_info['hardware'] device_type = 'server' device_table.add_row(['id', device['id']]) device_table.add_row(['name', device['fullyQualifiedDomainName']]) device_table.add_row(['type', device_type]) table.add_row(['device', device_table]) return table
def cli(env, identifier): """Get billing for a virtual device.""" virtual = SoftLayer.VSManager(env.client) virtual_id = helpers.resolve_id(virtual.resolve_ids, identifier, 'virtual') result = virtual.get_instance(virtual_id) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['Id', identifier]) table.add_row( ['Billing Item Id', utils.lookup(result, 'billingItem', 'id')]) table.add_row( ['Recurring Fee', utils.lookup(result, 'billingItem', 'recurringFee')]) table.add_row([ 'Total', utils.lookup(result, 'billingItem', 'nextInvoiceTotalRecurringAmount') ]) table.add_row(['Provision Date', utils.lookup(result, 'provisionDate')]) price_table = formatting.Table(['Description', 'Recurring Price']) for item in utils.lookup(result, 'billingItem', 'children') or []: price_table.add_row( [item['description'], item['nextInvoiceTotalRecurringAmount']]) table.add_row(['prices', price_table]) env.fout(table)
def cli(env, unique_id, history): """Detail a CDN Account.""" manager = SoftLayer.CDNManager(env.client) cdn_mapping = manager.get_cdn(unique_id) cdn_metrics = manager.get_usage_metrics(unique_id, history=history) # usage metrics total_bandwidth = "%s GB" % cdn_metrics['totals'][0] total_hits = cdn_metrics['totals'][1] hit_ratio = "%s %%" % cdn_metrics['totals'][2] table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['unique_id', cdn_mapping['uniqueId']]) table.add_row(['hostname', cdn_mapping['domain']]) table.add_row(['protocol', cdn_mapping['protocol']]) table.add_row(['origin', cdn_mapping['originHost']]) table.add_row(['origin_type', cdn_mapping['originType']]) table.add_row(['path', cdn_mapping['path']]) table.add_row(['provider', cdn_mapping['vendorName']]) table.add_row(['status', cdn_mapping['status']]) table.add_row(['total_bandwidth', total_bandwidth]) table.add_row(['total_hits', total_hits]) table.add_row(['hit_radio', hit_ratio]) env.fout(table)
def cli(env, name, note, os_code, uri): """Import an image. The URI for an object storage object (.vhd/.iso file) of the format: swift://<objectStorageAccount>@<cluster>/<container>/<objectPath> """ image_mgr = SoftLayer.ImageManager(env.client) result = image_mgr.import_image_from_uri( name=name, note=note, os_code=os_code, uri=uri, ) if not result: raise exceptions.CLIAbort("Failed to import Image") table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['name', result['name']]) table.add_row(['id', result['id']]) table.add_row(['created', result['createDate']]) table.add_row(['guid', result['globalIdentifier']]) env.fout(table)
def cli(env, identifier): """Get details for a hardware monitors device.""" hardware = SoftLayer.HardwareManager(env.client) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' monitoring = hardware.get_hardware(identifier) table.add_row(['Domain', monitoring.get('fullyQualifiedDomainName')]) table.add_row(['Public Ip', monitoring.get('primaryIpAddress')]) table.add_row(['Private Ip', monitoring.get('primaryBackendIpAddress')]) table.add_row(['Location', monitoring['datacenter']['longName']]) monitoring_table = formatting.Table( ['Id', 'IpAddress', 'Status', 'Type', 'Notify']) for monitor in monitoring['networkMonitors']: monitoring_table.add_row([ monitor.get('id'), monitor.get('ipAddress'), monitor.get('status'), monitor['queryType']['name'], monitor['responseAction']['actionDescription'] ]) table.add_row(['Devices monitors', monitoring_table]) env.fout(table)
def get_network(): """Returns a list of tables with public and private network details.""" meta = SoftLayer.MetadataManager() network_tables = [] for network_func in [meta.public_network, meta.private_network]: network = network_func() table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row([ 'mac addresses', formatting.listing(network['mac_addresses'], separator=',') ]) table.add_row(['router', network['router']]) table.add_row( ['vlans', formatting.listing(network['vlans'], separator=',')]) table.add_row([ 'vlan ids', formatting.listing(network['vlan_ids'], separator=',') ]) network_tables.append(table) return network_tables
def cli(env, identifier): """Display details for a specified email.""" email_manager = EmailManager(env.client) result = email_manager.get_instance(identifier) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', result.get('id')]) table.add_row(['username', result.get('username')]) table.add_row(['email_address', result.get('emailAddress')]) table.add_row(['create_date', result.get('createDate')]) table.add_row( ['category_code', utils.lookup(result, 'billingItem', 'categoryCode')]) table.add_row( ['description', utils.lookup(result, 'billingItem', 'description')]) table.add_row( ['type_description', utils.lookup(result, 'type', 'description')]) table.add_row(['type', utils.lookup(result, 'type', 'keyName')]) table.add_row(['vendor', utils.lookup(result, 'vendor', 'keyName')]) statistics = email_manager.get_statistics(identifier) for statistic in statistics: table.add_row(['statistics', build_statistics_table(statistic)]) env.fout(table)
def execute(self, args): vsi = SoftLayer.VSManager(self.client) vs_id = helpers.resolve_id(vsi.resolve_ids, args.get('<identifier>'), 'VS') if args['--all']: additional_disks = True else: additional_disks = False capture = vsi.capture(vs_id, args.get('--name'), additional_disks, args.get('--note')) table = formatting.KeyValueTable(['Name', 'Value']) table.align['Name'] = 'r' table.align['Value'] = 'l' table.add_row(['vs_id', capture['guestId']]) table.add_row(['date', capture['createDate'][:10]]) table.add_row(['time', capture['createDate'][11:19]]) table.add_row(['transaction', formatting.transaction_status(capture)]) table.add_row(['transaction_id', capture['id']]) table.add_row(['all_disks', additional_disks]) 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]): update = wrap_string(update['entry']) table.add_row(['Update %s' % (i + 1, ), update]) return table
def cli(env, name, note, os_code, uri, ibm_api_key, root_key_crn, wrapped_dek, cloud_init, byol, is_encrypted): """Import an image. The URI for an object storage object (.vhd/.iso file) of the format: swift://<objectStorageAccount>@<cluster>/<container>/<objectPath> or cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud Object Storage """ image_mgr = SoftLayer.ImageManager(env.client) result = image_mgr.import_image_from_uri( name=name, note=note, os_code=os_code, uri=uri, ibm_api_key=ibm_api_key, root_key_crn=root_key_crn, wrapped_dek=wrapped_dek, cloud_init=cloud_init, byol=byol, is_encrypted=is_encrypted ) if not result: raise exceptions.CLIAbort("Failed to import Image") table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['name', result['name']]) table.add_row(['id', result['id']]) table.add_row(['created', result['createDate']]) table.add_row(['guid', result['globalIdentifier']]) env.fout(table)
def _get_context_table(context): """Yields a formatted table to print context details. :param dict context: The tunnel context :return Table: Formatted for tunnel context output """ table = formatting.KeyValueTable(['name', 'value'], title='Context Details') table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', context.get('id', '')]) table.add_row(['name', context.get('name', '')]) table.add_row(['friendly name', context.get('friendlyName', '')]) table.add_row(['internal peer IP address', context.get('internalPeerIpAddress', '')]) table.add_row(['remote peer IP address', context.get('customerPeerIpAddress', '')]) table.add_row(['advanced configuration flag', context.get('advancedConfigurationFlag', '')]) table.add_row(['preshared key', context.get('presharedKey', '')]) table.add_row(['phase 1 authentication', context.get('phaseOneAuthentication', '')]) table.add_row(['phase 1 diffie hellman group', context.get('phaseOneDiffieHellmanGroup', '')]) table.add_row(['phase 1 encryption', context.get('phaseOneEncryption', '')]) table.add_row(['phase 1 key life', context.get('phaseOneKeylife', '')]) table.add_row(['phase 2 authentication', context.get('phaseTwoAuthentication', '')]) table.add_row(['phase 2 diffie hellman group', context.get('phaseTwoDiffieHellmanGroup', '')]) table.add_row(['phase 2 encryption', context.get('phaseTwoEncryption', '')]) table.add_row(['phase 2 key life', context.get('phaseTwoKeylife', '')]) table.add_row(['phase 2 perfect forward secrecy', context.get('phaseTwoPerfectForwardSecrecy', '')]) table.add_row(['created', context.get('createDate')]) table.add_row(['modified', context.get('modifyDate')]) return table
def cli(env, identifier): """Detail firewall.""" mgr = SoftLayer.FirewallManager(env.client) firewall_type, firewall_id = firewall.parse_id(identifier) _firewall = mgr.get_instance(firewall_id) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', _firewall.get('id')]) table.add_row(['primaryIpAddress', _firewall.get('primaryIpAddress')]) table.add_row( ['datacenter', utils.lookup(_firewall, 'datacenter', 'longName')]) table.add_row( ['networkVlan', utils.lookup(_firewall, 'networkVlan', 'name')]) table.add_row( ['networkVlaniD', utils.lookup(_firewall, 'networkVlan', 'id')]) if firewall_type == 'vlan': rules = mgr.get_dedicated_fwl_rules(firewall_id) else: rules = mgr.get_standard_fwl_rules(firewall_id) table.add_row(['rules', get_rules_table(rules)]) env.fout(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 cli(env, identifier, no_vs, no_hardware): """Get subnet details.""" mgr = SoftLayer.NetworkManager(env.client) subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier, name='subnet') subnet = mgr.get_subnet(subnet_id) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', subnet['id']]) table.add_row([ 'identifier', '%s/%s' % (subnet['networkIdentifier'], str(subnet['cidr'])) ]) table.add_row(['subnet type', subnet['subnetType']]) table.add_row( ['network space', utils.lookup(subnet, 'networkVlan', 'networkSpace')]) table.add_row(['gateway', subnet.get('gateway', formatting.blank())]) table.add_row( ['broadcast', subnet.get('broadcastAddress', formatting.blank())]) table.add_row(['datacenter', subnet['datacenter']['name']]) table.add_row( ['usable ips', subnet.get('usableIpAddressCount', formatting.blank())]) if not no_vs: if subnet['virtualGuests']: vs_table = formatting.Table( ['hostname', 'domain', 'public_ip', 'private_ip']) for vsi in subnet['virtualGuests']: vs_table.add_row([ vsi['hostname'], vsi['domain'], vsi.get('primaryIpAddress'), vsi.get('primaryBackendIpAddress') ]) table.add_row(['vs', vs_table]) else: table.add_row(['vs', 'none']) if not no_hardware: if subnet['hardware']: hw_table = formatting.Table( ['hostname', 'domain', 'public_ip', 'private_ip']) for hardware in subnet['hardware']: hw_table.add_row([ hardware['hostname'], hardware['domain'], hardware.get('primaryIpAddress'), hardware.get('primaryBackendIpAddress') ]) table.add_row(['hardware', hw_table]) else: table.add_row(['hardware', 'none']) env.fout(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 get_snapshot_table(account): """Generates a table for printing account summary data""" table = formatting.KeyValueTable(["Name", "Value"], title="Account Snapshot") table.align['Name'] = 'r' table.align['Value'] = 'l' table.add_row(['Company Name', account.get('companyName', '-')]) table.add_row([ 'Balance', utils.lookup(account, 'pendingInvoice', 'startingBalance') ]) table.add_row([ 'Upcoming Invoice', utils.lookup(account, 'pendingInvoice', 'invoiceTotalAmount') ]) table.add_row( ['Image Templates', account.get('blockDeviceTemplateGroupCount', '-')]) table.add_row(['Dedicated Hosts', account.get('dedicatedHostCount', '-')]) table.add_row(['Hardware', account.get('hardwareCount', '-')]) table.add_row(['Virtual Guests', account.get('virtualGuestCount', '-')]) table.add_row(['Domains', account.get('domainCount', '-')]) table.add_row( ['Network Storage Volumes', account.get('networkStorageCount', '-')]) table.add_row(['Open Tickets', account.get('openTicketCount', '-')]) table.add_row(['Network Vlans', account.get('networkVlanCount', '-')]) table.add_row(['Subnets', account.get('subnetCount', '-')]) table.add_row(['Users', account.get('userCount', '-')]) return table
def cli(env, name, note, osrefcode, uri): """Import an image.""" image_mgr = SoftLayer.ImageManager(env.client) data = {} output = [] if name: data['name'] = name if note: data['note'] = note if osrefcode: data['operatingSystemReferenceCode'] = osrefcode if uri: data['uri'] = uri # not sure if u should validate here or not # if uri.endswith(".vhd") and osrefcode == "": # raise exceptions.CLIAbort("Please specify osrefcode for .vhdImage") result = image_mgr.import_image_from_uri(data) if not result: raise exceptions.CLIAbort("Failed to import Image") table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['name', result['name']]) table.add_row(['id', result['id']]) table.add_row(['created', result['createDate']]) table.add_row(['guid', result['globalIdentifier']]) output.append(table) env.fout(output)
def cli(env, **args): """Order/create a dedicated server.""" template.update_with_template_args(args, list_args=['disk', 'key']) mgr = SoftLayer.HardwareManager(env.client) ds_options = mgr.get_dedicated_server_create_options(args['chassis']) order = _process_args(env, args, ds_options) # Do not create hardware server with --test or --export do_create = not (args['export'] or args['test']) output = None if args.get('test'): result = mgr.verify_order(**order) table = formatting.Table(['Item', 'cost']) table.align['Item'] = 'r' table.align['cost'] = 'r' total = 0.0 for price in result['prices']: total += float(price.get('recurringFee', 0.0)) rate = "%.2f" % float(price['recurringFee']) table.add_row([price['item']['description'], rate]) table.add_row(['Total monthly cost', "%.2f" % total]) output = [] output.append(table) output.append( formatting.FormattedItem( '', ' -- ! Prices reflected here are retail and do not ' 'take account level discounts and are not guaranteed.')) if args['export']: export_file = args.pop('export') template.export_to_template(export_file, args, exclude=['wait', 'test']) return 'Successfully exported options to a template file.' if do_create: if env.skip_confirmations or formatting.confirm( "This action will incur charges on your account. " "Continue?"): result = mgr.place_order(**order) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', result['orderId']]) table.add_row(['created', result['orderDate']]) output = table else: raise exceptions.CLIAbort('Aborting dedicated server order.') return output
def cli(env, username, email, password, from_user, template, api_key): """Creates a user Users. :Example: slcli user create [email protected] -e [email protected] -p generate -a -t '{"firstName": "Test", "lastName": "Testerson"}' Remember to set the permissions and access for this new user. """ mgr = SoftLayer.UserManager(env.client) user_mask = ( "mask[id, firstName, lastName, email, companyName, address1, city, country, postalCode, " "state, userStatusId, timezoneId]") from_user_id = None if from_user is None: user_template = mgr.get_current_user(objectmask=user_mask) from_user_id = user_template['id'] else: from_user_id = helpers.resolve_id(mgr.resolve_ids, from_user, 'username') user_template = mgr.get_user(from_user_id, objectmask=user_mask) # If we send the ID back to the API, an exception will be thrown del user_template['id'] if template is not None: try: template_object = json.loads(template) for key in template_object: user_template[key] = template_object[key] except ValueError as ex: raise exceptions.ArgumentError("Unable to parse --template. %s" % ex) user_template['username'] = username if password == 'generate': password = generate_password() user_template['email'] = email if not env.skip_confirmations: table = formatting.KeyValueTable(['name', 'value']) for key in user_template: table.add_row([key, user_template[key]]) table.add_row(['password', password]) click.secho("You are about to create the following user...", fg='green') env.fout(table) if not formatting.confirm("Do you wish to continue?"): raise exceptions.CLIAbort("Canceling creation!") result = mgr.create_user(user_template, password) new_api_key = None if api_key: click.secho("Adding API key...", fg='green') new_api_key = mgr.add_api_authentication_key(result['id']) table = formatting.Table(['Username', 'Email', 'Password', 'API Key']) table.add_row([result['username'], result['email'], password, new_api_key]) env.fout(table)
def test_format_output_json_keyvaluetable(self): t = formatting.KeyValueTable(['key', 'value']) t.add_row(['nothing', formatting.blank()]) t.sortby = 'nothing' ret = formatting.format_output(t, 'json') self.assertEqual('''{ "nothing": null }''', ret)
def cli(env, identifier, no_vs, no_hardware): """Cancel a subnet.""" mgr = SoftLayer.NetworkManager(env.client) subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier, name='subnet') subnet = mgr.get_subnet(subnet_id) table = formatting.KeyValueTable(['Name', 'Value']) table.align['Name'] = 'r' table.align['Value'] = 'l' table.add_row(['id', subnet['id']]) table.add_row([ 'identifier', '%s/%s' % (subnet['networkIdentifier'], str(subnet['cidr'])) ]) table.add_row(['subnet type', subnet['subnetType']]) table.add_row(['gateway', subnet.get('gateway', formatting.blank())]) table.add_row( ['broadcast', subnet.get('broadcastAddress', formatting.blank())]) table.add_row(['datacenter', subnet['datacenter']['name']]) table.add_row( ['usable ips', subnet.get('usableIpAddressCount', formatting.blank())]) if not no_vs: if subnet['virtualGuests']: vs_table = formatting.Table(['Hostname', 'Domain', 'IP']) vs_table.align['Hostname'] = 'r' vs_table.align['IP'] = 'l' for vsi in subnet['virtualGuests']: vs_table.add_row([ vsi['hostname'], vsi['domain'], vsi.get('primaryIpAddress') ]) table.add_row(['vs', vs_table]) else: table.add_row(['vs', 'none']) if not no_hardware: if subnet['hardware']: hw_table = formatting.Table(['Hostname', 'Domain', 'IP']) hw_table.align['Hostname'] = 'r' hw_table.align['IP'] = 'l' for hardware in subnet['hardware']: hw_table.add_row([ hardware['hostname'], hardware['domain'], hardware.get('primaryIpAddress') ]) table.add_row(['hardware', hw_table]) else: table.add_row(['hardware', 'none']) return table
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): """Show all licenses.""" manager = account.AccountManager(env.client) control_panel = manager.get_active_virtual_licenses() vmwares = manager.get_active_account_licenses() table_panel = formatting.KeyValueTable([ 'id', 'ip_address', 'manufacturer', 'software', 'key', 'subnet', 'subnet notes' ], title="Control Panel Licenses") table_vmware = formatting.KeyValueTable([ 'name', 'license_key', 'cpus', 'description', 'manufacturer', 'requiredUser' ], title="VMware Licenses") for panel in control_panel: table_panel.add_row([ panel.get('id'), panel.get('ipAddress'), utils.lookup(panel, 'softwareDescription', 'manufacturer'), utils.trim_to( utils.lookup(panel, 'softwareDescription', 'longDescription'), 40), panel.get('key'), utils.lookup(panel, 'subnet', 'broadcastAddress'), utils.lookup(panel, 'subnet', 'note') ]) env.fout(table_panel) for vmware in vmwares: table_vmware.add_row([ utils.lookup(vmware, 'softwareDescription', 'name'), vmware.get('key'), vmware.get('capacity'), utils.lookup(vmware, 'billingItem', 'description'), utils.lookup(vmware, 'softwareDescription', 'manufacturer'), utils.lookup(vmware, 'softwareDescription', 'requiredUser') ]) env.fout(table_vmware)
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 execute(self, args): mgr = SoftLayer.LoadBalancerManager(self.client) routing_types = mgr.get_routing_types() table = formatting.KeyValueTable(['ID', 'Name']) table.align['ID'] = 'l' table.align['Name'] = 'l' table.sortby = 'ID' for routing_type in routing_types: table.add_row([routing_type['id'], routing_type['name']]) return table
def parse_receipt(receipt): """Takes an order receipt and nicely formats it for cli output""" table = formatting.KeyValueTable(['Item', 'Cost'], title="Order: {}".format(receipt.get('orderId', 'Quote'))) if receipt.get('prices'): for price in receipt.get('prices'): table.add_row([price['item']['description'], price['hourlyRecurringFee']]) elif receipt.get('orderDetails'): for price in receipt['orderDetails']['prices']: table.add_row([price['item']['description'], price['hourlyRecurringFee']]) return table
def format_api_dict(result): """Format dictionary responses into key-value table.""" table = formatting.KeyValueTable(['Name', 'Value']) table.align['Name'] = 'r' table.align['Value'] = 'l' for key, value in result.items(): value = format_api_result(value) table.add_row([key, value]) return table
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) children_images = image.get('children') total_size = utils.lookup(image, 'firstChild', 'blockDevicesDiskSpaceTotal') or 0 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.listing(_get_transaction_groups(children_images), separator=','), ]) 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(['total_size', formatting.b_to_gb(total_size)]) table.add_row(['datacenters', _get_datacenter_table(children_images)]) env.fout(table)