Files
patrickandClaude Sonnet 5.5 650806bfce Alert when Livepatch is broken or has stopped reporting
The alert check now also notifies, once per problem, when a host's Livepatch has
been unhealthy for livepatch_alert_after_hours (default 6), or when a host that
used to report Livepatch no longer does (a dead daemon leaves the agent with
nothing to send). A livepatch_alerts table records which hosts have reported
Livepatch, when the current problem began and whether it was notified, so hosts
without Livepatch never alert and restarts do not repeat messages. Stale hosts
are skipped.

livepatch_problem() is now the single test for unhealthy, shared with the cover
rule for pending reboots, and names the check state when that is the problem.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 12:18:39 -04:00

260 lines
12 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, livepatch_problem
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)
if cfg.livepatch_alert_after_hours > 0:
failures += _check_livepatch(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 _check_livepatch(cfg: Config, conn: sqlite3.Connection) -> int:
"""Notify once per episode when Livepatch has been broken for the grace period.
Two cases: Livepatch reports an unhealthy state, or a host that used to report
Livepatch no longer does (its daemon died, or `canonical-livepatch status` fails,
so the agent has nothing to send). A host is only "used to" once it has reported
Livepatch, so hosts without it never alert. Getting healthy again forgets the
problem, so a later one alerts again. Stale hosts are skipped: their data can't
be trusted and the stale alert covers them."""
saved = db.livepatch_alerts(conn)
grace = cfg.livepatch_alert_after_hours * 3600
failures = 0
for h in db.latest_reports(conn):
name, report, now = h["host"], h["report"], time.time()
if evaluate(h["received_at"], report, now, cfg).level == "stale":
continue
state = report.get("livepatch_state")
if state is None and name not in saved:
continue
problem = (livepatch_problem(report) if state is not None
else "livepatch status is no longer being reported")
since, notified = saved.get(name, (None, False))
if problem is None:
current = (None, False)
else:
since = int(now) if since is None else since
current = (since, notified)
if not notified and now - since >= grace:
title = f"kernelwatch: {name} Livepatch problem"
if state is None:
detail = ("It reported Livepatch before and no longer does, so the Livepatch "
"daemon may have stopped or been disabled.")
else:
detail = (f"State: {state}, check: {report.get('livepatch_check_state') or '?'}, "
f"supported: {report.get('livepatch_supported') or '?'}.")
message = (f"{name}: {problem} since {_utc(since)}.\n{detail}\n"
"The running kernel may be missing live patches. On the host, check "
"`canonical-livepatch status` and `systemctl status kernelwatch-livepatch`.")
try:
publish(cfg, title, message, stale=True, tag="shield")
except DeliveryError as exc:
print(f"kernelwatch: notification failed for {name}: {exc}", file=sys.stderr)
failures += 1
else:
current = (since, True)
print(f"kernelwatch: livepatch notification sent for {name}")
if saved.get(name) != current:
db.save_livepatch_alert(conn, name, *current)
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