Add ntfy alerts for stale hosts and reporting recovery
CI / tests (Python 3.10) (pull_request) Successful in 19s
CI / tests (Python 3.11) (pull_request) Successful in 17s
CI / tests (Python 3.12) (pull_request) Successful in 17s
CI / tests (Python 3.13) (pull_request) Successful in 18s
CI / lint (pull_request) Successful in 3s

This commit is contained in:
patrick committed 2026-10-24 15:15:48 -04:00
1 parent bd0db302b0
commit 47f93968e9
11 files changed
+631 -4

No files matched your search

+340
View File
@@ -0,0 +1,340 @@
"""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 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()