get the mapping between token->node ip
    without taking replication into consideration
    https://issues.apache.org/jira/browse/CASSANDRA-4092
8000
def describe_token_map(self, ):
    
    self._seqid += 1
    d = self._reqs[self._seqid] = defer.Deferred()
    self.send_describe_token_map()
    return d
599110
def get_client_ip(request):
    
    # set the default value of the ip to be the REMOTE_ADDR if available
    # else None
    ip = request.META.get('REMOTE_ADDR')
    # try to get the first non-proxy ip (not a private ip) from the
    # HTTP_X_FORWARDED_FOR
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        proxies = x_forwarded_for.split(',')
        # remove the private ips from the beginning
        proxies = [proxy for proxy in proxies
                   if not proxy.startswith(settings.PRIVATE_IPS_PREFIX)]
        # take the first ip which is not a private one (of a proxy)
        if len(proxies) > 0:
            ip = proxies[0]

    return ip
67003
def get_account_tokens(address, hostport=None, proxy=None):
    
    assert proxy or hostport, 'Need proxy or hostport'
    if proxy is None:
        proxy = connect_hostport(hostport)

    tokens_schema = {
        'type': 'object',
        'properties': {
            'token_types': {
                'type': 'array',
                'pattern': '^(.+){1,19}',
            },
        },
        'required': [
            'token_types',
        ]
    }

    schema = json_response_schema(tokens_schema)

    try:
        resp = proxy.get_account_tokens(address)
        resp = json_validate(schema, resp)
        if json_is_error(resp):
            return resp

    except ValidationError as ve:
        if BLOCKSTACK_DEBUG:
            log.exception(ve)

        resp = {'error': 'Server response did not match expected schema.  You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
        return resp

    except socket.timeout:
        log.error("Connection timed out")
        resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
        return resp

    except socket.error as se:
        log.error("Connection error {}".format(se.errno))
        resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
        return resp

    except AssertionError as ae:
        if BLOCKSTACK_DEBUG:
            log.exception(ae)

        resp = json_traceback(resp.get('error'))
        return resp

    except Exception as ee:
        if BLOCKSTACK_DEBUG:
            log.exception(ee)

        log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
        resp = {'error': 'Failed to contact Blockstack node.  Try again with `--debug`.', 'http_status': 500}
        return resp

    resp['token_types'].sort()
    return resp['token_types']
1107620
def getSlaveStatus(self):
        
        info_dict = {}
        if self.checkVersion('9.1'):
            cols = ['procpid', 'usename', 'application_name', 
                    'client_addr', 'client_port', 'backend_start', 'state', 
                    'sent_location', 'write_location', 'flush_location', 
                    'replay_location', 'sync_priority', 'sync_state',]
            cur = self._conn.cursor()
            cur.execute("""SELECT %s FROM pg_stat_replication;""" 
                        % ','.join(cols))
            rows = cur.fetchall()
            for row in rows:
                info_dict[row[0]] = dict(zip(cols[1:], row[1:]))
        else:
            return None
        return info_dict
128324
def reformat_node(item=None, full=False):
    '''
    
    '''
    desired_keys = [
        'id', 'name', 'state', 'public_ips', 'private_ips', 'size', 'image',
        'location'
    ]
    item['private_ips'] = []
    item['public_ips'] = []
    if 'ips' in item:
        for ip in item['ips']:
            if salt.utils.cloud.is_public_ip(ip):
                item['public_ips'].append(ip)
            else:
                item['private_ips'].append(ip)

    # add any undefined desired keys
    for key in desired_keys:
        if key not in item:
            item[key] = None

    # remove all the extra key value pairs to provide a brief listing
    to_del = []
    if not full:
        for key in six.iterkeys(item):  # iterate over a copy of the keys
            if key not in desired_keys:
                to_del.append(key)

    for key in to_del:
        del item[key]

    if 'state' in item:
        item['state'] = joyent_node_state(item['state'])

    return item
80639
def get_jid(jid):
    '''
    
    '''
    query = '''SELECT minion_id, full_ret FROM {keyspace}.salt_returns
               WHERE jid = ?;'''.format(keyspace=_get_keyspace())

    ret = {}

    # cassandra_cql.cql_query may raise a CommandExecutionError
    try:
        data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_jid', [jid])
        if data:
            for row in data:
                minion = row.get('minion_id')
                full_ret = row.get('full_ret')
                if minion and full_ret:
                    ret[minion] = salt.utils.json.loads(full_ret)
    except CommandExecutionError:
        log.critical('Could not select job specific information.')
        raise
    except Exception as e:
        log.critical(
            'Unexpected error while getting job specific information: %s', e)
        raise

    return ret
1061617
def get_jids():
    '''
    
    '''
    query = '''SELECT jid, load FROM {keyspace}.jids;'''.format(keyspace=_get_keyspace())

    ret = {}

    # cassandra_cql.cql_query may raise a CommandExecutionError
    try:
        data = __salt__['cassandra_cql.cql_query'](query)
        if data:
            for row in data:
                jid = row.get('jid')
                load = row.get('load')
                if jid and load:
                    ret[jid] = salt.utils.jid.format_jid_instance(
                        jid,
                        salt.utils.json.loads(load))
    except CommandExecutionError:
        log.critical('Could not get a list of all job ids.')
        raise
    except Exception as e:
        log.critical(
            'Unexpected error while getting list of all job ids: %s', e)
        raise

    return ret
20918
def get_namespace_record(namespace_id, proxy=None, hostport=None):
    

    assert proxy or hostport, 'Need either proxy handle or hostport string'
    if proxy is None:
        proxy = connect_hostport(hostport)
    
    namespace_schema = {
        'type': 'object',
        'properties': NAMESPACE_SCHEMA_PROPERTIES,
        'required': NAMESPACE_SCHEMA_REQUIRED
    }

    rec_schema = {
        'type': 'object',
        'properties': {
            'record': namespace_schema,
        },
        'required': [
            'record',
        ],
    }

    resp_schema = json_response_schema( rec_schema )
            
    ret = {}
    try:
        ret = proxy.get_namespace_blockchain_record(namespace_id)
        ret = json_validate(resp_schema, ret)
        if json_is_error(ret):
            return ret

        ret = ret['record']

        # this isn't needed
        ret.pop('opcode', None)

    except socket.timeout:
        log.error("Connection timed out")
        resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
        return resp

    except socket.error as se:
        log.error("Connection error {}".format(se.errno))
        resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
        return resp

    except ValidationError as e:
        if BLOCKSTACK_DEBUG:
            log.exception(e)

        resp = {'error': 'Server response did not match expected schema.  You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
        return resp

    except Exception as ee:
        if BLOCKSTACK_DEBUG:
            log.exception(ee)

        log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
        resp = {'error': 'Failed to contact Blockstack node.  Try again with `--debug`.', 'http_status': 500}
        return resp

    return ret
803892
private Block getBlockInfo(LocatedBlock locatedblock) throws IOException {
    if (locatedblock == null || locatedblock.getLocations().length == 0) {
      return null;
    }
    int replicaNotFoundCount = locatedblock.getLocations().length;

    for(DatanodeInfo datanode : locatedblock.getLocations()) {
      ProtocolProxy<ClientDatanodeProtocol> cdp = null;

      try {
        cdp = DFSClient.createClientDNProtocolProxy(datanode,
            dfsClient.conf, dfsClient.socketTimeout);

        final Block newBlock;
        if (cdp.isMethodSupported("getBlockInfo", int.class, Block.class)) {
          newBlock = cdp.getProxy().getBlockInfo(
              dfsClient.namespaceId, locatedblock.getBlock());
        } else {
          newBlock = cdp.getProxy().getBlockInfo(locatedblock.getBlock());
        }

        if (newBlock == null) {
          // special case : replica might not be on the DN, treat as 0 length
          replicaNotFoundCount--;
        } else {
          return newBlock;
        }
      }
      catch(IOException ioe) {
        if (DFSClient.LOG.isDebugEnabled()) {
          DFSClient.LOG.debug("Failed to getBlockInfo from datanode "
              + datanode + " for block " + locatedblock.getBlock(), ioe);
        }
      } finally {
        if (cdp != null) {
          RPC.stopProxy(cdp.getProxy());
        }
      }
    }

    // Namenode told us about these locations, but none know about the replica
    // means that we hit the race between pipeline creation start and end.
    // we require all because some other exception could have happened
    // on a DN that has it.  we want to report that error
    if (replicaNotFoundCount == 0) {
      DFSClient.LOG
          .warn("Cannot get block info from any datanode having block "
              + locatedblock.getBlock() + " for file " + src);
      return null;
    }

    throw new IOException("Cannot obtain block info for " + locatedblock);
  }
392933
public InetAddress replicaNodeForId(final String id, int replicaNum) {
        if (replicaNum < 1 || replicaNum > 3) {
            throw new IllegalArgumentException("Replica number must be between 1 and 3.");
        }

        BucketConfig config = bucketConfig.get();

        if (config instanceof CouchbaseBucketConfig) {
            CouchbaseBucketConfig cbc = (CouchbaseBucketConfig) config;
            int partitionId = (int) hashId(id) & cbc.numberOfPartitions() - 1;
            int nodeId = cbc.nodeIndexForReplica(partitionId, replicaNum - 1, false);
            if (nodeId == -1) {
                throw new IllegalStateException("No partition assigned to node for Document ID: " + id);
            }
            if (nodeId == -2) {
                throw new IllegalStateException("Replica not configured for this bucket.");
            }
            try {
                return InetAddress.getByName(cbc.nodeAtIndex(nodeId).hostname().address());
            } catch (UnknownHostException e) {
                throw new IllegalStateException(e);
            }
        }  else {
            throw new UnsupportedOperationException("Bucket type not supported: " + config.getClass().getName());
        }
    }
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))
896947
public int getNodeIdForZoneNary(int zoneId, int zoneNary, byte[] key) {
        List<Node> replicatingNodes = this.routingStrategy.routeRequest(key);
        int zoneNAry = -1;
        for(Node node: replicatingNodes) {
            // bump up the counter if we encounter a replica in the given zone;
            // return current node if counter now matches requested
            if(node.getZoneId() == zoneId) {
                zoneNAry++;

                if(zoneNAry == zoneNary) {
                    return node.getId();
                }
            }
        }
        if(zoneNAry == -1) {
            throw new VoldemortException("Could not find any replicas for the key "
                                         + ByteUtils.toHexString(key) + " in given zone " + zoneId);
        } else {
            throw new VoldemortException("Could not find " + (zoneNary + 1)
                                         + " replicas for the key " + ByteUtils.toHexString(key)
                                         + " in given zone " + zoneId + ". Only found "
                                         + (zoneNAry + 1));
        }
    }
