Ejemplo n.º 1
0
def _display_oci_volume_list(volumes, output_mode, details, truncate):
    """
    display information about list of block volume
    argument:
        volumes : list of OCIVOlume
        output_mode : output_mode
        details : display details information ?
        truncate : truncate text ?
    """
    def _get_displayable_size(_, volume):
        return volume.get_size(format_str=OCI_VOLUME_SIZE_FMT.HUMAN.name)

    def _get_attached_instance_name(_, volume):
        global _this_instance_ocid
        if not volume.is_attached():
            return '-'
        _vol_instance_attach_to = volume.get_instance()
        if _vol_instance_attach_to.get_ocid() == _this_instance_ocid:
            return "this instance"
        else:
            pip = _vol_instance_attach_to.get_public_ip()
            if pip:
                return "%s (%s)" % (_vol_instance_attach_to.get_display_name(),
                                    _vol_instance_attach_to.get_public_ip())
            return _vol_instance_attach_to.get_display_name()
        return '-'

    def _get_comp_name(_, volume):
        """ keep track of compartment per ID as it may be expensive info to fetch """
        _map = getattr(_get_comp_name, 'c_id_to_name', {})
        if volume.get_compartment_id() not in _map:
            _map[volume.get_compartment_id()] = volume.get_compartment(
            ).get_display_name()
        setattr(_get_comp_name, 'c_id_to_name', _map)
        return _map[volume.get_compartment_id()]

    _title = 'Block volumes information'
    _columns = [['Name', 32, 'get_display_name'],
                ['Size', 6, _get_displayable_size],
                ['Attached to', 32, _get_attached_instance_name],
                ['OCID', 32, 'get_ocid']]
    if details:
        _columns.extend(
            (['IQN', 14, 'get_iqn'], ['Compartement', 14, _get_comp_name],
             ['Availability domain', 19, 'get_availability_domain_name']))
    if output_mode == 'compat':
        printerKlass = get_row_printer_impl('text')
    else:
        printerKlass = get_row_printer_impl(output_mode)

    printer = printerKlass(title=_title,
                           columns=_columns,
                           text_truncate=truncate)
    printer.printHeader()
    for vol in volumes:
        printer.printRow(vol)
        printer.rowBreak()
    printer.printFooter()
    printer.finish()
Ejemplo n.º 2
0
def do_show_vnics_information(vnics, mode, details=False):
    """
    Show given vNIC information
    parameter
    ---------
        vnics : OCIVNIC instances
        mode : the output mode as str (text,json,parsable)
        details : display detailed information ?
    """
    def _display_secondary_ip_subnet(_, privip):
        _sn = privip.get_subnet()
        return '%s (%s)' % (_sn.get_display_name(), _sn.get_cidr_block())

    _title = 'VNIs Information'
    _columns = [['Name', 32, 'get_display_name']]
    _columns.append(['Private IP', 15, 'get_private_ip'])
    _columns.append(['OCID', 90, 'get_ocid'])
    _columns.append(['MAC', 17, 'get_mac_address'])
    printerKlass = get_row_printer_impl(mode)
    if details:
        printerKlass = get_row_printer_impl('text')
        _columns.append(['Primary', 7, 'is_primary'])
        _columns.append(['Subnet', 25, 'get_subnet'])
        _columns.append(['NIC', 3, 'get_nic_index'])
        _columns.append(['Public IP', 15, 'get_public_ip'])
        _columns.append(
            ['Availability domain', 20, 'get_availability_domain_name'])

        ips_printer = TextPrinter(
            title='Private IP addresses:',
            columns=(['IP address', 15,
                      'get_address'], ['OCID', '90', 'get_ocid'
                                       ], ['Hostname', 25, 'get_hostname'],
                     ['Subnet', 24, _display_secondary_ip_subnet]),
            printer=IndentPrinter(3))

    printer = printerKlass(title=_title, columns=_columns)
    printer.printHeader()
    for vnic in vnics:
        print()
        printer.printRow(vnic)
        if details:
            private_ips = vnic.all_private_ips()
            if len(private_ips) > 1:
                # private_ips include the primary we won't print (>1)
                ips_printer.printHeader()
                for p_ip in private_ips:
                    if not p_ip.is_primary():
                        # primary already displayed
                        ips_printer.printRow(p_ip)
                        print()
            ips_printer.printFooter()
            ips_printer.finish()
    printer.printFooter()
    printer.finish()
