Notify when a host has needed a reboot or updates for too long

The alert timer now evaluates each host with the dashboard's status logic
and sends one ntfy message once a host has been in reboot or update for
status_alert_after_hours, measured from when it entered that status.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
patrickandClaude Sonnet 5.5 committed 2026-10-29 20:32:24 -04:00
1 parent d6480ef1b9
commit ce231bd471
4 files changed
+196 -4

No files matched your search

+51 -3
View File
@@ -12,6 +12,7 @@ from urllib.request import HTTPRedirectHandler, Request, build_opener
from . import db from . import db
from .config import Config from .config import Config
from .status import LEVELS, evaluate
class DeliveryError(Exception): class DeliveryError(Exception):
@@ -24,13 +25,14 @@ class _NoRedirect(HTTPRedirectHandler):
return None return None
def publish(cfg: Config, title: str, message: str, *, stale: bool = False) -> None: def publish(cfg: Config, title: str, message: str, *, stale: bool = False,
tag: str | None = None) -> None:
if not cfg.ntfy_url: if not cfg.ntfy_url:
raise DeliveryError("ntfy_url is not configured") raise DeliveryError("ntfy_url is not configured")
headers = { headers = {
"Content-Type": "text/plain; charset=utf-8", "Content-Type": "text/plain; charset=utf-8",
"Title": title, "Title": title,
"Tags": "warning" if stale else "white_check_mark", "Tags": tag or ("warning" if stale else "white_check_mark"),
"Priority": "high" if stale else "default", "Priority": "high" if stale else "default",
} }
if cfg.ntfy_token: if cfg.ntfy_token:
@@ -71,7 +73,10 @@ def check(cfg: Config) -> int:
return 0 return 0
conn = db.connect(cfg.db_path) conn = db.connect(cfg.db_path)
try: try:
return _check_hosts(cfg, conn) failures = _check_hosts(cfg, conn)
if cfg.status_alert_after_hours > 0:
failures += _check_status(cfg, conn)
return failures
finally: finally:
conn.close() conn.close()
@@ -110,3 +115,46 @@ def _check_hosts(cfg: Config, conn: sqlite3.Connection) -> int:
db.clear_stale_alert(conn, name) db.clear_stale_alert(conn, name)
print(f"kernelwatch: {'stale' if stale else 'recovery'} notification sent for {name}") print(f"kernelwatch: {'stale' if stale else 'recovery'} notification sent for {name}")
return failures 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
+1 -1
View File
@@ -149,7 +149,7 @@ def main(argv: list[str] | None = None) -> int:
sub = parser.add_subparsers(dest="command", required=True) sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("serve", help="run the HTTP server").set_defaults(func=cmd_serve) sub.add_parser("serve", help="run the HTTP server").set_defaults(func=cmd_serve)
sub.add_parser("check-alerts", help="send stale-host and recovery notifications").set_defaults( sub.add_parser("check-alerts", help="send stale, recovery, reboot and update notifications").set_defaults(
func=cmd_check_alerts) func=cmd_check_alerts)
sub.add_parser("test-alert", help="send a test notification to the configured ntfy topic").set_defaults( sub.add_parser("test-alert", help="send a test notification to the configured ntfy topic").set_defaults(
func=cmd_test_alert) func=cmd_test_alert)
+136
View File
@@ -205,6 +205,142 @@ class AlertTransitionsTest(unittest.TestCase):
self.publish.assert_not_called() 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 NtfyHTTPTest(unittest.TestCase): class NtfyHTTPTest(unittest.TestCase):
def setUp(self): def setUp(self):
class Sink(BaseHTTPRequestHandler): class Sink(BaseHTTPRequestHandler):
+8
View File
@@ -67,6 +67,14 @@ class ConfigTest(unittest.TestCase):
with self.assertRaises(SystemExit): with self.assertRaises(SystemExit):
config.load(self.write(tmp, "secure_cookies = 1\n")) config.load(self.write(tmp, "secure_cookies = 1\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"))
.status_alert_after_hours, 0)
for bad in ("-1", "inf", "nan"):
with self.subTest(bad=bad), self.assertRaises(SystemExit):
config.load(self.write(tmp, f"status_alert_after_hours = {bad}\n"))
def test_fallback_parser_matches_tomllib(self): def test_fallback_parser_matches_tomllib(self):
"""Python 3.10 has no tomllib; the fallback must read the same configs.""" """Python 3.10 has no tomllib; the fallback must read the same configs."""
if config.tomllib is None: if config.tomllib is None: