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
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:
1 parent
3624f0e5d9
commit
4a9bc77a08
10 files changed
+281
-3
No files matched your search
@@ -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"),
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user