diff --git a/README.md b/README.md index d29d8d7..3c6e93b 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,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. | | `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, or apt's package lists are too old (`apt_stale_after_hours`) for "no updates" to mean anything. | +| `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. | | `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 @@ -42,9 +42,23 @@ How the agent works it out: (`6.12.57-1`, `6.8.0-85.85`, `6.14.0-33.33~24.04.1`). A mismatch means the package was upgraded in place after boot; `uname -r` didn't change, but a reboot is still needed. - - [`needrestart`](https://github.com/liske/needrestart) `-b -k`, when it's - installed and can read `/boot`. It's optional. The agent runs unprivileged, so - on Ubuntu (root-only `/boot/vmlinuz-*`) it reports "unknown" and is ignored. + - [`needrestart`](https://github.com/liske/needrestart)'s kernel result, for + build strings the server doesn't recognise (see below). +- **Services needing a restart** (e.g. nginx still using the old OpenSSL + after an upgrade): from `needrestart -b`, if it's installed. Ubuntu ships it; + on Debian, install with `install.sh --with-needrestart`. Without it, the + Services column shows `?` and status isn't affected. needrestart has to + inspect every process, so it runs as root in its own unit, + `kernelwatch-needrestart.service`. That unit has no network access, only the + two capabilities needrestart needs, and list-only mode, so it never restarts + anything. It writes its results to `/run/kernelwatch/needrestart`, and the + unprivileged agent unit runs it just before each report and reads the file. + Neither unit has both root and network access. Fix it on the host: + `sudo needrestart -r a` (or restart the listed services), and the next report + clears it. +- **Agent version**: each report includes it. Hosts running an older agent + than the server shipped with get a note to run `agent/deploy.sh`; their status + isn't changed. - **Available updates**: a simulated `apt-get dist-upgrade`. It is read-only, takes no locks and writes no cache files. `dist-upgrade` is used so that new-ABI kernel packages pulled in by the meta-package show up. Lines whose origin contains @@ -185,6 +199,11 @@ to 15 minutes of jitter. For unattended installs, set `KERNELWATCH_TOKEN=...` instead of using the prompt. +Add `--with-needrestart` to also report services needing a restart (Debian +needs this; Ubuntu already has needrestart). It installs needrestart if +missing and sets it to *list* services after apt upgrades instead of asking +interactively. Delete `/etc/needrestart/conf.d/kernelwatch.conf` to undo that. + Useful on a host: ```sh @@ -212,6 +231,7 @@ agent/deploy.sh # upgrade every host in agent/hosts agent/deploy.sh web01 # upgrade one agent/deploy.sh --rotate web01 # new token, reinstall agent/deploy.sh --dry-run # show the plan +agent/deploy.sh -- --with-needrestart # pass options through to install.sh ``` For each host it copies the agent into a private temp directory and runs @@ -249,6 +269,10 @@ sudo kernelwatch list-users - **Host identity comes from the token, not the payload.** A host can only report as itself. Tokens are 256-bit random values; only their SHA-256 is stored. +- **needrestart** runs in a separate root unit with `PrivateNetwork=yes`, a + capability set of just `CAP_SYS_PTRACE` + `CAP_DAC_READ_SEARCH` (to read other + processes' memory maps), a read-only filesystem except `/run/kernelwatch`, + and `-r l` (list, never restart). - **The agent** runs as a throwaway unprivileged user (`DynamicUser=yes`) with no capabilities, a read-only filesystem view and a syscall filter. The token reaches it through `LoadCredential=` and goes to curl on stdin, so it never diff --git a/agent/deploy.sh b/agent/deploy.sh index d1121e3..4012a5d 100755 --- a/agent/deploy.sh +++ b/agent/deploy.sh @@ -7,6 +7,7 @@ # agent/deploy.sh --register new01 register on the dashboard, then install # agent/deploy.sh --rotate web01 issue a new token, then reinstall # agent/deploy.sh --dry-run show what would happen +# agent/deploy.sh -- --with-needrestart pass the rest to install.sh # # Settings: agent/deploy.conf (see deploy.conf.example). Hosts: agent/hosts, # one per line: ` [kernelwatch name]`; the name defaults to the @@ -17,7 +18,8 @@ set -euo pipefail here=$(cd "$(dirname "$0")" && pwd) CONF=${KERNELWATCH_DEPLOY_CONF:-$here/deploy.conf} HOSTS_FILE=${KERNELWATCH_HOSTS:-$here/hosts} -FILES=(kernelwatch-agent kernelwatch-agent.service kernelwatch-agent.timer install.sh) +FILES=(kernelwatch-agent kernelwatch-agent.service kernelwatch-agent.timer + kernelwatch-needrestart.service install.sh) NAME_RE='^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$' SERVER_URL= @@ -97,7 +99,7 @@ deploy_one() { if ((dry_run)); then if [[ $mode == upgrade ]]; then - echo " copy agent to $target, run install.sh (keeps config and token)" >&2 + echo " copy agent to $target, run install.sh ${install_args[*]} (keeps config and token)" >&2 else echo " on $DASHBOARD: kernelwatch ${mode/register/add-host} ${name:-}" >&2 echo " copy agent and token to $target, run install.sh --server $SERVER_URL" >&2 @@ -120,7 +122,7 @@ deploy_one() { return 1 fi - local -a install=(sudo "$dir/install.sh") + local -a install=(sudo "$dir/install.sh" "${install_args[@]}") if [[ $mode != upgrade ]]; then # 2. Get a token from the dashboard and hand it over on stdin, never argv. say " $mode $name on $DASHBOARD" @@ -143,13 +145,19 @@ deploy_one() { fi } -usage() { sed -n '2,15s/^# \{0,1\}//p' "$0"; } +usage() { sed -n '2,16s/^# \{0,1\}//p' "$0"; } mode=upgrade dry_run=0 targets=() +install_args=() while (($#)); do case $1 in + --) + shift + install_args=("$@") + break + ;; --register) mode=register ;; --rotate) mode=rotate ;; --dry-run) dry_run=1 ;; diff --git a/agent/install.sh b/agent/install.sh index 68e15fd..85493dd 100755 --- a/agent/install.sh +++ b/agent/install.sh @@ -2,6 +2,11 @@ # Install or upgrade kernelwatch-agent on a Debian 12/13 or Ubuntu 22.04/24.04 host. # # sudo ./install.sh --server https://kernelwatch.example.internal [--ca ca.pem] +# [--with-needrestart] +# +# --with-needrestart installs needrestart (Ubuntu has it already) so the +# dashboard can show services needing a restart, and sets it to only list +# services after apt upgrades instead of asking interactively. # # The host token (from `kernelwatch add-host ` on the server) is read # from --token-file, the KERNELWATCH_TOKEN environment variable, or a prompt, @@ -13,13 +18,15 @@ here=$(cd "$(dirname "$0")" && pwd) server= ca= token_file= +with_needrestart=0 while (($#)); do case $1 in --server) server=${2:?--server needs a URL}; shift 2 ;; --ca) ca=${2:?--ca needs a file}; shift 2 ;; --token-file) token_file=${2:?--token-file needs a file}; shift 2 ;; - -h | --help) sed -n '2,9s/^# \{0,1\}//p' "$0"; exit 0 ;; + --with-needrestart) with_needrestart=1; shift ;; + -h | --help) sed -n '2,14s/^# \{0,1\}//p' "$0"; exit 0 ;; *) echo "unknown argument: $1" >&2; exit 2 ;; esac done @@ -36,10 +43,22 @@ esac if ! command -v curl >/dev/null; then apt-get install -y --no-install-recommends curl ca-certificates fi +if ((with_needrestart)); then + if [[ ! -x /usr/sbin/needrestart ]]; then + DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends needrestart + fi + install -d -m 0755 /etc/needrestart/conf.d + cat >/etc/needrestart/conf.d/kernelwatch.conf <<'NRCONF' +# Installed by kernelwatch: after apt upgrades, list services that need a +# restart instead of asking. Delete this file to restore the default. +$nrconf{restart} = 'l'; +NRCONF +fi install -d -m 0755 /etc/kernelwatch install -m 0755 "$here/kernelwatch-agent" /usr/local/sbin/kernelwatch-agent -install -m 0644 "$here/kernelwatch-agent.service" "$here/kernelwatch-agent.timer" /etc/systemd/system/ +install -m 0644 "$here/kernelwatch-agent.service" "$here/kernelwatch-agent.timer" \ + "$here/kernelwatch-needrestart.service" /etc/systemd/system/ if [[ -n $ca ]]; then install -m 0644 "$ca" /etc/kernelwatch/ca.pem diff --git a/agent/kernelwatch-agent b/agent/kernelwatch-agent index 9f0ab79..d70ad2b 100755 --- a/agent/kernelwatch-agent +++ b/agent/kernelwatch-agent @@ -6,7 +6,7 @@ # rules can change without redeploying agents. set -euo pipefail -AGENT_VERSION=0.1.0 +AGENT_VERSION=0.2.0 # Prefix for every file the agent reads. Only the test suite sets this. ROOT=${KERNELWATCH_ROOT:-} @@ -122,20 +122,33 @@ running_kernel_pkg_version() { awk '$1 == "ii" { print $2; exit }' || true } -# Sets NR_KSTA / NR_KEXP from `needrestart -b`. KSTA: 0 unknown, 1 current, -# 2 ABI-compatible upgrade pending, 3 version upgrade pending. Optional: as a -# normal user it can't read Ubuntu's root-only /boot images and reports 0. +# Results of `needrestart -b`, written as root by kernelwatch-needrestart.service +# (which this agent's unit pulls in, so it runs just before each report). The +# agent never runs needrestart itself: unprivileged it can't read Ubuntu's +# root-only /boot images or other users' processes, and gives wrong answers. +NEEDRESTART_FILE=$ROOT/run/kernelwatch/needrestart +NEEDRESTART_MAX_AGE=7200 + +# Sets NR_* from the results file, if it's there and fresh. KSTA: 0 unknown, +# 1 current, 2 ABI-compatible upgrade pending, 3 version upgrade pending. +NR_OK=0 NR_KSTA= NR_KEXP= +NR_SVCS= +NR_SESS=0 read_needrestart() { - command -v needrestart >/dev/null 2>&1 || return 0 - local line + local mtime line + mtime=$(stat -c %Y "$NEEDRESTART_FILE" 2>/dev/null) || return 0 + (($(date +%s) - mtime <= NEEDRESTART_MAX_AGE)) || return 0 + NR_OK=1 while IFS= read -r line; do case $line in NEEDRESTART-KSTA:*) NR_KSTA=${line#*: } ;; NEEDRESTART-KEXP:*) NR_KEXP=${line#*: } ;; + NEEDRESTART-SVC:*) NR_SVCS+=${line#*: }$'\n' ;; + NEEDRESTART-SESS:*) NR_SESS=$((NR_SESS + 1)) ;; esac - done < <(needrestart -b -k -r l 2>/dev/null || true) + done <"$NEEDRESTART_FILE" } # Simulated dist-upgrade. Reads only: no locks, no cache files written. @@ -200,6 +213,12 @@ build_report() { printf '"kernel_newest_installed":%s,' "$(json_str "$newest")" printf '"needrestart_ksta":%s,' "$(json_int "$NR_KSTA")" printf '"needrestart_kexp":%s,' "$(json_str "$NR_KEXP")" + if ((NR_OK)); then + printf '"services_need_restart":%s,' "$(sort -u <<<"$NR_SVCS" | json_str_array)" + printf '"sessions_need_restart":%s,' "$NR_SESS" + else + printf '"services_need_restart":null,"sessions_need_restart":null,' + fi printf '"reboot_required":%s,' "$(json_bool "$reboot_file")" printf '"reboot_required_pkgs":%s,' "$(json_str_array <<<"$reboot_pkgs")" printf '"upgradable_count":%s,' "$(json_int "$(grep -c . <<<"$inst" || true)")" diff --git a/agent/kernelwatch-agent.service b/agent/kernelwatch-agent.service index 329c4c4..c279415 100644 --- a/agent/kernelwatch-agent.service +++ b/agent/kernelwatch-agent.service @@ -1,7 +1,7 @@ [Unit] Description=Report kernel and update status to kernelwatch -Wants=network-online.target -After=network-online.target apt-daily.service +Wants=network-online.target kernelwatch-needrestart.service +After=network-online.target apt-daily.service kernelwatch-needrestart.service [Service] Type=oneshot diff --git a/agent/kernelwatch-needrestart.service b/agent/kernelwatch-needrestart.service new file mode 100644 index 0000000..ca2b1f5 --- /dev/null +++ b/agent/kernelwatch-needrestart.service @@ -0,0 +1,40 @@ +[Unit] +Description=Check for services needing a restart (for kernelwatch) +# Pulled in by kernelwatch-agent.service before each report. Skipped cleanly +# when needrestart isn't installed; the dashboard then shows "unknown". +ConditionPathExists=/usr/sbin/needrestart + +[Service] +Type=oneshot +# -b batch output, -r l list only: never restarts anything. +ExecStart=/bin/sh -c 'needrestart -b -r l > /run/kernelwatch/needrestart.new && mv /run/kernelwatch/needrestart.new /run/kernelwatch/needrestart' +RuntimeDirectory=kernelwatch +RuntimeDirectoryMode=0755 +RuntimeDirectoryPreserve=yes +UMask=0022 + +# Root, but only with what needrestart needs to inspect every process +# (/proc//maps of other users) and nothing else. No network at all. +User=root +CapabilityBoundingSet=CAP_SYS_PTRACE CAP_DAC_READ_SEARCH +AmbientCapabilities= +NoNewPrivileges=yes +PrivateNetwork=yes +ProtectSystem=strict +ProtectHome=read-only +PrivateTmp=yes +PrivateDevices=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +ProtectClock=yes +ProtectHostname=yes +RestrictNamespaces=yes +RestrictRealtime=yes +RestrictSUIDSGID=yes +LockPersonality=yes +MemoryDenyWriteExecute=yes +RestrictAddressFamilies=AF_UNIX +SystemCallArchitectures=native +SystemCallFilter=@system-service diff --git a/server/kernelwatch/__init__.py b/server/kernelwatch/__init__.py index d5e1deb..deacf42 100644 --- a/server/kernelwatch/__init__.py +++ b/server/kernelwatch/__init__.py @@ -1,3 +1,7 @@ """kernelwatch: fleet kernel and reboot status dashboard.""" -__version__ = "0.1.0" +__version__ = "0.2.0" + +# 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. +AGENT_VERSION = "0.2.0" diff --git a/server/kernelwatch/report.py b/server/kernelwatch/report.py index 686ff36..8fb1972 100644 --- a/server/kernelwatch/report.py +++ b/server/kernelwatch/report.py @@ -27,6 +27,8 @@ FIELDS: dict[str, str] = { "kernel_newest_installed": "str", "needrestart_ksta": "int", "needrestart_kexp": "str", + "services_need_restart": "strlist", + "sessions_need_restart": "int", "reboot_required": "bool", "reboot_required_pkgs": "strlist", "upgradable_count": "int", diff --git a/server/kernelwatch/status.py b/server/kernelwatch/status.py index e1b8e83..e54b29e 100644 --- a/server/kernelwatch/status.py +++ b/server/kernelwatch/status.py @@ -13,6 +13,7 @@ import re from dataclasses import dataclass, field from typing import Any +from . import AGENT_VERSION from .config import Config LEVELS = ("stale", "reboot", "update", "ok") @@ -34,6 +35,10 @@ class Status: 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] @@ -93,6 +98,14 @@ def kernel_reboot_pending(report: dict[str, Any]) -> str | None: return None +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 evaluate(received_at: int | None, report: dict[str, Any] | None, now: float, cfg: Config) -> Status: status = Status() @@ -116,10 +129,21 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float, if sec := report.get("security_count"): status.raise_to("update", f"{sec} security update{'s' if sec != 1 else ''} pending") + 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 agent_outdated(report.get("agent_version")): + status.note(f"agent {report['agent_version']} is older than {AGENT_VERSION}; " + "run agent/deploy.sh") + return status diff --git a/server/kernelwatch/web.py b/server/kernelwatch/web.py index 2e02c7b..c571910 100644 --- a/server/kernelwatch/web.py +++ b/server/kernelwatch/web.py @@ -84,6 +84,16 @@ def utc(ts: float | None) -> str: return time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(ts)) if ts else "" +def services_summary(report: dict[str, Any]) -> tuple[str, str]: + """(short cell text, full description) for services needing a restart.""" + services = report.get("services_need_restart") + if services is None: + return "?", "unknown: needrestart not installed (install.sh --with-needrestart)" + if not services: + return "0", "none" + return str(len(services)), ", ".join(services) + + def badge(level: str) -> str: return f'{e(level)}' @@ -397,7 +407,7 @@ class Handler(BaseHTTPRequestHandler): if not hosts else '
' "" - "" + "" "" + "".join(rows) + "
StatusHostOSRunning kernelNewest installedUpdatesUptimeLast seenNewest installedUpdatesServicesUptimeLast seenDetails
" ) body = f'
{summary}
{table}
' @@ -411,6 +421,7 @@ class Handler(BaseHTTPRequestHandler): sec = r.get("security_count") total = r.get("upgradable_count") updates = "–" if total is None else f"{total}" + (f" ({sec} sec)" if sec else "") + services = services_summary(r) return ( "" f"{badge(status.level)}" @@ -419,6 +430,7 @@ class Handler(BaseHTTPRequestHandler): f"{e(r.get('kernel_running') or '–')}" f"{e(r.get('kernel_newest_installed') or '–')}" f"{e(updates)}" + f'{e(services[0])}' f"{e(duration(r.get('uptime_seconds')))}" f'{e(ago(h["received_at"], now))}' f'{"
".join(e(x) for x in status.reasons) or "–"}' @@ -469,6 +481,8 @@ class Handler(BaseHTTPRequestHandler): field("Updates pending", r.get("upgradable_count")), field("Security updates", r.get("security_count")), field("Reboot-required packages", r.get("reboot_required_pkgs"), code=True), + field("Services needing restart", services_summary(r)[1]), + field("Sessions needing restart", r.get("sessions_need_restart")), field("Package lists age", duration(r.get("apt_lists_age_seconds")) 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), diff --git a/tests/test_agent.py b/tests/test_agent.py index e7d0291..aba2377 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -100,6 +100,47 @@ class AgentReportTest(AgentCase): self.assertEqual(r["kernel_upgradable"], ["linux-image-6.12.60+deb13-amd64"]) 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_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: @@ -109,8 +150,8 @@ class AgentReportTest(AgentCase): "*) 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") - stub(self.bin, "needrestart", "printf 'NEEDRESTART-VER: 3.6\\nNEEDRESTART-KCUR: 6.8.0-85-generic\\n" - "NEEDRESTART-KEXP: 6.8.0-100-generic\\nNEEDRESTART-KSTA: 3\\n'\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') diff --git a/tests/test_deploy.py b/tests/test_deploy.py index 002fdb8..d3d5cdc 100644 --- a/tests/test_deploy.py +++ b/tests/test_deploy.py @@ -57,7 +57,7 @@ class DeployTest(unittest.TestCase): os.makedirs(d) for name in ("deploy.sh", "kernelwatch-agent", "kernelwatch-agent.service", - "kernelwatch-agent.timer"): + "kernelwatch-agent.timer", "kernelwatch-needrestart.service"): shutil.copy2(os.path.join(AGENT_DIR, name), self.agent) write_exec(os.path.join(self.agent, "install.sh"), FAKE_INSTALL) @@ -145,6 +145,11 @@ class DeployTest(unittest.TestCase): self.assertNotIn("admin@dash", f.read(), "upgrades don't touch the dashboard") self.assert_clean() + def test_install_args_passed_through(self): + proc = self.deploy("web01.example.test", "--", "--with-needrestart") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(self.installed("web01.example.test")[0], ["--with-needrestart"]) + def test_register_existing_fails_but_others_continue(self): self.assertEqual(self.deploy("--register", "web01.example.test").returncode, 0) proc = self.deploy("--register", "web01.example.test", "new01.example.test") diff --git a/tests/test_status.py b/tests/test_status.py index ba2f066..b437a07 100644 --- a/tests/test_status.py +++ b/tests/test_status.py @@ -1,6 +1,9 @@ +import os +import re import unittest -from helpers import Config +from helpers import REPO, Config +from kernelwatch import AGENT_VERSION from kernelwatch.status import evaluate NOW = 1_800_000_000 @@ -127,6 +130,31 @@ class EvaluateTest(unittest.TestCase): rep["kernel_newest_installed"] = rep["kernel_running"] self.assertEqual(self.level(rep).level, "ok") + def test_services_need_restart(self): + s = self.level(report(services_need_restart=["nginx.service", "ssh.service"])) + self.assertEqual(s.level, "update") + self.assertEqual(s.reasons, ["2 services need restart: nginx, ssh"]) + many = [f"svc{i}.service" for i in range(8)] + self.assertIn("+3 more", self.level(report(services_need_restart=many)).reasons[0]) + self.assertEqual(self.level(report(services_need_restart=["a.service"])).reasons, + ["1 service needs restart: a"]) + + def test_services_unknown_or_none_is_ok(self): + self.assertEqual(self.level(report(services_need_restart=None)).level, "ok") + self.assertEqual(self.level(report(services_need_restart=[])).level, "ok") + + def test_outdated_agent_is_noted_not_escalated(self): + s = self.level(report(agent_version="0.1.0")) + self.assertEqual(s.level, "ok") + self.assertIn("agent 0.1.0 is older", s.reasons[0]) + self.assertEqual(self.level(report(agent_version=AGENT_VERSION)).reasons, []) + self.assertEqual(self.level(report(agent_version="0.10.0")).reasons, [], "numeric compare") + + def test_server_knows_shipped_agent_version(self): + with open(os.path.join(REPO, "agent", "kernelwatch-agent")) as f: + shipped = re.search(r"^AGENT_VERSION=(\S+)$", f.read(), re.M).group(1) + self.assertEqual(shipped, AGENT_VERSION, "bump kernelwatch.AGENT_VERSION with the agent") + def test_reboot_required_file(self): s = self.level(report(reboot_required=True, reboot_required_pkgs=["libc6", "dbus"])) self.assertEqual(s.level, "reboot") diff --git a/tests/test_web.py b/tests/test_web.py index 9c63d8a..be97f5b 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -125,7 +125,9 @@ class DashboardTest(ServerCase): self.post_report(token, {"kernel_running": "6.8.0-85-generic", "kernel_newest_installed": "6.8.0-87-generic", "os_pretty_name": "Ubuntu 24.04.3 LTS ", - "apt_lists_age_seconds": 60}) + "apt_lists_age_seconds": 60, + "agent_version": "0.1.0", + "services_need_restart": ["nginx.service"]}) status, headers, _ = self.login("admin", "a-long-password") self.assertEqual(status, 303) @@ -139,6 +141,8 @@ class DashboardTest(ServerCase): self.assertIn("db01", body) self.assertIn("6.8.0-87-generic installed", body) self.assertIn("never reported", body) + self.assertIn("1 service needs restart: nginx", body) + self.assertIn("agent 0.1.0 is older", body) self.assertIn("<b>", body, "report content must be escaped") self.assertNotIn("\n", body) # Worst first: stale db01 before reboot web01.