A reusable connection manager
330654
def opener(self):
        ""
        if self._opener is None:
            log.debug("Creating connection handler")
            opener = build_opener()
            if self._cookies:
                log.debug("Appending cookies")
            else:
                log.debug("No cookies to append")
            for cookie in self._cookies:
                cookie_str = cookie.name + '=' + cookie.value
                opener.addheaders.append(('Cookie', cookie_str))
            self._opener = opener
        else:
            log.debug("Reusing connection manager")
        return self._opener
1008574
def get_conns(cred, providers):
    """"""
    cld_svc_map = {"aws": conn_aws,
                   "azure": conn_az,
                   "gcp": conn_gcp,
                   "alicloud": conn_ali}
    sys.stdout.write("\rEstablishing Connections:  ")
    sys.stdout.flush()
    busy_obj = busy_disp_on()
    conn_fn = [[cld_svc_map[x.rstrip('1234567890')], cred[x], x]
               for x in providers]
    cgroup = Group()
    conn_res = []
    conn_res = cgroup.map(get_conn, conn_fn)
    cgroup.join()
    conn_objs = {}
    for item in conn_res:
        conn_objs.update(item)
    busy_disp_off(dobj=busy_obj)
    sys.stdout.write("\r                                                 \r")
    sys.stdout.write("\033[?25h")  # cursor back on
    sys.stdout.flush()
    return conn_objs
1367789
function _connectHandler(self) {
      return function() {
        // Assign
        var connection = this;

        // Pool destroyed stop the connection
        if (self.state === DESTROYED || self.state === DESTROYING) {
          return connection.destroy();
        }

        // Clear out all handlers
        handlers.forEach(function(event) {
          connection.removeAllListeners(event);
        });

        // Reset reconnect id
        self.reconnectId = null;

        // Apply pool connection handlers
        connection.on('error', connectionFailureHandler(self, 'error'));
        connection.on('close', connectionFailureHandler(self, 'close'));
        connection.on('timeout', connectionFailureHandler(self, 'timeout'));
        connection.on('parseError', connectionFailureHandler(self, 'parseError'));

        // Apply any auth to the connection
        reauthenticate(self, this, function() {
          // Reset retries
          self.retriesLeft = self.options.reconnectTries;
          // Push to available connections
          self.availableConnections.push(connection);
          // Set the reconnectConnection to null
          self.reconnectConnection = null;
          // Emit reconnect event
          self.emit('reconnect', self);
          // Trigger execute to start everything up again
          _execute(self)();
        });
      };
    }
293656
function executeReconnect(self) {
    return function() {
      if (self.state === DESTROYED || self.state === UNREFERENCED) {
        return;
      }

      connectNewServers(self, self.s.replicaSetState.unknownServers, function() {
        var monitoringFrequencey = self.s.replicaSetState.hasPrimary()
          ? _haInterval
          : self.s.minHeartbeatFrequencyMS;

        // Create a timeout
        self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start());
      });
    };
  }
153241
def _connectionEstablished(self, transport):
        ''''''
        self.transport = transport
        self.transport.writeOpen()
        self.heartbeater.schedule()
157120
def open_connections(self):
        """"""
        return [(host, len(li)) for (host, li) in self._cm.get_all().items()]
1345878
private static List<ConnectionNotation> getAllSelfCycleConnections(List<ConnectionNotation> connections) {
    List<ConnectionNotation> listSelfCycle = new ArrayList<ConnectionNotation>();
    for (ConnectionNotation connection : connections) {
      if ((connection.getTargetId().getId().equals(connection.getSourceId().getId()))) {
        listSelfCycle.add(connection);
      }
    }
    return listSelfCycle;
  }
