Files
unshackle/unshackle/core/remote_lifetime.py
T

202 lines
7.7 KiB
Python

"""The lifetime of a remote session on the client, from before its create request to after its DELETE."""
from __future__ import annotations
import atexit
import contextlib
import logging
import signal
import uuid
from collections.abc import Callable, Iterator
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, require_run
if TYPE_CHECKING:
from unshackle.core.remote_channel import Channel
log = logging.getLogger("remote_lifetime")
END_TIMEOUT = 15.0
GIVE_UP = 2
class Presses:
"""The Ctrl+C presses during the ends of this process. The first one is ignored, and at GIVE_UP no end waits."""
count = 0
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. 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.
"""
def __init__(self, client: RemoteClient, save_cache: Callable[[dict[str, str]], None]) -> None:
self.client = client
self.save_cache = save_cache
self.session_id: str | None = None
self.channel: Channel | None = None
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, 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:
"""The id of the open remote session, or raise."""
self.require_open()
if (session_id := self.session_id) is None:
raise RemoteError("No remote session is open", APIErrorCode.SESSION_NOT_FOUND)
return session_id
@contextlib.contextmanager
def opening(self) -> Iterator[None]:
"""Register the exit hook, then release all that the block opened when it raises or the owner has ended.
An error of a call that another thread ended this owner under is no news to the user, so it stays out of the log.
"""
with quiet(lambda: self.ended):
try:
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()
require_run()
except BaseException:
if self.ended:
self.end_at_exit()
else:
if not self.patiently(self.release) and process_exit.stopping():
raise KeyboardInterrupt from None
raise
def name(self) -> str:
"""The id that the next create request asks for, so that a DELETE can name the remote session before the answer."""
named = str(uuid.uuid4())
with self._lock:
self.require_open()
require_run()
self._held.add(named)
return named
def adopt(self, named: str, session_id: str) -> None:
"""Take the id of the create reply, which an older server picks itself."""
with self._lock:
self._held = (self._held - {named}) | {session_id}
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.
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()
self._delete_held()
if tunnel := self.client.tunnel:
tunnel.stop()
if self.client.tunnel is tunnel:
self.client.tunnel = None
def end(self) -> None:
"""Release everything for good: no thread opens a remote session through this owner again.
It raises KeyboardInterrupt when the user gave up on it, and the exit hook then stays.
"""
self.ended = True
if not self.patiently(self.release):
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."""
with contextlib.suppress(KeyboardInterrupt):
self.end()
def close_channel(self) -> None:
if channel := self.channel:
channel.close()
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 = {}
try:
endpoint = SESSION_ROUTE.format(session_id=session_id)
resp = self.client.send("delete", endpoint, min(END_TIMEOUT, self.client.timeout), background=True)
if resp.ok:
body = resp.json()
except Exception as e:
log.debug(f"The DELETE of the remote session failed: {type(e).__name__}")
self._saving = True
try:
self.save_cache(body.get("cache") or {})
except (Exception, SystemExit) as e:
log.warning(f"Failed to save the cache of the remote session: {e}")
finally:
self._saving = False
with self._lock:
self._held.discard(session_id)
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.
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.
"""
if current_thread() is not main_thread():
work()
return True
before = signal.getsignal(signal.SIGINT)
if Presses.count >= GIVE_UP:
return False
armed = True
def press(*_: object) -> None:
Presses.count += 1
if Presses.count >= GIVE_UP and armed and not self._saving:
raise KeyboardInterrupt
try:
try:
if callable(before):
signal.signal(signal.SIGINT, press)
with process_exit.held():
work()
finally:
armed = False
return True
except KeyboardInterrupt:
return False
finally:
if callable(before):
signal.signal(signal.SIGINT, before)