tasks.py 23.8 KB
Newer Older
1 2
"""Support for tasks, coroutines and the scheduler."""

3
__all__ = ['Task',
4 5
           'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED',
           'wait', 'wait_for', 'as_completed', 'sleep', 'async',
6
           'gather', 'shield', 'ensure_future', 'run_coroutine_threadsafe',
7 8 9 10 11
           ]

import concurrent.futures
import functools
import inspect
12
import warnings
13 14
import weakref

15
from . import base_tasks
16
from . import compat
17
from . import coroutines
18 19
from . import events
from . import futures
20
from .coroutines import coroutine
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37


class Task(futures.Future):
    """A coroutine wrapped in a Future."""

    # An important invariant maintained while a Task not done:
    #
    # - Either _fut_waiter is None, and _step() is scheduled;
    # - or _fut_waiter is some Future, and _step() is *not* scheduled.
    #
    # The only transition from the latter to the former is through
    # _wakeup().  When _fut_waiter is not None, one of its callbacks
    # must be _wakeup().

    # Weak set containing all tasks alive.
    _all_tasks = weakref.WeakSet()

38 39 40 41
    # Dictionary containing tasks that are currently active in
    # all running event loops.  {EventLoop: Task}
    _current_tasks = {}

42 43 44 45
    # If False, don't log a message if the task is destroyed whereas its
    # status is still pending
    _log_destroy_pending = True

46 47 48 49 50 51 52 53 54 55 56 57
    @classmethod
    def current_task(cls, loop=None):
        """Return the currently running task in an event loop or None.

        By default the current task for the current event loop is returned.

        None is returned when called not in the context of a Task.
        """
        if loop is None:
            loop = events.get_event_loop()
        return cls._current_tasks.get(loop)

58 59 60 61 62 63 64 65 66 67 68
    @classmethod
    def all_tasks(cls, loop=None):
        """Return a set of all tasks for an event loop.

        By default all tasks for the current event loop are returned.
        """
        if loop is None:
            loop = events.get_event_loop()
        return {t for t in cls._all_tasks if t._loop is loop}

    def __init__(self, coro, *, loop=None):
69
        assert coroutines.iscoroutine(coro), repr(coro)
70
        super().__init__(loop=loop)
71 72
        if self._source_traceback:
            del self._source_traceback[-1]
73
        self._coro = coro
74 75 76 77 78
        self._fut_waiter = None
        self._must_cancel = False
        self._loop.call_soon(self._step)
        self.__class__._all_tasks.add(self)

79 80 81 82 83 84 85 86 87 88
    def __del__(self):
        if self._state == futures._PENDING and self._log_destroy_pending:
            context = {
                'task': self,
                'message': 'Task was destroyed but it is pending!',
            }
            if self._source_traceback:
                context['source_traceback'] = self._source_traceback
            self._loop.call_exception_handler(context)
        futures.Future.__del__(self)
89

90
    def _repr_info(self):
91
        return base_tasks._task_repr_info(self)
92 93 94 95

    def get_stack(self, *, limit=None):
        """Return the list of stack frames for this task's coroutine.

96
        If the coroutine is not done, this returns the stack where it is
97 98 99 100 101 102 103
        suspended.  If the coroutine has completed successfully or was
        cancelled, this returns an empty list.  If the coroutine was
        terminated by an exception, this returns the list of traceback
        frames.

        The frames are always ordered from oldest to newest.

104
        The optional limit gives the maximum number of frames to
105 106 107 108 109 110 111 112 113
        return; by default all available frames are returned.  Its
        meaning differs depending on whether a stack or a traceback is
        returned: the newest frames of a stack are returned, but the
        oldest frames of a traceback are returned.  (This matches the
        behavior of the traceback module.)

        For reasons beyond our control, only one stack frame is
        returned for a suspended coroutine.
        """
114
        return base_tasks._task_get_stack(self, limit)
