This function accept a `elasticluster.cluster.Node` class,
    connects to a node and tries to discover the kind of batch system
    installed, and some other information.
507429
def inspect_node(node):
    
    node_information = {}
    ssh = node.connect()
    if not ssh:
        log.error("Unable to connect to node %s", node.name)
        return

    (_in, _out, _err) = ssh.exec_command("(type >& /dev/null -a srun && echo slurm) \
                      || (type >& /dev/null -a qconf && echo sge) \
                      || (type >& /dev/null -a pbsnodes && echo pbs) \
                      || echo UNKNOWN")
    node_information['type'] = _out.read().strip()

    (_in, _out, _err) = ssh.exec_command("arch")
    node_information['architecture'] = _out.read().strip()

    if node_information['type'] == 'slurm':
        inspect_slurm_cluster(ssh, node_information)
    elif node_information['type'] == 'sge':
        inspect_sge_cluster(ssh, node_information)
    ssh.close()
    return node_information
592810
def add_elasticache_node(self, node, cluster, region):
        '''  '''

        # Only want available nodes unless all_elasticache_nodes is True
        if not self.all_elasticache_nodes and node['CacheNodeStatus'] != 'available':
            return

        # Select the best destination address
        dest = node['Endpoint']['Address']

        if not dest:
            # Skip nodes we cannot address (e.g. private VPC subnet)
            return

        node_id = self.to_safe(cluster['CacheClusterId'] + '_' + node['CacheNodeId'])

        # Add to index
        self.index[dest] = [region, node_id]

        # Inventory: Group by node ID (always a group of 1)
        if self.group_by_instance_id:
            self.inventory[node_id] = [dest]
            if self.nested_groups:
                self.push_group(self.inventory, 'instances', node_id)

        # Inventory: Group by region
        if self.group_by_region:
            self.push(self.inventory, region, dest)
            if self.nested_groups:
                self.push_group(self.inventory, 'regions', region)

        # Inventory: Group by availability zone
        if self.group_by_availability_zone:
            self.push(self.inventory, cluster['PreferredAvailabilityZone'], dest)
            if self.nested_groups:
                if self.group_by_region:
                    self.push_group(self.inventory, region, cluster['PreferredAvailabilityZone'])
                self.push_group(self.inventory, 'zones', cluster['PreferredAvailabilityZone'])

        # Inventory: Group by node type
        if self.group_by_instance_type:
            type_name = self.to_safe('type_' + cluster['CacheNodeType'])
            self.push(self.inventory, type_name, dest)
            if self.nested_groups:
                self.push_group(self.inventory, 'types', type_name)

        # Inventory: Group by VPC (information not available in the current
        # AWS API version for ElastiCache)

        # Inventory: Group by security group
        if self.group_by_security_group:

            # Check for the existence of the 'SecurityGroups' key and also if
            # this key has some value. When the cluster is not placed in a SG
            # the query can return None here and cause an error.
            if 'SecurityGroups' in cluster and cluster['SecurityGroups'] is not None:
                for security_group in cluster['SecurityGroups']:
                    key = self.to_safe("security_group_" + security_group['SecurityGroupId'])
                    self.push(self.inventory, key, dest)
                    if self.nested_groups:
                        self.push_group(self.inventory, 'security_groups', key)

        # Inventory: Group by engine
        if self.group_by_elasticache_engine:
            self.push(self.inventory, self.to_safe("elasticache_" + cluster['Engine']), dest)
            if self.nested_groups:
                self.push_group(self.inventory, 'elasticache_engines', self.to_safe("elasticache_" + cluster['Engine']))

        # Inventory: Group by parameter group (done at cluster level)

        # Inventory: Group by replication group (done at cluster level)

        # Inventory: Group by ElastiCache Cluster
        if self.group_by_elasticache_cluster:
            self.push(self.inventory, self.to_safe("elasticache_cluster_" + cluster['CacheClusterId']), dest)

        # Global Tag: all ElastiCache nodes
        self.push(self.inventory, 'elasticache_nodes', dest)

        host_info = self.get_host_info_dict_from_describe_dict(node)

        if dest in self.inventory["_meta"]["hostvars"]:
            self.inventory["_meta"]["hostvars"][dest].update(host_info)
        else:
            self.inventory["_meta"]["hostvars"][dest] = host_info
