twisted.internet.error.ConnectionDone

Here are the examples of the python api twisted.internet.error.ConnectionDone taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

63 Examples 7

Page 1 Selected Page 2

Example 1

Project: SubliminalCollaborator Source File: irc.py
    def clientConnectionLost(self, connector, reason):
        if error.ConnectionDone == reason.type:
            self.disconnect()
        else:
            # may want to reconnect, but for now lets print why
            self.logger.error('Connection lost: %s - %s' % (reason.type, reason.value))
            status_bar.status_message('connection lost to %s' % self.str())

Example 2

Project: SubliminalCollaborator Source File: test_smtp.py
    def testESMTPGreetingExtended(self):
        """
        Test that the string "ESMTP" does appear in the ESMTP server's
        greeting since L{smtp.ESMTP} does support the SMTP extensions which
        that advertises to the client.
        """
        s = smtp.ESMTP()
        t = StringTransport()
        s.makeConnection(t)
        s.connectionLost(error.ConnectionDone())
        self.assertIn("ESMTP", t.value())

Example 3

Project: lbry Source File: ServerProtocol.py
Function: connection_lost
    def connectionLost(self, reason=failure.Failure(error.ConnectionDone())):
        if self.request_handler is not None:
            self.request_handler.stopProducing()
        self.factory.rate_limiter.unregister_protocol(self)
        if not reason.check(error.ConnectionDone):
            log.warning("Closing a connection. Reason: %s", reason.getErrorMessage())

Example 4

Project: nagcat Source File: test_protocol.py
Function: tear_down
    def tearDown(self):
        def check(result):
            self.assertIsInstance(result, failure.Failure)
            self.assertIsInstance(result.value, error.ConnectionDone)

        self.client.stopTrying()
        d = self.client.sendLine("QUIT")
        d.addBoth(check)
        d.addBoth(lambda x: self.server.stopListening())
        return d

Example 5

Project: ldaptor Source File: inmemory.py
Function: connection_lost
    def connectionLost(self, reason):
        super(InMemoryLDIFProtocol, self).connectionLost(reason)
        if not reason.check(error.ConnectionDone):
            self._deferred.addCallback(lambda db: reason)
        else:
            self._deferred.chainDeferred(self.completed)

        del self._deferred # invalidate it to flush out bugs

Example 6

Project: mythbox Source File: test_session.py
Function: test_wrapprotocol
    def test_wrapProtocol(self):
        """
        L{wrapProtocol}, when passed a L{Protocol} should return something that
        has write(), writeSequence(), loseConnection() methods which call the
        Protocol's dataReceived() and connectionLost() methods, respectively.
        """
        protocol = MockProtocol()
        protocol.transport = StubTransport()
        protocol.connectionMade()
        wrapped = session.wrapProtocol(protocol)
        wrapped.dataReceived('dataReceived')
        self.assertEquals(protocol.transport.buf, 'dataReceived')
        wrapped.write('data')
        wrapped.writeSequence(['1', '2'])
        wrapped.loseConnection()
        self.assertEquals(protocol.data, 'data12')
        protocol.reason.trap(error.ConnectionDone)

Example 7

Project: SubliminalCollaborator Source File: test_epollreactor.py
    def test_connectionLostOnRead(self):
        """
        If a C{doRead} returns a value indicating disconnection,
        C{connectionLost} is called on it.
        """
        reactor = Clock()
        poller = _ContinuousPolling(reactor)
        desc = Descriptor()
        desc.doRead = lambda: ConnectionDone()
        poller.addReader(desc)
        self.assertEqual(desc.events, [])
        reactor.advance(0.001)
        self.assertEqual(desc.events, ["lost"])

Example 8

Project: SubliminalCollaborator Source File: test_smtp.py
    def testSMTPGreetingNotExtended(self):
        """
        Test that the string "ESMTP" does not appear in the SMTP server's
        greeting since that string strongly suggests the presence of support
        for various SMTP extensions which are not supported by L{smtp.SMTP}.
        """
        s = smtp.SMTP()
        t = StringTransport()
        s.makeConnection(t)
        s.connectionLost(error.ConnectionDone())
        self.assertNotIn("ESMTP", t.value())

