Returns a Node instance representing the current service node.

        Collects the host and IP information for the current machine and
        the port information from the given service.
513505
def current(cls, service, port):
        
        host = socket.getfqdn()
        return cls(
            host=host,
            ip=socket.gethostbyname(host),
            port=port,
            metadata=service.metadata
        )
964851
def get_node(conn, name):
    '''
    
    '''
    nodes = conn.list_nodes()
    for node in nodes:
        if node.name == name:
            __utils__['cloud.cache_node'](salt.utils.data.simple_types_filter(node.__dict__), __active_provider_name__, __opts__)
            return node
1373219
def get(security_token=None, key=None):
    
    if security_token is None:
        security_token = nago.core.get_my_info()['host_name']
    data = node_data.get(security_token, {})
    if not key:
        return data
    else:
        return data.get(key)
762209
def _node_info(conn):
    '''
    
    '''
    raw = conn.getInfo()
    info = {'cpucores': raw[6],
            'cpumhz': raw[3],
            'cpumodel': six.text_type(raw[0]),
            'cpus': raw[2],
            'cputhreads': raw[7],
            'numanodes': raw[4],
            'phymemory': raw[1],
            'sockets': raw[5]}
    return info
721176
def do(self):
        
        if not self._nodes:
            return
        # Let's retain original copy of _nodes
        node_copy = dict(self._nodes)

        self._do(node_copy)

        return self._factory.get_instantiated_services()
422353
def show_instance(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with -a or --action.'
        )

    nodes = list_nodes_full()
    # Find under which cloud service the name is listed, if any
    if name not in nodes:
        return {}
    if 'name' not in nodes[name]:
        nodes[name]['name'] = nodes[name]['id']
    try:
        __utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
    except TypeError:
        log.warning('Unable to show cache node data; this may be because the node has been deleted')
    return nodes[name]
279825
public ClusterNode getRunnableNode(RequestedNode requestedNode,
                                     LocalityLevel maxLevel,
                                     ResourceType type,
                                     Set<String> excluded) {
    ClusterNode node = null;
    RunnableIndices r = typeToIndices.get(type);

    // find host local
    node = r.getRunnableNodeForHost(requestedNode);

    if (maxLevel == LocalityLevel.NODE || node != null) {
      return node;
    }
    node = r.getRunnableNodeForRack(requestedNode, excluded);

    if (maxLevel == LocalityLevel.RACK || node != null) {
      return node;
    }

    // find any node
    node = r.getRunnableNodeForAny(excluded);

    return node;
  }
