Files
kernel-automation/server/kernelwatch/config.py
T
patrickandClaude Opus 5.5 15b1f5be4f
CI / tests (Python 3.10) (pull_request) Successful in 43s
CI / tests (Python 3.11) (pull_request) Successful in 44s
CI / tests (Python 3.12) (pull_request) Successful in 43s
CI / tests (Python 3.13) (pull_request) Successful in 42s
CI / lint (pull_request) Successful in 3s
Flag hosts without room on disk for their pending upgrades
A filesystem that fills up while apt downloads or dpkg unpacks leaves the
upgrade half-done and apt broken, the same failure as a full /boot but on
/ or /var. Nothing caught it until the host's updates stopped.

The agent (0.11.0) now works out what the pending upgrades need. A
simulation doesn't print apt's "Need to get" or "additional disk space"
lines, so it sums the package records from apt-cache show for each version
the simulation would install: Size for each .deb not already in
/var/cache/apt/archives, and the growth in Installed-Size over the
installed versions (from dpkg-query). Removals aren't subtracted, so it
errs high. It also reports free space and the mount point of the
filesystems holding /var/cache/apt/archives and /usr.

The server puts a host in update when the upgrades would leave less than
upgrade_min_free_mb (default 100, 0 disables) on either filesystem. The
download and the install both count when they're on the same one. With
nothing pending there is nothing to check, so this doesn't turn into
general disk monitoring. The host page gets a "Pending upgrades size" row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 20:16:54 -05:00

200 lines
9.3 KiB
Python

