protocol.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. # -*- test-case-name: twisted.test.test_factories,twisted.internet.test.test_protocol -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Standard implementations of Twisted protocol-related interfaces.
  6. Start here if you are looking to write a new protocol implementation for
  7. Twisted. The Protocol class contains some introductory material.
  8. """
  9. from __future__ import division, absolute_import
  10. import random
  11. from zope.interface import implementer
  12. from twisted.python import log, failure, components
  13. from twisted.internet import interfaces, error, defer
  14. from twisted.logger import _loggerFor
  15. from twisted.python._oldstyle import _oldStyle
  16. @implementer(interfaces.IProtocolFactory, interfaces.ILoggingContext)
  17. @_oldStyle
  18. class Factory:
  19. """
  20. This is a factory which produces protocols.
  21. By default, buildProtocol will create a protocol of the class given in
  22. self.protocol.
  23. """
  24. # Put a subclass of Protocol here:
  25. protocol = None
  26. numPorts = 0
  27. noisy = True
  28. @classmethod
  29. def forProtocol(cls, protocol, *args, **kwargs):
  30. """
  31. Create a factory for the given protocol.
  32. It sets the C{protocol} attribute and returns the constructed factory
  33. instance.
  34. @param protocol: A L{Protocol} subclass
  35. @param args: Positional arguments for the factory.
  36. @param kwargs: Keyword arguments for the factory.
  37. @return: A L{Factory} instance wired up to C{protocol}.
  38. """
  39. factory = cls(*args, **kwargs)
  40. factory.protocol = protocol
  41. return factory
  42. def logPrefix(self):
  43. """
  44. Describe this factory for log messages.
  45. """
  46. return self.__class__.__name__
  47. def doStart(self):
  48. """
  49. Make sure startFactory is called.
  50. Users should not call this function themselves!
  51. """
  52. if not self.numPorts:
  53. if self.noisy:
  54. _loggerFor(self).info("Starting factory {factory!r}",
  55. factory=self)
  56. self.startFactory()
  57. self.numPorts = self.numPorts + 1
  58. def doStop(self):
  59. """
  60. Make sure stopFactory is called.
  61. Users should not call this function themselves!
  62. """
  63. if self.numPorts == 0:
  64. # This shouldn't happen, but does sometimes and this is better
  65. # than blowing up in assert as we did previously.
  66. return
  67. self.numPorts = self.numPorts - 1
  68. if not self.numPorts:
  69. if self.noisy:
  70. _loggerFor(self).info("Stopping factory {factory!r}",
  71. factory=self)
  72. self.stopFactory()
  73. def startFactory(self):
  74. """
  75. This will be called before I begin listening on a Port or Connector.
  76. It will only be called once, even if the factory is connected
  77. to multiple ports.
  78. This can be used to perform 'unserialization' tasks that
  79. are best put off until things are actually running, such
  80. as connecting to a database, opening files, etcetera.
  81. """
  82. def stopFactory(self):
  83. """
  84. This will be called before I stop listening on all Ports/Connectors.
  85. This can be overridden to perform 'shutdown' tasks such as disconnecting
  86. database connections, closing files, etc.
  87. It will be called, for example, before an application shuts down,
  88. if it was connected to a port. User code should not call this function
  89. directly.
  90. """
  91. def buildProtocol(self, addr):
  92. """
  93. Create an instance of a subclass of Protocol.
  94. The returned instance will handle input on an incoming server
  95. connection, and an attribute "factory" pointing to the creating
  96. factory.
  97. Alternatively, L{None} may be returned to immediately close the
  98. new connection.
  99. Override this method to alter how Protocol instances get created.
  100. @param addr: an object implementing L{twisted.internet.interfaces.IAddress}
  101. """
  102. p = self.protocol()
  103. p.factory = self
  104. return p
  105. class ClientFactory(Factory):
  106. """
  107. A Protocol factory for clients.
  108. This can be used together with the various connectXXX methods in
  109. reactors.
  110. """
  111. def startedConnecting(self, connector):
  112. """
  113. Called when a connection has been started.
  114. You can call connector.stopConnecting() to stop the connection attempt.
  115. @param connector: a Connector object.
  116. """
  117. def clientConnectionFailed(self, connector, reason):
  118. """
  119. Called when a connection has failed to connect.
  120. It may be useful to call connector.connect() - this will reconnect.
  121. @type reason: L{twisted.python.failure.Failure}
  122. """
  123. def clientConnectionLost(self, connector, reason):
  124. """
  125. Called when an established connection is lost.
  126. It may be useful to call connector.connect() - this will reconnect.
  127. @type reason: L{twisted.python.failure.Failure}
  128. """
  129. class _InstanceFactory(ClientFactory):
  130. """
  131. Factory used by ClientCreator.
  132. @ivar deferred: The L{Deferred} which represents this connection attempt and
  133. which will be fired when it succeeds or fails.
  134. @ivar pending: After a connection attempt succeeds or fails, a delayed call
  135. which will fire the L{Deferred} representing this connection attempt.
  136. """
  137. noisy = False
  138. pending = None
  139. def __init__(self, reactor, instance, deferred):
  140. self.reactor = reactor
  141. self.instance = instance
  142. self.deferred = deferred
  143. def __repr__(self):
  144. return "<ClientCreator factory: %r>" % (self.instance, )
  145. def buildProtocol(self, addr):
  146. """
  147. Return the pre-constructed protocol instance and arrange to fire the
  148. waiting L{Deferred} to indicate success establishing the connection.
  149. """
  150. self.pending = self.reactor.callLater(
  151. 0, self.fire, self.deferred.callback, self.instance)
  152. self.deferred = None
  153. return self.instance
  154. def clientConnectionFailed(self, connector, reason):
  155. """
  156. Arrange to fire the waiting L{Deferred} with the given failure to
  157. indicate the connection could not be established.
  158. """
  159. self.pending = self.reactor.callLater(
  160. 0, self.fire, self.deferred.errback, reason)
  161. self.deferred = None
  162. def fire(self, func, value):
  163. """
  164. Clear C{self.pending} to avoid a reference cycle and then invoke func
  165. with the value.
  166. """
  167. self.pending = None
  168. func(value)
  169. @_oldStyle
  170. class ClientCreator:
  171. """
  172. Client connections that do not require a factory.
  173. The various connect* methods create a protocol instance using the given
  174. protocol class and arguments, and connect it, returning a Deferred of the
  175. resulting protocol instance.
  176. Useful for cases when we don't really need a factory. Mainly this
  177. is when there is no shared state between protocol instances, and no need
  178. to reconnect.
  179. The C{connectTCP}, C{connectUNIX}, and C{connectSSL} methods each return a
  180. L{Deferred} which will fire with an instance of the protocol class passed to
  181. L{ClientCreator.__init__}. These Deferred can be cancelled to abort the
  182. connection attempt (in a very unlikely case, cancelling the Deferred may not
  183. prevent the protocol from being instantiated and connected to a transport;
  184. if this happens, it will be disconnected immediately afterwards and the
  185. Deferred will still errback with L{CancelledError}).
  186. """
  187. def __init__(self, reactor, protocolClass, *args, **kwargs):
  188. self.reactor = reactor
  189. self.protocolClass = protocolClass
  190. self.args = args
  191. self.kwargs = kwargs
  192. def _connect(self, method, *args, **kwargs):
  193. """
  194. Initiate a connection attempt.
  195. @param method: A callable which will actually start the connection
  196. attempt. For example, C{reactor.connectTCP}.
  197. @param *args: Positional arguments to pass to C{method}, excluding the
  198. factory.
  199. @param **kwargs: Keyword arguments to pass to C{method}.
  200. @return: A L{Deferred} which fires with an instance of the protocol
  201. class passed to this L{ClientCreator}'s initializer or fails if the
  202. connection cannot be set up for some reason.
  203. """
  204. def cancelConnect(deferred):
  205. connector.disconnect()
  206. if f.pending is not None:
  207. f.pending.cancel()
  208. d = defer.Deferred(cancelConnect)
  209. f = _InstanceFactory(
  210. self.reactor, self.protocolClass(*self.args, **self.kwargs), d)
  211. connector = method(factory=f, *args, **kwargs)
  212. return d
  213. def connectTCP(self, host, port, timeout=30, bindAddress=None):
  214. """
  215. Connect to a TCP server.
  216. The parameters are all the same as to L{IReactorTCP.connectTCP} except
  217. that the factory parameter is omitted.
  218. @return: A L{Deferred} which fires with an instance of the protocol
  219. class passed to this L{ClientCreator}'s initializer or fails if the
  220. connection cannot be set up for some reason.
  221. """
  222. return self._connect(
  223. self.reactor.connectTCP, host, port, timeout=timeout,
  224. bindAddress=bindAddress)
  225. def connectUNIX(self, address, timeout=30, checkPID=False):
  226. """
  227. Connect to a Unix socket.
  228. The parameters are all the same as to L{IReactorUNIX.connectUNIX} except
  229. that the factory parameter is omitted.
  230. @return: A L{Deferred} which fires with an instance of the protocol
  231. class passed to this L{ClientCreator}'s initializer or fails if the
  232. connection cannot be set up for some reason.
  233. """
  234. return self._connect(
  235. self.reactor.connectUNIX, address, timeout=timeout,
  236. checkPID=checkPID)
  237. def connectSSL(self, host, port, contextFactory, timeout=30, bindAddress=None):
  238. """
  239. Connect to an SSL server.
  240. The parameters are all the same as to L{IReactorSSL.connectSSL} except
  241. that the factory parameter is omitted.
  242. @return: A L{Deferred} which fires with an instance of the protocol
  243. class passed to this L{ClientCreator}'s initializer or fails if the
  244. connection cannot be set up for some reason.
  245. """
  246. return self._connect(
  247. self.reactor.connectSSL, host, port,
  248. contextFactory=contextFactory, timeout=timeout,
  249. bindAddress=bindAddress)
  250. class ReconnectingClientFactory(ClientFactory):
  251. """
  252. Factory which auto-reconnects clients with an exponential back-off.
  253. Note that clients should call my resetDelay method after they have
  254. connected successfully.
  255. @ivar maxDelay: Maximum number of seconds between connection attempts.
  256. @ivar initialDelay: Delay for the first reconnection attempt.
  257. @ivar factor: A multiplicitive factor by which the delay grows
  258. @ivar jitter: Percentage of randomness to introduce into the delay length
  259. to prevent stampeding.
  260. @ivar clock: The clock used to schedule reconnection. It's mainly useful to
  261. be parametrized in tests. If the factory is serialized, this attribute
  262. will not be serialized, and the default value (the reactor) will be
  263. restored when deserialized.
  264. @type clock: L{IReactorTime}
  265. @ivar maxRetries: Maximum number of consecutive unsuccessful connection
  266. attempts, after which no further connection attempts will be made. If
  267. this is not explicitly set, no maximum is applied.
  268. """
  269. maxDelay = 3600
  270. initialDelay = 1.0
  271. # Note: These highly sensitive factors have been precisely measured by
  272. # the National Institute of Science and Technology. Take extreme care
  273. # in altering them, or you may damage your Internet!
  274. # (Seriously: <http://physics.nist.gov/cuu/Constants/index.html>)
  275. factor = 2.7182818284590451 # (math.e)
  276. # Phi = 1.6180339887498948 # (Phi is acceptable for use as a
  277. # factor if e is too large for your application.)
  278. # This is the value of the molar Planck constant times c, joule
  279. # meter/mole. The value is attributable to
  280. # https://physics.nist.gov/cgi-bin/cuu/Value?nahc|search_for=molar+planck+constant+times+c
  281. jitter = 0.119626565582
  282. delay = initialDelay
  283. retries = 0
  284. maxRetries = None
  285. _callID = None
  286. connector = None
  287. clock = None
  288. continueTrying = 1
  289. def clientConnectionFailed(self, connector, reason):
  290. if self.continueTrying:
  291. self.connector = connector
  292. self.retry()
  293. def clientConnectionLost(self, connector, unused_reason):
  294. if self.continueTrying:
  295. self.connector = connector
  296. self.retry()
  297. def retry(self, connector=None):
  298. """
  299. Have this connector connect again, after a suitable delay.
  300. """
  301. if not self.continueTrying:
  302. if self.noisy:
  303. log.msg("Abandoning %s on explicit request" % (connector,))
  304. return
  305. if connector is None:
  306. if self.connector is None:
  307. raise ValueError("no connector to retry")
  308. else:
  309. connector = self.connector
  310. self.retries += 1
  311. if self.maxRetries is not None and (self.retries > self.maxRetries):
  312. if self.noisy:
  313. log.msg("Abandoning %s after %d retries." %
  314. (connector, self.retries))
  315. return
  316. self.delay = min(self.delay * self.factor, self.maxDelay)
  317. if self.jitter:
  318. self.delay = random.normalvariate(self.delay,
  319. self.delay * self.jitter)
  320. if self.noisy:
  321. log.msg("%s will retry in %d seconds" % (connector, self.delay,))
  322. def reconnector():
  323. self._callID = None
  324. connector.connect()
  325. if self.clock is None:
  326. from twisted.internet import reactor
  327. self.clock = reactor
  328. self._callID = self.clock.callLater(self.delay, reconnector)
  329. def stopTrying(self):
  330. """
  331. Put a stop to any attempt to reconnect in progress.
  332. """
  333. # ??? Is this function really stopFactory?
  334. if self._callID:
  335. self._callID.cancel()
  336. self._callID = None
  337. self.continueTrying = 0
  338. if self.connector:
  339. try:
  340. self.connector.stopConnecting()
  341. except error.NotConnectingError:
  342. pass
  343. def resetDelay(self):
  344. """
  345. Call this method after a successful connection: it resets the delay and
  346. the retry counter.
  347. """
  348. self.delay = self.initialDelay
  349. self.retries = 0
  350. self._callID = None
  351. self.continueTrying = 1
  352. def __getstate__(self):
  353. """
  354. Remove all of the state which is mutated by connection attempts and
  355. failures, returning just the state which describes how reconnections
  356. should be attempted. This will make the unserialized instance
  357. behave just as this one did when it was first instantiated.
  358. """
  359. state = self.__dict__.copy()
  360. for key in ['connector', 'retries', 'delay',
  361. 'continueTrying', '_callID', 'clock']:
  362. if key in state:
  363. del state[key]
  364. return state
  365. class ServerFactory(Factory):
  366. """
  367. Subclass this to indicate that your protocol.Factory is only usable for servers.
  368. """
  369. @_oldStyle
  370. class BaseProtocol:
  371. """
  372. This is the abstract superclass of all protocols.
  373. Some methods have helpful default implementations here so that they can
  374. easily be shared, but otherwise the direct subclasses of this class are more
  375. interesting, L{Protocol} and L{ProcessProtocol}.
  376. """
  377. connected = 0
  378. transport = None
  379. def makeConnection(self, transport):
  380. """
  381. Make a connection to a transport and a server.
  382. This sets the 'transport' attribute of this Protocol, and calls the
  383. connectionMade() callback.
  384. """
  385. self.connected = 1
  386. self.transport = transport
  387. self.connectionMade()
  388. def connectionMade(self):
  389. """
  390. Called when a connection is made.
  391. This may be considered the initializer of the protocol, because
  392. it is called when the connection is completed. For clients,
  393. this is called once the connection to the server has been
  394. established; for servers, this is called after an accept() call
  395. stops blocking and a socket has been received. If you need to
  396. send any greeting or initial message, do it here.
  397. """
  398. connectionDone = failure.Failure(error.ConnectionDone())
  399. connectionDone.cleanFailure()
  400. @implementer(interfaces.IProtocol, interfaces.ILoggingContext)
  401. class Protocol(BaseProtocol):
  402. """
  403. This is the base class for streaming connection-oriented protocols.
  404. If you are going to write a new connection-oriented protocol for Twisted,
  405. start here. Any protocol implementation, either client or server, should
  406. be a subclass of this class.
  407. The API is quite simple. Implement L{dataReceived} to handle both
  408. event-based and synchronous input; output can be sent through the
  409. 'transport' attribute, which is to be an instance that implements
  410. L{twisted.internet.interfaces.ITransport}. Override C{connectionLost} to be
  411. notified when the connection ends.
  412. Some subclasses exist already to help you write common types of protocols:
  413. see the L{twisted.protocols.basic} module for a few of them.
  414. """
  415. def logPrefix(self):
  416. """
  417. Return a prefix matching the class name, to identify log messages
  418. related to this protocol instance.
  419. """
  420. return self.__class__.__name__
  421. def dataReceived(self, data):
  422. """
  423. Called whenever data is received.
  424. Use this method to translate to a higher-level message. Usually, some
  425. callback will be made upon the receipt of each complete protocol
  426. message.
  427. @param data: a string of indeterminate length. Please keep in mind
  428. that you will probably need to buffer some data, as partial
  429. (or multiple) protocol messages may be received! I recommend
  430. that unit tests for protocols call through to this method with
  431. differing chunk sizes, down to one byte at a time.
  432. """
  433. def connectionLost(self, reason=connectionDone):
  434. """
  435. Called when the connection is shut down.
  436. Clear any circular references here, and any external references
  437. to this Protocol. The connection has been closed.
  438. @type reason: L{twisted.python.failure.Failure}
  439. """
  440. @implementer(interfaces.IConsumer)
  441. class ProtocolToConsumerAdapter(components.Adapter):
  442. def write(self, data):
  443. self.original.dataReceived(data)
  444. def registerProducer(self, producer, streaming):
  445. pass
  446. def unregisterProducer(self):
  447. pass
  448. components.registerAdapter(ProtocolToConsumerAdapter, interfaces.IProtocol,
  449. interfaces.IConsumer)
  450. @implementer(interfaces.IProtocol)
  451. class ConsumerToProtocolAdapter(components.Adapter):
  452. def dataReceived(self, data):
  453. self.original.write(data)
  454. def connectionLost(self, reason):
  455. pass
  456. def makeConnection(self, transport):
  457. pass
  458. def connectionMade(self):
  459. pass
  460. components.registerAdapter(ConsumerToProtocolAdapter, interfaces.IConsumer,
  461. interfaces.IProtocol)
  462. @implementer(interfaces.IProcessProtocol)
  463. class ProcessProtocol(BaseProtocol):
  464. """
  465. Base process protocol implementation which does simple dispatching for
  466. stdin, stdout, and stderr file descriptors.
  467. """
  468. def childDataReceived(self, childFD, data):
  469. if childFD == 1:
  470. self.outReceived(data)
  471. elif childFD == 2:
  472. self.errReceived(data)
  473. def outReceived(self, data):
  474. """
  475. Some data was received from stdout.
  476. """
  477. def errReceived(self, data):
  478. """
  479. Some data was received from stderr.
  480. """
  481. def childConnectionLost(self, childFD):
  482. if childFD == 0:
  483. self.inConnectionLost()
  484. elif childFD == 1:
  485. self.outConnectionLost()
  486. elif childFD == 2:
  487. self.errConnectionLost()
  488. def inConnectionLost(self):
  489. """
  490. This will be called when stdin is closed.
  491. """
  492. def outConnectionLost(self):
  493. """
  494. This will be called when stdout is closed.
  495. """
  496. def errConnectionLost(self):
  497. """
  498. This will be called when stderr is closed.
  499. """
  500. def processExited(self, reason):
  501. """
  502. This will be called when the subprocess exits.
  503. @type reason: L{twisted.python.failure.Failure}
  504. """
  505. def processEnded(self, reason):
  506. """
  507. Called when the child process exits and all file descriptors
  508. associated with it have been closed.
  509. @type reason: L{twisted.python.failure.Failure}
  510. """
  511. @_oldStyle
  512. class AbstractDatagramProtocol:
  513. """
  514. Abstract protocol for datagram-oriented transports, e.g. IP, ICMP, ARP, UDP.
  515. """
  516. transport = None
  517. numPorts = 0
  518. noisy = True
  519. def __getstate__(self):
  520. d = self.__dict__.copy()
  521. d['transport'] = None
  522. return d
  523. def doStart(self):
  524. """
  525. Make sure startProtocol is called.
  526. This will be called by makeConnection(), users should not call it.
  527. """
  528. if not self.numPorts:
  529. if self.noisy:
  530. log.msg("Starting protocol %s" % self)
  531. self.startProtocol()
  532. self.numPorts = self.numPorts + 1
  533. def doStop(self):
  534. """
  535. Make sure stopProtocol is called.
  536. This will be called by the port, users should not call it.
  537. """
  538. assert self.numPorts > 0
  539. self.numPorts = self.numPorts - 1
  540. self.transport = None
  541. if not self.numPorts:
  542. if self.noisy:
  543. log.msg("Stopping protocol %s" % self)
  544. self.stopProtocol()
  545. def startProtocol(self):
  546. """
  547. Called when a transport is connected to this protocol.
  548. Will only be called once, even if multiple ports are connected.
  549. """
  550. def stopProtocol(self):
  551. """
  552. Called when the transport is disconnected.
  553. Will only be called once, after all ports are disconnected.
  554. """
  555. def makeConnection(self, transport):
  556. """
  557. Make a connection to a transport and a server.
  558. This sets the 'transport' attribute of this DatagramProtocol, and calls the
  559. doStart() callback.
  560. """
  561. assert self.transport == None
  562. self.transport = transport
  563. self.doStart()
  564. def datagramReceived(self, datagram, addr):
  565. """
  566. Called when a datagram is received.
  567. @param datagram: the string received from the transport.
  568. @param addr: tuple of source of datagram.
  569. """
  570. @implementer(interfaces.ILoggingContext)
  571. class DatagramProtocol(AbstractDatagramProtocol):
  572. """
  573. Protocol for datagram-oriented transport, e.g. UDP.
  574. @type transport: L{None} or
  575. L{IUDPTransport<twisted.internet.interfaces.IUDPTransport>} provider
  576. @ivar transport: The transport with which this protocol is associated,
  577. if it is associated with one.
  578. """
  579. def logPrefix(self):
  580. """
  581. Return a prefix matching the class name, to identify log messages
  582. related to this protocol instance.
  583. """
  584. return self.__class__.__name__
  585. def connectionRefused(self):
  586. """
  587. Called due to error from write in connected mode.
  588. Note this is a result of ICMP message generated by *previous*
  589. write.
  590. """
  591. class ConnectedDatagramProtocol(DatagramProtocol):
  592. """
  593. Protocol for connected datagram-oriented transport.
  594. No longer necessary for UDP.
  595. """
  596. def datagramReceived(self, datagram):
  597. """
  598. Called when a datagram is received.
  599. @param datagram: the string received from the transport.
  600. """
  601. def connectionFailed(self, failure):
  602. """
  603. Called if connecting failed.
  604. Usually this will be due to a DNS lookup failure.
  605. """
  606. @implementer(interfaces.ITransport)
  607. @_oldStyle
  608. class FileWrapper:
  609. """
  610. A wrapper around a file-like object to make it behave as a Transport.
  611. This doesn't actually stream the file to the attached protocol,
  612. and is thus useful mainly as a utility for debugging protocols.
  613. """
  614. closed = 0
  615. disconnecting = 0
  616. producer = None
  617. streamingProducer = 0
  618. def __init__(self, file):
  619. self.file = file
  620. def write(self, data):
  621. try:
  622. self.file.write(data)
  623. except:
  624. self.handleException()
  625. def _checkProducer(self):
  626. # Cheating; this is called at "idle" times to allow producers to be
  627. # found and dealt with
  628. if self.producer:
  629. self.producer.resumeProducing()
  630. def registerProducer(self, producer, streaming):
  631. """
  632. From abstract.FileDescriptor
  633. """
  634. self.producer = producer
  635. self.streamingProducer = streaming
  636. if not streaming:
  637. producer.resumeProducing()
  638. def unregisterProducer(self):
  639. self.producer = None
  640. def stopConsuming(self):
  641. self.unregisterProducer()
  642. self.loseConnection()
  643. def writeSequence(self, iovec):
  644. self.write(b"".join(iovec))
  645. def loseConnection(self):
  646. self.closed = 1
  647. try:
  648. self.file.close()
  649. except (IOError, OSError):
  650. self.handleException()
  651. def getPeer(self):
  652. # FIXME: https://twistedmatrix.com/trac/ticket/7820
  653. # According to ITransport, this should return an IAddress!
  654. return 'file', 'file'
  655. def getHost(self):
  656. # FIXME: https://twistedmatrix.com/trac/ticket/7820
  657. # According to ITransport, this should return an IAddress!
  658. return 'file'
  659. def handleException(self):
  660. pass
  661. def resumeProducing(self):
  662. # Never sends data anyways
  663. pass
  664. def pauseProducing(self):
  665. # Never sends data anyways
  666. pass
  667. def stopProducing(self):
  668. self.loseConnection()
  669. __all__ = ["Factory", "ClientFactory", "ReconnectingClientFactory", "connectionDone",
  670. "Protocol", "ProcessProtocol", "FileWrapper", "ServerFactory",
  671. "AbstractDatagramProtocol", "DatagramProtocol", "ConnectedDatagramProtocol",
  672. "ClientCreator"]