8259
private void reassociateConnectionHandle(Object connection,
                                             MCWrapper fromMCWrapper,
                                             MCWrapper toMCWrapper,
                                             UOWCoordinator uowCoord) throws ResourceException {

        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(this, tc, "reassociateConnectionHandle");

        try {
            toMCWrapper.associateConnection(connection, fromMCWrapper);
        } catch (ResourceException e) {

            /*
             * If the Resource Adapter throws a ResourceException and we are not in a
             * transaction and there are no other connections open on the ManagedConnection,
             * return the ManagedConnection to the pool before
             * rethrowing the exception. The ManagedConnection is probably OK - the exception
             * may only be a logon failure or similar so the MC shouldn't be 'lost'.
             *
             * If we are in a transaction, just throw the exception. Assume we will cleanup during
             * the aftercompletion call on the tran wrapper.
             */

            com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ejs.j2c.ConnectionManager.reassociateConnectionHandle", "479", this);
            if (uowCoord == null && toMCWrapper.getHandleCount() == 0) {
                try {
                    toMCWrapper.releaseToPoolManager();
                } catch (Exception exp) { // don't rethrow, already on exception path
                    com.ibm.ws.ffdc.FFDCFilter.processException(exp, "com.ibm.ejs.j2c.ConnectionManager.reassociateConnectionHandle", "487", this);
                    //if (TraceComponent.isAnyTracingEnabled()  && tc.isDebugEnabled())
                    Tr.error(tc, "FAILED_CONNECTION_RELEASE_J2CA0022", new Object[] { exp, toMCWrapper.gConfigProps.cfName });
                }
            }
            throw e;
        } catch (java.lang.Exception e) {
            com.ibm.ws.ffdc.FFDCFilter.processException(e,
                                                        "com.ibm.ejs.j2c.ConnectionManager.reassociateConnectionHandle",
                                                        "495", this);
            if (isTraceOn && tc.isDebugEnabled()) {
                Tr.debug(this, tc, "reassociateConnectionHandle: Caught a Non resource exception from mc.associateConnection()");
            }
            Tr.error(tc, "FAILED_CONNECTION_J2CA0021", new Object[] { e, toMCWrapper.gConfigProps.cfName });
            /*
             * If the Resource Adapter throws an Exception and we are not in a
             * transaction and there are no other connections open on the ManagedConnection,
             * return the ManagedConnection to the pool before
             * rethrowing the exception. The ManagedConnection is probably OK - the exception
             * may only be a logon failure or similar so the MC shouldn't be 'lost'.
             *
             * If we are in a transaction, just throw the exception. Assume we will cleanup during
             * the aftercompletion call on the tran wrapper.
             */

            if (uowCoord == null && toMCWrapper.getHandleCount() == 0) {
                try {
                    toMCWrapper.releaseToPoolManager();
                } catch (Exception exp) { // don't rethrow, already on exception path
                    com.ibm.ws.ffdc.FFDCFilter.processException(exp,
                                                                "com.ibm.ejs.j2c.ConnectionManager.reassociateConnectionHandle",
                                                                "518", this);
                    //if (TraceComponent.isAnyTracingEnabled()  && tc.isDebugEnabled())
                    Tr.error(tc, "FAILED_CONNECTION_RELEASE_J2CA0022", new Object[] { exp, toMCWrapper.gConfigProps.cfName });
                }
            }
            ResourceException re = new ResourceException("reassociateConnectionHandle: caught Exception");
            re.initCause(e);
            throw re;
        }

        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(this, tc, "reassociateConnectionHandle");

    }
1130221
def get_connection_by_dest(self, dest):
        ''''''
        with self._mutex:
            for conn in self.connections:
                if conn.has_port(self) and conn.has_port(dest):
                    return conn
            return None
999356
public static ConnectionBuilder connectionBuilder(XnioWorker worker, ByteBufferPool bufferPool, URI uri) {
        return new ConnectionBuilder(worker, bufferPool, uri);
    }
994220
def get_connection_by_name(self, name):
        ''''''
        with self._mutex:
            for conn in self.connections:
                if conn.name == name:
                    return conn
            return None
588986
def router_connections(self):
        """"""
        clients = []
        for server in self._routers:
            if Servers().is_alive(server):
                client = self.create_connection(Servers().hostname(server))
                clients.append(client)
        return clients
