def test_init(self):
        l = formatting.listing([1, 'two'], separator=':')
        self.assertEqual([1, 'two'], list(l))
        self.assertEqual(':', l.separator)

        l = formatting.listing([])
        self.assertEqual(',', l.separator)
    def test_init(self):
        l = formatting.listing([1, 'two'], separator=':')
        self.assertEqual([1, 'two'], list(l))
        self.assertEqual(':', l.separator)

        l = formatting.listing([])
        self.assertEqual(',', l.separator)
    def test_init(self):
        l = formatting.listing([1, "two"], separator=":")
        self.assertEqual([1, "two"], list(l))
        self.assertEqual(":", l.separator)

        l = formatting.listing([])
        self.assertEqual(",", l.separator)
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 test_to_python(self):
        l = formatting.listing([1, 'two'])
        result = l.to_python()
        self.assertEqual([1, 'two'], result)

        l = formatting.listing(x for x in [1, 'two'])
        result = l.to_python()
        self.assertEqual([1, 'two'], result)
    def test_str(self):
        l = formatting.listing([1, "two"])
        result = str(l)
        self.assertEqual("1,two", result)

        l = formatting.listing((x for x in [1, "two"]), separator=":")
        result = str(l)
        self.assertEqual("1:two", result)
    def test_str(self):
        l = formatting.listing([1, 'two'])
        result = str(l)
        self.assertEqual('1,two', result)

        l = formatting.listing((x for x in [1, 'two']), separator=':')
        result = str(l)
        self.assertEqual('1:two', result)
    def test_str(self):
        l = formatting.listing([1, 'two'])
        result = str(l)
        self.assertEqual('1,two', result)

        l = formatting.listing((x for x in [1, 'two']), separator=':')
        result = str(l)
        self.assertEqual('1:two', result)
    def test_to_python(self):
        l = formatting.listing([1, 'two'])
        result = l.to_python()
        self.assertEqual([1, 'two'], result)

        l = formatting.listing(x for x in [1, 'two'])
        result = l.to_python()
        self.assertEqual([1, 'two'], result)
Exemple #10
0
def cli(env, prices, location=None):
    """Server order options for a given chassis."""

    hardware_manager = hardware.HardwareManager(env.client)
    account_manager = account.AccountManager(env.client)
    options = hardware_manager.get_create_options(location)
    routers = account_manager.get_routers(location)
    tables = []

    # Datacenters
    dc_table = formatting.Table(['Datacenter', 'Value'], title="Datacenters")
    dc_table.sortby = 'Value'
    dc_table.align = 'l'
    for location_info in options['locations']:
        dc_table.add_row([location_info['name'], location_info['key']])
    tables.append(dc_table)

    tables.append(_preset_prices_table(options['sizes'], prices))
    tables.append(_os_prices_table(options['operating_systems'], prices))
    tables.append(_port_speed_prices_table(options['port_speeds'], prices))
    tables.append(_extras_prices_table(options['extras'], prices))
    tables.append(_get_routers(routers))

    # since this is multiple tables, this is required for a valid JSON object to be rendered.
    env.fout(formatting.listing(tables, separator='\n'))
Exemple #11
0
def cli(env):
    """List firewalls."""

    mgr = SoftLayer.FirewallManager(env.client)
    table = formatting.Table(['firewall id',
                              'type',
                              'features',
                              'server/vlan id'])
    fwvlans = mgr.get_firewalls()
    dedicated_firewalls = [firewall for firewall in fwvlans
                           if firewall['dedicatedFirewallFlag']]

    for vlan in dedicated_firewalls:
        features = []
        if vlan['highAvailabilityFirewallFlag']:
            features.append('HA')

        if features:
            feature_list = formatting.listing(features, separator=',')
        else:
            feature_list = formatting.blank()

        table.add_row([
            'vlan:%s' % vlan['networkVlanFirewall']['id'],
            'VLAN - dedicated',
            feature_list,
            vlan['id']
        ])

    shared_vlan = [firewall for firewall in fwvlans
                   if not firewall['dedicatedFirewallFlag']]
    for vlan in shared_vlan:
        vs_firewalls = [guest
                        for guest in vlan['firewallGuestNetworkComponents']
                        if has_firewall_component(guest)]

        for firewall in vs_firewalls:
            table.add_row([
                'vs:%s' % firewall['id'],
                'Virtual Server - standard',
                '-',
                firewall['guestNetworkComponent']['guest']['id']
            ])

        server_firewalls = [server
                            for server in vlan['firewallNetworkComponents']
                            if has_firewall_component(server)]

        for firewall in server_firewalls:
            table.add_row([
                'server:%s' % firewall['id'],
                'Server - standard',
                '-',
                utils.lookup(firewall,
                             'networkComponent',
                             'downlinkComponent',
                             'hardwareId')
            ])

    env.fout(table)
Exemple #12
0
            def add_cpus_row(cpu_options, name):
                """ Add CPU rows to the table """
                cpus = []
                for cpu_option in cpu_options:
                    cpus.append(str(cpu_option['template']['startCpus']))

                table.add_row(['cpus (%s)' % name,
                               formatting.listing(cpus, separator=',')])
Exemple #13
0
            def add_cpus_row(cpu_options, name):
                """ Add CPU rows to the table """
                cpus = []
                for cpu_option in cpu_options:
                    cpus.append(str(cpu_option['template']['startCpus']))

                table.add_row(['cpus (%s)' % name,
                               formatting.listing(cpus, separator=',')])
Exemple #14
0
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)
Exemple #15
0
def topic_table(topic):
    """Returns a table with details about a topic."""
    table = formatting.Table(['property', 'value'])
    table.align['property'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['name', topic['name']])
    table.add_row(['tags', formatting.listing(topic['tags'] or [])])
    return table
def _add_flavors_to_table(result, table):
    grouping = {
        'balanced': {
            'key_starts_with': 'B1',
            'flavors': []
        },
        'balanced local - hdd': {
            'key_starts_with': 'BL1',
            'flavors': []
        },
        'balanced local - ssd': {
            'key_starts_with': 'BL2',
            'flavors': []
        },
        'compute': {
            'key_starts_with': 'C1',
            'flavors': []
        },
        'memory': {
            'key_starts_with': 'M1',
            'flavors': []
        },
        'GPU': {
            'key_starts_with': 'AC',
            'flavors': []
        },
        'transient': {
            'transient': True,
            'flavors': []
        },
    }

    if result.get('flavors', None) is None:
        return

    for flavor_option in result['flavors']:
        flavor_key_name = utils.lookup(flavor_option, 'flavor', 'keyName')

        for name, group in grouping.items():
            if utils.lookup(flavor_option, 'template',
                            'transientGuestFlag') is True:
                if utils.lookup(group, 'transient') is True:
                    group['flavors'].append(flavor_key_name)
                    break

            elif utils.lookup(group, 'key_starts_with') is not None \
                    and flavor_key_name.startswith(group['key_starts_with']):
                group['flavors'].append(flavor_key_name)
                break

    for name, group in grouping.items():
        if len(group['flavors']) > 0:
            table.add_row([
                'flavors (%s)' % name,
                formatting.listing(group['flavors'], separator='\n')
            ])
Exemple #17
0
def cli(env, package_keyname, keyword, category, prices, location=None):
    """List package items used for ordering.

    The item keyNames listed can be used with `slcli order place` to specify
    the items that are being ordered in the package.

    .. Note::
        Items with a numbered category, like disk0 or gpu0, can be included
        multiple times in an order to match how many of the item you want to order.

    ::

        # List all items in the VSI package
        slcli order item-list CLOUD_SERVER

        # List Ubuntu OSes from the os category of the Bare Metal package
        slcli order item-list BARE_METAL_SERVER --category os --keyword ubuntu

    """
    manager = ordering.OrderingManager(env.client)

    tables = []

    _filter = {'items': {}}
    if keyword:
        _filter['items']['description'] = {'operation': '*= %s' % keyword}
    if category:
        _filter['items']['categories'] = {
            'categoryCode': {
                'operation': '_= %s' % category
            }
        }

    items = manager.list_items(package_keyname, filter=_filter)
    sorted_items = sort_items(items)

    categories = sorted_items.keys()
    if prices:
        _item_list_prices(categories, sorted_items, tables)
        if location:
            location_prices = manager.get_item_prices_by_location(
                location, package_keyname)
            _location_item_prices(location_prices, location, tables)
    else:
        table_items_detail = formatting.Table(COLUMNS)
        for category_name in sorted(categories):
            for item in sorted_items[category_name]:
                table_items_detail.add_row([
                    category_name, item['keyName'], item['description'],
                    get_price(item)
                ])
        tables.append(table_items_detail)
    env.fout(formatting.listing(tables, separator='\n'))
