Example #1
0
def cancel_all_tasks(loop: asyncio.AbstractEventLoop) -> None:
    """Cancels all tasks in a loop.

    Parameters
    ----------
    loop: :class:`asyncio.AbstractEventLoop`
        Event loop to cancel tasks in.
    """
    try:
        to_cancel = asyncio.all_tasks(loop)
    except AttributeError:  # py < 3.7
        to_cancel = asyncio.Task.all_tasks(loop)

    if not to_cancel:
        return

    for task in to_cancel:
        task.cancel()

    loop.run_until_complete(
        asyncio.gather(*to_cancel, loop=loop, return_exceptions=True))

    for task in to_cancel:
        if task.cancelled():
            continue

        if task.exception() is not None:
            loop.call_exception_handler({
                'message': 'Unhandled exception during runner shutdown',
                'exception': task.exception(),
                'task': task
            })
def _cancel_all_tasks(loop: asyncio.AbstractEventLoop) -> None:
    if sys.version_info >= (3, 7):
        to_cancel = asyncio.all_tasks(loop)
    else:
        to_cancel = [t for t in asyncio.Task.all_tasks(loop) if not t.done()]
    if not to_cancel:
        return

    for task in to_cancel:
        task.cancel()

    loop.run_until_complete(
        asyncio.gather(*to_cancel, loop=loop, return_exceptions=True))

    # temporary shut up the logger until aiohttp will be fixed
    # the message scares people :)
    return
    for task in to_cancel:
        if task.cancelled():
            continue
        if task.exception() is not None:
            loop.call_exception_handler({
                "message": "unhandled exception during asyncio.run() shutdown",
                "exception": task.exception(),
                "task": task,
            })
def _cancel_all_tasks_with_timeout(loop: asyncio.AbstractEventLoop,
                                   timeout: int) -> None:
    """Adapted _cancel_all_tasks from python 3.9 with a timeout."""
    to_cancel = asyncio.all_tasks(loop)
    if not to_cancel:
        return

    for task in to_cancel:
        task.cancel()

    loop.run_until_complete(asyncio.wait(to_cancel, timeout=timeout))

    for task in to_cancel:
        if task.cancelled():
            continue
        if not task.done():
            _LOGGER.warning(
                "Task could not be canceled and was still running after shutdown: %s",
                task,
            )
            continue
        if task.exception() is not None:
            loop.call_exception_handler({
                "message": "unhandled exception during shutdown",
                "exception": task.exception(),
                "task": task,
            })
def _cancel_all_tasks(loop: AbstractEventLoop) -> None:
    """Cancels all tasks the supplied event loop is running

    :param loop: The event loop to use
    """
    to_cancel = tasks.all_tasks(loop)
    if not to_cancel:
        return

    for task in to_cancel:
        task.cancel()

    loop.run_until_complete(
        tasks.gather(*to_cancel, loop=loop, return_exceptions=True))

    for task in to_cancel:
        if task.cancelled():
            continue
        if task.exception() is not None:
            loop.call_exception_handler({
                "message":
                "unhandled exception during run_automation() shutdown",
                "exception": task.exception(),
                "task": task,
            })
Example #5
0
def _shutdown_tasks(loop: asyncio.AbstractEventLoop) -> None:
    """Завершение в случае ошибки.

    После ошибки происходит отмена всех заданий, чтобы не захламлять сообщение об ошибке множеством
    сообщений, о том, что результат выполнения задания не был awaited.

    Идея кода позаимствована из реализации asyncio.app.
    """
    to_cancel = asyncio.all_tasks(loop)
    if not to_cancel:
        return

    for task in to_cancel:
        task.cancel()

    loop.run_until_complete(asyncio.gather(*to_cancel, loop=loop, return_exceptions=True))

    for canceled_task in to_cancel:
        if canceled_task.cancelled():
            continue
        if canceled_task.exception() is not None:
            loop.call_exception_handler(
                {
                    "message": "unhandled EventBus exception",
                    "exception": canceled_task.exception(),
                    "task": canceled_task,
                },
            )

    loop.run_until_complete(loop.shutdown_asyncgens())
    loop.run_until_complete(loop.shutdown_default_executor())
Example #6
0
def _cancel_all_tasks(
    loop: asyncio.AbstractEventLoop,
    ignored_exceptions: Optional[Set[Type[Exception]]] = None,
) -> None:
    """
    Cancel all tasks on the given event loop.

    :param loop:                The loop to cancel all tasks on
    :param ignored_exceptions:  The set of exceptions classes to silently ignore
    :return:                    None
    """
    to_cancel = asyncio.Task.all_tasks(loop)
    if not to_cancel:
        return

    for task in to_cancel:
        task.cancel()

    loop.run_until_complete(
        asyncio.tasks.gather(*to_cancel, loop=loop, return_exceptions=True))

    for task in to_cancel:
        if task.cancelled():
            continue
        if task.exception() is not None:
            exception = task.exception()
            if ignored_exceptions and any(
                    isinstance(exception, exception_type)
                    for exception_type in ignored_exceptions):
                continue
            loop.call_exception_handler({
                "message": "unhandled exception during asyncio.run() shutdown",
                "exception": exception,
                "task": task,
            })
def default_araise(exc: Exception, *, loop: AbstractEventLoop) -> bool:
    loop.call_exception_handler(
        {
            "message": f"Unhandled error propagated through {AnonymousObserver.__qualname__}",
            "exception": exc,
        }
    )
    return False