228491
async def inspect(self, *, node_id: str) -> Mapping[str, Any]:
        

        response = await self.docker._query_json(
            "nodes/{node_id}".format(node_id=node_id), method="GET"
        )
        return response
167813
def explore(node):
    
    explored = set()
    explored.add(node)
    dfs(node, callback=lambda n: explored.add(n))
    return explored
1214145
def discover(self):
        
        # need self.args['command'] so fail if it's not available
        if (not self.args or 'command' not in self.args or not
                self.args['command']):
            return

        # load .mlaunch_startup file for start, stop, list, use current
        # parameters for init
        if self.args['command'] == 'init':
            self.loaded_args = self.args
            self.loaded_unknown_args = self.unknown_args
        else:
            if not self._load_parameters():
                startup_file = os.path.join(self.dir, ".mlaunch_startup")
                raise SystemExit("Can't read %s, use 'mlaunch init ...' first."
                                 % startup_file)

        self.ssl_pymongo_options = self._get_ssl_pymongo_options(
            self.loaded_args)

        # reset cluster_* variables
        self.cluster_tree = {}
        self.cluster_tags = defaultdict(list)
        self.cluster_running = {}

        # get shard names
        shard_names = self._get_shard_names(self.loaded_args)

        # some shortcut variables
        is_sharded = ('sharded' in self.loaded_args and
                      self.loaded_args['sharded'] is not None)
        is_replicaset = ('replicaset' in self.loaded_args and
                         self.loaded_args['replicaset'])
        is_single = 'single' in self.loaded_args and self.loaded_args['single']
        has_arbiter = ('arbiter' in self.loaded_args and
                       self.loaded_args['arbiter'])

        # determine number of nodes to inspect
        if is_sharded:
            num_config = self.loaded_args['config']
            # at least one temp. mongos for adding shards, will be
            # killed later on
            num_mongos = max(1, self.loaded_args['mongos'])
            num_shards = len(shard_names)
        else:
            num_shards = 1
            num_config = 0
            num_mongos = 0

        num_nodes_per_shard = self.loaded_args['nodes'] if is_replicaset else 1
        if has_arbiter:
            num_nodes_per_shard += 1

        num_nodes = num_shards * num_nodes_per_shard + num_config + num_mongos

        current_port = self.loaded_args['port']

        # tag all nodes with 'all'
        self.cluster_tags['all'].extend(list(range(current_port,
                                                   current_port + num_nodes)))

        # tag all nodes with their port number (as string) and whether
        # they are running
        for port in range(current_port, current_port + num_nodes):
            self.cluster_tags[str(port)].append(port)

            running = self.is_running(port)
            self.cluster_running[port] = running
            self.cluster_tags['running' if running else 'down'].append(port)

        # find all mongos
        for i in range(num_mongos):
            port = i + current_port

            # add mongos to cluster tree
            self.cluster_tree.setdefault('mongos', []).append(port)
            # add mongos to tags
            self.cluster_tags['mongos'].append(port)

        current_port += num_mongos

        # find all mongods (sharded, replicaset or single)
        if shard_names is None:
            shard_names = [None]

        for shard in shard_names:
            port_range = list(range(current_port,
                                    current_port + num_nodes_per_shard))

            # all of these are mongod nodes
            self.cluster_tags['mongod'].extend(port_range)

            if shard:
                # if this is a shard, store in cluster_tree and tag shard name
                self.cluster_tree.setdefault('shard', []).append(port_range)
                self.cluster_tags[shard].extend(port_range)

            if is_replicaset:
                # get replica set states
                rs_name = shard if shard else self.loaded_args['name']

                try:
                    mrsc = self.client(
                        ','.join('localhost:%i' % i for i in port_range),
                        replicaSet=rs_name)

                    # primary, secondaries, arbiters
                    # @todo: this is no longer working because MongoClient
                    # is now non-blocking
                    if mrsc.primary:
                        self.cluster_tags['primary'].append(mrsc.primary[1])
                    self.cluster_tags['secondary'].extend(list(map
                                                          (itemgetter(1),
                                                           mrsc.secondaries)))
                    self.cluster_tags['arbiter'].extend(list(map(itemgetter(1),
                                                             mrsc.arbiters)))

                    # secondaries in cluster_tree (order is now important)
                    self.cluster_tree.setdefault('secondary', [])
                    for i, secondary in enumerate(sorted(map
                                                         (itemgetter(1),
                                                          mrsc.secondaries))):
                        if len(self.cluster_tree['secondary']) <= i:
                            self.cluster_tree['secondary'].append([])
                        self.cluster_tree['secondary'][i].append(secondary)

                except (ConnectionFailure, ConfigurationError):
                    pass

            elif is_single:
                self.cluster_tags['single'].append(current_port)

            # increase current_port
            current_port += num_nodes_per_shard

        # add config server to cluster tree
        self.cluster_tree.setdefault('config', []).append(port)

        # If not CSRS, set the number of config servers to be 1 or 3
        # This is needed, otherwise `mlaunch init --sharded 2 --replicaset
        # --config 2` on <3.3.0 will crash
        if not self.args.get('csrs') and self.args['command'] == 'init':
            if num_config >= 3:
                num_config = 3
            else:
                num_config = 1

        for i in range(num_config):
            port = i + current_port

            try:
                mc = self.client('localhost:%i' % port)
                mc.admin.command('ping')
                running = True

            except ConnectionFailure:
                # node not reachable
                running = False

            # add config server to cluster tree
            self.cluster_tree.setdefault('config', []).append(port)
            # add config server to tags
            self.cluster_tags['config'].append(port)
            self.cluster_tags['mongod'].append(port)

        current_port += num_mongos
