ioloop.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  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. In Tornado 6.0, `.IOLoop` is a wrapper around the `asyncio` event loop, with a
  17. slightly different interface. The `.IOLoop` interface is now provided primarily
  18. for backwards compatibility; new code should generally use the `asyncio` event
  19. loop interface directly. The `IOLoop.current` class method provides the
  20. `IOLoop` instance corresponding to the running `asyncio` event loop.
  21. """
  22. import asyncio
  23. import concurrent.futures
  24. import datetime
  25. import functools
  26. import numbers
  27. import os
  28. import sys
  29. import time
  30. import math
  31. import random
  32. import warnings
  33. from inspect import isawaitable
  34. from tornado.concurrent import (
  35. Future,
  36. is_future,
  37. chain_future,
  38. future_set_exc_info,
  39. future_add_done_callback,
  40. )
  41. from tornado.log import app_log
  42. from tornado.util import Configurable, TimeoutError, import_object
  43. import typing
  44. from typing import Union, Any, Type, Optional, Callable, TypeVar, Tuple, Awaitable
  45. if typing.TYPE_CHECKING:
  46. from typing import Dict, List, Set, TypedDict # noqa: F401
  47. from typing_extensions import Protocol
  48. else:
  49. Protocol = object
  50. class _Selectable(Protocol):
  51. def fileno(self) -> int:
  52. pass
  53. def close(self) -> None:
  54. pass
  55. _T = TypeVar("_T")
  56. _S = TypeVar("_S", bound=_Selectable)
  57. class IOLoop(Configurable):
  58. """An I/O event loop.
  59. As of Tornado 6.0, `IOLoop` is a wrapper around the `asyncio` event loop.
  60. Example usage for a simple TCP server:
  61. .. testcode::
  62. import asyncio
  63. import errno
  64. import functools
  65. import socket
  66. import tornado
  67. from tornado.iostream import IOStream
  68. async def handle_connection(connection, address):
  69. stream = IOStream(connection)
  70. message = await stream.read_until_close()
  71. print("message from client:", message.decode().strip())
  72. def connection_ready(sock, fd, events):
  73. while True:
  74. try:
  75. connection, address = sock.accept()
  76. except BlockingIOError:
  77. return
  78. connection.setblocking(0)
  79. io_loop = tornado.ioloop.IOLoop.current()
  80. io_loop.spawn_callback(handle_connection, connection, address)
  81. async def main():
  82. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
  83. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  84. sock.setblocking(0)
  85. sock.bind(("", 8888))
  86. sock.listen(128)
  87. io_loop = tornado.ioloop.IOLoop.current()
  88. callback = functools.partial(connection_ready, sock)
  89. io_loop.add_handler(sock.fileno(), callback, io_loop.READ)
  90. await asyncio.Event().wait()
  91. if __name__ == "__main__":
  92. asyncio.run(main())
  93. Most applications should not attempt to construct an `IOLoop` directly,
  94. and instead initialize the `asyncio` event loop and use `IOLoop.current()`.
  95. In some cases, such as in test frameworks when initializing an `IOLoop`
  96. to be run in a secondary thread, it may be appropriate to construct
  97. an `IOLoop` with ``IOLoop(make_current=False)``.
  98. In general, an `IOLoop` cannot survive a fork or be shared across processes
  99. in any way. When multiple processes are being used, each process should
  100. create its own `IOLoop`, which also implies that any objects which depend on
  101. the `IOLoop` (such as `.AsyncHTTPClient`) must also be created in the child
  102. processes. As a guideline, anything that starts processes (including the
  103. `tornado.process` and `multiprocessing` modules) should do so as early as
  104. possible, ideally the first thing the application does after loading its
  105. configuration, and *before* any calls to `.IOLoop.start` or `asyncio.run`.
  106. .. versionchanged:: 4.2
  107. Added the ``make_current`` keyword argument to the `IOLoop`
  108. constructor.
  109. .. versionchanged:: 5.0
  110. Uses the `asyncio` event loop by default. The ``IOLoop.configure`` method
  111. cannot be used on Python 3 except to redundantly specify the `asyncio`
  112. event loop.
  113. .. versionchanged:: 6.3
  114. ``make_current=True`` is now the default when creating an IOLoop -
  115. previously the default was to make the event loop current if there wasn't
  116. already a current one.
  117. """
  118. # These constants were originally based on constants from the epoll module.
  119. NONE = 0
  120. READ = 0x001
  121. WRITE = 0x004
  122. ERROR = 0x018
  123. # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.
  124. _ioloop_for_asyncio = dict() # type: Dict[asyncio.AbstractEventLoop, IOLoop]
  125. # Maintain a set of all pending tasks to follow the warning in the docs
  126. # of asyncio.create_tasks:
  127. # https://docs.python.org/3.11/library/asyncio-task.html#asyncio.create_task
  128. # This ensures that all pending tasks have a strong reference so they
  129. # will not be garbage collected before they are finished.
  130. # (Thus avoiding "task was destroyed but it is pending" warnings)
  131. # An analogous change has been proposed in cpython for 3.13:
  132. # https://github.com/python/cpython/issues/91887
  133. # If that change is accepted, this can eventually be removed.
  134. # If it is not, we will consider the rationale and may remove this.
  135. _pending_tasks = set() # type: Set[Future]
  136. @classmethod
  137. def configure(
  138. cls, impl: "Union[None, str, Type[Configurable]]", **kwargs: Any
  139. ) -> None:
  140. from tornado.platform.asyncio import BaseAsyncIOLoop
  141. if isinstance(impl, str):
  142. impl = import_object(impl)
  143. if isinstance(impl, type) and not issubclass(impl, BaseAsyncIOLoop):
  144. raise RuntimeError("only AsyncIOLoop is allowed when asyncio is available")
  145. super().configure(impl, **kwargs)
  146. @staticmethod
  147. def instance() -> "IOLoop":
  148. """Deprecated alias for `IOLoop.current()`.
  149. .. versionchanged:: 5.0
  150. Previously, this method returned a global singleton
  151. `IOLoop`, in contrast with the per-thread `IOLoop` returned
  152. by `current()`. In nearly all cases the two were the same
  153. (when they differed, it was generally used from non-Tornado
  154. threads to communicate back to the main thread's `IOLoop`).
  155. This distinction is not present in `asyncio`, so in order
  156. to facilitate integration with that package `instance()`
  157. was changed to be an alias to `current()`. Applications
  158. using the cross-thread communications aspect of
  159. `instance()` should instead set their own global variable
  160. to point to the `IOLoop` they want to use.
  161. .. deprecated:: 5.0
  162. """
  163. return IOLoop.current()
  164. def install(self) -> None:
  165. """Deprecated alias for `make_current()`.
  166. .. versionchanged:: 5.0
  167. Previously, this method would set this `IOLoop` as the
  168. global singleton used by `IOLoop.instance()`. Now that
  169. `instance()` is an alias for `current()`, `install()`
  170. is an alias for `make_current()`.
  171. .. deprecated:: 5.0
  172. """
  173. self.make_current()
  174. @staticmethod
  175. def clear_instance() -> None:
  176. """Deprecated alias for `clear_current()`.
  177. .. versionchanged:: 5.0
  178. Previously, this method would clear the `IOLoop` used as
  179. the global singleton by `IOLoop.instance()`. Now that
  180. `instance()` is an alias for `current()`,
  181. `clear_instance()` is an alias for `clear_current()`.
  182. .. deprecated:: 5.0
  183. """
  184. IOLoop.clear_current()
  185. @typing.overload
  186. @staticmethod
  187. def current() -> "IOLoop":
  188. pass
  189. @typing.overload
  190. @staticmethod
  191. def current(instance: bool = True) -> Optional["IOLoop"]: # noqa: F811
  192. pass
  193. @staticmethod
  194. def current(instance: bool = True) -> Optional["IOLoop"]: # noqa: F811
  195. """Returns the current thread's `IOLoop`.
  196. If an `IOLoop` is currently running or has been marked as
  197. current by `make_current`, returns that instance. If there is
  198. no current `IOLoop` and ``instance`` is true, creates one.
  199. .. versionchanged:: 4.1
  200. Added ``instance`` argument to control the fallback to
  201. `IOLoop.instance()`.
  202. .. versionchanged:: 5.0
  203. On Python 3, control of the current `IOLoop` is delegated
  204. to `asyncio`, with this and other methods as pass-through accessors.
  205. The ``instance`` argument now controls whether an `IOLoop`
  206. is created automatically when there is none, instead of
  207. whether we fall back to `IOLoop.instance()` (which is now
  208. an alias for this method). ``instance=False`` is deprecated,
  209. since even if we do not create an `IOLoop`, this method
  210. may initialize the asyncio loop.
  211. .. deprecated:: 6.2
  212. It is deprecated to call ``IOLoop.current()`` when no `asyncio`
  213. event loop is running.
  214. """
  215. try:
  216. loop = asyncio.get_event_loop()
  217. except RuntimeError:
  218. if not instance:
  219. return None
  220. # Create a new asyncio event loop for this thread.
  221. loop = asyncio.new_event_loop()
  222. asyncio.set_event_loop(loop)
  223. try:
  224. return IOLoop._ioloop_for_asyncio[loop]
  225. except KeyError:
  226. if instance:
  227. from tornado.platform.asyncio import AsyncIOMainLoop
  228. current = AsyncIOMainLoop() # type: Optional[IOLoop]
  229. else:
  230. current = None
  231. return current
  232. def make_current(self) -> None:
  233. """Makes this the `IOLoop` for the current thread.
  234. An `IOLoop` automatically becomes current for its thread
  235. when it is started, but it is sometimes useful to call
  236. `make_current` explicitly before starting the `IOLoop`,
  237. so that code run at startup time can find the right
  238. instance.
  239. .. versionchanged:: 4.1
  240. An `IOLoop` created while there is no current `IOLoop`
  241. will automatically become current.
  242. .. versionchanged:: 5.0
  243. This method also sets the current `asyncio` event loop.
  244. .. deprecated:: 6.2
  245. Setting and clearing the current event loop through Tornado is
  246. deprecated. Use ``asyncio.set_event_loop`` instead if you need this.
  247. """
  248. warnings.warn(
  249. "make_current is deprecated; start the event loop first",
  250. DeprecationWarning,
  251. stacklevel=2,
  252. )
  253. self._make_current()
  254. def _make_current(self) -> None:
  255. # The asyncio event loops override this method.
  256. raise NotImplementedError()
  257. @staticmethod
  258. def clear_current() -> None:
  259. """Clears the `IOLoop` for the current thread.
  260. Intended primarily for use by test frameworks in between tests.
  261. .. versionchanged:: 5.0
  262. This method also clears the current `asyncio` event loop.
  263. .. deprecated:: 6.2
  264. """
  265. warnings.warn(
  266. "clear_current is deprecated",
  267. DeprecationWarning,
  268. stacklevel=2,
  269. )
  270. IOLoop._clear_current()
  271. @staticmethod
  272. def _clear_current() -> None:
  273. old = IOLoop.current(instance=False)
  274. if old is not None:
  275. old._clear_current_hook()
  276. def _clear_current_hook(self) -> None:
  277. """Instance method called when an IOLoop ceases to be current.
  278. May be overridden by subclasses as a counterpart to make_current.
  279. """
  280. pass
  281. @classmethod
  282. def configurable_base(cls) -> Type[Configurable]:
  283. return IOLoop
  284. @classmethod
  285. def configurable_default(cls) -> Type[Configurable]:
  286. from tornado.platform.asyncio import AsyncIOLoop
  287. return AsyncIOLoop
  288. def initialize(self, make_current: bool = True) -> None:
  289. if make_current:
  290. self._make_current()
  291. def close(self, all_fds: bool = False) -> None:
  292. """Closes the `IOLoop`, freeing any resources used.
  293. If ``all_fds`` is true, all file descriptors registered on the
  294. IOLoop will be closed (not just the ones created by the
  295. `IOLoop` itself).
  296. Many applications will only use a single `IOLoop` that runs for the
  297. entire lifetime of the process. In that case closing the `IOLoop`
  298. is not necessary since everything will be cleaned up when the
  299. process exits. `IOLoop.close` is provided mainly for scenarios
  300. such as unit tests, which create and destroy a large number of
  301. ``IOLoops``.
  302. An `IOLoop` must be completely stopped before it can be closed. This
  303. means that `IOLoop.stop()` must be called *and* `IOLoop.start()` must
  304. be allowed to return before attempting to call `IOLoop.close()`.
  305. Therefore the call to `close` will usually appear just after
  306. the call to `start` rather than near the call to `stop`.
  307. .. versionchanged:: 3.1
  308. If the `IOLoop` implementation supports non-integer objects
  309. for "file descriptors", those objects will have their
  310. ``close`` method when ``all_fds`` is true.
  311. """
  312. raise NotImplementedError()
  313. @typing.overload
  314. def add_handler(
  315. self, fd: int, handler: Callable[[int, int], None], events: int
  316. ) -> None:
  317. pass
  318. @typing.overload # noqa: F811
  319. def add_handler(
  320. self, fd: _S, handler: Callable[[_S, int], None], events: int
  321. ) -> None:
  322. pass
  323. def add_handler( # noqa: F811
  324. self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int
  325. ) -> None:
  326. """Registers the given handler to receive the given events for ``fd``.
  327. The ``fd`` argument may either be an integer file descriptor or
  328. a file-like object with a ``fileno()`` and ``close()`` method.
  329. The ``events`` argument is a bitwise or of the constants
  330. ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``.
  331. When an event occurs, ``handler(fd, events)`` will be run.
  332. .. versionchanged:: 4.0
  333. Added the ability to pass file-like objects in addition to
  334. raw file descriptors.
  335. """
  336. raise NotImplementedError()
  337. def update_handler(self, fd: Union[int, _Selectable], events: int) -> None:
  338. """Changes the events we listen for ``fd``.
  339. .. versionchanged:: 4.0
  340. Added the ability to pass file-like objects in addition to
  341. raw file descriptors.
  342. """
  343. raise NotImplementedError()
  344. def remove_handler(self, fd: Union[int, _Selectable]) -> None:
  345. """Stop listening for events on ``fd``.
  346. .. versionchanged:: 4.0
  347. Added the ability to pass file-like objects in addition to
  348. raw file descriptors.
  349. """
  350. raise NotImplementedError()
  351. def start(self) -> None:
  352. """Starts the I/O loop.
  353. The loop will run until one of the callbacks calls `stop()`, which
  354. will make the loop stop after the current event iteration completes.
  355. """
  356. raise NotImplementedError()
  357. def stop(self) -> None:
  358. """Stop the I/O loop.
  359. If the event loop is not currently running, the next call to `start()`
  360. will return immediately.
  361. Note that even after `stop` has been called, the `IOLoop` is not
  362. completely stopped until `IOLoop.start` has also returned.
  363. Some work that was scheduled before the call to `stop` may still
  364. be run before the `IOLoop` shuts down.
  365. """
  366. raise NotImplementedError()
  367. def run_sync(self, func: Callable, timeout: Optional[float] = None) -> Any:
  368. """Starts the `IOLoop`, runs the given function, and stops the loop.
  369. The function must return either an awaitable object or
  370. ``None``. If the function returns an awaitable object, the
  371. `IOLoop` will run until the awaitable is resolved (and
  372. `run_sync()` will return the awaitable's result). If it raises
  373. an exception, the `IOLoop` will stop and the exception will be
  374. re-raised to the caller.
  375. The keyword-only argument ``timeout`` may be used to set
  376. a maximum duration for the function. If the timeout expires,
  377. a `asyncio.TimeoutError` is raised.
  378. This method is useful to allow asynchronous calls in a
  379. ``main()`` function::
  380. async def main():
  381. # do stuff...
  382. if __name__ == '__main__':
  383. IOLoop.current().run_sync(main)
  384. .. versionchanged:: 4.3
  385. Returning a non-``None``, non-awaitable value is now an error.
  386. .. versionchanged:: 5.0
  387. If a timeout occurs, the ``func`` coroutine will be cancelled.
  388. .. versionchanged:: 6.2
  389. ``tornado.util.TimeoutError`` is now an alias to ``asyncio.TimeoutError``.
  390. """
  391. if typing.TYPE_CHECKING:
  392. FutureCell = TypedDict( # noqa: F841
  393. "FutureCell", {"future": Optional[Future], "timeout_called": bool}
  394. )
  395. future_cell = {"future": None, "timeout_called": False} # type: FutureCell
  396. def run() -> None:
  397. try:
  398. result = func()
  399. if result is not None:
  400. from tornado.gen import convert_yielded
  401. result = convert_yielded(result)
  402. except Exception:
  403. fut = Future() # type: Future[Any]
  404. future_cell["future"] = fut
  405. future_set_exc_info(fut, sys.exc_info())
  406. else:
  407. if is_future(result):
  408. future_cell["future"] = result
  409. else:
  410. fut = Future()
  411. future_cell["future"] = fut
  412. fut.set_result(result)
  413. assert future_cell["future"] is not None
  414. self.add_future(future_cell["future"], lambda future: self.stop())
  415. self.add_callback(run)
  416. if timeout is not None:
  417. def timeout_callback() -> None:
  418. # signal that timeout is triggered
  419. future_cell["timeout_called"] = True
  420. # If we can cancel the future, do so and wait on it. If not,
  421. # Just stop the loop and return with the task still pending.
  422. # (If we neither cancel nor wait for the task, a warning
  423. # will be logged).
  424. assert future_cell["future"] is not None
  425. if not future_cell["future"].cancel():
  426. self.stop()
  427. timeout_handle = self.add_timeout(self.time() + timeout, timeout_callback)
  428. self.start()
  429. if timeout is not None:
  430. self.remove_timeout(timeout_handle)
  431. assert future_cell["future"] is not None
  432. if future_cell["future"].cancelled() or not future_cell["future"].done():
  433. if future_cell["timeout_called"]:
  434. raise TimeoutError("Operation timed out after %s seconds" % timeout)
  435. else:
  436. # timeout not called; maybe stop() was called explicitly
  437. # or some other cancellation
  438. raise RuntimeError("Event loop stopped before Future completed.")
  439. return future_cell["future"].result()
  440. def time(self) -> float:
  441. """Returns the current time according to the `IOLoop`'s clock.
  442. The return value is a floating-point number relative to an
  443. unspecified time in the past.
  444. Historically, the IOLoop could be customized to use e.g.
  445. `time.monotonic` instead of `time.time`, but this is not
  446. currently supported and so this method is equivalent to
  447. `time.time`.
  448. """
  449. return time.time()
  450. def add_timeout(
  451. self,
  452. deadline: Union[float, datetime.timedelta],
  453. callback: Callable,
  454. *args: Any,
  455. **kwargs: Any,
  456. ) -> object:
  457. """Runs the ``callback`` at the time ``deadline`` from the I/O loop.
  458. Returns an opaque handle that may be passed to
  459. `remove_timeout` to cancel.
  460. ``deadline`` may be a number denoting a time (on the same
  461. scale as `IOLoop.time`, normally `time.time`), or a
  462. `datetime.timedelta` object for a deadline relative to the
  463. current time. Since Tornado 4.0, `call_later` is a more
  464. convenient alternative for the relative case since it does not
  465. require a timedelta object.
  466. Note that it is not safe to call `add_timeout` from other threads.
  467. Instead, you must use `add_callback` to transfer control to the
  468. `IOLoop`'s thread, and then call `add_timeout` from there.
  469. Subclasses of IOLoop must implement either `add_timeout` or
  470. `call_at`; the default implementations of each will call
  471. the other. `call_at` is usually easier to implement, but
  472. subclasses that wish to maintain compatibility with Tornado
  473. versions prior to 4.0 must use `add_timeout` instead.
  474. .. versionchanged:: 4.0
  475. Now passes through ``*args`` and ``**kwargs`` to the callback.
  476. """
  477. if isinstance(deadline, numbers.Real):
  478. return self.call_at(deadline, callback, *args, **kwargs)
  479. elif isinstance(deadline, datetime.timedelta):
  480. return self.call_at(
  481. self.time() + deadline.total_seconds(), callback, *args, **kwargs
  482. )
  483. else:
  484. raise TypeError("Unsupported deadline %r" % deadline)
  485. def call_later(
  486. self, delay: float, callback: Callable, *args: Any, **kwargs: Any
  487. ) -> object:
  488. """Runs the ``callback`` after ``delay`` seconds have passed.
  489. Returns an opaque handle that may be passed to `remove_timeout`
  490. to cancel. Note that unlike the `asyncio` method of the same
  491. name, the returned object does not have a ``cancel()`` method.
  492. See `add_timeout` for comments on thread-safety and subclassing.
  493. .. versionadded:: 4.0
  494. """
  495. return self.call_at(self.time() + delay, callback, *args, **kwargs)
  496. def call_at(
  497. self, when: float, callback: Callable, *args: Any, **kwargs: Any
  498. ) -> object:
  499. """Runs the ``callback`` at the absolute time designated by ``when``.
  500. ``when`` must be a number using the same reference point as
  501. `IOLoop.time`.
  502. Returns an opaque handle that may be passed to `remove_timeout`
  503. to cancel. Note that unlike the `asyncio` method of the same
  504. name, the returned object does not have a ``cancel()`` method.
  505. See `add_timeout` for comments on thread-safety and subclassing.
  506. .. versionadded:: 4.0
  507. """
  508. return self.add_timeout(when, callback, *args, **kwargs)
  509. def remove_timeout(self, timeout: object) -> None:
  510. """Cancels a pending timeout.
  511. The argument is a handle as returned by `add_timeout`. It is
  512. safe to call `remove_timeout` even if the callback has already
  513. been run.
  514. """
  515. raise NotImplementedError()
  516. def add_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:
  517. """Calls the given callback on the next I/O loop iteration.
  518. It is safe to call this method from any thread at any time,
  519. except from a signal handler. Note that this is the **only**
  520. method in `IOLoop` that makes this thread-safety guarantee; all
  521. other interaction with the `IOLoop` must be done from that
  522. `IOLoop`'s thread. `add_callback()` may be used to transfer
  523. control from other threads to the `IOLoop`'s thread.
  524. """
  525. raise NotImplementedError()
  526. def add_callback_from_signal(
  527. self, callback: Callable, *args: Any, **kwargs: Any
  528. ) -> None:
  529. """Calls the given callback on the next I/O loop iteration.
  530. Intended to be afe for use from a Python signal handler; should not be
  531. used otherwise.
  532. .. deprecated:: 6.4
  533. Use ``asyncio.AbstractEventLoop.add_signal_handler`` instead.
  534. This method is suspected to have been broken since Tornado 5.0 and
  535. will be removed in version 7.0.
  536. """
  537. raise NotImplementedError()
  538. def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:
  539. """Calls the given callback on the next IOLoop iteration.
  540. As of Tornado 6.0, this method is equivalent to `add_callback`.
  541. .. versionadded:: 4.0
  542. """
  543. self.add_callback(callback, *args, **kwargs)
  544. def add_future(
  545. self,
  546. future: "Union[Future[_T], concurrent.futures.Future[_T]]",
  547. callback: Callable[["Future[_T]"], None],
  548. ) -> None:
  549. """Schedules a callback on the ``IOLoop`` when the given
  550. `.Future` is finished.
  551. The callback is invoked with one argument, the
  552. `.Future`.
  553. This method only accepts `.Future` objects and not other
  554. awaitables (unlike most of Tornado where the two are
  555. interchangeable).
  556. """
  557. if isinstance(future, Future):
  558. # Note that we specifically do not want the inline behavior of
  559. # tornado.concurrent.future_add_done_callback. We always want
  560. # this callback scheduled on the next IOLoop iteration (which
  561. # asyncio.Future always does).
  562. #
  563. # Wrap the callback in self._run_callback so we control
  564. # the error logging (i.e. it goes to tornado.log.app_log
  565. # instead of asyncio's log).
  566. future.add_done_callback(
  567. lambda f: self._run_callback(functools.partial(callback, f))
  568. )
  569. else:
  570. assert is_future(future)
  571. # For concurrent futures, we use self.add_callback, so
  572. # it's fine if future_add_done_callback inlines that call.
  573. future_add_done_callback(future, lambda f: self.add_callback(callback, f))
  574. def run_in_executor(
  575. self,
  576. executor: Optional[concurrent.futures.Executor],
  577. func: Callable[..., _T],
  578. *args: Any,
  579. ) -> "Future[_T]":
  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 executor is None:
  586. if not hasattr(self, "_executor"):
  587. from tornado.process import cpu_count
  588. self._executor = concurrent.futures.ThreadPoolExecutor(
  589. max_workers=(cpu_count() * 5)
  590. ) # type: concurrent.futures.Executor
  591. executor = self._executor
  592. c_future = executor.submit(func, *args)
  593. # Concurrent Futures are not usable with await. Wrap this in a
  594. # Tornado Future instead, using self.add_future for thread-safety.
  595. t_future = Future() # type: Future[_T]
  596. self.add_future(c_future, lambda f: chain_future(f, t_future))
  597. return t_future
  598. def set_default_executor(self, executor: concurrent.futures.Executor) -> None:
  599. """Sets the default executor to use with :meth:`run_in_executor`.
  600. .. versionadded:: 5.0
  601. """
  602. self._executor = executor
  603. def _run_callback(self, callback: Callable[[], Any]) -> None:
  604. """Runs a callback with error handling.
  605. .. versionchanged:: 6.0
  606. CancelledErrors are no longer logged.
  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 asyncio.CancelledError:
  626. pass
  627. except Exception:
  628. app_log.error("Exception in callback %r", callback, exc_info=True)
  629. def _discard_future_result(self, future: Future) -> None:
  630. """Avoid unhandled-exception warnings from spawned coroutines."""
  631. future.result()
  632. def split_fd(
  633. self, fd: Union[int, _Selectable]
  634. ) -> Tuple[int, Union[int, _Selectable]]:
  635. # """Returns an (fd, obj) pair from an ``fd`` parameter.
  636. # We accept both raw file descriptors and file-like objects as
  637. # input to `add_handler` and related methods. When a file-like
  638. # object is passed, we must retain the object itself so we can
  639. # close it correctly when the `IOLoop` shuts down, but the
  640. # poller interfaces favor file descriptors (they will accept
  641. # file-like objects and call ``fileno()`` for you, but they
  642. # always return the descriptor itself).
  643. # This method is provided for use by `IOLoop` subclasses and should
  644. # not generally be used by application code.
  645. # .. versionadded:: 4.0
  646. # """
  647. if isinstance(fd, int):
  648. return fd, fd
  649. return fd.fileno(), fd
  650. def close_fd(self, fd: Union[int, _Selectable]) -> None:
  651. # """Utility method to close an ``fd``.
  652. # If ``fd`` is a file-like object, we close it directly; otherwise
  653. # we use `os.close`.
  654. # This method is provided for use by `IOLoop` subclasses (in
  655. # implementations of ``IOLoop.close(all_fds=True)`` and should
  656. # not generally be used by application code.
  657. # .. versionadded:: 4.0
  658. # """
  659. try:
  660. if isinstance(fd, int):
  661. os.close(fd)
  662. else:
  663. fd.close()
  664. except OSError:
  665. pass
  666. def _register_task(self, f: Future) -> None:
  667. self._pending_tasks.add(f)
  668. def _unregister_task(self, f: Future) -> None:
  669. self._pending_tasks.discard(f)
  670. class _Timeout:
  671. """An IOLoop timeout, a UNIX timestamp and a callback"""
  672. # Reduce memory overhead when there are lots of pending callbacks
  673. __slots__ = ["deadline", "callback", "tdeadline"]
  674. def __init__(
  675. self, deadline: float, callback: Callable[[], None], io_loop: IOLoop
  676. ) -> None:
  677. if not isinstance(deadline, numbers.Real):
  678. raise TypeError("Unsupported deadline %r" % deadline)
  679. self.deadline = deadline
  680. self.callback = callback
  681. self.tdeadline = (
  682. deadline,
  683. next(io_loop._timeout_counter),
  684. ) # type: Tuple[float, int]
  685. # Comparison methods to sort by deadline, with object id as a tiebreaker
  686. # to guarantee a consistent ordering. The heapq module uses __le__
  687. # in python2.5, and __lt__ in 2.6+ (sort() and most other comparisons
  688. # use __lt__).
  689. def __lt__(self, other: "_Timeout") -> bool:
  690. return self.tdeadline < other.tdeadline
  691. def __le__(self, other: "_Timeout") -> bool:
  692. return self.tdeadline <= other.tdeadline
  693. class PeriodicCallback:
  694. """Schedules the given callback to be called periodically.
  695. The callback is called every ``callback_time`` milliseconds when
  696. ``callback_time`` is a float. Note that the timeout is given in
  697. milliseconds, while most other time-related functions in Tornado use
  698. seconds. ``callback_time`` may alternatively be given as a
  699. `datetime.timedelta` object.
  700. If ``jitter`` is specified, each callback time will be randomly selected
  701. within a window of ``jitter * callback_time`` milliseconds.
  702. Jitter can be used to reduce alignment of events with similar periods.
  703. A jitter of 0.1 means allowing a 10% variation in callback time.
  704. The window is centered on ``callback_time`` so the total number of calls
  705. within a given interval should not be significantly affected by adding
  706. jitter.
  707. If the callback runs for longer than ``callback_time`` milliseconds,
  708. subsequent invocations will be skipped to get back on schedule.
  709. `start` must be called after the `PeriodicCallback` is created.
  710. .. versionchanged:: 5.0
  711. The ``io_loop`` argument (deprecated since version 4.1) has been removed.
  712. .. versionchanged:: 5.1
  713. The ``jitter`` argument is added.
  714. .. versionchanged:: 6.2
  715. If the ``callback`` argument is a coroutine, and a callback runs for
  716. longer than ``callback_time``, subsequent invocations will be skipped.
  717. Previously this was only true for regular functions, not coroutines,
  718. which were "fire-and-forget" for `PeriodicCallback`.
  719. The ``callback_time`` argument now accepts `datetime.timedelta` objects,
  720. in addition to the previous numeric milliseconds.
  721. """
  722. def __init__(
  723. self,
  724. callback: Callable[[], Optional[Awaitable]],
  725. callback_time: Union[datetime.timedelta, float],
  726. jitter: float = 0,
  727. ) -> None:
  728. self.callback = callback
  729. if isinstance(callback_time, datetime.timedelta):
  730. self.callback_time = callback_time / datetime.timedelta(milliseconds=1)
  731. else:
  732. if callback_time <= 0:
  733. raise ValueError("Periodic callback must have a positive callback_time")
  734. self.callback_time = callback_time
  735. self.jitter = jitter
  736. self._running = False
  737. self._timeout = None # type: object
  738. def start(self) -> None:
  739. """Starts the timer."""
  740. # Looking up the IOLoop here allows to first instantiate the
  741. # PeriodicCallback in another thread, then start it using
  742. # IOLoop.add_callback().
  743. self.io_loop = IOLoop.current()
  744. self._running = True
  745. self._next_timeout = self.io_loop.time()
  746. self._schedule_next()
  747. def stop(self) -> None:
  748. """Stops the timer."""
  749. self._running = False
  750. if self._timeout is not None:
  751. self.io_loop.remove_timeout(self._timeout)
  752. self._timeout = None
  753. def is_running(self) -> bool:
  754. """Returns ``True`` if this `.PeriodicCallback` has been started.
  755. .. versionadded:: 4.1
  756. """
  757. return self._running
  758. async def _run(self) -> None:
  759. if not self._running:
  760. return
  761. try:
  762. val = self.callback()
  763. if val is not None and isawaitable(val):
  764. await val
  765. except Exception:
  766. app_log.error("Exception in callback %r", self.callback, exc_info=True)
  767. finally:
  768. self._schedule_next()
  769. def _schedule_next(self) -> None:
  770. if self._running:
  771. self._update_next(self.io_loop.time())
  772. self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)
  773. def _update_next(self, current_time: float) -> None:
  774. callback_time_sec = self.callback_time / 1000.0
  775. if self.jitter:
  776. # apply jitter fraction
  777. callback_time_sec *= 1 + (self.jitter * (random.random() - 0.5))
  778. if self._next_timeout <= current_time:
  779. # The period should be measured from the start of one call
  780. # to the start of the next. If one call takes too long,
  781. # skip cycles to get back to a multiple of the original
  782. # schedule.
  783. self._next_timeout += (
  784. math.floor((current_time - self._next_timeout) / callback_time_sec) + 1
  785. ) * callback_time_sec
  786. else:
  787. # If the clock moved backwards, ensure we advance the next
  788. # timeout instead of recomputing the same value again.
  789. # This may result in long gaps between callbacks if the
  790. # clock jumps backwards by a lot, but the far more common
  791. # scenario is a small NTP adjustment that should just be
  792. # ignored.
  793. #
  794. # Note that on some systems if time.time() runs slower
  795. # than time.monotonic() (most common on windows), we
  796. # effectively experience a small backwards time jump on
  797. # every iteration because PeriodicCallback uses
  798. # time.time() while asyncio schedules callbacks using
  799. # time.monotonic().
  800. # https://github.com/tornadoweb/tornado/issues/2333
  801. self._next_timeout += callback_time_sec