115 116 117 118 119 120 121

    def print_stack(self, *, limit=None, file=None):
        """Print the stack or traceback for this task's coroutine.

        This produces output similar to that of the traceback module,
        for the frames retrieved by get_stack().  The limit argument
        is passed to get_stack().  The file argument is an I/O stream
122 123
        to which the output is written; by default output is written
        to sys.stderr.
124
        """
125
        return base_tasks._task_print_stack(self, limit, file)
126 127

    def cancel(self):
128
        """Request that this task cancel itself.
129

130
        This arranges for a CancelledError to be thrown into the
131 132 133 134
        wrapped coroutine on the next cycle through the event loop.
        The coroutine then has a chance to clean up or even deny
        the request using try/except/finally.

135
        Unlike Future.cancel, this does not guarantee that the
136
        task will be cancelled: the exception might be caught and
137 138 139
        acted upon, delaying cancellation of the task or preventing
        cancellation completely.  The task may also return a value or
        raise a different exception.
140 141 142 143 144 145 146

        Immediately after this method is called, Task.cancelled() will
        not return True (unless the task was already cancelled).  A
        task will be marked as cancelled when the wrapped coroutine
        terminates with a CancelledError exception (even if cancel()
        was not called).
        """
147
        self._log_traceback = False
148 149 150 151 152 153 154 155 156 157 158 159
        if self.done():
            return False
        if self._fut_waiter is not None:
            if self._fut_waiter.cancel():
                # Leave self._fut_waiter; it may be a Task that
                # catches and ignores the cancellation so we may have
                # to cancel it again later.
                return True
        # It must be the case that self._step is already scheduled.
        self._must_cancel = True
        return True

160
    def _step(self, exc=None):
161
        assert not self.done(), \
162
            '_step(): already done: {!r}, {!r}'.format(self, exc)
163 164 165 166 167 168
        if self._must_cancel:
            if not isinstance(exc, futures.CancelledError):
                exc = futures.CancelledError()
            self._must_cancel = False
        coro = self._coro
        self._fut_waiter = None
169 170

        self.__class__._current_tasks[self._loop] = self
171
        # Call either coro.throw(exc) or coro.send(None).
172
        try:
173 174 175 176
            if exc is None:
                # We use the `send` method directly, because coroutines
                # don't have `__iter__` and `__next__` methods.
                result = coro.send(None)
177
            else:
178
                result = coro.throw(exc)
179
        except StopIteration as exc:
180 181 182 183 184 185
            if self._must_cancel:
                # Task is cancelled right before coro stops.
                self._must_cancel = False
                self.set_exception(futures.CancelledError())
            else:
                self.set_result(exc.value)
186
        except futures.CancelledError:
187 188 189 190 191 192 193
            super().cancel()  # I.e., Future.cancel(self).
        except Exception as exc:
            self.set_exception(exc)
        except BaseException as exc:
            self.set_exception(exc)
            raise
        else:
194 195
            blocking = getattr(result, '_asyncio_future_blocking', None)
            if blocking is not None:
196
                # Yielded Future must come from Future.__iter__().
197 198 199 200 201 202
                if result._loop is not self._loop:
                    self._loop.call_soon(
                        self._step,
                        RuntimeError(
                            'Task {!r} got Future {!r} attached to a '
                            'different loop'.format(self, result)))
203
                elif blocking:
204 205 206 207 208 209 210 211 212 213 214 215 216
                    if result is self:
                        self._loop.call_soon(
                            self._step,
                            RuntimeError(
                                'Task cannot await on itself: {!r}'.format(
                                    self)))
                    else:
                        result._asyncio_future_blocking = False
                        result.add_done_callback(self._wakeup)
                        self._fut_waiter = result
                        if self._must_cancel:
                            if self._fut_waiter.cancel():
                                self._must_cancel = False
