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: