ioloop.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  1. #
  2. # Copyright 2009 Facebook
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. """An I/O event loop for non-blocking sockets.
  16. On Python 3, `.IOLoop` is a wrapper around the `asyncio` event loop.
  17. Typical applications will use a single `IOLoop` object, accessed via
  18. `IOLoop.current` class method. The `IOLoop.start` method (or
  19. equivalently, `asyncio.AbstractEventLoop.run_forever`) should usually
  20. be called at the end of the ``main()`` function. Atypical applications
  21. may use more than one `IOLoop`, such as one `IOLoop` per thread, or
  22. per `unittest` case.
  23. In addition to I/O events, the `IOLoop` can also schedule time-based
  24. events. `IOLoop.add_timeout` is a non-blocking alternative to
  25. `time.sleep`.
  26. """
  27. from __future__ import absolute_import, division, print_function
  28. import collections
  29. import datetime
  30. import errno
  31. import functools
  32. import heapq
  33. import itertools
  34. import logging
  35. import numbers
  36. import os
  37. import select
  38. import sys
  39. import threading
  40. import time
  41. import traceback
  42. import math
  43. import random
  44. from tornado.concurrent import Future, is_future, chain_future, future_set_exc_info, future_add_done_callback # noqa: E501
  45. from tornado.log import app_log, gen_log
  46. from tornado.platform.auto import set_close_exec, Waker
  47. from tornado import stack_context
  48. from tornado.util import (
  49. PY3, Configurable, errno_from_exception, timedelta_to_seconds,
  50. TimeoutError, unicode_type, import_object,
  51. )
  52. try:
  53. import signal
  54. except ImportError:
  55. signal = None
  56. try:
  57. from concurrent.futures import ThreadPoolExecutor
  58. except ImportError:
  59. ThreadPoolExecutor = None
  60. if PY3:
  61. import _thread as thread
  62. else:
  63. import thread
  64. try:
  65. import asyncio
  66. except ImportError:
  67. asyncio = None
  68. _POLL_TIMEOUT = 3600.0
  69. class IOLoop(Configurable):
  70. """A level-triggered I/O loop.
  71. On Python 3, `IOLoop` is a wrapper around the `asyncio` event
  72. loop. On Python 2, it uses ``epoll`` (Linux) or ``kqueue`` (BSD
  73. and Mac OS X) if they are available, or else we fall back on
  74. select(). If you are implementing a system that needs to handle
  75. thousands of simultaneous connections, you should use a system
  76. that supports either ``epoll`` or ``kqueue``.
  77. Example usage for a simple TCP server:
  78. .. testcode::
  79. import errno
  80. import functools
  81. import socket
  82. import tornado.ioloop
  83. from tornado.iostream import IOStream
  84. async def handle_connection(connection, address):
  85. stream = IOStream(connection)
  86. message = await stream.read_until_close()
  87. print("message from client:", message.decode().strip())
  88. def connection_ready(sock, fd, events):
  89. while True:
  90. try:
  91. connection, address = sock.accept()
  92. except socket.error as e:
  93. if e.args[0] not in (errno.EWOULDBLOCK, errno.EAGAIN):
  94. raise
  95. return
  96. connection.setblocking(0)
  97. io_loop = tornado.ioloop.IOLoop.current()
  98. io_loop.spawn_callback(handle_connection, connection, address)
  99. if __name__ == '__main__':
  100. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
  101. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  102. sock.setblocking(0)
  103. sock.bind(("", 8888))
  104. sock.listen(128)
  105. io_loop = tornado.ioloop.IOLoop.current()
  106. callback = functools.partial(connection_ready, sock)
  107. io_loop.add_handler(sock.fileno(), callback, io_loop.READ)
  108. io_loop.start()
  109. .. testoutput::
  110. :hide:
  111. By default, a newly-constructed `IOLoop` becomes the thread's current
  112. `IOLoop`, unless there already is a current `IOLoop`. This behavior
  113. can be controlled with the ``make_current`` argument to the `IOLoop`
  114. constructor: if ``make_current=True``, the new `IOLoop` will always
  115. try to become current and it raises an error if there is already a
  116. current instance. If ``make_current=False``, the new `IOLoop` will
  117. not try to become current.
  118. In general, an `IOLoop` cannot survive a fork or be shared across
  119. processes in any way. When multiple processes are being used, each
  120. process should create its own `IOLoop`, which also implies that
  121. any objects which depend on the `IOLoop` (such as
  122. `.AsyncHTTPClient`) must also be created in the child processes.
  123. As a guideline, anything that starts processes (including the
  124. `tornado.process` and `multiprocessing` modules) should do so as
  125. early as possible, ideally the first thing the application does
  126. after loading its configuration in ``main()``.
  127. .. versionchanged:: 4.2
  128. Added the ``make_current`` keyword argument to the `IOLoop`
  129. constructor.
  130. .. versionchanged:: 5.0
  131. Uses the `asyncio` event loop by default. The
  132. ``IOLoop.configure`` method cannot be used on Python 3 except
  133. to redundantly specify the `asyncio` event loop.
  134. """
  135. # Constants from the epoll module
  136. _EPOLLIN = 0x001
  137. _EPOLLPRI = 0x002
  138. _EPOLLOUT = 0x004
  139. _EPOLLERR = 0x008
  140. _EPOLLHUP = 0x010
  141. _EPOLLRDHUP = 0x2000
  142. _EPOLLONESHOT = (1 << 30)
  143. _EPOLLET = (1 << 31)
  144. # Our events map exactly to the epoll events
  145. NONE = 0
  146. READ = _EPOLLIN
  147. WRITE = _EPOLLOUT
  148. ERROR = _EPOLLERR | _EPOLLHUP
  149. # In Python 2, _current.instance points to the current IOLoop.
  150. _current = threading.local()
  151. # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.
  152. _ioloop_for_asyncio = dict()
  153. @classmethod
  154. def configure(cls, impl, **kwargs):
  155. if asyncio is not None:
  156. from tornado.platform.asyncio import BaseAsyncIOLoop
  157. if isinstance(impl, (str, unicode_type)):
  158. impl = import_object(impl)
  159. if not issubclass(impl, BaseAsyncIOLoop):
  160. raise RuntimeError(
  161. "only AsyncIOLoop is allowed when asyncio is available")
  162. super(IOLoop, cls).configure(impl, **kwargs)
  163. @staticmethod
  164. def instance():
  165. """Deprecated alias for `IOLoop.current()`.
  166. .. versionchanged:: 5.0
  167. Previously, this method returned a global singleton
  168. `IOLoop`, in contrast with the per-thread `IOLoop` returned
  169. by `current()`. In nearly all cases the two were the same
  170. (when they differed, it was generally used from non-Tornado
  171. threads to communicate back to the main thread's `IOLoop`).
  172. This distinction is not present in `asyncio`, so in order
  173. to facilitate integration with that package `instance()`
  174. was changed to be an alias to `current()`. Applications
  175. using the cross-thread communications aspect of
  176. `instance()` should instead set their own global variable
  177. to point to the `IOLoop` they want to use.
  178. .. deprecated:: 5.0
  179. """
  180. return IOLoop.current()
  181. def install(self):
  182. """Deprecated alias for `make_current()`.
  183. .. versionchanged:: 5.0
  184. Previously, this method would set this `IOLoop` as the
  185. global singleton used by `IOLoop.instance()`. Now that
  186. `instance()` is an alias for `current()`, `install()`
  187. is an alias for `make_current()`.
  188. .. deprecated:: 5.0
  189. """
  190. self.make_current()
  191. @staticmethod
  192. def clear_instance():
  193. """Deprecated alias for `clear_current()`.
  194. .. versionchanged:: 5.0
  195. Previously, this method would clear the `IOLoop` used as
  196. the global singleton by `IOLoop.instance()`. Now that
  197. `instance()` is an alias for `current()`,
  198. `clear_instance()` is an alias for `clear_current()`.
  199. .. deprecated:: 5.0
  200. """
  201. IOLoop.clear_current()
  202. @staticmethod
  203. def current(instance=True):
  204. """Returns the current thread's `IOLoop`.
  205. If an `IOLoop` is currently running or has been marked as
  206. current by `make_current`, returns that instance. If there is
  207. no current `IOLoop` and ``instance`` is true, creates one.
  208. .. versionchanged:: 4.1
  209. Added ``instance`` argument to control the fallback to
  210. `IOLoop.instance()`.
  211. .. versionchanged:: 5.0
  212. On Python 3, control of the current `IOLoop` is delegated
  213. to `asyncio`, with this and other methods as pass-through accessors.
  214. The ``instance`` argument now controls whether an `IOLoop`
  215. is created automatically when there is none, instead of
  216. whether we fall back to `IOLoop.instance()` (which is now
  217. an alias for this method). ``instance=False`` is deprecated,
  218. since even if we do not create an `IOLoop`, this method
  219. may initialize the asyncio loop.
  220. """
  221. if asyncio is None:
  222. current = getattr(IOLoop._current, "instance", None)
  223. if current is None and instance:
  224. current = IOLoop()
  225. if IOLoop._current.instance is not current:
  226. raise RuntimeError("new IOLoop did not become current")
  227. else:
  228. try:
  229. loop = asyncio.get_event_loop()
  230. except (RuntimeError, AssertionError):
  231. if not instance:
  232. return None
  233. raise
  234. try:
  235. return IOLoop._ioloop_for_asyncio[loop]
  236. except KeyError:
  237. if instance:
  238. from tornado.platform.asyncio import AsyncIOMainLoop
  239. current = AsyncIOMainLoop(make_current=True)
  240. else:
  241. current = None
  242. return current
  243. def make_current(self):
  244. """Makes this the `IOLoop` for the current thread.
  245. An `IOLoop` automatically becomes current for its thread
  246. when it is started, but it is sometimes useful to call
  247. `make_current` explicitly before starting the `IOLoop`,
  248. so that code run at startup time can find the right
  249. instance.
  250. .. versionchanged:: 4.1
  251. An `IOLoop` created while there is no current `IOLoop`
  252. will automatically become current.
  253. .. versionchanged:: 5.0
  254. This method also sets the current `asyncio` event loop.
  255. """
  256. # The asyncio event loops override this method.
  257. assert asyncio is None
  258. old = getattr(IOLoop._current, "instance", None)
  259. if old is not None:
  260. old.clear_current()
  261. IOLoop._current.instance = self
  262. @staticmethod
  263. def clear_current():
  264. """Clears the `IOLoop` for the current thread.
  265. Intended primarily for use by test frameworks in between tests.
  266. .. versionchanged:: 5.0
  267. This method also clears the current `asyncio` event loop.
  268. """
  269. old = IOLoop.current(instance=False)
  270. if old is not None:
  271. old._clear_current_hook()
  272. if asyncio is None:
  273. IOLoop._current.instance = None
  274. def _clear_current_hook(self):
  275. """Instance method called when an IOLoop ceases to be current.
  276. May be overridden by subclasses as a counterpart to make_current.
  277. """
  278. pass
  279. @classmethod
  280. def configurable_base(cls):
  281. return IOLoop
  282. @classmethod
  283. def configurable_default(cls):
  284. if asyncio is not None:
  285. from tornado.platform.asyncio import AsyncIOLoop
  286. return AsyncIOLoop
  287. return PollIOLoop
  288. def initialize(self, make_current=None):
  289. if make_current is None:
  290. if IOLoop.current(instance=False) is None:
  291. self.make_current()
  292. elif make_current:
  293. current = IOLoop.current(instance=False)
  294. # AsyncIO loops can already be current by this point.
  295. if current is not None and current is not self:
  296. raise RuntimeError("current IOLoop already exists")
  297. self.make_current()
  298. def close(self, all_fds=False):
  299. """Closes the `IOLoop`, freeing any resources used.
  300. If ``all_fds`` is true, all file descriptors registered on the
  301. IOLoop will be closed (not just the ones created by the
  302. `IOLoop` itself).
  303. Many applications will only use a single `IOLoop` that runs for the
  304. entire lifetime of the process. In that case closing the `IOLoop`
  305. is not necessary since everything will be cleaned up when the
  306. process exits. `IOLoop.close` is provided mainly for scenarios
  307. such as unit tests, which create and destroy a large number of
  308. ``IOLoops``.
  309. An `IOLoop` must be completely stopped before it can be closed. This
  310. means that `IOLoop.stop()` must be called *and* `IOLoop.start()` must
  311. be allowed to return before attempting to call `IOLoop.close()`.
  312. Therefore the call to `close` will usually appear just after
  313. the call to `start` rather than near the call to `stop`.
  314. .. versionchanged:: 3.1
  315. If the `IOLoop` implementation supports non-integer objects
  316. for "file descriptors", those objects will have their
  317. ``close`` method when ``all_fds`` is true.
  318. """
  319. raise NotImplementedError()
  320. def add_handler(self, fd, handler, events):
  321. """Registers the given handler to receive the given events for ``fd``.
  322. The ``fd`` argument may either be an integer file descriptor or
  323. a file-like object with a ``fileno()`` method (and optionally a
  324. ``close()`` method, which may be called when the `IOLoop` is shut
  325. down).
  326. The ``events`` argument is a bitwise or of the constants
  327. ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``.
  328. When an event occurs, ``handler(fd, events)`` will be run.
  329. .. versionchanged:: 4.0
  330. Added the ability to pass file-like objects in addition to
  331. raw file descriptors.
  332. """
  333. raise NotImplementedError()
  334. def update_handler(self, fd, events):
  335. """Changes the events we listen for ``fd``.
  336. .. versionchanged:: 4.0
  337. Added the ability to pass file-like objects in addition to
  338. raw file descriptors.
  339. """
  340. raise NotImplementedError()
  341. def remove_handler(self, fd):
  342. """Stop listening for events on ``fd``.
  343. .. versionchanged:: 4.0
  344. Added the ability to pass file-like objects in addition to
  345. raw file descriptors.
  346. """
  347. raise NotImplementedError()
  348. def set_blocking_signal_threshold(self, seconds, action):
  349. """Sends a signal if the `IOLoop` is blocked for more than
  350. ``s`` seconds.
  351. Pass ``seconds=None`` to disable. Requires Python 2.6 on a unixy
  352. platform.
  353. The action parameter is a Python signal handler. Read the
  354. documentation for the `signal` module for more information.
  355. If ``action`` is None, the process will be killed if it is
  356. blocked for too long.
  357. .. deprecated:: 5.0
  358. Not implemented on the `asyncio` event loop. Use the environment
  359. variable ``PYTHONASYNCIODEBUG=1`` instead. This method will be
  360. removed in Tornado 6.0.
  361. """
  362. raise NotImplementedError()
  363. def set_blocking_log_threshold(self, seconds):
  364. """Logs a stack trace if the `IOLoop` is blocked for more than
  365. ``s`` seconds.
  366. Equivalent to ``set_blocking_signal_threshold(seconds,
  367. self.log_stack)``
  368. .. deprecated:: 5.0
  369. Not implemented on the `asyncio` event loop. Use the environment
  370. variable ``PYTHONASYNCIODEBUG=1`` instead. This method will be
  371. removed in Tornado 6.0.
  372. """
  373. self.set_blocking_signal_threshold(seconds, self.log_stack)
  374. def log_stack(self, signal, frame):
  375. """Signal handler to log the stack trace of the current thread.
  376. For use with `set_blocking_signal_threshold`.
  377. .. deprecated:: 5.1
  378. This method will be removed in Tornado 6.0.
  379. """
  380. gen_log.warning('IOLoop blocked for %f seconds in\n%s',
  381. self._blocking_signal_threshold,
  382. ''.join(traceback.format_stack(frame)))
  383. def start(self):
  384. """Starts the I/O loop.
  385. The loop will run until one of the callbacks calls `stop()`, which
  386. will make the loop stop after the current event iteration completes.
  387. """
  388. raise NotImplementedError()
  389. def _setup_logging(self):
  390. """The IOLoop catches and logs exceptions, so it's
  391. important that log output be visible. However, python's
  392. default behavior for non-root loggers (prior to python
  393. 3.2) is to print an unhelpful "no handlers could be
  394. found" message rather than the actual log entry, so we
  395. must explicitly configure logging if we've made it this
  396. far without anything.
  397. This method should be called from start() in subclasses.
  398. """
  399. if not any([logging.getLogger().handlers,
  400. logging.getLogger('tornado').handlers,
  401. logging.getLogger('tornado.application').handlers]):
  402. logging.basicConfig()
  403. def stop(self):
  404. """Stop the I/O loop.
  405. If the event loop is not currently running, the next call to `start()`
  406. will return immediately.
  407. Note that even after `stop` has been called, the `IOLoop` is not
  408. completely stopped until `IOLoop.start` has also returned.
  409. Some work that was scheduled before the call to `stop` may still
  410. be run before the `IOLoop` shuts down.
  411. """
  412. raise NotImplementedError()
  413. def run_sync(self, func, timeout=None):
  414. """Starts the `IOLoop`, runs the given function, and stops the loop.
  415. The function must return either an awaitable object or
  416. ``None``. If the function returns an awaitable object, the
  417. `IOLoop` will run until the awaitable is resolved (and
  418. `run_sync()` will return the awaitable's result). If it raises
  419. an exception, the `IOLoop` will stop and the exception will be
  420. re-raised to the caller.
  421. The keyword-only argument ``timeout`` may be used to set
  422. a maximum duration for the function. If the timeout expires,
  423. a `tornado.util.TimeoutError` is raised.
  424. This method is useful to allow asynchronous calls in a
  425. ``main()`` function::
  426. async def main():
  427. # do stuff...
  428. if __name__ == '__main__':
  429. IOLoop.current().run_sync(main)
  430. .. versionchanged:: 4.3
  431. Returning a non-``None``, non-awaitable value is now an error.
  432. .. versionchanged:: 5.0
  433. If a timeout occurs, the ``func`` coroutine will be cancelled.
  434. """
  435. future_cell = [None]
  436. def run():
  437. try:
  438. result = func()
  439. if result is not None:
  440. from tornado.gen import convert_yielded
  441. result = convert_yielded(result)
  442. except Exception:
  443. future_cell[0] = Future()
  444. future_set_exc_info(future_cell[0], sys.exc_info())
  445. else:
  446. if is_future(result):
  447. future_cell[0] = result
  448. else:
  449. future_cell[0] = Future()
  450. future_cell[0].set_result(result)
  451. self.add_future(future_cell[0], lambda future: self.stop())
  452. self.add_callback(run)
  453. if timeout is not None:
  454. def timeout_callback():
  455. # If we can cancel the future, do so and wait on it. If not,
  456. # Just stop the loop and return with the task still pending.
  457. # (If we neither cancel nor wait for the task, a warning
  458. # will be logged).
  459. if not future_cell[0].cancel():
  460. self.stop()
  461. timeout_handle = self.add_timeout(self.time() + timeout, timeout_callback)
  462. self.start()
  463. if timeout is not None:
  464. self.remove_timeout(timeout_handle)
  465. if future_cell[0].cancelled() or not future_cell[0].done():
  466. raise TimeoutError('Operation timed out after %s seconds' % timeout)
  467. return future_cell[0].result()
  468. def time(self):
  469. """Returns the current time according to the `IOLoop`'s clock.
  470. The return value is a floating-point number relative to an
  471. unspecified time in the past.
  472. By default, the `IOLoop`'s time function is `time.time`. However,
  473. it may be configured to use e.g. `time.monotonic` instead.
  474. Calls to `add_timeout` that pass a number instead of a
  475. `datetime.timedelta` should use this function to compute the
  476. appropriate time, so they can work no matter what time function
  477. is chosen.
  478. """
  479. return time.time()
  480. def add_timeout(self, deadline, callback, *args, **kwargs):
  481. """Runs the ``callback`` at the time ``deadline`` from the I/O loop.
  482. Returns an opaque handle that may be passed to
  483. `remove_timeout` to cancel.
  484. ``deadline`` may be a number denoting a time (on the same
  485. scale as `IOLoop.time`, normally `time.time`), or a
  486. `datetime.timedelta` object for a deadline relative to the
  487. current time. Since Tornado 4.0, `call_later` is a more
  488. convenient alternative for the relative case since it does not
  489. require a timedelta object.
  490. Note that it is not safe to call `add_timeout` from other threads.
  491. Instead, you must use `add_callback` to transfer control to the
  492. `IOLoop`'s thread, and then call `add_timeout` from there.
  493. Subclasses of IOLoop must implement either `add_timeout` or
  494. `call_at`; the default implementations of each will call
  495. the other. `call_at` is usually easier to implement, but
  496. subclasses that wish to maintain compatibility with Tornado
  497. versions prior to 4.0 must use `add_timeout` instead.
  498. .. versionchanged:: 4.0
  499. Now passes through ``*args`` and ``**kwargs`` to the callback.
  500. """
  501. if isinstance(deadline, numbers.Real):
  502. return self.call_at(deadline, callback, *args, **kwargs)
  503. elif isinstance(deadline, datetime.timedelta):
  504. return self.call_at(self.time() + timedelta_to_seconds(deadline),
  505. callback, *args, **kwargs)
  506. else:
  507. raise TypeError("Unsupported deadline %r" % deadline)
  508. def call_later(self, delay, callback, *args, **kwargs):
  509. """Runs the ``callback`` after ``delay`` seconds have passed.
  510. Returns an opaque handle that may be passed to `remove_timeout`
  511. to cancel. Note that unlike the `asyncio` method of the same
  512. name, the returned object does not have a ``cancel()`` method.
  513. See `add_timeout` for comments on thread-safety and subclassing.
  514. .. versionadded:: 4.0
  515. """
  516. return self.call_at(self.time() + delay, callback, *args, **kwargs)
  517. def call_at(self, when, callback, *args, **kwargs):
  518. """Runs the ``callback`` at the absolute time designated by ``when``.
  519. ``when`` must be a number using the same reference point as
  520. `IOLoop.time`.
  521. Returns an opaque handle that may be passed to `remove_timeout`
  522. to cancel. Note that unlike the `asyncio` method of the same
  523. name, the returned object does not have a ``cancel()`` method.
  524. See `add_timeout` for comments on thread-safety and subclassing.
  525. .. versionadded:: 4.0
  526. """
  527. return self.add_timeout(when, callback, *args, **kwargs)
  528. def remove_timeout(self, timeout):
  529. """Cancels a pending timeout.
  530. The argument is a handle as returned by `add_timeout`. It is
  531. safe to call `remove_timeout` even if the callback has already
  532. been run.
  533. """
  534. raise NotImplementedError()
  535. def add_callback(self, callback, *args, **kwargs):
  536. """Calls the given callback on the next I/O loop iteration.
  537. It is safe to call this method from any thread at any time,
  538. except from a signal handler. Note that this is the **only**
  539. method in `IOLoop` that makes this thread-safety guarantee; all
  540. other interaction with the `IOLoop` must be done from that
  541. `IOLoop`'s thread. `add_callback()` may be used to transfer
  542. control from other threads to the `IOLoop`'s thread.
  543. To add a callback from a signal handler, see
  544. `add_callback_from_signal`.
  545. """
  546. raise NotImplementedError()
  547. def add_callback_from_signal(self, callback, *args, **kwargs):
  548. """Calls the given callback on the next I/O loop iteration.
  549. Safe for use from a Python signal handler; should not be used
  550. otherwise.
  551. Callbacks added with this method will be run without any
  552. `.stack_context`, to avoid picking up the context of the function
  553. that was interrupted by the signal.
  554. """
  555. raise NotImplementedError()
  556. def spawn_callback(self, callback, *args, **kwargs):
  557. """Calls the given callback on the next IOLoop iteration.
  558. Unlike all other callback-related methods on IOLoop,
  559. ``spawn_callback`` does not associate the callback with its caller's
  560. ``stack_context``, so it is suitable for fire-and-forget callbacks
  561. that should not interfere with the caller.
  562. .. versionadded:: 4.0
  563. """
  564. with stack_context.NullContext():
  565. self.add_callback(callback, *args, **kwargs)
  566. def add_future(self, future, callback):
  567. """Schedules a callback on the ``IOLoop`` when the given
  568. `.Future` is finished.
  569. The callback is invoked with one argument, the
  570. `.Future`.
  571. This method only accepts `.Future` objects and not other
  572. awaitables (unlike most of Tornado where the two are
  573. interchangeable).
  574. """
  575. assert is_future(future)
  576. callback = stack_context.wrap(callback)
  577. future_add_done_callback(
  578. future, lambda future: self.add_callback(callback, future))
  579. def run_in_executor(self, executor, func, *args):
  580. """Runs a function in a ``concurrent.futures.Executor``. If
  581. ``executor`` is ``None``, the IO loop's default executor will be used.
  582. Use `functools.partial` to pass keyword arguments to ``func``.
  583. .. versionadded:: 5.0
  584. """
  585. if ThreadPoolExecutor is None:
  586. raise RuntimeError(
  587. "concurrent.futures is required to use IOLoop.run_in_executor")
  588. if executor is None:
  589. if not hasattr(self, '_executor'):
  590. from tornado.process import cpu_count
  591. self._executor = ThreadPoolExecutor(max_workers=(cpu_count() * 5))
  592. executor = self._executor
  593. c_future = executor.submit(func, *args)
  594. # Concurrent Futures are not usable with await. Wrap this in a
  595. # Tornado Future instead, using self.add_future for thread-safety.
  596. t_future = Future()
  597. self.add_future(c_future, lambda f: chain_future(f, t_future))
  598. return t_future
  599. def set_default_executor(self, executor):
  600. """Sets the default executor to use with :meth:`run_in_executor`.
  601. .. versionadded:: 5.0
  602. """
  603. self._executor = executor
  604. def _run_callback(self, callback):
  605. """Runs a callback with error handling.
  606. For use in subclasses.
  607. """
  608. try:
  609. ret = callback()
  610. if ret is not None:
  611. from tornado import gen
  612. # Functions that return Futures typically swallow all
  613. # exceptions and store them in the Future. If a Future
  614. # makes it out to the IOLoop, ensure its exception (if any)
  615. # gets logged too.
  616. try:
  617. ret = gen.convert_yielded(ret)
  618. except gen.BadYieldError:
  619. # It's not unusual for add_callback to be used with
  620. # methods returning a non-None and non-yieldable
  621. # result, which should just be ignored.
  622. pass
  623. else:
  624. self.add_future(ret, self._discard_future_result)
  625. except Exception:
  626. self.handle_callback_exception(callback)
  627. def _discard_future_result(self, future):
  628. """Avoid unhandled-exception warnings from spawned coroutines."""
  629. future.result()
  630. def handle_callback_exception(self, callback):
  631. """This method is called whenever a callback run by the `IOLoop`
  632. throws an exception.
  633. By default simply logs the exception as an error. Subclasses
  634. may override this method to customize reporting of exceptions.
  635. The exception itself is not passed explicitly, but is available
  636. in `sys.exc_info`.
  637. .. versionchanged:: 5.0
  638. When the `asyncio` event loop is used (which is now the
  639. default on Python 3), some callback errors will be handled by
  640. `asyncio` instead of this method.
  641. .. deprecated: 5.1
  642. Support for this method will be removed in Tornado 6.0.
  643. """
  644. app_log.error("Exception in callback %r", callback, exc_info=True)
  645. def split_fd(self, fd):
  646. """Returns an (fd, obj) pair from an ``fd`` parameter.
  647. We accept both raw file descriptors and file-like objects as
  648. input to `add_handler` and related methods. When a file-like
  649. object is passed, we must retain the object itself so we can
  650. close it correctly when the `IOLoop` shuts down, but the
  651. poller interfaces favor file descriptors (they will accept
  652. file-like objects and call ``fileno()`` for you, but they
  653. always return the descriptor itself).
  654. This method is provided for use by `IOLoop` subclasses and should
  655. not generally be used by application code.
  656. .. versionadded:: 4.0
  657. """
  658. try:
  659. return fd.fileno(), fd
  660. except AttributeError:
  661. return fd, fd
  662. def close_fd(self, fd):
  663. """Utility method to close an ``fd``.
  664. If ``fd`` is a file-like object, we close it directly; otherwise
  665. we use `os.close`.
  666. This method is provided for use by `IOLoop` subclasses (in
  667. implementations of ``IOLoop.close(all_fds=True)`` and should
  668. not generally be used by application code.
  669. .. versionadded:: 4.0
  670. """
  671. try:
  672. try:
  673. fd.close()
  674. except AttributeError:
  675. os.close(fd)
  676. except OSError:
  677. pass
  678. class PollIOLoop(IOLoop):
  679. """Base class for IOLoops built around a select-like function.
  680. For concrete implementations, see `tornado.platform.epoll.EPollIOLoop`
  681. (Linux), `tornado.platform.kqueue.KQueueIOLoop` (BSD and Mac), or
  682. `tornado.platform.select.SelectIOLoop` (all platforms).
  683. """
  684. def initialize(self, impl, time_func=None, **kwargs):
  685. super(PollIOLoop, self).initialize(**kwargs)
  686. self._impl = impl
  687. if hasattr(self._impl, 'fileno'):
  688. set_close_exec(self._impl.fileno())
  689. self.time_func = time_func or time.time
  690. self._handlers = {}
  691. self._events = {}
  692. self._callbacks = collections.deque()
  693. self._timeouts = []
  694. self._cancellations = 0
  695. self._running = False
  696. self._stopped = False
  697. self._closing = False
  698. self._thread_ident = None
  699. self._pid = os.getpid()
  700. self._blocking_signal_threshold = None
  701. self._timeout_counter = itertools.count()
  702. # Create a pipe that we send bogus data to when we want to wake
  703. # the I/O loop when it is idle
  704. self._waker = Waker()
  705. self.add_handler(self._waker.fileno(),
  706. lambda fd, events: self._waker.consume(),
  707. self.READ)
  708. @classmethod
  709. def configurable_base(cls):
  710. return PollIOLoop
  711. @classmethod
  712. def configurable_default(cls):
  713. if hasattr(select, "epoll"):
  714. from tornado.platform.epoll import EPollIOLoop
  715. return EPollIOLoop
  716. if hasattr(select, "kqueue"):
  717. # Python 2.6+ on BSD or Mac
  718. from tornado.platform.kqueue import KQueueIOLoop
  719. return KQueueIOLoop
  720. from tornado.platform.select import SelectIOLoop
  721. return SelectIOLoop
  722. def close(self, all_fds=False):
  723. self._closing = True
  724. self.remove_handler(self._waker.fileno())
  725. if all_fds:
  726. for fd, handler in list(self._handlers.values()):
  727. self.close_fd(fd)
  728. self._waker.close()
  729. self._impl.close()
  730. self._callbacks = None
  731. self._timeouts = None
  732. if hasattr(self, '_executor'):
  733. self._executor.shutdown()
  734. def add_handler(self, fd, handler, events):
  735. fd, obj = self.split_fd(fd)
  736. self._handlers[fd] = (obj, stack_context.wrap(handler))
  737. self._impl.register(fd, events | self.ERROR)
  738. def update_handler(self, fd, events):
  739. fd, obj = self.split_fd(fd)
  740. self._impl.modify(fd, events | self.ERROR)
  741. def remove_handler(self, fd):
  742. fd, obj = self.split_fd(fd)
  743. self._handlers.pop(fd, None)
  744. self._events.pop(fd, None)
  745. try:
  746. self._impl.unregister(fd)
  747. except Exception:
  748. gen_log.debug("Error deleting fd from IOLoop", exc_info=True)
  749. def set_blocking_signal_threshold(self, seconds, action):
  750. if not hasattr(signal, "setitimer"):
  751. gen_log.error("set_blocking_signal_threshold requires a signal module "
  752. "with the setitimer method")
  753. return
  754. self._blocking_signal_threshold = seconds
  755. if seconds is not None:
  756. signal.signal(signal.SIGALRM,
  757. action if action is not None else signal.SIG_DFL)
  758. def start(self):
  759. if self._running:
  760. raise RuntimeError("IOLoop is already running")
  761. if os.getpid() != self._pid:
  762. raise RuntimeError("Cannot share PollIOLoops across processes")
  763. self._setup_logging()
  764. if self._stopped:
  765. self._stopped = False
  766. return
  767. old_current = IOLoop.current(instance=False)
  768. if old_current is not self:
  769. self.make_current()
  770. self._thread_ident = thread.get_ident()
  771. self._running = True
  772. # signal.set_wakeup_fd closes a race condition in event loops:
  773. # a signal may arrive at the beginning of select/poll/etc
  774. # before it goes into its interruptible sleep, so the signal
  775. # will be consumed without waking the select. The solution is
  776. # for the (C, synchronous) signal handler to write to a pipe,
  777. # which will then be seen by select.
  778. #
  779. # In python's signal handling semantics, this only matters on the
  780. # main thread (fortunately, set_wakeup_fd only works on the main
  781. # thread and will raise a ValueError otherwise).
  782. #
  783. # If someone has already set a wakeup fd, we don't want to
  784. # disturb it. This is an issue for twisted, which does its
  785. # SIGCHLD processing in response to its own wakeup fd being
  786. # written to. As long as the wakeup fd is registered on the IOLoop,
  787. # the loop will still wake up and everything should work.
  788. old_wakeup_fd = None
  789. if hasattr(signal, 'set_wakeup_fd') and os.name == 'posix':
  790. # requires python 2.6+, unix. set_wakeup_fd exists but crashes
  791. # the python process on windows.
  792. try:
  793. old_wakeup_fd = signal.set_wakeup_fd(self._waker.write_fileno())
  794. if old_wakeup_fd != -1:
  795. # Already set, restore previous value. This is a little racy,
  796. # but there's no clean get_wakeup_fd and in real use the
  797. # IOLoop is just started once at the beginning.
  798. signal.set_wakeup_fd(old_wakeup_fd)
  799. old_wakeup_fd = None
  800. except ValueError:
  801. # Non-main thread, or the previous value of wakeup_fd
  802. # is no longer valid.
  803. old_wakeup_fd = None
  804. try:
  805. while True:
  806. # Prevent IO event starvation by delaying new callbacks
  807. # to the next iteration of the event loop.
  808. ncallbacks = len(self._callbacks)
  809. # Add any timeouts that have come due to the callback list.
  810. # Do not run anything until we have determined which ones
  811. # are ready, so timeouts that call add_timeout cannot
  812. # schedule anything in this iteration.
  813. due_timeouts = []
  814. if self._timeouts:
  815. now = self.time()
  816. while self._timeouts:
  817. if self._timeouts[0].callback is None:
  818. # The timeout was cancelled. Note that the
  819. # cancellation check is repeated below for timeouts
  820. # that are cancelled by another timeout or callback.
  821. heapq.heappop(self._timeouts)
  822. self._cancellations -= 1
  823. elif self._timeouts[0].deadline <= now:
  824. due_timeouts.append(heapq.heappop(self._timeouts))
  825. else:
  826. break
  827. if (self._cancellations > 512 and
  828. self._cancellations > (len(self._timeouts) >> 1)):
  829. # Clean up the timeout queue when it gets large and it's
  830. # more than half cancellations.
  831. self._cancellations = 0
  832. self._timeouts = [x for x in self._timeouts
  833. if x.callback is not None]
  834. heapq.heapify(self._timeouts)
  835. for i in range(ncallbacks):
  836. self._run_callback(self._callbacks.popleft())
  837. for timeout in due_timeouts:
  838. if timeout.callback is not None:
  839. self._run_callback(timeout.callback)
  840. # Closures may be holding on to a lot of memory, so allow
  841. # them to be freed before we go into our poll wait.
  842. due_timeouts = timeout = None
  843. if self._callbacks:
  844. # If any callbacks or timeouts called add_callback,
  845. # we don't want to wait in poll() before we run them.
  846. poll_timeout = 0.0
  847. elif self._timeouts:
  848. # If there are any timeouts, schedule the first one.
  849. # Use self.time() instead of 'now' to account for time
  850. # spent running callbacks.
  851. poll_timeout = self._timeouts[0].deadline - self.time()
  852. poll_timeout = max(0, min(poll_timeout, _POLL_TIMEOUT))
  853. else:
  854. # No timeouts and no callbacks, so use the default.
  855. poll_timeout = _POLL_TIMEOUT
  856. if not self._running:
  857. break
  858. if self._blocking_signal_threshold is not None:
  859. # clear alarm so it doesn't fire while poll is waiting for
  860. # events.
  861. signal.setitimer(signal.ITIMER_REAL, 0, 0)
  862. try:
  863. event_pairs = self._impl.poll(poll_timeout)
  864. except Exception as e:
  865. # Depending on python version and IOLoop implementation,
  866. # different exception types may be thrown and there are
  867. # two ways EINTR might be signaled:
  868. # * e.errno == errno.EINTR
  869. # * e.args is like (errno.EINTR, 'Interrupted system call')
  870. if errno_from_exception(e) == errno.EINTR:
  871. continue
  872. else:
  873. raise
  874. if self._blocking_signal_threshold is not None:
  875. signal.setitimer(signal.ITIMER_REAL,
  876. self._blocking_signal_threshold, 0)
  877. # Pop one fd at a time from the set of pending fds and run
  878. # its handler. Since that handler may perform actions on
  879. # other file descriptors, there may be reentrant calls to
  880. # this IOLoop that modify self._events
  881. self._events.update(event_pairs)
  882. while self._events:
  883. fd, events = self._events.popitem()
  884. try:
  885. fd_obj, handler_func = self._handlers[fd]
  886. handler_func(fd_obj, events)
  887. except (OSError, IOError) as e:
  888. if errno_from_exception(e) == errno.EPIPE:
  889. # Happens when the client closes the connection
  890. pass
  891. else:
  892. self.handle_callback_exception(self._handlers.get(fd))
  893. except Exception:
  894. self.handle_callback_exception(self._handlers.get(fd))
  895. fd_obj = handler_func = None
  896. finally:
  897. # reset the stopped flag so another start/stop pair can be issued
  898. self._stopped = False
  899. if self._blocking_signal_threshold is not None:
  900. signal.setitimer(signal.ITIMER_REAL, 0, 0)
  901. if old_current is None:
  902. IOLoop.clear_current()
  903. elif old_current is not self:
  904. old_current.make_current()
  905. if old_wakeup_fd is not None:
  906. signal.set_wakeup_fd(old_wakeup_fd)
  907. def stop(self):
  908. self._running = False
  909. self._stopped = True
  910. self._waker.wake()
  911. def time(self):
  912. return self.time_func()
  913. def call_at(self, deadline, callback, *args, **kwargs):
  914. timeout = _Timeout(
  915. deadline,
  916. functools.partial(stack_context.wrap(callback), *args, **kwargs),
  917. self)
  918. heapq.heappush(self._timeouts, timeout)
  919. return timeout
  920. def remove_timeout(self, timeout):
  921. # Removing from a heap is complicated, so just leave the defunct
  922. # timeout object in the queue (see discussion in
  923. # http://docs.python.org/library/heapq.html).
  924. # If this turns out to be a problem, we could add a garbage
  925. # collection pass whenever there are too many dead timeouts.
  926. timeout.callback = None
  927. self._cancellations += 1
  928. def add_callback(self, callback, *args, **kwargs):
  929. if self._closing:
  930. return
  931. # Blindly insert into self._callbacks. This is safe even
  932. # from signal handlers because deque.append is atomic.
  933. self._callbacks.append(functools.partial(
  934. stack_context.wrap(callback), *args, **kwargs))
  935. if thread.get_ident() != self._thread_ident:
  936. # This will write one byte but Waker.consume() reads many
  937. # at once, so it's ok to write even when not strictly
  938. # necessary.
  939. self._waker.wake()
  940. else:
  941. # If we're on the IOLoop's thread, we don't need to wake anyone.
  942. pass
  943. def add_callback_from_signal(self, callback, *args, **kwargs):
  944. with stack_context.NullContext():
  945. self.add_callback(callback, *args, **kwargs)
  946. class _Timeout(object):
  947. """An IOLoop timeout, a UNIX timestamp and a callback"""
  948. # Reduce memory overhead when there are lots of pending callbacks
  949. __slots__ = ['deadline', 'callback', 'tdeadline']
  950. def __init__(self, deadline, callback, io_loop):
  951. if not isinstance(deadline, numbers.Real):
  952. raise TypeError("Unsupported deadline %r" % deadline)
  953. self.deadline = deadline
  954. self.callback = callback
  955. self.tdeadline = (deadline, next(io_loop._timeout_counter))
  956. # Comparison methods to sort by deadline, with object id as a tiebreaker
  957. # to guarantee a consistent ordering. The heapq module uses __le__
  958. # in python2.5, and __lt__ in 2.6+ (sort() and most other comparisons
  959. # use __lt__).
  960. def __lt__(self, other):
  961. return self.tdeadline < other.tdeadline
  962. def __le__(self, other):
  963. return self.tdeadline <= other.tdeadline
  964. class PeriodicCallback(object):
  965. """Schedules the given callback to be called periodically.
  966. The callback is called every ``callback_time`` milliseconds.
  967. Note that the timeout is given in milliseconds, while most other
  968. time-related functions in Tornado use seconds.
  969. If ``jitter`` is specified, each callback time will be randomly selected
  970. within a window of ``jitter * callback_time`` milliseconds.
  971. Jitter can be used to reduce alignment of events with similar periods.
  972. A jitter of 0.1 means allowing a 10% variation in callback time.
  973. The window is centered on ``callback_time`` so the total number of calls
  974. within a given interval should not be significantly affected by adding
  975. jitter.
  976. If the callback runs for longer than ``callback_time`` milliseconds,
  977. subsequent invocations will be skipped to get back on schedule.
  978. `start` must be called after the `PeriodicCallback` is created.
  979. .. versionchanged:: 5.0
  980. The ``io_loop`` argument (deprecated since version 4.1) has been removed.
  981. .. versionchanged:: 5.1
  982. The ``jitter`` argument is added.
  983. """
  984. def __init__(self, callback, callback_time, jitter=0):
  985. self.callback = callback
  986. if callback_time <= 0:
  987. raise ValueError("Periodic callback must have a positive callback_time")
  988. self.callback_time = callback_time
  989. self.jitter = jitter
  990. self._running = False
  991. self._timeout = None
  992. def start(self):
  993. """Starts the timer."""
  994. # Looking up the IOLoop here allows to first instantiate the
  995. # PeriodicCallback in another thread, then start it using
  996. # IOLoop.add_callback().
  997. self.io_loop = IOLoop.current()
  998. self._running = True
  999. self._next_timeout = self.io_loop.time()
  1000. self._schedule_next()
  1001. def stop(self):
  1002. """Stops the timer."""
  1003. self._running = False
  1004. if self._timeout is not None:
  1005. self.io_loop.remove_timeout(self._timeout)
  1006. self._timeout = None
  1007. def is_running(self):
  1008. """Return True if this `.PeriodicCallback` has been started.
  1009. .. versionadded:: 4.1
  1010. """
  1011. return self._running
  1012. def _run(self):
  1013. if not self._running:
  1014. return
  1015. try:
  1016. return self.callback()
  1017. except Exception:
  1018. self.io_loop.handle_callback_exception(self.callback)
  1019. finally:
  1020. self._schedule_next()
  1021. def _schedule_next(self):
  1022. if self._running:
  1023. self._update_next(self.io_loop.time())
  1024. self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)
  1025. def _update_next(self, current_time):
  1026. callback_time_sec = self.callback_time / 1000.0
  1027. if self.jitter:
  1028. # apply jitter fraction
  1029. callback_time_sec *= 1 + (self.jitter * (random.random() - 0.5))
  1030. if self._next_timeout <= current_time:
  1031. # The period should be measured from the start of one call
  1032. # to the start of the next. If one call takes too long,
  1033. # skip cycles to get back to a multiple of the original
  1034. # schedule.
  1035. self._next_timeout += (math.floor((current_time - self._next_timeout) /
  1036. callback_time_sec) + 1) * callback_time_sec
  1037. else:
  1038. # If the clock moved backwards, ensure we advance the next
  1039. # timeout instead of recomputing the same value again.
  1040. # This may result in long gaps between callbacks if the
  1041. # clock jumps backwards by a lot, but the far more common
  1042. # scenario is a small NTP adjustment that should just be
  1043. # ignored.
  1044. #
  1045. # Note that on some systems if time.time() runs slower
  1046. # than time.monotonic() (most common on windows), we
  1047. # effectively experience a small backwards time jump on
  1048. # every iteration because PeriodicCallback uses
  1049. # time.time() while asyncio schedules callbacks using
  1050. # time.monotonic().
  1051. # https://github.com/tornadoweb/tornado/issues/2333
  1052. self._next_timeout += callback_time_sec