From 60b8c6bff7641e7f4bac230624ba650cef485cef Mon Sep 17 00:00:00 2001 From: patrickbeane Date: Fri, 30 Oct 2026 11:31:32 -0400 Subject: [PATCH 1/2] Add heartbeat pings for the alert check and the nightly backup heartbeat_url is pinged after every alert check that sent its notifications without failures, and backup_heartbeat_url after every successful nightly backup, so an external monitor (healthchecks.io, Uptime Kuma) notices when the alert timer or the backup stops running. A failing heartbeat is logged without the URL and never fails the work it reports on. kernelwatch test-heartbeat pings each configured URL once. Co-Authored-By: Claude Sonnet 5.5 --- server/kernelwatch/alerts.py | 22 ++++ server/kernelwatch/cli.py | 24 ++++- server/kernelwatch/config.py | 18 ++++ tests/test_heartbeat.py | 194 +++++++++++++++++++++++++++++++++++ 4 files changed, 257 insertions(+), 1 deletion(-) create mode 100644 tests/test_heartbeat.py diff --git a/server/kernelwatch/alerts.py b/server/kernelwatch/alerts.py index fdf2adc..4c5f860 100644 --- a/server/kernelwatch/alerts.py +++ b/server/kernelwatch/alerts.py @@ -53,6 +53,28 @@ def publish(cfg: Config, title: str, message: str, *, stale: bool = False, raise DeliveryError(f"ntfy request failed ({type(exc).__name__})") from None +HEARTBEAT_TIMEOUT_SECONDS = 10.0 + + +def ping(url: str) -> bool: + """GET a heartbeat URL (healthchecks.io, Uptime Kuma push, ...). True if it answers 2xx. + + The URL is a secret (whoever has it can fake a heartbeat), so errors say only what + went wrong, never the URL. A failure here must never break the work it reports on, + so callers log and carry on.""" + try: + request = Request(url, headers={"User-Agent": "kernelwatch"}, method="GET") + # urllib raises HTTPError for anything but 2xx, and redirects aren't followed. + with build_opener(_NoRedirect()).open(request, timeout=HEARTBEAT_TIMEOUT_SECONDS): + return True + except HTTPError as exc: + print(f"kernelwatch: heartbeat returned HTTP {exc.code}", file=sys.stderr) + exc.close() + except (URLError, OSError, ValueError, HTTPException) as exc: + print(f"kernelwatch: heartbeat request failed ({type(exc).__name__})", file=sys.stderr) + return False + + def _utc(timestamp: int | float) -> str: return time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(timestamp)) diff --git a/server/kernelwatch/cli.py b/server/kernelwatch/cli.py index 36a4999..2fac21b 100644 --- a/server/kernelwatch/cli.py +++ b/server/kernelwatch/cli.py @@ -29,7 +29,25 @@ def cmd_serve(cfg, args) -> int: def cmd_check_alerts(cfg, args) -> int: - return int(alerts.check(cfg) > 0) + failures = alerts.check(cfg) + # Skipped when deliveries failed, so the monitor also notices a broken alert pipeline. + if cfg.heartbeat_url and not failures: + alerts.ping(cfg.heartbeat_url) + return int(failures > 0) + + +def cmd_test_heartbeat(cfg, args) -> int: + urls = [(name, url) for name, url in (("heartbeat_url", cfg.heartbeat_url), + ("backup_heartbeat_url", cfg.backup_heartbeat_url)) if url] + if not urls: + print("kernelwatch: neither heartbeat_url nor backup_heartbeat_url is configured", file=sys.stderr) + return 1 + failed = 0 + for name, url in urls: + ok = alerts.ping(url) + failed += not ok + print(f"{name}: {'ok' if ok else 'FAILED'}") + return int(failed > 0) def cmd_test_alert(cfg, args) -> int: @@ -66,6 +84,8 @@ def cmd_scheduled_backup(cfg, args) -> int: print(f"kernelwatch: scheduled backup failed: {exc}", file=sys.stderr) return 1 print(f"Backed up to {dest}") + if cfg.backup_heartbeat_url: + alerts.ping(cfg.backup_heartbeat_url) return 0 @@ -183,6 +203,8 @@ def main(argv: list[str] | None = None) -> int: p = sub.add_parser("backup", help="write a consistent copy of the database to PATH") p.add_argument("path") p.set_defaults(func=cmd_backup) + sub.add_parser("test-heartbeat", help="ping the configured heartbeat URLs once and report").set_defaults( + func=cmd_test_heartbeat) sub.add_parser("notify-backup-failure", help="send the failed-backup notification " "(run by systemd when kernelwatch-backup.service fails)").set_defaults( func=cmd_notify_backup_failure) diff --git a/server/kernelwatch/config.py b/server/kernelwatch/config.py index 03467af..97a313b 100644 --- a/server/kernelwatch/config.py +++ b/server/kernelwatch/config.py @@ -49,6 +49,12 @@ class Config: ntfy_url: str = "" ntfy_token: str = "" ntfy_timeout_seconds: float = 10.0 + + # Dead-man's-switch URLs (e.g. healthchecks.io): pinged after every successful + # alert check (every five minutes) and every successful nightly backup, so a + # monitor outside this host notices when either stops. Empty disables. + heartbeat_url: str = "" + backup_heartbeat_url: str = "" # Notify when a host has needed a reboot or updates for this long; 0 disables. status_alert_after_hours: float = 24.0 @@ -90,6 +96,18 @@ def load(path: str | None = None) -> Config: raise SystemExit(f"{path}: backup_dir must be an absolute path") if not math.isfinite(cfg.status_alert_after_hours) or cfg.status_alert_after_hours < 0: raise SystemExit(f"{path}: status_alert_after_hours must be zero or positive and finite") + for key in ("heartbeat_url", "backup_heartbeat_url"): + value = getattr(cfg, key) + if value: + try: + url = urlsplit(value) + valid = (url.scheme in ("http", "https") and url.hostname and url.port != 0 + and not url.fragment + and not any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in value)) + except ValueError: + valid = False + if not valid: + raise SystemExit(f"{path}: {key} must be an HTTP(S) URL without spaces or a fragment") if any(ord(c) < 32 or ord(c) == 127 for c in cfg.ntfy_url + cfg.ntfy_token): raise SystemExit(f"{path}: ntfy settings must not contain control characters") if cfg.ntfy_url: diff --git a/tests/test_heartbeat.py b/tests/test_heartbeat.py new file mode 100644 index 0000000..a339c45 --- /dev/null +++ b/tests/test_heartbeat.py @@ -0,0 +1,194 @@ +"""Heartbeat pings: real HTTP requests to a local server, and when the commands send them.""" + +import contextlib +import io +import os +import threading +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from unittest import mock + +from helpers import tempdir +from kernelwatch import alerts, cli, config + +SECRET = "0f1e2d3c-secret-uuid" + + +class HeartbeatCase(unittest.TestCase): + def setUp(self): + class Sink(BaseHTTPRequestHandler): + def do_GET(self): + self.server.hits.append((self.path, dict(self.headers))) + self.send_response(self.server.code) + if self.server.code in (301, 302): + self.send_header("Location", "/elsewhere") + self.send_header("Content-Length", "0") + self.end_headers() + + def log_message(self, *args): + pass + + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Sink) + self.server.hits, self.server.code = [], 200 + threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.01}, + daemon=True).start() + self.addCleanup(self.server.server_close) + self.addCleanup(self.server.shutdown) + self.base = f"http://127.0.0.1:{self.server.server_port}" + self.hits = self.server.hits + stack = contextlib.ExitStack() + self.addCleanup(stack.close) + self.out = stack.enter_context(contextlib.redirect_stdout(io.StringIO())) + self.err = stack.enter_context(contextlib.redirect_stderr(io.StringIO())) + + +class PingTest(HeartbeatCase): + def test_get_with_path_and_query_intact(self): + self.assertTrue(alerts.ping(f"{self.base}/ping/{SECRET}?status=up&msg=OK")) + self.assertEqual([h[0] for h in self.hits], [f"/ping/{SECRET}?status=up&msg=OK"]) + self.assertEqual(self.hits[0][1]["User-Agent"], "kernelwatch") + + def test_any_2xx_is_success(self): + for code in (200, 201, 204): + self.server.code = code + self.assertTrue(alerts.ping(f"{self.base}/p"), code) + + def test_other_statuses_fail_without_leaking_the_url(self): + for code in (302, 400, 404, 429, 500, 503): + with self.subTest(code=code): + self.server.code = code + self.assertFalse(alerts.ping(f"{self.base}/ping/{SECRET}")) + self.assertEqual(len(self.hits), 6, "redirects must not be followed") + self.assertIn("HTTP 503", self.err.getvalue()) + self.assertNotIn(SECRET, self.err.getvalue() + self.out.getvalue()) + + def test_unreachable_server_fails_without_leaking_the_url(self): + self.server.shutdown() + self.server.server_close() + self.assertFalse(alerts.ping(f"{self.base}/ping/{SECRET}")) + self.assertIn("heartbeat request failed", self.err.getvalue()) + self.assertNotIn(SECRET, self.err.getvalue()) + + def test_timeout_is_bounded(self): + with mock.patch("kernelwatch.alerts.build_opener") as opener: + opener.return_value.open.side_effect = TimeoutError(f"timed out {SECRET}") + self.assertFalse(alerts.ping(f"https://hc.example/{SECRET}")) + self.assertEqual(opener.return_value.open.call_args.kwargs["timeout"], + alerts.HEARTBEAT_TIMEOUT_SECONDS) + self.assertNotIn(SECRET, self.err.getvalue()) + + +class CommandsTest(HeartbeatCase): + def setUp(self): + super().setUp() + self.tmp = tempdir() + self.addCleanup(self.tmp.cleanup) + self.config_path = os.path.join(self.tmp.name, "server.toml") + + def configure(self, **values): + lines = [f'db_path = "{self.tmp.name}/kw.db"', f'backup_dir = "{self.tmp.name}/backups"'] + lines += [f'{k} = "{v}"' for k, v in values.items()] + with open(self.config_path, "w") as f: + f.write("\n".join(lines) + "\n") + + def run_cli(self, *args): + return cli.main(["-c", self.config_path, *args]) + + def test_check_alerts_pings_after_a_clean_run(self): + self.configure(heartbeat_url=f"{self.base}/hb") + self.assertEqual(self.run_cli("check-alerts"), 0) + self.assertEqual([h[0] for h in self.hits], ["/hb"]) + + def test_check_alerts_pings_even_without_ntfy(self): + # The timer is still alive, which is what the heartbeat reports. + self.configure(heartbeat_url=f"{self.base}/hb") + with mock.patch("kernelwatch.alerts.publish") as publish: + self.run_cli("check-alerts") + publish.assert_not_called() + self.assertEqual(len(self.hits), 1) + + def test_no_ping_when_notifications_failed(self): + self.configure(heartbeat_url=f"{self.base}/hb") + with mock.patch("kernelwatch.cli.alerts.check", return_value=2): + self.assertEqual(self.run_cli("check-alerts"), 1) + self.assertEqual(self.hits, []) + + def test_no_ping_when_the_check_crashes(self): + self.configure(heartbeat_url=f"{self.base}/hb") + with mock.patch("kernelwatch.cli.alerts.check", side_effect=RuntimeError("db locked")): + with self.assertRaises(RuntimeError): + self.run_cli("check-alerts") + self.assertEqual(self.hits, []) + + def test_nothing_is_pinged_unless_configured(self): + self.configure() + self.assertEqual(self.run_cli("check-alerts"), 0) + self.assertEqual(self.run_cli("scheduled-backup"), 0) + self.assertEqual(self.hits, []) + + def test_a_dead_heartbeat_never_fails_the_check(self): + self.server.code = 500 + self.configure(heartbeat_url=f"{self.base}/hb") + self.assertEqual(self.run_cli("check-alerts"), 0) + self.assertIn("HTTP 500", self.err.getvalue()) + + def test_backup_pings_its_own_url_only_on_success(self): + self.configure(heartbeat_url=f"{self.base}/alerts", backup_heartbeat_url=f"{self.base}/backup") + self.assertEqual(self.run_cli("scheduled-backup"), 0) + self.assertEqual([h[0] for h in self.hits], ["/backup"]) + del self.hits[:] + with mock.patch("kernelwatch.db.rotate_backups", side_effect=OSError("disk full")): + self.assertEqual(self.run_cli("scheduled-backup"), 1) + self.assertEqual(self.hits, []) + + def test_a_dead_backup_heartbeat_never_fails_the_backup(self): + self.server.code = 503 + self.configure(backup_heartbeat_url=f"{self.base}/backup") + self.assertEqual(self.run_cli("scheduled-backup"), 0) + self.assertTrue(os.listdir(os.path.join(self.tmp.name, "backups"))) + + def test_manual_backup_does_not_ping(self): + self.configure(backup_heartbeat_url=f"{self.base}/backup") + self.assertEqual(self.run_cli("backup", os.path.join(self.tmp.name, "manual.db")), 0) + self.assertEqual(self.hits, []) + + def test_test_heartbeat_reports_each_url(self): + self.configure(heartbeat_url=f"{self.base}/a", backup_heartbeat_url=f"{self.base}/b") + self.assertEqual(self.run_cli("test-heartbeat"), 0) + self.assertEqual(self.out.getvalue().splitlines(), ["heartbeat_url: ok", "backup_heartbeat_url: ok"]) + self.server.code = 404 + self.assertEqual(self.run_cli("test-heartbeat"), 1) + self.assertIn("heartbeat_url: FAILED", self.out.getvalue()) + + def test_test_heartbeat_needs_a_url(self): + self.configure() + self.assertEqual(self.run_cli("test-heartbeat"), 1) + self.assertIn("neither heartbeat_url nor backup_heartbeat_url", self.err.getvalue()) + + +class ConfigTest(unittest.TestCase): + def load(self, text): + with tempdir() as tmp: + path = os.path.join(tmp, "server.toml") + with open(path, "w") as f: + f.write(text) + return config.load(path) + + def test_accepts_plain_and_query_urls(self): + for url in ("https://hc-ping.com/0f1e2d3c", "http://kuma.example:3001/api/push/abc?status=up&msg=OK&ping="): + cfg = self.load(f'heartbeat_url = "{url}"\nbackup_heartbeat_url = "{url}"\n') + self.assertEqual((cfg.heartbeat_url, cfg.backup_heartbeat_url), (url, url)) + + def test_defaults_to_disabled(self): + self.assertEqual((config.Config().heartbeat_url, config.Config().backup_heartbeat_url), ("", "")) + + def test_rejects_bad_urls(self): + for key in ("heartbeat_url", "backup_heartbeat_url"): + for bad in ("hc-ping.com/x", "ftp://hc.example/x", "https://", "https://hc.example/a b", + "https://hc.example/x#frag", "https://hc.example:0/x", "https://hc.example:bad/x"): + with self.subTest(key=key, bad=bad), self.assertRaises(SystemExit): + self.load(f'{key} = "{bad}"\n') + + +if __name__ == "__main__": + unittest.main() -- 2.54.1 From 55a976641806dcdc17973f7199e2a6821170d6f5 Mon Sep 17 00:00:00 2001 From: patrickbeane Date: Fri, 30 Oct 2026 11:32:15 -0400 Subject: [PATCH 2/2] Document the heartbeat monitor setup Co-Authored-By: Claude Sonnet 5.5 --- README.md | 41 ++++++++++++++++++++++++++++++++++++++ server/server.toml.example | 6 ++++++ 2 files changed, 47 insertions(+) diff --git a/README.md b/README.md index f17180d..1ee8969 100644 --- a/README.md +++ b/README.md @@ -453,6 +453,46 @@ accept the POST without a browser login or redirect. The topic and token stay in the server config (root-owned, readable by the `kernelwatch` service group). Agents need no changes. +## Heartbeat: is kernelwatch itself running? + +Every alert above depends on `kernelwatch-alerts.timer` running on the dashboard +host. If that host is down, or the timer breaks, nothing tells you. A heartbeat +fixes this: kernelwatch pings an external monitor, and the monitor alerts when the +pings **stop**. [healthchecks.io](https://healthchecks.io) has a free tier; +Uptime Kuma's push monitors work the same way. + +1. In the monitor, create two checks and copy their ping URLs: + - **alerts**: period 5 minutes, grace 20 minutes. + - **backup**: period 1 day, grace a few hours (the timer fires about 03:30 and + can be up to 30 minutes late). +2. Add the URLs to `/etc/kernelwatch/server.toml` (no restart needed for the + alert check or the backup; they read it on every run): + + ```toml + heartbeat_url = "https://hc-ping.com/" + backup_heartbeat_url = "https://hc-ping.com/" + ``` + +3. Check both: `sudo kernelwatch test-heartbeat` pings each configured URL once. + +What counts as a heartbeat: + +- `heartbeat_url` is pinged at the end of every alert check (every five minutes) + that sent all its notifications. If ntfy delivery is failing, the ping is + skipped on purpose, so the monitor also notices a broken alert pipeline. It's + pinged even with no `ntfy_url`, since the timer is still alive. +- `backup_heartbeat_url` is pinged after each successful nightly backup, so a + timer that never ran, or a backup that failed, shows up as a missing ping. + A manual `kernelwatch backup` doesn't ping. +- A heartbeat that can't be delivered is logged (status code or error type, never + the URL) and never fails the check or the backup. + +The pings leave from the dashboard host, so a dead host is exactly what stops +them. Set the monitor to notify you some way that doesn't depend on that host: +email, the monitor's own app, or ntfy.sh. Not a ntfy server running behind it. +The URLs are secrets (whoever has one can fake a heartbeat), so keep +`server.toml` readable by root and the `kernelwatch` group only. + ## Server admin commands ``` @@ -468,6 +508,7 @@ sudo kernelwatch scheduled-backup dated copy in backup_dir, then prune old on sudo kernelwatch notify-backup-failure send the failed-backup notification now (also runs on failure) sudo kernelwatch check-alerts check for stale, recovered, reboot and update alerts now sudo kernelwatch test-alert send a test notification to the configured ntfy topic +sudo kernelwatch test-heartbeat ping the configured heartbeat URLs once and report ``` ## Backups diff --git a/server/server.toml.example b/server/server.toml.example index 6ffa3a1..872ba02 100644 --- a/server/server.toml.example +++ b/server/server.toml.example @@ -50,3 +50,9 @@ ntfy_timeout_seconds = 10.0 # Reaching a worse state (updates -> reboot) notifies again after another period. # 0 disables. Needs ntfy_url. status_alert_after_hours = 24.0 + +# Dead-man's switch: an external monitor (e.g. healthchecks.io) that alerts when the +# pings STOP, which is how you learn kernelwatch itself isn't running. Treat these +# URLs like passwords. Empty disables. +heartbeat_url = "" # pinged every five minutes by the alert check +backup_heartbeat_url = "" # pinged after each successful nightly backup -- 2.54.1