Example 9

Project: SubliminalCollaborator Source File: test_xmlrpc.py
    def setUp(self):
        # The _QueryFactory that we are testing. We don't care about any
        # of the constructor parameters.
        self.queryFactory = _QueryFactory(
            path=None, host=None, method='POST', user=None, password=None,
            allowNone=False, args=())
        # An XML-RPC response that will parse without raising an error.
        self.goodContents = xmlrpclib.dumps(('',))
        # An 'XML-RPC response' that will raise a parsing error.
        self.badContents = 'invalid xml'
        # A dummy 'reason' to pass to clientConnectionLost. We don't care
        # what it is.
        self.reason = failure.Failure(ConnectionDone())

Example 10

Project: filesync-server Source File: ssl_proxy.py
Function: connection_lost
    def connectionLost(self, reason=None):
        if reason and reason.check(error.ConnectionDone):
            self.peer.metrics.meter("backend_connection_done", 1)
            logger.debug("Backend connection done: %s -> %s -> %s",
                         self.source, self.local, self.dest)
        else:
            self.peer.metrics.meter("backend_connection_lost", 1)
            logger.debug("Backend connection lost: %s -> %s -> %s",
                         self.source, self.local, self.dest)
        portforward.ProxyClient.connectionLost(self, reason=reason)

Example 11

Project: nagcat Source File: twist.py
Function: close
    def close(self):
        """Close connection to rrdcached"""

        def filter_done(result):
            if isinstance(result.value, error.ConnectionDone):
                return None
            else:
                return result

        assert self._client
        self._client.stopTrying()
        deferred = self._client.sendLine('QUIT')
        deferred.addErrback(filter_done)
        self._client = None
        self.update = self._update_direct
        return deferred

Example 12

Project: ldaptor Source File: ldifdelta.py
Function: fromldiffile
def fromLDIFFile(f):
    """Read LDIF data from a file."""

    p = LDIFDelta()
    l = []
    p.gotEntry = l.append
    while 1:
        data = f.read()
        if not data:
            break
        p.dataReceived(data)
    p.connectionLost(Failure(error.ConnectionDone()))

    return l

Example 13

Project: txloadbalancer Source File: proxy.py
Function: connection_lost
    def connectionLost(self, reason):
        """
        The server is done, and has closed the connection. write out any
        remaining data, and close the socket.
        """
        if self.receiver is not None:
            if reason.type is error.ConnectionDone:
                pass
            elif reason.type is error.ConnectionLost:
                pass
            else:
                pass
            self.receiver.transport.loseConnection()

Example 14

Project: twimp Source File: test_dispatch.py
    def test_callRemote_disconnect(self):
        p, t, dmx, mux = self.build_proto()

        d = p.callRemote(1, 'echo', 'sing it back')

        self.assertEquals(len(mux.messages), 1)
        msg = mux.messages[0]
        self.assertEquals(msg[0:3] + msg[4:],
                          (0, chunks.MSG_COMMAND, 1, False))

        # can't rely on transaction number, so we skip it
        decoded = decode_amf(vb(msg[3]))
        self.assertEquals((decoded[0], decoded[2]), ('echo', 'sing it back'))

        p.connectionLost()

        self.assertFailure(d, error.ConnectionDone)
        return d

Example 15

Project: andcat Source File: netcat.py
Function: connection_lost
    def connectionLost(self, reason):
        if reason.check(error.ConnectionDone):
            msg = 'Transfer finished sucessfully!'
        else:
            msg = 'Error while receiving file: {}'.format(reason.value)

        self.factory.onDone(msg)

Example 16

Project: SubliminalCollaborator Source File: basic.py
    def clientConnectionLost(self, connector, reason):
        registry.removeSession(self)
        self.state = base.STATE_DISCONNECTED
        if error.ConnectionDone == reason.type:
            self.disconnect()
        else:
            status_bar.status_message('lost share session with %s' % self.str())
            # may want to reconnect, but for now lets print why
            self.logger.error('Connection lost: %s - %s' % (reason.type, reason.value))