513404
def get_client_ip(request):
    
    try:
        return request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip()
    except (KeyError, IndexError):
        return request.META.get('REMOTE_ADDR')
749036
def __get_known_node(self, ip, host):
        '''
        
        '''
        # already known by IP ?
        for ex in self.nodes:
            for exip in ex.ip:
                if (exip == '0.0.0.0'):
                    continue
                if (exip == ip):
                    return (ex, 0)

        # already known by HOST ?
        node = self.__get_known_node_by_host(host)
        if (node != None):
            # node already known
            if (ip not in node.ip):
                node.ip.append(ip)
                return (node, 1)
            return (node, 0)

        return (None, 0)
405141
public static Map<InetAddress, Map<String,String>> loadDcRackInfo()
    {
        Map<InetAddress, Map<String, String>> result = new HashMap<InetAddress, Map<String, String>>();
        for (UntypedResultSet.Row row : executeInternal("SELECT peer, data_center, rack from system." + PEERS_CF))
        {
            InetAddress peer = row.getInetAddress("peer");
            if (row.has("data_center") && row.has("rack"))
            {
                Map<String, String> dcRack = new HashMap<String, String>();
                dcRack.put("data_center", row.getString("data_center"));
                dcRack.put("rack", row.getString("rack"));
                result.put(peer, dcRack);
            }
        }
        return result;
    }
17882
def _get_cassandra_config(self):
        """"""
        parts = urlsplit(os.environ.get('CASSANDRA_URI', DEFAULT_URI))
        if parts.scheme != 'cassandra':
            raise RuntimeError(
                'CASSANDRA_URI scheme is not "cassandra://"!')

        _, _, ip_addresses = socket.gethostbyname_ex(parts.hostname)
        if not ip_addresses:
            raise RuntimeError('Unable to find Cassandra in DNS!')

        return {
            'contact_points': ip_addresses,
            'port': parts.port or DEFAULT_PORT,
        }
614351
def _registerNode(self, nodeAddress, agentId, nodePort=5051):
        
        executor = self.executors.get(nodeAddress)
        if executor is None or executor.agentId != agentId:
            executor = self.ExecutorInfo(nodeAddress=nodeAddress,
                                         agentId=agentId,
                                         nodeInfo=None,
                                         lastSeen=time.time())
            self.executors[nodeAddress] = executor
        else:
            executor.lastSeen = time.time()
            
        # Record the IP under the agent id
        self.agentsByID[agentId] = nodeAddress
            
        return executor