def test_bytes_to_human_illegal_size(input_data):
    """Test of bytes_to_human function, illegal objects are passed as a size."""
    e_regexp = (r'(no ordering relation is defined for complex numbers)|'
                r'(unsupported operand type\(s\) for /)|(unorderable types)|'
                r'(not supported between instances of)')
    with pytest.raises(TypeError, match=e_regexp):
        bytes_to_human(input_data)
Beispiel #2
0
def human_readable(size, isbits=False, unit=None):
    ''' Return a human readable string '''
    try:
        return formatters.bytes_to_human(size, isbits, unit)
    except TypeError as e:
        raise AssibleFilterTypeError(
            "human_readable() failed on bad input: %s" % to_native(e))
    except Exception:
        raise AssibleFilterError(
            "human_readable() can't interpret following string: %s" % size)
Beispiel #3
0
    def get_device_facts(self):
        # Device facts are derived for sdderr kstats. This code does not use the
        # full output, but rather queries for specific stats.
        # Example output:
        # sderr:0:sd0,err:Hard Errors     0
        # sderr:0:sd0,err:Illegal Request 6
        # sderr:0:sd0,err:Media Error     0
        # sderr:0:sd0,err:Predictive Failure Analysis     0
        # sderr:0:sd0,err:Product VBOX HARDDISK   9
        # sderr:0:sd0,err:Revision        1.0
        # sderr:0:sd0,err:Serial No       VB0ad2ec4d-074a
        # sderr:0:sd0,err:Size    53687091200
        # sderr:0:sd0,err:Soft Errors     0
        # sderr:0:sd0,err:Transport Errors        0
        # sderr:0:sd0,err:Vendor  ATA

        device_facts = {}
        device_facts['devices'] = {}

        disk_stats = {
            'Product': 'product',
            'Revision': 'revision',
            'Serial No': 'serial',
            'Size': 'size',
            'Vendor': 'vendor',
            'Hard Errors': 'hard_errors',
            'Soft Errors': 'soft_errors',
            'Transport Errors': 'transport_errors',
            'Media Error': 'media_errors',
            'Predictive Failure Analysis': 'predictive_failure_analysis',
            'Illegal Request': 'illegal_request',
        }

        cmd = ['/usr/bin/kstat', '-p']

        for ds in disk_stats:
            cmd.append('sderr:::%s' % ds)

        d = {}
        rc, out, err = self.module.run_command(cmd)
        if rc != 0:
            return device_facts

        sd_instances = frozenset(
            line.split(':')[1] for line in out.split('\n')
            if line.startswith('sderr'))
        for instance in sd_instances:
            lines = (line for line in out.split('\n')
                     if ':' in line and line.split(':')[1] == instance)
            for line in lines:
                text, value = line.split('\t')
                stat = text.split(':')[3]

                if stat == 'Size':
                    d[disk_stats.get(stat)] = bytes_to_human(float(value))
                else:
                    d[disk_stats.get(stat)] = value.rstrip()

            diskname = 'sd' + instance
            device_facts['devices'][diskname] = d
            d = {}

        return device_facts
def test_bytes_to_human_unit_isbits(input_data, unit, expected):
    """Test unit argument of bytes_to_human function with isbits=True proper results."""
    assert bytes_to_human(input_data, isbits=True, unit=unit) == expected
def test_bytes_to_human_unit(input_data, unit, expected):
    """Test unit argument of bytes_to_human function proper results."""
    assert bytes_to_human(input_data, unit=unit) == expected
def test_bytes_to_human_isbits(input_data, expected):
    """Test of bytes_to_human function with isbits=True proper results."""
    assert bytes_to_human(input_data, isbits=True) == expected
def test_bytes_to_human(input_data, expected):
    """Test of bytes_to_human function, only proper numbers are passed."""
    assert bytes_to_human(input_data) == expected
