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

+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: