How many peers are there in the db?
192576
def atlasdb_num_peers( con=None, path=None ):
    
    with AtlasDBOpen(con=con, path=path) as dbcon:

        sql = "SELECT MAX(peer_index) FROM peers;"
        args = ()

        cur = dbcon.cursor()
        res = atlasdb_query_execute( cur, sql, args )

        ret = []
        for row in res:
            tmp = {}
            tmp.update(row)
            ret.append(tmp)

        assert len(ret) == 1

    return ret[0]['MAX(peer_index)']
1182385
def update_existing_peers( self, num_to_remove, peer_table=None, con=None, path=None ):
        
        
        if path is None:
            path = self.atlasdb_path

        # remove peers that are too old
        if self.last_clean_time + atlas_peer_clean_interval() < time_now():
            # remove stale peers
            log.debug("%s: revalidate old peers" % self.my_hostport)
            atlas_revalidate_peers( con=con, path=path, peer_table=peer_table )
            self.last_clean_time = time_now()

        removed = self.remove_unhealthy_peers( num_to_remove, con=con, path=path, peer_table=peer_table )

        # if they're also in the new set, remove them there too
        for peer in removed:
            if peer in self.new_peers:
                self.new_peers.remove(peer)

        return len(removed)
787438
def add_new_peers( self, count, new_peers, current_peers, con=None, path=None, peer_table=None ):
        

        if self.ping_timeout is None:
            self.ping_timeout = atlas_ping_timeout()
 
        if path is None:
            path = self.atlasdb_path

        # only handle a few peers for now
        cnt = 0
        i = 0
        added = []
        present = []
        filtered = []
        while i < len(new_peers) and cnt < min(count, len(new_peers)):
            peer = self.canonical_peer( new_peers[i] )
            i += 1

            if peer == self.my_hostport:
                filtered.append(peer)
                continue

            if peer in current_peers:
                log.debug("%s is already known" % peer)
                present.append(peer)
                continue 

            cnt += 1

            # test the peer before adding
            res = atlas_peer_getinfo( peer, timeout=self.ping_timeout, peer_table=peer_table )
            if res is None:
                # didn't respond successfully
                filtered.append(peer)
                continue

            if not res.has_key('server_version'):
                # too old.  TODO: ban them
                filtered.append(peer)
                continue

            if (BLOCKSTACK_PUBLIC_TESTNET and res['server_version'] != MIN_ATLAS_VERSION) or (not BLOCKSTACK_PUBLIC_TESTNET and semver_newer(res['server_version'], MIN_ATLAS_VERSION)):
                # mainnet: too old to be a valid atlas node for this network version
                # testnet: not the same version == don't connect
                filtered.append(peer)
                log.debug("%s is too old to be an atlas node (version %s)" % (peer, res['server_version']))

                # TODO: ban them
                continue
            
            # advance our consensus hashes
            our_last_block = get_last_block(self.working_dir)
            if not self.consensus_hashes.has_key(our_last_block):
                cur_last_block = max(self.consensus_hashes.keys())
                new_consensus_hashes = get_snapshots(self.working_dir, start_block=cur_last_block, end_block=our_last_block+1)
                self.consensus_hashes.update(new_consensus_hashes)

            if self.consensus_hashes.has_key(our_last_block):

                their_last_block = res['last_block_processed']
                if their_last_block <= our_last_block and res['consensus'] not in self.consensus_hashes.values():
                    # on different consensus rules than us
                    log.debug("Peer {} has ({},{}), but we have ({},{}). Ignoring.".format(peer, their_last_block, res['consensus'], our_last_block, self.consensus_hashes[our_last_block]))

                    # TODO: drop them from the peer table, and don't reconnect with them for a while.
                    continue

            if res:
                log.debug("Add newly-discovered peer %s" % peer)
                atlasdb_add_peer( peer, con=con, path=path, peer_table=peer_table )
                added.append(peer)
            else:
                filtered.append(peer)

        return added, present, filtered
