fix(web-viewer): exit when the bot that launched the viewer is gone

A bot killed with kill -9 on a manual run left its web viewer holding the port, and the next start could not bind it. The bot now passes its PID as --exit-with-parent and the viewer exits once that process is gone. A viewer started on its own is unchanged. A bot-launched viewer skips the Werkzeug reloader in debug mode, since the reloader would make the server a grandchild of the bot and the parent check would watch the wrong process.
This commit is contained in:
agessaman committed 2026-11-14 08:45:02 -08:00
1 parent 13159d8555
commit 07ab4e34d5
5 files changed
+596 -7

No files matched your search

+1
View File
@@ -11,6 +11,7 @@ semantic versioning.
- The bot refuses to start when another instance is already running against the same database, and names that instance's PID. Two instances on one radio evicted each other from single-client companion servers in an endless reconnect loop. The lock is a `<db_path>.lock` file beside the bot database and is released by the OS when the process exits, so a killed bot never leaves a stale lock behind.
- SIGTERM and Ctrl-C now stop a bot whose terminal has gone away. The shutdown handler printed before setting its flags, and a print to a closed terminal raised `OSError`, which swallowed the signal and left a bot that only `kill -9` could stop.
- A bot started from a terminal now shuts down when that terminal closes. SIGHUP was always treated as a config reload, so the bot kept running unattended. SIGHUP is still a reload under systemd, launchd, Docker, and `nohup`, and when sent by hand while the terminal is open.
- The web viewer now exits when the bot that launched it is gone. A bot killed with `kill -9` on a manual run left the viewer holding its port, and the next start could not bind it. The bot passes its PID as `--exit-with-parent`; a viewer started on its own is unchanged. A bot-launched viewer no longer uses the Werkzeug reloader in debug mode.
## [1.2.0] - 2026-11-11
+25 -5
View File
@@ -5237,17 +5237,22 @@ class BotDataViewer(DashboardSnapshotMixin, LiveStreamMixin, SocketClientsMixin,
mesh_graph=self._get_mesh_graph(),
)
def run(self, host='127.0.0.1', port=8080, debug=False):
def run(self, host='127.0.0.1', port=8080, debug=False, *, use_reloader=None):
"""Run the modern web viewer"""
self.logger.info(f"Starting modern web viewer on {host}:{port}")
self._suppress_werkzeug_headers_error()
# Only override when the caller asks. Standalone --debug still reloads.
run_kwargs = {}
if use_reloader is not None:
run_kwargs["use_reloader"] = use_reloader
try:
self.socketio.run(
self.app,
host=host,
port=port,
debug=debug,
allow_unsafe_werkzeug=True
allow_unsafe_werkzeug=True,
**run_kwargs,
)
except Exception as e:
self.logger.error(f"Error running web viewer: {e}")
@@ -5273,10 +5278,12 @@ class BotDataViewer(DashboardSnapshotMixin, LiveStreamMixin, SocketClientsMixin,
for name in ("werkzeug", "werkzeug.serving"):
logging.getLogger(name).addFilter(_HeadersAlreadySetFilter())
def main():
def main(argv: list[str] | None = None) -> None:
"""Entry point for the meshcore-viewer command"""
import argparse
from modules.web_viewer.parent_watch import start_parent_watcher
parser = argparse.ArgumentParser(description='MeshCore Bot Data Viewer')
parser.add_argument('--host', default='127.0.0.1', help='Host to bind to')
parser.add_argument('--port', type=int, default=8080, help='Port to bind to')
@@ -5286,11 +5293,24 @@ def main():
default="config.ini",
help="Path to configuration file (default: config.ini)",
)
parser.add_argument(
"--exit-with-parent",
type=int,
default=None,
metavar="PID",
help="Exit when this parent process is gone (set by the bot that launched the viewer)",
)
args = parser.parse_args()
args = parser.parse_args(argv)
viewer = BotDataViewer(config_path=args.config)
viewer.run(host=args.host, port=args.port, debug=args.debug)
run_kwargs = {}
if args.exit_with_parent is not None:
start_parent_watcher(args.exit_with_parent, logger=viewer.logger)
# Werkzeug's reloader would make the server a grandchild of the bot,
# so getppid() would not be the bot and the port could outlive it.
run_kwargs["use_reloader"] = False
viewer.run(host=args.host, port=args.port, debug=args.debug, **run_kwargs)
if __name__ == '__main__':
main()
+5 -2
View File
@@ -1091,13 +1091,16 @@ class WebViewerIntegration:
config_path = getattr(self.bot, 'config_file', 'config.ini')
config_path = str(Path(config_path).resolve()) if config_path else 'config.ini'
# Build command
# restart_viewer() starts the viewer again through this command.
# Pass our pid so a hard kill of the bot reaps the viewer; a
# standalone `app.py` run never goes through here.
cmd = [
sys.executable,
str(viewer_script),
"--config", config_path,
"--host", self.host,
"--port", str(self.port)
"--port", str(self.port),
"--exit-with-parent", str(os.getpid()),
]
if self.debug:
+252
View File
@@ -0,0 +1,252 @@
"""Stop the web viewer when the bot process that launched it is gone.
systemd and Docker reap an orphaned viewer. A manual run does not, so a
SIGKILL of the bot leaves the viewer holding its port. The bot passes its
pid as ``--exit-with-parent``. This module polls that pid and shuts the
viewer down once the bot is gone.
On POSIX the kernel reparents an orphan, so the parent is gone when
``os.getppid()`` no longer matches the pid we were given. ``os.kill(pid, 0)``
is not enough: the pid can be reused by an unrelated process.
Windows does not change ``os.getppid()`` when the parent exits. The watcher
opens a process handle at start and waits on that handle, so a reused pid
cannot look like the original parent. If the handle cannot be opened
(access denied), the watcher does nothing: shutting down would be a guess.
"""
from __future__ import annotations
import ctypes
import logging
import os
import signal
import sys
import threading
import time
from collections.abc import Callable
# How often to recheck, and how long to wait after SIGTERM before forcing exit.
# SIGTERM lets the viewer's existing handler unwind; os._exit covers a handler
# that returns and leaves the port bound.
POLL_INTERVAL_SEC = 2.0
HARD_EXIT_GRACE_SEC = 5.0
PARENT_EXITED_MESSAGE = "Parent process exited; shutting down web viewer"
_VIEWER_LOGGER_NAME = "modern_web_viewer"
# Win32 wait. Only consulted when sys.platform == "win32".
_PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
_SYNCHRONIZE = 0x00100000
_WAIT_OBJECT_0 = 0
_WAIT_TIMEOUT = 0x00000102
_STILL_ACTIVE = 259
_ERROR_ACCESS_DENIED = 5
_kernel32_dll = None
def parent_is_gone(parent_pid: int) -> bool:
"""Return whether ``parent_pid`` is no longer this process's live parent.
POSIX compares ``os.getppid()`` to ``parent_pid``. Windows opens a handle
for this single call, which can race with pid reuse; :func:`watch_parent`
opens its handle once and reuses it.
"""
if sys.platform == "win32":
handle, already_gone, unwatchable = _open_windows_parent(parent_pid)
try:
if unwatchable:
return False
if already_gone:
return True
if handle is None:
return False
return _windows_process_exited(handle)
finally:
_close_windows_handle(handle)
return os.getppid() != parent_pid
def watch_parent(
parent_pid: int,
*,
logger: logging.Logger | None = None,
poll_interval: float = POLL_INTERVAL_SEC,
hard_exit_grace: float = HARD_EXIT_GRACE_SEC,
stop_event: threading.Event | None = None,
on_parent_gone: Callable[[], None] | None = None,
) -> None:
"""Poll until ``parent_pid`` is gone, then shut this process down.
``on_parent_gone`` replaces the shutdown. Tests use it so observing the
decision does not kill the test runner. ``stop_event`` ends the wait
without shutting down.
"""
handle: int | None = None
already_gone = False
try:
if sys.platform == "win32":
handle, already_gone, unwatchable = _open_windows_parent(parent_pid)
if unwatchable:
# No reliable wait on this process. Staying up matches a
# standalone viewer rather than exiting on a guess.
_logger(logger).warning(
"Cannot watch parent process %s on Windows; the viewer will keep running",
parent_pid,
)
return
while True:
if stop_event is not None and stop_event.is_set():
return
if already_gone or _parent_is_gone(parent_pid, handle):
break
if _wait(stop_event, poll_interval):
return
closing, handle = handle, None
_close_windows_handle(closing)
if on_parent_gone is not None:
on_parent_gone()
return
_shutdown_because_parent_exited(logger, hard_exit_grace)
finally:
_close_windows_handle(handle)
def start_parent_watcher(
parent_pid: int,
*,
logger: logging.Logger | None = None,
) -> threading.Thread:
"""Start the daemon thread that exits this process when ``parent_pid`` dies."""
thread = threading.Thread(
target=watch_parent,
kwargs={"parent_pid": parent_pid, "logger": logger},
name="web-viewer-parent-watch",
daemon=True,
)
thread.start()
return thread
def _parent_is_gone(parent_pid: int, handle: int | None) -> bool:
if sys.platform == "win32":
if handle is None:
return False
return _windows_process_exited(handle)
# Reparented when the launcher dies. A recycled pid would still pass
# kill(pid, 0), so only the ppid comparison counts.
return os.getppid() != parent_pid
def _wait(stop_event: threading.Event | None, poll_interval: float) -> bool:
"""Sleep for one poll. Return True when ``stop_event`` is set."""
if stop_event is None:
time.sleep(poll_interval)
return False
return stop_event.wait(poll_interval)
def _shutdown_because_parent_exited(logger: logging.Logger | None, grace: float) -> None:
log = _logger(logger)
log.info(PARENT_EXITED_MESSAGE)
_flush_logger(log)
try:
_request_sigterm()
except Exception:
log.debug("SIGTERM to self failed", exc_info=True)
# The signal handler may ignore SIGTERM or take a moment to unwind.
# Do not leave the viewer holding the port.
time.sleep(grace)
os._exit(0)
def _request_sigterm() -> None:
if sys.platform == "win32":
# os.kill(SIGTERM) is TerminateProcess and skips Python handlers.
signal.raise_signal(signal.SIGTERM)
return
os.kill(os.getpid(), signal.SIGTERM)
def _logger(logger: logging.Logger | None) -> logging.Logger:
if logger is not None:
return logger
return logging.getLogger(_VIEWER_LOGGER_NAME)
def _flush_logger(logger: logging.Logger) -> None:
current: logging.Logger | None = logger
seen: set[int] = set()
while current is not None and id(current) not in seen:
seen.add(id(current))
for handler in list(current.handlers):
try:
handler.flush()
except Exception:
continue
if not current.propagate:
break
current = current.parent
def _kernel32():
global _kernel32_dll
if _kernel32_dll is not None:
return _kernel32_dll
from ctypes import wintypes
dll = ctypes.WinDLL("kernel32", use_last_error=True)
dll.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)
dll.OpenProcess.restype = wintypes.HANDLE
dll.WaitForSingleObject.argtypes = (wintypes.HANDLE, wintypes.DWORD)
dll.WaitForSingleObject.restype = wintypes.DWORD
dll.GetExitCodeProcess.argtypes = (wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD))
dll.GetExitCodeProcess.restype = wintypes.BOOL
dll.CloseHandle.argtypes = (wintypes.HANDLE,)
dll.CloseHandle.restype = wintypes.BOOL
_kernel32_dll = dll
return dll
def _open_windows_parent(parent_pid: int) -> tuple[int | None, bool, bool]:
"""Return ``(handle, already_gone, unwatchable)``.
The handle is the process object, not a later lookup by pid.
"""
if parent_pid <= 0:
return None, True, False
kernel32 = _kernel32()
handle = kernel32.OpenProcess(
_PROCESS_QUERY_LIMITED_INFORMATION | _SYNCHRONIZE,
False,
parent_pid,
)
if not handle:
if ctypes.get_last_error() == _ERROR_ACCESS_DENIED:
return None, False, True
return None, True, False
return int(handle), False, False
def _windows_process_exited(handle: int) -> bool:
from ctypes import wintypes
kernel32 = _kernel32()
waited = kernel32.WaitForSingleObject(handle, 0)
if waited == _WAIT_OBJECT_0:
return True
if waited == _WAIT_TIMEOUT:
return False
# Wait failed. The exit code is the backup; STILL_ACTIVE means running.
code = wintypes.DWORD()
if not kernel32.GetExitCodeProcess(handle, ctypes.byref(code)):
return False
return int(code.value) != _STILL_ACTIVE
def _close_windows_handle(handle: int | None) -> None:
if sys.platform != "win32" or not handle:
return
_kernel32().CloseHandle(handle)
+313
View File
@@ -0,0 +1,313 @@
"""Viewer exits when the bot that launched it is gone."""
import os
import signal
import subprocess
import sys
import threading
import time
from configparser import ConfigParser
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
from modules.web_viewer.parent_watch import (
HARD_EXIT_GRACE_SEC,
PARENT_EXITED_MESSAGE,
POLL_INTERVAL_SEC,
parent_is_gone,
watch_parent,
)
# Intermediate parent: spawn the watcher child, record its pid, then sleep
# until SIGKILL. The child must be a separate process so killing the parent
# reparents it.
_PARENT_SCRIPT = """\
import os
import subprocess
import sys
import time
child_pid_path, child_log_path, child_script = sys.argv[1:4]
with open(child_log_path, "w", encoding="utf-8") as log_fh:
child = subprocess.Popen(
[sys.executable, child_script, str(os.getpid())],
stdout=log_fh,
stderr=subprocess.STDOUT,
)
with open(child_pid_path, "w", encoding="utf-8") as fh:
fh.write(str(child.pid))
while True:
time.sleep(30)
"""
_CHILD_SCRIPT = """\
import logging
import sys
from modules.web_viewer.parent_watch import watch_parent
logger = logging.getLogger("modern_web_viewer")
logger.setLevel(logging.INFO)
logger.propagate = False
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
handler.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
logger.addHandler(handler)
watch_parent(int(sys.argv[1]), logger=logger)
"""
def _pid_alive(pid: int) -> bool:
"""True when pid is a running process. Zombies count as gone."""
if pid <= 0:
return False
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
return True
try:
result = subprocess.run(
["ps", "-o", "state=", "-p", str(pid)],
check=False,
capture_output=True,
text=True,
timeout=5,
)
except (OSError, subprocess.TimeoutExpired):
return True
state = result.stdout.strip()
if not state:
return False
return not state.startswith("Z")
def _kill_if_alive(pid: int | None) -> None:
if pid is None or pid <= 1 or not _pid_alive(pid):
return
try:
os.kill(pid, signal.SIGKILL)
except ProcessLookupError:
return
def _wait_for_pidfile(path: Path, timeout: float) -> int:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if path.is_file():
text = path.read_text(encoding="utf-8").strip()
if text.isdigit():
return int(text)
time.sleep(0.05)
raise AssertionError(f"child pid was not written to {path}")
def _make_bot(config_file: str):
bot = MagicMock()
bot.logger = MagicMock()
bot.config_file = config_file
config = ConfigParser()
config.add_section("Bot")
config.add_section("Web_Viewer")
config.set("Web_Viewer", "host", "127.0.0.1")
config.set("Web_Viewer", "port", "18765")
config.set("Web_Viewer", "enabled", "false")
config.set("Web_Viewer", "auto_start", "false")
config.set("Web_Viewer", "debug", "false")
bot.config = config
bot.db_manager = MagicMock()
bot.db_manager.db_path = ":memory:"
return bot
def test_watcher_does_nothing_while_parent_is_alive():
assert parent_is_gone(os.getppid()) is False
fired: list[int] = []
stop = threading.Event()
thread = threading.Thread(
target=watch_parent,
kwargs={
"parent_pid": os.getppid(),
"poll_interval": 0.05,
"stop_event": stop,
"on_parent_gone": lambda: fired.append(1),
},
daemon=True,
)
thread.start()
try:
time.sleep(0.3)
assert fired == []
if sys.platform != "win32":
assert thread.is_alive()
finally:
stop.set()
thread.join(timeout=2)
assert fired == []
assert not thread.is_alive()
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX reparents orphans; getppid is the check")
def test_parent_is_gone_compares_ppid_not_kill():
# Our own pid is not our parent. kill(pid, 0) would still succeed.
assert parent_is_gone(os.getppid()) is False
assert parent_is_gone(os.getpid()) is True
fired = threading.Event()
watch_parent(os.getpid(), poll_interval=30, on_parent_gone=fired.set)
assert fired.is_set()
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX reparents orphans; Windows uses a process handle")
def test_child_exits_when_parent_is_sigkilled(tmp_path: Path):
repo = Path(__file__).resolve().parents[1]
parent_script = tmp_path / "parent_runner.py"
child_script = tmp_path / "child_runner.py"
parent_script.write_text(_PARENT_SCRIPT, encoding="utf-8")
child_script.write_text(_CHILD_SCRIPT, encoding="utf-8")
child_pid_path = tmp_path / "child.pid"
child_log_path = tmp_path / "child.log"
parent_log_path = tmp_path / "parent.log"
env = os.environ.copy()
env["PYTHONPATH"] = str(repo) + os.pathsep + env.get("PYTHONPATH", "")
parent: subprocess.Popen | None = None
child_pid: int | None = None
try:
with parent_log_path.open("w", encoding="utf-8") as parent_log:
parent = subprocess.Popen(
[
sys.executable,
str(parent_script),
str(child_pid_path),
str(child_log_path),
str(child_script),
],
cwd=str(repo),
env=env,
stdout=parent_log,
stderr=subprocess.STDOUT,
start_new_session=True,
)
child_pid = _wait_for_pidfile(child_pid_path, timeout=5)
assert _pid_alive(child_pid), _failure_logs(parent_log_path, child_log_path)
# One full poll must pass while the parent is still alive.
time.sleep(POLL_INTERVAL_SEC + 0.5)
assert _pid_alive(parent.pid)
assert _pid_alive(child_pid), _failure_logs(parent_log_path, child_log_path)
os.kill(parent.pid, signal.SIGKILL)
parent.wait(timeout=5)
deadline = time.monotonic() + POLL_INTERVAL_SEC + HARD_EXIT_GRACE_SEC + 3
while time.monotonic() < deadline and _pid_alive(child_pid):
time.sleep(0.1)
logs = _failure_logs(parent_log_path, child_log_path)
assert not _pid_alive(child_pid), logs
assert PARENT_EXITED_MESSAGE in child_log_path.read_text(encoding="utf-8"), logs
assert "INFO" in child_log_path.read_text(encoding="utf-8")
finally:
_kill_if_alive(child_pid)
if parent is not None and parent.poll() is None:
_kill_if_alive(parent.pid)
if parent is not None:
try:
parent.wait(timeout=5)
except subprocess.TimeoutExpired:
_kill_if_alive(parent.pid)
parent.wait(timeout=5)
def _failure_logs(parent_log: Path, child_log: Path) -> str:
parent_text = parent_log.read_text(encoding="utf-8") if parent_log.is_file() else ""
child_text = child_log.read_text(encoding="utf-8") if child_log.is_file() else ""
return f"parent log:\n{parent_text}\nchild log:\n{child_text}"
def test_run_viewer_command_includes_exit_with_parent(tmp_path: Path):
from modules.web_viewer.integration import WebViewerIntegration
bot = _make_bot(str(tmp_path / "config.ini"))
with patch("modules.web_viewer.integration.BotIntegration._init_http_session"), \
patch("modules.web_viewer.integration.BotIntegration._init_packet_stream_table"), \
patch("modules.web_viewer.integration.BotIntegration._start_drain_thread"):
wvi = WebViewerIntegration(bot)
wvi.port = 18765
captured: list[list[str]] = []
def fake_popen(cmd, **kwargs):
captured.append(list(cmd))
proc = MagicMock()
proc.poll.return_value = 1
proc.returncode = 1
return proc
with patch("modules.web_viewer.integration.subprocess.Popen", side_effect=fake_popen), \
patch("modules.web_viewer.integration.time.sleep"):
wvi._run_viewer()
assert len(captured) == 1
cmd = captured[0]
assert cmd[0] == sys.executable
assert cmd[1].endswith("app.py")
flag = cmd.index("--exit-with-parent")
assert cmd[flag + 1] == str(os.getpid())
def test_main_without_flag_does_not_start_watcher():
with patch("modules.web_viewer.app.BotDataViewer") as viewer_cls, \
patch("modules.web_viewer.parent_watch.start_parent_watcher") as start:
viewer_cls.return_value.run.return_value = None
from modules.web_viewer.app import main
main(["--config", "unused.ini", "--port", "18765"])
start.assert_not_called()
viewer_cls.return_value.run.assert_called_once_with(
host="127.0.0.1",
port=18765,
debug=False,
)
def test_main_debug_without_flag_still_uses_default_reloader():
with patch("modules.web_viewer.app.BotDataViewer") as viewer_cls, \
patch("modules.web_viewer.parent_watch.start_parent_watcher") as start:
from modules.web_viewer.app import main
main(["--debug", "--port", "18765"])
start.assert_not_called()
viewer_cls.return_value.run.assert_called_once_with(
host="127.0.0.1",
port=18765,
debug=True,
)
def test_main_with_flag_starts_watcher_before_run():
events: list[str] = []
with patch("modules.web_viewer.app.BotDataViewer") as viewer_cls, \
patch(
"modules.web_viewer.parent_watch.start_parent_watcher",
side_effect=lambda *args, **kwargs: events.append("watch"),
) as start:
viewer_cls.return_value.run.side_effect = lambda **kwargs: events.append("run")
from modules.web_viewer.app import main
main([
"--exit-with-parent", "4321",
"--debug",
"--config", "unused.ini",
"--port", "18765",
])
assert events == ["watch", "run"]
start.assert_called_once_with(4321, logger=viewer_cls.return_value.logger)
# The reloader would put the server one process further from the bot.
viewer_cls.return_value.run.assert_called_once_with(
host="127.0.0.1",
port=18765,
debug=True,
use_reloader=False,
)