217 218
                else:
                    self._loop.call_soon(
219
                        self._step,
220 221 222 223 224 225 226 227 228
                        RuntimeError(
                            'yield was used instead of yield from '
                            'in task {!r} with {!r}'.format(self, result)))
            elif result is None:
                # Bare yield relinquishes control for one event loop iteration.
                self._loop.call_soon(self._step)
            elif inspect.isgenerator(result):
                # Yielding a generator is just wrong.
                self._loop.call_soon(
229
                    self._step,
230 231 232 233 234 235 236
                    RuntimeError(
                        'yield was used instead of yield from for '
                        'generator in task {!r} with {}'.format(
                            self, result)))
            else:
                # Yielding something else is an error.
                self._loop.call_soon(
237
                    self._step,
238 239
                    RuntimeError(
                        'Task got bad yield: {!r}'.format(result)))
240 241
        finally:
            self.__class__._current_tasks.pop(self._loop)
242
            self = None  # Needed to break cycles when an exception occurs.
243 244 245

    def _wakeup(self, future):
        try:
246
            future.result()
247 248
        except Exception as exc:
            # This may also be a cancellation.
249
            self._step(exc)
250
        else:
251 252 253 254 255 256 257
            # Don't pass the value of `future.result()` explicitly,
            # as `Future.__iter__` and `Future.__await__` don't need it.
            # If we call `_step(value, None)` instead of `_step()`,
            # Python eval loop would use `.send(value)` method call,
            # instead of `__next__()`, which is slower for futures
            # that return non-generator iterators from their `__iter__`.
            self._step()
258 259 260
        self = None  # Needed to break cycles when an exception occurs.


261 262 263 264 265 266 267 268 269 270 271 272
_PyTask = Task


try:
    import _asyncio
except ImportError:
    pass
else:
    # _CTask is needed for tests.
    Task = _CTask = _asyncio.Task


273 274 275 276 277 278 279 280 281 282 283
# wait() and as_completed() similar to those in PEP 3148.

FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED
FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION
ALL_COMPLETED = concurrent.futures.ALL_COMPLETED


@coroutine
def wait(fs, *, loop=None, timeout=None, return_when=ALL_COMPLETED):
    """Wait for the Futures and coroutines given by fs to complete.

284 285
    The sequence futures must not be empty.

286 287 288 289 290 291 292 293 294 295 296
    Coroutines will be wrapped in Tasks.

    Returns two sets of Future: (done, pending).

    Usage:

        done, pending = yield from asyncio.wait(fs)

    Note: This does not raise TimeoutError! Futures that aren't done
    when the timeout occurs are returned in the second set.
    """
297
    if futures.isfuture(fs) or coroutines.iscoroutine(fs):
298
        raise TypeError("expect a list of futures, not %s" % type(fs).__name__)
299 300
    if not fs:
        raise ValueError('Set of coroutines/Futures is empty.')
301 302
    if return_when not in (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED):
        raise ValueError('Invalid return_when value: {}'.format(return_when))
303 304 305 306

    if loop is None:
        loop = events.get_event_loop()

307
    fs = {ensure_future(f, loop=loop) for f in set(fs)}
308 309 310 311

    return (yield from _wait(fs, timeout, return_when, loop))


312
def _release_waiter(waiter, *args):
313
    if not waiter.done():
314
        waiter.set_result(None)
315 316 317 318 319 320 321 322


@coroutine
def wait_for(fut, timeout, *, loop=None):
    """Wait for the single Future or coroutine to complete, with timeout.

    Coroutine will be wrapped in Task.

323 324 325
    Returns result of the Future or coroutine.  When a timeout occurs,
    it cancels the task and raises TimeoutError.  To avoid the task
    cancellation, wrap it in shield().
326

327
    If the wait is cancelled, the task is also cancelled.
328

329
    This function is a coroutine.
330 331 332 333
    """
    if loop is None:
        loop = events.get_event_loop()

334 335 336
    if timeout is None:
        return (yield from fut)

337
    waiter = loop.create_future()