1055675
def collect_snmp(self, device, host, port, community):
        
        # Log
        self.log.info("Collecting Netscaler statistics from: %s", device)

        # Set timestamp
        timestamp = time.time()

        # Collect Netscaler System OIDs
        for k, v in self.NETSCALER_SYSTEM_GUAGES.items():
            # Get Metric Name and Value
            metricName = '.'.join([k])
            metricValue = int(self.get(v, host, port, community)[v])
            # Get Metric Path
            metricPath = '.'.join(['devices', device, 'system', metricName])
            # Create Metric
            metric = Metric(metricPath, metricValue, timestamp, 0)
            # Publish Metric
            self.publish_metric(metric)

        # Collect Netscaler System Counter OIDs
        for k, v in self.NETSCALER_SYSTEM_COUNTERS.items():
            # Get Metric Name and Value
            metricName = '.'.join([k])
            # Get Metric Path
            metricPath = '.'.join(['devices', device, 'system', metricName])
            # Get Metric Value
            metricValue = self.derivative(metricPath, long(
                self.get(v, host, port, community)[v]), self.MAX_VALUE)
            # Create Metric
            metric = Metric(metricPath, metricValue, timestamp, 0)
            # Publish Metric
            self.publish_metric(metric)

        # Collect Netscaler Services
        serviceNames = [v.strip("\'") for v in self.walk(
            self.NETSCALER_SERVICE_NAMES, host, port, community).values()]

        for serviceName in serviceNames:
            # Get Service Name in OID form
            serviceNameOid = self.get_string_index_oid(serviceName)

            # Get Service Type
            serviceTypeOid = ".".join([self.NETSCALER_SERVICE_TYPE,
                                       self._convert_from_oid(serviceNameOid)])
            serviceType = int(self.get(serviceTypeOid,
                                       host,
                                       port,
                                       community)[serviceTypeOid].strip("\'"))

            # Filter excluded service types
            if serviceType in map(lambda v: int(v),
                                  self.config.get('exclude_service_type')):
                continue

            # Get Service State
            serviceStateOid = ".".join([self.NETSCALER_SERVICE_STATE,
                                        self._convert_from_oid(serviceNameOid)])
            serviceState = int(self.get(serviceStateOid,
                                        host,
                                        port,
                                        community)[serviceStateOid].strip("\'"))

            # Filter excluded service states
            if serviceState in map(lambda v: int(v),
                                   self.config.get('exclude_service_state')):
                continue

            for k, v in self.NETSCALER_SERVICE_GUAGES.items():
                serviceGuageOid = ".".join(
                    [v, self._convert_from_oid(serviceNameOid)])
                # Get Metric Name
                metricName = '.'.join([re.sub(r'\.|\\', '_', serviceName), k])
                # Get Metric Value
                metricValue = int(self.get(serviceGuageOid,
                                           host,
                                           port,
                                           community
                                           )[serviceGuageOid].strip("\'"))
                # Get Metric Path
                metricPath = '.'.join(['devices',
                                       device,
                                       'service',
                                       metricName])
                # Create Metric
                metric = Metric(metricPath, metricValue, timestamp, 0)
                # Publish Metric
                self.publish_metric(metric)

        # Collect Netscaler Vservers
        vserverNames = [v.strip("\'") for v in self.walk(
            self.NETSCALER_VSERVER_NAMES, host, port, community).values()]

        for vserverName in vserverNames:
            # Get Vserver Name in OID form
            vserverNameOid = self.get_string_index_oid(vserverName)

            # Get Vserver Type
            vserverTypeOid = ".".join([self.NETSCALER_VSERVER_TYPE,
                                       self._convert_from_oid(vserverNameOid)])
            vserverType = int(self.get(vserverTypeOid,
                                       host,
                                       port,
                                       community)[vserverTypeOid].strip("\'"))

            # filter excluded vserver types
            if vserverType in map(lambda v: int(v),
                                  self.config.get('exclude_vserver_type')):
                continue

            # Get Service State
            vserverStateOid = ".".join([self.NETSCALER_VSERVER_STATE,
                                        self._convert_from_oid(vserverNameOid)])
            vserverState = int(self.get(vserverStateOid,
                                        host,
                                        port,
                                        community)[vserverStateOid].strip("\'"))

            # Filter excluded vserver state
            if vserverState in map(lambda v: int(v),
                                   self.config.get('exclude_vserver_state')):
                continue

            for k, v in self.NETSCALER_VSERVER_GUAGES.items():
                vserverGuageOid = ".".join(
                    [v, self._convert_from_oid(vserverNameOid)])
                # Get Metric Name
                metricName = '.'.join([re.sub(r'\.|\\', '_', vserverName), k])
                # Get Metric Value
                metricValue = int(self.get(vserverGuageOid,
                                           host,
                                           port,
                                           community
                                           )[vserverGuageOid].strip("\'"))
                # Get Metric Path
                metricPath = '.'.join(['devices',
                                       device,
                                       'vserver',
                                       metricName])
                # Create Metric
                metric = Metric(metricPath, metricValue, timestamp, 0)
                # Publish Metric
                self.publish_metric(metric)
