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>
737 lines
33 KiB
Python
737 lines
33 KiB
Python
"""Stale/recovery transitions, durable deduplication, and real ntfy HTTP requests."""
|
|
|
|
import contextlib
|
|
import dataclasses
|
|
import io
|
|
import json
|
|
import os
|
|
import threading
|
|
import unittest
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from unittest import mock
|
|
from urllib.error import URLError
|
|
|
|
from helpers import temp_config, tempdir
|
|
from kernelwatch import alerts, auth, cli, config, db
|
|
|
|
NOW = 1_800_000_000
|
|
|
|
|
|
class AlertTransitionsTest(unittest.TestCase):
|
|
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")
|
|
db.init(self.cfg.db_path)
|
|
self.conn = db.connect(self.cfg.db_path)
|
|
self.addCleanup(self.conn.close)
|
|
clock = mock.patch("kernelwatch.alerts.time.time", return_value=NOW)
|
|
self.clock = 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)
|
|
self.output = stack.enter_context(contextlib.redirect_stdout(io.StringIO()))
|
|
self.errors = stack.enter_context(contextlib.redirect_stderr(io.StringIO()))
|
|
|
|
def host(self, name="web01", *, registered_age=86400, report_age=None):
|
|
db.add_host(self.conn, name, auth.token_hash(auth.new_token()))
|
|
self.conn.execute("UPDATE hosts SET created_at = ? WHERE name = ?",
|
|
(NOW - registered_age, name))
|
|
if report_age is not None:
|
|
self.report(name, report_age)
|
|
|
|
def report(self, name="web01", age=0):
|
|
# A host needing a reboot still counts as recovered when it reports again.
|
|
self.conn.execute("INSERT INTO reports (host, received_at, payload) VALUES (?, ?, ?)",
|
|
(name, NOW - age, json.dumps({"kernel_running": "x", "reboot_required": True})))
|
|
|
|
def test_hourly_reports_and_jitter_do_not_alert(self):
|
|
self.host(report_age=75 * 60)
|
|
self.assertEqual(alerts.check(self.cfg), 0)
|
|
self.publish.assert_not_called()
|
|
self.assertEqual(db.stale_alerts(self.conn), {})
|
|
|
|
def test_stale_boundary_matches_dashboard_and_survives_restart(self):
|
|
self.host(report_age=3 * 3600)
|
|
self.assertEqual(alerts.check(self.cfg), 0)
|
|
self.publish.assert_not_called()
|
|
self.clock.return_value = NOW + 1
|
|
self.assertEqual(alerts.check(self.cfg), 0)
|
|
self.assertIn("web01 is stale", self.publish.call_args.args[1])
|
|
self.assertIn("Last report received", self.publish.call_args.args[2])
|
|
self.assertTrue(self.publish.call_args.kwargs["stale"])
|
|
self.assertEqual(db.stale_alerts(self.conn), {"web01": NOW - 3 * 3600})
|
|
# Each run opens new connections, as a fresh timer process would.
|
|
self.clock.return_value = NOW + 86400
|
|
self.assertEqual(alerts.check(self.cfg), 0)
|
|
self.assertEqual(self.publish.call_count, 1)
|
|
|
|
def test_registration_grace_and_first_report_recovery(self):
|
|
self.host(registered_age=3600)
|
|
self.assertEqual(alerts.check(self.cfg), 0)
|
|
self.publish.assert_not_called()
|
|
self.clock.return_value = NOW + 7201
|
|
self.assertEqual(alerts.check(self.cfg), 0)
|
|
self.assertIn("No reports received since registration", self.publish.call_args.args[2])
|
|
self.report(age=-7201)
|
|
self.assertEqual(alerts.check(self.cfg), 0)
|
|
self.assertIn("reporting recovered", self.publish.call_args.args[1])
|
|
|
|
def test_one_recovery_and_rearms_for_next_outage(self):
|
|
self.host(report_age=10801)
|
|
alerts.check(self.cfg)
|
|
self.report()
|
|
alerts.check(self.cfg)
|
|
self.assertIn("web01 reporting recovered", self.publish.call_args.args[1])
|
|
self.assertIn("updates may still be pending", self.publish.call_args.args[2])
|
|
self.assertFalse(self.publish.call_args.kwargs["stale"])
|
|
self.assertEqual(db.stale_alerts(self.conn), {})
|
|
alerts.check(self.cfg)
|
|
self.assertEqual(self.publish.call_count, 2)
|
|
self.clock.return_value = NOW + 10801
|
|
alerts.check(self.cfg)
|
|
self.assertEqual(self.publish.call_count, 3)
|
|
self.assertTrue(self.publish.call_args.kwargs["stale"])
|
|
|
|
def test_healthy_host_has_no_initial_recovery(self):
|
|
self.host(report_age=1)
|
|
alerts.check(self.cfg)
|
|
self.publish.assert_not_called()
|
|
|
|
def test_recovery_in_same_second_as_stale_threshold(self):
|
|
self.clock.return_value = NOW + 0.5
|
|
for last_report in (None, 10800):
|
|
with self.subTest(last_report=last_report):
|
|
db.remove_host(self.conn, "web01")
|
|
self.host(registered_age=10800, report_age=last_report)
|
|
alerts.check(self.cfg)
|
|
self.publish.reset_mock()
|
|
self.report()
|
|
alerts.check(self.cfg)
|
|
self.assertEqual(self.publish.call_count, 1)
|
|
self.assertIn("reporting recovered", self.publish.call_args.args[1])
|
|
self.assertEqual(db.stale_alerts(self.conn), {})
|
|
|
|
def test_stale_failure_retried_and_other_hosts_checked(self):
|
|
self.host("a", report_age=10801)
|
|
self.host("b", report_age=10801)
|
|
self.publish.side_effect = [alerts.DeliveryError("ntfy returned HTTP 503"), None]
|
|
self.assertEqual(alerts.check(self.cfg), 1)
|
|
self.assertEqual(set(db.stale_alerts(self.conn)), {"b"})
|
|
self.assertIn("notification failed for a", self.errors.getvalue())
|
|
self.publish.side_effect = None
|
|
self.assertEqual(alerts.check(self.cfg), 0)
|
|
self.assertEqual(set(db.stale_alerts(self.conn)), {"a", "b"})
|
|
self.assertEqual(self.publish.call_count, 3)
|
|
|
|
def test_no_recovery_when_stale_was_not_delivered(self):
|
|
self.host(report_age=10801)
|
|
self.publish.side_effect = alerts.DeliveryError("offline")
|
|
self.assertEqual(alerts.check(self.cfg), 1)
|
|
self.report()
|
|
self.publish.side_effect = None
|
|
alerts.check(self.cfg)
|
|
self.assertEqual(self.publish.call_count, 1)
|
|
|
|
def test_recovery_failure_retried_without_repeating_stale(self):
|
|
self.host(report_age=10801)
|
|
alerts.check(self.cfg)
|
|
self.report()
|
|
self.publish.side_effect = alerts.DeliveryError("offline")
|
|
self.assertEqual(alerts.check(self.cfg), 1)
|
|
self.assertIn("web01", db.stale_alerts(self.conn))
|
|
self.publish.side_effect = None
|
|
self.assertEqual(alerts.check(self.cfg), 0)
|
|
self.assertEqual(db.stale_alerts(self.conn), {})
|
|
self.assertIn("reporting recovered", self.publish.call_args.args[1])
|
|
|
|
def test_changing_threshold_does_not_invent_recovery(self):
|
|
for last_report in (None, 10801):
|
|
with self.subTest(last_report=last_report):
|
|
db.remove_host(self.conn, "web01")
|
|
self.host(registered_age=10801, report_age=last_report)
|
|
alerts.check(self.cfg)
|
|
self.publish.reset_mock()
|
|
alerts.check(dataclasses.replace(self.cfg, stale_after_hours=6.0))
|
|
self.publish.assert_not_called()
|
|
self.assertIn("web01", db.stale_alerts(self.conn))
|
|
|
|
def test_removed_host_clears_state(self):
|
|
self.host(report_age=10801)
|
|
alerts.check(self.cfg)
|
|
db.remove_host(self.conn, "web01")
|
|
self.assertEqual(db.stale_alerts(self.conn), {})
|
|
self.host(report_age=1)
|
|
alerts.check(self.cfg)
|
|
self.assertEqual(self.publish.call_count, 1)
|
|
|
|
def test_upgrade_adds_alert_state_without_changing_existing_data(self):
|
|
self.host(report_age=3600)
|
|
self.conn.execute("DROP TABLE stale_alerts")
|
|
db.init(self.cfg.db_path)
|
|
self.assertEqual(db.stale_alerts(self.conn), {})
|
|
host = db.list_hosts(self.conn)[0]
|
|
self.assertEqual(host["name"], "web01")
|
|
self.assertEqual(host["last_seen"], NOW - 3600)
|
|
|
|
def test_report_ingestion_continues_during_delivery_and_runs_do_not_overlap(self):
|
|
self.host(report_age=10801)
|
|
|
|
def during_delivery(*args, **kwargs):
|
|
conn = db.connect(self.cfg.db_path)
|
|
try:
|
|
db.add_report(conn, "web01", {"kernel_running": "x"}, 30)
|
|
finally:
|
|
conn.close()
|
|
self.assertEqual(alerts.check(self.cfg), 0)
|
|
|
|
self.publish.side_effect = during_delivery
|
|
self.assertEqual(alerts.check(self.cfg), 0)
|
|
self.assertEqual(self.publish.call_count, 1)
|
|
|
|
def test_removal_during_delivery_does_not_restore_host(self):
|
|
self.host(report_age=10801)
|
|
self.publish.side_effect = lambda *a, **kw: db.remove_host(self.conn, "web01")
|
|
self.assertEqual(alerts.check(self.cfg), 0)
|
|
self.assertEqual(db.stale_alerts(self.conn), {})
|
|
|
|
def test_disabled_does_not_create_database_or_send(self):
|
|
cfg = dataclasses.replace(self.cfg, ntfy_url="", db_path=os.path.join(self.tmp.name, "unused.db"))
|
|
self.assertEqual(alerts.check(cfg), 0)
|
|
self.assertFalse(os.path.exists(cfg.db_path))
|
|
self.publish.assert_not_called()
|
|
|
|
|
|
class StatusAlertsTest(unittest.TestCase):
|
|
"""Reboot/update notifications after a host has needed them for the grace period."""
|
|
|
|
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=24.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, **fields):
|
|
# apt_lists_age_seconds keeps a clean report ok rather than "list age unknown".
|
|
payload = {"kernel_running": "6.1.0-1", "apt_lists_age_seconds": 60, **fields}
|
|
self.conn.execute("INSERT INTO reports (host, received_at, payload) VALUES (?, ?, ?)",
|
|
("web01", self.now, json.dumps(payload)))
|
|
|
|
def advance(self, hours):
|
|
self.now += int(hours * 3600)
|
|
|
|
def run_check(self):
|
|
self.assertEqual(alerts.check(self.cfg), 0)
|
|
|
|
def test_notifies_once_after_grace_period(self):
|
|
self.report(reboot_required=True)
|
|
self.run_check()
|
|
self.advance(23)
|
|
self.report(reboot_required=True)
|
|
self.run_check()
|
|
self.publish.assert_not_called()
|
|
self.advance(1.1)
|
|
self.report(reboot_required=True)
|
|
self.run_check()
|
|
self.assertEqual(self.publish.call_count, 1)
|
|
self.assertEqual(self.publish.call_args.args[1], "kernelwatch: web01 needs a reboot")
|
|
self.assertIn("/run/reboot-required", self.publish.call_args.args[2])
|
|
self.advance(48)
|
|
self.report(reboot_required=True)
|
|
self.run_check()
|
|
self.assertEqual(self.publish.call_count, 1)
|
|
|
|
def test_clock_runs_from_entering_the_level_not_the_last_report(self):
|
|
self.report(security_count=2)
|
|
self.run_check()
|
|
for _ in range(30): # hourly reports must not restart the grace period
|
|
self.advance(1)
|
|
self.report(security_count=2)
|
|
self.run_check()
|
|
self.assertEqual(self.publish.call_count, 1)
|
|
self.assertEqual(self.publish.call_args.args[1], "kernelwatch: web01 needs updates")
|
|
|
|
def test_fixed_host_is_forgotten_and_rearms(self):
|
|
self.report(reboot_required=True)
|
|
self.run_check()
|
|
self.advance(25)
|
|
self.report(reboot_required=True)
|
|
self.run_check()
|
|
self.assertEqual(self.publish.call_count, 1)
|
|
self.report()
|
|
self.run_check()
|
|
self.assertEqual(db.status_alerts(self.conn), {})
|
|
self.advance(1)
|
|
self.report(reboot_required=True)
|
|
self.run_check()
|
|
self.advance(25)
|
|
self.report(reboot_required=True)
|
|
self.run_check()
|
|
self.assertEqual(self.publish.call_count, 2)
|
|
|
|
def test_escalation_notifies_again_but_downgrade_does_not(self):
|
|
self.report(security_count=1)
|
|
self.run_check()
|
|
self.advance(25)
|
|
self.report(security_count=1)
|
|
self.run_check()
|
|
self.assertEqual(self.publish.call_count, 1)
|
|
self.report(security_count=1, reboot_required=True)
|
|
self.run_check()
|
|
self.assertEqual(self.publish.call_count, 1)
|
|
self.advance(25)
|
|
self.report(security_count=1, reboot_required=True)
|
|
self.run_check()
|
|
self.assertEqual(self.publish.call_count, 2)
|
|
self.assertIn("needs a reboot", self.publish.call_args.args[1])
|
|
self.report(security_count=1)
|
|
self.run_check()
|
|
self.advance(25)
|
|
self.report(security_count=1)
|
|
self.run_check()
|
|
self.assertEqual(self.publish.call_count, 2)
|
|
|
|
def test_stale_host_is_skipped_and_keeps_its_clock(self):
|
|
self.report(reboot_required=True)
|
|
self.run_check()
|
|
self.advance(13)
|
|
self.run_check() # stale (3h), so the stale alert fires, not this one
|
|
self.assertEqual([c.args[1] for c in self.publish.call_args_list],
|
|
["kernelwatch: web01 is stale"])
|
|
self.assertEqual(db.status_alerts(self.conn)["web01"][1], NOW)
|
|
|
|
def test_failed_delivery_is_retried(self):
|
|
self.report(reboot_required=True)
|
|
self.run_check()
|
|
self.advance(25)
|
|
self.report(reboot_required=True)
|
|
self.publish.side_effect = alerts.DeliveryError("offline")
|
|
self.assertEqual(alerts.check(self.cfg), 1)
|
|
self.assertEqual(db.status_alerts(self.conn)["web01"][2], None)
|
|
self.publish.side_effect = None
|
|
self.run_check()
|
|
self.assertEqual(db.status_alerts(self.conn)["web01"][2], "reboot")
|
|
|
|
def test_zero_disables(self):
|
|
cfg = dataclasses.replace(self.cfg, status_alert_after_hours=0)
|
|
self.report(reboot_required=True)
|
|
self.assertEqual(alerts.check(cfg), 0)
|
|
self.advance(100)
|
|
self.report(reboot_required=True)
|
|
self.assertEqual(alerts.check(cfg), 0)
|
|
self.publish.assert_not_called()
|
|
self.assertEqual(db.status_alerts(self.conn), {})
|
|
|
|
|
|
class BackupFailureAlertTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempdir()
|
|
self.addCleanup(self.tmp.cleanup)
|
|
self.dir = os.path.join(self.tmp.name, "backups")
|
|
self.cfg = temp_config(self.tmp.name, ntfy_url="https://ntfy.example.test/fleet",
|
|
backup_dir=self.dir)
|
|
stack = contextlib.ExitStack()
|
|
self.addCleanup(stack.close)
|
|
self.publish = stack.enter_context(mock.patch("kernelwatch.alerts.publish"))
|
|
self.output = stack.enter_context(contextlib.redirect_stdout(io.StringIO()))
|
|
self.errors = stack.enter_context(contextlib.redirect_stderr(io.StringIO()))
|
|
|
|
def touch(self, *names):
|
|
os.makedirs(self.dir, exist_ok=True)
|
|
for name in names:
|
|
open(os.path.join(self.dir, name), "w").close()
|
|
|
|
def test_sends_an_urgent_notification_naming_the_newest_backup(self):
|
|
self.touch("kernelwatch-2026-11-18.db", "kernelwatch-2026-11-19.db", "kernelwatch-2026-11-20.db.tmp-4")
|
|
self.assertEqual(alerts.notify_backup_failure(self.cfg), 0)
|
|
(cfg, title, message), kwargs = self.publish.call_args
|
|
self.assertEqual(title, "kernelwatch: nightly backup failed")
|
|
self.assertIn("Newest backup still on disk: kernelwatch-2026-11-19.db.", message)
|
|
self.assertIn("journalctl -u kernelwatch-backup", message)
|
|
self.assertTrue(kwargs["stale"]) # high priority
|
|
|
|
def test_says_when_there_is_no_backup_at_all(self):
|
|
self.assertEqual(alerts.notify_backup_failure(self.cfg), 0)
|
|
self.assertIn("Newest backup still on disk: none.", self.publish.call_args.args[2])
|
|
|
|
def test_delivery_failure_is_reported_and_fails_the_unit(self):
|
|
self.publish.side_effect = alerts.DeliveryError("ntfy returned HTTP 503")
|
|
self.assertEqual(alerts.notify_backup_failure(self.cfg), 1)
|
|
self.assertIn("ntfy returned HTTP 503", self.errors.getvalue())
|
|
|
|
def test_without_ntfy_it_says_so_and_does_not_fail(self):
|
|
cfg = dataclasses.replace(self.cfg, ntfy_url="")
|
|
self.assertEqual(alerts.notify_backup_failure(cfg), 0)
|
|
self.publish.assert_not_called()
|
|
self.assertIn("ntfy_url is not configured", self.errors.getvalue())
|
|
|
|
def test_cli_command(self):
|
|
path = os.path.join(self.tmp.name, "server.toml")
|
|
with open(path, "w") as f:
|
|
f.write(f'ntfy_url = "https://ntfy.example.test/fleet"\nbackup_dir = "{self.dir}"\n')
|
|
self.assertEqual(cli.main(["-c", path, "notify-backup-failure"]), 0)
|
|
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):
|
|
def do_POST(self):
|
|
self.server.messages.append((self.path, dict(self.headers),
|
|
self.rfile.read(int(self.headers["Content-Length"]))))
|
|
self.send_response(self.server.response_code)
|
|
if self.server.response_code == 302:
|
|
self.send_header("Location", "/redirected")
|
|
self.send_header("Content-Length", "0")
|
|
self.end_headers()
|
|
|
|
def log_message(self, *args):
|
|
pass
|
|
|
|
self.server = ThreadingHTTPServer(("127.0.0.1", 0), Sink)
|
|
self.server.messages = []
|
|
self.server.response_code = 200
|
|
thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
|
thread.start()
|
|
self.addCleanup(self.server.server_close)
|
|
self.addCleanup(self.server.shutdown)
|
|
self.cfg = config.Config(ntfy_url=f"http://127.0.0.1:{self.server.server_port}/fleet",
|
|
ntfy_token="tk_secret")
|
|
|
|
def test_authenticated_publish(self):
|
|
alerts.publish(self.cfg, "kernelwatch: web01 is stale", "Host missed reports.", stale=True)
|
|
path, headers, data = self.server.messages[0]
|
|
self.assertEqual(path, "/fleet")
|
|
self.assertEqual(headers["Authorization"], "Bearer tk_secret")
|
|
self.assertEqual(headers["Title"], "kernelwatch: web01 is stale")
|
|
self.assertEqual(headers["Priority"], "high")
|
|
self.assertEqual(headers["Tags"], "warning")
|
|
self.assertEqual(data, b"Host missed reports.")
|
|
|
|
def test_recovery_without_auth(self):
|
|
alerts.publish(dataclasses.replace(self.cfg, ntfy_token=""), "Recovered", "Reporting again.")
|
|
_, headers, _ = self.server.messages[0]
|
|
self.assertNotIn("Authorization", headers)
|
|
self.assertEqual(headers["Priority"], "default")
|
|
self.assertEqual(headers["Tags"], "white_check_mark")
|
|
|
|
def test_redirect_rejected_without_following(self):
|
|
self.server.response_code = 302
|
|
with self.assertRaisesRegex(alerts.DeliveryError, "HTTP 302"):
|
|
alerts.publish(self.cfg, "Test", "Body")
|
|
self.assertEqual(len(self.server.messages), 1)
|
|
|
|
def test_http_failures_and_unexpected_success_codes(self):
|
|
for code in (204, 401, 429, 503):
|
|
with self.subTest(code=code):
|
|
self.server.response_code = code
|
|
with self.assertRaisesRegex(alerts.DeliveryError, f"HTTP {code}") as error:
|
|
alerts.publish(self.cfg, "Test", "Body")
|
|
self.assertNotIn("tk_secret", str(error.exception))
|
|
self.assertNotIn(self.cfg.ntfy_url, str(error.exception))
|
|
|
|
def test_stale_and_recovery_through_real_http(self):
|
|
with tempdir() as tmp, mock.patch("kernelwatch.alerts.time.time", return_value=NOW), \
|
|
contextlib.redirect_stdout(io.StringIO()):
|
|
cfg = dataclasses.replace(self.cfg, db_path=os.path.join(tmp, "kw.db"))
|
|
db.init(cfg.db_path)
|
|
conn = db.connect(cfg.db_path)
|
|
try:
|
|
db.add_host(conn, "web01", auth.token_hash(auth.new_token()))
|
|
conn.execute("UPDATE hosts SET created_at = ?", (NOW - 10801,))
|
|
self.assertEqual(alerts.check(cfg), 0)
|
|
self.assertEqual(len(self.server.messages), 1)
|
|
self.assertIn("is stale", self.server.messages[-1][1]["Title"])
|
|
alerts.check(cfg)
|
|
self.assertEqual(len(self.server.messages), 1)
|
|
db.add_report(conn, "web01", {"kernel_running": "x"}, 30)
|
|
self.assertEqual(alerts.check(cfg), 0)
|
|
self.assertEqual(len(self.server.messages), 2)
|
|
self.assertIn("reporting recovered", self.server.messages[-1][1]["Title"])
|
|
self.assertEqual(db.stale_alerts(conn), {})
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
class AlertCommandsAndConfigTest(unittest.TestCase):
|
|
def test_network_errors_are_redacted_and_timeout_is_passed(self):
|
|
cfg = config.Config(ntfy_url="https://ntfy.example/secret-topic", ntfy_token="tk_secret",
|
|
ntfy_timeout_seconds=2.5)
|
|
with mock.patch("kernelwatch.alerts.build_opener") as opener:
|
|
opener.return_value.open.side_effect = URLError(cfg.ntfy_url + cfg.ntfy_token)
|
|
with self.assertRaises(alerts.DeliveryError) as error:
|
|
alerts.publish(cfg, "Test", "Body")
|
|
self.assertNotIn("secret", str(error.exception))
|
|
self.assertEqual(opener.return_value.open.call_args.kwargs["timeout"], 2.5)
|
|
|
|
def test_check_alerts_exit_status_and_test_notification(self):
|
|
with tempdir() as tmp:
|
|
path = os.path.join(tmp, "server.toml")
|
|
with open(path, "w") as f:
|
|
f.write('ntfy_url = "https://ntfy.example/fleet"\n')
|
|
with mock.patch("kernelwatch.cli.alerts.check", return_value=1) as check:
|
|
self.assertEqual(cli.main(["-c", path, "check-alerts"]), 1)
|
|
self.assertEqual(check.call_args.args[0].ntfy_url, "https://ntfy.example/fleet")
|
|
check.return_value = 0
|
|
self.assertEqual(cli.main(["-c", path, "check-alerts"]), 0)
|
|
with mock.patch("kernelwatch.cli.alerts.publish") as publish, contextlib.redirect_stdout(io.StringIO()):
|
|
self.assertEqual(cli.main(["-c", path, "test-alert"]), 0)
|
|
self.assertEqual(publish.call_count, 1)
|
|
publish.side_effect = alerts.DeliveryError("offline")
|
|
with contextlib.redirect_stderr(io.StringIO()):
|
|
self.assertEqual(cli.main(["-c", path, "test-alert"]), 1)
|
|
|
|
def test_disabled_test_alert_is_an_actionable_error(self):
|
|
with self.assertRaisesRegex(alerts.DeliveryError, "ntfy_url is not configured"):
|
|
alerts.publish(config.Config(), "Test", "Body")
|
|
|
|
def test_invalid_alert_config(self):
|
|
bad = ('stale_after_hours = 0', 'stale_after_hours = inf',
|
|
'ntfy_timeout_seconds = -1', 'ntfy_timeout_seconds = nan',
|
|
'ntfy_url = "https://ntfy.example"', 'ntfy_url = "file:///topic"',
|
|
'ntfy_url = "https://user:password@ntfy.example/topic"',
|
|
'ntfy_url = "https://ntfy.example/topic?auth=secret"',
|
|
'ntfy_url = "https://ntfy.example/topic#fragment"',
|
|
'ntfy_url = "https://ntfy.example:bad/topic"',
|
|
'ntfy_token = "bad\\nheader"')
|
|
with tempdir() as tmp:
|
|
path = os.path.join(tmp, "server.toml")
|
|
for text in bad:
|
|
with self.subTest(text=text):
|
|
with open(path, "w") as f:
|
|
f.write(text + "\n")
|
|
with self.assertRaises(SystemExit):
|
|
config.load(path)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|