338 339
    timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
    cb = functools.partial(_release_waiter, waiter)
340

341
    fut = ensure_future(fut, loop=loop)
342 343 344
    fut.add_done_callback(cb)

    try:
345
        # wait until the future completes or the timeout
346 347 348 349 350 351
        try:
            yield from waiter
        except futures.CancelledError:
            fut.remove_done_callback(cb)
            fut.cancel()
            raise
352 353

        if fut.done():
354 355 356
            return fut.result()
        else:
            fut.remove_done_callback(cb)
357
            fut.cancel()
358 359 360 361 362 363 364
            raise futures.TimeoutError()
    finally:
        timeout_handle.cancel()


@coroutine
def _wait(fs, timeout, return_when, loop):
365
    """Internal helper for wait() and wait_for().
366 367 368 369

    The fs argument must be a collection of Futures.
    """
    assert fs, 'Set of Futures is empty.'
370
    waiter = loop.create_future()
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
    timeout_handle = None
    if timeout is not None:
        timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
    counter = len(fs)

    def _on_completion(f):
        nonlocal counter
        counter -= 1
        if (counter <= 0 or
            return_when == FIRST_COMPLETED or
            return_when == FIRST_EXCEPTION and (not f.cancelled() and
                                                f.exception() is not None)):
            if timeout_handle is not None:
                timeout_handle.cancel()
            if not waiter.done():
386
                waiter.set_result(None)
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408

    for f in fs:
        f.add_done_callback(_on_completion)

    try:
        yield from waiter
    finally:
        if timeout_handle is not None:
            timeout_handle.cancel()

    done, pending = set(), set()
    for f in fs:
        f.remove_done_callback(_on_completion)
        if f.done():
            done.add(f)
        else:
            pending.add(f)
    return done, pending


# This is *not* a @coroutine!  It is just an iterator (yielding Futures).
def as_completed(fs, *, loop=None, timeout=None):
409 410 411 412 413
    """Return an iterator whose values are coroutines.

    When waiting for the yielded coroutines you'll get the results (or
    exceptions!) of the original Futures (or coroutines), in the order
    in which and as soon as they complete.
414 415 416 417 418 419 420

    This differs from PEP 3148; the proper way to use this is:

        for f in as_completed(fs):
            result = yield from f  # The 'yield from' may raise.
            # Use result.

421 422
    If a timeout is specified, the 'yield from' will raise
    TimeoutError when the timeout occurs before all Futures are done.
423 424 425

    Note: The futures 'f' are not necessarily members of fs.
    """
426
    if futures.isfuture(fs) or coroutines.iscoroutine(fs):
427
        raise TypeError("expect a list of futures, not %s" % type(fs).__name__)
428
    loop = loop if loop is not None else events.get_event_loop()
429
    todo = {ensure_future(f, loop=loop) for f in set(fs)}
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
    from .queues import Queue  # Import here to avoid circular import problem.
    done = Queue(loop=loop)
    timeout_handle = None

    def _on_timeout():
        for f in todo:
            f.remove_done_callback(_on_completion)
            done.put_nowait(None)  # Queue a dummy value for _wait_for_one().
        todo.clear()  # Can't do todo.remove(f) in the loop.

    def _on_completion(f):
        if not todo:
            return  # _on_timeout() was here first.
        todo.remove(f)
        done.put_nowait(f)
        if not todo and timeout_handle is not None:
            timeout_handle.cancel()
447 448 449

    @coroutine
    def _wait_for_one():
450 451 452 453 454
        f = yield from done.get()
        if f is None:
            # Dummy value from _on_timeout().
            raise futures.TimeoutError
        return f.result()  # May raise f.exception().
455

456 457 458 459
    for f in todo:
        f.add_done_callback(_on_completion)
    if todo and timeout is not None:
        timeout_handle = loop.call_later(timeout, _on_timeout)
460 461 462 463 464 465 466
    for _ in range(len(todo)):
        yield _wait_for_one()


