From 6d29197cfc083970bd16afe0d8857311b945d0b5 Mon Sep 17 00:00:00 2001 From: patrick Date: Fri, 30 Oct 2026 23:22:24 -0400 Subject: [PATCH 1/2] Report a failed apt simulation instead of reading it as "no updates" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The agent ran `apt-get -s dist-upgrade 2>/dev/null || true`, so when apt failed (unmet dependencies, a broken sources entry, a damaged package cache) the empty output counted as zero updates and the host could show ok while nothing could be installed. The agent now keeps apt's exit status and stderr, reports apt_simulation_ok and the first "E:" line as apt_simulation_error, and sends the update counts as null. The server puts such a host in update with "apt can't work out pending updates: ...", and the host page shows the result. Agents before 0.5.0 don't send the field and are judged as before. Also show "–" rather than "None" for an unknown count in a host's history, and stop hard-coding the agent version in the status CLI tests. Agent 0.5.0. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- agent/kernelwatch-agent | 47 ++++++++++++++++++++++++++++------ docs/how-it-works.md | 6 ++++- server/kernelwatch/__init__.py | 2 +- server/kernelwatch/report.py | 2 ++ server/kernelwatch/status.py | 5 ++++ server/kernelwatch/web.py | 4 ++- tests/test_agent.py | 29 +++++++++++++++++++++ tests/test_cli_status.py | 6 ++--- tests/test_status.py | 12 +++++++++ 10 files changed, 100 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 29ea98d..79e9e9b 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,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 for "no updates" to mean anything. | +| `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, or apt itself fails, so "no updates" can't be trusted. | | `ok` | Running the newest installed kernel, with no security or kernel updates pending. | Each row lists the reasons behind its status, and clicking a host shows its full diff --git a/agent/kernelwatch-agent b/agent/kernelwatch-agent index bd5fcef..3c04cdd 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.4.1 +AGENT_VERSION=0.5.0 # Prefix for every file the agent reads. Only the test suite sets this. ROOT=${KERNELWATCH_ROOT:-} @@ -193,13 +193,30 @@ json_str_or_null() { # with /proc/1/root. Unprivileged we can't read /proc/1/root, so ischroot # answers "chroot" and apt would offer every phased update. We're not in one: # say so, and apt applies phasing from /etc/machine-id like it does for root. +# +# apt's stderr goes to the file named by $1. A failed simulation prints nothing, +# which would otherwise read as "no updates", so the caller reports the failure. apt_simulation() { LC_ALL=C apt-get -s -q \ -o Dir::Bin::ischroot=/bin/false \ -o Debug::NoLocking=true \ -o Dir::Cache::pkgcache= \ -o Dir::Cache::srcpkgcache= \ - dist-upgrade 2>/dev/null || true + dist-upgrade 2>"$1" +} + +# Why apt failed, from its stderr on stdin: the first "E:" line, else the first +# line, else the exit status in $1. +apt_error() { + local line first= + while IFS= read -r line; do + if [[ $line == 'E: '* ]]; then + printf '%s' "${line#E: }" + return 0 + fi + [[ -z $first && -n $line ]] && first=$line + done + printf '%s' "${first:-apt-get exited with status $1}" } # Packages Ubuntu is holding back from this host for now (phased updates). apt @@ -233,7 +250,7 @@ uptime_seconds() { } build_report() { - local running newest kernels sim inst reboot_file=0 reboot_pkgs= + local running newest kernels sim inst sim_err rc apt_ok=1 apt_err= reboot_file=0 reboot_pkgs= running=$(uname -r) kernels=$(installed_kernels) @@ -241,7 +258,15 @@ build_report() { read_needrestart read_livepatch - sim=$(apt_simulation) + sim_err=$(mktemp) + if sim=$(apt_simulation "$sim_err"); then + : + else + rc=$? + apt_ok=0 sim= + apt_err=$(apt_error "$rc" <"$sim_err") + fi + rm -f "$sim_err" inst=$(grep '^Inst ' <<<"$sim" || true) if [[ -e $ROOT/run/reboot-required ]]; then @@ -270,10 +295,16 @@ build_report() { fi printf '"reboot_required":%s,' "$(json_bool "$reboot_file")" printf '"reboot_required_pkgs":%s,' "$(json_str_array <<<"$reboot_pkgs")" - printf '"upgradable_count":%s,' "$(json_int "$(grep -c . <<<"$inst" || true)")" - printf '"security_count":%s,' "$(json_int "$(grep -ci 'security' <<<"$inst" || true)")" - printf '"phased_packages":%s,' "$(phased_packages <<<"$sim" | json_str_array)" - printf '"kernel_upgradable":%s,' "$(awk '$2 ~ /^linux-image-/ { print $2 }' <<<"$inst" | json_str_array)" + if ((apt_ok)); then + printf '"upgradable_count":%s,' "$(json_int "$(grep -c . <<<"$inst" || true)")" + printf '"security_count":%s,' "$(json_int "$(grep -ci 'security' <<<"$inst" || true)")" + printf '"phased_packages":%s,' "$(phased_packages <<<"$sim" | json_str_array)" + printf '"kernel_upgradable":%s,' "$(awk '$2 ~ /^linux-image-/ { print $2 }' <<<"$inst" | json_str_array)" + else + printf '"upgradable_count":null,"security_count":null,"phased_packages":null,"kernel_upgradable":null,' + fi + printf '"apt_simulation_ok":%s,' "$(json_bool "$apt_ok")" + printf '"apt_simulation_error":%s,' "$(json_str_or_null "$apt_err")" printf '"livepatch_state":%s,' "$(json_str_or_null "$LP_STATE")" printf '"livepatch_check_state":%s,' "$(json_str_or_null "$LP_CHECK")" printf '"livepatch_supported":%s,' "$(json_str_or_null "$LP_SUPPORTED")" diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 6b87b34..43d5d8f 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -71,7 +71,11 @@ How the agent works it out: - **Available updates**: a simulated `apt-get dist-upgrade`. It is read-only, takes no locks and writes no cache files. `dist-upgrade` is used so that new-ABI kernel packages pulled in by the meta-package show up. Lines whose origin contains - `-security` count as security updates. + `-security` count as security updates. If the simulation fails (unmet + dependencies, a broken sources entry, a damaged package cache), apt prints no + updates at all, so the agent reports the counts as unknown along with apt's + error, and the host goes to `update` with "apt can't work out pending updates". + Agents before 0.5.0 can't tell a failure from "no updates". - **Fresh package lists**: the simulation only knows what apt's package lists say, and the agent can't refresh them itself. Ubuntu refreshes them about once a day. Debian doesn't by default unless `unattended-upgrades` is set up, so a diff --git a/server/kernelwatch/__init__.py b/server/kernelwatch/__init__.py index 9a79dd6..bbf6e83 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.4.1" +AGENT_VERSION = "0.5.0" diff --git a/server/kernelwatch/report.py b/server/kernelwatch/report.py index e42acfe..5de34b8 100644 --- a/server/kernelwatch/report.py +++ b/server/kernelwatch/report.py @@ -40,6 +40,8 @@ FIELDS: dict[str, str] = { "livepatch_supported": "str", "livepatch_upgrade_required": "str", "livepatch_fix_count": "int", + "apt_simulation_ok": "bool", + "apt_simulation_error": "str", "apt_lists_age_seconds": "int", "uptime_seconds": "int", } diff --git a/server/kernelwatch/status.py b/server/kernelwatch/status.py index 14441fc..e8cac3e 100644 --- a/server/kernelwatch/status.py +++ b/server/kernelwatch/status.py @@ -198,6 +198,11 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float, if livepatch_note and not covered: status.note(livepatch_note) + # 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. + if report.get("apt_simulation_ok") is False: + why = report.get("apt_simulation_error") or "no error message" + status.raise_to("update", f"apt can't work out pending updates: {why}") if kernels := report.get("kernel_upgradable"): status.raise_to("update", f"kernel update available: {', '.join(kernels)}") if sec := report.get("security_count"): diff --git a/server/kernelwatch/web.py b/server/kernelwatch/web.py index 730d29a..0992493 100644 --- a/server/kernelwatch/web.py +++ b/server/kernelwatch/web.py @@ -502,6 +502,8 @@ class Handler(BaseHTTPRequestHandler): field("Kernel packages upgradable", r.get("kernel_upgradable"), code=True), field("Updates pending", r.get("upgradable_count")), field("Security updates", r.get("security_count")), + field("apt simulation", None if r.get("apt_simulation_ok") is None else + "ok" if r["apt_simulation_ok"] else f"failed: {r.get('apt_simulation_error') or '?'}"), field("Deferred by phasing", r.get("phased_packages"), code=True), field("Reboot-required packages", r.get("reboot_required_pkgs"), code=True), field("Services needing restart", services_summary(r)[1]), @@ -518,7 +520,7 @@ class Handler(BaseHTTPRequestHandler): f'{e(ago(h["received_at"], now))}' f"{badge(evaluate(h['received_at'], h['report'], h['received_at'], self.cfg).level)}" f"{e(h['report'].get('kernel_running') or '–')}" - f"{e(str(h['report'].get('upgradable_count', '–')))}" + f"{e('–' if (n := h['report'].get('upgradable_count')) is None else str(n))}" "" for h in history ) diff --git a/tests/test_agent.py b/tests/test_agent.py index 27bf6af..1c4c730 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -271,6 +271,35 @@ X stub(self.bin, "apt-get", '[ "$LC_ALL" = C ] || exit 1; echo "Inst ok [1] (2 x [amd64])"\n') self.assertEqual(self.report()["upgradable_count"], 1) + def test_apt_simulation_ok(self): + r = self.report() + self.assertIs(r["apt_simulation_ok"], True) + self.assertIsNone(r["apt_simulation_error"]) + + def test_apt_failure_reports_unknown_counts_not_zero(self): + # A failed simulation prints no Inst lines; that must not read as "no updates". + stub(self.bin, "apt-get", "echo 'Reading package lists...'\n" + "echo 'W: Some warning' >&2\n" + "echo \"E: Unmet dependencies. Try 'apt --fix-broken install'.\" >&2\n" + "exit 100\n") + r = self.report() + self.assertIs(r["apt_simulation_ok"], False) + self.assertEqual(r["apt_simulation_error"], "Unmet dependencies. Try 'apt --fix-broken install'.") + for key in ("upgradable_count", "security_count", "kernel_upgradable", "phased_packages"): + self.assertIsNone(r[key], key) + + def test_apt_failure_without_an_error_line(self): + stub(self.bin, "apt-get", "echo 'something broke' >&2\nexit 1\n") + self.assertEqual(self.report()["apt_simulation_error"], "something broke") + stub(self.bin, "apt-get", "exit 100\n") + self.assertEqual(self.report()["apt_simulation_error"], "apt-get exited with status 100") + + def test_apt_warnings_dont_mix_into_the_simulation(self): + stub(self.bin, "apt-get", f"echo 'W: Inst fake [1] (2 x [amd64])' >&2\ncat <<'X'\n{APT_SIM_DEBIAN}X\n") + r = self.report() + self.assertIs(r["apt_simulation_ok"], True) + self.assertEqual(r["upgradable_count"], 3) + def test_hostile_strings_stay_valid_json(self): stub(self.bin, "hostname", "printf 'a\"b\\\\c\\tq'\n") self.assertEqual(self.report()["reported_hostname"], 'a"b\\cq') diff --git a/tests/test_cli_status.py b/tests/test_cli_status.py index 82a556f..adb6d82 100644 --- a/tests/test_cli_status.py +++ b/tests/test_cli_status.py @@ -9,14 +9,14 @@ import unittest from unittest import mock from helpers import tempdir -from kernelwatch import auth, cli, db +from kernelwatch import AGENT_VERSION, auth, cli, db from kernelwatch.status import evaluate NOW = calendar.timegm((2026, 11, 20, 12, 0, 0)) GOOD = {"kernel_running": "6.12.57", "kernel_newest_installed": "6.12.57", "needrestart_ksta": 1, "apt_lists_age_seconds": 60, "upgradable_count": 0, "security_count": 0, - "os_pretty_name": "Debian 13", "agent_version": "0.4.1"} + "os_pretty_name": "Debian 13", "agent_version": AGENT_VERSION} class StatusCommandTest(unittest.TestCase): @@ -78,7 +78,7 @@ class StatusCommandTest(unittest.TestCase): self.assertEqual(web["last_report_at"], "2026-11-20T11:59:00Z") self.assertEqual(web["last_report_age_seconds"], 60) self.assertEqual((web["kernel_running"], web["kernel_newest_installed"]), ("6.8.0-136", "6.8.0-138")) - self.assertEqual((web["os"], web["agent_version"]), ("Debian 13", "0.4.1")) + self.assertEqual((web["os"], web["agent_version"]), ("Debian 13", AGENT_VERSION)) db_host = next(h for h in self.fleet()["hosts"] if h["name"] == "db01") self.assertEqual((db_host["updates_pending"], db_host["security_updates"]), (7, 3)) self.assertEqual(db_host["reasons"], ["3 security updates pending"]) diff --git a/tests/test_status.py b/tests/test_status.py index 5c3ebcc..341a626 100644 --- a/tests/test_status.py +++ b/tests/test_status.py @@ -296,6 +296,18 @@ class EvaluateTest(unittest.TestCase): self.assertEqual(self.level(report(apt_lists_age_seconds=5 * 86400)).level, "update") self.assertEqual(self.level(report(apt_lists_age_seconds=None)).level, "update") + def test_failed_apt_simulation(self): + s = self.level(report(apt_simulation_ok=False, apt_simulation_error="Unmet dependencies.", + security_count=None, upgradable_count=None, kernel_upgradable=None)) + self.assertEqual(s.level, "update") + self.assertEqual(s.reasons, ["apt can't work out pending updates: Unmet dependencies."]) + s = self.level(report(apt_simulation_ok=False)) + self.assertEqual(s.reasons, ["apt can't work out pending updates: no error message"]) + + def test_apt_simulation_ok_or_unreported(self): + self.assertEqual(self.level(report(apt_simulation_ok=True)).level, "ok") + self.assertEqual(self.level(report()).level, "ok", "agents before 0.5.0 don't send it") + def test_reboot_outranks_update(self): s = self.level(report(needrestart_ksta=3, security_count=2)) self.assertEqual(s.level, "reboot") -- 2.54.1 From fc6ee03ae5fa3f3234ff331b7e2b855a43a84c0b Mon Sep 17 00:00:00 2001 From: patrick Date: Fri, 30 Oct 2026 23:25:50 -0400 Subject: [PATCH 2/2] Quote an empty local in the agent for shellcheck (SC1007) 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 3c04cdd..7985166 100755 --- a/agent/kernelwatch-agent +++ b/agent/kernelwatch-agent @@ -250,7 +250,7 @@ uptime_seconds() { } build_report() { - local running newest kernels sim inst sim_err rc apt_ok=1 apt_err= reboot_file=0 reboot_pkgs= + local running newest kernels sim inst sim_err rc apt_ok=1 apt_err='' reboot_file=0 reboot_pkgs= running=$(uname -r) kernels=$(installed_kernels) -- 2.54.1