Exemple #18
0
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
Exemple #19
0
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)
    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 _add_flavor_rows(flavor_key, flavor_label, flavor_options):
        flavors = []

        for flavor_option in flavor_options:
            flavor_key_name = utils.lookup(flavor_option, 'flavor', 'keyName')
            if not flavor_key_name.startswith(flavor_key):
                continue

            flavors.append(flavor_key_name)

        if len(flavors) > 0:
            table.add_row(['flavors (%s)' % flavor_label,
                           formatting.listing(flavors, separator='\n')])
Exemple #22
0
def queue_table(queue):
    """Returns a table with details about a queue."""
    table = formatting.Table(['property', 'value'])
    table.align['property'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['name', queue['name']])
    table.add_row(['message_count', queue['message_count']])
    table.add_row(['visible_message_count', queue['visible_message_count']])
    table.add_row(['tags', formatting.listing(queue['tags'] or [])])
    table.add_row(['expiration', queue['expiration']])
    table.add_row(['visibility_interval', queue['visibility_interval']])
    return table
Exemple #23
0
    def _add_flavor_rows(flavor_key, flavor_label, flavor_options):
        flavors = []

        for flavor_option in flavor_options:
            flavor_key_name = utils.lookup(flavor_option, 'flavor', 'keyName')
            if not flavor_key_name.startswith(flavor_key):
                continue

            flavors.append(flavor_key_name)

        if len(flavors) > 0:
            table.add_row([
                'flavors (%s)' % flavor_label,
                formatting.listing(flavors, separator='\n')
            ])
Exemple #24
0
            def add_block_rows(disks, name):
                """ Add block rows to the table """
                simple = {}
                for disk in disks:
                    block = disk['template']['blockDevices'][0]
                    bid = block['device']

                    if bid not in simple:
                        simple[bid] = []

                    simple[bid].append(str(block['diskImage']['capacity']))

                for label in sorted(simple.keys()):
                    table.add_row(['%s disk(%s)' % (name, label),
                                   formatting.listing(simple[label],
                                                      separator=',')])
    def add_block_rows(disks, name):
        """Add block rows to the table."""
        simple = {}
        for disk in disks:
            block = disk['template']['blockDevices'][0]
            bid = block['device']

            if bid not in simple:
                simple[bid] = []

            simple[bid].append(str(block['diskImage']['capacity']))

        for label in sorted(simple):
            table.add_row(['%s disk(%s)' % (name, label),
                           formatting.listing(simple[label],
                                              separator=',')])
Exemple #26
0
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):
    """Server order options for a given chassis."""

    hardware_manager = hardware.HardwareManager(env.client)
    options = hardware_manager.get_create_options()

    tables = []

    # Datacenters
    dc_table = formatting.Table(['datacenter', 'value'])
    dc_table.sortby = 'value'
    for location in options['locations']:
        dc_table.add_row([location['name'], location['key']])
    tables.append(dc_table)

    # Presets
    preset_table = formatting.Table(['size', 'value'])
    preset_table.sortby = 'value'
    for size in options['sizes']:
        preset_table.add_row([size['name'], size['key']])
    tables.append(preset_table)

    # Operating systems
    os_table = formatting.Table(['operating_system', 'value'])
    os_table.sortby = 'value'
    for operating_system in options['operating_systems']:
        os_table.add_row([operating_system['name'], operating_system['key']])
    tables.append(os_table)

    # Port speed
    port_speed_table = formatting.Table(['port_speed', 'value'])
    port_speed_table.sortby = 'value'
    for speed in options['port_speeds']:
        port_speed_table.add_row([speed['name'], speed['key']])
    tables.append(port_speed_table)

    # Extras
    extras_table = formatting.Table(['extras', 'value'])
    extras_table.sortby = 'value'
    for extra in options['extras']:
        extras_table.add_row([extra['name'], extra['key']])
    tables.append(extras_table)

    env.fout(formatting.listing(tables, separator='\n'))
def cli(env):
    """Server order options for a given chassis."""

    hardware_manager = hardware.HardwareManager(env.client)
    options = hardware_manager.get_create_options()

    tables = []

    # Datacenters
    dc_table = formatting.Table(['datacenter', 'value'])
    dc_table.sortby = 'value'
    for location in options['locations']:
        dc_table.add_row([location['name'], location['key']])
    tables.append(dc_table)

    # Presets
    preset_table = formatting.Table(['size', 'value'])
    preset_table.sortby = 'value'
    for size in options['sizes']:
        preset_table.add_row([size['name'], size['key']])
    tables.append(preset_table)

    # Operating systems
    os_table = formatting.Table(['operating_system', 'value'])
    os_table.sortby = 'value'
    for operating_system in options['operating_systems']:
        os_table.add_row([operating_system['name'], operating_system['key']])
    tables.append(os_table)

    # Port speed
    port_speed_table = formatting.Table(['port_speed', 'value'])
    port_speed_table.sortby = 'value'
    for speed in options['port_speeds']:
        port_speed_table.add_row([speed['name'], speed['key']])
    tables.append(port_speed_table)

    # Extras
    extras_table = formatting.Table(['extras', 'value'])
    extras_table.sortby = 'value'
    for extra in options['extras']:
        extras_table.add_row([extra['name'], extra['key']])
    tables.append(extras_table)

    env.fout(formatting.listing(tables, separator='\n'))
Exemple #29
0
    def execute(self, args):
        image_mgr = SoftLayer.ImageManager(self.client)
        image_id = helpers.resolve_id(image_mgr.resolve_ids,
                                      args.get('<identifier>'),
                                      'image')

        image = image_mgr.get_image(image_id, mask=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(['account', image.get('accountId', formatting.blank())])
        table.add_row(['visibility',
                       PUBLIC_TYPE if image['publicFlag'] else 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=',')])

        return table
def cli(env, **kwargs):
    """host order options for a given dedicated host.

    To get a list of available backend routers see example:
    slcli dh create-options --datacenter dal05 --flavor 56_CORES_X_242_RAM_X_1_4_TB
    """

    mgr = SoftLayer.DedicatedHostManager(env.client)
    tables = []

    if not kwargs['flavor'] and not kwargs['datacenter']:
        options = mgr.get_create_options()

        # Datacenters
        dc_table = formatting.Table(['datacenter', 'value'])
        dc_table.sortby = 'value'
        for location in options['locations']:
            dc_table.add_row([location['name'], location['key']])
        tables.append(dc_table)

        dh_table = formatting.Table(
            ['Dedicated Virtual Host Flavor(s)', 'value'])
        dh_table.sortby = 'value'
        for item in options['dedicated_host']:
            dh_table.add_row([item['name'], item['key']])
        tables.append(dh_table)
    else:
        if kwargs['flavor'] is None or kwargs['datacenter'] is None:
            raise exceptions.ArgumentError('Both a flavor and datacenter need '
                                           'to be passed as arguments '
                                           'ex. slcli dh create-options -d '
                                           'ams01 -f '
                                           '56_CORES_X_242_RAM_X_1_4_TB')
        router_opt = mgr.get_router_options(kwargs['datacenter'],
                                            kwargs['flavor'])
        br_table = formatting.Table(['Available Backend Routers'])
        for router in router_opt:
            br_table.add_row([router['hostname']])
        tables.append(br_table)

    env.fout(formatting.listing(tables, separator='\n'))
def cli(env, **kwargs):
    """host order options for a given dedicated host.

    To get a list of available backend routers see example:
    slcli dh create-options --datacenter dal05 --flavor 56_CORES_X_242_RAM_X_1_4_TB
    """

    mgr = SoftLayer.DedicatedHostManager(env.client)
    tables = []

    if not kwargs['flavor'] and not kwargs['datacenter']:
        options = mgr.get_create_options()

        # Datacenters
        dc_table = formatting.Table(['datacenter', 'value'])
        dc_table.sortby = 'value'
        for location in options['locations']:
            dc_table.add_row([location['name'], location['key']])
        tables.append(dc_table)

        dh_table = formatting.Table(['Dedicated Virtual Host Flavor(s)', 'value'])
        dh_table.sortby = 'value'
        for item in options['dedicated_host']:
            dh_table.add_row([item['name'], item['key']])
        tables.append(dh_table)
    else:
        if kwargs['flavor'] is None or kwargs['datacenter'] is None:
            raise exceptions.ArgumentError('Both a flavor and datacenter need '
                                           'to be passed as arguments '
                                           'ex. slcli dh create-options -d '
                                           'ams01 -f '
                                           '56_CORES_X_242_RAM_X_1_4_TB')
        router_opt = mgr.get_router_options(kwargs['datacenter'], kwargs['flavor'])
        br_table = formatting.Table(
            ['Available Backend Routers'])
        for router in router_opt:
            br_table.add_row([router['hostname']])
        tables.append(br_table)

    env.fout(formatting.listing(tables, separator='\n'))