@coroutine
def sleep(delay, result=None, *, loop=None):
    """Coroutine that completes after a given time (in seconds)."""
467 468 469 470
    if delay == 0:
        yield
        return result

471 472 473
    if loop is None:
        loop = events.get_event_loop()
    future = loop.create_future()
474
    h = future._loop.call_later(delay,
475 476
                                futures._set_result_unless_cancelled,
                                future, result)
477 478 479 480 481 482
    try:
        return (yield from future)
    finally:
        h.cancel()


Yury Selivanov's avatar
Yury Selivanov committed
483
def async_(coro_or_future, *, loop=None):
484 485
    """Wrap a coroutine in a future.

486 487 488 489 490 491
    If the argument is a Future, it is returned directly.

    This function is deprecated in 3.5. Use asyncio.ensure_future() instead.
    """

    warnings.warn("asyncio.async() function is deprecated, use ensure_future()",
492 493
                  DeprecationWarning,
                  stacklevel=2)
494 495 496

    return ensure_future(coro_or_future, loop=loop)

Yury Selivanov's avatar
Yury Selivanov committed
497 498 499 500 501
# Silence DeprecationWarning:
globals()['async'] = async_
async_.__name__ = 'async'
del async_

502 503

def ensure_future(coro_or_future, *, loop=None):
504
    """Wrap a coroutine or an awaitable in a future.
505

506 507
    If the argument is a Future, it is returned directly.
    """
508
    if futures.isfuture(coro_or_future):
509 510 511
        if loop is not None and loop is not coro_or_future._loop:
            raise ValueError('loop argument must agree with Future')
        return coro_or_future
512
    elif coroutines.iscoroutine(coro_or_future):
513 514 515
        if loop is None:
            loop = events.get_event_loop()
        task = loop.create_task(coro_or_future)
516 517 518
        if task._source_traceback:
            del task._source_traceback[-1]
        return task
519 520
    elif compat.PY35 and inspect.isawaitable(coro_or_future):
        return ensure_future(_wrap_awaitable(coro_or_future), loop=loop)
521
    else:
522 523
        raise TypeError('An asyncio.Future, a coroutine or an awaitable is '
                        'required')
524 525 526 527 528 529 530 531 532 533


@coroutine
def _wrap_awaitable(awaitable):
    """Helper for asyncio.ensure_future().

    Wraps awaitable (an object with __await__) into a coroutine
    that will later be wrapped in a Task by ensure_future().
    """
    return (yield from awaitable.__await__())
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550


class _GatheringFuture(futures.Future):
    """Helper for gather().

    This overrides cancel() to cancel all the children and act more
    like Task.cancel(), which doesn't immediately mark itself as
    cancelled.
    """

    def __init__(self, children, *, loop=None):
        super().__init__(loop=loop)
        self._children = children

    def cancel(self):
        if self.done():
            return False
551
        ret = False
552
        for child in self._children:
553 554 555
            if child.cancel():
                ret = True
        return ret
556 557 558 559 560 561


def gather(*coros_or_futures, loop=None, return_exceptions=False):
    """Return a future aggregating results from the given coroutines
    or futures.

562 563 564 565
    Coroutines will be wrapped in a future and scheduled in the event
    loop. They will not necessarily be scheduled in the same order as
    passed in.

566 567 568
    All futures must share the same event loop.  If all the tasks are
    done successfully, the returned future's result is the list of
    results (in the order of the original sequence, not necessarily
569
    the order of results arrival).  If *return_exceptions* is True,
570 571 572 573 574 575 576 577 578 579 580 581
    exceptions in the tasks are treated the same as successful
    results, and gathered in the result list; otherwise, the first
    raised exception will be immediately propagated to the returned
    future.

    Cancellation: if the outer Future is cancelled, all children (that
    have not completed yet) are also cancelled.  If any child is
    cancelled, this is treated as if it raised CancelledError --
    the outer Future is *not* cancelled in this case.  (This is to
    prevent the cancellation of one child to cause other children to
    be cancelled.)
    """
