예제 #1
0
    def parse(self, inventory, loader, path, cache=True):

        try:
            self._vbox_path = get_bin_path(self.VBOX, True)
        except ValueError as e:
            raise AnsibleParserError(e)

        super(InventoryModule, self).parse(inventory, loader, path)

        cache_key = self.get_cache_key(path)

        config_data = self._read_config_data(path)

        # set _options from config data
        self._consume_options(config_data)

        source_data = None
        if cache:
            cache = self.get_option('cache')

        update_cache = False
        if cache:
            try:
                source_data = self._cache[cache_key]
            except KeyError:
                update_cache = True

        if not source_data:
            b_pwfile = to_bytes(self.get_option('settings_password_file'),
                                errors='surrogate_or_strict',
                                nonstring='passthru')
            running = self.get_option('running_only')

            # start getting data
            cmd = [self._vbox_path, b'list', b'-l']
            if running:
                cmd.append(b'runningvms')
            else:
                cmd.append(b'vms')

            if b_pwfile and os.path.exists(b_pwfile):
                cmd.append(b'--settingspwfile')
                cmd.append(b_pwfile)

            try:
                p = Popen(cmd, stdout=PIPE)
            except Exception as e:
                raise AnsibleParserError(to_native(e))

            source_data = p.stdout.read().splitlines()

        using_current_cache = cache and not update_cache
        cacheable_results = self._populate_from_source(source_data,
                                                       using_current_cache)

        if update_cache:
            self._cache[cache_key] = cacheable_results
예제 #2
0
    def _connect(self):
        ''' connect to the chroot '''
        if os.path.isabs(self.get_option('chroot_exe')):
            self.chroot_cmd = self.get_option('chroot_exe')
        else:
            self.chroot_cmd = get_bin_path(self.get_option('chroot_exe'))

        if not self.chroot_cmd:
            raise AnsibleError("chroot command (%s) not found in PATH" %
                               to_native(self.get_option('chroot_exe')))

        super(Connection, self)._connect()
        if not self._connected:
            display.vvv("THIS IS A LOCAL CHROOT DIR", host=self.chroot)
            self._connected = True
예제 #3
0
    def _run_command(self, args):
        if not self.DOCKER_MACHINE_PATH:
            try:
                self.DOCKER_MACHINE_PATH = get_bin_path('docker-machine', required=True)
            except ValueError as e:
                raise AnsibleError('Unable to locate the docker-machine binary.', orig_exc=e)

        command = [self.DOCKER_MACHINE_PATH]
        command.extend(args)
        display.debug('Executing command {0}'.format(command))
        try:
            result = subprocess.check_output(command)
        except subprocess.CalledProcessError as e:
            display.warning('Exception {0} caught while executing command {1}, this was the original exception: {2}'.format(type(e).__name__, command, e))
            raise e

        return to_text(result).strip()
