Return a copy of the known server array sorted in the order of
their last-disconnect-time. Due to the fact a failed connect is
considered a disconnect, this will cause servers to be tried in
a round robin pattern.
192551
function filterAndSortAvailableServers (serverArray) {
        var copyOfServerArray = JSON.parse(JSON.stringify(serverArray));
        copyOfServerArray.sort(function (itemOne, itemTwo) {
            return sortValue(itemOne) - sortValue(itemTwo);
        });

        // Filter servers we've too-recently disconnected from
        return copyOfServerArray.filter(haveNotDisconnectedFromRecently);
    }
180357
@Override
    public List<Pair<Long, String>> getLastNCanceledInstances() {
        List<Pair<Long, String>> list = new ArrayList<Pair<Long, String>>();
        synchronized (recentCanceledQueue) {
            for (Pair<Long, String> aRecentCanceledQueue : recentCanceledQueue) {
                list.add(aRecentCanceledQueue);
            }
        }
        Collections.reverse(list);
        return list;
    }
275049
def _log_disconnect(self):
        
        if self.logged:
            self.server.stats.connectionClosed()
            self.logged = False
1276434
def _on_server_disconnect(self, exception):
        """"""
        self._protocol = None
        if self._on_disconnect_callback_func and callable(self._on_disconnect_callback_func):
            self._on_disconnect_callback_func(exception)
        if self._reconnect:
            self._reconnect_cb()
1192325
def busy_connections(self):
        
        return [c for c in self.connections.values()
                if c.busy and not c.closed]
771800
def shutdown(self):
        
        self._shuttingDown = {key: Deferred()
                              for key in self.cachedConnections.keys()}
        return DeferredList(
            [maybeDeferred(p.transport.loseConnection)
             for p in self.cachedConnections.values()]
             + self._shuttingDown.values())
1079850
def _on_connection_failed(self, conn_id, handle, clean, reason):
        

        with self.count_lock:
            self.connecting_count -= 1

        self._logger.info("_on_connection_failed conn_id=%d, reason=%s", conn_id, str(reason))

        conndata = self._get_connection(handle)

        if conndata is None:
            self._logger.info("Unable to obtain connection data on unknown connection %d", conn_id)
            return

        callback = conndata['callback']
        conn_id = conndata['connection_id']
        failure_reason = conndata['failure_reason']

        # If this was an early disconnect from the device, automatically retry
        if 'error_code' in conndata and conndata['error_code'] == 0x23e and conndata['retries'] > 0:
            self._remove_connection(handle)
            self.connect_async(conn_id, conndata['connection_string'], callback, conndata['retries'] - 1)
        else:
            callback(conn_id, self.id, False, failure_reason)
            self._remove_connection(handle)
716272
def disconnect(self):
        ''''''
        with self._mutex:
            if not self.ports:
                raise exceptions.NotConnectedError
            # Some of the connection participants may not be in the tree,
            # causing the port search in self.ports to return ('Unknown', None)
            # for those participants. Search the list to find the first
            # participant that is in the tree (there must be at least one).
            p = self.ports[0][1]
            ii = 1
            while not p and ii < len(self.ports):
                p = self.ports[ii][1]
                ii += 1
            if not p:
                raise exceptions.UnknownConnectionOwnerError
            p.object.disconnect(self.id)
1127152
def last_time_non_ok_or_up(self):
        
        non_ok_times = [x for x in [self.last_time_warning,
                                    self.last_time_critical,
                                    self.last_time_unknown]
                        if x > self.last_time_ok]
        if not non_ok_times:
            last_time_non_ok = 0  # todo: program_start would be better?
        else:
            last_time_non_ok = min(non_ok_times)
        return last_time_non_ok
689014
def _ensure_connection(self):
        """"""
        conn = self.connect()
        if conn.recycle and conn.recycle < time.time():
            logger.debug('Client session expired after %is. Recycling.', self._recycle)
            self.close()
            conn = self.connect()
        return conn
319234
@Override
    public List<Pair<Long, String>> getLastNRegisteredInstances() {
        List<Pair<Long, String>> list = new ArrayList<Pair<Long, String>>();

        synchronized (recentRegisteredQueue) {
            for (Pair<Long, String> aRecentRegisteredQueue : recentRegisteredQueue) {
                list.add(aRecentRegisteredQueue);
            }
        }
        Collections.reverse(list);
        return list;
    }
