Пример #1
0
    def get_cpu_facts(self):
        cpu_facts = {}

        i = 0
        physid = 0
        sockets = {}
        if not os.access("/proc/cpuinfo", os.R_OK):
            return cpu_facts
        cpu_facts['processor'] = []
        for line in get_file_lines("/proc/cpuinfo"):
            data = line.split(":", 1)
            key = data[0].strip()
            # model name is for Intel arch, Processor (mind the uppercase P)
            # works for some ARM devices, like the Sheevaplug.
            if key == 'model name' or key == 'Processor':
                if 'processor' not in cpu_facts:
                    cpu_facts['processor'] = []
                cpu_facts['processor'].append(data[1].strip())
                i += 1
            elif key == 'physical id':
                physid = data[1].strip()
                if physid not in sockets:
                    sockets[physid] = 1
            elif key == 'cpu cores':
                sockets[physid] = int(data[1].strip())
        if len(sockets) > 0:
            cpu_facts['processor_count'] = len(sockets)
            cpu_facts['processor_cores'] = reduce(lambda x, y: x + y,
                                                  sockets.values())
        else:
            cpu_facts['processor_count'] = i
            cpu_facts['processor_cores'] = 'NA'

        return cpu_facts
Пример #2
0
    def collect(self, module=None, collected_facts=None):
        """
        Example contents /sys/class/fc_host/*/port_name:

        0x21000014ff52a9bb

        """

        fc_facts = {}
        fc_facts['fibre_channel_wwn'] = []
        if sys.platform.startswith('linux'):
            for fcfile in glob.glob('/sys/class/fc_host/*/port_name'):
                for line in get_file_lines(fcfile):
                    fc_facts['fibre_channel_wwn'].append(line.rstrip()[2:])
        elif sys.platform.startswith('sunos'):
            """
            on solaris 10 or solaris 11 should use `fcinfo hba-port`
            TBD (not implemented): on solaris 9 use `prtconf -pv`
            """
            cmd = module.get_bin_path('fcinfo')
            cmd = cmd + " hba-port"
            rc, fcinfo_out, err = module.run_command(cmd)
            """
            # fcinfo hba-port  | grep "Port WWN"
            HBA Port WWN: 10000090fa1658de
            """
            if fcinfo_out:
                for line in fcinfo_out.splitlines():
                    if 'Port WWN' in line:
                        data = line.split(' ')
                        fc_facts['fibre_channel_wwn'].append(data[-1].rstrip())
        elif sys.platform.startswith('aix'):
            # get list of available fibre-channel devices (fcs)
            cmd = module.get_bin_path('lsdev')
            cmd = cmd + " -Cc adapter -l fcs*"
            rc, lsdev_out, err = module.run_command(cmd)
            if lsdev_out:
                lscfg_cmd = module.get_bin_path('lscfg')
                for line in lsdev_out.splitlines():
                    # if device is available (not in defined state), get its WWN
                    if 'Available' in line:
                        data = line.split(' ')
                        cmd = lscfg_cmd + " -vl %s" % data[0]
                        rc, lscfg_out, err = module.run_command(cmd)
                        # example output
                        # lscfg -vpl fcs3 | grep "Network Address"
                        #        Network Address.............10000090FA551509
                        for line in lscfg_out.splitlines():
                            if 'Network Address' in line:
                                data = line.split('.')
                                fc_facts['fibre_channel_wwn'].append(
                                    data[-1].rstrip())
        return fc_facts
Пример #3
0
    def get_memory_facts(self):
        memory_facts = {}
        if not os.access("/proc/meminfo", os.R_OK):
            return memory_facts
        for line in get_file_lines("/proc/meminfo"):
            data = line.split(":", 1)
            key = data[0]
            if key in NetBSDHardware.MEMORY_FACTS:
                val = data[1].strip().split(' ')[0]
                memory_facts["%s_mb" % key.lower()] = int(val) // 1024

        return memory_facts
