Esempio n. 1
0
    def test_normalize_ascii(self):
        """
        normalize_ascii() should only return a string containing ascii characters with decimal
        codes between 1 and 127. All other codes are translated to space.
        """
        string = ''
        for i in range(1, 256):
            string += chr(i)

        self.assertEqual(len(string), 255)

        string = normalize_ascii(string)

        self.assertEqual(len(string), 255)

        for char in string:
            self.assertTrue(ord(char) > 0)
            self.assertTrue(ord(char) < 127)
Esempio n. 2
0
    def write_ansible_local(db_machine, ansible_machine):
        """
        Write ansible information retrieved from a json file to the system.
        For developing/debugging this interface can directly be use
        (without doing a rescan of the remote machine) via e.g.
        manage runscript store_machine_info --script-args lammermuir.arch.suse.de
        This can be useful if one wants to assign data which was already via ansible
        to the correct database fields here.
        """

        db_machine.fqdn = ansible_machine.get("fqdn", "")
        db_machine.cpu_physical = ansible_machine.get("processor_count", 0)
        db_machine.cpu_cores = ansible_machine.get("processor_cores", 0)
        db_machine.cpu_threads = ansible_machine.get("processor_threads_per_core", 0)
        # db_machine.cpu_model =
        # db_machine.cpu_flags = # --> check if in ansible, else create facts file
        # db_machine.cpu_speed =
        # db_machine.cpu_id =
        db_machine.ram_amount = int(ansible_machine.get("memtotal_mb", 0)) * 1024
        # db_machine.disk_primary_size = # sectors * sector_size der 1. platte (in bytes). danach hwinfo --disk entfernen.
        # db_machine.disk_type =

        db_machine.lsmod = normalize_ascii("".join(ansible_machine.get("ansible_local", {}).get("lsmod", {}).get("noargs", {}).get("stdout", "")))
        db_machine.lspci = normalize_ascii("".join(ansible_machine.get("lspci", {}).get("-vvv -nn", {}).get("stdout", "")))
        last = ansible_machine.get("ansible_local", {}).get("last", {}).get("latest", {}).get("stdout", "")
        db_machine.last = last[0:8] + last[38:49] if len(last) > 49 else ""
        db_machine.hwinfo = normalize_ascii("".join(ansible_machine.get("ansible_local", {}).get("hwinfo", {}).get("full", {}).get("stdout", "")))
        db_machine.dmidecode = normalize_ascii("".join(ansible_machine.get("ansible_local", {}).get("dmidecode", {}).get("noargs", {}).get("stdout", "")))
        db_machine.dmesg = normalize_ascii("".join(ansible_machine.get("ansible_local", {}).get("dmesg", {}).get("-xl", {}).get("stdout", "")))
        db_machine.lsscsi = normalize_ascii("".join(ansible_machine.get("ansible_local", {}).get("lsscsi", {}).get("-s", {}).get("stdout", "")))
        db_machine.lsusb = normalize_ascii("".join(ansible_machine.get("ansible_local", {}).get("lsusb", {}).get("noargs", {}).get("stdout", "")))
        db_machine.ipmi = "IPMI" in db_machine.dmidecode

        try:
            bios_date = ansible_machine.get("bios_date", None)
            if bios_date == "NA":
                bios_date = None
            if bios_date:
                # Django date fields must be in "%Y-%m-%d" format
                db_machine.bios_date = datetime.strptime(bios_date, "%m/%d/%Y").strftime("%Y-%m-%d")
        except (ValueError, TypeError):
            logger.exception("Could not parse bios date [%s]", db_machine.fqdn)

        db_machine.bios_version = ansible_machine.get("bios_version", "")
