From f88261d2f590632e6494784ac719626ea958b6ba Mon Sep 17 00:00:00 2001 From: patrick Date: Sun, 1 Nov 2026 15:23:05 -0500 Subject: [PATCH 1/4] 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/.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 --- Makefile | 2 +- agent/deploy.sh | 2 +- agent/install.sh | 1 + agent/kernelwatch-agent | 26 ++++++- agent/kernelwatch-apt-update.service | 7 ++ agent/kernelwatch-needrestart.service | 3 + agent/kernelwatch-unit-result | 29 ++++++++ docs/how-it-works.md | 16 +++- server/kernelwatch/__init__.py | 2 +- server/kernelwatch/report.py | 1 + server/kernelwatch/status.py | 47 ++++++++++++ server/kernelwatch/web.py | 17 ++++- tests/test_agent.py | 15 ++++ tests/test_deploy.py | 2 +- tests/test_install.py | 2 +- tests/test_status.py | 26 +++++++ tests/test_unit_result.py | 102 ++++++++++++++++++++++++++ tests/test_web.py | 11 +++ 18 files changed, 303 insertions(+), 8 deletions(-) create mode 100755 agent/kernelwatch-unit-result create mode 100644 tests/test_unit_result.py diff --git a/Makefile b/Makefile index f0db517..d671bf8 100644 --- a/Makefile +++ b/Makefile @@ -6,4 +6,4 @@ test: $(PYTHON) -m unittest discover -s tests lint: - shellcheck agent/kernelwatch-agent agent/install.sh agent/deploy.sh server/install.sh server/kernelwatch.sh + shellcheck agent/kernelwatch-agent agent/kernelwatch-unit-result agent/install.sh agent/deploy.sh server/install.sh server/kernelwatch.sh diff --git a/agent/deploy.sh b/agent/deploy.sh index fdd8e4f..dd2968e 100755 --- a/agent/deploy.sh +++ b/agent/deploy.sh @@ -21,7 +21,7 @@ CONF=${KERNELWATCH_DEPLOY_CONF:-$here/deploy.conf} HOSTS_FILE=${KERNELWATCH_HOSTS:-$here/hosts} FILES=(kernelwatch-agent kernelwatch-agent.service kernelwatch-agent.timer kernelwatch-needrestart.service kernelwatch-livepatch kernelwatch-livepatch.service - kernelwatch-apt-update.service install.sh) + kernelwatch-apt-update.service kernelwatch-unit-result install.sh) NAME_RE='^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$' SERVER_URL= diff --git a/agent/install.sh b/agent/install.sh index ae1f0f9..04c471c 100755 --- a/agent/install.sh +++ b/agent/install.sh @@ -82,6 +82,7 @@ mkdir -p "$root/usr/local/sbin" "$root/etc/systemd/system" install -d -m 0755 "$etc" install -m 0755 "$here/kernelwatch-agent" "$root/usr/local/sbin/kernelwatch-agent" install -m 0755 "$here/kernelwatch-livepatch" "$root/usr/local/sbin/kernelwatch-livepatch" +install -m 0755 "$here/kernelwatch-unit-result" "$root/usr/local/sbin/kernelwatch-unit-result" install -m 0644 "$here/kernelwatch-agent.service" "$here/kernelwatch-agent.timer" \ "$here/kernelwatch-needrestart.service" "$here/kernelwatch-livepatch.service" \ "$here/kernelwatch-apt-update.service" "$root/etc/systemd/system/" diff --git a/agent/kernelwatch-agent b/agent/kernelwatch-agent index 40c10ea..47f37b6 100755 --- a/agent/kernelwatch-agent +++ b/agent/kernelwatch-agent @@ -6,7 +6,7 @@ # rules can change without redeploying agents. set -euo pipefail -AGENT_VERSION=0.9.0 +AGENT_VERSION=0.10.0 # Prefix for every file the agent reads. Only the test suite sets this. ROOT=${KERNELWATCH_ROOT:-} @@ -180,6 +180,29 @@ read_livepatch() { done <"$LIVEPATCH_FILE" } +# How kernelwatch's helper units last ended, as recorded by kernelwatch-unit-result +# (their ExecStopPost=): one "NAME RESULT EXIT_CODE EXIT_STATUS FAILURES" line per +# unit that ran recently, e.g. "apt-update exit-code exited 100 3", FAILURES being +# failed runs in a row. This unit only Wants= them, so when they fail the report +# still goes out, with stale or missing data, and nothing else would say why. +# Livepatch isn't listed: its unit fails by design where the snap is installed +# but Livepatch isn't enabled, and its health is reported on its own. +HELPER_UNITS=(apt-update needrestart) +HELPER_MAX_AGE=7200 +helper_units() { + local name file mtime now result= code= status= failures= + now=$(date +%s) + for name in "${HELPER_UNITS[@]}"; do + file=$ROOT/run/kernelwatch/$name.result + mtime=$(stat -c %Y "$file" 2>/dev/null) || continue + ((now - mtime <= HELPER_MAX_AGE)) || continue + read -r result code status failures _ <"$file" || [[ -n $result ]] || continue + [[ $result =~ ^[a-z-]{1,32}$ && $code =~ ^[a-z-]{1,16}$ && + $status =~ ^[A-Za-z0-9-]{1,16}$ && $failures =~ ^[0-9]{1,6}$ ]] || continue + printf '%s %s %s %s %s\n' "$name" "$result" "$code" "$status" "$failures" + done +} + # String, or null when empty. json_str_or_null() { if [[ -n $1 ]]; then json_str "$1"; else printf 'null'; fi @@ -446,6 +469,7 @@ build_report() { printf '"apt_lists_age_seconds":%s,' "$(json_int "$(apt_lists_age)")" printf '"security_repo_suite":%s,' "$(json_str_or_null "$sec_suite")" printf '"security_repo_age_seconds":%s,' "$(json_int "$sec_age")" + printf '"helper_units":%s,' "$(helper_units | json_str_array)" printf '"uptime_seconds":%s' "$(json_int "$(uptime_seconds)")" printf '}\n' } diff --git a/agent/kernelwatch-apt-update.service b/agent/kernelwatch-apt-update.service index c2ea60b..11625c9 100644 --- a/agent/kernelwatch-apt-update.service +++ b/agent/kernelwatch-apt-update.service @@ -19,6 +19,13 @@ ExecStart=/usr/bin/apt-get -q update # age; Debian has nothing else that writes it. lists/partial, the agent's last # resort, changes even when the update fails. ExecStartPost=/bin/sh -c 'mkdir -p /var/lib/apt/periodic && touch /var/lib/apt/periodic/update-success-stamp' +# Records how the run ended, success or not, so the agent can report failures, +# which are otherwise silent while apt-daily keeps the lists fresh. +ExecStopPost=/usr/local/sbin/kernelwatch-unit-result apt-update +RuntimeDirectory=kernelwatch +RuntimeDirectoryMode=0755 +RuntimeDirectoryPreserve=yes +UMask=0022 TimeoutStartSec=5min Nice=10 IOSchedulingClass=idle diff --git a/agent/kernelwatch-needrestart.service b/agent/kernelwatch-needrestart.service index ca2b1f5..c78d615 100644 --- a/agent/kernelwatch-needrestart.service +++ b/agent/kernelwatch-needrestart.service @@ -8,6 +8,9 @@ ConditionPathExists=/usr/sbin/needrestart Type=oneshot # -b batch output, -r l list only: never restarts anything. ExecStart=/bin/sh -c 'needrestart -b -r l > /run/kernelwatch/needrestart.new && mv /run/kernelwatch/needrestart.new /run/kernelwatch/needrestart' +# Records how the run ended, success or not, so the agent can report failures: +# otherwise the results just go missing and the dashboard shows "unknown". +ExecStopPost=/usr/local/sbin/kernelwatch-unit-result needrestart RuntimeDirectory=kernelwatch RuntimeDirectoryMode=0755 RuntimeDirectoryPreserve=yes diff --git a/agent/kernelwatch-unit-result b/agent/kernelwatch-unit-result new file mode 100755 index 0000000..7d42773 --- /dev/null +++ b/agent/kernelwatch-unit-result @@ -0,0 +1,29 @@ +#!/bin/sh +# Records how a kernelwatch helper unit's run ended, for the agent to report. +# Run as the unit's ExecStopPost=, which systemd runs after every run, failed or +# not, with SERVICE_RESULT, EXIT_CODE and EXIT_STATUS set (systemd.exec(5)). +# +# Usage: kernelwatch-unit-result NAME +# Writes /run/kernelwatch/NAME.result as "RESULT EXIT_CODE EXIT_STATUS FAILURES", +# e.g. "exit-code exited 100 3", where FAILURES counts failed runs in a row and +# is 0 after a success. A missing value is written as "-". +set -u + +name=${1:-} +case $name in +'' | *[!a-z0-9-]*) + echo "usage: kernelwatch-unit-result NAME" >&2 + exit 2 + ;; +esac +file=${KERNELWATCH_RUN_DIR:-/run/kernelwatch}/$name.result + +result=${SERVICE_RESULT:--} +failures=0 +if [ "$result" != success ]; then + failures=$(awk '$4 ~ /^[0-9]+$/ { print $4 }' "$file" 2>/dev/null) + failures=$((${failures:-0} + 1)) +fi + +printf '%s %s %s %s\n' "$result" "${EXIT_CODE:--}" "${EXIT_STATUS:--}" "$failures" >"$file.new" && + mv "$file.new" "$file" diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 488c2e0..34c320d 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -10,7 +10,7 @@ Each host gets one status. When several apply, the worst one wins: |----------|---------| | `stale` | No report in `stale_after_hours` (default 3h), or never. Other data can't be trusted. | | `reboot` | A newer kernel is installed but not running, or `/run/reboot-required` exists. | -| `update` | A kernel or security update is available but not installed, services are running outdated libraries and need a restart, or apt's package lists are too old (`apt_stale_after_hours`) for "no updates" to mean anything. Also when `/boot` has less than `boot_min_free_mb` free, dpkg left packages half-installed, the OS release no longer gets security updates, unattended-upgrades is enabled but hasn't succeeded in `unattended_upgrades_stale_after_days`, or the release's security repository is missing from apt or hasn't refreshed in `security_repo_stale_after_days`. | +| `update` | A kernel or security update is available but not installed, services are running outdated libraries and need a restart, or apt's package lists are too old (`apt_stale_after_hours`) for "no updates" to mean anything. Also when `/boot` has less than `boot_min_free_mb` free, dpkg left packages half-installed, the OS release no longer gets security updates, unattended-upgrades is enabled but hasn't succeeded in `unattended_upgrades_stale_after_days`, the release's security repository is missing from apt or hasn't refreshed in `security_repo_stale_after_days`, or one of kernelwatch's own helper units has failed three runs in a row. | | `ok` | Running the newest installed kernel, with no security or kernel updates pending. | Each row also lists the reasons behind its status, and clicking a host shows @@ -54,6 +54,20 @@ How the agent works it out: root and a snap cgroup, so like needrestart it runs in its own unit, `kernelwatch-livepatch.service`, which writes `/run/kernelwatch/livepatch` before each report. It's skipped when the snap isn't installed. +- **kernelwatch's own helpers**: `kernelwatch-apt-update.service` and + `kernelwatch-needrestart.service` run as root just before each report. The + agent only `Wants=` them, so if they fail the report still goes out, with + stale lists or no needrestart results, and nothing would say why. So each one + records how its run ended (`ExecStopPost=kernelwatch-unit-result`, in + `/run/kernelwatch/.result`), counting failures in a row, and the agent + reports it. One or two failures are a note, since one run can fail now and + then (an admin's apt holding the lock). Three in a row, about three hours, + put the host in `update`: "kernelwatch-apt-update.service failed its last 3 + runs (exit status 100); see journalctl -u kernelwatch-apt-update.service". + The host page's "kernelwatch helpers" row shows each one. 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. Agents before 0.10.0 don't + report it. - **Agent version**: each report includes it. Hosts running an older agent than the server shipped with get a note to run `agent/deploy.sh`; their status isn't changed. diff --git a/server/kernelwatch/__init__.py b/server/kernelwatch/__init__.py index 7f1f5fa..c86f8e4 100644 --- a/server/kernelwatch/__init__.py +++ b/server/kernelwatch/__init__.py @@ -4,4 +4,4 @@ __version__ = "0.4.0" # Version of agent/kernelwatch-agent shipped alongside this server; older agents # are noted on the dashboard. tests/test_status.py checks the two stay in sync. -AGENT_VERSION = "0.9.0" +AGENT_VERSION = "0.10.0" diff --git a/server/kernelwatch/report.py b/server/kernelwatch/report.py index 6fe5581..19d62be 100644 --- a/server/kernelwatch/report.py +++ b/server/kernelwatch/report.py @@ -54,6 +54,7 @@ FIELDS: dict[str, str] = { "apt_lists_age_seconds": "int", "security_repo_suite": "str", "security_repo_age_seconds": "int", + "helper_units": "strlist", "uptime_seconds": "int", } diff --git a/server/kernelwatch/status.py b/server/kernelwatch/status.py index 0ac9911..36825ed 100644 --- a/server/kernelwatch/status.py +++ b/server/kernelwatch/status.py @@ -218,6 +218,46 @@ def security_repo_problem(report: dict[str, Any], cfg: Config, today: date) -> s f"run apt update and look for errors about {suite}") +# kernelwatch's helper units (apt-update, needrestart) run before every report, so +# about hourly. This many failures in a row put the host in update; fewer are a +# note, since one can fail now and then (apt's lock held by an admin's apt run). +HELPER_FAILURES_BEFORE_PROBLEM = 3 + + +def helper_units(report: dict[str, Any]) -> list[tuple[str, str, str, str, int]]: + """(name, result, exit code, exit status, failures in a row) for each helper unit + the agent reported. Agents before 0.10.0 report none.""" + out = [] + for entry in report.get("helper_units") or []: + parts = entry.split() + if len(parts) == 5 and parts[4].isdigit(): + out.append((*parts[:4], int(parts[4]))) + return out + + +def helper_failure(result: str, code: str, status: str) -> str: + """How a helper unit's run failed, in words.""" + if code == "exited": + return f"exit status {status}" + if code in ("killed", "dumped"): + return f"{result}, signal {status}" + return result + + +def helper_unit_problems(report: dict[str, Any]) -> list[tuple[bool, str]]: + """(is it a problem, why) for each kernelwatch helper unit whose last run failed.""" + found = [] + for name, result, code, status, failures in helper_units(report): + if result == "success" or not failures: + continue + unit = f"kernelwatch-{name}.service" + runs = "run" if failures == 1 else f"{failures} runs" + found.append((failures >= HELPER_FAILURES_BEFORE_PROBLEM, + f"{unit} failed its last {runs} ({helper_failure(result, code, status)}); " + f"see journalctl -u {unit}")) + return found + + def _kernel_only_reboot_file(report: dict[str, Any]) -> bool: """/run/reboot-required exists only because of kernel packages.""" pkgs = report.get("reboot_required_pkgs") or [] @@ -324,6 +364,13 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float, status.raise_to("update", f"package lists {apt_age / 86400:.0f}d old; apt update not running?") if why := security_repo_problem(report, cfg, datetime.fromtimestamp(now, timezone.utc).date()): status.raise_to("update", why) + # A failing helper leaves its data stale or missing, which the checks above may + # read as fine (needrestart's results just go "unknown"). + for problem, why in helper_unit_problems(report): + if problem: + status.raise_to("update", why) + else: + status.note(why) if host and (reported := hostname_mismatch(host, report)): status.note(f"registered as {host} but reports itself as {reported}; " diff --git a/server/kernelwatch/web.py b/server/kernelwatch/web.py index e94abcc..ed0aaa1 100644 --- a/server/kernelwatch/web.py +++ b/server/kernelwatch/web.py @@ -22,7 +22,7 @@ from urllib.parse import parse_qs, quote, unquote, urlsplit from . import __version__, auth, db, support from .config import Config from .report import MAX_BODY_BYTES, ReportError, sanitize -from .status import LEVELS, Status, evaluate +from .status import LEVELS, Status, evaluate, helper_failure, helper_units SESSION_COOKIE = "kw_session" HOST_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$") @@ -105,6 +105,20 @@ def security_repo_summary(report: dict[str, Any]) -> str | None: return f"{suite}, published {duration(age)} before the report" +def helper_units_summary(report: dict[str, Any]) -> str | None: + units = helper_units(report) + if not units: + return None # agents before 0.10.0, or nothing ran in the last two hours + parts = [] + for name, result, code, st, failures in units: + if result == "success" or not failures: + parts.append(f"{name}: ok") + else: + row = "" if failures == 1 else f", {failures} runs in a row" + parts.append(f"{name}: failed ({helper_failure(result, code, st)}{row})") + return ", ".join(parts) + + def phased_summary(report: dict[str, Any]) -> tuple[str, str]: """(short cell text, full description) for updates deferred by Ubuntu's phasing.""" if report.get("os_id") not in (None, "ubuntu"): @@ -538,6 +552,7 @@ class Handler(BaseHTTPRequestHandler): field("Package lists age", duration(r.get("apt_lists_age_seconds")) if r.get("apt_lists_age_seconds") is not None else None), field("Security repository", security_repo_summary(r)), + field("kernelwatch helpers", helper_units_summary(r)), field("Uptime", duration(r.get("uptime_seconds")) if r.get("uptime_seconds") is not None else None), field("Agent version", r.get("agent_version")), ]) diff --git a/tests/test_agent.py b/tests/test_agent.py index 4cb0323..60715f5 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -527,6 +527,21 @@ X self.assertIsNone(r["security_repo_suite"]) self.assertIsNone(r["security_repo_age_seconds"]) + def test_helper_units(self): + self.write_root("run/kernelwatch/apt-update.result", "exit-code exited 100 3\n") + self.write_root("run/kernelwatch/needrestart.result", "success exited 0 0\n") + self.write_root("run/kernelwatch/livepatch.result", "exit-code exited 1 9\n") # not a tracked helper + self.assertEqual(self.report()["helper_units"], + ["apt-update exit-code exited 100 3", "needrestart success exited 0 0"]) + + def test_helper_units_stale_or_garbled_results_ignored(self): + self.write_root("run/kernelwatch/apt-update.result", "exit-code exited 100 3\n", age=3 * 3600) + self.write_root("run/kernelwatch/needrestart.result", 'exit-code exited 1 "x\n') + self.assertEqual(self.report()["helper_units"], []) + + def test_no_helper_results(self): + self.assertEqual(self.report()["helper_units"], []) + def test_send_without_config_fails_cleanly(self): proc = self.run_agent() self.assertNotEqual(proc.returncode, 0) diff --git a/tests/test_deploy.py b/tests/test_deploy.py index 917dace..5ccb91a 100644 --- a/tests/test_deploy.py +++ b/tests/test_deploy.py @@ -60,7 +60,7 @@ class DeployTest(unittest.TestCase): for name in ("deploy.sh", "kernelwatch-agent", "kernelwatch-agent.service", "kernelwatch-agent.timer", "kernelwatch-needrestart.service", "kernelwatch-livepatch", "kernelwatch-livepatch.service", - "kernelwatch-apt-update.service"): + "kernelwatch-apt-update.service", "kernelwatch-unit-result"): shutil.copy2(os.path.join(AGENT_DIR, name), self.agent) write_exec(os.path.join(self.agent, "install.sh"), FAKE_INSTALL) diff --git a/tests/test_install.py b/tests/test_install.py index bf6c580..fffdd97 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -122,7 +122,7 @@ class AgentInstallTest(InstallCase): def test_installs_every_agent_script_and_unit(self): self.fresh() - for script in ("kernelwatch-agent", "kernelwatch-livepatch"): + for script in ("kernelwatch-agent", "kernelwatch-livepatch", "kernelwatch-unit-result"): installed = self.path("usr/local/sbin", script) self.assertEqual(read(installed), read(os.path.join(AGENT_DIR, script))) self.assertEqual(mode(installed), 0o755) diff --git a/tests/test_status.py b/tests/test_status.py index 7a7d89b..f1fe019 100644 --- a/tests/test_status.py +++ b/tests/test_status.py @@ -405,6 +405,32 @@ class EvaluateTest(unittest.TestCase): s = self.sec(age=10 * 86400, suite="jammy-security", os_id="ubuntu", os_version_id="22.04") self.assertEqual(s.level, "update") + def test_helper_units_healthy(self): + s = self.level(report(helper_units=["apt-update success exited 0 0", "needrestart success exited 0 0"])) + self.assertEqual((s.level, s.reasons), ("ok", [])) + + def test_helper_unit_failing_once_is_a_note(self): + s = self.level(report(helper_units=["apt-update exit-code exited 100 1"])) + self.assertEqual(s.level, "ok") + self.assertEqual(s.reasons, ["kernelwatch-apt-update.service failed its last run (exit status 100); " + "see journalctl -u kernelwatch-apt-update.service"]) + + def test_helper_unit_failing_repeatedly_is_a_problem(self): + s = self.level(report(helper_units=["apt-update exit-code exited 100 3", + "needrestart timeout killed TERM 5"])) + self.assertEqual(s.level, "update") + self.assertEqual(s.reasons, [ + "kernelwatch-apt-update.service failed its last 3 runs (exit status 100); " + "see journalctl -u kernelwatch-apt-update.service", + "kernelwatch-needrestart.service failed its last 5 runs (timeout, signal TERM); " + "see journalctl -u kernelwatch-needrestart.service"]) + + def test_helper_units_odd_entries_ignored(self): + s = self.level(report(helper_units=["apt-update exit-code", "x y z w many"])) + self.assertEqual((s.level, s.reasons), ("ok", [])) + s = self.level(report(helper_units=["needrestart resources - - 4"])) + self.assertIn("kernelwatch-needrestart.service failed its last 4 runs (resources)", s.reasons[0]) + def uu(self, success=6 * 3600, run=6 * 3600, state="enabled", **kw): return self.level(report(unattended_upgrades=state, unattended_upgrades_success_age_seconds=success, unattended_upgrades_run_age_seconds=run, **kw)) diff --git a/tests/test_unit_result.py b/tests/test_unit_result.py new file mode 100644 index 0000000..472e62e --- /dev/null +++ b/tests/test_unit_result.py @@ -0,0 +1,102 @@ +"""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() diff --git a/tests/test_web.py b/tests/test_web.py index 42a4fd8..62a3d6b 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -239,6 +239,17 @@ class DashboardTest(ServerCase): self.assertIn("noble-security: not in apt's sources", body) self.assertIn("apt has no noble-security repository", body) + def test_host_page_shows_helper_units(self): + self.add_user("admin", "a-long-password") + token = self.add_host("web01") + self.post_report(token, {"kernel_running": "6.8.0-136-generic", "apt_lists_age_seconds": 60, + "helper_units": ["apt-update exit-code exited 100 4", + "needrestart success exited 0 0"]}) + _, headers, _ = self.login("admin", "a-long-password") + body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2] + self.assertIn("apt-update: failed (exit status 100, 4 runs in a row), needrestart: ok", body) + self.assertIn("kernelwatch-apt-update.service failed its last 4 runs", body) + def test_login_dashboard_logout(self): self.add_user("admin", "a-long-password") token = self.add_host("web01") -- 2.54.1 From 46769421088fd1b1697db3a251623502a22e87e8 Mon Sep 17 00:00:00 2001 From: patrick Date: Sun, 1 Nov 2026 15:24:27 -0500 Subject: [PATCH 2/4] Report packages on hold, and flag held kernel packages A held package never upgrades, and apt's simulation leaves it out, so its updates (security ones included) appear nowhere. A leftover hold on linux-image-amd64 or linux-generic keeps a host on its kernel while it looks current. The agent reports installed held packages (dpkg's "hi") as held_packages. A held linux-* package puts the host in update with the apt-mark unhold hint; other holds, usually deliberate, get a note. The host page lists them. Co-Authored-By: Claude Opus 5.5 --- agent/kernelwatch-agent | 10 ++++++++++ docs/how-it-works.md | 11 ++++++++++- server/kernelwatch/report.py | 1 + server/kernelwatch/status.py | 15 +++++++++++++++ server/kernelwatch/web.py | 1 + tests/test_agent.py | 12 ++++++++++++ tests/test_status.py | 12 ++++++++++++ 7 files changed, 61 insertions(+), 1 deletion(-) diff --git a/agent/kernelwatch-agent b/agent/kernelwatch-agent index 47f37b6..b91d1ca 100755 --- a/agent/kernelwatch-agent +++ b/agent/kernelwatch-agent @@ -308,6 +308,15 @@ security_repo() { return 0 } +# Installed packages on hold (`apt-mark hold`, or dpkg's "hold" selection). apt +# never upgrades them and the simulation doesn't list them, so their updates, +# security ones included, don't show up anywhere else. +held_packages() { + dpkg-query -W -f='${db:Status-Abbrev}\t${binary:Package}\n' 2>/dev/null | + awk -F '\t' 'substr($1, 1, 2) == "hi" { print $2 }' | + sort -u || true +} + # Size and free space of the filesystem holding /boot, in KiB, as "SIZE FREE"; # empty if df can't tell. That's the root filesystem when /boot isn't its own # mount. A full /boot makes the next kernel's postinst fail, so the host stays @@ -456,6 +465,7 @@ build_report() { printf '"boot_size_kb":%s,' "$(json_int "$boot_size")" printf '"boot_free_kb":%s,' "$(json_int "$boot_free")" printf '"dpkg_unfinished_packages":%s,' "$(unfinished_packages | json_str_array)" + printf '"held_packages":%s,' "$(held_packages | json_str_array)" case $pro_attached in true | false) printf '"ubuntu_pro_attached":%s,' "$pro_attached" ;; *) printf '"ubuntu_pro_attached":null,' ;; diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 34c320d..d8e9f22 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -10,7 +10,7 @@ Each host gets one status. When several apply, the worst one wins: |----------|---------| | `stale` | No report in `stale_after_hours` (default 3h), or never. Other data can't be trusted. | | `reboot` | A newer kernel is installed but not running, or `/run/reboot-required` exists. | -| `update` | A kernel or security update is available but not installed, services are running outdated libraries and need a restart, or apt's package lists are too old (`apt_stale_after_hours`) for "no updates" to mean anything. Also when `/boot` has less than `boot_min_free_mb` free, dpkg left packages half-installed, the OS release no longer gets security updates, unattended-upgrades is enabled but hasn't succeeded in `unattended_upgrades_stale_after_days`, the release's security repository is missing from apt or hasn't refreshed in `security_repo_stale_after_days`, or one of kernelwatch's own helper units has failed three runs in a row. | +| `update` | A kernel or security update is available but not installed, services are running outdated libraries and need a restart, or apt's package lists are too old (`apt_stale_after_hours`) for "no updates" to mean anything. Also when `/boot` has less than `boot_min_free_mb` free, dpkg left packages half-installed, a kernel package is on hold, the OS release no longer gets security updates, unattended-upgrades is enabled but hasn't succeeded in `unattended_upgrades_stale_after_days`, the release's security repository is missing from apt or hasn't refreshed in `security_repo_stale_after_days`, or one of kernelwatch's own helper units has failed three runs in a row. | | `ok` | Running the newest installed kernel, with no security or kernel updates pending. | Each row also lists the reasons behind its status, and clicking a host shows @@ -106,6 +106,15 @@ How the agent works it out: host: `sudo dpkg --configure -a` (after freeing space, if that was the cause). A report taken while apt is mid-install can show this briefly; the next one clears it. Agents before 0.6.0 send neither field and are judged as before. +- **Packages on hold**: installed packages marked `hold` (`apt-mark hold`, or + dpkg's selection), from dpkg's status database. apt never upgrades them, and + the simulation doesn't list them, so their updates (security ones included) + don't show up anywhere else. A held `linux-*` package (`linux-image-amd64`, + `linux-generic`) would leave the host on its current kernel while looking up + to date, so it puts the host in `update`; release it with + `sudo apt-mark unhold `. Other holds are usually deliberate and only + get a note. The host page lists them all. Agents before 0.10.0 don't report + holds. - **OS end of support**: once a release stops getting security updates, apt never offers one again, so the host would show `ok` indefinitely. The server knows when each supported release's free security support ends diff --git a/server/kernelwatch/report.py b/server/kernelwatch/report.py index 19d62be..969c97c 100644 --- a/server/kernelwatch/report.py +++ b/server/kernelwatch/report.py @@ -45,6 +45,7 @@ FIELDS: dict[str, str] = { "boot_size_kb": "int", "boot_free_kb": "int", "dpkg_unfinished_packages": "strlist", + "held_packages": "strlist", "ubuntu_pro_attached": "bool", "ubuntu_esm_infra": "str", "unattended_upgrades": "str", diff --git a/server/kernelwatch/status.py b/server/kernelwatch/status.py index 36825ed..2c9b55e 100644 --- a/server/kernelwatch/status.py +++ b/server/kernelwatch/status.py @@ -327,6 +327,21 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float, more = f", +{n - 5} more" if n > 5 else "" status.raise_to("update", f"{n} package{'s' if n != 1 else ''} not fully installed: " f"{', '.join(unfinished[:5])}{more}; run dpkg --configure -a") + # Held packages never upgrade, and the simulation doesn't list them, so a held + # kernel package would make a host look current forever. Other holds are + # usually deliberate, but their updates (security ones too) are invisible. + if held := report.get("held_packages"): + kernel = [p for p in held if p.startswith("linux-")] + other = [p for p in held if not p.startswith("linux-")] + if kernel: + status.raise_to("update", f"kernel package{'s' if len(kernel) != 1 else ''} on hold, so " + f"kernel updates won't install: {', '.join(kernel[:5])}" + f"{', …' if len(kernel) > 5 else ''}; apt-mark unhold to release") + if other: + more = f", +{len(other) - 5} more" if len(other) > 5 else "" + status.note(f"{len(other)} package{'s' if len(other) != 1 else ''} on hold, " + f"updates to {'them' if len(other) != 1 else 'it'} won't show: " + f"{', '.join(other[:5])}{more}") if low := boot_space_low(report, cfg): status.raise_to("update", low) diff --git a/server/kernelwatch/web.py b/server/kernelwatch/web.py index ed0aaa1..21de8a4 100644 --- a/server/kernelwatch/web.py +++ b/server/kernelwatch/web.py @@ -547,6 +547,7 @@ class Handler(BaseHTTPRequestHandler): field("/boot free", None if r.get("boot_free_kb") is None else f"{r['boot_free_kb'] // 1024} MB of {(r.get('boot_size_kb') or 0) // 1024} MB"), field("Unfinished dpkg packages", r.get("dpkg_unfinished_packages"), code=True), + field("Packages on hold", r.get("held_packages"), code=True), field("unattended-upgrades", unattended_upgrades_summary(r)), field("Kept back by unattended-upgrades", r.get("unattended_upgrades_kept_back"), code=True), field("Package lists age", duration(r.get("apt_lists_age_seconds")) diff --git a/tests/test_agent.py b/tests/test_agent.py index 60715f5..78f5121 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -172,6 +172,18 @@ class AgentReportTest(AgentCase): "libbar2", "libfoo1:amd64", "linux-headers-6.12.60+deb13-amd64", "linux-image-6.12.60+deb13-amd64", "man-db"]) + def test_held_packages(self): + with open(os.path.join(self.root, "dpkg-all"), "w") as f: + f.write("ii \tcurl\n" + "hi \tlinux-image-amd64\n" + "hi \tpostgresql-16\n" + "hn \tnot-installed\n" + "hc \tremoved-but-held\n" + "iF \tbroken\n") + r = self.report() + self.assertEqual(r["held_packages"], ["linux-image-amd64", "postgresql-16"]) + self.assertEqual(r["dpkg_unfinished_packages"], ["broken"]) + def test_no_unfinished_packages(self): with open(os.path.join(self.root, "dpkg-all"), "w") as f: f.write("ii \tcurl\nrc \told-pkg\n") diff --git a/tests/test_status.py b/tests/test_status.py index f1fe019..37abf43 100644 --- a/tests/test_status.py +++ b/tests/test_status.py @@ -339,6 +339,18 @@ class EvaluateTest(unittest.TestCase): self.assertEqual(self.level(report(dpkg_unfinished_packages=[])).level, "ok") self.assertEqual(self.level(report(dpkg_unfinished_packages=None)).level, "ok") + def test_held_kernel_package_is_a_problem(self): + s = self.level(report(held_packages=["linux-image-amd64"])) + self.assertEqual(s.level, "update") + self.assertEqual(s.reasons, ["kernel package on hold, so kernel updates won't install: " + "linux-image-amd64; apt-mark unhold to release"]) + + def test_other_held_packages_are_a_note(self): + s = self.level(report(held_packages=["postgresql-16", "docker-ce"])) + self.assertEqual(s.level, "ok") + self.assertEqual(s.reasons, ["2 packages on hold, updates to them won't show: postgresql-16, docker-ce"]) + self.assertEqual(self.level(report(held_packages=[])).reasons, []) + def test_os_past_end_of_support(self): s = self.level(report(os_id="debian", os_version_id="11")) self.assertEqual(s.level, "update") -- 2.54.1 From 8174f1df817ed678632ec39a3ba2aaa0b1cf382e Mon Sep 17 00:00:00 2001 From: patrick Date: Sun, 1 Nov 2026 15:25:57 -0500 Subject: [PATCH 3/4] Put hosts with unloaded CPU microcode updates in reboot On bare metal, needrestart -b reports NEEDRESTART-UCSTA: 2 when the installed intel-microcode/amd64-microcode is newer than what the CPU loaded at boot, which only a reboot fixes. The agent dropped those lines. It now reports needrestart_ucsta, _uccur and _ucexp, and the server puts the host in reboot with both revisions. Livepatch doesn't cover it. needrestart skips the check in VMs, so only physical hosts (debian-homelab today) report it; the host page gets a "CPU microcode" row. Co-Authored-By: Claude Opus 5.5 --- agent/kernelwatch-agent | 12 ++++++++++++ docs/how-it-works.md | 10 +++++++++- server/kernelwatch/report.py | 3 +++ server/kernelwatch/status.py | 7 +++++++ server/kernelwatch/web.py | 11 +++++++++++ tests/test_agent.py | 14 ++++++++++++++ tests/test_status.py | 13 +++++++++++++ tests/test_web.py | 10 ++++++++++ 8 files changed, 79 insertions(+), 1 deletion(-) diff --git a/agent/kernelwatch-agent b/agent/kernelwatch-agent index b91d1ca..25180de 100755 --- a/agent/kernelwatch-agent +++ b/agent/kernelwatch-agent @@ -134,9 +134,15 @@ NEEDRESTART_MAX_AGE=7200 # Sets NR_* from the results file, if it's there and fresh. KSTA: 0 unknown, # 1 current, 2 ABI-compatible upgrade pending, 3 version upgrade pending. +# UCSTA (CPU microcode, bare metal only; needrestart skips it in VMs): 0 unknown, +# 1 current, 2 a newer revision is installed but needs a reboot to load. UCCUR +# and UCEXP are the loaded and installed revisions. NR_OK=0 NR_KSTA= NR_KEXP= +NR_UCSTA= +NR_UCCUR= +NR_UCEXP= NR_SVCS= NR_SESS=0 read_needrestart() { @@ -148,6 +154,9 @@ read_needrestart() { case $line in NEEDRESTART-KSTA:*) NR_KSTA=${line#*: } ;; NEEDRESTART-KEXP:*) NR_KEXP=${line#*: } ;; + NEEDRESTART-UCSTA:*) NR_UCSTA=${line#*: } ;; + NEEDRESTART-UCCUR:*) NR_UCCUR=${line#*: } ;; + NEEDRESTART-UCEXP:*) NR_UCEXP=${line#*: } ;; NEEDRESTART-SVC:*) NR_SVCS+=${line#*: }$'\n' ;; NEEDRESTART-SESS:*) NR_SESS=$((NR_SESS + 1)) ;; esac @@ -439,6 +448,9 @@ build_report() { printf '"kernel_newest_installed":%s,' "$(json_str "$newest")" printf '"needrestart_ksta":%s,' "$(json_int "$NR_KSTA")" printf '"needrestart_kexp":%s,' "$(json_str "$NR_KEXP")" + printf '"needrestart_ucsta":%s,' "$(json_int "$NR_UCSTA")" + printf '"needrestart_uccur":%s,' "$(json_str_or_null "$NR_UCCUR")" + printf '"needrestart_ucexp":%s,' "$(json_str_or_null "$NR_UCEXP")" if ((NR_OK)); then printf '"services_need_restart":%s,' "$(sort -u <<<"$NR_SVCS" | json_str_array)" printf '"sessions_need_restart":%s,' "$NR_SESS" diff --git a/docs/how-it-works.md b/docs/how-it-works.md index d8e9f22..17a251f 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -9,7 +9,7 @@ Each host gets one status. When several apply, the worst one wins: | Status | Meaning | |----------|---------| | `stale` | No report in `stale_after_hours` (default 3h), or never. Other data can't be trusted. | -| `reboot` | A newer kernel is installed but not running, or `/run/reboot-required` exists. | +| `reboot` | A newer kernel is installed but not running, `/run/reboot-required` exists, or newer CPU microcode is installed but not loaded. | | `update` | A kernel or security update is available but not installed, services are running outdated libraries and need a restart, or apt's package lists are too old (`apt_stale_after_hours`) for "no updates" to mean anything. Also when `/boot` has less than `boot_min_free_mb` free, dpkg left packages half-installed, a kernel package is on hold, the OS release no longer gets security updates, unattended-upgrades is enabled but hasn't succeeded in `unattended_upgrades_stale_after_days`, the release's security repository is missing from apt or hasn't refreshed in `security_repo_stale_after_days`, or one of kernelwatch's own helper units has failed three runs in a row. | | `ok` | Running the newest installed kernel, with no security or kernel updates pending. | @@ -39,6 +39,14 @@ How the agent works it out: The agent never runs as root, and needrestart never gets network access. Fix it on the host: `sudo needrestart -r a` (or restart the listed services), and the next report clears it. +- **CPU microcode**: on bare metal, needrestart also compares the microcode + revision the CPU loaded at boot with the one the installed `intel-microcode` + or `amd64-microcode` package provides. A newer one only loads on a reboot, so + it puts the host in `reboot`: "CPU microcode update installed but not loaded + (0x001e → 0x0020)". Livepatch doesn't cover it. needrestart skips the check in + virtual machines (the hypervisor handles microcode), so the host page's "CPU + microcode" row only appears on physical hosts. Agents before 0.10.0 don't + report it. - **Ubuntu Livepatch**: with [Livepatch](https://ubuntu.com/security/livepatch) (free for personal use with Ubuntu Pro), a newer kernel being installed doesn't mean the running one is unpatched. If Livepatch is healthy (`applied` or diff --git a/server/kernelwatch/report.py b/server/kernelwatch/report.py index 969c97c..952a9b0 100644 --- a/server/kernelwatch/report.py +++ b/server/kernelwatch/report.py @@ -27,6 +27,9 @@ FIELDS: dict[str, str] = { "kernel_newest_installed": "str", "needrestart_ksta": "int", "needrestart_kexp": "str", + "needrestart_ucsta": "int", + "needrestart_uccur": "str", + "needrestart_ucexp": "str", "services_need_restart": "strlist", "sessions_need_restart": "int", "reboot_required": "bool", diff --git a/server/kernelwatch/status.py b/server/kernelwatch/status.py index 2c9b55e..601f826 100644 --- a/server/kernelwatch/status.py +++ b/server/kernelwatch/status.py @@ -30,6 +30,8 @@ LIVEPATCH_HEALTHY_STATES = ("applied", "nothing-to-apply") KSTA_CURRENT = 1 KSTA_ABI_UPGRADE = 2 KSTA_VERSION_UPGRADE = 3 +# needrestart's NEEDRESTART-UCSTA: a newer CPU microcode is installed but not loaded. +UCSTA_OBSOLETE = 2 @dataclass @@ -309,6 +311,11 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float, status.raise_to("reboot", f"/run/reboot-required{detail}") if livepatch_note and not covered: status.note(livepatch_note) + # Microcode loads at boot; Livepatch doesn't cover it. + if report.get("needrestart_ucsta") == UCSTA_OBSOLETE: + cur, exp = report.get("needrestart_uccur"), report.get("needrestart_ucexp") + detail = f" ({cur} → {exp})" if cur and exp else "" + status.raise_to("reboot", f"CPU microcode update installed but not loaded{detail}") # An agent whose apt simulation failed sends no update counts, so "no security # updates" would be a guess. Agents before 0.5.0 don't send the field. diff --git a/server/kernelwatch/web.py b/server/kernelwatch/web.py index 21de8a4..3a29b5e 100644 --- a/server/kernelwatch/web.py +++ b/server/kernelwatch/web.py @@ -105,6 +105,16 @@ def security_repo_summary(report: dict[str, Any]) -> str | None: return f"{suite}, published {duration(age)} before the report" +def microcode_summary(report: dict[str, Any]) -> str | None: + state = {1: "current", 2: "update needs a reboot"}.get(report.get("needrestart_ucsta")) + if state is None: + return None # unknown, a VM, or no needrestart + cur, exp = report.get("needrestart_uccur"), report.get("needrestart_ucexp") + revs = f" (loaded {cur}, installed {exp})" if state != "current" and cur and exp else \ + f" ({cur})" if cur else "" + return state + revs + + def helper_units_summary(report: dict[str, Any]) -> str | None: units = helper_units(report) if not units: @@ -532,6 +542,7 @@ class Handler(BaseHTTPRequestHandler): field("Installed kernels", r.get("kernels_installed"), code=True), field("needrestart", None if r.get("needrestart_ksta") is None else f"KSTA={r['needrestart_ksta']} expected={r.get('needrestart_kexp') or '?'}"), + field("CPU microcode", microcode_summary(r)), field("Livepatch", None if r.get("livepatch_state") is None else f"{r['livepatch_state']}, {r.get('livepatch_fix_count') or 0} fixes applied, " f"{r.get('livepatch_supported') or '?'} until {r.get('livepatch_upgrade_required') or '?'}"), diff --git a/tests/test_agent.py b/tests/test_agent.py index 78f5121..7ccc887 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -136,6 +136,20 @@ class AgentReportTest(AgentCase): self.assertEqual(r["services_need_restart"], ["nginx.service", "ssh.service"]) self.assertEqual(r["sessions_need_restart"], 1) + def test_needrestart_microcode(self): + self.write_needrestart("NEEDRESTART-KSTA: 1\nNEEDRESTART-UCSTA: 2\n" + "NEEDRESTART-UCCUR: 0x001e\nNEEDRESTART-UCEXP: 0x0020\n") + r = self.report() + self.assertEqual((r["needrestart_ucsta"], r["needrestart_uccur"], r["needrestart_ucexp"]), + (2, "0x001e", "0x0020")) + + def test_needrestart_without_microcode_lines(self): + # Virtual machines: needrestart leaves the UC* lines out. + self.write_needrestart("NEEDRESTART-KSTA: 1\n") + r = self.report() + self.assertIsNone(r["needrestart_ucsta"]) + self.assertIsNone(r["needrestart_uccur"]) + def write_livepatch(self, text, age=60): d = os.path.join(self.root, "run/kernelwatch") os.makedirs(d, exist_ok=True) diff --git a/tests/test_status.py b/tests/test_status.py index 37abf43..e09e5ac 100644 --- a/tests/test_status.py +++ b/tests/test_status.py @@ -339,6 +339,19 @@ class EvaluateTest(unittest.TestCase): self.assertEqual(self.level(report(dpkg_unfinished_packages=[])).level, "ok") self.assertEqual(self.level(report(dpkg_unfinished_packages=None)).level, "ok") + def test_microcode_update_needs_a_reboot(self): + s = self.level(report(needrestart_ucsta=2, needrestart_uccur="0x001e", needrestart_ucexp="0x0020")) + self.assertEqual(s.level, "reboot") + self.assertEqual(s.reasons, ["CPU microcode update installed but not loaded (0x001e → 0x0020)"]) + for ucsta in (0, 1, None): + with self.subTest(ucsta=ucsta): + self.assertEqual(self.level(report(needrestart_ucsta=ucsta)).level, "ok") + + def test_livepatch_doesnt_cover_microcode(self): + s = evaluate(NOW - 60, livepatched(needrestart_ucsta=2), NOW, CFG) + self.assertEqual(s.level, "reboot") + self.assertIn("CPU microcode update installed but not loaded", s.reasons) + def test_held_kernel_package_is_a_problem(self): s = self.level(report(held_packages=["linux-image-amd64"])) self.assertEqual(s.level, "update") diff --git a/tests/test_web.py b/tests/test_web.py index 62a3d6b..6a9671a 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -239,6 +239,16 @@ class DashboardTest(ServerCase): self.assertIn("noble-security: not in apt's sources", body) self.assertIn("apt has no noble-security repository", body) + def test_host_page_shows_microcode(self): + self.add_user("admin", "a-long-password") + token = self.add_host("web01") + self.post_report(token, {"kernel_running": "6.12.57+deb13-amd64", "apt_lists_age_seconds": 60, + "needrestart_ucsta": 2, "needrestart_uccur": "0x001e", + "needrestart_ucexp": "0x0020"}) + _, headers, _ = self.login("admin", "a-long-password") + body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2] + self.assertIn("update needs a reboot (loaded 0x001e, installed 0x0020)", body) + def test_host_page_shows_helper_units(self): self.add_user("admin", "a-long-password") token = self.add_host("web01") -- 2.54.1 From 1b6cfce18bfb9bced09c15174502f05a6cf4dabd Mon Sep 17 00:00:00 2001 From: patrick Date: Sun, 1 Nov 2026 15:31:10 -0500 Subject: [PATCH 4/4] Fix shellcheck SC1007 in helper_units `local x=` reads to shellcheck like a mistyped assignment; spell the empty values as ''. Co-Authored-By: Claude Opus 5.5 --- agent/kernelwatch-agent | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/agent/kernelwatch-agent b/agent/kernelwatch-agent index 25180de..33bd751 100755 --- a/agent/kernelwatch-agent +++ b/agent/kernelwatch-agent @@ -199,7 +199,7 @@ read_livepatch() { HELPER_UNITS=(apt-update needrestart) HELPER_MAX_AGE=7200 helper_units() { - local name file mtime now result= code= status= failures= + local name file mtime now result='' code='' status='' failures='' now=$(date +%s) for name in "${HELPER_UNITS[@]}"; do file=$ROOT/run/kernelwatch/$name.result -- 2.54.1