def cli(env, prices, location=None):
    """Server order options for a given chassis."""

    hardware_manager = hardware.HardwareManager(env.client)
    account_manager = account.AccountManager(env.client)
    options = hardware_manager.get_create_options(location)
    routers = account_manager.get_routers(location=location)
    network_manager = network.NetworkManager(env.client)

    pods = network_manager.get_closed_pods()

    tables = []

    # Datacenters
    dc_table = formatting.Table(['Datacenter', 'Value', 'Note'],
                                title="Datacenters")
    dc_table.sortby = 'Value'
    dc_table.align = 'l'
    for location_info in options['locations']:
        closure = []
        for pod in pods:
            if location_info['key'] in str(pod['name']):
                closure.append(pod['name'])

        notes = '-'
        if len(closure) > 0:
            notes = 'closed soon: %s' % (', '.join(closure))
        dc_table.add_row([location_info['name'], location_info['key'], notes])
    tables.append(dc_table)

    tables.append(_preset_prices_table(options['sizes'], prices))
    tables.append(_os_prices_table(options['operating_systems'], prices))
    tables.append(_port_speed_prices_table(options['port_speeds'], prices))
    tables.append(_extras_prices_table(options['extras'], prices))
    tables.append(_get_routers(routers))

    # since this is multiple tables, this is required for a valid JSON object to be rendered.
    env.fout(formatting.listing(tables, separator='\n'))
Exemple #33
0
    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):
    """Virtual server order options."""

    vsi = SoftLayer.VSManager(env.client)
    result = vsi.get_create_options()

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    # Datacenters
    datacenters = [dc['template']['datacenter']['name']
                   for dc in result['datacenters']]
    datacenters = sorted(datacenters)

    table.add_row(['datacenter',
                   formatting.listing(datacenters, separator='\n')])

    def _add_flavor_rows(flavor_key, flavor_label, flavor_options):
        flavors = []

        for flavor_option in flavor_options:
            flavor_key_name = utils.lookup(flavor_option, 'flavor', 'keyName')
            if not flavor_key_name.startswith(flavor_key):
                continue

            flavors.append(flavor_key_name)

        if len(flavors) > 0:
            table.add_row(['flavors (%s)' % flavor_label,
                           formatting.listing(flavors, separator='\n')])

    if result.get('flavors', None):
        _add_flavor_rows('B1', 'balanced', result['flavors'])
        _add_flavor_rows('BL1', 'balanced local - hdd', result['flavors'])
        _add_flavor_rows('BL2', 'balanced local - ssd', result['flavors'])
        _add_flavor_rows('C1', 'compute', result['flavors'])
        _add_flavor_rows('M1', 'memory', result['flavors'])

    # CPUs
    standard_cpus = [int(x['template']['startCpus']) for x in result['processors']
                     if not x['template'].get('dedicatedAccountHostOnlyFlag',
                                              False)
                     and not x['template'].get('dedicatedHost', None)]
    ded_cpus = [int(x['template']['startCpus']) for x in result['processors']
                if x['template'].get('dedicatedAccountHostOnlyFlag', False)]
    ded_host_cpus = [int(x['template']['startCpus']) for x in result['processors']
                     if x['template'].get('dedicatedHost', None)]

    standard_cpus = sorted(standard_cpus)
    table.add_row(['cpus (standard)', formatting.listing(standard_cpus, separator=',')])
    ded_cpus = sorted(ded_cpus)
    table.add_row(['cpus (dedicated)', formatting.listing(ded_cpus, separator=',')])
    ded_host_cpus = sorted(ded_host_cpus)
    table.add_row(['cpus (dedicated host)', formatting.listing(ded_host_cpus, separator=',')])

    # Memory
    memory = [int(m['template']['maxMemory']) for m in result['memory']
              if not m['itemPrice'].get('dedicatedHostInstanceFlag', False)]
    ded_host_memory = [int(m['template']['maxMemory']) for m in result['memory']
                       if m['itemPrice'].get('dedicatedHostInstanceFlag', False)]

    memory = sorted(memory)
    table.add_row(['memory',
                   formatting.listing(memory, separator=',')])

    ded_host_memory = sorted(ded_host_memory)
    table.add_row(['memory (dedicated host)',
                   formatting.listing(ded_host_memory, separator=',')])

    # Operating Systems
    op_sys = [o['template']['operatingSystemReferenceCode'] for o in
              result['operatingSystems']]

    op_sys = sorted(op_sys)
    os_summary = set()

    for operating_system in op_sys:
        os_summary.add(operating_system[0:operating_system.find('_')])

    for summary in sorted(os_summary):
        table.add_row([
            'os (%s)' % summary,
            os.linesep.join(sorted([x for x in op_sys
                                    if x[0:len(summary)] == summary]))
        ])

    # Disk
    local_disks = [x for x in result['blockDevices']
                   if x['template'].get('localDiskFlag', False)
                   and not x['itemPrice'].get('dedicatedHostInstanceFlag',
                                              False)]

    ded_host_local_disks = [x for x in result['blockDevices']
                            if x['template'].get('localDiskFlag', False)
                            and x['itemPrice'].get('dedicatedHostInstanceFlag',
                                                   False)]

    san_disks = [x for x in result['blockDevices']
                 if not x['template'].get('localDiskFlag', False)]

    def add_block_rows(disks, name):
        """Add block rows to the table."""
        simple = {}
        for disk in disks:
            block = disk['template']['blockDevices'][0]
            bid = block['device']

            if bid not in simple:
                simple[bid] = []

            simple[bid].append(str(block['diskImage']['capacity']))

        for label in sorted(simple):
            table.add_row(['%s disk(%s)' % (name, label),
                           formatting.listing(simple[label],
                                              separator=',')])

    add_block_rows(san_disks, 'san')
    add_block_rows(local_disks, 'local')
    add_block_rows(ded_host_local_disks, 'local (dedicated host)')

    # Network
    speeds = []
    ded_host_speeds = []
    for option in result['networkComponents']:
        template = option.get('template', None)
        price = option.get('itemPrice', None)

        if not template or not price \
                or not template.get('networkComponents', None):
            continue

        if not template['networkComponents'][0] \
                or not template['networkComponents'][0].get('maxSpeed', None):
            continue

        max_speed = str(template['networkComponents'][0]['maxSpeed'])
        if price.get('dedicatedHostInstanceFlag', False) \
                and max_speed not in ded_host_speeds:
            ded_host_speeds.append(max_speed)
        elif max_speed not in speeds:
            speeds.append(max_speed)

    speeds = sorted(speeds)
    table.add_row(['nic', formatting.listing(speeds, separator=',')])

    ded_host_speeds = sorted(ded_host_speeds)
    table.add_row(['nic (dedicated host)',
                   formatting.listing(ded_host_speeds, separator=',')])

    env.fout(table)
Exemple #35
0
def cli(env, identifier, passwords=False, price=False):
    """Get details for a virtual server."""

    vsi = SoftLayer.VSManager(env.client)
    table = formatting.KeyValueTable(['Name', 'Value'])
    table.align['Name'] = 'r'
    table.align['Value'] = 'l'

    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
    result = vsi.get_instance(vs_id)
    result = utils.NestedDict(result)

    table.add_row(['id', result['id']])
    table.add_row(['guid', result['globalIdentifier']])
    table.add_row(['hostname', result['hostname']])
    table.add_row(['domain', result['domain']])
    table.add_row(['fqdn', result['fullyQualifiedDomainName']])
    table.add_row([
        'status',
        formatting.FormattedItem(
            result['status']['keyName'] or formatting.blank(),
            result['status']['name'] or formatting.blank())
    ])
    table.add_row([
        'state',
        formatting.FormattedItem(
            utils.lookup(result, 'powerState', 'keyName'),
            utils.lookup(result, 'powerState', 'name'),
        )
    ])
    table.add_row(['active_transaction', formatting.active_txn(result)])
    table.add_row(
        ['datacenter', result['datacenter']['name'] or formatting.blank()])
    operating_system = utils.lookup(result, 'operatingSystem',
                                    'softwareLicense',
                                    'softwareDescription') or {}
    table.add_row([
        'os',
        formatting.FormattedItem(
            operating_system.get('version') or formatting.blank(),
            operating_system.get('name') or formatting.blank())
    ])
    table.add_row(
        ['os_version',
         operating_system.get('version') or formatting.blank()])
    table.add_row(['cores', result['maxCpu']])
    table.add_row(['memory', formatting.mb_to_gb(result['maxMemory'])])
    table.add_row(
        ['public_ip', result['primaryIpAddress'] or formatting.blank()])
    table.add_row([
        'private_ip', result['primaryBackendIpAddress'] or formatting.blank()
    ])
    table.add_row(['private_only', result['privateNetworkOnlyFlag']])
    table.add_row(['private_cpu', result['dedicatedAccountHostOnlyFlag']])
    table.add_row(['created', result['createDate']])
    table.add_row(['modified', result['modifyDate']])
    if utils.lookup(result, 'billingItem') != []:
        table.add_row([
            'owner',
            formatting.FormattedItem(
                utils.lookup(result, 'billingItem', 'orderItem', 'order',
                             'userRecord', 'username') or formatting.blank(), )
        ])
    else:
        table.add_row(['owner', formatting.blank()])

    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])

    if result.get('notes'):
        table.add_row(['notes', result['notes']])

    if price:
        table.add_row(['price rate', result['billingItem']['recurringFee']])

    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])

    tag_row = []
    for tag_detail in result['tagReferences']:
        tag = utils.lookup(tag_detail, 'tag', 'name')
        if tag is not None:
            tag_row.append(tag)

    if tag_row:
        table.add_row(['tags', formatting.listing(tag_row, separator=', ')])

    # Test to see if this actually has a primary (public) ip address
    try:
        if not result['privateNetworkOnlyFlag']:
            ptr_domains = env.client.call(
                'Virtual_Guest',
                'getReverseDomainRecords',
                id=vs_id,
            )

            for ptr_domain in ptr_domains:
                for ptr in ptr_domain['resourceRecords']:
                    table.add_row(['ptr', ptr['data']])
    except SoftLayer.SoftLayerAPIError:
        pass

    env.fout(table)