107492
def get_node_by_name(self, nodename):
        
        for kind, nodes in self.nodes.items():
            for node in nodes:
                if node.name == nodename:
                    return node
        else:
            raise NodeNotFound(
                "Node `{0}` not found in cluster `{1}`"
                .format(nodename, self.name))
1216817
def list_nodes(conn=None, call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The list_nodes function must be called with -f or --function.'
        )

    if not conn:
        conn = get_conn()   # pylint: disable=E0602

    nodes = conn.list_nodes()
    ret = {}
    for node in nodes:
        ret[node.name] = {
            'id': node.id,
            'image': node.image,
            'name': node.name,
            'private_ips': node.private_ips,
            'public_ips': node.public_ips,
            'size': node.size,
            'state': node_state(node.state)
        }
    return ret
1110785
def discover_details(self):
        '''
        
        '''
        if (self.root_node == None):
            return

        if (self.verbose > 0):
            print('\nCollecting node details...')

        ni = 0
        for n in self.nodes:
            ni = ni + 1

            indicator = '+'
            if (n.snmpobj.success == 0):
                indicator = '!'

            if (self.verbose > 0):
                sys.stdout.write('[%i/%i]%s %s (%s)' % (ni, len(self.nodes), indicator, n.name, n.snmpobj._ip))
                sys.stdout.flush()

            # set what details to discover for this node
            n.opts.get_router        = True
            n.opts.get_ospf_id       = True
            n.opts.get_bgp_las       = True
            n.opts.get_hsrp_pri      = True
            n.opts.get_hsrp_vip      = True
            n.opts.get_serial        = True 
            n.opts.get_stack         = True
            n.opts.get_stack_details = self.config.diagram.get_stack_members
            n.opts.get_vss           = True
            n.opts.get_vss_details   = self.config.diagram.get_vss_members
            n.opts.get_svi           = True
            n.opts.get_lo            = True
            n.opts.get_vpc           = True
            n.opts.get_ios           = True
            n.opts.get_plat          = True

            start = timer()
            n.query_node()
            end = timer()
            if (self.verbose > 0):
                print(' %.2f sec' % (end - start))

        # There is some back fill information we can populate now that
        # we know all there is to know.
        if (self.verbose > 0):
            print('\nBack filling node details...')

        for n in self.nodes:
            # Find and link VPC nodes together for easy reference later
            if ((n.vpc_domain != None) & (n.vpc_peerlink_node == None)):
                for link in n.links:
                    if ((link.local_port == n.vpc_peerlink_if) | (link.local_lag == n.vpc_peerlink_if)):
                        n.vpc_peerlink_node         = link.node
                        link.node.vpc_peerlink_node = n
                        break
608761
def check_hardware_virtualization(self, source_node):
        

        for project in self._projects.values():
            for node in project.nodes:
                if node == source_node:
                    continue
                if node.hw_virtualization and node.__class__.__name__ != source_node.__class__.__name__:
                    return False
        return True
