Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/guide/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ The number of signals before a hard kill can be configured with the `--hardkill-
* `--ack-type` - Type of acknowledgement. This parameter is used to set when to acknowledge the task. Possible values are `when_received`, `when_executed`, `when_saved`, `manual`. Default is `when_saved`.
* `--max-tasks-per-child` - maximum number of tasks to be executed by a single worker process before restart.
* `--max-fails` - Maximum number of child process exits.
* `--shutdown-timeout` - maximum amount of time for graceful broker's shutdown in seconds (default 5).
* `--shutdown-timeout` - maximum amount of time for graceful broker's shutdown in seconds (default 5). A worker process that is still running 1 second after this timeout, for example because the broker left a non-daemon thread behind, is terminated, so the process manager can restart it.
* `--wait-tasks-timeout` - if cannot read new messages from the broker or maximum number of tasks is reached, worker will wait for all current tasks to finish. This parameter sets the maximum amount of time to wait until shutdown.
* `--hardkill-count` - Number of termination signals to the main process before performing a hardkill.

Expand Down
55 changes: 53 additions & 2 deletions taskiq/cli/worker/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
import os
import signal
import sys
import threading
from concurrent.futures import Executor, ProcessPoolExecutor, ThreadPoolExecutor
from multiprocessing import get_start_method, set_start_method
from multiprocessing import get_start_method, parent_process, set_start_method
from sys import platform
from typing import Any

Expand All @@ -28,6 +29,41 @@

logger = logging.getLogger("taskiq.worker")

# Extra time given to a worker process to exit on its own
# after the broker shutdown timeout has elapsed.
EXIT_GRACE_PERIOD = 1.0


def force_exit_after(timeout: float) -> None:
"""
Terminate the current process if it doesn't exit within the timeout.

A worker process that finished a graceful shutdown may still be kept alive.
A broker can leave a non-daemon thread behind, which makes the interpreter
wait for it at exit, or it can block the event loop in `shutdown`, which
makes `asyncio.wait_for` unable to fire. The process manager restarts
only dead workers, so such a worker would neither consume tasks
nor be restarted, for example after `--max-tasks-per-child` is reached.

The watchdog is a daemon thread, so it doesn't delay a process
that exits in time, and it keeps running while the interpreter
waits for non-daemon threads.

:param timeout: seconds to wait for the process to exit on its own.
"""

def _exit() -> None:
logger.warning(
"Worker process didn't exit in %s seconds after shutdown. Forcing exit.",
timeout,
)
logging.shutdown()
os._exit(0)

watchdog = threading.Timer(timeout, _exit)
watchdog.daemon = True
watchdog.start()


async def shutdown_broker(broker: AsyncBroker, timeout: float) -> None:
"""
Expand Down Expand Up @@ -56,6 +92,21 @@ async def shutdown_broker(broker: AsyncBroker, timeout: float) -> None:
)


async def shutdown_worker(broker: AsyncBroker, timeout: float) -> None:
"""
Shutdown the broker and make sure that the worker process exits.

:param broker: current broker.
:param timeout: maximum amount of time to shutdown the broker.
"""
# Only enforce the exit in a child process of the process manager.
# This can also run in the current process when `start_listen`
# is called directly, and such a process must never be killed.
if parent_process() is not None:
force_exit_after(timeout + EXIT_GRACE_PERIOD)
await shutdown_broker(broker, timeout)


def get_receiver_type(args: WorkerArgs) -> type[Receiver]:
"""
Import Receiver from args.
Expand Down Expand Up @@ -175,7 +226,7 @@ def interrupt_handler(signum: int, _frame: Any) -> None:
)
loop.run_until_complete(receiver.listen(shutdown_event))
finally:
loop.run_until_complete(shutdown_broker(broker, args.shutdown_timeout))
loop.run_until_complete(shutdown_worker(broker, args.shutdown_timeout))


def run_worker(args: WorkerArgs) -> int | None:
Expand Down
209 changes: 209 additions & 0 deletions tests/cli/worker/test_worker_exit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
import multiprocessing
import os
import queue
import signal
import subprocess
import sys
import threading
import time
from pathlib import Path

import pytest

from taskiq.cli.worker import run

# A broker that feeds a single task to a worker, which is enough for
# `--max-tasks-per-child 1`, and then misbehaves in `shutdown` depending
# on the `BROKER_MODE` environment variable.
BROKER_MODULE = """
import asyncio
import os
import threading
import time
from collections.abc import AsyncGenerator

from taskiq import AsyncBroker, BrokerMessage

MODE = os.environ["BROKER_MODE"]


class MisbehavingBroker(AsyncBroker):
async def kick(self, message: BrokerMessage) -> None:
pass

async def listen(self) -> AsyncGenerator[bytes, None]:
yield (
b'{"task_id": "1", "task_name": "misbehaving_broker:noop",'
b' "labels": {}, "args": [], "kwargs": {}}'
)
while True:
await asyncio.sleep(3600)

async def shutdown(self) -> None:
if MODE == "thread":
# A non-daemon thread makes the interpreter wait for it at exit.
threading.Thread(target=time.sleep, args=(3600,)).start()
elif MODE == "blocking":
# Blocks the event loop, so asyncio.wait_for can't time it out.
time.sleep(3600)


broker = MisbehavingBroker()


@broker.task
async def noop() -> None:
pass
"""

# Runs the taskiq CLI, optionally forcing a multiprocessing start method first.
CLI_RUNNER = """
import multiprocessing
import sys

from taskiq.__main__ import main

if __name__ == "__main__":
start_method = sys.argv.pop(1)
if start_method != "default":
multiprocessing.set_start_method(start_method)
main()
"""

RESTART_TIMEOUT = 30
RESTARTED = "is dead. Scheduling reload."
FORCED_EXIT = "Forcing exit."


def worker_start_methods() -> list[str]:
# The worker always uses "spawn" on macOS: forcing another method would conflict.
if sys.platform == "darwin":
return ["default"]
return multiprocessing.get_all_start_methods()


def read_output_until(process: subprocess.Popen[str], text: str) -> list[str]:
"""Collect the process output until a line with the text appears."""
lines: queue.Queue[str] = queue.Queue()

def read_output() -> None:
assert process.stdout is not None
for line in process.stdout:
lines.put(line)

threading.Thread(target=read_output, daemon=True).start()
collected: list[str] = []
deadline = time.monotonic() + RESTART_TIMEOUT
while (remaining := deadline - time.monotonic()) > 0:
try:
line = lines.get(timeout=remaining)
except queue.Empty:
break
collected.append(line)
if text in line:
break
return collected


def kill_process_group(process: subprocess.Popen[str]) -> None:
"""
Kill the process manager together with all its workers.

The worker is being restarted when the output is checked, so stopping
the manager gracefully would race with the start of a new worker.
"""
os.killpg(process.pid, signal.SIGKILL)
process.wait()


def run_worker_with_max_tasks(
tmp_path: Path,
start_method: str,
broker_mode: str,
) -> list[str]:
"""Run a worker that stops after one task and return the output until restart."""
(tmp_path / "misbehaving_broker.py").write_text(BROKER_MODULE)
(tmp_path / "run_cli.py").write_text(CLI_RUNNER)
process = subprocess.Popen( # noqa: S603
[
sys.executable,
"run_cli.py",
start_method,
"worker",
"misbehaving_broker:broker",
"misbehaving_broker",
"--workers",
"1",
"--max-tasks-per-child",
"1",
"--shutdown-timeout",
"0.5",
"--log-level",
"INFO",
],
cwd=tmp_path,
env={**os.environ, "BROKER_MODE": broker_mode},
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
start_new_session=True,
)
try:
return read_output_until(process, RESTARTED)
finally:
kill_process_group(process)


@pytest.mark.skipif(
sys.platform == "win32",
reason="Process groups are not supported on Windows.",
)
@pytest.mark.parametrize("broker_mode", ["thread", "blocking"])
@pytest.mark.parametrize("start_method", worker_start_methods())
def test_worker_is_restarted_when_broker_blocks_exit(
tmp_path: Path,
start_method: str,
broker_mode: str,
) -> None:
"""
A worker is restarted even if the broker prevents it from exiting.

Without a forced exit the worker process stays alive after it reached
`--max-tasks-per-child`, and the process manager never restarts it.
"""
output = "".join(run_worker_with_max_tasks(tmp_path, start_method, broker_mode))

assert RESTARTED in output
assert FORCED_EXIT in output


@pytest.mark.skipif(
sys.platform == "win32",
reason="Process groups are not supported on Windows.",
)
@pytest.mark.parametrize("start_method", worker_start_methods())
def test_worker_exit_is_not_forced_when_shutdown_is_clean(
tmp_path: Path,
start_method: str,
) -> None:
"""A worker that exits on its own is restarted without being terminated."""
output = "".join(run_worker_with_max_tasks(tmp_path, start_method, "clean"))

assert RESTARTED in output
assert FORCED_EXIT not in output


def test_force_exit_after_terminates_process(monkeypatch: pytest.MonkeyPatch) -> None:
exit_codes: list[int] = []
exited = threading.Event()

def fake_exit(code: int) -> None:
exit_codes.append(code)
exited.set()

monkeypatch.setattr(run.os, "_exit", fake_exit)

run.force_exit_after(0.05)

assert exited.wait(timeout=5)
assert exit_codes == [0]
Loading