Exemple #36
0
 def _execute(self, _):
     backend_macs = SoftLayer.MetadataManager().get("backend_mac")
     return formatting.listing(backend_macs, separator=",")
Exemple #37
0
    def execute(self, args):
        vsi = SoftLayer.VSManager(self.client)
        table = formatting.KeyValueTable(['Name', 'Value'])
        table.align['Name'] = 'r'
        table.align['Value'] = 'l'

        vs_id = helpers.resolve_id(vsi.resolve_ids,
                                   args.get('<identifier>'),
                                   'VS')
        result = vsi.get_instance(vs_id)
        result = utils.NestedDict(result)

        table.add_row(['id', result['id']])
        table.add_row(['hostname', result['fullyQualifiedDomainName']])
        table.add_row(['status', formatting.FormattedItem(
            result['status']['keyName'] or formatting.blank(),
            result['status']['name'] or formatting.blank()
        )])
        table.add_row(['active_transaction', formatting.active_txn(result)])
        table.add_row(['state', formatting.FormattedItem(
            utils.lookup(result, 'powerState', 'keyName'),
            utils.lookup(result, 'powerState', 'name'),
        )])
        table.add_row(['datacenter',
                       result['datacenter']['name'] or formatting.blank()])
        operating_system = utils.lookup(result,
                                        'operatingSystem',
                                        'softwareLicense',
                                        'softwareDescription') or {}
        table.add_row([
            'os',
            formatting.FormattedItem(
                operating_system.get('version') or formatting.blank(),
                operating_system.get('name') or formatting.blank()
            )])
        table.add_row(['os_version',
                       operating_system.get('version') or formatting.blank()])
        table.add_row(['cores', result['maxCpu']])
        table.add_row(['memory', formatting.mb_to_gb(result['maxMemory'])])
        table.add_row(['public_ip',
                       result['primaryIpAddress'] or formatting.blank()])
        table.add_row(['private_ip',
                       result['primaryBackendIpAddress']
                       or formatting.blank()])
        table.add_row(['private_only', result['privateNetworkOnlyFlag']])
        table.add_row(['private_cpu', result['dedicatedAccountHostOnlyFlag']])
        table.add_row(['created', result['createDate']])
        table.add_row(['modified', result['modifyDate']])
        table.add_row(['owner', FormattedItem(
            lookup(result, 'billingItem', 'orderItem',
                   'order', 'userRecord', 'username'),
        )])

        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])

        if result.get('notes'):
            table.add_row(['notes', result['notes']])

        if args.get('--price'):
            table.add_row(['price rate',
                           result['billingItem']['recurringFee']])

        if args.get('--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])

        tag_row = []
        for tag in result['tagReferences']:
            tag_row.append(tag['tag']['name'])

        if tag_row:
            table.add_row(['tags', formatting.listing(tag_row, separator=',')])

        # Test to see if this actually has a primary (public) ip address
        if result['primaryIpAddress']:
            ptr_domains = (self.client['Virtual_Guest']
                           .getReverseDomainRecords(id=vs_id))

            for ptr_domain in ptr_domains:
                for ptr in ptr_domain['resourceRecords']:
                    table.add_row(['ptr', ptr['data']])

        return table
Exemple #38
0
    def execute(self, args):
        vsi = SoftLayer.VSManager(self.client)
        result = vsi.get_create_options()

        show_all = True
        for opt_name in self.options:
            if args.get("--" + opt_name):
                show_all = False
                break

        if args['--all']:
            show_all = True

        table = formatting.KeyValueTable(['Name', 'Value'])
        table.align['Name'] = 'r'
        table.align['Value'] = 'l'

        if args['--datacenter'] or show_all:
            datacenters = [dc['template']['datacenter']['name']
                           for dc in result['datacenters']]
            table.add_row(['datacenter',
                           formatting.listing(datacenters, separator=',')])

        if args['--cpu'] or show_all:
            standard_cpu = [x for x in result['processors']
                            if not x['template'].get(
                                'dedicatedAccountHostOnlyFlag', False)]

            ded_cpu = [x for x in result['processors']
                       if x['template'].get('dedicatedAccountHostOnlyFlag',
                                            False)]

            def add_cpus_row(cpu_options, name):
                """ Add CPU rows to the table """
                cpus = []
                for cpu_option in cpu_options:
                    cpus.append(str(cpu_option['template']['startCpus']))

                table.add_row(['cpus (%s)' % name,
                               formatting.listing(cpus, separator=',')])

            add_cpus_row(ded_cpu, 'private')
            add_cpus_row(standard_cpu, 'standard')

        if args['--memory'] or show_all:
            memory = [
                str(m['template']['maxMemory']) for m in result['memory']]
            table.add_row(['memory',
                           formatting.listing(memory, separator=',')])

        if args['--os'] or show_all:
            op_sys = [
                o['template']['operatingSystemReferenceCode'] for o in
                result['operatingSystems']]

            op_sys = sorted(op_sys)
            os_summary = set()

            for operating_system in op_sys:
                os_summary.add(operating_system[0:operating_system.find('_')])

            for summary in sorted(os_summary):
                table.add_row([
                    'os (%s)' % summary,
                    os.linesep.join(sorted([x for x in op_sys
                                            if x[0:len(summary)] == summary]))
                ])

        if args['--disk'] or show_all:
            local_disks = [x for x in result['blockDevices']
                           if x['template'].get('localDiskFlag', False)]

            san_disks = [x for x in result['blockDevices']
                         if not x['template'].get('localDiskFlag', False)]

            def add_block_rows(disks, name):
                """ Add block rows to the table """
                simple = {}
                for disk in disks:
                    block = disk['template']['blockDevices'][0]
                    bid = block['device']

                    if bid not in simple:
                        simple[bid] = []

                    simple[bid].append(str(block['diskImage']['capacity']))

                for label in sorted(simple.keys()):
                    table.add_row(['%s disk(%s)' % (name, label),
                                   formatting.listing(simple[label],
                                                      separator=',')])

            add_block_rows(local_disks, 'local')
            add_block_rows(san_disks, 'san')

        if args['--nic'] or show_all:
            speeds = []
            for comp in result['networkComponents']:
                speed = comp['template']['networkComponents'][0]['maxSpeed']
                speeds.append(str(speed))

            speeds = sorted(speeds)

            table.add_row(['nic', formatting.listing(speeds, separator=',')])

        return table
Exemple #39
0
def cli(env, identifier, passwords=False, price=False):
    """Get details for a virtual server."""

    vsi = SoftLayer.VSManager(env.client)
    table = formatting.KeyValueTable(['Name', 'Value'])
    table.align['Name'] = 'r'
    table.align['Value'] = 'l'

    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
    result = vsi.get_instance(vs_id)
    result = utils.NestedDict(result)

    table.add_row(['id', result['id']])
    table.add_row(['guid', result['globalIdentifier']])
    table.add_row(['hostname', result['hostname']])
    table.add_row(['domain', result['domain']])
    table.add_row(['fqdn', result['fullyQualifiedDomainName']])
    table.add_row(['status', formatting.FormattedItem(
        result['status']['keyName'] or formatting.blank(),
        result['status']['name'] or formatting.blank()
    )])
    table.add_row(['state', formatting.FormattedItem(
        utils.lookup(result, 'powerState', 'keyName'),
        utils.lookup(result, 'powerState', 'name'),
    )])
    table.add_row(['active_transaction', formatting.active_txn(result)])
    table.add_row(['datacenter',
                   result['datacenter']['name'] or formatting.blank()])
    operating_system = utils.lookup(result,
                                    'operatingSystem',
                                    'softwareLicense',
                                    'softwareDescription') or {}
    table.add_row([
        'os',
        formatting.FormattedItem(
            operating_system.get('version') or formatting.blank(),
            operating_system.get('name') or formatting.blank()
        )])
    table.add_row(['os_version',
                   operating_system.get('version') or formatting.blank()])
    table.add_row(['cores', result['maxCpu']])
    table.add_row(['memory', formatting.mb_to_gb(result['maxMemory'])])
    table.add_row(['public_ip',
                   result['primaryIpAddress'] or formatting.blank()])
    table.add_row(['private_ip',
                   result['primaryBackendIpAddress'] or formatting.blank()])
    table.add_row(['private_only', result['privateNetworkOnlyFlag']])
    table.add_row(['private_cpu', result['dedicatedAccountHostOnlyFlag']])
    table.add_row(['created', result['createDate']])
    table.add_row(['modified', result['modifyDate']])
    if utils.lookup(result, 'billingItem') != []:
        table.add_row(['owner', formatting.FormattedItem(
            utils.lookup(result, 'billingItem', 'orderItem',
                         'order', 'userRecord',
                         'username') or formatting.blank(),
        )])
    else:
        table.add_row(['owner', formatting.blank()])

    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])

    if result.get('notes'):
        table.add_row(['notes', result['notes']])

    if price:
        table.add_row(['price rate',
                       result['billingItem']['recurringFee']])

    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])

    tag_row = []
    for tag_detail in result['tagReferences']:
        tag = utils.lookup(tag_detail, 'tag', 'name')
        if tag is not None:
            tag_row.append(tag)

    if tag_row:
        table.add_row(['tags', formatting.listing(tag_row, separator=', ')])

    # Test to see if this actually has a primary (public) ip address
    try:
        if not result['privateNetworkOnlyFlag']:
            ptr_domains = env.client.call(
                'Virtual_Guest', 'getReverseDomainRecords',
                id=vs_id,
            )

            for ptr_domain in ptr_domains:
                for ptr in ptr_domain['resourceRecords']:
                    table.add_row(['ptr', ptr['data']])
    except SoftLayer.SoftLayerAPIError:
        pass

    env.fout(table)
