Compare commits

..
23 Commits
Author SHA1 Message Date
patrick 2b53170b51 Merge pull request 'Fix stale OS version comments in the installer headers' (#35) from docs/install-os-versions into main
CI / tests (Python 3.10) (push) Successful in 45s
CI / tests (Python 3.11) (push) Successful in 43s
CI / tests (Python 3.12) (push) Successful in 43s
CI / tests (Python 3.13) (push) Successful in 42s
CI / lint (push) Successful in 3s
Reviewed-on: #35
2026-11-11 21:44:57 +00:00
patrick 5fcd95eeb4 Fix stale OS version comments in the installer headers
CI / tests (Python 3.11) (pull_request) Successful in 43s
CI / tests (Python 3.10) (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
2026-11-11 16:36:39 -05:00
patrick 9a5ee5610b Merge pull request 'Stop kernelwatch-apt-update starving for disk on busy hosts' (#34) from fix/apt-update-io-priority into main
CI / tests (Python 3.11) (push) Successful in 42s
CI / tests (Python 3.10) (push) Successful in 42s
CI / tests (Python 3.12) (push) Successful in 43s
CI / tests (Python 3.13) (push) Successful in 42s
CI / lint (push) Successful in 4s
Reviewed-on: #34
2026-11-08 20:49:17 +00:00
patrickandClaude Opus 5.5 f314fa331e Stop kernelwatch-apt-update starving for disk on busy hosts
CI / tests (Python 3.10) (pull_request) Successful in 43s
CI / tests (Python 3.11) (pull_request) Successful in 43s
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
On nike (I/O pressure "full" around 86%), kernelwatch-apt-update.service
timed out after 5 minutes every run. The downloads were quick, but apt
then spent the rest of the time reading and writing its lists. At normal
priority the same apt-get update took 1m31s.

The unit ran in the idle I/O class, which gets disk time only when
nothing else wants it, so under constant I/O apt got almost none. It now
uses the lowest best-effort priority (IOSchedulingPriority=7). That still
yields to everything else on the host, but apt can't be starved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 15:46:44 -05:00
patrick f48551a4a6 Merge pull request 'Flag hosts without room on disk for their pending upgrades' (#33) from feat/upgrade-space-check into main
CI / tests (Python 3.10) (push) Successful in 41s
CI / tests (Python 3.11) (push) Successful in 42s
CI / tests (Python 3.12) (push) Successful in 41s
CI / tests (Python 3.13) (push) Successful in 42s
CI / lint (push) Successful in 3s
Reviewed-on: #33
2026-11-08 01:21:18 +00:00
patrickandClaude Opus 5.5 15b1f5be4f Flag hosts without room on disk for their pending upgrades
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>
2026-11-07 20:16:54 -05:00
patrick b5be19f85d Merge pull request 'Document automatic reboots with unattended-upgrades' (#32) from docs/automatic-reboots into main
CI / tests (Python 3.11) (push) Successful in 39s
CI / tests (Python 3.10) (push) Successful in 39s
CI / tests (Python 3.12) (push) Successful in 39s
CI / tests (Python 3.13) (push) Successful in 39s
CI / lint (push) Successful in 4s
Reviewed-on: #32
2026-11-01 21:20:42 +00:00
patrickandClaude Opus 5.5 7090038626 Document automatic reboots with unattended-upgrades
CI / tests (Python 3.10) (pull_request) Successful in 39s
CI / tests (Python 3.11) (pull_request) Successful in 38s
CI / tests (Python 3.12) (pull_request) Successful in 39s
CI / tests (Python 3.13) (pull_request) Successful in 38s
CI / lint (pull_request) Successful in 3s
kernelwatch flags pending reboots but never reboots anything. For hosts
without Livepatch, add "Rebooting automatically" to the agents guide:
enabling unattended-upgrades on Debian (its kernel hook is what creates
/run/reboot-required there), a drop-in for Automatic-Reboot and
Automatic-Reboot-Time, picking times before 05:00 so the reboot lands
inside the 24h reboot alert window (apt-daily-upgrade runs 06:00-07:00),
staggering dependent hosts and the dashboard host, and how each outcome
shows up in kernelwatch: back to ok minutes after boot, stale if it
doesn't come back, a reboot alert if it never happens. Also why to leave
it off on Livepatch hosts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 15:50:31 -05:00
patrick 8710584446 Merge pull request 'Report failing helper units, held packages and unloaded microcode' (#31) from feat/helper-unit-health into main
CI / tests (Python 3.11) (push) Successful in 38s
CI / tests (Python 3.10) (push) Successful in 39s
CI / tests (Python 3.12) (push) Successful in 38s
CI / tests (Python 3.13) (push) Successful in 39s
CI / lint (push) Successful in 3s
Reviewed-on: #31
2026-11-01 20:33:32 +00:00
patrickandClaude Opus 5.5 1b6cfce18b Fix shellcheck SC1007 in helper_units
CI / tests (Python 3.11) (pull_request) Successful in 39s
CI / tests (Python 3.10) (pull_request) Successful in 39s
CI / tests (Python 3.12) (pull_request) Successful in 40s
CI / tests (Python 3.13) (pull_request) Successful in 39s
CI / lint (pull_request) Successful in 3s
`local x=` reads to shellcheck like a mistyped assignment; spell the empty
values as ''.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 15:31:10 -05:00
patrickandClaude Opus 5.5 8174f1df81 Put hosts with unloaded CPU microcode updates in reboot
CI / tests (Python 3.11) (pull_request) Successful in 39s
CI / tests (Python 3.12) (pull_request) Successful in 38s
CI / tests (Python 3.13) (pull_request) Successful in 38s
CI / lint (pull_request) Failing after 3s
CI / tests (Python 3.10) (pull_request) Successful in 40s
On bare metal, needrestart -b reports NEEDRESTART-UCSTA: 2 when the
installed intel-microcode/amd64-microcode is newer than what the CPU
loaded at boot, which only a reboot fixes. The agent dropped those
lines. It now reports needrestart_ucsta, _uccur and _ucexp, and the
server puts the host in reboot with both revisions. Livepatch doesn't
cover it. needrestart skips the check in VMs, so only physical hosts
(debian-homelab today) report it; the host page gets a "CPU microcode"
row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 15:25:57 -05:00
patrickandClaude Opus 5.5 4676942108 Report packages on hold, and flag held kernel packages
A held package never upgrades, and apt's simulation leaves it out, so
its updates (security ones included) appear nowhere. A leftover hold on
linux-image-amd64 or linux-generic keeps a host on its kernel while it
looks current.

The agent reports installed held packages (dpkg's "hi") as
held_packages. A held linux-* package puts the host in update with the
apt-mark unhold hint; other holds, usually deliberate, get a note. The
host page lists them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 15:24:27 -05:00
patrickandClaude Opus 5.5 f88261d2f5 Report when kernelwatch's own helper units keep failing
kernelwatch-apt-update.service failed hourly on most hosts for weeks
without anything showing it. The agent only Wants= its helper units, so
the report goes out regardless, with stale lists or (for needrestart)
results that quietly turn "unknown".

Each helper (apt-update, needrestart) now runs kernelwatch-unit-result
as its ExecStopPost=, which systemd runs after failed runs too. It
writes "RESULT EXIT_CODE EXIT_STATUS FAILURES" to
/run/kernelwatch/<name>.result, FAILURES counting failed runs in a row.
The agent (0.10.0) reports results from the last two hours as
helper_units. On the server, one or two failures are a note (an admin's
apt can hold the lock now and then); three in a row put the host in
update, naming the unit and its exit status and pointing at journalctl.
The host page gets a "kernelwatch helpers" row.

The Livepatch unit isn't tracked: it fails by design where the snap is
installed but Livepatch isn't enabled, and Livepatch has its own check.

The apt-update unit now has RuntimeDirectory=kernelwatch (preserved,
like the others) for its result file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 15:23:05 -05:00
patrick ad310a4948 Merge pull request 'Fix apt refresh on apt 2.7+ and check the security repository' (#30) from feat/security-repo-check into main
CI / tests (Python 3.10) (push) Successful in 36s
CI / tests (Python 3.11) (push) Successful in 37s
CI / tests (Python 3.12) (push) Successful in 35s
CI / tests (Python 3.13) (push) Successful in 35s
CI / lint (push) Successful in 3s
Reviewed-on: #30
2026-11-01 20:08:36 +00:00
patrickandClaude Opus 5.5 c9912d5fbc Check that the release's security repository is configured and fresh
CI / tests (Python 3.10) (pull_request) Successful in 36s
CI / tests (Python 3.11) (pull_request) Successful in 36s
CI / tests (Python 3.12) (pull_request) Successful in 37s
CI / tests (Python 3.13) (pull_request) Successful in 37s
CI / lint (pull_request) Successful in 4s
security_count is only meaningful if apt has the release's security
suite. A host missing it from its sources shows 0 security updates
forever, and one whose apt can't fetch it (expired key, wrong URL after
a release upgrade, a mirror that fell behind) keeps the last copy while
the update stamps and other lists move on, so neither the simulation nor
the package list age notices.

The agent (0.9.0) now finds apt's list for <codename>-security by its
Suite: (Ubuntu) or Codename: (Debian) field, since file names depend on
the mirror (mirror+file: sources, several mirrors), and reports
security_repo_suite and security_repo_age_seconds from its Date:, the
newest copy winning. The server puts the host in update when there's no
such list, or when it's older than security_repo_stale_after_days
(default 7) while the package lists are otherwise fresh; if all of
them are old, the existing "package lists N days old" reason covers
it. Releases past the end of support are skipped: their suite has
stopped publishing, and support.check already says so. ESM suites
publish too rarely to judge by date and aren't checked.

The host page gets a "Security repository" row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 14:58:10 -05:00
patrickandClaude Opus 5.5 fa6cca4f64 Don't let failed apt updates make package lists look fresh
apt touches /var/lib/apt/lists/partial on every update attempt,
including ones that fail, and the agent took the newest of it and the
two success stamps. So a host whose apt update failed hourly reported
lists an hour old. Use the success stamps (update-success-stamp,
update-stamp) and fall back to lists/partial only when neither exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 14:53:19 -05:00
patrickandClaude Opus 5.5 195fd035e0 Fix kernelwatch-apt-update failing on apt 2.7+
With User=root, NoNewPrivileges=yes and any seccomp-based sandbox option
together, apt 2.7+ (Ubuntu 24.04+, Debian 13) can't drop to _apt:

  E: seteuid 42 failed - seteuid (1: Operation not permitted)
  E: Method http has died unexpectedly!

so apt-get update exited 100 on every run on 10 of 13 hosts. The '-'
prefix hid it, and apt touches lists/partial even when it fails, so the
agent's list age looked fresh. Only hosts with older apt (22.04, Debian
12) refreshed. On Ubuntu apt-daily kept the lists fresh regardless; a
Debian 13 host relying on this unit alone had lists three days old.

Root is the default, so drop User=root. Let a failed update fail the
unit (the agent only Wants= it, so the report still goes), and touch
/var/lib/apt/periodic/update-success-stamp, the stamp Ubuntu writes after
each successful apt update, only when it succeeds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 14:52:36 -05:00
patrick 233645c738 Merge pull request 'Document setting up Ubuntu Livepatch for a host' (#29) from docs/livepatch-setup into main
CI / tests (Python 3.11) (push) Successful in 34s
CI / tests (Python 3.10) (push) Successful in 34s
CI / tests (Python 3.12) (push) Successful in 33s
CI / tests (Python 3.13) (push) Successful in 33s
CI / lint (push) Successful in 3s
Reviewed-on: #29
2026-11-01 00:55:40 +00:00
patrickandClaude Opus 5.5 b6fc7fc05e Document setting up Ubuntu Livepatch for a host
CI / tests (Python 3.10) (pull_request) Successful in 34s
CI / tests (Python 3.11) (pull_request) Successful in 34s
CI / tests (Python 3.12) (pull_request) Successful in 34s
CI / tests (Python 3.13) (pull_request) Successful in 34s
CI / lint (pull_request) Successful in 2s
docs/agents.md had nothing on Livepatch, though it's where you look when
adding a host. New section: attaching Ubuntu Pro and enabling Livepatch,
checking kernelwatch picks it up, what changes on the dashboard (reboot
cover, its 14-day margin, alerts), that attaching also enables the ESM the
end-of-support check counts, and the caveats (supported kernels only,
turning it off sends one alert, nothing for Debian).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:52:42 -04:00
patrick 249e8c2b2a Merge pull request 'Stop deploy.sh running under sudo or from an outdated checkout' (#28) from feat/deploy-safety-checks into main
CI / tests (Python 3.11) (push) Successful in 35s
CI / tests (Python 3.10) (push) Successful in 35s
CI / tests (Python 3.12) (push) Successful in 34s
CI / tests (Python 3.13) (push) Successful in 34s
CI / lint (push) Successful in 3s
Reviewed-on: #28
2026-11-01 00:49:45 +00:00
patrickandClaude Opus 5.5 253ccb02f6 Document deploy.sh's sudo and outdated-checkout checks
CI / tests (Python 3.11) (pull_request) Successful in 34s
CI / tests (Python 3.10) (pull_request) Successful in 35s
CI / tests (Python 3.12) (pull_request) Successful in 33s
CI / tests (Python 3.13) (pull_request) Successful in 34s
CI / lint (pull_request) Successful in 2s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:46:32 -04:00
patrickandClaude Opus 5.5 c3ed3c026b Stop deploy.sh running under sudo or from an outdated checkout
Under sudo, ssh reads root's config and keys, so a custom Port silently
disappears and the deploy fails with "connect to host ... port 22:
Connection refused". deploy.sh needs no root locally (install.sh runs
under sudo on each host), so it now refuses when run as root via sudo,
naming the user to run it as. A real root login is still allowed.

Deploying from a checkout behind its upstream ships an older agent than
the server expects, and the dashboard keeps saying "agent is older" after
a deploy that looked fine. deploy.sh now fetches the upstream (20s limit)
and, if the checkout is behind, asks on a terminal or refuses otherwise;
--allow-outdated deploys anyway and --dry-run only warns. A failed fetch
warns and carries on; no checkout or no upstream skips the check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:46:32 -04:00
patrick 4f45187ca0 Merge pull request 'Flag hosts where unattended-upgrades has stopped succeeding' (#27) from feat/unattended-upgrades into main
CI / tests (Python 3.10) (push) Successful in 31s
CI / tests (Python 3.11) (push) Successful in 31s
CI / tests (Python 3.12) (push) Successful in 31s
CI / tests (Python 3.13) (push) Successful in 31s
CI / lint (push) Successful in 3s
Reviewed-on: #27
2026-11-01 00:28:50 +00:00
24 changed files with 1439 additions and 31 deletions

No files matched your search

+1 -1
View File
@@ -6,4 +6,4 @@ test:
$(PYTHON) -m unittest discover -s tests
lint:
shellcheck agent/kernelwatch-agent agent/install.sh agent/deploy.sh server/install.sh server/kernelwatch.sh
shellcheck agent/kernelwatch-agent agent/kernelwatch-unit-result agent/install.sh agent/deploy.sh server/install.sh server/kernelwatch.sh
+1 -1
View File
@@ -29,7 +29,7 @@ Each host gets one status. When several apply, the worst one wins:
|----------|---------|
| `stale` | No report in `stale_after_hours` (default 3h), or never. Other data can't be trusted. |
| `reboot` | A newer kernel is installed but not running, or `/run/reboot-required` exists. |
| `update` | A kernel or security update is available but not installed, services are running outdated libraries and need a restart, or apt's package lists are too old, or apt itself fails, so "no updates" can't be trusted. Also when `/boot` is too full for the next kernel, dpkg left packages half-installed, the OS release no longer gets security updates, or unattended-upgrades is enabled but has stopped succeeding. |
| `update` | A kernel or security update is available but not installed, services are running outdated libraries and need a restart, or apt's package lists are too old, or apt itself fails, so "no updates" can't be trusted. Also when `/boot` is too full for the next kernel, the disk is too full for the pending upgrades, dpkg left packages half-installed, the OS release no longer gets security updates, or unattended-upgrades is enabled but has stopped succeeding. |
| `ok` | Running the newest installed kernel, with no security or kernel updates pending. |
Each row lists the reasons behind its status, and clicking a host shows its full
+44 -2
View File
@@ -8,6 +8,7 @@
# 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
# agent/deploy.sh --allow-outdated deploy even if this checkout is behind
#
# Settings: agent/deploy.conf (see deploy.conf.example). Hosts: agent/hosts,
# one per line: `<ssh target> [kernelwatch name]`; the name defaults to the
@@ -20,7 +21,7 @@ CONF=${KERNELWATCH_DEPLOY_CONF:-$here/deploy.conf}
HOSTS_FILE=${KERNELWATCH_HOSTS:-$here/hosts}
FILES=(kernelwatch-agent kernelwatch-agent.service kernelwatch-agent.timer
kernelwatch-needrestart.service kernelwatch-livepatch kernelwatch-livepatch.service
kernelwatch-apt-update.service install.sh)
kernelwatch-apt-update.service kernelwatch-unit-result install.sh)
NAME_RE='^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$'
SERVER_URL=
@@ -149,10 +150,47 @@ deploy_one() {
fi
}
usage() { sed -n '2,16s/^# \{0,1\}//p' "$0"; }
usage() { sed -n '2,17s/^# \{0,1\}//p' "$0"; }
# Under sudo, ssh would read root's ~/.ssh/config and keys instead of yours (a
# custom Port or IdentityFile silently disappears, so it tries port 22). Nothing
# here needs root locally: install.sh runs under sudo on each host.
refuse_sudo() {
[[ -n ${SUDO_USER:-} && $(id -u) == 0 ]] || return 0
die "don't run this with sudo: it uses your own SSH config and keys, and runs sudo on each host itself. Run it as $SUDO_USER."
}
# Deploying from a checkout that's behind its upstream ships an old agent: the
# dashboard keeps showing "agent is older" after a deploy that looked fine.
# Fetches with a time limit; a failed fetch only warns. Behind: asks on a
# terminal, otherwise needs --allow-outdated. Skipped outside a git checkout or
# without an upstream branch.
check_checkout() {
local repo upstream behind
repo=$(git -C "$here" rev-parse --show-toplevel 2>/dev/null) || return 0
upstream=$(git -C "$repo" rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null) || return 0
local -a fetch=(git -C "$repo" fetch --quiet)
command -v timeout >/dev/null && fetch=(timeout 20 "${fetch[@]}")
if ! GIT_TERMINAL_PROMPT=0 "${fetch[@]}" >/dev/null 2>&1; then
echo "deploy: warning: couldn't fetch $upstream to check this checkout is up to date" >&2
return 0
fi
behind=$(git -C "$repo" rev-list --count "HEAD..$upstream" 2>/dev/null) || return 0
((behind > 0)) || return 0
local msg="this checkout is $behind commit(s) behind $upstream, so it would deploy an older agent (git pull first)"
if ((allow_outdated || dry_run)); then
echo "deploy: warning: $msg" >&2
return 0
fi
[[ -t 0 && -t 2 ]] || die "$msg; pass --allow-outdated to deploy it anyway"
local answer
read -r -p "deploy: $msg. Deploy anyway? [y/N] " answer
[[ $answer == [yY]* ]] || die "stopped; nothing was deployed"
}
mode=upgrade
dry_run=0
allow_outdated=0
targets=()
install_args=()
while (($#)); do
@@ -165,6 +203,7 @@ while (($#)); do
--register) mode=register ;;
--rotate) mode=rotate ;;
--dry-run) dry_run=1 ;;
--allow-outdated) allow_outdated=1 ;;
-h | --help) usage; exit 0 ;;
-*) usage >&2; exit 2 ;;
*) targets+=("$1") ;;
@@ -172,6 +211,7 @@ while (($#)); do
shift
done
refuse_sudo
load_config
[[ -n $SERVER_URL ]] || die "SERVER_URL is not set in $CONF"
[[ $mode == upgrade || -n $DASHBOARD ]] || die "DASHBOARD is not set in $CONF"
@@ -182,6 +222,8 @@ if ((${#targets[@]} == 0)); then
((${#targets[@]})) || die "no hosts given and none in $HOSTS_FILE"
fi
check_checkout
failed=()
for t in "${targets[@]}"; do
say "==> $t"
+2 -1
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
# 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/26.04 host.
#
# sudo ./install.sh --server https://kernelwatch.example.internal [--ca ca.pem]
# [--with-needrestart] [--with-apt-update | --without-apt-update]
@@ -82,6 +82,7 @@ mkdir -p "$root/usr/local/sbin" "$root/etc/systemd/system"
install -d -m 0755 "$etc"
install -m 0755 "$here/kernelwatch-agent" "$root/usr/local/sbin/kernelwatch-agent"
install -m 0755 "$here/kernelwatch-livepatch" "$root/usr/local/sbin/kernelwatch-livepatch"
install -m 0755 "$here/kernelwatch-unit-result" "$root/usr/local/sbin/kernelwatch-unit-result"
install -m 0644 "$here/kernelwatch-agent.service" "$here/kernelwatch-agent.timer" \
"$here/kernelwatch-needrestart.service" "$here/kernelwatch-livepatch.service" \
"$here/kernelwatch-apt-update.service" "$root/etc/systemd/system/"
+183 -6
View File
@@ -6,7 +6,7 @@
# rules can change without redeploying agents.
set -euo pipefail
AGENT_VERSION=0.8.0
AGENT_VERSION=0.11.0
# Prefix for every file the agent reads. Only the test suite sets this.
ROOT=${KERNELWATCH_ROOT:-}
@@ -134,9 +134,15 @@ 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.
# UCSTA (CPU microcode, bare metal only; needrestart skips it in VMs): 0 unknown,
# 1 current, 2 a newer revision is installed but needs a reboot to load. UCCUR
# and UCEXP are the loaded and installed revisions.
NR_OK=0
NR_KSTA=
NR_KEXP=
NR_UCSTA=
NR_UCCUR=
NR_UCEXP=
NR_SVCS=
NR_SESS=0
read_needrestart() {
@@ -148,6 +154,9 @@ read_needrestart() {
case $line in
NEEDRESTART-KSTA:*) NR_KSTA=${line#*: } ;;
NEEDRESTART-KEXP:*) NR_KEXP=${line#*: } ;;
NEEDRESTART-UCSTA:*) NR_UCSTA=${line#*: } ;;
NEEDRESTART-UCCUR:*) NR_UCCUR=${line#*: } ;;
NEEDRESTART-UCEXP:*) NR_UCEXP=${line#*: } ;;
NEEDRESTART-SVC:*) NR_SVCS+=${line#*: }$'\n' ;;
NEEDRESTART-SESS:*) NR_SESS=$((NR_SESS + 1)) ;;
esac
@@ -180,6 +189,29 @@ read_livepatch() {
done <"$LIVEPATCH_FILE"
}
# How kernelwatch's helper units last ended, as recorded by kernelwatch-unit-result
# (their ExecStopPost=): one "NAME RESULT EXIT_CODE EXIT_STATUS FAILURES" line per
# unit that ran recently, e.g. "apt-update exit-code exited 100 3", FAILURES being
# failed runs in a row. This unit only Wants= them, so when they fail the report
# still goes out, with stale or missing data, and nothing else would say why.
# Livepatch isn't listed: its unit fails by design where the snap is installed
# but Livepatch isn't enabled, and its health is reported on its own.
HELPER_UNITS=(apt-update needrestart)
HELPER_MAX_AGE=7200
helper_units() {
local name file mtime now result='' code='' status='' failures=''
now=$(date +%s)
for name in "${HELPER_UNITS[@]}"; do
file=$ROOT/run/kernelwatch/$name.result
mtime=$(stat -c %Y "$file" 2>/dev/null) || continue
((now - mtime <= HELPER_MAX_AGE)) || continue
read -r result code status failures _ <"$file" || [[ -n $result ]] || continue
[[ $result =~ ^[a-z-]{1,32}$ && $code =~ ^[a-z-]{1,16}$ &&
$status =~ ^[A-Za-z0-9-]{1,16}$ && $failures =~ ^[0-9]{1,6}$ ]] || continue
printf '%s %s %s %s %s\n' "$name" "$result" "$code" "$status" "$failures"
done
}
# String, or null when empty.
json_str_or_null() {
if [[ -n $1 ]]; then json_str "$1"; else printf 'null'; fi
@@ -228,20 +260,72 @@ phased_packages() {
}
# Seconds since apt last refreshed its package lists, or empty if unknown.
# Both stamps are touched only after a successful update: update-success-stamp by
# Ubuntu's update-notifier hook and kernelwatch-apt-update.service, update-stamp by
# apt-daily. lists/partial changes on every attempt, failed ones too, so it's only
# a last resort for hosts that have neither (Debian without either timer).
apt_lists_age() {
local newest=0 f m
for f in \
"$ROOT/var/lib/apt/periodic/update-success-stamp" \
"$ROOT/var/lib/apt/periodic/update-stamp" \
"$ROOT/var/lib/apt/lists/partial"; do
[[ -e $f ]] || continue
"$ROOT/var/lib/apt/periodic/update-stamp"; do
m=$(stat -c %Y "$f" 2>/dev/null) || continue
((m > newest)) && newest=$m
done
((newest > 0)) && printf '%s' $(($(date +%s) - newest))
if ((newest == 0)); then
newest=$(stat -c %Y "$ROOT/var/lib/apt/lists/partial" 2>/dev/null) || return 0
fi
printf '%s' $(($(date +%s) - newest))
}
# The release's security suite (trixie-security, noble-security) and how old,
# in seconds, apt's newest list for it is, as "SUITE AGE". The age is by the
# list's Date: field, when the repository last published as of apt's last
# successful fetch, so it grows if fetches fail even while other repositories
# refresh. AGE is empty if apt has no list for the suite: it isn't in the
# sources, and security updates can't arrive. Nothing at all without a release
# codename. Lists are matched by their Suite: (Ubuntu) or Codename: (Debian)
# field, since file names depend on the mirror; with several mirrors the newest
# counts.
APT_LISTS_DIR=$ROOT/var/lib/apt/lists
security_repo() {
local codename suite f published t newest=0 now
codename=$(os_release_field VERSION_CODENAME)
[[ -n $codename ]] || codename=$(os_release_field UBUNTU_CODENAME)
[[ $codename =~ ^[a-z]+$ ]] || return 0
suite=$codename-security
for f in "$APT_LISTS_DIR"/*_InRelease "$APT_LISTS_DIR"/*_Release; do
[[ -f $f ]] || continue
# The fields come before the checksum lists, which can be long.
published=$(awk -v want="$suite" '
/^(MD5Sum|SHA1|SHA256|SHA512):/ { exit }
($1 == "Suite:" || $1 == "Codename:") && $2 == want { found = 1 }
$1 == "Date:" { sub(/^Date:[ \t]*/, ""); date = $0 }
END { if (found) print (date == "" ? "-" : date) }' "$f" 2>/dev/null) || continue
[[ -n $published ]] || continue
if [[ $published == - ]] || ! t=$(date -d "$published" +%s 2>/dev/null); then
# apt sets a list's mtime from the server's Last-Modified.
t=$(stat -c %Y "$f" 2>/dev/null) || continue
fi
((t > newest)) && newest=$t
done
printf '%s ' "$suite"
if ((newest > 0)); then
now=$(date +%s)
printf '%s' $((now > newest ? now - newest : 0))
fi
return 0
}
# Installed packages on hold (`apt-mark hold`, or dpkg's "hold" selection). apt
# never upgrades them and the simulation doesn't list them, so their updates,
# security ones included, don't show up anywhere else.
held_packages() {
dpkg-query -W -f='${db:Status-Abbrev}\t${binary:Package}\n' 2>/dev/null |
awk -F '\t' 'substr($1, 1, 2) == "hi" { print $2 }' |
sort -u || true
}
# Size and free space of the filesystem holding /boot, in KiB, as "SIZE FREE";
# empty if df can't tell. That's the root filesystem when /boot isn't its own
# mount. A full /boot makes the next kernel's postinst fail, so the host stays
@@ -251,6 +335,81 @@ boot_space() {
awk 'NR == 2 && $2 ~ /^[0-9]+$/ && $4 ~ /^[0-9]+$/ { print $2, $4 }' || true
}
# Free space in KiB and mount point of the filesystem holding $1, as "FREE MOUNT";
# empty if df can't tell. The mount point is everything after df's fifth column,
# so one with spaces survives.
fs_free() {
df -Pk "$1" 2>/dev/null |
awk 'NR == 2 && $4 ~ /^[0-9]+$/ {
m = $0
for (i = 1; i <= 5; i++) sub(/^[^ ]+ +/, "", m)
print $4, m
}' || true
}
# Archives apt downloads into before installing. The agent assumes the default.
APT_ARCHIVES=$ROOT/var/cache/apt/archives
# Space the pending upgrades need, in KiB, as "DOWNLOAD INSTALL", from the
# simulation's Inst lines on stdin; empty if apt-cache can't say. A simulation
# doesn't print apt's "Need to get" and "additional disk space" lines, so this
# adds them up from the package records instead: Size for each .deb not already
# in $APT_ARCHIVES (unattended-upgrades often downloads ahead), and the growth in
# Installed-Size, the new versions' minus the installed ones'. INSTALL can be
# negative. Packages the upgrade removes aren't counted, so it errs high.
upgrade_space() {
local name f3 f4 ver file size isize records dl=0 grow=0
local -a specs=() upgraded=()
while read -r _ name f3 f4 _; do
[[ -n $name ]] || continue
# "Inst NAME [OLD] (NEW ...)" for an upgrade, "Inst NAME (NEW ...)" for a new package.
if [[ $f3 == '['* ]]; then
ver=${f4#(}
upgraded+=("$name")
else
ver=${f3#(}
fi
specs+=("$name=$ver")
done
if ((${#specs[@]} == 0)); then
echo "0 0"
return 0
fi
# apt stores archives as NAME_VERSION_ARCH.deb with ':' (epochs) as %3a.
records=$(LC_ALL=C apt-cache -q \
-o Dir::Cache::pkgcache= \
-o Dir::Cache::srcpkgcache= \
show "${specs[@]}" 2>/dev/null | awk 'BEGIN { RS = "" } {
pkg = ver = arch = ""; size = isize = 0
n = split($0, line, "\n")
for (i = 1; i <= n; i++) {
if (line[i] ~ /^Package: /) pkg = substr(line[i], 10)
else if (line[i] ~ /^Version: /) ver = substr(line[i], 10)
else if (line[i] ~ /^Architecture: /) arch = substr(line[i], 15)
else if (line[i] ~ /^Size: /) size = substr(line[i], 7) + 0
else if (line[i] ~ /^Installed-Size: /) isize = substr(line[i], 17) + 0
}
if (pkg == "" || ver == "") next
gsub(/:/, "%3a", ver)
file = pkg "_" ver "_" arch ".deb"
if (seen[file]++) next
print file, size, isize
}') || return 0
[[ -n $records ]] || return 0
while read -r file size isize; do
grow=$((grow + isize))
[[ -e $APT_ARCHIVES/$file ]] || dl=$((dl + size))
done <<<"$records"
if ((${#upgraded[@]})); then
while read -r isize; do
[[ $isize =~ ^[0-9]+$ ]] && grow=$((grow - isize))
done < <(dpkg-query -W -f='${Installed-Size}\n' "${upgraded[@]}" 2>/dev/null || true)
fi
echo "$(((dl + 1023) / 1024)) $grow"
}
# Packages dpkg didn't finish installing or removing: half-installed, unpacked,
# half-configured, awaiting or pending triggers, or flagged reinst-required.
# The same states `dpkg --audit` reports; usually a failed postinst, cleared by
@@ -322,7 +481,8 @@ uptime_seconds() {
build_report() {
local running newest kernels sim inst sim_err rc apt_ok=1 apt_err='' reboot_file=0 reboot_pkgs=
local boot_size='' boot_free='' pro_attached='' pro_esm=''
local boot_size='' boot_free='' pro_attached='' pro_esm='' sec_suite='' sec_age=''
local up_dl='' up_grow='' arch_free='' arch_mount='' usr_free='' usr_mount=''
running=$(uname -r)
kernels=$(installed_kernels)
@@ -347,7 +507,11 @@ build_report() {
fi
read -r boot_size boot_free <<<"$(boot_space)" || true
((apt_ok)) && { read -r up_dl up_grow <<<"$(upgrade_space <<<"$inst")" || true; }
read -r arch_free arch_mount <<<"$(fs_free "$APT_ARCHIVES")" || true
read -r usr_free usr_mount <<<"$(fs_free "$ROOT/usr")" || true
read -r pro_attached pro_esm <<<"$(ubuntu_pro)" || true
read -r sec_suite sec_age <<<"$(security_repo)" || true
[[ $pro_esm == - ]] && pro_esm=
printf '{'
@@ -363,6 +527,9 @@ 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")"
printf '"needrestart_ucsta":%s,' "$(json_int "$NR_UCSTA")"
printf '"needrestart_uccur":%s,' "$(json_str_or_null "$NR_UCCUR")"
printf '"needrestart_ucexp":%s,' "$(json_str_or_null "$NR_UCEXP")"
if ((NR_OK)); then
printf '"services_need_restart":%s,' "$(sort -u <<<"$NR_SVCS" | json_str_array)"
printf '"sessions_need_restart":%s,' "$NR_SESS"
@@ -388,7 +555,14 @@ build_report() {
printf '"livepatch_fix_count":%s,' "$(json_int "$LP_FIXES")"
printf '"boot_size_kb":%s,' "$(json_int "$boot_size")"
printf '"boot_free_kb":%s,' "$(json_int "$boot_free")"
printf '"upgrade_download_kb":%s,' "$(json_int "$up_dl")"
printf '"upgrade_install_kb":%s,' "$(json_int "$up_grow")"
printf '"apt_archives_free_kb":%s,' "$(json_int "$arch_free")"
printf '"apt_archives_mount":%s,' "$(json_str_or_null "$arch_mount")"
printf '"usr_free_kb":%s,' "$(json_int "$usr_free")"
printf '"usr_mount":%s,' "$(json_str_or_null "$usr_mount")"
printf '"dpkg_unfinished_packages":%s,' "$(unfinished_packages | json_str_array)"
printf '"held_packages":%s,' "$(held_packages | json_str_array)"
case $pro_attached in
true | false) printf '"ubuntu_pro_attached":%s,' "$pro_attached" ;;
*) printf '"ubuntu_pro_attached":null,' ;;
@@ -400,6 +574,9 @@ build_report() {
printf '"unattended_upgrades_kept_back":%s,' \
"$( { [[ -r $UU_KEPT_FILE ]] && tr -s ' \t' '\n' <"$UU_KEPT_FILE"; } | sort -u | json_str_array)"
printf '"apt_lists_age_seconds":%s,' "$(json_int "$(apt_lists_age)")"
printf '"security_repo_suite":%s,' "$(json_str_or_null "$sec_suite")"
printf '"security_repo_age_seconds":%s,' "$(json_int "$sec_age")"
printf '"helper_units":%s,' "$(helper_units | json_str_array)"
printf '"uptime_seconds":%s' "$(json_int "$(uptime_seconds)")"
printf '}\n'
}
+26 -6
View File
@@ -10,16 +10,36 @@ After=network-online.target
[Service]
Type=oneshot
# Same as `apt-get update`: downloads lists, installs nothing. A failure (no
# network, lock held by an admin's apt run) mustn't stop the report; the
# dashboard flags lists that stay old.
ExecStart=-/usr/bin/apt-get -q update
# network, lock held by an admin's apt run) fails this unit but not the report,
# since kernelwatch-agent.service only Wants= it. The stamp then stops moving
# and the dashboard flags the lists as old.
ExecStart=/usr/bin/apt-get -q update
# Reached only when apt succeeded. It's the stamp Ubuntu's update-notifier hook
# writes after every successful apt update, and the agent reads it as the lists'
# age; Debian has nothing else that writes it. lists/partial, the agent's last
# resort, changes even when the update fails.
ExecStartPost=/bin/sh -c 'mkdir -p /var/lib/apt/periodic && touch /var/lib/apt/periodic/update-success-stamp'
# Records how the run ended, success or not, so the agent can report failures,
# which are otherwise silent while apt-daily keeps the lists fresh.
ExecStopPost=/usr/local/sbin/kernelwatch-unit-result apt-update
RuntimeDirectory=kernelwatch
RuntimeDirectoryMode=0755
RuntimeDirectoryPreserve=yes
UMask=0022
TimeoutStartSec=5min
# Lowest best-effort disk priority, not the idle class: idle gets disk time only
# when nothing else wants it, so on a host with constant I/O apt waits on
# reading and writing its lists until the timeout kills it, every run.
Nice=10
IOSchedulingClass=idle
IOSchedulingClass=best-effort
IOSchedulingPriority=7
# apt needs root to write /var/lib/apt and drops to _apt for downloads, so this
# keeps root but loses everything apt update doesn't touch.
User=root
# runs as root (the default) but loses everything apt update doesn't touch.
# Don't add User=root: with it, NoNewPrivileges and any of the seccomp-based
# options below, apt 2.7+ (Ubuntu 24.04, Debian 13) can't switch to _apt
# ("seteuid 42 failed - seteuid (1: Operation not permitted)") and every update
# fails.
NoNewPrivileges=yes
ProtectHome=yes
PrivateTmp=yes
+3
View File
@@ -8,6 +8,9 @@ ConditionPathExists=/usr/sbin/needrestart
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'
# Records how the run ended, success or not, so the agent can report failures:
# otherwise the results just go missing and the dashboard shows "unknown".
ExecStopPost=/usr/local/sbin/kernelwatch-unit-result needrestart
RuntimeDirectory=kernelwatch
RuntimeDirectoryMode=0755
RuntimeDirectoryPreserve=yes
+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
# Records how a kernelwatch helper unit's run ended, for the agent to report.
# Run as the unit's ExecStopPost=, which systemd runs after every run, failed or
# not, with SERVICE_RESULT, EXIT_CODE and EXIT_STATUS set (systemd.exec(5)).
#
# Usage: kernelwatch-unit-result NAME
# Writes /run/kernelwatch/NAME.result as "RESULT EXIT_CODE EXIT_STATUS FAILURES",
# e.g. "exit-code exited 100 3", where FAILURES counts failed runs in a row and
# is 0 after a success. A missing value is written as "-".
set -u
name=${1:-}
case $name in
'' | *[!a-z0-9-]*)
echo "usage: kernelwatch-unit-result NAME" >&2
exit 2
;;
esac
file=${KERNELWATCH_RUN_DIR:-/run/kernelwatch}/$name.result
result=${SERVICE_RESULT:--}
failures=0
if [ "$result" != success ]; then
failures=$(awk '$4 ~ /^[0-9]+$/ { print $4 }' "$file" 2>/dev/null)
failures=$((${failures:-0} + 1))
fi
printf '%s %s %s %s\n' "$result" "${EXIT_CODE:--}" "${EXIT_STATUS:--}" "$failures" >"$file.new" &&
mv "$file.new" "$file"
+158
View File
@@ -47,6 +47,150 @@ systemctl list-timers kernelwatch-agent.timer
journalctl -u kernelwatch-agent
```
## Ubuntu Livepatch
[Livepatch](https://ubuntu.com/security/livepatch) applies high and critical
kernel fixes without a reboot. kernelwatch needs no setup for it: the agent
always installs `kernelwatch-livepatch.service`, which runs only on hosts that
have the `canonical-livepatch` snap. Turn Livepatch on for the host and the next
report picks it up. What it changes on the dashboard is in
[How it works](how-it-works.md) under "Ubuntu Livepatch".
Livepatch is part of [Ubuntu Pro](https://ubuntu.com/pro), which is free for
personal use on up to five machines. Get your token from the
[Pro dashboard](https://ubuntu.com/pro/dashboard), then on the host:
```sh
sudo pro attach <token> # usually enables Livepatch and ESM too
sudo pro enable livepatch # no-op if attach already did
sudo canonical-livepatch status # check the kernel is supported and patches applied
```
Check that kernelwatch sees it:
```sh
sudo systemctl start kernelwatch-agent # runs kernelwatch-livepatch.service first
sudo cat /run/kernelwatch/livepatch # LIVEPATCH-STATE: applied (or nothing-to-apply)
```
The host page then shows a Livepatch row, such as "applied, 2 fixes applied,
supported until 2027-09-07". From then on:
- A newer kernel that's installed but not running, or a `/run/reboot-required`
caused only by `linux-*` packages, shows as a note ("live-patched; kernel
upgrade needed by ...") instead of putting the host in `reboot`. Other reboot
reasons (libc, systemd) still count.
- That cover ends 14 days before the running kernel's Livepatch support does,
and the host goes to `reboot` as usual.
- If Livepatch breaks, or a host that used to report it stops, you get an
[ntfy alert](alerts.md#stale-host-reboot-and-update-alerts-ntfy) after
`livepatch_alert_after_hours` (default 6).
Attaching to Pro also enables ESM (`esm-infra`), which the OS end-of-support
check counts: an Ubuntu release past standard support stays fine while ESM is
on. The host page's "OS security support" row shows it.
Things to know:
- **Supported kernels only.** Livepatch covers LTS releases on the kernel
flavours Canonical supports. On any other kernel, `canonical-livepatch status`
says it isn't supported, and kernelwatch shows "livepatch not healthy (...,
unsupported)" and gives no reboot cover.
- **Turning it off.** After `sudo pro disable livepatch` (or `pro detach`), the
host stops reporting Livepatch, which looks the same as a dead daemon: you get
one alert after `livepatch_alert_after_hours`, then nothing more. That's
expected.
- **Debian** has no Livepatch; nothing here applies, and nothing needs turning off.
For hosts without Livepatch, see [Rebooting automatically](#rebooting-automatically).
## Rebooting automatically
kernelwatch tells you a host needs a reboot; it never reboots anything. On hosts
without Livepatch, unattended-upgrades can do it: after a run that leaves
`/run/reboot-required` (a new kernel, libc, systemd), it reboots the host at a
set time. kernelwatch then confirms the reboot happened.
unattended-upgrades has to be installed and enabled first. Ubuntu Server has
it already; on Debian:
```sh
sudo apt install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades # answer yes
```
The host page's "unattended-upgrades" row should then say `enabled`. Its kernel
hook (`/etc/kernel/postinst.d/unattended-upgrades`) creates
`/run/reboot-required` on Debian too, which Debian's kernel packages don't do
themselves.
Then turn the reboots on with a file of your own, so package upgrades never
overwrite it. Settings in later files win over `50unattended-upgrades`:
```sh
sudo tee /etc/apt/apt.conf.d/52automatic-reboot <<'EOF'
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "03:30";
EOF
apt-config dump | grep Automatic-Reboot # check it took
```
Or from your workstation, for one host:
```sh
printf '%s\n' 'Unattended-Upgrade::Automatic-Reboot "true";' \
'Unattended-Upgrade::Automatic-Reboot-Time "03:30";' |
ssh -t web01 'sudo tee /etc/apt/apt.conf.d/52automatic-reboot'
```
Choosing the times:
- **Pick a time between midnight and 05:00.** `apt-daily-upgrade.timer` runs
unattended-upgrades between 06:00 and 07:00, and the reboot then waits for the
next occurrence of `Automatic-Reboot-Time`. A time in that window or just
after it can leave the host in `reboot` for nearly a full day, and the
[reboot alert](alerts.md#stale-host-reboot-and-update-alerts-ntfy) fires
after `status_alert_after_hours` (default 24). A time before 05:00 keeps the
wait under a day.
- **Stagger them.** Give hosts that depend on each other different times, half
an hour or more apart. That includes a database and the services that use it,
an SSH jump host and the hosts behind it, and redundant pairs. Then one
that doesn't come back is a single problem, not an outage.
- **Give the dashboard host its own slot.** While it's down nothing gets
alerted, though the [heartbeat](alerts.md#heartbeat-is-kernelwatch-itself-running)
notices if it stays down. It's best rebooted when nothing else is.
- Leave out `Automatic-Reboot-Time` (or set it to `now`) to reboot right after
the run, around 06:00–07:00.
- `Unattended-Upgrade::Automatic-Reboot-WithUsers "false"` skips the reboot
while anyone is logged in. A host someone stays logged into then never
reboots, and kernelwatch alerts after a day.
How kernelwatch shows it:
- After the upgrade the host is in `reboot` with the reason, such as "kernel:
running 6.8.0-136-generic, 6.8.0-138-generic installed".
- The agent reports 2 minutes after boot, so the host goes back to `ok` within
minutes of the reboot, and the host page's Uptime starts again.
- If it doesn't come back, it goes `stale` after `stale_after_hours` (default 3)
and you get the stale alert.
- If the reboot never happens (unattended-upgrades failing, a logged-in user
with `WithUsers "false"`, an upgrade you ran by hand that unattended-upgrades
had nothing to do with), the host stays in `reboot` and you get the reboot
alert after `status_alert_after_hours`. A failing unattended-upgrades also
shows up as its own reason.
Things to know:
- **Livepatch hosts:** leave this off there. Livepatch's cover only applies to
kernel reboots, and with `Automatic-Reboot` on, unattended-upgrades reboots
for the new kernel anyway, which throws that cover away. kernelwatch tells
you when the cover runs out.
- **Services needing a restart** (outdated libraries) never cause a reboot;
the host page lists them. On Ubuntu, needrestart restarts most of them after
the upgrade. On Debian with `--with-needrestart`, kernelwatch sets
needrestart to only list them, so run `sudo needrestart -r a`.
- **Turning it off:** delete `/etc/apt/apt.conf.d/52automatic-reboot`.
## Deploying to many hosts
`agent/deploy.sh` does all of the above over SSH from your workstation's
@@ -67,6 +211,7 @@ 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
agent/deploy.sh -- --with-apt-update # refresh package lists before each report
agent/deploy.sh --allow-outdated # deploy even if this checkout is behind upstream
```
For each host it copies the agent into a private temp directory and runs
@@ -78,6 +223,19 @@ in your terminal. A plain run is an upgrade: config and token stay as they
are. You'll get sudo prompts on each host, and on the dashboard when
registering, unless you have passwordless sudo.
Run it as yourself, not with `sudo`: it connects with your own SSH config and
keys and runs `sudo` on each host itself. Under `sudo`, ssh would read root's
config instead, so a custom `Port` or `IdentityFile` disappears and it tries
port 22. It refuses to run that way.
Before deploying, it fetches your checkout's upstream branch. If the checkout
is behind (you pulled on the dashboard host but not here, say), it would ship an
older agent than the server expects, and the dashboard would keep saying
"agent is older" after a deploy that looked fine. So it asks before going on,
or refuses when it isn't run from a terminal; `git pull` first, or pass
`--allow-outdated` to deploy it anyway. `--dry-run` only warns. If the fetch
fails (offline, say), it warns and deploys.
Both files are git-ignored. Host names default to each host's `hostname -s`;
put `<ssh target> <name>` in `agent/hosts` to override. For a host your
workstation can't reach directly (e.g. IPv6-only while you're on IPv4), give it
+79 -5
View File
@@ -9,8 +9,8 @@ Each host gets one status. When several apply, the worst one wins:
| Status | Meaning |
|----------|---------|
| `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, services are running outdated libraries and need a restart, or apt's package lists are too old (`apt_stale_after_hours`) for "no updates" to mean anything. Also when `/boot` has less than `boot_min_free_mb` free, dpkg left packages half-installed, the OS release no longer gets security updates, or unattended-upgrades is enabled but hasn't succeeded in `unattended_upgrades_stale_after_days`. |
| `reboot` | A newer kernel is installed but not running, `/run/reboot-required` exists, or newer CPU microcode is installed but not loaded. |
| `update` | A kernel or security update is available but not installed, services are running outdated libraries and need a restart, or apt's package lists are too old (`apt_stale_after_hours`) for "no updates" to mean anything. Also when `/boot` has less than `boot_min_free_mb` free, the pending upgrades would leave less than `upgrade_min_free_mb` free where apt downloads or installs them, dpkg left packages half-installed, a kernel package is on hold, the OS release no longer gets security updates, unattended-upgrades is enabled but hasn't succeeded in `unattended_upgrades_stale_after_days`, the release's security repository is missing from apt or hasn't refreshed in `security_repo_stale_after_days`, or one of kernelwatch's own helper units has failed three runs in a row. |
| `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
@@ -39,6 +39,14 @@ How the agent works it out:
The agent never runs as root, and needrestart never gets network access. Fix it on the host:
`sudo needrestart -r a` (or restart the listed services), and the next report
clears it.
- **CPU microcode**: on bare metal, needrestart also compares the microcode
revision the CPU loaded at boot with the one the installed `intel-microcode`
or `amd64-microcode` package provides. A newer one only loads on a reboot, so
it puts the host in `reboot`: "CPU microcode update installed but not loaded
(0x001e → 0x0020)". Livepatch doesn't cover it. needrestart skips the check in
virtual machines (the hypervisor handles microcode), so the host page's "CPU
microcode" row only appears on physical hosts. Agents before 0.10.0 don't
report it.
- **Ubuntu Livepatch**: with [Livepatch](https://ubuntu.com/security/livepatch)
(free for personal use with Ubuntu Pro), a newer kernel being installed doesn't
mean the running one is unpatched. If Livepatch is healthy (`applied` or
@@ -54,6 +62,20 @@ How the agent works it out:
root and a snap cgroup, so like needrestart it runs in its own unit,
`kernelwatch-livepatch.service`, which writes `/run/kernelwatch/livepatch`
before each report. It's skipped when the snap isn't installed.
- **kernelwatch's own helpers**: `kernelwatch-apt-update.service` and
`kernelwatch-needrestart.service` run as root just before each report. The
agent only `Wants=` them, so if they fail the report still goes out, with
stale lists or no needrestart results, and nothing would say why. So each one
records how its run ended (`ExecStopPost=kernelwatch-unit-result`, in
`/run/kernelwatch/<name>.result`), counting failures in a row, and the agent
reports it. One or two failures are a note, since one run can fail now and
then (an admin's apt holding the lock). Three in a row, about three hours,
put the host in `update`: "kernelwatch-apt-update.service failed its last 3
runs (exit status 100); see journalctl -u kernelwatch-apt-update.service".
The host page's "kernelwatch helpers" row shows each one. The Livepatch unit
isn't tracked: it fails by design where the snap is installed but Livepatch
isn't enabled, and Livepatch has its own check. Agents before 0.10.0 don't
report 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.
@@ -84,6 +106,28 @@ How the agent works it out:
`boot_min_free_mb` (default 200) free puts the host in `update` with "/boot has
N MB free". Fix it on the host: `sudo apt autoremove --purge` removes old
kernels.
- **Room for the pending upgrades**: if a filesystem fills up while apt
downloads or dpkg unpacks, the upgrade stops half-way and apt is left broken,
as with a full `/boot`. Under unattended-upgrades, nobody is watching when it
happens. A
simulation doesn't print apt's "Need to get" and "additional disk space"
figures, so the agent works them out from the package records (`apt-cache
show` for each version the simulation would install). The download is the
`Size` of each `.deb` not already in `/var/cache/apt/archives`;
unattended-upgrades often downloads ahead. The install is the growth in
`Installed-Size`: the new versions' minus the installed ones', or all of it
for new packages. Packages the upgrade would remove aren't subtracted, so
the estimate errs high. The agent also reports free space and the mount
point of the filesystems holding `/var/cache/apt/archives` and `/usr`. If
they're the same filesystem, the download and the install both count against
it. A filesystem the upgrades would leave with less than
`upgrade_min_free_mb` (default 100) free puts the host in `update` with
"pending upgrades need N MB on /var (...), M MB free". Nothing pending means
nothing to check, however full the disk is. kernelwatch doesn't monitor disk
usage in general; use your usual monitoring for that. Fix it on the host:
`sudo apt clean` empties the download cache, and `sudo apt autoremove
--purge` removes old kernels' modules from `/usr/lib/modules`. Agents before
0.11.0 don't report it.
- **Unfinished packages**: packages dpkg didn't finish installing, read from its
status database (the same states `dpkg --audit` reports: half-installed,
unpacked, half-configured, waiting on triggers, or reinst-required). These are
@@ -92,6 +136,15 @@ How the agent works it out:
host: `sudo dpkg --configure -a` (after freeing space, if that was the cause).
A report taken while apt is mid-install can show this briefly; the next one
clears it. Agents before 0.6.0 send neither field and are judged as before.
- **Packages on hold**: installed packages marked `hold` (`apt-mark hold`, or
dpkg's selection), from dpkg's status database. apt never upgrades them, and
the simulation doesn't list them, so their updates (security ones included)
don't show up anywhere else. A held `linux-*` package (`linux-image-amd64`,
`linux-generic`) would leave the host on its current kernel while looking up
to date, so it puts the host in `update`; release it with
`sudo apt-mark unhold <package>`. Other holds are usually deliberate and only
get a note. The host page lists them all. Agents before 0.10.0 don't report
holds.
- **OS end of support**: once a release stops getting security updates, apt
never offers one again, so the host would show `ok` indefinitely. The server
knows when each supported release's free security support ends
@@ -134,6 +187,22 @@ How the agent works it out:
`kernelwatch-apt-update.service` runs `apt-get update` just before each
report, so updates show up within the hour. Either way, lists older than
`apt_stale_after_hours` put the host in `update`.
- **Security repository**: security updates come from one suite,
`<codename>-security` (`trixie-security`, `noble-security`). A host whose apt
sources lack it sees "0 security updates" forever. One whose apt can't fetch
it (an expired key, a wrong URL after a release upgrade, a mirror that fell
behind) keeps the last copy while the update stamps and other lists move on.
So the agent finds apt's list for that suite by its `Suite:`/`Codename:` field
(file names depend on the mirror) and reports how old its `Date:` is, the
newest copy if there are several mirrors. No list puts the host in `update`
("apt has no trixie-security repository"), and so does a copy older than
`security_repo_stale_after_days` (default 7; both suites publish at least
daily) while the package lists are otherwise fresh. If all the lists are old,
only "package lists N days old" is shown. ESM suites aren't checked, as they
publish rarely, and nor is a release past the end of support, whose suite has
stopped. The host page's "Security repository" row shows the suite and its
age. Set `security_repo_stale_after_days = 0` to turn this off, e.g. for a
local mirror that renames the suite. Agents before 0.9.0 don't report it.
- **Phased updates** (Ubuntu only): Ubuntu rolls some updates out gradually and
holds them back from a share of machines at first. apt doesn't offer these to
the host yet, so they aren't counted as available updates. They appear as
@@ -141,9 +210,14 @@ How the agent works it out:
list also on the host page.
They never affect status, because Ubuntu doesn't phase security updates and
there's nothing to act on until apt offers them.
- **Package list freshness**: the mtime of apt's update stamps. The agent
**doesn't run `apt update`** itself; it relies on the stock `apt-daily.timer`.
If that's disabled, the host shows `update` with "package lists N days old".
- **Package list freshness**: the mtime of apt's success stamps,
`update-success-stamp` (Ubuntu, and `kernelwatch-apt-update.service`) and
`update-stamp` (`apt-daily`), both in `/var/lib/apt/periodic/` and touched
only when `apt update` succeeds. A host with neither falls back to
`/var/lib/apt/lists/partial`, which changes on failed updates too. The agent
**doesn't run `apt update`** itself; it relies on `apt-daily.timer` or
`--with-apt-update`. If the lists stop refreshing, the host shows `update`
with "package lists N days old".
The agent sends raw facts and the server decides what they mean, so you can
change the status rules without touching the agents.
+1 -1
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
# Install or upgrade the kernelwatch server on Debian 12/13 or Ubuntu 24.04.
# Install or upgrade the kernelwatch server on Debian 12+ or Ubuntu 22.04+.
#
# sudo ./install.sh
#
+1 -1
View File
@@ -4,4 +4,4 @@ __version__ = "0.4.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.8.0"
AGENT_VERSION = "0.11.0"
+13
View File
@@ -33,6 +33,10 @@ class Config:
# Less free space than this on /boot's filesystem puts a host in update: the next
# kernel (image plus initramfs, often over 100 MB) may not fit. 0 disables.
boot_min_free_mb: int = 200
# Pending upgrades that would leave less free space than this on the filesystem
# apt downloads to, or the one /usr is on, put a host in update: dpkg would run
# out of room part-way. 0 disables.
upgrade_min_free_mb: int = 100
# Note a host this many days before its OS release stops getting security updates
# (or Ubuntu standard support ends without ESM). 0 disables the warning; a host
# past the date is in update either way.
@@ -40,6 +44,11 @@ class Config:
# A host with unattended-upgrades enabled that hasn't had a successful run in this
# long is in update. It normally runs daily. 0 disables the check.
unattended_upgrades_stale_after_days: float = 3.0
# A host whose apt lists have no repository for its release's security suite
# (e.g. trixie-security), or whose copy of it is older than this while its other
# lists refresh, is in update: security updates can't reach it. Debian and
# Ubuntu publish it at least daily. 0 disables the check.
security_repo_stale_after_days: float = 7.0
# Where `scheduled-backup` (kernelwatch-backup.timer) writes dated copies of the
# database, and how many days of them it keeps; 0 keeps them all. It must stay
@@ -105,10 +114,14 @@ def load(path: str | None = None) -> Config:
raise SystemExit(f"{path}: report_min_interval_seconds must be zero or positive")
if not math.isfinite(cfg.unattended_upgrades_stale_after_days) or cfg.unattended_upgrades_stale_after_days < 0:
raise SystemExit(f"{path}: unattended_upgrades_stale_after_days must be zero or positive and finite")
if not math.isfinite(cfg.security_repo_stale_after_days) or cfg.security_repo_stale_after_days < 0:
raise SystemExit(f"{path}: security_repo_stale_after_days must be zero or positive and finite")
if cfg.os_eol_warn_days < 0:
raise SystemExit(f"{path}: os_eol_warn_days must be zero or positive")
if cfg.boot_min_free_mb < 0:
raise SystemExit(f"{path}: boot_min_free_mb must be zero or positive")
if cfg.upgrade_min_free_mb < 0:
raise SystemExit(f"{path}: upgrade_min_free_mb must be zero or positive")
if cfg.backup_keep_days < 0:
raise SystemExit(f"{path}: backup_keep_days must be zero or positive")
if not cfg.backup_dir.startswith("/") or any(ord(c) < 32 or ord(c) == 127 for c in cfg.backup_dir):
+13
View File
@@ -27,6 +27,9 @@ FIELDS: dict[str, str] = {
"kernel_newest_installed": "str",
"needrestart_ksta": "int",
"needrestart_kexp": "str",
"needrestart_ucsta": "int",
"needrestart_uccur": "str",
"needrestart_ucexp": "str",
"services_need_restart": "strlist",
"sessions_need_restart": "int",
"reboot_required": "bool",
@@ -44,7 +47,14 @@ FIELDS: dict[str, str] = {
"apt_simulation_error": "str",
"boot_size_kb": "int",
"boot_free_kb": "int",
"upgrade_download_kb": "int",
"upgrade_install_kb": "int",
"apt_archives_free_kb": "int",
"apt_archives_mount": "str",
"usr_free_kb": "int",
"usr_mount": "str",
"dpkg_unfinished_packages": "strlist",
"held_packages": "strlist",
"ubuntu_pro_attached": "bool",
"ubuntu_esm_infra": "str",
"unattended_upgrades": "str",
@@ -52,6 +62,9 @@ FIELDS: dict[str, str] = {
"unattended_upgrades_run_age_seconds": "int",
"unattended_upgrades_kept_back": "strlist",
"apt_lists_age_seconds": "int",
"security_repo_suite": "str",
"security_repo_age_seconds": "int",
"helper_units": "strlist",
"uptime_seconds": "int",
}
+130
View File
@@ -30,6 +30,8 @@ LIVEPATCH_HEALTHY_STATES = ("applied", "nothing-to-apply")
KSTA_CURRENT = 1
KSTA_ABI_UPGRADE = 2
KSTA_VERSION_UPGRADE = 3
# needrestart's NEEDRESTART-UCSTA: a newer CPU microcode is installed but not loaded.
UCSTA_OBSOLETE = 2
@dataclass
@@ -157,6 +159,36 @@ def boot_space_low(report: dict[str, Any], cfg: Config) -> str | None:
return f"/boot has {free_kb // 1024} MB free{used}; the next kernel may not fit"
def _mb(kb: int) -> int:
"""KiB to MB, rounded up so a small need never reads as 0 MB."""
return -(-kb // 1024)
def upgrade_space_low(report: dict[str, Any], cfg: Config) -> list[str]:
"""Filesystems the pending upgrades would leave with under upgrade_min_free_mb
free. Downloads land on the filesystem holding /var/cache/apt/archives, installed
files on /usr's; when that's the same filesystem, both count against it. Nothing
pending means nothing to check, however full the disk: general disk usage is out
of scope. Agents before 0.11.0 don't report it; unknown counts as fine."""
download, install = report.get("upgrade_download_kb"), report.get("upgrade_install_kb")
if not cfg.upgrade_min_free_mb or download is None or install is None:
return []
needs: dict[str, list[int]] = {} # mount -> [download KiB, install KiB, free KiB]
for prefix, slot, amount in (("apt_archives", 0, download), ("usr", 1, max(install, 0))):
mount, free = report.get(f"{prefix}_mount"), report.get(f"{prefix}_free_kb")
if mount and free is not None:
needs.setdefault(mount, [0, 0, free])[slot] += amount
reasons = []
for mount, (dl, inst, free) in needs.items():
if not dl + inst or free - dl - inst >= cfg.upgrade_min_free_mb * 1024:
continue
parts = [f"{_mb(dl)} MB download" if dl else "", f"{_mb(inst)} MB installed" if inst else ""]
reasons.append(f"pending upgrades need {_mb(dl + inst)} MB on {mount} "
f"({' + '.join(p for p in parts if p)}), {free // 1024} MB free; "
f"they may fail part-way")
return reasons
UU_LOG = "/var/log/unattended-upgrades/"
@@ -191,6 +223,73 @@ def unattended_upgrades_problem(report: dict[str, Any], cfg: Config) -> tuple[bo
"is apt-daily-upgrade.timer enabled?")
def security_repo_problem(report: dict[str, Any], cfg: Config, today: date) -> str | None:
"""Why security updates may not be reaching this host from its release's security
suite, or None. Agents before 0.9.0, and releases without a codename, don't
report the suite.
The age is of the suite's Date: field as of apt's last successful fetch of it, so
it keeps growing when fetching that repository fails, even while the update
stamps and other lists move on."""
suite = report.get("security_repo_suite")
if not suite or not cfg.security_repo_stale_after_days:
return None
rel = support.release(report)
if rel is not None and today > rel.end:
return None # the suite has stopped publishing; support.check covers it
age = report.get("security_repo_age_seconds")
if age is None:
return (f"apt has no {suite} repository, so security updates can't arrive; "
"add it to the apt sources and run apt update")
if age <= cfg.security_repo_stale_after_days * 86400:
return None
apt_age = report.get("apt_lists_age_seconds")
if apt_age is None or apt_age / 3600 > cfg.apt_stale_after_hours:
return None # apt isn't refreshing anything; the package list reason covers it
return (f"apt's {suite} list is {_age(age)} old while apt update otherwise succeeds; "
f"run apt update and look for errors about {suite}")
# kernelwatch's helper units (apt-update, needrestart) run before every report, so
# about hourly. This many failures in a row put the host in update; fewer are a
# note, since one can fail now and then (apt's lock held by an admin's apt run).
HELPER_FAILURES_BEFORE_PROBLEM = 3
def helper_units(report: dict[str, Any]) -> list[tuple[str, str, str, str, int]]:
"""(name, result, exit code, exit status, failures in a row) for each helper unit
the agent reported. Agents before 0.10.0 report none."""
out = []
for entry in report.get("helper_units") or []:
parts = entry.split()
if len(parts) == 5 and parts[4].isdigit():
out.append((*parts[:4], int(parts[4])))
return out
def helper_failure(result: str, code: str, status: str) -> str:
"""How a helper unit's run failed, in words."""
if code == "exited":
return f"exit status {status}"
if code in ("killed", "dumped"):
return f"{result}, signal {status}"
return result
def helper_unit_problems(report: dict[str, Any]) -> list[tuple[bool, str]]:
"""(is it a problem, why) for each kernelwatch helper unit whose last run failed."""
found = []
for name, result, code, status, failures in helper_units(report):
if result == "success" or not failures:
continue
unit = f"kernelwatch-{name}.service"
runs = "run" if failures == 1 else f"{failures} runs"
found.append((failures >= HELPER_FAILURES_BEFORE_PROBLEM,
f"{unit} failed its last {runs} ({helper_failure(result, code, status)}); "
f"see journalctl -u {unit}"))
return found
def _kernel_only_reboot_file(report: dict[str, Any]) -> bool:
"""/run/reboot-required exists only because of kernel packages."""
pkgs = report.get("reboot_required_pkgs") or []
@@ -242,6 +341,11 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float,
status.raise_to("reboot", f"/run/reboot-required{detail}")
if livepatch_note and not covered:
status.note(livepatch_note)
# Microcode loads at boot; Livepatch doesn't cover it.
if report.get("needrestart_ucsta") == UCSTA_OBSOLETE:
cur, exp = report.get("needrestart_uccur"), report.get("needrestart_ucexp")
detail = f" ({cur} → {exp})" if cur and exp else ""
status.raise_to("reboot", f"CPU microcode update installed but not loaded{detail}")
# An agent whose apt simulation failed sends no update counts, so "no security
# updates" would be a guess. Agents before 0.5.0 don't send the field.
@@ -260,8 +364,25 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float,
more = f", +{n - 5} more" if n > 5 else ""
status.raise_to("update", f"{n} package{'s' if n != 1 else ''} not fully installed: "
f"{', '.join(unfinished[:5])}{more}; run dpkg --configure -a")
# Held packages never upgrade, and the simulation doesn't list them, so a held
# kernel package would make a host look current forever. Other holds are
# usually deliberate, but their updates (security ones too) are invisible.
if held := report.get("held_packages"):
kernel = [p for p in held if p.startswith("linux-")]
other = [p for p in held if not p.startswith("linux-")]
if kernel:
status.raise_to("update", f"kernel package{'s' if len(kernel) != 1 else ''} on hold, so "
f"kernel updates won't install: {', '.join(kernel[:5])}"
f"{', …' if len(kernel) > 5 else ''}; apt-mark unhold to release")
if other:
more = f", +{len(other) - 5} more" if len(other) > 5 else ""
status.note(f"{len(other)} package{'s' if len(other) != 1 else ''} on hold, "
f"updates to {'them' if len(other) != 1 else 'it'} won't show: "
f"{', '.join(other[:5])}{more}")
if low := boot_space_low(report, cfg):
status.raise_to("update", low)
for low in upgrade_space_low(report, cfg):
status.raise_to("update", low)
if found := unattended_upgrades_problem(report, cfg):
problem, why = found
@@ -295,6 +416,15 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float,
status.raise_to("update", "package list age unknown")
elif apt_age / 3600 > cfg.apt_stale_after_hours:
status.raise_to("update", f"package lists {apt_age / 86400:.0f}d old; apt update not running?")
if why := security_repo_problem(report, cfg, datetime.fromtimestamp(now, timezone.utc).date()):
status.raise_to("update", why)
# A failing helper leaves its data stale or missing, which the checks above may
# read as fine (needrestart's results just go "unknown").
for problem, why in helper_unit_problems(report):
if problem:
status.raise_to("update", why)
else:
status.note(why)
if host and (reported := hostname_mismatch(host, report)):
status.note(f"registered as {host} but reports itself as {reported}; "
+56 -1
View File
@@ -22,7 +22,7 @@ from urllib.parse import parse_qs, quote, unquote, urlsplit
from . import __version__, auth, db, support
from .config import Config
from .report import MAX_BODY_BYTES, ReportError, sanitize
from .status import LEVELS, Status, evaluate
from .status import LEVELS, Status, evaluate, helper_failure, helper_units
SESSION_COOKIE = "kw_session"
HOST_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$")
@@ -95,6 +95,56 @@ def unattended_upgrades_summary(report: dict[str, Any]) -> str | None:
for what, age in last.items())
def security_repo_summary(report: dict[str, Any]) -> str | None:
suite = report.get("security_repo_suite")
if not suite:
return None # agents before 0.9.0, or no release codename
age = report.get("security_repo_age_seconds")
if age is None:
return f"{suite}: not in apt's sources"
return f"{suite}, published {duration(age)} before the report"
def upgrade_space_summary(r: dict[str, Any]) -> str | None:
"""Download and install size of the pending upgrades, and free space where they go."""
download, install = r.get("upgrade_download_kb"), r.get("upgrade_install_kb")
if download is None or install is None:
return None # agents before 0.11.0, or apt couldn't say
sign = "+" if install >= 0 else "-"
text = f"{-(-download // 1024)} MB to download, {sign}{-(-abs(install) // 1024)} MB installed"
free: dict[str, int] = {}
for prefix in ("apt_archives", "usr"):
mount, kb = r.get(f"{prefix}_mount"), r.get(f"{prefix}_free_kb")
if mount and kb is not None:
free.setdefault(mount, kb)
shown = ", ".join(f"{mount} has {kb // 1024} MB free" for mount, kb in free.items())
return f"{text}; {shown}" if shown else text
def microcode_summary(report: dict[str, Any]) -> str | None:
state = {1: "current", 2: "update needs a reboot"}.get(report.get("needrestart_ucsta"))
if state is None:
return None # unknown, a VM, or no needrestart
cur, exp = report.get("needrestart_uccur"), report.get("needrestart_ucexp")
revs = f" (loaded {cur}, installed {exp})" if state != "current" and cur and exp else \
f" ({cur})" if cur else ""
return state + revs
def helper_units_summary(report: dict[str, Any]) -> str | None:
units = helper_units(report)
if not units:
return None # agents before 0.10.0, or nothing ran in the last two hours
parts = []
for name, result, code, st, failures in units:
if result == "success" or not failures:
parts.append(f"{name}: ok")
else:
row = "" if failures == 1 else f", {failures} runs in a row"
parts.append(f"{name}: failed ({helper_failure(result, code, st)}{row})")
return ", ".join(parts)
def phased_summary(report: dict[str, Any]) -> tuple[str, str]:
"""(short cell text, full description) for updates deferred by Ubuntu's phasing."""
if report.get("os_id") not in (None, "ubuntu"):
@@ -508,6 +558,7 @@ class Handler(BaseHTTPRequestHandler):
field("Installed kernels", r.get("kernels_installed"), code=True),
field("needrestart", None if r.get("needrestart_ksta") is None else
f"KSTA={r['needrestart_ksta']} expected={r.get('needrestart_kexp') or '?'}"),
field("CPU microcode", microcode_summary(r)),
field("Livepatch", None if r.get("livepatch_state") is None else
f"{r['livepatch_state']}, {r.get('livepatch_fix_count') or 0} fixes applied, "
f"{r.get('livepatch_supported') or '?'} until {r.get('livepatch_upgrade_required') or '?'}"),
@@ -522,11 +573,15 @@ class Handler(BaseHTTPRequestHandler):
field("Sessions needing restart", r.get("sessions_need_restart")),
field("/boot free", None if r.get("boot_free_kb") is None else
f"{r['boot_free_kb'] // 1024} MB of {(r.get('boot_size_kb') or 0) // 1024} MB"),
field("Pending upgrades size", upgrade_space_summary(r)),
field("Unfinished dpkg packages", r.get("dpkg_unfinished_packages"), code=True),
field("Packages on hold", r.get("held_packages"), code=True),
field("unattended-upgrades", unattended_upgrades_summary(r)),
field("Kept back by unattended-upgrades", r.get("unattended_upgrades_kept_back"), code=True),
field("Package lists age", duration(r.get("apt_lists_age_seconds"))
if r.get("apt_lists_age_seconds") is not None else None),
field("Security repository", security_repo_summary(r)),
field("kernelwatch helpers", helper_units_summary(r)),
field("Uptime", duration(r.get("uptime_seconds")) if r.get("uptime_seconds") is not None else None),
field("Agent version", r.get("agent_version")),
])
+11
View File
@@ -19,6 +19,11 @@ report_retention_days = 30
# fails half-way. 0 disables.
boot_min_free_mb = 200
# Pending upgrades that would leave less free space than this (MB) where apt
# downloads them (/var/cache/apt/archives) or installs them (/usr) put a host in
# "update": dpkg could run out of room half-way. 0 disables.
upgrade_min_free_mb = 100
# A host whose OS release no longer gets security updates (Debian past LTS, Ubuntu
# past standard support without ESM) is in "update". This many days before that,
# its row gets a note. 0 disables the note.
@@ -29,6 +34,12 @@ os_eol_warn_days = 90
# 0 disables the check.
unattended_upgrades_stale_after_days = 3.0
# A host with no repository for its release's security suite (trixie-security,
# noble-security) in apt's lists is in "update", and so is one whose copy is older
# than this many days while its other lists refresh (fetching it is failing).
# Both suites publish at least daily. 0 disables the check.
security_repo_stale_after_days = 7.0
# kernelwatch-backup.timer writes a dated copy of the database here every night
# and deletes copies this many days old or older (0 keeps them all). Keep the
# directory under /var/lib/kernelwatch; the unit can't write elsewhere. Copy the
+236 -2
View File
@@ -31,6 +31,37 @@ 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)
@@ -61,11 +92,21 @@ class AgentCase(unittest.TestCase):
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 ").
stub(self.bin, "dpkg-query", 'case "$*" in *" unattended-upgrades") cat "$KERNELWATCH_ROOT/dpkg-uu" 2>/dev/null;; '
# 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")
self.stub_df("/dev/sda1 999320 187364 743144 21% /boot\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")
@@ -77,6 +118,10 @@ class AgentCase(unittest.TestCase):
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']}",
@@ -136,6 +181,20 @@ class AgentReportTest(AgentCase):
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)
@@ -159,6 +218,73 @@ class AgentReportTest(AgentCase):
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"
@@ -172,6 +298,18 @@ class AgentReportTest(AgentCase):
"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")
@@ -446,6 +584,102 @@ X
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)
+125 -2
View File
@@ -60,7 +60,7 @@ class DeployTest(unittest.TestCase):
for name in ("deploy.sh", "kernelwatch-agent", "kernelwatch-agent.service",
"kernelwatch-agent.timer", "kernelwatch-needrestart.service",
"kernelwatch-livepatch", "kernelwatch-livepatch.service",
"kernelwatch-apt-update.service"):
"kernelwatch-apt-update.service", "kernelwatch-unit-result"):
shutil.copy2(os.path.join(AGENT_DIR, name), self.agent)
write_exec(os.path.join(self.agent, "install.sh"), FAKE_INSTALL)
@@ -189,6 +189,111 @@ class DeployTest(unittest.TestCase):
self.assertNotEqual(proc.returncode, 0)
self.assertIn("deploy.conf.example", proc.stderr)
def fake_uid(self, uid):
write_exec(os.path.join(self.tmp, "bin", "id"),
f'#!/bin/sh\n[ "$1" = -u ] && {{ echo {uid}; exit 0; }}\nexec /usr/bin/id "$@"\n')
def test_refuses_to_run_under_sudo(self):
self.fake_uid(0)
self.env["SUDO_USER"] = "patrick"
proc = self.deploy("web01.example.test")
self.assertNotEqual(proc.returncode, 0)
self.assertIn("don't run this with sudo", proc.stderr)
self.assertIn("Run it as patrick", proc.stderr)
self.assertFalse(os.path.exists(os.path.join(self.log, "ssh.log")), "nothing was contacted")
def test_root_login_without_sudo_is_allowed(self):
# Root's own SSH config is the one it means to use.
self.fake_uid(0)
self.env.pop("SUDO_USER", None)
self.assertEqual(self.deploy("web01.example.test").returncode, 0)
def test_sudo_user_set_but_not_root_is_allowed(self):
# e.g. a shell started from `sudo -u patrick -s`: not root, so ssh reads the right config.
self.fake_uid(1000)
self.env["SUDO_USER"] = "someone"
self.assertEqual(self.deploy("web01.example.test").returncode, 0)
@unittest.skipUnless(shutil.which("bash") and shutil.which("tar") and shutil.which("git"),
"needs bash, tar and git")
class DeployCheckoutTest(DeployTest):
"""deploy.sh compares its checkout with the upstream branch before deploying."""
def git(self, *args, cwd=None):
env = {**os.environ, "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1",
"GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@example.test",
"GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@example.test"}
subprocess.run(["git", *args], cwd=cwd or self.tmp, env=env, check=True,
capture_output=True, timeout=30)
def setUp(self):
super().setUp()
# self.tmp becomes a checkout of a local "origin" with agent/ committed.
self.origin = os.path.join(self.tmp, "origin.git")
self.git("init", "-q", "--bare", "-b", "main", self.origin)
with open(os.path.join(self.tmp, ".gitignore"), "w") as f:
f.write("/log/\n/homes/\n/remote-tmp/\n/bin/\n/origin.git/\n/other/\n*.db\n*.toml\n")
self.git("init", "-q", "-b", "main")
self.git("add", "-A")
self.git("commit", "-q", "-m", "agent")
self.git("remote", "add", "origin", self.origin)
self.git("push", "-q", "-u", "origin", "main")
for key in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"):
self.env.pop(key, None)
self.env.update(GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM="1")
def push_newer_commit(self):
other = os.path.join(self.tmp, "other")
self.git("clone", "-q", self.origin, other)
self.git("commit", "-q", "--allow-empty", "-m", "newer agent", cwd=other)
self.git("push", "-q", "origin", "main", cwd=other)
def test_up_to_date_checkout_deploys_quietly(self):
proc = self.deploy("web01.example.test")
self.assertEqual(proc.returncode, 0, proc.stderr)
self.assertNotIn("behind", proc.stderr)
def test_outdated_checkout_is_refused_without_a_terminal(self):
self.push_newer_commit()
proc = self.deploy("web01.example.test")
self.assertNotEqual(proc.returncode, 0)
self.assertIn("this checkout is 1 commit(s) behind origin/main", proc.stderr)
self.assertIn("--allow-outdated", proc.stderr)
self.assertFalse(os.path.exists(os.path.join(self.log, "ssh.log")), "nothing was deployed")
def test_allow_outdated_deploys_with_a_warning(self):
self.push_newer_commit()
proc = self.deploy("--allow-outdated", "web01.example.test")
self.assertEqual(proc.returncode, 0, proc.stderr)
self.assertIn("warning: this checkout is 1 commit(s) behind", proc.stderr)
self.installed("web01.example.test")
def test_dry_run_only_warns(self):
self.push_newer_commit()
proc = self.deploy("--dry-run", "web01.example.test")
self.assertEqual(proc.returncode, 0, proc.stderr)
self.assertIn("warning: this checkout is 1 commit(s) behind", proc.stderr)
def test_unreachable_upstream_only_warns(self):
shutil.rmtree(self.origin)
proc = self.deploy("web01.example.test")
self.assertEqual(proc.returncode, 0, proc.stderr)
self.assertIn("couldn't fetch origin/main", proc.stderr)
def test_ahead_of_upstream_is_fine(self):
self.git("commit", "-q", "--allow-empty", "-m", "local work")
proc = self.deploy("web01.example.test")
self.assertEqual(proc.returncode, 0, proc.stderr)
self.assertNotIn("behind", proc.stderr)
def test_no_upstream_skips_the_check(self):
self.git("branch", "-q", "--unset-upstream")
self.push_newer_commit()
proc = self.deploy("web01.example.test")
self.assertEqual(proc.returncode, 0, proc.stderr)
self.assertNotIn("behind", proc.stderr)
class PackagingTest(unittest.TestCase):
@@ -205,11 +310,29 @@ class PackagingTest(unittest.TestCase):
def test_apt_update_is_opt_in_and_runs_before_reports(self):
unit = self.read("kernelwatch-apt-update.service")
self.assertIn("ConditionPathExists=/etc/kernelwatch/apt-update", unit)
self.assertIn("ExecStart=-/usr/bin/apt-get -q update", unit, "failure mustn't block the report")
self.assertIn("\nExecStart=/usr/bin/apt-get -q update\n", unit,
"a failed update must fail the unit, so ExecStartPost doesn't mark it fresh")
post = next(l for l in unit.splitlines() if l.startswith("ExecStartPost="))
self.assertIn("touch /var/lib/apt/periodic/update-success-stamp", post)
agent = self.read("kernelwatch-agent.service")
for key in ("Wants=", "After="):
line = next(l for l in agent.splitlines() if l.startswith(key))
self.assertIn("kernelwatch-apt-update.service", line)
self.assertNotRegex(agent, r"(?m)^(Requires|Requisite|BindsTo)=.*kernelwatch-apt-update",
"a failed apt update mustn't stop the report")
def test_apt_update_runs_as_root_without_user_root(self):
# User=root plus NoNewPrivileges plus any seccomp-based option stops apt 2.7+
# dropping to _apt, so every update fails. Root is the default anyway.
unit = self.read("kernelwatch-apt-update.service")
self.assertNotRegex(unit, r"(?m)^(User|DynamicUser)=")
def test_apt_update_disk_priority_cant_be_starved(self):
# The idle class gets no disk time while anything else does I/O, so on a busy
# host apt never finished inside TimeoutStartSec.
unit = self.read("kernelwatch-apt-update.service")
self.assertNotRegex(unit, r"(?m)^IOSchedulingClass=(idle|3)\s*$")
self.assertIn("\nIOSchedulingClass=best-effort\n", unit)
if __name__ == "__main__":
+1 -1
View File
@@ -122,7 +122,7 @@ class AgentInstallTest(InstallCase):
def test_installs_every_agent_script_and_unit(self):
self.fresh()
for script in ("kernelwatch-agent", "kernelwatch-livepatch"):
for script in ("kernelwatch-agent", "kernelwatch-livepatch", "kernelwatch-unit-result"):
installed = self.path("usr/local/sbin", script)
self.assertEqual(read(installed), read(os.path.join(AGENT_DIR, script)))
self.assertEqual(mode(installed), 0o755)
+17
View File
@@ -100,6 +100,14 @@ class ConfigTest(unittest.TestCase):
with self.subTest(bad=bad), self.assertRaises(SystemExit):
config.load(self.write(tmp, f"boot_min_free_mb = {bad}\n"))
def test_upgrade_min_free_validated(self):
with tempdir() as tmp:
self.assertEqual(config.Config().upgrade_min_free_mb, 100)
self.assertEqual(config.load(self.write(tmp, "upgrade_min_free_mb = 0\n")).upgrade_min_free_mb, 0)
for bad in ("-1", "1.5", '"100"'):
with self.subTest(bad=bad), self.assertRaises(SystemExit):
config.load(self.write(tmp, f"upgrade_min_free_mb = {bad}\n"))
def test_os_eol_warn_days_validated(self):
with tempdir() as tmp:
self.assertEqual(config.Config().os_eol_warn_days, 90)
@@ -117,6 +125,15 @@ class ConfigTest(unittest.TestCase):
with self.subTest(bad=bad), self.assertRaises(SystemExit):
config.load(self.write(tmp, f"unattended_upgrades_stale_after_days = {bad}\n"))
def test_security_repo_stale_days_validated(self):
with tempdir() as tmp:
self.assertEqual(config.Config().security_repo_stale_after_days, 7.0)
self.assertEqual(config.load(self.write(tmp, "security_repo_stale_after_days = 0\n"))
.security_repo_stale_after_days, 0)
for bad in ("-1", "inf", "nan", '"7"'):
with self.subTest(bad=bad), self.assertRaises(SystemExit):
config.load(self.write(tmp, f"security_repo_stale_after_days = {bad}\n"))
def test_fallback_parser_matches_tomllib(self):
"""Python 3.10 has no tomllib; the fallback must read the same configs."""
if config.tomllib is None:
+156 -1
View File
@@ -264,7 +264,8 @@ class EvaluateTest(unittest.TestCase):
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")
self.assertEqual(self.level(report(agent_version="0.100.0")).reasons, [],
"numeric compare: lexically older than 0.11.0")
def test_server_knows_shipped_agent_version(self):
with open(os.path.join(REPO, "agent", "kernelwatch-agent")) as f:
@@ -326,6 +327,56 @@ class EvaluateTest(unittest.TestCase):
self.assertEqual(evaluate(NOW, report(boot_free_kb=0), NOW, Config(boot_min_free_mb=0)).level,
"ok", "0 disables")
@staticmethod
def upgrade(download_mb, install_mb, archives=("/", 1000), usr=("/", 1000), **kw):
fields = dict(upgrade_download_kb=download_mb * 1024, upgrade_install_kb=install_mb * 1024,
apt_archives_mount=archives[0], apt_archives_free_kb=archives[1] * 1024,
usr_mount=usr[0], usr_free_kb=usr[1] * 1024)
return report(**{**fields, **kw})
def test_upgrade_space_shared_filesystem(self):
# 300 + 650 needed on /, 1000 free: 50 MB left, under the 100 MB default.
s = self.level(self.upgrade(300, 650))
self.assertEqual(s.level, "update")
self.assertEqual(s.reasons, ["pending upgrades need 950 MB on / (300 MB download + 650 MB installed), "
"1000 MB free; they may fail part-way"])
self.assertEqual(self.level(self.upgrade(300, 600)).level, "ok", "exactly 100 MB left")
def test_upgrade_space_separate_filesystems(self):
s = self.level(self.upgrade(300, 650, archives=("/var", 350), usr=("/", 2000)))
self.assertEqual(s.reasons, ["pending upgrades need 300 MB on /var (300 MB download), "
"350 MB free; they may fail part-way"])
s = self.level(self.upgrade(300, 1950, archives=("/var", 5000), usr=("/", 2000)))
self.assertEqual(s.reasons, ["pending upgrades need 1950 MB on / (1950 MB installed), "
"2000 MB free; they may fail part-way"])
self.assertEqual(len(self.level(self.upgrade(300, 1950, archives=("/var", 350))).reasons), 2)
def test_upgrade_space_shrinking_install_counts_as_zero(self):
self.assertEqual(self.level(self.upgrade(850, -500)).level, "ok")
self.assertEqual(self.level(self.upgrade(950, -500)).level, "update",
"the download still has to fit before the old files go")
def test_upgrade_space_ignores_full_disk_with_nothing_pending(self):
self.assertEqual(self.level(self.upgrade(0, 0, archives=("/", 5), usr=("/", 5))).level, "ok")
def test_upgrade_space_rounds_need_up(self):
rep = report(upgrade_download_kb=10, upgrade_install_kb=0, apt_archives_mount="/",
apt_archives_free_kb=50 * 1024, usr_mount="/", usr_free_kb=50 * 1024)
self.assertEqual(self.level(rep).reasons, ["pending upgrades need 1 MB on / (1 MB download), "
"50 MB free; they may fail part-way"])
def test_upgrade_space_unknown_or_unreported(self):
self.assertEqual(self.level(report()).level, "ok", "agents before 0.11.0 don't send it")
self.assertEqual(self.level(self.upgrade(300, 650, upgrade_download_kb=None)).level, "ok")
self.assertEqual(self.level(self.upgrade(300, 650, apt_archives_free_kb=None, usr_mount=None)).level,
"ok", "df failed")
def test_upgrade_space_threshold_is_configurable(self):
self.assertEqual(evaluate(NOW, self.upgrade(300, 650), NOW, Config(upgrade_min_free_mb=0)).level,
"ok", "0 disables")
self.assertEqual(evaluate(NOW, self.upgrade(300, 300), NOW, Config(upgrade_min_free_mb=500)).level,
"update")
def test_unfinished_dpkg_packages(self):
s = self.level(report(dpkg_unfinished_packages=["linux-image-6.12.60+deb13-amd64"]))
self.assertEqual(s.level, "update")
@@ -339,6 +390,31 @@ class EvaluateTest(unittest.TestCase):
self.assertEqual(self.level(report(dpkg_unfinished_packages=[])).level, "ok")
self.assertEqual(self.level(report(dpkg_unfinished_packages=None)).level, "ok")
def test_microcode_update_needs_a_reboot(self):
s = self.level(report(needrestart_ucsta=2, needrestart_uccur="0x001e", needrestart_ucexp="0x0020"))
self.assertEqual(s.level, "reboot")
self.assertEqual(s.reasons, ["CPU microcode update installed but not loaded (0x001e → 0x0020)"])
for ucsta in (0, 1, None):
with self.subTest(ucsta=ucsta):
self.assertEqual(self.level(report(needrestart_ucsta=ucsta)).level, "ok")
def test_livepatch_doesnt_cover_microcode(self):
s = evaluate(NOW - 60, livepatched(needrestart_ucsta=2), NOW, CFG)
self.assertEqual(s.level, "reboot")
self.assertIn("CPU microcode update installed but not loaded", s.reasons)
def test_held_kernel_package_is_a_problem(self):
s = self.level(report(held_packages=["linux-image-amd64"]))
self.assertEqual(s.level, "update")
self.assertEqual(s.reasons, ["kernel package on hold, so kernel updates won't install: "
"linux-image-amd64; apt-mark unhold to release"])
def test_other_held_packages_are_a_note(self):
s = self.level(report(held_packages=["postgresql-16", "docker-ce"]))
self.assertEqual(s.level, "ok")
self.assertEqual(s.reasons, ["2 packages on hold, updates to them won't show: postgresql-16, docker-ce"])
self.assertEqual(self.level(report(held_packages=[])).reasons, [])
def test_os_past_end_of_support(self):
s = self.level(report(os_id="debian", os_version_id="11"))
self.assertEqual(s.level, "update")
@@ -352,6 +428,85 @@ class EvaluateTest(unittest.TestCase):
evaluate(NOW, rep, NOW, Config(os_eol_warn_days=200)).reasons[0])
self.assertEqual(self.level(rep).reasons, [], "outside the default 90 days")
def sec(self, age=3 * 3600, suite="trixie-security", cfg=CFG, **kw):
fields = dict(os_id="debian", os_version_id="13", security_repo_suite=suite,
security_repo_age_seconds=age)
fields.update(kw)
return evaluate(NOW - 60, report(**fields), NOW, cfg)
def test_security_repo_fresh(self):
s = self.sec()
self.assertEqual((s.level, s.reasons), ("ok", []))
def test_security_repo_missing(self):
s = self.sec(age=None)
self.assertEqual(s.level, "update")
self.assertEqual(s.reasons, ["apt has no trixie-security repository, so security updates "
"can't arrive; add it to the apt sources and run apt update"])
def test_security_repo_stale_while_apt_update_succeeds(self):
s = self.sec(age=10 * 86400)
self.assertEqual(s.level, "update")
self.assertEqual(s.reasons, ["apt's trixie-security list is 10d old while apt update otherwise "
"succeeds; run apt update and look for errors about trixie-security"])
self.assertEqual(self.sec(age=6 * 86400).level, "ok", "within the default 7 days")
def test_security_repo_stale_with_all_lists_stale_reports_once(self):
s = self.sec(age=10 * 86400, apt_lists_age_seconds=10 * 86400)
self.assertEqual(s.reasons, ["package lists 10d old; apt update not running?"])
def test_security_repo_check_can_be_disabled(self):
cfg = Config(security_repo_stale_after_days=0)
self.assertEqual(self.sec(age=None, cfg=cfg).level, "ok")
self.assertEqual(self.sec(age=30 * 86400, cfg=cfg).level, "ok")
def test_security_repo_not_reported(self):
# Agents before 0.9.0, and releases without a codename.
self.assertEqual(self.sec(suite=None, age=None).level, "ok")
rep = report(os_id="debian", os_version_id="13")
self.assertEqual(self.level(rep).level, "ok")
def test_security_repo_ignored_past_end_of_support(self):
# NOW is 2027-01-15. Debian 11's LTS ended 2026-08-31, so bullseye-security no
# longer publishes; the end-of-support reason is the one that matters.
s = self.sec(age=60 * 86400, suite="bullseye-security", os_version_id="11")
self.assertEqual(len(s.reasons), 1, s.reasons)
self.assertIn("Debian 11 security support ended", s.reasons[0])
# Ubuntu 20.04 past standard support with ESM: focal-security is frozen, but fine.
s = self.sec(age=400 * 86400, suite="focal-security", os_id="ubuntu", os_version_id="20.04",
ubuntu_esm_infra="enabled")
self.assertEqual((s.level, s.reasons), ("ok", []))
def test_security_repo_checked_within_standard_support(self):
s = self.sec(age=10 * 86400, suite="jammy-security", os_id="ubuntu", os_version_id="22.04")
self.assertEqual(s.level, "update")
def test_helper_units_healthy(self):
s = self.level(report(helper_units=["apt-update success exited 0 0", "needrestart success exited 0 0"]))
self.assertEqual((s.level, s.reasons), ("ok", []))
def test_helper_unit_failing_once_is_a_note(self):
s = self.level(report(helper_units=["apt-update exit-code exited 100 1"]))
self.assertEqual(s.level, "ok")
self.assertEqual(s.reasons, ["kernelwatch-apt-update.service failed its last run (exit status 100); "
"see journalctl -u kernelwatch-apt-update.service"])
def test_helper_unit_failing_repeatedly_is_a_problem(self):
s = self.level(report(helper_units=["apt-update exit-code exited 100 3",
"needrestart timeout killed TERM 5"]))
self.assertEqual(s.level, "update")
self.assertEqual(s.reasons, [
"kernelwatch-apt-update.service failed its last 3 runs (exit status 100); "
"see journalctl -u kernelwatch-apt-update.service",
"kernelwatch-needrestart.service failed its last 5 runs (timeout, signal TERM); "
"see journalctl -u kernelwatch-needrestart.service"])
def test_helper_units_odd_entries_ignored(self):
s = self.level(report(helper_units=["apt-update exit-code", "x y z w many"]))
self.assertEqual((s.level, s.reasons), ("ok", []))
s = self.level(report(helper_units=["needrestart resources - - 4"]))
self.assertIn("kernelwatch-needrestart.service failed its last 4 runs (resources)", s.reasons[0])
def uu(self, success=6 * 3600, run=6 * 3600, state="enabled", **kw):
return self.level(report(unattended_upgrades=state, unattended_upgrades_success_age_seconds=success,
unattended_upgrades_run_age_seconds=run, **kw))
+102
View File
@@ -0,0 +1,102 @@
"""kernelwatch-unit-result, the helper units' ExecStopPost=, and how they use it."""
import os
import re
import subprocess
import unittest
from helpers import REPO, tempdir
AGENT_DIR = os.path.join(REPO, "agent")
SCRIPT = os.path.join(AGENT_DIR, "kernelwatch-unit-result")
def read(name):
with open(os.path.join(AGENT_DIR, name)) as f:
return f.read()
class UnitResultTest(unittest.TestCase):
def setUp(self):
self._tmp = tempdir()
self.dir = self._tmp.name
def tearDown(self):
self._tmp.cleanup()
def run_script(self, *args, **env):
return subprocess.run(["sh", SCRIPT, *args], capture_output=True, text=True, timeout=10,
env={"PATH": os.environ["PATH"], "KERNELWATCH_RUN_DIR": self.dir, **env})
def ended(self, result, code="exited", status="0"):
proc = self.run_script("apt-update", SERVICE_RESULT=result, EXIT_CODE=code, EXIT_STATUS=status)
self.assertEqual(proc.returncode, 0, proc.stderr)
with open(os.path.join(self.dir, "apt-update.result")) as f:
return f.read()
def test_success(self):
self.assertEqual(self.ended("success"), "success exited 0 0\n")
def test_failures_in_a_row_are_counted_and_reset_by_a_success(self):
self.assertEqual(self.ended("exit-code", status="100"), "exit-code exited 100 1\n")
self.assertEqual(self.ended("exit-code", status="100"), "exit-code exited 100 2\n")
self.assertEqual(self.ended("timeout", "killed", "TERM"), "timeout killed TERM 3\n")
self.assertEqual(self.ended("success"), "success exited 0 0\n")
self.assertEqual(self.ended("exit-code", status="1"), "exit-code exited 1 1\n")
self.assertFalse(os.path.exists(os.path.join(self.dir, "apt-update.result.new")))
def test_garbage_in_the_old_file_restarts_the_count(self):
with open(os.path.join(self.dir, "apt-update.result"), "w") as f:
f.write("exit-code exited 100 lots\n")
self.assertEqual(self.ended("exit-code", status="100"), "exit-code exited 100 1\n")
def test_missing_variables(self):
proc = self.run_script("needrestart")
self.assertEqual(proc.returncode, 0, proc.stderr)
with open(os.path.join(self.dir, "needrestart.result")) as f:
self.assertEqual(f.read(), "- - - 1\n", "no SERVICE_RESULT isn't a success")
def test_bad_names_are_refused(self):
for name in ("", "../etc/passwd", "Apt", "a b"):
with self.subTest(name=name):
self.assertEqual(self.run_script(name).returncode, 2)
self.assertEqual(os.listdir(self.dir), [])
class HelperUnitsTest(unittest.TestCase):
def recorded_units(self):
"""Units that record their result, by the name they record it under."""
found = {}
for unit in os.listdir(AGENT_DIR):
if unit.endswith(".service"):
m = re.search(r"^ExecStopPost=/usr/local/sbin/kernelwatch-unit-result (\S+)$",
read(unit), re.M)
if m:
found[m.group(1)] = unit
return found
def test_agent_reads_every_recorded_unit(self):
names = re.search(r"^HELPER_UNITS=\(([^)]*)\)", read("kernelwatch-agent"), re.M).group(1).split()
self.assertEqual(sorted(self.recorded_units()), sorted(names))
self.assertEqual(self.recorded_units(), {"apt-update": "kernelwatch-apt-update.service",
"needrestart": "kernelwatch-needrestart.service"})
def test_units_sharing_the_runtime_directory_keep_it(self):
# Without RuntimeDirectoryPreserve, stopping one unit would delete the others'
# results (and its own .result, just after writing it).
for unit in os.listdir(AGENT_DIR):
if unit.endswith(".service") and "RuntimeDirectory=kernelwatch" in read(unit):
with self.subTest(unit=unit):
self.assertIn("\nRuntimeDirectoryPreserve=yes\n", read(unit))
for unit in self.recorded_units().values():
self.assertIn("\nRuntimeDirectory=kernelwatch\n", read(unit))
def test_the_agent_unit_pulls_the_helpers_in_without_depending_on_them(self):
agent = read("kernelwatch-agent.service")
for unit in self.recorded_units().values():
self.assertRegex(agent, rf"(?m)^Wants=.*\b{re.escape(unit)}\b")
self.assertNotRegex(agent, rf"(?m)^(Requires|Requisite|BindsTo)=.*\b{re.escape(unit)}\b")
if __name__ == "__main__":
unittest.main()
+51
View File
@@ -197,6 +197,18 @@ class DashboardTest(ServerCase):
self.assertIn("<code>linux-image-6.8.0-138-generic</code>", body)
self.assertIn("/boot has 95 MB free, 81% used; the next kernel may not fit", body)
def test_host_page_shows_upgrade_space(self):
self.add_user("admin", "a-long-password")
token = self.add_host("web01")
self.post_report(token, {"kernel_running": "6.8.0-136-generic", "apt_lists_age_seconds": 60,
"upgrade_download_kb": 300 * 1024, "upgrade_install_kb": 650 * 1024,
"apt_archives_mount": "/var", "apt_archives_free_kb": 350 * 1024,
"usr_mount": "/", "usr_free_kb": 2000 * 1024})
_, headers, _ = self.login("admin", "a-long-password")
body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2]
self.assertIn("300 MB to download, +650 MB installed; /var has 350 MB free, / has 2000 MB free", body)
self.assertIn("pending upgrades need 300 MB on /var (300 MB download), 350 MB free", body)
def test_host_page_shows_unattended_upgrades(self):
self.add_user("admin", "a-long-password")
token = self.add_host("web01")
@@ -221,6 +233,45 @@ class DashboardTest(ServerCase):
body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2]
self.assertIn("standard until 2029-05-31, ESM until 2034-04-25 (esm-infra: enabled)", body)
def test_host_page_shows_security_repo(self):
self.add_user("admin", "a-long-password")
token = self.add_host("web01")
self.post_report(token, {"kernel_running": "6.8.0-136-generic", "apt_lists_age_seconds": 60,
"security_repo_suite": "noble-security",
"security_repo_age_seconds": 14 * 3600 + 120})
_, headers, _ = self.login("admin", "a-long-password")
cookie = {"Cookie": headers["Set-Cookie"].split(";")[0]}
body = self.request("GET", "/host/web01", headers=cookie)[2]
self.assertIn("noble-security, published 14h 2m before the report", body)
self.post_report(self.add_host("web02"), {"kernel_running": "6.8.0-136-generic",
"apt_lists_age_seconds": 60,
"security_repo_suite": "noble-security"})
body = self.request("GET", "/host/web02", headers=cookie)[2]
self.assertIn("noble-security: not in apt&#x27;s sources", body)
self.assertIn("apt has no noble-security repository", body)
def test_host_page_shows_microcode(self):
self.add_user("admin", "a-long-password")
token = self.add_host("web01")
self.post_report(token, {"kernel_running": "6.12.57+deb13-amd64", "apt_lists_age_seconds": 60,
"needrestart_ucsta": 2, "needrestart_uccur": "0x001e",
"needrestart_ucexp": "0x0020"})
_, headers, _ = self.login("admin", "a-long-password")
body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2]
self.assertIn("update needs a reboot (loaded 0x001e, installed 0x0020)", body)
def test_host_page_shows_helper_units(self):
self.add_user("admin", "a-long-password")
token = self.add_host("web01")
self.post_report(token, {"kernel_running": "6.8.0-136-generic", "apt_lists_age_seconds": 60,
"helper_units": ["apt-update exit-code exited 100 4",
"needrestart success exited 0 0"]})
_, headers, _ = self.login("admin", "a-long-password")
body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2]
self.assertIn("apt-update: failed (exit status 100, 4 runs in a row), needrestart: ok", body)
self.assertIn("kernelwatch-apt-update.service failed its last 4 runs", body)
def test_login_dashboard_logout(self):
self.add_user("admin", "a-long-password")
token = self.add_host("web01")