diff --git a/server/kernelwatch/alerts.py b/server/kernelwatch/alerts.py index 4c5f860..653e6fe 100644 --- a/server/kernelwatch/alerts.py +++ b/server/kernelwatch/alerts.py @@ -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. diff --git a/server/kernelwatch/config.py b/server/kernelwatch/config.py index 97a313b..3636e99 100644 --- a/server/kernelwatch/config.py +++ b/server/kernelwatch/config.py @@ -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: diff --git a/server/kernelwatch/db.py b/server/kernelwatch/db.py index 6f5ff2f..6d8a154 100644 --- a/server/kernelwatch/db.py +++ b/server/kernelwatch/db.py @@ -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: diff --git a/server/kernelwatch/status.py b/server/kernelwatch/status.py index b31a887..14441fc 100644 --- a/server/kernelwatch/status.py +++ b/server/kernelwatch/status.py @@ -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 diff --git a/tests/test_alerts.py b/tests/test_alerts.py index fd08ccf..194cf66 100644 --- a/tests/test_alerts.py +++ b/tests/test_alerts.py @@ -391,6 +391,216 @@ class BackupFailureAlertTest(unittest.TestCase): self.assertEqual(self.publish.call_count, 1) +class LivepatchAlertsTest(unittest.TestCase): + """Notify when Livepatch is unhealthy, or stops being reported, for too long.""" + + HEALTHY = {"livepatch_state": "applied", "livepatch_check_state": "checked", + "livepatch_supported": "supported", "livepatch_upgrade_required": "2099-01-01", + "livepatch_fix_count": 2} + + def setUp(self): + self.tmp = tempdir() + self.addCleanup(self.tmp.cleanup) + self.cfg = temp_config(self.tmp.name, ntfy_url="https://ntfy.example.test/fleet", + status_alert_after_hours=0, livepatch_alert_after_hours=6.0) + db.init(self.cfg.db_path) + self.conn = db.connect(self.cfg.db_path) + self.addCleanup(self.conn.close) + self.now = NOW + clock = mock.patch("kernelwatch.alerts.time.time", side_effect=lambda: self.now) + clock.start() + self.addCleanup(clock.stop) + publisher = mock.patch("kernelwatch.alerts.publish") + self.publish = publisher.start() + self.addCleanup(publisher.stop) + stack = contextlib.ExitStack() + self.addCleanup(stack.close) + stack.enter_context(contextlib.redirect_stdout(io.StringIO())) + self.errors = stack.enter_context(contextlib.redirect_stderr(io.StringIO())) + db.add_host(self.conn, "web01", auth.token_hash(auth.new_token())) + + def report(self, host="web01", livepatch=True, **fields): + payload = {"kernel_running": "6.8.0-136-generic", "apt_lists_age_seconds": 60} + if livepatch: + payload.update(self.HEALTHY) + payload.update(fields) + self.conn.execute("INSERT INTO reports (host, received_at, payload) VALUES (?, ?, ?)", + (host, self.now, json.dumps(payload))) + + def hours(self, n): + self.now += int(n * 3600) + + def run_check(self): + self.assertEqual(alerts.check(self.cfg), 0) + + def titles(self): + return [c.args[1] for c in self.publish.call_args_list] + + def test_unhealthy_state_alerts_once_after_the_grace_period(self): + self.report(livepatch_state="apply-failed") + self.run_check() + self.hours(5) + self.report(livepatch_state="apply-failed") + self.run_check() + self.publish.assert_not_called() + self.hours(1.1) + self.report(livepatch_state="apply-failed") + self.run_check() + self.assertEqual(self.titles(), ["kernelwatch: web01 Livepatch problem"]) + (_, _, message), kwargs = self.publish.call_args + self.assertIn("livepatch not healthy (apply-failed, supported)", message) + self.assertIn("State: apply-failed, check: checked, supported: supported.", message) + self.assertIn("canonical-livepatch status", message) + self.assertTrue(kwargs["stale"]) # high priority + for _ in range(5): # never repeated while the same episode lasts + self.hours(1) + self.report(livepatch_state="apply-failed") + self.run_check() + self.assertEqual(self.publish.call_count, 1) + + def test_each_kind_of_unhealthy_counts(self): + for fields in ({"livepatch_state": "applying"}, {"livepatch_check_state": "check-failed"}, + {"livepatch_supported": "unsupported"}, {"livepatch_state": "kernel-upgrade-required"}): + with self.subTest(fields=fields): + self.publish.reset_mock() + db.remove_host(self.conn, "web01") + db.add_host(self.conn, "web01", auth.token_hash(auth.new_token())) + self.report(**fields) + self.run_check() + self.hours(7) + self.report(**fields) + self.run_check() + self.assertEqual(self.publish.call_count, 1) + + def test_healthy_states_never_alert(self): + for state in ("applied", "nothing-to-apply"): + self.report(livepatch_state=state) + self.run_check() + self.hours(48) + self.report(livepatch_state=state) + self.run_check() + self.publish.assert_not_called() + + def test_a_brief_problem_that_clears_never_alerts_and_resets_the_clock(self): + self.report(livepatch_check_state="check-failed") + self.run_check() + self.hours(5) + self.report() + self.run_check() + self.assertEqual(db.livepatch_alerts(self.conn)["web01"], (None, False)) + self.hours(5) # a new problem starts a fresh grace period, not the old one + self.report(livepatch_check_state="check-failed") + self.run_check() + self.hours(5) + self.report(livepatch_check_state="check-failed") + self.run_check() + self.publish.assert_not_called() + + def test_a_later_problem_alerts_again(self): + self.report(livepatch_state="apply-failed") + self.run_check() + self.hours(7) + self.report(livepatch_state="apply-failed") + self.run_check() + self.report() + self.run_check() + self.hours(1) + self.report(livepatch_state="apply-failed") + self.run_check() + self.hours(7) + self.report(livepatch_state="apply-failed") + self.run_check() + self.assertEqual(self.publish.call_count, 2) + + def test_a_host_that_stops_reporting_livepatch_alerts(self): + self.report() # healthy: now known to use Livepatch + self.run_check() + self.assertIn("web01", db.livepatch_alerts(self.conn)) + self.hours(1) + self.report(livepatch=False) # the daemon died; the agent has nothing to send + self.run_check() + self.hours(5) + self.report(livepatch=False) + self.run_check() + self.publish.assert_not_called() + self.hours(1.1) + self.report(livepatch=False) + self.run_check() + self.assertEqual(self.publish.call_count, 1) + message = self.publish.call_args.args[2] + self.assertIn("no longer being reported", message) + self.assertIn("It reported Livepatch before and no longer does", message) + + def test_a_blip_of_missing_data_between_good_reports_is_forgiven(self): + self.report() + self.run_check() + self.hours(1) + self.report(livepatch=False) # e.g. snapd was restarting for one report + self.run_check() + self.hours(1) + self.report() + self.run_check() + self.hours(8) + self.report() + self.run_check() + self.publish.assert_not_called() + + def test_hosts_that_never_had_livepatch_never_alert(self): + for _ in range(4): + self.report(livepatch=False) + self.run_check() + self.hours(24) + self.publish.assert_not_called() + self.assertEqual(db.livepatch_alerts(self.conn), {}) + + def test_stale_hosts_are_skipped(self): + self.report(livepatch_state="apply-failed") + self.run_check() + self.hours(20) # no reports since: stale, so only the stale alert speaks + self.run_check() + self.assertEqual(self.titles(), ["kernelwatch: web01 is stale"]) + + def test_failed_delivery_is_retried_until_it_succeeds(self): + self.report(livepatch_state="apply-failed") + self.run_check() + self.hours(7) + self.report(livepatch_state="apply-failed") + self.publish.side_effect = alerts.DeliveryError("ntfy returned HTTP 503") + self.assertEqual(alerts.check(self.cfg), 1) + self.assertEqual(db.livepatch_alerts(self.conn)["web01"][1], False) + self.assertIn("notification failed for web01", self.errors.getvalue()) + self.publish.side_effect = None + self.run_check() + self.assertEqual(db.livepatch_alerts(self.conn)["web01"][1], True) + self.run_check() + self.assertEqual(self.publish.call_count, 2) # the failed try and the one that landed + + def test_zero_disables_it(self): + cfg = dataclasses.replace(self.cfg, livepatch_alert_after_hours=0) + self.report(livepatch_state="apply-failed") + self.assertEqual(alerts.check(cfg), 0) + self.hours(100) + self.report(livepatch_state="apply-failed") + self.assertEqual(alerts.check(cfg), 0) + self.publish.assert_not_called() + self.assertEqual(db.livepatch_alerts(self.conn), {}) + + def test_removing_a_host_forgets_it(self): + self.report() + self.run_check() + db.remove_host(self.conn, "web01") + self.assertEqual(db.livepatch_alerts(self.conn), {}) + + def test_state_is_only_written_when_it_changes(self): + self.report() + self.run_check() + with mock.patch("kernelwatch.alerts.db.save_livepatch_alert") as save: + self.hours(1) + self.report() + self.run_check() + save.assert_not_called() + + class NtfyHTTPTest(unittest.TestCase): def setUp(self): class Sink(BaseHTTPRequestHandler): diff --git a/tests/test_report_auth_config.py b/tests/test_report_auth_config.py index 090ff2b..816b598 100644 --- a/tests/test_report_auth_config.py +++ b/tests/test_report_auth_config.py @@ -75,6 +75,15 @@ class ConfigTest(unittest.TestCase): with self.subTest(bad=bad), self.assertRaises(SystemExit): config.load(self.write(tmp, f"report_min_interval_seconds = {bad}\n")) + def test_livepatch_alert_hours_validated(self): + with tempdir() as tmp: + self.assertEqual(config.Config().livepatch_alert_after_hours, 6.0) + self.assertEqual(config.load(self.write(tmp, "livepatch_alert_after_hours = 0\n")) + .livepatch_alert_after_hours, 0) + for bad in ("-1", "inf", "nan", '"6"'): + with self.subTest(bad=bad), self.assertRaises(SystemExit): + config.load(self.write(tmp, f"livepatch_alert_after_hours = {bad}\n")) + def test_status_alert_hours_validated(self): with tempdir() as tmp: self.assertEqual(config.load(self.write(tmp, "status_alert_after_hours = 0\n")) diff --git a/tests/test_status.py b/tests/test_status.py index 9305341..5c3ebcc 100644 --- a/tests/test_status.py +++ b/tests/test_status.py @@ -37,6 +37,27 @@ def livepatched(days_left=300, **kw): return report(**fields) +class LivepatchProblemTest(unittest.TestCase): + def test_none_when_healthy_or_not_in_use(self): + from kernelwatch.status import livepatch_problem + self.assertIsNone(livepatch_problem(report())) + self.assertIsNone(livepatch_problem(livepatched())) + self.assertIsNone(livepatch_problem(livepatched(livepatch_state="nothing-to-apply"))) + + def test_describes_each_unhealthy_case(self): + from kernelwatch.status import livepatch_problem + self.assertEqual(livepatch_problem(livepatched(livepatch_state="apply-failed")), + "livepatch not healthy (apply-failed, supported)") + self.assertEqual(livepatch_problem(livepatched(livepatch_check_state="check-failed")), + "livepatch not healthy (applied, supported, check: check-failed)") + self.assertEqual(livepatch_problem(livepatched(livepatch_check_state=None)), + "livepatch not healthy (applied, supported, check: ?)") + self.assertEqual(livepatch_problem(livepatched(livepatch_supported="unsupported")), + "livepatch not healthy (applied, unsupported)") + self.assertEqual(livepatch_problem(livepatched(livepatch_supported=None)), + "livepatch not healthy (applied, ?)") + + class LivepatchTest(unittest.TestCase): def evaluate(self, rep): return evaluate(NOW - 60, rep, NOW, CFG)