Exemple #40
0
    def execute(self, args):
        hardware = SoftLayer.HardwareManager(self.client)

        table = formatting.KeyValueTable(['Name', 'Value'])
        table.align['Name'] = 'r'
        table.align['Value'] = 'l'

        hardware_id = helpers.resolve_id(hardware.resolve_ids,
                                         args.get('<identifier>'), 'hardware')
        result = hardware.get_hardware(hardware_id)
        result = utils.NestedDict(result)

        table.add_row(['id', result['id']])
        table.add_row(['hostname', 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', formatting.gb(result['memoryCapacity'])])
        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',
            formatting.FormattedItem(
                result['operatingSystem']['softwareLicense']
                ['softwareDescription']['referenceCode'] or formatting.blank(),
                result['operatingSystem']['softwareLicense']
                ['softwareDescription']['name'] or formatting.blank())
        ])

        table.add_row(
            ['created', result['provisionDate'] or formatting.blank()])

        table.add_row([
            'owner',
            formatting.FormattedItem(
                utils.lookup(result, 'billingItem', 'orderItem', 'order',
                             'userRecord', 'username') or formatting.blank())
        ])

        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])

        if result.get('notes'):
            table.add_row(['notes', result['notes']])

        if args.get('--price'):
            table.add_row(
                ['price rate', result['billingItem']['recurringFee']])

        if args.get('--passwords'):
            user_strs = []
            for item in result['operatingSystem']['passwords']:
                user_strs.append("%s %s" %
                                 (item['username'], item['password']))
            table.add_row(['users', formatting.listing(user_strs)])

        tag_row = []
        for tag in result['tagReferences']:
            tag_row.append(tag['tag']['name'])

        if tag_row:
            table.add_row(['tags', formatting.listing(tag_row, separator=',')])

        # Test to see if this actually has a primary (public) ip address
        try:
            if not result['privateNetworkOnlyFlag']:
                ptr_domains = (
                    self.client['Hardware_Server'].getReverseDomainRecords(
                        id=hardware_id))

                for ptr_domain in ptr_domains:
                    for ptr in ptr_domain['resourceRecords']:
                        table.add_row(['ptr', ptr['data']])
        except SoftLayer.SoftLayerAPIError:
            pass
        return table
Exemple #41
0
def cli(env):
    """List firewalls."""

    mgr = SoftLayer.FirewallManager(env.client)
    table = formatting.Table(
        ['firewall id', 'type', 'features', 'server/vlan id'],
        title='Single Server Firewalls')
    fwvlans = mgr.get_firewalls()
    dedicated_firewalls = [
        firewall for firewall in fwvlans if firewall['dedicatedFirewallFlag']
    ]

    for vlan in dedicated_firewalls:
        features = []
        if vlan['highAvailabilityFirewallFlag']:
            features.append('HA')

        if features:
            feature_list = formatting.listing(features, separator=',')
        else:
            feature_list = formatting.blank()

        table.add_row([
            'vlan:%s' % vlan['networkVlanFirewall']['id'], 'VLAN - dedicated',
            feature_list, vlan['id']
        ])

    shared_vlan = [
        firewall for firewall in fwvlans
        if not firewall['dedicatedFirewallFlag']
    ]
    for vlan in shared_vlan:
        vs_firewalls = [
            guest for guest in vlan['firewallGuestNetworkComponents']
            if has_firewall_component(guest)
        ]

        for firewall in vs_firewalls:
            table.add_row([
                'vs:%s' % firewall['id'], 'Virtual Server - standard', '-',
                firewall['guestNetworkComponent']['guest']['id']
            ])

        server_firewalls = [
            server for server in vlan['firewallNetworkComponents']
            if has_firewall_component(server)
        ]

        for firewall in server_firewalls:
            table.add_row([
                'server:%s' % firewall['id'], 'Server - standard', '-',
                utils.lookup(firewall, 'networkComponent', 'downlinkComponent',
                             'hardwareId')
            ])

    table_gatewalls = formatting.Table([
        'Id', 'firewall', 'type', 'Hostname', 'Location', 'Public Ip',
        'Private Ip', 'Associated vlan', 'status'
    ],
                                       title='Multi Vlan Firewall')
    fw_gatewwalls = mgr.get_firewalls_gatewalls()

    for gatewalls in fw_gatewwalls:
        table_gatewalls.add_row([
            gatewalls['networkFirewall']['id'],
            gatewalls.get('name'),
            gatewalls['networkFirewall']['firewallType'],
            gatewalls['members'][0]['hardware']['hostname'],
            gatewalls['networkFirewall']['datacenter']['name'],
            gatewalls['publicIpAddress']['ipAddress'],
            gatewalls['privateIpAddress']['ipAddress'],
            len(gatewalls['insideVlans']), gatewalls['status']['keyName']
        ])
    env.fout(table)
    env.fout(table_gatewalls)
