o b,@sdZddlmZddlmZddlmZddlmZddl m Z ddl m Z m Z mZmZmZddlmZdd lmZdd lmZd d ZGd ddejZGdddeZGdddeZdZdZGdddeZGdddeZGdddeZ GdddeZ!GdddeZ"Gdd d eZ#Gd!d"d"eZ$Gd#d$d$eZ%Gd%d&d&eZ&Gd'd(d(eZ'Gd)d*d*eZ(Gd+d,d,ejZ)Gd-d.d.ejZ*Gd/d0d0Z+Gd1d2d2Z,d3d4d5efd6d7Z-e-Z.d8d9Z/Gd:d;d;Z0GdZ2d?S)@a Reactor-based Services Here are services to run clients, servers and periodic services using the reactor. If you want to run a server service, L{StreamServerEndpointService} defines a service that can wrap an arbitrary L{IStreamServerEndpoint } as an L{IService}. See also L{twisted.application.strports.service} for constructing one of these directly from a descriptive string. Additionally, this module (dynamically) defines various Service subclasses that let you represent clients and servers in a Service hierarchy. Endpoints APIs should be preferred for stream server services, but since those APIs do not yet exist for clients or datagram services, many of these are still useful. They are as follows:: TCPServer, TCPClient, UNIXServer, UNIXClient, SSLServer, SSLClient, UDPServer, UNIXDatagramServer, UNIXDatagramClient, MulticastServer These classes take arbitrary arguments in their constructors and pass them straight on to their respective reactor.listenXXX or reactor.connectXXX calls. For example, the following service starts a web server on port 8080: C{TCPServer(8080, server.Site(r))}. See the documentation for the reactor.listen/connect* methods for more information. )random)List)MethodicalMachine)service)task)CancelledErrorDeferredfail maybeDeferredsucceed)Logger)log)FailurecCs|dur ddlm}|S|S)zR @return: the argument, or the global reactor if the argument is L{None}. Nr)reactor)twisted.internetr) maybeReactorrr>/usr/lib/python3/dist-packages/twisted/application/internet.py_maybeGlobalReactor<s rc@s&eZdZUgZeeed<ddZdS)_VolatileDataServicevolatilecCs*tj|}|jD] }||vr||=q |SN)rService __getstate__r)selfdattrrrrrLs  z!_VolatileDataService.__getstate__N)__name__ __module__ __qualname__rrstr__annotations__rrrrrrHs  rc@sTeZdZUdZdgZdZeed<dZdZ ddZ dd Z d d Z d d Z ddZdS)_AbstractServera @cvar volatile: list of attribute to remove from pickling. @type volatile: C{list} @ivar method: the type of method to call on the reactor, one of B{TCP}, B{UDP}, B{SSL} or B{UNIX}. @type method: C{str} @ivar reactor: the current running reactor. @type reactor: a provider of C{IReactorTCP}, C{IReactorUDP}, C{IReactorSSL} or C{IReactorUnix}. @ivar _port: instance of port set when the service is started. @type _port: a provider of L{twisted.internet.interfaces.IListeningPort}. _portmethodNcO$||_d|vr |d|_||_dSNrargspoprkwargsrr)r+rrr__init__k  z_AbstractServer.__init__cCtj|||_dSr)rrprivilegedStartService_getPortr#rrrrr0q z&_AbstractServer.privilegedStartServicecCs(tj||jdur||_dSdSr)rr startServicer#r1r2rrrr4us  z_AbstractServer.startServicecCs,tj||jdur|j}|`|SdSr)rr stopServicer# stopListening)rrrrrr5zs   z_AbstractServer.stopServicecCs&tt|jd|j|ji|jS)z Wrapper around the appropriate listen method of the reactor. @return: the port object returned by the listen method. @rtype: an object providing L{twisted.internet.interfaces.IListeningPort}. zlisten{})getattrrrformatr%r)r+r2rrrr1sz_AbstractServer._getPort)rrr__doc__rr%r r!rr#r-r0r4r5r1rrrrr"Ts   r"c@sLeZdZUdZdgZdZeed<dZdZ ddZ dd Z d d Z d d Z dS)_AbstractClienta& @cvar volatile: list of attribute to remove from pickling. @type volatile: C{list} @ivar method: the type of method to call on the reactor, one of B{TCP}, B{UDP}, B{SSL} or B{UNIX}. @type method: C{str} @ivar reactor: the current running reactor. @type reactor: a provider of C{IReactorTCP}, C{IReactorUDP}, C{IReactorSSL} or C{IReactorUnix}. @ivar _connection: instance of connection set when the service is started. @type _connection: a provider of L{twisted.internet.interfaces.IConnector}. _connectionr$r%NcOr&r'r(r,rrrr-r.z_AbstractClient.__init__cCr/r)rrr4_getConnectionr;r2rrrr4r3z_AbstractClient.startServicecCs,tj||jdur|j|`dSdSr)rrr5r; disconnectr2rrrr5s   z_AbstractClient.stopServicecCs&tt|jd|j|ji|jS)z Wrapper around the appropriate connect method of the reactor. @return: the port object returned by the connect method. @rtype: an object providing L{twisted.internet.interfaces.IConnector}. connect)r7rrr%r)r+r2rrrr<s z_AbstractClient._getConnection)rrrr9rr%r r!rr;r-r4r5r<rrrrr:s   r:ztConnect to {tran} Call reactor.connect{tran} when the service starts, with the arguments given to the constructor. zServe {tran} clients Call reactor.listen{tran} when the service starts, with the arguments given to the constructor. When the service stops, stop listening. See twisted.internet.interfaces for documentation on arguments to the reactor method. c@eZdZejddZdZdS) TCPServerTCPtranNrrr _serverDocr8r9r%rrrrr@ r@c@r?) TCPClientrArBNrrr _clientDocr8r9r%rrrrrGrFrGc@r?) UNIXServerUNIXrBNrDrrrrrJrFrJc@r?) UNIXClientrKrBNrHrrrrrLrFrLc@r?) SSLServerSSLrBNrDrrrrrMrFrMc@r?) SSLClientrNrBNrHrrrrrOrFrOc@r?) UDPServerUDPrBNrDrrrrrPrFrPc@r?)UNIXDatagramServer UNIXDatagramrBNrDrrrrrRrFrRc@r?)UNIXDatagramClientrSrBNrHrrrrrTrFrTc@r?)MulticastServer MulticastrBNrDrrrrrUrFrUc@s8eZdZdZddgZddZddZdd Zd d Zd S) TimerServicea Service to periodically call a function Every C{step} seconds call the given function with the given arguments. The service starts the calls when it starts, and cancels them when it stops. @ivar clock: Source of time. This defaults to L{None} which is causes L{twisted.internet.reactor} to be used. Feel free to set this to something else, but it probably ought to be set *before* calling L{startService}. @type clock: L{IReactorTime} @ivar call: Function and arguments to call periodically. @type call: L{tuple} of C{(callable, args, kwargs)} _loop _loopFinishedcOs||_|||f|_d|_dS)a+ @param step: The number of seconds between calls. @type step: L{float} @param callable: Function to call @type callable: L{callable} @param args: Positional arguments to pass to function @param kwargs: Keyword arguments to pass to function N)stepcallclock)rrZcallabler)r+rrrr-s  zTimerService.__init__cCsftj||j\}}}tj|g|Ri||_t|j|j_|jj |j dd|_ |j |j dS)NT)now)rrr4r[r LoopingCallrXrr\startrZrY addErrback_failed)rr]r)r+rrrr4*s  zTimerService.startServicecCsd|j_t|dSNF)rXrunningr err)rwhyrrrrb6szTimerService._failedcs,jjr jjfddjS)z Stop the service. @rtype: L{Deferred} @return: a L{Deferred} which is fired when the currently running call (if any) is finished. cs tjSr)rrr5_r2rrGs z*TimerService.stopService..)rXrdstoprY addCallbackr2rr2rr5=s zTimerService.stopServiceN) rrrr9rr-r4rbr5rrrrrWs rWc@s0eZdZdZddZddZddZdd Zd S) CooperatorServicezb Simple L{service.IService} which starts and stops a L{twisted.internet.task.Cooperator}. cCstjdd|_dS)NF)started)r Cooperatorcoopr2rrrr-PszCooperatorService.__init__cC |j|Sr)ro coiterate)riteratorrrrrqS zCooperatorService.coiteratecC|jdSr)ror`r2rrrr4VzCooperatorService.startServicecCrtr)rorjr2rrrr5YruzCooperatorService.stopServiceN)rrrr9r-rqr4r5rrrrrlKs  rlc@s4eZdZdZdZddZddZddZd d Zd S) StreamServerEndpointServiceaP A L{StreamServerEndpointService} is an L{IService} which runs a server on a listening port described by an L{IStreamServerEndpoint }. @ivar factory: A server factory which will be used to listen on the endpoint. @ivar endpoint: An L{IStreamServerEndpoint } provider which will be used to listen when the service starts. @ivar _waitingForPort: a Deferred, if C{listen} has yet been invoked on the endpoint, otherwise None. @ivar _raiseSynchronously: Defines error-handling behavior for the case where C{listen(...)} raises an exception before C{startService} or C{privilegedStartService} have completed. @type _raiseSynchronously: C{bool} @since: 10.2 FcCs||_||_d|_dSr)endpointfactory_waitingForPort)rrwrxrrrr-xs z$StreamServerEndpointService.__init__csTtjjj_gfdd}j|r%dd_ dS)z2 Start listening on the endpoint. cs0jr |dS|tst|dSdSr)_raiseSynchronouslyappendcheckrr re)re raisedNowrrrhandleIts  zDStreamServerEndpointService.privilegedStartService..handleItrFN) rrr0rwlistenrxryraraiseExceptionrz)rrrr}rr0}s    z2StreamServerEndpointService.privilegedStartServicecCs&tj||jdur|dSdS)zu Start listening on the endpoint, unless L{privilegedStartService} got around to it already. N)rrr4ryr0r2rrrr4s   z(StreamServerEndpointService.startServicecs8jdd}j|}fdd}|||S)a Stop listening on the port if it is already listening, otherwise, cancel the attempt to listen. @return: a L{Deferred} which fires with L{None} when the port has stopped listening. cSs|dur|SdSr)r6)portrrrstopItsz7StreamServerEndpointService.stopService..stopItcs d_|Src)rd) passthroughr2rrrjsz5StreamServerEndpointService.stopService..stop)rycancelrkaddBoth)rrrrjrr2rr5s    z'StreamServerEndpointService.stopServiceN) rrrr9rzr-r0r4r5rrrrrv]s rvc@6eZdZdZddZddZddZdefd d Zd S) _ReconnectingProtocolProxyz A proxy for a Protocol to provide connectionLost notification to a client connection service, in support of reconnecting when connections are lost. cCs||_||_dS)a Create a L{_ReconnectingProtocolProxy}. @param protocol: the application-provided L{interfaces.IProtocol} provider. @type protocol: provider of L{interfaces.IProtocol} which may additionally provide L{interfaces.IHalfCloseableProtocol} and L{interfaces.IFileDescriptorReceiver}. @param lostNotification: a 1-argument callable to invoke with the C{reason} when the connection is lost. N) _protocol_lostNotification)rprotocollostNotificationrrrr-s z#_ReconnectingProtocolProxy.__init__c Cs&z |j|W||S||w)z The connection was lost. Relay this information. @param reason: The reason the connection was lost. @return: the underlying protocol's result )rconnectionLostr)rreasonrrrrs z)_ReconnectingProtocolProxy.connectionLostcC t|j|Sr)r7rritemrrr __getattr__rsz&_ReconnectingProtocolProxy.__getattr__returncCsd|jjd|jdS)N) __class__rrr2rrr__repr__sz#_ReconnectingProtocolProxy.__repr__N) rrrr9r-rrr rrrrrrs  rc@r) _DisconnectFactoryz A L{_DisconnectFactory} is a proxy for L{IProtocolFactory} that catches C{connectionLost} notifications and relays them. cCs||_||_dSr)_protocolFactory_protocolDisconnected)rprotocolFactoryprotocolDisconnectedrrrr-s z_DisconnectFactory.__init__cCst|j||jS)a2 Create a L{_ReconnectingProtocolProxy} with the disconnect-notification callback we were called with. @param addr: The address the connection is coming from. @return: a L{_ReconnectingProtocolProxy} for a protocol produced by C{self._protocolFactory} )rr buildProtocolr)raddrrrrrs z _DisconnectFactory.buildProtocolcCrr)r7rrrrrrrsz_DisconnectFactory.__getattr__rcCsd|jj|jS)Nz<{} wrapping {!r}>)r8rrrr2rrrrs z_DisconnectFactory.__repr__N) rrrr9r-rrr rrrrrrs rg?gN@g?csfdd}|S)a A timeout policy for L{ClientService} which computes an exponential backoff interval with configurable parameters. @since: 16.1.0 @param initialDelay: Delay for the first reconnection attempt (default 1.0s). @type initialDelay: L{float} @param maxDelay: Maximum number of seconds between connection attempts (default 60 seconds, or one minute). Note that this value is before jitter is applied, so the actual maximum possible delay is this value plus the maximum possible result of C{jitter()}. @type maxDelay: L{float} @param factor: A multiplicative factor by which the delay grows on each failed reattempt. Default: 1.5. @type factor: L{float} @param jitter: A 0-argument callable that introduces noise into the delay. By default, C{random.random}, i.e. a pseudorandom floating-point value between zero and one. @type jitter: 0-argument callable returning L{float} @return: a 1-argument callable that, given an attempt count, returns a floating point number; the number of seconds to delay. @rtype: see L{ClientService.__init__}'s C{retryPolicy} argument. cs>zttd|}Wn ty}Ynw|S)Nd)min OverflowError)attemptdelayfactor initialDelayjittermaxDelayrrpolicys   zbackoffPolicy..policyr)rrrrrrrr backoffPolicys!rcCs t|dS)aO Return the first element of a generator and exhaust it. C{MethodicalMachine.upon}'s C{collector} argument takes a generator of output results. If the generator is exhausted, the later outputs aren't actually run. @param gen: Generator to extract values from @return: The first element of the generator. r)list)genrrr _firstResult*s rc@s|eZdZdZeZddZejddddZedd Z ed d Z ed d Z eddZ eddZ eddZeddZeddZddZeddZeddZeddZed d!Zed"d#Zed$d%Zed&d'Zed(d)Zed*d+Zed,d-Zed.d/Zd0d1Zed2d3Z ed4d5Z!ed6d7Z"ed8d9Z#ed:d;Z$edd?Z&d@dAZ'edSdCdDZ(edSdEdFZ)edSdGdHZ*edSdIdJZ+edKdLZ,dMdNZ-edOdPZ.ej/ee egdQej/eee,ge0dRe j/ee gdQe j/ee eege0dRe j/ee egdQe j/ee ee.gdQe j/ee gdQe j/eeee#ee%ge0dRe j/e e egdQe j/ee gdQe j/ee eege0dRe j/e!e e"egdQe j/ee egdQe j/ee ege0dRe j/e!ee#e%e"gdQe j/eee$e&gdQe j/ee gdQe j/ee ege0dRe j/e!e e%egdQej/ee egdQej/eee,ge0dRej/e(ee+ge0dRe j/e(e e+ge0dRe j/e(e e+ge0dRe j/e(e e)ge0dRe j/e(e e+ge0dRe j/e(e e+ge0dRej/e(ee*ge0dRdBS)T_ClientMachinea State machine for maintaining a single outgoing connection to an endpoint. @ivar _awaitingConnected: notifications to make when connection succeeds, fails, or is cancelled @type _awaitingConnected: list of (Deferred, count) tuples @see: L{ClientService} cCsJ||_d|_d|_||_||_||_||_td|_g|_ g|_ ||_ dS)z @see: L{ClientService.__init__} @param log: The logger for the L{ClientService} instance this state machine is associated to. @type log: L{Logger} rFN) _endpoint_failedAttempts_stopped_factory_timeoutForAttempt_clock_prepareConnectionr _connectionInProgress_awaitingConnected _stopWaiters_log)rrwrx retryPolicyr\prepareConnectionr rrrr-Fs  z_ClientMachine.__init__T)initialcCdS)z3 The service has not been started. Nrr2rrr_init\z_ClientMachine._initcCr)z5 The service has started connecting. Nrr2rrr _connectingbrz_ClientMachine._connectingcCr)za The service is waiting for the reconnection period before reconnecting. Nrr2rrr_waitinghrz_ClientMachine._waitingcCr)z+ The service is connected. Nrr2rrr _connectedorz_ClientMachine._connectedcCr)zM The service is disconnecting after being asked to shutdown. Nrr2rrr_disconnectingurz_ClientMachine._disconnectingcCr)zM The service is disconnecting and has been asked to restart. Nrr2rrr _restarting{rz_ClientMachine._restartingcCr)zC The service has been stopped and is disconnected. Nrr2rrrrrz_ClientMachine._stoppedcCr)T Start this L{ClientService}, initiating the connection retry loop. Nrr2rrrr`rz_ClientMachine.startcs>tjfdd}j|jjj_ dS)z- Start a connection attempt. csSr)_clientDisconnectedrgr2rrrisz)_ClientMachine._connect..N) rrrr>rk_runPrepareConnection_connectionMadera_connectionFailedr)r factoryProxyrr2r_connects z_ClientMachine._connectcs$|jrt|jfddSS)am Run any C{prepareConnection} callback with the connected protocol, ignoring its return value but propagating any failure. @param protocol: The protocol of the connection. @type protocol: L{IProtocol} @return: Either: - A L{Deferred} that succeeds with the protocol when the C{prepareConnection} callback has executed successfully. - A L{Deferred} that fails when the C{prepareConnection} callback throws or returns a failed L{Deferred}. - The protocol, when no C{prepareConnection} callback is defined. csSrrrgrrrrirz6_ClientMachine._runPrepareConnection..)rr rkrrrrrrs   z$_ClientMachine._runPrepareConnectioncCs d|_dS)z6 Reset the number of failed attempts. rN)rr2rrr_resetFailedAttemptss z#_ClientMachine._resetFailedAttemptscCr)z Stop trying to connect and disconnect any current connection. @return: a L{Deferred} that fires when all outstanding connections are closed and all in-progress connection attempts halted. Nrr2rrrrjrz_ClientMachine.stopcCs|jt|jdS)z Return a deferred that will fire when the service has finished disconnecting. @return: L{Deferred} that fires when the service has finished disconnecting. )rr{rr2rrr _waitForStops z_ClientMachine._waitForStopcCs|jdS)z2 Stop pending connection attempt. N)rrr2rrr_stopConnectingsz_ClientMachine._stopConnectingcCs|j|`dS)z4 Stop pending attempt to reconnect. N) _retryCallrr2rrr _stopRetryings z_ClientMachine._stopRetryingcCs|jjdS)z4 Disconnect the current connection. N)_currentConnection transportloseConnectionr2rrr _disconnectsz_ClientMachine._disconnectcCr)z A connection has been made. @param protocol: The protocol of the connection. @type protocol: L{IProtocol} Nrrrrrrrz_ClientMachine._connectionMadecCsd|_|j|_||jdS)z Notify all pending requests for a connection that a connection has been made. @param protocol: The protocol of the connection. @type protocol: L{IProtocol} rN)rrr_unawaitrrrr_notifyWaiterss z_ClientMachine._notifyWaiterscCr)z8 The current connection attempt failed. Nrrfrrrrrz _ClientMachine._connectionFailedcC |dS)z+ Schedule a retry attempt. N_doWaitr2rrr_wait z_ClientMachine._waitcCs|S)zM Schedule a retry attempt, and ignore the Failure passed in. rrrrr_ignoreAndWait z_ClientMachine._ignoreAndWaitcCsH|jd7_||j}|jjd|j|j|d|j||j|_dS)NzDScheduling retry {attempt} to connect {endpoint} in {delay} seconds.)rrwr) rrrinforr callLater _reconnectr)rrrrrrs z_ClientMachine._doWaitcCr)z? The wait between connection attempts is done. Nrr2rrrrrz_ClientMachine._reconnectcCr)z? The current connection has been disconnected. Nrr2rrrr%rz"_ClientMachine._clientDisconnectedcCs|`dS)z0 Forget the current connection. N)rr2rrr_forgetConnection+rz _ClientMachine._forgetConnectioncC|ttdS)zm Notify all pending requests for a connection that no more connections are expected. Nrrrr2rrr_cancelConnectWaiters2z$_ClientMachine._cancelConnectWaiterscCr)z Notify all pending requests for a connection that no more connections are expected, after ignoring the Failure passed in. Nrrrrr_ignoreAndCancelConnectWaiters:rz-_ClientMachine._ignoreAndCancelConnectWaiterscCr)zG Notify all deferreds waiting on the service stopping. N_doFinishStoppingr2rrr_finishStoppingBrz_ClientMachine._finishStoppingcCr)zq Notify all deferreds waiting on the service stopping, and ignore the Failure passed in. Nrrrrr_ignoreAndFinishStoppingIs z'_ClientMachine._ignoreAndFinishStoppingcCs&g|j|_}|D]}|dq dSr)rcallback)rwaitingwrrrrQs z _ClientMachine._doFinishStoppingNcCr)i Retrieve the currently-connected L{Protocol}, or the next one to connect. @param failAfterFailures: number of connection failures after which the Deferred will deliver a Failure (None means the Deferred will only fail if/when the service is stopped). Set this to 1 to make the very first connection failure signal an error. Use 2 to allow one failure but signal an error if the subsequent retry then fails. @type failAfterFailures: L{int} or None @return: a Deferred that fires with a protocol produced by the factory passed to C{__init__} @rtype: L{Deferred} that may: - fire with L{IProtocol} - fail with L{CancelledError} when the service is stopped - fail with e.g. L{DNSLookupError} or L{ConnectionRefusedError} when the number of consecutive failed connection attempts equals the value of "failAfterFailures" NrrfailAfterFailuresrrr whenConnectedVrz_ClientMachine.whenConnectedcCs t|jS)z Return the currently connected protocol. @return: L{Deferred} that is fired with currently connected protocol. )r rrrrrrs z!_ClientMachine._currentConnectioncCs ttS)z Notify the caller that no connection is expected. @return: L{Deferred} that is fired with L{CancelledError}. )r rrrrr _noConnection|rz_ClientMachine._noConnectioncCst}|j||f|S)z Return a deferred that will fire with the next connected protocol. @return: L{Deferred} that will fire with the next connected protocol. )rrr{)rrresultrrr_awaitingConnectionsz"_ClientMachine._awaitingConnectioncCstdS)z Return a deferred that has already fired with L{None}. @return: A L{Deferred} that has already fired with L{None}. N)r r2rrr_deferredSucceededWithNonesz)_ClientMachine._deferredSucceededWithNonecCs*g|j|_}|D] \}}||q dS)z Fire all outstanding L{ClientService.whenConnected} L{Deferred}s. @param value: the value to fire the L{Deferred}s with. N)rr)rvaluerr remainingrrrrs  z_ClientMachine._unawaitcCstg}g}|jD]#\}}|dur|||fq|dkr!||q|||dfq||_|D]}||q0dS)z Deliver connection failures to any L{ClientService.whenConnected} L{Deferred}s that have met their failAfterFailures threshold. @param f: the Failure to fire the L{Deferred}s with. Nr)rr{r)rrreadynotReadyrrrrr_deliverConnectionFailures  z(_ClientMachine._deliverConnectionFailure)enteroutputs)rr collectorr)1rrrr9r_machiner-staterrrrrrrinputr`outputrrrrjrrrrrrrrrrrrrrrrrrrrrrrrruponrrrrrr9sf                                          rcsHeZdZdZeZ d ddZd ddZfddZfd d Z Z S) ClientServicez A L{ClientService} maintains a single outgoing connection to a client endpoint, reconnecting after a configurable timeout when a connection fails, either before or after connecting. @since: 16.1.0 NcCs4t|}|dur tn|}t||||||jd|_dS)aZ @param endpoint: A L{stream client endpoint } provider which will be used to connect when the service starts. @param factory: A L{protocol factory } which will be used to create clients for the endpoint. @param retryPolicy: A policy configuring how long L{ClientService} will wait between attempts to connect to C{endpoint}. @type retryPolicy: callable taking (the number of failed connection attempts made in a row (L{int})) and returning the number of seconds to wait before making another attempt. @param clock: The clock used to schedule reconnection. It's mainly useful to be parametrized in tests. If the factory is serialized, this attribute will not be serialized, and the default value (the reactor) will be restored when deserialized. @type clock: L{IReactorTime} @param prepareConnection: A single argument L{callable} that may return a L{Deferred}. It will be called once with the L{protocol } each time a new connection is made. It may call methods on the protocol to prepare it for use (e.g. authenticate) or validate it (check its health). The C{prepareConnection} callable may raise an exception or return a L{Deferred} which fails to reject the connection. A rejected connection is not used to fire an L{Deferred} returned by L{whenConnected}. Instead, L{ClientService} handles the failure and continues as if the connection attempt were a failure (incrementing the counter passed to C{retryPolicy}). L{Deferred}s returned by L{whenConnected} will not fire until any L{Deferred} returned by the C{prepareConnection} callable fire. Otherwise its successful return value is consumed, but ignored. Present Since Twisted 18.7.0 @type prepareConnection: L{callable} N)rr )r_defaultPolicyrrr)rrwrxrr\rrrrr-;s. zClientService.__init__cCrp)r)rrrrrrrus zClientService.whenConnectedcs.|jr |jddSt|jdS)rz1Duplicate ClientService.startService {log_source}N)rdrwarnsuperr4rr`r2rrrr4s   zClientService.startServicecst|jS)z Stop attempting to reconnect and close any existing connections. @return: a L{Deferred} that fires when all outstanding connections are closed and all in-progress connection attempts halted. )r r5rrjr2rrrr5s  zClientService.stopService)NNNr) rrrr9r rr-rr4r5 __classcell__rrrrr 0s :  r )rWrlrUrvrPr r@rGrJrLrMrOrRrTN)3r9r_goodEnoughRandomtypingrautomatrtwisted.applicationrrrtwisted.internet.deferrrr r r twisted.loggerr twisted.pythonr twisted.python.failurerrrrr"r:rIrEr@rGrJrLrMrOrPrRrTrUrWrlrvrrrr rrr __all__rrrrsR $         ?3 DT*" +z w