Virtual-LPU / lpu /runtime /lifecycle.py
iparaco's picture
Upload 118 files
e59bd9d verified
Raw History Blame Contribute Delete
5.37 kB
"""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