Exemple #42
0
def cli(env, identifier, passwords, price):
    """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)

    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', formatting.gb(result['memoryCapacity'])])
    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',
        formatting.FormattedItem(
            result['operatingSystem']['softwareLicense']
            ['softwareDescription']['referenceCode'] or formatting.blank(),
            result['operatingSystem']['softwareLicense']
            ['softwareDescription']['name'] or formatting.blank()
        )])

    table.add_row(
        ['created', result['provisionDate'] or formatting.blank()])

    table.add_row(['owner', formatting.FormattedItem(
        utils.lookup(result, 'billingItem', 'orderItem',
                     'order', 'userRecord',
                     'username') or formatting.blank()
    )])

    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])

    if result.get('notes'):
        table.add_row(['notes', result['notes']])

    if price:
        table.add_row(['price rate',
                       utils.lookup(result,
                                    'billingItem',
                                    'nextInvoiceTotalRecurringAmount')])

    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])

    tag_row = []
    for tag in result['tagReferences']:
        tag_row.append(tag['tag']['name'])

    if tag_row:
        table.add_row(['tags', formatting.listing(tag_row, separator=',')])

    # Test to see if this actually has a primary (public) ip address
    try:
        if not result['privateNetworkOnlyFlag']:
            ptr_domains = (env.client['Hardware_Server']
                           .getReverseDomainRecords(id=hardware_id))

            for ptr_domain in ptr_domains:
                for ptr in ptr_domain['resourceRecords']:
                    table.add_row(['ptr', ptr['data']])
    except SoftLayer.SoftLayerAPIError:
        pass

    return table
Exemple #43
0
    def execute(self, args):
        mgr = SoftLayer.HardwareManager(self.client)

        table = formatting.KeyValueTable(['Name', 'Value'])
        table.align['Name'] = 'r'
        table.align['Value'] = 'l'

        chassis_id = args.get('<chassis_id>')

        found = False
        for chassis in mgr.get_available_dedicated_server_packages():
            if chassis_id == str(chassis[0]):
                found = True
                break

        if not found:
            raise exceptions.CLIAbort('Invalid chassis specified.')

        ds_options = mgr.get_dedicated_server_create_options(chassis_id)

        show_all = True
        for opt_name in self.options:
            if args.get("--" + opt_name):
                show_all = False
                break

        if args['--all']:
            show_all = True

        # Determine if this is a "Bare Metal Instance" or regular server
        bmc = False
        if chassis_id == str(mgr.get_bare_metal_package_id()):
            bmc = True

        if args['--datacenter'] or show_all:
            results = self.get_create_options(ds_options, 'datacenter')[0]

            table.add_row([results[0], formatting.listing(sorted(results[1]))])

        if (args['--cpu'] or show_all) and not bmc:
            results = self.get_create_options(ds_options, 'cpu')

            cpu_table = formatting.Table(['ID', 'Description'])
            cpu_table.align['ID'] = 'r'
            cpu_table.align['Description'] = 'l'

            for result in sorted(results, key=lambda x: x[1]):
                cpu_table.add_row([result[1], result[0]])
            table.add_row(['cpu', cpu_table])

        if (args['--memory'] or show_all) and not bmc:
            results = self.get_create_options(ds_options, 'memory')[0]

            table.add_row([results[0], formatting.listing(
                item[0] for item in sorted(results[1]))])

        if bmc and (show_all or args['--memory'] or args['--cpu']):
            results = self.get_create_options(ds_options, 'server_core')
            memory_cpu_table = formatting.Table(['memory', 'cpu'])
            for result in results:
                memory_cpu_table.add_row([
                    result[0],
                    formatting.listing(
                        [item[0] for item in sorted(
                            result[1], key=lambda x: int(x[0])
                        )])])
            table.add_row(['memory/cpu', memory_cpu_table])

        if args['--os'] or show_all:
            results = self.get_create_options(ds_options, 'os')

            for result in results:
                table.add_row([
                    result[0],
                    formatting.listing(
                        [item[0] for item in sorted(result[1])],
                        separator=os.linesep
                    )])

        if args['--disk'] or show_all:
            results = self.get_create_options(ds_options, 'disk')[0]

            table.add_row([
                results[0],
                formatting.listing(
                    [item[0] for item in sorted(results[1])],
                    separator=os.linesep
                )])

        if args['--nic'] or show_all:
            results = self.get_create_options(ds_options, 'nic')

            for result in results:
                table.add_row([result[0], formatting.listing(
                    item[0] for item in sorted(result[1],))])

        if (args['--controller'] or show_all) and not bmc:
            results = self.get_create_options(ds_options, 'disk_controller')[0]

            table.add_row([results[0], formatting.listing(
                item[0] for item in sorted(results[1],))])

        return table
 def _execute(self, _):
     return formatting.listing(SoftLayer.MetadataManager().get('tags'),
                               separator=',')
    def execute(self, args):
        hardware = SoftLayer.HardwareManager(self.client)

        table = formatting.KeyValueTable(['Name', 'Value'])
        table.align['Name'] = 'r'
        table.align['Value'] = 'l'

        hardware_id = helpers.resolve_id(
            hardware.resolve_ids, args.get('<identifier>'), 'hardware')
        result = hardware.get_hardware(hardware_id)
        result = utils.NestedDict(result)

        table.add_row(['id', result['id']])
        table.add_row(['hostname', 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',
                       formatting.gb(result['memoryCapacity'])])
        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',
            formatting.FormattedItem(
                result['operatingSystem']['softwareLicense']
                ['softwareDescription']['referenceCode'] or formatting.blank(),
                result['operatingSystem']['softwareLicense']
                ['softwareDescription']['name'] or formatting.blank()
            )])
        table.add_row(['created',
                       result['provisionDate'] or formatting.blank()])

        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])

        if result.get('notes'):
            table.add_row(['notes', result['notes']])

        if args.get('--price'):
            table.add_row(['price rate',
                           result['billingItem']['recurringFee']])

        if args.get('--passwords'):
            user_strs = []
            for item in result['operatingSystem']['passwords']:
                user_strs.append(
                    "%s %s" % (item['username'], item['password']))
            table.add_row(['users', formatting.listing(user_strs)])

        tag_row = []
        for tag in result['tagReferences']:
            tag_row.append(tag['tag']['name'])

        if tag_row:
            table.add_row(['tags', formatting.listing(tag_row, separator=',')])

        # Test to see if this actually has a primary (public) ip address
        if result['primaryIpAddress']:
            ptr_domains = (self.client['Hardware_Server']
                           .getReverseDomainRecords(id=hardware_id))

            for ptr_domain in ptr_domains:
                for ptr in ptr_domain['resourceRecords']:
                    table.add_row(['ptr', ptr['data']])

        return table
 def _execute(self, _):
     frontend_macs = SoftLayer.MetadataManager().get('frontend_mac')
     return formatting.listing(frontend_macs, separator=',')
Exemple #47
0
    def execute(self, args):
        mgr = SoftLayer.HardwareManager(self.client)

        table = formatting.KeyValueTable(['Name', 'Value'])
        table.align['Name'] = 'r'
        table.align['Value'] = 'l'

        chassis_id = args.get('<chassis_id>')

        found = False
        for chassis in mgr.get_available_dedicated_server_packages():
            if chassis_id == str(chassis[0]):
                found = True
                break

        if not found:
            raise exceptions.CLIAbort('Invalid chassis specified.')

        ds_options = mgr.get_dedicated_server_create_options(chassis_id)

        show_all = True
        for opt_name in self.options:
            if args.get("--" + opt_name):
                show_all = False
                break

        if args['--all']:
            show_all = True

        # Determine if this is a "Bare Metal Instance" or regular server
        bmc = False
        if chassis_id == str(mgr.get_bare_metal_package_id()):
            bmc = True

        if args['--datacenter'] or show_all:
            results = self.get_create_options(ds_options, 'datacenter')[0]

            table.add_row([results[0], formatting.listing(sorted(results[1]))])

        if (args['--cpu'] or show_all) and not bmc:
            results = self.get_create_options(ds_options, 'cpu')

            cpu_table = formatting.Table(['ID', 'Description'])
            cpu_table.align['ID'] = 'r'
            cpu_table.align['Description'] = 'l'

            for result in sorted(results, key=lambda x: x[1]):
                cpu_table.add_row([result[1], result[0]])
            table.add_row(['cpu', cpu_table])

        if (args['--memory'] or show_all) and not bmc:
            results = self.get_create_options(ds_options, 'memory')[0]

            table.add_row([
                results[0],
                formatting.listing(item[0] for item in sorted(results[1]))
            ])

        if bmc and (show_all or args['--memory'] or args['--cpu']):
            results = self.get_create_options(ds_options, 'server_core')
            memory_cpu_table = formatting.Table(['memory', 'cpu'])
            for result in results:
                memory_cpu_table.add_row([
                    result[0],
                    formatting.listing([
                        item[0]
                        for item in sorted(result[1], key=lambda x: int(x[0]))
                    ])
                ])
            table.add_row(['memory/cpu', memory_cpu_table])

        if args['--os'] or show_all:
            results = self.get_create_options(ds_options, 'os')

            for result in results:
                table.add_row([
                    result[0],
                    formatting.listing([item[0] for item in sorted(result[1])],
                                       separator=os.linesep)
                ])

        if args['--disk'] or show_all:
            results = self.get_create_options(ds_options, 'disk')[0]

            table.add_row([
                results[0],
                formatting.listing([item[0] for item in sorted(results[1])],
                                   separator=os.linesep)
            ])

        if args['--nic'] or show_all:
            results = self.get_create_options(ds_options, 'nic')

            for result in results:
                table.add_row([
                    result[0],
                    formatting.listing(item[0] for item in sorted(result[1], ))
                ])

        if (args['--controller'] or show_all) and not bmc:
            results = self.get_create_options(ds_options, 'disk_controller')[0]

            table.add_row([
                results[0],
                formatting.listing(item[0] for item in sorted(results[1], ))
            ])

        return table
Exemple #48
0
def cli(env, chassis_id):
    """Server order options for a given chassis."""

    mgr = SoftLayer.HardwareManager(env.client)

    table = formatting.KeyValueTable(['Name', 'Value'])
    table.align['Name'] = 'r'
    table.align['Value'] = 'l'

    found = False
    for chassis in mgr.get_available_dedicated_server_packages():
        if chassis_id == str(chassis[0]):
            found = True
            break

    if not found:
        raise exceptions.CLIAbort('Invalid chassis specified.')

    ds_options = mgr.get_dedicated_server_create_options(chassis_id)

    # Determine if this is a "Bare Metal Instance" or regular server
    bmc = False
    if chassis_id == str(mgr.get_bare_metal_package_id()):
        bmc = True

    results = server.get_create_options(ds_options, 'datacenter')[0]
    table.add_row([results[0], formatting.listing(sorted(results[1]))])

    # BMC options
    if bmc:
        # CPU and memory options
        results = server.get_create_options(ds_options, 'server_core')
        memory_cpu_table = formatting.Table(['memory', 'cpu'])
        for result in results:
            memory_cpu_table.add_row([
                result[0],
                formatting.listing(
                    [item[0] for item in sorted(
                        result[1], key=lambda x: int(x[0])
                    )])])
        table.add_row(['memory/cpu', memory_cpu_table])

    # Normal hardware options
    else:
        # CPU options
        results = server.get_create_options(ds_options, 'cpu')
        cpu_table = formatting.Table(['ID', 'Description'])
        cpu_table.align['ID'] = 'r'
        cpu_table.align['Description'] = 'l'

        for result in sorted(results, key=lambda x: x[1]):
            cpu_table.add_row([result[1], result[0]])
        table.add_row(['cpu', cpu_table])

        # Memory options
        results = server.get_create_options(ds_options, 'memory')[0]
        table.add_row([results[0], formatting.listing(
            item[0] for item in sorted(results[1]))])

        # Disk controller options
        results = server.get_create_options(ds_options, 'disk_controller')[0]
        table.add_row([results[0], formatting.listing(
            item[0] for item in sorted(results[1],))])

    # Disk options
    results = server.get_create_options(ds_options, 'disk')[0]
    table.add_row([
        results[0],
        formatting.listing(
            [item[0] for item in sorted(results[1])],
            separator=os.linesep
        )])

    # Operating system options
    results = server.get_create_options(ds_options, 'os')
    for result in results:
        table.add_row([
            result[0],
            formatting.listing(
                [item[0] for item in sorted(result[1])],
                separator=os.linesep
            )])

    # NIC options
    results = server.get_create_options(ds_options, 'nic')
    for result in results:
        table.add_row([result[0], formatting.listing(
            item[0] for item in sorted(result[1],))])

    return table
def cli(env):
    """Virtual server order options."""

    vsi = SoftLayer.VSManager(env.client)
    result = vsi.get_create_options()

    table = formatting.KeyValueTable(['Name', 'Value'])
    table.align['Name'] = 'r'
    table.align['Value'] = 'l'

    # Datacenters
    datacenters = [
        dc['template']['datacenter']['name'] for dc in result['datacenters']
    ]
    table.add_row(
        ['datacenter',
         formatting.listing(datacenters, separator=',')])

    # CPUs
    standard_cpu = [
        x for x in result['processors']
        if not x['template'].get('dedicatedAccountHostOnlyFlag', False)
    ]

    ded_cpu = [
        x for x in result['processors']
        if x['template'].get('dedicatedAccountHostOnlyFlag', False)
    ]

    def add_cpus_row(cpu_options, name):
        """Add CPU rows to the table."""
        cpus = []
        for cpu_option in cpu_options:
            cpus.append(str(cpu_option['template']['startCpus']))

        table.add_row(
            ['cpus (%s)' % name,
             formatting.listing(cpus, separator=',')])

    add_cpus_row(ded_cpu, 'private')
    add_cpus_row(standard_cpu, 'standard')

    # Memory
    memory = [str(m['template']['maxMemory']) for m in result['memory']]
    table.add_row(['memory', formatting.listing(memory, separator=',')])

    # Operating Systems
    op_sys = [
        o['template']['operatingSystemReferenceCode']
        for o in result['operatingSystems']
    ]

    op_sys = sorted(op_sys)
    os_summary = set()

    for operating_system in op_sys:
        os_summary.add(operating_system[0:operating_system.find('_')])

    for summary in sorted(os_summary):
        table.add_row([
            'os (%s)' % summary,
            os.linesep.join(
                sorted([x for x in op_sys if x[0:len(summary)] == summary]))
        ])

    # Disk
    local_disks = [
        x for x in result['blockDevices']
        if x['template'].get('localDiskFlag', False)
    ]

    san_disks = [
        x for x in result['blockDevices']
        if not x['template'].get('localDiskFlag', False)
    ]

    def add_block_rows(disks, name):
        """Add block rows to the table."""
        simple = {}
        for disk in disks:
            block = disk['template']['blockDevices'][0]
            bid = block['device']

            if bid not in simple:
                simple[bid] = []

            simple[bid].append(str(block['diskImage']['capacity']))

        for label in sorted(simple.keys()):
            table.add_row([
                '%s disk(%s)' % (name, label),
                formatting.listing(simple[label], separator=',')
            ])

    add_block_rows(local_disks, 'local')
    add_block_rows(san_disks, 'san')

    # Network
    speeds = []
    for comp in result['networkComponents']:
        speed = comp['template']['networkComponents'][0]['maxSpeed']
        speeds.append(str(speed))

    speeds = sorted(speeds)

    table.add_row(['nic', formatting.listing(speeds, separator=',')])

    env.fout(table)
Exemple #50
0
    def execute(self, args):
        vsi = SoftLayer.VSManager(self.client)
        result = vsi.get_create_options()

        show_all = True
        for opt_name in self.options:
            if args.get("--" + opt_name):
                show_all = False
                break

        if args['--all']:
            show_all = True

        table = formatting.KeyValueTable(['Name', 'Value'])
        table.align['Name'] = 'r'
        table.align['Value'] = 'l'

        if args['--datacenter'] or show_all:
            datacenters = [dc['template']['datacenter']['name']
                           for dc in result['datacenters']]
            table.add_row(['datacenter',
                           formatting.listing(datacenters, separator=',')])

        if args['--cpu'] or show_all:
            standard_cpu = [x for x in result['processors']
                            if not x['template'].get(
                                'dedicatedAccountHostOnlyFlag', False)]

            ded_cpu = [x for x in result['processors']
                       if x['template'].get('dedicatedAccountHostOnlyFlag',
                                            False)]

            def add_cpus_row(cpu_options, name):
                """ Add CPU rows to the table """
                cpus = []
                for cpu_option in cpu_options:
                    cpus.append(str(cpu_option['template']['startCpus']))

                table.add_row(['cpus (%s)' % name,
                               formatting.listing(cpus, separator=',')])

            add_cpus_row(ded_cpu, 'private')
            add_cpus_row(standard_cpu, 'standard')

        if args['--memory'] or show_all:
            memory = [
                str(m['template']['maxMemory']) for m in result['memory']]
            table.add_row(['memory',
                           formatting.listing(memory, separator=',')])

        if args['--os'] or show_all:
            op_sys = [
                o['template']['operatingSystemReferenceCode'] for o in
                result['operatingSystems']]

            op_sys = sorted(op_sys)
            os_summary = set()

            for operating_system in op_sys:
                os_summary.add(operating_system[0:operating_system.find('_')])

            for summary in sorted(os_summary):
                table.add_row([
                    'os (%s)' % summary,
                    os.linesep.join(sorted([x for x in op_sys
                                            if x[0:len(summary)] == summary]))
                ])

        if args['--disk'] or show_all:
            local_disks = [x for x in result['blockDevices']
                           if x['template'].get('localDiskFlag', False)]

            san_disks = [x for x in result['blockDevices']
                         if not x['template'].get('localDiskFlag', False)]

            def add_block_rows(disks, name):
                """ Add block rows to the table """
                simple = {}
                for disk in disks:
                    block = disk['template']['blockDevices'][0]
                    bid = block['device']

                    if bid not in simple:
                        simple[bid] = []

                    simple[bid].append(str(block['diskImage']['capacity']))

                for label in sorted(simple.keys()):
                    table.add_row(['%s disk(%s)' % (name, label),
                                   formatting.listing(simple[label],
                                                      separator=',')])

            add_block_rows(local_disks, 'local')
            add_block_rows(san_disks, 'san')

        if args['--nic'] or show_all:
            speeds = []
            for comp in result['networkComponents']:
                speed = comp['template']['networkComponents'][0]['maxSpeed']
                speeds.append(str(speed))

            speeds = sorted(speeds)

            table.add_row(['nic', formatting.listing(speeds, separator=',')])

        return table
Exemple #51
0
def cli(env, identifier, passwords, price):
    """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)

    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', formatting.gb(result['memoryCapacity'])])
    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',
        formatting.FormattedItem(
            result['operatingSystem']['softwareLicense']['softwareDescription']
            ['referenceCode'] or formatting.blank(), result['operatingSystem']
            ['softwareLicense']['softwareDescription']['name']
            or formatting.blank())
    ])

    table.add_row(['created', result['provisionDate'] or formatting.blank()])

    if utils.lookup(result, 'billingItem') != []:
        table.add_row([
            'owner',
            formatting.FormattedItem(
                utils.lookup(result, 'billingItem', 'orderItem', 'order',
                             'userRecord', 'username') or formatting.blank(), )
        ])
    else:
        table.add_row(['owner', formatting.blank()])

    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])

    if result.get('notes'):
        table.add_row(['notes', result['notes']])

    if price:
        table.add_row([
            'price rate',
            utils.lookup(result, 'billingItem',
                         'nextInvoiceTotalRecurringAmount')
        ])

    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])

    tag_row = []
    for tag_detail in result['tagReferences']:
        tag = utils.lookup(tag_detail, 'tag', 'name')
        if tag is not None:
            tag_row.append(tag)

    if tag_row:
        table.add_row(['tags', formatting.listing(tag_row, separator=',')])

    # Test to see if this actually has a primary (public) ip address
    try:
        if not result['privateNetworkOnlyFlag']:
            ptr_domains = (
                env.client['Hardware_Server'].getReverseDomainRecords(
                    id=hardware_id))

            for ptr_domain in ptr_domains:
                for ptr in ptr_domain['resourceRecords']:
                    table.add_row(['ptr', ptr['data']])
    except SoftLayer.SoftLayerAPIError:
        pass

    env.fout(table)
Exemple #52
0
def cli(env):
    """Virtual server order options."""

    vsi = SoftLayer.VSManager(env.client)
    result = vsi.get_create_options()

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    # Datacenters
    datacenters = [
        dc['template']['datacenter']['name'] for dc in result['datacenters']
    ]
    datacenters = sorted(datacenters)

    table.add_row(
        ['datacenter',
         formatting.listing(datacenters, separator='\n')])

    def _add_flavor_rows(flavor_key, flavor_label, flavor_options):
        flavors = []

        for flavor_option in flavor_options:
            flavor_key_name = utils.lookup(flavor_option, 'flavor', 'keyName')
            if not flavor_key_name.startswith(flavor_key):
                continue

            flavors.append(flavor_key_name)

        if len(flavors) > 0:
            table.add_row([
                'flavors (%s)' % flavor_label,
                formatting.listing(flavors, separator='\n')
            ])

    if result.get('flavors', None):
        _add_flavor_rows('B1', 'balanced', result['flavors'])
        _add_flavor_rows('BL1', 'balanced local - hdd', result['flavors'])
        _add_flavor_rows('BL2', 'balanced local - ssd', result['flavors'])
        _add_flavor_rows('C1', 'compute', result['flavors'])
        _add_flavor_rows('M1', 'memory', result['flavors'])
        _add_flavor_rows('AC', 'GPU', result['flavors'])

    # CPUs
    standard_cpus = [
        int(x['template']['startCpus']) for x in result['processors']
        if not x['template'].get('dedicatedAccountHostOnlyFlag', False)
        and not x['template'].get('dedicatedHost', None)
    ]
    ded_cpus = [
        int(x['template']['startCpus']) for x in result['processors']
        if x['template'].get('dedicatedAccountHostOnlyFlag', False)
    ]
    ded_host_cpus = [
        int(x['template']['startCpus']) for x in result['processors']
        if x['template'].get('dedicatedHost', None)
    ]

    standard_cpus = sorted(standard_cpus)
    table.add_row(
        ['cpus (standard)',
         formatting.listing(standard_cpus, separator=',')])
    ded_cpus = sorted(ded_cpus)
    table.add_row(
        ['cpus (dedicated)',
         formatting.listing(ded_cpus, separator=',')])
    ded_host_cpus = sorted(ded_host_cpus)
    table.add_row([
        'cpus (dedicated host)',
        formatting.listing(ded_host_cpus, separator=',')
    ])

    # Memory
    memory = [
        int(m['template']['maxMemory']) for m in result['memory']
        if not m['itemPrice'].get('dedicatedHostInstanceFlag', False)
    ]
    ded_host_memory = [
        int(m['template']['maxMemory']) for m in result['memory']
        if m['itemPrice'].get('dedicatedHostInstanceFlag', False)
    ]

    memory = sorted(memory)
    table.add_row(['memory', formatting.listing(memory, separator=',')])

    ded_host_memory = sorted(ded_host_memory)
    table.add_row([
        'memory (dedicated host)',
        formatting.listing(ded_host_memory, separator=',')
    ])

    # Operating Systems
    op_sys = [
        o['template']['operatingSystemReferenceCode']
        for o in result['operatingSystems']
    ]

    op_sys = sorted(op_sys)
    os_summary = set()

    for operating_system in op_sys:
        os_summary.add(operating_system[0:operating_system.find('_')])

    for summary in sorted(os_summary):
        table.add_row([
            'os (%s)' % summary,
            os.linesep.join(
                sorted([x for x in op_sys if x[0:len(summary)] == summary]))
        ])

    # Disk
    local_disks = [
        x for x in result['blockDevices']
        if x['template'].get('localDiskFlag', False)
        and not x['itemPrice'].get('dedicatedHostInstanceFlag', False)
    ]

    ded_host_local_disks = [
        x for x in result['blockDevices']
        if x['template'].get('localDiskFlag', False)
        and x['itemPrice'].get('dedicatedHostInstanceFlag', False)
    ]

    san_disks = [
        x for x in result['blockDevices']
        if not x['template'].get('localDiskFlag', False)
    ]

    def add_block_rows(disks, name):
        """Add block rows to the table."""
        simple = {}
        for disk in disks:
            block = disk['template']['blockDevices'][0]
            bid = block['device']

            if bid not in simple:
                simple[bid] = []

            simple[bid].append(str(block['diskImage']['capacity']))

        for label in sorted(simple):
            table.add_row([
                '%s disk(%s)' % (name, label),
                formatting.listing(simple[label], separator=',')
            ])

    add_block_rows(san_disks, 'san')
    add_block_rows(local_disks, 'local')
    add_block_rows(ded_host_local_disks, 'local (dedicated host)')

    # Network
    speeds = []
    ded_host_speeds = []
    for option in result['networkComponents']:
        template = option.get('template', None)
        price = option.get('itemPrice', None)

        if not template or not price \
                or not template.get('networkComponents', None):
            continue

        if not template['networkComponents'][0] \
                or not template['networkComponents'][0].get('maxSpeed', None):
            continue

        max_speed = str(template['networkComponents'][0]['maxSpeed'])
        if price.get('dedicatedHostInstanceFlag', False) \
                and max_speed not in ded_host_speeds:
            ded_host_speeds.append(max_speed)
        elif max_speed not in speeds:
            speeds.append(max_speed)

    speeds = sorted(speeds)
    table.add_row(['nic', formatting.listing(speeds, separator=',')])

    ded_host_speeds = sorted(ded_host_speeds)
    table.add_row([
        'nic (dedicated host)',
        formatting.listing(ded_host_speeds, separator=',')
    ])

    env.fout(table)
