Back up the database nightly with a timer
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>
This commit is contained in:
patrickandClaude Sonnet 5.5 committed 2026-10-30 10:23:45 -04:00
1 parent 3624f0e5d9
commit 4a9bc77a08
10 files changed
+281 -3

No files matched your search

+3 -1
View File
@@ -44,11 +44,13 @@ fi
install -d -m 0750 -o kernelwatch -g kernelwatch "$root/var/lib/kernelwatch"
install -m 0644 "$here/kernelwatch.service" "$root/etc/systemd/system/"
install -m 0644 "$here/kernelwatch-alerts.service" "$here/kernelwatch-alerts.timer" "$root/etc/systemd/system/"
install -m 0644 "$here/kernelwatch-alerts.service" "$here/kernelwatch-alerts.timer" \
"$here/kernelwatch-backup.service" "$here/kernelwatch-backup.timer" "$root/etc/systemd/system/"
systemctl daemon-reload
systemctl enable kernelwatch.service
systemctl restart kernelwatch.service
systemctl enable --now kernelwatch-alerts.timer
systemctl enable --now kernelwatch-backup.timer
echo
echo "kernelwatch is running on $(grep -E '^listen_' "$root/etc/kernelwatch/server.toml" | tr '\n' ' ')"
+37
View File
@@ -0,0 +1,37 @@
[Unit]
Description=Back up the kernelwatch database
[Service]
Type=oneshot
User=kernelwatch
Group=kernelwatch
Environment=KERNELWATCH_CONFIG=/etc/kernelwatch/server.toml
ExecStart=/usr/bin/python3 -I /opt/kernelwatch/kernelwatch-server scheduled-backup
TimeoutStartSec=10min
StateDirectory=kernelwatch
StateDirectoryMode=0750
CapabilityBoundingSet=
AmbientCapabilities=
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectClock=yes
ProtectHostname=yes
ProtectProc=invisible
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
LockPersonality=yes
MemoryDenyWriteExecute=yes
RestrictAddressFamilies=AF_UNIX
PrivateNetwork=yes
SystemCallArchitectures=native
SystemCallFilter=@system-service
UMask=0077
+10
View File
@@ -0,0 +1,10 @@
[Unit]
Description=Nightly kernelwatch database backup
[Timer]
OnCalendar=*-*-* 03:30:00
RandomizedDelaySec=30min
Persistent=true
[Install]
WantedBy=timers.target
+13
View File
@@ -54,6 +54,17 @@ def cmd_backup(cfg, args) -> int:
return 0
def cmd_scheduled_backup(cfg, args) -> int:
db.init(cfg.db_path)
try:
dest = db.rotate_backups(cfg.db_path, cfg.backup_dir, cfg.backup_keep_days)
except (OSError, ValueError, sqlite3.Error) as exc:
print(f"kernelwatch: scheduled backup failed: {exc}", file=sys.stderr)
return 1
print(f"Backed up to {dest}")
return 0
def cmd_add_host(cfg, args) -> int:
token = auth.new_token()
conn = _conn(cfg)
@@ -168,6 +179,8 @@ def main(argv: list[str] | None = None) -> int:
p = sub.add_parser("backup", help="write a consistent copy of the database to PATH")
p.add_argument("path")
p.set_defaults(func=cmd_backup)
sub.add_parser("scheduled-backup", help="back up to backup_dir and prune old backups "
"(run by kernelwatch-backup.timer)").set_defaults(func=cmd_scheduled_backup)
for name, func, help_ in (
("add-host", cmd_add_host, "register a host and print its token"),
+10
View File
@@ -30,6 +30,12 @@ class Config:
# 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
@@ -78,6 +84,10 @@ def load(path: str | None = None) -> Config:
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):
+30
View File
@@ -2,8 +2,10 @@
from __future__ import annotations
import calendar
import json
import os
import re
import sqlite3
import time
from typing import Any
@@ -91,6 +93,34 @@ def backup(path: str, dest: str) -> None:
src.close()
_BACKUP_NAME = re.compile(r"^kernelwatch-(\d{4})-(\d{2})-(\d{2})\.db$")
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:
+7
View File
@@ -14,6 +14,13 @@ apt_stale_after_hours = 48.0
report_retention_days = 30
# kernelwatch-backup.timer writes a dated copy of the database here every night
# and deletes copies this many days old or older (0 keeps them all). Keep the
# directory under /var/lib/kernelwatch; the unit can't write elsewhere. Copy the
# files off this machine yourself: they don't protect against losing it.
backup_dir = "/var/lib/kernelwatch/backups"
backup_keep_days = 7
# Refuse (HTTP 429) a report that arrives sooner than this after the host's
# previous one. Agents report hourly; this only stops a stuck or abusive client
# from flooding the history. 0 disables.