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
@@ -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
|
||||
Reference in new issue
Block a user