Python twisted.internet.error.ConnectError() Examples

The following are 30 code examples of twisted.internet.error.ConnectError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.internet.error , or try the search function .
Example #1
Source File: gcm.py    From autopush with Mozilla Public License 2.0 6 votes vote down vote up
def _process_error(self, failure):
        err = failure.value
        if isinstance(err, gcmclient.GCMAuthenticationError):
            self.log.error("GCM Authentication Error: %s" % err)
            raise RouterException("Server error", status_code=500,
                                  errno=901)
        if isinstance(err, TimeoutError):
            self.log.warn("GCM Timeout: %s" % err)
            self.metrics.increment("notification.bridge.error",
                                   tags=make_tags(
                                       self._base_tags,
                                       reason="timeout"))
            raise RouterException("Server error", status_code=502,
                                  errno=903,
                                  log_exception=False)
        if isinstance(err, ConnectError):
            self.log.warn("GCM Unavailable: %s" % err)
            self.metrics.increment("notification.bridge.error",
                                   tags=make_tags(
                                       self._base_tags,
                                       reason="connection_unavailable"))
            raise RouterException("Server error", status_code=502,
                                  errno=902,
                                  log_exception=False)
        return failure 
Example #2
Source File: twisted.py    From python-consul2 with MIT License 6 votes vote down vote up
def request(self, callback, method, url, **kwargs):
        if 'data' in kwargs and not isinstance(kwargs['data'], bytes):
            # python2/3 compatibility
            data = kwargs.pop('data')
            kwargs['data'] = data.encode(encoding='utf-8') \
                if hasattr(data, 'encode') else b(data)

        try:
            response = yield self.client.request(method, url, **kwargs)
            parsed = yield self._get_resp(response)
            returnValue(callback(self.response(*parsed)))
        except ConnectError as e:
            raise ConsulException(
                '{}: {}'.format(e.__class__.__name__, e.message))
        except ResponseNeverReceived:
            # this exception is raised if the connection to the server is lost
            # when yielding a response, this could be due to network issues or
            # server restarts
            raise ConsulException(
                'Server connection lost: {} {}'.format(method.upper(), url))
        except RequestTransmissionFailed:
            # this exception is expected if the reactor is stopped mid request
            raise ConsulException(
                'Request incomplete: {} {}'.format(method.upper(), url)) 
Example #3
Source File: test_endpoints.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_endpointConnectFailure(self):
        """
        If an endpoint tries to connect to a non-listening port it gets
        a C{ConnectError} failure.
        """
        expectedError = error.ConnectError(string="Connection Failed")
        mreactor = RaisingMemoryReactorWithClock(connectException=expectedError)
        clientFactory = object()

        ep, ignoredArgs, ignoredDest = self.createClientEndpoint(
            mreactor, clientFactory)

        d = ep.connect(clientFactory)
        mreactor.advance(0.3)
        self.assertEqual(self.failureResultOf(d).value, expectedError)
        self.assertEqual([], mreactor.getDelayedCalls()) 
Example #4
Source File: test_endpoints.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_endpointConnectFailureAfterIteration(self):
        """
        If a connection attempt initiated by
        L{HostnameEndpoint.connect} fails only after
        L{HostnameEndpoint} has exhausted the list of possible server
        addresses, the returned L{Deferred} will fail with
        C{ConnectError}.
        """
        expectedError = error.ConnectError(string="Connection Failed")

        mreactor = MemoryReactor()

        clientFactory = object()

        ep, ignoredArgs, ignoredDest = self.createClientEndpoint(
            mreactor, clientFactory)

        d = ep.connect(clientFactory)
        mreactor.advance(0.3)
        host, port, factory, timeout, bindAddress = mreactor.tcpClients[0]
        factory.clientConnectionFailed(mreactor.connectors[0], expectedError)
        self.assertEqual(self.failureResultOf(d).value, expectedError)
        self.assertEqual([], mreactor.getDelayedCalls()) 
Example #5
Source File: test_endpoints.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_endpointConnectFailure(self):
        """
        If L{HostnameEndpoint.connect} is invoked and there is no server
        listening for connections, the returned L{Deferred} will fail with
        C{ConnectError}.
        """
        expectedError = error.ConnectError(string="Connection Failed")

        mreactor = RaisingMemoryReactorWithClock(
                connectException=expectedError)

        clientFactory = object()

        ep, ignoredArgs, ignoredDest = self.createClientEndpoint(
            mreactor, clientFactory)

        d = ep.connect(clientFactory)
        mreactor.advance(endpoints.HostnameEndpoint._DEFAULT_ATTEMPT_DELAY)
        self.assertEqual(self.failureResultOf(d).value, expectedError)
        self.assertEqual([], mreactor.getDelayedCalls()) 
Example #6
Source File: test_endpoints.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_endpointConnectFailure(self):
        """
        If an endpoint tries to connect to a non-listening port it gets
        a C{ConnectError} failure.
        """
        expectedError = error.ConnectError(string="Connection Failed")

        mreactor = RaisingMemoryReactor(connectException=expectedError)

        clientFactory = object()

        ep, ignoredArgs, ignoredDest = self.createClientEndpoint(
            mreactor, clientFactory)

        d = ep.connect(clientFactory)

        receivedExceptions = []

        def checkFailure(f):
            receivedExceptions.append(f.value)

        d.addErrback(checkFailure)

        self.assertEqual(receivedExceptions, [expectedError]) 
Example #7
Source File: test_endpoints.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_clientConnectionFailed(self):
        """
        Calls to L{_WrappingFactory.clientConnectionLost} should errback the
        L{_WrappingFactory._onConnection} L{Deferred}
        """
        wf = endpoints._WrappingFactory(TestFactory())
        expectedFailure = Failure(error.ConnectError(string="fail"))

        wf.clientConnectionFailed(None, expectedFailure)

        errors = []

        def gotError(f):
            errors.append(f)

        wf._onConnection.addErrback(gotError)

        self.assertEqual(errors, [expectedFailure]) 
Example #8
Source File: test_endpoints.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_clientConnectionFailed(self):
        """
        Calls to L{_WrappingFactory.clientConnectionLost} should errback the
        L{_WrappingFactory._onConnection} L{Deferred}
        """
        wf = endpoints._WrappingFactory(TestFactory(), None)
        expectedFailure = Failure(error.ConnectError(string="fail"))

        wf.clientConnectionFailed(
            None,
            expectedFailure)

        errors = []
        def gotError(f):
            errors.append(f)

        wf._onConnection.addErrback(gotError)

        self.assertEquals(errors, [expectedFailure]) 
Example #9
Source File: basesupport.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def logOn(self, chatui):
        """Log on to this account.

        Takes care to not start a connection if a connection is
        already in progress.  You will need to implement
        L{_startLogOn} for this to work, and it would be a good idea
        to override L{_loginFailed} too.

        @returntype: Deferred L{interfaces.IClient}
        """
        if (not self._isConnecting) and (not self._isOnline):
            self._isConnecting = 1
            d = self._startLogOn(chatui)
            d.addCallback(self._cb_logOn)
            # if chatui is not None:
            # (I don't particularly like having to pass chatUI to this function,
            # but we haven't factored it out yet.)
            d.addCallback(chatui.registerAccountClient)
            d.addErrback(self._loginFailed)
            return d
        else:
            raise error.ConnectError("Connection in progress") 
Example #10
Source File: basesupport.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def logOn(self, chatui):
        """Log on to this account.

        Takes care to not start a connection if a connection is
        already in progress.  You will need to implement
        L{_startLogOn} for this to work, and it would be a good idea
        to override L{_loginFailed} too.

        @returntype: Deferred L{interfaces.IClient}
        """
        if (not self._isConnecting) and (not self._isOnline):
            self._isConnecting = 1
            d = self._startLogOn(chatui)
            d.addCallback(self._cb_logOn)
            # if chatui is not None:
            # (I don't particularly like having to pass chatUI to this function,
            # but we haven't factored it out yet.)
            d.addCallback(chatui.registerAccountClient)
            d.addErrback(self._loginFailed)
            return d
        else:
            raise error.ConnectError("Connection in progress") 
