Python socket.connect() Examples

The following are code examples for showing how to use socket.connect(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: tornado-zh   Author: tao12345666333   File: iostream.py    MIT License 6 votes vote down vote up
def _handle_connect(self):
        # Call the superclass method to check for errors.
        super(SSLIOStream, self)._handle_connect()
        if self.closed():
            return
        # When the connection is complete, wrap the socket for SSL
        # traffic.  Note that we do this by overriding _handle_connect
        # instead of by passing a callback to super().connect because
        # user callbacks are enqueued asynchronously on the IOLoop,
        # but since _handle_events calls _handle_connect immediately
        # followed by _handle_write we need this to be synchronous.
        #
        # The IOLoop will get confused if we swap out self.socket while the
        # fd is registered, so remove it now and re-register after
        # wrap_socket().
        self.io_loop.remove_handler(self.socket)
        old_state = self._state
        self._state = None
        self.socket = ssl_wrap_socket(self.socket, self._ssl_options,
                                      server_hostname=self._server_hostname,
                                      do_handshake_on_connect=False)
        self._add_io_state(old_state) 
Example 2
Project: tornado-zh   Author: tao12345666333   File: iostream.py    MIT License 6 votes vote down vote up
def _handle_connect(self):
        # Call the superclass method to check for errors.
        super(SSLIOStream, self)._handle_connect()
        if self.closed():
            return
        # When the connection is complete, wrap the socket for SSL
        # traffic.  Note that we do this by overriding _handle_connect
        # instead of by passing a callback to super().connect because
        # user callbacks are enqueued asynchronously on the IOLoop,
        # but since _handle_events calls _handle_connect immediately
        # followed by _handle_write we need this to be synchronous.
        #
        # The IOLoop will get confused if we swap out self.socket while the
        # fd is registered, so remove it now and re-register after
        # wrap_socket().
        self.io_loop.remove_handler(self.socket)
        old_state = self._state
        self._state = None
        self.socket = ssl_wrap_socket(self.socket, self._ssl_options,
                                      server_hostname=self._server_hostname,
                                      do_handshake_on_connect=False)
        self._add_io_state(old_state) 
Example 3
Project: TornadoWeb   Author: VxCoder   File: netutil.py    Apache License 2.0 6 votes vote down vote up
def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None):
        """Resolves an address.

        The ``host`` argument is a string which may be a hostname or a
        literal IP address.

        Returns a `.Future` whose result is a list of (family,
        address) pairs, where address is a tuple suitable to pass to
        `socket.connect <socket.socket.connect>` (i.e. a ``(host,
        port)`` pair for IPv4; additional fields may be present for
        IPv6). If a ``callback`` is passed, it will be run with the
        result as an argument when it is complete.

        :raises IOError: if the address cannot be resolved.

        .. versionchanged:: 4.4
           Standardized all implementations to raise `IOError`.
        """
        raise NotImplementedError() 
Example 4
Project: TornadoWeb   Author: VxCoder   File: iostream.py    Apache License 2.0 6 votes vote down vote up
def _handle_connect(self):
        # Call the superclass method to check for errors.
        super(SSLIOStream, self)._handle_connect()
        if self.closed():
            return
        # When the connection is complete, wrap the socket for SSL
        # traffic.  Note that we do this by overriding _handle_connect
        # instead of by passing a callback to super().connect because
        # user callbacks are enqueued asynchronously on the IOLoop,
        # but since _handle_events calls _handle_connect immediately
        # followed by _handle_write we need this to be synchronous.
        #
        # The IOLoop will get confused if we swap out self.socket while the
        # fd is registered, so remove it now and re-register after
        # wrap_socket().
        self.io_loop.remove_handler(self.socket)
        old_state = self._state
        self._state = None
        self.socket = ssl_wrap_socket(self.socket, self._ssl_options,
                                      server_hostname=self._server_hostname,
                                      do_handshake_on_connect=False)
        self._add_io_state(old_state) 
Example 5
Project: redis-marshal   Author: mitjafelicijan   File: connection.py    MIT License 6 votes vote down vote up
def connect(self):
        "Connects to the Redis server if not already connected"
        if self._sock:
            return
        try:
            sock = self._connect()
        except socket.timeout:
            raise TimeoutError("Timeout connecting to server")
        except socket.error:
            e = sys.exc_info()[1]
            raise ConnectionError(self._error_message(e))

        self._sock = sock
        try:
            self.on_connect()
        except RedisError:
            # clean up after any error in on_connect
            self.disconnect()
            raise

        # run any user callbacks. right now the only internal callback
        # is for pubsub channel/pattern resubscription
        for callback in self._connect_callbacks:
            callback(self) 
Example 6
Project: redis-marshal   Author: mitjafelicijan   File: connection.py    MIT License 6 votes vote down vote up
def send_packed_command(self, command):
        "Send an already packed command to the Redis server"
        if not self._sock:
            self.connect()
        try:
            if isinstance(command, str):
                command = [command]
            for item in command:
                self._sock.sendall(item)
        except socket.timeout:
            self.disconnect()
            raise TimeoutError("Timeout writing to socket")
        except socket.error:
            e = sys.exc_info()[1]
            self.disconnect()
            if len(e.args) == 1:
                errno, errmsg = 'UNKNOWN', e.args[0]
            else:
                errno = e.args[0]
                errmsg = e.args[1]
            raise ConnectionError("Error %s while writing to socket. %s." %
                                  (errno, errmsg))
        except:
            self.disconnect()
            raise 
Example 7
Project: recruit   Author: Frank-qlu   File: mongo_client.py    Apache License 2.0 6 votes vote down vote up
def _cache_credentials(self, source, credentials, connect=True):
        """Add credentials to the database authentication cache
        for automatic login when a socket is created. If `connect` is True,
        verify the credentials on the server first.
        """
        if source in self.__auth_credentials:
            # Nothing to do if we already have these credentials.
            if credentials == self.__auth_credentials[source]:
                return
            raise OperationFailure('Another user is already authenticated '
                                   'to this database. You must logout first.')

        if connect:
            member = self.__ensure_member()
            sock_info = self.__socket(member)
            try:
                # Since __check_auth was called in __socket
                # there is no need to call it here.
                auth.authenticate(credentials, sock_info, self.__simple_command)
                sock_info.authset.add(credentials)
            finally:
                member.maybe_return_socket(sock_info)

        self.__auth_credentials[source] = credentials 
Example 8
Project: recruit   Author: Frank-qlu   File: mongo_client.py    Apache License 2.0 6 votes vote down vote up
def end_request(self):
        """**DEPRECATED**: Undo :meth:`start_request`. If :meth:`end_request`
        is called as many times as :meth:`start_request`, the request is over
        and this thread's connection returns to the pool. Extra calls to
        :meth:`end_request` have no effect.

        Ending a request allows the :class:`~socket.socket` that has
        been reserved for this thread by :meth:`start_request` to be returned to
        the pool. Other threads will then be able to re-use that
        :class:`~socket.socket`. If your application uses many threads, or has
        long-running threads that infrequently perform MongoDB operations, then
        judicious use of this method can lead to performance gains. Care should
        be taken, however, to make sure that :meth:`end_request` is not called
        in the middle of a sequence of operations in which ordering is
        important. This could lead to unexpected results.
        """
        member = self.__member  # Don't try to connect if disconnected.
        if member:
            member.end_request() 
Example 9
Project: TESTGIT   Author: B-ROY   File: mongo_client.py    Apache License 2.0 6 votes vote down vote up
def _cache_credentials(self, source, credentials, connect=True):
        """Add credentials to the database authentication cache
        for automatic login when a socket is created. If `connect` is True,
        verify the credentials on the server first.
        """
        if source in self.__auth_credentials:
            # Nothing to do if we already have these credentials.
            if credentials == self.__auth_credentials[source]:
                return
            raise OperationFailure('Another user is already authenticated '
                                   'to this database. You must logout first.')

        if connect:
            sock_info = self.__socket()
            try:
                # Since __check_auth was called in __socket
                # there is no need to call it here.
                auth.authenticate(credentials, sock_info, self.__simple_command)
                sock_info.authset.add(credentials)
            finally:
                self.__pool.maybe_return_socket(sock_info)

        self.__auth_credentials[source] = credentials 
Example 10
Project: TESTGIT   Author: B-ROY   File: mongo_client.py    Apache License 2.0 6 votes vote down vote up
def __socket(self):
        """Get a SocketInfo from the pool.
        """
        host, port = (self.__host, self.__port)
        if host is None or (port is None and '/' not in host):
            host, port = self.__find_node()

        try:
            if self.auto_start_request and not self.in_request():
                self.start_request()

            sock_info = self.__pool.get_socket((host, port))
        except socket.error, why:
            self.disconnect()

            # Check if a unix domain socket
            if host.endswith('.sock'):
                host_details = "%s:" % host
            else:
                host_details = "%s:%d:" % (host, port)
            raise AutoReconnect("could not connect to "
                                "%s %s" % (host_details, str(why))) 
Example 11
Project: redis-py-threaded   Author: paepcke   File: connection.py    MIT License 6 votes vote down vote up
def connect(self):
        "Connects to the Redis server if not already connected"
        if self._sock:
            return
        try:
            sock = self._connect()
        except socket.error:
            e = sys.exc_info()[1]
            raise ConnectionError(self._error_message(e))

        self._sock = sock
        try:
            self.on_connect()
        except RedisError:
            # clean up after any error in on_connect
            self.disconnect()
            raise

        # run any user callbacks. right now the only internal callback
        # is for pubsub channel/pattern resubscription
        for callback in self._connect_callbacks:
            callback(self) 
Example 12
Project: redis-py-threaded   Author: paepcke   File: connection.py    MIT License 6 votes vote down vote up
def send_packed_command(self, command):
        "Send an already packed command to the Redis server"
        if not self._sock:
            self.connect()
        try:
            if isinstance(command, str):
                command = [command]
            for item in command:
                self._sock.sendall(item)
        except socket.timeout:
            self.disconnect()
            raise TimeoutError("Timeout writing to socket")
        except socket.error:
            e = sys.exc_info()[1]
            self.disconnect()
            if len(e.args) == 1:
                _errno, errmsg = 'UNKNOWN', e.args[0]
            else:
                _errno, errmsg = e.args
            raise ConnectionError("Error %s while writing to socket. %s." %
                                  (_errno, errmsg))
        except:
            self.disconnect()
            raise 
Example 13
Project: redis-py-threaded   Author: paepcke   File: threadedConnection.py    MIT License 6 votes vote down vote up
def send_packed_command(self, command):
        "Send an already packed command to the Redis server"
        if not self._sock:
            self.connect()
        try:
            if isinstance(command, str):
                command = [command]
            for item in command:
                self._sock.sendall(item)
        except socket.timeout:
            self.disconnect()
            raise TimeoutError("Timeout writing to socket")
        except socket.error:
            e = sys.exc_info()[1]
            self.disconnect()
            if len(e.args) == 1:
                _errno, errmsg = 'UNKNOWN', e.args[0]
            else:
                _errno, errmsg = e.args
            raise ConnectionError("Error %s while writing to socket. %s." %
                                  (_errno, errmsg))
        except:
            self.disconnect()
            raise 
Example 14
Project: unhuman-resources   Author: agajdosi   File: netutil.py    GNU General Public License v3.0 6 votes vote down vote up
def resolve(
        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
    ) -> Awaitable[List[Tuple[int, Any]]]:
        """Resolves an address.

        The ``host`` argument is a string which may be a hostname or a
        literal IP address.

        Returns a `.Future` whose result is a list of (family,
        address) pairs, where address is a tuple suitable to pass to
        `socket.connect <socket.socket.connect>` (i.e. a ``(host,
        port)`` pair for IPv4; additional fields may be present for
        IPv6). If a ``callback`` is passed, it will be run with the
        result as an argument when it is complete.

        :raises IOError: if the address cannot be resolved.

        .. versionchanged:: 4.4
           Standardized all implementations to raise `IOError`.

        .. versionchanged:: 6.0 The ``callback`` argument was removed.
           Use the returned awaitable object instead.

        """
        raise NotImplementedError() 
Example 15
Project: unhuman-resources   Author: agajdosi   File: iostream.py    GNU General Public License v3.0 6 votes vote down vote up
def connect(
        self, address: Tuple, server_hostname: str = None
    ) -> "Future[SSLIOStream]":
        self._server_hostname = server_hostname
        # Ignore the result of connect(). If it fails,
        # wait_for_handshake will raise an error too. This is
        # necessary for the old semantics of the connect callback
        # (which takes no arguments). In 6.0 this can be refactored to
        # be a regular coroutine.
        # TODO: This is trickier than it looks, since if write()
        # is called with a connect() pending, we want the connect
        # to resolve before the write. Or do we care about this?
        # (There's a test for it, but I think in practice users
        # either wait for the connect before performing a write or
        # they don't care about the connect Future at all)
        fut = super(SSLIOStream, self).connect(address)
        fut.add_done_callback(lambda f: f.exception())
        return self.wait_for_handshake() 
Example 16
Project: unhuman-resources   Author: agajdosi   File: iostream.py    GNU General Public License v3.0 6 votes vote down vote up
def connect(
        self, address: Tuple, server_hostname: str = None
    ) -> "Future[SSLIOStream]":
        self._server_hostname = server_hostname
        # Ignore the result of connect(). If it fails,
        # wait_for_handshake will raise an error too. This is
        # necessary for the old semantics of the connect callback
        # (which takes no arguments). In 6.0 this can be refactored to
        # be a regular coroutine.
        # TODO: This is trickier than it looks, since if write()
        # is called with a connect() pending, we want the connect
        # to resolve before the write. Or do we care about this?
        # (There's a test for it, but I think in practice users
        # either wait for the connect before performing a write or
        # they don't care about the connect Future at all)
        fut = super(SSLIOStream, self).connect(address)
        fut.add_done_callback(lambda f: f.exception())
        return self.wait_for_handshake() 
Example 17
Project: banruo   Author: yingshang   File: netutil.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None):
        """Resolves an address.

        The ``host`` argument is a string which may be a hostname or a
        literal IP address.

        Returns a `.Future` whose result is a list of (family,
        address) pairs, where address is a tuple suitable to pass to
        `socket.connect <socket.socket.connect>` (i.e. a ``(host,
        port)`` pair for IPv4; additional fields may be present for
        IPv6). If a ``callback`` is passed, it will be run with the
        result as an argument when it is complete.

        :raises IOError: if the address cannot be resolved.

        .. versionchanged:: 4.4
           Standardized all implementations to raise `IOError`.
        """
        raise NotImplementedError() 
Example 18
Project: banruo   Author: yingshang   File: iostream.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _handle_connect(self):
        # Call the superclass method to check for errors.
        super(SSLIOStream, self)._handle_connect()
        if self.closed():
            return
        # When the connection is complete, wrap the socket for SSL
        # traffic.  Note that we do this by overriding _handle_connect
        # instead of by passing a callback to super().connect because
        # user callbacks are enqueued asynchronously on the IOLoop,
        # but since _handle_events calls _handle_connect immediately
        # followed by _handle_write we need this to be synchronous.
        #
        # The IOLoop will get confused if we swap out self.socket while the
        # fd is registered, so remove it now and re-register after
        # wrap_socket().
        self.io_loop.remove_handler(self.socket)
        old_state = self._state
        self._state = None
        self.socket = ssl_wrap_socket(self.socket, self._ssl_options,
                                      server_hostname=self._server_hostname,
                                      do_handshake_on_connect=False)
        self._add_io_state(old_state) 
Example 19
Project: opendevops   Author: opendevops-cn   File: netutil.py    GNU General Public License v3.0 6 votes vote down vote up
def resolve(
        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
    ) -> Awaitable[List[Tuple[int, Any]]]:
        """Resolves an address.

        The ``host`` argument is a string which may be a hostname or a
        literal IP address.

        Returns a `.Future` whose result is a list of (family,
        address) pairs, where address is a tuple suitable to pass to
        `socket.connect <socket.socket.connect>` (i.e. a ``(host,
        port)`` pair for IPv4; additional fields may be present for
        IPv6). If a ``callback`` is passed, it will be run with the
        result as an argument when it is complete.

        :raises IOError: if the address cannot be resolved.

        .. versionchanged:: 4.4
           Standardized all implementations to raise `IOError`.

        .. versionchanged:: 6.0 The ``callback`` argument was removed.
           Use the returned awaitable object instead.

        """
        raise NotImplementedError() 
Example 20
Project: opendevops   Author: opendevops-cn   File: iostream.py    GNU General Public License v3.0 6 votes vote down vote up
def connect(
        self, address: Tuple, server_hostname: str = None
    ) -> "Future[SSLIOStream]":
        self._server_hostname = server_hostname
        # Ignore the result of connect(). If it fails,
        # wait_for_handshake will raise an error too. This is
        # necessary for the old semantics of the connect callback
        # (which takes no arguments). In 6.0 this can be refactored to
        # be a regular coroutine.
        # TODO: This is trickier than it looks, since if write()
        # is called with a connect() pending, we want the connect
        # to resolve before the write. Or do we care about this?
        # (There's a test for it, but I think in practice users
        # either wait for the connect before performing a write or
        # they don't care about the connect Future at all)
        fut = super(SSLIOStream, self).connect(address)
        fut.add_done_callback(lambda f: f.exception())
        return self.wait_for_handshake() 
Example 21
Project: open-recipe   Author: dspray95   File: tcp.py    The Unlicense 6 votes vote down vote up
def _finishInit(self, whenDone, skt, error, reactor):
        """
        Called by subclasses to continue to the stage of initialization where
        the socket connect attempt is made.

        @param whenDone: A 0-argument callable to invoke once the connection is
            set up.  This is L{None} if the connection could not be prepared
            due to a previous error.

        @param skt: The socket object to use to perform the connection.
        @type skt: C{socket._socketobject}

        @param error: The error to fail the connection with.

        @param reactor: The reactor to use for this client.
        @type reactor: L{twisted.internet.interfaces.IReactorTime}
        """
        if whenDone:
            self._commonConnection.__init__(self, skt, None, reactor)
            reactor.callLater(0, whenDone)
        else:
            reactor.callLater(0, self.failIfNotConnected, error) 
Example 22
Project: open-recipe   Author: dspray95   File: tcp.py    The Unlicense 6 votes vote down vote up
def failIfNotConnected(self, err):
        """
        Generic method called when the attempts to connect failed. It basically
        cleans everything it can: call connectionFailed, stop read and write,
        delete socket related members.
        """
        if (self.connected or self.disconnected or
            not hasattr(self, "connector")):
            return

        self._stopReadingAndWriting()
        try:
            self._closeSocket(True)
        except AttributeError:
            pass
        else:
            self._collectSocketDetails()
        self.connector.connectionFailed(failure.Failure(err))
        del self.connector 
Example 23
Project: open-recipe   Author: dspray95   File: tcp.py    The Unlicense 6 votes vote down vote up
def _resolveIPv6(ip, port):
    """
    Resolve an IPv6 literal into an IPv6 address.

    This is necessary to resolve any embedded scope identifiers to the relevant
    C{sin6_scope_id} for use with C{socket.connect()}, C{socket.listen()}, or
    C{socket.bind()}; see U{RFC 3493 <https://tools.ietf.org/html/rfc3493>} for
    more information.

    @param ip: An IPv6 address literal.
    @type ip: C{str}

    @param port: A port number.
    @type port: C{int}

    @return: a 4-tuple of C{(host, port, flow, scope)}, suitable for use as an
        IPv6 address.

    @raise socket.gaierror: if either the IP or port is not numeric as it
        should be.
    """
    return socket.getaddrinfo(ip, port, 0, 0, 0, _NUMERIC_ONLY)[0][4] 
Example 24
Project: vnpy_crypto   Author: birforce   File: tunnel.py    MIT License 6 votes vote down vote up
def _try_passwordless_paramiko(server, keyfile):
    """Try passwordless login with paramiko."""
    if paramiko is None:
        msg = "Paramiko unavailable, "
        if sys.platform == 'win32':
            msg += "Paramiko is required for ssh tunneled connections on Windows."
        else:
            msg += "use OpenSSH."
        raise ImportError(msg)
    username, server, port = _split_server(server)
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())
    try:
        client.connect(server, port, username=username, key_filename=keyfile,
               look_for_keys=True)
    except paramiko.AuthenticationException:
        return False
    else:
        client.close()
        return True 
Example 25
Project: Computable   Author: ktraunmueller   File: tunnel.py    MIT License 6 votes vote down vote up
def _try_passwordless_paramiko(server, keyfile):
    """Try passwordless login with paramiko."""
    if paramiko is None:
        msg = "Paramiko unavaliable, "
        if sys.platform == 'win32':
            msg += "Paramiko is required for ssh tunneled connections on Windows."
        else:
            msg += "use OpenSSH."
        raise ImportError(msg)
    username, server, port = _split_server(server)
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())
    try:
        client.connect(server, port, username=username, key_filename=keyfile,
               look_for_keys=True)
    except paramiko.AuthenticationException:
        return False
    else:
        client.close()
        return True 
Example 26
Project: tornado-zh   Author: tao12345666333   File: netutil.py    MIT License 5 votes vote down vote up
def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None):
        """Resolves an address.

        The ``host`` argument is a string which may be a hostname or a
        literal IP address.

        Returns a `.Future` whose result is a list of (family,
        address) pairs, where address is a tuple suitable to pass to
        `socket.connect <socket.socket.connect>` (i.e. a ``(host,
        port)`` pair for IPv4; additional fields may be present for
        IPv6). If a ``callback`` is passed, it will be run with the
        result as an argument when it is complete.
        """
        raise NotImplementedError() 
Example 27
Project: tornado-zh   Author: tao12345666333   File: iostream.py    MIT License 5 votes vote down vote up
def connect(self, address, callback=None, server_hostname=None):
        self._server_hostname = server_hostname
        # Pass a dummy callback to super.connect(), which is slightly
        # more efficient than letting it return a Future we ignore.
        super(SSLIOStream, self).connect(address, callback=lambda: None)
        return self.wait_for_handshake(callback) 
Example 28
Project: tornado-zh   Author: tao12345666333   File: iostream.py    MIT License 5 votes vote down vote up
def wait_for_handshake(self, callback=None):
        """Wait for the initial SSL handshake to complete.

        If a ``callback`` is given, it will be called with no
        arguments once the handshake is complete; otherwise this
        method returns a `.Future` which will resolve to the
        stream itself after the handshake is complete.

        Once the handshake is complete, information such as
        the peer's certificate and NPN/ALPN selections may be
        accessed on ``self.socket``.

        This method is intended for use on server-side streams
        or after using `IOStream.start_tls`; it should not be used
        with `IOStream.connect` (which already waits for the
        handshake to complete). It may only be called once per stream.

        .. versionadded:: 4.2
        """
        if (self._ssl_connect_callback is not None or
                self._ssl_connect_future is not None):
            raise RuntimeError("Already waiting")
        if callback is not None:
            self._ssl_connect_callback = stack_context.wrap(callback)
            future = None
        else:
            future = self._ssl_connect_future = TracebackFuture()
        if not self._ssl_accepting:
            self._run_ssl_connect_callback()
        return future 
Example 29
Project: tornado-zh   Author: tao12345666333   File: iostream.py    MIT License 5 votes vote down vote up
def connect(self, address, callback=None, server_hostname=None):
        self._server_hostname = server_hostname
        # Pass a dummy callback to super.connect(), which is slightly
        # more efficient than letting it return a Future we ignore.
        super(SSLIOStream, self).connect(address, callback=lambda: None)
        return self.wait_for_handshake(callback) 
Example 30
Project: tornado-zh   Author: tao12345666333   File: iostream.py    MIT License 5 votes vote down vote up
def wait_for_handshake(self, callback=None):
        """Wait for the initial SSL handshake to complete.

        If a ``callback`` is given, it will be called with no
        arguments once the handshake is complete; otherwise this
        method returns a `.Future` which will resolve to the
        stream itself after the handshake is complete.

        Once the handshake is complete, information such as
        the peer's certificate and NPN/ALPN selections may be
        accessed on ``self.socket``.

        This method is intended for use on server-side streams
        or after using `IOStream.start_tls`; it should not be used
        with `IOStream.connect` (which already waits for the
        handshake to complete). It may only be called once per stream.

        .. versionadded:: 4.2
        """
        if (self._ssl_connect_callback is not None or
                self._ssl_connect_future is not None):
            raise RuntimeError("Already waiting")
        if callback is not None:
            self._ssl_connect_callback = stack_context.wrap(callback)
            future = None
        else:
            future = self._ssl_connect_future = TracebackFuture()
        if not self._ssl_accepting:
            self._run_ssl_connect_callback()
        return future 
Example 31
Project: TornadoWeb   Author: VxCoder   File: iostream.py    Apache License 2.0 5 votes vote down vote up
def connect(self, address, callback=None, server_hostname=None):
        self._server_hostname = server_hostname
        # Pass a dummy callback to super.connect(), which is slightly
        # more efficient than letting it return a Future we ignore.
        super(SSLIOStream, self).connect(address, callback=lambda: None)
        return self.wait_for_handshake(callback) 
Example 32
Project: TornadoWeb   Author: VxCoder   File: iostream.py    Apache License 2.0 5 votes vote down vote up
def wait_for_handshake(self, callback=None):
        """Wait for the initial SSL handshake to complete.

        If a ``callback`` is given, it will be called with no
        arguments once the handshake is complete; otherwise this
        method returns a `.Future` which will resolve to the
        stream itself after the handshake is complete.

        Once the handshake is complete, information such as
        the peer's certificate and NPN/ALPN selections may be
        accessed on ``self.socket``.

        This method is intended for use on server-side streams
        or after using `IOStream.start_tls`; it should not be used
        with `IOStream.connect` (which already waits for the
        handshake to complete). It may only be called once per stream.

        .. versionadded:: 4.2
        """
        if (self._ssl_connect_callback is not None or
                self._ssl_connect_future is not None):
            raise RuntimeError("Already waiting")
        if callback is not None:
            self._ssl_connect_callback = stack_context.wrap(callback)
            future = None
        else:
            future = self._ssl_connect_future = TracebackFuture()
        if not self._ssl_accepting:
            self._run_ssl_connect_callback()
        return future 
Example 33
Project: redis-marshal   Author: mitjafelicijan   File: connection.py    MIT License 5 votes vote down vote up
def _connect(self):
        "Create a TCP socket connection"
        # we want to mimic what socket.create_connection does to support
        # ipv4/ipv6, but we want to set options prior to calling
        # socket.connect()
        err = None
        for res in socket.getaddrinfo(self.host, self.port, self.socket_type,
                                      socket.SOCK_STREAM):
            family, socktype, proto, canonname, socket_address = res
            sock = None
            try:
                sock = socket.socket(family, socktype, proto)
                # TCP_NODELAY
                sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

                # TCP_KEEPALIVE
                if self.socket_keepalive:
                    sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                    for k, v in iteritems(self.socket_keepalive_options):
                        sock.setsockopt(socket.SOL_TCP, k, v)

                # set the socket_connect_timeout before we connect
                sock.settimeout(self.socket_connect_timeout)

                # connect
                sock.connect(socket_address)

                # set the socket_timeout now that we're connected
                sock.settimeout(self.socket_timeout)
                return sock

            except socket.error as _:
                err = _
                if sock is not None:
                    sock.close()

        if err is not None:
            raise err
        raise socket.error("socket.getaddrinfo returned an empty list") 
Example 34
Project: redis-marshal   Author: mitjafelicijan   File: connection.py    MIT License 5 votes vote down vote up
def can_read(self, timeout=0):
        "Poll the socket to see if there's data that can be read."
        sock = self._sock
        if not sock:
            self.connect()
            sock = self._sock
        return self._parser.can_read() or \
            bool(select([sock], [], [], timeout)[0]) 
