Return the minions found by looking via ipcidr
979497
def _check_ipcidr_minions(self, expr, greedy):
        '''
        
        '''
        cache_enabled = self.opts.get('minion_data_cache', False)

        if greedy:
            minions = self._pki_minions()
        elif cache_enabled:
            minions = self.cache.list('minions')
        else:
            return {'minions': [],
                    'missing': []}

        if cache_enabled:
            if greedy:
                cminions = self.cache.list('minions')
            else:
                cminions = minions
            if cminions is None:
                return {'minions': minions,
                        'missing': []}

            tgt = expr
            try:
                # Target is an address?
                tgt = ipaddress.ip_address(tgt)
            except Exception:
                try:
                    # Target is a network?
                    tgt = ipaddress.ip_network(tgt)
                except Exception:
                    log.error('Invalid IP/CIDR target: %s', tgt)
                    return {'minions': [],
                            'missing': []}
            proto = 'ipv{0}'.format(tgt.version)

            minions = set(minions)
            for id_ in cminions:
                mdata = self.cache.fetch('minions/{0}'.format(id_), 'data')
                if mdata is None:
                    if not greedy:
                        minions.remove(id_)
                    continue
                grains = mdata.get('grains')
                if grains is None or proto not in grains:
                    match = False
                elif isinstance(tgt, (ipaddress.IPv4Address, ipaddress.IPv6Address)):
                    match = six.text_type(tgt) in grains[proto]
                else:
                    match = salt.utils.network.in_subnet(tgt, grains[proto])

                if not match and id_ in minions:
                    minions.remove(id_)

        return {'minions': list(minions),
                'missing': []}
561472
def connected_ids(self, subset=None, show_ip=False, show_ipv4=None, include_localhost=None):
        '''
        
        '''
        if include_localhost is not None:
            salt.utils.versions.warn_until(
                'Sodium',
                'The \'include_localhost\' argument is no longer required; any'
                'connected localhost minion will always be included.'
            )
        if show_ipv4 is not None:
            salt.utils.versions.warn_until(
                'Sodium',
                'The \'show_ipv4\' argument has been renamed to \'show_ip\' as'
                'it now also includes IPv6 addresses for IPv6-connected'
                'minions.'
            )
        minions = set()
        if self.opts.get('minion_data_cache', False):
            search = self.cache.list('minions')
            if search is None:
                return minions
            addrs = salt.utils.network.local_port_tcp(int(self.opts['publish_port']))
            if '127.0.0.1' in addrs:
                # Add in the address of a possible locally-connected minion.
                addrs.discard('127.0.0.1')
                addrs.update(set(salt.utils.network.ip_addrs(include_loopback=False)))
            if '::1' in addrs:
                # Add in the address of a possible locally-connected minion.
                addrs.discard('::1')
                addrs.update(set(salt.utils.network.ip_addrs6(include_loopback=False)))
            if subset:
                search = subset
            for id_ in search:
                try:
                    mdata = self.cache.fetch('minions/{0}'.format(id_), 'data')
                except SaltCacheError:
                    # If a SaltCacheError is explicitly raised during the fetch operation,
                    # permission was denied to open the cached data.p file. Continue on as
                    # in the releases <= 2016.3. (An explicit error raise was added in PR
                    # #35388. See issue #36867 for more information.
                    continue
                if mdata is None:
                    continue
                grains = mdata.get('grains', {})
                for ipv4 in grains.get('ipv4', []):
                    if ipv4 in addrs:
                        if show_ip:
                            minions.add((id_, ipv4))
                        else:
                            minions.add(id_)
                        break
                for ipv6 in grains.get('ipv6', []):
                    if ipv6 in addrs:
                        if show_ip:
                            minions.add((id_, ipv6))
                        else:
                            minions.add(id_)
                        break
        return minions
745633
def file_list(load):
    '''
    
    '''
    if 'env' in load:
        # "env" is not supported; Use "saltenv".
        load.pop('env')

    if load['saltenv'] not in envs():
        return []
    mountpoint = salt.utils.url.strip_proto(__opts__['minionfs_mountpoint'])
    prefix = load.get('prefix', '').strip('/')
    if mountpoint and prefix.startswith(mountpoint + os.path.sep):
        prefix = prefix[len(mountpoint + os.path.sep):]

    minions_cache_dir = os.path.join(__opts__['cachedir'], 'minions')
    minion_dirs = os.listdir(minions_cache_dir)

    # If the prefix is not an empty string, then get the minion id from it. The
    # minion ID will be the part before the first slash, so if there is no
    # slash, this is an invalid path.
    if prefix:
        tgt_minion, _, prefix = prefix.partition('/')
        if not prefix:
            # No minion ID in path
            return []
        # Reassign minion_dirs so we don't unnecessarily walk every minion's
        # pushed files
        if tgt_minion not in minion_dirs:
            log.warning(
                'No files found in minionfs cache for minion ID \'%s\'',
                tgt_minion
            )
            return []
        minion_dirs = [tgt_minion]

    ret = []
    for minion in minion_dirs:
        if not _is_exposed(minion):
            continue
        minion_files_dir = os.path.join(minions_cache_dir, minion, 'files')
        if not os.path.isdir(minion_files_dir):
            log.debug(
                'minionfs: could not find files directory under %s!',
                os.path.join(minions_cache_dir, minion)
            )
            continue
        walk_dir = os.path.join(minion_files_dir, prefix)
        # Do not follow links for security reasons
        for root, _, files in salt.utils.path.os_walk(walk_dir, followlinks=False):
            for fname in files:
                # Ignore links for security reasons
                if os.path.islink(os.path.join(root, fname)):
                    continue
                relpath = os.path.relpath(
                    os.path.join(root, fname), minion_files_dir
                )
                if relpath.startswith('../'):
                    continue
                rel_fn = os.path.join(mountpoint, minion, relpath)
                if not salt.fileserver.is_file_ignored(__opts__, rel_fn):
                    ret.append(rel_fn)
    return ret
250135
def _all_minions(self, expr=None):
        '''
        
        '''
        mlist = []
        for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(os.path.join(self.opts['pki_dir'], self.acc))):
            if not fn_.startswith('.') and os.path.isfile(os.path.join(self.opts['pki_dir'], self.acc, fn_)):
                mlist.append(fn_)
        return {'minions': mlist, 'missing': []}
828536
def get_ipaddr(self):
        '''
        
        '''
        # Loopbacks - first interface
        if (len(self.loopbacks)):
            ips = self.loopbacks[0].ips
            if (len(ips)):
                ips.sort()
                return util.strip_slash_masklen(ips[0])

        # SVIs + all known - lowest address
        ips = []
        for svi in self.svis:
            ips.extend(svi.ip)
        ips.extend(self.ip)
        if (len(ips)):
            ips.sort()
            return util.strip_slash_masklen(ips[0])

        return ''
1009389
def ret_glob_minions(self):
        '''
        
        '''
        fnfilter = functools.partial(fnmatch.filter, pat=self.tgt)
        return self._ret_minions(fnfilter)
195982
def _check_list_minions(self, expr, greedy, ignore_missing=False):  # pylint: disable=unused-argument
        '''
        
        '''
        if isinstance(expr, six.string_types):
            expr = [m for m in expr.split(',') if m]
        minions = self._pki_minions()
        return {'minions': [x for x in expr if x in minions],
                'missing': [] if ignore_missing else [x for x in expr if x not in minions]}
830726
def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'):
    '''
    
    '''
    ret = set()

    ifaces = interface_data \
        if isinstance(interface_data, dict) \
        else interfaces()
    if interface is None:
        target_ifaces = ifaces
    else:
        target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces)
                              if k == interface])
        if not target_ifaces:
            log.error('Interface %s not found.', interface)
    for ip_info in six.itervalues(target_ifaces):
        addrs = ip_info.get(proto, [])
        addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto])

        for addr in addrs:
            addr = ipaddress.ip_address(addr.get('address'))
            if not addr.is_loopback or include_loopback:
                ret.add(addr)
    return [six.text_type(addr) for addr in sorted(ret)]
1000397
def gather_cache(self):
        '''
        
        '''
        cache = {'grains': {}, 'pillar': {}}
        if self.grains or self.pillar:
            if self.opts.get('minion_data_cache'):
                minions = self.cache.list('minions')
                if not minions:
                    return cache
                for minion in minions:
                    total = self.cache.fetch('minions/{0}'.format(minion), 'data')

                    if 'pillar' in total:
                        if self.pillar_keys:
                            for key in self.pillar_keys:
                                if key in total['pillar']:
                                    cache['pillar'][minion][key] = total['pillar'][key]
                        else:
                            cache['pillar'][minion] = total['pillar']
                    else:
                        cache['pillar'][minion] = {}

                    if 'grains' in total:
                        if self.grain_keys:
                            for key in self.grain_keys:
                                if key in total['grains']:
                                    cache['grains'][minion][key] = total['grains'][key]
                        else:
                            cache['grains'][minion] = total['grains']
                    else:
                        cache['grains'][minion] = {}
        return cache
