Files
unshackle/unshackle/core/remote_lifetime.py
T

181 lines
6.6 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 RLock, current_thread, main_thread
from typing import TYPE_CHECKING
from unshackle.core.remote_protocol import SESSION_ROUTE, APIErrorCode, SessionClosed
from unshackle.core.remote_service import RemoteClient, RemoteError, quiet
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, and neither waits on a reopen of another thread.
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._saving = False
def require_open(self) -> None:
"""Raise when this owner has ended."""
if self.ended:
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)
yield
self.require_open()
except BaseException:
if self.ended:
self.end_at_exit()
else:
self.patiently(self.release)
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()
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."""
with self._lock:
if gone:
self._held -= {self.session_id}
self.session_id = None
self.close_channel()
for session_id in list(self._held):
self._delete(session_id)
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)
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(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.
Only the main thread can, 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):
work()
return True
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:
signal.signal(signal.SIGINT, press)
work()
finally:
armed = False
return True
except KeyboardInterrupt:
return False
finally:
signal.signal(signal.SIGINT, before)