Compare commits

...
4 Commits
Author SHA1 Message Date
patrick c67a8e27a0 Merge pull request 'Add ntfy alerts for hosts that need a reboot or updates for too long' (#10) from feat/status-alerts into main
CI / tests (Python 3.10) (push) Successful in 18s
CI / tests (Python 3.11) (push) Successful in 17s
CI / tests (Python 3.12) (push) Successful in 18s
CI / tests (Python 3.13) (push) Successful in 18s
CI / lint (push) Successful in 3s
Reviewed-on: #10
2026-10-30 00:35:02 +00:00
patrickandClaude Sonnet 5.5 b6957e3ca4 Document reboot and update alerts
CI / tests (Python 3.10) (pull_request) Successful in 19s
CI / tests (Python 3.11) (pull_request) Successful in 18s
CI / tests (Python 3.12) (pull_request) Successful in 17s
CI / tests (Python 3.13) (pull_request) Successful in 17s
CI / lint (pull_request) Successful in 3s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-29 20:32:24 -04:00
patrickandClaude Sonnet 5.5 ce231bd471 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>
2026-10-29 20:32:24 -04:00
patrickandClaude Sonnet 5.5 d6480ef1b9 Add status_alerts table and status_alert_after_hours setting
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-29 20:30:51 -04:00
8 changed files with 249 additions and 7 deletions

No files matched your search

+13 -3
View File
@@ -369,7 +369,7 @@ Host zeus
ProxyJump eurus ProxyJump eurus
``` ```
## Stale-host and recovery alerts (ntfy) ## Stale-host, reboot and update alerts (ntfy)
The server can notify an [ntfy](https://ntfy.sh/) topic when a host stops The server can notify an [ntfy](https://ntfy.sh/) topic when a host stops
reporting and when its reports resume. Agents report hourly with up to 15 minutes reporting and when its reports resume. Agents report hourly with up to 15 minutes
@@ -413,6 +413,16 @@ fresh report. Run `sudo kernelwatch check-alerts` to check immediately, or inspe
`stale_after_hours`, restart `kernelwatch.service` too so the dashboard uses the `stale_after_hours`, restart `kernelwatch.service` too so the dashboard uses the
new threshold. new threshold.
- **Reboot and update alerts.** A host that has stayed in `reboot` or `update`
for `status_alert_after_hours` (default 24) gets one notification listing the
reasons shown on the dashboard. The clock starts when the host entered that
status, so hourly reports don't restart it. Fixing the host (back to `ok`)
re-arms it. Going from `update` to `reboot` notifies again after another
period; going back down doesn't. Stale hosts are skipped, since the stale
alert covers them. Set `status_alert_after_hours = 0` to turn these off.
Upgrading starts the clock at the first check, so expect the first
notifications a day after you re-run `install.sh`.
Use the topic's direct publish URL, with token authentication if needed; it must Use the topic's direct publish URL, with token authentication if needed; it must
accept the POST without a browser login or redirect. The topic and token stay accept the POST without a browser login or redirect. The topic and token stay
in the server config (root-owned, readable by the `kernelwatch` service group). in the server config (root-owned, readable by the `kernelwatch` service group).
@@ -428,7 +438,7 @@ sudo kernelwatch list-hosts hosts and when they last reported
sudo kernelwatch set-password USER create a user / change password (logs out their sessions) sudo kernelwatch set-password USER create a user / change password (logs out their sessions)
sudo kernelwatch remove-user USER sudo kernelwatch remove-user USER
sudo kernelwatch list-users sudo kernelwatch list-users
sudo kernelwatch check-alerts check for stale hosts and reporting recovery now sudo kernelwatch check-alerts check for stale, recovered, reboot and update alerts now
sudo kernelwatch test-alert send a test notification to the configured ntfy topic sudo kernelwatch test-alert send a test notification to the configured ntfy topic
``` ```
@@ -483,7 +493,7 @@ export KERNELWATCH_CONFIG=/tmp/kw.toml
## Ideas for later ## Ideas for later
- Notifications for pending updates/reboots, and additional delivery channels - Additional notification channels
- Ubuntu Livepatch / Pro status, so live-patched hosts aren't flagged for reboot - Ubuntu Livepatch / Pro status, so live-patched hosts aren't flagged for reboot
- A JSON endpoint for scripting - A JSON endpoint for scripting
- Grouping or tagging hosts (prod/staging, location) - Grouping or tagging hosts (prod/staging, location)
+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)
+4
View File
@@ -41,6 +41,8 @@ class Config:
ntfy_url: str = "" ntfy_url: str = ""
ntfy_token: str = "" ntfy_token: str = ""
ntfy_timeout_seconds: float = 10.0 ntfy_timeout_seconds: float = 10.0
# Notify when a host has needed a reboot or updates for this long; 0 disables.
status_alert_after_hours: float = 24.0
def load(path: str | None = None) -> Config: def load(path: str | None = None) -> Config:
@@ -72,6 +74,8 @@ def load(path: str | None = None) -> Config:
raise SystemExit(f"{path}: stale_after_hours must be positive and finite") raise SystemExit(f"{path}: stale_after_hours must be positive and finite")
if not math.isfinite(cfg.ntfy_timeout_seconds) or cfg.ntfy_timeout_seconds <= 0: if not math.isfinite(cfg.ntfy_timeout_seconds) or cfg.ntfy_timeout_seconds <= 0:
raise SystemExit(f"{path}: ntfy_timeout_seconds must be positive and finite") raise SystemExit(f"{path}: ntfy_timeout_seconds must be positive and finite")
if not math.isfinite(cfg.status_alert_after_hours) or cfg.status_alert_after_hours < 0:
raise SystemExit(f"{path}: status_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): 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") raise SystemExit(f"{path}: ntfy settings must not contain control characters")
if cfg.ntfy_url: if cfg.ntfy_url:
+30
View File
@@ -34,6 +34,12 @@ CREATE TABLE IF NOT EXISTS stale_alerts (
host TEXT PRIMARY KEY REFERENCES hosts(name) ON DELETE CASCADE, host TEXT PRIMARY KEY REFERENCES hosts(name) ON DELETE CASCADE,
last_seen INTEGER last_seen INTEGER
); );
CREATE TABLE IF NOT EXISTS status_alerts (
host TEXT PRIMARY KEY REFERENCES hosts(name) ON DELETE CASCADE,
level TEXT NOT NULL,
since INTEGER NOT NULL,
notified_level TEXT
);
""" """
@@ -164,6 +170,30 @@ def clear_stale_alert(conn: sqlite3.Connection, host: str) -> None:
conn.execute("DELETE FROM stale_alerts WHERE host = ?", (host,)) conn.execute("DELETE FROM stale_alerts WHERE host = ?", (host,))
# --- pending reboot/update notifications ------------------------------------
def status_alerts(conn: sqlite3.Connection) -> dict[str, tuple[str, int, str | None]]:
"""host -> (level, when it entered that level, level last notified for)."""
return {r["host"]: (r["level"], r["since"], r["notified_level"])
for r in conn.execute("SELECT * FROM status_alerts")}
def save_status_alert(conn: sqlite3.Connection, host: str, level: str, since: int,
notified_level: str | None) -> None:
# The host may have been removed while a notification was in flight.
conn.execute(
"INSERT INTO status_alerts (host, level, since, notified_level) "
"SELECT name, ?, ?, ? FROM hosts WHERE name = ? "
"ON CONFLICT(host) DO UPDATE SET level = excluded.level, since = excluded.since, "
"notified_level = excluded.notified_level",
(level, since, notified_level, host),
)
def clear_status_alert(conn: sqlite3.Connection, host: str) -> None:
conn.execute("DELETE FROM status_alerts WHERE host = ?", (host,))
# --- users & sessions ------------------------------------------------------- # --- users & sessions -------------------------------------------------------
def set_user(conn: sqlite3.Connection, name: str, pw_hash: str) -> None: def set_user(conn: sqlite3.Connection, name: str, pw_hash: str) -> None:
+6
View File
@@ -31,3 +31,9 @@ trust_proxy_headers = false
ntfy_url = "" # e.g. "https://ntfy.example.com/kernelwatch" ntfy_url = "" # e.g. "https://ntfy.example.com/kernelwatch"
ntfy_token = "" # optional ntfy access token (Bearer auth) ntfy_token = "" # optional ntfy access token (Bearer auth)
ntfy_timeout_seconds = 10.0 ntfy_timeout_seconds = 10.0
# Also notify (once) when a host has needed a reboot or updates for this long.
# Measured from when the host entered that state, not from its latest report.
# Reaching a worse state (updates -> reboot) notifies again after another period.
# 0 disables. Needs ntfy_url.
status_alert_after_hours = 24.0
+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: