CI / tests (Python 3.10) (pull_request) Successful in 36s
CI / tests (Python 3.11) (pull_request) Successful in 36s
CI / tests (Python 3.12) (pull_request) Successful in 37s
CI / tests (Python 3.13) (pull_request) Successful in 37s
CI / lint (pull_request) Successful in 4s
security_count is only meaningful if apt has the release's security suite. A host missing it from its sources shows 0 security updates forever, and one whose apt can't fetch it (expired key, wrong URL after a release upgrade, a mirror that fell behind) keeps the last copy while the update stamps and other lists move on, so neither the simulation nor the package list age notices. The agent (0.9.0) now finds apt's list for <codename>-security by its Suite: (Ubuntu) or Codename: (Debian) field, since file names depend on the mirror (mirror+file: sources, several mirrors), and reports security_repo_suite and security_repo_age_seconds from its Date:, the newest copy winning. The server puts the host in update when there's no such list, or when it's older than security_repo_stale_after_days (default 7) while the package lists are otherwise fresh; if all of them are old, the existing "package lists N days old" reason covers it. Releases past the end of support are skipped: their suite has stopped publishing, and support.check already says so. ESM suites publish too rarely to judge by date and aren't checked. The host page gets a "Security repository" row. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
383 lines
17 KiB
Python
383 lines
17 KiB
Python
"""Turn a host's latest report into a dashboard status.
|
|
|
|
Levels, worst first:
|
|
stale - no report recently (or ever); nothing else can be trusted
|
|
reboot - a newer kernel (or other reboot-requiring update) is installed but not running
|
|
update - updates are waiting to be installed, or the package lists are too old to tell
|
|
ok - running the newest installed kernel, nothing pending
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import time
|
|
from dataclasses import dataclass, field
|
|
from datetime import date, datetime, timezone
|
|
from typing import Any
|
|
|
|
from . import AGENT_VERSION, support
|
|
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
|
|
KSTA_VERSION_UPGRADE = 3
|
|
|
|
|
|
@dataclass
|
|
class Status:
|
|
level: str = "ok"
|
|
reasons: list[str] = field(default_factory=list)
|
|
|
|
def raise_to(self, level: str, reason: str) -> None:
|
|
if _RANK[level] < _RANK[self.level]:
|
|
self.level = level
|
|
self.reasons.append(reason)
|
|
|
|
def note(self, reason: str) -> None:
|
|
"""A reason worth showing that doesn't change the level."""
|
|
self.reasons.append(reason)
|
|
|
|
@property
|
|
def rank(self) -> int:
|
|
return _RANK[self.level]
|
|
|
|
|
|
# Debian `uname -v`: "#1 SMP PREEMPT_DYNAMIC Debian 6.12.57-1 (2025-11-05)"
|
|
_DEBIAN_BUILD = re.compile(r"\bDebian (\S+)")
|
|
# Ubuntu `uname -v`: "#85-Ubuntu SMP ..." (GA) or "#33~24.04.1-Ubuntu SMP ..." (HWE)
|
|
_UBUNTU_BUILD = re.compile(r"^#(\S+)-Ubuntu\b")
|
|
# Ubuntu package version: "6.8.0-85.85" or "6.14.0-33.33~24.04.1"; upload part after "-ABI."
|
|
_UBUNTU_PKG = re.compile(r"^\d+\.\d+\.\d+-\d+\.(\S+)$")
|
|
|
|
|
|
def running_build(report: dict[str, Any]) -> tuple[str, str] | None:
|
|
"""(build of the running kernel, installed package version of that kernel), in
|
|
comparable form, or None if we can't tell (e.g. an unrecognised build string).
|
|
|
|
If they differ, the package was upgraded in place since boot (same `uname -r`)."""
|
|
build = report.get("kernel_build") or ""
|
|
pkg = report.get("kernel_running_pkg_version")
|
|
if not pkg:
|
|
return None
|
|
if m := _DEBIAN_BUILD.search(build):
|
|
return m.group(1), pkg
|
|
if (m := _UBUNTU_BUILD.match(build)) and (p := _UBUNTU_PKG.match(pkg)):
|
|
return m.group(1), p.group(1)
|
|
return None
|
|
|
|
|
|
def kernel_reboot_pending(report: dict[str, Any]) -> str | None:
|
|
"""Why the running kernel is out of date, or None if it isn't (as far as we can tell)."""
|
|
running = report.get("kernel_running") or "?"
|
|
newest = report.get("kernel_newest_installed")
|
|
|
|
if build := running_build(report):
|
|
built, installed = build
|
|
if built != installed:
|
|
return f"running {running} build {built}, package upgraded in place to {installed}"
|
|
# Conclusive, so skip needrestart: run unprivileged it can't read Ubuntu's
|
|
# root-only /boot images and reports false ABI upgrades.
|
|
if newest and newest != running:
|
|
return f"running {running}, {newest} installed"
|
|
return None
|
|
|
|
ksta = report.get("needrestart_ksta")
|
|
if ksta == KSTA_VERSION_UPGRADE:
|
|
expected = report.get("needrestart_kexp") or report.get("kernel_newest_installed") or "?"
|
|
return f"running {running}, {expected} installed"
|
|
if ksta == KSTA_ABI_UPGRADE:
|
|
return f"running {running}, an ABI-compatible update of it is installed"
|
|
if ksta == KSTA_CURRENT:
|
|
return None
|
|
|
|
# No usable needrestart result: compare against the newest installed image.
|
|
if newest and newest != running:
|
|
return f"running {running}, {newest} installed"
|
|
return None
|
|
|
|
|
|
def livepatch_problem(report: dict[str, Any]) -> str | None:
|
|
"""Why Livepatch isn't working on this host, or None if it is (or isn't in use).
|
|
|
|
"Working" means a state we recognise as healthy, a completed check and a
|
|
supported kernel. The same test decides cover for a pending reboot and whether
|
|
to send a Livepatch alert."""
|
|
state = report.get("livepatch_state")
|
|
if state is None:
|
|
return None
|
|
if (state not in LIVEPATCH_HEALTHY_STATES or report.get("livepatch_check_state") != "checked"
|
|
or report.get("livepatch_supported") != "supported"):
|
|
parts = [state, report.get("livepatch_supported") or "?"]
|
|
if report.get("livepatch_check_state") != "checked":
|
|
parts.append(f"check: {report.get('livepatch_check_state') or '?'}")
|
|
return f"livepatch not healthy ({', '.join(parts)})"
|
|
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."""
|
|
if report.get("livepatch_state") is None:
|
|
return False, None
|
|
if problem := livepatch_problem(report):
|
|
return False, problem
|
|
try:
|
|
deadline = date.fromisoformat(report.get("livepatch_upgrade_required") or "")
|
|
except ValueError:
|
|
deadline = None
|
|
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 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"
|
|
|
|
|
|
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 security_repo_problem(report: dict[str, Any], cfg: Config, today: date) -> str | None:
|
|
"""Why security updates may not be reaching this host from its release's security
|
|
suite, or None. Agents before 0.9.0, and releases without a codename, don't
|
|
report the suite.
|
|
|
|
The age is of the suite's Date: field as of apt's last successful fetch of it, so
|
|
it keeps growing when fetching that repository fails, even while the update
|
|
stamps and other lists move on."""
|
|
suite = report.get("security_repo_suite")
|
|
if not suite or not cfg.security_repo_stale_after_days:
|
|
return None
|
|
rel = support.release(report)
|
|
if rel is not None and today > rel.end:
|
|
return None # the suite has stopped publishing; support.check covers it
|
|
age = report.get("security_repo_age_seconds")
|
|
if age is None:
|
|
return (f"apt has no {suite} repository, so security updates can't arrive; "
|
|
"add it to the apt sources and run apt update")
|
|
if age <= cfg.security_repo_stale_after_days * 86400:
|
|
return None
|
|
apt_age = report.get("apt_lists_age_seconds")
|
|
if apt_age is None or apt_age / 3600 > cfg.apt_stale_after_hours:
|
|
return None # apt isn't refreshing anything; the package list reason covers it
|
|
return (f"apt's {suite} list is {_age(age)} old while apt update otherwise succeeds; "
|
|
f"run apt update and look for errors about {suite}")
|
|
|
|
|
|
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("."))
|
|
|
|
|
|
def agent_outdated(version: str | None) -> bool:
|
|
return bool(version) and _version_tuple(version) < _version_tuple(AGENT_VERSION)
|
|
|
|
|
|
def hostname_mismatch(registered: str, report: dict[str, Any]) -> str | None:
|
|
"""The hostname the agent reports, if it can't be the machine `registered` names.
|
|
|
|
Registered names are usually `hostname -s` while the agent reports `hostname -f`,
|
|
so only the first DNS label is compared, ignoring case."""
|
|
reported = report.get("reported_hostname")
|
|
if not reported or reported.split(".")[0].lower() == registered.split(".")[0].lower():
|
|
return None
|
|
return reported
|
|
|
|
|
|
def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float,
|
|
cfg: Config, host: str | None = None) -> Status:
|
|
status = Status()
|
|
if received_at is None or report is None:
|
|
status.raise_to("stale", "never reported")
|
|
return status
|
|
|
|
age_h = (now - received_at) / 3600
|
|
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)
|
|
|
|
# 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"):
|
|
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 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()
|
|
if found := support.check(report, today, cfg.os_eol_warn_days):
|
|
problem, why = found
|
|
if problem:
|
|
status.raise_to("update", why)
|
|
else:
|
|
status.note(why)
|
|
|
|
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 ""
|
|
n = len(services)
|
|
status.raise_to("update", f"{n} service{'s' if n != 1 else ''} need{'' if n != 1 else 's'} "
|
|
f"restart: {shown}{more}")
|
|
|
|
apt_age = report.get("apt_lists_age_seconds")
|
|
if apt_age is None:
|
|
status.raise_to("update", "package list age unknown")
|
|
elif apt_age / 3600 > cfg.apt_stale_after_hours:
|
|
status.raise_to("update", f"package lists {apt_age / 86400:.0f}d old; apt update not running?")
|
|
if why := security_repo_problem(report, cfg, datetime.fromtimestamp(now, timezone.utc).date()):
|
|
status.raise_to("update", why)
|
|
|
|
if host and (reported := hostname_mismatch(host, report)):
|
|
status.note(f"registered as {host} but reports itself as {reported}; "
|
|
"token on the wrong machine?")
|
|
|
|
if agent_outdated(report.get("agent_version")):
|
|
status.note(f"agent {report['agent_version']} is older than {AGENT_VERSION}; "
|
|
"run agent/deploy.sh")
|
|
|
|
return status
|
|
|
|
|
|
def _iso(ts: float | None) -> str | None:
|
|
return None if ts is None else time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(ts))
|
|
|
|
|
|
def fleet_status(rows: list[dict[str, Any]], now: float, cfg: Config) -> dict[str, Any]:
|
|
"""The whole fleet as plain data, worst hosts first (as the dashboard orders them).
|
|
|
|
`rows` are db.latest_reports() entries. A stable, secret-free shape for scripts:
|
|
status and reasons come from evaluate(), the same call the dashboard makes."""
|
|
hosts = []
|
|
for row in rows:
|
|
report = row["report"] or {}
|
|
status = evaluate(row["received_at"], row["report"], now, cfg, row["host"])
|
|
livepatch = None
|
|
if report.get("livepatch_state") is not None:
|
|
livepatch = {"state": report["livepatch_state"],
|
|
"supported": report.get("livepatch_supported"),
|
|
"upgrade_required": report.get("livepatch_upgrade_required"),
|
|
"fixes": report.get("livepatch_fix_count")}
|
|
hosts.append({
|
|
"name": row["host"],
|
|
"status": status.level,
|
|
"reasons": status.reasons,
|
|
"last_report_at": _iso(row["received_at"]),
|
|
"last_report_age_seconds": None if row["received_at"] is None else max(0, int(now - row["received_at"])),
|
|
"os": report.get("os_pretty_name"),
|
|
"kernel_running": report.get("kernel_running"),
|
|
"kernel_newest_installed": report.get("kernel_newest_installed"),
|
|
"reboot_required": report.get("reboot_required"),
|
|
"updates_pending": report.get("upgradable_count"),
|
|
"security_updates": report.get("security_count"),
|
|
"kernel_updates": report.get("kernel_upgradable"),
|
|
"services_need_restart": report.get("services_need_restart"),
|
|
"livepatch": livepatch,
|
|
"uptime_seconds": report.get("uptime_seconds"),
|
|
"agent_version": report.get("agent_version"),
|
|
"_rank": status.rank,
|
|
})
|
|
hosts.sort(key=lambda h: (h["_rank"], h["name"]))
|
|
counts = {level: 0 for level in LEVELS}
|
|
for h in hosts:
|
|
counts[h["status"]] += 1
|
|
del h["_rank"]
|
|
return {"generated_at": _iso(now), "counts": counts, "hosts": hosts}
|