Query NetBox API for minion data
768619
def ext_pillar(minion_id, pillar, *args, **kwargs):
    '''
    
    '''
    if minion_id == '*':
        log.info('There\'s no data to collect from NetBox for the Master')
        return {}
    # Pull settings from kwargs
    api_url = kwargs['api_url'].rstrip('/')
    api_token = kwargs.get('api_token')
    site_details = kwargs.get('site_details', True)
    site_prefixes = kwargs.get('site_prefixes', True)
    proxy_username = kwargs.get('proxy_username', None)
    proxy_return = kwargs.get('proxy_return', True)
    ret = {}

    # Fetch device from API
    headers = {}
    if api_token:
        headers = {
            'Authorization': 'Token {}'.format(api_token)
        }
    device_url = '{api_url}/{app}/{endpoint}'.format(api_url=api_url,
                                                     app='dcim',
                                                     endpoint='devices')
    device_results = salt.utils.http.query(device_url,
                                           params={'name': minion_id},
                                           header_dict=headers,
                                           decode=True)
   # Check status code for API call
    if 'error' in device_results:
        log.error('API query failed for "%s", status code: %d',
                  minion_id, device_results['status'])
        log.error(device_results['error'])
        return ret
    # Assign results from API call to "netbox" key
    devices = device_results['dict']['results']
    if len(devices) == 1:
        ret['netbox'] = devices[0]
    elif len(devices) > 1:
        log.error('More than one device found for "%s"', minion_id)
        return ret
    else:
        log.error('Unable to pull NetBox data for "%s"', minion_id)
        return ret
    site_id = ret['netbox']['site']['id']
    site_name = ret['netbox']['site']['name']
    if site_details:
        log.debug('Retrieving site details for "%s" - site %s (ID %d)',
                  minion_id, site_name, site_id)
        site_url = '{api_url}/{app}/{endpoint}/{site_id}/'.format(api_url=api_url,
                                                                  app='dcim',
                                                                  endpoint='sites',
                                                                  site_id=site_id)
        site_details_ret = salt.utils.http.query(site_url,
                                                 header_dict=headers,
                                                 decode=True)
        if 'error' in site_details_ret:
            log.error('Unable to retrieve site details for %s (ID %d)',
                      site_name, site_id)
            log.error('Status code: %d, error: %s',
                      site_details_ret['status'],
                      site_details_ret['error'])
        else:
            ret['netbox']['site'] = site_details_ret['dict']
    if site_prefixes:
        log.debug('Retrieving site prefixes for "%s" - site %s (ID %d)',
                  minion_id, site_name, site_id)
        prefixes_url = '{api_url}/{app}/{endpoint}'.format(api_url=api_url,
                                                           app='ipam',
                                                           endpoint='prefixes')
        site_prefixes_ret = salt.utils.http.query(prefixes_url,
                                                  params={'site_id': site_id},
                                                  header_dict=headers,
                                                  decode=True)
        if 'error' in site_prefixes_ret:
            log.error('Unable to retrieve site prefixes for %s (ID %d)',
                      site_name, site_id)
            log.error('Status code: %d, error: %s',
                      site_prefixes_ret['status'],
                      site_prefixes_ret['error'])
        else:
            ret['netbox']['site']['prefixes'] = site_prefixes_ret['dict']['results']
    if proxy_return:
        # Attempt to add "proxy" key, based on platform API call
        try:
            # Fetch device from API
            platform_results = salt.utils.http.query(ret['netbox']['platform']['url'],
                                                     header_dict=headers,
                                                     decode=True)
            # Check status code for API call
            if 'error' in platform_results:
                log.info('API query failed for "%s": %s',
                         minion_id, platform_results['error'])
            # Assign results from API call to "proxy" key if the platform has a
            # napalm_driver defined.
            napalm_driver = platform_results['dict'].get('napalm_driver')
            if napalm_driver:
                ret['proxy'] = {
                    'host': str(ipaddress.IPv4Interface(
                                ret['netbox']['primary_ip4']['address']).ip),
                    'driver': napalm_driver,
                    'proxytype': 'napalm',
                }
                if proxy_username:
                    ret['proxy']['username'] = proxy_username

        except Exception:
            log.debug(
                'Could not create proxy config data for "%s"', minion_id)

    return ret
