Spaces:
Running
Running
File size: 5,367 Bytes
e59bd9d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | """Lifecycle management: single-instance lock, signals, graceful shutdown.
The background controller is designed to be started by a per-user Windows
Task Scheduler job at logon (see scripts/install.ps1). This module provides
the in-process half: exclusive singleton lock, stop-request polling, signal
handlers (CTRL_C / CTRL_BREAK / SIGTERM), and orderly resource release.
"""
from __future__ import annotations
import json
import os
import signal
import sys
import time
from pathlib import Path
from typing import Callable, Optional
from ..monitoring.logger import lpu_home
class Lifecycle:
def __init__(self, name: str = "controller", log=None):
self.name = name
self.home = lpu_home()
self.lock_path = self.home / f"{name}.lock"
self.stop_flag_path = self.home / f"{name}.stop"
self.pid = os.getpid()
self._log = log
self._stop_requested = False
self._cleanup_hooks: list = []
# -- singleton lock -------------------------------------------------------
def acquire_lock(self) -> bool:
"""True when we are THE instance.
Race-hardened: the lock file is created EXCLUSIVELY (O_CREAT|O_EXCL).
On collision we run the pid-liveness check and only steal the lock of
a CONFIRMED-DEAD pid via atomic temp+replace. Concurrent starters can
no longer both pass the check (logon task racing a manual start).
"""
self.home.mkdir(parents=True, exist_ok=True)
payload = json.dumps({"pid": self.pid, "started": time.time(),
"cmdline": sys.argv[:10]})
try:
fd = os.open(str(self.lock_path), os.O_CREAT | os.O_EXCL | os.O_WRONLY)
with os.fdopen(fd, "w", encoding="utf-8") as fh:
fh.write(payload)
return True
except FileExistsError:
try:
data = json.loads(self.lock_path.read_text(encoding="utf-8"))
old_pid = int(data.get("pid", -1))
if old_pid != self.pid and _pid_alive(old_pid):
if self._log:
self._log.info("another %s instance is running (pid %d)",
self.name, old_pid)
return False
except (ValueError, OSError, json.JSONDecodeError):
pass # corrupt lock -> steal below
# confirmed dead or corrupt: atomic takeover
import tempfile
fd, tmp = tempfile.mkstemp(dir=str(self.home), suffix=".tmp")
with os.fdopen(fd, "w", encoding="utf-8") as fh:
fh.write(payload)
os.replace(tmp, self.lock_path)
return True
def release_lock(self) -> None:
try:
if self.lock_path.exists():
data = json.loads(self.lock_path.read_text(encoding="utf-8") or "{}")
if int(data.get("pid", -1)) == self.pid:
self.lock_path.unlink()
except (ValueError, OSError, json.JSONDecodeError):
pass
# -- stop requests ------------------------------------------------------------
def request_stop(self) -> bool:
"""External stop: create the stop-flag file (used by CLI `lpu stop`)."""
self.stop_flag_path.write_text(str(time.time()), encoding="utf-8")
return self.stop_flag_path.exists()
def stop_requested(self) -> bool:
return self._stop_requested or self.stop_flag_path.exists()
def clear_stop(self) -> None:
self._stop_requested = False
try:
self.stop_flag_path.unlink()
except OSError:
pass
def on_stop(self, fn: Callable[[], None]) -> None:
self._cleanup_hooks.append(fn)
def run_cleanup(self) -> None:
for fn in self._cleanup_hooks:
try:
fn()
except Exception: # noqa: BLE001
if self._log:
self._log.exception("cleanup hook failed")
self._cleanup_hooks.clear()
# -- signals ---------------------------------------------------------------
def install_signal_handlers(self) -> None:
def handler(signum, frame):
self._stop_requested = True
if self._log:
self._log.info("signal %s received -> graceful stop requested", signum)
for sig in (signal.SIGINT, signal.SIGTERM, getattr(signal, "CTRL_BREAK_EVENT", signal.SIGINT),
getattr(signal, "SIGHUP", signal.SIGTERM)):
try:
signal.signal(sig, handler)
except (ValueError, OSError, AttributeError):
continue
def _pid_alive(pid: int) -> bool:
if pid <= 0:
return False
try:
import psutil
p = psutil.Process(pid)
return p.is_running() and p.status() != psutil.STATUS_ZOMBIE
except Exception: # noqa: BLE001 - psutil absent or pid gone
return False
def find_controller_pid() -> Optional[int]:
"""Read the controller lock and return its live pid (or None)."""
lock = lpu_home() / "controller.lock"
try:
data = json.loads(lock.read_text(encoding="utf-8"))
pid = int(data.get("pid", -1))
return pid if _pid_alive(pid) else None
except (OSError, ValueError, json.JSONDecodeError):
return None
|