Report services needing a restart via a separate root needrestart unit #2

Merged
patrick merged 2 commits from feature/needrestart-services into main 2026-10-17 15:56:28 +00:00
14 changed files with 258 additions and 26 deletions

No files matched your search

+28 -4
View File
@@ -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. | | `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, 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. | | `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
@@ -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 (`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 package was upgraded in place after boot; `uname -r` didn't change, but a
reboot is still needed. reboot is still needed.
- [`needrestart`](https://github.com/liske/needrestart) `-b -k`, when it's - [`needrestart`](https://github.com/liske/needrestart)'s kernel result, for
installed and can read `/boot`. It's optional. The agent runs unprivileged, so build strings the server doesn't recognise (see below).
on Ubuntu (root-only `/boot/vmlinuz-*`) it reports "unknown" and is ignored. - **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 - **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 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 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. 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: Useful on a host:
```sh ```sh
@@ -212,6 +231,7 @@ agent/deploy.sh # upgrade every host in agent/hosts
agent/deploy.sh web01 # upgrade one agent/deploy.sh web01 # upgrade one
agent/deploy.sh --rotate web01 # new token, reinstall agent/deploy.sh --rotate web01 # new token, reinstall
agent/deploy.sh --dry-run # show the plan 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 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 - **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. 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 - **The agent** runs as a throwaway unprivileged user (`DynamicUser=yes`) with
no capabilities, a read-only filesystem view and a syscall filter. The token 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 reaches it through `LoadCredential=` and goes to curl on stdin, so it never
+12 -4
View File
@@ -7,6 +7,7 @@
# agent/deploy.sh --register new01 register on the dashboard, then install # 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 --rotate web01 issue a new token, then reinstall
# agent/deploy.sh --dry-run show what would happen # 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, # Settings: agent/deploy.conf (see deploy.conf.example). Hosts: agent/hosts,
# one per line: `<ssh target> [kernelwatch name]`; the name defaults to the # one per line: `<ssh target> [kernelwatch name]`; the name defaults to the
@@ -17,7 +18,8 @@ set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd) here=$(cd "$(dirname "$0")" && pwd)
CONF=${KERNELWATCH_DEPLOY_CONF:-$here/deploy.conf} CONF=${KERNELWATCH_DEPLOY_CONF:-$here/deploy.conf}
HOSTS_FILE=${KERNELWATCH_HOSTS:-$here/hosts} 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}$' NAME_RE='^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$'
SERVER_URL= SERVER_URL=
@@ -97,7 +99,7 @@ deploy_one() {
if ((dry_run)); then if ((dry_run)); then
if [[ $mode == upgrade ]]; 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 else
echo " on $DASHBOARD: kernelwatch ${mode/register/add-host} ${name:-<its hostname -s>}" >&2 echo " on $DASHBOARD: kernelwatch ${mode/register/add-host} ${name:-<its hostname -s>}" >&2
echo " copy agent and token to $target, run install.sh --server $SERVER_URL" >&2 echo " copy agent and token to $target, run install.sh --server $SERVER_URL" >&2
@@ -120,7 +122,7 @@ deploy_one() {
return 1 return 1
fi fi
local -a install=(sudo "$dir/install.sh") local -a install=(sudo "$dir/install.sh" "${install_args[@]}")
if [[ $mode != upgrade ]]; then if [[ $mode != upgrade ]]; then
# 2. Get a token from the dashboard and hand it over on stdin, never argv. # 2. Get a token from the dashboard and hand it over on stdin, never argv.
say " $mode $name on $DASHBOARD" say " $mode $name on $DASHBOARD"
@@ -143,13 +145,19 @@ deploy_one() {
fi fi
} }
usage() { sed -n '2,15s/^# \{0,1\}//p' "$0"; } usage() { sed -n '2,16s/^# \{0,1\}//p' "$0"; }
mode=upgrade mode=upgrade
dry_run=0 dry_run=0
targets=() targets=()
install_args=()
while (($#)); do while (($#)); do
case $1 in case $1 in
--)
shift
install_args=("$@")
break
;;
--register) mode=register ;; --register) mode=register ;;
--rotate) mode=rotate ;; --rotate) mode=rotate ;;
--dry-run) dry_run=1 ;; --dry-run) dry_run=1 ;;
+21 -2
View File
@@ -2,6 +2,11 @@
# Install or upgrade kernelwatch-agent on a Debian 12/13 or Ubuntu 22.04/24.04 host. # 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] # 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 <name>` on the server) is read # The host token (from `kernelwatch add-host <name>` on the server) is read
# from --token-file, the KERNELWATCH_TOKEN environment variable, or a prompt, # from --token-file, the KERNELWATCH_TOKEN environment variable, or a prompt,
@@ -13,13 +18,15 @@ here=$(cd "$(dirname "$0")" && pwd)
server= server=
ca= ca=
token_file= token_file=
with_needrestart=0
while (($#)); do while (($#)); do
case $1 in case $1 in
--server) server=${2:?--server needs a URL}; shift 2 ;; --server) server=${2:?--server needs a URL}; shift 2 ;;
--ca) ca=${2:?--ca needs a file}; shift 2 ;; --ca) ca=${2:?--ca needs a file}; shift 2 ;;
--token-file) token_file=${2:?--token-file 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 ;; *) echo "unknown argument: $1" >&2; exit 2 ;;
esac esac
done done
@@ -36,10 +43,22 @@ esac
if ! command -v curl >/dev/null; then if ! command -v curl >/dev/null; then
apt-get install -y --no-install-recommends curl ca-certificates apt-get install -y --no-install-recommends curl ca-certificates
fi 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 -d -m 0755 /etc/kernelwatch
install -m 0755 "$here/kernelwatch-agent" /usr/local/sbin/kernelwatch-agent 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 if [[ -n $ca ]]; then
install -m 0644 "$ca" /etc/kernelwatch/ca.pem install -m 0644 "$ca" /etc/kernelwatch/ca.pem
+26 -7
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.1.0 AGENT_VERSION=0.2.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:-}
@@ -122,20 +122,33 @@ running_kernel_pkg_version() {
awk '$1 == "ii" { print $2; exit }' || true awk '$1 == "ii" { print $2; exit }' || true
} }
# Sets NR_KSTA / NR_KEXP from `needrestart -b`. KSTA: 0 unknown, 1 current, # Results of `needrestart -b`, written as root by kernelwatch-needrestart.service
# 2 ABI-compatible upgrade pending, 3 version upgrade pending. Optional: as a # (which this agent's unit pulls in, so it runs just before each report). The
# normal user it can't read Ubuntu's root-only /boot images and reports 0. # 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_KSTA=
NR_KEXP= NR_KEXP=
NR_SVCS=
NR_SESS=0
read_needrestart() { read_needrestart() {
command -v needrestart >/dev/null 2>&1 || return 0 local mtime line
local 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 while IFS= read -r line; do
case $line in case $line in
NEEDRESTART-KSTA:*) NR_KSTA=${line#*: } ;; NEEDRESTART-KSTA:*) NR_KSTA=${line#*: } ;;
NEEDRESTART-KEXP:*) NR_KEXP=${line#*: } ;; NEEDRESTART-KEXP:*) NR_KEXP=${line#*: } ;;
NEEDRESTART-SVC:*) NR_SVCS+=${line#*: }$'\n' ;;
NEEDRESTART-SESS:*) NR_SESS=$((NR_SESS + 1)) ;;
esac 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. # 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 '"kernel_newest_installed":%s,' "$(json_str "$newest")"
printf '"needrestart_ksta":%s,' "$(json_int "$NR_KSTA")" printf '"needrestart_ksta":%s,' "$(json_int "$NR_KSTA")"
printf '"needrestart_kexp":%s,' "$(json_str "$NR_KEXP")" 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":%s,' "$(json_bool "$reboot_file")"
printf '"reboot_required_pkgs":%s,' "$(json_str_array <<<"$reboot_pkgs")" printf '"reboot_required_pkgs":%s,' "$(json_str_array <<<"$reboot_pkgs")"
printf '"upgradable_count":%s,' "$(json_int "$(grep -c . <<<"$inst" || true)")" printf '"upgradable_count":%s,' "$(json_int "$(grep -c . <<<"$inst" || true)")"
+2 -2
View File
@@ -1,7 +1,7 @@
[Unit] [Unit]
Description=Report kernel and update status to kernelwatch Description=Report kernel and update status to kernelwatch
Wants=network-online.target Wants=network-online.target kernelwatch-needrestart.service
After=network-online.target apt-daily.service After=network-online.target apt-daily.service kernelwatch-needrestart.service
[Service] [Service]
Type=oneshot Type=oneshot
+40
View File
@@ -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/<pid>/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
+5 -1
View File
@@ -1,3 +1,7 @@
"""kernelwatch: fleet kernel and reboot status dashboard.""" """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"
+2
View File
@@ -27,6 +27,8 @@ FIELDS: dict[str, str] = {
"kernel_newest_installed": "str", "kernel_newest_installed": "str",
"needrestart_ksta": "int", "needrestart_ksta": "int",
"needrestart_kexp": "str", "needrestart_kexp": "str",
"services_need_restart": "strlist",
"sessions_need_restart": "int",
"reboot_required": "bool", "reboot_required": "bool",
"reboot_required_pkgs": "strlist", "reboot_required_pkgs": "strlist",
"upgradable_count": "int", "upgradable_count": "int",
+24
View File
@@ -13,6 +13,7 @@ import re
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Any from typing import Any
from . import AGENT_VERSION
from .config import Config from .config import Config
LEVELS = ("stale", "reboot", "update", "ok") LEVELS = ("stale", "reboot", "update", "ok")
@@ -34,6 +35,10 @@ class Status:
self.level = level self.level = level
self.reasons.append(reason) 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 @property
def rank(self) -> int: def rank(self) -> int:
return _RANK[self.level] return _RANK[self.level]
@@ -93,6 +98,14 @@ def kernel_reboot_pending(report: dict[str, Any]) -> str | None:
return 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, def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float,
cfg: Config) -> Status: cfg: Config) -> Status:
status = 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"): if sec := report.get("security_count"):
status.raise_to("update", f"{sec} security update{'s' if sec != 1 else ''} pending") 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") apt_age = report.get("apt_lists_age_seconds")
if apt_age is None: if apt_age is None:
status.raise_to("update", "package list age unknown") status.raise_to("update", "package list age unknown")
elif apt_age / 3600 > cfg.apt_stale_after_hours: 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?") 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 return status
+15 -1
View File
@@ -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 "" 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: def badge(level: str) -> str:
return f'<span class="badge {e(level)}">{e(level)}</span>' return f'<span class="badge {e(level)}">{e(level)}</span>'
@@ -397,7 +407,7 @@ class Handler(BaseHTTPRequestHandler):
if not hosts else if not hosts else
'<div class="table-wrap"><table><thead><tr>' '<div class="table-wrap"><table><thead><tr>'
"<th>Status</th><th>Host</th><th>OS</th><th>Running kernel</th>" "<th>Status</th><th>Host</th><th>OS</th><th>Running kernel</th>"
"<th>Newest installed</th><th>Updates</th><th>Uptime</th><th>Last seen</th>" "<th>Newest installed</th><th>Updates</th><th>Services</th><th>Uptime</th><th>Last seen</th>"
"<th>Details</th></tr></thead><tbody>" + "".join(rows) + "</tbody></table></div>" "<th>Details</th></tr></thead><tbody>" + "".join(rows) + "</tbody></table></div>"
) )
body = f'<main><div class="summary">{summary}</div>{table}</main>' body = f'<main><div class="summary">{summary}</div>{table}</main>'
@@ -411,6 +421,7 @@ class Handler(BaseHTTPRequestHandler):
sec = r.get("security_count") sec = r.get("security_count")
total = r.get("upgradable_count") total = r.get("upgradable_count")
updates = "–" if total is None else f"{total}" + (f" ({sec} sec)" if sec else "") updates = "–" if total is None else f"{total}" + (f" ({sec} sec)" if sec else "")
services = services_summary(r)
return ( return (
"<tr>" "<tr>"
f"<td>{badge(status.level)}</td>" f"<td>{badge(status.level)}</td>"
@@ -419,6 +430,7 @@ class Handler(BaseHTTPRequestHandler):
f"<td><code>{e(r.get('kernel_running') or '–')}</code></td>" f"<td><code>{e(r.get('kernel_running') or '–')}</code></td>"
f"<td><code>{e(r.get('kernel_newest_installed') or '–')}</code></td>" f"<td><code>{e(r.get('kernel_newest_installed') or '–')}</code></td>"
f"<td>{e(updates)}</td>" f"<td>{e(updates)}</td>"
f'<td title="{e(services[1])}">{e(services[0])}</td>'
f"<td>{e(duration(r.get('uptime_seconds')))}</td>" f"<td>{e(duration(r.get('uptime_seconds')))}</td>"
f'<td title="{e(utc(h["received_at"]))}">{e(ago(h["received_at"], now))}</td>' f'<td title="{e(utc(h["received_at"]))}">{e(ago(h["received_at"], now))}</td>'
f'<td class="reasons">{"<br>".join(e(x) for x in status.reasons) or "–"}</td>' f'<td class="reasons">{"<br>".join(e(x) for x in status.reasons) or "–"}</td>'
@@ -469,6 +481,8 @@ class Handler(BaseHTTPRequestHandler):
field("Updates pending", r.get("upgradable_count")), field("Updates pending", r.get("upgradable_count")),
field("Security updates", r.get("security_count")), field("Security updates", r.get("security_count")),
field("Reboot-required packages", r.get("reboot_required_pkgs"), code=True), 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")) 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),
+43 -2
View File
@@ -100,6 +100,47 @@ class AgentReportTest(AgentCase):
self.assertEqual(r["kernel_upgradable"], ["linux-image-6.12.60+deb13-amd64"]) self.assertEqual(r["kernel_upgradable"], ["linux-image-6.12.60+deb13-amd64"])
self.assertAlmostEqual(r["apt_lists_age_seconds"], 7200, delta=60) self.assertAlmostEqual(r["apt_lists_age_seconds"], 7200, delta=60)
self.assertEqual(r["uptime_seconds"], 93784) 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): def test_ubuntu_with_needrestart_and_reboot_required(self):
with open(os.path.join(self.root, "etc/os-release"), "w") as f: 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" "*) printf 'ii linux-image-6.8.0-85-generic\\n"
"ii linux-image-unsigned-6.8.0-100-generic\\n';; esac\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, "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" 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'\n") "NEEDRESTART-KEXP: 6.8.0-100-generic\nNEEDRESTART-KSTA: 3\n")
open(os.path.join(self.root, "run/reboot-required"), "w").close() 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: 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') f.write('linux-image-6.8.0-100-generic\nlinux-base\nlinux-base\n')
+6 -1
View File
@@ -57,7 +57,7 @@ class DeployTest(unittest.TestCase):
os.makedirs(d) os.makedirs(d)
for name in ("deploy.sh", "kernelwatch-agent", "kernelwatch-agent.service", 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) shutil.copy2(os.path.join(AGENT_DIR, name), self.agent)
write_exec(os.path.join(self.agent, "install.sh"), FAKE_INSTALL) 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.assertNotIn("admin@dash", f.read(), "upgrades don't touch the dashboard")
self.assert_clean() 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): def test_register_existing_fails_but_others_continue(self):
self.assertEqual(self.deploy("--register", "web01.example.test").returncode, 0) self.assertEqual(self.deploy("--register", "web01.example.test").returncode, 0)
proc = self.deploy("--register", "web01.example.test", "new01.example.test") proc = self.deploy("--register", "web01.example.test", "new01.example.test")
+29 -1
View File
@@ -1,6 +1,9 @@
import os
import re
import unittest import unittest
from helpers import Config from helpers import REPO, Config
from kernelwatch import AGENT_VERSION
from kernelwatch.status import evaluate from kernelwatch.status import evaluate
NOW = 1_800_000_000 NOW = 1_800_000_000
@@ -127,6 +130,31 @@ class EvaluateTest(unittest.TestCase):
rep["kernel_newest_installed"] = rep["kernel_running"] rep["kernel_newest_installed"] = rep["kernel_running"]
self.assertEqual(self.level(rep).level, "ok") 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): def test_reboot_required_file(self):
s = self.level(report(reboot_required=True, reboot_required_pkgs=["libc6", "dbus"])) s = self.level(report(reboot_required=True, reboot_required_pkgs=["libc6", "dbus"]))
self.assertEqual(s.level, "reboot") self.assertEqual(s.level, "reboot")
+5 -1
View File
@@ -125,7 +125,9 @@ class DashboardTest(ServerCase):
self.post_report(token, {"kernel_running": "6.8.0-85-generic", self.post_report(token, {"kernel_running": "6.8.0-85-generic",
"kernel_newest_installed": "6.8.0-87-generic", "kernel_newest_installed": "6.8.0-87-generic",
"os_pretty_name": "Ubuntu 24.04.3 LTS <b>", "os_pretty_name": "Ubuntu 24.04.3 LTS <b>",
"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") status, headers, _ = self.login("admin", "a-long-password")
self.assertEqual(status, 303) self.assertEqual(status, 303)
@@ -139,6 +141,8 @@ class DashboardTest(ServerCase):
self.assertIn("db01", body) self.assertIn("db01", body)
self.assertIn("6.8.0-87-generic installed", body) self.assertIn("6.8.0-87-generic installed", body)
self.assertIn("never reported", 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("&lt;b&gt;", body, "report content must be escaped") self.assertIn("&lt;b&gt;", body, "report content must be escaped")
self.assertNotIn("<b>\n", body) self.assertNotIn("<b>\n", body)
# Worst first: stale db01 before reboot web01. # Worst first: stale db01 before reboot web01.