Files
kernel-automation/tests/test_unit_result.py
T
patrickandClaude Opus 5.5 f88261d2f5 Report when kernelwatch's own helper units keep failing
kernelwatch-apt-update.service failed hourly on most hosts for weeks
without anything showing it. The agent only Wants= its helper units, so
the report goes out regardless, with stale lists or (for needrestart)
results that quietly turn "unknown".

Each helper (apt-update, needrestart) now runs kernelwatch-unit-result
as its ExecStopPost=, which systemd runs after failed runs too. It
writes "RESULT EXIT_CODE EXIT_STATUS FAILURES" to
/run/kernelwatch/<name>.result, FAILURES counting failed runs in a row.
The agent (0.10.0) reports results from the last two hours as
helper_units. On the server, one or two failures are a note (an admin's
apt can hold the lock now and then); three in a row put the host in
update, naming the unit and its exit status and pointing at journalctl.
The host page gets a "kernelwatch helpers" row.

The Livepatch unit isn't tracked: it fails by design where the snap is
installed but Livepatch isn't enabled, and Livepatch has its own check.

The apt-update unit now has RuntimeDirectory=kernelwatch (preserved,
like the others) for its result file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 15:23:05 -05:00

103 lines
4.5 KiB
Python

"""kernelwatch-unit-result, the helper units' ExecStopPost=, and how they use it."""
import os
import re
import subprocess
import unittest
from helpers import REPO, tempdir
AGENT_DIR = os.path.join(REPO, "agent")
SCRIPT = os.path.join(AGENT_DIR, "kernelwatch-unit-result")
def read(name):
with open(os.path.join(AGENT_DIR, name)) as f:
return f.read()
class UnitResultTest(unittest.TestCase):
def setUp(self):
self._tmp = tempdir()
self.dir = self._tmp.name
def tearDown(self):
self._tmp.cleanup()
def run_script(self, *args, **env):
return subprocess.run(["sh", SCRIPT, *args], capture_output=True, text=True, timeout=10,
env={"PATH": os.environ["PATH"], "KERNELWATCH_RUN_DIR": self.dir, **env})
def ended(self, result, code="exited", status="0"):
proc = self.run_script("apt-update", SERVICE_RESULT=result, EXIT_CODE=code, EXIT_STATUS=status)
self.assertEqual(proc.returncode, 0, proc.stderr)
with open(os.path.join(self.dir, "apt-update.result")) as f:
return f.read()
def test_success(self):
self.assertEqual(self.ended("success"), "success exited 0 0\n")
def test_failures_in_a_row_are_counted_and_reset_by_a_success(self):
self.assertEqual(self.ended("exit-code", status="100"), "exit-code exited 100 1\n")
self.assertEqual(self.ended("exit-code", status="100"), "exit-code exited 100 2\n")
self.assertEqual(self.ended("timeout", "killed", "TERM"), "timeout killed TERM 3\n")
self.assertEqual(self.ended("success"), "success exited 0 0\n")
self.assertEqual(self.ended("exit-code", status="1"), "exit-code exited 1 1\n")
self.assertFalse(os.path.exists(os.path.join(self.dir, "apt-update.result.new")))
def test_garbage_in_the_old_file_restarts_the_count(self):
with open(os.path.join(self.dir, "apt-update.result"), "w") as f:
f.write("exit-code exited 100 lots\n")
self.assertEqual(self.ended("exit-code", status="100"), "exit-code exited 100 1\n")
def test_missing_variables(self):
proc = self.run_script("needrestart")
self.assertEqual(proc.returncode, 0, proc.stderr)
with open(os.path.join(self.dir, "needrestart.result")) as f:
self.assertEqual(f.read(), "- - - 1\n", "no SERVICE_RESULT isn't a success")
def test_bad_names_are_refused(self):
for name in ("", "../etc/passwd", "Apt", "a b"):
with self.subTest(name=name):
self.assertEqual(self.run_script(name).returncode, 2)
self.assertEqual(os.listdir(self.dir), [])
class HelperUnitsTest(unittest.TestCase):
def recorded_units(self):
"""Units that record their result, by the name they record it under."""
found = {}
for unit in os.listdir(AGENT_DIR):
if unit.endswith(".service"):
m = re.search(r"^ExecStopPost=/usr/local/sbin/kernelwatch-unit-result (\S+)$",
read(unit), re.M)
if m:
found[m.group(1)] = unit
return found
def test_agent_reads_every_recorded_unit(self):
names = re.search(r"^HELPER_UNITS=\(([^)]*)\)", read("kernelwatch-agent"), re.M).group(1).split()
self.assertEqual(sorted(self.recorded_units()), sorted(names))
self.assertEqual(self.recorded_units(), {"apt-update": "kernelwatch-apt-update.service",
"needrestart": "kernelwatch-needrestart.service"})
def test_units_sharing_the_runtime_directory_keep_it(self):
# Without RuntimeDirectoryPreserve, stopping one unit would delete the others'
# results (and its own .result, just after writing it).
for unit in os.listdir(AGENT_DIR):
if unit.endswith(".service") and "RuntimeDirectory=kernelwatch" in read(unit):
with self.subTest(unit=unit):
self.assertIn("\nRuntimeDirectoryPreserve=yes\n", read(unit))
for unit in self.recorded_units().values():
self.assertIn("\nRuntimeDirectory=kernelwatch\n", read(unit))
def test_the_agent_unit_pulls_the_helpers_in_without_depending_on_them(self):
agent = read("kernelwatch-agent.service")
for unit in self.recorded_units().values():
self.assertRegex(agent, rf"(?m)^Wants=.*\b{re.escape(unit)}\b")
self.assertNotRegex(agent, rf"(?m)^(Requires|Requisite|BindsTo)=.*\b{re.escape(unit)}\b")
if __name__ == "__main__":
unittest.main()