Beispiel #8
0
    def get_device_facts(self):
        device_facts = {}

        device_facts['devices'] = {}
        lspci = self.module.get_bin_path('lspci')
        if lspci:
            rc, pcidata, err = self.module.run_command(
                [lspci, '-D'], errors='surrogate_then_replace')
        else:
            pcidata = None

        try:
            block_devs = os.listdir("/sys/block")
        except OSError:
            return device_facts

        devs_wwn = {}
        try:
            devs_by_id = os.listdir("/dev/disk/by-id")
        except OSError:
            pass
        else:
            for link_name in devs_by_id:
                if link_name.startswith("wwn-"):
                    try:
                        wwn_link = os.readlink(
                            os.path.join("/dev/disk/by-id", link_name))
                    except OSError:
                        continue
                    devs_wwn[os.path.basename(wwn_link)] = link_name[4:]

        links = self.get_all_device_links()
        device_facts['device_links'] = links

        for block in block_devs:
            virtual = 1
            sysfs_no_links = 0
            try:
                path = os.readlink(os.path.join("/sys/block/", block))
            except OSError:
                e = sys.exc_info()[1]
                if e.errno == errno.EINVAL:
                    path = block
                    sysfs_no_links = 1
                else:
                    continue
            sysdir = os.path.join("/sys/block", path)
            if sysfs_no_links == 1:
                for folder in os.listdir(sysdir):
                    if "device" in folder:
                        virtual = 0
                        break
            d = {}
            d['virtual'] = virtual
            d['links'] = {}
            for (link_type, link_values) in iteritems(links):
                d['links'][link_type] = link_values.get(block, [])
            diskname = os.path.basename(sysdir)
            for key in ['vendor', 'model', 'sas_address', 'sas_device_handle']:
                d[key] = get_file_content(sysdir + "/device/" + key)

            sg_inq = self.module.get_bin_path('sg_inq')

            # we can get NVMe device's serial number from /sys/block/<name>/device/serial
            serial_path = "/sys/block/%s/device/serial" % (block)

            if sg_inq:
                device = "/dev/%s" % (block)
                rc, drivedata, err = self.module.run_command([sg_inq, device])
                if rc == 0:
                    serial = re.search(r"Unit serial number:\s+(\w+)",
                                       drivedata)
                    if serial:
                        d['serial'] = serial.group(1)
            else:
                serial = get_file_content(serial_path)
                if serial:
                    d['serial'] = serial

            for key, test in [
                ('removable', '/removable'),
                ('support_discard', '/queue/discard_granularity'),
            ]:
                d[key] = get_file_content(sysdir + test)

            if diskname in devs_wwn:
                d['wwn'] = devs_wwn[diskname]

            d['partitions'] = {}
            for folder in os.listdir(sysdir):
                m = re.search("(" + diskname + r"[p]?\d+)", folder)
                if m:
                    part = {}
                    partname = m.group(1)
                    part_sysdir = sysdir + "/" + partname

                    part['links'] = {}
                    for (link_type, link_values) in iteritems(links):
                        part['links'][link_type] = link_values.get(
                            partname, [])

                    part['start'] = get_file_content(part_sysdir + "/start", 0)
                    part['sectors'] = get_file_content(part_sysdir + "/size",
                                                       0)

                    part['sectorsize'] = get_file_content(
                        part_sysdir + "/queue/logical_block_size")
                    if not part['sectorsize']:
                        part['sectorsize'] = get_file_content(
                            part_sysdir + "/queue/hw_sector_size", 512)
                    part['size'] = bytes_to_human(
                        (float(part['sectors']) * 512.0))
                    part['uuid'] = get_partition_uuid(partname)
                    self.get_holders(part, part_sysdir)

                    d['partitions'][partname] = part

            d['rotational'] = get_file_content(sysdir + "/queue/rotational")
            d['scheduler_mode'] = ""
            scheduler = get_file_content(sysdir + "/queue/scheduler")
            if scheduler is not None:
                m = re.match(r".*?(\[(.*)\])", scheduler)
                if m:
                    d['scheduler_mode'] = m.group(2)

            d['sectors'] = get_file_content(sysdir + "/size")
            if not d['sectors']:
                d['sectors'] = 0
            d['sectorsize'] = get_file_content(sysdir +
                                               "/queue/logical_block_size")
            if not d['sectorsize']:
                d['sectorsize'] = get_file_content(
                    sysdir + "/queue/hw_sector_size", 512)
            d['size'] = bytes_to_human(float(d['sectors']) * 512.0)

            d['host'] = ""

            # domains are numbered (0 to ffff), bus (0 to ff), slot (0 to 1f), and function (0 to 7).
            m = re.match(r".+/([a-f0-9]{4}:[a-f0-9]{2}:[0|1][a-f0-9]\.[0-7])/",
                         sysdir)
            if m and pcidata:
                pciid = m.group(1)
                did = re.escape(pciid)
                m = re.search("^" + did + r"\s(.*)$", pcidata, re.MULTILINE)
                if m:
                    d['host'] = m.group(1)

            self.get_holders(d, sysdir)

            device_facts['devices'][diskname] = d

        return device_facts