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 <noreply@anthropic.com>
This commit is contained in:
patrickandClaude Sonnet 5.5 committed 2026-10-30 11:31:32 -04:00
1 parent e3013921d1
commit 60b8c6bff7
4 files changed
+257 -1

No files matched your search

+22
View File
@@ -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))
+23 -1
View File
@@ -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)
+18
View File
@@ -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:
+194
View File
@@ -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()