The server only needed Python 3.11 for tomllib. Fall back to a small parser for the flat key = value subset the config uses, checked against tomllib on the shipped example. Relax the installer's version check to 3.10 and list Ubuntu 22.04 as supported for agents and server. Add status tests using uname -v / package versions captured from real 22.04.5 and 24.04.4 HWE hosts, confirming the Ubuntu build mapping. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
106 lines
3.7 KiB
Python
106 lines
3.7 KiB
Python
"""Server configuration, loaded from a flat TOML file."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import dataclasses
|
|
import os
|
|
import re
|
|
from dataclasses import dataclass
|
|
from typing import Any
|
|
|
|
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
|
|
|
|
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
|
|
|
|
|
|
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
|
|
return Config(**values)
|
|
|
|
|
|
_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}")
|