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

+135 -1
View File
@@ -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()
+13 -1
View File
@@ -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 <command>` 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")])