Files
unshackle/tests/remote/unit/test_relay_stop.py
T

533 lines
18 KiB
Python

"""The stop of a serve that relays: it ends the remote logins and the idle pooled sessions on the upstream server.
A stop is a signal to a real ``serve`` process whose upstream is a server in this process.
"""
from __future__ import annotations
import asyncio
import json
import signal
import time
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from threading import Event, Lock, Semaphore
from types import SimpleNamespace
from typing import Any
import pytest
import requests
from aiohttp import web
from tests.remote.unit.test_process_exit import BOUND, lasting_sessions, posix, run, settings, wait_line # noqa: F401
from tests.remote.unit.test_remote_loopback import KEY, StubService, count, forget, make_client, server # noqa: F401
from tests.remote.unit.test_session_lifetime import DEADLINE, error_code, in_thread, logins, sessions # noqa: F401
from tests.remote.unit.test_tunnel import wait_until
from unshackle.core.api import handlers, routes
from unshackle.core.api.errors import APIError
from unshackle.core.api.handlers import (
RelayStop,
RemoteLease,
RemoteLogin,
close_remote_pool,
end_remote_pool,
end_reopening,
setup_remote_service,
)
from unshackle.core.api.routes import setup_routes
from unshackle.core.remote_protocol import (
PROMPT_ROUTE,
SESSION_ROUTE,
TITLES_ROUTE,
APIErrorCode,
)
pytestmark = [pytest.mark.unit, pytest.mark.process]
RELAY = """
import asyncio, json, sys
from pathlib import Path
from aiohttp import web
from unshackle.core.config import config
config.__init__(**json.loads(sys.argv[1]))
from unshackle.commands.serve import serve
from unshackle.core import remote_channel, remote_service, services
from unshackle.core.api import handlers, routes
handlers.LOGIN_WAIT = float(sys.argv[2])
remote_channel.AUTH_POLL_INTERVAL = 0.05
services.load_all = lambda: None
remote_service.remote_service_list = lambda name: [{"tag": "EXAMPLE", "aliases": [], "cli_params": []}]
start, shutdown = web.TCPSite.start, web.Application.shutdown
async def started(site):
await start(site)
print("port", site._server.sockets[0].getsockname()[1], flush=True)
async def shut_down(app):
await shutdown(app)
print("the shutdown hooks ended", flush=True)
async def hold(app):
while not Path(sys.argv[3]).exists():
await asyncio.sleep(0.01)
if sys.argv[3:]:
routes.shutdown_download_manager = hold
reopens = handlers.end_reopening
def end_reopening(stop):
reopens(stop)
print("the reopens ended", flush=True)
handlers.end_reopening = end_reopening
web.TCPSite.start = started
web.Application.shutdown = shut_down
serve(args=["-q", "-h", "127.0.0.1", "-p", "0", "--api-only"])
"""
class Relay:
"""A ``serve`` process that relays to the upstream server of the test."""
def __init__(self, run: Callable[..., Any], url: str, path: Path, *hold: str, wait: float = 5) -> None: # noqa: F811
data = {**settings(url.replace("127.0.0.1", "localhost"), path), "serve": {"api_secret": KEY}}
self.process = run("-c", RELAY, json.dumps(data), str(wait), *hold)
self.url = f"http://127.0.0.1:{wait_line(self.process, 'port ').split()[1]}"
def list(self, route: str = "list-titles", title: str = "example-1") -> Callable[[], requests.Response]:
"""Send a list call; the returned function waits for its answer."""
body = {"service": "EXAMPLE", "title_id": title, "remote": "test", "no_proxy": True}
url, headers = f"{self.url}/api/{route}", {"X-Secret-Key": KEY}
return in_thread(lambda: requests.post(url, json=body, headers=headers, timeout=DEADLINE))
def asks(self) -> bool:
reply = requests.get(self.url + "/api/remote/logins", headers={"X-Secret-Key": KEY}, timeout=DEADLINE)
return any(login["prompt"] for login in reply.json()["logins"])
def stop(self) -> None:
self.process.send_signal(signal.SIGTERM)
def ended_well(self) -> None:
"""The process ends in time, and its upstream server has no remote session left."""
output, _ = self.process.communicate(timeout=BOUND)
assert self.process.returncode == 0, output
assert "Traceback" not in output
assert sessions() == []
@pytest.fixture
def relay(run: Callable[..., Any], server: SimpleNamespace, tmp_path: Path) -> Relay: # noqa: F811
return Relay(run, server.url, tmp_path / "relay")
def ask(stub: StubService) -> None:
stub._input_bridge.request_input("Enter the EXAMPLE code")
def poll_a_device(stub: StubService) -> None:
while True:
stub._input_bridge.ensure_active()
time.sleep(0.01)
def lose_session(server: SimpleNamespace, stub: StubService) -> None: # noqa: F811
for entry in sessions():
forget(server, entry.session_id)
stub._input_bridge.ensure_active()
def nothing(stub: StubService) -> None:
pass
@posix
@pytest.mark.parametrize(
("server", "login", "titles"),
[
(True, ask, nothing),
(True, poll_a_device, nothing),
(True, nothing, ask),
(False, ask, nothing),
(False, poll_a_device, nothing),
],
ids=["prompt", "device", "prompt-after-login", "prompt-polling", "device-polling"],
indirect=["server"],
)
def test_a_stop_ends_a_remote_login(
server: SimpleNamespace, # noqa: F811
relay: Relay,
monkeypatch: pytest.MonkeyPatch,
login: Callable[[StubService], None],
titles: Callable[[StubService], None],
) -> None:
"""The login waits on the user, so nothing but the stop can end it, and its list call gets an answer."""
monkeypatch.setattr(StubService, "authenticate", lambda self, cookies, credential: login(self))
StubService.hooks["titles"] = titles
reply = relay.list()
assert wait_until(
lambda: count(server, "GET", PROMPT_ROUTE) > 0 or any(entry.channel.attached for entry in sessions()), DEADLINE
)
assert ask not in (login, titles) or wait_until(relay.asks, DEADLINE)
relay.stop()
relay.ended_well()
assert (reply().status_code, error_code(reply())) == (409, APIErrorCode.SERVER_DRAINING)
@posix
def test_no_other_shutdown_hook_delays_the_end_of_a_login(
run: Callable[..., Any], # noqa: F811
server: SimpleNamespace, # noqa: F811
tmp_path: Path,
) -> None:
released = tmp_path / "released"
relay = Relay(run, server.url, tmp_path / "relay", str(released))
relay.list()
assert wait_until(relay.asks, DEADLINE)
relay.stop()
assert wait_until(lambda: sessions() == [], DEADLINE)
released.touch()
relay.ended_well()
@posix
@pytest.mark.parametrize("in_flight", [False, True], ids=["idle", "in-flight"])
def test_a_stop_ends_the_pooled_sessions_at_the_same_time(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
relay: Relay,
monkeypatch: pytest.MonkeyPatch,
in_flight: bool,
) -> None:
"""No DELETE is answered before the last one has arrived."""
ids = ("example-1", "example-2", "example-3")
started, release = Semaphore(0), Event()
def hold(stub: StubService) -> None:
started.release()
assert release.wait(DEADLINE), "the test did not release the titles"
if in_flight:
StubService.hooks["titles"] = hold
replies = [relay.list(title=title) for title in ids]
for reply in replies:
assert started.acquire(timeout=DEADLINE) if in_flight else reply().status_code == 200
assert len(sessions()) == len(ids)
together = asyncio.Barrier(len(ids))
handler = routes.session_delete_handler
async def held(session_id: str, request: Any) -> Any:
await asyncio.wait_for(together.wait(), DEADLINE)
return await handler(session_id, request)
monkeypatch.setattr(routes, "session_delete_handler", held)
relay.stop()
if in_flight:
wait_line(relay.process, "the shutdown hooks ended")
release.set()
relay.ended_well()
assert [reply().status_code for reply in replies] == [200] * len(ids)
@posix
@pytest.mark.parametrize("pooled", [False, True], ids=["first-call", "pooled-session"])
def test_a_request_in_flight_finishes_on_its_own_session(
run: Callable[..., Any], # noqa: F811
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
tmp_path: Path,
pooled: bool,
) -> None:
"""The first call of a session fetches its titles while its login is still listed."""
relay = Relay(run, server.url, tmp_path / "relay", wait=0.2)
started, release = Event(), Event()
def hold(stub: StubService) -> None:
started.set()
assert release.wait(DEADLINE), "the test did not release the titles"
if pooled:
assert relay.list("list-tracks")().status_code == 200
StubService.hooks["titles"] = hold
reply = relay.list("list-titles" if pooled else "list-tracks")
assert started.wait(DEADLINE)
relay.stop()
wait_line(relay.process, "the reopens ended")
release.set()
assert reply().status_code == 200
relay.ended_well()
assert len(logins) == 1
assert count(server, "GET", TITLES_ROUTE) == 1 + pooled
assert count(server, "DELETE", SESSION_ROUTE) == 1
@posix
def test_a_session_lost_late_in_the_stop_does_not_hold_it(
run: Callable[..., Any], # noqa: F811
server: SimpleNamespace, # noqa: F811
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
relay = Relay(run, server.url, tmp_path / "relay", wait=0.2)
started, release = Event(), Event()
def lose(stub: StubService) -> None:
started.set()
assert release.wait(DEADLINE), "the test did not release the titles"
lose_session(server, stub)
def login(stub: StubService, cookies: Any, credential: Any) -> None:
if release.is_set():
poll_a_device(stub)
monkeypatch.setattr(StubService, "authenticate", login)
StubService.hooks["titles"] = lose
reply = relay.list()
assert started.wait(DEADLINE)
relay.stop()
wait_line(relay.process, "the reopens ended")
release.set()
assert reply().status_code == 409
relay.ended_well()
@posix
@pytest.mark.parametrize("waits", [True, False], ids=["waits", "finishes"])
@pytest.mark.parametrize("pooled", [False, True], ids=["first-call", "pooled-session"])
def test_a_request_that_opens_its_lost_session_again_finishes_in_time_or_is_cut(
run: Callable[..., Any], # noqa: F811
server: SimpleNamespace, # noqa: F811
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
pooled: bool,
waits: bool,
) -> None:
"""The upstream server loses the remote session, and the login of the next one waits for an approval."""
relay = Relay(run, server.url, tmp_path / "relay", wait=0.2 if waits else DEADLINE)
lost, reopening, approved = Event(), Event(), Event()
def lose(stub: StubService) -> None:
StubService.hooks.clear()
lost.set()
lose_session(server, stub)
def login(stub: StubService, cookies: Any, credential: Any) -> None:
if lost.is_set():
reopening.set()
while not approved.wait(0.01):
stub._input_bridge.ensure_active()
monkeypatch.setattr(StubService, "authenticate", login)
if pooled:
assert relay.list("list-tracks")().status_code == 200
StubService.hooks["titles"] = lose
reply = relay.list()
assert reopening.wait(DEADLINE)
relay.stop()
wait_line(relay.process, "the shutdown hooks ended")
if not waits:
approved.set()
assert reply().status_code == (409 if waits else 200)
relay.ended_well()
def relay_app() -> web.Application:
app = web.Application()
setup_routes(app)
return app
@pytest.fixture
def pool(monkeypatch: pytest.MonkeyPatch) -> dict[tuple, RemoteLease]:
monkeypatch.setattr(handlers, "_remote_pool", {})
monkeypatch.setattr(handlers, "_remote_logins", {})
return handlers._remote_pool
def log_in(app: web.Application, client: Any, monkeypatch: pytest.MonkeyPatch) -> Any:
"""Log *client* in as a list call of *app* does. With no client, the call must not build one."""
monkeypatch.setattr(handlers, "relay_service", lambda *args: client or pytest.fail("the relay built a service"))
request: Any = SimpleNamespace(app=app, headers={"X-Secret-Key": KEY})
return setup_remote_service({"service": "EXAMPLE"}, "test", None, "example-1", request)
class Registry(dict[str, Any]):
"""The logins in progress of a relay that stops when the thread of a login adds itself, before or after the add."""
def __init__(self, app: web.Application, before: bool) -> None:
super().__init__()
self.app, self.before = app, before
def __setitem__(self, key: str, login: Any) -> None:
if self.before:
asyncio.run(end_remote_pool(self.app))
super().__setitem__(key, login)
if not self.before:
asyncio.run(end_remote_pool(self.app))
@pytest.mark.parametrize("before", [True, False], ids=["before-the-add", "after-the-add"])
def test_a_login_that_starts_as_the_relay_stops_is_refused(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
pool: dict[tuple, RemoteLease],
monkeypatch: pytest.MonkeyPatch,
before: bool,
) -> None:
app = relay_app()
monkeypatch.setattr(handlers, "_remote_logins", Registry(app, before))
with pytest.raises(APIError) as refused:
log_in(app, make_client(server.url), monkeypatch)
assert refused.value.error_code == APIErrorCode.SERVER_DRAINING
assert (refused.value.retryable, "\n" in refused.value.message) == (True, False)
assert server.seen == [] and not handlers._remote_logins
def test_a_login_that_the_stop_reaches_before_its_create_opens_no_session(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
pool: dict[tuple, RemoteLease],
monkeypatch: pytest.MonkeyPatch,
) -> None:
app, client = relay_app(), make_client(server.url)
authenticate = client.authenticate
def stop_first() -> None:
asyncio.run(end_remote_pool(app))
authenticate()
monkeypatch.setattr(client, "authenticate", stop_first)
with pytest.raises(APIError) as refused:
log_in(app, client, monkeypatch)
assert refused.value.error_code == APIErrorCode.SERVER_DRAINING
assert server.seen == []
def test_a_request_in_flight_keeps_its_own_error(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
pool: dict[tuple, RemoteLease],
monkeypatch: pytest.MonkeyPatch,
) -> None:
app = relay_app()
def fail(stub: StubService) -> None:
asyncio.run(end_remote_pool(app))
raise ValueError("EXAMPLE failed")
StubService.hooks["titles"] = fail
with pytest.raises(APIError, match="EXAMPLE failed"):
log_in(app, make_client(server.url), monkeypatch)
assert sessions() == []
def test_the_stop_refuses_before_it_reads_the_logins(
pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch
) -> None:
app = relay_app()
started: list[bool] = []
class Logins(dict[str, Any]):
def values(self) -> Any:
started.append(app["relay_stop"].started)
return super().values()
monkeypatch.setattr(handlers, "_remote_logins", Logins())
asyncio.run(end_remote_pool(app))
assert started == [True]
def test_another_app_of_the_process_still_logs_in(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
pool: dict[tuple, RemoteLease],
monkeypatch: pytest.MonkeyPatch,
) -> None:
stopped, app = relay_app(), relay_app()
asyncio.run(end_remote_pool(stopped))
with pytest.raises(APIError):
log_in(stopped, None, monkeypatch)
log_in(app, make_client(server.url), monkeypatch).close()
assert len(logins) == 1
async def test_the_stop_waits_for_the_ends_and_not_for_the_default_executor(
pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch
) -> None:
"""The ends finish while the stop waits. A busy remote session stays open."""
closed: list[str] = []
begun, finish, free_workers = Event(), Event(), Event()
workers = ThreadPoolExecutor(1)
asyncio.get_running_loop().set_default_executor(workers)
workers.submit(free_workers.wait, DEADLINE)
def end(name: str) -> None:
begun.set()
assert finish.wait(DEADLINE)
closed.append(name)
async def finish_later() -> None:
while not begun.is_set():
await asyncio.sleep(0.01)
finish.set()
monkeypatch.setattr(handlers, "LOGIN_WAIT", DEADLINE / 4)
for name in ("a", "b", "busy"):
service = SimpleNamespace(close=lambda name=name: end(name))
pool[(name,)] = RemoteLease((name,), service=service, busy=int(name == "busy"))
app = relay_app()
try:
later = asyncio.create_task(finish_later())
await close_remote_pool(app)
assert sorted(closed) == ["a", "b"] and list(pool) == [("busy",)]
assert all(thread.daemon for thread in app["relay_stop"].ends)
await later
finally:
free_workers.set()
finish.set()
async def test_an_end_that_does_not_finish_holds_the_stop_no_longer_than_the_wait(
pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch
) -> None:
closed, release = Event(), Event()
def end() -> None:
release.wait(DEADLINE)
closed.set()
monkeypatch.setattr(handlers, "LOGIN_WAIT", 0.05)
pool[("stuck",)] = RemoteLease(("stuck",), service=SimpleNamespace(close=end))
try:
await asyncio.wait_for(close_remote_pool(relay_app()), DEADLINE / 2)
assert not closed.is_set()
finally:
release.set()
async def test_a_reopen_is_ended_once(pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch) -> None:
lifetime = SimpleNamespace(ended=False)
service = SimpleNamespace(lifetime=lifetime, _reopen_lock=Lock(), close=lambda: setattr(lifetime, "ended", True))
monkeypatch.setattr(handlers, "LOGIN_WAIT", DEADLINE)
pool[("EXAMPLE",)] = RemoteLease(("EXAMPLE",), service=service, busy=1)
stop = RelayStop()
with service._reopen_lock:
for _ in range(2):
end_reopening(stop)
stop.ends[0].join(DEADLINE)
assert len(stop.ends) == 1
async def test_the_last_call_ends_also_the_login_of_a_request_that_did_not_finish(
pool: dict[tuple, RemoteLease],
) -> None:
closed: list[str] = []
login = RemoteLogin("owner", "test", "EXAMPLE", "example-1", SimpleNamespace(close=lambda: closed.append("login")))
login.done = True
handlers._remote_logins[login.id] = login
app = relay_app()
await end_remote_pool(app)
assert not app["relay_stop"].ends
await close_remote_pool(app)
assert closed == ["login"]