Example 17

Project: mythbox Source File: test_error.py
    def test_connectionDoneSubclassOfConnectionClosed(self):
        """
        L{error.ConnectionClosed} is a superclass of L{error.ConnectionDone}.
        """
        self.assertTrue(issubclass(error.ConnectionDone,
                                   error.ConnectionClosed))

Example 18

Project: SubliminalCollaborator Source File: test_smtp.py
    def testSMTPGreetingHost(self, serverClass=smtp.SMTP):
        """
        Test that the specified hostname shows up in the SMTP server's
        greeting.
        """
        s = serverClass()
        s.host = "example.com"
        t = StringTransport()
        s.makeConnection(t)
        s.connectionLost(error.ConnectionDone())
        self.assertIn("example.com", t.value())

Example 19

Project: lbry Source File: ClientProtocol.py
Function: connection_lost
    def connectionLost(self, reason):
        self.connection_closed = True
        if reason.check(error.ConnectionDone):
            err = failure.Failure(ConnectionClosedBeforeResponseError())
        else:
            err = reason
        #if self._response_deferreds:
        #    log.warning("Lost connection with active response deferreds. %s", str(self._response_deferreds))
        for key, d in self._response_deferreds.items():
            del self._response_deferreds[key]
            d.errback(err)
        if self._blob_download_request is not None:
            self._blob_download_request.cancel(err)
        self._connection_manager.protocol_disconnected(self.peer, self)

Example 20

Project: SubliminalCollaborator Source File: test_xmlrpc.py
    def test_interruptedDeferredResponse(self):
        """
        While waiting for the L{Deferred} returned by an L{XMLRPC} C{xmlrpc_*}
        method to fire, the connection the request was issued over may close.
        If this happens, neither C{write} nor C{finish} is called on the
        request.
        """
        self.resource.render(self.request)
        self.request.processingFailed(
            failure.Failure(ConnectionDone("Simulated")))
        self.result.callback("result")
        self.assertEqual(self.request.written, [])
        self.assertEqual(self.request.finished, 0)

Example 21

Project: lbry Source File: client.py
Function: connection_lost
    def connectionLost(self, reason):
        if reason.check(error.ConnectionDone):
            log.debug('Finished sending data via reflector')
            self.factory.finished_deferred.callback(True)
        else:
            log.debug('Reflector finished: %s', reason)
            self.factory.finished_deferred.callback(reason)

Example 22

Project: lbry Source File: client.py
Function: connection_lost
    def connectionLost(self, reason):
        if reason.check(error.ConnectionDone):
            self.factory.sent_blobs = self.sent_blobs
            if self.factory.sent_blobs:
                log.info('Finished sending data via reflector')
            self.factory.finished_deferred.callback(True)
        else:
            log.info('Reflector finished: %s', reason)
            self.factory.finished_deferred.callback(reason)

Example 23

Project: SubliminalCollaborator Source File: test_httpauth.py
    def test_logoutOnError(self):
        """
        The realm's logout callback is also invoked if there is an error
        generating the response (for example, if the client disconnects
        early).
        """
        request = self._logoutTest()
        request.processingFailed(
            Failure(ConnectionDone("Simulated disconnect")))
        self.assertEqual(self.realm.loggedOut, 1)

Example 24

Project: ldaptor Source File: inmemory.py
Function: fromldiffile
def fromLDIFFile(f):
    """Read LDIF data from a file."""

    p = InMemoryLDIFProtocol()
    while 1:
        data = f.read()
        if not data:
            break
        p.dataReceived(data)
    p.connectionLost(Failure(error.ConnectionDone()))

    return p.completed

Example 25

Project: wokkel Source File: test_subprotocols.py
    def test_requestDisconnectTimeoutCancellation(self):
        """
        Test if timeouts for iq's that haven't yet received a response
        are cancelled on stream disconnect.
        """

        self.request.timeout = 60
        d = self.streamManager.request(self.request)

        self.xmlstream.connectionLost(failure.Failure(ConnectionDone()))
        self.assertFailure(d, ConnectionDone)
        self.assertFalse(self.clock.calls)
        return d

