/asyncio/tasks.py

https://bitbucket.org/iwienand/trollius · Python · 681 lines · 517 code · 49 blank · 115 comment · 43 complexity · e4af902dd1449ece945f52963af70cb7 MD5 · raw file

  1. """Support for tasks, coroutines and the scheduler."""
  2. __all__ = ['coroutine', 'Task',
  3. 'iscoroutinefunction', 'iscoroutine',
  4. 'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED',
  5. 'wait', 'wait_for', 'as_completed', 'sleep', 'async',
  6. 'gather', 'shield',
  7. ]
  8. import collections
  9. import concurrent.futures
  10. import functools
  11. import inspect
  12. import linecache
  13. import traceback
  14. import weakref
  15. from . import events
  16. from . import futures
  17. from .log import logger
  18. # If you set _DEBUG to true, @coroutine will wrap the resulting
  19. # generator objects in a CoroWrapper instance (defined below). That
  20. # instance will log a message when the generator is never iterated
  21. # over, which may happen when you forget to use "yield from" with a
  22. # coroutine call. Note that the value of the _DEBUG flag is taken
  23. # when the decorator is used, so to be of any use it must be set
  24. # before you define your coroutines. A downside of using this feature
  25. # is that tracebacks show entries for the CoroWrapper.__next__ method
  26. # when _DEBUG is true.
  27. _DEBUG = False
  28. class CoroWrapper:
  29. # Wrapper for coroutine in _DEBUG mode.
  30. __slots__ = ['gen', 'func', '__name__', '__doc__']
  31. def __init__(self, gen, func):
  32. assert inspect.isgenerator(gen), gen
  33. self.gen = gen
  34. self.func = func
  35. def __iter__(self):
  36. return self
  37. def __next__(self):
  38. return next(self.gen)
  39. def send(self, value):
  40. return self.gen.send(value)
  41. def throw(self, exc):
  42. return self.gen.throw(exc)
  43. def close(self):
  44. return self.gen.close()
  45. def __del__(self):
  46. frame = self.gen.gi_frame
  47. if frame is not None and frame.f_lasti == -1:
  48. func = self.func
  49. code = func.__code__
  50. filename = code.co_filename
  51. lineno = code.co_firstlineno
  52. logger.error(
  53. 'Coroutine %r defined at %s:%s was never yielded from',
  54. func.__name__, filename, lineno)
  55. def coroutine(func):
  56. """Decorator to mark coroutines.
  57. If the coroutine is not yielded from before it is destroyed,
  58. an error message is logged.
  59. """
  60. if inspect.isgeneratorfunction(func):
  61. coro = func
  62. else:
  63. @functools.wraps(func)
  64. def coro(*args, **kw):
  65. res = func(*args, **kw)
  66. if isinstance(res, futures.Future) or inspect.isgenerator(res):
  67. res = yield from res
  68. return res
  69. if not _DEBUG:
  70. wrapper = coro
  71. else:
  72. @functools.wraps(func)
  73. def wrapper(*args, **kwds):
  74. w = CoroWrapper(coro(*args, **kwds), func)
  75. w.__name__ = coro.__name__
  76. w.__doc__ = coro.__doc__
  77. return w
  78. wrapper._is_coroutine = True # For iscoroutinefunction().
  79. return wrapper
  80. def iscoroutinefunction(func):
  81. """Return True if func is a decorated coroutine function."""
  82. return getattr(func, '_is_coroutine', False)
  83. def iscoroutine(obj):
  84. """Return True if obj is a coroutine object."""
  85. return isinstance(obj, CoroWrapper) or inspect.isgenerator(obj)
  86. class Task(futures.Future):
  87. """A coroutine wrapped in a Future."""
  88. # An important invariant maintained while a Task not done:
  89. #
  90. # - Either _fut_waiter is None, and _step() is scheduled;
  91. # - or _fut_waiter is some Future, and _step() is *not* scheduled.
  92. #
  93. # The only transition from the latter to the former is through
  94. # _wakeup(). When _fut_waiter is not None, one of its callbacks
  95. # must be _wakeup().
  96. # Weak set containing all tasks alive.
  97. _all_tasks = weakref.WeakSet()
  98. # Dictionary containing tasks that are currently active in
  99. # all running event loops. {EventLoop: Task}
  100. _current_tasks = {}
  101. @classmethod
  102. def current_task(cls, loop=None):
  103. """Return the currently running task in an event loop or None.
  104. By default the current task for the current event loop is returned.
  105. None is returned when called not in the context of a Task.
  106. """
  107. if loop is None:
  108. loop = events.get_event_loop()
  109. return cls._current_tasks.get(loop)
  110. @classmethod
  111. def all_tasks(cls, loop=None):
  112. """Return a set of all tasks for an event loop.
  113. By default all tasks for the current event loop are returned.
  114. """
  115. if loop is None:
  116. loop = events.get_event_loop()
  117. return {t for t in cls._all_tasks if t._loop is loop}
  118. def __init__(self, coro, *, loop=None):
  119. assert iscoroutine(coro), repr(coro) # Not a coroutine function!
  120. super().__init__(loop=loop)
  121. self._coro = iter(coro) # Use the iterator just in case.
  122. self._fut_waiter = None
  123. self._must_cancel = False
  124. self._loop.call_soon(self._step)
  125. self.__class__._all_tasks.add(self)
  126. def __repr__(self):
  127. res = super().__repr__()
  128. if (self._must_cancel and
  129. self._state == futures._PENDING and
  130. '<PENDING' in res):
  131. res = res.replace('<PENDING', '<CANCELLING', 1)
  132. i = res.find('<')
  133. if i < 0:
  134. i = len(res)
  135. res = res[:i] + '(<{}>)'.format(self._coro.__name__) + res[i:]
  136. return res
  137. def get_stack(self, *, limit=None):
  138. """Return the list of stack frames for this task's coroutine.
  139. If the coroutine is active, this returns the stack where it is
  140. suspended. If the coroutine has completed successfully or was
  141. cancelled, this returns an empty list. If the coroutine was
  142. terminated by an exception, this returns the list of traceback
  143. frames.
  144. The frames are always ordered from oldest to newest.
  145. The optional limit gives the maximum nummber of frames to
  146. return; by default all available frames are returned. Its
  147. meaning differs depending on whether a stack or a traceback is
  148. returned: the newest frames of a stack are returned, but the
  149. oldest frames of a traceback are returned. (This matches the
  150. behavior of the traceback module.)
  151. For reasons beyond our control, only one stack frame is
  152. returned for a suspended coroutine.
  153. """
  154. frames = []
  155. f = self._coro.gi_frame
  156. if f is not None:
  157. while f is not None:
  158. if limit is not None:
  159. if limit <= 0:
  160. break
  161. limit -= 1
  162. frames.append(f)
  163. f = f.f_back
  164. frames.reverse()
  165. elif self._exception is not None:
  166. tb = self._exception.__traceback__
  167. while tb is not None:
  168. if limit is not None:
  169. if limit <= 0:
  170. break
  171. limit -= 1
  172. frames.append(tb.tb_frame)
  173. tb = tb.tb_next
  174. return frames
  175. def print_stack(self, *, limit=None, file=None):
  176. """Print the stack or traceback for this task's coroutine.
  177. This produces output similar to that of the traceback module,
  178. for the frames retrieved by get_stack(). The limit argument
  179. is passed to get_stack(). The file argument is an I/O stream
  180. to which the output goes; by default it goes to sys.stderr.
  181. """
  182. extracted_list = []
  183. checked = set()
  184. for f in self.get_stack(limit=limit):
  185. lineno = f.f_lineno
  186. co = f.f_code
  187. filename = co.co_filename
  188. name = co.co_name
  189. if filename not in checked:
  190. checked.add(filename)
  191. linecache.checkcache(filename)
  192. line = linecache.getline(filename, lineno, f.f_globals)
  193. extracted_list.append((filename, lineno, name, line))
  194. exc = self._exception
  195. if not extracted_list:
  196. print('No stack for %r' % self, file=file)
  197. elif exc is not None:
  198. print('Traceback for %r (most recent call last):' % self,
  199. file=file)
  200. else:
  201. print('Stack for %r (most recent call last):' % self,
  202. file=file)
  203. traceback.print_list(extracted_list, file=file)
  204. if exc is not None:
  205. for line in traceback.format_exception_only(exc.__class__, exc):
  206. print(line, file=file, end='')
  207. def cancel(self):
  208. if self.done():
  209. return False
  210. if self._fut_waiter is not None:
  211. if self._fut_waiter.cancel():
  212. # Leave self._fut_waiter; it may be a Task that
  213. # catches and ignores the cancellation so we may have
  214. # to cancel it again later.
  215. return True
  216. # It must be the case that self._step is already scheduled.
  217. self._must_cancel = True
  218. return True
  219. def _step(self, value=None, exc=None):
  220. assert not self.done(), \
  221. '_step(): already done: {!r}, {!r}, {!r}'.format(self, value, exc)
  222. if self._must_cancel:
  223. if not isinstance(exc, futures.CancelledError):
  224. exc = futures.CancelledError()
  225. self._must_cancel = False
  226. coro = self._coro
  227. self._fut_waiter = None
  228. self.__class__._current_tasks[self._loop] = self
  229. # Call either coro.throw(exc) or coro.send(value).
  230. try:
  231. if exc is not None:
  232. result = coro.throw(exc)
  233. elif value is not None:
  234. result = coro.send(value)
  235. else:
  236. result = next(coro)
  237. except StopIteration as exc:
  238. self.set_result(exc.value)
  239. except futures.CancelledError as exc:
  240. super().cancel() # I.e., Future.cancel(self).
  241. except Exception as exc:
  242. self.set_exception(exc)
  243. except BaseException as exc:
  244. self.set_exception(exc)
  245. raise
  246. else:
  247. if isinstance(result, futures.Future):
  248. # Yielded Future must come from Future.__iter__().
  249. if result._blocking:
  250. result._blocking = False
  251. result.add_done_callback(self._wakeup)
  252. self._fut_waiter = result
  253. if self._must_cancel:
  254. if self._fut_waiter.cancel():
  255. self._must_cancel = False
  256. else:
  257. self._loop.call_soon(
  258. self._step, None,
  259. RuntimeError(
  260. 'yield was used instead of yield from '
  261. 'in task {!r} with {!r}'.format(self, result)))
  262. elif result is None:
  263. # Bare yield relinquishes control for one event loop iteration.
  264. self._loop.call_soon(self._step)
  265. elif inspect.isgenerator(result):
  266. # Yielding a generator is just wrong.
  267. self._loop.call_soon(
  268. self._step, None,
  269. RuntimeError(
  270. 'yield was used instead of yield from for '
  271. 'generator in task {!r} with {}'.format(
  272. self, result)))
  273. else:
  274. # Yielding something else is an error.
  275. self._loop.call_soon(
  276. self._step, None,
  277. RuntimeError(
  278. 'Task got bad yield: {!r}'.format(result)))
  279. finally:
  280. self.__class__._current_tasks.pop(self._loop)
  281. self = None
  282. def _wakeup(self, future):
  283. try:
  284. value = future.result()
  285. except Exception as exc:
  286. # This may also be a cancellation.
  287. self._step(None, exc)
  288. else:
  289. self._step(value, None)
  290. self = None # Needed to break cycles when an exception occurs.
  291. # wait() and as_completed() similar to those in PEP 3148.
  292. FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED
  293. FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION
  294. ALL_COMPLETED = concurrent.futures.ALL_COMPLETED
  295. @coroutine
  296. def wait(fs, *, loop=None, timeout=None, return_when=ALL_COMPLETED):
  297. """Wait for the Futures and coroutines given by fs to complete.
  298. Coroutines will be wrapped in Tasks.
  299. Returns two sets of Future: (done, pending).
  300. Usage:
  301. done, pending = yield from asyncio.wait(fs)
  302. Note: This does not raise TimeoutError! Futures that aren't done
  303. when the timeout occurs are returned in the second set.
  304. """
  305. if isinstance(fs, futures.Future) or iscoroutine(fs):
  306. raise TypeError("expect a list of futures, not %s" % type(fs).__name__)
  307. if not fs:
  308. raise ValueError('Set of coroutines/Futures is empty.')
  309. if loop is None:
  310. loop = events.get_event_loop()
  311. fs = {async(f, loop=loop) for f in set(fs)}
  312. if return_when not in (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED):
  313. raise ValueError('Invalid return_when value: {}'.format(return_when))
  314. return (yield from _wait(fs, timeout, return_when, loop))
  315. def _release_waiter(waiter, value=True, *args):
  316. if not waiter.done():
  317. waiter.set_result(value)
  318. @coroutine
  319. def wait_for(fut, timeout, *, loop=None):
  320. """Wait for the single Future or coroutine to complete, with timeout.
  321. Coroutine will be wrapped in Task.
  322. Returns result of the Future or coroutine. When a timeout occurs,
  323. it cancels the task and raises TimeoutError. To avoid the task
  324. cancellation, wrap it in shield().
  325. Usage:
  326. result = yield from asyncio.wait_for(fut, 10.0)
  327. """
  328. if loop is None:
  329. loop = events.get_event_loop()
  330. if timeout is None:
  331. return (yield from fut)
  332. waiter = futures.Future(loop=loop)
  333. timeout_handle = loop.call_later(timeout, _release_waiter, waiter, False)
  334. cb = functools.partial(_release_waiter, waiter, True)
  335. fut = async(fut, loop=loop)
  336. fut.add_done_callback(cb)
  337. try:
  338. if (yield from waiter):
  339. return fut.result()
  340. else:
  341. fut.remove_done_callback(cb)
  342. fut.cancel()
  343. raise futures.TimeoutError()
  344. finally:
  345. timeout_handle.cancel()
  346. @coroutine
  347. def _wait(fs, timeout, return_when, loop):
  348. """Internal helper for wait() and _wait_for().
  349. The fs argument must be a collection of Futures.
  350. """
  351. assert fs, 'Set of Futures is empty.'
  352. waiter = futures.Future(loop=loop)
  353. timeout_handle = None
  354. if timeout is not None:
  355. timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
  356. counter = len(fs)
  357. def _on_completion(f):
  358. nonlocal counter
  359. counter -= 1
  360. if (counter <= 0 or
  361. return_when == FIRST_COMPLETED or
  362. return_when == FIRST_EXCEPTION and (not f.cancelled() and
  363. f.exception() is not None)):
  364. if timeout_handle is not None:
  365. timeout_handle.cancel()
  366. if not waiter.done():
  367. waiter.set_result(False)
  368. for f in fs:
  369. f.add_done_callback(_on_completion)
  370. try:
  371. yield from waiter
  372. finally:
  373. if timeout_handle is not None:
  374. timeout_handle.cancel()
  375. done, pending = set(), set()
  376. for f in fs:
  377. f.remove_done_callback(_on_completion)
  378. if f.done():
  379. done.add(f)
  380. else:
  381. pending.add(f)
  382. return done, pending
  383. # This is *not* a @coroutine! It is just an iterator (yielding Futures).
  384. def as_completed(fs, *, loop=None, timeout=None):
  385. """Return an iterator whose values are coroutines.
  386. When waiting for the yielded coroutines you'll get the results (or
  387. exceptions!) of the original Futures (or coroutines), in the order
  388. in which and as soon as they complete.
  389. This differs from PEP 3148; the proper way to use this is:
  390. for f in as_completed(fs):
  391. result = yield from f # The 'yield from' may raise.
  392. # Use result.
  393. If a timeout is specified, the 'yield from' will raise
  394. TimeoutError when the timeout occurs before all Futures are done.
  395. Note: The futures 'f' are not necessarily members of fs.
  396. """
  397. if isinstance(fs, futures.Future) or iscoroutine(fs):
  398. raise TypeError("expect a list of futures, not %s" % type(fs).__name__)
  399. loop = loop if loop is not None else events.get_event_loop()
  400. deadline = None if timeout is None else loop.time() + timeout
  401. todo = {async(f, loop=loop) for f in set(fs)}
  402. from .queues import Queue # Import here to avoid circular import problem.
  403. done = Queue(loop=loop)
  404. timeout_handle = None
  405. def _on_timeout():
  406. for f in todo:
  407. f.remove_done_callback(_on_completion)
  408. done.put_nowait(None) # Queue a dummy value for _wait_for_one().
  409. todo.clear() # Can't do todo.remove(f) in the loop.
  410. def _on_completion(f):
  411. if not todo:
  412. return # _on_timeout() was here first.
  413. todo.remove(f)
  414. done.put_nowait(f)
  415. if not todo and timeout_handle is not None:
  416. timeout_handle.cancel()
  417. @coroutine
  418. def _wait_for_one():
  419. f = yield from done.get()
  420. if f is None:
  421. # Dummy value from _on_timeout().
  422. raise futures.TimeoutError
  423. return f.result() # May raise f.exception().
  424. for f in todo:
  425. f.add_done_callback(_on_completion)
  426. if todo and timeout is not None:
  427. timeout_handle = loop.call_later(timeout, _on_timeout)
  428. for _ in range(len(todo)):
  429. yield _wait_for_one()
  430. @coroutine
  431. def sleep(delay, result=None, *, loop=None):
  432. """Coroutine that completes after a given time (in seconds)."""
  433. future = futures.Future(loop=loop)
  434. h = future._loop.call_later(delay, future.set_result, result)
  435. try:
  436. return (yield from future)
  437. finally:
  438. h.cancel()
  439. def async(coro_or_future, *, loop=None):
  440. """Wrap a coroutine in a future.
  441. If the argument is a Future, it is returned directly.
  442. """
  443. if isinstance(coro_or_future, futures.Future):
  444. if loop is not None and loop is not coro_or_future._loop:
  445. raise ValueError('loop argument must agree with Future')
  446. return coro_or_future
  447. elif iscoroutine(coro_or_future):
  448. return Task(coro_or_future, loop=loop)
  449. else:
  450. raise TypeError('A Future or coroutine is required')
  451. class _GatheringFuture(futures.Future):
  452. """Helper for gather().
  453. This overrides cancel() to cancel all the children and act more
  454. like Task.cancel(), which doesn't immediately mark itself as
  455. cancelled.
  456. """
  457. def __init__(self, children, *, loop=None):
  458. super().__init__(loop=loop)
  459. self._children = children
  460. def cancel(self):
  461. if self.done():
  462. return False
  463. for child in self._children:
  464. child.cancel()
  465. return True
  466. def gather(*coros_or_futures, loop=None, return_exceptions=False):
  467. """Return a future aggregating results from the given coroutines
  468. or futures.
  469. All futures must share the same event loop. If all the tasks are
  470. done successfully, the returned future's result is the list of
  471. results (in the order of the original sequence, not necessarily
  472. the order of results arrival). If *return_exceptions* is True,
  473. exceptions in the tasks are treated the same as successful
  474. results, and gathered in the result list; otherwise, the first
  475. raised exception will be immediately propagated to the returned
  476. future.
  477. Cancellation: if the outer Future is cancelled, all children (that
  478. have not completed yet) are also cancelled. If any child is
  479. cancelled, this is treated as if it raised CancelledError --
  480. the outer Future is *not* cancelled in this case. (This is to
  481. prevent the cancellation of one child to cause other children to
  482. be cancelled.)
  483. """
  484. arg_to_fut = {arg: async(arg, loop=loop) for arg in set(coros_or_futures)}
  485. children = [arg_to_fut[arg] for arg in coros_or_futures]
  486. n = len(children)
  487. if n == 0:
  488. outer = futures.Future(loop=loop)
  489. outer.set_result([])
  490. return outer
  491. if loop is None:
  492. loop = children[0]._loop
  493. for fut in children:
  494. if fut._loop is not loop:
  495. raise ValueError("futures are tied to different event loops")
  496. outer = _GatheringFuture(children, loop=loop)
  497. nfinished = 0
  498. results = [None] * n
  499. def _done_callback(i, fut):
  500. nonlocal nfinished
  501. if outer._state != futures._PENDING:
  502. if fut._exception is not None:
  503. # Mark exception retrieved.
  504. fut.exception()
  505. return
  506. if fut._state == futures._CANCELLED:
  507. res = futures.CancelledError()
  508. if not return_exceptions:
  509. outer.set_exception(res)
  510. return
  511. elif fut._exception is not None:
  512. res = fut.exception() # Mark exception retrieved.
  513. if not return_exceptions:
  514. outer.set_exception(res)
  515. return
  516. else:
  517. res = fut._result
  518. results[i] = res
  519. nfinished += 1
  520. if nfinished == n:
  521. outer.set_result(results)
  522. for i, fut in enumerate(children):
  523. fut.add_done_callback(functools.partial(_done_callback, i))
  524. return outer
  525. def shield(arg, *, loop=None):
  526. """Wait for a future, shielding it from cancellation.
  527. The statement
  528. res = yield from shield(something())
  529. is exactly equivalent to the statement
  530. res = yield from something()
  531. *except* that if the coroutine containing it is cancelled, the
  532. task running in something() is not cancelled. From the POV of
  533. something(), the cancellation did not happen. But its caller is
  534. still cancelled, so the yield-from expression still raises
  535. CancelledError. Note: If something() is cancelled by other means
  536. this will still cancel shield().
  537. If you want to completely ignore cancellation (not recommended)
  538. you can combine shield() with a try/except clause, as follows:
  539. try:
  540. res = yield from shield(something())
  541. except CancelledError:
  542. res = None
  543. """
  544. inner = async(arg, loop=loop)
  545. if inner.done():
  546. # Shortcut.
  547. return inner
  548. loop = inner._loop
  549. outer = futures.Future(loop=loop)
  550. def _done_callback(inner):
  551. if outer.cancelled():
  552. # Mark inner's result as retrieved.
  553. inner.cancelled() or inner.exception()
  554. return
  555. if inner.cancelled():
  556. outer.cancel()
  557. else:
  558. exc = inner.exception()
  559. if exc is not None:
  560. outer.set_exception(exc)
  561. else:
  562. outer.set_result(inner.result())
  563. inner.add_done_callback(_done_callback)
  564. return outer