Flag hosts where unattended-upgrades has stopped succeeding
On a host with unattended-upgrades enabled, no successful run in
unattended_upgrades_stale_after_days (default 3, 0 disables) puts it in
update. The reason says which way it broke: still running but failing
("last succeeded 5d ago and is failing (last ran 6h ago); check
/var/log/unattended-upgrades/"), not running at all ("is
apt-daily-upgrade.timer enabled?"), or never succeeded. A host where it
hasn't completed its first run yet gets a note, and packages it keeps back
are noted. Hosts with it disabled or not installed, and agents before
0.8.0, are judged as before. The host page shows the state, both stamp
ages and the kept-back packages.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
df097c9da3
commit
bfac723850
7 files changed
+143
No files matched your search
@@ -37,6 +37,9 @@ class Config:
|
|||||||
# (or Ubuntu standard support ends without ESM). 0 disables the warning; a host
|
# (or Ubuntu standard support ends without ESM). 0 disables the warning; a host
|
||||||
# past the date is in update either way.
|
# past the date is in update either way.
|
||||||
os_eol_warn_days: int = 90
|
os_eol_warn_days: int = 90
|
||||||
|
# A host with unattended-upgrades enabled that hasn't had a successful run in this
|
||||||
|
# long is in update. It normally runs daily. 0 disables the check.
|
||||||
|
unattended_upgrades_stale_after_days: float = 3.0
|
||||||
|
|
||||||
# Where `scheduled-backup` (kernelwatch-backup.timer) writes dated copies of the
|
# 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
|
# database, and how many days of them it keeps; 0 keeps them all. It must stay
|
||||||
@@ -100,6 +103,8 @@ def load(path: str | None = None) -> Config:
|
|||||||
raise SystemExit(f"{path}: ntfy_timeout_seconds must be positive and finite")
|
raise SystemExit(f"{path}: ntfy_timeout_seconds must be positive and finite")
|
||||||
if cfg.report_min_interval_seconds < 0:
|
if cfg.report_min_interval_seconds < 0:
|
||||||
raise SystemExit(f"{path}: report_min_interval_seconds must be zero or positive")
|
raise SystemExit(f"{path}: report_min_interval_seconds must be zero or positive")
|
||||||
|
if not math.isfinite(cfg.unattended_upgrades_stale_after_days) or cfg.unattended_upgrades_stale_after_days < 0:
|
||||||
|
raise SystemExit(f"{path}: unattended_upgrades_stale_after_days must be zero or positive and finite")
|
||||||
if cfg.os_eol_warn_days < 0:
|
if cfg.os_eol_warn_days < 0:
|
||||||
raise SystemExit(f"{path}: os_eol_warn_days must be zero or positive")
|
raise SystemExit(f"{path}: os_eol_warn_days must be zero or positive")
|
||||||
if cfg.boot_min_free_mb < 0:
|
if cfg.boot_min_free_mb < 0:
|
||||||
|
|||||||
@@ -157,6 +157,40 @@ def boot_space_low(report: dict[str, Any], cfg: Config) -> str | None:
|
|||||||
return f"/boot has {free_kb // 1024} MB free{used}; the next kernel may not fit"
|
return f"/boot has {free_kb // 1024} MB free{used}; the next kernel may not fit"
|
||||||
|
|
||||||
|
|
||||||
|
UU_LOG = "/var/log/unattended-upgrades/"
|
||||||
|
|
||||||
|
|
||||||
|
def _age(seconds: int) -> str:
|
||||||
|
return f"{seconds // 86400}d" if seconds >= 86400 else f"{seconds // 3600}h"
|
||||||
|
|
||||||
|
|
||||||
|
def unattended_upgrades_problem(report: dict[str, Any], cfg: Config) -> tuple[bool, str] | None:
|
||||||
|
"""(is it a problem, why) about unattended-upgrades on a host that has it enabled,
|
||||||
|
or None. Hosts without it, and agents before 0.8.0, get nothing.
|
||||||
|
|
||||||
|
The success stamp is apt.systemd.daily's (touched only when unattended-upgrade
|
||||||
|
exits 0); the run stamp is unattended-upgrade's own (written even when the run
|
||||||
|
then fails). Ages are as of the report."""
|
||||||
|
if report.get("unattended_upgrades") != "enabled" or not cfg.unattended_upgrades_stale_after_days:
|
||||||
|
return None
|
||||||
|
success = report.get("unattended_upgrades_success_age_seconds")
|
||||||
|
run = report.get("unattended_upgrades_run_age_seconds")
|
||||||
|
if success is None:
|
||||||
|
if run is None:
|
||||||
|
# Freshly installed: the first daily run hasn't happened yet.
|
||||||
|
return False, "unattended-upgrades is enabled but hasn't completed a run yet"
|
||||||
|
return True, (f"unattended-upgrades has never succeeded (last ran {_age(run)} ago); "
|
||||||
|
f"check {UU_LOG}")
|
||||||
|
if success <= cfg.unattended_upgrades_stale_after_days * 86400:
|
||||||
|
return None
|
||||||
|
# A successful run writes both stamps within moments of each other.
|
||||||
|
if run is not None and run < success - 3600:
|
||||||
|
return True, (f"unattended-upgrades last succeeded {_age(success)} ago and is failing "
|
||||||
|
f"(last ran {_age(run)} ago); check {UU_LOG}")
|
||||||
|
return True, (f"unattended-upgrades hasn't run in {_age(success)}; "
|
||||||
|
"is apt-daily-upgrade.timer enabled?")
|
||||||
|
|
||||||
|
|
||||||
def _kernel_only_reboot_file(report: dict[str, Any]) -> bool:
|
def _kernel_only_reboot_file(report: dict[str, Any]) -> bool:
|
||||||
"""/run/reboot-required exists only because of kernel packages."""
|
"""/run/reboot-required exists only because of kernel packages."""
|
||||||
pkgs = report.get("reboot_required_pkgs") or []
|
pkgs = report.get("reboot_required_pkgs") or []
|
||||||
@@ -229,6 +263,18 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float,
|
|||||||
if low := boot_space_low(report, cfg):
|
if low := boot_space_low(report, cfg):
|
||||||
status.raise_to("update", low)
|
status.raise_to("update", low)
|
||||||
|
|
||||||
|
if found := unattended_upgrades_problem(report, cfg):
|
||||||
|
problem, why = found
|
||||||
|
if problem:
|
||||||
|
status.raise_to("update", why)
|
||||||
|
else:
|
||||||
|
status.note(why)
|
||||||
|
# Packages from its allowed origins (by default security) it won't install: held,
|
||||||
|
# blacklisted or stuck on a conffile prompt. They stay pending until someone acts.
|
||||||
|
if report.get("unattended_upgrades") == "enabled" and (kept := report.get("unattended_upgrades_kept_back")):
|
||||||
|
more = f", +{len(kept) - 5} more" if len(kept) > 5 else ""
|
||||||
|
status.note(f"unattended-upgrades is keeping back {', '.join(kept[:5])}{more}")
|
||||||
|
|
||||||
today = datetime.fromtimestamp(now, timezone.utc).date()
|
today = datetime.fromtimestamp(now, timezone.utc).date()
|
||||||
if found := support.check(report, today, cfg.os_eol_warn_days):
|
if found := support.check(report, today, cfg.os_eol_warn_days):
|
||||||
problem, why = found
|
problem, why = found
|
||||||
|
|||||||
@@ -84,6 +84,17 @@ def utc(ts: float | None) -> str:
|
|||||||
return time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(ts)) if ts else ""
|
return time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(ts)) if ts else ""
|
||||||
|
|
||||||
|
|
||||||
|
def unattended_upgrades_summary(report: dict[str, Any]) -> str | None:
|
||||||
|
state = report.get("unattended_upgrades")
|
||||||
|
if state != "enabled":
|
||||||
|
return state # "disabled", "not-installed", or None from agents before 0.8.0
|
||||||
|
last = {"success": report.get("unattended_upgrades_success_age_seconds"),
|
||||||
|
"run": report.get("unattended_upgrades_run_age_seconds")}
|
||||||
|
return "enabled, " + ", ".join(
|
||||||
|
f"last {what} " + ("never" if age is None else f"{duration(age)} before the report")
|
||||||
|
for what, age in last.items())
|
||||||
|
|
||||||
|
|
||||||
def phased_summary(report: dict[str, Any]) -> tuple[str, str]:
|
def phased_summary(report: dict[str, Any]) -> tuple[str, str]:
|
||||||
"""(short cell text, full description) for updates deferred by Ubuntu's phasing."""
|
"""(short cell text, full description) for updates deferred by Ubuntu's phasing."""
|
||||||
if report.get("os_id") not in (None, "ubuntu"):
|
if report.get("os_id") not in (None, "ubuntu"):
|
||||||
@@ -512,6 +523,8 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
field("/boot free", None if r.get("boot_free_kb") is None else
|
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"),
|
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("Unfinished dpkg packages", r.get("dpkg_unfinished_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"))
|
field("Package lists age", duration(r.get("apt_lists_age_seconds"))
|
||||||
if r.get("apt_lists_age_seconds") is not None else None),
|
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),
|
field("Uptime", duration(r.get("uptime_seconds")) if r.get("uptime_seconds") is not None else None),
|
||||||
|
|||||||
@@ -24,6 +24,11 @@ boot_min_free_mb = 200
|
|||||||
# its row gets a note. 0 disables the note.
|
# its row gets a note. 0 disables the note.
|
||||||
os_eol_warn_days = 90
|
os_eol_warn_days = 90
|
||||||
|
|
||||||
|
# On hosts with unattended-upgrades enabled (it runs daily), no successful run in
|
||||||
|
# this many days puts the host in "update". Hosts without it aren't affected.
|
||||||
|
# 0 disables the check.
|
||||||
|
unattended_upgrades_stale_after_days = 3.0
|
||||||
|
|
||||||
# kernelwatch-backup.timer writes a dated copy of the database here every night
|
# 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
|
# 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
|
# directory under /var/lib/kernelwatch; the unit can't write elsewhere. Copy the
|
||||||
|
|||||||
@@ -108,6 +108,15 @@ class ConfigTest(unittest.TestCase):
|
|||||||
with self.subTest(bad=bad), self.assertRaises(SystemExit):
|
with self.subTest(bad=bad), self.assertRaises(SystemExit):
|
||||||
config.load(self.write(tmp, f"os_eol_warn_days = {bad}\n"))
|
config.load(self.write(tmp, f"os_eol_warn_days = {bad}\n"))
|
||||||
|
|
||||||
|
def test_unattended_upgrades_stale_days_validated(self):
|
||||||
|
with tempdir() as tmp:
|
||||||
|
self.assertEqual(config.Config().unattended_upgrades_stale_after_days, 3.0)
|
||||||
|
self.assertEqual(config.load(self.write(tmp, "unattended_upgrades_stale_after_days = 0\n"))
|
||||||
|
.unattended_upgrades_stale_after_days, 0)
|
||||||
|
for bad in ("-1", "inf", "nan", '"3"'):
|
||||||
|
with self.subTest(bad=bad), self.assertRaises(SystemExit):
|
||||||
|
config.load(self.write(tmp, f"unattended_upgrades_stale_after_days = {bad}\n"))
|
||||||
|
|
||||||
def test_fallback_parser_matches_tomllib(self):
|
def test_fallback_parser_matches_tomllib(self):
|
||||||
"""Python 3.10 has no tomllib; the fallback must read the same configs."""
|
"""Python 3.10 has no tomllib; the fallback must read the same configs."""
|
||||||
if config.tomllib is None:
|
if config.tomllib is None:
|
||||||
|
|||||||
@@ -352,6 +352,57 @@ class EvaluateTest(unittest.TestCase):
|
|||||||
evaluate(NOW, rep, NOW, Config(os_eol_warn_days=200)).reasons[0])
|
evaluate(NOW, rep, NOW, Config(os_eol_warn_days=200)).reasons[0])
|
||||||
self.assertEqual(self.level(rep).reasons, [], "outside the default 90 days")
|
self.assertEqual(self.level(rep).reasons, [], "outside the default 90 days")
|
||||||
|
|
||||||
|
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))
|
||||||
|
|
||||||
|
def test_unattended_upgrades_healthy(self):
|
||||||
|
self.assertEqual((self.uu().level, self.uu().reasons), ("ok", []))
|
||||||
|
self.assertEqual(self.uu(success=3 * 86400, run=3 * 86400).level, "ok", "at the limit")
|
||||||
|
|
||||||
|
def test_unattended_upgrades_not_running(self):
|
||||||
|
s = self.uu(success=5 * 86400, run=5 * 86400)
|
||||||
|
self.assertEqual(s.level, "update")
|
||||||
|
self.assertEqual(s.reasons, ["unattended-upgrades hasn't run in 5d; is apt-daily-upgrade.timer enabled?"])
|
||||||
|
s = self.uu(success=5 * 86400, run=None)
|
||||||
|
self.assertIn("hasn't run in 5d", s.reasons[0], "older unattended-upgrades without its own stamp")
|
||||||
|
|
||||||
|
def test_unattended_upgrades_running_but_failing(self):
|
||||||
|
s = self.uu(success=5 * 86400, run=6 * 3600)
|
||||||
|
self.assertEqual(s.level, "update")
|
||||||
|
self.assertEqual(s.reasons, ["unattended-upgrades last succeeded 5d ago and is failing (last ran 6h ago); "
|
||||||
|
"check /var/log/unattended-upgrades/"])
|
||||||
|
|
||||||
|
def test_unattended_upgrades_never_succeeded(self):
|
||||||
|
s = self.uu(success=None, run=6 * 3600)
|
||||||
|
self.assertEqual(s.level, "update")
|
||||||
|
self.assertEqual(s.reasons, ["unattended-upgrades has never succeeded (last ran 6h ago); "
|
||||||
|
"check /var/log/unattended-upgrades/"])
|
||||||
|
|
||||||
|
def test_unattended_upgrades_not_run_yet_is_a_note(self):
|
||||||
|
s = self.uu(success=None, run=None)
|
||||||
|
self.assertEqual((s.level, s.reasons), ("ok", ["unattended-upgrades is enabled but hasn't completed a run yet"]))
|
||||||
|
|
||||||
|
def test_unattended_upgrades_off_or_unreported_is_ignored(self):
|
||||||
|
for state in ("disabled", "not-installed"):
|
||||||
|
with self.subTest(state=state):
|
||||||
|
s = self.uu(success=None, run=None, state=state, unattended_upgrades_kept_back=["openssl"])
|
||||||
|
self.assertEqual((s.level, s.reasons), ("ok", []))
|
||||||
|
self.assertEqual(self.level(report()).reasons, [], "agents before 0.8.0")
|
||||||
|
|
||||||
|
def test_unattended_upgrades_check_can_be_disabled(self):
|
||||||
|
rep = report(unattended_upgrades="enabled", unattended_upgrades_success_age_seconds=30 * 86400)
|
||||||
|
self.assertEqual(evaluate(NOW, rep, NOW, Config(unattended_upgrades_stale_after_days=0)).level, "ok")
|
||||||
|
self.assertEqual(evaluate(NOW, rep, NOW, Config(unattended_upgrades_stale_after_days=60)).level, "ok")
|
||||||
|
|
||||||
|
def test_unattended_upgrades_kept_back_is_noted(self):
|
||||||
|
s = self.uu(unattended_upgrades_kept_back=["libssl3t64", "openssl"], security_count=2)
|
||||||
|
self.assertEqual(s.level, "update")
|
||||||
|
self.assertEqual(s.reasons, ["2 security updates pending",
|
||||||
|
"unattended-upgrades is keeping back libssl3t64, openssl"])
|
||||||
|
s = self.uu(unattended_upgrades_kept_back=[f"p{i}" for i in range(7)])
|
||||||
|
self.assertEqual(s.reasons, ["unattended-upgrades is keeping back p0, p1, p2, p3, p4, +2 more"])
|
||||||
|
|
||||||
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")
|
||||||
|
|||||||
@@ -197,6 +197,20 @@ class DashboardTest(ServerCase):
|
|||||||
self.assertIn("<code>linux-image-6.8.0-138-generic</code>", 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)
|
self.assertIn("/boot has 95 MB free, 81% used; the next kernel may not fit", body)
|
||||||
|
|
||||||
|
def test_host_page_shows_unattended_upgrades(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,
|
||||||
|
"unattended_upgrades": "enabled",
|
||||||
|
"unattended_upgrades_success_age_seconds": 5 * 86400 + 7200,
|
||||||
|
"unattended_upgrades_run_age_seconds": 6 * 3600,
|
||||||
|
"unattended_upgrades_kept_back": ["openssl"]})
|
||||||
|
_, headers, _ = self.login("admin", "a-long-password")
|
||||||
|
body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2]
|
||||||
|
self.assertIn("enabled, last success 5d 2h before the report, last run 6h 0m before the report", body)
|
||||||
|
self.assertIn("<code>openssl</code>", body)
|
||||||
|
self.assertIn("unattended-upgrades last succeeded 5d ago and is failing", body)
|
||||||
|
|
||||||
def test_host_page_shows_os_support(self):
|
def test_host_page_shows_os_support(self):
|
||||||
self.add_user("admin", "a-long-password")
|
self.add_user("admin", "a-long-password")
|
||||||
token = self.add_host("web01")
|
token = self.add_host("web01")
|
||||||
|
|||||||
Reference in new issue
Block a user