Example 26

Project: ldaptor Source File: util.py
Function: pump
    def pump(self):
        FasterIOPump.pump(self)
        if (self.clientTransport.disconnecting
            and not self.clientTransport.data.getvalue()
            and not self.clientTransport.disconnect_done):
            self.server.connectionLost(error.ConnectionDone)
            self.clientTransport.disconnect_done = True

        if (self.serverTransport.disconnecting
            and not self.serverTransport.data.getvalue()
            and not self.serverTransport.disconnect_done):
            self.client.connectionLost(error.ConnectionDone)
            self.serverTransport.disconnect_done = True

        if (self.clientTransport.disconnect_done
            and self.serverTransport.disconnect_done):
            self.active.remove(self)

Example 27

Project: ldaptor Source File: test_proxy.py
    def test_unbind_clientUnbinds(self):
        server = self.createServer([ pureldap.LDAPBindResponse(resultCode=0),
                                     ],
                                   [],
                                   )
        server.dataReceived(str(pureldap.LDAPMessage(pureldap.LDAPBindRequest(), id=2)))
        reactor.iterate() #TODO
        client = server.client
        client.assertSent(pureldap.LDAPBindRequest())
        self.assertEquals(server.transport.value(),
                          str(pureldap.LDAPMessage(pureldap.LDAPBindResponse(resultCode=0), id=2)))
        server.dataReceived(str(pureldap.LDAPMessage(pureldap.LDAPUnbindRequest(), id=3)))
        server.connectionLost(error.ConnectionDone)
        reactor.iterate() #TODO
        client.assertSent(pureldap.LDAPBindRequest(),
                          pureldap.LDAPUnbindRequest())
        self.assertEquals(server.transport.value(),
                          str(pureldap.LDAPMessage(pureldap.LDAPBindResponse(resultCode=0), id=2)))

Example 28

Project: Telephus Source File: pool.py
    def client_conn_lost(self, f, reason):
        if reason.check(error.ConnectionDone):
            self.log('Thrift pool connection to %s failed (cleanly)' % (f.node,))
        else:
            self.err(reason, 'Thrift pool connection to %s was lost' % (f.node,))
        if f.last_error is None or f.last_error.check(*self.retryables):
            self.log('Retrying connection right away')
            self.remove_good_conn(f)
            f.retry()
        else:
            f.node.conn_fail(reason)
            f.stopFactory()
            self.remove_connector(f)
            self.fill_pool()

Example 29

Project: nagcat Source File: test_protocol.py
Function: tear_down
    def tearDown(self):
        def check(result):
            self.assertIsInstance(result, failure.Failure)
            self.assertIsInstance(result.value, error.ConnectionDone)

        d = self.client.sendLine("QUIT")
        d.addBoth(check)
        return d

Example 30

Project: andcat Source File: netcat.py
Function: on_termination
    def _onTermination(self, reason):
        self._finput.close()

        if self._progress:
            if reason.check(error.ConnectionDone):
                msg = "Transfer finished!"
            else:
                msg = "Possible problem with the transfer".format(reason.value)
            self._progress.show_msg(msg)
            self._progress.show_exit()

Example 31

Project: txtorcon Source File: test_torcontrolprotocol.py
    def test_disconnect_callback(self):
        """
        see that we get our callback on_disconnect if the transport
        goes away
        """
        def it_was_called(*args):
            it_was_called.yes = True
            return None
        it_was_called.yes = False
        self.protocol.on_disconnect.addCallback(it_was_called)
        self.protocol.on_disconnect.addErrback(it_was_called)
        f = failure.Failure(error.ConnectionDone("It's all over"))
        self.protocol.connectionLost(f)
        self.assertTrue(it_was_called.yes)

Example 32

