Get or create a connection to a broker using host and port
497777
def _get_conn(self, host, port, afi):
        """"""
        host_key = (host, port)
        if host_key not in self._conns:
            self._conns[host_key] = BrokerConnection(
                host, port, afi,
                request_timeout_ms=self.timeout * 1000,
                client_id=self.client_id
            )

        conn = self._conns[host_key]
        if not conn.connect_blocking(self.timeout):
            conn.close()
            raise KafkaConnectionError("%s:%s (%s)" % (host, port, afi))
        return conn
971949
def connect(self, *args, **kwargs):
        """"""
        defaults = {}

        for i, k in enumerate(('host', 'port', 'channel', 'use_ssl', 'password')):
            if i < len(args):
                defaults[k] = args[i]
            elif k in kwargs:
                defaults[k] = kwargs[k]
            else:
                def_k = 'default_' + k
                defaults[k] = getattr(self, def_k, None)

        if defaults['use_ssl'] is None:
            defaults['use_ssl'] = False

        if defaults['host'] is None:
            raise TypeError("missing 1 required positional argument: 'host'")

        logging.info("Connecting to %s:%s and joining channels %s",
                     defaults['host'],
                     defaults['port'],
                     defaults['channel'],
                     )
        client.SimpleClient.connect(self, **defaults)
1107279
async def create_connection(
    host,
    port,
    *,
    loop=None,
    secure=True,
    ssl_context=None,
    **kwargs,
):
    
    loop = loop or asyncio.get_event_loop()

    secure = True if port == 443 else secure
    connection = HTTP2ClientConnection(host, loop=loop, secure=secure)
    if not isinstance(ssl_context, SSLContext):
        ssl_context = default_ssl_context()

    await loop.create_connection(
        lambda: connection,
        host=host,
        port=port,
        ssl=ssl_context,
    )

    return connection
719053
def _try_connect(self, host):
        
        log.debug("[control connection] Opening new connection to %s", host)

        while True:
            try:
                connection = self._cluster.connection_factory(host.endpoint, is_control_connection=True)
                if self._is_shutdown:
                    connection.close()
                    raise DriverException("Reconnecting during shutdown")
                break
            except ProtocolVersionUnsupported as e:
                self._cluster.protocol_downgrade(host.endpoint, e.startup_version)

        log.debug("[control connection] Established new connection %r, "
                  "registering watchers and refreshing schema and topology",
                  connection)

        # use weak references in both directions
        # _clear_watcher will be called when this ControlConnection is about to be finalized
        # _watch_callback will get the actual callback from the Connection and relay it to
        # this object (after a dereferencing a weakref)
        self_weakref = weakref.ref(self, partial(_clear_watcher, weakref.proxy(connection)))
        try:
            connection.register_watchers({
                "TOPOLOGY_CHANGE": partial(_watch_callback, self_weakref, '_handle_topology_change'),
                "STATUS_CHANGE": partial(_watch_callback, self_weakref, '_handle_status_change'),
                "SCHEMA_CHANGE": partial(_watch_callback, self_weakref, '_handle_schema_change')
            }, register_timeout=self._timeout)

            sel_peers = self._SELECT_PEERS if self._token_meta_enabled else self._SELECT_PEERS_NO_TOKENS
            sel_local = self._SELECT_LOCAL if self._token_meta_enabled else self._SELECT_LOCAL_NO_TOKENS
            peers_query = QueryMessage(query=sel_peers, consistency_level=ConsistencyLevel.ONE)
            local_query = QueryMessage(query=sel_local, consistency_level=ConsistencyLevel.ONE)
            shared_results = connection.wait_for_responses(
                peers_query, local_query, timeout=self._timeout)

            self._refresh_node_list_and_token_map(connection, preloaded_results=shared_results)
            self._refresh_schema(connection, preloaded_results=shared_results, schema_agreement_wait=-1)
        except Exception:
            connection.close()
            raise

        return connection
763935
def create_transport(host, connect_timeout, ssl=False):
    """"""
    if ssl:
        return SSLTransport(host, connect_timeout, ssl)
    else:
        return TCPTransport(host, connect_timeout)
