Treat Ubuntu Livepatch as cover for pending kernel reboots
New livepatch_* report fields. When Livepatch is healthy (applied or nothing-to-apply, checked, supported) and the kernel's support end date is more than 14 days away, a pending kernel reboot, or a reboot-required file caused only by linux-* packages, becomes a note instead of the reboot status. Anything else about Livepatch gives no cover and is noted. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
40bfdc3236
commit
4fa86de11f
5 files changed
+140
No files matched your search
@@ -35,6 +35,11 @@ FIELDS: dict[str, str] = {
|
||||
"security_count": "int",
|
||||
"kernel_upgradable": "strlist",
|
||||
"phased_packages": "strlist",
|
||||
"livepatch_state": "str",
|
||||
"livepatch_check_state": "str",
|
||||
"livepatch_supported": "str",
|
||||
"livepatch_upgrade_required": "str",
|
||||
"livepatch_fix_count": "int",
|
||||
"apt_lists_age_seconds": "int",
|
||||
"uptime_seconds": "int",
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from . import AGENT_VERSION
|
||||
@@ -19,6 +20,11 @@ from .config import Config
|
||||
LEVELS = ("stale", "reboot", "update", "ok")
|
||||
_RANK = {level: i for i, level in enumerate(LEVELS)}
|
||||
|
||||
# Ubuntu Livepatch: a pending kernel reboot stops counting this long before the
|
||||
# running kernel's patch support ends (`UpgradeRequiredDate`).
|
||||
LIVEPATCH_MARGIN_DAYS = 14
|
||||
LIVEPATCH_HEALTHY_STATES = ("applied", "nothing-to-apply")
|
||||
|
||||
# needrestart's NEEDRESTART-KSTA values.
|
||||
KSTA_CURRENT = 1
|
||||
KSTA_ABI_UPGRADE = 2
|
||||
@@ -98,6 +104,37 @@ def kernel_reboot_pending(report: dict[str, Any]) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def livepatch_cover(report: dict[str, Any], now: float) -> tuple[bool, str | None]:
|
||||
"""(is the running kernel kept patched by Livepatch, a note about it).
|
||||
|
||||
Livepatch only fixes high and critical CVEs and only until the kernel's
|
||||
support ends, so cover lapses LIVEPATCH_MARGIN_DAYS before that date. Hosts
|
||||
without Livepatch data, or with Livepatch in any state we don't recognise as
|
||||
healthy, get no cover and are judged as before."""
|
||||
state = report.get("livepatch_state")
|
||||
if state is None:
|
||||
return False, None
|
||||
try:
|
||||
deadline = date.fromisoformat(report.get("livepatch_upgrade_required") or "")
|
||||
except ValueError:
|
||||
deadline = None
|
||||
if (state not in LIVEPATCH_HEALTHY_STATES or report.get("livepatch_check_state") != "checked"
|
||||
or report.get("livepatch_supported") != "supported"):
|
||||
return False, f"livepatch not healthy ({state}, {report.get('livepatch_supported') or '?'})"
|
||||
if deadline is None:
|
||||
return False, "livepatch end of support date unknown"
|
||||
left = (deadline - datetime.fromtimestamp(now, timezone.utc).date()).days
|
||||
if left <= LIVEPATCH_MARGIN_DAYS:
|
||||
return False, f"livepatch support for this kernel ends {deadline}; reboot into a newer one"
|
||||
return True, f"live-patched; kernel upgrade needed by {deadline}"
|
||||
|
||||
|
||||
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 []
|
||||
return bool(pkgs) and all(p.startswith("linux-") for p in pkgs)
|
||||
|
||||
|
||||
def _version_tuple(v: str) -> tuple[int, ...]:
|
||||
return tuple(int(p) if p.isdigit() else 0 for p in v.split("."))
|
||||
|
||||
@@ -128,12 +165,21 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float,
|
||||
if age_h > cfg.stale_after_hours:
|
||||
status.raise_to("stale", f"last report {age_h:.0f}h ago")
|
||||
|
||||
covered, livepatch_note = livepatch_cover(report, now)
|
||||
if why := kernel_reboot_pending(report):
|
||||
if covered:
|
||||
status.note(f"kernel: {why} ({livepatch_note})")
|
||||
else:
|
||||
status.raise_to("reboot", f"kernel: {why}")
|
||||
if report.get("reboot_required"):
|
||||
pkgs = report.get("reboot_required_pkgs") or []
|
||||
detail = f" ({', '.join(pkgs[:5])}{', …' if len(pkgs) > 5 else ''})" if pkgs else ""
|
||||
if covered and _kernel_only_reboot_file(report):
|
||||
status.note(f"/run/reboot-required{detail} ({livepatch_note})")
|
||||
else:
|
||||
status.raise_to("reboot", f"/run/reboot-required{detail}")
|
||||
if livepatch_note and not covered:
|
||||
status.note(livepatch_note)
|
||||
|
||||
if kernels := report.get("kernel_upgradable"):
|
||||
status.raise_to("update", f"kernel update available: {', '.join(kernels)}")
|
||||
|
||||
@@ -496,6 +496,9 @@ 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("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 '?'}"),
|
||||
field("Kernel packages upgradable", r.get("kernel_upgradable"), code=True),
|
||||
field("Updates pending", r.get("upgradable_count")),
|
||||
field("Security updates", r.get("security_count")),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import os
|
||||
import re
|
||||
import unittest
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from helpers import REPO, Config
|
||||
from kernelwatch import AGENT_VERSION
|
||||
@@ -25,6 +26,80 @@ def report(**kw):
|
||||
return base
|
||||
|
||||
|
||||
def livepatched(days_left=300, **kw):
|
||||
"""A report from an Ubuntu host with a newer kernel installed and healthy Livepatch."""
|
||||
deadline = datetime.fromtimestamp(NOW, timezone.utc).date() + timedelta(days=days_left)
|
||||
fields = dict(kernel_running="6.8.0-136-generic", kernel_newest_installed="6.8.0-138-generic",
|
||||
needrestart_ksta=None, livepatch_state="applied", livepatch_check_state="checked",
|
||||
livepatch_supported="supported", livepatch_upgrade_required=deadline.isoformat(),
|
||||
livepatch_fix_count=2)
|
||||
fields.update(kw)
|
||||
return report(**fields)
|
||||
|
||||
|
||||
class LivepatchTest(unittest.TestCase):
|
||||
def evaluate(self, rep):
|
||||
return evaluate(NOW - 60, rep, NOW, CFG)
|
||||
|
||||
def test_without_livepatch_a_newer_kernel_needs_a_reboot(self):
|
||||
rep = livepatched()
|
||||
for k in [k for k in rep if k.startswith("livepatch_")]:
|
||||
del rep[k]
|
||||
self.assertEqual(self.evaluate(rep).level, "reboot")
|
||||
|
||||
def test_healthy_livepatch_turns_pending_kernel_into_a_note(self):
|
||||
s = self.evaluate(livepatched())
|
||||
self.assertEqual(s.level, "ok")
|
||||
self.assertEqual(len(s.reasons), 1)
|
||||
self.assertIn("running 6.8.0-136-generic, 6.8.0-138-generic installed", s.reasons[0])
|
||||
self.assertIn("live-patched; kernel upgrade needed by", s.reasons[0])
|
||||
|
||||
def test_nothing_to_apply_also_counts_as_healthy(self):
|
||||
self.assertEqual(self.evaluate(livepatched(livepatch_state="nothing-to-apply")).level, "ok")
|
||||
|
||||
def test_cover_lapses_two_weeks_before_support_ends(self):
|
||||
self.assertEqual(self.evaluate(livepatched(days_left=15)).level, "ok")
|
||||
s = self.evaluate(livepatched(days_left=14))
|
||||
self.assertEqual(s.level, "reboot")
|
||||
self.assertTrue(any("livepatch support for this kernel ends" in r for r in s.reasons), s.reasons)
|
||||
self.assertEqual(self.evaluate(livepatched(days_left=-5)).level, "reboot")
|
||||
|
||||
def test_unhealthy_livepatch_gives_no_cover(self):
|
||||
for kw in ({"livepatch_state": "apply-failed"}, {"livepatch_state": "applying"},
|
||||
{"livepatch_check_state": "check-failed"},
|
||||
{"livepatch_supported": "unsupported"},
|
||||
{"livepatch_upgrade_required": ""}, {"livepatch_upgrade_required": "soon"}):
|
||||
with self.subTest(kw=kw):
|
||||
s = self.evaluate(livepatched(**kw))
|
||||
self.assertEqual(s.level, "reboot")
|
||||
self.assertTrue(any("livepatch" in r for r in s.reasons), s.reasons)
|
||||
|
||||
def test_unhealthy_livepatch_is_noted_even_when_nothing_is_pending(self):
|
||||
rep = report(livepatch_state="apply-failed", livepatch_check_state="checked",
|
||||
livepatch_supported="supported", livepatch_upgrade_required="2099-01-01")
|
||||
s = self.evaluate(rep)
|
||||
self.assertEqual(s.level, "ok")
|
||||
self.assertIn("livepatch not healthy (apply-failed, supported)", s.reasons)
|
||||
|
||||
def test_reboot_required_for_kernel_packages_only_is_covered(self):
|
||||
rep = livepatched(reboot_required=True,
|
||||
reboot_required_pkgs=["linux-image-6.8.0-138-generic", "linux-base"])
|
||||
self.assertEqual(self.evaluate(rep).level, "ok")
|
||||
|
||||
def test_reboot_required_for_other_packages_still_counts(self):
|
||||
for pkgs in (["libc6"], ["linux-image-6.8.0-138-generic", "libc6"], []):
|
||||
with self.subTest(pkgs=pkgs):
|
||||
rep = livepatched(reboot_required=True, reboot_required_pkgs=pkgs)
|
||||
s = self.evaluate(rep)
|
||||
self.assertEqual(s.level, "reboot")
|
||||
self.assertTrue(any(r.startswith("/run/reboot-required") for r in s.reasons))
|
||||
|
||||
def test_in_place_kernel_upgrade_is_covered_too(self):
|
||||
rep = livepatched(kernel_running="6.8.0-136-generic", kernel_newest_installed="6.8.0-136-generic",
|
||||
kernel_build="#136-Ubuntu SMP", kernel_running_pkg_version="6.8.0-138.138")
|
||||
self.assertEqual(self.evaluate(rep).level, "ok")
|
||||
|
||||
|
||||
class EvaluateTest(unittest.TestCase):
|
||||
def level(self, rep, age=60):
|
||||
return evaluate(NOW - age, rep, NOW, CFG)
|
||||
|
||||
@@ -174,6 +174,17 @@ class DashboardTest(ServerCase):
|
||||
body = self.request("GET", path, headers=cookie)[2]
|
||||
self.assertIn("registered as web01 but reports itself as db01.example.internal <b>", body)
|
||||
|
||||
def test_host_page_shows_livepatch(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,
|
||||
"livepatch_state": "applied", "livepatch_fix_count": 2,
|
||||
"livepatch_supported": "supported",
|
||||
"livepatch_upgrade_required": "2099-09-07"})
|
||||
_, headers, _ = self.login("admin", "a-long-password")
|
||||
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_login_dashboard_logout(self):
|
||||
self.add_user("admin", "a-long-password")
|
||||
token = self.add_host("web01")
|
||||
|
||||
Reference in new issue
Block a user