Project: mythbox Source File: test_manhole.py
    def testControlBackslash(self):
        self._testwrite("cancelled line")
        partialLine = self.recvlineClient.expect("cancelled line")

        def gotPartialLine(ign):
            self._assertBuffer(
                [">>> cancelled line"])
            self._testwrite(manhole.CTRL_BACKSLASH)

            d = self.recvlineClient.onDisconnection
            return self.assertFailure(d, error.ConnectionDone)

        def gotClearedLine(ign):
            self._assertBuffer(
                [""])

        return partialLine.addCallback(gotPartialLine).addCallback(gotClearedLine)

Example 33

Project: twimp Source File: test_dispatch.py
    def test_waitStatus_disconnected(self):
        p, t, dmx, mux = self.build_proto()

        # wait for any event
        d = p.waitStatus(1, None)
        self.assertFailure(d, error.ConnectionDone)

        p.connectionLost()

        return d

Example 34

Project: wokkel Source File: test_subprotocols.py
    def test_requestDisconnectCleanup(self):
        """
        Test if deferreds for iq's that haven't yet received a response
        have their errback called on stream disconnect.
        """
        d = self.streamManager.request(self.request)
        xs = self.xmlstream
        xs.connectionLost(failure.Failure(ConnectionDone()))
        self.assertFailure(d, ConnectionDone)
        return d

Example 35

Project: SubliminalCollaborator Source File: basic.py
    def connectionLost(self, reason):
        registry.removeSession(self)
        if self.peerType == base.CLIENT:
            # ignore this, clientConnectionLost() below will also be called
            return
        self.state = base.STATE_DISCONNECTED
        if error.ConnectionDone == reason.type:
            self.disconnect()
        else:
            status_bar.heartbeat_message('lost share session with %s' % self.str())
            # may want to reconnect, but for now lets print why
            self.logger.error('Connection lost: %s - %s' % (reason.type, reason.value))

Example 36

Project: mythbox Source File: _posixstdio.py
Function: childconnectionlost
    def childConnectionLost(self, fd, reason):
        if self.disconnected:
            return

        if reason.value.__class__ == error.ConnectionDone:
            # Normal close
            if fd == 'read':
                self._readConnectionLost(reason)
            else:
                self._writeConnectionLost(reason)
        else:
            self.connectionLost(reason)

Example 37

Project: SubliminalCollaborator Source File: test_session.py
    def test_wrapProtocol(self):
        """
        L{wrapProtocol}, when passed a L{Protocol} should return something that
        has write(), writeSequence(), loseConnection() methods which call the
        Protocol's dataReceived() and connectionLost() methods, respectively.
        """
        protocol = MockProtocol()
        protocol.transport = StubTransport()
        protocol.connectionMade()
        wrapped = session.wrapProtocol(protocol)
        wrapped.dataReceived('dataReceived')
        self.assertEqual(protocol.transport.buf, 'dataReceived')
        wrapped.write('data')
        wrapped.writeSequence(['1', '2'])
        wrapped.loseConnection()
        self.assertEqual(protocol.data, 'data12')
        protocol.reason.trap(error.ConnectionDone)

Example 38

Project: Limnoria Source File: Twisted.py
Function: connection_lost
    def connectionLost(self, r):
        self.mostRecentCall.cancel()
        if r.check(error.ConnectionDone):
            drivers.log.disconnect(self.factory.currentServer)
        else:
            drivers.log.disconnect(self.factory.currentServer, errorMsg(r))
        if self.irc.zombie:
            self.factory.stopTrying()
            while self.irc.takeMsg():
                continue
        else:
            self.irc.reset()

Example 39

Project: SubliminalCollaborator Source File: test_epollreactor.py
    def test_connectionLostOnWrite(self):
        """
        If a C{doWrite} returns a value indicating disconnection,
        C{connectionLost} is called on it.
        """
        reactor = Clock()
        poller = _ContinuousPolling(reactor)
        desc = Descriptor()
        desc.doWrite = lambda: ConnectionDone()
        poller.addWriter(desc)
        self.assertEqual(desc.events, [])
        reactor.advance(0.001)
        self.assertEqual(desc.events, ["lost"])

Example 40

