CI / tests (Python 3.10) (pull_request) Successful in 29s
CI / tests (Python 3.11) (pull_request) Successful in 30s
CI / tests (Python 3.12) (pull_request) Successful in 29s
CI / tests (Python 3.13) (pull_request) Successful in 28s
CI / lint (pull_request) Successful in 4s
A full /boot makes the next kernel's postinst fail: apt is left half-done
and the host quietly stays on its old kernel, which kernelwatch only
noticed indirectly, if at all. The agent now reports the size and free
space of the filesystem holding /boot (df) and the packages dpkg didn't
finish installing (half-installed, unpacked, half-configured, trigger
states or reinst-required, as dpkg --audit counts them).
The server puts a host in update when /boot has less than
boot_min_free_mb (default 200, 0 disables) free, or any package is
unfinished, with the fix in the reason ("run dpkg --configure -a"). The
host page shows both. Agents before 0.6.0 send neither field and are
judged as before. Agent 0.6.0.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
176 lines
7.6 KiB
Python
176 lines
7.6 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
|
|
|
|
# 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 cfg.boot_min_free_mb < 0:
|
|
raise SystemExit(f"{path}: boot_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}")
|