519652
def sort_servers_closest(servers: Sequence[str]) -> Sequence[Tuple[str, float]]:
    
    if not {urlparse(url).scheme for url in servers}.issubset({'http', 'https'}):
        raise TransportError('Invalid server urls')

    get_rtt_jobs = set(
        gevent.spawn(lambda url: (url, get_http_rtt(url)), server_url)
        for server_url
        in servers
    )
    # these tasks should never raise, returns None on errors
    gevent.joinall(get_rtt_jobs, raise_error=False)  # block and wait tasks
    sorted_servers: List[Tuple[str, float]] = sorted(
        (job.value for job in get_rtt_jobs if job.value[1] is not None),
        key=itemgetter(1),
    )
    log.debug('Matrix homeserver RTT times', rtt_times=sorted_servers)
    return sorted_servers
925433
def _get_next_server(self):
        """"""

        current_try = 0
        max_tries = len(self._servers)

        while current_try < max_tries:

            server_index = self._raise_server_index()
            server = self._servers[server_index]
            down_until = server['down_until']

            self._logger.debug('Checking server ' + str(current_try + 1) + '/' + str(max_tries) + ': ' + server['url'])

            if down_until == 0:
                self._logger.debug('Elected server: ' + server['url'])
                return server

            if down_until < time.time():
                if self._is_reachable(server):
                    server['down_until'] = 0
                    self._logger.debug('Elected server: ' + server['url'])

                    return server
                else:
                    self._logger.debug('Server still unavailable: ' + server['url'])
                    server['down_until'] = time.time() + 5

            current_try += 1

        raise TransportException('Cannot reach any redis server')
1349028
def disconnectAll(self):
        '''
        
        '''
        if not self.connections:
            return defer.succeed(None)
        result = self._notifier.wait('idle')
        for connection in self.connections:
            connection.transport.loseConnection()
        return result
1330968
function serverMonitoringCleanup(db, conn){
    var exclude = {
        eventDate: 0,
        pid: 0,
        version: 0,
        uptime: 0,
        network: 0,
        connectionName: 0,
        connections: 0,
        memory: 0,
        dataRetrieved: 0,
        docCounts: 0
    };

    var retainedRecords = (24 * 60) * 60 / 30; // 24 hours worth of 30 sec blocks (data refresh interval)

    db.find({connectionName: conn}).skip(retainedRecords).sort({eventDate: -1}).projection(exclude).exec(function (err, serverEvents){
        var idArray = [];
        _.each(serverEvents, function(value, key){
            idArray.push(value._id);
        });

        db.remove({'_id': {'$in': idArray}}, {multi: true}, function (err, newDoc){});
    });
}
479660
def remotesByConnected(self):
        
        conns, disconns = [], []
        for r in self.remotes.values():
            array = conns if self.isRemoteConnected(r) else disconns
            array.append(r)
        return conns, disconns
1005025
function connectToServers() {
        var knownServers = signallingServerSelector.getServerSpecsInPriorityOrder();

        for (var i = 0; i < knownServers.length; i++) {
            var connectionsRemaining = signallingServerService.getPreferredNumberOfSockets() - Object.keys(connectedSockets).length;

            //
            // We have enough connections
            //
            if (connectionsRemaining === 0) {
                break;
            }

            //
            // Try to connect to a new server
            //
            var serverSpec = knownServers[i];
            if (!currentlyConnectedToServer(serverSpec)) {
                var socket;
                try {
                    socket = socketFactory.createSocket(serverSpec);
                    storeSocket(serverSpec, socket);
                    addListeners(socket, serverSpec);
                    loggingService.info("Attempting to connect to signalling server (" + serverSpec.signallingApiBase + ")");
                }
                catch (error) {
                    loggingService.error("Error connecting to socket " + serverSpec.signallingApiBase, error);
                }
            }
        }

        //
        // Store the new set of connected servers in session storage so we
        // can prefer them in the event of a reload
        //
        signallingServerSelector.setLastConnectedServers(getListOfCurrentSignallingApiBases());
    }