Ejemplo n.º 3
0
def display_detached_iscsi_device(iqn, targets, attach_failed=()):
    """
    Display the iSCSI devices

    Parameters
    ----------
    iqn: str
        The iSCSI qualified name.
    targets: dict
        The targets.
    attach_failed: dict
        The devices for which attachment failed.
    """
    devicePrinter = get_row_printer_impl('table')(title="Target %s" % iqn,
                                                  text_truncate=False,
                                                  columns=(['Portal', 12, 'portal'], ['State', 12, 'state']))
    devicePrinter.printHeader()
    _item = {}
    for ipaddr in list(targets.keys()):
        _item['portal'] = "%s:3260" % ipaddr
        if iqn in attach_failed:
            _item['state'] = iscsiadm.error_message_from_code(attach_failed[iqn])
        else:
            _item['state'] = "Detached"
        devicePrinter.printRow(_item)
        devicePrinter.rowBreak()
    devicePrinter.printFooter()
    devicePrinter.finish()
Ejemplo n.º 4
0
def _display_ip_list(ip_list, displayALL, outputMode, displayDetails):
    """
    Receive a list of IPs and display them
    arguments:
      ip_list : list of IPs as string
      displayALL : display all or only the one on the primary vNIC
      outputMode : output mode (table, text, etc..)
      displayDetails : display detailed information ?
    """

    if displayALL:
        _ip_list_to_display = ip_list
    else:
        #we assume that primary is the first one and we want ot display only it
        _ip_list_to_display = ip_list[:1]

    _title = 'Public IPs information (primary on top)'
    _columns = [['IP Address', 15, 'ip']]
    if displayDetails:
        _columns.append(['vNIC name', 15, 'vnic_name'])
        _columns.append(['vNIC OCID', 90, 'vnic_ocid'])

    printerKlass = get_row_printer_impl(outputMode)

    _printer = printerKlass(title=_title, columns=_columns)
    _printer.printHeader()
    for _ip in ip_list:
        _printer.printRow(_ip)
    _printer.printFooter()
    _printer.finish()
    return 0
Ejemplo n.º 5
0
def display_attached_volumes(oci_sess, iscsiadm_session, disks, output_mode, details, truncate):
    """
    Display the attched iSCSI devices.

    Parameters
    ----------
    oci_sess: OCISession
        An OCI session
    iscsiadm_session: dict
        An iscsiadm session (as returned by oci_utils.iscsiadm.session())
    disks: dict
        List of disk to be displayed. Information about disks in the system,
        as returned by lsblk.list()
    output_mode : the output mode as str (text,json,parsable)
    details : display detailed information ?

    Returns
    -------
       No return value.
    """
    oci_vols = []
    try:
        oci_vols = sorted(oci_sess.this_instance().all_volumes())
    except Exception as e:
        oci_vols = []
        _logger.debug('Cannot get all volumes of this instance : %s', str(e))

    if not iscsiadm_session and len(oci_vols) > 0:
        print("Local iSCSI info not available. ")
        print("List info from Cloud instead(No boot volume).")
        print("")
        _display_oci_volume_list(oci_vols, output_mode, details, truncate)

    _columns = []
    if details:
        _columns.append(['Target', 32, 'target'])
    _columns.append(['Volume name', 32, 'name'])
    if details:
        _columns.append(['Volume OCID', 32, 'ocid'])
        _columns.append(['Persistent portal', 20, 'p_portal'])
        _columns.append(['Current portal', 20, 'c_portal'])
        _columns.append(['Session State', 13, 's_state'])
    _columns.append(['Attached device', 15, 'dev'])
    _columns.append(['Size', 6, 'size'])

    # this is only used in compatibility mode i.e using 'text'
    partitionPrinter = get_row_printer_impl('text')(title='Partitions',
                                                    columns=(['Device', 8, 'dev_name'], ['Size', 6, 'size'],
                                                             ['Filesystem', 12, 'fstype'], ['Mountpoint', 12, 'mountpoint']))
    _items = []
    for iqn in list(iscsiadm_session.keys()):
        _item = {}
        oci_vol = get_volume_by_iqn(oci_sess, iqn)
        _item['target'] = iqn
        if oci_vol is not None:
            _item['name'] = oci_vol.get_display_name()
            _item['ocid'] = oci_vol.get_ocid()
        _item['p_portal'] = "%s:%s" % (iscsiadm_session[iqn]['persistent_portal_ip'],
                                       iscsiadm_session[iqn]['persistent_portal_port'])
        _item['c_portal'] = "%s:%s" % (iscsiadm_session[iqn]['current_portal_ip'],
                                       iscsiadm_session[iqn]['current_portal_port'])
        _item['s_state'] = iscsiadm_session[iqn].get('session_state', 'n/a')
        device = iscsiadm_session[iqn].get('device', None)
        if device is None:
            _item['dev'] = '(not attached)'
        else:
            _item['dev'] = device
            if device in disks:
                _item['size'] = disks[device]['size']

        _items.append(_item)

    if output_mode == 'compat':
        iscsi_dev_printer = get_row_printer_impl('text')(
            title='Currently attached iSCSI devices', columns=_columns, text_truncate=truncate)
    else:
        iscsi_dev_printer = get_row_printer_impl(output_mode)(
            title='Currently attached iSCSI devices', columns=_columns, text_truncate=truncate)
    iscsi_dev_printer.printHeader()
    for _item in _items:
        iscsi_dev_printer.printRow(_item)
        if output_mode == 'compat':
            if 'partitions' not in disks[_item['dev']]:
                iscsi_dev_printer.printKeyValue('File system type', disks[_item['dev']]['fstype'])
                iscsi_dev_printer.printKeyValue('Mountpoint', disks[_item['dev']]['mountpoint'])
            else:
                partitions = disks[device]['partitions']
                partitionPrinter.printHeader()
                for part in sorted(list(partitions.keys())):
                    # add it as we need it during the print
                    partitions[part]['dev_name'] = part
                    partitionPrinter.printRow(partitions[part])
                    partitionPrinter.rowBreak()
                partitionPrinter.printFooter()
                partitionPrinter.finish()
        iscsi_dev_printer.rowBreak()
    iscsi_dev_printer.printFooter()
    iscsi_dev_printer.finish()