Example 35
Project: redis-marshal   Author: mitjafelicijan   File: connection.py    MIT License 5 votes vote down vote up
def _connect(self):
        "Create a Unix domain socket connection"
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        sock.settimeout(self.socket_timeout)
        sock.connect(self.path)
        return sock 
Example 36
Project: recruit   Author: Frank-qlu   File: mongo_client.py    Apache License 2.0 5 votes vote down vote up
def _partition_node(node):
    """Split a host:port string returned from mongod/s into
    a (host, int(port)) pair needed for socket.connect().
    """
    host = node
    port = 27017
    idx = node.rfind(':')
    if idx != -1:
        host, port = node[:idx], int(node[idx + 1:])
    if host.startswith('['):
        host = host[1:-1]
    return host, port 
Example 37
Project: recruit   Author: Frank-qlu   File: mongo_client.py    Apache License 2.0 5 votes vote down vote up
def __socket(self, member):
        """Get a SocketInfo.

        Calls disconnect() on error.
        """
        try:
            if self.auto_start_request and not member.in_request():
                member.start_request()

            sock_info = member.get_socket()
        except socket.error as why:
            self.disconnect()

            # Check if a unix domain socket
            host, port = member.host
            if host.endswith('.sock'):
                host_details = "%s:" % host
            else:
                host_details = "%s:%d:" % (host, port)
            raise AutoReconnect("could not connect to "
                                "%s %s" % (host_details, str(why)))
        try:
            self.__check_auth(sock_info)
        except:
            member.maybe_return_socket(sock_info)
            raise
        return sock_info 
Example 38
Project: recruit   Author: Frank-qlu   File: mongo_client.py    Apache License 2.0 5 votes vote down vote up
def alive(self):
        """Return ``False`` if there has been an error communicating with the
        server, else ``True``.

        This method attempts to check the status of the server with minimal I/O.
        The current thread / greenlet retrieves a socket from the pool (its
        request socket if it's in a request, or a random idle socket if it's not
        in a request) and checks whether calling `select`_ on it raises an
        error. If there are currently no idle sockets, :meth:`alive` will
        attempt to actually connect to the server.

        A more certain way to determine server availability is::

            client.admin.command('ping')

        .. _select: http://docs.python.org/2/library/select.html#select.select
        """
        # In the common case, a socket is available and was used recently, so
        # calling select() on it is a reasonable attempt to see if the OS has
        # reported an error.
        self.__connecting_lock.acquire()
        member = self.__member
        self.__connecting_lock.release()
        if not member:
            return False
        else:
            sock_info = None
            try:
                try:
                    sock_info = member.get_socket()
                    return not pool._closed(sock_info.sock)
                except (socket.error, ConnectionFailure):
                    return False
            finally:
                member.maybe_return_socket(sock_info) 
Example 39
Project: recruit   Author: Frank-qlu   File: mongo_replica_set_client.py    Apache License 2.0 5 votes vote down vote up
def _partition_node(node):
    """Split a host:port string returned from mongod/s into
    a (host, int(port)) pair needed for socket.connect().
    """
    host = node
    port = 27017
    idx = node.rfind(':')
    if idx != -1:
        host, port = node[:idx], int(node[idx + 1:])
    if host.startswith('['):
        host = host[1:-1]
    return host, port


# Concurrency notes: A MongoReplicaSetClient keeps its view of the replica-set
# state in an RSState instance. RSStates are immutable, except for
# host-pinning. Pools, which are internally thread / greenlet safe, can be
# copied from old to new RSStates safely. The client updates its view of the
# set's state not by modifying its RSState but by replacing it with an updated
# copy.

# In __init__, MongoReplicaSetClient gets a list of potential members called
# 'seeds' from its initial parameters, and calls refresh(). refresh() iterates
# over the the seeds in arbitrary order looking for a member it can connect to.
# Once it finds one, it calls 'ismaster' and sets self.__hosts to the list of
# members in the response, and connects to the rest of the members. refresh()
# sets the MongoReplicaSetClient's RSState. Finally, __init__ launches the
# replica-set monitor.

# The monitor calls refresh() every 30 seconds, or whenever the client has
# encountered an error that prompts it to wake the monitor.

# Every method that accesses the RSState multiple times within the method makes
# a local reference first and uses that throughout, so it's isolated from a
# concurrent method replacing the RSState with an updated copy. This technique
# avoids the need to lock around accesses to the RSState. 
Example 40
Project: recruit   Author: Frank-qlu   File: mongo_replica_set_client.py    Apache License 2.0 5 votes vote down vote up
def error_message(self):
        """The error, if any, raised when trying to connect to the primary"""
        return self._error_message 
Example 41
Project: recruit   Author: Frank-qlu   File: mongo_replica_set_client.py    Apache License 2.0 5 votes vote down vote up
def _cache_credentials(self, source, credentials, connect=True):
        """Add credentials to the database authentication cache
        for automatic login when a socket is created. If `connect` is True,
        verify the credentials on the server first.

        Raises OperationFailure if other credentials are already stored for
        this source.
        """
        if source in self.__auth_credentials:
            # Nothing to do if we already have these credentials.
            if credentials == self.__auth_credentials[source]:
                return
            raise OperationFailure('Another user is already authenticated '
                                   'to this database. You must logout first.')

        if connect:
            # Try to authenticate even during failover.
            member = select_member(
                self.__rs_state.members, ReadPreference.PRIMARY_PREFERRED)

            if not member:
                raise AutoReconnect(
                    "No replica set members available for authentication")

            sock_info = self.__socket(member)
            try:
                # Since __check_auth was called in __socket
                # there is no need to call it here.
                auth.authenticate(credentials, sock_info, self.__simple_command)
                sock_info.authset.add(credentials)
            finally:
                member.maybe_return_socket(sock_info)

        self.__auth_credentials[source] = credentials 
Example 42
Project: recruit   Author: Frank-qlu   File: mongo_replica_set_client.py    Apache License 2.0 5 votes vote down vote up
def seeds(self):
        """The seed list used to connect to this replica set.

        A sequence of (host, port) pairs.
        """
        return self.__seeds 
Example 43
Project: TESTGIT   Author: B-ROY   File: iostream.py    Apache License 2.0 5 votes vote down vote up
def connect(self, address, callback=None):
        """Connects the socket to a remote address without blocking.

        May only be called if the socket passed to the constructor was
        not previously connected.  The address parameter is in the
        same format as for socket.connect, i.e. a (host, port) tuple.
        If callback is specified, it will be called when the
        connection is completed.

        Note that it is safe to call IOStream.write while the
        connection is pending, in which case the data will be written
        as soon as the connection is ready.  Calling IOStream read
        methods before the socket is connected works on some platforms
        but is non-portable.
        """
        self._connecting = True
        try:
            self.socket.connect(address)
        except socket.error, e:
            # In non-blocking mode we expect connect() to raise an
            # exception with EINPROGRESS or EWOULDBLOCK.
            #
            # On freebsd, other errors such as ECONNREFUSED may be
            # returned immediately when attempting to connect to
            # localhost, so handle them the same way as an error
            # reported later in _handle_connect.
            if e.args[0] not in (errno.EINPROGRESS, errno.EWOULDBLOCK):
                logging.warning("Connect error on fd %d: %s",
                                self.socket.fileno(), e)
                self.close()
                return 
Example 44
Project: TESTGIT   Author: B-ROY   File: iostream.py    Apache License 2.0 5 votes vote down vote up
def connect(self, address, callback=None):
        # Save the user's callback and run it after the ssl handshake
        # has completed.
        self._ssl_connect_callback = callback
        super(SSLIOStream, self).connect(address, callback=None) 
Example 45
Project: TESTGIT   Author: B-ROY   File: iostream.py    Apache License 2.0 5 votes vote down vote up
def _handle_connect(self):
        # When the connection is complete, wrap the socket for SSL
        # traffic.  Note that we do this by overriding _handle_connect
        # instead of by passing a callback to super().connect because
        # user callbacks are enqueued asynchronously on the IOLoop,
        # but since _handle_events calls _handle_connect immediately
        # followed by _handle_write we need this to be synchronous.
        self.socket = ssl.wrap_socket(self.socket,
                                      do_handshake_on_connect=False,
                                      **self._ssl_options)
        super(SSLIOStream, self)._handle_connect() 
Example 46
Project: TESTGIT   Author: B-ROY   File: mongo_client.py    Apache License 2.0 5 votes vote down vote up
def _partition_node(node):
    """Split a host:port string returned from mongod/s into
    a (host, int(port)) pair needed for socket.connect().
    """
    host = node
    port = 27017
    idx = node.rfind(':')
    if idx != -1:
        host, port = node[:idx], int(node[idx + 1:])
    if host.startswith('['):
        host = host[1:-1]
    return host, port 
Example 47
Project: TESTGIT   Author: B-ROY   File: mongo_client.py    Apache License 2.0 5 votes vote down vote up
def alive(self):
        """Return ``False`` if there has been an error communicating with the
        server, else ``True``.

        This method attempts to check the status of the server with minimal I/O.
        The current thread / greenlet retrieves a socket from the pool (its
        request socket if it's in a request, or a random idle socket if it's not
        in a request) and checks whether calling `select`_ on it raises an
        error. If there are currently no idle sockets, :meth:`alive` will
        attempt to actually connect to the server.

        A more certain way to determine server availability is::

            client.admin.command('ping')

        .. _select: http://docs.python.org/2/library/select.html#select.select
        """
        # In the common case, a socket is available and was used recently, so
        # calling select() on it is a reasonable attempt to see if the OS has
        # reported an error. Note this can be wasteful: __socket implicitly
        # calls select() if the socket hasn't been checked in the last second,
        # or it may create a new socket, in which case calling select() is
        # redundant.
        try:
            sock_info = self.__socket()
            return not pool._closed(sock_info.sock)
        except (socket.error, ConnectionFailure):
            return False 
Example 48
Project: TESTGIT   Author: B-ROY   File: mongo_replica_set_client.py    Apache License 2.0 5 votes vote down vote up
def _partition_node(node):
    """Split a host:port string returned from mongod/s into
    a (host, int(port)) pair needed for socket.connect().
    """
    host = node
    port = 27017
    idx = node.rfind(':')
    if idx != -1:
        host, port = node[:idx], int(node[idx + 1:])
    if host.startswith('['):
        host = host[1:-1]
    return host, port


# Concurrency notes: A MongoReplicaSetClient keeps its view of the replica-set
# state in an RSState instance. RSStates are immutable, except for
# host-pinning. Pools, which are internally thread / greenlet safe, can be
# copied from old to new RSStates safely. The client updates its view of the
# set's state not by modifying its RSState but by replacing it with an updated
# copy.

# In __init__, MongoReplicaSetClient gets a list of potential members called
# 'seeds' from its initial parameters, and calls refresh(). refresh() iterates
# over the the seeds in arbitrary order looking for a member it can connect to.
# Once it finds one, it calls 'ismaster' and sets self.__hosts to the list of
# members in the response, and connects to the rest of the members. refresh()
# sets the MongoReplicaSetClient's RSState. Finally, __init__ launches the
# replica-set monitor.

# The monitor calls refresh() every 30 seconds, or whenever the client has
# encountered an error that prompts it to wake the monitor.

# Every method that accesses the RSState multiple times within the method makes
# a local reference first and uses that throughout, so it's isolated from a
# concurrent method replacing the RSState with an updated copy. This technique
# avoids the need to lock around accesses to the RSState. 
Example 49
Project: TESTGIT   Author: B-ROY   File: mongo_replica_set_client.py    Apache License 2.0 5 votes vote down vote up
def error_message(self):
        """The error, if any, raised when trying to connect to the primary"""
        return self._error_message 
Example 50
Project: TESTGIT   Author: B-ROY   File: mongo_replica_set_client.py    Apache License 2.0 5 votes vote down vote up
def seeds(self):
        """The seed list used to connect to this replica set.

        A sequence of (host, port) pairs.
        """
        return self.__seeds 
Example 51
Project: TESTGIT   Author: B-ROY   File: mongo_replica_set_client.py    Apache License 2.0 5 votes vote down vote up
def alive(self):
        """Return ``False`` if there has been an error communicating with the
        primary, else ``True``.

        This method attempts to check the status of the primary with minimal
        I/O. The current thread / greenlet retrieves a socket (its request
        socket if it's in a request, or a random idle socket if it's not in a
        request) from the primary's connection pool and checks whether calling
        select_ on it raises an error. If there are currently no idle sockets,
        or if there is no known primary, :meth:`alive` will attempt to actually
        find and connect to the primary.

        A more certain way to determine primary availability is to ping it::

            client.admin.command('ping')

        .. _select: http://docs.python.org/2/library/select.html#select.select
        """
        # In the common case, a socket is available and was used recently, so
        # calling select() on it is a reasonable attempt to see if the OS has
        # reported an error. Note this can be wasteful: __socket implicitly
        # calls select() if the socket hasn't been checked in the last second,
        # or it may create a new socket, in which case calling select() is
        # redundant.
        try:
            sock_info = self.__socket(self.__find_primary())
            return not pool._closed(sock_info.sock)
        except (socket.error, ConnectionFailure):
            return False 
Example 52
Project: redis-py-threaded   Author: paepcke   File: connection.py    MIT License 5 votes vote down vote up
def _connect(self):
        "Create a TCP socket connection"
        # we want to mimic what socket.create_connection does to support
        # ipv4/ipv6, but we want to set options prior to calling
        # socket.connect()
        err = None
        for res in socket.getaddrinfo(self.host, self.port, 0,
                                      socket.SOCK_STREAM):
            family, socktype, proto, canonname, socket_address = res
            sock = None
            try:
                sock = socket.socket(family, socktype, proto)
                # TCP_NODELAY
                sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

                # TCP_KEEPALIVE
                if self.socket_keepalive:
                    sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                    for k, v in iteritems(self.socket_keepalive_options):
                        sock.setsockopt(socket.SOL_TCP, k, v)

                # set the socket_connect_timeout before we connect
                sock.settimeout(self.socket_connect_timeout)

                # connect
                sock.connect(socket_address)

                # set the socket_timeout now that we're connected
                sock.settimeout(self.socket_timeout)
                return sock

            except socket.error as _:
                err = _
                if sock is not None:
                    sock.close()

        if err is not None:
            raise err
        raise socket.error("socket.getaddrinfo returned an empty list") 
Example 53
Project: redis-py-threaded   Author: paepcke   File: connection.py    MIT License 5 votes vote down vote up
def can_read(self, timeout=0):
        "Poll the socket to see if there's data that can be read."
        sock = self._sock
        if not sock:
            self.connect()
            sock = self._sock
        return self._parser.can_read() or \
            bool(select([sock], [], [], timeout)[0]) 
Example 54
Project: redis-py-threaded   Author: paepcke   File: connection.py    MIT License 5 votes vote down vote up
def _connect(self):
        "Create a Unix domain socket connection"
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        sock.settimeout(self.socket_timeout)
        sock.connect(self.path)
        return sock 
Example 55
Project: redis-py-threaded   Author: paepcke   File: threadedConnection.py    MIT License 5 votes vote down vote up
def _connect(self):
        "Create a TCP socket connection"
        # we want to mimic what socket.create_connection does to support
        # ipv4/ipv6, but we want to set options prior to calling
        # socket.connect()
        err = None
        for res in socket.getaddrinfo(self.host, self.port, 0,
                                      socket.SOCK_STREAM):
            family, socktype, proto, canonname, socket_address = res
            sock = None
            try:
                sock = socket.socket(family, socktype, proto)
                # TCP_NODELAY
                sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

                # TCP_KEEPALIVE
                if self.socket_keepalive:
                    sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                    for k, v in iteritems(self.socket_keepalive_options):
                        sock.setsockopt(socket.SOL_TCP, k, v)

                # set the socket_connect_timeout before we connect
                sock.settimeout(self.socket_connect_timeout)

                # connect
                sock.connect(socket_address)

                # set the socket_timeout now that we're connected
                sock.settimeout(self.socket_timeout)
                return sock

            except socket.error as _:
                err = _
                if sock is not None:
                    sock.close()

        if err is not None:
            raise err
        raise socket.error("socket.getaddrinfo returned an empty list") 
Example 56
Project: redis-py-threaded   Author: paepcke   File: threadedConnection.py    MIT License 5 votes vote down vote up
def can_read(self, timeout=0):
        "Poll the socket to see if there's data that can be read."
        sock = self._sock
        if not sock:
            self.connect()
            sock = self._sock
        return self._parser.can_read() or \
            bool(select([sock], [], [], timeout)[0]) 
Example 57
Project: redis-py-threaded   Author: paepcke   File: threadedConnection.py    MIT License 5 votes vote down vote up
def _connect(self):
        "Create a Unix domain socket connection"
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        sock.settimeout(self.socket_timeout)
        sock.connect(self.path)
        return sock 
Example 58
Project: unhuman-resources   Author: agajdosi   File: iostream.py    GNU General Public License v3.0 5 votes vote down vote up
def _handle_connect(self) -> None:
        # Call the superclass method to check for errors.
        super(SSLIOStream, self)._handle_connect()
        if self.closed():
            return
        # When the connection is complete, wrap the socket for SSL
        # traffic.  Note that we do this by overriding _handle_connect
        # instead of by passing a callback to super().connect because
        # user callbacks are enqueued asynchronously on the IOLoop,
        # but since _handle_events calls _handle_connect immediately
        # followed by _handle_write we need this to be synchronous.
        #
        # The IOLoop will get confused if we swap out self.socket while the
        # fd is registered, so remove it now and re-register after
        # wrap_socket().
        self.io_loop.remove_handler(self.socket)
        old_state = self._state
        assert old_state is not None
        self._state = None
        self.socket = ssl_wrap_socket(
            self.socket,
            self._ssl_options,
            server_hostname=self._server_hostname,
            do_handshake_on_connect=False,
        )
        self._add_io_state(old_state) 
Example 59
Project: unhuman-resources   Author: agajdosi   File: iostream.py    GNU General Public License v3.0 5 votes vote down vote up
def wait_for_handshake(self) -> "Future[SSLIOStream]":
        """Wait for the initial SSL handshake to complete.

        If a ``callback`` is given, it will be called with no
        arguments once the handshake is complete; otherwise this
        method returns a `.Future` which will resolve to the
        stream itself after the handshake is complete.

        Once the handshake is complete, information such as
        the peer's certificate and NPN/ALPN selections may be
        accessed on ``self.socket``.

        This method is intended for use on server-side streams
        or after using `IOStream.start_tls`; it should not be used
        with `IOStream.connect` (which already waits for the
        handshake to complete). It may only be called once per stream.

        .. versionadded:: 4.2

        .. versionchanged:: 6.0

           The ``callback`` argument was removed. Use the returned
           `.Future` instead.

        """
        if self._ssl_connect_future is not None:
            raise RuntimeError("Already waiting")
        future = self._ssl_connect_future = Future()
        if not self._ssl_accepting:
            self._finish_ssl_connect()
        return future 
