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>
This commit is contained in:
1 parent
203c729e14
commit
650806bfce
7 files changed
+346
-6
No files matched your search
@@ -13,7 +13,7 @@ from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
|
||||
from . import db
|
||||
from .config import Config
|
||||
from .status import LEVELS, evaluate
|
||||
from .status import LEVELS, evaluate, livepatch_problem
|
||||
|
||||
|
||||
class DeliveryError(Exception):
|
||||
@@ -99,6 +99,8 @@ def check(cfg: Config) -> int:
|
||||
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()
|
||||
@@ -183,6 +185,57 @@ def _check_status(cfg: Config, conn: sqlite3.Connection) -> int:
|
||||
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.
|
||||
|
||||
|
||||
@@ -57,6 +57,9 @@ class Config:
|
||||
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
|
||||
# Notify when Livepatch has been unhealthy, or a host that used to report it has
|
||||
# stopped, for this long; 0 disables.
|
||||
livepatch_alert_after_hours: float = 6.0
|
||||
|
||||
|
||||
def load(path: str | None = None) -> Config:
|
||||
@@ -108,6 +111,8 @@ def load(path: str | None = None) -> Config:
|
||||
valid = False
|
||||
if not valid:
|
||||
raise SystemExit(f"{path}: {key} must be an HTTP(S) URL without spaces or a fragment")
|
||||
if not math.isfinite(cfg.livepatch_alert_after_hours) or cfg.livepatch_alert_after_hours < 0:
|
||||
raise SystemExit(f"{path}: livepatch_alert_after_hours must be zero or positive and finite")
|
||||
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:
|
||||
|
||||
@@ -42,6 +42,11 @@ CREATE TABLE IF NOT EXISTS status_alerts (
|
||||
since INTEGER NOT NULL,
|
||||
notified_level TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS livepatch_alerts (
|
||||
host TEXT PRIMARY KEY REFERENCES hosts(name) ON DELETE CASCADE,
|
||||
since INTEGER,
|
||||
notified INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
@@ -271,6 +276,27 @@ def clear_status_alert(conn: sqlite3.Connection, host: str) -> None:
|
||||
conn.execute("DELETE FROM status_alerts WHERE host = ?", (host,))
|
||||
|
||||
|
||||
# --- livepatch notifications -------------------------------------------------
|
||||
|
||||
def livepatch_alerts(conn: sqlite3.Connection) -> dict[str, tuple[int | None, bool]]:
|
||||
"""host -> (when its current Livepatch problem began or None, whether it was
|
||||
notified). A host appears once it has reported Livepatch at all, which is how
|
||||
"stopped reporting it" is told apart from "never had it"."""
|
||||
return {r["host"]: (r["since"], bool(r["notified"]))
|
||||
for r in conn.execute("SELECT * FROM livepatch_alerts")}
|
||||
|
||||
|
||||
def save_livepatch_alert(conn: sqlite3.Connection, host: str, since: int | None,
|
||||
notified: bool) -> None:
|
||||
# The host may have been removed while a notification was in flight.
|
||||
conn.execute(
|
||||
"INSERT INTO livepatch_alerts (host, since, notified) "
|
||||
"SELECT name, ?, ? FROM hosts WHERE name = ? "
|
||||
"ON CONFLICT(host) DO UPDATE SET since = excluded.since, notified = excluded.notified",
|
||||
(since, int(notified), host),
|
||||
)
|
||||
|
||||
|
||||
# --- users & sessions -------------------------------------------------------
|
||||
|
||||
def set_user(conn: sqlite3.Connection, name: str, pw_hash: str) -> None:
|
||||
|
||||
@@ -105,6 +105,24 @@ def kernel_reboot_pending(report: dict[str, Any]) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def livepatch_problem(report: dict[str, Any]) -> str | None:
|
||||
"""Why Livepatch isn't working on this host, or None if it is (or isn't in use).
|
||||
|
||||
"Working" means a state we recognise as healthy, a completed check and a
|
||||
supported kernel. The same test decides cover for a pending reboot and whether
|
||||
to send a Livepatch alert."""
|
||||
state = report.get("livepatch_state")
|
||||
if state is None:
|
||||
return None
|
||||
if (state not in LIVEPATCH_HEALTHY_STATES or report.get("livepatch_check_state") != "checked"
|
||||
or report.get("livepatch_supported") != "supported"):
|
||||
parts = [state, report.get("livepatch_supported") or "?"]
|
||||
if report.get("livepatch_check_state") != "checked":
|
||||
parts.append(f"check: {report.get('livepatch_check_state') or '?'}")
|
||||
return f"livepatch not healthy ({', '.join(parts)})"
|
||||
return None
|
||||
|
||||
|
||||
def livepatch_cover(report: dict[str, Any], now: float) -> tuple[bool, str | None]:
|
||||
"""(is the running kernel kept patched by Livepatch, a note about it).
|
||||
|
||||
@@ -112,16 +130,14 @@ def livepatch_cover(report: dict[str, Any], now: float) -> tuple[bool, str | Non
|
||||
support ends, so cover lapses LIVEPATCH_MARGIN_DAYS before that date. Hosts
|
||||
without Livepatch data, or with Livepatch in any state we don't recognise as
|
||||
healthy, get no cover and are judged as before."""
|
||||
state = report.get("livepatch_state")
|
||||
if state is None:
|
||||
if report.get("livepatch_state") is None:
|
||||
return False, None
|
||||
if problem := livepatch_problem(report):
|
||||
return False, problem
|
||||
try:
|
||||
deadline = date.fromisoformat(report.get("livepatch_upgrade_required") or "")
|
||||
except ValueError:
|
||||
deadline = None
|
||||
if (state not in LIVEPATCH_HEALTHY_STATES or report.get("livepatch_check_state") != "checked"
|
||||
or report.get("livepatch_supported") != "supported"):
|
||||
return False, f"livepatch not healthy ({state}, {report.get('livepatch_supported') or '?'})"
|
||||
if deadline is None:
|
||||
return False, "livepatch end of support date unknown"
|
||||
left = (deadline - datetime.fromtimestamp(now, timezone.utc).date()).days
|
||||
|
||||
Reference in new issue
Block a user