Пример #4
0
    def get_memory_facts(self):
        memory_facts = {}
        if not os.access("/proc/meminfo", os.R_OK):
            return memory_facts

        memstats = {}
        for line in get_file_lines("/proc/meminfo"):
            data = line.split(":", 1)
            key = data[0]
            if key in self.ORIGINAL_MEMORY_FACTS:
                val = data[1].strip().split(' ')[0]
                memory_facts["%s_mb" % key.lower()] = int(val) // 1024

            if key in self.MEMORY_FACTS:
                val = data[1].strip().split(' ')[0]
                memstats[key.lower()] = int(val) // 1024

        if None not in (memstats.get('memtotal'), memstats.get('memfree')):
            memstats['real:used'] = memstats['memtotal'] - memstats['memfree']
        if None not in (memstats.get('cached'), memstats.get('memfree'),
                        memstats.get('buffers')):
            memstats['nocache:free'] = memstats['cached'] + memstats[
                'memfree'] + memstats['buffers']
        if None not in (memstats.get('memtotal'),
                        memstats.get('nocache:free')):
            memstats['nocache:used'] = memstats['memtotal'] - memstats[
                'nocache:free']
        if None not in (memstats.get('swaptotal'), memstats.get('swapfree')):
            memstats[
                'swap:used'] = memstats['swaptotal'] - memstats['swapfree']

        memory_facts['memory_mb'] = {
            'real': {
                'total': memstats.get('memtotal'),
                'used': memstats.get('real:used'),
                'free': memstats.get('memfree'),
            },
            'nocache': {
                'free': memstats.get('nocache:free'),
                'used': memstats.get('nocache:used'),
            },
            'swap': {
                'total': memstats.get('swaptotal'),
                'free': memstats.get('swapfree'),
                'used': memstats.get('swap:used'),
                'cached': memstats.get('swapcached'),
            },
        }

        return memory_facts
Пример #5
0
    def _lsb_release_file(self, etc_lsb_release_location):
        lsb_facts = {}

        if not os.path.exists(etc_lsb_release_location):
            return lsb_facts

        for line in get_file_lines(etc_lsb_release_location):
            value = line.split('=', 1)[1].strip()

            if 'DISTRIB_ID' in line:
                lsb_facts['id'] = value
            elif 'DISTRIB_RELEASE' in line:
                lsb_facts['release'] = value
            elif 'DISTRIB_DESCRIPTION' in line:
                lsb_facts['description'] = value
            elif 'DISTRIB_CODENAME' in line:
                lsb_facts['codename'] = value

        return lsb_facts
Пример #6
0
def main():
    module = AssibleModule(argument_spec=dict(
        test=dict(type='str', default='strip'),
        touch_file=dict(type='str', default='/dev/null'),
        line_sep_file=dict(type='str', default='/dev/null'),
        line_sep_sep=dict(type='str', default='\n'),
    ))

    test = module.params['test']
    facts = {}

    if test == 'strip':
        etc_passwd = get_file_content('/etc/passwd')
        etc_passwd_unstripped = get_file_content('/etc/passwd', strip=False)
        facts['etc_passwd_newlines'] = etc_passwd.count('\n')
        facts['etc_passwd_newlines_unstripped'] = etc_passwd_unstripped.count(
            '\n')

    elif test == 'default':
        path = module.params['touch_file']
        facts['touch_default'] = get_file_content(path,
                                                  default='i am a default')

    elif test == 'line_sep':
        path = module.params['line_sep_file']
        sep = module.params['line_sep_sep']
        facts['line_sep'] = get_file_lines(path, line_sep=sep)

    elif test == 'invalid_mountpoint':
        facts['invalid_mountpoint'] = get_mount_size('/doesnotexist')

    result = {
        'changed': False,
        'assible_facts': facts,
    }

    module.exit_json(**result)
