diff --git a/docs/dev/rest-api/job-lifecycle.md b/docs/dev/rest-api/job-lifecycle.md index 8db34c75..a3e3be2f 100644 --- a/docs/dev/rest-api/job-lifecycle.md +++ b/docs/dev/rest-api/job-lifecycle.md @@ -417,7 +417,9 @@ Each job carries a cancellation event. When you `DELETE` a live job: to `cancelled`. The polling loop notices the event, `terminate()`s the job worker subprocess (escalating to `kill()` if it does not exit within 5 seconds), and raises a cancellation so the task unwinds. The subprocess model is what makes this a clean, - immediate stop rather than a cooperative one. + immediate stop rather than a cooperative one. A job with the `remote` parameter first ends its + [remote session](remote-sessions.md#when-the-client-ends-a-remote-session), in at most 4 + seconds, and runs no post-script after the cancel. ### Secret handling in serialized jobs diff --git a/docs/dev/rest-api/remote-sessions.md b/docs/dev/rest-api/remote-sessions.md index 54abc026..c8755b7d 100644 --- a/docs/dev/rest-api/remote-sessions.md +++ b/docs/dev/rest-api/remote-sessions.md @@ -808,13 +808,13 @@ saves the returned cache and then stops the tunnel. It does so: - when `dl` has finished every title, before the run post-scripts - when the process exits: `--list`, an error, or Ctrl+C in any step, also before `create` answers +- when a signal or a closed console stops the process, or the cancel of a download job stops its worker - when the login or any other step of the opening fails, or `create` times out or its answer is cut off - when a serve that relays for a REST client closes its pooled remote session The `DELETE` has a connect and read timeout of 15s each. The client sends it again only once, when a gateway answers with -an error page or asks for the API key in the other header. It does not wait for a rate limit. A process that ends without its exit hooks (`SIGHUP`, -`SIGTERM`, `SIGKILL`, a closed console window) sends no `DELETE`, so the remote session stays until its TTL. Ctrl+C -waits for the download threads before it ends the remote session. +an error page or asks for the API key in the other header. It does not wait for a rate limit. A Ctrl+C waits for the +download threads before it ends the remote session. While the client ends a remote session, it ignores the first Ctrl+C, so it does not lose the returned cache. The next Ctrl+C stops the wait at once, and the process then waits for no other end. The count of Ctrl+C is one for the process. @@ -822,6 +822,22 @@ When the run itself called the end, after the last title, that Ctrl+C also stops counts when the network read that blocks returns, so the 15s timeout limits the wait. After the end, no thread of the client opens a remote session again. +`SIGHUP` (a closed terminal) and `SIGTERM` stop `dl`, `search` and `tunnel-test` as Ctrl+C does, with an exit code other +than 0. Three things are different: + +- The `DELETE` goes first: before the wait for the download threads, for a CDM call and for the channel. +- The process ends 8s after the first signal at the latest, also when the server does not answer. +- A later signal changes nothing, and Ctrl+C keeps its own count. + +After `SIGHUP` the process writes nothing more to a terminal. A redirected output gets each line. `nohup` keeps its effect. +Source: `unshackle/core/process_exit.py`. + +On Windows, a closed console window and Ctrl+Break send the `DELETE` and then end the process, without the rest of the +Ctrl+C steps. The system gives a closed window about 5s. A kill (`SIGKILL`, a Windows task end, the cancel of a download +job on Windows) sends no `DELETE`, so only the server ends the remote session, at its own limits. + +A cancelled job that uses a remote server sends the `DELETE` for at most 4s, then its worker ends. + The `DELETE` can arrive while the server still works on `create`. The server then answers `200` with no cache, and the `create` makes no remote session, starts no login and answers `404 SESSION_NOT_FOUND`. diff --git a/tests/conftest.py b/tests/conftest.py index 660bcbaf..8c2ba9dc 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -11,7 +11,7 @@ from typing import Any import pytest -from unshackle.core import binaries +from unshackle.core import binaries, process_exit from unshackle.core import session as http_session from unshackle.core.config import config from unshackle.core.providers import anilist @@ -59,6 +59,14 @@ def client_process(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(http_session, "record_bodies", True) +@pytest.fixture(autouse=True) +def keep_signal_handlers(monkeypatch: pytest.MonkeyPatch) -> None: + """Keep the signal handlers of a command or a job worker out of the pytest process.""" + monkeypatch.setattr(process_exit, "listen", lambda *args: None) + monkeypatch.setattr(process_exit.Stop, "raised", False) + monkeypatch.setattr(process_exit, "ends", set()) + + @pytest.fixture(autouse=True) def fresh_proxy_catalogues() -> None: """Fetch each proxy provider catalogue again, so one test's stub never answers another test.""" diff --git a/tests/remote/unit/test_process_exit.py b/tests/remote/unit/test_process_exit.py new file mode 100644 index 00000000..b75b2c8b --- /dev/null +++ b/tests/remote/unit/test_process_exit.py @@ -0,0 +1,949 @@ +"""Each way a client process dies ends its remote session: a signal, a closed terminal, a cancelled job.""" + +from __future__ import annotations + +import asyncio +import json +import os +import shutil +import signal +import subprocess +import sys +import tempfile +import time +from collections.abc import Callable, Iterator +from dataclasses import asdict +from pathlib import Path +from threading import Event +from types import SimpleNamespace +from typing import Any + +import pytest + +from tests.remote.unit.test_remote_loopback import KEY, StubService, count, make_client, server # noqa: F401 +from tests.remote.unit.test_session_lifetime import ( # noqa: F401 + DEADLINE, + ROOT, + HeldDelete, + answered, + build, + held_delete, + logins, + sessions, +) +from tests.remote.unit.test_tunnel import wait_until +from unshackle.core import process_exit, tunnel +from unshackle.core.api import download_manager +from unshackle.core.api.job_channel import JobPayload, WorkerProcess +from unshackle.core.config import config +from unshackle.core.remote_protocol import SESSION_CREATE_ROUTE, SESSION_ROUTE +from unshackle.core.remote_service import RemoteError + +pytestmark = pytest.mark.unit + +posix = pytest.mark.skipif(sys.platform == "win32", reason="POSIX signals") +SIGNALS = ["CTRL_BREAK_EVENT"] if sys.platform == "win32" else ["SIGHUP", "SIGTERM"] +BOUND = 8.0 + +CLIENT = """ +import asyncio, contextlib, ctypes, os, signal, sys, time +from threading import Event, Thread +import click +from unshackle.core import process_exit +from unshackle.core.config import config +config.__init__(directories={"cache": sys.argv[2], "cookies": sys.argv[2] + "/cookies"}) +from tests.remote.unit.test_remote_loopback import make_client +from unshackle.core.remote_channel import WebSocketChannel +from unshackle.core.remote_service import RemoteError +service = make_client(sys.argv[1]) +phase, deadline = sys.argv[3], float(sys.argv[4]) +if phase == "login": + service._input_bridge = click.UNPROCESSED + click.UNPROCESSED.request_input = lambda prompt, qr=None: time.sleep(120) + +def stuck(*args): + Event().wait(120) + +def say(line): + print(line, flush=True) + +async def take_wakeup_fd(): + if sys.platform != "win32": + asyncio.get_running_loop().add_signal_handler(signal.SIGUSR1, stuck) + asyncio.get_running_loop().remove_signal_handler(signal.SIGUSR1) + +@click.command() +@click.pass_context +def run(ctx): + ctx.with_resource(process_exit.unwinding(deadline, linger=phase != "job-loop")) + service.authenticate() + say("ready") + if phase.endswith("-loop"): + asyncio.run(take_wakeup_fd()) + if phase == "close": + service.close() + say("closed") + elif phase == "swallow": + with contextlib.suppress(KeyboardInterrupt): + time.sleep(120) + sys.exit(0) + elif phase in ("pool", "pool-loop"): + def late(): + while service.lifetime._held: + time.sleep(0.01) + with contextlib.suppress(SystemExit): + service.get_titles() + stuck() + Thread(target=late).start() + elif phase == "return": + return + elif phase in ("print", "prints"): + def prints(write): + while True: + write("x" * 80) + time.sleep(0.01) + # Python aborts at exit when a daemon thread is in a print, so the thread does not use sys.stdout + Thread(target=prints, args=[lambda line: os.write(1, line.encode())], daemon=True).start() + say("set up") + if phase == "prints": + prints(say) + elif phase == "channel": + WebSocketChannel.close = stuck + elif phase == "cdm": + service.channel.messages.cdm_lock.acquire() + elif phase == "call": + thread = Thread(target=stuck, daemon=True) + thread.start() + say("set up") + if sys.platform == "win32": + ctypes.windll.kernel32.Sleep(120_000) + else: + ctypes.CDLL(None).pthread_join(ctypes.c_ulong(thread.ident), None) + elif phase == "reopen": + def refuse(credential): + raise RemoteError("EXAMPLE refused", "EXAMPLE") + service.open_session = refuse + service.lifetime.close_channel = lambda: os.kill(os.getpid(), signal.SIGTERM) + with contextlib.suppress(RemoteError): + service.authenticate() + say("goes on") + elif phase == "finally": + try: + say("set up") + time.sleep(120) + finally: + hung_up = Event() + process_exit.drop_terminals = hung_up.set + say("unwinds") + while not hung_up.is_set(): + time.sleep(0.01) + say("unwound") + elif phase == "handlers": + print(*(repr(signal.getsignal(s)) for s in (signal.SIGHUP, signal.SIGTERM)), flush=True) + say("set up") + time.sleep(120) + +if phase == "handlers": + signal.signal(signal.SIGHUP, signal.SIG_IGN) + signal.signal(signal.SIGTERM, lambda *args: os._exit(3)) +run(args=[]) +""" + +COMMAND = """ +import json, sys +from unshackle.core.config import config +config.__init__(**json.loads(sys.argv[1])) +from unshackle.core.utils import ip_info +ip_info.get_ip_info = lambda *args, **kwargs: {"ip": "192.0.2.1", "country": "us"} +from unshackle.core.__main__ import main +main(args=sys.argv[2:]) +""" + +WORKER = """#!{python} +import json, runpy, sys +sys.path.insert(0, {root!r}) +from unshackle.core.config import config +config.__init__(**json.loads({settings!r})) +module, sys.argv = sys.argv[2], sys.argv[2:] +runpy.run_module(module, run_name="__main__", alter_sys=True) +""" + + +def worker_script(url: str, path: Path) -> Path: + """An interpreter for a job worker that reaches the test server and nothing else.""" + script = path / "worker" + text = json.dumps(settings(url, path)) + script.write_text(WORKER.format(python=sys.executable, root=str(ROOT), settings=text), encoding="utf-8") + script.chmod(0o755) + return script + + +@pytest.fixture +def run(tmp_path: Path) -> Iterator[Callable[..., subprocess.Popen[str]]]: + """Start a process in a session or a console group of its own; a fixture so that no process outlives its test.""" + started: list[subprocess.Popen[str]] = [] + + def begin(*argv: str, **options: Any) -> subprocess.Popen[str]: + defaults: dict[str, Any] = {"stdin": subprocess.DEVNULL, "stdout": subprocess.PIPE, "stderr": subprocess.STDOUT} + if sys.platform == "win32": + defaults["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP + else: + defaults["start_new_session"] = True + argv = (sys.executable, *argv) + options = {**defaults, **options} + started.append(subprocess.Popen(argv, cwd=ROOT, text=True, encoding="utf-8", errors="replace", **options)) + return started[-1] + + yield begin + for process in started: + process.kill() + process.wait() + if process.stdout: + process.stdout.close() + + +def client(run: Callable[..., Any], url: str, cache: Path, phase: str, deadline: float = BOUND, **options: Any) -> Any: + return run("-c", CLIENT, url, str(cache), phase, str(deadline), **options) + + +def wait_line(process: subprocess.Popen[str], text: str) -> str: + assert process.stdout is not None + for line in process.stdout: + if text in line: + return line + pytest.fail(f"the client did not print {text!r}") + + +def still_runs(process: subprocess.Popen[str]) -> None: + with pytest.raises(subprocess.TimeoutExpired): + process.wait(0.3) + + +def read_until(controller: int, text: bytes) -> bytes: + output = b"" + while text not in output: + output += os.read(controller, 65536) + return output + + +def send(process: subprocess.Popen[str], name: str) -> None: + process.send_signal(getattr(signal, name)) + + +def settings(url: str, path: Path) -> dict[str, Any]: + """The config of a client process that reaches the test server and nothing else.""" + folders = ("cache", "cookies", "downloads", "temp", "logs", "services", "wvds", "prds") + return { + "remote_services": {"test": {"url": url, "api_key": KEY}}, + "directories": {name: str(path / name) for name in folders}, + "update_checks": False, + "title_cache_enabled": False, + "output_template": {"movies": "{title}", "series": "{title}", "songs": "{title}"}, + } + + +@pytest.fixture(autouse=True) +def lasting_sessions(server: SimpleNamespace) -> None: # noqa: F811 + """A session must not expire on the server while a test holds the DELETE back.""" + config.serve["session_ttl"] = 300 + + +@pytest.fixture +def titles( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], # noqa: F811 + example_service: None, +) -> Iterator[SimpleNamespace]: + """A server whose ``get_titles`` waits for ``release``.""" + barrier = SimpleNamespace(server=server, started=Event(), release=Event()) + + def hold(stub: StubService) -> None: + barrier.started.set() + assert barrier.release.wait(DEADLINE), "the test did not release the titles" + + StubService.hooks["titles"] = hold + try: + yield barrier + finally: + barrier.release.set() + + +def store_cache() -> None: + (entry,) = sessions() + stored = config.directories.cache / str(entry.cache_tag) / "token.json" + stored.parent.mkdir(parents=True) + stored.write_text('"EXAMPLE"', encoding="utf-8") + + +def saved(cache: Path) -> bool: + return (cache / "EXAMPLE" / "token.json").exists() + + +@pytest.mark.parametrize("name", SIGNALS) +def test_a_signal_before_the_create_reply_leaves_no_session( + build: SimpleNamespace, # noqa: F811 + run: Callable[..., Any], + tmp_path: Path, + name: str, +) -> None: + process = client(run, build.server.url, tmp_path / "client", "idle") + assert build.started.wait(DEADLINE) + send(process, name) + output, _ = process.communicate(timeout=DEADLINE) + assert process.returncode != 0 and "Traceback" not in output + assert count(build.server, "DELETE", SESSION_ROUTE) == 1 + + build.release.set() + assert wait_until(lambda: answered(build.server, 404), DEADLINE) + assert sessions() == [] and build.logins == [] + + +@pytest.mark.parametrize("name", SIGNALS) +def test_a_signal_during_the_login_leaves_no_session( + server: SimpleNamespace, # noqa: F811 + run: Callable[..., Any], + tmp_path: Path, + name: str, +) -> None: + process = client(run, server.url, tmp_path / "client", "login") + assert wait_until(lambda: [s for s in sessions() if s.input_bridge and s.channel.attached], DEADLINE) + send(process, name) + output, _ = process.communicate(timeout=DEADLINE) + assert process.returncode != 0 and "Traceback" not in output + assert sessions() == [] + + +@pytest.mark.parametrize("name", SIGNALS) +@pytest.mark.parametrize("phase", ["idle", "swallow"]) +def test_a_signal_waits_for_the_delete_and_saves_its_cache( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], # noqa: F811 + held_delete: HeldDelete, # noqa: F811 + run: Callable[..., Any], + tmp_path: Path, + phase: str, + name: str, +) -> None: + """A second signal does not stop the wait, and a run that goes on after its KeyboardInterrupt is no success.""" + process = client(run, server.url, tmp_path / "client", phase) + wait_line(process, "ready") + store_cache() + send(process, name) + assert held_delete.started.wait(DEADLINE) + if sys.platform != "win32": + send(process, name) + still_runs(process) + held_delete.release.set() + output, _ = process.communicate(timeout=DEADLINE) + + assert process.returncode != 0 and "Traceback" not in output + assert phase == "swallow" or sys.platform == "win32" or "Aborted" in output + assert saved(tmp_path / "client") + assert sessions() == [] and count(server, "DELETE", SESSION_ROUTE) == 1 + + +@pytest.mark.parametrize("name", SIGNALS) +@pytest.mark.parametrize("phase", ["close", "return"]) +def test_a_signal_during_the_end_of_the_session_is_no_success( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], # noqa: F811 + held_delete: HeldDelete, # noqa: F811 + run: Callable[..., Any], + tmp_path: Path, + phase: str, + name: str, +) -> None: + """The run closes its session, or returns with it open, such as ``--list``.""" + process = client(run, server.url, tmp_path / "client", phase) + wait_line(process, "ready") + assert held_delete.started.wait(DEADLINE) + store_cache() + send(process, name) + still_runs(process) + held_delete.release.set() + output, _ = process.communicate(timeout=DEADLINE) + + assert process.returncode != 0 + assert "closed" not in output and "Traceback" not in output + assert saved(tmp_path / "client") + assert sessions() == [] and count(server, "DELETE", SESSION_ROUTE) == 1 + + +@pytest.mark.parametrize("name", SIGNALS[-1:]) +@pytest.mark.parametrize("phase", ["pool", "channel", "cdm", "call", "pool-loop", "job-loop"]) +def test_a_wait_that_does_not_end_does_not_hold_the_delete_back( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], # noqa: F811 + run: Callable[..., Any], + tmp_path: Path, + phase: str, + name: str, +) -> None: + """A thread that the exit waits for and that calls the server after the end, a channel that does not close, a CDM + call that does not return, and a call in the main thread that no signal breaks. An event loop takes the wakeup fd. + """ + process = client(run, server.url, tmp_path / "client", phase, deadline=3) + wait_line(process, "set up") + store_cache() + sent = time.monotonic() + send(process, name) + assert wait_until(lambda: sessions() == [], 2.5) + output, _ = process.communicate(timeout=DEADLINE) + assert time.monotonic() - sent < 5 + assert process.returncode != 0 and saved(tmp_path / "client") + assert "error" not in output.lower() + + +@pytest.mark.parametrize("name", SIGNALS[-1:]) +def test_a_delete_that_the_server_does_not_answer_ends_at_the_deadline( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], # noqa: F811 + held_delete: HeldDelete, # noqa: F811 + run: Callable[..., Any], + tmp_path: Path, + name: str, +) -> None: + ignored = {} if sys.platform == "win32" else {"preexec_fn": lambda: signal.signal(signal.SIGALRM, signal.SIG_IGN)} + process = client(run, server.url, tmp_path / "client", "idle", deadline=2, **ignored) + wait_line(process, "ready") + sent = time.monotonic() + send(process, name) + assert held_delete.started.wait(DEADLINE) + if sys.platform != "win32": + with pytest.raises(subprocess.TimeoutExpired): + process.wait(1.5 - (time.monotonic() - sent)) + send(process, name) + process.communicate(timeout=DEADLINE) + assert 1.9 <= time.monotonic() - sent < 3.4 + assert process.returncode == (1 if sys.platform == "win32" else -signal.SIGALRM) + + +@posix +def test_only_the_first_signal_interrupts_the_unwind( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], # noqa: F811 + run: Callable[..., Any], + tmp_path: Path, +) -> None: + process = client(run, server.url, tmp_path / "client", "finally") + wait_line(process, "set up") + process.send_signal(signal.SIGTERM) + wait_line(process, "unwinds") + process.send_signal(signal.SIGTERM) + process.send_signal(signal.SIGHUP) + output, _ = process.communicate(timeout=DEADLINE) + assert "unwound" in output and "Aborted" in output and process.returncode == 1 + + +@posix +def test_a_signal_after_a_ctrl_c_ends_the_session_that_the_pool_holds( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], # noqa: F811 + run: Callable[..., Any], + tmp_path: Path, +) -> None: + process = client(run, server.url, tmp_path / "client", "pool", deadline=1) + wait_line(process, "set up") + process.send_signal(signal.SIGINT) + wait_line(process, "Aborted") + with pytest.raises(subprocess.TimeoutExpired): + process.wait(1.5) + assert len(sessions()) == 1 + process.send_signal(signal.SIGTERM) + assert process.wait(DEADLINE) != 0 + assert sessions() == [] + + +@posix +def test_a_signal_during_the_release_of_a_failed_reopen_stops_the_run( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], # noqa: F811 + run: Callable[..., Any], + tmp_path: Path, +) -> None: + output, _ = client(run, server.url, tmp_path / "client", "reopen").communicate(timeout=DEADLINE) + assert "ready" in output and "goes on" not in output and "Aborted" in output + assert sessions() == [] + + +@posix +def test_a_session_that_does_not_end_does_not_hold_the_next_one_back(run: Callable[..., Any]) -> None: + script = """ +import threading, time +from unshackle.core import process_exit + +ran = [] + +def fail(): + ran.append(1) + print("fails", flush=True) + raise RuntimeError + +def off_main(): + with process_exit.unwinding(): + print("thread ran", flush=True) + +thread = threading.Thread(target=off_main) +thread.start() +thread.join() +process_exit.Stop.raised = False +with process_exit.unwinding(): + for n in range(2): + process_exit.ends.add(lambda n=n: fail()) + try: + print("ready", flush=True) + time.sleep(120) + finally: + while len(ran) < 2: + time.sleep(0.01) +""" + process = run("-c", script) + wait_line(process, "thread ran") + assert wait_line(process, "").strip() == "ready" + process.send_signal(signal.SIGTERM) + output, _ = process.communicate(timeout=DEADLINE) + assert output.count("fails") == 2 and "RuntimeError" not in output + + +@posix +def test_a_signal_does_not_break_an_exit_hook(run: Callable[..., Any]) -> None: + script = """ +import atexit, time +from unshackle.core import process_exit + +def hook(): + print("exits", flush=True) + time.sleep(1) + print("exited", flush=True) + +atexit.register(hook) +with process_exit.unwinding(): + pass +""" + process = run("-c", script) + wait_line(process, "exits") + process.send_signal(signal.SIGTERM) + output, _ = process.communicate(timeout=DEADLINE) + assert output.strip() == "exited" + + +@posix +@pytest.mark.parametrize( + ("remote", "outcome", "code"), + [(True, "return []", 128 + 15), (True, "raise RuntimeError", 1), (False, "return []", -15)], + ids=["remote", "fails", "local"], +) +def test_a_stopped_worker_writes_no_file_again( + run: Callable[..., Any], tmp_path: Path, remote: bool, outcome: str, code: int +) -> None: + """The manager removes the files of a cancelled job at once. A local job has no session, so SIGTERM kills it.""" + script = """ +import sys, time +from unshackle.core import process_exit +from unshackle.core.api import download_worker + +def perform(*args, progress_callback): + process_exit.ends.add(lambda: time.sleep(0.3)) + progress_callback({"title": "EXAMPLE"}) + print("ready", flush=True) + while not process_exit.stopping(): + time.sleep(0.01) + progress_callback({"title": "OTHER"}) + OUTCOME + +download_worker.perform_download = perform +sys.exit(download_worker.main(sys.argv)) +""" + files = [tmp_path / name for name in ("payload", "result", "progress")] + payload = JobPayload("job", "EXAMPLE", "example-1", {"remote": "test"} if remote else {}) + files[0].write_text(json.dumps(asdict(payload)), encoding="utf-8") + process = run("-c", script.replace("OUTCOME", outcome), *map(str, files), stdin=subprocess.PIPE) + wait_line(process, "ready") + for path in files: + path.unlink(missing_ok=True) + process.send_signal(signal.SIGTERM) + output, _ = process.communicate(timeout=DEADLINE) + assert process.returncode == code, output + assert list(tmp_path.iterdir()) == [] + + +@posix +def test_the_only_process_of_a_container_ends_at_the_deadline(run: Callable[..., Any]) -> None: + """The kernel ignores the default action of a signal of PID 1. unshare ignores SIGTERM, so it is SIGHUP here.""" + inside = ["unshare", "-Urpf", "--kill-child"] + if not shutil.which("unshare") or subprocess.run([*inside, "true"], capture_output=True).returncode: + pytest.skip("no user namespace") + script = """ +import os, signal, time +from unshackle.core import process_exit +with process_exit.unwinding(1): + try: + os.kill(os.getpid(), signal.SIGHUP) + time.sleep(120) + finally: + time.sleep(120) +""" + process = run("-c", "import os, sys; os.execvp(sys.argv[1], sys.argv[1:])", *inside, sys.executable, "-c", script) + assert process.wait(DEADLINE) == 1 + + +@posix +def test_a_job_that_stops_runs_no_post_script(run: Callable[..., Any], tmp_path: Path) -> None: + ran = tmp_path / "ran" + script = """ +import shlex, sys, time +from unshackle.core import process_exit +from unshackle.core.utils.post_scripts import dispatch +with process_exit.unwinding(2, linger=False): + process_exit.ends.add(lambda: time.sleep(120)) + print("ready", flush=True) + while not process_exit.stopping(): + time.sleep(0.01) + dispatch("success", "file", {}, [shlex.join([sys.executable, "-c", f"open({sys.argv[1]!r}, 'w')"])]) + print("dispatched", flush=True) + time.sleep(120) +""" + process = run("-c", script, str(ran)) + wait_line(process, "ready") + process.send_signal(signal.SIGTERM) + wait_line(process, "dispatched") + assert process.wait(DEADLINE) == -signal.SIGALRM + assert not ran.exists() + + +def test_a_process_that_stops_opens_no_session( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], # noqa: F811 + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A job worker that ended the sessions it knew exits without a DELETE for a later one.""" + monkeypatch.setattr(process_exit.Stop, "signum", 1) + monkeypatch.setattr(process_exit.Stop, "raised", True) + with pytest.raises(RemoteError): + make_client(server.url).authenticate() + assert count(server, "POST", SESSION_CREATE_ROUTE) == 0 + + +@posix +def test_a_kill_leaves_the_terminal_as_it_is(run: Callable[..., Any]) -> None: + import pty + + controller, terminal = pty.openpty() + script = """ +import time +from unshackle.core import process_exit +with process_exit.unwinding(): + try: + print("ready", flush=True) + time.sleep(120) + except KeyboardInterrupt: + print("last line", flush=True) +""" + process = run("-c", script, stdin=terminal, stdout=terminal, stderr=terminal) + os.close(terminal) + output = read_until(controller, b"ready") + process.send_signal(signal.SIGTERM) + assert process.wait(DEADLINE) == 128 + signal.SIGTERM + output += os.read(controller, 65536) + os.close(controller) + assert b"last line" in output + + +@posix +def test_an_object_that_the_signal_left_half_made_prints_nothing(run: Callable[..., Any]) -> None: + script = """ +import time +from unshackle.core import process_exit + +class Half: + def __del__(self): + raise AttributeError(self.name) + +with process_exit.unwinding(): + made = Half() + made.name = "before" + del made + made = Half() + try: + print("ready", flush=True) + time.sleep(120) + except KeyboardInterrupt: + del made +""" + process = run("-c", script) + wait_line(process, "Exception ignored") + wait_line(process, "ready") + process.send_signal(signal.SIGTERM) + output, _ = process.communicate(timeout=DEADLINE) + assert process.returncode == 128 + signal.SIGTERM and output == "" + + +@posix +def test_nohup_and_the_handler_of_another_owner_stay( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], # noqa: F811 + run: Callable[..., Any], + tmp_path: Path, +) -> None: + process = client(run, server.url, tmp_path / "client", "handlers") + assert "Handlers.SIG_IGN" in wait_line(process, "lambda") + process.send_signal(signal.SIGHUP) + still_runs(process) + process.send_signal(signal.SIGTERM) + assert process.wait(DEADLINE) == 3 + + +@posix +def test_the_child_of_a_process_takes_no_handler_and_no_deadline(tmp_path: Path, run: Callable[..., Any]) -> None: + script = """ +import subprocess, sys, time +from unshackle.core import process_exit +with process_exit.unwinding(): + show = "import signal; print(signal.getsignal(1) is signal.getsignal(15) is signal.SIG_DFL)" + print(subprocess.check_output([sys.executable, "-c", show], text=True, encoding="utf-8", errors="replace")) +""" + output, _ = run("-c", script).communicate(timeout=DEADLINE) + assert output.strip() == "True" + + +@posix +@pytest.mark.parametrize("first", ["", "SIGTERM"], ids=["close", "term-close"]) +@pytest.mark.parametrize("stderr", ["terminal", "file"]) +def test_a_closed_terminal_ends_the_session_in_silence( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], # noqa: F811 + held_delete: HeldDelete, # noqa: F811 + run: Callable[..., Any], + tmp_path: Path, + stderr: str, + first: str, +) -> None: + """The client leads the session of a real pty, and prints to it from a thread until the end. + + A service manager that stops a login session sends SIGTERM before the terminal closes. + """ + import fcntl + import pty + import termios + + controller, terminal = pty.openpty() + log = (tmp_path / "stderr.log").open("w") + + def take_terminal() -> None: + os.setsid() + fcntl.ioctl(terminal, termios.TIOCSCTTY, 0) + + process = client( + run, server.url, tmp_path / "client", "print", + stdin=terminal, stdout=terminal, stderr=terminal if stderr == "terminal" else log, + start_new_session=False, preexec_fn=take_terminal, + ) # fmt: skip + os.close(terminal) + read_until(controller, b"set up") + store_cache() + if first: + send(process, first) + assert held_delete.started.wait(DEADLINE) + os.close(controller) + assert held_delete.started.wait(DEADLINE) + still_runs(process) + held_delete.release.set() + + assert process.wait(DEADLINE) == 1 + log.close() + assert "Traceback" not in (tmp_path / "stderr.log").read_text(encoding="utf-8") + assert saved(tmp_path / "client") and sessions() == [] + + +@posix +def test_a_terminal_that_closes_without_a_signal_ends_the_run_in_silence( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], # noqa: F811 + run: Callable[..., Any], + tmp_path: Path, +) -> None: + """The client is in the session of another process, so the writes fail and no SIGHUP comes.""" + import pty + + controller, terminal = pty.openpty() + with (tmp_path / "stderr.log").open("w") as log: + process = client( + run, server.url, tmp_path / "client", "prints", stdin=terminal, stdout=terminal, stderr=log + ) # fmt: skip + os.close(terminal) + read_until(controller, b"set up") + store_cache() + os.close(controller) + assert process.wait(DEADLINE) == 1 + assert (tmp_path / "stderr.log").read_text(encoding="utf-8") == "" + assert saved(tmp_path / "client") and sessions() == [] + + +@posix +@pytest.mark.parametrize("name", SIGNALS) +def test_a_redirected_file_keeps_its_lines(run: Callable[..., Any], tmp_path: Path, name: str) -> None: + script = """ +import sys, time +from unshackle.core import process_exit +with process_exit.unwinding(): + try: + print("ready", file=sys.stderr, flush=True) + time.sleep(120) + finally: + print("last line", flush=True) +""" + with (tmp_path / "out.log").open("w") as out: + process = run("-c", script, stdout=out, stderr=subprocess.PIPE) + assert process.stderr is not None and "ready" in process.stderr.readline() + send(process, name) + process.stderr.close() + process.wait(DEADLINE) + assert "last line" in (tmp_path / "out.log").read_text(encoding="utf-8") + + +@posix +def test_an_error_of_a_thread_still_shows(run: Callable[..., Any]) -> None: + """Only a write to a closed terminal is silent, not the same error of a disk.""" + script = """ +import errno +from threading import Thread +from unshackle.core import process_exit + +def fail(error): + raise error + +with process_exit.unwinding(): + for error in (RuntimeError("first"), OSError(errno.EIO, "second")): + Thread(target=fail, args=[error]).start() +""" + output, _ = run("-c", script).communicate(timeout=DEADLINE) + assert "first" in output and "second" in output + + +@pytest.mark.parametrize("name", SIGNALS) +@pytest.mark.parametrize("command", ["dl", "search"]) +def test_the_command_ends_its_session( + titles: SimpleNamespace, + run: Callable[..., Any], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + command: str, + name: str, +) -> None: + """The real command line; the search route opens no remote session, so its request is held on the server.""" + if command == "search": + + async def held(*args: Any, **kwargs: Any) -> Any: + titles.started.set() + await asyncio.to_thread(titles.release.wait, DEADLINE) + raise RuntimeError("held") + + monkeypatch.setattr("unshackle.core.api.routes.search_handler", held) + argv = [command, "--remote", "EXAMPLE", "example-1"] + process = run("-c", COMMAND, json.dumps(settings(titles.server.url, tmp_path)), *argv) + assert titles.started.wait(DEADLINE), process.kill() or process.communicate()[0] + send(process, name) + output, _ = process.communicate(timeout=DEADLINE) + assert process.returncode != 0 and "Traceback" not in output + if sys.platform != "win32": + assert process.returncode == 1 and "Aborted" in output + assert sessions() == [] + assert count(titles.server, "DELETE", SESSION_ROUTE) == (command == "dl") + + +@posix +@pytest.mark.parametrize("name", SIGNALS) +def test_the_tunnel_test_closes_its_tunnel( + server: SimpleNamespace, # noqa: F811 + run: Callable[..., Any], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + name: str, +) -> None: + started, release = Event(), Event() + + async def held(*args: Any, **kwargs: Any) -> Any: + started.set() + await asyncio.to_thread(release.wait, DEADLINE) + raise RuntimeError("held") + + monkeypatch.setattr("unshackle.core.api.routes.tunnel_check_handler", held) + process = run("-c", COMMAND, json.dumps(settings(server.url, tmp_path)), "tunnel-test") + try: + assert started.wait(DEADLINE), process.kill() or process.communicate()[0] + send(process, name) + output, _ = process.communicate(timeout=DEADLINE) + finally: + release.set() + assert process.returncode == 1 and "Aborted" in output and "Traceback" not in output + assert wait_until(lambda: not tunnel.TUNNELS, DEADLINE) + + +@posix +@pytest.mark.parametrize("delete", ["answers", "hangs"]) +def test_a_cancelled_job_ends_its_remote_session( + titles: SimpleNamespace, + held_delete: HeldDelete, # noqa: F811 + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + delete: str, +) -> None: + """The worker dies before the grace of ``stop`` ends, also on a DELETE with no answer, and writes no result.""" + script = worker_script(titles.server.url, tmp_path) + + async def cancel() -> tuple[float, int | None, Any, str]: + with monkeypatch.context() as patch: + patch.setattr(sys, "executable", str(script)) + worker = await WorkerProcess.spawn(JobPayload("job", "EXAMPLE", "example-1", {"remote": "test"})) + try: + if not await asyncio.to_thread(titles.started.wait, DEADLINE): + await worker.stop() + pytest.fail(str(worker.output())) + store_cache() + if delete == "answers": + held_delete.release.set() + sent = time.monotonic() + await worker.stop() + took = time.monotonic() - sent + assert await worker.wait(DEADLINE) + return took, worker.returncode, await worker.result(), worker.output()[1] + finally: + await worker.close() + + took, returncode, result, stderr = asyncio.run(cancel()) + assert took < 5 and returncode not in (0, -signal.SIGKILL) and result is None + assert "Traceback" not in stderr + assert held_delete.started.is_set() + if delete == "answers": + assert took < 3 and saved(tmp_path / "cache") and sessions() == [] + + +@posix +def test_the_manager_keeps_a_cancelled_job_cancelled( + titles: SimpleNamespace, + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + jobs = tmp_path / "jobs" + jobs.mkdir() + monkeypatch.setattr(tempfile, "tempdir", str(jobs)) + monkeypatch.setattr(sys, "executable", str(worker_script(titles.server.url, tmp_path))) + monkeypatch.setattr("unshackle.core.api.job_admission.check_job_start", lambda *args: None) + monkeypatch.setattr(download_manager, "record_job_history", lambda job: None) + + async def cancel() -> Any: + manager = download_manager.DownloadQueueManager() + job = manager.create_job("EXAMPLE", "example-1", remote="test") + running = asyncio.create_task(manager.download_worker("test")) + assert await asyncio.to_thread(titles.started.wait, DEADLINE) + worker = manager._workers[job.job_id] + assert manager.cancel_job(job.job_id) + await asyncio.wait_for(worker.process.wait(), DEADLINE) + running.cancel() + await asyncio.gather(running, return_exceptions=True) + return job + + job = asyncio.run(cancel()) + assert job.status == download_manager.JobStatus.CANCELLED and job.error_message is None + assert list(jobs.iterdir()) == [] + assert wait_until(lambda: sessions() == [], DEADLINE) diff --git a/tests/remote/unit/test_session_lifetime.py b/tests/remote/unit/test_session_lifetime.py index 6124492d..80ecba14 100644 --- a/tests/remote/unit/test_session_lifetime.py +++ b/tests/remote/unit/test_session_lifetime.py @@ -30,7 +30,7 @@ from tests.remote.unit.test_remote_loopback import ( from tests.remote.unit.test_remote_service_helpers import blob from tests.remote.unit.test_session_reopen import SERVER, make_service from tests.remote.unit.test_tunnel import wait_until -from unshackle.core import remote_channel, remote_lifetime, remote_service +from unshackle.core import process_exit, remote_channel, remote_lifetime, remote_service from unshackle.core.api import handlers, routes, session_store from unshackle.core.api.download_manager import busy_services from unshackle.core.api.session_store import SessionEntry @@ -860,7 +860,7 @@ def test_a_reopen_after_a_drain_ends_the_session_and_not_its_owner( assert count(server, "DELETE", SESSION_ROUTE) == 1 assert len(exit_hooks) == 1 and not service.lifetime.ended service.close() - assert sessions() == [] and exit_hooks == [] + assert sessions() == [] and exit_hooks == [] and process_exit.ends == set() def test_the_save_of_the_returned_cache_is_not_interrupted() -> None: diff --git a/unshackle/commands/dl.py b/unshackle/commands/dl.py index 3ef5e335..f88c04fb 100644 --- a/unshackle/commands/dl.py +++ b/unshackle/commands/dl.py @@ -27,7 +27,7 @@ from rich.rule import Rule from rich.spinner import Spinner from rich.table import Table -from unshackle.core import binaries, login +from unshackle.core import binaries, login, process_exit from unshackle.core.cdm.choice import choose_cdm from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_remote_cdm from unshackle.core.config import ( @@ -1147,6 +1147,7 @@ class dl: ) @click.pass_context def cli(ctx: click.Context, **kwargs: Any) -> dl: + ctx.with_resource(process_exit.unwinding()) return dl(ctx, **kwargs) keys: ContentKeyResolver diff --git a/unshackle/commands/search.py b/unshackle/commands/search.py index ef175c8a..32777c97 100644 --- a/unshackle/commands/search.py +++ b/unshackle/commands/search.py @@ -10,7 +10,7 @@ from rich.padding import Padding from rich.rule import Rule from rich.tree import Tree -from unshackle.core import login +from unshackle.core import login, process_exit from unshackle.core.config import config from unshackle.core.console import console from unshackle.core.constants import context_settings @@ -67,6 +67,7 @@ def search( remote: bool = False, server: str | None = None, ) -> None: + ctx.with_resource(process_exit.unwinding()) if not ctx.invoked_subcommand: raise ValueError("A subcommand to invoke was not specified, the main code cannot continue.") diff --git a/unshackle/commands/tunnel_test.py b/unshackle/commands/tunnel_test.py index a9524025..d983447f 100644 --- a/unshackle/commands/tunnel_test.py +++ b/unshackle/commands/tunnel_test.py @@ -3,6 +3,7 @@ import logging import click import requests +from unshackle.core import process_exit from unshackle.core.proxies.resolve import load_proxy_providers from unshackle.core.remote_service import remote_client, resolve_proxy_arg, start_tunnel from unshackle.core.tunnel import CHECK_ROUTE @@ -18,6 +19,7 @@ from unshackle.core.utils.redact import safe_display_url @click.option( "--proxy", type=str, default=None, help="Check the tunnel through this proxy, as --local-proxy --proxy does." ) +@process_exit.unwinding() def tunnel_test(server: str | None, proxy: str | None) -> None: """Check --local-proxy before a real --remote run. diff --git a/unshackle/core/api/download_worker.py b/unshackle/core/api/download_worker.py index 379ae145..1fd26a6b 100644 --- a/unshackle/core/api/download_worker.py +++ b/unshackle/core/api/download_worker.py @@ -8,8 +8,10 @@ import queue import sys import threading import traceback +from contextlib import nullcontext from pathlib import Path +from unshackle.core import process_exit from unshackle.core import session as http_session from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT from unshackle.core.api.job_channel import ( @@ -28,6 +30,9 @@ from .download_manager import perform_download log = logging.getLogger("download_worker") +STOP_DEADLINE = 4.0 +"""Shorter than the grace of ``WorkerProcess.stop``.""" + def relay_prompts(progress_callback: ProgressSink) -> None: """Send each prompt_user() prompt to the parent as ``input_prompt`` progress, and read the answer from stdin. @@ -97,9 +102,11 @@ def main(argv: list[str]) -> int: log.info(f"Worker starting job {payload.job_id} ({payload.service}:{payload.title_id})") relay_prompts(progress) - output_files = perform_download( - payload.job_id, payload.service, payload.title_id, payload.parameters, progress_callback=progress - ) + remote = payload.parameters.get("remote") + with process_exit.unwinding(STOP_DEADLINE, linger=False) if remote else nullcontext(): + output_files = perform_download( + payload.job_id, payload.service, payload.title_id, payload.parameters, progress_callback=progress + ) result = WorkerResult(status="success", output_files=output_files) @@ -129,7 +136,7 @@ def main(argv: list[str]) -> int: finally: try: - if result is not None: + if result is not None and not process_exit.stopping(): write_result(result_path, result) except Exception as exc: # noqa: BLE001 - last resort logging log.error(f"Failed to write worker result file: {exc}") diff --git a/unshackle/core/api/job_channel.py b/unshackle/core/api/job_channel.py index e6ae774c..e55c98b2 100644 --- a/unshackle/core/api/job_channel.py +++ b/unshackle/core/api/job_channel.py @@ -21,6 +21,8 @@ from pathlib import Path from typing import Any, TypeVar from uuid import uuid4 +from unshackle.core import process_exit + log = logging.getLogger("job_channel") ProgressSink = Callable[[dict[str, Any]], None] @@ -125,7 +127,12 @@ class ProgressFile: self._lock = threading.Lock() def __call__(self, update: dict[str, Any]) -> None: - """Write the record with ``update`` applied; it logs and drops a bad update and never raises.""" + """Write the record with ``update`` applied; it logs and drops a bad update and never raises. + + A worker that stops writes nothing: the parent has removed the file of a cancelled job. + """ + if process_exit.stopping(): + return try: with self._lock: state = replace(self.state) diff --git a/unshackle/core/process_exit.py b/unshackle/core/process_exit.py new file mode 100644 index 00000000..ee150edc --- /dev/null +++ b/unshackle/core/process_exit.py @@ -0,0 +1,179 @@ +"""How a client process ends when a signal or a closed console stops it: each way runs the unwind of Ctrl+C.""" + +from __future__ import annotations + +import contextlib +import errno +import faulthandler +import os +import signal +import sys +import threading +from collections.abc import Callable, Iterator +from threading import Thread, current_thread, main_thread + +DEADLINE = 8.0 + +ends: set[Callable[[], None]] = set() +"""What ends each open remote session. It runs on a thread of its own, because the main thread can wait for others.""" + + +class Stop: + """The stop of this process: its first signal, and whether the main thread gets no KeyboardInterrupt for it any more.""" + + signum = 0 + raised = False + held = False + terminals: list[int] = [] + null = -1 + + +def stopping() -> bool: + """Whether a signal or a closed console stops this process.""" + return Stop.signum != 0 + + +@contextlib.contextmanager +def unwinding(deadline: float = DEADLINE, linger: bool = True) -> Iterator[None]: + """Stop the block as Ctrl+C does on SIGHUP, SIGTERM, Ctrl+Break and a closed console, and never end it as a success. + + A process enters it once, and ends at the latest ``deadline`` seconds after the first of them. With ``linger`` False + the block gets no KeyboardInterrupt, and the process ends as soon as its remote sessions have ended. A block that + ends by itself also ends them, while the exit code can still change. + """ + if current_thread() is main_thread(): + listen(deadline, linger) + try: + yield + success = sys.exc_info()[0] is None # click before 8.3 does not pass on the exception of its block + if success: + end_all() + except SystemExit as e: + if e.code or not Stop.signum: + raise + success = True + except OSError as e: + if not hung_up(e): + raise + drop_terminals() + sys.exit(1) + finally: + Stop.raised = True + if success and Stop.signum: + sys.exit(128 + Stop.signum) + + +@contextlib.contextmanager +def held() -> Iterator[None]: + """Hold the KeyboardInterrupt of a signal back until the block has ended. Only for the main thread.""" + Stop.held = True + try: + yield + finally: + Stop.held = False + if Stop.signum: + interrupt() + + +def interrupt() -> None: + if not Stop.raised: + Stop.raised = True + raise KeyboardInterrupt + + +def hung_up(error: BaseException | None) -> bool: + """Whether a write failed because the terminal closed. The SIGHUP comes a moment later, or only to the shell.""" + return isinstance(error, OSError) and error.errno == errno.EIO and not all(map(os.isatty, Stop.terminals)) + + +def drop_terminals() -> None: + for fd in Stop.terminals: + os.dup2(Stop.null, fd) + + +def end_all() -> None: + for end in list(ends): + with contextlib.suppress(Exception, SystemExit, KeyboardInterrupt): + end() + + +if sys.platform == "win32": + + def listen(deadline: float, linger: bool) -> None: + """Add the console control handler. The system ends the process when it returns, and at a close after about 5s.""" + import atexit + import ctypes + + Stop.null = os.open(os.devnull, os.O_WRONLY) + + @ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_uint32) + def handler(event: int) -> int: + if event != signal.CTRL_C_EVENT and not Stop.signum: + Stop.signum = signal.SIGBREAK + faulthandler.dump_traceback_later(deadline, exit=True, file=Stop.null) + end_all() + return 0 + + set_handler = ctypes.windll.kernel32.SetConsoleCtrlHandler + set_handler(handler, 1) + atexit.register(set_handler, handler, 0) + +else: + + def listen(deadline: float, linger: bool) -> None: + """Handle SIGHUP and SIGTERM where nothing else does: nohup and another owner keep theirs. + + The wakeup fd tells the thread of a signal while the main thread is in a call that no signal breaks. An event + loop of the main thread can take it, so the Python handler tells the thread also. The kernel keeps the deadline, + so it holds in such a call and at interpreter shutdown. It ignores the timer of a PID 1, the only process of a + container, so there a native thread keeps it. + """ + mine = [s for s in (signal.SIGHUP, signal.SIGTERM) if signal.getsignal(s) is signal.SIG_DFL] + if not mine: + return + Stop.null = os.open(os.devnull, os.O_WRONLY) + Stop.terminals = [fd for fd in (1, 2) if os.isatty(fd)] + source, sink = os.pipe() + os.set_blocking(sink, False) + + def begin(signum: int) -> None: + if signum == signal.SIGHUP: + drop_terminals() + if not Stop.signum: + signal.setitimer(signal.ITIMER_REAL, deadline) + if os.getpid() == 1: + faulthandler.dump_traceback_later(deadline, exit=True, file=Stop.null) + # a KeyboardInterrupt can leave an object half made, and then its __del__ prints a traceback + sys.unraisablehook = lambda unraisable: None + Stop.signum = signum + os.write(sink, bytes([signum])) + + def watch() -> None: + while (signum := os.read(source, 1)[0]) not in mine: + pass + begin(signum) + # the kernel can give the signal to any thread, and then nothing breaks the call of the main thread + if not Stop.raised: + signal.pthread_kill(main_thread().ident or 0, signum) + end_all() + if not linger: + os._exit(128 + signum) + + def handler(signum: int, frame: object) -> None: + begin(signum) + if not Stop.held: + interrupt() + + show = threading.excepthook + + def show_thread_error(args: threading.ExceptHookArgs) -> None: + if not hung_up(args.exc_value): + show(args) + + threading.excepthook = show_thread_error + Stop.raised = not linger + Thread(target=watch, name="process-exit", daemon=True).start() + signal.signal(signal.SIGALRM, signal.SIG_DFL) + signal.set_wakeup_fd(sink, warn_on_full_buffer=False) + for signum in mine: + signal.signal(signum, handler) diff --git a/unshackle/core/remote_lifetime.py b/unshackle/core/remote_lifetime.py index affa4d7d..8afaae9b 100644 --- a/unshackle/core/remote_lifetime.py +++ b/unshackle/core/remote_lifetime.py @@ -8,9 +8,10 @@ import logging import signal import uuid from collections.abc import Callable, Iterator -from threading import RLock, current_thread, main_thread +from threading import Lock, RLock, current_thread, main_thread from typing import TYPE_CHECKING +from unshackle.core import process_exit from unshackle.core.remote_protocol import SESSION_ROUTE, APIErrorCode, SessionClosed from unshackle.core.remote_service import RemoteClient, RemoteError, quiet @@ -33,7 +34,7 @@ class RemoteSessionLifetime: """The one owner of a remote session, its tunnel and its session channel. :meth:`release` gives up what is open, and the owner can open again, as a reopen does. :meth:`end` is final. - Both can run again after an interrupt and from any thread, and neither waits on a reopen of another thread. + Both can run again after an interrupt and from any thread. Of a reopen of another thread they wait only for its DELETE. It holds an id from before its create request until the server answers its DELETE or the DELETE fails. """ @@ -45,11 +46,12 @@ class RemoteSessionLifetime: self.ended = False self._held: set[str] = set() self._lock = RLock() + self._deletes = Lock() self._saving = False def require_open(self) -> None: - """Raise when this owner has ended.""" - if self.ended: + """Raise when this owner has ended, or when the process stops: it can have ended its owners already.""" + if self.ended or process_exit.stopping(): raise RemoteError("The remote session has ended", APIErrorCode.SESSION_NOT_FOUND) def require_session(self) -> str: @@ -70,13 +72,15 @@ class RemoteSessionLifetime: self.require_open() atexit.unregister(self.end_at_exit) atexit.register(self.end_at_exit) + process_exit.ends.add(self.end_at_exit) yield self.require_open() except BaseException: if self.ended: self.end_at_exit() else: - self.patiently(self.release) + if not self.patiently(self.release) and process_exit.stopping(): + raise KeyboardInterrupt from None raise def name(self) -> str: @@ -94,14 +98,18 @@ class RemoteSessionLifetime: self.session_id = session_id def release(self, gone: bool = False) -> None: - """Give up the remote session, its channel and its tunnel; ``gone`` when the server said it has no such session.""" + """Give up the remote session, its channel and its tunnel; ``gone`` when the server said it has no such session. + + In a process that stops, the DELETE goes before the waits for the channel and for a CDM call. + """ with self._lock: if gone: self._held -= {self.session_id} self.session_id = None + if process_exit.stopping(): + self._delete_held() self.close_channel() - for session_id in list(self._held): - self._delete(session_id) + self._delete_held() if tunnel := self.client.tunnel: tunnel.stop() if self.client.tunnel is tunnel: @@ -117,6 +125,7 @@ class RemoteSessionLifetime: raise KeyboardInterrupt # a long-lived serve opens many of these; the exit hook would keep every one alive atexit.unregister(self.end_at_exit) + process_exit.ends.discard(self.end_at_exit) def end_at_exit(self) -> None: """:meth:`end` where no caller is left to stop.""" @@ -129,6 +138,12 @@ class RemoteSessionLifetime: if self.channel is channel: self.channel = None + def _delete_held(self) -> None: + """Send each DELETE; another thread that gives up the same id waits here for the cache that comes back.""" + with self._deletes: + for session_id in list(self._held): + self._delete(session_id) + def _delete(self, session_id: str) -> None: """Send one DELETE and save the cache it returns. An interrupt keeps the id, so a later release sends it again.""" body: SessionClosed = {} @@ -152,12 +167,13 @@ class RemoteSessionLifetime: def patiently(self, work: Callable[[], None]) -> bool: """Run ``work``, ignore the first Ctrl+C and stop at the next one; False when the user gave up. - Only the main thread can, so on another thread ``work`` runs with the signal handlers as they are. + Another signal that stops the process does not stop ``work``: it makes the result False. Only the main thread + gets signals, so on another thread ``work`` runs with the signal handlers as they are. """ - before = signal.getsignal(signal.SIGINT) - if current_thread() is not main_thread() or not callable(before): + if current_thread() is not main_thread(): work() return True + before = signal.getsignal(signal.SIGINT) if Presses.count >= GIVE_UP: return False armed = True @@ -169,12 +185,15 @@ class RemoteSessionLifetime: try: try: - signal.signal(signal.SIGINT, press) - work() + if callable(before): + signal.signal(signal.SIGINT, press) + with process_exit.held(): + work() finally: armed = False return True except KeyboardInterrupt: return False finally: - signal.signal(signal.SIGINT, before) + if callable(before): + signal.signal(signal.SIGINT, before) diff --git a/unshackle/core/remote_service.py b/unshackle/core/remote_service.py index 53224546..0d38a1c2 100644 --- a/unshackle/core/remote_service.py +++ b/unshackle/core/remote_service.py @@ -39,7 +39,7 @@ from rich.padding import Padding from rich.rule import Rule from rich.spinner import Spinner -from unshackle.core import login +from unshackle.core import login, process_exit from unshackle.core.config import config from unshackle.core.console import SyncLive, console from unshackle.core.constants import AnyTrack @@ -134,7 +134,7 @@ class _Mute(local): """This thread's RemoteError log state: inside ``session_call`` (``recovering``) and under ``quiet()``.""" recovering = False - quiet: Callable[[], bool] = staticmethod(lambda: False) + quiet: Callable[[], bool] = staticmethod(process_exit.stopping) _mute = _Mute() diff --git a/unshackle/core/utils/post_scripts.py b/unshackle/core/utils/post_scripts.py index 9a0c2dc6..238707ae 100644 --- a/unshackle/core/utils/post_scripts.py +++ b/unshackle/core/utils/post_scripts.py @@ -24,6 +24,7 @@ from pathlib import Path from types import SimpleNamespace from typing import Any +from unshackle.core import process_exit from unshackle.core.config import config from unshackle.core.console import console from unshackle.core.utilities import log_event @@ -217,7 +218,9 @@ def _entries(event: str, mode: str, overrides: Sequence[str] = ()) -> Iterator[t def dispatch(event: str, mode: str, context: dict[str, str], overrides: Sequence[str] = ()) -> None: - """Spawn every post-script configured for `event` and `mode`. Never raises.""" + """Spawn every post-script configured for `event` and `mode`, or none when a signal stops the process. Never raises.""" + if process_exit.stopping(): + return for command, wait in _entries(event, mode, overrides): try: tokens = tokenize(command)