"""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 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