cfreactor.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. # -*- test-case-name: twisted.internet.test.test_core -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. A reactor for integrating with U{CFRunLoop<http://bit.ly/cfrunloop>}, the
  6. CoreFoundation main loop used by macOS.
  7. This is useful for integrating Twisted with U{PyObjC<http://pyobjc.sf.net/>}
  8. applications.
  9. """
  10. from __future__ import annotations
  11. __all__ = ["install", "CFReactor"]
  12. import sys
  13. from zope.interface import implementer
  14. from CFNetwork import (
  15. CFSocketCreateRunLoopSource,
  16. CFSocketCreateWithNative,
  17. CFSocketDisableCallBacks,
  18. CFSocketEnableCallBacks,
  19. CFSocketInvalidate,
  20. CFSocketSetSocketFlags,
  21. kCFSocketAutomaticallyReenableReadCallBack,
  22. kCFSocketAutomaticallyReenableWriteCallBack,
  23. kCFSocketConnectCallBack,
  24. kCFSocketReadCallBack,
  25. kCFSocketWriteCallBack,
  26. )
  27. from CoreFoundation import (
  28. CFAbsoluteTimeGetCurrent,
  29. CFRunLoopAddSource,
  30. CFRunLoopAddTimer,
  31. CFRunLoopGetCurrent,
  32. CFRunLoopRemoveSource,
  33. CFRunLoopRun,
  34. CFRunLoopStop,
  35. CFRunLoopTimerCreate,
  36. CFRunLoopTimerInvalidate,
  37. kCFAllocatorDefault,
  38. kCFRunLoopCommonModes,
  39. )
  40. from twisted.internet.interfaces import IReactorFDSet
  41. from twisted.internet.posixbase import _NO_FILEDESC, PosixReactorBase
  42. from twisted.python import log
  43. # We know that we're going to run on macOS so we can just pick the
  44. # POSIX-appropriate waker. This also avoids having a dynamic base class and
  45. # so lets more things get type checked.
  46. from ._signals import _UnixWaker
  47. _READ = 0
  48. _WRITE = 1
  49. _preserveSOError = 1 << 6
  50. class _WakerPlus(_UnixWaker):
  51. """
  52. The normal Twisted waker will simply wake up the main loop, which causes an
  53. iteration to run, which in turn causes L{ReactorBase.runUntilCurrent}
  54. to get invoked.
  55. L{CFReactor} has a slightly different model of iteration, though: rather
  56. than have each iteration process the thread queue, then timed calls, then
  57. file descriptors, each callback is run as it is dispatched by the CFRunLoop
  58. observer which triggered it.
  59. So this waker needs to not only unblock the loop, but also make sure the
  60. work gets done; so, it reschedules the invocation of C{runUntilCurrent} to
  61. be immediate (0 seconds from now) even if there is no timed call work to
  62. do.
  63. """
  64. def __init__(self, reactor):
  65. super().__init__()
  66. self.reactor = reactor
  67. def doRead(self):
  68. """
  69. Wake up the loop and force C{runUntilCurrent} to run immediately in the
  70. next timed iteration.
  71. """
  72. result = super().doRead()
  73. self.reactor._scheduleSimulate(True)
  74. return result
  75. @implementer(IReactorFDSet)
  76. class CFReactor(PosixReactorBase):
  77. """
  78. The CoreFoundation reactor.
  79. You probably want to use this via the L{install} API.
  80. @ivar _fdmap: a dictionary, mapping an integer (a file descriptor) to a
  81. 4-tuple of:
  82. - source: a C{CFRunLoopSource}; the source associated with this
  83. socket.
  84. - socket: a C{CFSocket} wrapping the file descriptor.
  85. - descriptor: an L{IReadDescriptor} and/or L{IWriteDescriptor}
  86. provider.
  87. - read-write: a 2-C{list} of booleans: respectively, whether this
  88. descriptor is currently registered for reading or registered for
  89. writing.
  90. @ivar _idmap: a dictionary, mapping the id() of an L{IReadDescriptor} or
  91. L{IWriteDescriptor} to a C{fd} in L{_fdmap}. Implemented in this
  92. manner so that we don't have to rely (even more) on the hashability of
  93. L{IReadDescriptor} providers, and we know that they won't be collected
  94. since these are kept in sync with C{_fdmap}. Necessary because the
  95. .fileno() of a file descriptor may change at will, so we need to be
  96. able to look up what its file descriptor I{used} to be, so that we can
  97. look it up in C{_fdmap}
  98. @ivar _cfrunloop: the C{CFRunLoop} pyobjc object wrapped
  99. by this reactor.
  100. @ivar _inCFLoop: Is C{CFRunLoopRun} currently running?
  101. @type _inCFLoop: L{bool}
  102. @ivar _currentSimulator: if a CFTimer is currently scheduled with the CF
  103. run loop to run Twisted callLater calls, this is a reference to it.
  104. Otherwise, it is L{None}
  105. """
  106. def __init__(self, runLoop=None, runner=None):
  107. self._fdmap = {}
  108. self._idmap = {}
  109. if runner is None:
  110. runner = CFRunLoopRun
  111. self._runner = runner
  112. if runLoop is None:
  113. runLoop = CFRunLoopGetCurrent()
  114. self._cfrunloop = runLoop
  115. PosixReactorBase.__init__(self)
  116. def _wakerFactory(self) -> _WakerPlus:
  117. return _WakerPlus(self)
  118. def _socketCallback(
  119. self, cfSocket, callbackType, ignoredAddress, ignoredData, context
  120. ):
  121. """
  122. The socket callback issued by CFRunLoop. This will issue C{doRead} or
  123. C{doWrite} calls to the L{IReadDescriptor} and L{IWriteDescriptor}
  124. registered with the file descriptor that we are being notified of.
  125. @param cfSocket: The C{CFSocket} which has got some activity.
  126. @param callbackType: The type of activity that we are being notified
  127. of. Either C{kCFSocketReadCallBack} or C{kCFSocketWriteCallBack}.
  128. @param ignoredAddress: Unused, because this is not used for either of
  129. the callback types we register for.
  130. @param ignoredData: Unused, because this is not used for either of the
  131. callback types we register for.
  132. @param context: The data associated with this callback by
  133. C{CFSocketCreateWithNative} (in C{CFReactor._watchFD}). A 2-tuple
  134. of C{(int, CFRunLoopSource)}.
  135. """
  136. (fd, smugglesrc) = context
  137. if fd not in self._fdmap:
  138. # Spurious notifications seem to be generated sometimes if you
  139. # CFSocketDisableCallBacks in the middle of an event. I don't know
  140. # about this FD, any more, so let's get rid of it.
  141. CFRunLoopRemoveSource(self._cfrunloop, smugglesrc, kCFRunLoopCommonModes)
  142. return
  143. src, skt, readWriteDescriptor, rw = self._fdmap[fd]
  144. def _drdw():
  145. why = None
  146. isRead = False
  147. try:
  148. if readWriteDescriptor.fileno() == -1:
  149. why = _NO_FILEDESC
  150. else:
  151. isRead = callbackType == kCFSocketReadCallBack
  152. # CFSocket seems to deliver duplicate read/write
  153. # notifications sometimes, especially a duplicate
  154. # writability notification when first registering the
  155. # socket. This bears further investigation, since I may
  156. # have been mis-interpreting the behavior I was seeing.
  157. # (Running the full Twisted test suite, while thorough, is
  158. # not always entirely clear.) Until this has been more
  159. # thoroughly investigated , we consult our own
  160. # reading/writing state flags to determine whether we
  161. # should actually attempt a doRead/doWrite first. -glyph
  162. if isRead:
  163. if rw[_READ]:
  164. why = readWriteDescriptor.doRead()
  165. else:
  166. if rw[_WRITE]:
  167. why = readWriteDescriptor.doWrite()
  168. except BaseException:
  169. why = sys.exc_info()[1]
  170. log.err()
  171. if why:
  172. self._disconnectSelectable(readWriteDescriptor, why, isRead)
  173. log.callWithLogger(readWriteDescriptor, _drdw)
  174. def _watchFD(self, fd, descr, flag):
  175. """
  176. Register a file descriptor with the C{CFRunLoop}, or modify its state
  177. so that it's listening for both notifications (read and write) rather
  178. than just one; used to implement C{addReader} and C{addWriter}.
  179. @param fd: The file descriptor.
  180. @type fd: L{int}
  181. @param descr: the L{IReadDescriptor} or L{IWriteDescriptor}
  182. @param flag: the flag to register for callbacks on, either
  183. C{kCFSocketReadCallBack} or C{kCFSocketWriteCallBack}
  184. """
  185. if fd == -1:
  186. raise RuntimeError("Invalid file descriptor.")
  187. if fd in self._fdmap:
  188. src, cfs, gotdescr, rw = self._fdmap[fd]
  189. # do I need to verify that it's the same descr?
  190. else:
  191. ctx = []
  192. ctx.append(fd)
  193. cfs = CFSocketCreateWithNative(
  194. kCFAllocatorDefault,
  195. fd,
  196. kCFSocketReadCallBack
  197. | kCFSocketWriteCallBack
  198. | kCFSocketConnectCallBack,
  199. self._socketCallback,
  200. ctx,
  201. )
  202. CFSocketSetSocketFlags(
  203. cfs,
  204. kCFSocketAutomaticallyReenableReadCallBack
  205. | kCFSocketAutomaticallyReenableWriteCallBack
  206. |
  207. # This extra flag is to ensure that CF doesn't (destructively,
  208. # because destructively is the only way to do it) retrieve
  209. # SO_ERROR and thereby break twisted.internet.tcp.BaseClient,
  210. # which needs SO_ERROR to tell it whether or not it needs to
  211. # call connect_ex a second time.
  212. _preserveSOError,
  213. )
  214. src = CFSocketCreateRunLoopSource(kCFAllocatorDefault, cfs, 0)
  215. ctx.append(src)
  216. CFRunLoopAddSource(self._cfrunloop, src, kCFRunLoopCommonModes)
  217. CFSocketDisableCallBacks(
  218. cfs,
  219. kCFSocketReadCallBack
  220. | kCFSocketWriteCallBack
  221. | kCFSocketConnectCallBack,
  222. )
  223. rw = [False, False]
  224. self._idmap[id(descr)] = fd
  225. self._fdmap[fd] = src, cfs, descr, rw
  226. rw[self._flag2idx(flag)] = True
  227. CFSocketEnableCallBacks(cfs, flag)
  228. def _flag2idx(self, flag):
  229. """
  230. Convert a C{kCFSocket...} constant to an index into the read/write
  231. state list (C{_READ} or C{_WRITE}) (the 4th element of the value of
  232. C{self._fdmap}).
  233. @param flag: C{kCFSocketReadCallBack} or C{kCFSocketWriteCallBack}
  234. @return: C{_READ} or C{_WRITE}
  235. """
  236. return {kCFSocketReadCallBack: _READ, kCFSocketWriteCallBack: _WRITE}[flag]
  237. def _unwatchFD(self, fd, descr, flag):
  238. """
  239. Unregister a file descriptor with the C{CFRunLoop}, or modify its state
  240. so that it's listening for only one notification (read or write) as
  241. opposed to both; used to implement C{removeReader} and C{removeWriter}.
  242. @param fd: a file descriptor
  243. @type fd: C{int}
  244. @param descr: an L{IReadDescriptor} or L{IWriteDescriptor}
  245. @param flag: C{kCFSocketWriteCallBack} C{kCFSocketReadCallBack}
  246. """
  247. if id(descr) not in self._idmap:
  248. return
  249. if fd == -1:
  250. # need to deal with it in this case, I think.
  251. realfd = self._idmap[id(descr)]
  252. else:
  253. realfd = fd
  254. src, cfs, descr, rw = self._fdmap[realfd]
  255. CFSocketDisableCallBacks(cfs, flag)
  256. rw[self._flag2idx(flag)] = False
  257. if not rw[_READ] and not rw[_WRITE]:
  258. del self._idmap[id(descr)]
  259. del self._fdmap[realfd]
  260. CFRunLoopRemoveSource(self._cfrunloop, src, kCFRunLoopCommonModes)
  261. CFSocketInvalidate(cfs)
  262. def addReader(self, reader):
  263. """
  264. Implement L{IReactorFDSet.addReader}.
  265. """
  266. self._watchFD(reader.fileno(), reader, kCFSocketReadCallBack)
  267. def addWriter(self, writer):
  268. """
  269. Implement L{IReactorFDSet.addWriter}.
  270. """
  271. self._watchFD(writer.fileno(), writer, kCFSocketWriteCallBack)
  272. def removeReader(self, reader):
  273. """
  274. Implement L{IReactorFDSet.removeReader}.
  275. """
  276. self._unwatchFD(reader.fileno(), reader, kCFSocketReadCallBack)
  277. def removeWriter(self, writer):
  278. """
  279. Implement L{IReactorFDSet.removeWriter}.
  280. """
  281. self._unwatchFD(writer.fileno(), writer, kCFSocketWriteCallBack)
  282. def removeAll(self):
  283. """
  284. Implement L{IReactorFDSet.removeAll}.
  285. """
  286. allDesc = {descr for src, cfs, descr, rw in self._fdmap.values()}
  287. allDesc -= set(self._internalReaders)
  288. for desc in allDesc:
  289. self.removeReader(desc)
  290. self.removeWriter(desc)
  291. return list(allDesc)
  292. def getReaders(self):
  293. """
  294. Implement L{IReactorFDSet.getReaders}.
  295. """
  296. return [descr for src, cfs, descr, rw in self._fdmap.values() if rw[_READ]]
  297. def getWriters(self):
  298. """
  299. Implement L{IReactorFDSet.getWriters}.
  300. """
  301. return [descr for src, cfs, descr, rw in self._fdmap.values() if rw[_WRITE]]
  302. def _moveCallLaterSooner(self, tple):
  303. """
  304. Override L{PosixReactorBase}'s implementation of L{IDelayedCall.reset}
  305. so that it will immediately reschedule. Normally
  306. C{_moveCallLaterSooner} depends on the fact that C{runUntilCurrent} is
  307. always run before the mainloop goes back to sleep, so this forces it to
  308. immediately recompute how long the loop needs to stay asleep.
  309. """
  310. result = PosixReactorBase._moveCallLaterSooner(self, tple)
  311. self._scheduleSimulate()
  312. return result
  313. def startRunning(self, installSignalHandlers: bool = True) -> None:
  314. """
  315. Start running the reactor, then kick off the timer that advances
  316. Twisted's clock to keep pace with CFRunLoop's.
  317. """
  318. super().startRunning(installSignalHandlers)
  319. # Before 'startRunning' is called, the reactor is not attached to the
  320. # CFRunLoop[1]; specifically, the CFTimer that runs all of Twisted's
  321. # timers is not active and will not have been added to the loop by any
  322. # application code. Now that _running is probably[2] True, we need to
  323. # ensure that timed calls will actually run on the main loop. This
  324. # call needs to be here, rather than at the top of mainLoop, because
  325. # it's possible to use startRunning to *attach* a reactor to an
  326. # already-running CFRunLoop, i.e. within a plugin for an application
  327. # that doesn't otherwise use Twisted, rather than calling it via run().
  328. self._scheduleSimulate(force=True)
  329. # [1]: readers & writers are still active in the loop, but arguably
  330. # they should not be.
  331. # [2]: application code within a 'startup' system event trigger *may*
  332. # have already crashed the reactor and thus set _started to False,
  333. # but that specific case is handled by mainLoop, since that case
  334. # is inherently irrelevant in an attach-to-application case and is
  335. # only necessary to handle mainLoop spuriously blocking.
  336. _inCFLoop = False
  337. def mainLoop(self) -> None:
  338. """
  339. Run the runner (C{CFRunLoopRun} or something that calls it), which runs
  340. the run loop until C{crash()} is called.
  341. """
  342. if not self._started:
  343. # If we arrive here, we were crashed by application code in a
  344. # 'startup' system event trigger, (or crashed manually before the
  345. # application calls 'mainLoop' directly for whatever reason; sigh,
  346. # this method should not be public). However, application code
  347. # doing obscure things will expect an invocation of this loop to
  348. # have at least *one* pass over ready readers, writers, and delayed
  349. # calls. iterate(), in particular, is emulated in exactly this way
  350. # in this reactor implementation. In order to ensure that we enter
  351. # the real implementation of the mainloop and do all of those
  352. # things, we need to set _started back to True so that callLater
  353. # actually schedules itself against the CFRunLoop, but immediately
  354. # crash once we are in the context of the loop where we've run
  355. # ready I/O and timers.
  356. def docrash() -> None:
  357. self.crash()
  358. self._started = True
  359. self.callLater(0, docrash)
  360. already = False
  361. try:
  362. while self._started:
  363. if already:
  364. # Sometimes CFRunLoopRun (or its equivalents) may exit
  365. # without CFRunLoopStop being called.
  366. # This is really only *supposed* to happen when it runs out
  367. # of sources & timers to process. However, in full Twisted
  368. # test-suite runs we have observed, extremely rarely (once
  369. # in every 3000 tests or so) CFRunLoopRun exiting in cases
  370. # where it seems as though there *is* still some work to
  371. # do. However, given the difficulty of reproducing the
  372. # race conditions necessary to make this happen, it's
  373. # possible that we have missed some nuance of when
  374. # CFRunLoop considers the list of work "empty" and various
  375. # callbacks and timers to be "invalidated". Therefore we
  376. # are not fully confident that this is a platform bug, but
  377. # it is nevertheless unexpected behavior from our reading
  378. # of the documentation.
  379. # To accommodate this rare and slightly ambiguous stress
  380. # case, we make extra sure that our scheduled timer is
  381. # re-created on the loop as a CFRunLoopTimer, which
  382. # reliably gives the loop some work to do and 'fixes' it if
  383. # it exited due to having no active sources or timers.
  384. self._scheduleSimulate()
  385. # At this point, there may be a little more code that we
  386. # would need to put here for full correctness for a very
  387. # peculiar type of application: if you're writing a
  388. # command-line tool using CFReactor, adding *nothing* to
  389. # the reactor itself, disabling even the internal Waker
  390. # file descriptors, then there's a possibility that
  391. # CFRunLoopRun will exit early, and if we have no timers,
  392. # we might busy-loop here. Because we cannot seem to force
  393. # this to happen under normal circumstances, we're leaving
  394. # that code out.
  395. already = True
  396. self._inCFLoop = True
  397. try:
  398. self._runner()
  399. finally:
  400. self._inCFLoop = False
  401. finally:
  402. self._stopSimulating()
  403. _currentSimulator: object | None = None
  404. def _stopSimulating(self) -> None:
  405. """
  406. If we have a CFRunLoopTimer registered with the CFRunLoop, invalidate
  407. it and set it to None.
  408. """
  409. if self._currentSimulator is None:
  410. return
  411. CFRunLoopTimerInvalidate(self._currentSimulator)
  412. self._currentSimulator = None
  413. def _scheduleSimulate(self, force: bool = False) -> None:
  414. """
  415. Schedule a call to C{self.runUntilCurrent}. This will cancel the
  416. currently scheduled call if it is already scheduled.
  417. @param force: Even if there are no timed calls, make sure that
  418. C{runUntilCurrent} runs immediately (in a 0-seconds-from-now
  419. C{CFRunLoopTimer}). This is necessary for calls which need to
  420. trigger behavior of C{runUntilCurrent} other than running timed
  421. calls, such as draining the thread call queue or calling C{crash()}
  422. when the appropriate flags are set.
  423. @type force: C{bool}
  424. """
  425. self._stopSimulating()
  426. if not self._started:
  427. # If the reactor is not running (e.g. we are scheduling callLater
  428. # calls before starting the reactor) we should not be scheduling
  429. # CFRunLoopTimers against the global CFRunLoop.
  430. return
  431. timeout = 0.0 if force else self.timeout()
  432. if timeout is None:
  433. return
  434. fireDate = CFAbsoluteTimeGetCurrent() + timeout
  435. def simulate(cftimer, extra):
  436. self._currentSimulator = None
  437. self.runUntilCurrent()
  438. self._scheduleSimulate()
  439. c = self._currentSimulator = CFRunLoopTimerCreate(
  440. kCFAllocatorDefault, fireDate, 0, 0, 0, simulate, None
  441. )
  442. CFRunLoopAddTimer(self._cfrunloop, c, kCFRunLoopCommonModes)
  443. def callLater(self, _seconds, _f, *args, **kw):
  444. """
  445. Implement L{IReactorTime.callLater}.
  446. """
  447. delayedCall = PosixReactorBase.callLater(self, _seconds, _f, *args, **kw)
  448. self._scheduleSimulate()
  449. return delayedCall
  450. def stop(self):
  451. """
  452. Implement L{IReactorCore.stop}.
  453. """
  454. PosixReactorBase.stop(self)
  455. self._scheduleSimulate(True)
  456. def crash(self):
  457. """
  458. Implement L{IReactorCore.crash}
  459. """
  460. PosixReactorBase.crash(self)
  461. if not self._inCFLoop:
  462. return
  463. CFRunLoopStop(self._cfrunloop)
  464. def iterate(self, delay=0):
  465. """
  466. Emulate the behavior of C{iterate()} for things that want to call it,
  467. by letting the loop run for a little while and then scheduling a timed
  468. call to exit it.
  469. """
  470. self._started = True
  471. # Since the CoreFoundation loop doesn't have the concept of "iterate"
  472. # we can't ask it to do this. Instead we will make arrangements to
  473. # crash it *very* soon and then make it run. This is a rough
  474. # approximation of "an iteration". Using crash and mainLoop here
  475. # means that it's safe (as safe as anything using "iterate" can be) to
  476. # do this repeatedly.
  477. self.callLater(0, self.crash)
  478. self.mainLoop()
  479. def install(runLoop=None, runner=None):
  480. """
  481. Configure the twisted mainloop to be run inside CFRunLoop.
  482. @param runLoop: the run loop to use.
  483. @param runner: the function to call in order to actually invoke the main
  484. loop. This will default to C{CFRunLoopRun} if not specified. However,
  485. this is not an appropriate choice for GUI applications, as you need to
  486. run NSApplicationMain (or something like it). For example, to run the
  487. Twisted mainloop in a PyObjC application, your C{main.py} should look
  488. something like this::
  489. from PyObjCTools import AppHelper
  490. from twisted.internet.cfreactor import install
  491. install(runner=AppHelper.runEventLoop)
  492. # initialize your application
  493. reactor.run()
  494. @return: The installed reactor.
  495. @rtype: C{CFReactor}
  496. """
  497. reactor = CFReactor(runLoop=runLoop, runner=runner)
  498. from twisted.internet.main import installReactor
  499. installReactor(reactor)
  500. return reactor