991284
def get_ips(self, instance_id):
        
        if not instance_id:
          raise InstanceError("could not retrieve the ip address for node: "
                              "no associated instance id")
        gce = self._connect()
        instances = gce.instances()
        try:
            request = instances.get(instance=instance_id,
                                    project=self._project_id, zone=self._zone)
            response = self._execute_request(request)
            ip_public = None

            # If the instance is in status TERMINATED, then there will be
            # no IP addresses.
            if response and response['status'] in ('STOPPING', 'TERMINATED'):
              log.info("node '%s' state is '%s'; no IP address(es)" %
                       (instance_id, response['status']))
              return [None]

            if response and "networkInterfaces" in response:
                interfaces = response['networkInterfaces']
                if interfaces:
                    if "accessConfigs" in interfaces[0]:
                        ip_public = interfaces[0]['accessConfigs'][0]['natIP']

            if ip_public:
                return [ip_public]
            else:
                raise InstanceError("could not retrieve the ip address for "
                                    "node `%s`, please check the node "
                                    "through the cloud provider interface"
                                    % instance_id)

        except (HttpError, CloudProviderError) as e:
            raise InstanceError('could not retrieve the ip address of `%s`: '
                                '`%s`' % (instance_id, e))
1327320
def get_service_name(self, service_id: str) -> str:
        
        # Raise an exception if we are not a manager
        if not self._manager:
            raise RuntimeError('Only the Swarm manager node can retrieve all'
                               ' the services details.')

        service = self._client.services.get(service_id)
        return service.name
