Compare commits

..
2 Commits
Author SHA1 Message Date
patrick 5a11d31e66 Merge pull request 'Flag a /boot too full for the next kernel and packages dpkg left unfinished' (#25) from feat/boot-space-dpkg-audit into main
CI / tests (Python 3.10) (push) Successful in 27s
CI / tests (Python 3.11) (push) Successful in 27s
CI / tests (Python 3.12) (push) Successful in 27s
CI / tests (Python 3.13) (push) Successful in 28s
CI / lint (push) Successful in 4s
Reviewed-on: #25
2026-10-31 23:26:41 +00:00
patrickandClaude Opus 5.5 70272efed5 Flag a /boot too full for the next kernel and packages dpkg left unfinished
CI / tests (Python 3.10) (pull_request) Successful in 29s
CI / tests (Python 3.11) (pull_request) Successful in 30s
CI / tests (Python 3.12) (pull_request) Successful in 29s
CI / tests (Python 3.13) (pull_request) Successful in 28s
CI / lint (pull_request) Successful in 4s
A full /boot makes the next kernel's postinst fail: apt is left half-done
and the host quietly stays on its old kernel, which kernelwatch only
noticed indirectly, if at all. The agent now reports the size and free
space of the filesystem holding /boot (df) and the packages dpkg didn't
finish installing (half-installed, unpacked, half-configured, trigger
states or reinst-required, as dpkg --audit counts them).

The server puts a host in update when /boot has less than
boot_min_free_mb (default 200, 0 disables) free, or any package is
unfinished, with the fix in the reason ("run dpkg --configure -a"). The
host page shows both. Agents before 0.6.0 send neither field and are
judged as before. Agent 0.6.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 18:54:47 -04:00
13 changed files with 173 additions and 5 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. |
| `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, or apt itself fails, so "no updates" can't be trusted. |
| `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. Also when `/boot` is too full for the next kernel, or dpkg left packages half-installed. |
| `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
+26 -1
View File
@@ -6,7 +6,7 @@
# rules can change without redeploying agents.
set -euo pipefail
AGENT_VERSION=0.5.0
AGENT_VERSION=0.6.0
# Prefix for every file the agent reads. Only the test suite sets this.
ROOT=${KERNELWATCH_ROOT:-}
@@ -242,6 +242,25 @@ apt_lists_age() {
return 0
}
# 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
# on its old kernel with apt half-done.
boot_space() {
df -Pk "$ROOT/boot" 2>/dev/null |
awk 'NR == 2 && $2 ~ /^[0-9]+$/ && $4 ~ /^[0-9]+$/ { print $2, $4 }' || true
}
# Packages dpkg didn't finish installing or removing: half-installed, unpacked,
# half-configured, awaiting or pending triggers, or flagged reinst-required.
# The same states `dpkg --audit` reports; usually a failed postinst, cleared by
# `dpkg --configure -a`. Reads the status database only.
unfinished_packages() {
dpkg-query -W -f='${db:Status-Abbrev}\t${binary:Package}\n' 2>/dev/null |
awk -F '\t' 'substr($1, 2, 1) ~ /[HUFWt]/ || substr($1, 3, 1) == "R" { print $2 }' |
sort -u || true
}
uptime_seconds() {
local up _
[[ -r $ROOT/proc/uptime ]] || return 0
@@ -251,6 +270,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 boot_size='' boot_free=''
running=$(uname -r)
kernels=$(installed_kernels)
@@ -274,6 +294,8 @@ build_report() {
[[ -r $ROOT/run/reboot-required.pkgs ]] && reboot_pkgs=$(sort -u "$ROOT/run/reboot-required.pkgs")
fi
read -r boot_size boot_free <<<"$(boot_space)" || true
printf '{'
printf '"agent_version":%s,' "$(json_str "$AGENT_VERSION")"
printf '"reported_hostname":%s,' "$(json_str "${REPORT_HOSTNAME:-$(hostname -f 2>/dev/null || hostname)}")"
@@ -310,6 +332,9 @@ build_report() {
printf '"livepatch_supported":%s,' "$(json_str_or_null "$LP_SUPPORTED")"
printf '"livepatch_upgrade_required":%s,' "$(json_str_or_null "$LP_UPGRADE")"
printf '"livepatch_fix_count":%s,' "$(json_int "$LP_FIXES")"
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 '"apt_lists_age_seconds":%s,' "$(json_int "$(apt_lists_age)")"
printf '"uptime_seconds":%s' "$(json_int "$(uptime_seconds)")"
printf '}\n'
+17 -1
View File
@@ -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. |
| `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, or dpkg left packages half-installed. |
| `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
@@ -76,6 +76,22 @@ How the agent works it out:
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".
- **Room for the next kernel**: each kernel adds an image and an initramfs to
`/boot`, often over 100 MB together. When `/boot` fills up, the new kernel's
install fails half-way, apt is left broken, and the host quietly stays on its
old kernel. The agent reports the size and free space of the filesystem holding
`/boot` (from `df`; the root filesystem when `/boot` isn't separate). Under
`boot_min_free_mb` (default 200) free puts the host in `update` with "/boot has
N MB free". Fix it on the host: `sudo apt autoremove --purge` removes old
kernels.
- **Unfinished packages**: packages dpkg didn't finish installing, read from its
status database (the same states `dpkg --audit` reports: half-installed,
unpacked, half-configured, waiting on triggers, or reinst-required). These are
usually left by a failed install script, often because `/boot` was full. They
put the host in `update` with "N packages not fully installed". Fix it on the
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.
- **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
+1 -1
View File
@@ -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.5.0"
AGENT_VERSION = "0.6.0"
+5
View File
@@ -30,6 +30,9 @@ class Config:
# Package lists older than this make "no updates" untrustworthy.
apt_stale_after_hours: float = 48.0
report_retention_days: int = 30
# Less free space than this on /boot's filesystem puts a host in update: the next
# kernel (image plus initramfs, often over 100 MB) may not fit. 0 disables.
boot_min_free_mb: int = 200
# Where `scheduled-backup` (kernelwatch-backup.timer) writes dated copies of the
# database, and how many days of them it keeps; 0 keeps them all. It must stay
@@ -93,6 +96,8 @@ def load(path: str | None = None) -> Config:
raise SystemExit(f"{path}: ntfy_timeout_seconds must be positive and finite")
if cfg.report_min_interval_seconds < 0:
raise SystemExit(f"{path}: report_min_interval_seconds must be zero or positive")
if cfg.boot_min_free_mb < 0:
raise SystemExit(f"{path}: boot_min_free_mb must be zero or positive")
if cfg.backup_keep_days < 0:
raise SystemExit(f"{path}: backup_keep_days must be zero or positive")
if not cfg.backup_dir.startswith("/") or any(ord(c) < 32 or ord(c) == 127 for c in cfg.backup_dir):
+3
View File
@@ -42,6 +42,9 @@ FIELDS: dict[str, str] = {
"livepatch_fix_count": "int",
"apt_simulation_ok": "bool",
"apt_simulation_error": "str",
"boot_size_kb": "int",
"boot_free_kb": "int",
"dpkg_unfinished_packages": "strlist",
"apt_lists_age_seconds": "int",
"uptime_seconds": "int",
}
+21
View File
@@ -146,6 +146,17 @@ def livepatch_cover(report: dict[str, Any], now: float) -> tuple[bool, str | Non
return True, f"live-patched; kernel upgrade needed by {deadline}"
def boot_space_low(report: dict[str, Any], cfg: Config) -> str | None:
"""Why /boot may be too full for the next kernel, or None. Agents before 0.6.0
don't report it, and a host whose df failed sends null; both count as fine."""
free_kb = report.get("boot_free_kb")
if not cfg.boot_min_free_mb or free_kb is None or free_kb >= cfg.boot_min_free_mb * 1024:
return None
size_kb = report.get("boot_size_kb")
used = f", {100 - free_kb * 100 // size_kb}% used" if size_kb else ""
return f"/boot has {free_kb // 1024} MB free{used}; the next kernel may not fit"
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 []
@@ -208,6 +219,16 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float,
if sec := report.get("security_count"):
status.raise_to("update", f"{sec} security update{'s' if sec != 1 else ''} pending")
# dpkg stopped part-way (usually a failed postinst, often from a full /boot), so
# whatever it was installing, maybe a kernel, isn't in place yet.
if unfinished := report.get("dpkg_unfinished_packages"):
n = len(unfinished)
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")
if low := boot_space_low(report, cfg):
status.raise_to("update", low)
if services := report.get("services_need_restart"):
shown = ", ".join(s.removesuffix(".service") for s in services[:5])
more = f", +{len(services) - 5} more" if len(services) > 5 else ""
+3
View File
@@ -508,6 +508,9 @@ class Handler(BaseHTTPRequestHandler):
field("Reboot-required packages", r.get("reboot_required_pkgs"), code=True),
field("Services needing restart", services_summary(r)[1]),
field("Sessions needing restart", r.get("sessions_need_restart")),
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("Package lists age", duration(r.get("apt_lists_age_seconds"))
if r.get("apt_lists_age_seconds") is not None else None),
field("Uptime", duration(r.get("uptime_seconds")) if r.get("uptime_seconds") is not None else None),
+5
View File
@@ -14,6 +14,11 @@ apt_stale_after_hours = 48.0
report_retention_days = 30
# Less free space than this (MB) on the filesystem holding /boot puts a host in
# "update": the next kernel's image and initramfs may not fit, and its install
# fails half-way. 0 disables.
boot_min_free_mb = 200
# kernelwatch-backup.timer writes a dated copy of the database here every night
# and deletes copies this many days old or older (0 keeps them all). Keep the
# directory under /var/lib/kernelwatch; the unit can't write elsewhere. Copy the
+40 -1
View File
@@ -59,13 +59,20 @@ class AgentCase(unittest.TestCase):
stub(self.bin, "uname", 'case "$1" in -r) echo 6.12.48+deb13-amd64;; '
'-v) echo "#1 SMP PREEMPT_DYNAMIC Debian 6.12.48-1";; esac\n')
stub(self.bin, "hostname", "echo web01.example\n")
stub(self.bin, "dpkg-query", 'case "$*" in *Version*) echo "ii 6.12.48-2";; *) cat <<\'X\'\n'
# The full-database query (unfinished packages) prints $KERNELWATCH_ROOT/dpkg-all.
stub(self.bin, "dpkg-query", 'case "$*" in *binary:Package*) cat "$KERNELWATCH_ROOT/dpkg-all" 2>/dev/null;; '
'*Version*) echo "ii 6.12.48-2";; *) cat <<\'X\'\n'
f"{DPKG_DEBIAN}X\n;; esac\n")
self.stub_df("/dev/sda1 999320 187364 743144 21% /boot\n")
stub(self.bin, "apt-get", f"cat <<'X'\n{APT_SIM_DEBIAN}X\n")
def tearDown(self):
self._tmp.cleanup()
def stub_df(self, line, rc=0):
stub(self.bin, "df", "echo 'Filesystem 1024-blocks Used Available Capacity Mounted on'\n"
f"cat <<'X'\n{line}X\nexit {rc}\n")
def run_agent(self, *args, env=None):
full_env = {
"PATH": f"{self.bin}:{os.environ['PATH']}",
@@ -134,6 +141,38 @@ class AgentReportTest(AgentCase):
t = time.time() - age
os.utime(path, (t, t))
def test_boot_space(self):
r = self.report()
self.assertEqual((r["boot_size_kb"], r["boot_free_kb"]), (999320, 743144))
def test_boot_space_unknown_when_df_fails(self):
self.stub_df("", rc=1)
r = self.report()
self.assertIsNone(r["boot_size_kb"])
self.assertIsNone(r["boot_free_kb"])
def test_boot_space_unknown_when_df_prints_garbage(self):
self.stub_df("/dev/sda1 - - - - /boot\n")
self.assertIsNone(self.report()["boot_free_kb"])
def test_unfinished_packages(self):
with open(os.path.join(self.root, "dpkg-all"), "w") as f:
f.write("ii \tcurl\n"
"iF \tlinux-image-6.12.60+deb13-amd64\n"
"iU \tlinux-headers-6.12.60+deb13-amd64\n"
"iHR\tlibfoo1:amd64\n"
"iiR\tlibbar2\n"
"it \tman-db\n"
"rc \told-pkg\n")
self.assertEqual(self.report()["dpkg_unfinished_packages"], [
"libbar2", "libfoo1:amd64", "linux-headers-6.12.60+deb13-amd64",
"linux-image-6.12.60+deb13-amd64", "man-db"])
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")
self.assertEqual(self.report()["dpkg_unfinished_packages"], [])
def test_every_reported_field_is_accepted_by_the_server(self):
from kernelwatch.report import FIELDS
self.write_livepatch("LIVEPATCH-STATE: applied\nLIVEPATCH-FIXES: 2\n")
+8
View File
@@ -92,6 +92,14 @@ class ConfigTest(unittest.TestCase):
with self.subTest(bad=bad), self.assertRaises(SystemExit):
config.load(self.write(tmp, f"status_alert_after_hours = {bad}\n"))
def test_boot_min_free_validated(self):
with tempdir() as tmp:
self.assertEqual(config.Config().boot_min_free_mb, 200)
self.assertEqual(config.load(self.write(tmp, "boot_min_free_mb = 0\n")).boot_min_free_mb, 0)
for bad in ("-1", "1.5", '"200"'):
with self.subTest(bad=bad), self.assertRaises(SystemExit):
config.load(self.write(tmp, f"boot_min_free_mb = {bad}\n"))
def test_fallback_parser_matches_tomllib(self):
"""Python 3.10 has no tomllib; the fallback must read the same configs."""
if config.tomllib is None:
+31
View File
@@ -308,6 +308,37 @@ class EvaluateTest(unittest.TestCase):
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_low_boot_space(self):
s = self.level(report(boot_size_kb=487 * 1024, boot_free_kb=95 * 1024))
self.assertEqual(s.level, "update")
self.assertEqual(s.reasons, ["/boot has 95 MB free, 81% used; the next kernel may not fit"])
s = self.level(report(boot_free_kb=95 * 1024))
self.assertEqual(s.reasons, ["/boot has 95 MB free; the next kernel may not fit"], "size unknown")
def test_enough_boot_space_or_unreported(self):
self.assertEqual(self.level(report(boot_size_kb=999320, boot_free_kb=200 * 1024)).level, "ok")
self.assertEqual(self.level(report(boot_free_kb=None)).level, "ok", "df failed")
self.assertEqual(self.level(report()).level, "ok", "agents before 0.6.0 don't send it")
def test_boot_space_threshold_is_configurable(self):
rep = report(boot_size_kb=999320, boot_free_kb=300 * 1024)
self.assertEqual(evaluate(NOW, rep, NOW, Config(boot_min_free_mb=500)).level, "update")
self.assertEqual(evaluate(NOW, report(boot_free_kb=0), NOW, Config(boot_min_free_mb=0)).level,
"ok", "0 disables")
def test_unfinished_dpkg_packages(self):
s = self.level(report(dpkg_unfinished_packages=["linux-image-6.12.60+deb13-amd64"]))
self.assertEqual(s.level, "update")
self.assertEqual(s.reasons, ["1 package not fully installed: linux-image-6.12.60+deb13-amd64; "
"run dpkg --configure -a"])
s = self.level(report(dpkg_unfinished_packages=[f"p{i}" for i in range(7)]))
self.assertEqual(s.reasons, ["7 packages not fully installed: p0, p1, p2, p3, p4, +2 more; "
"run dpkg --configure -a"])
def test_no_unfinished_dpkg_packages_or_unreported(self):
self.assertEqual(self.level(report(dpkg_unfinished_packages=[])).level, "ok")
self.assertEqual(self.level(report(dpkg_unfinished_packages=None)).level, "ok")
def test_reboot_outranks_update(self):
s = self.level(report(needrestart_ksta=3, security_count=2))
self.assertEqual(s.level, "reboot")
+12
View File
@@ -185,6 +185,18 @@ class DashboardTest(ServerCase):
body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2]
self.assertIn("applied, 2 fixes applied, supported until 2099-09-07", body)
def test_host_page_shows_boot_space_and_unfinished_packages(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,
"boot_size_kb": 487 * 1024, "boot_free_kb": 95 * 1024,
"dpkg_unfinished_packages": ["linux-image-6.8.0-138-generic"]})
_, headers, _ = self.login("admin", "a-long-password")
body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2]
self.assertIn("95 MB of 487 MB", body)
self.assertIn("<code>linux-image-6.8.0-138-generic</code>", body)
self.assertIn("/boot has 95 MB free, 81% used; the next kernel may not fit", body)
def test_login_dashboard_logout(self):
self.add_user("admin", "a-long-password")
token = self.add_host("web01")