Files
patrickandClaude Sonnet 5.5 650806bfce Alert when Livepatch is broken or has stopped reporting
The alert check now also notifies, once per problem, when a host's Livepatch has
been unhealthy for livepatch_alert_after_hours (default 6), or when a host that
used to report Livepatch no longer does (a dead daemon leaves the agent with
nothing to send). A livepatch_alerts table records which hosts have reported
Livepatch, when the current problem began and whether it was notified, so hosts
without Livepatch never alert and restarts do not repeat messages. Stale hosts
are skipped.

livepatch_problem() is now the single test for unhealthy, shared with the cover
rule for pending reboots, and names the check state when that is the problem.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 12:18:39 -04:00

344 lines
12 KiB
Python

"""SQLite storage. One connection per thread/request; WAL keeps readers and the writer apart."""
from __future__ import annotations
import calendar
import json
import os
import re
import sqlite3
import time
from typing import Any
SCHEMA = """
CREATE TABLE IF NOT EXISTS hosts (
name TEXT PRIMARY KEY,
token_hash TEXT NOT NULL UNIQUE,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS reports (
id INTEGER PRIMARY KEY,
host TEXT NOT NULL REFERENCES hosts(name) ON DELETE CASCADE,
received_at INTEGER NOT NULL,
payload TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS reports_host_time ON reports(host, received_at);
CREATE TABLE IF NOT EXISTS users (
name TEXT PRIMARY KEY,
pw_hash TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
id_hash TEXT PRIMARY KEY,
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
);
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
);
CREATE TABLE IF NOT EXISTS livepatch_alerts (
host TEXT PRIMARY KEY REFERENCES hosts(name) ON DELETE CASCADE,
since INTEGER,
notified INTEGER NOT NULL DEFAULT 0
);
"""
def connect(path: str) -> sqlite3.Connection:
conn = sqlite3.connect(path, timeout=10, isolation_level=None)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
conn.execute("PRAGMA journal_mode = WAL")
conn.execute("PRAGMA busy_timeout = 10000")
return conn
def init(path: str) -> None:
directory = os.path.dirname(os.path.abspath(path))
os.makedirs(directory, exist_ok=True)
conn = connect(path)
try:
conn.executescript(SCHEMA)
finally:
conn.close()
os.chmod(path, 0o600)
def backup(path: str, dest: str) -> None:
"""Write a consistent copy of the database to dest, replacing any existing file.
Uses SQLite's online backup, which is safe while the server is writing in WAL
mode (a plain file copy could miss the -wal file). The copy is built next to
dest and renamed into place, so a failure never leaves a partial backup."""
dest = os.path.abspath(dest)
if os.path.exists(dest) and os.path.samefile(path, dest):
raise ValueError("backup destination is the live database")
tmp = f"{dest}.tmp-{os.getpid()}"
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
os.close(fd)
src = connect(path)
try:
out = sqlite3.connect(tmp)
try:
src.backup(out)
finally:
out.close()
os.replace(tmp, dest)
except BaseException:
if os.path.exists(tmp):
os.unlink(tmp)
raise
finally:
src.close()
_BACKUP_NAME = re.compile(r"^kernelwatch-(\d{4})-(\d{2})-(\d{2})\.db$")
def latest_backup(directory: str) -> str | None:
"""Name of the newest dated backup in directory, or None."""
try:
names = [n for n in os.listdir(directory) if _BACKUP_NAME.match(n)]
except OSError:
return None
return max(names, default=None)
def rotate_backups(path: str, directory: str, keep_days: int, now: float | None = None) -> str:
"""Back the database up to <directory>/kernelwatch-YYYY-MM-DD.db (UTC date),
replacing that day's file, then delete dated backups that are keep_days or more
days old. Pruning happens only after a successful backup, and touches only files
with that exact name, so a failing backup never costs you the ones you have.
Returns the new backup's path."""
now = time.time() if now is None else now
os.makedirs(directory, mode=0o700, exist_ok=True)
dest = os.path.join(directory, time.strftime("kernelwatch-%Y-%m-%d.db", time.gmtime(now)))
backup(path, dest)
if keep_days > 0:
today = int(now // 86400)
for name in os.listdir(directory):
m = _BACKUP_NAME.match(name)
if not m:
continue
try:
day = calendar.timegm(time.strptime("-".join(m.groups()), "%Y-%m-%d")) // 86400
except (ValueError, OverflowError):
continue
if today - day >= keep_days:
os.unlink(os.path.join(directory, name))
return dest
# --- hosts ------------------------------------------------------------------
def add_host(conn: sqlite3.Connection, name: str, token_hash: str) -> None:
conn.execute(
"INSERT INTO hosts (name, token_hash, created_at) VALUES (?, ?, ?)",
(name, token_hash, int(time.time())),
)
def set_host_token(conn: sqlite3.Connection, name: str, token_hash: str) -> bool:
cur = conn.execute("UPDATE hosts SET token_hash = ? WHERE name = ?", (token_hash, name))
return cur.rowcount == 1
def remove_host(conn: sqlite3.Connection, name: str) -> bool:
return conn.execute("DELETE FROM hosts WHERE name = ?", (name,)).rowcount == 1
def host_for_token(conn: sqlite3.Connection, token_hash: str) -> str | None:
row = conn.execute("SELECT name FROM hosts WHERE token_hash = ?", (token_hash,)).fetchone()
return row["name"] if row else None
def list_hosts(conn: sqlite3.Connection) -> list[sqlite3.Row]:
return conn.execute(
"""
SELECT h.name, h.created_at, MAX(r.received_at) AS last_seen
FROM hosts h LEFT JOIN reports r ON r.host = h.name
GROUP BY h.name ORDER BY h.name
"""
).fetchall()
# --- reports ----------------------------------------------------------------
def add_report(conn: sqlite3.Connection, host: str, payload: dict[str, Any],
retention_days: int, min_interval: int = 0) -> int:
"""Store a report. Returns 0, or the seconds to wait if the host's previous report
is newer than min_interval (nothing is stored then). The check and the insert share
one transaction, so concurrent requests can't both slip past it."""
now = int(time.time())
conn.execute("BEGIN IMMEDIATE")
try:
last = conn.execute("SELECT MAX(received_at) FROM reports WHERE host = ?",
(host,)).fetchone()[0]
if last is not None and 0 <= now - last < min_interval:
conn.execute("ROLLBACK")
return min_interval - (now - last)
conn.execute(
"INSERT INTO reports (host, received_at, payload) VALUES (?, ?, ?)",
(host, now, json.dumps(payload, separators=(",", ":"))),
)
conn.execute(
"DELETE FROM reports WHERE host = ? AND received_at < ?",
(host, now - retention_days * 86400),
)
conn.execute("COMMIT")
return 0
except BaseException:
if conn.in_transaction:
conn.execute("ROLLBACK")
raise
def latest_reports(conn: sqlite3.Connection) -> list[dict[str, Any]]:
"""Every host with its most recent report (or None)."""
rows = conn.execute(
"""
SELECT h.name, r.received_at, r.payload
FROM hosts h
LEFT JOIN reports r ON r.id = (
SELECT id FROM reports WHERE host = h.name ORDER BY received_at DESC, id DESC LIMIT 1
)
ORDER BY h.name
"""
).fetchall()
return [
{
"host": row["name"],
"received_at": row["received_at"],
"report": json.loads(row["payload"]) if row["payload"] else None,
}
for row in rows
]
def host_history(conn: sqlite3.Connection, host: str, limit: int = 50) -> list[dict[str, Any]]:
rows = conn.execute(
"SELECT received_at, payload FROM reports WHERE host = ? "
"ORDER BY received_at DESC, id DESC LIMIT ?",
(host, limit),
).fetchall()
return [{"received_at": r["received_at"], "report": json.loads(r["payload"])} for r in rows]
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,))
# --- 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,))
# --- livepatch notifications -------------------------------------------------
def livepatch_alerts(conn: sqlite3.Connection) -> dict[str, tuple[int | None, bool]]:
"""host -> (when its current Livepatch problem began or None, whether it was
notified). A host appears once it has reported Livepatch at all, which is how
"stopped reporting it" is told apart from "never had it"."""
return {r["host"]: (r["since"], bool(r["notified"]))
for r in conn.execute("SELECT * FROM livepatch_alerts")}
def save_livepatch_alert(conn: sqlite3.Connection, host: str, since: int | None,
notified: bool) -> None:
# The host may have been removed while a notification was in flight.
conn.execute(
"INSERT INTO livepatch_alerts (host, since, notified) "
"SELECT name, ?, ? FROM hosts WHERE name = ? "
"ON CONFLICT(host) DO UPDATE SET since = excluded.since, notified = excluded.notified",
(since, int(notified), host),
)
# --- users & sessions -------------------------------------------------------
def set_user(conn: sqlite3.Connection, name: str, pw_hash: str) -> None:
conn.execute(
"INSERT INTO users (name, pw_hash) VALUES (?, ?) "
"ON CONFLICT(name) DO UPDATE SET pw_hash = excluded.pw_hash",
(name, pw_hash),
)
# A password change logs out existing sessions.
conn.execute("DELETE FROM sessions WHERE user = ?", (name,))
def remove_user(conn: sqlite3.Connection, name: str) -> bool:
return conn.execute("DELETE FROM users WHERE name = ?", (name,)).rowcount == 1
def user_pw_hash(conn: sqlite3.Connection, name: str) -> str | None:
row = conn.execute("SELECT pw_hash FROM users WHERE name = ?", (name,)).fetchone()
return row["pw_hash"] if row else None
def list_users(conn: sqlite3.Connection) -> list[str]:
return [r["name"] for r in conn.execute("SELECT name FROM users ORDER BY name")]
def create_session(conn: sqlite3.Connection, id_hash: str, user: str, ttl_seconds: int) -> None:
now = int(time.time())
conn.execute("DELETE FROM sessions WHERE expires_at < ?", (now,))
conn.execute(
"INSERT INTO sessions (id_hash, user, expires_at) VALUES (?, ?, ?)",
(id_hash, user, now + ttl_seconds),
)
def session_user(conn: sqlite3.Connection, id_hash: str) -> str | None:
row = conn.execute(
"SELECT user FROM sessions WHERE id_hash = ? AND expires_at >= ?",
(id_hash, int(time.time())),
).fetchone()
return row["user"] if row else None
def delete_session(conn: sqlite3.Connection, id_hash: str) -> None:
conn.execute("DELETE FROM sessions WHERE id_hash = ?", (id_hash,))