Ejemplo n.º 6
0
def do_show_information (vnic_utils, mode, details=False):
    """
    Display network information
    parameter
    ---------
        vnic_utils : instance ov VNICUtil
        mode : output mode (text,parsable etc...)
        details : display detailed information ?
    """

    sess = get_oci_api_session()
    if sess is None:
        raise Exception("Failed to get API session.")



    vnics = sess.this_instance().all_vnics()
    network_config = vnic_utils.get_network_config()

    def _display_subnet(_, interface):
        """ return network subnet. if interface match a vnic return OCI vnic subnet """
        if interface['VNIC']:
            vnic = [v for v in vnics if v.get_ocid() == interface['VNIC']][0]
            return '%s/%s (%s)' % (interface['SPREFIX'],interface['SBITS'],vnic.get_subnet().get_display_name())
        return '%s/%s' % (interface['SPREFIX'],interface['SBITS'])

    def _get_vnic_name(_, interface):
        """ if interface match a vnic return its display name """
        if interface['VNIC']:
            vnic = [v for v in vnics if v.get_ocid() == interface['VNIC']][0]
            return vnic.get_display_name()

    def _get_hostname(_, interface):
        """ if interface match a vnic return its hostname """
        if interface['VNIC']:
            vnic = [v for v in vnics if v.get_ocid() == interface['VNIC']][0]
            return vnic.get_hostname()

    _columns = []
    _columns.append(['State',6,'CONFSTATE'])
    _columns.append(['Link',15,'IFACE'])
    _columns.append(['Status',6,'STATE'])
    _columns.append(['Ip address',15,'ADDR'])
    _columns.append(['VNIC',30,_get_vnic_name])
    _columns.append(['MAC',17,'MAC'])
    if details:
        _columns.append(['Hostname',25,_get_hostname])
        _columns.append(['Subnet',32,_display_subnet])
        _columns.append(['Router IP',15,'VIRTRT'])
        _columns.append(['Namespace',10,'NS'])
        _columns.append(['Index',5,'IND'])
        _columns.append(['VLAN tag',8,'VLTAG'])
        _columns.append(['VLAN',11,'VLAN'])

    printerKlass = get_row_printer_impl(mode)
    printer = printerKlass(title='Network configuration', columns=_columns)

    printer.printHeader()
    for item in network_config:
        printer.printRow(item)
    printer.printFooter()
    printer.finish()