958628
async def connect(self, hostname=None, port=None, tls=False, **kwargs):
        
        if not port:
            if tls:
                port = DEFAULT_TLS_PORT
            else:
                port = rfc1459.protocol.DEFAULT_PORT
        return await super().connect(hostname, port, tls=tls, **kwargs)
352192
def acquire_proxy(self, host, port, use_ssl=False, host_key=None,
                      tunnel=True):
        '''
        '''
        if self._host_filter and not self._host_filter.test(host):
            connection = yield from \
                super().acquire(host, port, use_ssl, host_key)

            return connection

        host_key = host_key or (host, port, use_ssl)
        proxy_host, proxy_port = self._proxy_address

        connection = yield from super().acquire(
            proxy_host, proxy_port, self._proxy_ssl, host_key=host_key
        )
        connection.proxied = True

        _logger.debug('Request for proxy connection.')

        if connection.closed():
            _logger.debug('Connecting to proxy.')
            yield from connection.connect()

            if tunnel:
                yield from self._establish_tunnel(connection, (host, port))

            if use_ssl:
                ssl_connection = yield from connection.start_tls(self._ssl_context)
                ssl_connection.proxied = True
                ssl_connection.tunneled = True

                self._connection_map[ssl_connection] = connection
                connection.wrapped_connection = ssl_connection

                return ssl_connection

        if connection.wrapped_connection:
            ssl_connection = connection.wrapped_connection
            self._connection_map[ssl_connection] = connection
            return ssl_connection
        else:
            return connection
1255722
def get(key, host=DEFAULT_HOST, port=DEFAULT_PORT):
    '''
    
    '''
    conn = _connect(host, port)
    _check_stats(conn)
    return conn.get(key)
566205
def connect(host=nil, port=nil, &cb)
      host ||= opts[:upstream_host] || raise('no upstream host')
      port ||= opts[:upstream_port] || raise('no upstream port')
      cb   ||= lambda { |conn| opts[:session_callback].call(self, conn) }
      log.debug "Making upstream connection to #{host}:#{port}"
      EM.connect(host, port, Connection, opts[:upstream_args], &cb)
    end
936860
async def _make_connection(self):
        """"""
        return await aioredis.create_redis(
            'redis://{}:{}'.format(
                self._redis_params.get('host', 'localhost'),
                self._redis_params.get('port', 6379)
            ),
            db=int(self._redis_params.get('db', 1))
        )
582557
def connect(host, port, connection_name = nil, *initializer_args, &block)
      if block_given?
        initializer_args.unshift connection_name if connection_name

        klass = Class.new Cool.io::TCPSocket
        connection_builder = ConnectionBuilder.new klass
        connection_builder.instance_eval(&block)
      else
        raise ArgumentError, "no connection name or block given" unless connection_name
        klass = self[connection_name]
      end

      client = klass.connect host, port, *initializer_args
      client.attach Cool.io::Loop.default
      client
    end
995307
def _acquire_connection(self, host, port, use_ssl=False, tunnel=True):
        ''''''
        if hasattr(self._connection_pool, 'acquire_proxy'):
            connection = yield from \
                self._connection_pool.acquire_proxy(host, port, use_ssl,
                                                    tunnel=tunnel)
        else:
            connection = yield from \
                self._connection_pool.acquire(host, port, use_ssl)

        self._connections.add(connection)

        return connection
549847
function getConnection(options) {
  debug('getConnection','start',options);

  let key = null;
  let promise = null;
  try {
    //clone options
    options = clone(options);

    //serialize the options as a key for pools
    key = stringify(options || {});

    //if there's already a promise for the given connection, return it
    if (promises[key]) return promises[key];

    //create a new promise for the given connection options
    promise = promises[key] = createConnectionPromise(key, options);

    debug('getConnection','success')
    return promise;
  } catch(err) {
    debug('getConnection','error',err);
    return Promise.reject(err);
  }
}
886824
async def connect(host, port, ssl=None):
    '''
    
    '''
    info = {'host': host, 'port': port, 'ssl': ssl}
    reader, writer = await asyncio.open_connection(host, port, ssl=ssl)
    return await Link.anit(reader, writer, info=info)