1005379
def get_cli_static_event_returns(
            self,
            jid,
            minions,
            timeout=None,
            tgt='*',
            tgt_type='glob',
            verbose=False,
            show_timeout=False,
            show_jid=False):
        '''
        
        '''
        log.trace('entered - function get_cli_static_event_returns()')
        minions = set(minions)
        if verbose:
            msg = 'Executing job with jid {0}'.format(jid)
            print(msg)
            print('-' * len(msg) + '\n')
        elif show_jid:
            print('jid: {0}'.format(jid))

        if timeout is None:
            timeout = self.opts['timeout']

        start = int(time.time())
        timeout_at = start + timeout
        found = set()
        ret = {}
        # Check to see if the jid is real, if not return the empty dict
        try:
            if self.returners['{0}.get_load'.format(self.opts['master_job_cache'])](jid) == {}:
                log.warning('jid does not exist')
                return ret
        except Exception as exc:
            raise SaltClientError('Load could not be retrieved from '
                                  'returner {0}. Exception details: {1}'.format(
                                      self.opts['master_job_cache'],
                                      exc))
        # Wait for the hosts to check in
        while True:
            # Process events until timeout is reached or all minions have returned
            time_left = timeout_at - int(time.time())
            # Wait 0 == forever, use a minimum of 1s
            wait = max(1, time_left)
            jid_tag = 'salt/job/{0}'.format(jid)
            raw = self.event.get_event(wait, jid_tag, auto_reconnect=self.auto_reconnect)
            if raw is not None and 'return' in raw:
                if 'minions' in raw.get('data', {}):
                    minions.update(raw['data']['minions'])
                    continue
                found.add(raw['id'])
                ret[raw['id']] = {'ret': raw['return']}
                ret[raw['id']]['success'] = raw.get('success', False)
                if 'out' in raw:
                    ret[raw['id']]['out'] = raw['out']
                if len(found.intersection(minions)) >= len(minions):
                    # All minions have returned, break out of the loop
                    break
                continue
            # Then event system timeout was reached and nothing was returned
            if len(found.intersection(minions)) >= len(minions):
                # All minions have returned, break out of the loop
                break
            if int(time.time()) > timeout_at:
                if verbose or show_timeout:
                    if self.opts.get('minion_data_cache', False) \
                            or tgt_type in ('glob', 'pcre', 'list'):
                        if len(found) < len(minions):
                            fail = sorted(list(minions.difference(found)))
                            for minion in fail:
                                ret[minion] = {
                                    'out': 'no_return',
                                    'ret': 'Minion did not return'
                                }
                break
            time.sleep(0.01)

        self._clean_up_subscriptions(jid)
        return ret
157478
def connected():
    '''
    
    '''
    opts = salt.config.master_config(__opts__['conf_file'])

    if opts.get('con_cache'):
        cache_cli = CacheCli(opts)
        minions = cache_cli.get_cached()
    else:
        minions = list(salt.utils.minions.CkMinions(opts).connected_ids())
    return minions
913404
def list_keys(self):
        '''
        
        '''
        key_dirs = self._check_minions_directories()

        ret = {}

        for dir_ in key_dirs:
            if dir_ is None:
                continue
            ret[os.path.basename(dir_)] = []
            try:
                for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
                    if not fn_.startswith('.'):
                        if os.path.isfile(os.path.join(dir_, fn_)):
                            ret[os.path.basename(dir_)].append(
                                salt.utils.stringutils.to_unicode(fn_)
                            )
            except (OSError, IOError):
                # key dir kind is not created yet, just skip
                continue
        return ret
1227743
def scan(self):
        """"""
        found = []
        for addr in range(0,0x80):
            try:
                self._i2c_bus.read_byte(addr)
            except OSError:
                continue
            found.append(addr)
        return found
1085635
def get_load(jid):
    '''
    
    '''
    cb_ = _get_connection()

    try:
        jid_doc = cb_.get(six.text_type(jid))
    except couchbase.exceptions.NotFoundError:
        return {}

    ret = {}
    try:
        ret = jid_doc.value['load']
        ret['Minions'] = jid_doc.value['minions']
    except KeyError as e:
        log.error(e)

    return ret
1101579
def get_minion_data(minion, opts):
    '''
    
    '''
    grains = None
    pillar = None
    if opts.get('minion_data_cache', False):
        cache = salt.cache.factory(opts)
        if minion is None:
            for id_ in cache.list('minions'):
                data = cache.fetch('minions/{0}'.format(id_), 'data')
                if data is None:
                    continue
        else:
            data = cache.fetch('minions/{0}'.format(minion), 'data')
        if data is not None:
            grains = data.get('grains', None)
            pillar = data.get('pillar', None)
    return minion if minion else None, grains, pillar
692490
def find_minion_by_name(minion_name, raise_error = true)
      # raise(Thor::Error, "Node not specified.") if node_name.nil? || node_name.empty?
      raise('Minion not specified.') if minion_name.nil? || minion_name.empty?
      return {minion_name => minions_filtered[minion_name]} if minions[minion_name]
      minions.each do |key, value|
        return {key => value} if key.start_with?(minion_name)
      end
      raise("Not found:  #{minion_name} in #{stage_name}.") if raise_error
      # raise(Thor::Error, "Not found:  #{node_name} in #{stage_name}.")
      nil
    end
942785
def get_minions():
    '''
    
    '''
    options = _get_options(ret=None)

    # Make sure the views are valid, which includes the minions..
    if not ensure_views():
        return []

    # Make the request for the view..
    _response = _request("GET",
                         options['url'] +
                                 options['db'] +
                                 "/_design/salt/_view/minions?group=true")

    # Verify that we got a response back.
    if 'rows' not in _response:
        log.error('Unable to get available minions: %s', _response)
        return []

    # Iterate over the rows to build up a list return it.
    _ret = []
    for row in _response['rows']:
        _ret.append(row['key'])
    return _ret