cfreactor.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. __all__ = [
  11. 'install',
  12. 'CFReactor'
  13. ]
  14. import sys
  15. from zope.interface import implementer
  16. from twisted.internet.interfaces import IReactorFDSet
  17. from twisted.internet.posixbase import PosixReactorBase, _Waker
  18. from twisted.internet.posixbase import _NO_FILEDESC
  19. from twisted.python import log
  20. from CoreFoundation import (
  21. CFRunLoopAddSource, CFRunLoopRemoveSource, CFRunLoopGetMain, CFRunLoopRun,
  22. CFRunLoopStop, CFRunLoopTimerCreate, CFRunLoopAddTimer,
  23. CFRunLoopTimerInvalidate, kCFAllocatorDefault, kCFRunLoopCommonModes,
  24. CFAbsoluteTimeGetCurrent)
  25. from CFNetwork import (
  26. CFSocketCreateWithNative, CFSocketSetSocketFlags, CFSocketEnableCallBacks,
  27. CFSocketCreateRunLoopSource, CFSocketDisableCallBacks, CFSocketInvalidate,
  28. kCFSocketWriteCallBack, kCFSocketReadCallBack, kCFSocketConnectCallBack,
  29. kCFSocketAutomaticallyReenableReadCallBack,
  30. kCFSocketAutomaticallyReenableWriteCallBack)
  31. _READ = 0
  32. _WRITE = 1
  33. _preserveSOError = 1 << 6
  34. class _WakerPlus(_Waker):
  35. """
  36. The normal Twisted waker will simply wake up the main loop, which causes an
  37. iteration to run, which in turn causes L{ReactorBase.runUntilCurrent}
  38. to get invoked.
  39. L{CFReactor} has a slightly different model of iteration, though: rather
  40. than have each iteration process the thread queue, then timed calls, then
  41. file descriptors, each callback is run as it is dispatched by the CFRunLoop
  42. observer which triggered it.
  43. So this waker needs to not only unblock the loop, but also make sure the
  44. work gets done; so, it reschedules the invocation of C{runUntilCurrent} to
  45. be immediate (0 seconds from now) even if there is no timed call work to
  46. do.
  47. """
  48. def doRead(self):
  49. """
  50. Wake up the loop and force C{runUntilCurrent} to run immediately in the
  51. next timed iteration.
  52. """
  53. result = _Waker.doRead(self)
  54. self.reactor._scheduleSimulate(True)
  55. return result
  56. @implementer(IReactorFDSet)
  57. class CFReactor(PosixReactorBase):
  58. """
  59. The CoreFoundation reactor.
  60. You probably want to use this via the L{install} API.
  61. @ivar _fdmap: a dictionary, mapping an integer (a file descriptor) to a
  62. 4-tuple of:
  63. - source: a C{CFRunLoopSource}; the source associated with this
  64. socket.
  65. - socket: a C{CFSocket} wrapping the file descriptor.
  66. - descriptor: an L{IReadDescriptor} and/or L{IWriteDescriptor}
  67. provider.
  68. - read-write: a 2-C{list} of booleans: respectively, whether this
  69. descriptor is currently registered for reading or registered for
  70. writing.
  71. @ivar _idmap: a dictionary, mapping the id() of an L{IReadDescriptor} or
  72. L{IWriteDescriptor} to a C{fd} in L{_fdmap}. Implemented in this
  73. manner so that we don't have to rely (even more) on the hashability of
  74. L{IReadDescriptor} providers, and we know that they won't be collected
  75. since these are kept in sync with C{_fdmap}. Necessary because the
  76. .fileno() of a file descriptor may change at will, so we need to be
  77. able to look up what its file descriptor I{used} to be, so that we can
  78. look it up in C{_fdmap}
  79. @ivar _cfrunloop: the C{CFRunLoop} pyobjc object wrapped
  80. by this reactor.
  81. @ivar _inCFLoop: Is C{CFRunLoopRun} currently running?
  82. @type _inCFLoop: L{bool}
  83. @ivar _currentSimulator: if a CFTimer is currently scheduled with the CF
  84. run loop to run Twisted callLater calls, this is a reference to it.
  85. Otherwise, it is L{None}
  86. """
  87. def __init__(self, runLoop=None, runner=None):
  88. self._fdmap = {}
  89. self._idmap = {}
  90. if runner is None:
  91. runner = CFRunLoopRun
  92. self._runner = runner
  93. if runLoop is None:
  94. runLoop = CFRunLoopGetMain()
  95. self._cfrunloop = runLoop
  96. PosixReactorBase.__init__(self)
  97. def installWaker(self):
  98. """
  99. Override C{installWaker} in order to use L{_WakerPlus}; otherwise this
  100. should be exactly the same as the parent implementation.
  101. """
  102. if not self.waker:
  103. self.waker = _WakerPlus(self)
  104. self._internalReaders.add(self.waker)
  105. self.addReader(self.waker)
  106. def _socketCallback(self, cfSocket, callbackType,
  107. ignoredAddress, ignoredData, context):
  108. """
  109. The socket callback issued by CFRunLoop. This will issue C{doRead} or
  110. C{doWrite} calls to the L{IReadDescriptor} and L{IWriteDescriptor}
  111. registered with the file descriptor that we are being notified of.
  112. @param cfSocket: The C{CFSocket} which has got some activity.
  113. @param callbackType: The type of activity that we are being notified
  114. of. Either C{kCFSocketReadCallBack} or C{kCFSocketWriteCallBack}.
  115. @param ignoredAddress: Unused, because this is not used for either of
  116. the callback types we register for.
  117. @param ignoredData: Unused, because this is not used for either of the
  118. callback types we register for.
  119. @param context: The data associated with this callback by
  120. C{CFSocketCreateWithNative} (in C{CFReactor._watchFD}). A 2-tuple
  121. of C{(int, CFRunLoopSource)}.
  122. """
  123. (fd, smugglesrc) = context
  124. if fd not in self._fdmap:
  125. # Spurious notifications seem to be generated sometimes if you
  126. # CFSocketDisableCallBacks in the middle of an event. I don't know
  127. # about this FD, any more, so let's get rid of it.
  128. CFRunLoopRemoveSource(
  129. self._cfrunloop, smugglesrc, kCFRunLoopCommonModes
  130. )
  131. return
  132. src, skt, readWriteDescriptor, rw = self._fdmap[fd]
  133. def _drdw():
  134. why = None
  135. isRead = False
  136. try:
  137. if readWriteDescriptor.fileno() == -1:
  138. why = _NO_FILEDESC
  139. else:
  140. isRead = callbackType == kCFSocketReadCallBack
  141. # CFSocket seems to deliver duplicate read/write
  142. # notifications sometimes, especially a duplicate
  143. # writability notification when first registering the
  144. # socket. This bears further investigation, since I may
  145. # have been mis-interpreting the behavior I was seeing.
  146. # (Running the full Twisted test suite, while thorough, is
  147. # not always entirely clear.) Until this has been more
  148. # thoroughly investigated , we consult our own
  149. # reading/writing state flags to determine whether we
  150. # should actually attempt a doRead/doWrite first. -glyph
  151. if isRead:
  152. if rw[_READ]:
  153. why = readWriteDescriptor.doRead()
  154. else:
  155. if rw[_WRITE]:
  156. why = readWriteDescriptor.doWrite()
  157. except:
  158. why = sys.exc_info()[1]
  159. log.err()
  160. if why:
  161. self._disconnectSelectable(readWriteDescriptor, why, isRead)
  162. log.callWithLogger(readWriteDescriptor, _drdw)
  163. def _watchFD(self, fd, descr, flag):
  164. """
  165. Register a file descriptor with the C{CFRunLoop}, or modify its state
  166. so that it's listening for both notifications (read and write) rather
  167. than just one; used to implement C{addReader} and C{addWriter}.
  168. @param fd: The file descriptor.
  169. @type fd: L{int}
  170. @param descr: the L{IReadDescriptor} or L{IWriteDescriptor}
  171. @param flag: the flag to register for callbacks on, either
  172. C{kCFSocketReadCallBack} or C{kCFSocketWriteCallBack}
  173. """
  174. if fd == -1:
  175. raise RuntimeError("Invalid file descriptor.")
  176. if fd in self._fdmap:
  177. src, cfs, gotdescr, rw = self._fdmap[fd]
  178. # do I need to verify that it's the same descr?
  179. else:
  180. ctx = []
  181. ctx.append(fd)
  182. cfs = CFSocketCreateWithNative(
  183. kCFAllocatorDefault, fd,
  184. kCFSocketReadCallBack | kCFSocketWriteCallBack |
  185. kCFSocketConnectCallBack,
  186. self._socketCallback, ctx
  187. )
  188. CFSocketSetSocketFlags(
  189. cfs,
  190. kCFSocketAutomaticallyReenableReadCallBack |
  191. kCFSocketAutomaticallyReenableWriteCallBack |
  192. # This extra flag is to ensure that CF doesn't (destructively,
  193. # because destructively is the only way to do it) retrieve
  194. # SO_ERROR and thereby break twisted.internet.tcp.BaseClient,
  195. # which needs SO_ERROR to tell it whether or not it needs to
  196. # call connect_ex a second time.
  197. _preserveSOError
  198. )
  199. src = CFSocketCreateRunLoopSource(kCFAllocatorDefault, cfs, 0)
  200. ctx.append(src)
  201. CFRunLoopAddSource(self._cfrunloop, src, kCFRunLoopCommonModes)
  202. CFSocketDisableCallBacks(
  203. cfs,
  204. kCFSocketReadCallBack | kCFSocketWriteCallBack |
  205. kCFSocketConnectCallBack
  206. )
  207. rw = [False, False]
  208. self._idmap[id(descr)] = fd
  209. self._fdmap[fd] = src, cfs, descr, rw
  210. rw[self._flag2idx(flag)] = True
  211. CFSocketEnableCallBacks(cfs, flag)
  212. def _flag2idx(self, flag):
  213. """
  214. Convert a C{kCFSocket...} constant to an index into the read/write
  215. state list (C{_READ} or C{_WRITE}) (the 4th element of the value of
  216. C{self._fdmap}).
  217. @param flag: C{kCFSocketReadCallBack} or C{kCFSocketWriteCallBack}
  218. @return: C{_READ} or C{_WRITE}
  219. """
  220. return {kCFSocketReadCallBack: _READ,
  221. kCFSocketWriteCallBack: _WRITE}[flag]
  222. def _unwatchFD(self, fd, descr, flag):
  223. """
  224. Unregister a file descriptor with the C{CFRunLoop}, or modify its state
  225. so that it's listening for only one notification (read or write) as
  226. opposed to both; used to implement C{removeReader} and C{removeWriter}.
  227. @param fd: a file descriptor
  228. @type fd: C{int}
  229. @param descr: an L{IReadDescriptor} or L{IWriteDescriptor}
  230. @param flag: C{kCFSocketWriteCallBack} C{kCFSocketReadCallBack}
  231. """
  232. if id(descr) not in self._idmap:
  233. return
  234. if fd == -1:
  235. # need to deal with it in this case, I think.
  236. realfd = self._idmap[id(descr)]
  237. else:
  238. realfd = fd
  239. src, cfs, descr, rw = self._fdmap[realfd]
  240. CFSocketDisableCallBacks(cfs, flag)
  241. rw[self._flag2idx(flag)] = False
  242. if not rw[_READ] and not rw[_WRITE]:
  243. del self._idmap[id(descr)]
  244. del self._fdmap[realfd]
  245. CFRunLoopRemoveSource(self._cfrunloop, src, kCFRunLoopCommonModes)
  246. CFSocketInvalidate(cfs)
  247. def addReader(self, reader):
  248. """
  249. Implement L{IReactorFDSet.addReader}.
  250. """
  251. self._watchFD(reader.fileno(), reader, kCFSocketReadCallBack)
  252. def addWriter(self, writer):
  253. """
  254. Implement L{IReactorFDSet.addWriter}.
  255. """
  256. self._watchFD(writer.fileno(), writer, kCFSocketWriteCallBack)
  257. def removeReader(self, reader):
  258. """
  259. Implement L{IReactorFDSet.removeReader}.
  260. """
  261. self._unwatchFD(reader.fileno(), reader, kCFSocketReadCallBack)
  262. def removeWriter(self, writer):
  263. """
  264. Implement L{IReactorFDSet.removeWriter}.
  265. """
  266. self._unwatchFD(writer.fileno(), writer, kCFSocketWriteCallBack)
  267. def removeAll(self):
  268. """
  269. Implement L{IReactorFDSet.removeAll}.
  270. """
  271. allDesc = set([descr for src, cfs, descr, rw in self._fdmap.values()])
  272. allDesc -= set(self._internalReaders)
  273. for desc in allDesc:
  274. self.removeReader(desc)
  275. self.removeWriter(desc)
  276. return list(allDesc)
  277. def getReaders(self):
  278. """
  279. Implement L{IReactorFDSet.getReaders}.
  280. """
  281. return [descr for src, cfs, descr, rw in self._fdmap.values()
  282. if rw[_READ]]
  283. def getWriters(self):
  284. """
  285. Implement L{IReactorFDSet.getWriters}.
  286. """
  287. return [descr for src, cfs, descr, rw in self._fdmap.values()
  288. if rw[_WRITE]]
  289. def _moveCallLaterSooner(self, tple):
  290. """
  291. Override L{PosixReactorBase}'s implementation of L{IDelayedCall.reset}
  292. so that it will immediately reschedule. Normally
  293. C{_moveCallLaterSooner} depends on the fact that C{runUntilCurrent} is
  294. always run before the mainloop goes back to sleep, so this forces it to
  295. immediately recompute how long the loop needs to stay asleep.
  296. """
  297. result = PosixReactorBase._moveCallLaterSooner(self, tple)
  298. self._scheduleSimulate()
  299. return result
  300. _inCFLoop = False
  301. def mainLoop(self):
  302. """
  303. Run the runner (C{CFRunLoopRun} or something that calls it), which runs
  304. the run loop until C{crash()} is called.
  305. """
  306. self._inCFLoop = True
  307. try:
  308. self._runner()
  309. finally:
  310. self._inCFLoop = False
  311. _currentSimulator = None
  312. def _scheduleSimulate(self, force=False):
  313. """
  314. Schedule a call to C{self.runUntilCurrent}. This will cancel the
  315. currently scheduled call if it is already scheduled.
  316. @param force: Even if there are no timed calls, make sure that
  317. C{runUntilCurrent} runs immediately (in a 0-seconds-from-now
  318. C{CFRunLoopTimer}). This is necessary for calls which need to
  319. trigger behavior of C{runUntilCurrent} other than running timed
  320. calls, such as draining the thread call queue or calling C{crash()}
  321. when the appropriate flags are set.
  322. @type force: C{bool}
  323. """
  324. if self._currentSimulator is not None:
  325. CFRunLoopTimerInvalidate(self._currentSimulator)
  326. self._currentSimulator = None
  327. timeout = self.timeout()
  328. if force:
  329. timeout = 0.0
  330. if timeout is not None:
  331. fireDate = (CFAbsoluteTimeGetCurrent() + timeout)
  332. def simulate(cftimer, extra):
  333. self._currentSimulator = None
  334. self.runUntilCurrent()
  335. self._scheduleSimulate()
  336. c = self._currentSimulator = CFRunLoopTimerCreate(
  337. kCFAllocatorDefault, fireDate,
  338. 0, 0, 0, simulate, None
  339. )
  340. CFRunLoopAddTimer(self._cfrunloop, c, kCFRunLoopCommonModes)
  341. def callLater(self, _seconds, _f, *args, **kw):
  342. """
  343. Implement L{IReactorTime.callLater}.
  344. """
  345. delayedCall = PosixReactorBase.callLater(
  346. self, _seconds, _f, *args, **kw
  347. )
  348. self._scheduleSimulate()
  349. return delayedCall
  350. def stop(self):
  351. """
  352. Implement L{IReactorCore.stop}.
  353. """
  354. PosixReactorBase.stop(self)
  355. self._scheduleSimulate(True)
  356. def crash(self):
  357. """
  358. Implement L{IReactorCore.crash}
  359. """
  360. wasStarted = self._started
  361. PosixReactorBase.crash(self)
  362. if self._inCFLoop:
  363. self._stopNow()
  364. else:
  365. if wasStarted:
  366. self.callLater(0, self._stopNow)
  367. def _stopNow(self):
  368. """
  369. Immediately stop the CFRunLoop (which must be running!).
  370. """
  371. CFRunLoopStop(self._cfrunloop)
  372. def iterate(self, delay=0):
  373. """
  374. Emulate the behavior of C{iterate()} for things that want to call it,
  375. by letting the loop run for a little while and then scheduling a timed
  376. call to exit it.
  377. """
  378. self.callLater(delay, self._stopNow)
  379. self.mainLoop()
  380. def install(runLoop=None, runner=None):
  381. """
  382. Configure the twisted mainloop to be run inside CFRunLoop.
  383. @param runLoop: the run loop to use.
  384. @param runner: the function to call in order to actually invoke the main
  385. loop. This will default to C{CFRunLoopRun} if not specified. However,
  386. this is not an appropriate choice for GUI applications, as you need to
  387. run NSApplicationMain (or something like it). For example, to run the
  388. Twisted mainloop in a PyObjC application, your C{main.py} should look
  389. something like this::
  390. from PyObjCTools import AppHelper
  391. from twisted.internet.cfreactor import install
  392. install(runner=AppHelper.runEventLoop)
  393. # initialize your application
  394. reactor.run()
  395. @return: The installed reactor.
  396. @rtype: C{CFReactor}
  397. """
  398. reactor = CFReactor(runLoop=runLoop, runner=runner)
  399. from twisted.internet.main import installReactor
  400. installReactor(reactor)
  401. return reactor