1150179
def get_peers(self):
        
        node = NodeLeader.Instance()
        result = {"connected": [], "unconnected": [], "bad": []}
        connected_peers = []

        for peer in node.Peers:
            result['connected'].append({"address": peer.host,
                                        "port": peer.port})
            connected_peers.append("{}:{}".format(peer.host, peer.port))

        for addr in node.DEAD_ADDRS:
            host, port = addr.rsplit(':', 1)
            result['bad'].append({"address": host, "port": port})

        # "UnconnectedPeers" is never used. So a check is needed to
        # verify that a given address:port does not belong to a connected peer
        for addr in node.KNOWN_ADDRS:
            host, port = addr.rsplit(':', 1)
            if addr not in connected_peers:
                result['unconnected'].append({"address": host,
                                              "port": int(port)})

        return result
536645
def peer_store(key, value, relation_name='cluster'):
    """"""
    cluster_rels = relation_ids(relation_name)
    if len(cluster_rels) > 0:
        cluster_rid = cluster_rels[0]
        relation_set(relation_id=cluster_rid,
                     relation_settings={key: value})
    else:
        raise ValueError('Unable to detect '
                         'peer relation {}'.format(relation_name))
736355
def get_limits(self):
        
        if self.limits != {}:
            return self.limits
        limits = {}
        limits['DB instances'] = AwsLimit(
            'DB instances',
            self,
            40,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::RDS::DBInstance'
        )
        limits['Reserved Instances'] = AwsLimit(
            'Reserved Instances',
            self,
            40,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::RDS::DBInstance',
        )
        limits['Storage quota (GB)'] = AwsLimit(
            'Storage quota (GB)',
            self,
            100000,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::RDS::DBInstance',
        )
        limits['DB snapshots per user'] = AwsLimit(
            'DB snapshots per user',
            self,
            100,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::RDS::DBSnapshot',
        )
        limits['DB parameter groups'] = AwsLimit(
            'DB parameter groups',
            self,
            50,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::RDS::DBParameterGroup',
        )
        limits['DB security groups'] = AwsLimit(
            'DB security groups',
            self,
            25,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::RDS::DBSecurityGroup',
        )
        limits['VPC Security Groups'] = AwsLimit(
            'VPC Security Groups',
            self,
            5,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::RDS::DBSecurityGroup',
        )
        limits['Subnet Groups'] = AwsLimit(
            'Subnet Groups',
            self,
            50,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::RDS::DBSubnetGroup',
            ta_limit_name='Subnet groups'
        )
        limits['Subnets per Subnet Group'] = AwsLimit(
            'Subnets per Subnet Group',
            self,
            20,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::RDS::DBSubnetGroup',
            ta_limit_name='Subnets per subnet group'
        )
        limits['Option Groups'] = AwsLimit(
            'Option Groups',
            self,
            20,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::RDS::DBOptionGroup',
        )
        limits['Event Subscriptions'] = AwsLimit(
            'Event Subscriptions',
            self,
            20,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::RDS::DBEventSubscription',
            ta_limit_name='Event subscriptions'
        )
        limits['Read replicas per master'] = AwsLimit(
            'Read replicas per master',
            self,
            5,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::RDS::DBInstance',
        )
        # this is the number of rules per security group
        limits['Max auths per security group'] = AwsLimit(
            'Max auths per security group',
            self,
            20,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::RDS::DBSecurityGroup',
            limit_subtype='AWS::RDS::DBSecurityGroupIngress',
        )
        limits['DB Clusters'] = AwsLimit(
            'DB Clusters',
            self,
            40,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::RDS::DBCluster',
            ta_limit_name='Clusters'
        )
        limits['DB Cluster Parameter Groups'] = AwsLimit(
            'DB Cluster Parameter Groups',
            self,
            50,
            self.warning_threshold,
            self.critical_threshold,
            limit_type='AWS::RDS::DBClusterParameterGroup',
            ta_limit_name='Cluster parameter groups'
        )
        self.limits = limits
        return limits
1203412
def peers(cls):
        """"""
        contentType = ContentType.objects.get_for_model(cls)
        return cls.objects.filter(content_type=contentType)
1053805
public void peers(List<TcpEndpoint> value) {
        tcp_endpoint_vector v = new tcp_endpoint_vector();

        for (TcpEndpoint endp : value) {
            v.push_back(endp.swig());
        }

        p.set_peers(v);
    }
1263489
async def count(self, query, clear_limit=False):
        
        query = self._swap_database(query)
        return (await count(query, clear_limit=clear_limit))
1148316
def manageConnections(classifiedPeers)

      n = classifiedPeers.handshakingPeers.size + classifiedPeers.establishedPeers.size
      if n < @targetActivePeerCount
        result = classifiedPeers.disconnectedPeers.shuffle.first(@targetActivePeerCount - n)
        @logger.debug "There are #{n} peers connected or in handshaking. Will establish #{result.size} more connections to peers."
        result
      else
        []
      end
    end
1098920
def atlas_zonefile_find_push_peers( zonefile_hash, peer_table=None, zonefile_bits=None, con=None, path=None ):
    

    if zonefile_bits is None:
        zonefile_bits = atlasdb_get_zonefile_bits( zonefile_hash, path=path, con=con )
        if len(zonefile_bits) == 0:
            # we don't even know about it
            return []

    push_peers = []
    
    with AtlasPeerTableLocked(peer_table) as ptbl:
        for peer_hostport in ptbl.keys():
            zonefile_inv = atlas_peer_get_zonefile_inventory( peer_hostport, peer_table=ptbl )
            res = atlas_inventory_test_zonefile_bits( zonefile_inv, zonefile_bits )
            if res:
                push_peers.append( peer_hostport )

    return push_peers
887625
def get_connection_count(self, is_full: bool = False) -> int:
        
        payload = self.generate_json_rpc_payload(RpcMethod.GET_NODE_COUNT)
        response = self.__post(self.__url, payload)
        if is_full:
            return response
        return response['result']
195523
def peer_relation_id():
    ''''''
    md = metadata()
    section = md.get('peers')
    if section:
        for key in section:
            relids = relation_ids(key)
            if relids:
                return relids[0]
    return None
966840
@ObjectiveCName("findPeersWithQuery:")
    public Command<List<PeerSearchEntity>> findPeers(String query) {
        return callback -> modules.getSearchModule().findPeers(query)
                .then(v -> callback.onResult(v))
                .failure(e -> callback.onError(e));
    }
861964
def atlasdb_load_peer_table( con=None, path=None ):
    
    peer_table = {}
    
    with AtlasDBOpen(con=con, path=path) as dbcon:

        sql = "SELECT * FROM peers;"
        args = ()

        cur = dbcon.cursor()
        res = atlasdb_query_execute( cur, sql, args )

        # build it up 
        count = 0
        for row in res:
           if count > 0 and count % 100 == 0:
               log.debug("Loaded %s peers..." % count)

           atlas_init_peer_info( peer_table, row['peer_hostport'] )
           count += 1

    return peer_table
847297
def atlas_get_peer( peer_hostport, peer_table=None ):
    

    ret = None
    with AtlasPeerTableLocked(peer_table) as ptbl:
        ret = ptbl.get(peer_hostport, None)

    return ret
197100
protected int discoverPeers() {
        // Don't hold the lock whilst doing peer discovery: it can take a long time and cause high API latency.
        checkState(!lock.isHeldByCurrentThread());
        int maxPeersToDiscoverCount = this.vMaxPeersToDiscoverCount;
        long peerDiscoveryTimeoutMillis = this.vPeerDiscoveryTimeoutMillis;
        final Stopwatch watch = Stopwatch.createStarted();
        final List<PeerAddress> addressList = Lists.newLinkedList();
        for (PeerDiscovery peerDiscovery : peerDiscoverers /* COW */) {
            InetSocketAddress[] addresses;
            try {
                addresses = peerDiscovery.getPeers(requiredServices, peerDiscoveryTimeoutMillis, TimeUnit.MILLISECONDS);
            } catch (PeerDiscoveryException e) {
                log.warn(e.getMessage());
                continue;
            }
            for (InetSocketAddress address : addresses) addressList.add(new PeerAddress(params, address));
            if (addressList.size() >= maxPeersToDiscoverCount) break;
        }
        if (!addressList.isEmpty()) {
            for (PeerAddress address : addressList) {
                addInactive(address);
            }
            final ImmutableSet<PeerAddress> peersDiscoveredSet = ImmutableSet.copyOf(addressList);
            for (final ListenerRegistration<PeerDiscoveredEventListener> registration : peerDiscoveredEventListeners /* COW */) {
                registration.executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        registration.listener.onPeersDiscovered(peersDiscoveredSet);
                    }
                });
            }
        }
        watch.stop();
        log.info("Peer discovery took {} and returned {} items", watch, addressList.size());
        return addressList.size();
    }