Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

abstract.py 19KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. # -*- test-case-name: twisted.test.test_abstract -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Support for generic select()able objects.
  6. """
  7. from socket import AF_INET, AF_INET6, inet_pton
  8. from typing import Iterable, List, Optional
  9. from zope.interface import implementer
  10. from twisted.internet import interfaces, main
  11. from twisted.python import failure, reflect
  12. # Twisted Imports
  13. from twisted.python.compat import lazyByteSlice
  14. def _dataMustBeBytes(obj):
  15. if not isinstance(obj, bytes): # no, really, I mean it
  16. raise TypeError("Data must be bytes")
  17. # Python 3.4+ can join bytes and memoryviews; using a
  18. # memoryview prevents the slice from copying
  19. def _concatenate(bObj, offset, bArray):
  20. return b"".join([memoryview(bObj)[offset:]] + bArray)
  21. class _ConsumerMixin:
  22. """
  23. L{IConsumer} implementations can mix this in to get C{registerProducer} and
  24. C{unregisterProducer} methods which take care of keeping track of a
  25. producer's state.
  26. Subclasses must provide three attributes which L{_ConsumerMixin} will read
  27. but not write:
  28. - connected: A C{bool} which is C{True} as long as the consumer has
  29. someplace to send bytes (for example, a TCP connection), and then
  30. C{False} when it no longer does.
  31. - disconnecting: A C{bool} which is C{False} until something like
  32. L{ITransport.loseConnection} is called, indicating that the send buffer
  33. should be flushed and the connection lost afterwards. Afterwards,
  34. C{True}.
  35. - disconnected: A C{bool} which is C{False} until the consumer no longer
  36. has a place to send bytes, then C{True}.
  37. Subclasses must also override the C{startWriting} method.
  38. @ivar producer: L{None} if no producer is registered, otherwise the
  39. registered producer.
  40. @ivar producerPaused: A flag indicating whether the producer is currently
  41. paused.
  42. @type producerPaused: L{bool}
  43. @ivar streamingProducer: A flag indicating whether the producer was
  44. registered as a streaming (ie push) producer or not (ie a pull
  45. producer). This will determine whether the consumer may ever need to
  46. pause and resume it, or if it can merely call C{resumeProducing} on it
  47. when buffer space is available.
  48. @ivar streamingProducer: C{bool} or C{int}
  49. """
  50. producer = None
  51. producerPaused = False
  52. streamingProducer = False
  53. def startWriting(self):
  54. """
  55. Override in a subclass to cause the reactor to monitor this selectable
  56. for write events. This will be called once in C{unregisterProducer} if
  57. C{loseConnection} has previously been called, so that the connection can
  58. actually close.
  59. """
  60. raise NotImplementedError("%r did not implement startWriting")
  61. def registerProducer(self, producer, streaming):
  62. """
  63. Register to receive data from a producer.
  64. This sets this selectable to be a consumer for a producer. When this
  65. selectable runs out of data on a write() call, it will ask the producer
  66. to resumeProducing(). When the FileDescriptor's internal data buffer is
  67. filled, it will ask the producer to pauseProducing(). If the connection
  68. is lost, FileDescriptor calls producer's stopProducing() method.
  69. If streaming is true, the producer should provide the IPushProducer
  70. interface. Otherwise, it is assumed that producer provides the
  71. IPullProducer interface. In this case, the producer won't be asked to
  72. pauseProducing(), but it has to be careful to write() data only when its
  73. resumeProducing() method is called.
  74. """
  75. if self.producer is not None:
  76. raise RuntimeError(
  77. "Cannot register producer %s, because producer %s was never "
  78. "unregistered." % (producer, self.producer)
  79. )
  80. if self.disconnected:
  81. producer.stopProducing()
  82. else:
  83. self.producer = producer
  84. self.streamingProducer = streaming
  85. if not streaming:
  86. producer.resumeProducing()
  87. def unregisterProducer(self):
  88. """
  89. Stop consuming data from a producer, without disconnecting.
  90. """
  91. self.producer = None
  92. if self.connected and self.disconnecting:
  93. self.startWriting()
  94. @implementer(interfaces.ILoggingContext)
  95. class _LogOwner:
  96. """
  97. Mixin to help implement L{interfaces.ILoggingContext} for transports which
  98. have a protocol, the log prefix of which should also appear in the
  99. transport's log prefix.
  100. """
  101. def _getLogPrefix(self, applicationObject: object) -> str:
  102. """
  103. Determine the log prefix to use for messages related to
  104. C{applicationObject}, which may or may not be an
  105. L{interfaces.ILoggingContext} provider.
  106. @return: A C{str} giving the log prefix to use.
  107. """
  108. if interfaces.ILoggingContext.providedBy(applicationObject):
  109. return applicationObject.logPrefix()
  110. return applicationObject.__class__.__name__
  111. def logPrefix(self):
  112. """
  113. Override this method to insert custom logging behavior. Its
  114. return value will be inserted in front of every line. It may
  115. be called more times than the number of output lines.
  116. """
  117. return "-"
  118. @implementer(
  119. interfaces.IPushProducer,
  120. interfaces.IReadWriteDescriptor,
  121. interfaces.IConsumer,
  122. interfaces.ITransport,
  123. interfaces.IHalfCloseableDescriptor,
  124. )
  125. class FileDescriptor(_ConsumerMixin, _LogOwner):
  126. """
  127. An object which can be operated on by select().
  128. This is an abstract superclass of all objects which may be notified when
  129. they are readable or writable; e.g. they have a file-descriptor that is
  130. valid to be passed to select(2).
  131. """
  132. connected = 0
  133. disconnected = 0
  134. disconnecting = 0
  135. _writeDisconnecting = False
  136. _writeDisconnected = False
  137. dataBuffer = b""
  138. offset = 0
  139. SEND_LIMIT = 128 * 1024
  140. def __init__(self, reactor: Optional[interfaces.IReactorFDSet] = None):
  141. """
  142. @param reactor: An L{IReactorFDSet} provider which this descriptor will
  143. use to get readable and writeable event notifications. If no value
  144. is given, the global reactor will be used.
  145. """
  146. if not reactor:
  147. from twisted.internet import reactor as _reactor
  148. reactor = _reactor # type: ignore[assignment]
  149. self.reactor = reactor
  150. # will be added to dataBuffer in doWrite
  151. self._tempDataBuffer: List[bytes] = []
  152. self._tempDataLen = 0
  153. def connectionLost(self, reason):
  154. """The connection was lost.
  155. This is called when the connection on a selectable object has been
  156. lost. It will be called whether the connection was closed explicitly,
  157. an exception occurred in an event handler, or the other end of the
  158. connection closed it first.
  159. Clean up state here, but make sure to call back up to FileDescriptor.
  160. """
  161. self.disconnected = 1
  162. self.connected = 0
  163. if self.producer is not None:
  164. self.producer.stopProducing()
  165. self.producer = None
  166. self.stopReading()
  167. self.stopWriting()
  168. def writeSomeData(self, data: bytes) -> None:
  169. """
  170. Write as much as possible of the given data, immediately.
  171. This is called to invoke the lower-level writing functionality, such
  172. as a socket's send() method, or a file's write(); this method
  173. returns an integer or an exception. If an integer, it is the number
  174. of bytes written (possibly zero); if an exception, it indicates the
  175. connection was lost.
  176. """
  177. raise NotImplementedError(
  178. "%s does not implement writeSomeData" % reflect.qual(self.__class__)
  179. )
  180. def doRead(self):
  181. """
  182. Called when data is available for reading.
  183. Subclasses must override this method. The result will be interpreted
  184. in the same way as a result of doWrite().
  185. """
  186. raise NotImplementedError(
  187. "%s does not implement doRead" % reflect.qual(self.__class__)
  188. )
  189. def doWrite(self):
  190. """
  191. Called when data can be written.
  192. @return: L{None} on success, an exception or a negative integer on
  193. failure.
  194. @see: L{twisted.internet.interfaces.IWriteDescriptor.doWrite}.
  195. """
  196. if len(self.dataBuffer) - self.offset < self.SEND_LIMIT:
  197. # If there is currently less than SEND_LIMIT bytes left to send
  198. # in the string, extend it with the array data.
  199. self.dataBuffer = _concatenate(
  200. self.dataBuffer, self.offset, self._tempDataBuffer
  201. )
  202. self.offset = 0
  203. self._tempDataBuffer = []
  204. self._tempDataLen = 0
  205. # Send as much data as you can.
  206. if self.offset:
  207. l = self.writeSomeData(lazyByteSlice(self.dataBuffer, self.offset))
  208. else:
  209. l = self.writeSomeData(self.dataBuffer)
  210. # There is no writeSomeData implementation in Twisted which returns
  211. # < 0, but the documentation for writeSomeData used to claim negative
  212. # integers meant connection lost. Keep supporting this here,
  213. # although it may be worth deprecating and removing at some point.
  214. if isinstance(l, Exception) or l < 0:
  215. return l
  216. self.offset += l
  217. # If there is nothing left to send,
  218. if self.offset == len(self.dataBuffer) and not self._tempDataLen:
  219. self.dataBuffer = b""
  220. self.offset = 0
  221. # stop writing.
  222. self.stopWriting()
  223. # If I've got a producer who is supposed to supply me with data,
  224. if self.producer is not None and (
  225. (not self.streamingProducer) or self.producerPaused
  226. ):
  227. # tell them to supply some more.
  228. self.producerPaused = False
  229. self.producer.resumeProducing()
  230. elif self.disconnecting:
  231. # But if I was previously asked to let the connection die, do
  232. # so.
  233. return self._postLoseConnection()
  234. elif self._writeDisconnecting:
  235. # I was previously asked to half-close the connection. We
  236. # set _writeDisconnected before calling handler, in case the
  237. # handler calls loseConnection(), which will want to check for
  238. # this attribute.
  239. self._writeDisconnected = True
  240. result = self._closeWriteConnection()
  241. return result
  242. return None
  243. def _postLoseConnection(self):
  244. """Called after a loseConnection(), when all data has been written.
  245. Whatever this returns is then returned by doWrite.
  246. """
  247. # default implementation, telling reactor we're finished
  248. return main.CONNECTION_DONE
  249. def _closeWriteConnection(self):
  250. # override in subclasses
  251. pass
  252. def writeConnectionLost(self, reason):
  253. # in current code should never be called
  254. self.connectionLost(reason)
  255. def readConnectionLost(self, reason: failure.Failure) -> None:
  256. # override in subclasses
  257. self.connectionLost(reason)
  258. def getHost(self):
  259. # ITransport.getHost
  260. raise NotImplementedError()
  261. def getPeer(self):
  262. # ITransport.getPeer
  263. raise NotImplementedError()
  264. def _isSendBufferFull(self):
  265. """
  266. Determine whether the user-space send buffer for this transport is full
  267. or not.
  268. When the buffer contains more than C{self.bufferSize} bytes, it is
  269. considered full. This might be improved by considering the size of the
  270. kernel send buffer and how much of it is free.
  271. @return: C{True} if it is full, C{False} otherwise.
  272. """
  273. return len(self.dataBuffer) + self._tempDataLen > self.bufferSize
  274. def _maybePauseProducer(self):
  275. """
  276. Possibly pause a producer, if there is one and the send buffer is full.
  277. """
  278. # If we are responsible for pausing our producer,
  279. if self.producer is not None and self.streamingProducer:
  280. # and our buffer is full,
  281. if self._isSendBufferFull():
  282. # pause it.
  283. self.producerPaused = True
  284. self.producer.pauseProducing()
  285. def write(self, data: bytes) -> None:
  286. """Reliably write some data.
  287. The data is buffered until the underlying file descriptor is ready
  288. for writing. If there is more than C{self.bufferSize} data in the
  289. buffer and this descriptor has a registered streaming producer, its
  290. C{pauseProducing()} method will be called.
  291. """
  292. _dataMustBeBytes(data)
  293. if not self.connected or self._writeDisconnected:
  294. return
  295. if data:
  296. self._tempDataBuffer.append(data)
  297. self._tempDataLen += len(data)
  298. self._maybePauseProducer()
  299. self.startWriting()
  300. def writeSequence(self, iovec: Iterable[bytes]) -> None:
  301. """
  302. Reliably write a sequence of data.
  303. Currently, this is a convenience method roughly equivalent to::
  304. for chunk in iovec:
  305. fd.write(chunk)
  306. It may have a more efficient implementation at a later time or in a
  307. different reactor.
  308. As with the C{write()} method, if a buffer size limit is reached and a
  309. streaming producer is registered, it will be paused until the buffered
  310. data is written to the underlying file descriptor.
  311. """
  312. for i in iovec:
  313. _dataMustBeBytes(i)
  314. if not self.connected or not iovec or self._writeDisconnected:
  315. return
  316. self._tempDataBuffer.extend(iovec)
  317. for i in iovec:
  318. self._tempDataLen += len(i)
  319. self._maybePauseProducer()
  320. self.startWriting()
  321. def loseConnection(self):
  322. """Close the connection at the next available opportunity.
  323. Call this to cause this FileDescriptor to lose its connection. It will
  324. first write any data that it has buffered.
  325. If there is data buffered yet to be written, this method will cause the
  326. transport to lose its connection as soon as it's done flushing its
  327. write buffer. If you have a producer registered, the connection won't
  328. be closed until the producer is finished. Therefore, make sure you
  329. unregister your producer when it's finished, or the connection will
  330. never close.
  331. """
  332. if self.connected and not self.disconnecting:
  333. if self._writeDisconnected:
  334. # doWrite won't trigger the connection close anymore
  335. self.stopReading()
  336. self.stopWriting()
  337. self.connectionLost(failure.Failure(main.CONNECTION_DONE))
  338. else:
  339. self.stopReading()
  340. self.startWriting()
  341. self.disconnecting = 1
  342. def loseWriteConnection(self):
  343. self._writeDisconnecting = True
  344. self.startWriting()
  345. def stopReading(self):
  346. """Stop waiting for read availability.
  347. Call this to remove this selectable from being notified when it is
  348. ready for reading.
  349. """
  350. self.reactor.removeReader(self)
  351. def stopWriting(self):
  352. """Stop waiting for write availability.
  353. Call this to remove this selectable from being notified when it is ready
  354. for writing.
  355. """
  356. self.reactor.removeWriter(self)
  357. def startReading(self):
  358. """Start waiting for read availability."""
  359. self.reactor.addReader(self)
  360. def startWriting(self):
  361. """Start waiting for write availability.
  362. Call this to have this FileDescriptor be notified whenever it is ready for
  363. writing.
  364. """
  365. self.reactor.addWriter(self)
  366. # Producer/consumer implementation
  367. # first, the consumer stuff. This requires no additional work, as
  368. # any object you can write to can be a consumer, really.
  369. producer = None
  370. bufferSize = 2 ** 2 ** 2 ** 2
  371. def stopConsuming(self):
  372. """Stop consuming data.
  373. This is called when a producer has lost its connection, to tell the
  374. consumer to go lose its connection (and break potential circular
  375. references).
  376. """
  377. self.unregisterProducer()
  378. self.loseConnection()
  379. # producer interface implementation
  380. def resumeProducing(self):
  381. if self.connected and not self.disconnecting:
  382. self.startReading()
  383. def pauseProducing(self):
  384. self.stopReading()
  385. def stopProducing(self):
  386. self.loseConnection()
  387. def fileno(self):
  388. """File Descriptor number for select().
  389. This method must be overridden or assigned in subclasses to
  390. indicate a valid file descriptor for the operating system.
  391. """
  392. return -1
  393. def isIPAddress(addr: str, family: int = AF_INET) -> bool:
  394. """
  395. Determine whether the given string represents an IP address of the given
  396. family; by default, an IPv4 address.
  397. @param addr: A string which may or may not be the decimal dotted
  398. representation of an IPv4 address.
  399. @param family: The address family to test for; one of the C{AF_*} constants
  400. from the L{socket} module. (This parameter has only been available
  401. since Twisted 17.1.0; previously L{isIPAddress} could only test for IPv4
  402. addresses.)
  403. @return: C{True} if C{addr} represents an IPv4 address, C{False} otherwise.
  404. """
  405. if isinstance(addr, bytes): # type: ignore[unreachable]
  406. try: # type: ignore[unreachable]
  407. addr = addr.decode("ascii")
  408. except UnicodeDecodeError:
  409. return False
  410. if family == AF_INET6:
  411. # On some platforms, inet_ntop fails unless the scope ID is valid; this
  412. # is a test for whether the given string *is* an IP address, so strip
  413. # any potential scope ID before checking.
  414. addr = addr.split("%", 1)[0]
  415. elif family == AF_INET:
  416. # On Windows, where 3.5+ implement inet_pton, "0" is considered a valid
  417. # IPv4 address, but we want to ensure we have all 4 segments.
  418. if addr.count(".") != 3:
  419. return False
  420. else:
  421. raise ValueError(f"unknown address family {family!r}")
  422. try:
  423. # This might be a native implementation or the one from
  424. # twisted.python.compat.
  425. inet_pton(family, addr)
  426. except (ValueError, OSError):
  427. return False
  428. return True
  429. def isIPv6Address(addr: str) -> bool:
  430. """
  431. Determine whether the given string represents an IPv6 address.
  432. @param addr: A string which may or may not be the hex
  433. representation of an IPv6 address.
  434. @type addr: C{str}
  435. @return: C{True} if C{addr} represents an IPv6 address, C{False}
  436. otherwise.
  437. @rtype: C{bool}
  438. """
  439. return isIPAddress(addr, AF_INET6)
  440. __all__ = ["FileDescriptor", "isIPAddress", "isIPv6Address"]