CI / tests (Python 3.10) (pull_request) Successful in 43s
CI / tests (Python 3.11) (pull_request) Successful in 44s
CI / tests (Python 3.12) (pull_request) Successful in 43s
CI / tests (Python 3.13) (pull_request) Successful in 42s
CI / lint (pull_request) Successful in 3s
A filesystem that fills up while apt downloads or dpkg unpacks leaves the upgrade half-done and apt broken, the same failure as a full /boot but on / or /var. Nothing caught it until the host's updates stopped. The agent (0.11.0) now works out what the pending upgrades need. A simulation doesn't print apt's "Need to get" or "additional disk space" lines, so it sums the package records from apt-cache show for each version the simulation would install: Size for each .deb not already in /var/cache/apt/archives, and the growth in Installed-Size over the installed versions (from dpkg-query). Removals aren't subtracted, so it errs high. It also reports free space and the mount point of the filesystems holding /var/cache/apt/archives and /usr. The server puts a host in update when the upgrades would leave less than upgrade_min_free_mb (default 100, 0 disables) on either filesystem. The download and the install both count when they're on the same one. With nothing pending there is nothing to check, so this doesn't turn into general disk monitoring. The host page gets a "Pending upgrades size" row. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
733 lines
36 KiB
Python
733 lines
36 KiB
Python
"""Runs the real agent script against stubbed system commands and a fake root."""
|
|
|
|
import json
|
|
import os
|
|
import shutil
|
|
import stat
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
import unittest
|
|
|
|
from helpers import REPO, temp_config, tempdir
|
|
from kernelwatch import auth, db, web
|
|
from kernelwatch.status import evaluate
|
|
|
|
AGENT = os.path.join(REPO, "agent", "kernelwatch-agent")
|
|
|
|
DPKG_DEBIAN = """\
|
|
ii linux-image-6.12.48+deb13-amd64
|
|
ii linux-image-6.12.57+deb13-amd64
|
|
rc linux-image-6.12.38+deb13-amd64
|
|
ii linux-image-6.12.57+deb13-amd64-dbg
|
|
"""
|
|
|
|
APT_SIM_DEBIAN = """\
|
|
NOTE: This is only a simulation!
|
|
Reading package lists...
|
|
Inst libssl3t64 [3.5.1-1] (3.5.1-1+deb13u1 Debian-Security:13/stable-security [amd64])
|
|
Inst linux-image-6.12.60+deb13-amd64 (6.12.60-1 Debian-Security:13/stable-security [amd64])
|
|
Inst curl [8.14.1-2] (8.14.1-2+deb13u1 Debian:13.2/stable [amd64])
|
|
Conf libssl3t64 (3.5.1-1+deb13u1 Debian-Security:13/stable-security [amd64])
|
|
"""
|
|
|
|
# `apt-cache show` records for the simulation's three new versions. curl's record
|
|
# appears twice, as it does when two sources carry the same version.
|
|
APT_CACHE_DEBIAN = """\
|
|
Package: libssl3t64
|
|
Architecture: amd64
|
|
Version: 3.5.1-1+deb13u1
|
|
Installed-Size: 9000
|
|
Size: 2500000
|
|
|
|
Package: linux-image-6.12.60+deb13-amd64
|
|
Architecture: amd64
|
|
Version: 6.12.60-1
|
|
Installed-Size: 400000
|
|
Size: 100000000
|
|
|
|
Package: curl
|
|
Architecture: amd64
|
|
Version: 8.14.1-2+deb13u1
|
|
Installed-Size: 500
|
|
Size: 300000
|
|
|
|
Package: curl
|
|
Architecture: amd64
|
|
Version: 8.14.1-2+deb13u1
|
|
Installed-Size: 500
|
|
Size: 300000
|
|
"""
|
|
|
|
# Installed-Size of the installed libssl3t64 and curl, the two upgrades.
|
|
DPKG_SIZES_DEBIAN = "8900\n500\n"
|
|
|
|
|
|
def stub(bindir, name, script):
|
|
path = os.path.join(bindir, name)
|
|
with open(path, "w") as f:
|
|
f.write("#!/bin/sh\n" + script)
|
|
os.chmod(path, os.stat(path).st_mode | stat.S_IEXEC)
|
|
|
|
|
|
class AgentCase(unittest.TestCase):
|
|
def setUp(self):
|
|
self._tmp = tempdir()
|
|
self.tmp = self._tmp.name
|
|
self.root = os.path.join(self.tmp, "root")
|
|
self.bin = os.path.join(self.tmp, "bin")
|
|
for d in ("etc/kernelwatch", "proc", "run", "var/lib/apt/periodic", self.bin):
|
|
os.makedirs(os.path.join(self.root, d), exist_ok=True)
|
|
with open(os.path.join(self.root, "etc/os-release"), "w") as f:
|
|
f.write('PRETTY_NAME="Debian GNU/Linux 13 (trixie)"\nID=debian\nVERSION_ID="13"\n')
|
|
with open(os.path.join(self.root, "proc/uptime"), "w") as f:
|
|
f.write("93784.21 180000.00\n")
|
|
stamp = os.path.join(self.root, "var/lib/apt/periodic/update-success-stamp")
|
|
open(stamp, "w").close()
|
|
two_hours_ago = time.time() - 7200
|
|
os.utime(stamp, (two_hours_ago, two_hours_ago))
|
|
|
|
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")
|
|
# The full-database query (unfinished packages) prints $KERNELWATCH_ROOT/dpkg-all.
|
|
# The unattended-upgrades query prints $KERNELWATCH_ROOT/dpkg-uu (its status, e.g. "ii ").
|
|
# The Installed-Size query prints $KERNELWATCH_ROOT/dpkg-sizes.
|
|
stub(self.bin, "dpkg-query", 'case "$*" in *Installed-Size*) cat "$KERNELWATCH_ROOT/dpkg-sizes" 2>/dev/null;; '
|
|
'*" 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'
|
|
f"{DPKG_DEBIAN}X\n;; esac\n")
|
|
# df answers per path: /boot and /usr on the root filesystem, apt's archives on /var.
|
|
stub(self.bin, "df", "echo 'Filesystem 1024-blocks Used Available Capacity Mounted on'\n"
|
|
'case "$2" in */var/cache/apt/archives) '
|
|
"echo '/dev/sda2 4062912 3500000 358124 91% /var';; "
|
|
"*) echo '/dev/sda1 999320 187364 743144 21% /';; esac\n")
|
|
with open(os.path.join(self.root, "dpkg-sizes"), "w") as f:
|
|
f.write(DPKG_SIZES_DEBIAN)
|
|
# apt-cache records its arguments in $KERNELWATCH_ROOT/apt-cache-args.
|
|
self.stub_apt_cache(APT_CACHE_DEBIAN)
|
|
# `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")
|
|
|
|
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 stub_apt_cache(self, records, rc=0):
|
|
stub(self.bin, "apt-cache", 'printf "%s\\n" "$@" >"$KERNELWATCH_ROOT/apt-cache-args"\n'
|
|
f"cat <<'X'\n{records}X\nexit {rc}\n")
|
|
|
|
def run_agent(self, *args, env=None):
|
|
full_env = {
|
|
"PATH": f"{self.bin}:{os.environ['PATH']}",
|
|
"KERNELWATCH_ROOT": self.root,
|
|
**(env or {}),
|
|
}
|
|
return subprocess.run(["bash", AGENT, *args], env=full_env, capture_output=True,
|
|
text=True, timeout=30)
|
|
|
|
def report(self):
|
|
proc = self.run_agent("--print")
|
|
self.assertEqual(proc.returncode, 0, proc.stderr)
|
|
return json.loads(proc.stdout)
|
|
|
|
|
|
@unittest.skipUnless(shutil.which("bash") and shutil.which("curl"), "needs bash and curl")
|
|
class AgentReportTest(AgentCase):
|
|
def test_debian_report(self):
|
|
r = self.report()
|
|
self.assertEqual(r["os_id"], "debian")
|
|
self.assertEqual(r["os_version_id"], "13")
|
|
self.assertEqual(r["os_pretty_name"], "Debian GNU/Linux 13 (trixie)")
|
|
self.assertEqual(r["reported_hostname"], "web01.example")
|
|
self.assertEqual(r["kernel_running"], "6.12.48+deb13-amd64")
|
|
self.assertEqual(r["kernels_installed"], ["6.12.48+deb13-amd64", "6.12.57+deb13-amd64"])
|
|
self.assertEqual(r["kernel_newest_installed"], "6.12.57+deb13-amd64")
|
|
self.assertEqual(r["kernel_running_pkg_version"], "6.12.48-2")
|
|
self.assertIsNone(r["needrestart_ksta"])
|
|
self.assertFalse(r["reboot_required"])
|
|
self.assertEqual(r["upgradable_count"], 3)
|
|
self.assertEqual(r["security_count"], 2)
|
|
self.assertEqual(r["kernel_upgradable"], ["linux-image-6.12.60+deb13-amd64"])
|
|
self.assertEqual(r["phased_packages"], [], "Debian: no phasing")
|
|
self.assertAlmostEqual(r["apt_lists_age_seconds"], 7200, delta=60)
|
|
self.assertEqual(r["uptime_seconds"], 93784)
|
|
self.assertIsNone(r["services_need_restart"], "no needrestart results: unknown")
|
|
self.assertIsNone(r["sessions_need_restart"])
|
|
|
|
def write_needrestart(self, text, age=60):
|
|
d = os.path.join(self.root, "run/kernelwatch")
|
|
os.makedirs(d, exist_ok=True)
|
|
path = os.path.join(d, "needrestart")
|
|
with open(path, "w") as f:
|
|
f.write(text)
|
|
t = time.time() - age
|
|
os.utime(path, (t, t))
|
|
|
|
def test_needrestart_results(self):
|
|
self.write_needrestart(
|
|
"NEEDRESTART-VER: 3.6\nNEEDRESTART-KCUR: 6.12.48+deb13-amd64\n"
|
|
"NEEDRESTART-KEXP: 6.12.57+deb13-amd64\nNEEDRESTART-KSTA: 3\n"
|
|
"NEEDRESTART-SVC: ssh.service\nNEEDRESTART-SVC: nginx.service\n"
|
|
"NEEDRESTART-SVC: nginx.service\nNEEDRESTART-SESS: patrick @ session #3\n")
|
|
r = self.report()
|
|
self.assertEqual(r["needrestart_ksta"], 3)
|
|
self.assertEqual(r["needrestart_kexp"], "6.12.57+deb13-amd64")
|
|
self.assertEqual(r["services_need_restart"], ["nginx.service", "ssh.service"])
|
|
self.assertEqual(r["sessions_need_restart"], 1)
|
|
|
|
def test_needrestart_microcode(self):
|
|
self.write_needrestart("NEEDRESTART-KSTA: 1\nNEEDRESTART-UCSTA: 2\n"
|
|
"NEEDRESTART-UCCUR: 0x001e\nNEEDRESTART-UCEXP: 0x0020\n")
|
|
r = self.report()
|
|
self.assertEqual((r["needrestart_ucsta"], r["needrestart_uccur"], r["needrestart_ucexp"]),
|
|
(2, "0x001e", "0x0020"))
|
|
|
|
def test_needrestart_without_microcode_lines(self):
|
|
# Virtual machines: needrestart leaves the UC* lines out.
|
|
self.write_needrestart("NEEDRESTART-KSTA: 1\n")
|
|
r = self.report()
|
|
self.assertIsNone(r["needrestart_ucsta"])
|
|
self.assertIsNone(r["needrestart_uccur"])
|
|
|
|
def write_livepatch(self, text, age=60):
|
|
d = os.path.join(self.root, "run/kernelwatch")
|
|
os.makedirs(d, exist_ok=True)
|
|
path = os.path.join(d, "livepatch")
|
|
with open(path, "w") as f:
|
|
f.write(text)
|
|
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_upgrade_space(self):
|
|
r = self.report()
|
|
# 102.8 MB of .debs, rounded up to KiB; 409500 KiB of new versions less the
|
|
# 9400 KiB of the libssl3t64 and curl they replace.
|
|
self.assertEqual(r["upgrade_download_kb"], 100391)
|
|
self.assertEqual(r["upgrade_install_kb"], 400100)
|
|
self.assertEqual((r["apt_archives_free_kb"], r["apt_archives_mount"]), (358124, "/var"))
|
|
self.assertEqual((r["usr_free_kb"], r["usr_mount"]), (743144, "/"))
|
|
with open(os.path.join(self.root, "apt-cache-args")) as f:
|
|
args = f.read().split()
|
|
self.assertEqual(args[-4:], ["show", "libssl3t64=3.5.1-1+deb13u1",
|
|
"linux-image-6.12.60+deb13-amd64=6.12.60-1", "curl=8.14.1-2+deb13u1"])
|
|
|
|
def test_upgrade_space_skips_downloaded_archives(self):
|
|
archives = os.path.join(self.root, "var/cache/apt/archives")
|
|
os.makedirs(archives)
|
|
open(os.path.join(archives, "curl_8.14.1-2+deb13u1_amd64.deb"), "w").close()
|
|
open(os.path.join(archives, "libssl3t64_3.5.1-1_amd64.deb"), "w").close() # the old version
|
|
self.assertEqual(self.report()["upgrade_download_kb"], 100098)
|
|
|
|
def test_upgrade_space_epoch_in_archive_name(self):
|
|
stub(self.bin, "apt-get", "echo 'Inst tzdata [1:2024a-1] (1:2025b-1 Debian:13/stable [all])'\n")
|
|
self.stub_apt_cache("Package: tzdata\nArchitecture: all\nVersion: 1:2025b-1\n"
|
|
"Installed-Size: 3000\nSize: 2048\n")
|
|
archives = os.path.join(self.root, "var/cache/apt/archives")
|
|
os.makedirs(archives)
|
|
open(os.path.join(archives, "tzdata_1%3a2025b-1_all.deb"), "w").close()
|
|
with open(os.path.join(self.root, "dpkg-sizes"), "w") as f:
|
|
f.write("3100\n")
|
|
r = self.report()
|
|
self.assertEqual((r["upgrade_download_kb"], r["upgrade_install_kb"]), (0, -100))
|
|
|
|
def test_upgrade_space_new_package_counts_in_full(self):
|
|
stub(self.bin, "apt-get", "echo 'Inst linux-image-6.12.60+deb13-amd64 (6.12.60-1 Debian:13/stable [amd64])'\n")
|
|
self.stub_apt_cache(APT_CACHE_DEBIAN.split("\n\n")[1] + "\n")
|
|
os.remove(os.path.join(self.root, "dpkg-sizes"))
|
|
r = self.report()
|
|
self.assertEqual((r["upgrade_download_kb"], r["upgrade_install_kb"]), (97657, 400000))
|
|
|
|
def test_upgrade_space_nothing_pending(self):
|
|
stub(self.bin, "apt-get", "echo 'NOTE: This is only a simulation!'\n")
|
|
r = self.report()
|
|
self.assertEqual((r["upgrade_download_kb"], r["upgrade_install_kb"]), (0, 0))
|
|
self.assertFalse(os.path.exists(os.path.join(self.root, "apt-cache-args")), "apt-cache not run")
|
|
|
|
def test_upgrade_space_unknown_when_apt_cache_fails(self):
|
|
self.stub_apt_cache("", rc=100)
|
|
r = self.report()
|
|
self.assertIsNone(r["upgrade_download_kb"])
|
|
self.assertIsNone(r["upgrade_install_kb"])
|
|
|
|
def test_upgrade_space_unknown_when_simulation_fails(self):
|
|
stub(self.bin, "apt-get", "echo 'E: Unmet dependencies.' >&2; exit 100\n")
|
|
r = self.report()
|
|
self.assertIsNone(r["upgrade_download_kb"])
|
|
self.assertFalse(os.path.exists(os.path.join(self.root, "apt-cache-args")))
|
|
|
|
def test_filesystem_free_unknown_when_df_fails(self):
|
|
self.stub_df("", rc=1)
|
|
r = self.report()
|
|
self.assertIsNone(r["apt_archives_free_kb"])
|
|
self.assertIsNone(r["usr_mount"])
|
|
|
|
def test_mount_point_with_spaces(self):
|
|
self.stub_df("/dev/sdb1 999320 187364 743144 21% /srv/my disk\n")
|
|
self.assertEqual(self.report()["usr_mount"], "/srv/my disk")
|
|
|
|
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_held_packages(self):
|
|
with open(os.path.join(self.root, "dpkg-all"), "w") as f:
|
|
f.write("ii \tcurl\n"
|
|
"hi \tlinux-image-amd64\n"
|
|
"hi \tpostgresql-16\n"
|
|
"hn \tnot-installed\n"
|
|
"hc \tremoved-but-held\n"
|
|
"iF \tbroken\n")
|
|
r = self.report()
|
|
self.assertEqual(r["held_packages"], ["linux-image-amd64", "postgresql-16"])
|
|
self.assertEqual(r["dpkg_unfinished_packages"], ["broken"])
|
|
|
|
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 write_pro_status(self, text):
|
|
d = os.path.join(self.root, "var/lib/ubuntu-advantage")
|
|
os.makedirs(d, exist_ok=True)
|
|
with open(os.path.join(d, "status.json"), "w") as f:
|
|
f.write(text)
|
|
|
|
def test_ubuntu_pro_attached_with_esm(self):
|
|
self.write_pro_status(json.dumps({"attached": True, "services": [
|
|
{"name": "esm-apps", "status": "enabled"}, {"name": "esm-infra", "status": "enabled"},
|
|
{"name": "livepatch", "status": "enabled"}]}))
|
|
r = self.report()
|
|
self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (True, "enabled"))
|
|
|
|
def test_ubuntu_pro_attached_esm_disabled(self):
|
|
self.write_pro_status(json.dumps({"attached": True, "services": [
|
|
{"name": "esm-infra", "status": "disabled"}]}))
|
|
r = self.report()
|
|
self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (True, "disabled"))
|
|
|
|
def test_ubuntu_pro_not_attached(self):
|
|
# Unattached, the cache lists services as available, which isn't the same as on.
|
|
self.write_pro_status(json.dumps({"attached": False, "services": [
|
|
{"name": "esm-infra", "available": "yes", "status": "enabled"}]}))
|
|
r = self.report()
|
|
self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (False, None))
|
|
|
|
def test_no_pro_client_or_unreadable_status(self):
|
|
r = self.report()
|
|
self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (None, None))
|
|
self.write_pro_status("{not json")
|
|
r = self.report()
|
|
self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (None, None))
|
|
|
|
def test_odd_esm_status_is_dropped(self):
|
|
self.write_pro_status(json.dumps({"attached": True, "services": [
|
|
{"name": "esm-infra", "status": "en abled\" x"}]}))
|
|
r = self.report()
|
|
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):
|
|
from kernelwatch.report import FIELDS
|
|
self.write_livepatch("LIVEPATCH-STATE: applied\nLIVEPATCH-FIXES: 2\n")
|
|
self.write_pro_status('{"attached": true, "services": [{"name": "esm-infra", "status": "enabled"}]}')
|
|
self.assertEqual(sorted(set(self.report()) - set(FIELDS)), [])
|
|
|
|
def write_conf(self, text):
|
|
with open(os.path.join(self.root, "etc/kernelwatch/agent.conf"), "w") as f:
|
|
f.write(text)
|
|
|
|
def test_report_hostname_overrides_the_machines_own(self):
|
|
self.write_conf("SERVER_URL=http://x\nREPORT_HOSTNAME=iris\n")
|
|
self.assertEqual(self.report()["reported_hostname"], "iris")
|
|
|
|
def test_blank_report_hostname_uses_the_machines_own(self):
|
|
self.write_conf("REPORT_HOSTNAME=\n")
|
|
self.assertEqual(self.report()["reported_hostname"], "web01.example")
|
|
|
|
def test_report_hostname_is_json_escaped(self):
|
|
self.write_conf('REPORT_HOSTNAME=a"b\\c\n')
|
|
self.assertEqual(self.report()["reported_hostname"], 'a"b\\c')
|
|
|
|
def test_no_livepatch_file_reports_nulls(self):
|
|
r = self.report()
|
|
for key in ("state", "check_state", "supported", "upgrade_required", "fix_count"):
|
|
self.assertIsNone(r["livepatch_" + key])
|
|
|
|
def test_livepatch_results(self):
|
|
self.write_livepatch("LIVEPATCH-STATE: applied\nLIVEPATCH-CHECK: checked\n"
|
|
"LIVEPATCH-SUPPORTED: supported\nLIVEPATCH-UPGRADE-REQUIRED: 2027-09-07\n"
|
|
"LIVEPATCH-FIXES: 2\n")
|
|
r = self.report()
|
|
self.assertEqual((r["livepatch_state"], r["livepatch_check_state"], r["livepatch_supported"]),
|
|
("applied", "checked", "supported"))
|
|
self.assertEqual((r["livepatch_upgrade_required"], r["livepatch_fix_count"]), ("2027-09-07", 2))
|
|
|
|
def test_stale_livepatch_results_ignored(self):
|
|
self.write_livepatch("LIVEPATCH-STATE: applied\nLIVEPATCH-FIXES: 2\n", age=3 * 3600)
|
|
r = self.report()
|
|
self.assertIsNone(r["livepatch_state"])
|
|
self.assertIsNone(r["livepatch_fix_count"])
|
|
|
|
def test_agent_never_runs_livepatch_itself(self):
|
|
marker = os.path.join(self.tmp, "livepatch-ran")
|
|
stub(self.bin, "canonical-livepatch", f"touch {marker}\n")
|
|
self.report()
|
|
self.assertFalse(os.path.exists(marker))
|
|
|
|
def test_needrestart_nothing_to_restart(self):
|
|
self.write_needrestart("NEEDRESTART-VER: 3.6\nNEEDRESTART-KSTA: 1\n")
|
|
r = self.report()
|
|
self.assertEqual(r["services_need_restart"], [])
|
|
self.assertEqual(r["sessions_need_restart"], 0)
|
|
|
|
def test_stale_needrestart_results_ignored(self):
|
|
self.write_needrestart("NEEDRESTART-KSTA: 3\nNEEDRESTART-SVC: ssh.service\n", age=3 * 3600)
|
|
r = self.report()
|
|
self.assertIsNone(r["needrestart_ksta"])
|
|
self.assertIsNone(r["services_need_restart"])
|
|
|
|
def test_agent_never_runs_needrestart_itself(self):
|
|
marker = os.path.join(self.tmp, "needrestart-ran")
|
|
stub(self.bin, "needrestart", f"touch {marker}\n")
|
|
self.report()
|
|
self.assertFalse(os.path.exists(marker))
|
|
|
|
def test_ubuntu_with_needrestart_and_reboot_required(self):
|
|
with open(os.path.join(self.root, "etc/os-release"), "w") as f:
|
|
f.write('PRETTY_NAME="Ubuntu 24.04.3 LTS"\nID=ubuntu\nVERSION_ID="24.04"\n')
|
|
stub(self.bin, "uname", 'case "$1" in -r) echo 6.8.0-85-generic;; -v) echo "#85-Ubuntu";; esac\n')
|
|
stub(self.bin, "dpkg-query", 'case "$*" in *Version*) echo "ii 6.8.0-85.85";; '
|
|
"*) printf 'ii linux-image-6.8.0-85-generic\\n"
|
|
"ii linux-image-unsigned-6.8.0-100-generic\\n';; esac\n")
|
|
stub(self.bin, "apt-get", "echo 'NOTE: This is only a simulation!'\n")
|
|
self.write_needrestart("NEEDRESTART-VER: 3.6\nNEEDRESTART-KCUR: 6.8.0-85-generic\n"
|
|
"NEEDRESTART-KEXP: 6.8.0-100-generic\nNEEDRESTART-KSTA: 3\n")
|
|
open(os.path.join(self.root, "run/reboot-required"), "w").close()
|
|
with open(os.path.join(self.root, "run/reboot-required.pkgs"), "w") as f:
|
|
f.write('linux-image-6.8.0-100-generic\nlinux-base\nlinux-base\n')
|
|
|
|
r = self.report()
|
|
self.assertEqual(r["os_id"], "ubuntu")
|
|
self.assertEqual(r["kernel_newest_installed"], "6.8.0-100-generic", "sort -V, not lexical")
|
|
self.assertEqual(r["kernel_running_pkg_version"], "6.8.0-85.85")
|
|
self.assertEqual(r["needrestart_ksta"], 3)
|
|
self.assertEqual(r["needrestart_kexp"], "6.8.0-100-generic")
|
|
self.assertTrue(r["reboot_required"])
|
|
self.assertEqual(r["reboot_required_pkgs"], ["linux-base", "linux-image-6.8.0-100-generic"])
|
|
self.assertEqual(r["upgradable_count"], 0)
|
|
self.assertEqual(r["security_count"], 0)
|
|
self.assertEqual(r["kernel_upgradable"], [])
|
|
|
|
def test_ubuntu_phased_updates(self):
|
|
# Shape of real `apt-get -s dist-upgrade` output on 24.04 with phasing.
|
|
stub(self.bin, "apt-get", """cat <<'X'
|
|
NOTE: This is only a simulation!
|
|
apt-get needs root privileges for real execution.
|
|
Keep also in mind that locking is deactivated,
|
|
so don't depend on the relevance to the real current situation!
|
|
Reading package lists...
|
|
Building dependency tree...
|
|
Reading state information...
|
|
Calculating upgrade...
|
|
The following upgrades have been deferred due to phasing:
|
|
libnss-systemd libpam-systemd libsystemd-shared libsystemd0 libudev1 systemd
|
|
systemd-resolved udev
|
|
The following packages will be upgraded:
|
|
curl libcurl4t64
|
|
2 upgraded, 0 newly installed, 0 to remove and 8 not upgraded.
|
|
Inst libcurl4t64 [8.5.0-2ubuntu10.6] (8.5.0-2ubuntu10.7 Ubuntu:24.04/noble-security [amd64])
|
|
Inst curl [8.5.0-2ubuntu10.6] (8.5.0-2ubuntu10.7 Ubuntu:24.04/noble-security [amd64])
|
|
Conf libcurl4t64 (8.5.0-2ubuntu10.7 Ubuntu:24.04/noble-security [amd64])
|
|
X
|
|
""")
|
|
r = self.report()
|
|
self.assertEqual(r["upgradable_count"], 2)
|
|
self.assertEqual(r["security_count"], 2)
|
|
self.assertEqual(r["phased_packages"], sorted(
|
|
["libnss-systemd", "libpam-systemd", "libsystemd-shared", "libsystemd0", "libudev1",
|
|
"systemd", "systemd-resolved", "udev"]))
|
|
|
|
def test_apt_told_it_is_not_in_a_chroot(self):
|
|
# Otherwise unprivileged apt thinks it's in a chroot and ignores phasing
|
|
# (seen on a real 26.04 host: 4 phased updates counted as installable).
|
|
stub(self.bin, "apt-get", 'case "$*" in *Dir::Bin::ischroot=/bin/false*) ;; *) exit 1;; esac\n'
|
|
'echo "The following upgrades have been deferred due to phasing:"\n'
|
|
'echo " snapd open-vm-tools"\n'
|
|
'echo "0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded."\n')
|
|
r = self.report()
|
|
self.assertEqual(r["phased_packages"], ["open-vm-tools", "snapd"])
|
|
self.assertEqual(r["upgradable_count"], 0)
|
|
|
|
def test_apt_runs_in_c_locale(self):
|
|
stub(self.bin, "apt-get", 'echo "Inst locale-$LC_ALL [1] (2 x [amd64])"\n')
|
|
self.assertEqual(self.report()["upgradable_count"], 1)
|
|
stub(self.bin, "apt-get", '[ "$LC_ALL" = C ] || exit 1; echo "Inst ok [1] (2 x [amd64])"\n')
|
|
self.assertEqual(self.report()["upgradable_count"], 1)
|
|
|
|
def test_apt_simulation_ok(self):
|
|
r = self.report()
|
|
self.assertIs(r["apt_simulation_ok"], True)
|
|
self.assertIsNone(r["apt_simulation_error"])
|
|
|
|
def test_apt_failure_reports_unknown_counts_not_zero(self):
|
|
# A failed simulation prints no Inst lines; that must not read as "no updates".
|
|
stub(self.bin, "apt-get", "echo 'Reading package lists...'\n"
|
|
"echo 'W: Some warning' >&2\n"
|
|
"echo \"E: Unmet dependencies. Try 'apt --fix-broken install'.\" >&2\n"
|
|
"exit 100\n")
|
|
r = self.report()
|
|
self.assertIs(r["apt_simulation_ok"], False)
|
|
self.assertEqual(r["apt_simulation_error"], "Unmet dependencies. Try 'apt --fix-broken install'.")
|
|
for key in ("upgradable_count", "security_count", "kernel_upgradable", "phased_packages"):
|
|
self.assertIsNone(r[key], key)
|
|
|
|
def test_apt_failure_without_an_error_line(self):
|
|
stub(self.bin, "apt-get", "echo 'something broke' >&2\nexit 1\n")
|
|
self.assertEqual(self.report()["apt_simulation_error"], "something broke")
|
|
stub(self.bin, "apt-get", "exit 100\n")
|
|
self.assertEqual(self.report()["apt_simulation_error"], "apt-get exited with status 100")
|
|
|
|
def test_apt_warnings_dont_mix_into_the_simulation(self):
|
|
stub(self.bin, "apt-get", f"echo 'W: Inst fake [1] (2 x [amd64])' >&2\ncat <<'X'\n{APT_SIM_DEBIAN}X\n")
|
|
r = self.report()
|
|
self.assertIs(r["apt_simulation_ok"], True)
|
|
self.assertEqual(r["upgradable_count"], 3)
|
|
|
|
def test_hostile_strings_stay_valid_json(self):
|
|
stub(self.bin, "hostname", "printf 'a\"b\\\\c\\tq'\n")
|
|
self.assertEqual(self.report()["reported_hostname"], 'a"b\\cq')
|
|
|
|
def test_missing_apt_stamps(self):
|
|
os.remove(os.path.join(self.root, "var/lib/apt/periodic/update-success-stamp"))
|
|
self.assertIsNone(self.report()["apt_lists_age_seconds"])
|
|
|
|
def test_newest_success_stamp_wins(self):
|
|
self.write_root("var/lib/apt/periodic/update-stamp", age=600)
|
|
self.assertAlmostEqual(self.report()["apt_lists_age_seconds"], 600, delta=60)
|
|
|
|
def test_failed_updates_touching_partial_dont_count_as_fresh(self):
|
|
# apt touches lists/partial even when the update fails.
|
|
os.makedirs(os.path.join(self.root, "var/lib/apt/lists/partial"))
|
|
self.assertAlmostEqual(self.report()["apt_lists_age_seconds"], 7200, delta=60)
|
|
|
|
def test_partial_is_the_last_resort_without_stamps(self):
|
|
os.remove(os.path.join(self.root, "var/lib/apt/periodic/update-success-stamp"))
|
|
partial = os.path.join(self.root, "var/lib/apt/lists/partial")
|
|
os.makedirs(partial)
|
|
t = time.time() - 3600
|
|
os.utime(partial, (t, t))
|
|
self.assertAlmostEqual(self.report()["apt_lists_age_seconds"], 3600, delta=60)
|
|
|
|
def write_list(self, name, fields, age=3600, mtime_age=None):
|
|
"""An apt list (Release or InRelease) in the fake root, its Date: `age` seconds ago."""
|
|
body = "".join(f"{k}: {v}\n" for k, v in fields.items())
|
|
if age is not None:
|
|
body += "Date: " + time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time() - age)) + "\n"
|
|
body += "MD5Sum:\n 0123 456 main/binary-amd64/Packages\nSHA256:\n abcd 456 Suite: trixie-security\n"
|
|
if name.endswith("_InRelease"):
|
|
body = "-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA512\n\n" + body + "-----BEGIN PGP SIGNATURE-----\n"
|
|
self.write_root(f"var/lib/apt/lists/{name}", body, age=mtime_age)
|
|
|
|
def set_os(self, text):
|
|
self.write_root("etc/os-release", text)
|
|
|
|
def test_security_repo_debian(self):
|
|
self.write_list("deb.debian.org_debian_dists_trixie_InRelease",
|
|
{"Suite": "stable", "Codename": "trixie"}, age=60)
|
|
self.write_list("security.debian.org_debian-security_dists_trixie-security_InRelease",
|
|
{"Suite": "stable-security", "Codename": "trixie-security"}, age=5 * 3600)
|
|
self.set_os('ID=debian\nVERSION_ID="13"\nVERSION_CODENAME=trixie\n')
|
|
r = self.report()
|
|
self.assertEqual(r["security_repo_suite"], "trixie-security")
|
|
self.assertAlmostEqual(r["security_repo_age_seconds"], 5 * 3600, delta=60)
|
|
|
|
def test_security_repo_ubuntu_newest_mirror_and_odd_file_names(self):
|
|
# Ubuntu: Suite is the pocket, Codename the release. Mirrors and mirror+file:
|
|
# sources give other file names; the newest copy counts.
|
|
self.write_list("archive.ubuntu.com_ubuntu_dists_noble-security_InRelease",
|
|
{"Suite": "noble-security", "Codename": "noble"}, age=3 * 86400)
|
|
self.write_list("_etc_apt_mirrors_ubuntu.list_dists_noble-security_InRelease",
|
|
{"Suite": "noble-security", "Codename": "noble"}, age=7200)
|
|
self.write_list("esm.ubuntu.com_infra_ubuntu_dists_noble-infra-security_InRelease",
|
|
{"Suite": "noble-infra-security", "Codename": "noble-infra-security"}, age=60)
|
|
self.set_os('ID=ubuntu\nVERSION_ID="24.04"\nVERSION_CODENAME=noble\nUBUNTU_CODENAME=noble\n')
|
|
r = self.report()
|
|
self.assertEqual(r["security_repo_suite"], "noble-security")
|
|
self.assertAlmostEqual(r["security_repo_age_seconds"], 7200, delta=60)
|
|
|
|
def test_security_repo_missing(self):
|
|
self.write_list("deb.debian.org_debian_dists_trixie_InRelease",
|
|
{"Suite": "stable", "Codename": "trixie"})
|
|
self.set_os('ID=debian\nVERSION_ID="13"\nVERSION_CODENAME=trixie\n')
|
|
r = self.report()
|
|
self.assertEqual(r["security_repo_suite"], "trixie-security")
|
|
self.assertIsNone(r["security_repo_age_seconds"])
|
|
|
|
def test_security_repo_matches_fields_not_checksum_lines(self):
|
|
# write_list puts "Suite: trixie-security" in a checksum line of every list.
|
|
self.write_list("deb.debian.org_debian_dists_trixie_Release",
|
|
{"Suite": "stable", "Codename": "trixie"})
|
|
self.set_os('ID=debian\nVERSION_ID="13"\nVERSION_CODENAME=trixie\n')
|
|
self.assertIsNone(self.report()["security_repo_age_seconds"])
|
|
|
|
def test_security_repo_without_date_uses_mtime(self):
|
|
self.write_list("local_dists_trixie-security_Release",
|
|
{"Codename": "trixie-security"}, age=None, mtime_age=4 * 3600)
|
|
self.set_os('ID=debian\nVERSION_ID="13"\nVERSION_CODENAME=trixie\n')
|
|
self.assertAlmostEqual(self.report()["security_repo_age_seconds"], 4 * 3600, delta=60)
|
|
|
|
def test_security_repo_without_codename(self):
|
|
# The default fake os-release has no VERSION_CODENAME (like Debian sid).
|
|
r = self.report()
|
|
self.assertIsNone(r["security_repo_suite"])
|
|
self.assertIsNone(r["security_repo_age_seconds"])
|
|
|
|
def test_helper_units(self):
|
|
self.write_root("run/kernelwatch/apt-update.result", "exit-code exited 100 3\n")
|
|
self.write_root("run/kernelwatch/needrestart.result", "success exited 0 0\n")
|
|
self.write_root("run/kernelwatch/livepatch.result", "exit-code exited 1 9\n") # not a tracked helper
|
|
self.assertEqual(self.report()["helper_units"],
|
|
["apt-update exit-code exited 100 3", "needrestart success exited 0 0"])
|
|
|
|
def test_helper_units_stale_or_garbled_results_ignored(self):
|
|
self.write_root("run/kernelwatch/apt-update.result", "exit-code exited 100 3\n", age=3 * 3600)
|
|
self.write_root("run/kernelwatch/needrestart.result", 'exit-code exited 1 "x\n')
|
|
self.assertEqual(self.report()["helper_units"], [])
|
|
|
|
def test_no_helper_results(self):
|
|
self.assertEqual(self.report()["helper_units"], [])
|
|
|
|
def test_send_without_config_fails_cleanly(self):
|
|
proc = self.run_agent()
|
|
self.assertNotEqual(proc.returncode, 0)
|
|
self.assertIn("SERVER_URL", proc.stderr)
|
|
|
|
|
|
@unittest.skipUnless(shutil.which("bash") and shutil.which("curl"), "needs bash and curl")
|
|
class AgentEndToEndTest(AgentCase):
|
|
def test_agent_reports_to_server(self):
|
|
cfg = temp_config(self.tmp)
|
|
server = web.make_server(cfg)
|
|
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
try:
|
|
token = auth.new_token()
|
|
conn = db.connect(cfg.db_path)
|
|
db.add_host(conn, "web01", auth.token_hash(token))
|
|
conn.close()
|
|
|
|
port = server.server_address[1]
|
|
with open(os.path.join(self.root, "etc/kernelwatch/agent.conf"), "w") as f:
|
|
f.write(f"SERVER_URL=http://127.0.0.1:{port}/\n")
|
|
creds = os.path.join(self.tmp, "creds")
|
|
os.mkdir(creds)
|
|
with open(os.path.join(creds, "token"), "w") as f:
|
|
f.write(token + "\n")
|
|
|
|
proc = self.run_agent(env={"CREDENTIALS_DIRECTORY": creds})
|
|
self.assertEqual(proc.returncode, 0, proc.stderr)
|
|
self.assertNotIn(token, proc.stdout + proc.stderr)
|
|
|
|
conn = db.connect(cfg.db_path)
|
|
latest = db.latest_reports(conn)
|
|
conn.close()
|
|
self.assertEqual(latest[0]["report"]["kernel_newest_installed"], "6.12.57+deb13-amd64")
|
|
# Stub uname -v says build 6.12.48-1, dpkg says 6.12.48-2: upgraded in place.
|
|
status = evaluate(latest[0]["received_at"], latest[0]["report"], time.time(), cfg)
|
|
self.assertEqual(status.level, "reboot")
|
|
self.assertIn("upgraded in place to 6.12.48-2", status.reasons[0])
|
|
|
|
with open(os.path.join(creds, "token"), "w") as f:
|
|
f.write("wrong-token\n")
|
|
proc = self.run_agent(env={"CREDENTIALS_DIRECTORY": creds})
|
|
self.assertNotEqual(proc.returncode, 0)
|
|
finally:
|
|
server.shutdown()
|
|
server.server_close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|