def get_order_table(order): """Formats a table for billing order""" title = "Order {id}".format(id=order.get('id')) date_format = '%Y-%m-%d' table = formatting.Table(["Key", "Value"], title=title) table.align = 'l' ordered_by = "IBM" user = order.get('userRecord', None) if user: ordered_by = "{} ({})".format(user.get('displayName'), utils.lookup(user, 'userStatus', 'name')) table.add_row(['Ordered By', ordered_by]) table.add_row(['Create Date', utils.clean_time(order.get('createDate'), date_format, date_format)]) table.add_row(['Modify Date', utils.clean_time(order.get('modifyDate'), date_format, date_format)]) table.add_row(['Order Approval Date', utils.clean_time(order.get('orderApprovalDate'), date_format, date_format)]) table.add_row(['Status', order.get('status')]) table.add_row(['Order Total Amount', "{price:.2f}".format(price=float(order.get('orderTotalAmount', '0')))]) table.add_row(['Invoice Total Amount', "{price:.2f}". format(price=float(order.get('initialInvoice', {}).get('invoiceTotalAmount', '0')))]) items = order.get('items', []) item_table = formatting.Table(["Item Description"]) item_table.align['description'] = 'l' for item in items: item_table.add_row([item.get('description')]) table.add_row(['Items', item_table]) return table
def item_table(item): """Formats a table for billing items""" date_format = '%Y-%m-%d' table = formatting.Table(["Key", "Value"], title="{}".format(item.get('description', 'Billing Item'))) table.add_row(['createDate', utils.clean_time(item.get('createDate'), date_format, date_format)]) table.add_row(['cycleStartDate', utils.clean_time(item.get('cycleStartDate'), date_format, date_format)]) table.add_row(['cancellationDate', utils.clean_time(item.get('cancellationDate'), date_format, date_format)]) table.add_row(['description', item.get('description')]) table.align = 'l' fqdn = "{}.{}".format(item.get('hostName'), item.get('domain')) if fqdn != ".": table.add_row(['FQDN', fqdn]) if item.get('hourlyFlag', False): table.add_row(['hourlyRecurringFee', item.get('hourlyRecurringFee')]) table.add_row(['hoursUsed', item.get('hoursUsed')]) table.add_row(['currentHourlyCharge', item.get('currentHourlyCharge')]) else: table.add_row(['recurringFee', item.get('recurringFee')]) ordered_by = "IBM" user = utils.lookup(item, 'orderItem', 'order', 'userRecord') if user: ordered_by = "{} ({})".format(user.get('displayName'), utils.lookup(user, 'userStatus', 'name')) table.add_row(['Ordered By', ordered_by]) table.add_row(['Notes', item.get('notes')]) table.add_row(['Location', utils.lookup(item, 'location', 'name')]) if item.get('children'): for child in item.get('children'): table.add_row([child.get('categoryCode'), child.get('description')]) return table
def cli(env, date_min, date_max, obj_event, obj_id, obj_type, utc_offset, metadata, limit): """Get Event Logs Example: slcli event-log get -d 01/01/2019 -D 02/01/2019 -t User -l 10 """ columns = ['Event', 'Object', 'Type', 'Date', 'Username'] event_mgr = SoftLayer.EventLogManager(env.client) user_mgr = SoftLayer.UserManager(env.client) request_filter = event_mgr.build_filter(date_min, date_max, obj_event, obj_id, obj_type, utc_offset) logs = event_mgr.get_event_logs(request_filter) log_time = "%Y-%m-%dT%H:%M:%S.%f%z" user_data = {} if metadata: columns.append('Metadata') row_count = 0 click.secho(", ".join(columns)) for log in logs: if log is None: click.secho('No logs available for filter %s.' % request_filter, fg='red') return user = log['userType'] label = log.get('label', '') if user == "CUSTOMER": username = user_data.get(log['userId']) if username is None: username = user_mgr.get_user(log['userId'], "mask[username]")['username'] user_data[log['userId']] = username user = username if metadata: metadata_data = log['metaData'].strip("\n\t") click.secho("'{0}','{1}','{2}','{3}','{4}','{5}'".format( log['eventName'], label, log['objectName'], utils.clean_time(log['eventCreateDate'], in_format=log_time), user, metadata_data)) else: click.secho("'{0}','{1}','{2}','{3}','{4}'".format( log['eventName'], label, log['objectName'], utils.clean_time(log['eventCreateDate'], in_format=log_time), user)) row_count = row_count + 1 if row_count >= limit and limit != -1: return
def cli(env, date_min, date_max, obj_event, obj_id, obj_type, utc_offset, metadata, limit): """Get Event Logs Example: slcli event-log get -d 01/01/2019 -D 02/01/2019 -t User -l 10 """ columns = ['Event', 'Object', 'Type', 'Date', 'Username'] event_mgr = SoftLayer.EventLogManager(env.client) user_mgr = SoftLayer.UserManager(env.client) request_filter = event_mgr.build_filter(date_min, date_max, obj_event, obj_id, obj_type, utc_offset) logs = event_mgr.get_event_logs(request_filter) log_time = "%Y-%m-%dT%H:%M:%S.%f%z" user_data = {} if metadata: columns.append('Metadata') row_count = 0 click.secho(", ".join(columns)) for log in logs: if isinstance(log, str) or log is None: click.secho('No logs available for filter %s.' % request_filter, fg='red') return user = log['userType'] label = log.get('label', '') if user == "CUSTOMER": username = user_data.get(log['userId']) if username is None: username = user_mgr.get_user(log['userId'], "mask[username]")['username'] user_data[log['userId']] = username user = username if metadata: metadata_data = log['metaData'].strip("\n\t") click.secho("'{0}','{1}','{2}','{3}','{4}','{5}'".format( log['eventName'], label, log['objectName'], utils.clean_time(log['eventCreateDate'], in_format=log_time), user, metadata_data)) else: click.secho("'{0}','{1}','{2}','{3}','{4}'".format( log['eventName'], label, log['objectName'], utils.clean_time(log['eventCreateDate'], in_format=log_time), user)) row_count = row_count + 1 if row_count >= limit and limit != -1: return
def basic_event_table(event): """Formats a basic event table""" table = formatting.Table(["Id", "Status", "Type", "Start", "End"], title=utils.clean_splitlines(event.get('subject'))) table.add_row([ event.get('id'), utils.lookup(event, 'statusCode', 'name'), utils.lookup(event, 'notificationOccurrenceEventType', 'keyName'), utils.clean_time(event.get('startDate')), utils.clean_time(event.get('endDate')) ]) return table
def basic_event_table(event): """Formats a basic event table""" table = formatting.Table(["Id", "Status", "Type", "Start", "End"], title=utils.clean_splitlines(event.get('subject'))) table.add_row([ event.get('id'), utils.lookup(event, 'statusCode', 'name'), utils.lookup(event, 'notificationOccurrenceEventType', 'keyName'), utils.clean_time(event.get('startDate')), utils.clean_time(event.get('endDate')) ]) return table
def item_table(items): """Formats a table for billing items""" table = formatting.Table([ "Id", "Create Date", "Cost", "Category Code", "Ordered By", "Description", "Notes" ], title="Billing Items") table.align['Description'] = 'l' table.align['Category Code'] = 'l' for item in items: description = item.get('description') fqdn = "{}.{}".format(item.get('hostName', ''), item.get('domainName', '')) if fqdn != ".": description = fqdn user = utils.lookup(item, 'orderItem', 'order', 'userRecord') ordered_by = "IBM" create_date = utils.clean_time(item.get('createDate'), in_format='%Y-%m-%d', out_format='%Y-%m-%d') if user: # ordered_by = "{} ({})".format(user.get('displayName'), utils.lookup(user, 'userStatus', 'name')) ordered_by = user.get('displayName') table.add_row([ item.get('id'), create_date, item.get('nextInvoiceTotalRecurringAmount'), item.get('categoryCode'), ordered_by, utils.trim_to(description, 50), utils.trim_to(item.get('notes', 'None'), 40), ]) return table
def cli(env, limit, closed=False, get_all=False): """Invoices and all that mess""" manager = AccountManager(env.client) invoices = manager.get_invoices(limit, closed, get_all) table = formatting.Table([ "Id", "Created", "Type", "Status", "Starting Balance", "Ending Balance", "Invoice Amount", "Items" ]) table.align['Starting Balance'] = 'l' table.align['Ending Balance'] = 'l' table.align['Invoice Amount'] = 'l' table.align['Items'] = 'l' if isinstance(invoices, dict): invoices = [invoices] for invoice in invoices: table.add_row([ invoice.get('id'), utils.clean_time(invoice.get('createDate'), out_format="%Y-%m-%d"), invoice.get('typeCode'), invoice.get('statusCode'), invoice.get('startingBalance'), invoice.get('endingBalance'), invoice.get('invoiceTotalAmount'), invoice.get('itemCount') ]) env.fout(table)
def cli(env, limit, closed=False, get_all=False): """List invoices""" manager = AccountManager(env.client) invoices = manager.get_invoices(limit, closed, get_all) table = formatting.Table([ "Id", "Created", "Type", "Status", "Starting Balance", "Ending Balance", "Invoice Amount", "Items" ]) table.align['Starting Balance'] = 'l' table.align['Ending Balance'] = 'l' table.align['Invoice Amount'] = 'l' table.align['Items'] = 'l' if isinstance(invoices, dict): invoices = [invoices] for invoice in invoices: table.add_row([ invoice.get('id'), utils.clean_time(invoice.get('createDate'), out_format="%Y-%m-%d"), invoice.get('typeCode'), invoice.get('statusCode'), invoice.get('startingBalance'), invoice.get('endingBalance'), invoice.get('invoiceTotalAmount'), invoice.get('itemCount') ]) env.fout(table)
def build_resource_object(name_property, vlan, resource, entry): """builds out a resource object and puts the required values in the right place. :param: name_property is what property to use as the name from resource :param: vlan is the vlan object :param: resource has the data we want :param: entry is for any existing data """ new_entry = { 'id': resource.get('id'), 'name': resource.get(name_property), 'vlan': { vlan.get('networkSpace'): vlan.get('vlanNumber') }, 'cancelDate': utils.clean_time( utils.lookup(resource, 'billingItem', 'cancellationDate')) } if entry: entry['vlan'][vlan.get('networkSpace')] = vlan.get('vlanNumber') else: entry = new_entry return entry
def cli(env, identifier, date_min): """Retreive logs for an autoscale group""" autoscale = AutoScaleManager(env.client) mask = "mask[id,createDate,description]" object_filter = {} if date_min: object_filter['logs'] = { 'createDate': { 'operation': 'greaterThanDate', 'options': [{ 'name': 'date', 'value': [date_min.strftime("%m/%d/%Y")] }] } } logs = autoscale.get_logs(identifier, mask=mask, object_filter=object_filter) table = formatting.Table(['Date', 'Entry'], title="Logs") table.align['Entry'] = 'l' for log in logs: table.add_row( [utils.clean_time(log.get('createDate')), log.get('description')]) env.fout(table)
def cli(env, identifier, scale_up, scale_by, amount): """Scales an Autoscale group. Bypasses a scale group's cooldown period.""" autoscale = AutoScaleManager(env.client) # Scale By, and go down, need to use negative amount if not scale_up and scale_by: amount = amount * -1 result = [] if scale_by: click.secho("Scaling group {} by {}".format(identifier, amount), fg='green') result = autoscale.scale(identifier, amount) else: click.secho("Scaling group {} to {}".format(identifier, amount), fg='green') result = autoscale.scale_to(identifier, amount) try: # Check if the first guest has a cancellation date, assume we are removing guests if it is. cancel_date = result[0]['virtualGuest']['billingItem']['cancellationDate'] or False except (IndexError, KeyError, TypeError): cancel_date = False if cancel_date: member_table = formatting.Table(['Id', 'Hostname', 'Created'], title="Cancelled Guests") else: member_table = formatting.Table(['Id', 'Hostname', 'Created'], title="Added Guests") for guest in result: real_guest = guest.get('virtualGuest') member_table.add_row([ guest.get('id'), real_guest.get('hostname'), utils.clean_time(real_guest.get('createDate')) ]) env.fout(member_table)
def cli(env, quote): """Save a quote""" manager = ordering.OrderingManager(env.client) result = manager.save_quote(quote) table = formatting.Table(['Id', 'Name', 'Created', 'Modified', 'Status']) table.align['Name'] = 'l' table.add_row([ result.get('id'), result.get('name'), clean_time(result.get('createDate')), clean_time(result.get('modifyDate')), result.get('status'), ]) env.fout(table)
def update_table(event): """Formats a basic event update table""" update_number = 0 for update in event.get('updates', []): update_number = update_number + 1 header = "======= Update #%s on %s =======" % (update_number, utils.clean_time(update.get('startDate'))) click.secho(header, fg='green') text = update.get('contents') # deals with all the \r\n from the API click.secho(utils.clean_splitlines(text))
def update_table(event): """Formats a basic event update table""" update_number = 0 for update in event.get('updates', []): header = "======= Update #%s on %s =======" % (update_number, utils.clean_time(update.get('startDate'))) click.secho(header, fg='green') update_number = update_number + 1 text = update.get('contents') # deals with all the \r\n from the API click.secho(utils.clean_splitlines(text))
def event_table(events): """Formats a table for events""" table = formatting.Table([ "Id", "Start Date", "End Date", "Subject", "Status", "Acknowledged", "Updates", "Impacted Resources" ], title="Upcoming Events") table.align['Subject'] = 'l' table.align['Impacted Resources'] = 'l' for event in events: table.add_row([ event.get('id'), utils.clean_time(event.get('startDate')), utils.clean_time(event.get('endDate')), # Some subjects can have \r\n for some reason. utils.clean_splitlines(event.get('subject')), utils.lookup(event, 'statusCode', 'name'), event.get('acknowledgedFlag'), event.get('updateCount'), event.get('impactedResourceCount') ]) return table
def unplanned_event_table(events): """Formats a table for events""" unplanned_table = formatting.Table([ 'Id', 'Event ID', 'Subject', 'Status', 'Items', 'Start Date', 'Last Updated', 'Acknowledged', 'Updates' ], title="Unplanned Events") unplanned_table.align['Subject'] = 'l' unplanned_table.align['Impacted Resources'] = 'l' for event in events: unplanned_table.add_row([ event.get('id'), event.get('systemTicketId'), # Some subjects can have \r\n for some reason. utils.clean_splitlines(event.get('subject')), utils.lookup(event, 'statusCode', 'name'), event.get('impactedResourceCount'), utils.clean_time(event.get('startDate')), utils.clean_time(event.get('modifyDate')), event.get('acknowledgedFlag'), event.get('updateCount'), ]) return unplanned_table
def cli(env, identifier): """Get bandwidth pool details.""" manager = AccountManager(env.client) bandwidths = manager.getBandwidthDetail(identifier) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['Id', bandwidths['id']]) table.add_row(['Name', bandwidths['name']]) table.add_row([ 'Create Date', utils.clean_time(bandwidths.get('createDate'), '%Y-%m-%d') ]) current = "{} GB".format( utils.lookup(bandwidths, 'billingCyclePublicBandwidthUsage', 'amountOut')) if current is None: current = '-' table.add_row(['Current Usage', current]) projected = "{} GB".format( bandwidths.get('projectedPublicBandwidthUsage', 0)) if projected is None: projected = '-' table.add_row(['Projected Usage', projected]) inbound = "{} GB".format(bandwidths.get('inboundPublicBandwidthUsage', 0)) if inbound is None: inbound = '-' table.add_row(['Inbound Usage', inbound]) if bandwidths['hardware'] != []: table.add_row(['hardware', _bw_table(bandwidths['hardware'])]) else: table.add_row(['hardware', 'Not Found']) if bandwidths['virtualGuests'] != []: table.add_row( ['virtualGuests', _virtual_table(bandwidths['virtualGuests'])]) else: table.add_row(['virtualGuests', 'Not Found']) if bandwidths['bareMetalInstances'] != []: table.add_row( ['Netscaler', _bw_table(bandwidths['bareMetalInstances'])]) else: table.add_row(['Netscaler', 'Not Found']) env.fout(table)
def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network, hourly, monthly, tag, columns, limit, transient, hardware, all_guests): """List virtual servers.""" vsi = SoftLayer.VSManager(env.client) guests = vsi.list_instances(hourly=hourly, monthly=monthly, hostname=hostname, domain=domain, cpus=cpu, memory=memory, datacenter=datacenter, nic_speed=network, transient=transient, tags=tag, mask=columns.mask(), limit=limit) table = formatting.Table(columns.columns) table.sortby = sortby if not hardware or all_guests: for guest in guests: table.add_row( [value or formatting.blank() for value in columns.row(guest)]) env.fout(table) if hardware or all_guests: hardware_guests = vsi.get_hardware_guests() for hd_guest in hardware_guests: if hd_guest['virtualHost']['guests']: title = "Hardware(id = {hardwareId}) guests associated".format( hardwareId=hd_guest['id']) table_hardware_guest = formatting.Table([ 'id', 'hostname', 'CPU', 'Memory', 'Start Date', 'Status', 'powerState' ], title=title) table_hardware_guest.sortby = 'hostname' for guest in hd_guest['virtualHost']['guests']: table_hardware_guest.add_row([ guest['id'], guest['hostname'], '%i %s' % (guest['maxCpu'], guest['maxCpuUnits']), guest['maxMemory'], utils.clean_time(guest['createDate']), guest['status']['keyName'], guest['powerState']['keyName'] ]) env.fout(table_hardware_guest)
def get_hp_table(this_lb): """Generates a table from a list of LBaaS devices""" # https://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_LBaaS_HealthMonitor/ hp_table = formatting.Table(['UUID', 'Interval', 'Retries', 'Type', 'ServerTimeout ', 'Modify', 'Active']) for health in this_lb.get('healthMonitors', []): hp_table.add_row([ health.get('uuid'), health.get('interval'), health.get('maxRetries'), health.get('monitorType'), health.get('serverTimeout'), utils.clean_time(health.get('modifyDate')), health.get('provisioningStatus') ]) return hp_table
def get_l7pool_table(this_lb): """Generates a l7Pools table from a list of LBaaS devices""" # https://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_LBaaS_L7Pool/ l7_table = formatting.Table(['Id', 'UUID', 'Balancer', 'Name', 'Protocol', 'Modify', 'Active']) for layer7 in this_lb.get('l7Pools', []): l7_table.add_row([ layer7.get('id'), layer7.get('uuid'), layer7.get('loadBalancingAlgorithm'), layer7.get('name'), layer7.get('protocol'), utils.clean_time(layer7.get('modifyDate')), layer7.get('provisioningStatus') ]) return l7_table
def cli(env): """List all active quotes on an account""" table = formatting.Table([ 'Id', 'Name', 'Created', 'Expiration', 'Status', 'Package Name', 'Package Id' ]) table.align['Name'] = 'l' table.align['Package Name'] = 'r' table.align['Package Id'] = 'l' manager = ordering.OrderingManager(env.client) items = manager.get_quotes() for item in items: package = item['order']['items'][0]['package'] table.add_row([ item.get('id'), item.get('name'), clean_time(item.get('createDate')), clean_time(item.get('modifyDate')), item.get('status'), package.get('keyName'), package.get('id') ]) env.fout(table)
def cli(env, limit): """Lists account orders. Use `slcli order lookup <ID>` to find more details about a specific order.""" manager = AccountManager(env.client) orders = manager.get_account_all_billing_orders(limit) order_table = formatting.Table(['Id', 'State', 'User', 'Date', 'Amount', 'Item'], title="orders") order_table.align = 'l' for order in orders: items = [] for item in order['items']: items.append(item['description']) create_date = utils.clean_time(order['createDate'], in_format='%Y-%m-%d', out_format='%Y-%m-%d') order_table.add_row([order['id'], order['status'], order['userRecord']['username'], create_date, order['orderTotalAmount'], utils.trim_to(' '.join(map(str, items)), 50)]) env.fout(order_table)
def get_invoice_table(identifier, top_items, details): """Formats a table for invoice top level items. :param int identifier: Invoice identifier. :param list top_items: invoiceTopLevelItems. :param bool details: To add very detailed list of charges. """ title = "Invoice %s" % identifier table = formatting.Table([ "Item Id", "Category", "Description", "Single", "Monthly", "Create Date", "Location" ], title=title) table.align['category'] = 'l' table.align['description'] = 'l' for item in top_items: fqdn = "%s.%s" % (item.get('hostName', ''), item.get('domainName', '')) # category id=2046, ram_usage doesn't have a name... category = utils.lookup(item, 'category', 'name') or item.get('categoryCode') description = nice_string(item.get('description')) if fqdn != '.': description = "%s (%s)" % (item.get('description'), fqdn) table.add_row([ item.get('id'), category, nice_string(description), "$%.2f" % float(item.get('oneTimeAfterTaxAmount')), "$%.2f" % float(item.get('recurringAfterTaxAmount')), utils.clean_time(item.get('createDate'), out_format="%Y-%m-%d"), utils.lookup(item, 'location', 'name') ]) if details: for child in item.get('children', []): table.add_row([ '>>>', utils.lookup(child, 'category', 'name'), nice_string(child.get('description')), "$%.2f" % float(child.get('oneTimeAfterTaxAmount')), "$%.2f" % float(child.get('recurringAfterTaxAmount')), '---', '---' ]) return table
def generate_netscaler_table(netscalers): """Tales a list of SoftLayer_Network_Application_Delivery_Controller and makes a table""" table = formatting.Table([ 'Id', 'Location', 'Name', 'Description', 'IP Address', 'Management Ip', 'Bandwidth', 'Create Date' ], title="Netscalers") for adc in sorted(netscalers, key=location_sort): table.add_row([ adc.get('id'), utils.lookup(adc, 'datacenter', 'longName'), adc.get('name'), adc.get('description'), adc.get('primaryIpAddress'), adc.get('managementIpAddress'), adc.get('outboundPublicBandwidthUsage', 0), utils.clean_time(adc.get('createDate')) ]) return table
def get_listener_table(this_lb): """Generates a protocols table from a list of LBaaS devices""" pools = {} # https://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_LBaaS_Listener/ listener_table = formatting.Table(['UUID', 'Max Connection', 'Mapping', 'Balancer', 'Modify', 'Active']) for listener in this_lb.get('listeners', []): pool = listener.get('defaultPool') priv_map = "{}:{}".format(pool['protocol'], pool['protocolPort']) pools[pool['uuid']] = priv_map mapping = "{}:{} -> {}".format(listener.get('protocol'), listener.get('protocolPort'), priv_map) listener_table.add_row([ listener.get('uuid'), listener.get('connectionLimit', 'None'), mapping, pool.get('loadBalancingAlgorithm', 'None'), utils.clean_time(listener.get('modifyDate')), listener.get('provisioningStatus') ]) return listener_table, pools
def cli(env, identifier, details): """Invoices and all that mess""" manager = AccountManager(env.client) top_items = manager.get_billing_items(identifier) title = "Invoice %s" % identifier table = formatting.Table([ "Item Id", "Category", "Description", "Single", "Monthly", "Create Date", "Location" ], title=title) table.align['category'] = 'l' table.align['description'] = 'l' for item in top_items: fqdn = "%s.%s" % (item.get('hostName', ''), item.get('domainName', '')) # category id=2046, ram_usage doesn't have a name... category = utils.lookup(item, 'category', 'name') or item.get('categoryCode') description = nice_string(item.get('description')) if fqdn != '.': description = "%s (%s)" % (item.get('description'), fqdn) table.add_row([ item.get('id'), category, nice_string(description), "$%.2f" % float(item.get('oneTimeAfterTaxAmount')), "$%.2f" % float(item.get('recurringAfterTaxAmount')), utils.clean_time(item.get('createDate'), out_format="%Y-%m-%d"), utils.lookup(item, 'location', 'name') ]) if details: for child in item.get('children', []): table.add_row([ '>>>', utils.lookup(child, 'category', 'name'), nice_string(child.get('description')), "$%.2f" % float(child.get('oneTimeAfterTaxAmount')), "$%.2f" % float(child.get('recurringAfterTaxAmount')), '---', '---' ]) env.fout(table)
def cli(env, identifier, start_date, end_date, valid_type, summary_period): """Usage information of a virtual server.""" vsi = SoftLayer.VSManager(env.client) table = formatting.Table(['counter', 'dateTime', 'type']) table_average = formatting.Table(['Average']) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') result = vsi.get_summary_data_usage(vs_id, start_date=start_date, end_date=end_date, valid_type=valid_type.upper(), summary_period=summary_period) if len(result) == 0: raise exceptions.CLIAbort( 'No metric data for this range of dates provided') count = 0 counter = 0.00 for data in result: if valid_type.upper() == "MEMORY_USAGE": usage_counter = data['counter'] / 2**30 else: usage_counter = data['counter'] table.add_row([ round(usage_counter, 2), clean_time(data['dateTime']), data['type'], ]) counter = counter + usage_counter count = count + 1 average = counter / count env.fout(table_average.add_row([round(average, 2)])) env.fout(table_average) env.fout(table)
def get_member_table(this_lb, pools): """Generates a members table from a list of LBaaS devices""" # https://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_LBaaS_Member/ member_col = ['UUID', 'Address', 'Weight', 'Modify', 'Active'] counter = 0 for uuid in pools.values(): member_col.append(f'P{counter}-> {uuid}') counter += 1 member_table = formatting.Table(member_col) for member in this_lb.get('members', []): row = [ member.get('uuid'), member.get('address'), member.get('weight'), utils.clean_time(member.get('modifyDate')), member.get('provisioningStatus') ] for uuid in pools: row.append(get_member_hp(this_lb.get('health'), member.get('uuid'), uuid)) member_table.add_row(row) return member_table
def cli(env, identifier, details): """Invoices and all that mess""" manager = AccountManager(env.client) top_items = manager.get_billing_items(identifier) title = "Invoice %s" % identifier table = formatting.Table(["Item Id", "Category", "Description", "Single", "Monthly", "Create Date", "Location"], title=title) table.align['category'] = 'l' table.align['description'] = 'l' for item in top_items: fqdn = "%s.%s" % (item.get('hostName', ''), item.get('domainName', '')) # category id=2046, ram_usage doesn't have a name... category = utils.lookup(item, 'category', 'name') or item.get('categoryCode') description = nice_string(item.get('description')) if fqdn != '.': description = "%s (%s)" % (item.get('description'), fqdn) table.add_row([ item.get('id'), category, nice_string(description), "$%.2f" % float(item.get('oneTimeAfterTaxAmount')), "$%.2f" % float(item.get('recurringAfterTaxAmount')), utils.clean_time(item.get('createDate'), out_format="%Y-%m-%d"), utils.lookup(item, 'location', 'name') ]) if details: for child in item.get('children', []): table.add_row([ '>>>', utils.lookup(child, 'category', 'name'), nice_string(child.get('description')), "$%.2f" % float(child.get('oneTimeAfterTaxAmount')), "$%.2f" % float(child.get('recurringAfterTaxAmount')), '---', '---' ]) env.fout(table)
def cli(env): """List all zones.""" manager = SoftLayer.DNSManager(env.client) object_mask = "mask[id,name,serial,updateDate,resourceRecordCount]" zones = manager.list_zones(mask=object_mask) table = formatting.Table(['id', 'zone', 'serial', 'updated', 'records']) table.align = 'l' for zone in zones: zone_serial = str(zone.get('serial')) zone_date = zone.get('updateDate', None) if zone_date is None: # The serial is just YYYYMMDD##, and since there is no createDate, just format it like it was one. zone_date = "{}-{}-{}T00:00:00-06:00".format( zone_serial[0:4], zone_serial[4:6], zone_serial[6:8]) table.add_row([ zone['id'], zone['name'], zone_serial, clean_time(zone_date), zone.get('resourceRecordCount', 0) ]) env.fout(table)
def generate_lbaas_table(lbaas): """Takes a list of SoftLayer_Network_LBaaS_LoadBalancer and makes a table""" table = formatting.Table([ 'Id', 'Location', 'Name', 'Description', 'Public', 'Create Date', 'Members', 'Listeners' ], title="IBM Cloud LoadBalancer") table.align['Name'] = 'l' table.align['Description'] = 'l' table.align['Location'] = 'l' for this_lb in sorted(lbaas, key=location_sort): table.add_row([ this_lb.get('id'), utils.lookup(this_lb, 'datacenter', 'longName'), this_lb.get('name'), this_lb.get('description'), 'Yes' if this_lb.get('isPublic', 1) == 1 else 'No', utils.clean_time(this_lb.get('createDate')), this_lb.get('memberCount', 0), this_lb.get('listenerCount', 0) ]) return table
def cli(env, identifier, start_date, end_date, valid_type, summary_period): """Usage information of a virtual server.""" vsi = SoftLayer.VSManager(env.client) table = formatting.Table(['counter', 'dateTime', 'type']) table_average = formatting.Table(['Average']) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') result = vsi.get_summary_data_usage(vs_id, start_date=start_date, end_date=end_date, valid_type=valid_type, summary_period=summary_period) if len(result) == 0: raise exceptions.CLIAbort('No metric data for this range of dates provided') count = 0 counter = 0.00 for data in result: if valid_type == "MEMORY_USAGE": usage_counter = data['counter'] / 2 ** 30 else: usage_counter = data['counter'] table.add_row([ round(usage_counter, 2), clean_time(data['dateTime']), data['type'], ]) counter = counter + usage_counter count = count + 1 average = counter / count env.fout(table_average.add_row([round(average, 2)])) env.fout(table_average) env.fout(table)
def cli(env, identifier): """Lists the Virtual Guests running on this server.""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') hw_guests = mgr.get_hardware_guests(hw_id) if not hw_guests: raise exceptions.CLIAbort("No Virtual Guests found.") table = formatting.Table([ 'id', 'hostname', 'CPU', 'Memory', 'Start Date', 'Status', 'powerState' ]) table.sortby = 'hostname' for guest in hw_guests: table.add_row([ guest['id'], guest['hostname'], '%i %s' % (guest['maxCpu'], guest['maxCpuUnits']), guest['maxMemory'], utils.clean_time(guest['createDate']), guest['status']['keyName'], guest['powerState']['keyName'] ]) env.fout(table)
def netscaler_table(this_lb): """Formats the netscaler info table""" table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['Id', this_lb.get('id')]) table.add_row(['Type', this_lb.get('description')]) table.add_row(['Name', this_lb.get('name')]) table.add_row( ['Location', utils.lookup(this_lb, 'datacenter', 'longName')]) table.add_row(['Managment Ip', this_lb.get('managementIpAddress')]) table.add_row( ['Root Password', utils.lookup(this_lb, 'password', 'password')]) table.add_row(['Primary Ip', this_lb.get('primaryIpAddress')]) table.add_row([ 'License Expiration', utils.clean_time(this_lb.get('licenseExpirationDate')) ]) subnet_table = formatting.Table(['Id', 'Subnet', 'Type', 'Space']) for subnet in this_lb.get('subnets', []): subnet_table.add_row([ subnet.get('id'), "{}/{}".format(subnet.get('networkIdentifier'), subnet.get('cidr')), subnet.get('subnetType'), subnet.get('addressSpace') ]) table.add_row(['Subnets', subnet_table]) vlan_table = formatting.Table(['Id', 'Number']) for vlan in this_lb.get('networkVlans', []): vlan_table.add_row([vlan.get('id'), vlan.get('vlanNumber')]) table.add_row(['Vlans', vlan_table]) return table
def cli(env, identifier, passwords, price, components): """Get details for a hardware device.""" hardware = SoftLayer.HardwareManager(env.client) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' hardware_id = helpers.resolve_id(hardware.resolve_ids, identifier, 'hardware') result = hardware.get_hardware(hardware_id) result = utils.NestedDict(result) hard_drives = hardware.get_hard_drives(hardware_id) operating_system = utils.lookup(result, 'operatingSystem', 'softwareLicense', 'softwareDescription') or {} memory = formatting.gb(result.get('memoryCapacity', 0)) owner = None if utils.lookup(result, 'billingItem') != []: owner = utils.lookup(result, 'billingItem', 'orderItem', 'order', 'userRecord', 'username') table_hard_drives = formatting.Table(['Name', 'Capacity', 'Serial #']) for drives in hard_drives: name = drives['hardwareComponentModel']['manufacturer'] + " " + drives[ 'hardwareComponentModel']['name'] capacity = str( drives['hardwareComponentModel']['hardwareGenericComponentModel'] ['capacity']) + " " + str( drives['hardwareComponentModel'] ['hardwareGenericComponentModel']['units']) serial = drives['serialNumber'] table_hard_drives.add_row([name, capacity, serial]) table.add_row(['id', result['id']]) table.add_row(['guid', result['globalIdentifier'] or formatting.blank()]) table.add_row(['hostname', result['hostname']]) table.add_row(['domain', result['domain']]) table.add_row(['fqdn', result['fullyQualifiedDomainName']]) table.add_row(['status', result['hardwareStatus']['status']]) table.add_row( ['datacenter', result['datacenter']['name'] or formatting.blank()]) table.add_row(['cores', result['processorPhysicalCoreAmount']]) table.add_row(['memory', memory]) table.add_row(['drives', table_hard_drives]) table.add_row( ['public_ip', result['primaryIpAddress'] or formatting.blank()]) table.add_row([ 'private_ip', result['primaryBackendIpAddress'] or formatting.blank() ]) table.add_row([ 'ipmi_ip', result['networkManagementIpAddress'] or formatting.blank() ]) table.add_row(['os', operating_system.get('name') or formatting.blank()]) table.add_row( ['os_version', operating_system.get('version') or formatting.blank()]) table.add_row(['created', result['provisionDate'] or formatting.blank()]) table.add_row(['owner', owner or formatting.blank()]) last_transaction = "{} ({})".format( utils.lookup(result, 'lastTransaction', 'transactionGroup', 'name'), utils.clean_time(utils.lookup(result, 'lastTransaction', 'modifyDate'))) table.add_row(['last_transaction', last_transaction]) table.add_row( ['billing', 'Hourly' if result['hourlyBillingFlag'] else 'Monthly']) vlan_table = formatting.Table(['type', 'number', 'id']) for vlan in result['networkVlans']: vlan_table.add_row( [vlan['networkSpace'], vlan['vlanNumber'], vlan['id']]) table.add_row(['vlans', vlan_table]) bandwidth = hardware.get_bandwidth_allocation(hardware_id) bw_table = _bw_table(bandwidth) table.add_row(['Bandwidth', bw_table]) system_table = _system_table(result['activeComponents']) table.add_row(['System_data', system_table]) if result.get('notes'): table.add_row(['notes', result['notes']]) if price: total_price = utils.lookup(result, 'billingItem', 'nextInvoiceTotalRecurringAmount') or 0 price_table = formatting.Table( ['Item', 'CategoryCode', 'Recurring Price']) price_table.align['Item'] = 'l' price_table.add_row(['Total', '-', total_price]) for item in utils.lookup(result, 'billingItem', 'nextInvoiceChildren') or []: price_table.add_row([ item['description'], item['categoryCode'], item['nextInvoiceTotalRecurringAmount'] ]) table.add_row(['prices', price_table]) if passwords: pass_table = formatting.Table(['username', 'password']) for item in result['operatingSystem']['passwords']: pass_table.add_row([item['username'], item['password']]) table.add_row(['users', pass_table]) pass_table = formatting.Table(['ipmi_username', 'password']) for item in result['remoteManagementAccounts']: pass_table.add_row([item['username'], item['password']]) table.add_row(['remote users', pass_table]) if components: components = hardware.get_components(identifier) components_table = formatting.Table( ['name', 'Firmware version', 'Firmware build date', 'Type']) components_table.align['date'] = 'l' component_ids = [] for hw_component in components: if hw_component['id'] not in component_ids: firmware = hw_component['hardwareComponentModel']['firmwares'][ 0] components_table.add_row([ utils.lookup(hw_component, 'hardwareComponentModel', 'longDescription'), utils.lookup(firmware, 'version'), utils.clean_time(utils.lookup(firmware, 'createDate')), utils.lookup(hw_component, 'hardwareComponentModel', 'hardwareGenericComponentModel', 'hardwareComponentType', 'keyName') ]) component_ids.append(hw_component['id']) table.add_row(['components', components_table]) table.add_row(['tags', formatting.tags(result['tagReferences'])]) env.fout(table)