internet.py 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  1. # -*- test-case-name: twisted.application.test.test_internet,twisted.test.test_application,twisted.test.test_cooperator -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Reactor-based Services
  6. Here are services to run clients, servers and periodic services using
  7. the reactor.
  8. If you want to run a server service, L{StreamServerEndpointService} defines a
  9. service that can wrap an arbitrary L{IStreamServerEndpoint
  10. <twisted.internet.interfaces.IStreamServerEndpoint>}
  11. as an L{IService}. See also L{twisted.application.strports.service} for
  12. constructing one of these directly from a descriptive string.
  13. Additionally, this module (dynamically) defines various Service subclasses that
  14. let you represent clients and servers in a Service hierarchy. Endpoints APIs
  15. should be preferred for stream server services, but since those APIs do not yet
  16. exist for clients or datagram services, many of these are still useful.
  17. They are as follows::
  18. TCPServer, TCPClient,
  19. UNIXServer, UNIXClient,
  20. SSLServer, SSLClient,
  21. UDPServer,
  22. UNIXDatagramServer, UNIXDatagramClient,
  23. MulticastServer
  24. These classes take arbitrary arguments in their constructors and pass
  25. them straight on to their respective reactor.listenXXX or
  26. reactor.connectXXX calls.
  27. For example, the following service starts a web server on port 8080:
  28. C{TCPServer(8080, server.Site(r))}. See the documentation for the
  29. reactor.listen/connect* methods for more information.
  30. """
  31. from __future__ import absolute_import, division
  32. from random import random as _goodEnoughRandom
  33. from twisted.python import log
  34. from twisted.logger import Logger
  35. from twisted.application import service
  36. from twisted.internet import task
  37. from twisted.python.failure import Failure
  38. from twisted.internet.defer import (
  39. CancelledError, Deferred, succeed, fail, maybeDeferred
  40. )
  41. from automat import MethodicalMachine
  42. def _maybeGlobalReactor(maybeReactor):
  43. """
  44. @return: the argument, or the global reactor if the argument is L{None}.
  45. """
  46. if maybeReactor is None:
  47. from twisted.internet import reactor
  48. return reactor
  49. else:
  50. return maybeReactor
  51. class _VolatileDataService(service.Service):
  52. volatile = []
  53. def __getstate__(self):
  54. d = service.Service.__getstate__(self)
  55. for attr in self.volatile:
  56. if attr in d:
  57. del d[attr]
  58. return d
  59. class _AbstractServer(_VolatileDataService):
  60. """
  61. @cvar volatile: list of attribute to remove from pickling.
  62. @type volatile: C{list}
  63. @ivar method: the type of method to call on the reactor, one of B{TCP},
  64. B{UDP}, B{SSL} or B{UNIX}.
  65. @type method: C{str}
  66. @ivar reactor: the current running reactor.
  67. @type reactor: a provider of C{IReactorTCP}, C{IReactorUDP},
  68. C{IReactorSSL} or C{IReactorUnix}.
  69. @ivar _port: instance of port set when the service is started.
  70. @type _port: a provider of L{twisted.internet.interfaces.IListeningPort}.
  71. """
  72. volatile = ['_port']
  73. method = None
  74. reactor = None
  75. _port = None
  76. def __init__(self, *args, **kwargs):
  77. self.args = args
  78. if 'reactor' in kwargs:
  79. self.reactor = kwargs.pop("reactor")
  80. self.kwargs = kwargs
  81. def privilegedStartService(self):
  82. service.Service.privilegedStartService(self)
  83. self._port = self._getPort()
  84. def startService(self):
  85. service.Service.startService(self)
  86. if self._port is None:
  87. self._port = self._getPort()
  88. def stopService(self):
  89. service.Service.stopService(self)
  90. # TODO: if startup failed, should shutdown skip stopListening?
  91. # _port won't exist
  92. if self._port is not None:
  93. d = self._port.stopListening()
  94. del self._port
  95. return d
  96. def _getPort(self):
  97. """
  98. Wrapper around the appropriate listen method of the reactor.
  99. @return: the port object returned by the listen method.
  100. @rtype: an object providing
  101. L{twisted.internet.interfaces.IListeningPort}.
  102. """
  103. return getattr(_maybeGlobalReactor(self.reactor),
  104. 'listen%s' % (self.method,))(*self.args, **self.kwargs)
  105. class _AbstractClient(_VolatileDataService):
  106. """
  107. @cvar volatile: list of attribute to remove from pickling.
  108. @type volatile: C{list}
  109. @ivar method: the type of method to call on the reactor, one of B{TCP},
  110. B{UDP}, B{SSL} or B{UNIX}.
  111. @type method: C{str}
  112. @ivar reactor: the current running reactor.
  113. @type reactor: a provider of C{IReactorTCP}, C{IReactorUDP},
  114. C{IReactorSSL} or C{IReactorUnix}.
  115. @ivar _connection: instance of connection set when the service is started.
  116. @type _connection: a provider of L{twisted.internet.interfaces.IConnector}.
  117. """
  118. volatile = ['_connection']
  119. method = None
  120. reactor = None
  121. _connection = None
  122. def __init__(self, *args, **kwargs):
  123. self.args = args
  124. if 'reactor' in kwargs:
  125. self.reactor = kwargs.pop("reactor")
  126. self.kwargs = kwargs
  127. def startService(self):
  128. service.Service.startService(self)
  129. self._connection = self._getConnection()
  130. def stopService(self):
  131. service.Service.stopService(self)
  132. if self._connection is not None:
  133. self._connection.disconnect()
  134. del self._connection
  135. def _getConnection(self):
  136. """
  137. Wrapper around the appropriate connect method of the reactor.
  138. @return: the port object returned by the connect method.
  139. @rtype: an object providing L{twisted.internet.interfaces.IConnector}.
  140. """
  141. return getattr(_maybeGlobalReactor(self.reactor),
  142. 'connect%s' % (self.method,))(*self.args, **self.kwargs)
  143. _doc={
  144. 'Client':
  145. """Connect to %(tran)s
  146. Call reactor.connect%(tran)s when the service starts, with the
  147. arguments given to the constructor.
  148. """,
  149. 'Server':
  150. """Serve %(tran)s clients
  151. Call reactor.listen%(tran)s when the service starts, with the
  152. arguments given to the constructor. When the service stops,
  153. stop listening. See twisted.internet.interfaces for documentation
  154. on arguments to the reactor method.
  155. """,
  156. }
  157. for tran in 'TCP UNIX SSL UDP UNIXDatagram Multicast'.split():
  158. for side in 'Server Client'.split():
  159. if tran == "Multicast" and side == "Client":
  160. continue
  161. if tran == "UDP" and side == "Client":
  162. continue
  163. base = globals()['_Abstract'+side]
  164. doc = _doc[side] % vars()
  165. klass = type(tran+side, (base,), {'method': tran, '__doc__': doc})
  166. globals()[tran+side] = klass
  167. class TimerService(_VolatileDataService):
  168. """
  169. Service to periodically call a function
  170. Every C{step} seconds call the given function with the given arguments.
  171. The service starts the calls when it starts, and cancels them
  172. when it stops.
  173. @ivar clock: Source of time. This defaults to L{None} which is
  174. causes L{twisted.internet.reactor} to be used.
  175. Feel free to set this to something else, but it probably ought to be
  176. set *before* calling L{startService}.
  177. @type clock: L{IReactorTime<twisted.internet.interfaces.IReactorTime>}
  178. @ivar call: Function and arguments to call periodically.
  179. @type call: L{tuple} of C{(callable, args, kwargs)}
  180. """
  181. volatile = ['_loop', '_loopFinished']
  182. def __init__(self, step, callable, *args, **kwargs):
  183. """
  184. @param step: The number of seconds between calls.
  185. @type step: L{float}
  186. @param callable: Function to call
  187. @type callable: L{callable}
  188. @param args: Positional arguments to pass to function
  189. @param kwargs: Keyword arguments to pass to function
  190. """
  191. self.step = step
  192. self.call = (callable, args, kwargs)
  193. self.clock = None
  194. def startService(self):
  195. service.Service.startService(self)
  196. callable, args, kwargs = self.call
  197. # we have to make a new LoopingCall each time we're started, because
  198. # an active LoopingCall remains active when serialized. If
  199. # LoopingCall were a _VolatileDataService, we wouldn't need to do
  200. # this.
  201. self._loop = task.LoopingCall(callable, *args, **kwargs)
  202. self._loop.clock = _maybeGlobalReactor(self.clock)
  203. self._loopFinished = self._loop.start(self.step, now=True)
  204. self._loopFinished.addErrback(self._failed)
  205. def _failed(self, why):
  206. # make a note that the LoopingCall is no longer looping, so we don't
  207. # try to shut it down a second time in stopService. I think this
  208. # should be in LoopingCall. -warner
  209. self._loop.running = False
  210. log.err(why)
  211. def stopService(self):
  212. """
  213. Stop the service.
  214. @rtype: L{Deferred<defer.Deferred>}
  215. @return: a L{Deferred<defer.Deferred>} which is fired when the
  216. currently running call (if any) is finished.
  217. """
  218. if self._loop.running:
  219. self._loop.stop()
  220. self._loopFinished.addCallback(lambda _:
  221. service.Service.stopService(self))
  222. return self._loopFinished
  223. class CooperatorService(service.Service):
  224. """
  225. Simple L{service.IService} which starts and stops a L{twisted.internet.task.Cooperator}.
  226. """
  227. def __init__(self):
  228. self.coop = task.Cooperator(started=False)
  229. def coiterate(self, iterator):
  230. return self.coop.coiterate(iterator)
  231. def startService(self):
  232. self.coop.start()
  233. def stopService(self):
  234. self.coop.stop()
  235. class StreamServerEndpointService(service.Service, object):
  236. """
  237. A L{StreamServerEndpointService} is an L{IService} which runs a server on a
  238. listening port described by an L{IStreamServerEndpoint
  239. <twisted.internet.interfaces.IStreamServerEndpoint>}.
  240. @ivar factory: A server factory which will be used to listen on the
  241. endpoint.
  242. @ivar endpoint: An L{IStreamServerEndpoint
  243. <twisted.internet.interfaces.IStreamServerEndpoint>} provider
  244. which will be used to listen when the service starts.
  245. @ivar _waitingForPort: a Deferred, if C{listen} has yet been invoked on the
  246. endpoint, otherwise None.
  247. @ivar _raiseSynchronously: Defines error-handling behavior for the case
  248. where C{listen(...)} raises an exception before C{startService} or
  249. C{privilegedStartService} have completed.
  250. @type _raiseSynchronously: C{bool}
  251. @since: 10.2
  252. """
  253. _raiseSynchronously = False
  254. def __init__(self, endpoint, factory):
  255. self.endpoint = endpoint
  256. self.factory = factory
  257. self._waitingForPort = None
  258. def privilegedStartService(self):
  259. """
  260. Start listening on the endpoint.
  261. """
  262. service.Service.privilegedStartService(self)
  263. self._waitingForPort = self.endpoint.listen(self.factory)
  264. raisedNow = []
  265. def handleIt(err):
  266. if self._raiseSynchronously:
  267. raisedNow.append(err)
  268. elif not err.check(CancelledError):
  269. log.err(err)
  270. self._waitingForPort.addErrback(handleIt)
  271. if raisedNow:
  272. raisedNow[0].raiseException()
  273. self._raiseSynchronously = False
  274. def startService(self):
  275. """
  276. Start listening on the endpoint, unless L{privilegedStartService} got
  277. around to it already.
  278. """
  279. service.Service.startService(self)
  280. if self._waitingForPort is None:
  281. self.privilegedStartService()
  282. def stopService(self):
  283. """
  284. Stop listening on the port if it is already listening, otherwise,
  285. cancel the attempt to listen.
  286. @return: a L{Deferred<twisted.internet.defer.Deferred>} which fires
  287. with L{None} when the port has stopped listening.
  288. """
  289. self._waitingForPort.cancel()
  290. def stopIt(port):
  291. if port is not None:
  292. return port.stopListening()
  293. d = self._waitingForPort.addCallback(stopIt)
  294. def stop(passthrough):
  295. self.running = False
  296. return passthrough
  297. d.addBoth(stop)
  298. return d
  299. class _ReconnectingProtocolProxy(object):
  300. """
  301. A proxy for a Protocol to provide connectionLost notification to a client
  302. connection service, in support of reconnecting when connections are lost.
  303. """
  304. def __init__(self, protocol, lostNotification):
  305. """
  306. Create a L{_ReconnectingProtocolProxy}.
  307. @param protocol: the application-provided L{interfaces.IProtocol}
  308. provider.
  309. @type protocol: provider of L{interfaces.IProtocol} which may
  310. additionally provide L{interfaces.IHalfCloseableProtocol} and
  311. L{interfaces.IFileDescriptorReceiver}.
  312. @param lostNotification: a 1-argument callable to invoke with the
  313. C{reason} when the connection is lost.
  314. """
  315. self._protocol = protocol
  316. self._lostNotification = lostNotification
  317. def connectionLost(self, reason):
  318. """
  319. The connection was lost. Relay this information.
  320. @param reason: The reason the connection was lost.
  321. @return: the underlying protocol's result
  322. """
  323. try:
  324. return self._protocol.connectionLost(reason)
  325. finally:
  326. self._lostNotification(reason)
  327. def __getattr__(self, item):
  328. return getattr(self._protocol, item)
  329. def __repr__(self):
  330. return '<%s wrapping %r>' % (
  331. self.__class__.__name__, self._protocol)
  332. class _DisconnectFactory(object):
  333. """
  334. A L{_DisconnectFactory} is a proxy for L{IProtocolFactory} that catches
  335. C{connectionLost} notifications and relays them.
  336. """
  337. def __init__(self, protocolFactory, protocolDisconnected):
  338. self._protocolFactory = protocolFactory
  339. self._protocolDisconnected = protocolDisconnected
  340. def buildProtocol(self, addr):
  341. """
  342. Create a L{_ReconnectingProtocolProxy} with the disconnect-notification
  343. callback we were called with.
  344. @param addr: The address the connection is coming from.
  345. @return: a L{_ReconnectingProtocolProxy} for a protocol produced by
  346. C{self._protocolFactory}
  347. """
  348. return _ReconnectingProtocolProxy(
  349. self._protocolFactory.buildProtocol(addr),
  350. self._protocolDisconnected
  351. )
  352. def __getattr__(self, item):
  353. return getattr(self._protocolFactory, item)
  354. def __repr__(self):
  355. return '<%s wrapping %r>' % (
  356. self.__class__.__name__, self._protocolFactory)
  357. def backoffPolicy(initialDelay=1.0, maxDelay=60.0, factor=1.5,
  358. jitter=_goodEnoughRandom):
  359. """
  360. A timeout policy for L{ClientService} which computes an exponential backoff
  361. interval with configurable parameters.
  362. @since: 16.1.0
  363. @param initialDelay: Delay for the first reconnection attempt (default
  364. 1.0s).
  365. @type initialDelay: L{float}
  366. @param maxDelay: Maximum number of seconds between connection attempts
  367. (default 60 seconds, or one minute). Note that this value is before
  368. jitter is applied, so the actual maximum possible delay is this value
  369. plus the maximum possible result of C{jitter()}.
  370. @type maxDelay: L{float}
  371. @param factor: A multiplicative factor by which the delay grows on each
  372. failed reattempt. Default: 1.5.
  373. @type factor: L{float}
  374. @param jitter: A 0-argument callable that introduces noise into the delay.
  375. By default, C{random.random}, i.e. a pseudorandom floating-point value
  376. between zero and one.
  377. @type jitter: 0-argument callable returning L{float}
  378. @return: a 1-argument callable that, given an attempt count, returns a
  379. floating point number; the number of seconds to delay.
  380. @rtype: see L{ClientService.__init__}'s C{retryPolicy} argument.
  381. """
  382. def policy(attempt):
  383. try:
  384. delay = min(initialDelay * (factor ** min(100, attempt)), maxDelay)
  385. except OverflowError:
  386. delay = maxDelay
  387. return delay + jitter()
  388. return policy
  389. _defaultPolicy = backoffPolicy()
  390. def _firstResult(gen):
  391. """
  392. Return the first element of a generator and exhaust it.
  393. C{MethodicalMachine.upon}'s C{collector} argument takes a generator of
  394. output results. If the generator is exhausted, the later outputs aren't
  395. actually run.
  396. @param gen: Generator to extract values from
  397. @return: The first element of the generator.
  398. """
  399. return list(gen)[0]
  400. class _ClientMachine(object):
  401. """
  402. State machine for maintaining a single outgoing connection to an endpoint.
  403. @see: L{ClientService}
  404. """
  405. _machine = MethodicalMachine()
  406. def __init__(self, endpoint, factory, retryPolicy, clock,
  407. prepareConnection, log):
  408. """
  409. @see: L{ClientService.__init__}
  410. @param log: The logger for the L{ClientService} instance this state
  411. machine is associated to.
  412. @type log: L{Logger}
  413. @ivar _awaitingConnected: notifications to make when connection
  414. succeeds, fails, or is cancelled
  415. @type _awaitingConnected: list of (Deferred, count) tuples
  416. """
  417. self._endpoint = endpoint
  418. self._failedAttempts = 0
  419. self._stopped = False
  420. self._factory = factory
  421. self._timeoutForAttempt = retryPolicy
  422. self._clock = clock
  423. self._prepareConnection = prepareConnection
  424. self._connectionInProgress = succeed(None)
  425. self._awaitingConnected = []
  426. self._stopWaiters = []
  427. self._log = log
  428. @_machine.state(initial=True)
  429. def _init(self):
  430. """
  431. The service has not been started.
  432. """
  433. @_machine.state()
  434. def _connecting(self):
  435. """
  436. The service has started connecting.
  437. """
  438. @_machine.state()
  439. def _waiting(self):
  440. """
  441. The service is waiting for the reconnection period
  442. before reconnecting.
  443. """
  444. @_machine.state()
  445. def _connected(self):
  446. """
  447. The service is connected.
  448. """
  449. @_machine.state()
  450. def _disconnecting(self):
  451. """
  452. The service is disconnecting after being asked to shutdown.
  453. """
  454. @_machine.state()
  455. def _restarting(self):
  456. """
  457. The service is disconnecting and has been asked to restart.
  458. """
  459. @_machine.state()
  460. def _stopped(self):
  461. """
  462. The service has been stopped and is disconnected.
  463. """
  464. @_machine.input()
  465. def start(self):
  466. """
  467. Start this L{ClientService}, initiating the connection retry loop.
  468. """
  469. @_machine.output()
  470. def _connect(self):
  471. """
  472. Start a connection attempt.
  473. """
  474. factoryProxy = _DisconnectFactory(self._factory,
  475. lambda _: self._clientDisconnected())
  476. self._connectionInProgress = (
  477. self._endpoint.connect(factoryProxy)
  478. .addCallback(self._runPrepareConnection)
  479. .addCallback(self._connectionMade)
  480. .addErrback(self._connectionFailed))
  481. def _runPrepareConnection(self, protocol):
  482. """
  483. Run any C{prepareConnection} callback with the connected protocol,
  484. ignoring its return value but propagating any failure.
  485. @param protocol: The protocol of the connection.
  486. @type protocol: L{IProtocol}
  487. @return: Either:
  488. - A L{Deferred} that succeeds with the protocol when the
  489. C{prepareConnection} callback has executed successfully.
  490. - A L{Deferred} that fails when the C{prepareConnection} callback
  491. throws or returns a failed L{Deferred}.
  492. - The protocol, when no C{prepareConnection} callback is defined.
  493. """
  494. if self._prepareConnection:
  495. return (maybeDeferred(self._prepareConnection, protocol)
  496. .addCallback(lambda _: protocol))
  497. return protocol
  498. @_machine.output()
  499. def _resetFailedAttempts(self):
  500. """
  501. Reset the number of failed attempts.
  502. """
  503. self._failedAttempts = 0
  504. @_machine.input()
  505. def stop(self):
  506. """
  507. Stop trying to connect and disconnect any current connection.
  508. @return: a L{Deferred} that fires when all outstanding connections are
  509. closed and all in-progress connection attempts halted.
  510. """
  511. @_machine.output()
  512. def _waitForStop(self):
  513. """
  514. Return a deferred that will fire when the service has finished
  515. disconnecting.
  516. @return: L{Deferred} that fires when the service has finished
  517. disconnecting.
  518. """
  519. self._stopWaiters.append(Deferred())
  520. return self._stopWaiters[-1]
  521. @_machine.output()
  522. def _stopConnecting(self):
  523. """
  524. Stop pending connection attempt.
  525. """
  526. self._connectionInProgress.cancel()
  527. @_machine.output()
  528. def _stopRetrying(self):
  529. """
  530. Stop pending attempt to reconnect.
  531. """
  532. self._retryCall.cancel()
  533. del self._retryCall
  534. @_machine.output()
  535. def _disconnect(self):
  536. """
  537. Disconnect the current connection.
  538. """
  539. self._currentConnection.transport.loseConnection()
  540. @_machine.input()
  541. def _connectionMade(self, protocol):
  542. """
  543. A connection has been made.
  544. @param protocol: The protocol of the connection.
  545. @type protocol: L{IProtocol}
  546. """
  547. @_machine.output()
  548. def _notifyWaiters(self, protocol):
  549. """
  550. Notify all pending requests for a connection that a connection has been
  551. made.
  552. @param protocol: The protocol of the connection.
  553. @type protocol: L{IProtocol}
  554. """
  555. # This should be in _resetFailedAttempts but the signature doesn't
  556. # match.
  557. self._failedAttempts = 0
  558. self._currentConnection = protocol._protocol
  559. self._unawait(self._currentConnection)
  560. @_machine.input()
  561. def _connectionFailed(self, f):
  562. """
  563. The current connection attempt failed.
  564. """
  565. @_machine.output()
  566. def _wait(self):
  567. """
  568. Schedule a retry attempt.
  569. """
  570. self._doWait()
  571. @_machine.output()
  572. def _ignoreAndWait(self, f):
  573. """
  574. Schedule a retry attempt, and ignore the Failure passed in.
  575. """
  576. return self._doWait()
  577. def _doWait(self):
  578. self._failedAttempts += 1
  579. delay = self._timeoutForAttempt(self._failedAttempts)
  580. self._log.info("Scheduling retry {attempt} to connect {endpoint} "
  581. "in {delay} seconds.", attempt=self._failedAttempts,
  582. endpoint=self._endpoint, delay=delay)
  583. self._retryCall = self._clock.callLater(delay, self._reconnect)
  584. @_machine.input()
  585. def _reconnect(self):
  586. """
  587. The wait between connection attempts is done.
  588. """
  589. @_machine.input()
  590. def _clientDisconnected(self):
  591. """
  592. The current connection has been disconnected.
  593. """
  594. @_machine.output()
  595. def _forgetConnection(self):
  596. """
  597. Forget the current connection.
  598. """
  599. del self._currentConnection
  600. @_machine.output()
  601. def _cancelConnectWaiters(self):
  602. """
  603. Notify all pending requests for a connection that no more connections
  604. are expected.
  605. """
  606. self._unawait(Failure(CancelledError()))
  607. @_machine.output()
  608. def _ignoreAndCancelConnectWaiters(self, f):
  609. """
  610. Notify all pending requests for a connection that no more connections
  611. are expected, after ignoring the Failure passed in.
  612. """
  613. self._unawait(Failure(CancelledError()))
  614. @_machine.output()
  615. def _finishStopping(self):
  616. """
  617. Notify all deferreds waiting on the service stopping.
  618. """
  619. self._doFinishStopping()
  620. @_machine.output()
  621. def _ignoreAndFinishStopping(self, f):
  622. """
  623. Notify all deferreds waiting on the service stopping, and ignore the
  624. Failure passed in.
  625. """
  626. self._doFinishStopping()
  627. def _doFinishStopping(self):
  628. self._stopWaiters, waiting = [], self._stopWaiters
  629. for w in waiting:
  630. w.callback(None)
  631. @_machine.input()
  632. def whenConnected(self, failAfterFailures=None):
  633. """
  634. Retrieve the currently-connected L{Protocol}, or the next one to
  635. connect.
  636. @param failAfterFailures: number of connection failures after which
  637. the Deferred will deliver a Failure (None means the Deferred will
  638. only fail if/when the service is stopped). Set this to 1 to make
  639. the very first connection failure signal an error. Use 2 to
  640. allow one failure but signal an error if the subsequent retry
  641. then fails.
  642. @type failAfterFailures: L{int} or None
  643. @return: a Deferred that fires with a protocol produced by the
  644. factory passed to C{__init__}
  645. @rtype: L{Deferred} that may:
  646. - fire with L{IProtocol}
  647. - fail with L{CancelledError} when the service is stopped
  648. - fail with e.g.
  649. L{DNSLookupError<twisted.internet.error.DNSLookupError>} or
  650. L{ConnectionRefusedError<twisted.internet.error.ConnectionRefusedError>}
  651. when the number of consecutive failed connection attempts
  652. equals the value of "failAfterFailures"
  653. """
  654. @_machine.output()
  655. def _currentConnection(self, failAfterFailures=None):
  656. """
  657. Return the currently connected protocol.
  658. @return: L{Deferred} that is fired with currently connected protocol.
  659. """
  660. return succeed(self._currentConnection)
  661. @_machine.output()
  662. def _noConnection(self, failAfterFailures=None):
  663. """
  664. Notify the caller that no connection is expected.
  665. @return: L{Deferred} that is fired with L{CancelledError}.
  666. """
  667. return fail(CancelledError())
  668. @_machine.output()
  669. def _awaitingConnection(self, failAfterFailures=None):
  670. """
  671. Return a deferred that will fire with the next connected protocol.
  672. @return: L{Deferred} that will fire with the next connected protocol.
  673. """
  674. result = Deferred()
  675. self._awaitingConnected.append((result, failAfterFailures))
  676. return result
  677. @_machine.output()
  678. def _deferredSucceededWithNone(self):
  679. """
  680. Return a deferred that has already fired with L{None}.
  681. @return: A L{Deferred} that has already fired with L{None}.
  682. """
  683. return succeed(None)
  684. def _unawait(self, value):
  685. """
  686. Fire all outstanding L{ClientService.whenConnected} L{Deferred}s.
  687. @param value: the value to fire the L{Deferred}s with.
  688. """
  689. self._awaitingConnected, waiting = [], self._awaitingConnected
  690. for (w, remaining) in waiting:
  691. w.callback(value)
  692. @_machine.output()
  693. def _deliverConnectionFailure(self, f):
  694. """
  695. Deliver connection failures to any L{ClientService.whenConnected}
  696. L{Deferred}s that have met their failAfterFailures threshold.
  697. @param f: the Failure to fire the L{Deferred}s with.
  698. """
  699. ready = []
  700. notReady = []
  701. for (w, remaining) in self._awaitingConnected:
  702. if remaining is None:
  703. notReady.append((w, remaining))
  704. elif remaining <= 1:
  705. ready.append(w)
  706. else:
  707. notReady.append((w, remaining-1))
  708. self._awaitingConnected = notReady
  709. for w in ready:
  710. w.callback(f)
  711. # State Transitions
  712. _init.upon(start, enter=_connecting,
  713. outputs=[_connect])
  714. _init.upon(stop, enter=_stopped,
  715. outputs=[_deferredSucceededWithNone],
  716. collector=_firstResult)
  717. _connecting.upon(start, enter=_connecting, outputs=[])
  718. # Note that this synchonously triggers _connectionFailed in the
  719. # _disconnecting state.
  720. _connecting.upon(stop, enter=_disconnecting,
  721. outputs=[_waitForStop, _stopConnecting],
  722. collector=_firstResult)
  723. _connecting.upon(_connectionMade, enter=_connected,
  724. outputs=[_notifyWaiters])
  725. _connecting.upon(_connectionFailed, enter=_waiting,
  726. outputs=[_ignoreAndWait, _deliverConnectionFailure])
  727. _waiting.upon(start, enter=_waiting,
  728. outputs=[])
  729. _waiting.upon(stop, enter=_stopped,
  730. outputs=[_waitForStop,
  731. _cancelConnectWaiters,
  732. _stopRetrying,
  733. _finishStopping],
  734. collector=_firstResult)
  735. _waiting.upon(_reconnect, enter=_connecting,
  736. outputs=[_connect])
  737. _connected.upon(start, enter=_connected,
  738. outputs=[])
  739. _connected.upon(stop, enter=_disconnecting,
  740. outputs=[_waitForStop, _disconnect],
  741. collector=_firstResult)
  742. _connected.upon(_clientDisconnected, enter=_waiting,
  743. outputs=[_forgetConnection, _wait])
  744. _disconnecting.upon(start, enter=_restarting,
  745. outputs=[_resetFailedAttempts])
  746. _disconnecting.upon(stop, enter=_disconnecting,
  747. outputs=[_waitForStop],
  748. collector=_firstResult)
  749. _disconnecting.upon(_clientDisconnected, enter=_stopped,
  750. outputs=[_cancelConnectWaiters,
  751. _finishStopping,
  752. _forgetConnection])
  753. # Note that this is triggered synchonously with the transition from
  754. # _connecting
  755. _disconnecting.upon(_connectionFailed, enter=_stopped,
  756. outputs=[_ignoreAndCancelConnectWaiters,
  757. _ignoreAndFinishStopping])
  758. _restarting.upon(start, enter=_restarting,
  759. outputs=[])
  760. _restarting.upon(stop, enter=_disconnecting,
  761. outputs=[_waitForStop],
  762. collector=_firstResult)
  763. _restarting.upon(_clientDisconnected, enter=_connecting,
  764. outputs=[_finishStopping, _connect])
  765. _stopped.upon(start, enter=_connecting,
  766. outputs=[_connect])
  767. _stopped.upon(stop, enter=_stopped,
  768. outputs=[_deferredSucceededWithNone],
  769. collector=_firstResult)
  770. _init.upon(whenConnected, enter=_init,
  771. outputs=[_awaitingConnection],
  772. collector=_firstResult)
  773. _connecting.upon(whenConnected, enter=_connecting,
  774. outputs=[_awaitingConnection],
  775. collector=_firstResult)
  776. _waiting.upon(whenConnected, enter=_waiting,
  777. outputs=[_awaitingConnection],
  778. collector=_firstResult)
  779. _connected.upon(whenConnected, enter=_connected,
  780. outputs=[_currentConnection],
  781. collector=_firstResult)
  782. _disconnecting.upon(whenConnected, enter=_disconnecting,
  783. outputs=[_awaitingConnection],
  784. collector=_firstResult)
  785. _restarting.upon(whenConnected, enter=_restarting,
  786. outputs=[_awaitingConnection],
  787. collector=_firstResult)
  788. _stopped.upon(whenConnected, enter=_stopped,
  789. outputs=[_noConnection],
  790. collector=_firstResult)
  791. class ClientService(service.Service, object):
  792. """
  793. A L{ClientService} maintains a single outgoing connection to a client
  794. endpoint, reconnecting after a configurable timeout when a connection
  795. fails, either before or after connecting.
  796. @since: 16.1.0
  797. """
  798. _log = Logger()
  799. def __init__(self, endpoint, factory, retryPolicy=None, clock=None,
  800. prepareConnection=None):
  801. """
  802. @param endpoint: A L{stream client endpoint
  803. <interfaces.IStreamClientEndpoint>} provider which will be used to
  804. connect when the service starts.
  805. @param factory: A L{protocol factory <interfaces.IProtocolFactory>}
  806. which will be used to create clients for the endpoint.
  807. @param retryPolicy: A policy configuring how long L{ClientService} will
  808. wait between attempts to connect to C{endpoint}.
  809. @type retryPolicy: callable taking (the number of failed connection
  810. attempts made in a row (L{int})) and returning the number of
  811. seconds to wait before making another attempt.
  812. @param clock: The clock used to schedule reconnection. It's mainly
  813. useful to be parametrized in tests. If the factory is serialized,
  814. this attribute will not be serialized, and the default value (the
  815. reactor) will be restored when deserialized.
  816. @type clock: L{IReactorTime}
  817. @param prepareConnection: A single argument L{callable} that may return
  818. a L{Deferred}. It will be called once with the L{protocol
  819. <interfaces.IProtocol>} each time a new connection is made. It may
  820. call methods on the protocol to prepare it for use (e.g.
  821. authenticate) or validate it (check its health).
  822. The C{prepareConnection} callable may raise an exception or return
  823. a L{Deferred} which fails to reject the connection. A rejected
  824. connection is not used to fire an L{Deferred} returned by
  825. L{whenConnected}. Instead, L{ClientService} handles the failure
  826. and continues as if the connection attempt were a failure
  827. (incrementing the counter passed to C{retryPolicy}).
  828. L{Deferred}s returned by L{whenConnected} will not fire until
  829. any L{Deferred} returned by the C{prepareConnection} callable
  830. fire. Otherwise its successful return value is consumed, but
  831. ignored.
  832. Present Since Twisted 18.7.0
  833. @type prepareConnection: L{callable}
  834. """
  835. clock = _maybeGlobalReactor(clock)
  836. retryPolicy = _defaultPolicy if retryPolicy is None else retryPolicy
  837. self._machine = _ClientMachine(
  838. endpoint, factory, retryPolicy, clock,
  839. prepareConnection=prepareConnection, log=self._log,
  840. )
  841. def whenConnected(self, failAfterFailures=None):
  842. """
  843. Retrieve the currently-connected L{Protocol}, or the next one to
  844. connect.
  845. @param failAfterFailures: number of connection failures after which
  846. the Deferred will deliver a Failure (None means the Deferred will
  847. only fail if/when the service is stopped). Set this to 1 to make
  848. the very first connection failure signal an error. Use 2 to
  849. allow one failure but signal an error if the subsequent retry
  850. then fails.
  851. @type failAfterFailures: L{int} or None
  852. @return: a Deferred that fires with a protocol produced by the
  853. factory passed to C{__init__}
  854. @rtype: L{Deferred} that may:
  855. - fire with L{IProtocol}
  856. - fail with L{CancelledError} when the service is stopped
  857. - fail with e.g.
  858. L{DNSLookupError<twisted.internet.error.DNSLookupError>} or
  859. L{ConnectionRefusedError<twisted.internet.error.ConnectionRefusedError>}
  860. when the number of consecutive failed connection attempts
  861. equals the value of "failAfterFailures"
  862. """
  863. return self._machine.whenConnected(failAfterFailures)
  864. def startService(self):
  865. """
  866. Start this L{ClientService}, initiating the connection retry loop.
  867. """
  868. if self.running:
  869. self._log.warn("Duplicate ClientService.startService {log_source}")
  870. return
  871. super(ClientService, self).startService()
  872. self._machine.start()
  873. def stopService(self):
  874. """
  875. Stop attempting to reconnect and close any existing connections.
  876. @return: a L{Deferred} that fires when all outstanding connections are
  877. closed and all in-progress connection attempts halted.
  878. """
  879. super(ClientService, self).stopService()
  880. return self._machine.stop()
  881. __all__ = (['TimerService', 'CooperatorService', 'MulticastServer',
  882. 'StreamServerEndpointService', 'UDPServer',
  883. 'ClientService'] +
  884. [tran + side
  885. for tran in 'TCP UNIX SSL UNIXDatagram'.split()
  886. for side in 'Server Client'.split()])