471483
def execute(self):
        
        creator = make_creator(self.params.config,
                               storage_path=self.params.storage)
        cluster_name = self.params.cluster
        try:
            cluster = creator.load_cluster(cluster_name)
            if self.params.update:
                cluster.update()
        except (ClusterNotFound, ConfigurationError) as ex:
            log.error("Listing nodes from cluster %s: %s", cluster_name, ex)
            return

        if self.params.pretty_json:
            print(json.dumps(cluster, default=dict, indent=4))
        elif self.params.json:
            print(json.dumps(cluster, default=dict))
        else:
            print(cluster_summary(cluster))
            for cls in cluster.nodes:
                print("%s nodes:" % cls)
                print("")
                for node in cluster.nodes[cls]:
                    txt = ["    " + i for i in node.pprint().splitlines()]
                    print('  - ' + "\n".join(txt)[4:])
                    print("")
328043
def node_stats(self, nodes=None):
        
        parts = ["_cluster", "nodes", "stats"]
        if nodes:
            parts = ["_cluster", "nodes", ",".join(nodes), "stats"]

        path = make_path(*parts)
        return self.conn._send_request('GET', path)
1079232
private void joinCluster() throws InterruptedException, IOException {
        while (true) {
            NodeInfo myInfo;
            try {
                myInfo = new NodeInfo(NodeState.Fresh.toString(), zk.get().getSessionId());
            } catch (ZooKeeperConnectionException e) {
                throw ZKException.from(e);
            }
            byte[] encoded = JsonUtil.asJSONBytes(myInfo);
            if (ZKUtils.createEphemeral(zk, "/" + name + "/nodes/" + myNodeID, encoded)) {
                return;
            } else {
                Stat stat = new Stat();
                try {
                    byte[] bytes = zk.get().getData("/" + name + "/nodes/" + myNodeID, false, stat);
                    NodeInfo nodeInfo = JsonUtil.fromJSON(bytes, NodeInfo.class);
                    if(nodeInfo.connectionID == zk.get().getSessionId()) {
                        // As it turns out, our session is already registered!
                        return;
                    }
                } catch (ZooKeeperConnectionException e) {
                    throw ZKException.from(e);
                } catch (KeeperException e) {
                    throw ZKException.from(e);
                }
            }
            LOG.warn("Unable to register with Zookeeper on launch. " +
                    "Is {} already running on this host? Retrying in 1 second...", name);
            Thread.sleep(1000);
        }
    }
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
752951
public void locateCluster(String cluster, Handler<AsyncResult<String>> doneHandler) {
    Set<String> registry = vertx.sharedData().getSet(cluster);
    synchronized (registry) {
      if (!registry.isEmpty()) {
        locateNode(cluster, new HashSet<>(registry), doneHandler);
      }
    }
  }
389534
public void doAddNodes() {
    if (log.isDebugEnabled()) {
      log.debug("Node discovery running...");
    }
    Set<CassandraHost> foundHosts = discoverNodes();
    if (foundHosts != null && foundHosts.size() > 0) {
      log.info("Found {} new host(s) in Ring", foundHosts.size());
      for (CassandraHost cassandraHost : foundHosts) {
        log.info("Addding found host {} to pool", cassandraHost);
        cassandraHostConfigurator.applyConfig(cassandraHost);
        connectionManager.addCassandraHost(cassandraHost);
      }
    }
    if (log.isDebugEnabled()) {
      log.debug("Node discovery run complete.");
    }
  }
79554
def kube_node_status_network_unavailable(self, metric, scraper_config):
        
        service_check_name = scraper_config['namespace'] + '.node.network_unavailable'
        for sample in metric.samples:
            node_tag = self._label_to_tag("node", sample[self.SAMPLE_LABELS], scraper_config)
            self._condition_to_service_check(
                sample,
                service_check_name,
                self.condition_to_status_negative,
                tags=[node_tag] + scraper_config['custom_tags'],
            )
1241282
private void doNodeJoined(final Node node) {
    tasks.runTask(new Handler<Task>() {
      @Override
      public void handle(final Task task) {
        if (currentContext != null) {
          log.info(String.format("%s - %s joined the cluster. Uploading components to new node", NetworkManager.this, node.address()));
          installModules(node, currentContext, new Handler<AsyncResult<Void>>() {
            @Override
            public void handle(AsyncResult<Void> result) {
              if (result.failed()) {
                log.error(result.cause());
              } else {
                log.info(String.format("%s - Successfully uploaded components to %s", NetworkManager.this, node.address()));
              }
              task.complete();
            }
          });
        } else {
          task.complete();
        }
      }
    });
  }