select_servers() guts. Hold the lock when calling this.
19898
def _select_servers_loop(self, selector, timeout, address):
        """"""
        now = _time()
        end_time = now + timeout
        server_descriptions = self._description.apply_selector(
            selector, address, custom_selector=self._settings.server_selector)

        while not server_descriptions:
            # No suitable servers.
            if timeout == 0 or now > end_time:
                raise ServerSelectionTimeoutError(
                    self._error_message(selector))

            self._ensure_opened()
            self._request_check_all()

            # Release the lock and wait for the topology description to
            # change, or for a timeout. We won't miss any changes that
            # came after our most recent apply_selector call, since we've
            # held the lock until now.
            self._condition.wait(common.MIN_HEARTBEAT_INTERVAL)
            self._description.check_compatible()
            now = _time()
            server_descriptions = self._description.apply_selector(
                selector, address,
                custom_selector=self._settings.server_selector)

        self._description.check_compatible()
        return server_descriptions
1116020
def wait_for_servers(session, servers):
    
    nclient = nova.Client(NOVA_VERSION, session=session,
                          region_name=os.environ['OS_REGION_NAME'])
    while True:
        deployed = []
        undeployed = []
        for server in servers:
            c = nclient.servers.get(server.id)
            if c.addresses != {} and c.status == 'ACTIVE':
                deployed.append(server)
            if c.status == 'ERROR':
                undeployed.append(server)
        logger.info("[nova]: Polling the Deployment")
        logger.info("[nova]: %s deployed servers" % len(deployed))
        logger.info("[nova]: %s undeployed servers" % len(undeployed))
        if len(deployed) + len(undeployed) >= len(servers):
            break
        time.sleep(3)
    return deployed, undeployed
55
@Override
    public Server choose(Object key) {
        ILoadBalancer lb = getLoadBalancer();
        Optional<Server> server = getPredicate().chooseRoundRobinAfterFiltering(lb.getAllServers(), key);
        if (server.isPresent()) {
            return server.get();
        } else {
            return null;
        }       
    }
970837
def list_nodes_select(conn=None, call=None):
    '''
    
    '''
    if not conn:
        conn = get_conn()   # pylint: disable=E0602

    return salt.utils.cloud.list_nodes_select(
        list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
    )
1174425
def set_server(self, server_pos, key, value):
        """"""
        self.servers.set_server(server_pos, key, value)
829652
async def _keepalive(self):
        '''
            
        '''
        while self.protocol:
            vers = await self.RPC('server.version')
            logger.debug("Server version: " + repr(vers))

            # Five minutes isn't really enough anymore; looks like
            # servers are killing 2-minute old idle connections now.
            # But decreasing interval this seems rude.
            await asyncio.sleep(600)
1291928
def get_servers():
    '''
    
    '''
    cmd = ['w32tm', '/query', '/configuration']
    lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
    for line in lines:
        try:
            if line.startswith('NtpServer:'):
                _, ntpsvrs = line.rsplit(' (', 1)[0].split(':', 1)
                return sorted(ntpsvrs.split())
        except ValueError as e:
            return False
    return False
751007
def select(self, rows, status=True, progress=True):
        ""
        before = len(self._selectedRows)
        if options.bulk_select_clear:
            self._selectedRows.clear()
        for r in (Progress(rows, 'selecting') if progress else rows):
            self.selectRow(r)
        if status:
            if options.bulk_select_clear:
                msg = 'selected %s %s%s' % (len(self._selectedRows), self.rowtype, ' instead' if before > 0 else '')
            else:
                msg = 'selected %s%s %s' % (len(self._selectedRows)-before, ' more' if before > 0 else '', self.rowtype)
            vd.status(msg)
127515
def servers(self):
        """"""
        self.__init()
        items = []
        for k,v in self._json_dict.items():
            if k == "servers":
                for s in v:
                    if 'id' in s:
                        url = "%s/%s" % (self.root, s['id'])
                        items.append(
                            self.Server(url=url,
                                        securityHandler=self._securityHandler,
                                        proxy_url=self._proxy_url,
                                        proxy_port=self._proxy_port))
            del k,v
        return items
1352453
def _clean_servers(self):
        
        if len(self._telnet_servers) > 0:
            for telnet_server in self._telnet_servers:
                telnet_server.close()
                yield from telnet_server.wait_closed()
            self._telnet_servers = []
239202
def _server_loop(self, client, client_addr):
        """"""
        while not self._stopped and not _shutting_down:
            try:
                with self._unlock():
                    request = mock_server_receive_request(client, self)

                self._requests_count += 1
                self._log('%d\t%r' % (request.client_port, request))

                # Give most recently added responders precedence.
                for responder in reversed(self._autoresponders):
                    if responder.handle(request):
                        self._log('\t(autoresponse)')
                        break
                else:
                    self._request_q.put(request)
            except socket.error as error:
                if error.errno in (errno.ECONNRESET, errno.EBADF):
                    # We hung up, or the client did.
                    break
                raise
            except select.error as error:
                if error.args[0] == errno.EBADF:
                    # Closed.
                    break
                else:
                    raise
            except AssertionError:
                traceback.print_exc()
                break

        self._log('disconnected: %s' % format_addr(client_addr))
        client.close()
26354
def preserve_selection():
    
    sl = cmds.ls(sl=True)
    try:
        yield
    finally:
        cmds.select(sl, replace=True)
