Compare commits

..
3 Commits
Author SHA1 Message Date
patrick 669f1dc545 Merge pull request 'Report a failed apt simulation instead of reading it as "no updates"' (#23) from fix/apt-simulation-failure into main
CI / tests (Python 3.12) (push) Successful in 26s
CI / tests (Python 3.13) (push) Successful in 26s
CI / tests (Python 3.10) (push) Successful in 25s
CI / tests (Python 3.11) (push) Successful in 25s
CI / lint (push) Successful in 3s
Reviewed-on: #23
2026-10-31 03:28:45 +00:00
patrickandClaude Opus 5.5 fc6ee03ae5 Quote an empty local in the agent for shellcheck (SC1007)
CI / tests (Python 3.10) (pull_request) Successful in 26s
CI / tests (Python 3.11) (pull_request) Successful in 25s
CI / tests (Python 3.12) (pull_request) Successful in 26s
CI / tests (Python 3.13) (pull_request) Successful in 25s
CI / lint (pull_request) Successful in 3s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 23:25:50 -04:00
patrickandClaude Opus 5.5 6d29197cfc Report a failed apt simulation instead of reading it as "no updates"
CI / tests (Python 3.10) (pull_request) Successful in 26s
CI / tests (Python 3.11) (pull_request) Successful in 25s
CI / tests (Python 3.12) (pull_request) Successful in 25s
CI / tests (Python 3.13) (pull_request) Successful in 25s
CI / lint (pull_request) Failing after 3s
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 <noreply@anthropic.com>
2026-10-30 23:22:24 -04:00
10 changed files with 96 additions and 11 deletions

No files matched your search

+1 -1
View File
@@ -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. | | `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, 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. | | `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 Each row lists the reasons behind its status, and clicking a host shows its full
+35 -4
View File
@@ -6,7 +6,7 @@
# rules can change without redeploying agents. # rules can change without redeploying agents.
set -euo pipefail 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. # Prefix for every file the agent reads. Only the test suite sets this.
ROOT=${KERNELWATCH_ROOT:-} 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 # 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: # 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. # 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() { apt_simulation() {
LC_ALL=C apt-get -s -q \ LC_ALL=C apt-get -s -q \
-o Dir::Bin::ischroot=/bin/false \ -o Dir::Bin::ischroot=/bin/false \
-o Debug::NoLocking=true \ -o Debug::NoLocking=true \
-o Dir::Cache::pkgcache= \ -o Dir::Cache::pkgcache= \
-o Dir::Cache::srcpkgcache= \ -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 # Packages Ubuntu is holding back from this host for now (phased updates). apt
@@ -233,7 +250,7 @@ uptime_seconds() {
} }
build_report() { 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) running=$(uname -r)
kernels=$(installed_kernels) kernels=$(installed_kernels)
@@ -241,7 +258,15 @@ build_report() {
read_needrestart read_needrestart
read_livepatch 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) inst=$(grep '^Inst ' <<<"$sim" || true)
if [[ -e $ROOT/run/reboot-required ]]; then if [[ -e $ROOT/run/reboot-required ]]; then
@@ -270,10 +295,16 @@ build_report() {
fi fi
printf '"reboot_required":%s,' "$(json_bool "$reboot_file")" printf '"reboot_required":%s,' "$(json_bool "$reboot_file")"
printf '"reboot_required_pkgs":%s,' "$(json_str_array <<<"$reboot_pkgs")" printf '"reboot_required_pkgs":%s,' "$(json_str_array <<<"$reboot_pkgs")"
if ((apt_ok)); then
printf '"upgradable_count":%s,' "$(json_int "$(grep -c . <<<"$inst" || true)")" printf '"upgradable_count":%s,' "$(json_int "$(grep -c . <<<"$inst" || true)")"
printf '"security_count":%s,' "$(json_int "$(grep -ci 'security' <<<"$inst" || true)")" printf '"security_count":%s,' "$(json_int "$(grep -ci 'security' <<<"$inst" || true)")"
printf '"phased_packages":%s,' "$(phased_packages <<<"$sim" | json_str_array)" printf '"phased_packages":%s,' "$(phased_packages <<<"$sim" | json_str_array)"
printf '"kernel_upgradable":%s,' "$(awk '$2 ~ /^linux-image-/ { print $2 }' <<<"$inst" | 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_state":%s,' "$(json_str_or_null "$LP_STATE")"
printf '"livepatch_check_state":%s,' "$(json_str_or_null "$LP_CHECK")" printf '"livepatch_check_state":%s,' "$(json_str_or_null "$LP_CHECK")"
printf '"livepatch_supported":%s,' "$(json_str_or_null "$LP_SUPPORTED")" printf '"livepatch_supported":%s,' "$(json_str_or_null "$LP_SUPPORTED")"
+5 -1
View File
@@ -71,7 +71,11 @@ How the agent works it out:
- **Available updates**: a simulated `apt-get dist-upgrade`. It is read-only, takes - **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 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 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 - **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 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 a day. Debian doesn't by default unless `unattended-upgrades` is set up, so a
+1 -1
View File
@@ -4,4 +4,4 @@ __version__ = "0.4.0"
# Version of agent/kernelwatch-agent shipped alongside this server; older agents # 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. # 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"
+2
View File
@@ -40,6 +40,8 @@ FIELDS: dict[str, str] = {
"livepatch_supported": "str", "livepatch_supported": "str",
"livepatch_upgrade_required": "str", "livepatch_upgrade_required": "str",
"livepatch_fix_count": "int", "livepatch_fix_count": "int",
"apt_simulation_ok": "bool",
"apt_simulation_error": "str",
"apt_lists_age_seconds": "int", "apt_lists_age_seconds": "int",
"uptime_seconds": "int", "uptime_seconds": "int",
} }
+5
View File
@@ -198,6 +198,11 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float,
if livepatch_note and not covered: if livepatch_note and not covered:
status.note(livepatch_note) 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"): if kernels := report.get("kernel_upgradable"):
status.raise_to("update", f"kernel update available: {', '.join(kernels)}") status.raise_to("update", f"kernel update available: {', '.join(kernels)}")
if sec := report.get("security_count"): if sec := report.get("security_count"):
+3 -1
View File
@@ -502,6 +502,8 @@ class Handler(BaseHTTPRequestHandler):
field("Kernel packages upgradable", r.get("kernel_upgradable"), code=True), field("Kernel packages upgradable", r.get("kernel_upgradable"), code=True),
field("Updates pending", r.get("upgradable_count")), field("Updates pending", r.get("upgradable_count")),
field("Security updates", r.get("security_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("Deferred by phasing", r.get("phased_packages"), code=True),
field("Reboot-required packages", r.get("reboot_required_pkgs"), code=True), field("Reboot-required packages", r.get("reboot_required_pkgs"), code=True),
field("Services needing restart", services_summary(r)[1]), field("Services needing restart", services_summary(r)[1]),
@@ -518,7 +520,7 @@ class Handler(BaseHTTPRequestHandler):
f'<td title="{e(utc(h["received_at"]))}">{e(ago(h["received_at"], now))}</td>' f'<td title="{e(utc(h["received_at"]))}">{e(ago(h["received_at"], now))}</td>'
f"<td>{badge(evaluate(h['received_at'], h['report'], h['received_at'], self.cfg).level)}</td>" f"<td>{badge(evaluate(h['received_at'], h['report'], h['received_at'], self.cfg).level)}</td>"
f"<td><code>{e(h['report'].get('kernel_running') or '–')}</code></td>" f"<td><code>{e(h['report'].get('kernel_running') or '–')}</code></td>"
f"<td>{e(str(h['report'].get('upgradable_count', '–')))}</td>" f"<td>{e('–' if (n := h['report'].get('upgradable_count')) is None else str(n))}</td>"
"</tr>" "</tr>"
for h in history for h in history
) )
+29
View File
@@ -271,6 +271,35 @@ X
stub(self.bin, "apt-get", '[ "$LC_ALL" = C ] || exit 1; echo "Inst ok [1] (2 x [amd64])"\n') 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) 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): def test_hostile_strings_stay_valid_json(self):
stub(self.bin, "hostname", "printf 'a\"b\\\\c\\tq'\n") stub(self.bin, "hostname", "printf 'a\"b\\\\c\\tq'\n")
self.assertEqual(self.report()["reported_hostname"], 'a"b\\cq') self.assertEqual(self.report()["reported_hostname"], 'a"b\\cq')
+3 -3
View File
@@ -9,14 +9,14 @@ import unittest
from unittest import mock from unittest import mock
from helpers import tempdir from helpers import tempdir
from kernelwatch import auth, cli, db from kernelwatch import AGENT_VERSION, auth, cli, db
from kernelwatch.status import evaluate from kernelwatch.status import evaluate
NOW = calendar.timegm((2026, 11, 20, 12, 0, 0)) NOW = calendar.timegm((2026, 11, 20, 12, 0, 0))
GOOD = {"kernel_running": "6.12.57", "kernel_newest_installed": "6.12.57", "needrestart_ksta": 1, 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, "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): 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_at"], "2026-11-20T11:59:00Z")
self.assertEqual(web["last_report_age_seconds"], 60) 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["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") 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["updates_pending"], db_host["security_updates"]), (7, 3))
self.assertEqual(db_host["reasons"], ["3 security updates pending"]) self.assertEqual(db_host["reasons"], ["3 security updates pending"])
+12
View File
@@ -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=5 * 86400)).level, "update")
self.assertEqual(self.level(report(apt_lists_age_seconds=None)).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): def test_reboot_outranks_update(self):
s = self.level(report(needrestart_ksta=3, security_count=2)) s = self.level(report(needrestart_ksta=3, security_count=2))
self.assertEqual(s.level, "reboot") self.assertEqual(s.level, "reboot")