Example 60
Project: unhuman-resources   Author: agajdosi   File: iostream.py    GNU General Public License v3.0 5 votes vote down vote up
def _handle_connect(self) -> None:
        # Call the superclass method to check for errors.
        super(SSLIOStream, self)._handle_connect()
        if self.closed():
            return
        # When the connection is complete, wrap the socket for SSL
        # traffic.  Note that we do this by overriding _handle_connect
        # instead of by passing a callback to super().connect because
        # user callbacks are enqueued asynchronously on the IOLoop,
        # but since _handle_events calls _handle_connect immediately
        # followed by _handle_write we need this to be synchronous.
        #
        # The IOLoop will get confused if we swap out self.socket while the
        # fd is registered, so remove it now and re-register after
        # wrap_socket().
        self.io_loop.remove_handler(self.socket)
        old_state = self._state
        assert old_state is not None
        self._state = None
        self.socket = ssl_wrap_socket(
            self.socket,
            self._ssl_options,
            server_hostname=self._server_hostname,
            do_handshake_on_connect=False,
        )
        self._add_io_state(old_state) 
Example 61
Project: unhuman-resources   Author: agajdosi   File: iostream.py    GNU General Public License v3.0 5 votes vote down vote up
def wait_for_handshake(self) -> "Future[SSLIOStream]":
        """Wait for the initial SSL handshake to complete.

        If a ``callback`` is given, it will be called with no
        arguments once the handshake is complete; otherwise this
        method returns a `.Future` which will resolve to the
        stream itself after the handshake is complete.

        Once the handshake is complete, information such as
        the peer's certificate and NPN/ALPN selections may be
        accessed on ``self.socket``.

        This method is intended for use on server-side streams
        or after using `IOStream.start_tls`; it should not be used
        with `IOStream.connect` (which already waits for the
        handshake to complete). It may only be called once per stream.

        .. versionadded:: 4.2

        .. versionchanged:: 6.0

           The ``callback`` argument was removed. Use the returned
           `.Future` instead.

        """
        if self._ssl_connect_future is not None:
            raise RuntimeError("Already waiting")
        future = self._ssl_connect_future = Future()
        if not self._ssl_accepting:
            self._finish_ssl_connect()
        return future 
Example 62
Project: banruo   Author: yingshang   File: iostream.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def connect(self, address, callback=None, server_hostname=None):
        self._server_hostname = server_hostname
        # Pass a dummy callback to super.connect(), which is slightly
        # more efficient than letting it return a Future we ignore.
        super(SSLIOStream, self).connect(address, callback=lambda: None)
        return self.wait_for_handshake(callback) 
Example 63
Project: banruo   Author: yingshang   File: iostream.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def wait_for_handshake(self, callback=None):
        """Wait for the initial SSL handshake to complete.

        If a ``callback`` is given, it will be called with no
        arguments once the handshake is complete; otherwise this
        method returns a `.Future` which will resolve to the
        stream itself after the handshake is complete.

        Once the handshake is complete, information such as
        the peer's certificate and NPN/ALPN selections may be
        accessed on ``self.socket``.

        This method is intended for use on server-side streams
        or after using `IOStream.start_tls`; it should not be used
        with `IOStream.connect` (which already waits for the
        handshake to complete). It may only be called once per stream.

        .. versionadded:: 4.2
        """
        if (self._ssl_connect_callback is not None or
                self._ssl_connect_future is not None):
            raise RuntimeError("Already waiting")
        if callback is not None:
            self._ssl_connect_callback = stack_context.wrap(callback)
            future = None
        else:
            future = self._ssl_connect_future = TracebackFuture()
        if not self._ssl_accepting:
            self._run_ssl_connect_callback()
        return future 
Example 64
Project: opendevops   Author: opendevops-cn   File: iostream.py    GNU General Public License v3.0 5 votes vote down vote up
def _handle_connect(self) -> None:
        # Call the superclass method to check for errors.
        super(SSLIOStream, self)._handle_connect()
        if self.closed():
            return
        # When the connection is complete, wrap the socket for SSL
        # traffic.  Note that we do this by overriding _handle_connect
        # instead of by passing a callback to super().connect because
        # user callbacks are enqueued asynchronously on the IOLoop,
        # but since _handle_events calls _handle_connect immediately
        # followed by _handle_write we need this to be synchronous.
        #
        # The IOLoop will get confused if we swap out self.socket while the
        # fd is registered, so remove it now and re-register after
        # wrap_socket().
        self.io_loop.remove_handler(self.socket)
        old_state = self._state
        assert old_state is not None
        self._state = None
        self.socket = ssl_wrap_socket(
            self.socket,
            self._ssl_options,
            server_hostname=self._server_hostname,
            do_handshake_on_connect=False,
        )
        self._add_io_state(old_state) 
Example 65
Project: opendevops   Author: opendevops-cn   File: iostream.py    GNU General Public License v3.0 5 votes vote down vote up
def wait_for_handshake(self) -> "Future[SSLIOStream]":
        """Wait for the initial SSL handshake to complete.

        If a ``callback`` is given, it will be called with no
        arguments once the handshake is complete; otherwise this
        method returns a `.Future` which will resolve to the
        stream itself after the handshake is complete.

        Once the handshake is complete, information such as
        the peer's certificate and NPN/ALPN selections may be
        accessed on ``self.socket``.

        This method is intended for use on server-side streams
        or after using `IOStream.start_tls`; it should not be used
        with `IOStream.connect` (which already waits for the
        handshake to complete). It may only be called once per stream.

        .. versionadded:: 4.2

        .. versionchanged:: 6.0

           The ``callback`` argument was removed. Use the returned
           `.Future` instead.

        """
        if self._ssl_connect_future is not None:
            raise RuntimeError("Already waiting")
        future = self._ssl_connect_future = Future()
        if not self._ssl_accepting:
            self._finish_ssl_connect()
        return future 
Example 66
Project: open-recipe   Author: dspray95   File: tcp.py    The Unlicense 5 votes vote down vote up
def stopConnecting(self):
        """
        If a connection attempt is still outstanding (i.e.  no connection is
        yet established), immediately stop attempting to connect.
        """
        self.failIfNotConnected(error.UserError()) 
Example 67
Project: vnpy_crypto   Author: birforce   File: tunnel.py    MIT License 5 votes vote down vote up
def tunnel_connection(socket, addr, server, keyfile=None, password=None, paramiko=None, timeout=60):
    """Connect a socket to an address via an ssh tunnel.
    
    This is a wrapper for socket.connect(addr), when addr is not accessible
    from the local machine.  It simply creates an ssh tunnel using the remaining args,
    and calls socket.connect('tcp://localhost:lport') where lport is the randomly
    selected local port of the tunnel.
    
    """
    new_url, tunnel = open_tunnel(addr, server, keyfile=keyfile, password=password, paramiko=paramiko, timeout=timeout)
    socket.connect(new_url)
    return tunnel 
Example 68
Project: vnpy_crypto   Author: birforce   File: tunnel.py    MIT License 5 votes vote down vote up
def _paramiko_tunnel(lport, rport, server, remoteip, keyfile=None, password=None):
    """Function for actually starting a paramiko tunnel, to be passed
    to multiprocessing.Process(target=this), and not called directly.
    """
    username, server, port = _split_server(server)
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())

    try:
        client.connect(server, port, username=username, key_filename=keyfile,
                       look_for_keys=True, password=password)
#    except paramiko.AuthenticationException:
#        if password is None:
#            password = getpass("%s@%s's password: "%(username, server))
#            client.connect(server, port, username=username, password=password)
#        else:
#            raise
    except Exception as e:
        print('*** Failed to connect to %s:%d: %r' % (server, port, e))
        sys.exit(1)

    # Don't let SIGINT kill the tunnel subprocess
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    try:
        forward_tunnel(lport, remoteip, rport, client.get_transport())
    except KeyboardInterrupt:
        print('SIGINT: Port forwarding stopped cleanly')
        sys.exit(0)
    except Exception as e:
        print("Port forwarding stopped uncleanly: %s"%e)
        sys.exit(255) 
Example 69
Project: networkzero   Author: tjguk   File: discovery.py    MIT License 5 votes vote down vote up
def _rpc(action, *args, **kwargs):
    _logger.debug("About to send rpc request %s with args %s, kwargs %s", action, args, kwargs)
    wait_for_s = kwargs.pop("wait_for_s", 5)
    with sockets.context.socket(zmq.REQ) as socket:
        #
        # To avoid problems when restarting a beacon not long after it's been
        # closed, force the socket to shut down regardless about 1 second after 
        # it's been closed.
        #
        socket.connect("tcp://localhost:%s" % _Beacon.rpc_port)
        socket.send(_pack([action] + list(args)))
        reply = sockets._sockets._receive_with_timeout(socket, wait_for_s)
        return _unpack(reply) 
