Add kernelwatch backup command

Uses SQLite's online backup API, so it is consistent while the server is
writing in WAL mode. Writes mode 0600 via a temp file and rename, and
refuses to overwrite the live database.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
patrickandClaude Sonnet 5.5 committed 2026-10-29 20:37:54 -04:00
1 parent c67a8e27a0
commit 4365ed56e1
3 files changed
+112

No files matched your search

+28
View File
@@ -63,6 +63,34 @@ def init(path: str) -> None:
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 ------------------------------------------------------------------
def add_host(conn: sqlite3.Connection, name: str, token_hash: str) -> None: