Merge pull request 'Flag hosts where unattended-upgrades has stopped succeeding' (#27) from feat/unattended-upgrades into main
CI / tests (Python 3.10) (push) Successful in 31s
CI / tests (Python 3.11) (push) Successful in 31s
CI / tests (Python 3.12) (push) Successful in 31s
CI / tests (Python 3.13) (push) Successful in 31s
CI / lint (push) Successful in 3s

Reviewed-on: #27
This commit was merged in pull request #27.
This commit is contained in:
patrick committed 2026-11-01 00:28:50 +00:00
commit 4f45187ca0
13 files changed
+267 -5

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, or apt itself fails, so "no updates" can't be trusted. Also when `/boot` is too full for the next kernel, dpkg left packages half-installed, or the OS release no longer gets security updates. | | `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, dpkg left packages half-installed, the OS release no longer gets security updates, or unattended-upgrades is enabled but has stopped succeeding. |
| `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
+39 -1
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.7.0 AGENT_VERSION=0.8.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:-}
@@ -261,6 +261,39 @@ unfinished_packages() {
sort -u || true sort -u || true
} }
# unattended-upgrades: "enabled", "disabled" or "not-installed". Enabled means the
# package is installed (not just its leftover config, dpkg state rc) and
# APT::Periodic::Unattended-Upgrade is set and not 0, which is what makes
# apt-daily-upgrade.service (apt.systemd.daily) run it.
unattended_upgrades_state() {
local abbrev value
abbrev=$(dpkg-query -W -f='${db:Status-Abbrev}' unattended-upgrades 2>/dev/null || true)
if [[ $abbrev != ii* ]]; then
printf 'not-installed'
return 0
fi
value=$(apt-config dump APT::Periodic::Unattended-Upgrade 2>/dev/null |
sed -n 's/^APT::Periodic::Unattended-Upgrade "\(.*\)";$/\1/p' | tail -n1 || true)
if [[ -n $value && $value != 0 ]]; then printf 'enabled'; else printf 'disabled'; fi
}
# Seconds since the file at $1 was modified, or empty if it doesn't exist.
file_age() {
local m
m=$(stat -c %Y "$1" 2>/dev/null) || return 0
printf '%s' $(($(date +%s) - m))
}
# apt.systemd.daily touches upgrade-stamp only when unattended-upgrade exits 0.
# unattended-upgrade writes its own stamp whenever a run gets far enough to know
# what it would do, even if it then fails (e.g. on a conffile prompt). So a newer
# run stamp than success stamp means it's running but failing.
UU_SUCCESS_STAMP=$ROOT/var/lib/apt/periodic/upgrade-stamp
UU_RUN_STAMP=$ROOT/var/lib/apt/periodic/unattended-upgrades-stamp
# Packages from its allowed origins it didn't upgrade (held, blacklisted, conffile
# prompt), space-separated; removed when there are none.
UU_KEPT_FILE=$ROOT/var/lib/unattended-upgrades/kept-back
# Ubuntu Pro state from the pro client's status cache, which it keeps # Ubuntu Pro state from the pro client's status cache, which it keeps
# world-readable (the token lives in private/ next to it). Prints "ATTACHED ESM" # world-readable (the token lives in private/ next to it). Prints "ATTACHED ESM"
# (e.g. "true enabled", "false -"); nothing if there's no file or it can't be # (e.g. "true enabled", "false -"); nothing if there's no file or it can't be
@@ -361,6 +394,11 @@ build_report() {
*) printf '"ubuntu_pro_attached":null,' ;; *) printf '"ubuntu_pro_attached":null,' ;;
esac esac
printf '"ubuntu_esm_infra":%s,' "$(json_str_or_null "$pro_esm")" printf '"ubuntu_esm_infra":%s,' "$(json_str_or_null "$pro_esm")"
printf '"unattended_upgrades":%s,' "$(json_str "$(unattended_upgrades_state)")"
printf '"unattended_upgrades_success_age_seconds":%s,' "$(json_int "$(file_age "$UU_SUCCESS_STAMP")")"
printf '"unattended_upgrades_run_age_seconds":%s,' "$(json_int "$(file_age "$UU_RUN_STAMP")")"
printf '"unattended_upgrades_kept_back":%s,' \
"$( { [[ -r $UU_KEPT_FILE ]] && tr -s ' \t' '\n' <"$UU_KEPT_FILE"; } | sort -u | json_str_array)"
printf '"apt_lists_age_seconds":%s,' "$(json_int "$(apt_lists_age)")" printf '"apt_lists_age_seconds":%s,' "$(json_int "$(apt_lists_age)")"
printf '"uptime_seconds":%s' "$(json_int "$(uptime_seconds)")" printf '"uptime_seconds":%s' "$(json_int "$(uptime_seconds)")"
printf '}\n' printf '}\n'
+19 -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. | | `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 (`apt_stale_after_hours`) for "no updates" to mean anything. Also when `/boot` has less than `boot_min_free_mb` free, dpkg left packages half-installed, or the OS release no longer gets security updates. | | `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, dpkg left packages half-installed, the OS release no longer gets security updates, or unattended-upgrades is enabled but hasn't succeeded in `unattended_upgrades_stale_after_days`. |
| `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 also lists the reasons behind its status, and clicking a host shows Each row also lists the reasons behind its status, and clicking a host shows
@@ -108,6 +108,24 @@ How the agent works it out:
the server, so they need a kernelwatch update when a new release ships; the server, so they need a kernelwatch update when a new release ships;
a release the table doesn't know is noted. Agents before 0.7.0 don't report a release the table doesn't know is noted. Agents before 0.7.0 don't report
ESM, so an Ubuntu host on one counts as having none. ESM, so an Ubuntu host on one counts as having none.
- **unattended-upgrades**: Ubuntu Server enables it by default, and when it breaks
(a conffile prompt, a held package, a disabled timer) nothing shows until
security updates pile up. For hosts where it's **enabled** (the package is
installed and `APT::Periodic::Unattended-Upgrade` isn't `0`; leftover config
from a removed package doesn't count), the agent reports two timestamps from
`/var/lib/apt/periodic/`: `upgrade-stamp`, which apt's daily job touches only
when unattended-upgrades exits successfully, and `unattended-upgrades-stamp`,
which unattended-upgrades writes whenever a run gets far enough, even if it then
fails. No success in `unattended_upgrades_stale_after_days` (default 3) puts the
host in `update`, and the reason says which way it broke: "is failing" (it
runs, so read `/var/log/unattended-upgrades/` on the host) or "hasn't run" (check
`systemctl status apt-daily-upgrade.timer`). Packages it keeps back (held,
blacklisted, waiting on a conffile prompt) from
`/var/lib/unattended-upgrades/kept-back` are noted. Hosts where it's disabled or
not installed aren't affected; the host page shows which. It assumes the stock
`apt-daily-upgrade.timer` runs it: if you run `unattended-upgrade` from cron or
Ansible instead, the stamp isn't updated, so set
`unattended_upgrades_stale_after_days = 0`. Agents before 0.8.0 don't report it.
- **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.7.0" AGENT_VERSION = "0.8.0"
+5
View File
@@ -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:
+4
View File
@@ -47,6 +47,10 @@ FIELDS: dict[str, str] = {
"dpkg_unfinished_packages": "strlist", "dpkg_unfinished_packages": "strlist",
"ubuntu_pro_attached": "bool", "ubuntu_pro_attached": "bool",
"ubuntu_esm_infra": "str", "ubuntu_esm_infra": "str",
"unattended_upgrades": "str",
"unattended_upgrades_success_age_seconds": "int",
"unattended_upgrades_run_age_seconds": "int",
"unattended_upgrades_kept_back": "strlist",
"apt_lists_age_seconds": "int", "apt_lists_age_seconds": "int",
"uptime_seconds": "int", "uptime_seconds": "int",
} }
+46
View File
@@ -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
+13
View File
@@ -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),
+5
View File
@@ -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
+60 -1
View File
@@ -60,10 +60,14 @@ class AgentCase(unittest.TestCase):
'-v) echo "#1 SMP PREEMPT_DYNAMIC Debian 6.12.48-1";; esac\n') '-v) echo "#1 SMP PREEMPT_DYNAMIC Debian 6.12.48-1";; esac\n')
stub(self.bin, "hostname", "echo web01.example\n") stub(self.bin, "hostname", "echo web01.example\n")
# The full-database query (unfinished packages) prints $KERNELWATCH_ROOT/dpkg-all. # 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;; ' # The unattended-upgrades query prints $KERNELWATCH_ROOT/dpkg-uu (its status, e.g. "ii ").
stub(self.bin, "dpkg-query", 'case "$*" in *" unattended-upgrades") cat "$KERNELWATCH_ROOT/dpkg-uu" 2>/dev/null;; '
'*binary:Package*) cat "$KERNELWATCH_ROOT/dpkg-all" 2>/dev/null;; '
'*Version*) echo "ii 6.12.48-2";; *) cat <<\'X\'\n' '*Version*) echo "ii 6.12.48-2";; *) cat <<\'X\'\n'
f"{DPKG_DEBIAN}X\n;; esac\n") f"{DPKG_DEBIAN}X\n;; esac\n")
self.stub_df("/dev/sda1 999320 187364 743144 21% /boot\n") self.stub_df("/dev/sda1 999320 187364 743144 21% /boot\n")
# `apt-config dump KEY` prints $KERNELWATCH_ROOT/apt-config (nothing: the key is unset).
stub(self.bin, "apt-config", 'cat "$KERNELWATCH_ROOT/apt-config" 2>/dev/null; exit 0\n')
stub(self.bin, "apt-get", f"cat <<'X'\n{APT_SIM_DEBIAN}X\n") stub(self.bin, "apt-get", f"cat <<'X'\n{APT_SIM_DEBIAN}X\n")
def tearDown(self): def tearDown(self):
@@ -212,6 +216,61 @@ class AgentReportTest(AgentCase):
r = self.report() r = self.report()
self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (True, None)) self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (True, None))
def write_root(self, path, text="", age=None):
path = os.path.join(self.root, path)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
f.write(text)
if age is not None:
t = time.time() - age
os.utime(path, (t, t))
def uu(self, status="ii ", setting=None):
self.write_root("dpkg-uu", status)
if setting is not None:
self.write_root("apt-config", f'APT::Periodic::Unattended-Upgrade "{setting}";\n')
def test_unattended_upgrades_enabled(self):
self.uu(setting="1")
self.write_root("var/lib/apt/periodic/upgrade-stamp", age=6 * 3600)
self.write_root("var/lib/apt/periodic/unattended-upgrades-stamp", age=6 * 3600)
r = self.report()
self.assertEqual(r["unattended_upgrades"], "enabled")
self.assertAlmostEqual(r["unattended_upgrades_success_age_seconds"], 6 * 3600, delta=60)
self.assertAlmostEqual(r["unattended_upgrades_run_age_seconds"], 6 * 3600, delta=60)
self.assertEqual(r["unattended_upgrades_kept_back"], [])
def test_unattended_upgrades_interval_other_than_1_counts_as_enabled(self):
for setting in ("7", "always"):
with self.subTest(setting=setting):
self.uu(setting=setting)
self.assertEqual(self.report()["unattended_upgrades"], "enabled")
def test_unattended_upgrades_switched_off(self):
for setting in ("0", ""):
with self.subTest(setting=setting):
self.uu(setting=setting)
self.assertEqual(self.report()["unattended_upgrades"], "disabled")
os.remove(os.path.join(self.root, "apt-config"))
self.assertEqual(self.report()["unattended_upgrades"], "disabled", "setting absent")
def test_unattended_upgrades_removed_but_config_left(self):
# dpkg state rc keeps /etc/apt/apt.conf.d/20auto-upgrades, so the setting still reads 1.
self.uu(status="rc ", setting="1")
self.assertEqual(self.report()["unattended_upgrades"], "not-installed")
def test_unattended_upgrades_not_installed(self):
r = self.report()
self.assertEqual(r["unattended_upgrades"], "not-installed")
self.assertIsNone(r["unattended_upgrades_success_age_seconds"])
self.assertIsNone(r["unattended_upgrades_run_age_seconds"])
def test_unattended_upgrades_kept_back(self):
self.uu(setting="1")
self.write_root("var/lib/unattended-upgrades/kept-back", "openssl libssl3t64 linux-image-amd64")
self.assertEqual(self.report()["unattended_upgrades_kept_back"],
["libssl3t64", "linux-image-amd64", "openssl"])
def test_every_reported_field_is_accepted_by_the_server(self): def test_every_reported_field_is_accepted_by_the_server(self):
from kernelwatch.report import FIELDS from kernelwatch.report import FIELDS
self.write_livepatch("LIVEPATCH-STATE: applied\nLIVEPATCH-FIXES: 2\n") self.write_livepatch("LIVEPATCH-STATE: applied\nLIVEPATCH-FIXES: 2\n")
+9
View File
@@ -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:
+51
View File
@@ -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")
+14
View File
@@ -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")