diff --git a/CHANGELOG.md b/CHANGELOG.md index 94b0414..10efdaf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 Entries for releases before this file existed were generated from commit subjects. +## [Unreleased] + +## [2.4.0] - 2026-11-25 + +- Show modules that are shutting down as `stopping`, with how long they may still take (pyobs-core >= 2.29). + Stop no longer kills a module after 5 s, which cut a camera's warm-up; it only sends SIGTERM. +- Kill button for a stopping module. +- Restart runs as a background job that waits for the shutdown, then starts the module. +- Start is refused while a module is stopping or being restarted. +- Fix: starting a module timed out (and killed it) when web-admin ran with a socket as stdin, e.g. under + `manage.py runserver`. + +## [2.3.10] - 2026-10-12 + +- Remove empty or unparseable PID files so pyobs can daemonize again + +## [2.3.9] - 2026-10-04 + +- LICENSE: put email on the copyright line so GitHub detects MIT + +## [2.3.8] - 2026-10-04 + +- Add CONTRIBUTING.md and CHANGELOG.md, add readme and project URLs to pyproject.toml + ## [2.3.7] - 2026-10-04 - Add MIT LICENSE diff --git a/modules/context_processors.py b/modules/context_processors.py index 2474fce..62bd1e7 100644 --- a/modules/context_processors.py +++ b/modules/context_processors.py @@ -7,7 +7,7 @@ def _sort_modules(modules_with_status: list[dict]) -> list[dict]: - return sorted(modules_with_status, key=lambda m: (0 if m["status"] == "running" else 1, m["name"])) + return sorted(modules_with_status, key=lambda m: (0 if m["status"] in ("running", "stopping") else 1, m["name"])) # Cached for the life of the process: this app isn't installed as a distribution (no diff --git a/modules/management/__init__.py b/modules/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/modules/management/commands/__init__.py b/modules/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/modules/management/commands/restart_module.py b/modules/management/commands/restart_module.py new file mode 100644 index 0000000..a0b7c22 --- /dev/null +++ b/modules/management/commands/restart_module.py @@ -0,0 +1,18 @@ +"""The detached restart job started by services.restart_module(), see services.run_restart().""" + +from django.core.management.base import BaseCommand, CommandError + +from modules import services + + +class Command(BaseCommand): + help = "Restarts a module: stops it, waits until it is gone (e.g. a camera warming up), starts it again." + + def add_arguments(self, parser): + parser.add_argument("name", type=str) + + def handle(self, *args, **options): + ok, msg = services.run_restart(options["name"]) + if not ok: + raise CommandError(msg) + self.stdout.write(msg) diff --git a/modules/services.py b/modules/services.py index 1dd1f44..9194828 100644 --- a/modules/services.py +++ b/modules/services.py @@ -7,6 +7,7 @@ import shlex import signal import subprocess +import sys import time from collections import deque from concurrent.futures import ThreadPoolExecutor @@ -1015,6 +1016,27 @@ def _clear_stale_pid(name: str) -> None: pf.unlink(missing_ok=True) +# ── Stop file ──────────────────────────────────────────────────────────────── +# +# pyobs-core (since 2.29, pyobs.utils.shutdown) writes ".stopping" on SIGTERM and removes it at the end +# of its shutdown. It holds the deadline (epoch seconds, a float) until which the module may still take, e.g. while +# a camera warms up. Keep this in sync with pyobs.utils.shutdown.STOP_FILE_SUFFIX and read_stop_deadline(). + +_STOP_FILE_SUFFIX = ".stopping" + + +def _stop_file(name: str) -> Path: + pf = _pid_file(name) + return pf.with_name(pf.name + _STOP_FILE_SUFFIX) + + +def _read_stop_deadline(name: str) -> float | None: + try: + return float(_stop_file(name).read_text().strip()) + except (OSError, ValueError): + return None + + # ── Config drift ────────────────────────────────────────────────────────────── # # Modules load their YAML config once at startup and never hot-reload it, so there's no way to @@ -1057,20 +1079,31 @@ def config_stale(name: str) -> bool | None: # ── Public API ──────────────────────────────────────────────────────────────── def get_module_status(name: str) -> str: - """Returns 'running', 'stopped', or 'unknown'.""" + """Returns 'running', 'stopping' (got SIGTERM and is still shutting down, see _stop_file), or 'stopped'.""" validate_name(name) pid = _read_pid(name) if pid is not None and _is_alive(pid): - return "running" + return "stopping" if _stop_file(name).exists() else "running" _clear_stale_pid(name) + _stop_file(name).unlink(missing_ok=True) return "stopped" -def start_module(name: str) -> tuple[bool, str]: +def get_stop_deadline(name: str) -> float | None: + """Epoch seconds until which a stopping module may still take to shut down, or None if unknown.""" + return _read_stop_deadline(name) + + +def start_module(name: str, _restart_job: bool = False) -> tuple[bool, str]: validate_name(name) - if get_module_status(name) == "running": + status = get_module_status(name) + if status == "running": return False, f"{name} is already running" + if status == "stopping": + return False, f"{name} is still shutting down" + if not _restart_job and restart_in_progress(name): + return False, f"{name} is being restarted" _clear_stale_pid(name) @@ -1094,7 +1127,9 @@ def start_module(name: str) -> tuple[bool, str]: try: # pyobs daemonizes itself (python-daemon double-fork) when --pid-file is given. # The immediate child exits quickly; subprocess.run returns with code 0. - result = subprocess.run(args, capture_output=True, text=True, timeout=10) + # stdin from /dev/null: python-daemon doesn't detach if stdin is a socket (it takes that for inetd), and + # then this call runs into the timeout, which kills the module + result = subprocess.run(args, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=10) except subprocess.TimeoutExpired: return False, "Timed out waiting for module to start" except FileNotFoundError: @@ -1115,6 +1150,9 @@ def start_module(name: str) -> tuple[bool, str]: def stop_module(name: str) -> tuple[bool, str]: + """Sends SIGTERM and returns right away. The module shuts down on its own, which can take long (e.g. a + cooled camera warming up), and shows as "stopping" until it is gone. Since pyobs-core 2.29, a module whose + shutdown hangs ends itself after its deadline. kill_module() is for when that can't wait.""" validate_name(name) pid = _read_pid(name) @@ -1122,25 +1160,49 @@ def stop_module(name: str) -> tuple[bool, str]: _pid_file(name).unlink(missing_ok=True) return False, f"{name} is not running" + # a second SIGTERM would kill a module with an older pyobs-core in the middle of its shutdown + if _stop_file(name).exists(): + return True, f"{name} is already shutting down" + try: os.kill(pid, signal.SIGTERM) except OSError as e: return False, str(e) + return True, f"Stopping {name}" - # Wait up to 5 s for graceful exit - for _ in range(25): - if not _is_alive(pid): - _pid_file(name).unlink(missing_ok=True) - return True, f"Stopped {name}" - time.sleep(0.2) - # Force-kill if it didn't respond +# how long kill_module() waits for a killed module to be gone +_KILL_WAIT_SECONDS = 5.0 + + +def kill_module(name: str) -> tuple[bool, str]: + """Sends SIGKILL right away, also to a module that is shutting down. Cuts a camera's warm-up.""" + validate_name(name) + + pid = _read_pid(name) + if pid is None or not _is_alive(pid): + _remove_run_files(name) + return False, f"{name} is not running" + try: os.kill(pid, signal.SIGKILL) - except OSError: - pass + except OSError as e: + return False, str(e) + + # SIGKILL can't end a process stuck in the kernel (e.g. in a USB driver call) until that call returns. + # Keep the PID file of such a process, so that it doesn't show as stopped and can't be started twice. + deadline = time.time() + _KILL_WAIT_SECONDS + while _is_alive(pid): + if time.time() >= deadline: + return False, f"{name} (PID {pid}) is still alive after SIGKILL, probably stuck in a driver call" + time.sleep(0.1) + _remove_run_files(name) + return True, f"Killed {name}" + + +def _remove_run_files(name: str) -> None: _pid_file(name).unlink(missing_ok=True) - return True, f"Force-killed {name} (did not exit after SIGTERM)" + _stop_file(name).unlink(missing_ok=True) _process_cache: dict[str, psutil.Process] = {} @@ -1287,10 +1349,115 @@ def activate_module(name: str) -> tuple[bool, str]: def restart_module(name: str) -> tuple[bool, str]: + """Restarts a module. A stopped one is just started. For a running one, the stop can take long (e.g. a camera + warming up), so a detached job does it (manage.py restart_module, see run_restart()), and this returns right + away. The module shows as "stopping" and then "running".""" validate_name(name) - stopped, msg = stop_module(name) - ok, start_msg = start_module(name) - return ok, start_msg + _run_dir().mkdir(parents=True, exist_ok=True) + # the check for a running job and writing the lock must happen in one step, else two requests at the same time + # both start a job + flock_fd = os.open(_restart_flock_file(name), os.O_CREAT | os.O_RDWR) + try: + try: + fcntl.flock(flock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + return False, f"{name} is already being restarted" + return _restart_module_locked(name) + finally: + os.close(flock_fd) # also releases the flock + + +def _restart_module_locked(name: str) -> tuple[bool, str]: + if restart_in_progress(name): + return False, f"{name} is already being restarted" + if get_module_status(name) == "stopped": + return start_module(name) + + log_file = _restart_log_file(name) + try: + with open(log_file, "w") as log: + proc = subprocess.Popen( + [sys.executable, str(settings.BASE_DIR / "manage.py"), "restart_module", name], + cwd=settings.BASE_DIR, + start_new_session=True, # survives this request, and a restart of web-admin (KillMode=process) + stdin=subprocess.DEVNULL, + stdout=log, + stderr=subprocess.STDOUT, + ) + except OSError as e: + return False, f"Could not start restart job: {e}" + try: + create_time = psutil.Process(proc.pid).create_time() + except psutil.NoSuchProcess: + create_time = None + _restart_lock_file(name).write_text(json.dumps({"pid": proc.pid, "pid_create_time": create_time})) + return True, f"Restarting {name}" + + +def restart_in_progress(name: str) -> bool: + """Whether a restart job for name is still running.""" + try: + lock = json.loads(_restart_lock_file(name).read_text()) + except (OSError, ValueError): + return False + pid = lock.get("pid") + if pid and _pkg_update_process_alive(pid, lock.get("pid_create_time")) and not _is_zombie(pid): + return True + _restart_lock_file(name).unlink(missing_ok=True) + return False + + +def _is_zombie(pid: int) -> bool: + """The restart job is a child of the gunicorn worker that started it, so once it exits it stays a zombie + (still "alive" for os.kill(pid, 0)) until that worker happens to reap it.""" + try: + return psutil.Process(pid).status() == psutil.STATUS_ZOMBIE + except psutil.NoSuchProcess: + return True + + +# how long run_restart() waits for a module that asked for no extra time, before it sends SIGKILL; the same as +# pyobsd's default stop_timeout +_RESTART_STOP_TIMEOUT = 30.0 + + +def run_restart(name: str) -> tuple[bool, str]: + """The restart job itself, run detached by restart_module(): stops the module, waits until it is gone, starts + it again. Waits for the deadline from the stop file (at least _RESTART_STOP_TIMEOUT) and sends SIGKILL after + that, for modules with a pyobs-core that doesn't end itself.""" + try: + validate_name(name) + pid = _read_pid(name) + if pid is not None and _is_alive(pid): + if not _stop_file(name).exists(): + os.kill(pid, signal.SIGTERM) + default_deadline = time.time() + _RESTART_STOP_TIMEOUT + # keep the last deadline seen, the module removes its stop file a moment before it exits + requested: float | None = None + while _is_alive(pid): + requested = _read_stop_deadline(name) or requested + if time.time() >= max(default_deadline, requested or 0.0): + ok, msg = kill_module(name) + if not ok: + return False, msg + break + time.sleep(0.5) + _remove_run_files(name) + return start_module(name, _restart_job=True) + finally: + _restart_lock_file(name).unlink(missing_ok=True) + + +def _restart_lock_file(name: str) -> Path: + return _run_dir() / f"{_active_name(name)}.restart.json" + + +def _restart_flock_file(name: str) -> Path: + return _run_dir() / f"{_active_name(name)}.restart.flock" + + +def _restart_log_file(name: str) -> Path: + return _run_dir() / f"{_active_name(name)}.restart.log" # ── journald log backend ───────────────────────────────────────────────────── diff --git a/modules/tests.py b/modules/tests.py index 706bf26..8e78fee 100644 --- a/modules/tests.py +++ b/modules/tests.py @@ -3,7 +3,11 @@ import json import os import re +import signal +import subprocess +import sys import tempfile +import threading import time import unittest from datetime import UTC, datetime, timedelta @@ -4622,3 +4626,263 @@ def test_sync_updates_an_existing_user_that_drifted(self): def test_sync_does_nothing_when_unconfigured(self): sync_admin_user(sender=None) self.assertFalse(User.objects.filter(username=_TEST_ADMIN_USERNAME).exists()) + + +# ── stopping state, stop, kill, restart job ───────────────────────────────────── + +# Stand-in for a daemonized pyobs module (pyobs-core >= 2.29): on SIGTERM it writes a deadline s from +# now into its stop file and exits s later, removing the stop file just before. With mode "ignore" it +# ignores SIGTERM, like a module whose shutdown hangs (or an older pyobs-core without a watchdog). +_FAKE_MODULE = """ +import os, signal, sys, time +pid_file, mode, extend, delay = sys.argv[1], sys.argv[2], float(sys.argv[3]), float(sys.argv[4]) +exit_at = None +def on_term(*_): + global exit_at + if exit_at is not None: + return + with open(pid_file + ".stopping", "w") as f: + f.write(str(time.time() + extend)) + exit_at = time.time() + delay +signal.signal(signal.SIGTERM, signal.SIG_IGN if mode == "ignore" else on_term) +with open(pid_file + ".tmp", "w") as f: + f.write(str(os.getpid())) +os.rename(pid_file + ".tmp", pid_file) +while exit_at is None or time.time() < exit_at: + time.sleep(0.02) +os.remove(pid_file + ".stopping") +""" + + +class StoppingStateTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.tmp_path = Path(self.tmp.name) + self.run_dir = self.tmp_path / "run" + self.run_dir.mkdir() + (self.tmp_path / "config").mkdir() + (self.tmp_path / "config" / "camera.yaml").write_text("class: x\n") + self._settings = override_settings( + PYOBS_RUN_DIR=str(self.run_dir), PYOBS_CONFIG_DIR=str(self.tmp_path / "config"), + PYOBS_CONFIG_GIT_ENABLED=False, + ) + self._settings.enable() + self.procs = [] + + def tearDown(self): + for proc in self.procs: + if proc.poll() is None: + proc.kill() + proc.wait() + self._settings.disable() + self.tmp.cleanup() + + def _fake(self, mode="exit", extend=0.0, delay=0.0): + pid_file = self.run_dir / "camera.pid" + proc = subprocess.Popen([sys.executable, "-c", _FAKE_MODULE, str(pid_file), mode, str(extend), str(delay)]) + self.procs.append(proc) + # the test is the parent here, and an unreaped child would still look alive to os.kill(pid, 0) + threading.Thread(target=proc.wait, daemon=True).start() + for _ in range(100): + if pid_file.exists(): + return proc + time.sleep(0.05) + raise RuntimeError("fake module did not write its PID file") + + def _wait_dead(self, proc, timeout=5.0): + deadline = time.monotonic() + timeout + while proc.poll() is None and time.monotonic() < deadline: + time.sleep(0.05) + + def _wait_stopping(self): + for _ in range(100): + if services.get_module_status("camera") == "stopping": + return + time.sleep(0.02) + raise AssertionError("module never showed as stopping") + + def test_stop_returns_right_away_and_shows_stopping(self): + proc = self._fake(extend=600.0, delay=1.0) + start = time.monotonic() + ok, msg = services.stop_module("camera") + self.assertTrue(ok) + self.assertLess(time.monotonic() - start, 0.5) + self._wait_stopping() + deadline = services.get_stop_deadline("camera") + self.assertIsNotNone(deadline) + self.assertGreater(deadline, time.time() + 500) + self._wait_dead(proc) + self.assertEqual(proc.returncode, 0) # not killed after 5 s like before + self.assertEqual(services.get_module_status("camera"), "stopped") + self.assertFalse((self.run_dir / "camera.pid").exists()) + + def test_stop_does_not_signal_stopping_module_again(self): + self._fake(extend=600.0, delay=1.0) + services.stop_module("camera") + self._wait_stopping() + with patch("modules.services.os.kill") as kill: + ok, msg = services.stop_module("camera") + self.assertTrue(ok) + self.assertIn("already shutting down", msg) + self.assertNotIn(signal.SIGTERM, [c.args[1] for c in kill.call_args_list if len(c.args) > 1]) + + def test_start_refused_while_stopping(self): + self._fake(extend=600.0, delay=1.0) + services.stop_module("camera") + self._wait_stopping() + ok, msg = services.start_module("camera") + self.assertFalse(ok) + self.assertIn("still shutting down", msg) + + def test_kill_stopping_module(self): + proc = self._fake(extend=600.0, delay=30.0) + services.stop_module("camera") + self._wait_stopping() + ok, msg = services.kill_module("camera") + self.assertTrue(ok, msg) + self._wait_dead(proc) + self.assertEqual(proc.returncode, -9) + self.assertFalse((self.run_dir / "camera.pid").exists()) + self.assertFalse((self.run_dir / "camera.pid.stopping").exists()) + self.assertEqual(services.get_module_status("camera"), "stopped") + + def test_kill_not_running(self): + ok, msg = services.kill_module("camera") + self.assertFalse(ok) + self.assertIn("not running", msg) + + @patch("modules.services._KILL_WAIT_SECONDS", 0.2) + @patch("modules.services._is_alive", return_value=True) + @patch("modules.services.os.kill") + def test_kill_keeps_pid_file_of_process_that_survives(self, _kill, _alive): + (self.run_dir / "camera.pid").write_text("4242") + ok, msg = services.kill_module("camera") + self.assertFalse(ok) + self.assertIn("still alive after SIGKILL", msg) + self.assertTrue((self.run_dir / "camera.pid").exists()) + + def test_stale_stop_file_is_removed_with_dead_module(self): + (self.run_dir / "camera.pid.stopping").write_text(str(time.time() + 100)) + self.assertEqual(services.get_module_status("camera"), "stopped") + self.assertFalse((self.run_dir / "camera.pid.stopping").exists()) + + def test_run_restart_waits_for_shutdown_then_starts(self): + proc = self._fake(extend=600.0, delay=0.8) + with patch("modules.services.start_module", return_value=(True, "Started camera")) as start: + ok, msg = services.run_restart("camera") + self.assertTrue(ok) + self.assertEqual(proc.returncode, 0) # exited after its shutdown, not killed + start.assert_called_once_with("camera", _restart_job=True) + + @patch("modules.services._RESTART_STOP_TIMEOUT", 0.3) + def test_run_restart_kills_module_that_does_not_stop(self): + proc = self._fake(mode="ignore") + with patch("modules.services.start_module", return_value=(True, "Started camera")) as start: + ok, _ = services.run_restart("camera") + self.assertTrue(ok) + self._wait_dead(proc) + self.assertEqual(proc.returncode, -9) + start.assert_called_once() + + def test_run_restart_removes_its_lock(self): + services._restart_lock_file("camera").write_text(json.dumps({"pid": os.getpid()})) + with patch("modules.services.start_module", return_value=(True, "Started camera")): + services.run_restart("camera") + self.assertFalse(services._restart_lock_file("camera").exists()) + + def test_restart_stopped_module_starts_directly(self): + with patch("modules.services.start_module", return_value=(True, "Started camera")) as start, \ + patch("modules.services.subprocess.Popen") as popen: + ok, _ = services.restart_module("camera") + self.assertTrue(ok) + start.assert_called_once_with("camera") + popen.assert_not_called() + + def test_restart_running_module_spawns_detached_job(self): + self._fake() + with patch("modules.services.subprocess.Popen") as popen: + popen.return_value.pid = os.getpid() + ok, msg = services.restart_module("camera") + self.assertTrue(ok) + args = popen.call_args.args[0] + self.assertEqual(args[-2:], ["restart_module", "camera"]) + self.assertTrue(popen.call_args.kwargs["start_new_session"]) + self.assertTrue(services.restart_in_progress("camera")) # our own PID stands in for the job + ok, msg = services.restart_module("camera") + self.assertFalse(ok) + self.assertIn("already being restarted", msg) + + def test_restart_in_progress_ignores_dead_job(self): + services._restart_lock_file("camera").write_text(json.dumps({"pid": 999999999})) + self.assertFalse(services.restart_in_progress("camera")) + self.assertFalse(services._restart_lock_file("camera").exists()) + + def test_start_refused_during_restart(self): + services._restart_lock_file("camera").write_text(json.dumps({"pid": os.getpid()})) + ok, msg = services.start_module("camera") + self.assertFalse(ok) + self.assertIn("being restarted", msg) + + def test_concurrent_restarts_spawn_one_job(self): + self._fake() + real_popen = subprocess.Popen + spawned = [] + + def popen(*args, **kwargs): + time.sleep(0.1) # widen the window between the check and writing the lock + proc = real_popen(["sleep", "5"], stdin=subprocess.DEVNULL) + self.procs.append(proc) + spawned.append(proc) + return proc + + barrier = threading.Barrier(2) + results = [] + + def restart(): + barrier.wait() + results.append(services.restart_module("camera")) + + with patch("modules.services.subprocess.Popen", side_effect=popen): + threads = [threading.Thread(target=restart) for _ in range(2)] + for t in threads: + t.start() + for t in threads: + t.join() + self.assertEqual(len(spawned), 1) + self.assertEqual(sorted(ok for ok, _ in results), [False, True]) + self.assertIn("already being restarted", next(msg for ok, msg in results if not ok)) + + def test_start_reads_stdin_from_devnull(self): + with patch("modules.services.subprocess.run") as run: + run.return_value = MagicMock(returncode=1, stdout="", stderr="boom") + services.start_module("camera") + self.assertIs(run.call_args.kwargs["stdin"], subprocess.DEVNULL) + + +class StatusApiStoppingTests(unittest.TestCase): + def setUp(self): + self.factory = RequestFactory() + + def _get(self, view, *args): + request = self.factory.get("/") + request.session = {} + request.user = MagicMock(is_authenticated=True) + return json.loads(view(request, *args).content) + + @patch("modules.views._installed_pyobs_versions", return_value={}) + @patch("modules.views.services.restart_in_progress", return_value=False) + @patch("modules.views.services.get_stop_deadline", return_value=1234.5) + @patch("modules.views.services.get_module_stats", return_value={"pid": 1}) + @patch("modules.views.services.get_module_status", return_value="stopping") + @patch("modules.views._get_module_or_404") + def test_status_reports_stopping_with_deadline_and_stats(self, *_): + data = self._get(views.api_status, "camera") + self.assertEqual(data["status"], "stopping") + self.assertEqual(data["stop_deadline"], 1234.5) + self.assertFalse(data["restarting"]) + self.assertEqual(data["stats"], {"pid": 1}) + + def test_host_summary_counts_stopping_as_running(self): + summary = views._host_summary("h", [{"status": "running"}, {"status": "stopping"}, {"status": "stopped"}]) + self.assertEqual(summary["running"], 2) + self.assertEqual(summary["stopped"], 1) diff --git a/modules/urls.py b/modules/urls.py index 0ec8723..6fa45cc 100644 --- a/modules/urls.py +++ b/modules/urls.py @@ -27,6 +27,7 @@ path("api/modules//status/", views.api_status, name="api_status"), path("api/modules//start/", views.api_start, name="api_start"), path("api/modules//stop/", views.api_stop, name="api_stop"), + path("api/modules//kill/", views.api_kill, name="api_kill"), path("api/modules//activate/", views.api_activate, name="api_activate"), path("api/modules//deactivate/", views.api_deactivate, name="api_deactivate"), path("api/modules//restart/", views.api_restart, name="api_restart"), diff --git a/modules/views.py b/modules/views.py index 0b007d2..3bc37c4 100644 --- a/modules/views.py +++ b/modules/views.py @@ -151,7 +151,7 @@ def dashboard(request): def _host_summary(name: str, modules: list[dict]) -> dict: - running = sum(1 for m in modules if m.get("status") == "running") + running = sum(1 for m in modules if m.get("status") in _ALIVE) stopped = len(modules) - running cpu = sum(m["stats"]["cpu_percent"] for m in modules if m.get("stats")) mem = sum(m["stats"]["memory_mb"] for m in modules if m.get("stats")) @@ -179,7 +179,7 @@ def fleet_overview(request): local_modules = [] for name in services.list_modules(): status = services.get_module_status(name) - stats = services.get_module_stats(name) if status == "running" else None + stats = services.get_module_stats(name) if status in _ALIVE else None local_modules.append({"name": name, "status": status, "stats": stats}) hosts = [_host_summary("localhost", local_modules)] per_host_packages = [("localhost", services.get_package_overview())] @@ -448,6 +448,17 @@ def acl_matrix(request): # ── Status API ──────────────────────────────────────────────────────────────── +# statuses with a live process: "stopping" is still running, just shutting down +_ALIVE = ("running", "stopping") + + +def _stop_info(name: str, status: str) -> dict: + return { + "stop_deadline": services.get_stop_deadline(name) if status == "stopping" else None, + "restarting": services.restart_in_progress(name), + } + + def _installed_pyobs_versions() -> dict[str, str]: return {p["name"]: p["version"] for p in services.list_pyobs_packages()} @@ -473,12 +484,12 @@ def api_all_statuses(request): result = [] for m in modules: status = services.get_module_status(m) - stats = services.get_module_stats(m) if status == "running" else None + stats = services.get_module_stats(m) if status in _ALIVE else None versions, outdated = _versions_and_outdated(m, status, installed) config_stale = services.config_stale(m) if status == "running" else None result.append({ "name": m, "status": status, "stats": stats, "comm_user": services.get_comm_user(m), - "versions": versions, "outdated": outdated, "config_stale": config_stale, + "versions": versions, "outdated": outdated, "config_stale": config_stale, **_stop_info(m, status), }) return JsonResponse({"modules": result, "installed": installed}) @@ -490,13 +501,13 @@ def api_status(request, name: str): return _proxy(host, "GET", f"/api/modules/{name}/status/") _get_module_or_404(name) status = services.get_module_status(name) - stats = services.get_module_stats(name) if status == "running" else None + stats = services.get_module_stats(name) if status in _ALIVE else None installed = _installed_pyobs_versions() versions, outdated = _versions_and_outdated(name, status, installed) config_stale = services.config_stale(name) if status == "running" else None return JsonResponse({ "status": status, "stats": stats, "versions": versions, "outdated": outdated, - "installed": installed, "config_stale": config_stale, + "installed": installed, "config_stale": config_stale, **_stop_info(name, status), }) @@ -522,6 +533,16 @@ def api_stop(request, name: str): return JsonResponse({"success": success, "output": output}) +@require_POST +def api_kill(request, name: str): + host = _active_host(request) + if host: + return _proxy(host, "POST", f"/api/modules/{name}/kill/") + _get_module_or_404(name) + success, output = services.kill_module(name) + return JsonResponse({"success": success, "output": output}) + + @require_POST def api_restart(request, name: str): host = _active_host(request) @@ -1385,7 +1406,7 @@ def api_module_ejabberd(request, name: str): if comm_user is None: return JsonResponse({"comm_user": None}) shared_with = [n for n in services.find_modules_sharing_comm_user(comm_user) if n != name] - running = services.get_module_status(name) == "running" + running = services.get_module_status(name) in _ALIVE try: state = _ejabberd_user(comm_user) except Exception as e: diff --git a/pyproject.toml b/pyproject.toml index 8964bde..e893057 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "pyobs-web-admin" -version = "2.3.10" +version = "2.4.0" description = "Web-based administration interface for pyobs robotic telescope modules" authors = [ { name = "Tim-Oliver Husser", email = "thusser@uni-goettingen.de" }, diff --git a/specs/design/index.md b/specs/design/index.md index 73590bf..addaa61 100644 --- a/specs/design/index.md +++ b/specs/design/index.md @@ -119,6 +119,8 @@ is fine, that's what the Design section of the eventual doc is for. clone/fetch/pull/push/reset. **Implemented**, off by default. Two known gaps left open (see that doc's Open questions): `git_pull()` doesn't auto-stage/commit first as originally planned, and the page ignores `PYOBS_CONFIG_GIT_ENABLED` when visited directly. +- [module-shutdown.md](module-shutdown.md) — `stopping` state from pyobs-core's stop file, non-blocking stop, + kill button while stopping, restart as a detached job. **Implemented** for the PID-file mode. ## Ideas (not yet designed) diff --git a/specs/design/module-shutdown.md b/specs/design/module-shutdown.md new file mode 100644 index 0000000..721c06d --- /dev/null +++ b/specs/design/module-shutdown.md @@ -0,0 +1,56 @@ +# Module shutdown: stopping state, kill, background restart + +## Status + +Implemented (old PID-file mode). Needs pyobs-core >= 2.29 on the host for the full behavior (stop file and the +module's own watchdog), see `pyobs-core/specs/plans/2026-11-25-pyobsd-systemd-mode.md`. The systemd mode from that +plan is not part of this. + +## Motivation + +A module's shutdown can take long: a cooled camera warms up in `close()` (`CoolingRampMixin`), 37 min was seen on +iag50cam. web-admin used to send SIGTERM, wait 5 s and then SIGKILL, which cut the warm-up. Restart called stop and +then start right away, so with a long stop the start failed with "already running". + +## Current state before this + +- `stop_module`: SIGTERM, 5 s, SIGKILL. +- `restart_module`: `stop_module` then `start_module`, in the request. +- `get_module_status`: `running` or `stopped`. + +## Design + +pyobs-core (since 2.29, `pyobs.utils.shutdown`) writes `.stopping` on the first signal and removes it at +the end of its shutdown. The file holds a deadline (epoch seconds, float) until which the module may still take. +On the first signal the module also starts a watchdog that ends the process after that deadline (or 30 s, +`--stop-timeout`), plus 5 s. Further signals are ignored. web-admin reads that file and otherwise needs no waiting: + +- **Status**: live PID + stop file = `stopping`. The status APIs add `stop_deadline` and `restarting`. `stopping` + counts as running for stats, the dashboard counters, the fleet overview and the sidebar order. +- **Stop**: SIGTERM and return. No SIGTERM if the stop file already exists (a module with an older pyobs-core + would get killed by a second one). +- **Kill**: SIGKILL right away, also while stopping. Waits up to 5 s; a process that survives (stuck in a driver + call) keeps its PID file, so it can't be started twice. The UI shows the button only while stopping, with a + confirmation. +- **Restart**: a stopped module is just started. Otherwise a detached job, `manage.py restart_module ` + (`services.run_restart`), sends SIGTERM, waits until the module is gone and starts it. It waits for the deadline + from the stop file, at least 30 s, then sends SIGKILL, as a fallback for modules without the watchdog. The job + runs in its own session and survives a restart of web-admin (`KillMode=process`). Its lock is + `/.restart.json` (PID and create time, a zombie counts as done), its output goes to + `/.restart.log`. `restart_module` checks for a running job and writes the lock under an flock on + `/.restart.flock`, so two requests at the same moment can't both start a job. A manual `pyobsd restart` + doesn't know this lock, in that case one of the two starts fails with "already running". +- **Start** is refused while a module is stopping or a restart job runs. It runs pyobs with stdin from + `/dev/null`: python-daemon doesn't detach if stdin is a socket (e.g. under `manage.py runserver`), and the + start then runs into its 10 s timeout, which also kills the module. + +The stop file format is shared with pyobs-core (`STOP_FILE_SUFFIX`, `read_stop_deadline`). If it changes there, +`services._stop_file`/`_read_stop_deadline` have to follow. + +Why not call `pyobsd`: in the old mode, pyobsd reads its own config file for paths and the user to switch to, which +can differ from web-admin's settings, so every call would need `-c/-r/-l --chuid ""`. With the module's own +watchdog, a stop needs no waiter anymore, so there is little to share. The systemd mode will call `pyobsd`. + +## Open questions + +None currently. diff --git a/specs/index.md b/specs/index.md index 5809ad4..2aadd27 100644 --- a/specs/index.md +++ b/specs/index.md @@ -11,4 +11,6 @@ convention across the `pyobs` ecosystem (it additionally has `adrs/` and `steeri another sibling repo). See `pyobs-core`'s `specs/` for cross-repo design docs, plans, and ADRs that happen to touch this repo (tagged with a `Repos:` line there) — e.g. `../../pyobs-core/specs/design/shared-authz-keycloak.md` (proposed: centralized authorization via -Keycloak groups; replaces this repo's Django-admin activation for Keycloak-linked users). +Keycloak groups; replaces this repo's Django-admin activation for Keycloak-linked users), and +`../../pyobs-core/specs/plans/2026-11-25-pyobsd-systemd-mode.md` (proposed: systemd mode for +pyobsd; in that mode this repo calls `pyobsd` instead of managing PID files itself). diff --git a/templates/base.html b/templates/base.html index 7ba2394..20bbd56 100644 --- a/templates/base.html +++ b/templates/base.html @@ -73,6 +73,7 @@ } .status-dot.running { background: #198754; } .status-dot.stopped { background: #dc3545; } + .status-dot.stopping { background: #ffc107; } .status-dot.unknown { background: #495057; } /* A flex item's default min-width is auto (its content's own min-content size), not 0 -- diff --git a/templates/modules/dashboard.html b/templates/modules/dashboard.html index 149d4d7..cce035a 100644 --- a/templates/modules/dashboard.html +++ b/templates/modules/dashboard.html @@ -130,6 +130,9 @@

Dashboard

+ {% if mod|slice:':1' == '_' %}