582
    if not coros_or_futures:
583 584 585
        if loop is None:
            loop = events.get_event_loop()
        outer = loop.create_future()
586 587
        outer.set_result([])
        return outer
588 589 590

    arg_to_fut = {}
    for arg in set(coros_or_futures):
591
        if not futures.isfuture(arg):
592
            fut = ensure_future(arg, loop=loop)
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
            if loop is None:
                loop = fut._loop
            # The caller cannot control this future, the "destroy pending task"
            # warning should not be emitted.
            fut._log_destroy_pending = False
        else:
            fut = arg
            if loop is None:
                loop = fut._loop
            elif fut._loop is not loop:
                raise ValueError("futures are tied to different event loops")
        arg_to_fut[arg] = fut

    children = [arg_to_fut[arg] for arg in coros_or_futures]
    nchildren = len(children)
608 609
    outer = _GatheringFuture(children, loop=loop)
    nfinished = 0
610
    results = [None] * nchildren
611 612 613

    def _done_callback(i, fut):
        nonlocal nfinished
614 615
        if outer.done():
            if not fut.cancelled():
616 617 618
                # Mark exception retrieved.
                fut.exception()
            return
619

620
        if fut.cancelled():
621 622 623 624 625 626 627 628 629 630 631 632 633
            res = futures.CancelledError()
            if not return_exceptions:
                outer.set_exception(res)
                return
        elif fut._exception is not None:
            res = fut.exception()  # Mark exception retrieved.
            if not return_exceptions:
                outer.set_exception(res)
                return
        else:
            res = fut._result
        results[i] = res
        nfinished += 1
634
        if nfinished == nchildren:
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
            outer.set_result(results)

    for i, fut in enumerate(children):
        fut.add_done_callback(functools.partial(_done_callback, i))
    return outer


def shield(arg, *, loop=None):
    """Wait for a future, shielding it from cancellation.

    The statement

        res = yield from shield(something())

    is exactly equivalent to the statement

        res = yield from something()

    *except* that if the coroutine containing it is cancelled, the
    task running in something() is not cancelled.  From the POV of
    something(), the cancellation did not happen.  But its caller is
    still cancelled, so the yield-from expression still raises
    CancelledError.  Note: If something() is cancelled by other means
    this will still cancel shield().

    If you want to completely ignore cancellation (not recommended)
    you can combine shield() with a try/except clause, as follows:

        try:
            res = yield from shield(something())
        except CancelledError:
            res = None
    """
668
    inner = ensure_future(arg, loop=loop)
669 670 671 672
    if inner.done():
        # Shortcut.
        return inner
    loop = inner._loop
673
    outer = loop.create_future()
674 675 676

    def _done_callback(inner):
        if outer.cancelled():
677 678 679
            if not inner.cancelled():
                # Mark inner's result as retrieved.
                inner.exception()
680
            return
681

682 683 684 685 686 687 688 689 690 691 692
        if inner.cancelled():
            outer.cancel()
        else:
            exc = inner.exception()
            if exc is not None:
                outer.set_exception(exc)
            else:
                outer.set_result(inner.result())

    inner.add_done_callback(_done_callback)
    return outer
693 694 695 696 697 698 699 700 701 702 703 704


def run_coroutine_threadsafe(coro, loop):
    """Submit a coroutine object to a given event loop.

    Return a concurrent.futures.Future to access the result.
    """
    if not coroutines.iscoroutine(coro):
        raise TypeError('A coroutine object is required')
    future = concurrent.futures.Future()

    def callback():
705 706 707 708 709 710
        try:
            futures._chain_future(ensure_future(coro, loop=loop), future)
        except Exception as exc:
            if future.set_running_or_notify_cancel():
                future.set_exception(exc)
            raise
711 712 713

    loop.call_soon_threadsafe(callback)
    return future