Example #11
Source File: twisted.py    From python-consul with MIT License 6 votes vote down vote up
def request(self, callback, method, url, **kwargs):
        if 'data' in kwargs and not isinstance(kwargs['data'], bytes):
            # python2/3 compatibility
            data = kwargs.pop('data')
            kwargs['data'] = data.encode(encoding='utf-8') \
                if hasattr(data, 'encode') else b(data)

        try:
            response = yield self.client.request(method, url, **kwargs)
            parsed = yield self._get_resp(response)
            returnValue(callback(self.response(*parsed)))
        except ConnectError as e:
            raise ConsulException(
                '{}: {}'.format(e.__class__.__name__, e.message))
        except ResponseNeverReceived:
            # this exception is raised if the connection to the server is lost
            # when yielding a response, this could be due to network issues or
            # server restarts
            raise ConsulException(
                'Server connection lost: {} {}'.format(method.upper(), url))
        except RequestTransmissionFailed:
            # this exception is expected if the reactor is stopped mid request
            raise ConsulException(
                'Request incomplete: {} {}'.format(method.upper(), url)) 
Example #12
Source File: tahoe.py    From gridsync with GNU General Public License v3.0 6 votes vote down vote up
def get_grid_status(self):
        if not self.nodeurl:
            return None
        try:
            resp = yield treq.get(self.nodeurl + "?t=json")
        except ConnectError:
            return None
        if resp.code == 200:
            content = yield treq.content(resp)
            content = json.loads(content.decode("utf-8"))
            servers_connected = 0
            servers_known = 0
            available_space = 0
            if "servers" in content:
                servers = content["servers"]
                servers_known = len(servers)
                for server in servers:
                    if server["connection_status"].startswith("Connected"):
                        servers_connected += 1
                        if server["available_space"]:
                            available_space += server["available_space"]
            return servers_connected, servers_known, available_space
        return None 
Example #13
Source File: test_tor_manager.py    From magic-wormhole with MIT License 6 votes vote down vote up
def test_connect_custom_control_port_fails(self):
        reactor = object()
        tcp = "port"
        ep = object()
        connect_d = defer.Deferred()
        stderr = io.StringIO()
        with mock.patch(
                "wormhole.tor_manager.txtorcon.connect",
                side_effect=connect_d) as connect:
            with mock.patch(
                    "wormhole.tor_manager.clientFromString",
                    side_effect=[ep]) as sfs:
                d = get_tor(reactor, tor_control_port=tcp, stderr=stderr)
        self.assertEqual(sfs.mock_calls, [mock.call(reactor, tcp)])
        self.assertNoResult(d)
        self.assertEqual(connect.mock_calls, [mock.call(reactor, ep)])

        connect_d.errback(ConnectError())
        self.failureResultOf(d, ConnectError)
        self.assertEqual(stderr.getvalue(), "") 
Example #14
Source File: test_tor_manager.py    From magic-wormhole with MIT License 6 votes vote down vote up
def test_connect_fails(self):
        reactor = object()
        connect_d = defer.Deferred()
        stderr = io.StringIO()
        with mock.patch(
                "wormhole.tor_manager.txtorcon.connect",
                side_effect=connect_d) as connect:
            with mock.patch(
                    "wormhole.tor_manager.clientFromString",
                    side_effect=["foo"]) as sfs:
                d = get_tor(reactor, stderr=stderr)
        self.assertEqual(sfs.mock_calls, [])
        self.assertNoResult(d)
        self.assertEqual(connect.mock_calls, [mock.call(reactor)])

        connect_d.errback(ConnectError())
        tor = self.successResultOf(d)
        self.assertIsInstance(tor, SocksOnlyTor)
        self.assert_(ITorManager.providedBy(tor))
        self.assertEqual(tor._reactor, reactor)
        self.assertEqual(
            stderr.getvalue(),
            " unable to find default Tor control port, using SOCKS\n") 
