Merge pull request 'Add kernelwatch backup command' (#11) from feat/backup-command into main
CI / tests (Python 3.10) (push) Successful in 18s
CI / tests (Python 3.11) (push) Successful in 18s
CI / tests (Python 3.12) (push) Successful in 18s
CI / tests (Python 3.13) (push) Successful in 19s
CI / lint (push) Successful in 2s

Reviewed-on: #11
This commit was merged in pull request #11.
This commit is contained in:
patrick committed 2026-10-30 00:44:01 +00:00
commit 8cb7ef5e8b
4 files changed
+134

No files matched your search

+22
View File
@@ -438,10 +438,32 @@ sudo kernelwatch list-hosts hosts and when they last reported
sudo kernelwatch set-password USER create a user / change password (logs out their sessions) sudo kernelwatch set-password USER create a user / change password (logs out their sessions)
sudo kernelwatch remove-user USER sudo kernelwatch remove-user USER
sudo kernelwatch list-users sudo kernelwatch list-users
sudo kernelwatch backup PATH write a consistent copy of the database (safe while running)
sudo kernelwatch check-alerts check for stale, recovered, reboot and update alerts now 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 sudo kernelwatch test-alert send a test notification to the configured ntfy topic
``` ```
## Backups
Everything kernelwatch knows lives in one SQLite file, `/var/lib/kernelwatch/kernelwatch.db`:
host tokens (hashed), dashboard logins and report history. Without it you'd
re-register every host and reinstall its token. Don't copy the file while the
server runs, since recent writes can sit in its `-wal` sidecar. Use:
```sh
sudo kernelwatch backup /var/lib/kernelwatch/backups/kernelwatch.db
```
This uses SQLite's online backup, so it's safe while hosts are reporting. It
replaces any existing file at that path and writes it mode 0600. It refuses to
overwrite the live database. The command runs as the `kernelwatch` user, so the
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.
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.
## Security notes ## Security notes
- **Host identity comes from the token, not the payload.** A host can only - **Host identity comes from the token, not the payload.** A host can only
+15
View File
@@ -43,6 +43,17 @@ def cmd_test_alert(cfg, args) -> int:
return 0 return 0
def cmd_backup(cfg, args) -> int:
db.init(cfg.db_path)
try:
db.backup(cfg.db_path, args.path)
except (OSError, ValueError, sqlite3.Error) as exc:
print(f"kernelwatch: backup failed: {exc}", file=sys.stderr)
return 1
print(f"Backed up to {args.path}")
return 0
def cmd_add_host(cfg, args) -> int: def cmd_add_host(cfg, args) -> int:
token = auth.new_token() token = auth.new_token()
conn = _conn(cfg) conn = _conn(cfg)
@@ -154,6 +165,10 @@ def main(argv: list[str] | None = None) -> int:
sub.add_parser("test-alert", help="send a test notification to the configured ntfy topic").set_defaults( sub.add_parser("test-alert", help="send a test notification to the configured ntfy topic").set_defaults(
func=cmd_test_alert) func=cmd_test_alert)
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)
for name, func, help_ in ( for name, func, help_ in (
("add-host", cmd_add_host, "register a host and print its token"), ("add-host", cmd_add_host, "register a host and print its token"),
("rotate-token", cmd_rotate_token, "issue a new token for a host"), ("rotate-token", cmd_rotate_token, "issue a new token for a host"),
+28
View File
@@ -63,6 +63,34 @@ def init(path: str) -> None:
os.chmod(path, 0o600) os.chmod(path, 0o600)
def backup(path: str, dest: str) -> None:
"""Write a consistent copy of the database to dest, replacing any existing file.
Uses SQLite's online backup, which is safe while the server is writing in WAL
mode (a plain file copy could miss the -wal file). The copy is built next to
dest and renamed into place, so a failure never leaves a partial backup."""
dest = os.path.abspath(dest)
if os.path.exists(dest) and os.path.samefile(path, dest):
raise ValueError("backup destination is the live database")
tmp = f"{dest}.tmp-{os.getpid()}"
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
os.close(fd)
src = connect(path)
try:
out = sqlite3.connect(tmp)
try:
src.backup(out)
finally:
out.close()
os.replace(tmp, dest)
except BaseException:
if os.path.exists(tmp):
os.unlink(tmp)
raise
finally:
src.close()
# --- hosts ------------------------------------------------------------------ # --- hosts ------------------------------------------------------------------
def add_host(conn: sqlite3.Connection, name: str, token_hash: str) -> None: def add_host(conn: sqlite3.Connection, name: str, token_hash: str) -> None:
+69
View File
@@ -0,0 +1,69 @@
"""kernelwatch backup: consistent copy, permissions, and refusal to clobber the live DB."""
import contextlib
import io
import os
import sqlite3
import stat
import unittest
from helpers import temp_config, tempdir
from kernelwatch import auth, cli, db
class BackupTest(unittest.TestCase):
def setUp(self):
self.tmp = tempdir()
self.addCleanup(self.tmp.cleanup)
self.cfg = temp_config(self.tmp.name)
self.config_path = os.path.join(self.tmp.name, "server.toml")
with open(self.config_path, "w") as f:
f.write(f'db_path = "{self.cfg.db_path}"\n')
db.init(self.cfg.db_path)
self.conn = db.connect(self.cfg.db_path)
self.addCleanup(self.conn.close)
db.add_host(self.conn, "web01", auth.token_hash("tok"))
db.add_report(self.conn, "web01", {"kernel_running": "6.1.0-1"}, 30)
self.dest = os.path.join(self.tmp.name, "backup.db")
def run_cli(self, *args):
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = cli.main(["-c", self.config_path, *args])
return code, err.getvalue()
def test_backup_contains_data_and_is_private(self):
# The reader holds an open WAL connection, so the data may only be in the -wal file.
self.assertEqual(self.run_cli("backup", self.dest)[0], 0)
self.assertEqual(stat.S_IMODE(os.stat(self.dest).st_mode), 0o600)
copy = db.connect(self.dest)
self.addCleanup(copy.close)
self.assertEqual([h["name"] for h in db.list_hosts(copy)], ["web01"])
self.assertEqual(db.host_for_token(copy, auth.token_hash("tok")), "web01")
self.assertEqual(copy.execute("PRAGMA integrity_check").fetchone()[0], "ok")
self.assertFalse([n for n in os.listdir(self.tmp.name) if ".tmp-" in n])
def test_replaces_an_existing_backup(self):
with open(self.dest, "w") as f:
f.write("old")
self.assertEqual(self.run_cli("backup", self.dest)[0], 0)
copy = sqlite3.connect(self.dest)
self.addCleanup(copy.close)
self.assertEqual(copy.execute("SELECT count(*) FROM hosts").fetchone()[0], 1)
def test_refuses_the_live_database(self):
code, err = self.run_cli("backup", self.cfg.db_path)
self.assertEqual(code, 1)
self.assertIn("live database", err)
self.assertEqual([h["name"] for h in db.list_hosts(self.conn)], ["web01"])
def test_failure_leaves_no_partial_file(self):
missing = os.path.join(self.tmp.name, "nope", "backup.db")
code, err = self.run_cli("backup", missing)
self.assertEqual(code, 1)
self.assertIn("backup failed", err)
self.assertFalse([n for n in os.listdir(self.tmp.name) if ".tmp-" in n])
if __name__ == "__main__":
unittest.main()