Пример #7
0
    def get_virtual_facts(self):
        virtual_facts = {}

        # We want to maintain compatibility with the old "virtualization_type"
        # and "virtualization_role" entries, so we need to track if we found
        # them. We won't return them until the end, but if we found them early,
        # we should avoid updating them again.
        found_virt = False

        # But as we go along, we also want to track virt tech the new way.
        host_tech = set()
        guest_tech = set()

        # lxc/docker
        if os.path.exists('/proc/1/cgroup'):
            for line in get_file_lines('/proc/1/cgroup'):
                if re.search(r'/docker(/|-[0-9a-f]+\.scope)', line):
                    guest_tech.add('docker')
                    if not found_virt:
                        virtual_facts['virtualization_type'] = 'docker'
                        virtual_facts['virtualization_role'] = 'guest'
                        found_virt = True
                if re.search('/lxc/', line) or re.search(
                        '/machine.slice/machine-lxc', line):
                    guest_tech.add('lxc')
                    if not found_virt:
                        virtual_facts['virtualization_type'] = 'lxc'
                        virtual_facts['virtualization_role'] = 'guest'
                        found_virt = True
                if re.search('/system.slice/containerd.service', line):
                    guest_tech.add('containerd')
                    if not found_virt:
                        virtual_facts['virtualization_type'] = 'containerd'
                        virtual_facts['virtualization_role'] = 'guest'
                        found_virt = True

        # lxc does not always appear in cgroups anymore but sets 'container=lxc' environment var, requires root privs
        if os.path.exists('/proc/1/environ'):
            for line in get_file_lines('/proc/1/environ', line_sep='\x00'):
                if re.search('container=lxc', line):
                    guest_tech.add('lxc')
                    if not found_virt:
                        virtual_facts['virtualization_type'] = 'lxc'
                        virtual_facts['virtualization_role'] = 'guest'
                        found_virt = True
                if re.search('container=podman', line):
                    guest_tech.add('podman')
                    if not found_virt:
                        virtual_facts['virtualization_type'] = 'podman'
                        virtual_facts['virtualization_role'] = 'guest'
                        found_virt = True
                if re.search('^container=.', line):
                    guest_tech.add('container')
                    if not found_virt:
                        virtual_facts['virtualization_type'] = 'container'
                        virtual_facts['virtualization_role'] = 'guest'
                        found_virt = True

        if os.path.exists('/proc/vz') and not os.path.exists('/proc/lve'):
            virtual_facts['virtualization_type'] = 'openvz'
            if os.path.exists('/proc/bc'):
                host_tech.add('openvz')
                if not found_virt:
                    virtual_facts['virtualization_role'] = 'host'
            else:
                guest_tech.add('openvz')
                if not found_virt:
                    virtual_facts['virtualization_role'] = 'guest'
            found_virt = True

        systemd_container = get_file_content('/run/systemd/container')
        if systemd_container:
            guest_tech.add(systemd_container)
            if not found_virt:
                virtual_facts['virtualization_type'] = systemd_container
                virtual_facts['virtualization_role'] = 'guest'
                found_virt = True

        # ensure 'container' guest_tech is appropriately set
        if guest_tech.intersection(
                set(['docker', 'lxc', 'podman', 'openvz', 'containerd'
                     ])) or systemd_container:
            guest_tech.add('container')

        if os.path.exists("/proc/xen"):
            is_xen_host = False
            try:
                for line in get_file_lines('/proc/xen/capabilities'):
                    if "control_d" in line:
                        is_xen_host = True
            except IOError:
                pass

            if is_xen_host:
                host_tech.add('xen')
                if not found_virt:
                    virtual_facts['virtualization_type'] = 'xen'
                    virtual_facts['virtualization_role'] = 'host'
            else:
                if not found_virt:
                    virtual_facts['virtualization_type'] = 'xen'
                    virtual_facts['virtualization_role'] = 'guest'
            found_virt = True

        # assume guest for this block
        if not found_virt:
            virtual_facts['virtualization_role'] = 'guest'

        product_name = get_file_content(
            '/sys/devices/virtual/dmi/id/product_name')

        if product_name in ('KVM', 'KVM Server', 'Bochs', 'AHV'):
            guest_tech.add('kvm')
            if not found_virt:
                virtual_facts['virtualization_type'] = 'kvm'
                found_virt = True

        if product_name == 'RHEV Hypervisor':
            guest_tech.add('RHEV')
            if not found_virt:
                virtual_facts['virtualization_type'] = 'RHEV'
                found_virt = True

        if product_name in ('VMware Virtual Platform', 'VMware7,1'):
            guest_tech.add('VMware')
            if not found_virt:
                virtual_facts['virtualization_type'] = 'VMware'
                found_virt = True

        if product_name in ('OpenStack Compute', 'OpenStack Nova'):
            guest_tech.add('openstack')
            if not found_virt:
                virtual_facts['virtualization_type'] = 'openstack'
                found_virt = True

        bios_vendor = get_file_content(
            '/sys/devices/virtual/dmi/id/bios_vendor')

        if bios_vendor == 'Xen':
            guest_tech.add('xen')
            if not found_virt:
                virtual_facts['virtualization_type'] = 'xen'
                found_virt = True

        if bios_vendor == 'innotek GmbH':
            guest_tech.add('virtualbox')
            if not found_virt:
                virtual_facts['virtualization_type'] = 'virtualbox'
                found_virt = True

        if bios_vendor in ('Amazon EC2', 'DigitalOcean', 'Hetzner'):
            guest_tech.add('kvm')
            if not found_virt:
                virtual_facts['virtualization_type'] = 'kvm'
                found_virt = True

        sys_vendor = get_file_content('/sys/devices/virtual/dmi/id/sys_vendor')

        KVM_SYS_VENDORS = ('QEMU', 'oVirt', 'Amazon EC2', 'DigitalOcean',
                           'Google', 'Scaleway', 'Nutanix')
        if sys_vendor in KVM_SYS_VENDORS:
            guest_tech.add('kvm')
            if not found_virt:
                virtual_facts['virtualization_type'] = 'kvm'
                found_virt = True

        if sys_vendor == 'KubeVirt':
            guest_tech.add('KubeVirt')
            if not found_virt:
                virtual_facts['virtualization_type'] = 'KubeVirt'
                found_virt = True

        # FIXME: This does also match hyperv
        if sys_vendor == 'Microsoft Corporation':
            guest_tech.add('VirtualPC')
            if not found_virt:
                virtual_facts['virtualization_type'] = 'VirtualPC'
                found_virt = True

        if sys_vendor == 'Parallels Software International Inc.':
            guest_tech.add('parallels')
            if not found_virt:
                virtual_facts['virtualization_type'] = 'parallels'
                found_virt = True

        if sys_vendor == 'OpenStack Foundation':
            guest_tech.add('openstack')
            if not found_virt:
                virtual_facts['virtualization_type'] = 'openstack'
                found_virt = True

        # unassume guest
        if not found_virt:
            del virtual_facts['virtualization_role']

        if os.path.exists('/proc/self/status'):
            for line in get_file_lines('/proc/self/status'):
                if re.match(r'^VxID:\s+\d+', line):
                    if not found_virt:
                        virtual_facts['virtualization_type'] = 'linux_vserver'
                    if re.match(r'^VxID:\s+0', line):
                        host_tech.add('linux_vserver')
                        if not found_virt:
                            virtual_facts['virtualization_role'] = 'host'
                    else:
                        guest_tech.add('linux_vserver')
                        if not found_virt:
                            virtual_facts['virtualization_role'] = 'guest'
                    found_virt = True

        if os.path.exists('/proc/cpuinfo'):
            for line in get_file_lines('/proc/cpuinfo'):
                if re.match('^model name.*QEMU Virtual CPU', line):
                    guest_tech.add('kvm')
                    if not found_virt:
                        virtual_facts['virtualization_type'] = 'kvm'
                elif re.match('^vendor_id.*User Mode Linux', line):
                    guest_tech.add('uml')
                    if not found_virt:
                        virtual_facts['virtualization_type'] = 'uml'
                elif re.match('^model name.*UML', line):
                    guest_tech.add('uml')
                    if not found_virt:
                        virtual_facts['virtualization_type'] = 'uml'
                elif re.match('^machine.*CHRP IBM pSeries .emulated by qemu.',
                              line):
                    guest_tech.add('kvm')
                    if not found_virt:
                        virtual_facts['virtualization_type'] = 'kvm'
                elif re.match('^vendor_id.*PowerVM Lx86', line):
                    guest_tech.add('powervm_lx86')
                    if not found_virt:
                        virtual_facts['virtualization_type'] = 'powervm_lx86'
                elif re.match('^vendor_id.*IBM/S390', line):
                    guest_tech.add('PR/SM')
                    if not found_virt:
                        virtual_facts['virtualization_type'] = 'PR/SM'
                    lscpu = self.module.get_bin_path('lscpu')
                    if lscpu:
                        rc, out, err = self.module.run_command(["lscpu"])
                        if rc == 0:
                            for line in out.splitlines():
                                data = line.split(":", 1)
                                key = data[0].strip()
                                if key == 'Hypervisor':
                                    tech = data[1].strip()
                                    guest_tech.add(tech)
                                    if not found_virt:
                                        virtual_facts[
                                            'virtualization_type'] = tech
                    else:
                        guest_tech.add('ibm_systemz')
                        if not found_virt:
                            virtual_facts[
                                'virtualization_type'] = 'ibm_systemz'
                else:
                    continue
                if virtual_facts['virtualization_type'] == 'PR/SM':
                    if not found_virt:
                        virtual_facts['virtualization_role'] = 'LPAR'
                else:
                    if not found_virt:
                        virtual_facts['virtualization_role'] = 'guest'
                if not found_virt:
                    found_virt = True

        # Beware that we can have both kvm and virtualbox running on a single system
        if os.path.exists("/proc/modules") and os.access(
                '/proc/modules', os.R_OK):
            modules = []
            for line in get_file_lines("/proc/modules"):
                data = line.split(" ", 1)
                modules.append(data[0])

            if 'kvm' in modules:
                host_tech.add('kvm')
                if not found_virt:
                    virtual_facts['virtualization_type'] = 'kvm'
                    virtual_facts['virtualization_role'] = 'host'

                if os.path.isdir('/rhev/'):
                    # Check whether this is a RHEV hypervisor (is vdsm running ?)
                    for f in glob.glob('/proc/[0-9]*/comm'):
                        try:
                            with open(f) as virt_fh:
                                comm_content = virt_fh.read().rstrip()

                            if comm_content in ('vdsm', 'vdsmd'):
                                # We add both kvm and RHEV to host_tech in this case.
                                # It's accurate. RHEV uses KVM.
                                host_tech.add('RHEV')
                                if not found_virt:
                                    virtual_facts[
                                        'virtualization_type'] = 'RHEV'
                                break
                        except Exception:
                            pass

                found_virt = True

            if 'vboxdrv' in modules:
                host_tech.add('virtualbox')
                if not found_virt:
                    virtual_facts['virtualization_type'] = 'virtualbox'
                    virtual_facts['virtualization_role'] = 'host'
                    found_virt = True

            if 'virtio' in modules:
                host_tech.add('kvm')
                if not found_virt:
                    virtual_facts['virtualization_type'] = 'kvm'
                    virtual_facts['virtualization_role'] = 'guest'
                    found_virt = True

        # In older Linux Kernel versions, /sys filesystem is not available
        # dmidecode is the safest option to parse virtualization related values
        dmi_bin = self.module.get_bin_path('dmidecode')
        # We still want to continue even if dmidecode is not available
        if dmi_bin is not None:
            (rc, out, err) = self.module.run_command(
                '%s -s system-product-name' % dmi_bin)
            if rc == 0:
                # Strip out commented lines (specific dmidecode output)
                vendor_name = ''.join([
                    line.strip() for line in out.splitlines()
                    if not line.startswith('#')
                ])
                if vendor_name.startswith('VMware'):
                    guest_tech.add('VMware')
                    if not found_virt:
                        virtual_facts['virtualization_type'] = 'VMware'
                        virtual_facts['virtualization_role'] = 'guest'
                        found_virt = True

        if os.path.exists('/dev/kvm'):
            host_tech.add('kvm')
            if not found_virt:
                virtual_facts['virtualization_type'] = 'kvm'
                virtual_facts['virtualization_role'] = 'host'
                found_virt = True

        # If none of the above matches, return 'NA' for virtualization_type
        # and virtualization_role. This allows for proper grouping.
        if not found_virt:
            virtual_facts['virtualization_type'] = 'NA'
            virtual_facts['virtualization_role'] = 'NA'
            found_virt = True

        virtual_facts['virtualization_tech_guest'] = guest_tech
        virtual_facts['virtualization_tech_host'] = host_tech
        return virtual_facts