"""Server configuration, loaded from a flat TOML file."""
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
except ModuleNotFoundError: # Python 3.10 (Ubuntu 22.04): see _parse_flat_toml
tomllib = None
DEFAULT_PATH = "/etc/kernelwatch/server.toml"
@dataclass(frozen=True)
class Config:
# Bind to loopback by default; put a TLS reverse proxy in front.
listen_host: str = "127.0.0.1"
listen_port: int = 8080
db_path: str = "/var/lib/kernelwatch/kernelwatch.db"
# A host that hasn't reported for this long is shown as stale.
stale_after_hours: float = 3.0
# Package lists older than this make "no updates" untrustworthy.
apt_stale_after_hours: float = 48.0
report_retention_days: int = 30
# Less free space than this on /boot's filesystem puts a host in update: the next
# kernel (image plus initramfs, often over 100 MB) may not fit. 0 disables.
boot_min_free_mb: int = 200
# Pending upgrades that would leave less free space than this on the filesystem
# apt downloads to, or the one /usr is on, put a host in update: dpkg would run
# out of room part-way. 0 disables.
upgrade_min_free_mb: int = 100
# Note a host this many days before its OS release stops getting security updates
# (or Ubuntu standard support ends without ESM). 0 disables the warning; a host
# past the date is in update either way.
os_eol_warn_days: int = 90
# A host with unattended-upgrades enabled that hasn't had a successful run in this
# long is in update. It normally runs daily. 0 disables the check.
unattended_upgrades_stale_after_days: float = 3.0
# A host whose apt lists have no repository for its release's security suite
# (e.g. trixie-security), or whose copy of it is older than this while its other
# lists refresh, is in update: security updates can't reach it. Debian and
# Ubuntu publish it at least daily. 0 disables the check.
security_repo_stale_after_days: float = 7.0
# Where `scheduled-backup` (kernelwatch-backup.timer) writes dated copies of the
# database, and how many days of them it keeps; 0 keeps them all. It must stay
# under /var/lib/kernelwatch unless the backup unit is given more write access.
backup_dir: str = "/var/lib/kernelwatch/backups"
backup_keep_days: int = 7
# A host's reports closer together than this are refused with 429; 0 disables.
report_min_interval_seconds: int = 30
session_hours: int = 12
# Leave on unless you serve the dashboard over plain HTTP on a non-localhost name.
secure_cookies: bool = True
# 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
# Dead-man's-switch URLs (e.g. healthchecks.io): pinged after every successful
# alert check (every five minutes) and every successful nightly backup, so a
# monitor outside this host notices when either stops. Empty disables.
heartbeat_url: str = ""
backup_heartbeat_url: str = ""
# Notify when a host has needed a reboot or updates for this long; 0 disables.
status_alert_after_hours: float = 24.0
# Notify when Livepatch has been unhealthy, or a host that used to report it has
# stopped, for this long; 0 disables.
livepatch_alert_after_hours: float = 6.0
def load(path: str | None = None) -> Config:
path = path or os.environ.get("KERNELWATCH_CONFIG") or DEFAULT_PATH
if not os.path.exists(path):
if path == DEFAULT_PATH:
return Config()
raise SystemExit(f"config file not found: {path}")
with open(path, "rb") as f:
data = f.read()
raw = tomllib.loads(data.decode()) if tomllib else _parse_flat_toml(data.decode(), path)
fields = {f.name: f for f in dataclasses.fields(Config)}
unknown = sorted(set(raw) - set(fields))
if unknown:
raise SystemExit(f"{path}: unknown config keys: {', '.join(unknown)}")
values = {}
for name, value in raw.items():
expected = type(getattr(Config(), name))
if expected is float and isinstance(value, int) and not isinstance(value, bool):
value = float(value)
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
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 cfg.report_min_interval_seconds < 0:
raise SystemExit(f"{path}: report_min_interval_seconds must be zero or positive")
if not math.isfinite(cfg.unattended_upgrades_stale_after_days) or cfg.unattended_upgrades_stale_after_days < 0:
raise SystemExit(f"{path}: unattended_upgrades_stale_after_days must be zero or positive and finite")
if not math.isfinite(cfg.security_repo_stale_after_days) or cfg.security_repo_stale_after_days < 0:
raise SystemExit(f"{path}: security_repo_stale_after_days must be zero or positive and finite")
if cfg.os_eol_warn_days < 0:
raise SystemExit(f"{path}: os_eol_warn_days must be zero or positive")
if cfg.boot_min_free_mb < 0:
raise SystemExit(f"{path}: boot_min_free_mb must be zero or positive")
if cfg.upgrade_min_free_mb < 0:
raise SystemExit(f"{path}: upgrade_min_free_mb must be zero or positive")
if cfg.backup_keep_days < 0:
raise SystemExit(f"{path}: backup_keep_days must be zero or positive")
if not cfg.backup_dir.startswith("/") or any(ord(c) < 32 or ord(c) == 127 for c in cfg.backup_dir):
raise SystemExit(f"{path}: backup_dir must be an absolute path")
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")
for key in ("heartbeat_url", "backup_heartbeat_url"):
value = getattr(cfg, key)
if value:
try:
url = urlsplit(value)
valid = (url.scheme in ("http", "https") and url.hostname and url.port != 0
and not url.fragment
and not any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in value))
except ValueError:
valid = False
if not valid:
raise SystemExit(f"{path}: {key} must be an HTTP(S) URL without spaces or a fragment")
if not math.isfinite(cfg.livepatch_alert_after_hours) or cfg.livepatch_alert_after_hours < 0:
raise SystemExit(f"{path}: livepatch_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):
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*(.*)$")
def _parse_flat_toml(text: str, path: str) -> dict[str, Any]:
"""The subset of TOML the config uses (top-level `key = value` with strings,
booleans, integers and floats), for Pythons without tomllib."""
out: dict[str, Any] = {}
for lineno, line in enumerate(text.splitlines(), 1):
line = line.strip()
if not line or line.startswith("#"):
continue
m = _KEY_VALUE.match(line)
if not m:
raise SystemExit(f"{path}:{lineno}: expected `key = value`")
key, value = m.groups()
if key in out:
raise SystemExit(f"{path}:{lineno}: duplicate key {key}")
out[key] = _parse_flat_value(value, f"{path}:{lineno}")
return out
def _parse_flat_value(value: str, where: str) -> Any:
if value[:1] in ('"', "'"):
end = value.find(value[0], 1)
rest = value[end + 1:].strip() if end > 0 else ""
if end < 0 or (rest and not rest.startswith("#")):
raise SystemExit(f"{where}: bad string")
s = value[1:end]
if value[0] == '"' and "\\" in s:
raise SystemExit(f"{where}: escapes aren't supported; use a 'literal string'")
return s
value = value.split("#", 1)[0].strip()
if value in ("true", "false"):
return value == "true"
for conv in (int, float):
try:
return conv(value.replace("_", ""))
except ValueError:
pass
raise SystemExit(f"{where}: unsupported value {value!r}")