tasks.py 22 KB

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