689673
private void writeManagedConnection(Definition def, Writer out, int indent) throws IOException
   {
      writeWithIndent(out, indent, "/**\n");
      writeWithIndent(out, indent, " * Creates a new physical connection to the underlying EIS resource manager.\n");
      writeWithIndent(out, indent, " *\n");
      writeWithIndent(out, indent, " * @param subject Caller's security information\n");
      writeWithIndent(out, indent,
            " * @param cxRequestInfo Additional resource adapter " + "specific connection request information\n");
      writeWithIndent(out, indent, " * @throws ResourceException generic exception\n");
      writeWithIndent(out, indent, " * @return ManagedConnection instance \n");
      writeWithIndent(out, indent, " */\n");

      writeWithIndent(out, indent, "public ManagedConnection createManagedConnection(Subject subject,\n");
      writeIndent(out, indent + 2);
      out.write("ConnectionRequestInfo cxRequestInfo) throws ResourceException");
      writeLeftCurlyBracket(out, indent);
      writeLogging(def, out, indent + 1, "trace", "createManagedConnection", "subject", "cxRequestInfo");
      writeWithIndent(out, indent + 1, "return new " + def.getMcfDefs().get(getNumOfMcf()).getMcClass() + "(this);");
      writeRightCurlyBracket(out, indent);
      writeEol(out);

      writeWithIndent(out, indent, "/**\n");
      writeWithIndent(out, indent, " * Returns a matched connection from the candidate set of connections. \n");
      writeWithIndent(out, indent, " *\n");
      writeWithIndent(out, indent, " * @param connectionSet Candidate connection set\n");
      writeWithIndent(out, indent, " * @param subject Caller's security information\n");
      writeWithIndent(out, indent,
            " * @param cxRequestInfo Additional resource adapter " + "specific connection request information\n");
      writeWithIndent(out, indent, " * @throws ResourceException generic exception\n");
      writeWithIndent(out, indent,
            " * @return ManagedConnection if resource adapter finds an acceptable match otherwise null \n");
      writeWithIndent(out, indent, " */\n");

      writeWithIndent(out, indent, "public ManagedConnection matchManagedConnections(Set connectionSet,\n");
      writeIndent(out, indent + 2);
      out.write("Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException");
      writeLeftCurlyBracket(out, indent);
      writeLogging(def, out, indent + 1, "trace", "matchManagedConnections", "connectionSet", "subject",
            "cxRequestInfo");
      writeWithIndent(out, indent + 1, "ManagedConnection result = null;\n");
      writeWithIndent(out, indent + 1, "Iterator it = connectionSet.iterator();\n");
      writeWithIndent(out, indent + 1, "while (result == null && it.hasNext())");
      writeLeftCurlyBracket(out, indent + 1);
      writeIndent(out, indent + 2);
      out.write("ManagedConnection mc = (ManagedConnection)it.next();\n");
      writeIndent(out, indent + 2);
      out.write("if (mc instanceof " + def.getMcfDefs().get(getNumOfMcf()).getMcClass() + ")");
      writeLeftCurlyBracket(out, indent + 2);
      writeIndent(out, indent + 3);
      out.write("result = mc;");
      writeRightCurlyBracket(out, indent + 2);
      writeRightCurlyBracket(out, indent + 1);
      writeWithIndent(out, indent + 1, "return result;");

      writeRightCurlyBracket(out, indent);
      writeEol(out);
   }
253095
def connection(self):
        
        conn = self.session(**self.options)
        try:
            for item in self.middlewares:
                item(conn)
            yield conn
        finally:
            conn.teardown()
