Notify via ntfy when the nightly backup fails #18
No files matched your search
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import socket
|
||||
import sqlite3
|
||||
import sys
|
||||
import time
|
||||
@@ -158,3 +159,26 @@ def _check_status(cfg: Config, conn: sqlite3.Connection) -> int:
|
||||
db.save_status_alert(conn, name, level, since, level)
|
||||
print(f"kernelwatch: {level} notification sent for {name}")
|
||||
return failures
|
||||
|
||||
|
||||
def notify_backup_failure(cfg: Config) -> int:
|
||||
"""Tell the ntfy topic the nightly backup failed. Returns 1 if that couldn't be sent.
|
||||
|
||||
Run by systemd (OnFailure= on kernelwatch-backup.service), so it also covers
|
||||
failures the backup command can't report itself: a timeout, an out-of-memory
|
||||
kill, a crash. The cause is in `journalctl -u kernelwatch-backup`."""
|
||||
if not cfg.ntfy_url:
|
||||
print("kernelwatch: backup failed, but ntfy_url is not configured; no notification sent",
|
||||
file=sys.stderr)
|
||||
return 0
|
||||
latest = db.latest_backup(cfg.backup_dir)
|
||||
message = (f"The nightly kernelwatch database backup on {socket.gethostname()} failed.\n"
|
||||
f"Newest backup still on disk: {latest or 'none'}.\n"
|
||||
"Cause: journalctl -u kernelwatch-backup")
|
||||
try:
|
||||
publish(cfg, "kernelwatch: nightly backup failed", message, stale=True, tag="floppy_disk")
|
||||
except DeliveryError as exc:
|
||||
print(f"kernelwatch: backup failure notification failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
print("kernelwatch: backup failure notification sent")
|
||||
return 0
|
||||
@@ -43,6 +43,10 @@ def cmd_test_alert(cfg, args) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_notify_backup_failure(cfg, args) -> int:
|
||||
return alerts.notify_backup_failure(cfg)
|
||||
|
||||
|
||||
def cmd_backup(cfg, args) -> int:
|
||||
db.init(cfg.db_path)
|
||||
try:
|
||||
@@ -179,6 +183,9 @@ 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("notify-backup-failure", help="send the failed-backup notification "
|
||||
"(run by systemd when kernelwatch-backup.service fails)").set_defaults(
|
||||
func=cmd_notify_backup_failure)
|
||||
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)
|
||||
|
||||
|
||||
@@ -96,6 +96,15 @@ def backup(path: str, dest: str) -> None:
|
||||
_BACKUP_NAME = re.compile(r"^kernelwatch-(\d{4})-(\d{2})-(\d{2})\.db$")
|
||||
|
||||
|
||||
def latest_backup(directory: str) -> str | None:
|
||||
"""Name of the newest dated backup in directory, or None."""
|
||||
try:
|
||||
names = [n for n in os.listdir(directory) if _BACKUP_NAME.match(n)]
|
||||
except OSError:
|
||||
return None
|
||||
return max(names, default=None)
|
||||
|
||||
|
||||
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
|
||||
|
||||
@@ -341,6 +341,56 @@ class StatusAlertsTest(unittest.TestCase):
|
||||
self.assertEqual(db.status_alerts(self.conn), {})
|
||||
|
||||
|
||||
class BackupFailureAlertTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempdir()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.dir = os.path.join(self.tmp.name, "backups")
|
||||
self.cfg = temp_config(self.tmp.name, ntfy_url="https://ntfy.example.test/fleet",
|
||||
backup_dir=self.dir)
|
||||
stack = contextlib.ExitStack()
|
||||
self.addCleanup(stack.close)
|
||||
self.publish = stack.enter_context(mock.patch("kernelwatch.alerts.publish"))
|
||||
self.output = stack.enter_context(contextlib.redirect_stdout(io.StringIO()))
|
||||
self.errors = stack.enter_context(contextlib.redirect_stderr(io.StringIO()))
|
||||
|
||||
def touch(self, *names):
|
||||
os.makedirs(self.dir, exist_ok=True)
|
||||
for name in names:
|
||||
open(os.path.join(self.dir, name), "w").close()
|
||||
|
||||
def test_sends_an_urgent_notification_naming_the_newest_backup(self):
|
||||
self.touch("kernelwatch-2026-11-18.db", "kernelwatch-2026-11-19.db", "kernelwatch-2026-11-20.db.tmp-4")
|
||||
self.assertEqual(alerts.notify_backup_failure(self.cfg), 0)
|
||||
(cfg, title, message), kwargs = self.publish.call_args
|
||||
self.assertEqual(title, "kernelwatch: nightly backup failed")
|
||||
self.assertIn("Newest backup still on disk: kernelwatch-2026-11-19.db.", message)
|
||||
self.assertIn("journalctl -u kernelwatch-backup", message)
|
||||
self.assertTrue(kwargs["stale"]) # high priority
|
||||
|
||||
def test_says_when_there_is_no_backup_at_all(self):
|
||||
self.assertEqual(alerts.notify_backup_failure(self.cfg), 0)
|
||||
self.assertIn("Newest backup still on disk: none.", self.publish.call_args.args[2])
|
||||
|
||||
def test_delivery_failure_is_reported_and_fails_the_unit(self):
|
||||
self.publish.side_effect = alerts.DeliveryError("ntfy returned HTTP 503")
|
||||
self.assertEqual(alerts.notify_backup_failure(self.cfg), 1)
|
||||
self.assertIn("ntfy returned HTTP 503", self.errors.getvalue())
|
||||
|
||||
def test_without_ntfy_it_says_so_and_does_not_fail(self):
|
||||
cfg = dataclasses.replace(self.cfg, ntfy_url="")
|
||||
self.assertEqual(alerts.notify_backup_failure(cfg), 0)
|
||||
self.publish.assert_not_called()
|
||||
self.assertIn("ntfy_url is not configured", self.errors.getvalue())
|
||||
|
||||
def test_cli_command(self):
|
||||
path = os.path.join(self.tmp.name, "server.toml")
|
||||
with open(path, "w") as f:
|
||||
f.write(f'ntfy_url = "https://ntfy.example.test/fleet"\nbackup_dir = "{self.dir}"\n')
|
||||
self.assertEqual(cli.main(["-c", path, "notify-backup-failure"]), 0)
|
||||
self.assertEqual(self.publish.call_count, 1)
|
||||
|
||||
|
||||
class NtfyHTTPTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
class Sink(BaseHTTPRequestHandler):
|
||||
|
||||
Reference in new issue
Block a user