def cli(env):
    """Virtual server order options."""

    vsi = SoftLayer.VSManager(env.client)
    result = vsi.get_create_options()

    table = formatting.KeyValueTable(['Name', 'Value'])
    table.align['Name'] = 'r'
    table.align['Value'] = 'l'

    # Datacenters
    datacenters = [dc['template']['datacenter']['name']
                   for dc in result['datacenters']]
    table.add_row(['datacenter',
                   formatting.listing(datacenters, separator=',')])

    # CPUs
    standard_cpu = [x for x in result['processors']
                    if not x['template'].get(
                        'dedicatedAccountHostOnlyFlag', False)]

    ded_cpu = [x for x in result['processors']
               if x['template'].get('dedicatedAccountHostOnlyFlag',
                                    False)]

    def add_cpus_row(cpu_options, name):
        """Add CPU rows to the table."""
        cpus = []
        for cpu_option in cpu_options:
            cpus.append(str(cpu_option['template']['startCpus']))

        table.add_row(['cpus (%s)' % name,
                       formatting.listing(cpus, separator=',')])

    add_cpus_row(ded_cpu, 'private')
    add_cpus_row(standard_cpu, 'standard')

    # Memory
    memory = [str(m['template']['maxMemory']) for m in result['memory']]
    table.add_row(['memory',
                   formatting.listing(memory, separator=',')])

    # Operating Systems
    op_sys = [o['template']['operatingSystemReferenceCode'] for o in
              result['operatingSystems']]

    op_sys = sorted(op_sys)
    os_summary = set()

    for operating_system in op_sys:
        os_summary.add(operating_system[0:operating_system.find('_')])

    for summary in sorted(os_summary):
        table.add_row([
            'os (%s)' % summary,
            os.linesep.join(sorted([x for x in op_sys
                                    if x[0:len(summary)] == summary]))
        ])

    # Disk
    local_disks = [x for x in result['blockDevices']
                   if x['template'].get('localDiskFlag', False)]

    san_disks = [x for x in result['blockDevices']
                 if not x['template'].get('localDiskFlag', False)]

    def add_block_rows(disks, name):
        """Add block rows to the table."""
        simple = {}
        for disk in disks:
            block = disk['template']['blockDevices'][0]
            bid = block['device']

            if bid not in simple:
                simple[bid] = []

            simple[bid].append(str(block['diskImage']['capacity']))

        for label in sorted(simple.keys()):
            table.add_row(['%s disk(%s)' % (name, label),
                           formatting.listing(simple[label],
                                              separator=',')])

    add_block_rows(local_disks, 'local')
    add_block_rows(san_disks, 'san')

    # Network
    speeds = []
    for comp in result['networkComponents']:
        speed = comp['template']['networkComponents'][0]['maxSpeed']
        speeds.append(str(speed))

    speeds = sorted(speeds)

    table.add_row(['nic', formatting.listing(speeds, separator=',')])

    env.fout(table)