Esempio n. 3
0
def get_hardware_information(fqdn):
    """Retrieve information of the system."""
    try:
        machine = Machine.objects.get(fqdn=fqdn)
    except Machine.DoesNotExist:
        logger.warning("Machine '{}' does not exist".format(fqdn))
        return

    # set needed values for several checks from original machine
    machine_ = Machine(
        architecture=machine.architecture
    )

    conn = None
    timer = None
    try:
        conn = SSH(fqdn)
        conn.connect()
        timer = threading.Timer(5 * 60, conn.close)
        timer.start()

        # CPUs
        logger.debug("Get CPU number...")
        output, stderr, exitstatus = conn.execute_script_remote('machine_get_cpu_number.sh')
        if output:
            for line in output:
                if line.startswith('SOCKETS'):
                    machine_.cpu_physical = int(line.split('=')[1])
                elif line.startswith('CORES'):
                    machine_.cpu_cores = int(line.split('=')[1])
                elif line.startswith('THREADS'):
                    machine_.cpu_threads = int(line.split('=')[1])

        logger.debug("Get CPU type...")
        output, stderr, exitstatus = conn.execute_script_remote('machine_get_cpu_type.sh')
        if output and output[0]:
            machine_.cpu_model = output[0].strip()

        logger.debug("Get CPU flags...")
        output, stderr, exitstatus = conn.execute_script_remote('machine_get_cpu_flags.sh')
        if output and output[0]:
            machine_.cpu_flags = output[0].strip()

        logger.debug("Get CPU speed...")
        output, stderr, exitstatus = conn.execute_script_remote('machine_get_cpu_speed.sh')
        if output and output[0]:
            machine_.cpu_speed = Decimal(int(output[0].strip()) / 1000000)

        logger.debug("Get CPU ID...")
        output, stderr, exitstatus = conn.execute_script_remote('machine_get_cpu_id.sh')
        if output and output[0]:
            machine_.cpu_id = output[0].strip()

        # EFI
        logger.debug("Check for EFI...")
        try:
            efi_file = conn.get_file('/sys/firmware/efi', 'r')
            efi_file.close()
            machine_.efi = True
        except IOError:
            machine_.efi = False

        # Memory
        logger.debug("Get RAM amount...")
        for line in conn.read_file('/proc/meminfo'):
            if line.startswith('MemTotal'):
                machine_.ram_amount = int(int(line.split()[1]) / 1024)

        # Virtualization capability
        VM_HOST_MIN_RAM_MB = 7000
        machine_.vm_capable = False

        # Virtualization: x86
        logger.debug("Check for VM capability...")
        if machine_.architecture_id == Architecture.Type.X86_64:
            cpu_flags = machine_.cpu_flags
            if cpu_flags:
                cpu_flags = cpu_flags.upper()
                if ((cpu_flags.find('VMX') >= 0 or cpu_flags.find('SVM') >= 0) and
                        int(machine_.ram_amount) > VM_HOST_MIN_RAM_MB):
                    machine_.vm_capable = True

        # Virtualization: ppc64le
        if machine_.architecture_id == Architecture.Type.PPC64LE:
            for line in conn.read_file('/proc/cpuinfo'):
                if line.startswith('firmware') and 'OPAL' in line:
                    machine_.vm_capable = True

        # Disk
        logger.debug("Get disk information...")
        stdout, stderr, exitstatus = conn.execute('hwinfo --disk')
        for line in stdout:
            line = line.strip()
            if line.startswith('Size:'):
                machine_.disk_primary_size = int(int(line.split()[1]) / 2 / 1024 ** 2)
            elif line.startswith('Attached to:'):
                opening_bracket = line.find('(')
                closing_bracket = line.find(')')
                if opening_bracket > 0 and closing_bracket > 0:
                    machine_.disk_type = line[opening_bracket + 1:closing_bracket]
                else:
                    machine_.disk_type = 'Unknown disk type'
                break

        # lsmod
        logger.debug("Get 'lsmod'...")
        stdout, stderr, exitstatus = conn.execute('lsmod')
        machine_.lsmod = normalize_ascii("".join(stdout))

        # lspci
        logger.debug("Get 'lspci'...")
        stdout, stderr, exitstatus = conn.execute('lspci -vvv -nn')
        machine_.lspci = normalize_ascii("".join(stdout))

        # last
        logger.debug("Get 'last'...")
        output, stderr, exitstatus = conn.execute('last | grep -v reboot | head -n 1')
        string = ''.join(output)
        result = string[0:8] + string[38:49]
        machine_.last = normalize_ascii("".join(result))

        # hwinfo
        logger.debug("Get 'hwinfo' (full)...")
        stdout, stderr, exitstatus = conn.execute(
            'hwinfo --bios ' +
            '--block --bridge --cdrom --cpu --disk --floppy --framebuffer ' +
            '--gfxcard --hub --ide --isapnp --isdn --keyboard --memory ' +
            '--monitor --mouse --netcard --network --partition --pci --pcmcia ' +
            '--scsi --smp --sound --sys --tape --tv --usb --usb-ctrl --wlan'
        )
        machine_.hwinfo = normalize_ascii("".join(stdout))

        # dmidecode
        logger.debug("Get 'dmidecode'...")
        stdout, stderr, exitstatus = conn.execute('dmidecode')
        machine_.dmidecode = normalize_ascii("".join(stdout))

        # dmesg
        logger.debug("Get 'dmesg'...")
        stdout, stderr, exitstatus = conn.execute(
            'if [ -e /var/log/boot.msg ]; then ' +
            'cat /var/log/boot.msg; else journalctl -xl | head -n200; ' +
            'fi'
        )
        machine_.dmesg = normalize_ascii("".join(stdout))

        # lsscsi
        logger.debug("Get 'lsscsi'...")
        stdout, stderr, exitstatus = conn.execute('lsscsi -s')
        machine_.lsscsi = normalize_ascii("".join(stdout))

        # lsusb
        logger.debug("Get 'lsusb'...")
        stdout, stderr, exitstatus = conn.execute('lsusb')
        machine_.lsusb = normalize_ascii("".join(stdout))

        # IPMI
        logger.debug("Check for IPMI...")
        machine_.ipmi = machine_.dmidecode.find('IPMI') >= 0

        # Firmware script
        logger.debug("Get BIOS version...")
        output, stderr, exitstatus = conn.execute_script_remote('machine_get_firmware.sh')
        if output and output[0]:
            machine_.bios_version = output[0].strip()

        return machine_

    except Exception as e:
        logger.error("{} ({})".format(fqdn, e))
        return False
    finally:
        if conn:
            conn.close()
        if timer:
            timer.cancel()

    return None