PageRenderTime 63ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/asyncio/tasks.py

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