Example #8
0
async def test_asyncio_error_handler(
    client: TestClient,
    loop: asyncio.AbstractEventLoop,
) -> None:
    assert client.app.frozen

    context = {
        "message": "Error message",
    }

    with patch.object(app_logger, "warning") as warning:
        loop.call_exception_handler(context)

    message = "Caught asyncio exception: {message}".format_map(context)
    warning.assert_called_with(message)
Example #9
0
def _cancel_all_tasks(loop: asyncio.AbstractEventLoop) -> None:
    tasks = [task for task in asyncio.all_tasks(loop) if not task.done()]
    if not tasks:
        return

    for task in tasks:
        task.cancel()
    loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))

    for task in tasks:
        if not task.cancelled() and task.exception() is not None:
            loop.call_exception_handler({
                "message": "unhandled exception during shutdown",
                "exception": task.exception(),
                "task": task,
            })
Example #10
0
def _cancel_tasks(to_cancel: Set["asyncio.Task[Any]"],
                  loop: asyncio.AbstractEventLoop) -> None:
    if not to_cancel:
        return

    for task in to_cancel:
        task.cancel()

    loop.run_until_complete(asyncio.gather(*to_cancel, return_exceptions=True))

    for task in to_cancel:
        if task.cancelled():
            continue
        if task.exception() is not None:
            loop.call_exception_handler({
                "message": "unhandled exception during asyncio.run() shutdown",
                "exception": task.exception(),
                "task": task,
            })
Example #11
0
def _cancel_all_tasks(loop: asyncio.AbstractEventLoop) -> None:
    to_cancel = asyncio.all_tasks(loop)
    if not to_cancel:
        return

    for task in to_cancel:
        task.cancel()

    loop.run_until_complete(asyncio.gather(*to_cancel, return_exceptions=True))

    for task in to_cancel:
        if task.cancelled():
            continue
        if (exception := task.exception()) is not None:
            loop.call_exception_handler({
                "message": "unhandled exception during shutdown",
                "exception": exception,
                "task": task,
            })
Example #12
0
def _cancel_all_tasks(loop: asyncio.AbstractEventLoop) -> None:
    to_cancel = all_tasks(loop)
    if not to_cancel:
        return

    for task in to_cancel:
        task.cancel()

    loop.run_until_complete(
        asyncio.gather(*to_cancel, loop=loop, return_exceptions=True))

    for task in to_cancel:
        if task.cancelled():
            continue
        if task.exception() is not None:
            loop.call_exception_handler({
                'message': 'unhandled exception during asyncio.run() shutdown',
                'exception': task.exception(),
                'task': task,
            })
Example #13
0
def _cancel_all_tasks(loop: asyncio.AbstractEventLoop) -> None:
    to_cancel = all_tasks(loop)
    if not to_cancel:
        return

    for task in to_cancel:
        task.cancel()

    loop.run_until_complete(
        asyncio.gather(*to_cancel, loop=loop, return_exceptions=True))

    for task in to_cancel:
        if task.cancelled():
            continue
        if task.exception() is not None:
            loop.call_exception_handler({
                'message': 'unhandled exception during asyncio.run() shutdown',
                'exception': task.exception(),
                'task': task,
            })
Example #14
0
def _cancel_tasks(loop: asyncio.AbstractEventLoop) -> None:
    tasks = {t for t in asyncio.all_tasks(loop=loop) if not t.done()}

    if not tasks:
        return

    log.info('Cleaning up after %d tasks.', len(tasks))
    for task in tasks:
        task.cancel()

    loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
    log.info('All tasks finished cancelling.')

    for task in tasks:
        if task.cancelled():
            continue
        if task.exception() is not None:
            loop.call_exception_handler({
                'message': 'Unhandled exception during Client.run shutdown.',
                'exception': task.exception(),
                'task': task
            })
Example #15
0
def _cancel_tasks(loop: asyncio.AbstractEventLoop) -> None:
    tasks = asyncio.all_tasks(loop=loop)

    if not tasks:
        return

    log.info(f"Cleaning up after {len(tasks)} tasks.")
    for task in tasks:
        task.cancel()

    loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
    log.info("All tasks finished cancelling.")

    for task in tasks:
        if task.cancelled():
            continue
        if task.exception() is not None:
            loop.call_exception_handler({
                "message": "unhandled exception during Client.run shutdown.",
                "exception": task.exception(),
                "task": task,
            })
Example #16
0
def _cancel_all_tasks(loop: asyncio.AbstractEventLoop,
                      is_current: bool) -> None:
    to_cancel = asyncio.all_tasks(loop)
    if not to_cancel:
        return

    done = threading.Event()
    count = len(to_cancel)

    def one_task_finished(future):
        nonlocal count
        count -= 1
        if count == 0:
            done.set()

    for task in to_cancel:
        loop.call_soon_threadsafe(task.cancel)
        task.add_done_callback(one_task_finished)

    if is_current:
        loop.run_until_complete(
            wait_for(
                asyncio.gather(*to_cancel, loop=loop, return_exceptions=True),
                TIMEOUT))
    else:
        # user was responsible for cancelling all tasks
        if not done.wait(timeout=3):
            raise TimeoutError("Could not stop event loop in time")

    for task in to_cancel:
        if task.cancelled():
            continue
        if task.exception() is not None:
            loop.call_exception_handler({
                "message": "unhandled exception during event loop shutdown",
                "exception": task.exception(),
                "task": task,
            })