CI / tests (Python 3.10) (pull_request) Successful in 23s
CI / tests (Python 3.11) (pull_request) Successful in 25s
CI / tests (Python 3.12) (pull_request) Successful in 24s
CI / tests (Python 3.13) (pull_request) Successful in 24s
CI / lint (pull_request) Successful in 3s
kernelwatch scheduled-backup writes kernelwatch-YYYY-MM-DD.db into backup_dir and prunes dated copies backup_keep_days or older, only after the new backup succeeded and only files with exactly that name. kernelwatch-backup.timer runs it at about 03:30 as the unprivileged service user with no network, and server/install.sh enables it. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
148 lines
6.1 KiB
Python
148 lines
6.1 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
|
|
|
|
# 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
|
|
# Notify when a host has needed a reboot or updates for this long; 0 disables.
|
|
status_alert_after_hours: float = 24.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.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")
|
|
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}")
|