Compare commits
2
Commits
6652a4d795
...
48960e6faf
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48960e6faf | ||
|
|
8a9a3ca56d |
No files matched your search
@@ -465,6 +465,7 @@ 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 backup PATH write a consistent copy of the database (safe while running)
|
||||||
sudo kernelwatch scheduled-backup dated copy in backup_dir, then prune old ones (what the timer runs)
|
sudo kernelwatch scheduled-backup dated copy in backup_dir, then prune old ones (what the timer runs)
|
||||||
|
sudo kernelwatch notify-backup-failure send the failed-backup notification now (also runs on failure)
|
||||||
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
|
||||||
```
|
```
|
||||||
@@ -505,6 +506,17 @@ journalctl -u kernelwatch-backup # a failed run shows up here
|
|||||||
sudo systemctl start kernelwatch-backup # back up now
|
sudo systemctl start kernelwatch-backup # back up now
|
||||||
```
|
```
|
||||||
|
|
||||||
|
If a run fails, whether from an error, the 10-minute timeout, an out-of-memory
|
||||||
|
kill or a crash, systemd starts `kernelwatch-backup-failed.service`
|
||||||
|
(`OnFailure=`), which sends a high-priority message to your ntfy topic naming the
|
||||||
|
newest backup still on disk. The cause is in `journalctl -u kernelwatch-backup`.
|
||||||
|
Without `ntfy_url` it only logs that it had nothing to send to. If ntfy itself is
|
||||||
|
unreachable at that moment, the failure shows up only in the journal
|
||||||
|
(`journalctl -u kernelwatch-backup-failed`). It can't tell you that the timer
|
||||||
|
never ran at all, for example because the host was down; that needs a heartbeat
|
||||||
|
monitor. You can check delivery with
|
||||||
|
`sudo kernelwatch notify-backup-failure`, which sends the same message.
|
||||||
|
|
||||||
These copies sit on the dashboard host, so they protect against a corrupted or
|
These copies sit on the dashboard host, so they protect against a corrupted or
|
||||||
mistakenly changed database but not against losing the machine. Copy
|
mistakenly changed database but not against losing the machine. Copy
|
||||||
`/var/lib/kernelwatch/backups/` elsewhere with whatever you already back up with.
|
`/var/lib/kernelwatch/backups/` elsewhere with whatever you already back up with.
|
||||||
|
|||||||
+2
-1
@@ -45,7 +45,8 @@ install -d -m 0750 -o kernelwatch -g kernelwatch "$root/var/lib/kernelwatch"
|
|||||||
|
|
||||||
install -m 0644 "$here/kernelwatch.service" "$root/etc/systemd/system/"
|
install -m 0644 "$here/kernelwatch.service" "$root/etc/systemd/system/"
|
||||||
install -m 0644 "$here/kernelwatch-alerts.service" "$here/kernelwatch-alerts.timer" \
|
install -m 0644 "$here/kernelwatch-alerts.service" "$here/kernelwatch-alerts.timer" \
|
||||||
"$here/kernelwatch-backup.service" "$here/kernelwatch-backup.timer" "$root/etc/systemd/system/"
|
"$here/kernelwatch-backup.service" "$here/kernelwatch-backup.timer" \
|
||||||
|
"$here/kernelwatch-backup-failed.service" "$root/etc/systemd/system/"
|
||||||
systemctl daemon-reload
|
systemctl daemon-reload
|
||||||
systemctl enable kernelwatch.service
|
systemctl enable kernelwatch.service
|
||||||
systemctl restart kernelwatch.service
|
systemctl restart kernelwatch.service
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Notify that the kernelwatch backup failed
|
||||||
|
Wants=network-online.target
|
||||||
|
After=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
User=kernelwatch
|
||||||
|
Group=kernelwatch
|
||||||
|
Environment=KERNELWATCH_CONFIG=/etc/kernelwatch/server.toml
|
||||||
|
ExecStart=/usr/bin/python3 -I /opt/kernelwatch/kernelwatch-server notify-backup-failure
|
||||||
|
TimeoutStartSec=2min
|
||||||
|
StateDirectory=kernelwatch
|
||||||
|
StateDirectoryMode=0750
|
||||||
|
|
||||||
|
CapabilityBoundingSet=
|
||||||
|
AmbientCapabilities=
|
||||||
|
NoNewPrivileges=yes
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=yes
|
||||||
|
PrivateTmp=yes
|
||||||
|
PrivateDevices=yes
|
||||||
|
ProtectKernelTunables=yes
|
||||||
|
ProtectKernelModules=yes
|
||||||
|
ProtectKernelLogs=yes
|
||||||
|
ProtectControlGroups=yes
|
||||||
|
ProtectClock=yes
|
||||||
|
ProtectHostname=yes
|
||||||
|
ProtectProc=invisible
|
||||||
|
RestrictNamespaces=yes
|
||||||
|
RestrictRealtime=yes
|
||||||
|
RestrictSUIDSGID=yes
|
||||||
|
LockPersonality=yes
|
||||||
|
MemoryDenyWriteExecute=yes
|
||||||
|
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
|
||||||
|
SystemCallArchitectures=native
|
||||||
|
SystemCallFilter=@system-service
|
||||||
|
UMask=0077
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
[Unit]
|
[Unit]
|
||||||
Description=Back up the kernelwatch database
|
Description=Back up the kernelwatch database
|
||||||
|
# Any failure, including the timeout, an OOM kill or a crash, sends an ntfy
|
||||||
|
# message (a no-op if ntfy isn't configured).
|
||||||
|
OnFailure=kernelwatch-backup-failed.service
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
Type=oneshot
|
Type=oneshot
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import fcntl
|
import fcntl
|
||||||
|
import socket
|
||||||
import sqlite3
|
import sqlite3
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
@@ -158,3 +159,26 @@ def _check_status(cfg: Config, conn: sqlite3.Connection) -> int:
|
|||||||
db.save_status_alert(conn, name, level, since, level)
|
db.save_status_alert(conn, name, level, since, level)
|
||||||
print(f"kernelwatch: {level} notification sent for {name}")
|
print(f"kernelwatch: {level} notification sent for {name}")
|
||||||
return failures
|
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
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_notify_backup_failure(cfg, args) -> int:
|
||||||
|
return alerts.notify_backup_failure(cfg)
|
||||||
|
|
||||||
|
|
||||||
def cmd_backup(cfg, args) -> int:
|
def cmd_backup(cfg, args) -> int:
|
||||||
db.init(cfg.db_path)
|
db.init(cfg.db_path)
|
||||||
try:
|
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 = sub.add_parser("backup", help="write a consistent copy of the database to PATH")
|
||||||
p.add_argument("path")
|
p.add_argument("path")
|
||||||
p.set_defaults(func=cmd_backup)
|
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 "
|
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)
|
"(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$")
|
_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:
|
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),
|
"""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
|
replacing that day's file, then delete dated backups that are keep_days or more
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ report_retention_days = 30
|
|||||||
# and deletes copies this many days old or older (0 keeps them all). Keep the
|
# and deletes copies this many days old or older (0 keeps them all). Keep the
|
||||||
# directory under /var/lib/kernelwatch; the unit can't write elsewhere. Copy the
|
# directory under /var/lib/kernelwatch; the unit can't write elsewhere. Copy the
|
||||||
# files off this machine yourself: they don't protect against losing it.
|
# files off this machine yourself: they don't protect against losing it.
|
||||||
|
# A failed backup run sends an ntfy message (if ntfy_url is set).
|
||||||
backup_dir = "/var/lib/kernelwatch/backups"
|
backup_dir = "/var/lib/kernelwatch/backups"
|
||||||
backup_keep_days = 7
|
backup_keep_days = 7
|
||||||
|
|
||||||
|
|||||||
@@ -341,6 +341,56 @@ class StatusAlertsTest(unittest.TestCase):
|
|||||||
self.assertEqual(db.status_alerts(self.conn), {})
|
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):
|
class NtfyHTTPTest(unittest.TestCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
class Sink(BaseHTTPRequestHandler):
|
class Sink(BaseHTTPRequestHandler):
|
||||||
|
|||||||
@@ -329,6 +329,15 @@ class ServerInstallTest(InstallCase):
|
|||||||
for command in commands:
|
for command in commands:
|
||||||
self.assertRegex(help_text, rf"\b{re.escape(command)}\b")
|
self.assertRegex(help_text, rf"\b{re.escape(command)}\b")
|
||||||
|
|
||||||
|
def test_on_failure_targets_are_shipped_units(self):
|
||||||
|
"""A typo'd OnFailure= is silently ignored by systemd, so check the names."""
|
||||||
|
units = {n for n in os.listdir(SERVER_DIR) if n.endswith((".service", ".timer"))}
|
||||||
|
targets = set()
|
||||||
|
for unit in units:
|
||||||
|
targets.update(re.findall(r"^OnFailure=(\S+)$", read(os.path.join(SERVER_DIR, unit)), re.M))
|
||||||
|
self.assertIn("kernelwatch-backup-failed.service", targets)
|
||||||
|
self.assertEqual(sorted(targets - units), [])
|
||||||
|
|
||||||
def test_existing_user_is_not_recreated(self):
|
def test_existing_user_is_not_recreated(self):
|
||||||
self.install(KW_ID_RC="0")
|
self.install(KW_ID_RC="0")
|
||||||
self.assertFalse([c for c in self.calls() if c.startswith("useradd")])
|
self.assertFalse([c for c in self.calls() if c.startswith("useradd")])
|
||||||
|
|||||||
Reference in new issue
Block a user