From 4a9bc77a08ec8f9a55b5cdf19f3d63ecf89ed552 Mon Sep 17 00:00:00 2001 From: patrickbeane Date: Fri, 30 Oct 2026 10:23:45 -0400 Subject: [PATCH] Back up the database nightly with a timer 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 --- README.md | 23 +++++ server/install.sh | 4 +- server/kernelwatch-backup.service | 37 ++++++++ server/kernelwatch-backup.timer | 10 +++ server/kernelwatch/cli.py | 13 +++ server/kernelwatch/config.py | 10 +++ server/kernelwatch/db.py | 30 +++++++ server/server.toml.example | 7 ++ tests/test_backup.py | 136 +++++++++++++++++++++++++++++- tests/test_install.py | 14 ++- 10 files changed, 281 insertions(+), 3 deletions(-) create mode 100644 server/kernelwatch-backup.service create mode 100644 server/kernelwatch-backup.timer diff --git a/README.md b/README.md index f383ca2..87eb2a7 100644 --- a/README.md +++ b/README.md @@ -464,6 +464,7 @@ sudo kernelwatch set-password USER create a user / change password (logs out t sudo kernelwatch remove-user USER sudo kernelwatch list-users sudo kernelwatch backup PATH write a consistent copy of the database (safe while running) +sudo kernelwatch scheduled-backup dated copy in backup_dir, then prune old ones (what the timer runs) sudo kernelwatch check-alerts check for stale, recovered, reboot and update alerts now sudo kernelwatch test-alert send a test notification to the configured ntfy topic ``` @@ -486,6 +487,28 @@ destination directory has to be writable by it (create one with `sudo install -d -o kernelwatch -g kernelwatch -m 0700 /var/lib/kernelwatch/backups`), then copy the result off the machine with your usual backup tool. +### Nightly backups + +`server/install.sh` also enables `kernelwatch-backup.timer`, which runs +`kernelwatch scheduled-backup` at about 03:30 (up to 30 minutes late; a run missed +while the machine was off happens at the next boot). It writes +`/var/lib/kernelwatch/backups/kernelwatch-YYYY-MM-DD.db` (UTC date, mode 0600, +directory 0700) and then deletes dated backups that are `backup_keep_days` (default +7) or more days old. It deletes only files with exactly that name, and only after +the new backup succeeded, so a failing run never costs you the ones you have. Set +`backup_keep_days = 0` to keep them all. The unit can only write under +`/var/lib/kernelwatch`, so keep `backup_dir` there unless you give it more access. + +```sh +systemctl list-timers kernelwatch-backup.timer +journalctl -u kernelwatch-backup # a failed run shows up here +sudo systemctl start kernelwatch-backup # back up now +``` + +These copies sit on the dashboard host, so they protect against a corrupted or +mistakenly changed database but not against losing the machine. Copy +`/var/lib/kernelwatch/backups/` elsewhere with whatever you already back up with. + To restore, stop the service, put the file at `db_path` owned by `kernelwatch` (mode 0600), and start it again. The stale-alert state restores with it. diff --git a/server/install.sh b/server/install.sh index 7900af1..d97594d 100755 --- a/server/install.sh +++ b/server/install.sh @@ -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' ' ')" diff --git a/server/kernelwatch-backup.service b/server/kernelwatch-backup.service new file mode 100644 index 0000000..db5e12f --- /dev/null +++ b/server/kernelwatch-backup.service @@ -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 diff --git a/server/kernelwatch-backup.timer b/server/kernelwatch-backup.timer new file mode 100644 index 0000000..1180a16 --- /dev/null +++ b/server/kernelwatch-backup.timer @@ -0,0 +1,10 @@ +[Unit] +Description=Nightly kernelwatch database backup + +[Timer] +OnCalendar=*-*-* 03:30:00 +RandomizedDelaySec=30min +Persistent=true + +[Install] +WantedBy=timers.target diff --git a/server/kernelwatch/cli.py b/server/kernelwatch/cli.py index 37bbdd5..6463250 100644 --- a/server/kernelwatch/cli.py +++ b/server/kernelwatch/cli.py @@ -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"), diff --git a/server/kernelwatch/config.py b/server/kernelwatch/config.py index 0e9c806..03467af 100644 --- a/server/kernelwatch/config.py +++ b/server/kernelwatch/config.py @@ -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): diff --git a/server/kernelwatch/db.py b/server/kernelwatch/db.py index 4fe01a1..73529d9 100644 --- a/server/kernelwatch/db.py +++ b/server/kernelwatch/db.py @@ -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 /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: diff --git a/server/server.toml.example b/server/server.toml.example index 9593ab5..649ed8b 100644 --- a/server/server.toml.example +++ b/server/server.toml.example @@ -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. diff --git a/tests/test_backup.py b/tests/test_backup.py index 2dfe8bc..46b8966 100644 --- a/tests/test_backup.py +++ b/tests/test_backup.py @@ -1,14 +1,17 @@ """kernelwatch backup: consistent copy, permissions, and refusal to clobber the live DB.""" +import calendar import contextlib import io import os import sqlite3 import stat +import time import unittest +from unittest import mock from helpers import temp_config, tempdir -from kernelwatch import auth, cli, db +from kernelwatch import auth, cli, config, db class BackupTest(unittest.TestCase): @@ -65,5 +68,136 @@ class BackupTest(unittest.TestCase): self.assertFalse([n for n in os.listdir(self.tmp.name) if ".tmp-" in n]) +NOW = calendar.timegm((2026, 11, 20, 3, 30, 0)) + + +def day(offset): + return time.strftime("kernelwatch-%Y-%m-%d.db", time.gmtime(NOW + offset * 86400)) + + +class RotateBackupsTest(unittest.TestCase): + def setUp(self): + self.tmp = tempdir() + self.addCleanup(self.tmp.cleanup) + self.db_path = os.path.join(self.tmp.name, "kw.db") + self.dir = os.path.join(self.tmp.name, "backups") + db.init(self.db_path) + conn = db.connect(self.db_path) + self.addCleanup(conn.close) + db.add_host(conn, "web01", auth.token_hash("tok")) + + def touch(self, name): + os.makedirs(self.dir, exist_ok=True) + with open(os.path.join(self.dir, name), "w") as f: + f.write("x") + + def names(self): + return sorted(os.listdir(self.dir)) + + def rotate(self, keep=7, now=NOW): + return db.rotate_backups(self.db_path, self.dir, keep, now) + + def test_writes_a_dated_private_copy_and_creates_the_directory(self): + dest = self.rotate() + self.assertEqual(dest, os.path.join(self.dir, "kernelwatch-2026-11-20.db")) + self.assertEqual(stat.S_IMODE(os.stat(self.dir).st_mode), 0o700) + self.assertEqual(stat.S_IMODE(os.stat(dest).st_mode), 0o600) + copy = sqlite3.connect(dest) + self.addCleanup(copy.close) + self.assertEqual(copy.execute("SELECT name FROM hosts").fetchall(), [("web01",)]) + + def test_same_day_replaces_the_file(self): + self.rotate() + self.rotate() + self.assertEqual(self.names(), [day(0)]) + + def test_prunes_by_age_and_keeps_the_boundary(self): + for offset in range(-10, 0): + self.touch(day(offset)) + self.rotate(keep=7) + # keep=7 keeps today and the six days before it. + self.assertEqual(self.names(), sorted(day(o) for o in range(-6, 1))) + + def test_only_dated_backup_files_are_ever_deleted(self): + keepers = ["kernelwatch.db", "notes.txt", "kernelwatch-2020-01-01.db.bak", + "kernelwatch-2020-01-01.db.tmp-1", "kernelwatch-2020-13-45.db", + "other-2020-01-01.db"] + for name in keepers + [day(-30)]: + self.touch(name) + self.rotate(keep=7) + self.assertEqual(self.names(), sorted(keepers + [day(0)])) + + def test_zero_keeps_everything(self): + for offset in (-400, -30, -8): + self.touch(day(offset)) + self.rotate(keep=0) + self.assertEqual(len(self.names()), 4) + + def test_a_failed_backup_prunes_nothing(self): + for offset in (-30, -1): + self.touch(day(offset)) + with mock.patch("kernelwatch.db.backup", side_effect=sqlite3.OperationalError("disk full")): + with self.assertRaises(sqlite3.OperationalError): + self.rotate(keep=7) + self.assertEqual(self.names(), sorted([day(-30), day(-1)])) + + def test_the_live_database_is_never_pruned(self): + os.makedirs(self.dir) + live = os.path.join(self.dir, "kernelwatch-2000-01-01.db") + db.init(live) + with self.assertRaisesRegex(ValueError, "live database"): + db.rotate_backups(live, self.dir, 7, calendar.timegm((2000, 1, 1, 0, 0, 0))) + self.assertTrue(os.path.exists(live)) + + +class ScheduledBackupCommandTest(unittest.TestCase): + def setUp(self): + self.tmp = tempdir() + self.addCleanup(self.tmp.cleanup) + self.dir = os.path.join(self.tmp.name, "backups") + self.config_path = os.path.join(self.tmp.name, "server.toml") + self.write_config(f'db_path = "{self.tmp.name}/kw.db"\nbackup_dir = "{self.dir}"\nbackup_keep_days = 3\n') + + def write_config(self, text): + with open(self.config_path, "w") as f: + f.write(text) + + def run_cli(self): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = cli.main(["-c", self.config_path, "scheduled-backup"]) + return code, out.getvalue(), err.getvalue() + + def test_backs_up_to_the_configured_directory_and_prunes_with_the_configured_age(self): + os.makedirs(self.dir) + old = os.path.join(self.dir, "kernelwatch-2020-01-01.db") + open(old, "w").close() + code, out, _ = self.run_cli() + self.assertEqual(code, 0) + today = time.strftime("kernelwatch-%Y-%m-%d.db", time.gmtime()) + self.assertIn(os.path.join(self.dir, today), out) + self.assertEqual(os.listdir(self.dir), [today]) + + def test_failure_exits_nonzero(self): + with open(os.path.join(self.tmp.name, "blocker"), "w") as f: + f.write("a file where the directory should go") + self.write_config(f'db_path = "{self.tmp.name}/kw.db"\nbackup_dir = "{self.tmp.name}/blocker/x"\n') + code, _, err = self.run_cli() + self.assertEqual(code, 1) + self.assertIn("scheduled backup failed", err) + + def test_config_defaults_and_validation(self): + cfg = config.Config() + self.assertEqual((cfg.backup_dir, cfg.backup_keep_days), ("/var/lib/kernelwatch/backups", 7)) + for bad in ("backup_keep_days = -1", 'backup_dir = ""', 'backup_dir = "relative/dir"', + "backup_keep_days = 1.5", "backup_dir = 5"): + with self.subTest(bad=bad): + self.write_config(bad + "\n") + with self.assertRaises(SystemExit): + config.load(self.config_path) + self.write_config("backup_keep_days = 0\n") + self.assertEqual(config.load(self.config_path).backup_keep_days, 0) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_install.py b/tests/test_install.py index 03b4bd1..e1bf1c3 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -306,7 +306,7 @@ class ServerInstallTest(InstallCase): self.assertEqual(self.systemctl(), [ "daemon-reload", "enable kernelwatch.service", "restart kernelwatch.service", - "enable --now kernelwatch-alerts.timer"]) + "enable --now kernelwatch-alerts.timer", "enable --now kernelwatch-backup.timer"]) self.assertIn("listen_host = \"127.0.0.1\"", proc.stdout) self.assertIn("set-password admin", proc.stdout) @@ -317,6 +317,18 @@ class ServerInstallTest(InstallCase): for unit in units: self.assertEqual(mode(self.path("etc/systemd/system", unit)), 0o644) + def test_unit_commands_exist_in_the_cli(self): + """Every `kernelwatch-server ` a unit runs must be a real subcommand.""" + help_text = subprocess.run(["python3", "-I", os.path.join(SERVER_DIR, "kernelwatch-server"), "--help"], + capture_output=True, text=True, timeout=30).stdout + commands = set() + for unit in os.listdir(SERVER_DIR): + if unit.endswith(".service"): + commands.update(re.findall(r"kernelwatch-server (\S+)$", read(os.path.join(SERVER_DIR, unit)), re.M)) + self.assertTrue(commands) + for command in commands: + self.assertRegex(help_text, rf"\b{re.escape(command)}\b") + def test_existing_user_is_not_recreated(self): self.install(KW_ID_RC="0") self.assertFalse([c for c in self.calls() if c.startswith("useradd")])