248462
def _select_nonblock(sockets, remain=None):
    
    # pcap sockets aren't selectable, so we return all of them
    # and ask the selecting functions to use nonblock_recv instead of recv
    def _sleep_nonblock_recv(self):
        try:
            res = self.nonblock_recv()
            if res is None:
                time.sleep(conf.recv_poll_rate)
            return res
        except TimeoutElapsed:
            return None
    return sockets, _sleep_nonblock_recv
637346
public synchronized void serverStopping() {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "serverStopping ", new Object[] { this });

        _serverStopping = true;

        Statement lockingStmt = null;
        String queryString = "";
        ResultSet nonLockingRS = null;
        // Need to establish a reserved connection at this point that can be used in log close processing.
        try {
            _reservedConn = _theDS.getConnection();

            // The BPM Test team found a case where this connection could be stale - a failover had been performed but no recovery log
            // work had been done up to the point where the server stopped. So we'll just check that it isn't stale.
            lockingStmt = _reservedConn.createStatement();
            // Use RDBMS SELECT FOR UPDATE to lock table for recovery
            queryString = "SELECT SERVER_NAME" +
                          " FROM " + _recoveryTableName + _logIdentifierString + _recoveryTableNameSuffix +
                          " WHERE RU_ID=" + "-1";
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Attempt to select the HA LOCKING ROW BUT NOT for UPDATE - " + queryString);
            nonLockingRS = lockingStmt.executeQuery(queryString);
            if (!nonLockingRS.next())
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "HA Locking row was NOT found");
                else if (tc.isDebugEnabled())
                    Tr.debug(tc, "HA Locking row was found");
            lockingStmt.close();
            _reservedConn.commit();
        } catch (SQLException sqlex) {
            Throwable theNonTransientException = sqlex;
            Tr.audit(tc, "WTRN0107W: " +
                         "Caught SQLException when server stopping for SQL RecoveryLog " + _logName + " for server " + _serverName + " SQLException: " + sqlex);
            // Should we attempt to reconnect? This method works through the set of SQL exceptions and will
            // return TRUE if we determine that an transient DB error has occurred
            boolean retryBatch = sqlTransientErrorHandlingEnabled && isSQLErrorTransient(sqlex);
            boolean failAndReport = true;
            if (retryBatch) {
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "Try to reexecute the SQL using connection from DS: " + _theDS);

                // Re-execute the SQL
                try {
                    // Get a connection to database via its datasource
                    _reservedConn = _theDS.getConnection();
                    lockingStmt = _reservedConn.createStatement();
                    nonLockingRS = lockingStmt.executeQuery(queryString);
                    if (!nonLockingRS.next())
                        if (tc.isDebugEnabled())
                            Tr.debug(tc, "HA Locking row was NOT found");
                        else if (tc.isDebugEnabled())
                            Tr.debug(tc, "HA Locking row was found");
                    lockingStmt.close();
                    _reservedConn.commit();
                    failAndReport = false;
                } catch (SQLException sqlex2) {
                    // We've caught another SQLException. Assume that we've retried the connection too soon.
                    // Make sure we inspect the latest exception
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "reset the sqlex to " + sqlex2);
                    theNonTransientException = sqlex2;
                } catch (Throwable exc) {
                    // Not a SQLException, break out of the loop and report the exception
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Failed got exception: " + exc);

                    for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
                        if (tc.isDebugEnabled())
                            Tr.debug(tc, " " + ste);
                    }

                    theNonTransientException = exc;
                }
            }

            if (failAndReport) {
                // Throw an FFDC, but allow processing to continue
                FFDCFilter.processException(theNonTransientException, "com.ibm.ws.recoverylog.spi.SQLMultiScopeRecoveryLog.serverStopping", "464", this);

                _reservedConn = null;

                if (tc.isEntryEnabled())
                    Tr.exit(tc, "serverStopping", theNonTransientException);
            }
        } finally {
            try {
                if (nonLockingRS != null && !nonLockingRS.isClosed())
                    nonLockingRS.close();
                if (lockingStmt != null && !lockingStmt.isClosed())
                    lockingStmt.close();
            } catch (SQLException e) {
                // Log close failure but allow processing to continue
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "on closing SQL resources caught exception: " + e);
            }
        }

        if (tc.isEntryEnabled())
            Tr.exit(tc, "serverStopping");
    }
629398
def sessions_supported?
      if topology.data_bearing_servers?
        return !!topology.logical_session_timeout
      end

      begin
        ServerSelector.get(mode: :primary_preferred).select_server(self)
        !!topology.logical_session_timeout
      rescue Error::NoServerAvailable
        false
      end
    end
177688
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE")
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        }
        Server server = null;

        while (server == null) {
            if (Thread.interrupted()) {
                return null;
            }
            List<Server> upList = lb.getReachableServers();
            List<Server> allList = lb.getAllServers();

            int serverCount = allList.size();
            if (serverCount == 0) {
                /*
                 * No servers. End regardless of pass, because subsequent passes
                 * only get more restrictive.
                 */
                return null;
            }

            int index = chooseRandomInt(serverCount);
            server = upList.get(index);

            if (server == null) {
                /*
                 * The only time this should happen is if the server list were
                 * somehow trimmed. This is a transient condition. Retry after
                 * yielding.
                 */
                Thread.yield();
                continue;
            }

            if (server.isAlive()) {
                return (server);
            }

            // Shouldn't actually happen.. but must be transient or a bug.
            server = null;
            Thread.yield();
        }

        return server;

    }
287547
public synchronized void releaseServerLock() {
        if (serverLock != null) {
            try {
                serverLock.release();
            } catch (IOException e) {
            } finally {
                Utils.tryToClose(lockFileChannel);
            }
            serverLock = null;
            lockFileChannel = null;
        }
    }