heartbeat_url is pinged after every alert check that sent its notifications without failures, and backup_heartbeat_url after every successful nightly backup, so an external monitor (healthchecks.io, Uptime Kuma) notices when the alert timer or the backup stops running. A failing heartbeat is logged without the URL and never fails the work it reports on. kernelwatch test-heartbeat pings each configured URL once. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
195 lines
8.5 KiB
Python
195 lines
8.5 KiB
Python
"""Heartbeat pings: real HTTP requests to a local server, and when the commands send them."""
|
|
|
|
import contextlib
|
|
import io
|
|
import os
|
|
import threading
|
|
import unittest
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from unittest import mock
|
|
|
|
from helpers import tempdir
|
|
from kernelwatch import alerts, cli, config
|
|
|
|
SECRET = "0f1e2d3c-secret-uuid"
|
|
|
|
|
|
class HeartbeatCase(unittest.TestCase):
|
|
def setUp(self):
|
|
class Sink(BaseHTTPRequestHandler):
|
|
def do_GET(self):
|
|
self.server.hits.append((self.path, dict(self.headers)))
|
|
self.send_response(self.server.code)
|
|
if self.server.code in (301, 302):
|
|
self.send_header("Location", "/elsewhere")
|
|
self.send_header("Content-Length", "0")
|
|
self.end_headers()
|
|
|
|
def log_message(self, *args):
|
|
pass
|
|
|
|
self.server = ThreadingHTTPServer(("127.0.0.1", 0), Sink)
|
|
self.server.hits, self.server.code = [], 200
|
|
threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.01},
|
|
daemon=True).start()
|
|
self.addCleanup(self.server.server_close)
|
|
self.addCleanup(self.server.shutdown)
|
|
self.base = f"http://127.0.0.1:{self.server.server_port}"
|
|
self.hits = self.server.hits
|
|
stack = contextlib.ExitStack()
|
|
self.addCleanup(stack.close)
|
|
self.out = stack.enter_context(contextlib.redirect_stdout(io.StringIO()))
|
|
self.err = stack.enter_context(contextlib.redirect_stderr(io.StringIO()))
|
|
|
|
|
|
class PingTest(HeartbeatCase):
|
|
def test_get_with_path_and_query_intact(self):
|
|
self.assertTrue(alerts.ping(f"{self.base}/ping/{SECRET}?status=up&msg=OK"))
|
|
self.assertEqual([h[0] for h in self.hits], [f"/ping/{SECRET}?status=up&msg=OK"])
|
|
self.assertEqual(self.hits[0][1]["User-Agent"], "kernelwatch")
|
|
|
|
def test_any_2xx_is_success(self):
|
|
for code in (200, 201, 204):
|
|
self.server.code = code
|
|
self.assertTrue(alerts.ping(f"{self.base}/p"), code)
|
|
|
|
def test_other_statuses_fail_without_leaking_the_url(self):
|
|
for code in (302, 400, 404, 429, 500, 503):
|
|
with self.subTest(code=code):
|
|
self.server.code = code
|
|
self.assertFalse(alerts.ping(f"{self.base}/ping/{SECRET}"))
|
|
self.assertEqual(len(self.hits), 6, "redirects must not be followed")
|
|
self.assertIn("HTTP 503", self.err.getvalue())
|
|
self.assertNotIn(SECRET, self.err.getvalue() + self.out.getvalue())
|
|
|
|
def test_unreachable_server_fails_without_leaking_the_url(self):
|
|
self.server.shutdown()
|
|
self.server.server_close()
|
|
self.assertFalse(alerts.ping(f"{self.base}/ping/{SECRET}"))
|
|
self.assertIn("heartbeat request failed", self.err.getvalue())
|
|
self.assertNotIn(SECRET, self.err.getvalue())
|
|
|
|
def test_timeout_is_bounded(self):
|
|
with mock.patch("kernelwatch.alerts.build_opener") as opener:
|
|
opener.return_value.open.side_effect = TimeoutError(f"timed out {SECRET}")
|
|
self.assertFalse(alerts.ping(f"https://hc.example/{SECRET}"))
|
|
self.assertEqual(opener.return_value.open.call_args.kwargs["timeout"],
|
|
alerts.HEARTBEAT_TIMEOUT_SECONDS)
|
|
self.assertNotIn(SECRET, self.err.getvalue())
|
|
|
|
|
|
class CommandsTest(HeartbeatCase):
|
|
def setUp(self):
|
|
super().setUp()
|
|
self.tmp = tempdir()
|
|
self.addCleanup(self.tmp.cleanup)
|
|
self.config_path = os.path.join(self.tmp.name, "server.toml")
|
|
|
|
def configure(self, **values):
|
|
lines = [f'db_path = "{self.tmp.name}/kw.db"', f'backup_dir = "{self.tmp.name}/backups"']
|
|
lines += [f'{k} = "{v}"' for k, v in values.items()]
|
|
with open(self.config_path, "w") as f:
|
|
f.write("\n".join(lines) + "\n")
|
|
|
|
def run_cli(self, *args):
|
|
return cli.main(["-c", self.config_path, *args])
|
|
|
|
def test_check_alerts_pings_after_a_clean_run(self):
|
|
self.configure(heartbeat_url=f"{self.base}/hb")
|
|
self.assertEqual(self.run_cli("check-alerts"), 0)
|
|
self.assertEqual([h[0] for h in self.hits], ["/hb"])
|
|
|
|
def test_check_alerts_pings_even_without_ntfy(self):
|
|
# The timer is still alive, which is what the heartbeat reports.
|
|
self.configure(heartbeat_url=f"{self.base}/hb")
|
|
with mock.patch("kernelwatch.alerts.publish") as publish:
|
|
self.run_cli("check-alerts")
|
|
publish.assert_not_called()
|
|
self.assertEqual(len(self.hits), 1)
|
|
|
|
def test_no_ping_when_notifications_failed(self):
|
|
self.configure(heartbeat_url=f"{self.base}/hb")
|
|
with mock.patch("kernelwatch.cli.alerts.check", return_value=2):
|
|
self.assertEqual(self.run_cli("check-alerts"), 1)
|
|
self.assertEqual(self.hits, [])
|
|
|
|
def test_no_ping_when_the_check_crashes(self):
|
|
self.configure(heartbeat_url=f"{self.base}/hb")
|
|
with mock.patch("kernelwatch.cli.alerts.check", side_effect=RuntimeError("db locked")):
|
|
with self.assertRaises(RuntimeError):
|
|
self.run_cli("check-alerts")
|
|
self.assertEqual(self.hits, [])
|
|
|
|
def test_nothing_is_pinged_unless_configured(self):
|
|
self.configure()
|
|
self.assertEqual(self.run_cli("check-alerts"), 0)
|
|
self.assertEqual(self.run_cli("scheduled-backup"), 0)
|
|
self.assertEqual(self.hits, [])
|
|
|
|
def test_a_dead_heartbeat_never_fails_the_check(self):
|
|
self.server.code = 500
|
|
self.configure(heartbeat_url=f"{self.base}/hb")
|
|
self.assertEqual(self.run_cli("check-alerts"), 0)
|
|
self.assertIn("HTTP 500", self.err.getvalue())
|
|
|
|
def test_backup_pings_its_own_url_only_on_success(self):
|
|
self.configure(heartbeat_url=f"{self.base}/alerts", backup_heartbeat_url=f"{self.base}/backup")
|
|
self.assertEqual(self.run_cli("scheduled-backup"), 0)
|
|
self.assertEqual([h[0] for h in self.hits], ["/backup"])
|
|
del self.hits[:]
|
|
with mock.patch("kernelwatch.db.rotate_backups", side_effect=OSError("disk full")):
|
|
self.assertEqual(self.run_cli("scheduled-backup"), 1)
|
|
self.assertEqual(self.hits, [])
|
|
|
|
def test_a_dead_backup_heartbeat_never_fails_the_backup(self):
|
|
self.server.code = 503
|
|
self.configure(backup_heartbeat_url=f"{self.base}/backup")
|
|
self.assertEqual(self.run_cli("scheduled-backup"), 0)
|
|
self.assertTrue(os.listdir(os.path.join(self.tmp.name, "backups")))
|
|
|
|
def test_manual_backup_does_not_ping(self):
|
|
self.configure(backup_heartbeat_url=f"{self.base}/backup")
|
|
self.assertEqual(self.run_cli("backup", os.path.join(self.tmp.name, "manual.db")), 0)
|
|
self.assertEqual(self.hits, [])
|
|
|
|
def test_test_heartbeat_reports_each_url(self):
|
|
self.configure(heartbeat_url=f"{self.base}/a", backup_heartbeat_url=f"{self.base}/b")
|
|
self.assertEqual(self.run_cli("test-heartbeat"), 0)
|
|
self.assertEqual(self.out.getvalue().splitlines(), ["heartbeat_url: ok", "backup_heartbeat_url: ok"])
|
|
self.server.code = 404
|
|
self.assertEqual(self.run_cli("test-heartbeat"), 1)
|
|
self.assertIn("heartbeat_url: FAILED", self.out.getvalue())
|
|
|
|
def test_test_heartbeat_needs_a_url(self):
|
|
self.configure()
|
|
self.assertEqual(self.run_cli("test-heartbeat"), 1)
|
|
self.assertIn("neither heartbeat_url nor backup_heartbeat_url", self.err.getvalue())
|
|
|
|
|
|
class ConfigTest(unittest.TestCase):
|
|
def load(self, text):
|
|
with tempdir() as tmp:
|
|
path = os.path.join(tmp, "server.toml")
|
|
with open(path, "w") as f:
|
|
f.write(text)
|
|
return config.load(path)
|
|
|
|
def test_accepts_plain_and_query_urls(self):
|
|
for url in ("https://hc-ping.com/0f1e2d3c", "http://kuma.example:3001/api/push/abc?status=up&msg=OK&ping="):
|
|
cfg = self.load(f'heartbeat_url = "{url}"\nbackup_heartbeat_url = "{url}"\n')
|
|
self.assertEqual((cfg.heartbeat_url, cfg.backup_heartbeat_url), (url, url))
|
|
|
|
def test_defaults_to_disabled(self):
|
|
self.assertEqual((config.Config().heartbeat_url, config.Config().backup_heartbeat_url), ("", ""))
|
|
|
|
def test_rejects_bad_urls(self):
|
|
for key in ("heartbeat_url", "backup_heartbeat_url"):
|
|
for bad in ("hc-ping.com/x", "ftp://hc.example/x", "https://", "https://hc.example/a b",
|
|
"https://hc.example/x#frag", "https://hc.example:0/x", "https://hc.example:bad/x"):
|
|
with self.subTest(key=key, bad=bad), self.assertRaises(SystemExit):
|
|
self.load(f'{key} = "{bad}"\n')
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|