mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-01 21:45:10 +00:00
950 lines
33 KiB
Python
950 lines
33 KiB
Python
"""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, pytest.mark.process]
|
|
|
|
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)
|