Get peers older than now - PEER_LIFETIME
424590
def atlasdb_get_old_peers( now, con=None, path=None ):
    
    with AtlasDBOpen(con=con, path=path) as dbcon:

        if now is None:
            now = time.time()

        expire = now - atlas_peer_max_age()
        sql = "SELECT * FROM peers WHERE discovery_time < ?";
        args = (expire,)

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

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

    return rows
282144
def peers(self):
        ""
        return [addr for (addr, peer) in self._dispatcher.peers.items()
                if peer.up]
397572
def get_oldest_commit(self):
        '''
        
        '''
        return self.git.get_commits(self.content.source_path, self.follow)[-1]
823839
def step(self, con=None, path=None, peer_table=None, local_inv=None):
        
        if path is None:
            path = self.atlasdb_path

        peer_hostports = []
        stale_peers = []

        num_peers = None
        peer_hostports = None

        with AtlasPeerTableLocked(peer_table) as ptbl:
            num_peers = len(ptbl.keys())
            peer_hostports = ptbl.keys()[:]

            # who are we going to ping?
            # someone we haven't pinged in a while, chosen at random
            for peer in peer_hostports:
                if not atlas_peer_has_fresh_zonefile_inventory( peer, peer_table=ptbl ):
                    # haven't talked to this peer in a while
                    stale_peers.append(peer)
                    log.debug("Peer %s has a stale zonefile inventory" % peer)

        if len(stale_peers) > 0:
            log.debug("Refresh zonefile inventories for %s peers" % len(stale_peers))

        for peer_hostport in stale_peers:
            # refresh everyone
            log.debug("%s: Refresh zonefile inventory for %s" % (self.hostport, peer_hostport))
            res = atlas_peer_refresh_zonefile_inventory( self.hostport, peer_hostport, 0, con=con, path=path, peer_table=peer_table, local_inv=local_inv )
            if res is None:
                log.warning("Failed to refresh zonefile inventory for %s" % peer_hostport)
        
        return
286761
def query_by_expired(cls):
        """"""
        lifetime = current_app.permanent_session_lifetime
        expired_moment = datetime.utcnow() - lifetime
        return cls.query.filter(cls.created < expired_moment)
1212196
def retrieveVals(self):
        """"""
        ntpinfo = NTPinfo()
        stats = ntpinfo.getPeerStats()
        if stats:
            if self.hasGraph('ntp_peer_stratum'):
                self.setGraphVal('ntp_peer_stratum', 'stratum', 
                                 stats.get('stratum'))
            if self.hasGraph('ntp_peer_stats'):
                self.setGraphVal('ntp_peer_stats', 'offset', 
                                 stats.get('offset'))
                self.setGraphVal('ntp_peer_stats', 'delay', 
                                 stats.get('delay'))
                self.setGraphVal('ntp_peer_stats', 'jitter', 
                                 stats.get('jitter'))
917025
def refresh_peers(node, &block)
      node.peers.each do |node|
        if node.address.resolved
          block.call(node) unless seeds.include?(node)
          peers.push(node) unless peers.include?(node)
        end
      end
    end
39589
def getPeers(self):
        '''
            
        '''
        parentNode = self.parentNode
        # If no parent, no peers
        if not parentNode:
            return None

        peers = parentNode.children

        # Otherwise, get all children of parent excluding this node
        return TagCollection([peer for peer in peers if peer is not self])
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
44823
def get_neighbors( self, peer_hostport, con=None, path=None, peer_table=None ):
        
        if path is None:
            path = self.atlasdb_path

        if self.neighbors_timeout is None:
            self.neighbors_timeout = atlas_neighbors_timeout()
 
        peer_hostport = self.canonical_peer( peer_hostport )

        neighbors = None
        if peer_hostport == self.my_hostport:
            neighbors = atlas_get_live_neighbors( None, peer_table=peer_table ) 
        else:
            neighbors = atlas_peer_get_neighbors( self.my_hostport, peer_hostport, timeout=self.neighbors_timeout, peer_table=peer_table, path=path, con=con )

        if neighbors is not None:
            log.debug("%s: neighbors of %s are (%s): %s" % (self.my_hostport, peer_hostport, len(neighbors), ",".join(neighbors)))
        else:
            log.error("%s: failed to ask %s for neighbors" % (self.my_hostport, peer_hostport))

        return neighbors
1107979
def peer_header_value(self, peer, name):
        
        return return_fresh_string(lib.zyre_peer_header_value(self._as_parameter_, peer, name))
