ϪfdZddlmZddlmZddlmZddlmZddl m Z ddl m Z m Z mZmZmZddlmZdd lmZdd lmZd ZGd d ej0ZGddeZGddeZdZdZGddeZGddeZGddeZ GddeZ!GddeZ"GddeZ#Gd d!eZ$Gd"d#eZ%Gd$d%eZ&Gd&d'eZ'Gd(d)eZ(Gd*d+ej0Z)Gd,d-ej0Z*Gd.d/Z+Gd0d1Z,d2d3d4efd5Z-e-Z.d6Z/Gd7d8Z0Gd9d:ej0Z1gd;Z2y<)=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)Failurec|ddlm}|S|S)zR @return: the argument, or the global reactor if the argument is L{None}. r)reactor)twisted.internetr) maybeReactorrs >/usr/lib/python3/dist-packages/twisted/application/internet.py_maybeGlobalReactorr<s,c(eZdZUgZeeed<dZy)_VolatileDataServicevolatilecvtjj|}|jD] }||vs||= |SN)rService __getstate__r)selfdattrs rrz!_VolatileDataService.__getstate__Ks> OO ( ( .MM DqydG rN)__name__ __module__ __qualname__rrstr__annotations__rrrrrHsHd3irrcLeZdZUdZdgZdZeed<dZdZ dZ dZ dZ d Z d Zy) _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}. _portmethodNcT||_d|vr|jd|_||_yNrargspoprkwargsrr/r1s r__init__z_AbstractServer.__init__j(  !::i0DL rcltjj||j|_yr)rrprivilegedStartService_getPortr)rs rr6z&_AbstractServer.privilegedStartServiceps!..t4]]_ rctjj||j|j |_yyr)rr startServicer)r7r8s rr:z_AbstractServer.startServicets0$$T* :: DJ rctjj||j|jj }|`|Syr)rr stopServicer) stopListening)rrs rr<z_AbstractServer.stopServiceysA##D) :: ! ((*A H "rctt|jdj|j|j i|j S)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/r1r8s rr7z_AbstractServer._getPortsP w  -      99 %  % %r)r!r"r#__doc__rr+r$r%rr)r3r6r:r<r7r&rrr(r(Ss= yHFCG E %)  %rr(cFeZdZUdZdgZdZeed<dZdZ dZ dZ dZ d Z y) _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+NcT||_d|vr|jd|_||_yr-r.r2s rr3z_AbstractClient.__init__r4rcltjj||j|_yr)rrr:_getConnectionrDr8s rr:z_AbstractClient.startServices%$$T*..0rctjj||j|jj |`yyr)rrr<rD disconnectr8s rr<z_AbstractClient.stopServices=##D)    '    ' ' )  (rctt|jd|j|ji|j S)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)r?rrr+r/r1r8s rrGz_AbstractClient._getConnectionsCSw*4<<8GDKK=:QR YY ++  r)r!r"r#rArr+r$r%rrDr3r:r<rGr&rrrCrCs8 HFCGK 1!  rrCztConnect 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. c4eZdZej dZdZy) TCPServerTCPtranNr!r"r# _serverDocr@rAr+r&rrrMrMU+G FrrMc4eZdZej dZdZy) TCPClientrNrONr!r"r# _clientDocr@rAr+r&rrrUrUrSrrUc4eZdZej dZdZy) UNIXServerUNIXrONrQr&rrrYrYV,G FrrYc4eZdZej dZdZy) UNIXClientrZrONrVr&rrr]r]r[rr]c4eZdZej dZdZy) SSLServerSSLrONrQr&rrr_r_rSrr_c4eZdZej dZdZy) SSLClientr`rONrVr&rrrbrbrSrrbc4eZdZej dZdZy) UDPServerUDPrONrQr&rrrdrdrSrrdc4eZdZej dZdZy)UNIXDatagramServer UNIXDatagramrONrQr&rrrgrg^4G Frrgc4eZdZej dZdZy)UNIXDatagramClientrhrONrVr&rrrkrkrirrkc4eZdZej dZdZy)MulticastServer MulticastrONrQr&rrrmrms[1G Frrmc0eZdZdZddgZdZdZdZdZy) 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 _loopFinishedc4||_|||f|_d|_y)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)rrtcallabler/r1s rr3zTimerService.__init__s  tV,  rctjj||j\}}}t j |g|i||_t|j|j _|j j|jd|_ |jj|jy)NT)now)rrr:rur LoopingCallrqrrvstartrtrr addErrback_failed)rrwr/r1s rr:zTimerService.startService)s$$T*!%$ %%h@@@ .tzz: !ZZ--diiT-B %%dll3rcPd|j_tj|yNF)rqrunningrerr)rwhys rr}zTimerService._failed5s#   rcjjrjjjj fdjS)z Stop the service. @rtype: L{Deferred} @return: a L{Deferred} which is fired when the currently running call (if any) is finished. cBtjjSr)rrr<_rs rz*TimerService.stopService..Fs1L1LT1Rr)rqrstoprr addCallbackr8s`rr<zTimerService.stopService<sA ::   JJOO  &&'RS!!!rN) r!r"r#rArr3r:r}r<r&rrrprps'")H  4 "rrpc(eZdZdZdZdZdZdZy)CooperatorServicezb Simple L{service.IService} which starts and stops a L{twisted.internet.task.Cooperator}. c:tjd|_y)NF)started)r Cooperatorcoopr8s rr3zCooperatorService.__init__OsOOE2 rc8|jj|Sr)r coiterate)riterators rrzCooperatorService.coiterateRsyy""8,,rc8|jjyr)rr{r8s rr:zCooperatorService.startServiceUs rc8|jjyr)rrr8s rr<zCooperatorService.stopServiceXs rN)r!r"r#rAr3rr:r<r&rrrrJs3-rrc,eZdZdZdZdZdZdZdZy)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 Fc.||_||_d|_yr)endpointfactory_waitingForPort)rrrs rr3z$StreamServerEndpointService.__init__ws   #rctjjjj j _gfd}j j|rdjd_ y)z2 Start listening on the endpoint. cjrj|y|jtst j |yyr)_raiseSynchronouslyappendcheckrrr)r raisedNowrs rhandleItzDStreamServerEndpointService.privilegedStartService..handleIts6''  %YY~. /rrFN) rrr6rlistenrrr|raiseExceptionr)rrrs` @rr6z2StreamServerEndpointService.privilegedStartService|sm ..t4#}}33DLLA   ''1  aL ' ' )#( rc|tjj||j|j yy)zu Start listening on the endpoint, unless L{privilegedStartService} got around to it already. N)rrr:rr6r8s rr:z(StreamServerEndpointService.startServices3 $$T*    '  ' ' ) (rcjjd}jj|}fd}|j||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. c(||jSyr)r=)ports rstopItz7StreamServerEndpointService.stopService..stopIts))++ rcd_|Sr)r) passthroughrs rrz5StreamServerEndpointService.stopService..stops DL r)rcancelraddBoth)rrrrs` rr<z'StreamServerEndpointService.stopServicesK ##% ,  , ,V 4  $rN) r!r"r#rArr3r6r:r<r&rrrr\s#0 $ )&*rrc.eZdZdZdZdZdZdefdZy)_ReconnectingProtocolProxyz A proxy for a Protocol to provide connectionLost notification to a client connection service, in support of reconnecting when connections are lost. c ||_||_y)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)rprotocollostNotifications rr3z#_ReconnectingProtocolProxy.__init__s"!1rc |jj||j|S#|j|wxYw)z The connection was lost. Relay this information. @param reason: The reason the connection was lost. @return: the underlying protocol's result )rconnectionLostr)rreasons rrz)_ReconnectingProtocolProxy.connectionLosts6 +>>008  " "6 *D " "6 *s .Ac.t|j|Sr)r?rritems r __getattr__z&_ReconnectingProtocolProxy.__getattr__st~~t,,rreturncPd|jjd|jdS)N) __class__r!rr8s r__repr__z#_ReconnectingProtocolProxy.__repr__s'4>>**+:dnn5GqIIrN) r!r"r#rAr3rrr$rr&rrrrs$ 2 +-J#Jrrc.eZdZdZdZdZdZdefdZy)_DisconnectFactoryz A L{_DisconnectFactory} is a proxy for L{IProtocolFactory} that catches C{connectionLost} notifications and relays them. c ||_||_yr)_protocolFactory_protocolDisconnected)rprotocolFactoryprotocolDisconnecteds rr3z_DisconnectFactory.__init__s /%9"rc`t|jj||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)raddrs rrz _DisconnectFactory.buildProtocols-*  ! ! / / 5t7Q7Q  rc.t|j|Sr)r?rrs rrz_DisconnectFactory.__getattr__st,,d33rrcbdj|jj|jS)Nz<{} wrapping {!r}>)r@rr!rr8s rrz_DisconnectFactory.__repr__s*#** NN # #T%:%:  rN) r!r"r#rAr3rrr$rr&rrrrs" :  4 # rrg?gN@g?cfd}|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. ct ttd|zz}|zS#t$r}YwxYw)Nd)min OverflowError)attemptdelayfactor initialDelayjittermaxDelays rpolicyzbackoffPolicy..policysJ  #c72C(CDhOEvx E s ) 77r&)rrrrrs```` r backoffPolicyrsB  Mrct|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)gens r _firstResultr)s 9Q<rc eZdZdZeZdZejddZejdZ ejdZ ejdZ ejd Z ejd Z ejd Zejd Zej#d ZdZej#dZejdZej#dZej#dZej#dZej#dZejdZej#dZejdZej#dZej#dZdZejdZ ejdZ!ej#dZ"ej#dZ#ej#dZ$ej#d Z%ej#d!Z&d"Z'ejd-d$Z(ej#d-d%Z)ej#d-d&Z*ej#d-d'Z+ej#d(Z,d)Z-ej#d*Z.ej_ee eg+ej_eee,ge0,e j_ee g+e j_ee eege0,e j_ee eg+e j_ee ee.g+e j_ee g+e j_eeee#ee%ge0,e j_e e eg+e j_ee g+e j_ee eege0,e j_e!e e"eg+e j_ee eg+e j_ee ege0,e j_e!ee#e%e"g+e j_eee$e&g+e j_ee g+e j_ee ege0,e j_e!e e%eg+ej_ee eg+ej_eee,ge0,ej_e(ee+ge0,e j_e(e e+ge0,e j_e(e e+ge0,e j_e(e e)ge0,e j_e(e e+ge0,e j_e(e e+ge0,ej_e(ee*ge0,y#)._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} c||_d|_d|_||_||_||_||_td|_g|_ g|_ ||_ y)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)rrr retryPolicyrvprepareConnectionrs rr3z_ClientMachine.__init__Es["   "- "3%,T]""$ rT)initialcy)z3 The service has not been started. Nr&r8s r_initz_ClientMachine._init[rcy)z5 The service has started connecting. Nr&r8s r _connectingz_ClientMachine._connectingarrcy)za The service is waiting for the reconnection period before reconnecting. Nr&r8s r_waitingz_ClientMachine._waitinggrrcy)z+ The service is connected. Nr&r8s r _connectedz_ClientMachine._connectednrrcy)zM The service is disconnecting after being asked to shutdown. Nr&r8s r_disconnectingz_ClientMachine._disconnectingtrrcy)zM The service is disconnecting and has been asked to restart. Nr&r8s r _restartingz_ClientMachine._restartingzrrcy)zC The service has been stopped and is disconnected. Nr&r8s rrz_ClientMachine._stoppedrrcy)T Start this L{ClientService}, initiating the connection retry loop. Nr&r8s rr{z_ClientMachine.startrrctjfd}jj|j j j j jj_ y)z- Start a connection attempt. c$jSr)_clientDisconnectedrs rrz)_ClientMachine._connect..sT%=%=%?rN) rrrrKr_runPrepareConnection_connectionMader|_connectionFailedr)r factoryProxys` r_connectz_ClientMachine._connectse * MM? NN " "< 0 [33 4 [-- . Z.. / "rcp|jr(t|jjfdSS)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. cSrr&)rrs rrz6_ClientMachine._runPrepareConnection..s(r)rr rrrs `rrz$_ClientMachine._runPrepareConnections8$  " " !8!8(COO" rcd|_y)z6 Reset the number of failed attempts. rN)rr8s r_resetFailedAttemptsz#_ClientMachine._resetFailedAttemptss !rcy)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. Nr&r8s rrz_ClientMachine.stoprrcf|jjt|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. )rrr r8s r _waitForStopz_ClientMachine._waitForStops+   ,  $$rc8|jjy)z2 Stop pending connection attempt. N)rrr8s r_stopConnectingz_ClientMachine._stopConnectings ""))+rc<|jj|`y)z4 Stop pending attempt to reconnect. N) _retryCallrr8s r _stopRetryingz_ClientMachine._stopRetryings  OrcL|jjjy)z4 Disconnect the current connection. N)_currentConnection transportloseConnectionr8s r _disconnectz_ClientMachine._disconnects ))88:rcy)z A connection has been made. @param protocol: The protocol of the connection. @type protocol: L{IProtocol} Nr&r s rrz_ClientMachine._connectionMaderrcjd|_|j|_|j|jy)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_unawaitr s r_notifyWaitersz_ClientMachine._notifyWaiterss, !"*"4"4 d--.rcy)z8 The current connection attempt failed. Nr&rfs rrz _ClientMachine._connectionFailedrrc$|jy)z+ Schedule a retry attempt. N_doWaitr8s r_waitz_ClientMachine._waits rc"|jS)zM Schedule a retry attempt, and ignore the Failure passed in. r"rs r_ignoreAndWaitz_ClientMachine._ignoreAndWait s ||~rc |xjdz c_|j|j}|jjd|j|j||j j ||j|_y)NzDScheduling retry {attempt} to connect {endpoint} in {delay} seconds.)rrr) rrrinforr callLater _reconnectr)rrs rr#z_ClientMachine._doWaitsr !''(<(<=  U((^^  ++//tGrcy)z? The wait between connection attempts is done. Nr&r8s rr+z_ClientMachine._reconnectrrcy)z? The current connection has been disconnected. Nr&r8s rrz"_ClientMachine._clientDisconnected$rrc|`y)z0 Forget the current connection. N)rr8s r_forgetConnectionz _ClientMachine._forgetConnection*s  #rcH|jtty)zm Notify all pending requests for a connection that no more connections are expected. Nrrrr8s r_cancelConnectWaitersz$_ClientMachine._cancelConnectWaiters1 gn./0rcH|jtty)z Notify all pending requests for a connection that no more connections are expected, after ignoring the Failure passed in. Nr1rs r_ignoreAndCancelConnectWaitersz-_ClientMachine._ignoreAndCancelConnectWaiters9r3rc$|jy)zG Notify all deferreds waiting on the service stopping. N_doFinishStoppingr8s r_finishStoppingz_ClientMachine._finishStoppingAs  rc$|jy)zq Notify all deferreds waiting on the service stopping, and ignore the Failure passed in. Nr7rs r_ignoreAndFinishStoppingz'_ClientMachine._ignoreAndFinishStoppingHs  rc\g|jc|_}|D]}|jdyr)rcallback)rwaitingws rr8z _ClientMachine._doFinishStoppingPs2%'):):"7 A JJt  rNcy)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" Nr&rfailAfterFailuress r whenConnectedz_ClientMachine.whenConnectedUrrc,t|jS)z Return the currently connected protocol. @return: L{Deferred} that is fired with currently connected protocol. )r rrBs rrz!_ClientMachine._currentConnectionrst..//rc(ttS)z Notify the caller that no connection is expected. @return: L{Deferred} that is fired with L{CancelledError}. )r rrBs r _noConnectionz_ClientMachine._noConnection{sN$%%rcTt}|jj||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. )r rr)rrCresults r_awaitingConnectionz"_ClientMachine._awaitingConnections* &&0A'BC rctdS)z Return a deferred that has already fired with L{None}. @return: A L{Deferred} that has already fired with L{None}. N)r r8s r_deferredSucceededWithNonez)_ClientMachine._deferredSucceededWithNonest}rcbg|jc|_}|D]\}}|j|y)z Fire all outstanding L{ClientService.whenConnected} L{Deferred}s. @param value: the value to fire the L{Deferred}s with. N)rr=)rvaluer>r? remainings rrz_ClientMachine._unawaits8 ,.t/F/F(# LAy JJu  rcg}g}|jD]H\}}||j||f|dkr|j|3|j||dz fJ||_|D]}|j|y)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()rrr=)rr readynotReadyr?rOs r_deliverConnectionFailurez(_ClientMachine._deliverConnectionFailures 33 4LAy I/a QIM 23  4#+ A JJqM r)enteroutputs)rTrU collectorr)1r!r"r#rAr_machiner3staterrrrrrrinputr{outputrrr rrrrrrrrr$r&r#r+rr/r2r5r9r;r8rDrrGrJrLrrSuponrr&rrrr8s!"H,^^D^! " ^^  ^^  ^^  ^^  ^^  ^^  ^^  __    0__!! ^^  __ % %__,, ____;; ^^  __ / /^^  __ __ H^^  ^^  __$$ __11__11__!! __!! ^^  8__00__&&______, JJuK(J< JJ +, U+r: /  _J@PQ!:;  MM%xM4 MM 4m_U   MM*K(MDOOERO8OO {+  OO86G5O[;O:PQ N\Nl&9JK/1IJ U+r: N\Nl;(8S MM%{XJM? MM +,  JJ$%  $%   MM$%  OO#$  $%  $%   MMX ,rrcLeZdZdZeZ ddZddZfdZfdZ xZ 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 cnt|}|tn|}t||||||j|_y)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_defaultPolicyrrrW)rrrrrvrs rr3zClientService.__init__:s=\$E*(3(;n &    /   rc8|jj|S)rA)rWrDrBs rrDzClientService.whenConnectedts6}}**+<==rc|jr|jjdyt||j j y)rz1Duplicate ClientService.startService {log_source}N)rrwarnsuperr:rWr{rrs rr:zClientService.startServices; << IINNN O   rcTt||jjS)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. )rcr<rWrrds rr<zClientService.stopServices# }}!!##r)NNNr) r!r"r#rAr rr3rDr:r< __classcell__)rs@rr]r]/s2 8DRV8 t>:$$rr])rprrmrrdr]rMrUrYr]r_rbrgrkN)3rAr_goodEnoughRandomtypingrautomatrtwisted.applicationrrrtwisted.internet.deferrr r r r twisted.loggerr twisted.pythonrtwisted.python.failurerrrrr(rCrWrRrMrUrYr]r_rbrdrgrkrmrprrrrrr_rrr]__all__r&rrrpsz !H/%'!"* 7??<%*<%~0 *0 f           o A"'A"H$Q'//Qh'J'JT  DtC8I(V ttnt$GOOt$n r