예제 #4
0
    def get_memory_facts(self):
        memory_facts = {
            'memtotal_mb': int(self.sysctl['hw.memsize']) // 1024 // 1024
        }

        total_used = 0
        page_size = 4096
        vm_stat_command = get_bin_path('vm_stat')
        rc, out, err = self.module.run_command(vm_stat_command)
        if rc == 0:
            # Free = Total - (Wired + active + inactive)
            # Get a generator of tuples from the command output so we can later
            # turn it into a dictionary
            memory_stats = (line.rstrip('.').split(':', 1)
                            for line in out.splitlines())

            # Strip extra left spaces from the value
            memory_stats = dict((k, v.lstrip()) for k, v in memory_stats)

            for k, v in memory_stats.items():
                try:
                    memory_stats[k] = int(v)
                except ValueError as ve:
                    # Most values convert cleanly to integer values but if the field does
                    # not convert to an integer, just leave it alone.
                    pass

            if memory_stats.get('Pages wired down'):
                total_used += memory_stats['Pages wired down'] * page_size
            if memory_stats.get('Pages active'):
                total_used += memory_stats['Pages active'] * page_size
            if memory_stats.get('Pages inactive'):
                total_used += memory_stats['Pages inactive'] * page_size

        memory_facts['memfree_mb'] = memory_facts['memtotal_mb'] - (
            total_used // 1024 // 1024)

        return memory_facts
예제 #5
0
    def collect(self, module=None, collected_facts=None):
        """
        Example of contents of /etc/iscsi/initiatorname.iscsi:

        ## DO NOT EDIT OR REMOVE THIS FILE!
        ## If you remove this file, the iSCSI daemon will not start.
        ## If you change the InitiatorName, existing access control lists
        ## may reject this initiator.  The InitiatorName must be unique
        ## for each iSCSI initiator.  Do NOT duplicate iSCSI InitiatorNames.
        InitiatorName=iqn.1993-08.org.debian:01:44a42c8ddb8b

        Example of output from the AIX lsattr command:

        # lsattr -E -l iscsi0
        disc_filename  /etc/iscsi/targets            Configuration file                            False
        disc_policy    file                          Discovery Policy                              True
        initiator_name iqn.localhost.hostid.7f000002 iSCSI Initiator Name                          True
        isns_srvnames  auto                          iSNS Servers IP Addresses                     True
        isns_srvports                                iSNS Servers Port Numbers                     True
        max_targets    16                            Maximum Targets Allowed                       True
        num_cmd_elems  200                           Maximum number of commands to queue to driver True

        Example of output from the HP-UX iscsiutil command:

        #iscsiutil -l
        Initiator Name             : iqn.1986-03.com.hp:mcel_VMhost3.1f355cf6-e2db-11e0-a999-b44c0aef5537
        Initiator Alias            :

        Authentication Method      : None
        CHAP Method                : CHAP_UNI
        Initiator CHAP Name        :
        CHAP Secret                :
        NAS Hostname               :
        NAS Secret                 :
        Radius Server Hostname     :
        Header Digest              : None, CRC32C (default)
        Data Digest                : None, CRC32C (default)
        SLP Scope list for iSLPD   :
        """

        iscsi_facts = {}
        iscsi_facts['iscsi_iqn'] = ""
        if sys.platform.startswith('linux') or sys.platform.startswith(
                'sunos'):
            for line in get_file_content('/etc/iscsi/initiatorname.iscsi',
                                         '').splitlines():
                if line.startswith('#') or line.startswith(
                        ';') or line.strip() == '':
                    continue
                if line.startswith('InitiatorName='):
                    iscsi_facts['iscsi_iqn'] = line.split('=', 1)[1]
                    break
        elif sys.platform.startswith('aix'):
            cmd = get_bin_path('lsattr')
            if cmd:
                cmd += " -E -l iscsi0"
                rc, out, err = module.run_command(cmd)
                if rc == 0 and out:
                    line = self.findstr(out, 'initiator_name')
                    iscsi_facts['iscsi_iqn'] = line.split()[1].rstrip()
        elif sys.platform.startswith('hp-ux'):
            # try to find it in the default PATH and opt_dirs
            cmd = get_bin_path('iscsiutil', opt_dirs=['/opt/iscsi/bin'])
            if cmd:
                cmd += " -l"
                rc, out, err = module.run_command(cmd)
                if out:
                    line = self.findstr(out, 'Initiator Name')
                    iscsi_facts['iscsi_iqn'] = line.split(":", 1)[1].rstrip()
        return iscsi_facts
예제 #6
0
    def parse(self, inventory, loader, path, cache=False):

        try:
            self._nmap = get_bin_path('nmap', True)
        except ValueError as e:
            raise AnsibleParserError(e)

        if self._nmap is None:
            raise AnsibleParserError(
                'nmap inventory plugin requires the nmap cli tool to work')

        super(InventoryModule, self).parse(inventory,
                                           loader,
                                           path,
                                           cache=cache)

        self._read_config_data(path)

        # setup command
        cmd = [self._nmap]
        if not self._options['ports']:
            cmd.append('-sP')

        if self._options['ipv4'] and not self._options['ipv6']:
            cmd.append('-4')
        elif self._options['ipv6'] and not self._options['ipv4']:
            cmd.append('-6')
        elif not self._options['ipv6'] and not self._options['ipv4']:
            raise AnsibleParserError(
                'One of ipv4 or ipv6 must be enabled for this plugin')

        if self._options['exclude']:
            cmd.append('--exclude')
            cmd.append(','.join(self._options['exclude']))

        cmd.append(self._options['address'])
        try:
            # execute
            p = Popen(cmd, stdout=PIPE, stderr=PIPE)
            stdout, stderr = p.communicate()
            if p.returncode != 0:
                raise AnsibleParserError('Failed to run nmap, rc=%s: %s' %
                                         (p.returncode, to_native(stderr)))

            # parse results
            host = None
            ip = None
            ports = []

            try:
                t_stdout = to_text(stdout, errors='surrogate_or_strict')
            except UnicodeError as e:
                raise AnsibleParserError(
                    'Invalid (non unicode) input returned: %s' % to_native(e))

            for line in t_stdout.splitlines():
                hits = self.find_host.match(line)
                if hits:
                    if host is not None:
                        self.inventory.set_variable(host, 'ports', ports)

                    # if dns only shows arpa, just use ip instead as hostname
                    if hits.group(1).endswith('.in-addr.arpa'):
                        host = hits.group(2)
                    else:
                        host = hits.group(1)

                    ip = hits.group(2)

                    if host is not None:
                        # update inventory
                        self.inventory.add_host(host)
                        self.inventory.set_variable(host, 'ip', ip)
                        ports = []
                    continue

                host_ports = self.find_port.match(line)
                if host is not None and host_ports:
                    ports.append({
                        'port': host_ports.group(1),
                        'protocol': host_ports.group(2),
                        'state': host_ports.group(3),
                        'service': host_ports.group(4)
                    })
                    continue

                # TODO: parse more data, OS?

            # if any leftovers
            if host and ports:
                self.inventory.set_variable(host, 'ports', ports)

        except Exception as e:
            raise AnsibleParserError("failed to parse %s: %s " %
                                     (to_native(path), to_native(e)))
예제 #7
0
 def is_available(self):
     self._cli = get_bin_path(self.CLI, False)
     return bool(self._cli)