Project: wokkel Source File: test_subprotocols.py
    def test_requestNoModifyingDict(self):
        """
        Test to make sure the errbacks cannot cause the iteration of the
        iqDeferreds to blow up in our face.
        """

        def eb(failure):
            d = xmlstream.IQ(self.xmlstream).send()
            d.addErrback(eb)

        d = self.streamManager.request(self.request)
        d.addErrback(eb)
        self.xmlstream.connectionLost(failure.Failure(ConnectionDone()))
        return d

Example 41

Project: lbry Source File: FileStreamer.py
    def stopProducing(self):
        self._running = False
        self._file.close()
        self._deferred.addErrback(lambda err: err.trap(defer.CancelledError))
        self._deferred.addErrback(lambda err: err.trap(error.ConnectionDone))
        self._deferred.cancel()
        self._request.unregisterProducer()
        self._request.finish()

Example 42

Project: pika Source File: twisted_connection.py
    def connectionLost(self, reason):
        # If the connection was not closed cleanly, log the error
        if not reason.check(error.ConnectionDone):
            log.err(reason)

        self._on_terminate(connection.InternalCloseReasons.SOCKET_ERROR,
                           str(reason))

Example 43

Project: ldaptor Source File: test_proxy.py
    def test_unbind_clientEOF(self):
        server = self.createServer([ pureldap.LDAPBindResponse(resultCode=0),
                                     ],
                                   [],
                                   )
        server.dataReceived(str(pureldap.LDAPMessage(pureldap.LDAPBindRequest(), id=2)))
        reactor.iterate() #TODO
        client = server.client
        client.assertSent(pureldap.LDAPBindRequest())
        self.assertEquals(server.transport.value(),
                          str(pureldap.LDAPMessage(pureldap.LDAPBindResponse(resultCode=0), id=2)))
        server.connectionLost(error.ConnectionDone)
        reactor.iterate() #TODO
        client.assertSent(pureldap.LDAPBindRequest(),
                          'fake-unbind-by-LDAPClientTestDriver')
        self.assertEquals(server.transport.value(),
                          str(pureldap.LDAPMessage(pureldap.LDAPBindResponse(resultCode=0), id=2)))

Example 44

Project: vertex Source File: q2qclient.py
Function: clientconnectionlost
    def clientConnectionLost(self, connector, reason):
        reason.trap(error.ConnectionDone)

Example 45

Project: vertex Source File: q2qclient.py
def enregister(svc, newAddress, password):
    """
    Register a new account and return a Deferred that fires if it worked.

    @param svc: a Q2QService

    @param newAddress: a Q2QAddress object

    @param password: a shared secret (str)
    """
    return svc.connectQ2Q(q2q.Q2QAddress("",""),
                       q2q.Q2QAddress(newAddress.domain, "accounts"),
                       'identity-admin',
                       protocol.ClientFactory.forProtocol(AMP)
                       ).addCallback(
                           AMP.callRemote,
                           AddUser,
                           name=newAddress.resource,
                           password=password
                       ).addErrback(
                           Failure.trap,
                           error.ConnectionDone
                       )

Example 46

Project: foolscap Source File: pb.py
    def stopService(self):
        # note that once you stopService a Tub, I cannot be restarted. (at
        # least this code is not designed to make that possible.. it might be
        # doable in the future).
        assert self.running
        self.startService = self._tubsAreNotRestartable
        self.getReference = self._tubHasBeenShutDown
        self.connectTo = self._tubHasBeenShutDown

        # Tell everything to shut down now. We assume that it will stop
        # twitching by the next tick, so Trial unit tests won't complain
        # about a dirty reactor. We wait on a few things that might not
        # behave.
        dl = []
        for rc in list(self.reconnectors):
            rc.stopConnecting()
        del self.reconnectors
        for c in list(self._activeConnectors):
            c.shutdown()
        why = Failure(error.ConnectionDone("Tub.stopService was called"))
        for b in self.brokers.values():
            b.shutdown(why, fireDisconnectWatchers=False)

        d = defer.DeferredList(dl)
        d.addCallback(lambda _: service.MultiService.stopService(self))
        d.addCallback(eventual.fireEventually)
        return d

