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.

posixbase.py 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. # -*- test-case-name: twisted.test.test_internet,twisted.internet.test.test_posixbase -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Posix reactor base class
  6. """
  7. import socket
  8. import sys
  9. from typing import Sequence
  10. from zope.interface import classImplements, implementer
  11. from twisted.internet import error, tcp, udp
  12. from twisted.internet.base import ReactorBase, _SignalReactorMixin
  13. from twisted.internet.interfaces import (
  14. IHalfCloseableDescriptor,
  15. IReactorFDSet,
  16. IReactorMulticast,
  17. IReactorProcess,
  18. IReactorSocket,
  19. IReactorSSL,
  20. IReactorTCP,
  21. IReactorUDP,
  22. IReactorUNIX,
  23. IReactorUNIXDatagram,
  24. )
  25. from twisted.internet.main import CONNECTION_DONE, CONNECTION_LOST
  26. from twisted.python import failure, log
  27. from twisted.python.runtime import platform, platformType
  28. from ._signals import _SIGCHLDWaker, _Waker
  29. # Exceptions that doSelect might return frequently
  30. _NO_FILENO = error.ConnectionFdescWentAway("Handler has no fileno method")
  31. _NO_FILEDESC = error.ConnectionFdescWentAway("File descriptor lost")
  32. try:
  33. from twisted.protocols import tls as _tls
  34. except ImportError:
  35. tls = None
  36. else:
  37. tls = _tls
  38. try:
  39. from twisted.internet import ssl as _ssl
  40. except ImportError:
  41. ssl = None
  42. else:
  43. ssl = _ssl
  44. unixEnabled = platformType == "posix"
  45. processEnabled = False
  46. if unixEnabled:
  47. from twisted.internet import process, unix
  48. processEnabled = True
  49. if platform.isWindows():
  50. try:
  51. import win32process # type: ignore[import]
  52. processEnabled = True
  53. except ImportError:
  54. win32process = None
  55. class _DisconnectSelectableMixin:
  56. """
  57. Mixin providing the C{_disconnectSelectable} method.
  58. """
  59. def _disconnectSelectable(
  60. self,
  61. selectable,
  62. why,
  63. isRead,
  64. faildict={
  65. error.ConnectionDone: failure.Failure(error.ConnectionDone()),
  66. error.ConnectionLost: failure.Failure(error.ConnectionLost()),
  67. },
  68. ):
  69. """
  70. Utility function for disconnecting a selectable.
  71. Supports half-close notification, isRead should be boolean indicating
  72. whether error resulted from doRead().
  73. """
  74. self.removeReader(selectable)
  75. f = faildict.get(why.__class__)
  76. if f:
  77. if (
  78. isRead
  79. and why.__class__ == error.ConnectionDone
  80. and IHalfCloseableDescriptor.providedBy(selectable)
  81. ):
  82. selectable.readConnectionLost(f)
  83. else:
  84. self.removeWriter(selectable)
  85. selectable.connectionLost(f)
  86. else:
  87. self.removeWriter(selectable)
  88. selectable.connectionLost(failure.Failure(why))
  89. @implementer(IReactorTCP, IReactorUDP, IReactorMulticast)
  90. class PosixReactorBase(_SignalReactorMixin, _DisconnectSelectableMixin, ReactorBase):
  91. """
  92. A basis for reactors that use file descriptors.
  93. @ivar _childWaker: L{None} or a reference to the L{_SIGCHLDWaker}
  94. which is used to properly notice child process termination.
  95. """
  96. # Callable that creates a waker, overrideable so that subclasses can
  97. # substitute their own implementation:
  98. _wakerFactory = _Waker
  99. def installWaker(self):
  100. """
  101. Install a `waker' to allow threads and signals to wake up the IO thread.
  102. We use the self-pipe trick (http://cr.yp.to/docs/selfpipe.html) to wake
  103. the reactor. On Windows we use a pair of sockets.
  104. """
  105. if not self.waker:
  106. self.waker = self._wakerFactory(self)
  107. self._internalReaders.add(self.waker)
  108. self.addReader(self.waker)
  109. _childWaker = None
  110. def _handleSignals(self):
  111. """
  112. Extend the basic signal handling logic to also support
  113. handling SIGCHLD to know when to try to reap child processes.
  114. """
  115. _SignalReactorMixin._handleSignals(self)
  116. if platformType == "posix" and processEnabled:
  117. if not self._childWaker:
  118. self._childWaker = _SIGCHLDWaker(self)
  119. self._internalReaders.add(self._childWaker)
  120. self.addReader(self._childWaker)
  121. self._childWaker.install()
  122. # Also reap all processes right now, in case we missed any
  123. # signals before we installed the SIGCHLD waker/handler.
  124. # This should only happen if someone used spawnProcess
  125. # before calling reactor.run (and the process also exited
  126. # already).
  127. process.reapAllProcesses()
  128. def _uninstallHandler(self):
  129. """
  130. If a child waker was created and installed, uninstall it now.
  131. Since this disables reactor functionality and is only called
  132. when the reactor is stopping, it doesn't provide any directly
  133. useful functionality, but the cleanup of reactor-related
  134. process-global state that it does helps in unit tests
  135. involving multiple reactors and is generally just a nice
  136. thing.
  137. """
  138. # XXX This would probably be an alright place to put all of
  139. # the cleanup code for all internal readers (here and in the
  140. # base class, anyway). See #3063 for that cleanup task.
  141. if self._childWaker:
  142. self._childWaker.uninstall()
  143. # IReactorProcess
  144. def spawnProcess(
  145. self,
  146. processProtocol,
  147. executable,
  148. args=(),
  149. env={},
  150. path=None,
  151. uid=None,
  152. gid=None,
  153. usePTY=0,
  154. childFDs=None,
  155. ):
  156. if platformType == "posix":
  157. if usePTY:
  158. if childFDs is not None:
  159. raise ValueError(
  160. "Using childFDs is not supported with usePTY=True."
  161. )
  162. return process.PTYProcess(
  163. self, executable, args, env, path, processProtocol, uid, gid, usePTY
  164. )
  165. else:
  166. return process.Process(
  167. self,
  168. executable,
  169. args,
  170. env,
  171. path,
  172. processProtocol,
  173. uid,
  174. gid,
  175. childFDs,
  176. )
  177. elif platformType == "win32":
  178. if uid is not None:
  179. raise ValueError("Setting UID is unsupported on this platform.")
  180. if gid is not None:
  181. raise ValueError("Setting GID is unsupported on this platform.")
  182. if usePTY:
  183. raise ValueError("The usePTY parameter is not supported on Windows.")
  184. if childFDs:
  185. raise ValueError("Customizing childFDs is not supported on Windows.")
  186. if win32process:
  187. from twisted.internet._dumbwin32proc import Process
  188. return Process(self, processProtocol, executable, args, env, path)
  189. else:
  190. raise NotImplementedError(
  191. "spawnProcess not available since pywin32 is not installed."
  192. )
  193. else:
  194. raise NotImplementedError(
  195. "spawnProcess only available on Windows or POSIX."
  196. )
  197. # IReactorUDP
  198. def listenUDP(self, port, protocol, interface="", maxPacketSize=8192):
  199. """Connects a given L{DatagramProtocol} to the given numeric UDP port.
  200. @returns: object conforming to L{IListeningPort}.
  201. """
  202. p = udp.Port(port, protocol, interface, maxPacketSize, self)
  203. p.startListening()
  204. return p
  205. # IReactorMulticast
  206. def listenMulticast(
  207. self, port, protocol, interface="", maxPacketSize=8192, listenMultiple=False
  208. ):
  209. """Connects a given DatagramProtocol to the given numeric UDP port.
  210. EXPERIMENTAL.
  211. @returns: object conforming to IListeningPort.
  212. """
  213. p = udp.MulticastPort(
  214. port, protocol, interface, maxPacketSize, self, listenMultiple
  215. )
  216. p.startListening()
  217. return p
  218. # IReactorUNIX
  219. def connectUNIX(self, address, factory, timeout=30, checkPID=0):
  220. assert unixEnabled, "UNIX support is not present"
  221. c = unix.Connector(address, factory, timeout, self, checkPID)
  222. c.connect()
  223. return c
  224. def listenUNIX(self, address, factory, backlog=50, mode=0o666, wantPID=0):
  225. assert unixEnabled, "UNIX support is not present"
  226. p = unix.Port(address, factory, backlog, mode, self, wantPID)
  227. p.startListening()
  228. return p
  229. # IReactorUNIXDatagram
  230. def listenUNIXDatagram(self, address, protocol, maxPacketSize=8192, mode=0o666):
  231. """
  232. Connects a given L{DatagramProtocol} to the given path.
  233. EXPERIMENTAL.
  234. @returns: object conforming to L{IListeningPort}.
  235. """
  236. assert unixEnabled, "UNIX support is not present"
  237. p = unix.DatagramPort(address, protocol, maxPacketSize, mode, self)
  238. p.startListening()
  239. return p
  240. def connectUNIXDatagram(
  241. self, address, protocol, maxPacketSize=8192, mode=0o666, bindAddress=None
  242. ):
  243. """
  244. Connects a L{ConnectedDatagramProtocol} instance to a path.
  245. EXPERIMENTAL.
  246. """
  247. assert unixEnabled, "UNIX support is not present"
  248. p = unix.ConnectedDatagramPort(
  249. address, protocol, maxPacketSize, mode, bindAddress, self
  250. )
  251. p.startListening()
  252. return p
  253. # IReactorSocket (no AF_UNIX on Windows)
  254. if unixEnabled:
  255. _supportedAddressFamilies: Sequence[socket.AddressFamily] = (
  256. socket.AF_INET,
  257. socket.AF_INET6,
  258. socket.AF_UNIX,
  259. )
  260. else:
  261. _supportedAddressFamilies = (
  262. socket.AF_INET,
  263. socket.AF_INET6,
  264. )
  265. def adoptStreamPort(self, fileDescriptor, addressFamily, factory):
  266. """
  267. Create a new L{IListeningPort} from an already-initialized socket.
  268. This just dispatches to a suitable port implementation (eg from
  269. L{IReactorTCP}, etc) based on the specified C{addressFamily}.
  270. @see: L{twisted.internet.interfaces.IReactorSocket.adoptStreamPort}
  271. """
  272. if addressFamily not in self._supportedAddressFamilies:
  273. raise error.UnsupportedAddressFamily(addressFamily)
  274. if unixEnabled and addressFamily == socket.AF_UNIX:
  275. p = unix.Port._fromListeningDescriptor(self, fileDescriptor, factory)
  276. else:
  277. p = tcp.Port._fromListeningDescriptor(
  278. self, fileDescriptor, addressFamily, factory
  279. )
  280. p.startListening()
  281. return p
  282. def adoptStreamConnection(self, fileDescriptor, addressFamily, factory):
  283. """
  284. @see:
  285. L{twisted.internet.interfaces.IReactorSocket.adoptStreamConnection}
  286. """
  287. if addressFamily not in self._supportedAddressFamilies:
  288. raise error.UnsupportedAddressFamily(addressFamily)
  289. if unixEnabled and addressFamily == socket.AF_UNIX:
  290. return unix.Server._fromConnectedSocket(fileDescriptor, factory, self)
  291. else:
  292. return tcp.Server._fromConnectedSocket(
  293. fileDescriptor, addressFamily, factory, self
  294. )
  295. def adoptDatagramPort(
  296. self, fileDescriptor, addressFamily, protocol, maxPacketSize=8192
  297. ):
  298. if addressFamily not in (socket.AF_INET, socket.AF_INET6):
  299. raise error.UnsupportedAddressFamily(addressFamily)
  300. p = udp.Port._fromListeningDescriptor(
  301. self, fileDescriptor, addressFamily, protocol, maxPacketSize=maxPacketSize
  302. )
  303. p.startListening()
  304. return p
  305. # IReactorTCP
  306. def listenTCP(self, port, factory, backlog=50, interface=""):
  307. p = tcp.Port(port, factory, backlog, interface, self)
  308. p.startListening()
  309. return p
  310. def connectTCP(self, host, port, factory, timeout=30, bindAddress=None):
  311. c = tcp.Connector(host, port, factory, timeout, bindAddress, self)
  312. c.connect()
  313. return c
  314. # IReactorSSL (sometimes, not implemented)
  315. def connectSSL(
  316. self, host, port, factory, contextFactory, timeout=30, bindAddress=None
  317. ):
  318. if tls is not None:
  319. tlsFactory = tls.TLSMemoryBIOFactory(contextFactory, True, factory)
  320. return self.connectTCP(host, port, tlsFactory, timeout, bindAddress)
  321. elif ssl is not None:
  322. c = ssl.Connector(
  323. host, port, factory, contextFactory, timeout, bindAddress, self
  324. )
  325. c.connect()
  326. return c
  327. else:
  328. assert False, "SSL support is not present"
  329. def listenSSL(self, port, factory, contextFactory, backlog=50, interface=""):
  330. if tls is not None:
  331. tlsFactory = tls.TLSMemoryBIOFactory(contextFactory, False, factory)
  332. port = self.listenTCP(port, tlsFactory, backlog, interface)
  333. port._type = "TLS"
  334. return port
  335. elif ssl is not None:
  336. p = ssl.Port(port, factory, contextFactory, backlog, interface, self)
  337. p.startListening()
  338. return p
  339. else:
  340. assert False, "SSL support is not present"
  341. def _removeAll(self, readers, writers):
  342. """
  343. Remove all readers and writers, and list of removed L{IReadDescriptor}s
  344. and L{IWriteDescriptor}s.
  345. Meant for calling from subclasses, to implement removeAll, like::
  346. def removeAll(self):
  347. return self._removeAll(self._reads, self._writes)
  348. where C{self._reads} and C{self._writes} are iterables.
  349. """
  350. removedReaders = set(readers) - self._internalReaders
  351. for reader in removedReaders:
  352. self.removeReader(reader)
  353. removedWriters = set(writers)
  354. for writer in removedWriters:
  355. self.removeWriter(writer)
  356. return list(removedReaders | removedWriters)
  357. class _PollLikeMixin:
  358. """
  359. Mixin for poll-like reactors.
  360. Subclasses must define the following attributes::
  361. - _POLL_DISCONNECTED - Bitmask for events indicating a connection was
  362. lost.
  363. - _POLL_IN - Bitmask for events indicating there is input to read.
  364. - _POLL_OUT - Bitmask for events indicating output can be written.
  365. Must be mixed in to a subclass of PosixReactorBase (for
  366. _disconnectSelectable).
  367. """
  368. def _doReadOrWrite(self, selectable, fd, event):
  369. """
  370. fd is available for read or write, do the work and raise errors if
  371. necessary.
  372. """
  373. why = None
  374. inRead = False
  375. if event & self._POLL_DISCONNECTED and not (event & self._POLL_IN):
  376. # Handle disconnection. But only if we finished processing all
  377. # the pending input.
  378. if fd in self._reads:
  379. # If we were reading from the descriptor then this is a
  380. # clean shutdown. We know there are no read events pending
  381. # because we just checked above. It also might be a
  382. # half-close (which is why we have to keep track of inRead).
  383. inRead = True
  384. why = CONNECTION_DONE
  385. else:
  386. # If we weren't reading, this is an error shutdown of some
  387. # sort.
  388. why = CONNECTION_LOST
  389. else:
  390. # Any non-disconnect event turns into a doRead or a doWrite.
  391. try:
  392. # First check to see if the descriptor is still valid. This
  393. # gives fileno() a chance to raise an exception, too.
  394. # Ideally, disconnection would always be indicated by the
  395. # return value of doRead or doWrite (or an exception from
  396. # one of those methods), but calling fileno here helps make
  397. # buggy applications more transparent.
  398. if selectable.fileno() == -1:
  399. # -1 is sort of a historical Python artifact. Python
  400. # files and sockets used to change their file descriptor
  401. # to -1 when they closed. For the time being, we'll
  402. # continue to support this anyway in case applications
  403. # replicated it, plus abstract.FileDescriptor.fileno
  404. # returns -1. Eventually it'd be good to deprecate this
  405. # case.
  406. why = _NO_FILEDESC
  407. else:
  408. if event & self._POLL_IN:
  409. # Handle a read event.
  410. why = selectable.doRead()
  411. inRead = True
  412. if not why and event & self._POLL_OUT:
  413. # Handle a write event, as long as doRead didn't
  414. # disconnect us.
  415. why = selectable.doWrite()
  416. inRead = False
  417. except BaseException:
  418. # Any exception from application code gets logged and will
  419. # cause us to disconnect the selectable.
  420. why = sys.exc_info()[1]
  421. log.err()
  422. if why:
  423. self._disconnectSelectable(selectable, why, inRead)
  424. @implementer(IReactorFDSet)
  425. class _ContinuousPolling(_PollLikeMixin, _DisconnectSelectableMixin):
  426. """
  427. Schedule reads and writes based on the passage of time, rather than
  428. notification.
  429. This is useful for supporting polling filesystem files, which C{epoll(7)}
  430. does not support.
  431. The implementation uses L{_PollLikeMixin}, which is a bit hacky, but
  432. re-implementing and testing the relevant code yet again is unappealing.
  433. @ivar _reactor: The L{EPollReactor} that is using this instance.
  434. @ivar _loop: A C{LoopingCall} that drives the polling, or L{None}.
  435. @ivar _readers: A C{set} of C{FileDescriptor} objects that should be read
  436. from.
  437. @ivar _writers: A C{set} of C{FileDescriptor} objects that should be
  438. written to.
  439. """
  440. # Attributes for _PollLikeMixin
  441. _POLL_DISCONNECTED = 1
  442. _POLL_IN = 2
  443. _POLL_OUT = 4
  444. def __init__(self, reactor):
  445. self._reactor = reactor
  446. self._loop = None
  447. self._readers = set()
  448. self._writers = set()
  449. def _checkLoop(self):
  450. """
  451. Start or stop a C{LoopingCall} based on whether there are readers and
  452. writers.
  453. """
  454. if self._readers or self._writers:
  455. if self._loop is None:
  456. from twisted.internet.task import _EPSILON, LoopingCall
  457. self._loop = LoopingCall(self.iterate)
  458. self._loop.clock = self._reactor
  459. # LoopingCall seems unhappy with timeout of 0, so use very
  460. # small number:
  461. self._loop.start(_EPSILON, now=False)
  462. elif self._loop:
  463. self._loop.stop()
  464. self._loop = None
  465. def iterate(self):
  466. """
  467. Call C{doRead} and C{doWrite} on all readers and writers respectively.
  468. """
  469. for reader in list(self._readers):
  470. self._doReadOrWrite(reader, reader, self._POLL_IN)
  471. for writer in list(self._writers):
  472. self._doReadOrWrite(writer, writer, self._POLL_OUT)
  473. def addReader(self, reader):
  474. """
  475. Add a C{FileDescriptor} for notification of data available to read.
  476. """
  477. self._readers.add(reader)
  478. self._checkLoop()
  479. def addWriter(self, writer):
  480. """
  481. Add a C{FileDescriptor} for notification of data available to write.
  482. """
  483. self._writers.add(writer)
  484. self._checkLoop()
  485. def removeReader(self, reader):
  486. """
  487. Remove a C{FileDescriptor} from notification of data available to read.
  488. """
  489. try:
  490. self._readers.remove(reader)
  491. except KeyError:
  492. return
  493. self._checkLoop()
  494. def removeWriter(self, writer):
  495. """
  496. Remove a C{FileDescriptor} from notification of data available to
  497. write.
  498. """
  499. try:
  500. self._writers.remove(writer)
  501. except KeyError:
  502. return
  503. self._checkLoop()
  504. def removeAll(self):
  505. """
  506. Remove all readers and writers.
  507. """
  508. result = list(self._readers | self._writers)
  509. # Don't reset to new value, since self.isWriting and .isReading refer
  510. # to the existing instance:
  511. self._readers.clear()
  512. self._writers.clear()
  513. return result
  514. def getReaders(self):
  515. """
  516. Return a list of the readers.
  517. """
  518. return list(self._readers)
  519. def getWriters(self):
  520. """
  521. Return a list of the writers.
  522. """
  523. return list(self._writers)
  524. def isReading(self, fd):
  525. """
  526. Checks if the file descriptor is currently being observed for read
  527. readiness.
  528. @param fd: The file descriptor being checked.
  529. @type fd: L{twisted.internet.abstract.FileDescriptor}
  530. @return: C{True} if the file descriptor is being observed for read
  531. readiness, C{False} otherwise.
  532. @rtype: C{bool}
  533. """
  534. return fd in self._readers
  535. def isWriting(self, fd):
  536. """
  537. Checks if the file descriptor is currently being observed for write
  538. readiness.
  539. @param fd: The file descriptor being checked.
  540. @type fd: L{twisted.internet.abstract.FileDescriptor}
  541. @return: C{True} if the file descriptor is being observed for write
  542. readiness, C{False} otherwise.
  543. @rtype: C{bool}
  544. """
  545. return fd in self._writers
  546. if tls is not None or ssl is not None:
  547. classImplements(PosixReactorBase, IReactorSSL)
  548. if unixEnabled:
  549. classImplements(PosixReactorBase, IReactorUNIX, IReactorUNIXDatagram)
  550. if processEnabled:
  551. classImplements(PosixReactorBase, IReactorProcess)
  552. if getattr(socket, "fromfd", None) is not None:
  553. classImplements(PosixReactorBase, IReactorSocket)
  554. __all__ = ["PosixReactorBase"]