140173
def _ret_minions(self, filter_):
        '''
        
        '''
        minions = {}
        for minion in filter_(self.raw):
            data = self.get_data(minion)
            if data:
                minions[minion] = data.copy()
        return minions
488911
def fetch(self, vault_client):
        """"""
        result = self.read(vault_client)
        if result:
            if isinstance(result, dict) and 'data' in result:
                self.existing = result['data']
            else:
                self.existing = result
        else:
            self.existing = None
734055
def api(gandi):
    """"""
    key_name = 'API version'

    result = gandi.api.info()
    result[key_name] = result.pop('api_version')
    output_generic(gandi, result, [key_name])

    return result
1004779
function clientNetworkData(channelDefArray, opt) {
	var self = {
		__TYPE__ : MessageType.CS_NET,
		channelCount : new type.UInt32Le( function () {
			return self.channelDefArray.obj.length;
		}),
		channelDefArray : channelDefArray || new type.Factory( function (s) {
			self.channelDefArray = new type.Component([]);
			
			for (var i = 0; i < self.channelCount.value; i++) {
				self.channelDefArray.obj.push(channelDef().read(s));
			}
		})
	};
	
	return new type.Component(self, opt);
}
375195
def get_fun(fun):
    '''
    
    '''
    serv = _get_serv(ret=None)
    minions = _get_list(serv, 'minions')
    returns = serv.get_multi(minions, key_prefix='{0}:'.format(fun))
    # returns = {minion: return, minion: return, ...}
    ret = {}
    for minion, data in six.iteritems(returns):
        ret[minion] = salt.utils.json.loads(data)
    return ret
1086079
def get_labels(node=None, apiserver_url=None):
    '''
    

    '''
    # Get salt minion ID
    node = _guess_node_id(node)
    # Try to get kubernetes master
    apiserver_url = _guess_apiserver(apiserver_url)
    if apiserver_url is None:
        return False

    # Get data
    ret = _get_labels(node, apiserver_url)

    return {"labels": ret}
727164
def get_fun(fun):
    '''
    
    '''
    serv = _get_serv(ret=None)
    ret = {}
    for minion in serv.smembers('minions'):
        ind_str = '{0}:{1}'.format(minion, fun)
        try:
            jid = serv.get(ind_str)
        except Exception:
            continue
        if not jid:
            continue
        data = serv.get('{0}:{1}'.format(minion, jid))
        if data:
            ret[minion] = salt.utils.json.loads(data)
    return ret
968898
def _minion_event(self, load):
        '''
        
        '''
        load = self.__verify_load(load, ('id', 'tok'))
        if load is False:
            return {}
        # Route to master event bus
        self.masterapi._minion_event(load)
        # Process locally
        self._handle_minion_event(load)
1141181
def ret_glob_minions(self):
        '''
        
        '''
        minions = {}
        for minion in self.raw:
            if fnmatch.fnmatch(minion, self.tgt):
                data = self.get_data(minion)
                if data:
                    minions[minion] = data
        return minions
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
534284
def targets(tgt, tgt_type='glob', **kwargs):  # pylint: disable=W0613
    '''
    
    '''
    minions = salt.utils.minions.CkMinions(__opts__)
    _res = minions.check_minions(tgt, tgt_type)
    minions = _res['minions']

    ret = {}
    if not minions:
        return ret
    # log.debug(minions)

    cache = salt.cache.Cache(__opts__)

    roster_order = __opts__.get('roster_order', {
        'host': ('ipv6-private', 'ipv6-global', 'ipv4-private', 'ipv4-public')
    })

    ret = {}
    for minion_id in minions:
        try:
            minion = _load_minion(minion_id, cache)
        except LookupError:
            continue

        minion_res = copy.deepcopy(__opts__.get('roster_defaults', {}))
        for param, order in roster_order.items():
            if not isinstance(order, (list, tuple)):
                order = [order]
            for key in order:
                kres = _minion_lookup(minion_id, key, minion)
                if kres:
                    minion_res[param] = kres
                    break

        if 'host' in minion_res:
            ret[minion_id] = minion_res
        else:
            log.warning('Could not determine host information for minion %s', minion_id)

    log.debug('Roster lookup result: %s', ret)

    return ret
11614
def get_box_threads(self, box_key):
		'''
		'''
		uri = '/'.join([
						self.api_uri,
						self.boxes_suffix,
						box_key,
						self.threads_suffix
						])
		return self._req('get', uri)
837908
def fetch_api_by_name(api_name):
    
    api_records = console.get_rest_apis()['items']
    matches = filter(lambda x: x['name'] == api_name, api_records)
    if not matches:
        return None
    return matches[0]
178075
def get_clients(self, limit=None, offset=None):
        
        data = {}
        if limit:
            data['limit'] = limit
        if offset:
            data['offset'] = offset
        result = self._request('GET', '/clients', data=json.dumps(data))
        return result.json()
440712
def get_returns(
            self,
            jid,
            minions,
            timeout=None):
        '''
        
        '''
        minions = set(minions)
        if timeout is None:
            timeout = self.opts['timeout']
        start = int(time.time())
        timeout_at = start + timeout
        log.debug(
            'get_returns for jid %s sent to %s will timeout at %s',
            jid, minions, datetime.fromtimestamp(timeout_at).time()
        )

        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('Master job cache returner [{0}] failed to verify jid. '
                                  'Exception details: {1}'.format(self.opts['master_job_cache'], exc))

        # Wait for the hosts to check in
        while True:
            time_left = timeout_at - int(time.time())
            wait = max(1, time_left)
            raw = self.event.get_event(wait, jid, auto_reconnect=self.auto_reconnect)
            if raw is not None and 'return' in raw:
                found.add(raw['id'])
                ret[raw['id']] = raw['return']
                if len(found.intersection(minions)) >= len(minions):
                    # All minions have returned, break out of the loop
                    log.debug('jid %s found all minions', jid)
                    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
                log.debug('jid %s found all minions', jid)
                break
            if int(time.time()) > timeout_at:
                log.info(
                    'jid %s minions %s did not return in time',
                    jid, (minions - found)
                )
                break
            time.sleep(0.01)
        return ret
624617
def api(self):
        
        functions = [x[0]for x in inspect.getmembers(self, predicate=inspect.ismethod)
                     if not x[0].startswith('_')]

        full_api = {
            'doc': u"When posting data you have to use the JSON format.",
            'api': []
        }
        my_daemon_type = "%s" % getattr(self.app, 'type', 'unknown')
        my_address = getattr(self.app, 'host_name', getattr(self.app, 'name', 'unknown'))
        if getattr(self.app, 'address', '127.0.0.1') not in ['127.0.0.1']:
            # If an address is explicitely specified, I must use it!
            my_address = self.app.address
        for fun in functions:
            endpoint = {
                'daemon': my_daemon_type,
                'name': fun,
                'doc': getattr(self, fun).__doc__,
                'uri': '%s://%s:%s/%s' % (getattr(self.app, 'scheme', 'http'),
                                          my_address,
                                          self.app.port, fun),
                'args': {}
            }

            try:
                spec = inspect.getfullargspec(getattr(self, fun))
            except Exception:  # pylint: disable=broad-except
                # pylint: disable=deprecated-method
                spec = inspect.getargspec(getattr(self, fun))
            args = [a for a in spec.args if a not in ('self', 'cls')]
            if spec.defaults:
                a_dict = dict(list(zip(args, spec.defaults)))
            else:
                a_dict = dict(list(zip(args, ("No default value",) * len(args))))

            endpoint["args"] = a_dict
            full_api['api'].append(endpoint)

        return full_api