Files
kernel-automation/server/kernelwatch/alerts.py
T
patrickandClaude Sonnet 5.5 60b8c6bff7 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>
2026-10-30 11:31:32 -04:00

207 lines
8.8 KiB
Python

"""Periodic stale/recovery notifications, independent of report ingestion."""
from __future__ import annotations
import fcntl
import socket
import sqlite3
import sys
import time
from http.client import HTTPException
from urllib.error import HTTPError, URLError
from urllib.request import HTTPRedirectHandler, Request, build_opener
from . import db
from .config import Config
from .status import LEVELS, evaluate
class DeliveryError(Exception):
"""A safe-to-log delivery failure (never includes a URL or access token)."""
class _NoRedirect(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
# A login redirect is not a successful publish. Never forward credentials.
return None
def publish(cfg: Config, title: str, message: str, *, stale: bool = False,
tag: str | None = None) -> None:
if not cfg.ntfy_url:
raise DeliveryError("ntfy_url is not configured")
headers = {
"Content-Type": "text/plain; charset=utf-8",
"Title": title,
"Tags": tag or ("warning" if stale else "white_check_mark"),
"Priority": "high" if stale else "default",
}
if cfg.ntfy_token:
headers["Authorization"] = f"Bearer {cfg.ntfy_token}"
try:
request = Request(cfg.ntfy_url.rstrip("/"), data=message.encode(), headers=headers,
method="POST")
with build_opener(_NoRedirect()).open(request, timeout=cfg.ntfy_timeout_seconds) as response:
if response.status != 200:
raise DeliveryError(f"ntfy returned HTTP {response.status}; expected 200")
except HTTPError as exc:
code = exc.code
exc.close()
raise DeliveryError(f"ntfy returned HTTP {code}; expected 200") from None
except (URLError, OSError, ValueError, HTTPException) as exc:
# Exception text can contain the private topic URL. Log only its type.
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))
def check(cfg: Config) -> int:
"""Send transitions and return the number of failed deliveries.
Only successful notifications change the saved state. A process lock avoids
duplicates from overlapping timer/manual runs without holding a SQLite write
transaction during network I/O, so host reports can still be ingested.
"""
if not cfg.ntfy_url:
return 0
db.init(cfg.db_path)
with open(cfg.db_path + ".alerts.lock", "a") as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return 0
conn = db.connect(cfg.db_path)
try:
failures = _check_hosts(cfg, conn)
if cfg.status_alert_after_hours > 0:
failures += _check_status(cfg, conn)
return failures
finally:
conn.close()
def _check_hosts(cfg: Config, conn: sqlite3.Connection) -> int:
active = db.stale_alerts(conn)
failures = 0
for host in db.list_hosts(conn):
name, last_seen = host["name"], host["last_seen"]
now = time.time()
baseline = host["created_at"] if last_seen is None else last_seen
stale = now - baseline > cfg.stale_after_hours * 3600
if stale and name not in active:
detail = (f"Last report received at {_utc(last_seen)}." if last_seen is not None else
f"No reports received since registration at {_utc(baseline)}.")
title = f"kernelwatch: {name} is stale"
message = (f"{name} has stopped reporting. {detail}\n"
f"Stale threshold: {cfg.stale_after_hours:g} hours. "
"Check the host and kernelwatch-agent.timer.")
elif (not stale and name in active and last_seen is not None
and (active[name] is None or last_seen > active[name])):
title = f"kernelwatch: {name} reporting recovered"
message = (f"{name} is reporting again. Latest report received at {_utc(last_seen)}.\n"
"This confirms reporting has resumed; kernel or package updates may still be pending.")
else:
continue
try:
publish(cfg, title, message, stale=stale)
except DeliveryError as exc:
print(f"kernelwatch: notification failed for {name}: {exc}", file=sys.stderr)
failures += 1
continue
if stale:
db.record_stale_alert(conn, name, last_seen)
else:
db.clear_stale_alert(conn, name)
print(f"kernelwatch: {'stale' if stale else 'recovery'} notification sent for {name}")
return failures
def _check_status(cfg: Config, conn: sqlite3.Connection) -> int:
"""Notify once when a host has needed a reboot or updates for the grace period.
`since` is when the host entered its current level, so it measures how long the
need has gone unmet rather than how recently the host reported. Returning to ok
forgets the host; reaching a worse level (update -> reboot) notifies again after
another grace period. Stale hosts are left alone: the stale alert covers them
and their data can't be trusted."""
saved = db.status_alerts(conn)
grace = cfg.status_alert_after_hours * 3600
failures = 0
for h in db.latest_reports(conn):
name, now = h["host"], time.time()
status = evaluate(h["received_at"], h["report"], now, cfg)
if status.level == "stale":
continue
if status.level == "ok":
if name in saved:
db.clear_status_alert(conn, name)
continue
level, since, notified = saved.get(name, (status.level, int(now), None))
if level != status.level:
level, since = status.level, int(now)
worse = notified is None or LEVELS.index(level) < LEVELS.index(notified)
if now - since < grace or not worse:
db.save_status_alert(conn, name, level, since, notified)
continue
needs = "a reboot" if level == "reboot" else "updates"
title = f"kernelwatch: {name} needs {needs}"
message = (f"{name} has needed {needs} since {_utc(since)}.\n"
+ "\n".join(f"- {r}" for r in status.reasons))
try:
publish(cfg, title, message, tag="arrows_counterclockwise" if level == "reboot" else "package")
except DeliveryError as exc:
print(f"kernelwatch: notification failed for {name}: {exc}", file=sys.stderr)
failures += 1
db.save_status_alert(conn, name, level, since, notified)
continue
db.save_status_alert(conn, name, level, since, level)
print(f"kernelwatch: {level} notification sent for {name}")
return failures
def notify_backup_failure(cfg: Config) -> int:
"""Tell the ntfy topic the nightly backup failed. Returns 1 if that couldn't be sent.
Run by systemd (OnFailure= on kernelwatch-backup.service), so it also covers
failures the backup command can't report itself: a timeout, an out-of-memory
kill, a crash. The cause is in `journalctl -u kernelwatch-backup`."""
if not cfg.ntfy_url:
print("kernelwatch: backup failed, but ntfy_url is not configured; no notification sent",
file=sys.stderr)
return 0
latest = db.latest_backup(cfg.backup_dir)
message = (f"The nightly kernelwatch database backup on {socket.gethostname()} failed.\n"
f"Newest backup still on disk: {latest or 'none'}.\n"
"Cause: journalctl -u kernelwatch-backup")
try:
publish(cfg, "kernelwatch: nightly backup failed", message, stale=True, tag="floppy_disk")
except DeliveryError as exc:
print(f"kernelwatch: backup failure notification failed: {exc}", file=sys.stderr)
return 1
print("kernelwatch: backup failure notification sent")
return 0