Example 70
Project: networkzero   Author: tjguk   File: discovery.py    MIT License 5 votes vote down vote up
def discover(name, wait_for_s=60):
    """Discover a service by name
    
    Look for an advert to a named service::
    
        address = nw0.discover("myservice")
        
    :param name: any text
    :param wait_for_s: how many seconds to wait before giving up
    :returns: the address found or None
    """
    _start_beacon()
    #
    # It's possible to enter a deadlock situation where the first
    # process fires off a discovery request and waits for the
    # second process to advertise. But the second process has to
    # connect to the rpc port of the first process' beacon and
    # its advertisement is queued behind the pending discovery.
    #
    # To give both a chance of succeeding we operate in bursts,
    # allowing them to interleave.
    #
    t0 = time.time()
    while True:
        discovery = _rpc("discover", name, 0.5)
        if discovery:
            return discovery
        if timed_out(t0, wait_for_s):
            return None 
Example 71
Project: tornado-zh   Author: tao12345666333   File: iostream.py    MIT License 4 votes vote down vote up
def _handle_events(self, fd, events):
        if self.closed():
            gen_log.warning("Got events for closed stream %s", fd)
            return
        try:
            if self._connecting:
                # Most IOLoops will report a write failed connect
                # with the WRITE event, but SelectIOLoop reports a
                # READ as well so we must check for connecting before
                # either.
                self._handle_connect()
            if self.closed():
                return
            if events & self.io_loop.READ:
                self._handle_read()
            if self.closed():
                return
            if events & self.io_loop.WRITE:
                self._handle_write()
            if self.closed():
                return
            if events & self.io_loop.ERROR:
                self.error = self.get_fd_error()
                # We may have queued up a user callback in _handle_read or
                # _handle_write, so don't close the IOStream until those
                # callbacks have had a chance to run.
                self.io_loop.add_callback(self.close)
                return
            state = self.io_loop.ERROR
            if self.reading():
                state |= self.io_loop.READ
            if self.writing():
                state |= self.io_loop.WRITE
            if state == self.io_loop.ERROR and self._read_buffer_size == 0:
                # If the connection is idle, listen for reads too so
                # we can tell if the connection is closed.  If there is
                # data in the read buffer we won't run the close callback
                # yet anyway, so we don't need to listen in this case.
                state |= self.io_loop.READ
            if state != self._state:
                assert self._state is not None, \
                    "shouldn't happen: _handle_events without self._state"
                self._state = state
                self.io_loop.update_handler(self.fileno(), self._state)
        except UnsatisfiableReadError as e:
            gen_log.info("Unsatisfiable read, closing connection: %s" % e)
            self.close(exc_info=True)
        except Exception:
            gen_log.error("Uncaught exception, closing connection.",
                          exc_info=True)
            self.close(exc_info=True)
            raise 
Example 72
Project: tornado-zh   Author: tao12345666333   File: iostream.py    MIT License 4 votes vote down vote up
def _handle_events(self, fd, events):
        if self.closed():
            gen_log.warning("Got events for closed stream %s", fd)
            return
        try:
            if self._connecting:
                # Most IOLoops will report a write failed connect
                # with the WRITE event, but SelectIOLoop reports a
                # READ as well so we must check for connecting before
                # either.
                self._handle_connect()
            if self.closed():
                return
            if events & self.io_loop.READ:
                self._handle_read()
            if self.closed():
                return
            if events & self.io_loop.WRITE:
                self._handle_write()
            if self.closed():
                return
            if events & self.io_loop.ERROR:
                self.error = self.get_fd_error()
                # We may have queued up a user callback in _handle_read or
                # _handle_write, so don't close the IOStream until those
                # callbacks have had a chance to run.
                self.io_loop.add_callback(self.close)
                return
            state = self.io_loop.ERROR
            if self.reading():
                state |= self.io_loop.READ
            if self.writing():
                state |= self.io_loop.WRITE
            if state == self.io_loop.ERROR and self._read_buffer_size == 0:
                # If the connection is idle, listen for reads too so
                # we can tell if the connection is closed.  If there is
                # data in the read buffer we won't run the close callback
                # yet anyway, so we don't need to listen in this case.
                state |= self.io_loop.READ
            if state != self._state:
                assert self._state is not None, \
                    "shouldn't happen: _handle_events without self._state"
                self._state = state
                self.io_loop.update_handler(self.fileno(), self._state)
        except UnsatisfiableReadError as e:
            gen_log.info("Unsatisfiable read, closing connection: %s" % e)
            self.close(exc_info=True)
        except Exception:
            gen_log.error("Uncaught exception, closing connection.",
                          exc_info=True)
            self.close(exc_info=True)
            raise 
Example 73
Project: TornadoWeb   Author: VxCoder   File: iostream.py    Apache License 2.0 4 votes vote down vote up
def _handle_events(self, fd, events):
        if self.closed():
            gen_log.warning("Got events for closed stream %s", fd)
            return
        try:
            if self._connecting:
                # Most IOLoops will report a write failed connect
                # with the WRITE event, but SelectIOLoop reports a
                # READ as well so we must check for connecting before
                # either.
                self._handle_connect()
            if self.closed():
                return
            if events & self.io_loop.READ:
                self._handle_read()
            if self.closed():
                return
            if events & self.io_loop.WRITE:
                self._handle_write()
            if self.closed():
                return
            if events & self.io_loop.ERROR:
                self.error = self.get_fd_error()
                # We may have queued up a user callback in _handle_read or
                # _handle_write, so don't close the IOStream until those
                # callbacks have had a chance to run.
                self.io_loop.add_callback(self.close)
                return
            state = self.io_loop.ERROR
            if self.reading():
                state |= self.io_loop.READ
            if self.writing():
                state |= self.io_loop.WRITE
            if state == self.io_loop.ERROR and self._read_buffer_size == 0:
                # If the connection is idle, listen for reads too so
                # we can tell if the connection is closed.  If there is
                # data in the read buffer we won't run the close callback
                # yet anyway, so we don't need to listen in this case.
                state |= self.io_loop.READ
            if state != self._state:
                assert self._state is not None, \
                    "shouldn't happen: _handle_events without self._state"
                self._state = state
                self.io_loop.update_handler(self.fileno(), self._state)
        except UnsatisfiableReadError as e:
            gen_log.info("Unsatisfiable read, closing connection: %s" % e)
            self.close(exc_info=True)
        except Exception:
            gen_log.error("Uncaught exception, closing connection.",
                          exc_info=True)
            self.close(exc_info=True)
            raise 
Example 74
Project: recruit   Author: Frank-qlu   File: mongo_client.py    Apache License 2.0 4 votes vote down vote up
def __try_node(self, node):
        """Try to connect to this node and see if it works for our connection
        type. Returns a Member and set of hosts (including this one). Doesn't
        modify state.

        :Parameters:
         - `node`: The (host, port) pair to try.
        """
        # Call 'ismaster' directly so we can get a response time.
        connection_pool = self.__create_pool(node)
        sock_info = connection_pool.get_socket()
        try:
            response, res_time = self.__simple_command(sock_info,
                                                       'admin',
                                                       {'ismaster': 1})
        finally:
            connection_pool.maybe_return_socket(sock_info)

        member = Member(
            node,
            connection_pool,
            response,
            res_time)

        nodes = frozenset([node])

        # Replica Set?
        if not self.__direct:
            # Check that this host is part of the given replica set.
            if self.__repl and member.set_name != self.__repl:
                raise ConfigurationError("%s:%d is not a member of "
                                         "replica set %s"
                                         % (node[0], node[1], self.__repl))

            if "hosts" in response:
                nodes = frozenset([
                    _partition_node(h) for h in response["hosts"]])

            if member.is_primary:
                return member, nodes

            elif "primary" in response:
                # Shortcut: a secondary usually tells us who the primary is.
                candidate = _partition_node(response["primary"])
                return self.__try_node(candidate)

            # Explain why we aren't using this connection.
            raise AutoReconnect('%s:%d is not primary or master' % node)

        # Direct connection
        if member.is_arbiter and not self.__direct:
            raise ConfigurationError("%s:%d is an arbiter" % node)

        return member, nodes 
Example 75
Project: TESTGIT   Author: B-ROY   File: mongo_client.py    Apache License 2.0 4 votes vote down vote up
def __find_node(self, seeds=None):
        """Find a host, port pair suitable for our connection type.

        If only one host was supplied to __init__ see if we can connect
        to it. Don't check if the host is a master/primary so we can make
        a direct connection to read from a secondary or send commands to
        an arbiter.

        If more than one host was supplied treat them as a seed list for
        connecting to a replica set or to support high availability for
        mongos. If connecting to a replica set try to find the primary
        and fail if we can't, possibly updating any replSet information
        on success. If a mongos seed list was provided find the "nearest"
        mongos and return it.

        Otherwise we iterate through the list trying to find a host we can
        send write operations to.

        Sets __host and __port so that :attr:`host` and :attr:`port`
        will return the address of the connected host. Sets __is_primary to
        True if this is a primary or master, else False. Sets __is_mongos
        to True if the connection is to a mongos.
        """
        errors = []
        mongos_candidates = []
        candidates = seeds or self.__nodes.copy()
        for candidate in candidates:
            try:
                node, ismaster, isdbgrid, res_time = self.__try_node(candidate)
                self.__is_primary = ismaster
                self.__is_mongos = isdbgrid
                # No need to calculate nearest if we only have one mongos.
                if isdbgrid and not self.__direct:
                    mongos_candidates.append((node, res_time))
                    continue
                elif len(mongos_candidates):
                    raise ConfigurationError("Seed list cannot contain a mix "
                                             "of mongod and mongos instances.")
                return node
            except Exception, why:
                errors.append(str(why))

        # If we have a mongos seed list, pick the "nearest" member. 