Example 47

Project: filesync-server Source File: test_shutdown.py
    @defer.inlineCallbacks
    def test_requests_leak(self):
        """Test that the server waits for pending requests."""
        # create a server
        self.service = StorageServerService(
            0, "localhost", self.s4_conn.getHost().port, False,
            s4.AWS_DEFAULT_ACCESS_KEY_ID,
            s4.AWS_DEFAULT_SECRET_ACCESS_KEY,
            auth_provider_class=DummyAuthProvider,
            heartbeat_interval=0)
        # start it
        yield self.service.startService()

        make_storage_user(0, u"dummy", u"", 2 ** 20)
        client_d = defer.Deferred()
        f = TestClientFactory()
        f.connected = client_d.callback
        reactor.connectTCP("localhost", self.service.port, f)
        client = yield client_d
        # start with a client
        yield client.dummy_authenticate("open sesame")
        root_id = yield client.get_root()
        # create a bunch of files
        mk_deferreds = []

        def handle_conn_done(f):
            """Ignore ConnectionDone errors."""
            if f.check(error.ConnectionDone):
                return
            return f
        for i in range(10):
            mk = client.make_file(request.ROOT, root_id, "hola_%s" % i)
            mk.addErrback(handle_conn_done)
            mk_deferreds.append(mk)
        try:
            reactor.callLater(0.1, client.transport.loseConnection)
            yield defer.DeferredList(mk_deferreds)
        finally:
            self.assertTrue(self.service.factory.protocols[0].requests)
            # wait for protocol shutdown (this was hanging waiting for requests
            # to finish)
            yield self.service.factory.protocols[0].wait_for_shutdown()
            # see that the server has not protocols alive
            yield self.service.factory.wait_for_shutdown()
            # cleanup
            yield self.service.stopService()

Example 48

Project: wokkel Source File: subprotocols.py
Function: disconnected
    def _disconnected(self, reason):
        """
        Called when the stream has been closed.

        From this point on, the manager doesn't interact with the
        L{XmlStream} anymore and notifies each handler that the connection
        was lost by calling its C{connectionLost} method.
        """
        self.xmlstream = None
        self._initialized = False

        # Twisted versions before 11.0 passed an XmlStream here.
        if not hasattr(reason, 'trap'):
            reason = failure.Failure(ConnectionDone())

        # Notify all child services which implement
        # the IService interface
        for e in list(self):
            e.connectionLost(reason)

        # This errbacks all deferreds of iq's for which no response has
        # been received with a L{ConnectionLost} failure. Otherwise, the
        # deferreds will never be fired.
        iqDeferreds = self._iqDeferreds
        self._iqDeferreds = {}
        for d in itervalues(iqDeferreds):
            d.errback(reason)

Example 49

Project: openfaucet Source File: mock_ofproto.py
Function: lose_connection
    def loseConnection(self):
        self._protocol.connectionLost(twisted.python.failure.Failure(
            twisted.internet.error.ConnectionDone()))
        self.open = False

Example 50

Project: filesync-server Source File: upload.py
Function: startfactory
    @defer.inlineCallbacks
    def startFactory(self):
        """Start running the circus.

        Start a new consumer for each chunk and call self.part_done_cb when
        each chunk finish.
        """
        for chunk_size in self._chunk_iter():
            try:
                yield self._upload_part(chunk_size)
            except twisted.internet.error.ConnectionDone:
                # if we catch this as a result of being cancelled, it's ok,
                # whomever cancelled us doesn't expect us to go ka-boom
                if self.cancelled:
                    # stop the loop, but finish the factory
                    break
                failure = Failure()
                yield self.cancel()
                self.deferred.errback(failure)
                return
            except Exception:
                # catch everything else, and bailout
                failure = Failure()
                yield self.cancel()
                self.deferred.errback(failure)
                return

        self.finished = True
        self._current_client_factory = None
        if not self.deferred.called:
            self.deferred.callback(self)
See More Examples - Go to Next Page
Page 1 Selected Page 2