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
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:
1 parent
bd0db302b0
commit
47f93968e9
11 files changed
+631
-4
No files matched your search
@@ -1,6 +1,6 @@
|
||||
"""kernelwatch: fleet kernel and reboot status dashboard."""
|
||||
|
||||
__version__ = "0.3.3"
|
||||
__version__ = "0.4.0"
|
||||
|
||||
# Version of agent/kernelwatch-agent shipped alongside this server; older agents
|
||||
# are noted on the dashboard. tests/test_status.py checks the two stay in sync.
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Periodic stale/recovery notifications, independent of report ingestion."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import sqlite3
|
||||
import sys
|
||||
import time
|
||||
from http.client import HTTPException
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
|
||||
from . import db
|
||||
from .config import Config
|
||||
|
||||
|
||||
class DeliveryError(Exception):
|
||||
"""A safe-to-log delivery failure (never includes a URL or access token)."""
|
||||
|
||||
|
||||
class _NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
# A login redirect is not a successful publish. Never forward credentials.
|
||||
return None
|
||||
|
||||
|
||||
def publish(cfg: Config, title: str, message: str, *, stale: bool = False) -> None:
|
||||
if not cfg.ntfy_url:
|
||||
raise DeliveryError("ntfy_url is not configured")
|
||||
headers = {
|
||||
"Content-Type": "text/plain; charset=utf-8",
|
||||
"Title": title,
|
||||
"Tags": "warning" if stale else "white_check_mark",
|
||||
"Priority": "high" if stale else "default",
|
||||
}
|
||||
if cfg.ntfy_token:
|
||||
headers["Authorization"] = f"Bearer {cfg.ntfy_token}"
|
||||
try:
|
||||
request = Request(cfg.ntfy_url.rstrip("/"), data=message.encode(), headers=headers,
|
||||
method="POST")
|
||||
with build_opener(_NoRedirect()).open(request, timeout=cfg.ntfy_timeout_seconds) as response:
|
||||
if response.status != 200:
|
||||
raise DeliveryError(f"ntfy returned HTTP {response.status}; expected 200")
|
||||
except HTTPError as exc:
|
||||
code = exc.code
|
||||
exc.close()
|
||||
raise DeliveryError(f"ntfy returned HTTP {code}; expected 200") from None
|
||||
except (URLError, OSError, ValueError, HTTPException) as exc:
|
||||
# Exception text can contain the private topic URL. Log only its type.
|
||||
raise DeliveryError(f"ntfy request failed ({type(exc).__name__})") from None
|
||||
|
||||
|
||||
def _utc(timestamp: int | float) -> str:
|
||||
return time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(timestamp))
|
||||
|
||||
|
||||
def check(cfg: Config) -> int:
|
||||
"""Send transitions and return the number of failed deliveries.
|
||||
|
||||
Only successful notifications change the saved state. A process lock avoids
|
||||
duplicates from overlapping timer/manual runs without holding a SQLite write
|
||||
transaction during network I/O, so host reports can still be ingested.
|
||||
"""
|
||||
if not cfg.ntfy_url:
|
||||
return 0
|
||||
db.init(cfg.db_path)
|
||||
with open(cfg.db_path + ".alerts.lock", "a") as lock:
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
return 0
|
||||
conn = db.connect(cfg.db_path)
|
||||
try:
|
||||
return _check_hosts(cfg, conn)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _check_hosts(cfg: Config, conn: sqlite3.Connection) -> int:
|
||||
active = db.stale_alerts(conn)
|
||||
failures = 0
|
||||
for host in db.list_hosts(conn):
|
||||
name, last_seen = host["name"], host["last_seen"]
|
||||
now = time.time()
|
||||
baseline = host["created_at"] if last_seen is None else last_seen
|
||||
stale = now - baseline > cfg.stale_after_hours * 3600
|
||||
if stale and name not in active:
|
||||
detail = (f"Last report received at {_utc(last_seen)}." if last_seen is not None else
|
||||
f"No reports received since registration at {_utc(baseline)}.")
|
||||
title = f"kernelwatch: {name} is stale"
|
||||
message = (f"{name} has stopped reporting. {detail}\n"
|
||||
f"Stale threshold: {cfg.stale_after_hours:g} hours. "
|
||||
"Check the host and kernelwatch-agent.timer.")
|
||||
elif (not stale and name in active and last_seen is not None
|
||||
and (active[name] is None or last_seen > active[name])):
|
||||
title = f"kernelwatch: {name} reporting recovered"
|
||||
message = (f"{name} is reporting again. Latest report received at {_utc(last_seen)}.\n"
|
||||
"This confirms reporting has resumed; kernel or package updates may still be pending.")
|
||||
else:
|
||||
continue
|
||||
try:
|
||||
publish(cfg, title, message, stale=stale)
|
||||
except DeliveryError as exc:
|
||||
print(f"kernelwatch: notification failed for {name}: {exc}", file=sys.stderr)
|
||||
failures += 1
|
||||
continue
|
||||
if stale:
|
||||
db.record_stale_alert(conn, name, last_seen)
|
||||
else:
|
||||
db.clear_stale_alert(conn, name)
|
||||
print(f"kernelwatch: {'stale' if stale else 'recovery'} notification sent for {name}")
|
||||
return failures
|
||||
@@ -8,7 +8,7 @@ import sqlite3
|
||||
import sys
|
||||
import time
|
||||
|
||||
from . import __version__, auth, db, web
|
||||
from . import __version__, alerts, auth, db, web
|
||||
from .config import load
|
||||
|
||||
|
||||
@@ -28,6 +28,21 @@ def cmd_serve(cfg, args) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_check_alerts(cfg, args) -> int:
|
||||
return int(alerts.check(cfg) > 0)
|
||||
|
||||
|
||||
def cmd_test_alert(cfg, args) -> int:
|
||||
try:
|
||||
alerts.publish(cfg, "kernelwatch: test notification",
|
||||
"Stale-host and reporting-recovery notifications will be delivered to this topic.")
|
||||
except alerts.DeliveryError as exc:
|
||||
print(f"kernelwatch: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
print("Test notification sent.")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_add_host(cfg, args) -> int:
|
||||
token = auth.new_token()
|
||||
conn = _conn(cfg)
|
||||
@@ -134,6 +149,10 @@ def main(argv: list[str] | None = None) -> int:
|
||||
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("check-alerts", help="send stale-host and recovery notifications").set_defaults(
|
||||
func=cmd_check_alerts)
|
||||
sub.add_parser("test-alert", help="send a test notification to the configured ntfy topic").set_defaults(
|
||||
func=cmd_test_alert)
|
||||
|
||||
for name, func, help_ in (
|
||||
("add-host", cmd_add_host, "register a host and print its token"),
|
||||
|
||||
@@ -3,10 +3,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
try:
|
||||
import tomllib
|
||||
@@ -35,6 +37,11 @@ class Config:
|
||||
# Honour X-Forwarded-For (for login rate limiting). Enable only behind a proxy.
|
||||
trust_proxy_headers: bool = False
|
||||
|
||||
# Full ntfy topic URL; empty disables stale/recovery notifications.
|
||||
ntfy_url: str = ""
|
||||
ntfy_token: str = ""
|
||||
ntfy_timeout_seconds: float = 10.0
|
||||
|
||||
|
||||
def load(path: str | None = None) -> Config:
|
||||
path = path or os.environ.get("KERNELWATCH_CONFIG") or DEFAULT_PATH
|
||||
@@ -60,7 +67,24 @@ def load(path: str | None = None) -> Config:
|
||||
if not isinstance(value, expected) or (expected is int and isinstance(value, bool)):
|
||||
raise SystemExit(f"{path}: {name} must be {expected.__name__}")
|
||||
values[name] = value
|
||||
return Config(**values)
|
||||
cfg = Config(**values)
|
||||
if not math.isfinite(cfg.stale_after_hours) or cfg.stale_after_hours <= 0:
|
||||
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:
|
||||
raise SystemExit(f"{path}: ntfy_timeout_seconds must be 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:
|
||||
try:
|
||||
url = urlsplit(cfg.ntfy_url)
|
||||
valid = (url.scheme in ("http", "https") and url.hostname and url.port != 0
|
||||
and url.path.strip("/") and not url.username and not url.password
|
||||
and not url.query and not url.fragment and not any(c.isspace() for c in cfg.ntfy_url))
|
||||
except ValueError:
|
||||
valid = False
|
||||
if not valid:
|
||||
raise SystemExit(f"{path}: ntfy_url must be an HTTP(S) topic URL without credentials, query or fragment")
|
||||
return cfg
|
||||
|
||||
|
||||
_KEY_VALUE = re.compile(r"^([A-Za-z0-9_-]+)\s*=\s*(.*)$")
|
||||
|
||||
@@ -30,6 +30,10 @@ CREATE TABLE IF NOT EXISTS sessions (
|
||||
user TEXT NOT NULL REFERENCES users(name) ON DELETE CASCADE,
|
||||
expires_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS stale_alerts (
|
||||
host TEXT PRIMARY KEY REFERENCES hosts(name) ON DELETE CASCADE,
|
||||
last_seen INTEGER
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
@@ -142,6 +146,24 @@ def host_exists(conn: sqlite3.Connection, host: str) -> bool:
|
||||
return conn.execute("SELECT 1 FROM hosts WHERE name = ?", (host,)).fetchone() is not None
|
||||
|
||||
|
||||
# --- delivered stale notifications ------------------------------------------
|
||||
|
||||
def stale_alerts(conn: sqlite3.Connection) -> dict[str, int | None]:
|
||||
return {r["host"]: r["last_seen"] for r in conn.execute("SELECT * FROM stale_alerts")}
|
||||
|
||||
|
||||
def record_stale_alert(conn: sqlite3.Connection, host: str, last_seen: int | None) -> None:
|
||||
# The host may have been removed while the notification was in flight.
|
||||
conn.execute(
|
||||
"INSERT INTO stale_alerts (host, last_seen) SELECT name, ? FROM hosts WHERE name = ?",
|
||||
(last_seen, host),
|
||||
)
|
||||
|
||||
|
||||
def clear_stale_alert(conn: sqlite3.Connection, host: str) -> None:
|
||||
conn.execute("DELETE FROM stale_alerts WHERE host = ?", (host,))
|
||||
|
||||
|
||||
# --- users & sessions -------------------------------------------------------
|
||||
|
||||
def set_user(conn: sqlite3.Connection, name: str, pw_hash: str) -> None:
|
||||
|
||||
Reference in new issue
Block a user