474804
def atlas_revalidate_peers( con=None, path=None, now=None, peer_table=None ):
    
    global MIN_PEER_HEALTH

    if now is None:
        now = time_now()

    old_peer_infos = atlasdb_get_old_peers( now, con=con, path=path )
    for old_peer_info in old_peer_infos:
        res = atlas_peer_getinfo( old_peer_info['peer_hostport'] )
        if not res:
            log.debug("Failed to revalidate %s" % (old_peer_info['peer_hostport']))
            if atlas_peer_is_whitelisted( old_peer_info['peer_hostport'], peer_table=peer_table ):
                continue

            if atlas_peer_is_blacklisted( old_peer_info['peer_hostport'], peer_table=peer_table ):
                continue

            if atlas_peer_get_health( old_peer_info['peer_hostport'], peer_table=peer_table ) < MIN_PEER_HEALTH:
                atlasdb_remove_peer( old_peer_info['peer_hostport'], con=con, path=path, peer_table=peer_table )
        
        else:
            # renew 
            atlasdb_renew_peer( old_peer_info['peer_hostport'], now, con=con, path=path )

    return True
10322
def GetNonExpiredApprovers(self):
    """"""

    lifetime = rdfvalue.Duration(
        self.Get(self.Schema.LIFETIME) or config.CONFIG["ACL.token_expiry"])

    # Check that there are enough approvers.
    #
    # TODO(user): approvals have to be opened with
    # age=aff4.ALL_TIMES because versioning is used to store lists
    # of approvers. This doesn't seem right and has to be fixed.
    approvers = set()
    now = rdfvalue.RDFDatetime.Now()
    for approver in self.GetValuesForAttribute(self.Schema.APPROVER):
      if approver.age + lifetime > now:
        approvers.add(utils.SmartStr(approver))

    return list(approvers)
339972
def get_friends(self, limit=50, cacheable=False):
        

        seq = []
        for node in _collect_nodes(
            limit, self, self.ws_prefix + ".getFriends", cacheable
        ):
            seq.append(User(_extract(node, "name"), self.network))

        return seq
139487
private void syncInstancesIfTimestampDiffers(String appName, String id, InstanceInfo info, InstanceInfo infoFromPeer) {
        try {
            if (infoFromPeer != null) {
                logger.warn("Peer wants us to take the instance information from it, since the timestamp differs,"
                        + "Id : {} My Timestamp : {}, Peer's timestamp: {}", id, info.getLastDirtyTimestamp(), infoFromPeer.getLastDirtyTimestamp());

                if (infoFromPeer.getOverriddenStatus() != null && !InstanceStatus.UNKNOWN.equals(infoFromPeer.getOverriddenStatus())) {
                    logger.warn("Overridden Status info -id {}, mine {}, peer's {}", id, info.getOverriddenStatus(), infoFromPeer.getOverriddenStatus());
                    registry.storeOverriddenStatusIfRequired(appName, id, infoFromPeer.getOverriddenStatus());
                }
                registry.register(infoFromPeer, true);
            }
        } catch (Throwable e) {
            logger.warn("Exception when trying to set information from peer :", e);
        }
    }
1019244
function getOnLinePeers()
{
	var arrOnlinePeers = [];
	function compare(){
		return function(a,b){
			return b['count'] - a['count'];
		}
	}

	Object.keys(assocOnlinePeers).forEach(function(curUrl){    
		arrOnlinePeers.push({peer:curUrl, count:assocOnlinePeers[curUrl]});
	})
	if(arrOnlinePeers.length === 0)
		return [];
	else
		return arrOnlinePeers.sort(compare());
}
1275118
def timerExpired(metadata)
      if metadata.is_a?(Array) && metadata[0] == :manage_peers
        managePeers(metadata[1])
      elsif metadata.is_a?(Array) && metadata[0] == :request_blocks
        requestBlocks(metadata[1])
      elsif metadata.is_a?(Array) && metadata[0] == :check_piece_manager
        checkPieceManagerResults(metadata[1])
      elsif metadata.is_a?(Array) && metadata[0] == :handshake_timeout
        handleHandshakeTimeout(metadata[1])
      elsif metadata.is_a?(Array) && metadata[0] == :removetorrent
        handleRemoveTorrent(metadata[1], metadata[2])
      elsif metadata.is_a?(Array) && metadata[0] == :pausetorrent
        handlePause(metadata[1], metadata[2])
      elsif metadata.is_a?(Array) && metadata[0] == :get_torrent_data
        @torrentData.each do |k,v|
          begin
            if metadata[3].nil? || k == metadata[3]
              v = TorrentDataDelegate.new(v, self)
              metadata[1][k] = v
            end
          rescue
            @logger.error "Error building torrent data response for user: #{$!}"
            @logger.error "#{$!.backtrace.join("\n")}"
          end
        end
        metadata[2].signal
      elsif metadata.is_a?(Array) && metadata[0] == :update_torrent_data
        delegate = metadata[1]
        if ! @torrentData.has_key?(infoHash)
          delegate.state = :deleted 
        else
          delegate.internalRefresh
        end
        metadata[2].signal
      elsif metadata.is_a?(Array) && metadata[0] == :request_metadata_pieces
        requestMetadataPieces(metadata[1])
      elsif metadata.is_a?(Array) && metadata[0] == :check_metadata_piece_manager
        checkMetadataPieceManagerResults(metadata[1])
      elsif metadata.is_a?(Array) && metadata[0] == :runproc
        metadata[1].call
      else
        @logger.info "Unknown timer #{metadata} expired."
      end
    end