Example #15
Source File: test_endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_endpointConnectFailure(self):
        """
        If an endpoint tries to connect to a non-listening port it gets
        a C{ConnectError} failure.
        """
        expectedError = error.ConnectError(string="Connection Failed")
        mreactor = RaisingMemoryReactorWithClock(connectException=expectedError)
        clientFactory = object()

        ep, ignoredArgs, ignoredDest = self.createClientEndpoint(
            mreactor, clientFactory)

        d = ep.connect(clientFactory)
        mreactor.advance(0.3)
        self.assertEqual(self.failureResultOf(d).value, expectedError)
        self.assertEqual([], mreactor.getDelayedCalls()) 
Example #16
Source File: test_endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_endpointConnectFailureAfterIteration(self):
        """
        If a connection attempt initiated by
        L{HostnameEndpoint.connect} fails only after
        L{HostnameEndpoint} has exhausted the list of possible server
        addresses, the returned L{Deferred} will fail with
        C{ConnectError}.
        """
        expectedError = error.ConnectError(string="Connection Failed")

        mreactor = MemoryReactor()

        clientFactory = object()

        ep, ignoredArgs, ignoredDest = self.createClientEndpoint(
            mreactor, clientFactory)

        d = ep.connect(clientFactory)
        mreactor.advance(0.3)
        host, port, factory, timeout, bindAddress = mreactor.tcpClients[0]
        factory.clientConnectionFailed(mreactor.connectors[0], expectedError)
        self.assertEqual(self.failureResultOf(d).value, expectedError)
        self.assertEqual([], mreactor.getDelayedCalls()) 
Example #17
Source File: test_endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_endpointConnectFailure(self):
        """
        If L{HostnameEndpoint.connect} is invoked and there is no server
        listening for connections, the returned L{Deferred} will fail with
        C{ConnectError}.
        """
        expectedError = error.ConnectError(string="Connection Failed")

        mreactor = RaisingMemoryReactorWithClock(
                connectException=expectedError)

        clientFactory = object()

        ep, ignoredArgs, ignoredDest = self.createClientEndpoint(
            mreactor, clientFactory)

        d = ep.connect(clientFactory)
        mreactor.advance(endpoints.HostnameEndpoint._DEFAULT_ATTEMPT_DELAY)
        self.assertEqual(self.failureResultOf(d).value, expectedError)
        self.assertEqual([], mreactor.getDelayedCalls()) 
Example #18
Source File: test_endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_endpointConnectFailure(self):
        """
        If an endpoint tries to connect to a non-listening port it gets
        a C{ConnectError} failure.
        """
        expectedError = error.ConnectError(string="Connection Failed")

        mreactor = RaisingMemoryReactor(connectException=expectedError)

        clientFactory = object()

        ep, ignoredArgs, ignoredDest = self.createClientEndpoint(
            mreactor, clientFactory)

        d = ep.connect(clientFactory)

        receivedExceptions = []

        def checkFailure(f):
            receivedExceptions.append(f.value)

        d.addErrback(checkFailure)

        self.assertEqual(receivedExceptions, [expectedError]) 
Example #19
Source File: test_endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_clientConnectionFailed(self):
        """
        Calls to L{_WrappingFactory.clientConnectionLost} should errback the
        L{_WrappingFactory._onConnection} L{Deferred}
        """
        wf = endpoints._WrappingFactory(TestFactory())
        expectedFailure = Failure(error.ConnectError(string="fail"))

        wf.clientConnectionFailed(None, expectedFailure)

        errors = []

        def gotError(f):
            errors.append(f)

        wf._onConnection.addErrback(gotError)

        self.assertEqual(errors, [expectedFailure]) 
Example #20
Source File: basesupport.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def logOn(self, chatui):
        """Log on to this account.

        Takes care to not start a connection if a connection is
        already in progress.  You will need to implement
        L{_startLogOn} for this to work, and it would be a good idea
        to override L{_loginFailed} too.

        @returntype: Deferred L{interfaces.IClient}
        """
        if (not self._isConnecting) and (not self._isOnline):
            self._isConnecting = 1
            d = self._startLogOn(chatui)
            d.addCallback(self._cb_logOn)
            # if chatui is not None:
            # (I don't particularly like having to pass chatUI to this function,
            # but we haven't factored it out yet.)
            d.addCallback(chatui.registerAccountClient)
            d.addErrback(self._loginFailed)
            return d
        else:
            raise error.ConnectError("Connection in progress") 