962732
function startAllConnections() {
  try {
    myUtils.validateConfig();
  }
  catch(e) {
    console.error(e.message);
    process.exit(2);
  }

  // redefine keys method before connections are started
  if (config.get('redis.useScan')) {
    console.log('Using scan instead of keys');
    Object.defineProperty(Redis.prototype, 'keys', {
      value: function(pattern, cb) {
        let keys = [];
        let that = this;
        let scanCB = function(err, res) {
          if (err) {
            if (typeof cb === 'function') cb(err);
            else {
              console.log('ERROR in redefined "keys" function to use "scan" instead without callback: ' + JSON.stringify(err));
            }
          }
          else {
            let count = res[0], curKeys = res[1];
            console.log("scanning: " + count + ": " + curKeys.length);
            keys = keys.concat(curKeys);
            if (Number(count) === 0) {
              if (typeof cb === 'function') cb(null, keys);
              else {
                console.log('ERROR in redefined "keys" function to use "scan" instead - no callback given!');
              }
            }
            else {
              that.scan(count, 'MATCH', pattern, 'COUNT', config.get('redis.scanCount'), scanCB);
            }
          }
        };
        return this.scan(0, 'MATCH', pattern, 'COUNT', config.get('redis.scanCount'), scanCB);
      }
    });
  }

  // first default connections from config object
  // second connection from cli params (redis-host, redis-port, ...)
  startDefaultConnections(config.connections, function (err) {
    if (err) {
      console.log(err);
      process.exit();
    }
    let db = parseInt(args['redis-db']);
    if (isNaN(db)) {
        db = 0;
    }

    let client;
    if (args['sentinel-host'] || args['sentinels'] || args['redis-host'] || args['redis-port'] || args['redis-socket'] || args['redis-password']) {
      let newDefault = {
        "label": config.get('redis.defaultLabel'),
        "dbIndex": db,
        "password": args['redis-password'] || '',
        "connectionName": config.get('redis.connectionName')
      };

      if (args['redis-socket']) {
        newDefault.path = args['redis-socket'];
      }
      else {
        newDefault.host = args['redis-host'] || "localhost";
        newDefault.port = args['redis-port'] || "6379";
        newDefault.sentinel_name = args['sentinel-name'];
        if (args['sentinels']) {
          newDefault.sentinels = myUtils.parseRedisSentinel('--sentinels', args['sentinels']);
        }
        else if (args['sentinel-host']) {
          newDefault.sentinels = myUtils.parseRedisSentinel( '--sentinel-host or --sentinel-port',
            args['sentinel-host'] + ':' + args['sentinel-port']);
        }
      }

      if (args['redis-tls']) {
        newDefault.tls = {};
      }

      if (!myUtils.containsConnection(config.connections, newDefault)) {
        client = myUtils.createRedisClient(newDefault);
        redisConnections.push(client);
        config.connections.push(newDefault);
        if (!config.get('noSave')) {
          myUtils.saveConnections(config,function (err) {
            if (err) {
              console.log("Problem saving connection config.");
              console.error(err);
            }
          });
        }
        setUpConnection(client, db);
      }
    } else if (config.connections.length === 0) {
      // fallback to localhost if nothing else configured
      client = myUtils.createRedisClient({label: config.get('redis.defaultLabel')});
      redisConnections.push(client);
      setUpConnection(client, db);
    }

    return startWebApp();
  });

  // wait a bit before starting browser to let http server start
  if (args['open']) {
    setTimeout(function() {
      let address = '127.0.0.1';
      if (config.get('server.address') !== '0.0.0.0' && config.get('server.address') !== '::') {
        address = config.get('server.address');
      }
      require('opener')('http://' + address + ':' + config.get('server.port'));
    }, 1000);
  }
}
163236
private void reopen(final ConnectionPoolConnection conn) {

      if(isActive) {
         if(conn.reopenAttempts == 0) {
            conn.reopenAttempts++;
            reopenService.execute(new Reopener(conn));
         } else {
            long delayMillis = 100L * conn.reopenAttempts;
            if(delayMillis > maxReconnectDelayMillis) {
               delayMillis = maxReconnectDelayMillis;
            }
            conn.reopenAttempts++;
            reopenService.schedule(new Reopener(conn), delayMillis, TimeUnit.MILLISECONDS);
         }
      }
   }
767176
def add_connections(self, conns):
        
        rets = []
        for addr, kwargs in conns:
            r = self.add_connection(addr, **kwargs)
            rets.append(r)
        return rets