1230050
function Node (host, customSettings) {
  let node = new EventEmitter()

  let _settings = {...defaultSettings, ...customSettings, host}
  _validateSettings(_settings)

  let _id = getNodeId(_settings)
  let _name = nodeIdToName(_id)
  let _active = false
  let _deactivating = false
  let _canPublish = false
  let _receiving = false
  let _master = null

  let { external } = _settings

  //  Debug
  const _debugStr = `dnsmq-messagebus:${external ? 'externalnode' : 'dnsnode'}`
  const _debug = D(_debugStr)
  const debug = (...args) => _debug(_name, ...args)

  /**
   * starts a master node resolution;
   * if a master node is found starts a connection to it
   */
  const _seekForMaster = () => {
    if (!_active || _masterResolver.isResolving) return
    _masterResolver
    .resolve()
    .then(_connectToMaster)
    .catch(() => {
      _seekForMaster()
    })
  }
  /**
   * starts a connection of the PUB and SUB interfaces
   * to a given master
   * @param  {string} id
   * @param  {string} name
   * @param  {object} endpoints
   */
  const _connectToMaster = ({id, name, endpoints}) => {
    if (!_active) return
    _master = {id, name, endpoints}
    _subConnection.connect({name, endpoint: endpoints.pub})
    _pubConnection.connect({name, endpoint: endpoints.sub})
    if (!external) {
      name === _name ? _masterBroker.startHeartbeats() : _masterBroker.stoptHeartbeats()
    }
  }

  /**
   * publish interface
   * @type {object}
   */
  let _pubConnection = PubConnection(node)
  _pubConnection.on('connect', () => {
    _canPublish = true
    node.emit('can:publish')
    if (_receiving) node.emit('ready')
  })
  _pubConnection.on('disconnect', () => {
    _canPublish = false
    node.emit('cannot:publish')
    if (_receiving) node.emit('not:ready')
  })

  /**
   * subscribe interface
   * @type {object}
   */
  let _subConnection = SubConnection(node)
  _subConnection.on('missingmaster', () => {
    _pubConnection.disconnect()
    _seekForMaster()
  })
  _subConnection.on('newmaster', _connectToMaster)
  _subConnection.on('connect', () => {
    _receiving = true
    node.emit('receiving')
    if (_canPublish) node.emit('ready')
  })
  _subConnection.on('disconnect', () => {
    _receiving = false
    _master = null
    node.emit('not:receiving')
    if (_canPublish) node.emit('not:ready')
  })

  /**
   * master resolution component
   * @type {object}
   */
  let _masterResolver

  /**
   * master broker component
   * The external nodes dont have this component
   * @type {object}
   */
  let _masterBroker

  if (!external) {
    _masterBroker = MasterBroker(node)
    _masterResolver = MasterElector(node, _masterBroker)
    _masterResolver.on('newmaster', _connectToMaster)
  } else {
    _masterResolver = MasterFinder(node)
  }

  /**
   * Activates the node
   * @return {object} node instance
   */
  function activate () {
    if (_active) return node
    _active = true
    debug('activated')

    if (!external) {
      _masterBroker.bind()
      _masterResolver.bind()
    }
    if (!node.isReady) _seekForMaster()
    return node
  }
  /**
   * Starts the node's deactivation routine
   * @return {object} node instance
   */
  function deactivate () {
    if (!_active || _deactivating) return node
    debug('deactivating')

    if (external) {
      _active = false
      _subConnection.disconnect()
      _pubConnection.disconnect()
      node.emit('deactivated')
    } else {
      _deactivating = true
      let ensuredMaster = Promise.resolve()

      const isMaster = _subConnection.master && _subConnection.master.name === _name

      if (isMaster) {
        debug(`I'm the master node. I will try to elect another master before disconnecting.`)

        let advertiseId = `zz-zzzzzzzz-${_id}`
        ensuredMaster = _masterResolver
                        .resolve(advertiseId)
                        .then(master => {
                          debug(`successfully elected a new master: ${master.name}`)
                          try {
                            _masterBroker.signalNewMaster(master)
                          } catch (e) {
                            console.log(e)
                          }
                        })
                        .catch(() => {
                          debug(`failed to elect a new master. Disconnecting anyway.`)
                        })
      }

      ensuredMaster
      .then(() => {
        _subConnection.disconnect()
        _pubConnection.disconnect()
        _masterResolver.unbind()
        let timeout = isMaster ? 1000 : 1
        setTimeout(() => {
          debug('deactivated')
          node.emit('deactivated')
          _masterBroker.unbind()
        }, timeout)
      })
    }

    return node
  }
  /**
   * Sends a message through the bus, published on a particular channel
   * @param  {string} channel
   * @param  {array} args
   * @return {object} node instance
   */
  function publish (channel, ...args) {
    if (!isString(channel)) throw new TypeError(`${_debugStr}: .publish(channel, [...args]) channel MUST be a string`)
    if (~internalChannels.indexOf(channel)) {
      console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot publish in it`)
      return node
    }
    if (!_pubConnection.connected) {
      console.warn(`${_debugStr} cannot publish on bus.`)
      return node
    }
    _pubConnection.publish(channel, ...args)
    return node
  }
  /**
   * Subscribes the node to the provided channels
   * @param  {string|array<string>} channels
   * @return {object} node instance
   */
  function subscribe (channels) {
    if (!isArray(channels)) channels = [channels]
    if (!every(channels, isString)) throw new TypeError(`${_debugStr}: .subscribe([...channels]) channels must be represented by strings`)

    channels.forEach(channel => {
      if (~internalChannels.indexOf(channel)) {
        console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot subscribe to it.`)
        return
      }
      _subConnection.subscribe([channel])
    })
    return node
  }
  /**
   * Unsubscribes the node from the provided channels
   * @param  {string|array<string>} channels
   * @return {object} node instance
   */
  function unsubscribe (channels) {
    if (!isArray(channels)) channels = [channels]
    if (!every(channels, isString)) throw new TypeError(`${_debugStr}: .unsubscribe([channels]) channels must be represented by strings`)

    channels.forEach(channel => {
      if (~internalChannels.indexOf(channel)) {
        console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot unsubscribe from it.`)
        return
      }
      _subConnection.unsubscribe([channel])
    })
    return node
  }

  return Object.defineProperties(node, {
    id: {get: () => _id},
    name: {get: () => _name},
    settings: {get: () => ({..._settings})},
    type: {get: () => external ? EXTERNAL_NODE : DNS_NODE},
    canPublish: {get: () => _pubConnection.connected},
    isReceiving: {get: () => _subConnection.connected},
    isReady: {get: () => _pubConnection.connected && _subConnection.connected},
    subscribedChannels: {get: () => _subConnection.subscribedChannels},
    isMaster: {get: () => _master && _master.name === _name || false},
    master: {get: () => _master && {..._master, endpoints: {..._master.endpoints}}},
    activate: {value: activate},
    deactivate: {value: deactivate},
    publish: {value: publish},
    subscribe: {value: subscribe},
    unsubscribe: {value: unsubscribe}
  })
}
1142982
def get_state(self, hosts, services):
        
        # If we are a host or a service, we just got the host/service
        # hard state
        if self.operand == 'host':
            host = hosts[self.sons[0]]
            return self.get_host_node_state(host.last_hard_state_id,
                                            host.problem_has_been_acknowledged,
                                            host.in_scheduled_downtime)
        if self.operand == 'service':
            service = services[self.sons[0]]
            return self.get_service_node_state(service.last_hard_state_id,
                                               service.problem_has_been_acknowledged,
                                               service.in_scheduled_downtime)
        if self.operand == '|':
            return self.get_complex_or_node_state(hosts, services)

        if self.operand == '&':
            return self.get_complex_and_node_state(hosts, services)

        #  It's an Xof rule
        if self.operand == 'of:':
            return self.get_complex_xof_node_state(hosts, services)

        # We have an unknown node. Code is not reachable because we validate operands
        return 4
1352622
public static final Tree getNodeInfos(ServiceBroker broker, Transporter transporter) {
		Tree infos = new Tree();
		if (transporter == null) {
			infos.putObject(broker.getNodeID(), broker.getConfig().getServiceRegistry().getDescriptor());
		} else {
			Set<String> nodeIDset = transporter.getAllNodeIDs();
			String[] nodeIDarray = new String[nodeIDset.size()];
			nodeIDset.toArray(nodeIDarray);
			Arrays.sort(nodeIDarray, String.CASE_INSENSITIVE_ORDER);
			for (String nodeID : nodeIDarray) {
				Tree info = transporter.getDescriptor(nodeID);
				if (info == null) {
					continue;
				}
				infos.putObject(nodeID, info);
			}
		}
		return infos;
	}
219841
function getInstanceFromNode(node) {
  var inst = node[internalInstanceKey];
  if (inst) {
    if (inst.tag === HostComponent || inst.tag === HostText) {
      return inst;
    } else if (inst._hostNode === node) {
      return inst;
    } else {
      return null;
    }
  }
  inst = getClosestInstanceFromNode(node);
  if (inst != null && inst._hostNode === node) {
    return inst;
  } else {
    return null;
  }
}
823959
def get_network_folder(dc_ref):
    '''
    
    '''
    dc_name = get_managed_object_name(dc_ref)
    log.trace('Retrieving network folder in datacenter \'%s\'', dc_name)
    service_instance = get_service_instance_from_managed_object(dc_ref)
    traversal_spec = vmodl.query.PropertyCollector.TraversalSpec(
        path='networkFolder',
        skip=False,
        type=vim.Datacenter)
    entries = get_mors_with_properties(service_instance,
                                       vim.Folder,
                                       container_ref=dc_ref,
                                       property_list=['name'],
                                       traversal_spec=traversal_spec)
    if not entries:
        raise salt.exceptions.VMwareObjectRetrievalError(
            'Network folder in datacenter \'{0}\' wasn\'t retrieved'
            ''.format(dc_name))
    return entries[0]['object']
1260444
def nameserver(self):
        ''''''
        with self._mutex:
            if not self._parent:
                # The root node does not have a name server
                return None
            elif self._parent.name == '/':
                return self
            else:
                return self._parent.nameserver
200438
def get_node_ip_address(address="8.8.8.8:53"):
    
    ip_address, port = address.split(":")
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # This command will raise an exception if there is no internet
        # connection.
        s.connect((ip_address, int(port)))
        node_ip_address = s.getsockname()[0]
    except Exception as e:
        node_ip_address = "127.0.0.1"
        # [Errno 101] Network is unreachable
        if e.errno == 101:
            try:
                # try get node ip address from host name
                host_name = socket.getfqdn(socket.gethostname())
                node_ip_address = socket.gethostbyname(host_name)
            except Exception:
                pass
    finally:
        s.close()

    return node_ip_address