Merge pull request 'Back up the database nightly with a timer' (#17) from feat/backup-timer into main
CI / tests (Python 3.10) (push) Successful in 26s
CI / tests (Python 3.11) (push) Successful in 24s
CI / tests (Python 3.12) (push) Successful in 24s
CI / tests (Python 3.13) (push) Successful in 24s
CI / lint (push) Successful in 3s

Reviewed-on: #17
This commit was merged in pull request #17.
This commit is contained in:
patrick committed 2026-10-30 15:06:01 +00:00
commit 6652a4d795
10 files changed
+281 -3

No files matched your search

+23
View File
@@ -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.
+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.
+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")])