Example #21
Source File: clusterservice.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def _make_connections(self, eventloop, addresses):
        """Connect to `eventloop` using all `addresses`."""
        for address in addresses:
            try:
                connection = yield self._make_connection(eventloop, address)
            except ConnectError as error:
                host, port = address
                log.msg(
                    "Event-loop %s (%s:%d): %s"
                    % (eventloop, host, port, error)
                )
            except Exception:
                host, port = address
                log.err(
                    None,
                    (
                        "Failure with event-loop %s (%s:%d)"
                        % (eventloop, host, port)
                    ),
                )
            else:
                self.try_connections[eventloop] = connection
                break 
Example #22
Source File: adtran_device_handler.py    From voltha with Apache License 2.0 6 votes vote down vote up
def make_restconf_connection(self, get_timeout=None):
        client = self._rest_client

        if client is None:
            client = AdtranRestClient(self.ip_address,
                                      self.rest_port,
                                      self.rest_username,
                                      self.rest_password,
                                      self.timeout)

        timeout = get_timeout or self.timeout

        try:
            request = client.request('GET', self.HELLO_URI, name='hello', timeout=timeout)
            results = yield request
            if isinstance(results, dict) and 'module-info' in results:
                self._rest_client = client
                returnValue(results)
            else:
                from twisted.internet.error import ConnectError
                self._rest_client = None
                raise ConnectError(string='Results received but unexpected data type or contents')
        except Exception:
            self._rest_client = None
            raise 
Example #23
Source File: pb.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def connectionFailed(self):
        if not self.term:
            self.term = 1
            del self.broker
            self.deferred.errback(error.ConnectError(string="Connection failed"))
            del self.deferred 
Example #24
Source File: test_basesupport.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_alreadyConnecting(self):
        """
        Test that it can fail sensibly when someone tried to connect before
        we did. 
        """
        account = self.makeAccount()
        ui = self.makeUI()
        account.logOn(ui)
        self.assertRaises(error.ConnectError, account.logOn, ui) 
Example #25
Source File: tcp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def connectionLost(self, reason):
        if not self.connected:
            self.failIfNotConnected(error.ConnectError(string=reason))
        else:
            Connection.connectionLost(self, reason)
            self.connector.connectionLost(reason) 
Example #26
Source File: test_amp.py    From landscape-client with GNU General Public License v2.0 5 votes vote down vote up
def test_get_remote_object_failure(self):
        """
        If the factory fails to establish a connection the deferreds returned
        by C{getRemoteObject} will fail.
        """
        deferred = self.factory.getRemoteObject()
        self.factory.continueTrying = False  # Don't retry
        self.factory.clientConnectionFailed(None, Failure(ConnectError()))
        self.failureResultOf(deferred).trap(ConnectError) 
Example #27
Source File: testing.py    From landscape-client with GNU General Public License v2.0 5 votes vote down vote up
def connect_unix(self, path, factory):
        server = self._socket_paths.get(path)
        from landscape.lib.tests.test_amp import FakeConnector
        if server:
            connector = FakeConnector(factory, server)
            connector.connect()
        else:
            connector = object()  # Fake connector
            failure = Failure(ConnectError("No such file or directory"))
            factory.clientConnectionFailed(connector, failure)
        return connector 
Example #28
Source File: tcp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def connectionLost(self, reason):
        if not self.connected:
            self.failIfNotConnected(error.ConnectError(string=reason))
        else:
            Connection.connectionLost(self, reason)
            self.connector.connectionLost(reason) 
Example #29
Source File: test_pb.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testGoodFailedConnect(self):
        factory = pb.PBClientFactory()
        d = factory.getPerspective("guest", "guest", "test",
                                   perspectiveName="any")
        reactor.connectTCP("127.0.0.1", 69, factory)
        return self.assertFailure(d, error.ConnectError) 
Example #30
Source File: client.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def flush(self):
        try:
            yield self._sendCommand(FlushCommand)
            returnValue(None)
        except ConnectError:
            returnValue(None)