concurrent.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2012 Facebook
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License. You may obtain
  7. # a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. # License for the specific language governing permissions and limitations
  15. # under the License.
  16. """Utilities for working with threads and ``Futures``.
  17. ``Futures`` are a pattern for concurrent programming introduced in
  18. Python 3.2 in the `concurrent.futures` package. This package defines
  19. a mostly-compatible `Future` class designed for use from coroutines,
  20. as well as some utility functions for interacting with the
  21. `concurrent.futures` package.
  22. """
  23. from __future__ import absolute_import, division, print_function, with_statement
  24. import functools
  25. import platform
  26. import textwrap
  27. import traceback
  28. import sys
  29. from tornado.log import app_log
  30. from tornado.stack_context import ExceptionStackContext, wrap
  31. from tornado.util import raise_exc_info, ArgReplacer
  32. try:
  33. from concurrent import futures
  34. except ImportError:
  35. futures = None
  36. # Can the garbage collector handle cycles that include __del__ methods?
  37. # This is true in cpython beginning with version 3.4 (PEP 442).
  38. _GC_CYCLE_FINALIZERS = (platform.python_implementation() == 'CPython' and
  39. sys.version_info >= (3, 4))
  40. class ReturnValueIgnoredError(Exception):
  41. pass
  42. # This class and associated code in the future object is derived
  43. # from the Trollius project, a backport of asyncio to Python 2.x - 3.x
  44. class _TracebackLogger(object):
  45. """Helper to log a traceback upon destruction if not cleared.
  46. This solves a nasty problem with Futures and Tasks that have an
  47. exception set: if nobody asks for the exception, the exception is
  48. never logged. This violates the Zen of Python: 'Errors should
  49. never pass silently. Unless explicitly silenced.'
  50. However, we don't want to log the exception as soon as
  51. set_exception() is called: if the calling code is written
  52. properly, it will get the exception and handle it properly. But
  53. we *do* want to log it if result() or exception() was never called
  54. -- otherwise developers waste a lot of time wondering why their
  55. buggy code fails silently.
  56. An earlier attempt added a __del__() method to the Future class
  57. itself, but this backfired because the presence of __del__()
  58. prevents garbage collection from breaking cycles. A way out of
  59. this catch-22 is to avoid having a __del__() method on the Future
  60. class itself, but instead to have a reference to a helper object
  61. with a __del__() method that logs the traceback, where we ensure
  62. that the helper object doesn't participate in cycles, and only the
  63. Future has a reference to it.
  64. The helper object is added when set_exception() is called. When
  65. the Future is collected, and the helper is present, the helper
  66. object is also collected, and its __del__() method will log the
  67. traceback. When the Future's result() or exception() method is
  68. called (and a helper object is present), it removes the the helper
  69. object, after calling its clear() method to prevent it from
  70. logging.
  71. One downside is that we do a fair amount of work to extract the
  72. traceback from the exception, even when it is never logged. It
  73. would seem cheaper to just store the exception object, but that
  74. references the traceback, which references stack frames, which may
  75. reference the Future, which references the _TracebackLogger, and
  76. then the _TracebackLogger would be included in a cycle, which is
  77. what we're trying to avoid! As an optimization, we don't
  78. immediately format the exception; we only do the work when
  79. activate() is called, which call is delayed until after all the
  80. Future's callbacks have run. Since usually a Future has at least
  81. one callback (typically set by 'yield From') and usually that
  82. callback extracts the callback, thereby removing the need to
  83. format the exception.
  84. PS. I don't claim credit for this solution. I first heard of it
  85. in a discussion about closing files when they are collected.
  86. """
  87. __slots__ = ('exc_info', 'formatted_tb')
  88. def __init__(self, exc_info):
  89. self.exc_info = exc_info
  90. self.formatted_tb = None
  91. def activate(self):
  92. exc_info = self.exc_info
  93. if exc_info is not None:
  94. self.exc_info = None
  95. self.formatted_tb = traceback.format_exception(*exc_info)
  96. def clear(self):
  97. self.exc_info = None
  98. self.formatted_tb = None
  99. def __del__(self):
  100. if self.formatted_tb:
  101. app_log.error('Future exception was never retrieved: %s',
  102. ''.join(self.formatted_tb).rstrip())
  103. class Future(object):
  104. """Placeholder for an asynchronous result.
  105. A ``Future`` encapsulates the result of an asynchronous
  106. operation. In synchronous applications ``Futures`` are used
  107. to wait for the result from a thread or process pool; in
  108. Tornado they are normally used with `.IOLoop.add_future` or by
  109. yielding them in a `.gen.coroutine`.
  110. `tornado.concurrent.Future` is similar to
  111. `concurrent.futures.Future`, but not thread-safe (and therefore
  112. faster for use with single-threaded event loops).
  113. In addition to ``exception`` and ``set_exception``, methods ``exc_info``
  114. and ``set_exc_info`` are supported to capture tracebacks in Python 2.
  115. The traceback is automatically available in Python 3, but in the
  116. Python 2 futures backport this information is discarded.
  117. This functionality was previously available in a separate class
  118. ``TracebackFuture``, which is now a deprecated alias for this class.
  119. .. versionchanged:: 4.0
  120. `tornado.concurrent.Future` is always a thread-unsafe ``Future``
  121. with support for the ``exc_info`` methods. Previously it would
  122. be an alias for the thread-safe `concurrent.futures.Future`
  123. if that package was available and fall back to the thread-unsafe
  124. implementation if it was not.
  125. .. versionchanged:: 4.1
  126. If a `.Future` contains an error but that error is never observed
  127. (by calling ``result()``, ``exception()``, or ``exc_info()``),
  128. a stack trace will be logged when the `.Future` is garbage collected.
  129. This normally indicates an error in the application, but in cases
  130. where it results in undesired logging it may be necessary to
  131. suppress the logging by ensuring that the exception is observed:
  132. ``f.add_done_callback(lambda f: f.exception())``.
  133. """
  134. def __init__(self):
  135. self._done = False
  136. self._result = None
  137. self._exc_info = None
  138. self._log_traceback = False # Used for Python >= 3.4
  139. self._tb_logger = None # Used for Python <= 3.3
  140. self._callbacks = []
  141. # Implement the Python 3.5 Awaitable protocol if possible
  142. # (we can't use return and yield together until py33).
  143. if sys.version_info >= (3, 3):
  144. exec(textwrap.dedent("""
  145. def __await__(self):
  146. return (yield self)
  147. """))
  148. else:
  149. # Py2-compatible version for use with cython.
  150. def __await__(self):
  151. result = yield self
  152. # StopIteration doesn't take args before py33,
  153. # but Cython recognizes the args tuple.
  154. e = StopIteration()
  155. e.args = (result,)
  156. raise e
  157. def cancel(self):
  158. """Cancel the operation, if possible.
  159. Tornado ``Futures`` do not support cancellation, so this method always
  160. returns False.
  161. """
  162. return False
  163. def cancelled(self):
  164. """Returns True if the operation has been cancelled.
  165. Tornado ``Futures`` do not support cancellation, so this method
  166. always returns False.
  167. """
  168. return False
  169. def running(self):
  170. """Returns True if this operation is currently running."""
  171. return not self._done
  172. def done(self):
  173. """Returns True if the future has finished running."""
  174. return self._done
  175. def _clear_tb_log(self):
  176. self._log_traceback = False
  177. if self._tb_logger is not None:
  178. self._tb_logger.clear()
  179. self._tb_logger = None
  180. def result(self, timeout=None):
  181. """If the operation succeeded, return its result. If it failed,
  182. re-raise its exception.
  183. This method takes a ``timeout`` argument for compatibility with
  184. `concurrent.futures.Future` but it is an error to call it
  185. before the `Future` is done, so the ``timeout`` is never used.
  186. """
  187. self._clear_tb_log()
  188. if self._result is not None:
  189. return self._result
  190. if self._exc_info is not None:
  191. raise_exc_info(self._exc_info)
  192. self._check_done()
  193. return self._result
  194. def exception(self, timeout=None):
  195. """If the operation raised an exception, return the `Exception`
  196. object. Otherwise returns None.
  197. This method takes a ``timeout`` argument for compatibility with
  198. `concurrent.futures.Future` but it is an error to call it
  199. before the `Future` is done, so the ``timeout`` is never used.
  200. """
  201. self._clear_tb_log()
  202. if self._exc_info is not None:
  203. return self._exc_info[1]
  204. else:
  205. self._check_done()
  206. return None
  207. def add_done_callback(self, fn):
  208. """Attaches the given callback to the `Future`.
  209. It will be invoked with the `Future` as its argument when the Future
  210. has finished running and its result is available. In Tornado
  211. consider using `.IOLoop.add_future` instead of calling
  212. `add_done_callback` directly.
  213. """
  214. if self._done:
  215. fn(self)
  216. else:
  217. self._callbacks.append(fn)
  218. def set_result(self, result):
  219. """Sets the result of a ``Future``.
  220. It is undefined to call any of the ``set`` methods more than once
  221. on the same object.
  222. """
  223. self._result = result
  224. self._set_done()
  225. def set_exception(self, exception):
  226. """Sets the exception of a ``Future.``"""
  227. self.set_exc_info(
  228. (exception.__class__,
  229. exception,
  230. getattr(exception, '__traceback__', None)))
  231. def exc_info(self):
  232. """Returns a tuple in the same format as `sys.exc_info` or None.
  233. .. versionadded:: 4.0
  234. """
  235. self._clear_tb_log()
  236. return self._exc_info
  237. def set_exc_info(self, exc_info):
  238. """Sets the exception information of a ``Future.``
  239. Preserves tracebacks on Python 2.
  240. .. versionadded:: 4.0
  241. """
  242. self._exc_info = exc_info
  243. self._log_traceback = True
  244. if not _GC_CYCLE_FINALIZERS:
  245. self._tb_logger = _TracebackLogger(exc_info)
  246. try:
  247. self._set_done()
  248. finally:
  249. # Activate the logger after all callbacks have had a
  250. # chance to call result() or exception().
  251. if self._log_traceback and self._tb_logger is not None:
  252. self._tb_logger.activate()
  253. self._exc_info = exc_info
  254. def _check_done(self):
  255. if not self._done:
  256. raise Exception("DummyFuture does not support blocking for results")
  257. def _set_done(self):
  258. self._done = True
  259. for cb in self._callbacks:
  260. try:
  261. cb(self)
  262. except Exception:
  263. app_log.exception('Exception in callback %r for %r',
  264. cb, self)
  265. self._callbacks = None
  266. # On Python 3.3 or older, objects with a destructor part of a reference
  267. # cycle are never destroyed. It's no longer the case on Python 3.4 thanks to
  268. # the PEP 442.
  269. if _GC_CYCLE_FINALIZERS:
  270. def __del__(self):
  271. if not self._log_traceback:
  272. # set_exception() was not called, or result() or exception()
  273. # has consumed the exception
  274. return
  275. tb = traceback.format_exception(*self._exc_info)
  276. app_log.error('Future %r exception was never retrieved: %s',
  277. self, ''.join(tb).rstrip())
  278. TracebackFuture = Future
  279. if futures is None:
  280. FUTURES = Future
  281. else:
  282. FUTURES = (futures.Future, Future)
  283. def is_future(x):
  284. return isinstance(x, FUTURES)
  285. class DummyExecutor(object):
  286. def submit(self, fn, *args, **kwargs):
  287. future = TracebackFuture()
  288. try:
  289. future.set_result(fn(*args, **kwargs))
  290. except Exception:
  291. future.set_exc_info(sys.exc_info())
  292. return future
  293. def shutdown(self, wait=True):
  294. pass
  295. dummy_executor = DummyExecutor()
  296. def run_on_executor(*args, **kwargs):
  297. """Decorator to run a synchronous method asynchronously on an executor.
  298. The decorated method may be called with a ``callback`` keyword
  299. argument and returns a future.
  300. The `.IOLoop` and executor to be used are determined by the ``io_loop``
  301. and ``executor`` attributes of ``self``. To use different attributes,
  302. pass keyword arguments to the decorator::
  303. @run_on_executor(executor='_thread_pool')
  304. def foo(self):
  305. pass
  306. .. versionchanged:: 4.2
  307. Added keyword arguments to use alternative attributes.
  308. """
  309. def run_on_executor_decorator(fn):
  310. executor = kwargs.get("executor", "executor")
  311. io_loop = kwargs.get("io_loop", "io_loop")
  312. @functools.wraps(fn)
  313. def wrapper(self, *args, **kwargs):
  314. callback = kwargs.pop("callback", None)
  315. future = getattr(self, executor).submit(fn, self, *args, **kwargs)
  316. if callback:
  317. getattr(self, io_loop).add_future(
  318. future, lambda future: callback(future.result()))
  319. return future
  320. return wrapper
  321. if args and kwargs:
  322. raise ValueError("cannot combine positional and keyword args")
  323. if len(args) == 1:
  324. return run_on_executor_decorator(args[0])
  325. elif len(args) != 0:
  326. raise ValueError("expected 1 argument, got %d", len(args))
  327. return run_on_executor_decorator
  328. _NO_RESULT = object()
  329. def return_future(f):
  330. """Decorator to make a function that returns via callback return a
  331. `Future`.
  332. The wrapped function should take a ``callback`` keyword argument
  333. and invoke it with one argument when it has finished. To signal failure,
  334. the function can simply raise an exception (which will be
  335. captured by the `.StackContext` and passed along to the ``Future``).
  336. From the caller's perspective, the callback argument is optional.
  337. If one is given, it will be invoked when the function is complete
  338. with `Future.result()` as an argument. If the function fails, the
  339. callback will not be run and an exception will be raised into the
  340. surrounding `.StackContext`.
  341. If no callback is given, the caller should use the ``Future`` to
  342. wait for the function to complete (perhaps by yielding it in a
  343. `.gen.engine` function, or passing it to `.IOLoop.add_future`).
  344. Usage:
  345. .. testcode::
  346. @return_future
  347. def future_func(arg1, arg2, callback):
  348. # Do stuff (possibly asynchronous)
  349. callback(result)
  350. @gen.engine
  351. def caller(callback):
  352. yield future_func(arg1, arg2)
  353. callback()
  354. ..
  355. Note that ``@return_future`` and ``@gen.engine`` can be applied to the
  356. same function, provided ``@return_future`` appears first. However,
  357. consider using ``@gen.coroutine`` instead of this combination.
  358. """
  359. replacer = ArgReplacer(f, 'callback')
  360. @functools.wraps(f)
  361. def wrapper(*args, **kwargs):
  362. future = TracebackFuture()
  363. callback, args, kwargs = replacer.replace(
  364. lambda value=_NO_RESULT: future.set_result(value),
  365. args, kwargs)
  366. def handle_error(typ, value, tb):
  367. future.set_exc_info((typ, value, tb))
  368. return True
  369. exc_info = None
  370. with ExceptionStackContext(handle_error):
  371. try:
  372. result = f(*args, **kwargs)
  373. if result is not None:
  374. raise ReturnValueIgnoredError(
  375. "@return_future should not be used with functions "
  376. "that return values")
  377. except:
  378. exc_info = sys.exc_info()
  379. raise
  380. if exc_info is not None:
  381. # If the initial synchronous part of f() raised an exception,
  382. # go ahead and raise it to the caller directly without waiting
  383. # for them to inspect the Future.
  384. future.result()
  385. # If the caller passed in a callback, schedule it to be called
  386. # when the future resolves. It is important that this happens
  387. # just before we return the future, or else we risk confusing
  388. # stack contexts with multiple exceptions (one here with the
  389. # immediate exception, and again when the future resolves and
  390. # the callback triggers its exception by calling future.result()).
  391. if callback is not None:
  392. def run_callback(future):
  393. result = future.result()
  394. if result is _NO_RESULT:
  395. callback()
  396. else:
  397. callback(future.result())
  398. future.add_done_callback(wrap(run_callback))
  399. return future
  400. return wrapper
  401. def chain_future(a, b):
  402. """Chain two futures together so that when one completes, so does the other.
  403. The result (success or failure) of ``a`` will be copied to ``b``, unless
  404. ``b`` has already been completed or cancelled by the time ``a`` finishes.
  405. """
  406. def copy(future):
  407. assert future is a
  408. if b.done():
  409. return
  410. if (isinstance(a, TracebackFuture) and isinstance(b, TracebackFuture)
  411. and a.exc_info() is not None):
  412. b.set_exc_info(a.exc_info())
  413. elif a.exception() is not None:
  414. b.set_exception(a.exception())
  415. else:
  416. b.set_result(a.result())
  417. a.add_done_callback(copy)