810721
private void connect(String host, int port) throws SQLException, IOException {
    try {
      socket = Utils.createSocket(urlParser, host);
      if (options.socketTimeout != null) {
        socket.setSoTimeout(options.socketTimeout);
      }

      initializeSocketOption();

      // Bind the socket to a particular interface if the connection property
      // localSocketAddress has been defined.
      if (options.localSocketAddress != null) {
        InetSocketAddress localAddress = new InetSocketAddress(options.localSocketAddress, 0);
        socket.bind(localAddress);
      }

      if (!socket.isConnected()) {
        InetSocketAddress sockAddr =
            urlParser.getOptions().pipe == null ? new InetSocketAddress(host, port) : null;
        if (options.connectTimeout != 0) {
          socket.connect(sockAddr, options.connectTimeout);
        } else {
          socket.connect(sockAddr);
        }
      }

      handleConnectionPhases(host);

      connected = true;

      if (options.useCompression) {
        writer = new CompressPacketOutputStream(writer.getOutputStream(),
            options.maxQuerySizeToLog);
        reader = new DecompressPacketInputStream(
            ((StandardPacketInputStream) reader).getInputStream(),
            options.maxQuerySizeToLog);
        if (options.enablePacketDebug) {
          writer.setTraceCache(traceCache);
          reader.setTraceCache(traceCache);
        }
      }

      boolean mustLoadAdditionalInfo = true;
      if (globalInfo != null) {
        if (globalInfo.isAutocommit() == options.autocommit) {
          mustLoadAdditionalInfo = false;
        }
      }

      if (mustLoadAdditionalInfo) {
        Map<String, String> serverData = new TreeMap<>();
        if (options.usePipelineAuth && !options.createDatabaseIfNotExist) {
          try {
            sendPipelineAdditionalData();
            readPipelineAdditionalData(serverData);
          } catch (SQLException sqle) {
            if ("08".equals(sqle.getSQLState())) {
              throw sqle;
            }
            //in case pipeline is not supported
            //(proxy flush socket after reading first packet)
            additionalData(serverData);
          }
        } else {
          additionalData(serverData);
        }

        writer.setMaxAllowedPacket(Integer.parseInt(serverData.get("max_allowed_packet")));
        autoIncrementIncrement = Integer.parseInt(serverData.get("auto_increment_increment"));
        loadCalendar(serverData.get("time_zone"), serverData.get("system_time_zone"));

      } else {

        writer.setMaxAllowedPacket((int) globalInfo.getMaxAllowedPacket());
        autoIncrementIncrement = globalInfo.getAutoIncrementIncrement();
        loadCalendar(globalInfo.getTimeZone(), globalInfo.getSystemTimeZone());
      }

      reader.setServerThreadId(this.serverThreadId, isMasterConnection());
      writer.setServerThreadId(this.serverThreadId, isMasterConnection());

      activeStreamingResult = null;
      hostFailed = false;
    } catch (IOException | SQLException ioException) {
      ensureClosingSocketOnException();
      throw ioException;
    }
  }
1039223
def _get_connection(self, key, host='', port='', user='', password='', database_url='', tags=None, use_cached=True):
        ""
        if key in self.dbs and use_cached:
            return self.dbs[key]
        try:
            connect_kwargs = self._get_connect_kwargs(
                host=host, port=port, user=user, password=password, database_url=database_url
            )

            connection = pg.connect(**connect_kwargs)
            connection.set_isolation_level(pg.extensions.ISOLATION_LEVEL_AUTOCOMMIT)

        # re-raise the CheckExceptions raised by _get_connect_kwargs()
        except CheckException:
            raise

        except Exception:
            redacted_url = self._get_redacted_dsn(host, port, user, database_url)
            message = u'Cannot establish connection to {}'.format(redacted_url)

            self.service_check(
                self.SERVICE_CHECK_NAME,
                AgentCheck.CRITICAL,
                tags=self._get_service_checks_tags(host, port, database_url, tags),
                message=message,
            )
            raise

        self.dbs[key] = connection
        return connection
1214379
def _build_connstr(host, port, bucket):
    
    hostlist = []
    if isinstance(host, (tuple, list)):
        for curhost in host:
            if isinstance(curhost, (list, tuple)):
                hostlist.append(_fmthost(*curhost))
            else:
                hostlist.append(curhost)
    else:
        hostlist.append(_fmthost(host, port))

    return 'http://{0}/{1}'.format(','.join(hostlist), bucket)