Example 76
Project: unhuman-resources   Author: agajdosi   File: iostream.py    GNU General Public License v3.0 4 votes vote down vote up
def _handle_events(self, fd: Union[int, ioloop._Selectable], events: int) -> None:
        if self.closed():
            gen_log.warning("Got events for closed stream %s", fd)
            return
        try:
            if self._connecting:
                # Most IOLoops will report a write failed connect
                # with the WRITE event, but SelectIOLoop reports a
                # READ as well so we must check for connecting before
                # either.
                self._handle_connect()
            if self.closed():
                return
            if events & self.io_loop.READ:
                self._handle_read()
            if self.closed():
                return
            if events & self.io_loop.WRITE:
                self._handle_write()
            if self.closed():
                return
            if events & self.io_loop.ERROR:
                self.error = self.get_fd_error()
                # We may have queued up a user callback in _handle_read or
                # _handle_write, so don't close the IOStream until those
                # callbacks have had a chance to run.
                self.io_loop.add_callback(self.close)
                return
            state = self.io_loop.ERROR
            if self.reading():
                state |= self.io_loop.READ
            if self.writing():
                state |= self.io_loop.WRITE
            if state == self.io_loop.ERROR and self._read_buffer_size == 0:
                # If the connection is idle, listen for reads too so
                # we can tell if the connection is closed.  If there is
                # data in the read buffer we won't run the close callback
                # yet anyway, so we don't need to listen in this case.
                state |= self.io_loop.READ
            if state != self._state:
                assert (
                    self._state is not None
                ), "shouldn't happen: _handle_events without self._state"
                self._state = state
                self.io_loop.update_handler(self.fileno(), self._state)
        except UnsatisfiableReadError as e:
            gen_log.info("Unsatisfiable read, closing connection: %s" % e)
            self.close(exc_info=e)
        except Exception as e:
            gen_log.error("Uncaught exception, closing connection.", exc_info=True)
            self.close(exc_info=e)
            raise 
Example 77
Project: unhuman-resources   Author: agajdosi   File: iostream.py    GNU General Public License v3.0 4 votes vote down vote up
def _handle_events(self, fd: Union[int, ioloop._Selectable], events: int) -> None:
        if self.closed():
            gen_log.warning("Got events for closed stream %s", fd)
            return
        try:
            if self._connecting:
                # Most IOLoops will report a write failed connect
                # with the WRITE event, but SelectIOLoop reports a
                # READ as well so we must check for connecting before
                # either.
                self._handle_connect()
            if self.closed():
                return
            if events & self.io_loop.READ:
                self._handle_read()
            if self.closed():
                return
            if events & self.io_loop.WRITE:
                self._handle_write()
            if self.closed():
                return
            if events & self.io_loop.ERROR:
                self.error = self.get_fd_error()
                # We may have queued up a user callback in _handle_read or
                # _handle_write, so don't close the IOStream until those
                # callbacks have had a chance to run.
                self.io_loop.add_callback(self.close)
                return
            state = self.io_loop.ERROR
            if self.reading():
                state |= self.io_loop.READ
            if self.writing():
                state |= self.io_loop.WRITE
            if state == self.io_loop.ERROR and self._read_buffer_size == 0:
                # If the connection is idle, listen for reads too so
                # we can tell if the connection is closed.  If there is
                # data in the read buffer we won't run the close callback
                # yet anyway, so we don't need to listen in this case.
                state |= self.io_loop.READ
            if state != self._state:
                assert (
                    self._state is not None
                ), "shouldn't happen: _handle_events without self._state"
                self._state = state
                self.io_loop.update_handler(self.fileno(), self._state)
        except UnsatisfiableReadError as e:
            gen_log.info("Unsatisfiable read, closing connection: %s" % e)
            self.close(exc_info=e)
        except Exception as e:
            gen_log.error("Uncaught exception, closing connection.", exc_info=True)
            self.close(exc_info=e)
            raise 
Example 78
Project: banruo   Author: yingshang   File: iostream.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def _handle_events(self, fd, events):
        if self.closed():
            gen_log.warning("Got events for closed stream %s", fd)
            return
        try:
            if self._connecting:
                # Most IOLoops will report a write failed connect
                # with the WRITE event, but SelectIOLoop reports a
                # READ as well so we must check for connecting before
                # either.
                self._handle_connect()
            if self.closed():
                return
            if events & self.io_loop.READ:
                self._handle_read()
            if self.closed():
                return
            if events & self.io_loop.WRITE:
                self._handle_write()
            if self.closed():
                return
            if events & self.io_loop.ERROR:
                self.error = self.get_fd_error()
                # We may have queued up a user callback in _handle_read or
                # _handle_write, so don't close the IOStream until those
                # callbacks have had a chance to run.
                self.io_loop.add_callback(self.close)
                return
            state = self.io_loop.ERROR
            if self.reading():
                state |= self.io_loop.READ
            if self.writing():
                state |= self.io_loop.WRITE
            if state == self.io_loop.ERROR and self._read_buffer_size == 0:
                # If the connection is idle, listen for reads too so
                # we can tell if the connection is closed.  If there is
                # data in the read buffer we won't run the close callback
                # yet anyway, so we don't need to listen in this case.
                state |= self.io_loop.READ
            if state != self._state:
                assert self._state is not None, \
                    "shouldn't happen: _handle_events without self._state"
                self._state = state
                self.io_loop.update_handler(self.fileno(), self._state)
        except UnsatisfiableReadError as e:
            gen_log.info("Unsatisfiable read, closing connection: %s" % e)
            self.close(exc_info=True)
        except Exception:
            gen_log.error("Uncaught exception, closing connection.",
                          exc_info=True)
            self.close(exc_info=True)
            raise 
Example 79
Project: opendevops   Author: opendevops-cn   File: iostream.py    GNU General Public License v3.0 4 votes vote down vote up
def _handle_events(self, fd: Union[int, ioloop._Selectable], events: int) -> None:
        if self.closed():
            gen_log.warning("Got events for closed stream %s", fd)
            return
        try:
            if self._connecting:
                # Most IOLoops will report a write failed connect
                # with the WRITE event, but SelectIOLoop reports a
                # READ as well so we must check for connecting before
                # either.
                self._handle_connect()
            if self.closed():
                return
            if events & self.io_loop.READ:
                self._handle_read()
            if self.closed():
                return
            if events & self.io_loop.WRITE:
                self._handle_write()
            if self.closed():
                return
            if events & self.io_loop.ERROR:
                self.error = self.get_fd_error()
                # We may have queued up a user callback in _handle_read or
                # _handle_write, so don't close the IOStream until those
                # callbacks have had a chance to run.
                self.io_loop.add_callback(self.close)
                return
            state = self.io_loop.ERROR
            if self.reading():
                state |= self.io_loop.READ
            if self.writing():
                state |= self.io_loop.WRITE
            if state == self.io_loop.ERROR and self._read_buffer_size == 0:
                # If the connection is idle, listen for reads too so
                # we can tell if the connection is closed.  If there is
                # data in the read buffer we won't run the close callback
                # yet anyway, so we don't need to listen in this case.
                state |= self.io_loop.READ
            if state != self._state:
                assert (
                    self._state is not None
                ), "shouldn't happen: _handle_events without self._state"
                self._state = state
                self.io_loop.update_handler(self.fileno(), self._state)
        except UnsatisfiableReadError as e:
            gen_log.info("Unsatisfiable read, closing connection: %s" % e)
            self.close(exc_info=e)
        except Exception as e:
            gen_log.error("Uncaught exception, closing connection.", exc_info=True)
            self.close(exc_info=e)
            raise 
Example 80
Project: vnpy_crypto   Author: birforce   File: tunnel.py    MIT License 4 votes vote down vote up
def paramiko_tunnel(lport, rport, server, remoteip='127.0.0.1', keyfile=None, password=None, timeout=60):
    """launch a tunner with paramiko in a subprocess. This should only be used
    when shell ssh is unavailable (e.g. Windows).
    
    This creates a tunnel redirecting `localhost:lport` to `remoteip:rport`,
    as seen from `server`.
    
    If you are familiar with ssh tunnels, this creates the tunnel:
    
    ssh server -L localhost:lport:remoteip:rport
    
    keyfile and password may be specified, but ssh config is checked for defaults.
    
    
    Parameters
    ----------
    
    lport : int
        local port for connecting to the tunnel from this machine.
    rport : int
        port on the remote machine to connect to.
    server : str
        The ssh server to connect to. The full ssh server string will be parsed.
        user@server:port
    remoteip : str [Default: 127.0.0.1]
        The remote ip, specifying the destination of the tunnel.
        Default is localhost, which means that the tunnel would redirect
        localhost:lport on this machine to localhost:rport on the *server*.
        
    keyfile : str; path to public key file
        This specifies a key to be used in ssh login, default None.
        Regular default ssh keys will be used without specifying this argument.
    password : str; 
        Your ssh password to the ssh server. Note that if this is left None,
        you will be prompted for it if passwordless key based login is unavailable.
    timeout : int [default: 60]
        The time (in seconds) after which no activity will result in the tunnel
        closing.  This prevents orphaned tunnels from running forever.
    
    """
    if paramiko is None:
        raise ImportError("Paramiko not available")
    
    if password is None:
        if not _try_passwordless_paramiko(server, keyfile):
            password = getpass("%s's password: "%(server))

    p = Process(target=_paramiko_tunnel, 
            args=(lport, rport, server, remoteip), 
            kwargs=dict(keyfile=keyfile, password=password))
    p.daemon = True
    p.start()
    return p