win32eventreactor.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. A win32event based implementation of the Twisted main loop.
  5. This requires pywin32 (formerly win32all) or ActivePython to be installed.
  6. To install the event loop (and you should do this before any connections,
  7. listeners or connectors are added)::
  8. from twisted.internet import win32eventreactor
  9. win32eventreactor.install()
  10. LIMITATIONS:
  11. 1. WaitForMultipleObjects and thus the event loop can only handle 64 objects.
  12. 2. Process running has some problems (see L{twisted.internet.process} docstring).
  13. TODO:
  14. 1. Event loop handling of writes is *very* problematic (this is causing failed tests).
  15. Switch to doing it the correct way, whatever that means (see below).
  16. 2. Replace icky socket loopback waker with event based waker (use dummyEvent object)
  17. 3. Switch everyone to using Free Software so we don't have to deal with proprietary APIs.
  18. ALTERNATIVE SOLUTIONS:
  19. - IIRC, sockets can only be registered once. So we switch to a structure
  20. like the poll() reactor, thus allowing us to deal with write events in
  21. a decent fashion. This should allow us to pass tests, but we're still
  22. limited to 64 events.
  23. Or:
  24. - Instead of doing a reactor, we make this an addon to the select reactor.
  25. The WFMO event loop runs in a separate thread. This means no need to maintain
  26. separate code for networking, 64 event limit doesn't apply to sockets,
  27. we can run processes and other win32 stuff in default event loop. The
  28. only problem is that we're stuck with the icky socket based waker.
  29. Another benefit is that this could be extended to support >64 events
  30. in a simpler manner than the previous solution.
  31. The 2nd solution is probably what will get implemented.
  32. """
  33. import sys
  34. # System imports
  35. import time
  36. from threading import Thread
  37. from weakref import WeakKeyDictionary
  38. from zope.interface import implementer
  39. # Win32 imports
  40. from win32file import FD_ACCEPT, FD_CLOSE, FD_CONNECT, FD_READ, WSAEventSelect
  41. try:
  42. # WSAEnumNetworkEvents was added in pywin32 215
  43. from win32file import WSAEnumNetworkEvents
  44. except ImportError:
  45. import warnings
  46. warnings.warn(
  47. "Reliable disconnection notification requires pywin32 215 or later",
  48. category=UserWarning,
  49. )
  50. def WSAEnumNetworkEvents(fd, event):
  51. return {FD_READ}
  52. import win32gui # type: ignore[import-untyped]
  53. from win32event import (
  54. QS_ALLINPUT,
  55. WAIT_OBJECT_0,
  56. WAIT_TIMEOUT,
  57. CreateEvent,
  58. MsgWaitForMultipleObjects,
  59. )
  60. # Twisted imports
  61. from twisted.internet import posixbase
  62. from twisted.internet.interfaces import IReactorFDSet, IReactorWin32Events
  63. from twisted.internet.threads import blockingCallFromThread
  64. from twisted.python import failure, log, threadable
  65. @implementer(IReactorFDSet, IReactorWin32Events)
  66. class Win32Reactor(posixbase.PosixReactorBase):
  67. """
  68. Reactor that uses Win32 event APIs.
  69. @ivar _reads: A dictionary mapping L{FileDescriptor} instances to a
  70. win32 event object used to check for read events for that descriptor.
  71. @ivar _writes: A dictionary mapping L{FileDescriptor} instances to a
  72. arbitrary value. Keys in this dictionary will be given a chance to
  73. write out their data.
  74. @ivar _events: A dictionary mapping win32 event object to tuples of
  75. L{FileDescriptor} instances and event masks.
  76. @ivar _closedAndReading: Along with C{_closedAndNotReading}, keeps track of
  77. descriptors which have had close notification delivered from the OS but
  78. which we have not finished reading data from. MsgWaitForMultipleObjects
  79. will only deliver close notification to us once, so we remember it in
  80. these two dictionaries until we're ready to act on it. The OS has
  81. delivered close notification for each descriptor in this dictionary, and
  82. the descriptors are marked as allowed to handle read events in the
  83. reactor, so they can be processed. When a descriptor is marked as not
  84. allowed to handle read events in the reactor (ie, it is passed to
  85. L{IReactorFDSet.removeReader}), it is moved out of this dictionary and
  86. into C{_closedAndNotReading}. The descriptors are keys in this
  87. dictionary. The values are arbitrary.
  88. @type _closedAndReading: C{dict}
  89. @ivar _closedAndNotReading: These descriptors have had close notification
  90. delivered from the OS, but are not marked as allowed to handle read
  91. events in the reactor. They are saved here to record their closed
  92. state, but not processed at all. When one of these descriptors is
  93. passed to L{IReactorFDSet.addReader}, it is moved out of this dictionary
  94. and into C{_closedAndReading}. The descriptors are keys in this
  95. dictionary. The values are arbitrary. This is a weak key dictionary so
  96. that if an application tells the reactor to stop reading from a
  97. descriptor and then forgets about that descriptor itself, the reactor
  98. will also forget about it.
  99. @type _closedAndNotReading: C{WeakKeyDictionary}
  100. """
  101. dummyEvent = CreateEvent(None, 0, 0, None)
  102. def __init__(self):
  103. self._reads = {}
  104. self._writes = {}
  105. self._events = {}
  106. self._closedAndReading = {}
  107. self._closedAndNotReading = WeakKeyDictionary()
  108. posixbase.PosixReactorBase.__init__(self)
  109. def _makeSocketEvent(self, fd, action, why):
  110. """
  111. Make a win32 event object for a socket.
  112. """
  113. event = CreateEvent(None, 0, 0, None)
  114. WSAEventSelect(fd, event, why)
  115. self._events[event] = (fd, action)
  116. return event
  117. def addEvent(self, event, fd, action):
  118. """
  119. Add a new win32 event to the event loop.
  120. """
  121. self._events[event] = (fd, action)
  122. def removeEvent(self, event):
  123. """
  124. Remove an event.
  125. """
  126. del self._events[event]
  127. def addReader(self, reader):
  128. """
  129. Add a socket FileDescriptor for notification of data available to read.
  130. """
  131. if reader not in self._reads:
  132. self._reads[reader] = self._makeSocketEvent(
  133. reader, "doRead", FD_READ | FD_ACCEPT | FD_CONNECT | FD_CLOSE
  134. )
  135. # If the reader is closed, move it over to the dictionary of reading
  136. # descriptors.
  137. if reader in self._closedAndNotReading:
  138. self._closedAndReading[reader] = True
  139. del self._closedAndNotReading[reader]
  140. def addWriter(self, writer):
  141. """
  142. Add a socket FileDescriptor for notification of data available to write.
  143. """
  144. if writer not in self._writes:
  145. self._writes[writer] = 1
  146. def removeReader(self, reader):
  147. """Remove a Selectable for notification of data available to read."""
  148. if reader in self._reads:
  149. del self._events[self._reads[reader]]
  150. del self._reads[reader]
  151. # If the descriptor is closed, move it out of the dictionary of
  152. # reading descriptors into the dictionary of waiting descriptors.
  153. if reader in self._closedAndReading:
  154. self._closedAndNotReading[reader] = True
  155. del self._closedAndReading[reader]
  156. def removeWriter(self, writer):
  157. """Remove a Selectable for notification of data available to write."""
  158. if writer in self._writes:
  159. del self._writes[writer]
  160. def removeAll(self):
  161. """
  162. Remove all selectables, and return a list of them.
  163. """
  164. return self._removeAll(self._reads, self._writes)
  165. def getReaders(self):
  166. return list(self._reads.keys())
  167. def getWriters(self):
  168. return list(self._writes.keys())
  169. def doWaitForMultipleEvents(self, timeout):
  170. log.msg(channel="system", event="iteration", reactor=self)
  171. if timeout is None:
  172. timeout = 100
  173. # Keep track of whether we run any application code before we get to the
  174. # MsgWaitForMultipleObjects. If so, there's a chance it will schedule a
  175. # new timed call or stop the reactor or do something else that means we
  176. # shouldn't block in MsgWaitForMultipleObjects for the full timeout.
  177. ranUserCode = False
  178. # If any descriptors are trying to close, try to get them out of the way
  179. # first.
  180. for reader in list(self._closedAndReading.keys()):
  181. ranUserCode = True
  182. self._runAction("doRead", reader)
  183. for fd in list(self._writes.keys()):
  184. ranUserCode = True
  185. log.callWithLogger(fd, self._runWrite, fd)
  186. if ranUserCode:
  187. # If application code *might* have scheduled an event, assume it
  188. # did. If we're wrong, we'll get back here shortly anyway. If
  189. # we're right, we'll be sure to handle the event (including reactor
  190. # shutdown) in a timely manner.
  191. timeout = 0
  192. if not (self._events or self._writes):
  193. # sleep so we don't suck up CPU time
  194. time.sleep(timeout)
  195. return
  196. handles = list(self._events.keys()) or [self.dummyEvent]
  197. timeout = int(timeout * 1000)
  198. val = MsgWaitForMultipleObjects(handles, 0, timeout, QS_ALLINPUT)
  199. if val == WAIT_TIMEOUT:
  200. return
  201. elif val == WAIT_OBJECT_0 + len(handles):
  202. exit = win32gui.PumpWaitingMessages()
  203. if exit:
  204. self.callLater(0, self.stop)
  205. return
  206. elif val >= WAIT_OBJECT_0 and val < WAIT_OBJECT_0 + len(handles):
  207. event = handles[val - WAIT_OBJECT_0]
  208. fd, action = self._events[event]
  209. if fd in self._reads:
  210. # Before anything, make sure it's still a valid file descriptor.
  211. fileno = fd.fileno()
  212. if fileno == -1:
  213. self._disconnectSelectable(fd, posixbase._NO_FILEDESC, False)
  214. return
  215. # Since it's a socket (not another arbitrary event added via
  216. # addEvent) and we asked for FD_READ | FD_CLOSE, check to see if
  217. # we actually got FD_CLOSE. This needs a special check because
  218. # it only gets delivered once. If we miss it, it's gone forever
  219. # and we'll never know that the connection is closed.
  220. events = WSAEnumNetworkEvents(fileno, event)
  221. if FD_CLOSE in events:
  222. self._closedAndReading[fd] = True
  223. log.callWithLogger(fd, self._runAction, action, fd)
  224. def _runWrite(self, fd):
  225. closed = 0
  226. try:
  227. closed = fd.doWrite()
  228. except BaseException:
  229. closed = sys.exc_info()[1]
  230. log.deferr()
  231. if closed:
  232. self.removeReader(fd)
  233. self.removeWriter(fd)
  234. try:
  235. fd.connectionLost(failure.Failure(closed))
  236. except BaseException:
  237. log.deferr()
  238. elif closed is None:
  239. return 1
  240. def _runAction(self, action, fd):
  241. try:
  242. closed = getattr(fd, action)()
  243. except BaseException:
  244. closed = sys.exc_info()[1]
  245. log.deferr()
  246. if closed:
  247. self._disconnectSelectable(fd, closed, action == "doRead")
  248. doIteration = doWaitForMultipleEvents
  249. class _ThreadFDWrapper:
  250. """
  251. This wraps an event handler and translates notification in the helper
  252. L{Win32Reactor} thread into a notification in the primary reactor thread.
  253. @ivar _reactor: The primary reactor, the one to which event notification
  254. will be sent.
  255. @ivar _fd: The L{FileDescriptor} to which the event will be dispatched.
  256. @ivar _action: A C{str} giving the method of C{_fd} which handles the event.
  257. @ivar _logPrefix: The pre-fetched log prefix string for C{_fd}, so that
  258. C{_fd.logPrefix} does not need to be called in a non-main thread.
  259. """
  260. def __init__(self, reactor, fd, action, logPrefix):
  261. self._reactor = reactor
  262. self._fd = fd
  263. self._action = action
  264. self._logPrefix = logPrefix
  265. def logPrefix(self):
  266. """
  267. Return the original handler's log prefix, as it was given to
  268. C{__init__}.
  269. """
  270. return self._logPrefix
  271. def _execute(self):
  272. """
  273. Callback fired when the associated event is set. Run the C{action}
  274. callback on the wrapped descriptor in the main reactor thread and raise
  275. or return whatever it raises or returns to cause this event handler to
  276. be removed from C{self._reactor} if appropriate.
  277. """
  278. return blockingCallFromThread(
  279. self._reactor, lambda: getattr(self._fd, self._action)()
  280. )
  281. def connectionLost(self, reason):
  282. """
  283. Pass through to the wrapped descriptor, but in the main reactor thread
  284. instead of the helper C{Win32Reactor} thread.
  285. """
  286. self._reactor.callFromThread(self._fd.connectionLost, reason)
  287. @implementer(IReactorWin32Events)
  288. class _ThreadedWin32EventsMixin:
  289. """
  290. This mixin implements L{IReactorWin32Events} for another reactor by running
  291. a L{Win32Reactor} in a separate thread and dispatching work to it.
  292. @ivar _reactor: The L{Win32Reactor} running in the other thread. This is
  293. L{None} until it is actually needed.
  294. @ivar _reactorThread: The L{threading.Thread} which is running the
  295. L{Win32Reactor}. This is L{None} until it is actually needed.
  296. """
  297. _reactor = None
  298. _reactorThread = None
  299. def _unmakeHelperReactor(self):
  300. """
  301. Stop and discard the reactor started by C{_makeHelperReactor}.
  302. """
  303. self._reactor.callFromThread(self._reactor.stop)
  304. self._reactor = None
  305. def _makeHelperReactor(self):
  306. """
  307. Create and (in a new thread) start a L{Win32Reactor} instance to use for
  308. the implementation of L{IReactorWin32Events}.
  309. """
  310. self._reactor = Win32Reactor()
  311. # This is a helper reactor, it is not the global reactor and its thread
  312. # is not "the" I/O thread. Prevent it from registering it as such.
  313. self._reactor._registerAsIOThread = False
  314. self._reactorThread = Thread(target=self._reactor.run, args=(False,))
  315. self.addSystemEventTrigger("after", "shutdown", self._unmakeHelperReactor)
  316. self._reactorThread.start()
  317. def addEvent(self, event, fd, action):
  318. """
  319. @see: L{IReactorWin32Events}
  320. """
  321. if self._reactor is None:
  322. self._makeHelperReactor()
  323. self._reactor.callFromThread(
  324. self._reactor.addEvent,
  325. event,
  326. _ThreadFDWrapper(self, fd, action, fd.logPrefix()),
  327. "_execute",
  328. )
  329. def removeEvent(self, event):
  330. """
  331. @see: L{IReactorWin32Events}
  332. """
  333. self._reactor.callFromThread(self._reactor.removeEvent, event)
  334. def install():
  335. threadable.init(1)
  336. r = Win32Reactor()
  337. from . import main
  338. main.installReactor(r)
  339. __all__ = ["Win32Reactor", "install"]