Compare commits

...
10 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
18 changed files with 467 additions and 11 deletions

No files matched your search

+1 -1
View File
@@ -29,7 +29,7 @@ Each host gets one status. When several apply, the worst one wins:
|----------|---------| |----------|---------|
| `stale` | No report in `stale_after_hours` (default 3h), or never. Other data can't be trusted. | | `stale` | No report in `stale_after_hours` (default 3h), or never. Other data can't be trusted. |
| `reboot` | A newer kernel is installed but not running, or `/run/reboot-required` exists. | | `reboot` | A newer kernel is installed but not running, or `/run/reboot-required` exists. |
| `update` | A kernel or security update is available but not installed, services are running outdated libraries and need a restart, or apt's package lists are too old, or apt itself fails, so "no updates" can't be trusted. Also when `/boot` is too full for the next kernel, dpkg left packages half-installed, 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. | | `ok` | Running the newest installed kernel, with no security or kernel updates pending. |
Each row lists the reasons behind its status, and clicking a host shows its full Each row lists the reasons behind its status, and clicking a host shows its full
+1 -1
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bash #!/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] # sudo ./install.sh --server https://kernelwatch.example.internal [--ca ca.pem]
# [--with-needrestart] [--with-apt-update | --without-apt-update] # [--with-needrestart] [--with-apt-update | --without-apt-update]
+87 -2
View File
@@ -6,7 +6,7 @@
# rules can change without redeploying agents. # rules can change without redeploying agents.
set -euo pipefail set -euo pipefail
AGENT_VERSION=0.10.0 AGENT_VERSION=0.11.0
# Prefix for every file the agent reads. Only the test suite sets this. # Prefix for every file the agent reads. Only the test suite sets this.
ROOT=${KERNELWATCH_ROOT:-} ROOT=${KERNELWATCH_ROOT:-}
@@ -199,7 +199,7 @@ read_livepatch() {
HELPER_UNITS=(apt-update needrestart) HELPER_UNITS=(apt-update needrestart)
HELPER_MAX_AGE=7200 HELPER_MAX_AGE=7200
helper_units() { helper_units() {
local name file mtime now result= code= status= failures= local name file mtime now result='' code='' status='' failures=''
now=$(date +%s) now=$(date +%s)
for name in "${HELPER_UNITS[@]}"; do for name in "${HELPER_UNITS[@]}"; do
file=$ROOT/run/kernelwatch/$name.result file=$ROOT/run/kernelwatch/$name.result
@@ -335,6 +335,81 @@ boot_space() {
awk 'NR == 2 && $2 ~ /^[0-9]+$/ && $4 ~ /^[0-9]+$/ { print $2, $4 }' || true 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, # Packages dpkg didn't finish installing or removing: half-installed, unpacked,
# half-configured, awaiting or pending triggers, or flagged reinst-required. # half-configured, awaiting or pending triggers, or flagged reinst-required.
# The same states `dpkg --audit` reports; usually a failed postinst, cleared by # The same states `dpkg --audit` reports; usually a failed postinst, cleared by
@@ -407,6 +482,7 @@ uptime_seconds() {
build_report() { build_report() {
local running newest kernels sim inst sim_err rc apt_ok=1 apt_err='' reboot_file=0 reboot_pkgs= 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='' sec_suite='' sec_age='' 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) running=$(uname -r)
kernels=$(installed_kernels) kernels=$(installed_kernels)
@@ -431,6 +507,9 @@ build_report() {
fi fi
read -r boot_size boot_free <<<"$(boot_space)" || true 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 pro_attached pro_esm <<<"$(ubuntu_pro)" || true
read -r sec_suite sec_age <<<"$(security_repo)" || true read -r sec_suite sec_age <<<"$(security_repo)" || true
[[ $pro_esm == - ]] && pro_esm= [[ $pro_esm == - ]] && pro_esm=
@@ -476,6 +555,12 @@ build_report() {
printf '"livepatch_fix_count":%s,' "$(json_int "$LP_FIXES")" printf '"livepatch_fix_count":%s,' "$(json_int "$LP_FIXES")"
printf '"boot_size_kb":%s,' "$(json_int "$boot_size")" printf '"boot_size_kb":%s,' "$(json_int "$boot_size")"
printf '"boot_free_kb":%s,' "$(json_int "$boot_free")" 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 '"dpkg_unfinished_packages":%s,' "$(unfinished_packages | json_str_array)"
printf '"held_packages":%s,' "$(held_packages | json_str_array)" printf '"held_packages":%s,' "$(held_packages | json_str_array)"
case $pro_attached in case $pro_attached in
+5 -1
View File
@@ -27,8 +27,12 @@ RuntimeDirectoryMode=0755
RuntimeDirectoryPreserve=yes RuntimeDirectoryPreserve=yes
UMask=0022 UMask=0022
TimeoutStartSec=5min 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 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 # apt needs root to write /var/lib/apt and drops to _apt for downloads, so this
# runs as root (the default) but loses everything apt update doesn't touch. # runs as root (the default) but loses everything apt update doesn't touch.
+89
View File
@@ -102,6 +102,95 @@ Things to know:
expected. expected.
- **Debian** has no Livepatch; nothing here applies, and nothing needs turning off. - **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 ## Deploying to many hosts
`agent/deploy.sh` does all of the above over SSH from your workstation's `agent/deploy.sh` does all of the above over SSH from your workstation's
+23 -1
View File
@@ -10,7 +10,7 @@ Each host gets one status. When several apply, the worst one wins:
|----------|---------| |----------|---------|
| `stale` | No report in `stale_after_hours` (default 3h), or never. Other data can't be trusted. | | `stale` | No report in `stale_after_hours` (default 3h), or never. Other data can't be trusted. |
| `reboot` | A newer kernel is installed but not running, `/run/reboot-required` exists, or newer CPU microcode is installed but not loaded. | | `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, 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. | | `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. | | `ok` | Running the newest installed kernel, with no security or kernel updates pending. |
Each row also lists the reasons behind its status, and clicking a host shows Each row also lists the reasons behind its status, and clicking a host shows
@@ -106,6 +106,28 @@ How the agent works it out:
`boot_min_free_mb` (default 200) free puts the host in `update` with "/boot has `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 N MB free". Fix it on the host: `sudo apt autoremove --purge` removes old
kernels. 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 - **Unfinished packages**: packages dpkg didn't finish installing, read from its
status database (the same states `dpkg --audit` reports: half-installed, status database (the same states `dpkg --audit` reports: half-installed,
unpacked, half-configured, waiting on triggers, or reinst-required). These are unpacked, half-configured, waiting on triggers, or reinst-required). These are
+1 -1
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bash #!/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 # 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 # Version of agent/kernelwatch-agent shipped alongside this server; older agents
# are noted on the dashboard. tests/test_status.py checks the two stay in sync. # are noted on the dashboard. tests/test_status.py checks the two stay in sync.
AGENT_VERSION = "0.10.0" AGENT_VERSION = "0.11.0"
+6
View File
@@ -33,6 +33,10 @@ class Config:
# Less free space than this on /boot's filesystem puts a host in update: the next # 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. # kernel (image plus initramfs, often over 100 MB) may not fit. 0 disables.
boot_min_free_mb: int = 200 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 # 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 # (or Ubuntu standard support ends without ESM). 0 disables the warning; a host
# past the date is in update either way. # past the date is in update either way.
@@ -116,6 +120,8 @@ def load(path: str | None = None) -> Config:
raise SystemExit(f"{path}: os_eol_warn_days must be zero or positive") raise SystemExit(f"{path}: os_eol_warn_days must be zero or positive")
if cfg.boot_min_free_mb < 0: if cfg.boot_min_free_mb < 0:
raise SystemExit(f"{path}: boot_min_free_mb must be zero or positive") 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: if cfg.backup_keep_days < 0:
raise SystemExit(f"{path}: backup_keep_days must be zero or positive") 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): if not cfg.backup_dir.startswith("/") or any(ord(c) < 32 or ord(c) == 127 for c in cfg.backup_dir):
+6
View File
@@ -47,6 +47,12 @@ FIELDS: dict[str, str] = {
"apt_simulation_error": "str", "apt_simulation_error": "str",
"boot_size_kb": "int", "boot_size_kb": "int",
"boot_free_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", "dpkg_unfinished_packages": "strlist",
"held_packages": "strlist", "held_packages": "strlist",
"ubuntu_pro_attached": "bool", "ubuntu_pro_attached": "bool",
+32
View File
@@ -159,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" 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/" UU_LOG = "/var/log/unattended-upgrades/"
@@ -351,6 +381,8 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float,
f"{', '.join(other[:5])}{more}") f"{', '.join(other[:5])}{more}")
if low := boot_space_low(report, cfg): if low := boot_space_low(report, cfg):
status.raise_to("update", low) 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): if found := unattended_upgrades_problem(report, cfg):
problem, why = found problem, why = found
+17
View File
@@ -105,6 +105,22 @@ def security_repo_summary(report: dict[str, Any]) -> str | None:
return f"{suite}, published {duration(age)} before the report" 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: def microcode_summary(report: dict[str, Any]) -> str | None:
state = {1: "current", 2: "update needs a reboot"}.get(report.get("needrestart_ucsta")) state = {1: "current", 2: "update needs a reboot"}.get(report.get("needrestart_ucsta"))
if state is None: if state is None:
@@ -557,6 +573,7 @@ class Handler(BaseHTTPRequestHandler):
field("Sessions needing restart", r.get("sessions_need_restart")), field("Sessions needing restart", r.get("sessions_need_restart")),
field("/boot free", None if r.get("boot_free_kb") is None else field("/boot free", None if r.get("boot_free_kb") is None else
f"{r['boot_free_kb'] // 1024} MB of {(r.get('boot_size_kb') or 0) // 1024} MB"), f"{r['boot_free_kb'] // 1024} MB of {(r.get('boot_size_kb') or 0) // 1024} MB"),
field("Pending upgrades size", upgrade_space_summary(r)),
field("Unfinished dpkg packages", r.get("dpkg_unfinished_packages"), code=True), field("Unfinished dpkg packages", r.get("dpkg_unfinished_packages"), code=True),
field("Packages on hold", r.get("held_packages"), code=True), field("Packages on hold", r.get("held_packages"), code=True),
field("unattended-upgrades", unattended_upgrades_summary(r)), field("unattended-upgrades", unattended_upgrades_summary(r)),
+5
View File
@@ -19,6 +19,11 @@ report_retention_days = 30
# fails half-way. 0 disables. # fails half-way. 0 disables.
boot_min_free_mb = 200 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 # 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, # past standard support without ESM) is in "update". This many days before that,
# its row gets a note. 0 disables the note. # its row gets a note. 0 disables the note.
+114 -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]) 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): def stub(bindir, name, script):
path = os.path.join(bindir, name) path = os.path.join(bindir, name)
@@ -61,11 +92,21 @@ class AgentCase(unittest.TestCase):
stub(self.bin, "hostname", "echo web01.example\n") stub(self.bin, "hostname", "echo web01.example\n")
# The full-database query (unfinished packages) prints $KERNELWATCH_ROOT/dpkg-all. # The full-database query (unfinished packages) prints $KERNELWATCH_ROOT/dpkg-all.
# The unattended-upgrades query prints $KERNELWATCH_ROOT/dpkg-uu (its status, e.g. "ii "). # 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;; ' '*binary:Package*) cat "$KERNELWATCH_ROOT/dpkg-all" 2>/dev/null;; '
'*Version*) echo "ii 6.12.48-2";; *) cat <<\'X\'\n' '*Version*) echo "ii 6.12.48-2";; *) cat <<\'X\'\n'
f"{DPKG_DEBIAN}X\n;; esac\n") f"{DPKG_DEBIAN}X\n;; esac\n")
self.stub_df("/dev/sda1 999320 187364 743144 21% /boot\n") # 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). # `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-config", 'cat "$KERNELWATCH_ROOT/apt-config" 2>/dev/null; exit 0\n')
stub(self.bin, "apt-get", f"cat <<'X'\n{APT_SIM_DEBIAN}X\n") stub(self.bin, "apt-get", f"cat <<'X'\n{APT_SIM_DEBIAN}X\n")
@@ -77,6 +118,10 @@ class AgentCase(unittest.TestCase):
stub(self.bin, "df", "echo 'Filesystem 1024-blocks Used Available Capacity Mounted on'\n" stub(self.bin, "df", "echo 'Filesystem 1024-blocks Used Available Capacity Mounted on'\n"
f"cat <<'X'\n{line}X\nexit {rc}\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): def run_agent(self, *args, env=None):
full_env = { full_env = {
"PATH": f"{self.bin}:{os.environ['PATH']}", "PATH": f"{self.bin}:{os.environ['PATH']}",
@@ -173,6 +218,73 @@ class AgentReportTest(AgentCase):
self.stub_df("/dev/sda1 - - - - /boot\n") self.stub_df("/dev/sda1 - - - - /boot\n")
self.assertIsNone(self.report()["boot_free_kb"]) 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): def test_unfinished_packages(self):
with open(os.path.join(self.root, "dpkg-all"), "w") as f: with open(os.path.join(self.root, "dpkg-all"), "w") as f:
f.write("ii \tcurl\n" f.write("ii \tcurl\n"
+7
View File
@@ -327,6 +327,13 @@ class PackagingTest(unittest.TestCase):
unit = self.read("kernelwatch-apt-update.service") unit = self.read("kernelwatch-apt-update.service")
self.assertNotRegex(unit, r"(?m)^(User|DynamicUser)=") 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__": if __name__ == "__main__":
unittest.main() unittest.main()
+8
View File
@@ -100,6 +100,14 @@ class ConfigTest(unittest.TestCase):
with self.subTest(bad=bad), self.assertRaises(SystemExit): with self.subTest(bad=bad), self.assertRaises(SystemExit):
config.load(self.write(tmp, f"boot_min_free_mb = {bad}\n")) 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): def test_os_eol_warn_days_validated(self):
with tempdir() as tmp: with tempdir() as tmp:
self.assertEqual(config.Config().os_eol_warn_days, 90) self.assertEqual(config.Config().os_eol_warn_days, 90)
+52 -1
View File
@@ -264,7 +264,8 @@ class EvaluateTest(unittest.TestCase):
self.assertEqual(s.level, "ok") self.assertEqual(s.level, "ok")
self.assertIn("agent 0.1.0 is older", s.reasons[0]) 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=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): def test_server_knows_shipped_agent_version(self):
with open(os.path.join(REPO, "agent", "kernelwatch-agent")) as f: 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, self.assertEqual(evaluate(NOW, report(boot_free_kb=0), NOW, Config(boot_min_free_mb=0)).level,
"ok", "0 disables") "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): def test_unfinished_dpkg_packages(self):
s = self.level(report(dpkg_unfinished_packages=["linux-image-6.12.60+deb13-amd64"])) s = self.level(report(dpkg_unfinished_packages=["linux-image-6.12.60+deb13-amd64"]))
self.assertEqual(s.level, "update") self.assertEqual(s.level, "update")
+12
View File
@@ -197,6 +197,18 @@ class DashboardTest(ServerCase):
self.assertIn("<code>linux-image-6.8.0-138-generic</code>", body) self.assertIn("<code>linux-image-6.8.0-138-generic</code>", body)
self.assertIn("/boot has 95 MB free, 81% used; the next kernel may not fit", body) self.assertIn("/boot has 95 MB free, 81% used; the next kernel may not fit", body)
def test_host_page_shows_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): def test_host_page_shows_unattended_upgrades(self):
self.add_user("admin", "a-long-password") self.add_user("admin", "a-long-password")
token = self.add_host("web01") token = self.add_host("web01")