posixbase.py 26 KB

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