Пример #8
0
    def get_cpu_facts(self, collected_facts=None):
        cpu_facts = {}
        collected_facts = collected_facts or {}

        i = 0
        vendor_id_occurrence = 0
        model_name_occurrence = 0
        processor_occurence = 0
        physid = 0
        coreid = 0
        sockets = {}
        cores = {}

        xen = False
        xen_paravirt = False
        try:
            if os.path.exists('/proc/xen'):
                xen = True
            else:
                for line in get_file_lines('/sys/hypervisor/type'):
                    if line.strip() == 'xen':
                        xen = True
                    # Only interested in the first line
                    break
        except IOError:
            pass

        if not os.access("/proc/cpuinfo", os.R_OK):
            return cpu_facts

        cpu_facts['processor'] = []
        for line in get_file_lines('/proc/cpuinfo'):
            data = line.split(":", 1)
            key = data[0].strip()

            try:
                val = data[1].strip()
            except IndexError:
                val = ""

            if xen:
                if key == 'flags':
                    # Check for vme cpu flag, Xen paravirt does not expose this.
                    #   Need to detect Xen paravirt because it exposes cpuinfo
                    #   differently than Xen HVM or KVM and causes reporting of
                    #   only a single cpu core.
                    if 'vme' not in val:
                        xen_paravirt = True

            # model name is for Intel arch, Processor (mind the uppercase P)
            # works for some ARM devices, like the Sheevaplug.
            # 'ncpus active' is SPARC attribute
            if key in [
                    'model name', 'Processor', 'vendor_id', 'cpu', 'Vendor',
                    'processor'
            ]:
                if 'processor' not in cpu_facts:
                    cpu_facts['processor'] = []
                cpu_facts['processor'].append(val)
                if key == 'vendor_id':
                    vendor_id_occurrence += 1
                if key == 'model name':
                    model_name_occurrence += 1
                if key == 'processor':
                    processor_occurence += 1
                i += 1
            elif key == 'physical id':
                physid = val
                if physid not in sockets:
                    sockets[physid] = 1
            elif key == 'core id':
                coreid = val
                if coreid not in sockets:
                    cores[coreid] = 1
            elif key == 'cpu cores':
                sockets[physid] = int(val)
            elif key == 'siblings':
                cores[coreid] = int(val)
            elif key == '# processors':
                cpu_facts['processor_cores'] = int(val)
            elif key == 'ncpus active':
                i = int(val)

        # Skip for platforms without vendor_id/model_name in cpuinfo (e.g ppc64le)
        if vendor_id_occurrence > 0:
            if vendor_id_occurrence == model_name_occurrence:
                i = vendor_id_occurrence

        # The fields for ARM CPUs do not always include 'vendor_id' or 'model name',
        # and sometimes includes both 'processor' and 'Processor'.
        # The fields for Power CPUs include 'processor' and 'cpu'.
        # Always use 'processor' count for ARM and Power systems
        if collected_facts.get('assible_architecture', '').startswith(
            ('armv', 'aarch', 'ppc')):
            i = processor_occurence

        # FIXME
        if collected_facts.get('assible_architecture') != 's390x':
            if xen_paravirt:
                cpu_facts['processor_count'] = i
                cpu_facts['processor_cores'] = i
                cpu_facts['processor_threads_per_core'] = 1
                cpu_facts['processor_vcpus'] = i
            else:
                if sockets:
                    cpu_facts['processor_count'] = len(sockets)
                else:
                    cpu_facts['processor_count'] = i

                socket_values = list(sockets.values())
                if socket_values and socket_values[0]:
                    cpu_facts['processor_cores'] = socket_values[0]
                else:
                    cpu_facts['processor_cores'] = 1

                core_values = list(cores.values())
                if core_values:
                    cpu_facts['processor_threads_per_core'] = core_values[
                        0] // cpu_facts['processor_cores']
                else:
                    cpu_facts['processor_threads_per_core'] = 1 // cpu_facts[
                        'processor_cores']

                cpu_facts['processor_vcpus'] = (
                    cpu_facts['processor_threads_per_core'] *
                    cpu_facts['processor_count'] *
                    cpu_facts['processor_cores'])

                # if the number of processors available to the module's
                # thread cannot be determined, the processor count
                # reported by /proc will be the default:
                cpu_facts['processor_nproc'] = processor_occurence

                try:
                    cpu_facts['processor_nproc'] = len(os.sched_getaffinity(0))
                except AttributeError:
                    # In Python < 3.3, os.sched_getaffinity() is not available
                    try:
                        cmd = get_bin_path('nproc')
                    except ValueError:
                        pass
                    else:
                        rc, out, _err = self.module.run_command(cmd)
                        if rc == 0:
                            cpu_facts['processor_nproc'] = int(out)

        return cpu_facts