Ejemplo n.º 7
0
def _list_pool_vm(args):
    """
    List the filesystem pools.

    Parameters
    ----------
        args : namespace
            The parsed command line.
    Returns
    -------
        No return value.
    """
    _logger.debug('_list_pool_vm')

    pool_states = [
        'inactive', 'initializing', 'running', 'degraded', 'inaccessible'
    ]
    yes_no = ['no', 'yes']

    conn = libvirt.open(None)
    try:
        _sps = list()
        if conn:
            _sps = conn.listAllStoragePools()
        else:
            _logger.error('Failed to contact hypervisor')
            raise ValueError('Failed to contact hypervisor.')
    except Exception as e:
        _logger.error('Failed to collect vm pool data: %s', str(e))
        raise ValueError('Failed to collect vm pool data.') from e
    finally:
        conn.close()

    if len(_sps) == 0:
        _logger.info('No filesystem pools found.')
        return

    _collen = {
        'name': 4,
        'uuid': 4,
        'autostart': 9,
        'active': 6,
        'persistent': 10,
        'volumes': 7,
        'state': 5,
        'capacity': 8,
        'allocation': 10,
        'available': 9
    }
    #
    # format data and determine optimal lenght of fields.
    pool_data = list()
    for _sp in _sps:
        _sp_info = _sp.info()
        _sp_data = dict()
        # name
        _sp_name_len = len(_sp.name())
        _collen['name'] = _sp_name_len if _sp_name_len > _collen[
            'name'] else _collen['name']
        _sp_data['name'] = _sp.name()
        # uuid
        _sp_uuid_len = len(_sp.UUIDString())
        _collen['uuid'] = _sp_uuid_len if _sp_uuid_len > _collen[
            'uuid'] else _collen['uuid']
        _sp_data['uuid'] = _sp.UUIDString()
        # autostart
        _sp_data['autostart'] = yes_no[_sp.autostart()]
        # active
        _sp_data['active'] = yes_no[_sp.isActive()]
        # persistent
        _sp_data['persistent'] = yes_no[_sp.isPersistent()]
        # number of volumes
        _sp_data['volumes'] = _sp.numOfVolumes()
        # total capacity
        _sp_data['capacity'] = _format_size(int(_sp_info[1]))
        _sp_cap_len = len(_sp_data['capacity'])
        _collen['capacity'] = _sp_cap_len if _sp_cap_len > _collen[
            'capacity'] else _collen['capacity']
        # state
        _sp_data['state'] = pool_states[_sp_info[0]]
        _sp_state_len = len(_sp_data['state'])
        _collen['state'] = _sp_state_len if _sp_state_len > _collen[
            'state'] else _collen['state']
        # allocated space
        _sp_data['allocation'] = _format_size(int(_sp_info[2]))
        _sp_alloc_len = len(_sp_data['allocation'])
        _collen['allocation'] = _sp_alloc_len if _sp_alloc_len > _collen[
            'allocation'] else _collen['allocation']
        # available space
        _sp_data['available'] = _format_size(int(_sp_info[3]))
        _sp_avail_len = len(_sp_data['available'])
        _collen['available'] = _sp_avail_len if _sp_avail_len > _collen[
            'available'] else _collen['available']

        pool_data.append(_sp_data)

    _title = 'VM pool Information'
    _columns = list()
    _columns.append(['Name', _collen['name'] + 2, 'name'])
    _columns.append(['UUID', _collen['uuid'] + 2, 'uuid'])
    _columns.append(['Autostart', _collen['autostart'] + 2, 'autostart'])
    _columns.append(['Active', _collen['active'] + 2, 'active'])
    _columns.append(['Persistent', _collen['persistent'] + 2, 'persistent'])
    _columns.append(['Volumes', _collen['volumes'] + 2, 'volumes'])
    _columns.append(['State', _collen['state'] + 2, 'state'])
    _columns.append(['Capacity', _collen['capacity'] + 2, 'capacity'])
    _columns.append(['Allocation', _collen['allocation'] + 2, 'allocation'])
    _columns.append(['Available', _collen['available'] + 2, 'available'])

    printerKlass = get_row_printer_impl(args.output_mode)
    printer = printerKlass(title=_title, columns=_columns)
    printer.printHeader()

    for _sp in pool_data:
        printer.rowBreak()
        printer.printRow(_sp)
    printer.printFooter()
    printer.finish()
    return