Compare commits

...
54 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
patrickandClaude Opus 5.5 da84ec1625 Document the unattended-upgrades check
CI / tests (Python 3.11) (pull_request) Successful in 31s
CI / tests (Python 3.10) (pull_request) Successful in 31s
CI / tests (Python 3.12) (pull_request) Successful in 31s
CI / tests (Python 3.13) (pull_request) Successful in 31s
CI / lint (pull_request) Successful in 3s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:19:09 -04:00
patrickandClaude Opus 5.5 bfac723850 Flag hosts where unattended-upgrades has stopped succeeding
On a host with unattended-upgrades enabled, no successful run in
unattended_upgrades_stale_after_days (default 3, 0 disables) puts it in
update. The reason says which way it broke: still running but failing
("last succeeded 5d ago and is failing (last ran 6h ago); check
/var/log/unattended-upgrades/"), not running at all ("is
apt-daily-upgrade.timer enabled?"), or never succeeded. A host where it
hasn't completed its first run yet gets a note, and packages it keeps back
are noted. Hosts with it disabled or not installed, and agents before
0.8.0, are judged as before. The host page shows the state, both stamp
ages and the kept-back packages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:18:41 -04:00
patrickandClaude Opus 5.5 df097c9da3 Report unattended-upgrades state from the agent
The agent now sends whether unattended-upgrades is enabled (package
installed, not just its leftover config, and APT::Periodic::Unattended-
Upgrade set and non-zero), the age of apt.systemd.daily's upgrade-stamp
(touched only when unattended-upgrade exits 0), the age of
unattended-upgrade's own stamp (written whenever a run gets far enough,
even if it then fails) and the packages it keeps back. Nothing reads them
yet. Agent 0.8.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:17:13 -04:00
patrick 6cbc9665d8 Merge pull request 'Flag hosts whose OS release no longer gets security updates' (#26) from feat/os-end-of-support into main
CI / tests (Python 3.10) (push) Successful in 29s
CI / tests (Python 3.11) (push) Successful in 29s
CI / tests (Python 3.12) (push) Successful in 29s
CI / tests (Python 3.13) (push) Successful in 29s
CI / lint (push) Successful in 4s
Reviewed-on: #26
2026-10-31 23:53:27 +00:00
patrickandClaude Opus 5.5 bc46c55298 Flag hosts whose OS release no longer gets security updates
CI / tests (Python 3.10) (pull_request) Successful in 30s
CI / tests (Python 3.11) (pull_request) Successful in 30s
CI / tests (Python 3.12) (pull_request) Successful in 28s
CI / tests (Python 3.13) (pull_request) Successful in 28s
CI / lint (pull_request) Successful in 3s
Past its end of support a release gets no more security updates, so apt
offers nothing and the host showed ok indefinitely. The server now has a
table of when free security support ends for each release the agent
installs on (support.py): Debian's LTS end, and Ubuntu's end of standard
support plus end of ESM. Dates from Debian LTS and Ubuntu's release cycle
via endoflife.date; a test checks the table covers every release
agent/install.sh accepts.

The agent reports whether Ubuntu Pro is attached and esm-infra's status,
read from the pro client's world-readable status.json. A host past its
date goes to update; within os_eol_warn_days (default 90) of it, the row
gets a note. An Ubuntu host with ESM enabled isn't warned when standard
support ends, only before ESM does. The host page shows the dates.
Agent 0.7.0; older agents don't report ESM and count as having none.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 19:50:44 -04:00
patrick 5a11d31e66 Merge pull request 'Flag a /boot too full for the next kernel and packages dpkg left unfinished' (#25) from feat/boot-space-dpkg-audit into main
CI / tests (Python 3.10) (push) Successful in 27s
CI / tests (Python 3.11) (push) Successful in 27s
CI / tests (Python 3.12) (push) Successful in 27s
CI / tests (Python 3.13) (push) Successful in 28s
CI / lint (push) Successful in 4s
Reviewed-on: #25
2026-10-31 23:26:41 +00:00
patrickandClaude Opus 5.5 70272efed5 Flag a /boot too full for the next kernel and packages dpkg left unfinished
CI / tests (Python 3.10) (pull_request) Successful in 29s
CI / tests (Python 3.11) (pull_request) Successful in 30s
CI / tests (Python 3.12) (pull_request) Successful in 29s
CI / tests (Python 3.13) (pull_request) Successful in 28s
CI / lint (pull_request) Successful in 4s
A full /boot makes the next kernel's postinst fail: apt is left half-done
and the host quietly stays on its old kernel, which kernelwatch only
noticed indirectly, if at all. The agent now reports the size and free
space of the filesystem holding /boot (df) and the packages dpkg didn't
finish installing (half-installed, unpacked, half-configured, trigger
states or reinst-required, as dpkg --audit counts them).

The server puts a host in update when /boot has less than
boot_min_free_mb (default 200, 0 disables) free, or any package is
unfinished, with the fix in the reason ("run dpkg --configure -a"). The
host page shows both. Agents before 0.6.0 send neither field and are
judged as before. Agent 0.6.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 18:54:47 -04:00
patrick 3e2f550414 Merge pull request 'Give the backup unit network access so its heartbeat ping can leave' (#24) from fix/backup-heartbeat-network into main
CI / tests (Python 3.10) (push) Successful in 27s
CI / tests (Python 3.11) (push) Successful in 27s
CI / tests (Python 3.12) (push) Successful in 27s
CI / tests (Python 3.13) (push) Successful in 26s
CI / lint (push) Successful in 3s
Reviewed-on: #24
2026-10-31 19:04:20 +00:00
patrickandClaude Opus 5.5 f9d9660f71 Give the backup unit network access so its heartbeat ping can leave
CI / tests (Python 3.11) (pull_request) Successful in 28s
CI / tests (Python 3.10) (pull_request) Successful in 29s
CI / tests (Python 3.12) (pull_request) Successful in 25s
CI / tests (Python 3.13) (pull_request) Successful in 26s
CI / lint (pull_request) Successful in 2s
kernelwatch-backup.service still had PrivateNetwork=yes and
RestrictAddressFamilies=AF_UNIX from before scheduled-backup pinged
backup_heartbeat_url. Every nightly ping failed DNS inside the sandbox
("heartbeat request failed (URLError)"); the backup itself succeeded, so
the only symptom was the heartbeat monitor going down after a day.

Allow AF_INET/AF_INET6 like the alerts unit, and add a test that every
unit running a command that sends requests (check-alerts,
scheduled-backup, notify-backup-failure) keeps network access.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 14:58:51 -04:00
patrick 669f1dc545 Merge pull request 'Report a failed apt simulation instead of reading it as "no updates"' (#23) from fix/apt-simulation-failure into main
CI / tests (Python 3.12) (push) Successful in 26s
CI / tests (Python 3.13) (push) Successful in 26s
CI / tests (Python 3.10) (push) Successful in 25s
CI / tests (Python 3.11) (push) Successful in 25s
CI / lint (push) Successful in 3s
Reviewed-on: #23
2026-10-31 03:28:45 +00:00
patrickandClaude Opus 5.5 fc6ee03ae5 Quote an empty local in the agent for shellcheck (SC1007)
CI / tests (Python 3.10) (pull_request) Successful in 26s
CI / tests (Python 3.11) (pull_request) Successful in 25s
CI / tests (Python 3.12) (pull_request) Successful in 26s
CI / tests (Python 3.13) (pull_request) Successful in 25s
CI / lint (pull_request) Successful in 3s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 23:25:50 -04:00
patrickandClaude Opus 5.5 6d29197cfc Report a failed apt simulation instead of reading it as "no updates"
CI / tests (Python 3.10) (pull_request) Successful in 26s
CI / tests (Python 3.11) (pull_request) Successful in 25s
CI / tests (Python 3.12) (pull_request) Successful in 25s
CI / tests (Python 3.13) (pull_request) Successful in 25s
CI / lint (pull_request) Failing after 3s
The agent ran `apt-get -s dist-upgrade 2>/dev/null || true`, so when apt
failed (unmet dependencies, a broken sources entry, a damaged package cache)
the empty output counted as zero updates and the host could show ok while
nothing could be installed. The agent now keeps apt's exit status and stderr,
reports apt_simulation_ok and the first "E:" line as apt_simulation_error,
and sends the update counts as null. The server puts such a host in update
with "apt can't work out pending updates: ...", and the host page shows the
result. Agents before 0.5.0 don't send the field and are judged as before.

Also show "–" rather than "None" for an unknown count in a host's history,
and stop hard-coding the agent version in the status CLI tests. Agent 0.5.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 23:22:24 -04:00
patrick 1350c78676 Merge pull request 'Alert when Livepatch is broken or has stopped reporting' (#22) from feat/livepatch-alert into main
CI / tests (Python 3.10) (push) Successful in 28s
CI / tests (Python 3.11) (push) Successful in 25s
CI / tests (Python 3.12) (push) Successful in 24s
CI / tests (Python 3.13) (push) Successful in 24s
CI / lint (push) Successful in 3s
Reviewed-on: #22
2026-10-30 16:22:05 +00:00
patrickandClaude Sonnet 5.5 83d5e58ea5 Document Livepatch alerts
CI / tests (Python 3.10) (pull_request) Successful in 27s
CI / tests (Python 3.11) (pull_request) Successful in 26s
CI / tests (Python 3.12) (pull_request) Successful in 26s
CI / tests (Python 3.13) (pull_request) Successful in 27s
CI / lint (pull_request) Successful in 5s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 12:18:40 -04:00
patrickandClaude Sonnet 5.5 650806bfce Alert when Livepatch is broken or has stopped reporting
The alert check now also notifies, once per problem, when a host's Livepatch has
been unhealthy for livepatch_alert_after_hours (default 6), or when a host that
used to report Livepatch no longer does (a dead daemon leaves the agent with
nothing to send). A livepatch_alerts table records which hosts have reported
Livepatch, when the current problem began and whether it was notified, so hosts
without Livepatch never alert and restarts do not repeat messages. Stale hosts
are skipped.

livepatch_problem() is now the single test for unhealthy, shared with the cover
rule for pending reboots, and names the check state when that is the problem.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 12:18:39 -04:00
patrick 203c729e14 Merge pull request 'Split the README into an overview and docs/ pages' (#21) from docs/split-readme into main
CI / tests (Python 3.10) (push) Successful in 25s
CI / tests (Python 3.11) (push) Successful in 25s
CI / tests (Python 3.12) (push) Successful in 24s
CI / tests (Python 3.13) (push) Successful in 25s
CI / lint (push) Successful in 3s
Reviewed-on: #21
2026-10-30 16:13:33 +00:00
patrickandClaude Sonnet 5.5 4b5dcae2ad Add a one-line summary to each docs page and tidy the development page
CI / tests (Python 3.10) (pull_request) Successful in 25s
CI / tests (Python 3.11) (pull_request) Successful in 25s
CI / tests (Python 3.12) (pull_request) Successful in 24s
CI / tests (Python 3.13) (pull_request) Successful in 24s
CI / lint (pull_request) Successful in 3s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 12:10:45 -04:00
patrickandClaude Sonnet 5.5 e8c996965d Test that README and docs links resolve
Every relative link must point at an existing file and, when it has a #anchor,
at a real heading (slugged the way Gitea does); every docs page must be linked
from the README and link back to it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 12:10:13 -04:00
patrickandClaude Sonnet 5.5 404086ded1 Fix references that moved with the text
'above', 'below' and 'as above' pointed at sections that are now on other
pages, so they become links; server/install.sh's pointer to the README now
names docs/reverse-proxy.md; server.md gains the next steps that used to be
the following README sections.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 12:10:13 -04:00
patrickandClaude Sonnet 5.5 84c9952dd2 Slim the README to an overview and quick start
The README keeps the intro, diagram, status table, a three-step quick start and
an index of the docs/ pages; everything else lives in docs/.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 12:08:10 -04:00
patrickandClaude Sonnet 5.5 77a880880a Move README sections into docs/ pages
Content is moved verbatim (checked line by line against the old README). Each
page gets a title and a link back to the README; H3 sections that become pages
of their own are promoted to H2. The README itself is trimmed next.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 12:07:31 -04:00
patrick e7a9a49438 Merge pull request 'Add kernelwatch status [--json]' (#20) from feat/status-cli into main
CI / tests (Python 3.10) (push) Successful in 25s
CI / tests (Python 3.11) (push) Successful in 25s
CI / tests (Python 3.12) (push) Successful in 25s
CI / tests (Python 3.13) (push) Successful in 24s
CI / lint (push) Successful in 3s
Reviewed-on: #20
2026-10-30 15:46:32 +00:00
patrickandClaude Sonnet 5.5 63b9151b09 Add kernelwatch status [--json]
CI / tests (Python 3.10) (pull_request) Successful in 25s
CI / tests (Python 3.11) (pull_request) Successful in 24s
CI / tests (Python 3.12) (pull_request) Successful in 24s
CI / tests (Python 3.13) (pull_request) Successful in 25s
CI / lint (pull_request) Successful in 4s
Prints the fleet like the dashboard, worst hosts first, from the same
evaluate() call, so the CLI and the dashboard cannot disagree. --json gives
generated_at, whole-fleet counts and a stable per-host object with no secrets;
--host and --level (repeatable) trim the host list. No network surface.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 11:42:59 -04:00
patrick 9d80d3ea4c Merge pull request 'Add heartbeat pings for the alert check and the nightly backup' (#19) from feat/heartbeat into main
CI / tests (Python 3.10) (push) Successful in 25s
CI / tests (Python 3.11) (push) Successful in 25s
CI / tests (Python 3.12) (push) Successful in 25s
CI / tests (Python 3.13) (push) Successful in 24s
CI / lint (push) Successful in 3s
Reviewed-on: #19
2026-10-30 15:35:17 +00:00
patrickandClaude Sonnet 5.5 55a9766418 Document the heartbeat monitor setup
CI / tests (Python 3.10) (pull_request) Successful in 24s
CI / tests (Python 3.11) (pull_request) Successful in 24s
CI / tests (Python 3.12) (pull_request) Successful in 24s
CI / tests (Python 3.13) (pull_request) Successful in 24s
CI / lint (pull_request) Successful in 4s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 11:32:15 -04:00
patrickandClaude Sonnet 5.5 60b8c6bff7 Add heartbeat pings for the alert check and the nightly backup
heartbeat_url is pinged after every alert check that sent its notifications
without failures, and backup_heartbeat_url after every successful nightly
backup, so an external monitor (healthchecks.io, Uptime Kuma) notices when the
alert timer or the backup stops running. A failing heartbeat is logged without
the URL and never fails the work it reports on. kernelwatch test-heartbeat
pings each configured URL once.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 11:31:32 -04:00
patrick e3013921d1 Merge pull request 'Notify via ntfy when the nightly backup fails' (#18) from feat/backup-failure-alert into main
CI / tests (Python 3.10) (push) Successful in 24s
CI / tests (Python 3.11) (push) Successful in 24s
CI / tests (Python 3.12) (push) Successful in 24s
CI / tests (Python 3.13) (push) Successful in 24s
CI / lint (push) Successful in 3s
Reviewed-on: #18
2026-10-30 15:16:58 +00:00
patrickandClaude Sonnet 5.5 48960e6faf Notify via ntfy when the nightly backup fails
CI / tests (Python 3.10) (pull_request) Successful in 25s
CI / tests (Python 3.11) (pull_request) Successful in 24s
CI / tests (Python 3.12) (pull_request) Successful in 24s
CI / tests (Python 3.13) (pull_request) Successful in 25s
CI / lint (pull_request) Successful in 3s
kernelwatch-backup.service gets OnFailure=kernelwatch-backup-failed.service,
which runs notify-backup-failure, so timeouts, OOM kills and crashes are
reported as well as handled errors. The installer ships the new unit, and tests
check that every OnFailure= target is a real unit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 11:13:33 -04:00
patrickandClaude Sonnet 5.5 8a9a3ca56d Add notify-backup-failure command
Sends a high-priority ntfy message that the nightly backup failed, naming the
newest backup still on disk. It exits 1 if the message can't be delivered and 0
(with a note on stderr) when ntfy isn't configured.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 11:12:22 -04:00
patrick 6652a4d795 Merge pull request 'Back up the database nightly with a timer' (#17) from feat/backup-timer into main
CI / tests (Python 3.10) (push) Successful in 26s
CI / tests (Python 3.11) (push) Successful in 24s
CI / tests (Python 3.12) (push) Successful in 24s
CI / tests (Python 3.13) (push) Successful in 24s
CI / lint (push) Successful in 3s
Reviewed-on: #17
2026-10-30 15:06:01 +00:00
patrickandClaude Sonnet 5.5 4a9bc77a08 Back up the database nightly with a timer
CI / tests (Python 3.10) (pull_request) Successful in 23s
CI / tests (Python 3.11) (pull_request) Successful in 25s
CI / tests (Python 3.12) (pull_request) Successful in 24s
CI / tests (Python 3.13) (pull_request) Successful in 24s
CI / lint (pull_request) Successful in 3s
kernelwatch scheduled-backup writes kernelwatch-YYYY-MM-DD.db into backup_dir
and prunes dated copies backup_keep_days or older, only after the new backup
succeeded and only files with exactly that name. kernelwatch-backup.timer runs
it at about 03:30 as the unprivileged service user with no network, and
server/install.sh enables it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 10:23:45 -04:00
43 changed files with 4416 additions and 552 deletions

No files matched your search

+1 -1
View File
@@ -6,4 +6,4 @@ test:
$(PYTHON) -m unittest discover -s tests $(PYTHON) -m unittest discover -s tests
lint: 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
+36 -508
View File
@@ -19,7 +19,9 @@ Supported: agents on **Debian 12/13** and **Ubuntu 22.04/24.04/26.04 LTS**; serv
browser ──HTTPS──▶ Caddy/nginx ──▶ kernelwatch (127.0.0.1:8080) ──▶ SQLite browser ──HTTPS──▶ Caddy/nginx ──▶ kernelwatch (127.0.0.1:8080) ──▶ SQLite
``` ```
## What the dashboard tells you It's read-only by design: the server can't make hosts do anything.
## What you see
Each host gets one status. When several apply, the worst one wins: Each host gets one status. When several apply, the worst one wins:
@@ -27,92 +29,17 @@ 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 (`apt_stale_after_hours`) for "no updates" to mean anything. | | `update` | A kernel or security update is available but not installed, services are running outdated libraries and need a restart, or apt's package lists are too old, 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 also lists the reasons behind its status, and clicking a host shows Each row lists the reasons behind its status, and clicking a host shows its full
its full report and recent history. report and recent history. [How it works](docs/how-it-works.md) explains how the
agent works each of these out (kernel comparison, needrestart, Ubuntu Livepatch,
phased updates, package list freshness).
How the agent works it out: ## Quick start
- **Running vs. installed kernel**, three ways: **1. Install the server** on the dashboard host:
- A newer `linux-image-*` installed than `uname -r` means a version upgrade.
- The build in `uname -v` (`Debian 6.12.57-1`, `#85-Ubuntu`, `#33~24.04.1-Ubuntu`)
is compared with the installed package version of the running kernel
(`6.12.57-1`, `6.8.0-85.85`, `6.14.0-33.33~24.04.1`). A mismatch means the
package was upgraded in place after boot; `uname -r` didn't change, but a
reboot is still needed.
- [`needrestart`](https://github.com/liske/needrestart)'s kernel result, for
build strings the server doesn't recognise (see below).
- **Services needing a restart** (e.g. nginx still using the old OpenSSL
after an upgrade): from `needrestart -b`, if it's installed. Ubuntu ships it;
on Debian, install with `install.sh --with-needrestart`. Without it, the
Services column shows `?` and status isn't affected. needrestart has to
inspect every process, so it runs as root in its own unit,
`kernelwatch-needrestart.service`. That unit has no network access, only the
two capabilities needrestart needs, and list-only mode, so it never restarts
anything. It writes its results to `/run/kernelwatch/needrestart`, and the
unprivileged agent unit runs it just before each report and reads the file.
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.
- **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
`nothing-to-apply`, checked, supported), a pending kernel reboot, or a
`/run/reboot-required` caused only by `linux-*` packages, shows as a note
instead of `reboot`, and the note gives the date by which the kernel must be
upgraded. Livepatch only fixes high and critical CVEs, and only until that
date, so cover ends 14 days before it and the host goes to `reboot` as usual.
Any other reboot reason (libc, systemd) still counts. If Livepatch is failing,
unsupported or in a state we don't know, the host gets no cover and the reason
is noted. Hosts without Livepatch are unaffected. `canonical-livepatch` needs
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.
- **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.
- **Hostname check**: each report includes the host's own name. If its first
DNS label differs from the name the host is registered under (ignoring case),
the row gets a note: "registered as web01 but reports itself as db01". This
catches a token copied to the wrong machine. It never changes the status. A
host you registered under a custom label (`<ssh target> <name>` in
`agent/hosts`) shows the note until you tell its agent which name to report:
`agent/deploy.sh iris -- --report-hostname iris` (or `install.sh
--report-hostname iris` on the host, which sets `REPORT_HOSTNAME` in
`agent.conf`). Upgrades and `--rotate` keep it;
`--default-report-hostname` removes it. That's the host's own say-so, so it
only silences the note for hosts you've deliberately named.
- **Available updates**: a simulated `apt-get dist-upgrade`. It is read-only, takes
no locks and writes no cache files. `dist-upgrade` is used so that new-ABI kernel
packages pulled in by the meta-package show up. Lines whose origin contains
`-security` count as security updates.
- **Fresh package lists**: the simulation only knows what apt's package lists
say, and the agent can't refresh them itself. Ubuntu refreshes them about once
a day. Debian doesn't by default unless `unattended-upgrades` is set up, so a
new kernel or security update can stay invisible until someone runs
`apt update`. Install with `--with-apt-update` and
`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`.
- **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
their own Phased column (hover for the packages, `–` on Debian), with the
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".
The agent sends raw facts and the server decides what they mean, so you can
change the status rules without touching the agents.
## Server setup
On the dashboard host:
```sh ```sh
git clone <this repo> && cd kernel-automation git clone <this repo> && cd kernel-automation
@@ -120,441 +47,42 @@ sudo ./server/install.sh
sudo kernelwatch set-password admin # dashboard login sudo kernelwatch set-password admin # dashboard login
``` ```
This installs to `/opt/kernelwatch` and keeps config in `/etc/kernelwatch/server.toml` It listens on plain HTTP on `127.0.0.1:8080`. Put a TLS reverse proxy in front;
(see [`server/server.toml.example`](server/server.toml.example)) and data in [Reverse proxy and access control](docs/reverse-proxy.md) has Caddy, nginx,
`/var/lib/kernelwatch`. The `kernelwatch.service` unit runs it as the unprivileged CloudPanel and Authelia setups.
`kernelwatch` user. Re-run `install.sh` to upgrade; it keeps your config.
### TLS reverse proxy **2. Add a host.** On the server, `sudo kernelwatch add-host web01` prints a token
(shown once). Then on the host:
The server speaks plain HTTP on `127.0.0.1:8080`. Put a TLS proxy in front of it.
The agents and your browser both connect through it.
**Caddy** (simplest):
```caddyfile
kernelwatch.example.internal {
reverse_proxy 127.0.0.1:8080
}
```
**nginx**:
```nginx
server {
listen 443 ssl;
server_name kernelwatch.example.internal;
# ssl_certificate / ssl_certificate_key ...
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
```
With either proxy, set `trust_proxy_headers = true` in `server.toml` so login
rate limiting sees real client IPs.
If you use a private CA (e.g. Caddy's `tls internal`), give the agents its
root cert with `--ca` (below).
You can expose only `/api/v1/report` to the fleet network and keep the
dashboard on a VPN or tailnet. That's a proxy rule, not a kernelwatch setting.
### CloudPanel
CloudPanel gives each site its own Linux user and a document root at
`/home/<site-user>/htdocs/<domain>/`. kernelwatch doesn't use that directory.
nginx forwards requests to the app; it doesn't serve kernelwatch's files. Install
with `server/install.sh` as above, so the app runs as the `kernelwatch` user
with its data in `/var/lib/kernelwatch`, outside every site user's home. Leave
the document root empty, and keep your clone of this repo out of `htdocs`.
1. **Pick a free port.** CloudPanel's Varnish setup can run an nginx backend
on 8080. Check with `ss -ltnp | grep ':8080\b'`. If it's taken, set another port
in `/etc/kernelwatch/server.toml` and restart (`sudo systemctl restart kernelwatch`):
```toml
listen_port = 8095
trust_proxy_headers = true
```
Check it: `curl -s http://127.0.0.1:8095/healthz` should print `ok`.
2. **Create the site as a Reverse Proxy.** In CloudPanel: *Add Site → Create a
Reverse Proxy*, with your domain and Reverse Proxy URL
`http://127.0.0.1:8095`. CloudPanel can't change an existing site's type. If
the domain already exists as a PHP or static site, delete and recreate it.
Deleting a site also removes its site user and home directory, so move
anything you need out first.
3. **TLS.** In the site's *SSL/TLS* tab, issue a Let's Encrypt certificate. Agents
then need no `--ca`.
4. **Check the generated vhost** (the site's *Vhost* tab). The `location`
that proxies to the app should pass the original `Host` header and the
client address:
```nginx
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
```
Add them if they're missing. Without `Host`, logins fail the origin check
with "cross-origin request refused". Without `X-Forwarded-For`, every login
appears to come from 127.0.0.1, so one person's failed attempts lock everyone out.
Also check that the login page is styled. If `/static/style.css` returns 404,
a static-file `location` in the template is looking in the empty document root
instead of proxying. Make it fall through to the proxy, or remove it.
5. **Optionally restrict the dashboard.** The site's domain is public, so the
login page is reachable from the internet unless you limit it. Agents only
need `/api/v1/report`. In the Vhost tab, add an `allow <your IP>; deny all;`
to `location /` and a separate unrestricted
`location = /api/v1/report { proxy_pass http://127.0.0.1:8095; }`.
Changes made in the Vhost tab persist. Back them up before
recreating the site.
To require a login through Authelia instead of an IP allowlist, see
[Authelia (forward auth)](#authelia-forward-auth).
### Authelia (forward auth)
If you already run [Authelia](https://www.authelia.com/), you can put it in
front of the dashboard. That adds Authelia's 2FA and single sign-on, and
kernelwatch's own login still applies behind it. You log in to both, but
Authelia's remember-me makes that rare. This uses nginx's `auth_request`, so
you don't need an OIDC client.
**Agents must bypass Authelia.** They authenticate with their bearer token and
can't follow a login redirect. If Authelia covers `/api/v1/report`, every
report gets a redirect instead of a 401 or 204, and the whole fleet goes stale
within 3 hours.
1. **Authelia `access_control`.** Rules are checked in order, so put the bypass
first, and keep a single `rules:` list:
```yaml
access_control:
default_policy: two_factor
rules:
- domain: kernelwatch.example.com
resources:
- '^/api/v1/report$'
- '^/healthz$'
policy: bypass
- domain: "*.example.com"
policy: two_factor
```
For the redirect to the login page to work, your `session.cookies` entry has
to cover the dashboard's domain and set `authelia_url`. Without them, browsers
get a bare 401 page. Authelia reads this file only at startup, so restart it
after editing (in Kubernetes: `kubectl rollout restart deployment/authelia`).
Check the file first with `authelia validate-config`.
2. **nginx.** Add an internal location for Authelia's check, an exact-match
location for the agents with no check, and the check on `location /`.
For CloudPanel, edit the site's *Vhost* tab: leave the template's
`@reverse_proxy` block alone and add or replace these:
```nginx
# Authelia's check (internal subrequest only)
location = /internal/authelia/authz {
internal;
proxy_pass https://auth.example.com/api/authz/auth-request;
proxy_http_version 1.1;
proxy_ssl_server_name on;
proxy_set_header Host auth.example.com;
proxy_set_header X-Original-Method $request_method;
proxy_set_header X-Original-URL $scheme://$http_host$request_uri;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Content-Length "";
proxy_set_header Connection "";
proxy_pass_request_body off;
}
# Agents: token auth only
location = /api/v1/report {
try_files $uri @reverse_proxy;
}
# Dashboard: Authelia first, then kernelwatch's login
location / {
auth_request /internal/authelia/authz;
auth_request_set $redirection_url $upstream_http_location;
error_page 401 =302 $redirection_url;
try_files $uri @reverse_proxy;
}
```
Without CloudPanel, use `proxy_pass http://127.0.0.1:8095;` plus the `Host`
and `X-Forwarded-For` headers in place of `try_files ... @reverse_proxy`. If
Authelia runs on the same machine, point the check straight at it (e.g.
`http://127.0.0.1:9091/api/authz/auth-request`) and drop the
`proxy_ssl_server_name` and `Host` lines. Keep `location ^~ /.well-known`
unprotected so certificate renewals still work. If something monitors
`/healthz`, give it an exact-match location like the agents' one.
3. **Check it.**
```sh
curl -sI https://kernelwatch.example.com/ | head -3
# 302, Location pointing at Authelia
curl -si -X POST https://kernelwatch.example.com/api/v1/report | head -1
# 401 from kernelwatch (no token), not a 302
```
Then run `sudo systemctl start kernelwatch-agent` on one host and check
that its *Last seen* updates. If the POST gets a 302, the agents' location
isn't matching. Fix that before the fleet goes stale.
## Adding a host
On the server:
```sh ```sh
sudo kernelwatch add-host web01 sudo ./agent/install.sh --server https://kernelwatch.example.internal
# prints a token, shown once
```
On the host (copy the `agent/` directory over, or clone the repo):
```sh
sudo ./agent/install.sh --server https://kernelwatch.example.internal [--ca root.pem]
# paste the token when prompted # paste the token when prompted
``` ```
The installer puts the agent in `/usr/local/sbin`, writes `/etc/kernelwatch/agent.conf` or, for many hosts at once, from your workstation over SSH (after a one-time
and `agent.token` (root, 0600), enables `kernelwatch-agent.timer` and sends a first `agent/deploy.conf`, see [Agents](docs/agents.md)):
report. After that, the agent reports 2 minutes after boot and then hourly, with up
to 15 minutes of jitter.
For unattended installs, set `KERNELWATCH_TOKEN=...` instead of using the prompt.
Add `--with-needrestart` to also report services needing a restart (Debian
needs this; Ubuntu already has needrestart). It installs needrestart if
missing and sets it to *list* services after apt upgrades instead of asking
interactively. Delete `/etc/needrestart/conf.d/kernelwatch.conf` to undo that.
Add `--with-apt-update` to refresh apt's package lists before each report
(recommended on Debian, see above). It's the same as running `apt update`
hourly: lists only, nothing is installed. If apt is busy, the refresh is
skipped and the report goes ahead. `--without-apt-update` turns it off;
re-running the installer with neither keeps the current setting.
Useful on a host:
```sh ```sh
sudo kernelwatch-agent --print # see exactly what would be sent agent/deploy.sh --register web01 db01
sudo systemctl start kernelwatch-agent # report now
systemctl list-timers kernelwatch-agent.timer
journalctl -u kernelwatch-agent
``` ```
### Deploying to many hosts [Agents](docs/agents.md) also covers the options (private CA, needrestart, apt update,
reporting under a different name) and for upgrading the fleet.
`agent/deploy.sh` does all of the above over SSH from your workstation's **3. Set up alerts and backups** (recommended): [Alerts and
checkout, so hosts need neither git nor Gitea access. Set it up once: monitoring](docs/alerts.md) covers ntfy notifications and the heartbeat that
tells you if kernelwatch itself stops. [Operations](docs/operations.md) covers
nightly backups.
```sh ## Documentation
cp agent/deploy.conf.example agent/deploy.conf # SERVER_URL, DASHBOARD (ssh target)
cp agent/hosts.example agent/hosts # optional; --register fills it in
```
Then: | Page | What's in it |
|------|--------------|
```sh | [How it works](docs/how-it-works.md) | Status rules and how the agent collects each fact |
agent/deploy.sh --register web01 db01 # register on the dashboard + install | [Server](docs/server.md) | Installing and upgrading, the admin commands |
agent/deploy.sh # upgrade every host in agent/hosts | [Reverse proxy and access control](docs/reverse-proxy.md) | TLS with Caddy or nginx, CloudPanel, Authelia |
agent/deploy.sh web01 # upgrade one | [Agents](docs/agents.md) | Adding hosts, `agent/deploy.sh`, agent options |
agent/deploy.sh --rotate web01 # new token, reinstall | [Alerts and monitoring](docs/alerts.md) | ntfy alerts for stale, reboot and update, heartbeat monitoring |
agent/deploy.sh --dry-run # show the plan | [Operations](docs/operations.md) | `kernelwatch status --json` for scripts, backups and restore |
agent/deploy.sh -- --with-needrestart # pass options through to install.sh | [Security notes](docs/security.md) | How tokens, sandboxing and the dashboard are locked down |
agent/deploy.sh -- --with-apt-update # refresh package lists before each report | [Development](docs/development.md) | Running the tests, a local server, ideas for later |
```
For each host it copies the agent into a private temp directory and runs
`install.sh`, which sends a first report, then deletes the temp directory.
With `--register`/`--rotate`, it also runs
`sudo kernelwatch add-host --token-only` on the dashboard host and passes the
token to the host on SSH stdin. The token never appears on a command line or
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.
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
a jump host in `~/.ssh/config` and `deploy.sh` works unchanged:
```
Host zeus
ProxyJump eurus
```
## Stale-host, reboot and update alerts (ntfy)
The server can notify an [ntfy](https://ntfy.sh/) topic when a host stops
reporting and when its reports resume. Agents report hourly with up to 15 minutes
of jitter. Alerts use the same `stale_after_hours` as the dashboard (3 hours by
default), leaving room for ordinary delays. Newly registered hosts get that same
grace period to send their first report.
Re-run `sudo ./server/install.sh` to install the alert timer when upgrading.
The installer preserves your existing config, so add these settings to
`/etc/kernelwatch/server.toml`:
```toml
ntfy_url = "https://ntfy.example.com/kernelwatch"
ntfy_token = "" # optional access token with publish permission for this topic
ntfy_timeout_seconds = 10.0
```
Subscribe to that topic in your ntfy app, then check delivery:
```sh
sudo kernelwatch test-alert
systemctl list-timers kernelwatch-alerts.timer
```
`kernelwatch-alerts.timer` runs a separate, unprivileged check every five minutes,
even when no hosts report and nobody opens the dashboard. Notifications normally
arrive within about five minutes of crossing the stale threshold or receiving a
fresh report. Run `sudo kernelwatch check-alerts` to check immediately, or inspect
`journalctl -u kernelwatch-alerts.service` for delivery failures.
- Each host gets one stale notification and one reporting-recovery notification
per detected outage. Successful sends are saved in SQLite, so routine checks
and server restarts don't repeat them. Recovery confirms reporting has resumed;
the host may still need updates or a reboot.
- Failed sends are retried on the next check, and a failure for one host doesn't
stop checks for the others. A recovery is sent only after a stale notification
was successfully delivered. A timeout or crash after ntfy accepted a message
can cause a duplicate on retry.
- An empty `ntfy_url` disables notifications. The timer reads its configuration
on every run; changing ntfy settings needs no restart. If you change
`stale_after_hours`, restart `kernelwatch.service` too so the dashboard uses the
new threshold.
- **Reboot and update alerts.** A host that has stayed in `reboot` or `update`
for `status_alert_after_hours` (default 24) gets one notification listing the
reasons shown on the dashboard. The clock starts when the host entered that
status, so hourly reports don't restart it. Fixing the host (back to `ok`)
re-arms it. Going from `update` to `reboot` notifies again after another
period; going back down doesn't. Stale hosts are skipped, since the stale
alert covers them. Set `status_alert_after_hours = 0` to turn these off.
Upgrading starts the clock at the first check, so expect the first
notifications a day after you re-run `install.sh`.
Use the topic's direct publish URL, with token authentication if needed; it must
accept the POST without a browser login or redirect. The topic and token stay
in the server config (root-owned, readable by the `kernelwatch` service group).
Agents need no changes.
## Server admin commands
```
sudo kernelwatch add-host NAME register a host, print its token (--token-only for scripts)
sudo kernelwatch rotate-token NAME issue a new token (old one stops working)
sudo kernelwatch remove-host NAME delete a host and its history
sudo kernelwatch list-hosts hosts and when they last reported
sudo kernelwatch set-password USER create a user / change password (logs out their sessions)
sudo kernelwatch remove-user USER
sudo kernelwatch list-users
sudo kernelwatch backup PATH write a consistent copy of the database (safe while running)
sudo kernelwatch check-alerts check for stale, recovered, reboot and update alerts now
sudo kernelwatch test-alert send a test notification to the configured ntfy topic
```
## Backups
Everything kernelwatch knows lives in one SQLite file, `/var/lib/kernelwatch/kernelwatch.db`:
host tokens (hashed), dashboard logins and report history. Without it you'd
re-register every host and reinstall its token. Don't copy the file while the
server runs, since recent writes can sit in its `-wal` sidecar. Use:
```sh
sudo kernelwatch backup /var/lib/kernelwatch/backups/kernelwatch.db
```
This uses SQLite's online backup, so it's safe while hosts are reporting. It
replaces any existing file at that path and writes it mode 0600. It refuses to
overwrite the live database. The command runs as the `kernelwatch` user, so the
destination directory has to be writable by it (create one with
`sudo install -d -o kernelwatch -g kernelwatch -m 0700 /var/lib/kernelwatch/backups`),
then copy the result off the machine with your usual backup tool.
To restore, stop the service, put the file at `db_path` owned by `kernelwatch`
(mode 0600), and start it again. The stale-alert state restores with it.
## Security notes
- **Host identity comes from the token, not the payload.** A host can only
report as itself. Tokens are 256-bit random values; only their SHA-256 is stored.
- **Report rate limit.** A report arriving less than `report_min_interval_seconds`
(default 30) after the host's previous one gets HTTP 429 with a `Retry-After`
header, and isn't stored. So a stuck agent or a leaked token can't flood the
database or push real history off the host page. The agent's curl waits out the
`Retry-After` and retries, so running `systemctl start kernelwatch-agent` twice
in a row just pauses briefly. Set it to `0` to disable.
- **Livepatch status** runs in a separate root unit with no network access and a
read-only filesystem. It has no capability bound, syscall filter or
`NoNewPrivileges`, because the snap's setuid `snap-confine` can't run under
them (tested: `NoNewPrivileges=yes` fails with "cannot change profile for the
next exec call"). It only runs `canonical-livepatch status`.
- **needrestart** runs in a separate root unit with `PrivateNetwork=yes`, a
capability set of just `CAP_SYS_PTRACE` + `CAP_DAC_READ_SEARCH` (to read other
processes' memory maps), a read-only filesystem except `/run/kernelwatch`,
and `-r l` (list, never restart).
- **apt-get update** (with `--with-apt-update`) runs as root with network
access, like apt's own `apt-daily.service`, but sandboxed: no access to home
directories, devices or kernel settings. apt drops to its `_apt` user for the
downloads, and nothing gets installed.
- **The agent** runs as a throwaway unprivileged user (`DynamicUser=yes`) with
no capabilities, a read-only filesystem view and a syscall filter. The token
reaches it through `LoadCredential=` and goes to curl on stdin, so it never
appears in a process listing.
- **The dashboard** uses scrypt-hashed passwords, server-side sessions,
`HttpOnly` + `Secure` + `SameSite=Strict` cookies, an Origin check on form
posts, per-IP login rate limiting, and a strict CSP. Everything a host
reports is HTML-escaped.
- **It's read-only by design.** The server can't make hosts do anything.
Adding remote actions (like "reboot this host") would turn it into a
remote-execution system; think hard before doing that.
## Development
```sh
make test # unit + integration tests (stdlib unittest)
make lint # shellcheck, if available
```
Gitea Actions (`.gitea/workflows/ci.yml`) runs both on every push to `main`
and every pull request: the tests on Python 3.10–3.13 (the versions on the
supported Ubuntu and Debian releases) and shellcheck on the shell scripts.
The tests run a real server on an ephemeral port. They also run the real agent
script against stubbed `dpkg-query`/`apt-get`/`needrestart`/`uname` and a fake
filesystem root (`KERNELWATCH_ROOT`), including one end-to-end agent → server
report.
Both installers (`agent/install.sh`, `server/install.sh`) run for real in the tests
against a fake root: `KERNELWATCH_ROOT` prefixes every path they write and skips
their root check, and `systemctl`, `apt-get`, `useradd` and the like are stubs that
log their arguments. Don't set it on a real host.
Run a local server against a scratch database:
```sh
printf 'db_path = "/tmp/kw.db"\nsecure_cookies = false\n' > /tmp/kw.toml
export KERNELWATCH_CONFIG=/tmp/kw.toml
./server/kernelwatch-server set-password admin
./server/kernelwatch-server serve # http://127.0.0.1:8080
```
## Ideas for later
- Additional notification channels
- A JSON endpoint for scripting
- Grouping or tagging hosts (prod/staging, location)
+44 -2
View File
@@ -8,6 +8,7 @@
# agent/deploy.sh --rotate web01 issue a new token, then reinstall # agent/deploy.sh --rotate web01 issue a new token, then reinstall
# agent/deploy.sh --dry-run show what would happen # agent/deploy.sh --dry-run show what would happen
# agent/deploy.sh -- --with-needrestart pass the rest to install.sh # 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, # Settings: agent/deploy.conf (see deploy.conf.example). Hosts: agent/hosts,
# one per line: `<ssh target> [kernelwatch name]`; the name defaults to the # one per line: `<ssh target> [kernelwatch name]`; the name defaults to the
@@ -20,7 +21,7 @@ CONF=${KERNELWATCH_DEPLOY_CONF:-$here/deploy.conf}
HOSTS_FILE=${KERNELWATCH_HOSTS:-$here/hosts} HOSTS_FILE=${KERNELWATCH_HOSTS:-$here/hosts}
FILES=(kernelwatch-agent kernelwatch-agent.service kernelwatch-agent.timer FILES=(kernelwatch-agent kernelwatch-agent.service kernelwatch-agent.timer
kernelwatch-needrestart.service kernelwatch-livepatch kernelwatch-livepatch.service 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}$' NAME_RE='^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$'
SERVER_URL= SERVER_URL=
@@ -149,10 +150,47 @@ deploy_one() {
fi 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 mode=upgrade
dry_run=0 dry_run=0
allow_outdated=0
targets=() targets=()
install_args=() install_args=()
while (($#)); do while (($#)); do
@@ -165,6 +203,7 @@ while (($#)); do
--register) mode=register ;; --register) mode=register ;;
--rotate) mode=rotate ;; --rotate) mode=rotate ;;
--dry-run) dry_run=1 ;; --dry-run) dry_run=1 ;;
--allow-outdated) allow_outdated=1 ;;
-h | --help) usage; exit 0 ;; -h | --help) usage; exit 0 ;;
-*) usage >&2; exit 2 ;; -*) usage >&2; exit 2 ;;
*) targets+=("$1") ;; *) targets+=("$1") ;;
@@ -172,6 +211,7 @@ while (($#)); do
shift shift
done done
refuse_sudo
load_config load_config
[[ -n $SERVER_URL ]] || die "SERVER_URL is not set in $CONF" [[ -n $SERVER_URL ]] || die "SERVER_URL is not set in $CONF"
[[ $mode == upgrade || -n $DASHBOARD ]] || die "DASHBOARD 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" ((${#targets[@]})) || die "no hosts given and none in $HOSTS_FILE"
fi fi
check_checkout
failed=() failed=()
for t in "${targets[@]}"; do for t in "${targets[@]}"; do
say "==> $t" say "==> $t"
+2 -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]
@@ -82,6 +82,7 @@ mkdir -p "$root/usr/local/sbin" "$root/etc/systemd/system"
install -d -m 0755 "$etc" install -d -m 0755 "$etc"
install -m 0755 "$here/kernelwatch-agent" "$root/usr/local/sbin/kernelwatch-agent" 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-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" \ install -m 0644 "$here/kernelwatch-agent.service" "$here/kernelwatch-agent.timer" \
"$here/kernelwatch-needrestart.service" "$here/kernelwatch-livepatch.service" \ "$here/kernelwatch-needrestart.service" "$here/kernelwatch-livepatch.service" \
"$here/kernelwatch-apt-update.service" "$root/etc/systemd/system/" "$here/kernelwatch-apt-update.service" "$root/etc/systemd/system/"
+309 -12
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.4.1 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:-}
@@ -134,9 +134,15 @@ NEEDRESTART_MAX_AGE=7200
# Sets NR_* from the results file, if it's there and fresh. KSTA: 0 unknown, # 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. # 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_OK=0
NR_KSTA= NR_KSTA=
NR_KEXP= NR_KEXP=
NR_UCSTA=
NR_UCCUR=
NR_UCEXP=
NR_SVCS= NR_SVCS=
NR_SESS=0 NR_SESS=0
read_needrestart() { read_needrestart() {
@@ -148,6 +154,9 @@ read_needrestart() {
case $line in case $line in
NEEDRESTART-KSTA:*) NR_KSTA=${line#*: } ;; NEEDRESTART-KSTA:*) NR_KSTA=${line#*: } ;;
NEEDRESTART-KEXP:*) NR_KEXP=${line#*: } ;; NEEDRESTART-KEXP:*) NR_KEXP=${line#*: } ;;
NEEDRESTART-UCSTA:*) NR_UCSTA=${line#*: } ;;
NEEDRESTART-UCCUR:*) NR_UCCUR=${line#*: } ;;
NEEDRESTART-UCEXP:*) NR_UCEXP=${line#*: } ;;
NEEDRESTART-SVC:*) NR_SVCS+=${line#*: }$'\n' ;; NEEDRESTART-SVC:*) NR_SVCS+=${line#*: }$'\n' ;;
NEEDRESTART-SESS:*) NR_SESS=$((NR_SESS + 1)) ;; NEEDRESTART-SESS:*) NR_SESS=$((NR_SESS + 1)) ;;
esac esac
@@ -180,6 +189,29 @@ read_livepatch() {
done <"$LIVEPATCH_FILE" 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. # String, or null when empty.
json_str_or_null() { json_str_or_null() {
if [[ -n $1 ]]; then json_str "$1"; else printf 'null'; fi if [[ -n $1 ]]; then json_str "$1"; else printf 'null'; fi
@@ -193,13 +225,30 @@ json_str_or_null() {
# with /proc/1/root. Unprivileged we can't read /proc/1/root, so ischroot # with /proc/1/root. Unprivileged we can't read /proc/1/root, so ischroot
# answers "chroot" and apt would offer every phased update. We're not in one: # answers "chroot" and apt would offer every phased update. We're not in one:
# say so, and apt applies phasing from /etc/machine-id like it does for root. # say so, and apt applies phasing from /etc/machine-id like it does for root.
#
# apt's stderr goes to the file named by $1. A failed simulation prints nothing,
# which would otherwise read as "no updates", so the caller reports the failure.
apt_simulation() { apt_simulation() {
LC_ALL=C apt-get -s -q \ LC_ALL=C apt-get -s -q \
-o Dir::Bin::ischroot=/bin/false \ -o Dir::Bin::ischroot=/bin/false \
-o Debug::NoLocking=true \ -o Debug::NoLocking=true \
-o Dir::Cache::pkgcache= \ -o Dir::Cache::pkgcache= \
-o Dir::Cache::srcpkgcache= \ -o Dir::Cache::srcpkgcache= \
dist-upgrade 2>/dev/null || true dist-upgrade 2>"$1"
}
# Why apt failed, from its stderr on stdin: the first "E:" line, else the first
# line, else the exit status in $1.
apt_error() {
local line first=
while IFS= read -r line; do
if [[ $line == 'E: '* ]]; then
printf '%s' "${line#E: }"
return 0
fi
[[ -z $first && -n $line ]] && first=$line
done
printf '%s' "${first:-apt-get exited with status $1}"
} }
# Packages Ubuntu is holding back from this host for now (phased updates). apt # Packages Ubuntu is holding back from this host for now (phased updates). apt
@@ -211,20 +260,218 @@ phased_packages() {
} }
# Seconds since apt last refreshed its package lists, or empty if unknown. # 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() { apt_lists_age() {
local newest=0 f m local newest=0 f m
for f in \ for f in \
"$ROOT/var/lib/apt/periodic/update-success-stamp" \ "$ROOT/var/lib/apt/periodic/update-success-stamp" \
"$ROOT/var/lib/apt/periodic/update-stamp" \ "$ROOT/var/lib/apt/periodic/update-stamp"; do
"$ROOT/var/lib/apt/lists/partial"; do
[[ -e $f ]] || continue
m=$(stat -c %Y "$f" 2>/dev/null) || continue m=$(stat -c %Y "$f" 2>/dev/null) || continue
((m > newest)) && newest=$m ((m > newest)) && newest=$m
done 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 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
# on its old kernel with apt half-done.
boot_space() {
df -Pk "$ROOT/boot" 2>/dev/null |
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
# `dpkg --configure -a`. Reads the status database only.
unfinished_packages() {
dpkg-query -W -f='${db:Status-Abbrev}\t${binary:Package}\n' 2>/dev/null |
awk -F '\t' 'substr($1, 2, 1) ~ /[HUFWt]/ || substr($1, 3, 1) == "R" { print $2 }' |
sort -u || true
}
# unattended-upgrades: "enabled", "disabled" or "not-installed". Enabled means the
# package is installed (not just its leftover config, dpkg state rc) and
# APT::Periodic::Unattended-Upgrade is set and not 0, which is what makes
# apt-daily-upgrade.service (apt.systemd.daily) run it.
unattended_upgrades_state() {
local abbrev value
abbrev=$(dpkg-query -W -f='${db:Status-Abbrev}' unattended-upgrades 2>/dev/null || true)
if [[ $abbrev != ii* ]]; then
printf 'not-installed'
return 0
fi
value=$(apt-config dump APT::Periodic::Unattended-Upgrade 2>/dev/null |
sed -n 's/^APT::Periodic::Unattended-Upgrade "\(.*\)";$/\1/p' | tail -n1 || true)
if [[ -n $value && $value != 0 ]]; then printf 'enabled'; else printf 'disabled'; fi
}
# Seconds since the file at $1 was modified, or empty if it doesn't exist.
file_age() {
local m
m=$(stat -c %Y "$1" 2>/dev/null) || return 0
printf '%s' $(($(date +%s) - m))
}
# apt.systemd.daily touches upgrade-stamp only when unattended-upgrade exits 0.
# unattended-upgrade writes its own stamp whenever a run gets far enough to know
# what it would do, even if it then fails (e.g. on a conffile prompt). So a newer
# run stamp than success stamp means it's running but failing.
UU_SUCCESS_STAMP=$ROOT/var/lib/apt/periodic/upgrade-stamp
UU_RUN_STAMP=$ROOT/var/lib/apt/periodic/unattended-upgrades-stamp
# Packages from its allowed origins it didn't upgrade (held, blacklisted, conffile
# prompt), space-separated; removed when there are none.
UU_KEPT_FILE=$ROOT/var/lib/unattended-upgrades/kept-back
# Ubuntu Pro state from the pro client's status cache, which it keeps
# world-readable (the token lives in private/ next to it). Prints "ATTACHED ESM"
# (e.g. "true enabled", "false -"); nothing if there's no file or it can't be
# read, as on Debian. Past standard support, only esm-infra keeps main patched.
PRO_STATUS_FILE=$ROOT/var/lib/ubuntu-advantage/status.json
ubuntu_pro() {
[[ -r $PRO_STATUS_FILE ]] || return 0
command -v python3 >/dev/null || return 0
python3 -I -c '
import json, re, sys
d = json.load(open(sys.argv[1]))
attached = d.get("attached") is True
esm = next((s.get("status") for s in d.get("services") or []
if isinstance(s, dict) and s.get("name") == "esm-infra"), None)
esm = esm if attached and isinstance(esm, str) and re.fullmatch(r"[a-z/-]{1,20}", esm) else "-"
print("true" if attached else "false", esm)
' "$PRO_STATUS_FILE" 2>/dev/null || true
}
uptime_seconds() { uptime_seconds() {
local up _ local up _
[[ -r $ROOT/proc/uptime ]] || return 0 [[ -r $ROOT/proc/uptime ]] || return 0
@@ -233,7 +480,9 @@ uptime_seconds() {
} }
build_report() { build_report() {
local running newest kernels sim inst 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 up_dl='' up_grow='' arch_free='' arch_mount='' usr_free='' usr_mount=''
running=$(uname -r) running=$(uname -r)
kernels=$(installed_kernels) kernels=$(installed_kernels)
@@ -241,7 +490,15 @@ build_report() {
read_needrestart read_needrestart
read_livepatch read_livepatch
sim=$(apt_simulation) sim_err=$(mktemp)
if sim=$(apt_simulation "$sim_err"); then
:
else
rc=$?
apt_ok=0 sim=
apt_err=$(apt_error "$rc" <"$sim_err")
fi
rm -f "$sim_err"
inst=$(grep '^Inst ' <<<"$sim" || true) inst=$(grep '^Inst ' <<<"$sim" || true)
if [[ -e $ROOT/run/reboot-required ]]; then if [[ -e $ROOT/run/reboot-required ]]; then
@@ -249,6 +506,14 @@ build_report() {
[[ -r $ROOT/run/reboot-required.pkgs ]] && reboot_pkgs=$(sort -u "$ROOT/run/reboot-required.pkgs") [[ -r $ROOT/run/reboot-required.pkgs ]] && reboot_pkgs=$(sort -u "$ROOT/run/reboot-required.pkgs")
fi 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 '{' printf '{'
printf '"agent_version":%s,' "$(json_str "$AGENT_VERSION")" printf '"agent_version":%s,' "$(json_str "$AGENT_VERSION")"
printf '"reported_hostname":%s,' "$(json_str "${REPORT_HOSTNAME:-$(hostname -f 2>/dev/null || hostname)}")" printf '"reported_hostname":%s,' "$(json_str "${REPORT_HOSTNAME:-$(hostname -f 2>/dev/null || hostname)}")"
@@ -262,6 +527,9 @@ build_report() {
printf '"kernel_newest_installed":%s,' "$(json_str "$newest")" printf '"kernel_newest_installed":%s,' "$(json_str "$newest")"
printf '"needrestart_ksta":%s,' "$(json_int "$NR_KSTA")" printf '"needrestart_ksta":%s,' "$(json_int "$NR_KSTA")"
printf '"needrestart_kexp":%s,' "$(json_str "$NR_KEXP")" printf '"needrestart_kexp":%s,' "$(json_str "$NR_KEXP")"
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 if ((NR_OK)); then
printf '"services_need_restart":%s,' "$(sort -u <<<"$NR_SVCS" | json_str_array)" printf '"services_need_restart":%s,' "$(sort -u <<<"$NR_SVCS" | json_str_array)"
printf '"sessions_need_restart":%s,' "$NR_SESS" printf '"sessions_need_restart":%s,' "$NR_SESS"
@@ -270,16 +538,45 @@ build_report() {
fi fi
printf '"reboot_required":%s,' "$(json_bool "$reboot_file")" printf '"reboot_required":%s,' "$(json_bool "$reboot_file")"
printf '"reboot_required_pkgs":%s,' "$(json_str_array <<<"$reboot_pkgs")" printf '"reboot_required_pkgs":%s,' "$(json_str_array <<<"$reboot_pkgs")"
printf '"upgradable_count":%s,' "$(json_int "$(grep -c . <<<"$inst" || true)")" if ((apt_ok)); then
printf '"security_count":%s,' "$(json_int "$(grep -ci 'security' <<<"$inst" || true)")" printf '"upgradable_count":%s,' "$(json_int "$(grep -c . <<<"$inst" || true)")"
printf '"phased_packages":%s,' "$(phased_packages <<<"$sim" | json_str_array)" printf '"security_count":%s,' "$(json_int "$(grep -ci 'security' <<<"$inst" || true)")"
printf '"kernel_upgradable":%s,' "$(awk '$2 ~ /^linux-image-/ { print $2 }' <<<"$inst" | json_str_array)" printf '"phased_packages":%s,' "$(phased_packages <<<"$sim" | json_str_array)"
printf '"kernel_upgradable":%s,' "$(awk '$2 ~ /^linux-image-/ { print $2 }' <<<"$inst" | json_str_array)"
else
printf '"upgradable_count":null,"security_count":null,"phased_packages":null,"kernel_upgradable":null,'
fi
printf '"apt_simulation_ok":%s,' "$(json_bool "$apt_ok")"
printf '"apt_simulation_error":%s,' "$(json_str_or_null "$apt_err")"
printf '"livepatch_state":%s,' "$(json_str_or_null "$LP_STATE")" printf '"livepatch_state":%s,' "$(json_str_or_null "$LP_STATE")"
printf '"livepatch_check_state":%s,' "$(json_str_or_null "$LP_CHECK")" printf '"livepatch_check_state":%s,' "$(json_str_or_null "$LP_CHECK")"
printf '"livepatch_supported":%s,' "$(json_str_or_null "$LP_SUPPORTED")" printf '"livepatch_supported":%s,' "$(json_str_or_null "$LP_SUPPORTED")"
printf '"livepatch_upgrade_required":%s,' "$(json_str_or_null "$LP_UPGRADE")" printf '"livepatch_upgrade_required":%s,' "$(json_str_or_null "$LP_UPGRADE")"
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_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,' ;;
esac
printf '"ubuntu_esm_infra":%s,' "$(json_str_or_null "$pro_esm")"
printf '"unattended_upgrades":%s,' "$(json_str "$(unattended_upgrades_state)")"
printf '"unattended_upgrades_success_age_seconds":%s,' "$(json_int "$(file_age "$UU_SUCCESS_STAMP")")"
printf '"unattended_upgrades_run_age_seconds":%s,' "$(json_int "$(file_age "$UU_RUN_STAMP")")"
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 '"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 '"uptime_seconds":%s' "$(json_int "$(uptime_seconds)")"
printf '}\n' printf '}\n'
} }
+26 -6
View File
@@ -10,16 +10,36 @@ After=network-online.target
[Service] [Service]
Type=oneshot Type=oneshot
# Same as `apt-get update`: downloads lists, installs nothing. A failure (no # 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 # network, lock held by an admin's apt run) fails this unit but not the report,
# dashboard flags lists that stay old. # since kernelwatch-agent.service only Wants= it. The stamp then stops moving
ExecStart=-/usr/bin/apt-get -q update # 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 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
# keeps root but loses everything apt update doesn't touch. # runs as root (the default) but loses everything apt update doesn't touch.
User=root # 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 NoNewPrivileges=yes
ProtectHome=yes ProtectHome=yes
PrivateTmp=yes PrivateTmp=yes
+3
View File
@@ -8,6 +8,9 @@ ConditionPathExists=/usr/sbin/needrestart
Type=oneshot Type=oneshot
# -b batch output, -r l list only: never restarts anything. # -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' 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 RuntimeDirectory=kernelwatch
RuntimeDirectoryMode=0755 RuntimeDirectoryMode=0755
RuntimeDirectoryPreserve=yes 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"
+247
View File
@@ -0,0 +1,247 @@
# Agents
[← kernelwatch](../README.md)
Installing the agent on hosts, one at a time or across the whole fleet.
## Adding a host
On the server:
```sh
sudo kernelwatch add-host web01
# prints a token, shown once
```
On the host (copy the `agent/` directory over, or clone the repo):
```sh
sudo ./agent/install.sh --server https://kernelwatch.example.internal [--ca root.pem]
# paste the token when prompted
```
The installer puts the agent in `/usr/local/sbin`, writes `/etc/kernelwatch/agent.conf`
and `agent.token` (root, 0600), enables `kernelwatch-agent.timer` and sends a first
report. After that, the agent reports 2 minutes after boot and then hourly, with up
to 15 minutes of jitter.
For unattended installs, set `KERNELWATCH_TOKEN=...` instead of using the prompt.
Add `--with-needrestart` to also report services needing a restart (Debian
needs this; Ubuntu already has needrestart). It installs needrestart if
missing and sets it to *list* services after apt upgrades instead of asking
interactively. Delete `/etc/needrestart/conf.d/kernelwatch.conf` to undo that.
Add `--with-apt-update` to refresh apt's package lists before each report
(recommended on Debian, see "Fresh package lists" in [How it works](how-it-works.md)). It's the same as running `apt update`
hourly: lists only, nothing is installed. If apt is busy, the refresh is
skipped and the report goes ahead. `--without-apt-update` turns it off;
re-running the installer with neither keeps the current setting.
Useful on a host:
```sh
sudo kernelwatch-agent --print # see exactly what would be sent
sudo systemctl start kernelwatch-agent # report now
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
checkout, so hosts need neither git nor Gitea access. Set it up once:
```sh
cp agent/deploy.conf.example agent/deploy.conf # SERVER_URL, DASHBOARD (ssh target)
cp agent/hosts.example agent/hosts # optional; --register fills it in
```
Then:
```sh
agent/deploy.sh --register web01 db01 # register on the dashboard + install
agent/deploy.sh # upgrade every host in agent/hosts
agent/deploy.sh web01 # upgrade one
agent/deploy.sh --rotate web01 # new token, reinstall
agent/deploy.sh --dry-run # show the plan
agent/deploy.sh -- --with-needrestart # pass options through to install.sh
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
`install.sh`, which sends a first report, then deletes the temp directory.
With `--register`/`--rotate`, it also runs
`sudo kernelwatch add-host --token-only` on the dashboard host and passes the
token to the host on SSH stdin. The token never appears on a command line or
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
a jump host in `~/.ssh/config` and `deploy.sh` works unchanged:
```
Host zeus
ProxyJump eurus
```
+116
View File
@@ -0,0 +1,116 @@
# Alerts and monitoring
[← kernelwatch](../README.md)
ntfy notifications for stale hosts, pending reboots and updates, plus heartbeat monitoring so you find out if kernelwatch itself stops.
## Stale-host, reboot and update alerts (ntfy)
The server can notify an [ntfy](https://ntfy.sh/) topic when a host stops
reporting and when its reports resume. Agents report hourly with up to 15 minutes
of jitter. Alerts use the same `stale_after_hours` as the dashboard (3 hours by
default), leaving room for ordinary delays. Newly registered hosts get that same
grace period to send their first report.
Re-run `sudo ./server/install.sh` to install the alert timer when upgrading.
The installer preserves your existing config, so add these settings to
`/etc/kernelwatch/server.toml`:
```toml
ntfy_url = "https://ntfy.example.com/kernelwatch"
ntfy_token = "" # optional access token with publish permission for this topic
ntfy_timeout_seconds = 10.0
```
Subscribe to that topic in your ntfy app, then check delivery:
```sh
sudo kernelwatch test-alert
systemctl list-timers kernelwatch-alerts.timer
```
`kernelwatch-alerts.timer` runs a separate, unprivileged check every five minutes,
even when no hosts report and nobody opens the dashboard. Notifications normally
arrive within about five minutes of crossing the stale threshold or receiving a
fresh report. Run `sudo kernelwatch check-alerts` to check immediately, or inspect
`journalctl -u kernelwatch-alerts.service` for delivery failures.
- Each host gets one stale notification and one reporting-recovery notification
per detected outage. Successful sends are saved in SQLite, so routine checks
and server restarts don't repeat them. Recovery confirms reporting has resumed;
the host may still need updates or a reboot.
- Failed sends are retried on the next check, and a failure for one host doesn't
stop checks for the others. A recovery is sent only after a stale notification
was successfully delivered. A timeout or crash after ntfy accepted a message
can cause a duplicate on retry.
- An empty `ntfy_url` disables notifications. The timer reads its configuration
on every run; changing ntfy settings needs no restart. If you change
`stale_after_hours`, restart `kernelwatch.service` too so the dashboard uses the
new threshold.
- **Reboot and update alerts.** A host that has stayed in `reboot` or `update`
for `status_alert_after_hours` (default 24) gets one notification listing the
reasons shown on the dashboard. The clock starts when the host entered that
status, so hourly reports don't restart it. Fixing the host (back to `ok`)
re-arms it. Going from `update` to `reboot` notifies again after another
period; going back down doesn't. Stale hosts are skipped, since the stale
alert covers them. Set `status_alert_after_hours = 0` to turn these off.
Upgrading starts the clock at the first check, so expect the first
notifications a day after you re-run `install.sh`.
- **Livepatch alerts.** On Ubuntu hosts using
[Livepatch](how-it-works.md), a host whose live patching has been broken for
`livepatch_alert_after_hours` (default 6) gets one high-priority notification:
an unhealthy state (not `applied` or `nothing-to-apply`), a failed check, or an
unsupported kernel. It also fires when a host that *used to* report Livepatch
stops, which is what a dead Livepatch daemon looks like, since the agent then has
nothing to send. Hosts that have never reported Livepatch never alert. As with the
other alerts it's once per problem; getting healthy again re-arms it, and a brief
blip that clears within the period sends nothing. Stale hosts are skipped. A host
where you turn Livepatch off on purpose sends one message and then stays quiet.
`livepatch_alert_after_hours = 0` turns these off.
Use the topic's direct publish URL, with token authentication if needed; it must
accept the POST without a browser login or redirect. The topic and token stay
in the server config (root-owned, readable by the `kernelwatch` service group).
Agents need no changes.
## Heartbeat: is kernelwatch itself running?
Every alert above depends on `kernelwatch-alerts.timer` running on the dashboard
host. If that host is down, or the timer breaks, nothing tells you. A heartbeat
fixes this: kernelwatch pings an external monitor, and the monitor alerts when the
pings **stop**. [healthchecks.io](https://healthchecks.io) has a free tier;
Uptime Kuma's push monitors work the same way.
1. In the monitor, create two checks and copy their ping URLs:
- **alerts**: period 5 minutes, grace 20 minutes.
- **backup**: period 1 day, grace a few hours (the timer fires about 03:30 and
can be up to 30 minutes late).
2. Add the URLs to `/etc/kernelwatch/server.toml` (no restart needed for the
alert check or the backup; they read it on every run):
```toml
heartbeat_url = "https://hc-ping.com/<uuid>"
backup_heartbeat_url = "https://hc-ping.com/<other-uuid>"
```
3. Check both: `sudo kernelwatch test-heartbeat` pings each configured URL once.
What counts as a heartbeat:
- `heartbeat_url` is pinged at the end of every alert check (every five minutes)
that sent all its notifications. If ntfy delivery is failing, the ping is
skipped on purpose, so the monitor also notices a broken alert pipeline. It's
pinged even with no `ntfy_url`, since the timer is still alive.
- `backup_heartbeat_url` is pinged after each successful nightly backup, so a
timer that never ran, or a backup that failed, shows up as a missing ping.
A manual `kernelwatch backup` doesn't ping.
- A heartbeat that can't be delivered is logged (status code or error type, never
the URL) and never fails the check or the backup.
The pings leave from the dashboard host, so a dead host is exactly what stops
them. Set the monitor to notify you some way that doesn't depend on that host:
email, the monitor's own app, or ntfy.sh. Not a ntfy server running behind it.
The URLs are secrets (whoever has one can fake a heartbeat), so keep
`server.toml` readable by root and the `kernelwatch` group only.
+44
View File
@@ -0,0 +1,44 @@
# Development
[← kernelwatch](../README.md)
Running the tests and a local server.
```sh
make test # unit + integration tests (stdlib unittest)
make lint # shellcheck, if available
```
Gitea Actions (`.gitea/workflows/ci.yml`) runs both on every push to `main`
and every pull request: the tests on Python 3.10–3.13 (the versions on the
supported Ubuntu and Debian releases) and shellcheck on the shell scripts.
The tests run a real server on an ephemeral port. They also run the real agent
script against stubbed `dpkg-query`/`apt-get`/`needrestart`/`uname` and a fake
filesystem root (`KERNELWATCH_ROOT`), including one end-to-end agent → server
report.
Both installers (`agent/install.sh`, `server/install.sh`) run for real in the tests
against a fake root: `KERNELWATCH_ROOT` prefixes every path they write and skips
their root check, and `systemctl`, `apt-get`, `useradd` and the like are stubs that
log their arguments. Don't set it on a real host.
`tests/test_docs.py` checks that every relative link and `#anchor` in the README
and `docs/` resolves, so move or rename a heading and it tells you what broke.
Run a local server against a scratch database:
```sh
printf 'db_path = "/tmp/kw.db"\nsecure_cookies = false\n' > /tmp/kw.toml
export KERNELWATCH_CONFIG=/tmp/kw.toml
./server/kernelwatch-server set-password admin
./server/kernelwatch-server serve # http://127.0.0.1:8080
```
## Ideas for later
- Additional notification channels
- An HTTP endpoint for `kernelwatch status`, behind a hashed API token and your
proxy's IP allow-list, if something has to poll remotely (the CLI already
covers scripting on the dashboard host)
- Grouping or tagging hosts (prod/staging, location)
+223
View File
@@ -0,0 +1,223 @@
# How it works
[← kernelwatch](../README.md)
How each host's status is decided, and how the agent collects the facts behind it.
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, `/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
its full report and recent history.
How the agent works it out:
- **Running vs. installed kernel**, three ways:
- A newer `linux-image-*` installed than `uname -r` means a version upgrade.
- The build in `uname -v` (`Debian 6.12.57-1`, `#85-Ubuntu`, `#33~24.04.1-Ubuntu`)
is compared with the installed package version of the running kernel
(`6.12.57-1`, `6.8.0-85.85`, `6.14.0-33.33~24.04.1`). A mismatch means the
package was upgraded in place after boot; `uname -r` didn't change, but a
reboot is still needed.
- [`needrestart`](https://github.com/liske/needrestart)'s kernel result, for
build strings the server doesn't recognise (see "Services needing a restart", below).
- **Services needing a restart** (e.g. nginx still using the old OpenSSL
after an upgrade): from `needrestart -b`, if it's installed. Ubuntu ships it;
on Debian, install with `install.sh --with-needrestart`. Without it, the
Services column shows `?` and status isn't affected. needrestart has to
inspect every process, so it runs as root in its own unit,
`kernelwatch-needrestart.service`. That unit has no network access, only the
two capabilities needrestart needs, and list-only mode, so it never restarts
anything. It writes its results to `/run/kernelwatch/needrestart`, and the
unprivileged agent unit runs it just before each report and reads the file.
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
`nothing-to-apply`, checked, supported), a pending kernel reboot, or a
`/run/reboot-required` caused only by `linux-*` packages, shows as a note
instead of `reboot`, and the note gives the date by which the kernel must be
upgraded. Livepatch only fixes high and critical CVEs, and only until that
date, so cover ends 14 days before it and the host goes to `reboot` as usual.
Any other reboot reason (libc, systemd) still counts. If Livepatch is failing,
unsupported or in a state we don't know, the host gets no cover and the reason
is noted, and after `livepatch_alert_after_hours` you get an
[ntfy alert](alerts.md). Hosts without Livepatch are unaffected. `canonical-livepatch` needs
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.
- **Hostname check**: each report includes the host's own name. If its first
DNS label differs from the name the host is registered under (ignoring case),
the row gets a note: "registered as web01 but reports itself as db01". This
catches a token copied to the wrong machine. It never changes the status. A
host you registered under a custom label (`<ssh target> <name>` in
`agent/hosts`) shows the note until you tell its agent which name to report:
`agent/deploy.sh iris -- --report-hostname iris` (or `install.sh
--report-hostname iris` on the host, which sets `REPORT_HOSTNAME` in
`agent.conf`). Upgrades and `--rotate` keep it;
`--default-report-hostname` removes it. That's the host's own say-so, so it
only silences the note for hosts you've deliberately named.
- **Available updates**: a simulated `apt-get dist-upgrade`. It is read-only, takes
no locks and writes no cache files. `dist-upgrade` is used so that new-ABI kernel
packages pulled in by the meta-package show up. Lines whose origin contains
`-security` count as security updates. If the simulation fails (unmet
dependencies, a broken sources entry, a damaged package cache), apt prints no
updates at all, so the agent reports the counts as unknown along with apt's
error, and the host goes to `update` with "apt can't work out pending updates".
Agents before 0.5.0 can't tell a failure from "no updates".
- **Room for the next kernel**: each kernel adds an image and an initramfs to
`/boot`, often over 100 MB together. When `/boot` fills up, the new kernel's
install fails half-way, apt is left broken, and the host quietly stays on its
old kernel. The agent reports the size and free space of the filesystem holding
`/boot` (from `df`; the root filesystem when `/boot` isn't separate). Under
`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
usually left by a failed install script, often because `/boot` was full. They
put the host in `update` with "N packages not fully installed". Fix it on the
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
(`server/kernelwatch/support.py`): for Debian, the end of
[LTS](https://wiki.debian.org/LTS), which carries on from regular security
support through the same repository; for Ubuntu, the end of standard support,
or with [ESM](https://ubuntu.com/security/esm) (`esm-infra`, part of Ubuntu Pro,
free for personal use) the end of ESM. The agent reads whether ESM is on from the
Ubuntu Pro client's public status file, `/var/lib/ubuntu-advantage/status.json`.
A host past its date is in `update` ("Debian 11 security support ended
2026-08-31"); in the `os_eol_warn_days` (default 90) before it, the row gets a
note. An Ubuntu host with ESM enabled gets no warning when standard support
ends, only before ESM does. The host page shows the dates. They're a table in
the server, so they need a kernelwatch update when a new release ships;
a release the table doesn't know is noted. Agents before 0.7.0 don't report
ESM, so an Ubuntu host on one counts as having none.
- **unattended-upgrades**: Ubuntu Server enables it by default, and when it breaks
(a conffile prompt, a held package, a disabled timer) nothing shows until
security updates pile up. For hosts where it's **enabled** (the package is
installed and `APT::Periodic::Unattended-Upgrade` isn't `0`; leftover config
from a removed package doesn't count), the agent reports two timestamps from
`/var/lib/apt/periodic/`: `upgrade-stamp`, which apt's daily job touches only
when unattended-upgrades exits successfully, and `unattended-upgrades-stamp`,
which unattended-upgrades writes whenever a run gets far enough, even if it then
fails. No success in `unattended_upgrades_stale_after_days` (default 3) puts the
host in `update`, and the reason says which way it broke: "is failing" (it
runs, so read `/var/log/unattended-upgrades/` on the host) or "hasn't run" (check
`systemctl status apt-daily-upgrade.timer`). Packages it keeps back (held,
blacklisted, waiting on a conffile prompt) from
`/var/lib/unattended-upgrades/kept-back` are noted. Hosts where it's disabled or
not installed aren't affected; the host page shows which. It assumes the stock
`apt-daily-upgrade.timer` runs it: if you run `unattended-upgrade` from cron or
Ansible instead, the stamp isn't updated, so set
`unattended_upgrades_stale_after_days = 0`. Agents before 0.8.0 don't report it.
- **Fresh package lists**: the simulation only knows what apt's package lists
say, and the agent can't refresh them itself. Ubuntu refreshes them about once
a day. Debian doesn't by default unless `unattended-upgrades` is set up, so a
new kernel or security update can stay invisible until someone runs
`apt update`. Install with `--with-apt-update` and
`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
their own Phased column (hover for the packages, `–` on Debian), with the
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 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.
+107
View File
@@ -0,0 +1,107 @@
# Operations
[← kernelwatch](../README.md)
Day-to-day tasks: querying the fleet from a script, and backing up the database.
## Scripting: `kernelwatch status`
`kernelwatch status` prints the fleet the way the dashboard shows it, from the
database, with no network port or token involved. It needs `sudo`, like the other
[admin commands](server.md#admin-commands). Run it over SSH from anywhere else.
```
$ sudo kernelwatch status
stale new01 ? (last seen never)
- never reported
reboot web01 6.8.0-136 -> 6.8.0-138 (last seen 1m ago)
- kernel: running 6.8.0-136, 6.8.0-138 installed
- 2 security updates pending
ok db01 6.12.57 (last seen 1m ago)
3 hosts: 1 stale, 1 reboot, 0 update, 1 ok
```
Hosts come worst first, in the dashboard's order, and use the same status logic
(Livepatch cover, the hostname note and so on). Narrow it with `--host NAME` and
`--level stale|reboot|update|ok` (repeatable); both also work with `--json`.
`--json` is for scripts. It has `generated_at`, `counts` and `hosts`. The counts
always cover the whole fleet, and the filters only trim `hosts`. Each host has `name`,
`status`, `reasons`, `last_report_at` (UTC ISO 8601, or `null` if it never
reported), `last_report_age_seconds`, `os`, `kernel_running`,
`kernel_newest_installed`, `reboot_required`, `updates_pending`,
`security_updates`, `kernel_updates`, `services_need_restart`, `livepatch`
(or `null`), `uptime_seconds` and `agent_version`. Fields a host hasn't
reported are `null`, and the keys are always present. It never includes tokens
or password hashes.
```sh
# hosts that need a reboot
sudo kernelwatch status --json | jq -r '.hosts[] | select(.status=="reboot") | .name'
# one line per host that needs attention, with the reasons
sudo kernelwatch status --json --level reboot --level update |
jq -r '.hosts[] | "\(.name): \(.reasons | join("; "))"'
# from your workstation; exits non-zero (for cron or a monitor) if any host is stale
ssh triton 'sudo kernelwatch status --json' | jq -e '.counts.stale == 0' >/dev/null
```
There's deliberately no HTTP endpoint for this. It would expose every host's
kernel and pending security updates to anything holding a token, and nothing
needs it yet. If something has to poll remotely, add one behind your proxy's
IP allow-list rather than relying on a token alone.
## Backups
Everything kernelwatch knows lives in one SQLite file, `/var/lib/kernelwatch/kernelwatch.db`:
host tokens (hashed), dashboard logins and report history. Without it you'd
re-register every host and reinstall its token. Don't copy the file while the
server runs, since recent writes can sit in its `-wal` sidecar. Use:
```sh
sudo kernelwatch backup /var/lib/kernelwatch/backups/kernelwatch.db
```
This uses SQLite's online backup, so it's safe while hosts are reporting. It
replaces any existing file at that path and writes it mode 0600. It refuses to
overwrite the live database. The command runs as the `kernelwatch` user, so the
destination directory has to be writable by it (create one with
`sudo install -d -o kernelwatch -g kernelwatch -m 0700 /var/lib/kernelwatch/backups`),
then copy the result off the machine with your usual backup tool.
### Nightly backups
`server/install.sh` also enables `kernelwatch-backup.timer`, which runs
`kernelwatch scheduled-backup` at about 03:30 (up to 30 minutes late; a run missed
while the machine was off happens at the next boot). It writes
`/var/lib/kernelwatch/backups/kernelwatch-YYYY-MM-DD.db` (UTC date, mode 0600,
directory 0700) and then deletes dated backups that are `backup_keep_days` (default
7) or more days old. It deletes only files with exactly that name, and only after
the new backup succeeded, so a failing run never costs you the ones you have. Set
`backup_keep_days = 0` to keep them all. The unit can only write under
`/var/lib/kernelwatch`, so keep `backup_dir` there unless you give it more access.
```sh
systemctl list-timers kernelwatch-backup.timer
journalctl -u kernelwatch-backup # a failed run shows up here
sudo systemctl start kernelwatch-backup # back up now
```
If a run fails, whether from an error, the 10-minute timeout, an out-of-memory
kill or a crash, systemd starts `kernelwatch-backup-failed.service`
(`OnFailure=`), which sends a high-priority message to your ntfy topic naming the
newest backup still on disk. The cause is in `journalctl -u kernelwatch-backup`.
Without `ntfy_url` it only logs that it had nothing to send to. If ntfy itself is
unreachable at that moment, the failure shows up only in the journal
(`journalctl -u kernelwatch-backup-failed`). It can't tell you that the timer
never ran at all, for example because the host was down; that needs a [heartbeat
monitor](alerts.md#heartbeat-is-kernelwatch-itself-running). You can check delivery with
`sudo kernelwatch notify-backup-failure`, which sends the same message.
These copies sit on the dashboard host, so they protect against a corrupted or
mistakenly changed database but not against losing the machine. Copy
`/var/lib/kernelwatch/backups/` elsewhere with whatever you already back up with.
To restore, stop the service, put the file at `db_path` owned by `kernelwatch`
(mode 0600), and start it again. The stale-alert state restores with it.
+190
View File
@@ -0,0 +1,190 @@
# Reverse proxy and access control
[← kernelwatch](../README.md)
How to put TLS, and optionally extra access control, in front of the server.
## TLS reverse proxy
The server speaks plain HTTP on `127.0.0.1:8080`. Put a TLS proxy in front of it.
The agents and your browser both connect through it.
**Caddy** (simplest):
```caddyfile
kernelwatch.example.internal {
reverse_proxy 127.0.0.1:8080
}
```
**nginx**:
```nginx
server {
listen 443 ssl;
server_name kernelwatch.example.internal;
# ssl_certificate / ssl_certificate_key ...
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
```
With either proxy, set `trust_proxy_headers = true` in `server.toml` so login
rate limiting sees real client IPs.
If you use a private CA (e.g. Caddy's `tls internal`), give the agents its
root cert with `--ca` (see [Agents](agents.md#adding-a-host)).
You can expose only `/api/v1/report` to the fleet network and keep the
dashboard on a VPN or tailnet. That's a proxy rule, not a kernelwatch setting.
## CloudPanel
CloudPanel gives each site its own Linux user and a document root at
`/home/<site-user>/htdocs/<domain>/`. kernelwatch doesn't use that directory.
nginx forwards requests to the app; it doesn't serve kernelwatch's files. Install
with `server/install.sh` as in [Server](server.md), so the app runs as the `kernelwatch` user
with its data in `/var/lib/kernelwatch`, outside every site user's home. Leave
the document root empty, and keep your clone of this repo out of `htdocs`.
1. **Pick a free port.** CloudPanel's Varnish setup can run an nginx backend
on 8080. Check with `ss -ltnp | grep ':8080\b'`. If it's taken, set another port
in `/etc/kernelwatch/server.toml` and restart (`sudo systemctl restart kernelwatch`):
```toml
listen_port = 8095
trust_proxy_headers = true
```
Check it: `curl -s http://127.0.0.1:8095/healthz` should print `ok`.
2. **Create the site as a Reverse Proxy.** In CloudPanel: *Add Site → Create a
Reverse Proxy*, with your domain and Reverse Proxy URL
`http://127.0.0.1:8095`. CloudPanel can't change an existing site's type. If
the domain already exists as a PHP or static site, delete and recreate it.
Deleting a site also removes its site user and home directory, so move
anything you need out first.
3. **TLS.** In the site's *SSL/TLS* tab, issue a Let's Encrypt certificate. Agents
then need no `--ca`.
4. **Check the generated vhost** (the site's *Vhost* tab). The `location`
that proxies to the app should pass the original `Host` header and the
client address:
```nginx
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
```
Add them if they're missing. Without `Host`, logins fail the origin check
with "cross-origin request refused". Without `X-Forwarded-For`, every login
appears to come from 127.0.0.1, so one person's failed attempts lock everyone out.
Also check that the login page is styled. If `/static/style.css` returns 404,
a static-file `location` in the template is looking in the empty document root
instead of proxying. Make it fall through to the proxy, or remove it.
5. **Optionally restrict the dashboard.** The site's domain is public, so the
login page is reachable from the internet unless you limit it. Agents only
need `/api/v1/report`. In the Vhost tab, add an `allow <your IP>; deny all;`
to `location /` and a separate unrestricted
`location = /api/v1/report { proxy_pass http://127.0.0.1:8095; }`.
Changes made in the Vhost tab persist. Back them up before
recreating the site.
To require a login through Authelia instead of an IP allowlist, see
[Authelia (forward auth)](#authelia-forward-auth).
## Authelia (forward auth)
If you already run [Authelia](https://www.authelia.com/), you can put it in
front of the dashboard. That adds Authelia's 2FA and single sign-on, and
kernelwatch's own login still applies behind it. You log in to both, but
Authelia's remember-me makes that rare. This uses nginx's `auth_request`, so
you don't need an OIDC client.
**Agents must bypass Authelia.** They authenticate with their bearer token and
can't follow a login redirect. If Authelia covers `/api/v1/report`, every
report gets a redirect instead of a 401 or 204, and the whole fleet goes stale
within 3 hours.
1. **Authelia `access_control`.** Rules are checked in order, so put the bypass
first, and keep a single `rules:` list:
```yaml
access_control:
default_policy: two_factor
rules:
- domain: kernelwatch.example.com
resources:
- '^/api/v1/report$'
- '^/healthz$'
policy: bypass
- domain: "*.example.com"
policy: two_factor
```
For the redirect to the login page to work, your `session.cookies` entry has
to cover the dashboard's domain and set `authelia_url`. Without them, browsers
get a bare 401 page. Authelia reads this file only at startup, so restart it
after editing (in Kubernetes: `kubectl rollout restart deployment/authelia`).
Check the file first with `authelia validate-config`.
2. **nginx.** Add an internal location for Authelia's check, an exact-match
location for the agents with no check, and the check on `location /`.
For CloudPanel, edit the site's *Vhost* tab: leave the template's
`@reverse_proxy` block alone and add or replace these:
```nginx
# Authelia's check (internal subrequest only)
location = /internal/authelia/authz {
internal;
proxy_pass https://auth.example.com/api/authz/auth-request;
proxy_http_version 1.1;
proxy_ssl_server_name on;
proxy_set_header Host auth.example.com;
proxy_set_header X-Original-Method $request_method;
proxy_set_header X-Original-URL $scheme://$http_host$request_uri;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Content-Length "";
proxy_set_header Connection "";
proxy_pass_request_body off;
}
# Agents: token auth only
location = /api/v1/report {
try_files $uri @reverse_proxy;
}
# Dashboard: Authelia first, then kernelwatch's login
location / {
auth_request /internal/authelia/authz;
auth_request_set $redirection_url $upstream_http_location;
error_page 401 =302 $redirection_url;
try_files $uri @reverse_proxy;
}
```
Without CloudPanel, use `proxy_pass http://127.0.0.1:8095;` plus the `Host`
and `X-Forwarded-For` headers in place of `try_files ... @reverse_proxy`. If
Authelia runs on the same machine, point the check straight at it (e.g.
`http://127.0.0.1:9091/api/authz/auth-request`) and drop the
`proxy_ssl_server_name` and `Host` lines. Keep `location ^~ /.well-known`
unprotected so certificate renewals still work. If something monitors
`/healthz`, give it an exact-match location like the agents' one.
3. **Check it.**
```sh
curl -sI https://kernelwatch.example.com/ | head -3
# 302, Location pointing at Authelia
curl -si -X POST https://kernelwatch.example.com/api/v1/report | head -1
# 401 from kernelwatch (no token), not a 302
```
Then run `sudo systemctl start kernelwatch-agent` on one host and check
that its *Last seen* updates. If the POST gets a 302, the agents' location
isn't matching. Fix that before the fleet goes stale.
+43
View File
@@ -0,0 +1,43 @@
# Security notes
[← kernelwatch](../README.md)
How kernelwatch is locked down, and what it deliberately can't do.
- **Host identity comes from the token, not the payload.** A host can only
report as itself. Tokens are 256-bit random values; only their SHA-256 is stored.
- **Report rate limit.** A report arriving less than `report_min_interval_seconds`
(default 30) after the host's previous one gets HTTP 429 with a `Retry-After`
header, and isn't stored. So a stuck agent or a leaked token can't flood the
database or push real history off the host page. The agent's curl waits out the
`Retry-After` and retries, so running `systemctl start kernelwatch-agent` twice
in a row just pauses briefly. Set it to `0` to disable.
- **Livepatch status** runs in a separate root unit with no network access and a
read-only filesystem. It has no capability bound, syscall filter or
`NoNewPrivileges`, because the snap's setuid `snap-confine` can't run under
them (tested: `NoNewPrivileges=yes` fails with "cannot change profile for the
next exec call"). It only runs `canonical-livepatch status`.
- **needrestart** runs in a separate root unit with `PrivateNetwork=yes`, a
capability set of just `CAP_SYS_PTRACE` + `CAP_DAC_READ_SEARCH` (to read other
processes' memory maps), a read-only filesystem except `/run/kernelwatch`,
and `-r l` (list, never restart).
- **apt-get update** (with `--with-apt-update`) runs as root with network
access, like apt's own `apt-daily.service`, but sandboxed: no access to home
directories, devices or kernel settings. apt drops to its `_apt` user for the
downloads, and nothing gets installed.
- **The server's timer units** (alert check, nightly backup, backup-failure
notice) run as the `kernelwatch` user with no capabilities and a syscall
filter, limited to Unix and IP sockets. They need outbound network access
for ntfy and the heartbeat pings, so `PrivateNetwork=` isn't an option
there; `tests/test_install.py` enforces that.
- **The agent** runs as a throwaway unprivileged user (`DynamicUser=yes`) with
no capabilities, a read-only filesystem view and a syscall filter. The token
reaches it through `LoadCredential=` and goes to curl on stdin, so it never
appears in a process listing.
- **The dashboard** uses scrypt-hashed passwords, server-side sessions,
`HttpOnly` + `Secure` + `SameSite=Strict` cookies, an Origin check on form
posts, per-IP login rate limiting, and a strict CSP. Everything a host
reports is HTML-escaped.
- **It's read-only by design.** The server can't make hosts do anything.
Adding remote actions (like "reboot this host") would turn it into a
remote-execution system; think hard before doing that.
+44
View File
@@ -0,0 +1,44 @@
# Server
[← kernelwatch](../README.md)
Installing and upgrading the dashboard server, and the admin commands.
## Install and upgrade
On the dashboard host:
```sh
git clone <this repo> && cd kernel-automation
sudo ./server/install.sh
sudo kernelwatch set-password admin # dashboard login
```
This installs to `/opt/kernelwatch` and keeps config in `/etc/kernelwatch/server.toml`
(see [`server/server.toml.example`](../server/server.toml.example)) and data in
`/var/lib/kernelwatch`. The `kernelwatch.service` unit runs it as the unprivileged
`kernelwatch` user. Re-run `install.sh` to upgrade; it keeps your config.
The server speaks plain HTTP on `127.0.0.1:8080`. Put a TLS reverse proxy in front
of it; [Reverse proxy and access control](reverse-proxy.md) has the setups. Then
[add hosts](agents.md), and set up [alerts](alerts.md) and
[backups](operations.md#backups).
## Admin commands
```
sudo kernelwatch add-host NAME register a host, print its token (--token-only for scripts)
sudo kernelwatch rotate-token NAME issue a new token (old one stops working)
sudo kernelwatch remove-host NAME delete a host and its history
sudo kernelwatch list-hosts hosts and when they last reported
sudo kernelwatch status [--json] fleet status like the dashboard (--host, --level to filter)
sudo kernelwatch set-password USER create a user / change password (logs out their sessions)
sudo kernelwatch remove-user USER
sudo kernelwatch list-users
sudo kernelwatch backup PATH write a consistent copy of the database (safe while running)
sudo kernelwatch scheduled-backup dated copy in backup_dir, then prune old ones (what the timer runs)
sudo kernelwatch notify-backup-failure send the failed-backup notification now (also runs on failure)
sudo kernelwatch check-alerts check for stale, recovered, reboot and update alerts now
sudo kernelwatch test-alert send a test notification to the configured ntfy topic
sudo kernelwatch test-heartbeat ping the configured heartbeat URLs once and report
```
+6 -3
View File
@@ -1,11 +1,11 @@
#!/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
# #
# Installs to /opt/kernelwatch, config in /etc/kernelwatch/server.toml (kept # Installs to /opt/kernelwatch, config in /etc/kernelwatch/server.toml (kept
# on upgrade), data in /var/lib/kernelwatch. Then put a TLS reverse proxy in # on upgrade), data in /var/lib/kernelwatch. Then put a TLS reverse proxy in
# front (see README) and create a dashboard user: sudo kernelwatch set-password admin # front (see docs/reverse-proxy.md) and create a dashboard user: sudo kernelwatch set-password admin
set -euo pipefail set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd) here=$(cd "$(dirname "$0")" && pwd)
@@ -44,11 +44,14 @@ fi
install -d -m 0750 -o kernelwatch -g kernelwatch "$root/var/lib/kernelwatch" install -d -m 0750 -o kernelwatch -g kernelwatch "$root/var/lib/kernelwatch"
install -m 0644 "$here/kernelwatch.service" "$root/etc/systemd/system/" install -m 0644 "$here/kernelwatch.service" "$root/etc/systemd/system/"
install -m 0644 "$here/kernelwatch-alerts.service" "$here/kernelwatch-alerts.timer" "$root/etc/systemd/system/" install -m 0644 "$here/kernelwatch-alerts.service" "$here/kernelwatch-alerts.timer" \
"$here/kernelwatch-backup.service" "$here/kernelwatch-backup.timer" \
"$here/kernelwatch-backup-failed.service" "$root/etc/systemd/system/"
systemctl daemon-reload systemctl daemon-reload
systemctl enable kernelwatch.service systemctl enable kernelwatch.service
systemctl restart kernelwatch.service systemctl restart kernelwatch.service
systemctl enable --now kernelwatch-alerts.timer systemctl enable --now kernelwatch-alerts.timer
systemctl enable --now kernelwatch-backup.timer
echo echo
echo "kernelwatch is running on $(grep -E '^listen_' "$root/etc/kernelwatch/server.toml" | tr '\n' ' ')" echo "kernelwatch is running on $(grep -E '^listen_' "$root/etc/kernelwatch/server.toml" | tr '\n' ' ')"
+38
View File
@@ -0,0 +1,38 @@
[Unit]
Description=Notify that the kernelwatch backup failed
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
User=kernelwatch
Group=kernelwatch
Environment=KERNELWATCH_CONFIG=/etc/kernelwatch/server.toml
ExecStart=/usr/bin/python3 -I /opt/kernelwatch/kernelwatch-server notify-backup-failure
TimeoutStartSec=2min
StateDirectory=kernelwatch
StateDirectoryMode=0750
CapabilityBoundingSet=
AmbientCapabilities=
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectClock=yes
ProtectHostname=yes
ProtectProc=invisible
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
LockPersonality=yes
MemoryDenyWriteExecute=yes
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
SystemCallArchitectures=native
SystemCallFilter=@system-service
UMask=0077
+40
View File
@@ -0,0 +1,40 @@
[Unit]
Description=Back up the kernelwatch database
# Any failure, including the timeout, an OOM kill or a crash, sends an ntfy
# message (a no-op if ntfy isn't configured).
OnFailure=kernelwatch-backup-failed.service
[Service]
Type=oneshot
User=kernelwatch
Group=kernelwatch
Environment=KERNELWATCH_CONFIG=/etc/kernelwatch/server.toml
ExecStart=/usr/bin/python3 -I /opt/kernelwatch/kernelwatch-server scheduled-backup
TimeoutStartSec=10min
StateDirectory=kernelwatch
StateDirectoryMode=0750
CapabilityBoundingSet=
AmbientCapabilities=
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectClock=yes
ProtectHostname=yes
ProtectProc=invisible
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
LockPersonality=yes
MemoryDenyWriteExecute=yes
# Network only for the backup_heartbeat_url ping after a successful backup.
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
SystemCallArchitectures=native
SystemCallFilter=@system-service
UMask=0077
+10
View File
@@ -0,0 +1,10 @@
[Unit]
Description=Nightly kernelwatch database backup
[Timer]
OnCalendar=*-*-* 03:30:00
RandomizedDelaySec=30min
Persistent=true
[Install]
WantedBy=timers.target
+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.4.1" AGENT_VERSION = "0.11.0"
+100 -1
View File
@@ -3,6 +3,7 @@
from __future__ import annotations from __future__ import annotations
import fcntl import fcntl
import socket
import sqlite3 import sqlite3
import sys import sys
import time import time
@@ -12,7 +13,7 @@ from urllib.request import HTTPRedirectHandler, Request, build_opener
from . import db from . import db
from .config import Config from .config import Config
from .status import LEVELS, evaluate from .status import LEVELS, evaluate, livepatch_problem
class DeliveryError(Exception): class DeliveryError(Exception):
@@ -52,6 +53,28 @@ def publish(cfg: Config, title: str, message: str, *, stale: bool = False,
raise DeliveryError(f"ntfy request failed ({type(exc).__name__})") from None raise DeliveryError(f"ntfy request failed ({type(exc).__name__})") from None
HEARTBEAT_TIMEOUT_SECONDS = 10.0
def ping(url: str) -> bool:
"""GET a heartbeat URL (healthchecks.io, Uptime Kuma push, ...). True if it answers 2xx.
The URL is a secret (whoever has it can fake a heartbeat), so errors say only what
went wrong, never the URL. A failure here must never break the work it reports on,
so callers log and carry on."""
try:
request = Request(url, headers={"User-Agent": "kernelwatch"}, method="GET")
# urllib raises HTTPError for anything but 2xx, and redirects aren't followed.
with build_opener(_NoRedirect()).open(request, timeout=HEARTBEAT_TIMEOUT_SECONDS):
return True
except HTTPError as exc:
print(f"kernelwatch: heartbeat returned HTTP {exc.code}", file=sys.stderr)
exc.close()
except (URLError, OSError, ValueError, HTTPException) as exc:
print(f"kernelwatch: heartbeat request failed ({type(exc).__name__})", file=sys.stderr)
return False
def _utc(timestamp: int | float) -> str: def _utc(timestamp: int | float) -> str:
return time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(timestamp)) return time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(timestamp))
@@ -76,6 +99,8 @@ def check(cfg: Config) -> int:
failures = _check_hosts(cfg, conn) failures = _check_hosts(cfg, conn)
if cfg.status_alert_after_hours > 0: if cfg.status_alert_after_hours > 0:
failures += _check_status(cfg, conn) failures += _check_status(cfg, conn)
if cfg.livepatch_alert_after_hours > 0:
failures += _check_livepatch(cfg, conn)
return failures return failures
finally: finally:
conn.close() conn.close()
@@ -158,3 +183,77 @@ def _check_status(cfg: Config, conn: sqlite3.Connection) -> int:
db.save_status_alert(conn, name, level, since, level) db.save_status_alert(conn, name, level, since, level)
print(f"kernelwatch: {level} notification sent for {name}") print(f"kernelwatch: {level} notification sent for {name}")
return failures return failures
def _check_livepatch(cfg: Config, conn: sqlite3.Connection) -> int:
"""Notify once per episode when Livepatch has been broken for the grace period.
Two cases: Livepatch reports an unhealthy state, or a host that used to report
Livepatch no longer does (its daemon died, or `canonical-livepatch status` fails,
so the agent has nothing to send). A host is only "used to" once it has reported
Livepatch, so hosts without it never alert. Getting healthy again forgets the
problem, so a later one alerts again. Stale hosts are skipped: their data can't
be trusted and the stale alert covers them."""
saved = db.livepatch_alerts(conn)
grace = cfg.livepatch_alert_after_hours * 3600
failures = 0
for h in db.latest_reports(conn):
name, report, now = h["host"], h["report"], time.time()
if evaluate(h["received_at"], report, now, cfg).level == "stale":
continue
state = report.get("livepatch_state")
if state is None and name not in saved:
continue
problem = (livepatch_problem(report) if state is not None
else "livepatch status is no longer being reported")
since, notified = saved.get(name, (None, False))
if problem is None:
current = (None, False)
else:
since = int(now) if since is None else since
current = (since, notified)
if not notified and now - since >= grace:
title = f"kernelwatch: {name} Livepatch problem"
if state is None:
detail = ("It reported Livepatch before and no longer does, so the Livepatch "
"daemon may have stopped or been disabled.")
else:
detail = (f"State: {state}, check: {report.get('livepatch_check_state') or '?'}, "
f"supported: {report.get('livepatch_supported') or '?'}.")
message = (f"{name}: {problem} since {_utc(since)}.\n{detail}\n"
"The running kernel may be missing live patches. On the host, check "
"`canonical-livepatch status` and `systemctl status kernelwatch-livepatch`.")
try:
publish(cfg, title, message, stale=True, tag="shield")
except DeliveryError as exc:
print(f"kernelwatch: notification failed for {name}: {exc}", file=sys.stderr)
failures += 1
else:
current = (since, True)
print(f"kernelwatch: livepatch notification sent for {name}")
if saved.get(name) != current:
db.save_livepatch_alert(conn, name, *current)
return failures
def notify_backup_failure(cfg: Config) -> int:
"""Tell the ntfy topic the nightly backup failed. Returns 1 if that couldn't be sent.
Run by systemd (OnFailure= on kernelwatch-backup.service), so it also covers
failures the backup command can't report itself: a timeout, an out-of-memory
kill, a crash. The cause is in `journalctl -u kernelwatch-backup`."""
if not cfg.ntfy_url:
print("kernelwatch: backup failed, but ntfy_url is not configured; no notification sent",
file=sys.stderr)
return 0
latest = db.latest_backup(cfg.backup_dir)
message = (f"The nightly kernelwatch database backup on {socket.gethostname()} failed.\n"
f"Newest backup still on disk: {latest or 'none'}.\n"
"Cause: journalctl -u kernelwatch-backup")
try:
publish(cfg, "kernelwatch: nightly backup failed", message, stale=True, tag="floppy_disk")
except DeliveryError as exc:
print(f"kernelwatch: backup failure notification failed: {exc}", file=sys.stderr)
return 1
print("kernelwatch: backup failure notification sent")
return 0
+84 -1
View File
@@ -4,12 +4,14 @@ from __future__ import annotations
import argparse import argparse
import getpass import getpass
import json
import sqlite3 import sqlite3
import sys import sys
import time import time
from . import __version__, alerts, auth, db, web from . import __version__, alerts, auth, db, web
from .config import load from .config import load
from .status import LEVELS, fleet_status
def _conn(cfg): def _conn(cfg):
@@ -29,7 +31,25 @@ def cmd_serve(cfg, args) -> int:
def cmd_check_alerts(cfg, args) -> int: def cmd_check_alerts(cfg, args) -> int:
return int(alerts.check(cfg) > 0) failures = alerts.check(cfg)
# Skipped when deliveries failed, so the monitor also notices a broken alert pipeline.
if cfg.heartbeat_url and not failures:
alerts.ping(cfg.heartbeat_url)
return int(failures > 0)
def cmd_test_heartbeat(cfg, args) -> int:
urls = [(name, url) for name, url in (("heartbeat_url", cfg.heartbeat_url),
("backup_heartbeat_url", cfg.backup_heartbeat_url)) if url]
if not urls:
print("kernelwatch: neither heartbeat_url nor backup_heartbeat_url is configured", file=sys.stderr)
return 1
failed = 0
for name, url in urls:
ok = alerts.ping(url)
failed += not ok
print(f"{name}: {'ok' if ok else 'FAILED'}")
return int(failed > 0)
def cmd_test_alert(cfg, args) -> int: def cmd_test_alert(cfg, args) -> int:
@@ -43,6 +63,10 @@ def cmd_test_alert(cfg, args) -> int:
return 0 return 0
def cmd_notify_backup_failure(cfg, args) -> int:
return alerts.notify_backup_failure(cfg)
def cmd_backup(cfg, args) -> int: def cmd_backup(cfg, args) -> int:
db.init(cfg.db_path) db.init(cfg.db_path)
try: try:
@@ -54,6 +78,19 @@ def cmd_backup(cfg, args) -> int:
return 0 return 0
def cmd_scheduled_backup(cfg, args) -> int:
db.init(cfg.db_path)
try:
dest = db.rotate_backups(cfg.db_path, cfg.backup_dir, cfg.backup_keep_days)
except (OSError, ValueError, sqlite3.Error) as exc:
print(f"kernelwatch: scheduled backup failed: {exc}", file=sys.stderr)
return 1
print(f"Backed up to {dest}")
if cfg.backup_heartbeat_url:
alerts.ping(cfg.backup_heartbeat_url)
return 0
def cmd_add_host(cfg, args) -> int: def cmd_add_host(cfg, args) -> int:
token = auth.new_token() token = auth.new_token()
conn = _conn(cfg) conn = _conn(cfg)
@@ -113,6 +150,39 @@ def cmd_list_hosts(cfg, args) -> int:
return 0 return 0
def cmd_status(cfg, args) -> int:
conn = _conn(cfg)
try:
rows = db.latest_reports(conn)
finally:
conn.close()
if args.host and not any(r["host"] == args.host for r in rows):
print(f"no such host {args.host!r}", file=sys.stderr)
return 1
now = time.time()
fleet = fleet_status(rows, now, cfg)
# Counts always describe the whole fleet; the filters only trim the host list.
fleet["hosts"] = [h for h in fleet["hosts"]
if (not args.host or h["name"] == args.host)
and (not args.level or h["status"] in args.level)]
if args.json:
print(json.dumps(fleet, indent=2))
return 0
if fleet["hosts"]:
width = max(len(h["name"]) for h in fleet["hosts"])
for h in fleet["hosts"]:
kernel = h["kernel_running"] or "?"
if h["kernel_newest_installed"] and h["kernel_newest_installed"] != kernel:
kernel += f" -> {h['kernel_newest_installed']}"
seen = "never" if h["last_report_at"] is None else web.ago(now - h["last_report_age_seconds"], now)
print(f"{h['status']:<7} {h['name']:<{width}} {kernel} (last seen {seen})")
for reason in h["reasons"]:
print(f"{'':<8}- {reason}")
counts = fleet["counts"]
print(f"{sum(counts.values())} hosts: " + ", ".join(f"{counts[l]} {l}" for l in LEVELS))
return 0
def cmd_set_password(cfg, args) -> int: def cmd_set_password(cfg, args) -> int:
password = getpass.getpass(f"Password for {args.name}: ") password = getpass.getpass(f"Password for {args.name}: ")
if len(password) < 12: if len(password) < 12:
@@ -168,6 +238,13 @@ def main(argv: list[str] | None = None) -> int:
p = sub.add_parser("backup", help="write a consistent copy of the database to PATH") p = sub.add_parser("backup", help="write a consistent copy of the database to PATH")
p.add_argument("path") p.add_argument("path")
p.set_defaults(func=cmd_backup) p.set_defaults(func=cmd_backup)
sub.add_parser("test-heartbeat", help="ping the configured heartbeat URLs once and report").set_defaults(
func=cmd_test_heartbeat)
sub.add_parser("notify-backup-failure", help="send the failed-backup notification "
"(run by systemd when kernelwatch-backup.service fails)").set_defaults(
func=cmd_notify_backup_failure)
sub.add_parser("scheduled-backup", help="back up to backup_dir and prune old backups "
"(run by kernelwatch-backup.timer)").set_defaults(func=cmd_scheduled_backup)
for name, func, help_ in ( for name, func, help_ in (
("add-host", cmd_add_host, "register a host and print its token"), ("add-host", cmd_add_host, "register a host and print its token"),
@@ -182,6 +259,12 @@ def main(argv: list[str] | None = None) -> int:
p.set_defaults(func=func) p.set_defaults(func=func)
sub.add_parser("list-hosts", help="list hosts and when they last reported").set_defaults( sub.add_parser("list-hosts", help="list hosts and when they last reported").set_defaults(
func=cmd_list_hosts) func=cmd_list_hosts)
p = sub.add_parser("status", help="fleet status, as the dashboard shows it (--json for scripts)")
p.add_argument("--json", action="store_true", help="machine-readable output")
p.add_argument("--host", type=_valid_host, help="only this host")
p.add_argument("--level", action="append", choices=LEVELS,
help="only hosts with this status (repeatable)")
p.set_defaults(func=cmd_status)
for name, func, help_ in ( for name, func, help_ in (
("set-password", cmd_set_password, "create a dashboard user or change their password"), ("set-password", cmd_set_password, "create a dashboard user or change their password"),
+62
View File
@@ -30,6 +30,31 @@ class Config:
# Package lists older than this make "no updates" untrustworthy. # Package lists older than this make "no updates" untrustworthy.
apt_stale_after_hours: float = 48.0 apt_stale_after_hours: float = 48.0
report_retention_days: int = 30 report_retention_days: int = 30
# 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.
os_eol_warn_days: int = 90
# 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
# under /var/lib/kernelwatch unless the backup unit is given more write access.
backup_dir: str = "/var/lib/kernelwatch/backups"
backup_keep_days: int = 7
# A host's reports closer together than this are refused with 429; 0 disables. # A host's reports closer together than this are refused with 429; 0 disables.
report_min_interval_seconds: int = 30 report_min_interval_seconds: int = 30
@@ -43,8 +68,17 @@ class Config:
ntfy_url: str = "" ntfy_url: str = ""
ntfy_token: str = "" ntfy_token: str = ""
ntfy_timeout_seconds: float = 10.0 ntfy_timeout_seconds: float = 10.0
# Dead-man's-switch URLs (e.g. healthchecks.io): pinged after every successful
# alert check (every five minutes) and every successful nightly backup, so a
# monitor outside this host notices when either stops. Empty disables.
heartbeat_url: str = ""
backup_heartbeat_url: str = ""
# Notify when a host has needed a reboot or updates for this long; 0 disables. # Notify when a host has needed a reboot or updates for this long; 0 disables.
status_alert_after_hours: float = 24.0 status_alert_after_hours: float = 24.0
# Notify when Livepatch has been unhealthy, or a host that used to report it has
# stopped, for this long; 0 disables.
livepatch_alert_after_hours: float = 6.0
def load(path: str | None = None) -> Config: def load(path: str | None = None) -> Config:
@@ -78,8 +112,36 @@ def load(path: str | None = None) -> Config:
raise SystemExit(f"{path}: ntfy_timeout_seconds must be positive and finite") raise SystemExit(f"{path}: ntfy_timeout_seconds must be positive and finite")
if cfg.report_min_interval_seconds < 0: if cfg.report_min_interval_seconds < 0:
raise SystemExit(f"{path}: report_min_interval_seconds must be zero or positive") 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):
raise SystemExit(f"{path}: backup_dir must be an absolute path")
if not math.isfinite(cfg.status_alert_after_hours) or cfg.status_alert_after_hours < 0: if not math.isfinite(cfg.status_alert_after_hours) or cfg.status_alert_after_hours < 0:
raise SystemExit(f"{path}: status_alert_after_hours must be zero or positive and finite") raise SystemExit(f"{path}: status_alert_after_hours must be zero or positive and finite")
for key in ("heartbeat_url", "backup_heartbeat_url"):
value = getattr(cfg, key)
if value:
try:
url = urlsplit(value)
valid = (url.scheme in ("http", "https") and url.hostname and url.port != 0
and not url.fragment
and not any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in value))
except ValueError:
valid = False
if not valid:
raise SystemExit(f"{path}: {key} must be an HTTP(S) URL without spaces or a fragment")
if not math.isfinite(cfg.livepatch_alert_after_hours) or cfg.livepatch_alert_after_hours < 0:
raise SystemExit(f"{path}: livepatch_alert_after_hours must be zero or positive and finite")
if any(ord(c) < 32 or ord(c) == 127 for c in cfg.ntfy_url + cfg.ntfy_token): if any(ord(c) < 32 or ord(c) == 127 for c in cfg.ntfy_url + cfg.ntfy_token):
raise SystemExit(f"{path}: ntfy settings must not contain control characters") raise SystemExit(f"{path}: ntfy settings must not contain control characters")
if cfg.ntfy_url: if cfg.ntfy_url:
+65
View File
@@ -2,8 +2,10 @@
from __future__ import annotations from __future__ import annotations
import calendar
import json import json
import os import os
import re
import sqlite3 import sqlite3
import time import time
from typing import Any from typing import Any
@@ -40,6 +42,11 @@ CREATE TABLE IF NOT EXISTS status_alerts (
since INTEGER NOT NULL, since INTEGER NOT NULL,
notified_level TEXT notified_level TEXT
); );
CREATE TABLE IF NOT EXISTS livepatch_alerts (
host TEXT PRIMARY KEY REFERENCES hosts(name) ON DELETE CASCADE,
since INTEGER,
notified INTEGER NOT NULL DEFAULT 0
);
""" """
@@ -91,6 +98,43 @@ def backup(path: str, dest: str) -> None:
src.close() src.close()
_BACKUP_NAME = re.compile(r"^kernelwatch-(\d{4})-(\d{2})-(\d{2})\.db$")
def latest_backup(directory: str) -> str | None:
"""Name of the newest dated backup in directory, or None."""
try:
names = [n for n in os.listdir(directory) if _BACKUP_NAME.match(n)]
except OSError:
return None
return max(names, default=None)
def rotate_backups(path: str, directory: str, keep_days: int, now: float | None = None) -> str:
"""Back the database up to <directory>/kernelwatch-YYYY-MM-DD.db (UTC date),
replacing that day's file, then delete dated backups that are keep_days or more
days old. Pruning happens only after a successful backup, and touches only files
with that exact name, so a failing backup never costs you the ones you have.
Returns the new backup's path."""
now = time.time() if now is None else now
os.makedirs(directory, mode=0o700, exist_ok=True)
dest = os.path.join(directory, time.strftime("kernelwatch-%Y-%m-%d.db", time.gmtime(now)))
backup(path, dest)
if keep_days > 0:
today = int(now // 86400)
for name in os.listdir(directory):
m = _BACKUP_NAME.match(name)
if not m:
continue
try:
day = calendar.timegm(time.strptime("-".join(m.groups()), "%Y-%m-%d")) // 86400
except (ValueError, OverflowError):
continue
if today - day >= keep_days:
os.unlink(os.path.join(directory, name))
return dest
# --- hosts ------------------------------------------------------------------ # --- hosts ------------------------------------------------------------------
def add_host(conn: sqlite3.Connection, name: str, token_hash: str) -> None: def add_host(conn: sqlite3.Connection, name: str, token_hash: str) -> None:
@@ -232,6 +276,27 @@ def clear_status_alert(conn: sqlite3.Connection, host: str) -> None:
conn.execute("DELETE FROM status_alerts WHERE host = ?", (host,)) conn.execute("DELETE FROM status_alerts WHERE host = ?", (host,))
# --- livepatch notifications -------------------------------------------------
def livepatch_alerts(conn: sqlite3.Connection) -> dict[str, tuple[int | None, bool]]:
"""host -> (when its current Livepatch problem began or None, whether it was
notified). A host appears once it has reported Livepatch at all, which is how
"stopped reporting it" is told apart from "never had it"."""
return {r["host"]: (r["since"], bool(r["notified"]))
for r in conn.execute("SELECT * FROM livepatch_alerts")}
def save_livepatch_alert(conn: sqlite3.Connection, host: str, since: int | None,
notified: bool) -> None:
# The host may have been removed while a notification was in flight.
conn.execute(
"INSERT INTO livepatch_alerts (host, since, notified) "
"SELECT name, ?, ? FROM hosts WHERE name = ? "
"ON CONFLICT(host) DO UPDATE SET since = excluded.since, notified = excluded.notified",
(since, int(notified), host),
)
# --- users & sessions ------------------------------------------------------- # --- users & sessions -------------------------------------------------------
def set_user(conn: sqlite3.Connection, name: str, pw_hash: str) -> None: def set_user(conn: sqlite3.Connection, name: str, pw_hash: str) -> None:
+24
View File
@@ -27,6 +27,9 @@ FIELDS: dict[str, str] = {
"kernel_newest_installed": "str", "kernel_newest_installed": "str",
"needrestart_ksta": "int", "needrestart_ksta": "int",
"needrestart_kexp": "str", "needrestart_kexp": "str",
"needrestart_ucsta": "int",
"needrestart_uccur": "str",
"needrestart_ucexp": "str",
"services_need_restart": "strlist", "services_need_restart": "strlist",
"sessions_need_restart": "int", "sessions_need_restart": "int",
"reboot_required": "bool", "reboot_required": "bool",
@@ -40,7 +43,28 @@ FIELDS: dict[str, str] = {
"livepatch_supported": "str", "livepatch_supported": "str",
"livepatch_upgrade_required": "str", "livepatch_upgrade_required": "str",
"livepatch_fix_count": "int", "livepatch_fix_count": "int",
"apt_simulation_ok": "bool",
"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",
"unattended_upgrades_success_age_seconds": "int",
"unattended_upgrades_run_age_seconds": "int",
"unattended_upgrades_kept_back": "strlist",
"apt_lists_age_seconds": "int", "apt_lists_age_seconds": "int",
"security_repo_suite": "str",
"security_repo_age_seconds": "int",
"helper_units": "strlist",
"uptime_seconds": "int", "uptime_seconds": "int",
} }
+279 -6
View File
@@ -10,11 +10,12 @@ Levels, worst first:
from __future__ import annotations from __future__ import annotations
import re import re
import time
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import date, datetime, timezone from datetime import date, datetime, timezone
from typing import Any from typing import Any
from . import AGENT_VERSION from . import AGENT_VERSION, support
from .config import Config from .config import Config
LEVELS = ("stale", "reboot", "update", "ok") LEVELS = ("stale", "reboot", "update", "ok")
@@ -29,6 +30,8 @@ LIVEPATCH_HEALTHY_STATES = ("applied", "nothing-to-apply")
KSTA_CURRENT = 1 KSTA_CURRENT = 1
KSTA_ABI_UPGRADE = 2 KSTA_ABI_UPGRADE = 2
KSTA_VERSION_UPGRADE = 3 KSTA_VERSION_UPGRADE = 3
# needrestart's NEEDRESTART-UCSTA: a newer CPU microcode is installed but not loaded.
UCSTA_OBSOLETE = 2
@dataclass @dataclass
@@ -104,6 +107,24 @@ def kernel_reboot_pending(report: dict[str, Any]) -> str | None:
return None return None
def livepatch_problem(report: dict[str, Any]) -> str | None:
"""Why Livepatch isn't working on this host, or None if it is (or isn't in use).
"Working" means a state we recognise as healthy, a completed check and a
supported kernel. The same test decides cover for a pending reboot and whether
to send a Livepatch alert."""
state = report.get("livepatch_state")
if state is None:
return None
if (state not in LIVEPATCH_HEALTHY_STATES or report.get("livepatch_check_state") != "checked"
or report.get("livepatch_supported") != "supported"):
parts = [state, report.get("livepatch_supported") or "?"]
if report.get("livepatch_check_state") != "checked":
parts.append(f"check: {report.get('livepatch_check_state') or '?'}")
return f"livepatch not healthy ({', '.join(parts)})"
return None
def livepatch_cover(report: dict[str, Any], now: float) -> tuple[bool, str | None]: def livepatch_cover(report: dict[str, Any], now: float) -> tuple[bool, str | None]:
"""(is the running kernel kept patched by Livepatch, a note about it). """(is the running kernel kept patched by Livepatch, a note about it).
@@ -111,16 +132,14 @@ def livepatch_cover(report: dict[str, Any], now: float) -> tuple[bool, str | Non
support ends, so cover lapses LIVEPATCH_MARGIN_DAYS before that date. Hosts support ends, so cover lapses LIVEPATCH_MARGIN_DAYS before that date. Hosts
without Livepatch data, or with Livepatch in any state we don't recognise as without Livepatch data, or with Livepatch in any state we don't recognise as
healthy, get no cover and are judged as before.""" healthy, get no cover and are judged as before."""
state = report.get("livepatch_state") if report.get("livepatch_state") is None:
if state is None:
return False, None return False, None
if problem := livepatch_problem(report):
return False, problem
try: try:
deadline = date.fromisoformat(report.get("livepatch_upgrade_required") or "") deadline = date.fromisoformat(report.get("livepatch_upgrade_required") or "")
except ValueError: except ValueError:
deadline = None deadline = None
if (state not in LIVEPATCH_HEALTHY_STATES or report.get("livepatch_check_state") != "checked"
or report.get("livepatch_supported") != "supported"):
return False, f"livepatch not healthy ({state}, {report.get('livepatch_supported') or '?'})"
if deadline is None: if deadline is None:
return False, "livepatch end of support date unknown" return False, "livepatch end of support date unknown"
left = (deadline - datetime.fromtimestamp(now, timezone.utc).date()).days left = (deadline - datetime.fromtimestamp(now, timezone.utc).date()).days
@@ -129,6 +148,148 @@ def livepatch_cover(report: dict[str, Any], now: float) -> tuple[bool, str | Non
return True, f"live-patched; kernel upgrade needed by {deadline}" return True, f"live-patched; kernel upgrade needed by {deadline}"
def boot_space_low(report: dict[str, Any], cfg: Config) -> str | None:
"""Why /boot may be too full for the next kernel, or None. Agents before 0.6.0
don't report it, and a host whose df failed sends null; both count as fine."""
free_kb = report.get("boot_free_kb")
if not cfg.boot_min_free_mb or free_kb is None or free_kb >= cfg.boot_min_free_mb * 1024:
return None
size_kb = report.get("boot_size_kb")
used = f", {100 - free_kb * 100 // size_kb}% used" if size_kb else ""
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/"
def _age(seconds: int) -> str:
return f"{seconds // 86400}d" if seconds >= 86400 else f"{seconds // 3600}h"
def unattended_upgrades_problem(report: dict[str, Any], cfg: Config) -> tuple[bool, str] | None:
"""(is it a problem, why) about unattended-upgrades on a host that has it enabled,
or None. Hosts without it, and agents before 0.8.0, get nothing.
The success stamp is apt.systemd.daily's (touched only when unattended-upgrade
exits 0); the run stamp is unattended-upgrade's own (written even when the run
then fails). Ages are as of the report."""
if report.get("unattended_upgrades") != "enabled" or not cfg.unattended_upgrades_stale_after_days:
return None
success = report.get("unattended_upgrades_success_age_seconds")
run = report.get("unattended_upgrades_run_age_seconds")
if success is None:
if run is None:
# Freshly installed: the first daily run hasn't happened yet.
return False, "unattended-upgrades is enabled but hasn't completed a run yet"
return True, (f"unattended-upgrades has never succeeded (last ran {_age(run)} ago); "
f"check {UU_LOG}")
if success <= cfg.unattended_upgrades_stale_after_days * 86400:
return None
# A successful run writes both stamps within moments of each other.
if run is not None and run < success - 3600:
return True, (f"unattended-upgrades last succeeded {_age(success)} ago and is failing "
f"(last ran {_age(run)} ago); check {UU_LOG}")
return True, (f"unattended-upgrades hasn't run in {_age(success)}; "
"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: def _kernel_only_reboot_file(report: dict[str, Any]) -> bool:
"""/run/reboot-required exists only because of kernel packages.""" """/run/reboot-required exists only because of kernel packages."""
pkgs = report.get("reboot_required_pkgs") or [] pkgs = report.get("reboot_required_pkgs") or []
@@ -180,12 +341,69 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float,
status.raise_to("reboot", f"/run/reboot-required{detail}") status.raise_to("reboot", f"/run/reboot-required{detail}")
if livepatch_note and not covered: if livepatch_note and not covered:
status.note(livepatch_note) 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.
if report.get("apt_simulation_ok") is False:
why = report.get("apt_simulation_error") or "no error message"
status.raise_to("update", f"apt can't work out pending updates: {why}")
if kernels := report.get("kernel_upgradable"): if kernels := report.get("kernel_upgradable"):
status.raise_to("update", f"kernel update available: {', '.join(kernels)}") status.raise_to("update", f"kernel update available: {', '.join(kernels)}")
if sec := report.get("security_count"): if sec := report.get("security_count"):
status.raise_to("update", f"{sec} security update{'s' if sec != 1 else ''} pending") status.raise_to("update", f"{sec} security update{'s' if sec != 1 else ''} pending")
# dpkg stopped part-way (usually a failed postinst, often from a full /boot), so
# whatever it was installing, maybe a kernel, isn't in place yet.
if unfinished := report.get("dpkg_unfinished_packages"):
n = len(unfinished)
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
if problem:
status.raise_to("update", why)
else:
status.note(why)
# Packages from its allowed origins (by default security) it won't install: held,
# blacklisted or stuck on a conffile prompt. They stay pending until someone acts.
if report.get("unattended_upgrades") == "enabled" and (kept := report.get("unattended_upgrades_kept_back")):
more = f", +{len(kept) - 5} more" if len(kept) > 5 else ""
status.note(f"unattended-upgrades is keeping back {', '.join(kept[:5])}{more}")
today = datetime.fromtimestamp(now, timezone.utc).date()
if found := support.check(report, today, cfg.os_eol_warn_days):
problem, why = found
if problem:
status.raise_to("update", why)
else:
status.note(why)
if services := report.get("services_need_restart"): if services := report.get("services_need_restart"):
shown = ", ".join(s.removesuffix(".service") for s in services[:5]) shown = ", ".join(s.removesuffix(".service") for s in services[:5])
more = f", +{len(services) - 5} more" if len(services) > 5 else "" more = f", +{len(services) - 5} more" if len(services) > 5 else ""
@@ -198,6 +416,15 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float,
status.raise_to("update", "package list age unknown") status.raise_to("update", "package list age unknown")
elif apt_age / 3600 > cfg.apt_stale_after_hours: elif apt_age / 3600 > cfg.apt_stale_after_hours:
status.raise_to("update", f"package lists {apt_age / 86400:.0f}d old; apt update not running?") status.raise_to("update", f"package lists {apt_age / 86400:.0f}d old; apt update not running?")
if 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)): if host and (reported := hostname_mismatch(host, report)):
status.note(f"registered as {host} but reports itself as {reported}; " status.note(f"registered as {host} but reports itself as {reported}; "
@@ -208,3 +435,49 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float,
"run agent/deploy.sh") "run agent/deploy.sh")
return status return status
def _iso(ts: float | None) -> str | None:
return None if ts is None else time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(ts))
def fleet_status(rows: list[dict[str, Any]], now: float, cfg: Config) -> dict[str, Any]:
"""The whole fleet as plain data, worst hosts first (as the dashboard orders them).
`rows` are db.latest_reports() entries. A stable, secret-free shape for scripts:
status and reasons come from evaluate(), the same call the dashboard makes."""
hosts = []
for row in rows:
report = row["report"] or {}
status = evaluate(row["received_at"], row["report"], now, cfg, row["host"])
livepatch = None
if report.get("livepatch_state") is not None:
livepatch = {"state": report["livepatch_state"],
"supported": report.get("livepatch_supported"),
"upgrade_required": report.get("livepatch_upgrade_required"),
"fixes": report.get("livepatch_fix_count")}
hosts.append({
"name": row["host"],
"status": status.level,
"reasons": status.reasons,
"last_report_at": _iso(row["received_at"]),
"last_report_age_seconds": None if row["received_at"] is None else max(0, int(now - row["received_at"])),
"os": report.get("os_pretty_name"),
"kernel_running": report.get("kernel_running"),
"kernel_newest_installed": report.get("kernel_newest_installed"),
"reboot_required": report.get("reboot_required"),
"updates_pending": report.get("upgradable_count"),
"security_updates": report.get("security_count"),
"kernel_updates": report.get("kernel_upgradable"),
"services_need_restart": report.get("services_need_restart"),
"livepatch": livepatch,
"uptime_seconds": report.get("uptime_seconds"),
"agent_version": report.get("agent_version"),
"_rank": status.rank,
})
hosts.sort(key=lambda h: (h["_rank"], h["name"]))
counts = {level: 0 for level in LEVELS}
for h in hosts:
counts[h["status"]] += 1
del h["_rank"]
return {"generated_at": _iso(now), "counts": counts, "hosts": hosts}
+98
View File
@@ -0,0 +1,98 @@
"""When each supported OS release stops getting security updates.
A host past that date shows `ok` forever, because no updates will ever arrive to
flag. So the status check compares the host's release (`os_id`, `os_version_id`)
with the dates below.
Sources: the Debian security team and Debian LTS (wiki.debian.org/LTS) and
Ubuntu's release cycle (ubuntu.com/about/release-cycle), as collected by
endoflife.date. Add each new release when it ships; tests/test_support.py checks
that every release the agent supports is listed.
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any
@dataclass(frozen=True)
class Release:
name: str
# Debian: end of LTS, the last free security support (regular security support
# ends about two years earlier and LTS continues it from the same repository).
# Ubuntu: end of standard support for the main archive.
end: date
# Ubuntu only: end of Expanded Security Maintenance (esm-infra, part of Ubuntu
# Pro), which keeps patching main after standard support ends.
esm_end: date | None = None
RELEASES: dict[tuple[str, str], Release] = {
("debian", "11"): Release("Debian 11", date(2026, 8, 31)),
("debian", "12"): Release("Debian 12", date(2028, 6, 30)),
("debian", "13"): Release("Debian 13", date(2030, 6, 30)),
("ubuntu", "20.04"): Release("Ubuntu 20.04", date(2025, 5, 31), date(2030, 4, 23)),
("ubuntu", "22.04"): Release("Ubuntu 22.04", date(2027, 6, 1), date(2032, 4, 21)),
("ubuntu", "24.04"): Release("Ubuntu 24.04", date(2029, 5, 31), date(2034, 4, 25)),
("ubuntu", "26.04"): Release("Ubuntu 26.04", date(2031, 5, 29), date(2036, 4, 23)),
}
def release(report: dict[str, Any]) -> Release | None:
return RELEASES.get((report.get("os_id") or "", report.get("os_version_id") or ""))
def _esm(report: dict[str, Any]) -> bool:
return report.get("ubuntu_esm_infra") == "enabled"
def check(report: dict[str, Any], today: date, warn_days: int) -> tuple[bool, str] | None:
"""(is it a problem, why) about this host's OS support, or None if there's nothing to say.
A problem means no security updates are coming: the release is past its last
support date, or an Ubuntu release is past standard support without ESM. The
rest are warnings for the `warn_days` before such a date (0 disables them)."""
os_id, version = report.get("os_id"), report.get("os_version_id")
if os_id not in ("debian", "ubuntu") or not version:
return None # Debian testing/sid has no VERSION_ID; other distros aren't supported
rel = release(report)
if rel is None:
return False, f"no end-of-support date known for {os_id} {version}"
def soon(day: date) -> int | None:
left = (day - today).days
return left if warn_days and 0 <= left <= warn_days else None
if rel.esm_end is None:
if today > rel.end:
return True, f"{rel.name} security support ended {rel.end}; upgrade the release"
if (left := soon(rel.end)) is not None:
return False, f"{rel.name} security support ends {rel.end} (in {left} days); plan the upgrade"
return None
if today > rel.esm_end:
return True, f"{rel.name} ESM ended {rel.esm_end}; upgrade the release"
if _esm(report):
if today > rel.end and (left := soon(rel.esm_end)) is not None:
return False, f"{rel.name} ESM ends {rel.esm_end} (in {left} days); plan the upgrade"
return None
if today > rel.end:
return True, (f"{rel.name} standard support ended {rel.end} and ESM isn't enabled; "
"enable it with Ubuntu Pro or upgrade the release")
if (left := soon(rel.end)) is not None:
return False, (f"{rel.name} standard support ends {rel.end} (in {left} days); "
"enable ESM with Ubuntu Pro or plan the upgrade")
return None
def summary(report: dict[str, Any]) -> str | None:
"""The host page's one-line view of the release's support dates."""
rel = release(report)
if rel is None:
return None
if rel.esm_end is None:
return f"until {rel.end}"
esm = report.get("ubuntu_esm_infra")
return f"standard until {rel.end}, ESM until {rel.esm_end} (esm-infra: {esm or 'unknown'})"
+77 -3
View File
@@ -19,10 +19,10 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any from typing import Any
from urllib.parse import parse_qs, quote, unquote, urlsplit from urllib.parse import parse_qs, quote, unquote, urlsplit
from . import __version__, auth, db from . import __version__, auth, db, support
from .config import Config from .config import Config
from .report import MAX_BODY_BYTES, ReportError, sanitize 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" SESSION_COOKIE = "kw_session"
HOST_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$") HOST_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$")
@@ -84,6 +84,67 @@ def utc(ts: float | None) -> str:
return time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(ts)) if ts else "" return time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(ts)) if ts else ""
def unattended_upgrades_summary(report: dict[str, Any]) -> str | None:
state = report.get("unattended_upgrades")
if state != "enabled":
return state # "disabled", "not-installed", or None from agents before 0.8.0
last = {"success": report.get("unattended_upgrades_success_age_seconds"),
"run": report.get("unattended_upgrades_run_age_seconds")}
return "enabled, " + ", ".join(
f"last {what} " + ("never" if age is None else f"{duration(age)} before the report")
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]: def phased_summary(report: dict[str, Any]) -> tuple[str, str]:
"""(short cell text, full description) for updates deferred by Ubuntu's phasing.""" """(short cell text, full description) for updates deferred by Ubuntu's phasing."""
if report.get("os_id") not in (None, "ubuntu"): if report.get("os_id") not in (None, "ubuntu"):
@@ -490,24 +551,37 @@ class Handler(BaseHTTPRequestHandler):
if latest else None), if latest else None),
field("Reported hostname", r.get("reported_hostname")), field("Reported hostname", r.get("reported_hostname")),
field("OS", r.get("os_pretty_name")), field("OS", r.get("os_pretty_name")),
field("OS security support", support.summary(r)),
field("Running kernel", r.get("kernel_running"), code=True), field("Running kernel", r.get("kernel_running"), code=True),
field("Kernel build", r.get("kernel_build"), code=True), field("Kernel build", r.get("kernel_build"), code=True),
field("Running kernel package", r.get("kernel_running_pkg_version"), code=True), field("Running kernel package", r.get("kernel_running_pkg_version"), code=True),
field("Installed kernels", r.get("kernels_installed"), code=True), field("Installed kernels", r.get("kernels_installed"), code=True),
field("needrestart", None if r.get("needrestart_ksta") is None else field("needrestart", None if r.get("needrestart_ksta") is None else
f"KSTA={r['needrestart_ksta']} expected={r.get('needrestart_kexp') or '?'}"), 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 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['livepatch_state']}, {r.get('livepatch_fix_count') or 0} fixes applied, "
f"{r.get('livepatch_supported') or '?'} until {r.get('livepatch_upgrade_required') or '?'}"), f"{r.get('livepatch_supported') or '?'} until {r.get('livepatch_upgrade_required') or '?'}"),
field("Kernel packages upgradable", r.get("kernel_upgradable"), code=True), field("Kernel packages upgradable", r.get("kernel_upgradable"), code=True),
field("Updates pending", r.get("upgradable_count")), field("Updates pending", r.get("upgradable_count")),
field("Security updates", r.get("security_count")), field("Security updates", r.get("security_count")),
field("apt simulation", None if r.get("apt_simulation_ok") is None else
"ok" if r["apt_simulation_ok"] else f"failed: {r.get('apt_simulation_error') or '?'}"),
field("Deferred by phasing", r.get("phased_packages"), code=True), field("Deferred by phasing", r.get("phased_packages"), code=True),
field("Reboot-required packages", r.get("reboot_required_pkgs"), code=True), field("Reboot-required packages", r.get("reboot_required_pkgs"), code=True),
field("Services needing restart", services_summary(r)[1]), field("Services needing restart", services_summary(r)[1]),
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
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")) field("Package lists age", duration(r.get("apt_lists_age_seconds"))
if r.get("apt_lists_age_seconds") is not None else None), if r.get("apt_lists_age_seconds") is not None else None),
field("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("Uptime", duration(r.get("uptime_seconds")) if r.get("uptime_seconds") is not None else None),
field("Agent version", r.get("agent_version")), field("Agent version", r.get("agent_version")),
]) ])
@@ -518,7 +592,7 @@ class Handler(BaseHTTPRequestHandler):
f'<td title="{e(utc(h["received_at"]))}">{e(ago(h["received_at"], now))}</td>' f'<td title="{e(utc(h["received_at"]))}">{e(ago(h["received_at"], now))}</td>'
f"<td>{badge(evaluate(h['received_at'], h['report'], h['received_at'], self.cfg).level)}</td>" f"<td>{badge(evaluate(h['received_at'], h['report'], h['received_at'], self.cfg).level)}</td>"
f"<td><code>{e(h['report'].get('kernel_running') or '–')}</code></td>" f"<td><code>{e(h['report'].get('kernel_running') or '–')}</code></td>"
f"<td>{e(str(h['report'].get('upgradable_count', '–')))}</td>" f"<td>{e('–' if (n := h['report'].get('upgradable_count')) is None else str(n))}</td>"
"</tr>" "</tr>"
for h in history for h in history
) )
+44
View File
@@ -14,6 +14,40 @@ apt_stale_after_hours = 48.0
report_retention_days = 30 report_retention_days = 30
# Less free space than this (MB) on the filesystem holding /boot puts a host in
# "update": the next kernel's image and initramfs may not fit, and its install
# 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.
os_eol_warn_days = 90
# On hosts with unattended-upgrades enabled (it runs daily), no successful run in
# this many days puts the host in "update". Hosts without it aren't affected.
# 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
# files off this machine yourself: they don't protect against losing it.
# A failed backup run sends an ntfy message (if ntfy_url is set).
backup_dir = "/var/lib/kernelwatch/backups"
backup_keep_days = 7
# Refuse (HTTP 429) a report that arrives sooner than this after the host's # Refuse (HTTP 429) a report that arrives sooner than this after the host's
# previous one. Agents report hourly; this only stops a stuck or abusive client # previous one. Agents report hourly; this only stops a stuck or abusive client
# from flooding the history. 0 disables. # from flooding the history. 0 disables.
@@ -42,3 +76,13 @@ ntfy_timeout_seconds = 10.0
# Reaching a worse state (updates -> reboot) notifies again after another period. # Reaching a worse state (updates -> reboot) notifies again after another period.
# 0 disables. Needs ntfy_url. # 0 disables. Needs ntfy_url.
status_alert_after_hours = 24.0 status_alert_after_hours = 24.0
# Also notify (once per problem) when Ubuntu Livepatch has been unhealthy, or a host
# that used to report it has stopped, for this long. 0 disables. Needs ntfy_url.
livepatch_alert_after_hours = 6.0
# Dead-man's switch: an external monitor (e.g. healthchecks.io) that alerts when the
# pings STOP, which is how you learn kernelwatch itself isn't running. Treat these
# URLs like passwords. Empty disables.
heartbeat_url = "" # pinged every five minutes by the alert check
backup_heartbeat_url = "" # pinged after each successful nightly backup
+402 -1
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)
@@ -59,13 +90,38 @@ class AgentCase(unittest.TestCase):
stub(self.bin, "uname", 'case "$1" in -r) echo 6.12.48+deb13-amd64;; ' stub(self.bin, "uname", 'case "$1" in -r) echo 6.12.48+deb13-amd64;; '
'-v) echo "#1 SMP PREEMPT_DYNAMIC Debian 6.12.48-1";; esac\n') '-v) echo "#1 SMP PREEMPT_DYNAMIC Debian 6.12.48-1";; esac\n')
stub(self.bin, "hostname", "echo web01.example\n") stub(self.bin, "hostname", "echo web01.example\n")
stub(self.bin, "dpkg-query", 'case "$*" in *Version*) echo "ii 6.12.48-2";; *) cat <<\'X\'\n' # The full-database query (unfinished packages) prints $KERNELWATCH_ROOT/dpkg-all.
# The unattended-upgrades query prints $KERNELWATCH_ROOT/dpkg-uu (its status, e.g. "ii ").
# The Installed-Size query prints $KERNELWATCH_ROOT/dpkg-sizes.
stub(self.bin, "dpkg-query", 'case "$*" in *Installed-Size*) cat "$KERNELWATCH_ROOT/dpkg-sizes" 2>/dev/null;; '
'*" unattended-upgrades") cat "$KERNELWATCH_ROOT/dpkg-uu" 2>/dev/null;; '
'*binary:Package*) cat "$KERNELWATCH_ROOT/dpkg-all" 2>/dev/null;; '
'*Version*) echo "ii 6.12.48-2";; *) cat <<\'X\'\n'
f"{DPKG_DEBIAN}X\n;; esac\n") f"{DPKG_DEBIAN}X\n;; esac\n")
# df answers per path: /boot and /usr on the root filesystem, apt's archives on /var.
stub(self.bin, "df", "echo 'Filesystem 1024-blocks Used Available Capacity Mounted on'\n"
'case "$2" in */var/cache/apt/archives) '
"echo '/dev/sda2 4062912 3500000 358124 91% /var';; "
"*) echo '/dev/sda1 999320 187364 743144 21% /';; esac\n")
with open(os.path.join(self.root, "dpkg-sizes"), "w") as f:
f.write(DPKG_SIZES_DEBIAN)
# apt-cache records its arguments in $KERNELWATCH_ROOT/apt-cache-args.
self.stub_apt_cache(APT_CACHE_DEBIAN)
# `apt-config dump KEY` prints $KERNELWATCH_ROOT/apt-config (nothing: the key is unset).
stub(self.bin, "apt-config", 'cat "$KERNELWATCH_ROOT/apt-config" 2>/dev/null; exit 0\n')
stub(self.bin, "apt-get", f"cat <<'X'\n{APT_SIM_DEBIAN}X\n") stub(self.bin, "apt-get", f"cat <<'X'\n{APT_SIM_DEBIAN}X\n")
def tearDown(self): def tearDown(self):
self._tmp.cleanup() self._tmp.cleanup()
def stub_df(self, line, rc=0):
stub(self.bin, "df", "echo 'Filesystem 1024-blocks Used Available Capacity Mounted on'\n"
f"cat <<'X'\n{line}X\nexit {rc}\n")
def stub_apt_cache(self, records, rc=0):
stub(self.bin, "apt-cache", 'printf "%s\\n" "$@" >"$KERNELWATCH_ROOT/apt-cache-args"\n'
f"cat <<'X'\n{records}X\nexit {rc}\n")
def run_agent(self, *args, env=None): 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']}",
@@ -125,6 +181,20 @@ class AgentReportTest(AgentCase):
self.assertEqual(r["services_need_restart"], ["nginx.service", "ssh.service"]) self.assertEqual(r["services_need_restart"], ["nginx.service", "ssh.service"])
self.assertEqual(r["sessions_need_restart"], 1) 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): def write_livepatch(self, text, age=60):
d = os.path.join(self.root, "run/kernelwatch") d = os.path.join(self.root, "run/kernelwatch")
os.makedirs(d, exist_ok=True) os.makedirs(d, exist_ok=True)
@@ -134,9 +204,215 @@ class AgentReportTest(AgentCase):
t = time.time() - age t = time.time() - age
os.utime(path, (t, t)) os.utime(path, (t, t))
def test_boot_space(self):
r = self.report()
self.assertEqual((r["boot_size_kb"], r["boot_free_kb"]), (999320, 743144))
def test_boot_space_unknown_when_df_fails(self):
self.stub_df("", rc=1)
r = self.report()
self.assertIsNone(r["boot_size_kb"])
self.assertIsNone(r["boot_free_kb"])
def test_boot_space_unknown_when_df_prints_garbage(self):
self.stub_df("/dev/sda1 - - - - /boot\n")
self.assertIsNone(self.report()["boot_free_kb"])
def test_upgrade_space(self):
r = self.report()
# 102.8 MB of .debs, rounded up to KiB; 409500 KiB of new versions less the
# 9400 KiB of the libssl3t64 and curl they replace.
self.assertEqual(r["upgrade_download_kb"], 100391)
self.assertEqual(r["upgrade_install_kb"], 400100)
self.assertEqual((r["apt_archives_free_kb"], r["apt_archives_mount"]), (358124, "/var"))
self.assertEqual((r["usr_free_kb"], r["usr_mount"]), (743144, "/"))
with open(os.path.join(self.root, "apt-cache-args")) as f:
args = f.read().split()
self.assertEqual(args[-4:], ["show", "libssl3t64=3.5.1-1+deb13u1",
"linux-image-6.12.60+deb13-amd64=6.12.60-1", "curl=8.14.1-2+deb13u1"])
def test_upgrade_space_skips_downloaded_archives(self):
archives = os.path.join(self.root, "var/cache/apt/archives")
os.makedirs(archives)
open(os.path.join(archives, "curl_8.14.1-2+deb13u1_amd64.deb"), "w").close()
open(os.path.join(archives, "libssl3t64_3.5.1-1_amd64.deb"), "w").close() # the old version
self.assertEqual(self.report()["upgrade_download_kb"], 100098)
def test_upgrade_space_epoch_in_archive_name(self):
stub(self.bin, "apt-get", "echo 'Inst tzdata [1:2024a-1] (1:2025b-1 Debian:13/stable [all])'\n")
self.stub_apt_cache("Package: tzdata\nArchitecture: all\nVersion: 1:2025b-1\n"
"Installed-Size: 3000\nSize: 2048\n")
archives = os.path.join(self.root, "var/cache/apt/archives")
os.makedirs(archives)
open(os.path.join(archives, "tzdata_1%3a2025b-1_all.deb"), "w").close()
with open(os.path.join(self.root, "dpkg-sizes"), "w") as f:
f.write("3100\n")
r = self.report()
self.assertEqual((r["upgrade_download_kb"], r["upgrade_install_kb"]), (0, -100))
def test_upgrade_space_new_package_counts_in_full(self):
stub(self.bin, "apt-get", "echo 'Inst linux-image-6.12.60+deb13-amd64 (6.12.60-1 Debian:13/stable [amd64])'\n")
self.stub_apt_cache(APT_CACHE_DEBIAN.split("\n\n")[1] + "\n")
os.remove(os.path.join(self.root, "dpkg-sizes"))
r = self.report()
self.assertEqual((r["upgrade_download_kb"], r["upgrade_install_kb"]), (97657, 400000))
def test_upgrade_space_nothing_pending(self):
stub(self.bin, "apt-get", "echo 'NOTE: This is only a simulation!'\n")
r = self.report()
self.assertEqual((r["upgrade_download_kb"], r["upgrade_install_kb"]), (0, 0))
self.assertFalse(os.path.exists(os.path.join(self.root, "apt-cache-args")), "apt-cache not run")
def test_upgrade_space_unknown_when_apt_cache_fails(self):
self.stub_apt_cache("", rc=100)
r = self.report()
self.assertIsNone(r["upgrade_download_kb"])
self.assertIsNone(r["upgrade_install_kb"])
def test_upgrade_space_unknown_when_simulation_fails(self):
stub(self.bin, "apt-get", "echo 'E: Unmet dependencies.' >&2; exit 100\n")
r = self.report()
self.assertIsNone(r["upgrade_download_kb"])
self.assertFalse(os.path.exists(os.path.join(self.root, "apt-cache-args")))
def test_filesystem_free_unknown_when_df_fails(self):
self.stub_df("", rc=1)
r = self.report()
self.assertIsNone(r["apt_archives_free_kb"])
self.assertIsNone(r["usr_mount"])
def test_mount_point_with_spaces(self):
self.stub_df("/dev/sdb1 999320 187364 743144 21% /srv/my disk\n")
self.assertEqual(self.report()["usr_mount"], "/srv/my disk")
def test_unfinished_packages(self):
with open(os.path.join(self.root, "dpkg-all"), "w") as f:
f.write("ii \tcurl\n"
"iF \tlinux-image-6.12.60+deb13-amd64\n"
"iU \tlinux-headers-6.12.60+deb13-amd64\n"
"iHR\tlibfoo1:amd64\n"
"iiR\tlibbar2\n"
"it \tman-db\n"
"rc \told-pkg\n")
self.assertEqual(self.report()["dpkg_unfinished_packages"], [
"libbar2", "libfoo1:amd64", "linux-headers-6.12.60+deb13-amd64",
"linux-image-6.12.60+deb13-amd64", "man-db"])
def test_held_packages(self):
with open(os.path.join(self.root, "dpkg-all"), "w") as f:
f.write("ii \tcurl\n"
"hi \tlinux-image-amd64\n"
"hi \tpostgresql-16\n"
"hn \tnot-installed\n"
"hc \tremoved-but-held\n"
"iF \tbroken\n")
r = self.report()
self.assertEqual(r["held_packages"], ["linux-image-amd64", "postgresql-16"])
self.assertEqual(r["dpkg_unfinished_packages"], ["broken"])
def test_no_unfinished_packages(self):
with open(os.path.join(self.root, "dpkg-all"), "w") as f:
f.write("ii \tcurl\nrc \told-pkg\n")
self.assertEqual(self.report()["dpkg_unfinished_packages"], [])
def write_pro_status(self, text):
d = os.path.join(self.root, "var/lib/ubuntu-advantage")
os.makedirs(d, exist_ok=True)
with open(os.path.join(d, "status.json"), "w") as f:
f.write(text)
def test_ubuntu_pro_attached_with_esm(self):
self.write_pro_status(json.dumps({"attached": True, "services": [
{"name": "esm-apps", "status": "enabled"}, {"name": "esm-infra", "status": "enabled"},
{"name": "livepatch", "status": "enabled"}]}))
r = self.report()
self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (True, "enabled"))
def test_ubuntu_pro_attached_esm_disabled(self):
self.write_pro_status(json.dumps({"attached": True, "services": [
{"name": "esm-infra", "status": "disabled"}]}))
r = self.report()
self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (True, "disabled"))
def test_ubuntu_pro_not_attached(self):
# Unattached, the cache lists services as available, which isn't the same as on.
self.write_pro_status(json.dumps({"attached": False, "services": [
{"name": "esm-infra", "available": "yes", "status": "enabled"}]}))
r = self.report()
self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (False, None))
def test_no_pro_client_or_unreadable_status(self):
r = self.report()
self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (None, None))
self.write_pro_status("{not json")
r = self.report()
self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (None, None))
def test_odd_esm_status_is_dropped(self):
self.write_pro_status(json.dumps({"attached": True, "services": [
{"name": "esm-infra", "status": "en abled\" x"}]}))
r = self.report()
self.assertEqual((r["ubuntu_pro_attached"], r["ubuntu_esm_infra"]), (True, None))
def write_root(self, path, text="", age=None):
path = os.path.join(self.root, path)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
f.write(text)
if age is not None:
t = time.time() - age
os.utime(path, (t, t))
def uu(self, status="ii ", setting=None):
self.write_root("dpkg-uu", status)
if setting is not None:
self.write_root("apt-config", f'APT::Periodic::Unattended-Upgrade "{setting}";\n')
def test_unattended_upgrades_enabled(self):
self.uu(setting="1")
self.write_root("var/lib/apt/periodic/upgrade-stamp", age=6 * 3600)
self.write_root("var/lib/apt/periodic/unattended-upgrades-stamp", age=6 * 3600)
r = self.report()
self.assertEqual(r["unattended_upgrades"], "enabled")
self.assertAlmostEqual(r["unattended_upgrades_success_age_seconds"], 6 * 3600, delta=60)
self.assertAlmostEqual(r["unattended_upgrades_run_age_seconds"], 6 * 3600, delta=60)
self.assertEqual(r["unattended_upgrades_kept_back"], [])
def test_unattended_upgrades_interval_other_than_1_counts_as_enabled(self):
for setting in ("7", "always"):
with self.subTest(setting=setting):
self.uu(setting=setting)
self.assertEqual(self.report()["unattended_upgrades"], "enabled")
def test_unattended_upgrades_switched_off(self):
for setting in ("0", ""):
with self.subTest(setting=setting):
self.uu(setting=setting)
self.assertEqual(self.report()["unattended_upgrades"], "disabled")
os.remove(os.path.join(self.root, "apt-config"))
self.assertEqual(self.report()["unattended_upgrades"], "disabled", "setting absent")
def test_unattended_upgrades_removed_but_config_left(self):
# dpkg state rc keeps /etc/apt/apt.conf.d/20auto-upgrades, so the setting still reads 1.
self.uu(status="rc ", setting="1")
self.assertEqual(self.report()["unattended_upgrades"], "not-installed")
def test_unattended_upgrades_not_installed(self):
r = self.report()
self.assertEqual(r["unattended_upgrades"], "not-installed")
self.assertIsNone(r["unattended_upgrades_success_age_seconds"])
self.assertIsNone(r["unattended_upgrades_run_age_seconds"])
def test_unattended_upgrades_kept_back(self):
self.uu(setting="1")
self.write_root("var/lib/unattended-upgrades/kept-back", "openssl libssl3t64 linux-image-amd64")
self.assertEqual(self.report()["unattended_upgrades_kept_back"],
["libssl3t64", "linux-image-amd64", "openssl"])
def test_every_reported_field_is_accepted_by_the_server(self): def test_every_reported_field_is_accepted_by_the_server(self):
from kernelwatch.report import FIELDS from kernelwatch.report import FIELDS
self.write_livepatch("LIVEPATCH-STATE: applied\nLIVEPATCH-FIXES: 2\n") self.write_livepatch("LIVEPATCH-STATE: applied\nLIVEPATCH-FIXES: 2\n")
self.write_pro_status('{"attached": true, "services": [{"name": "esm-infra", "status": "enabled"}]}')
self.assertEqual(sorted(set(self.report()) - set(FIELDS)), []) self.assertEqual(sorted(set(self.report()) - set(FIELDS)), [])
def write_conf(self, text): def write_conf(self, text):
@@ -271,6 +547,35 @@ X
stub(self.bin, "apt-get", '[ "$LC_ALL" = C ] || exit 1; echo "Inst ok [1] (2 x [amd64])"\n') stub(self.bin, "apt-get", '[ "$LC_ALL" = C ] || exit 1; echo "Inst ok [1] (2 x [amd64])"\n')
self.assertEqual(self.report()["upgradable_count"], 1) self.assertEqual(self.report()["upgradable_count"], 1)
def test_apt_simulation_ok(self):
r = self.report()
self.assertIs(r["apt_simulation_ok"], True)
self.assertIsNone(r["apt_simulation_error"])
def test_apt_failure_reports_unknown_counts_not_zero(self):
# A failed simulation prints no Inst lines; that must not read as "no updates".
stub(self.bin, "apt-get", "echo 'Reading package lists...'\n"
"echo 'W: Some warning' >&2\n"
"echo \"E: Unmet dependencies. Try 'apt --fix-broken install'.\" >&2\n"
"exit 100\n")
r = self.report()
self.assertIs(r["apt_simulation_ok"], False)
self.assertEqual(r["apt_simulation_error"], "Unmet dependencies. Try 'apt --fix-broken install'.")
for key in ("upgradable_count", "security_count", "kernel_upgradable", "phased_packages"):
self.assertIsNone(r[key], key)
def test_apt_failure_without_an_error_line(self):
stub(self.bin, "apt-get", "echo 'something broke' >&2\nexit 1\n")
self.assertEqual(self.report()["apt_simulation_error"], "something broke")
stub(self.bin, "apt-get", "exit 100\n")
self.assertEqual(self.report()["apt_simulation_error"], "apt-get exited with status 100")
def test_apt_warnings_dont_mix_into_the_simulation(self):
stub(self.bin, "apt-get", f"echo 'W: Inst fake [1] (2 x [amd64])' >&2\ncat <<'X'\n{APT_SIM_DEBIAN}X\n")
r = self.report()
self.assertIs(r["apt_simulation_ok"], True)
self.assertEqual(r["upgradable_count"], 3)
def test_hostile_strings_stay_valid_json(self): def test_hostile_strings_stay_valid_json(self):
stub(self.bin, "hostname", "printf 'a\"b\\\\c\\tq'\n") stub(self.bin, "hostname", "printf 'a\"b\\\\c\\tq'\n")
self.assertEqual(self.report()["reported_hostname"], 'a"b\\cq') self.assertEqual(self.report()["reported_hostname"], 'a"b\\cq')
@@ -279,6 +584,102 @@ X
os.remove(os.path.join(self.root, "var/lib/apt/periodic/update-success-stamp")) os.remove(os.path.join(self.root, "var/lib/apt/periodic/update-success-stamp"))
self.assertIsNone(self.report()["apt_lists_age_seconds"]) 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): def test_send_without_config_fails_cleanly(self):
proc = self.run_agent() proc = self.run_agent()
self.assertNotEqual(proc.returncode, 0) self.assertNotEqual(proc.returncode, 0)
+260
View File
@@ -341,6 +341,266 @@ class StatusAlertsTest(unittest.TestCase):
self.assertEqual(db.status_alerts(self.conn), {}) self.assertEqual(db.status_alerts(self.conn), {})
class BackupFailureAlertTest(unittest.TestCase):
def setUp(self):
self.tmp = tempdir()
self.addCleanup(self.tmp.cleanup)
self.dir = os.path.join(self.tmp.name, "backups")
self.cfg = temp_config(self.tmp.name, ntfy_url="https://ntfy.example.test/fleet",
backup_dir=self.dir)
stack = contextlib.ExitStack()
self.addCleanup(stack.close)
self.publish = stack.enter_context(mock.patch("kernelwatch.alerts.publish"))
self.output = stack.enter_context(contextlib.redirect_stdout(io.StringIO()))
self.errors = stack.enter_context(contextlib.redirect_stderr(io.StringIO()))
def touch(self, *names):
os.makedirs(self.dir, exist_ok=True)
for name in names:
open(os.path.join(self.dir, name), "w").close()
def test_sends_an_urgent_notification_naming_the_newest_backup(self):
self.touch("kernelwatch-2026-11-18.db", "kernelwatch-2026-11-19.db", "kernelwatch-2026-11-20.db.tmp-4")
self.assertEqual(alerts.notify_backup_failure(self.cfg), 0)
(cfg, title, message), kwargs = self.publish.call_args
self.assertEqual(title, "kernelwatch: nightly backup failed")
self.assertIn("Newest backup still on disk: kernelwatch-2026-11-19.db.", message)
self.assertIn("journalctl -u kernelwatch-backup", message)
self.assertTrue(kwargs["stale"]) # high priority
def test_says_when_there_is_no_backup_at_all(self):
self.assertEqual(alerts.notify_backup_failure(self.cfg), 0)
self.assertIn("Newest backup still on disk: none.", self.publish.call_args.args[2])
def test_delivery_failure_is_reported_and_fails_the_unit(self):
self.publish.side_effect = alerts.DeliveryError("ntfy returned HTTP 503")
self.assertEqual(alerts.notify_backup_failure(self.cfg), 1)
self.assertIn("ntfy returned HTTP 503", self.errors.getvalue())
def test_without_ntfy_it_says_so_and_does_not_fail(self):
cfg = dataclasses.replace(self.cfg, ntfy_url="")
self.assertEqual(alerts.notify_backup_failure(cfg), 0)
self.publish.assert_not_called()
self.assertIn("ntfy_url is not configured", self.errors.getvalue())
def test_cli_command(self):
path = os.path.join(self.tmp.name, "server.toml")
with open(path, "w") as f:
f.write(f'ntfy_url = "https://ntfy.example.test/fleet"\nbackup_dir = "{self.dir}"\n')
self.assertEqual(cli.main(["-c", path, "notify-backup-failure"]), 0)
self.assertEqual(self.publish.call_count, 1)
class LivepatchAlertsTest(unittest.TestCase):
"""Notify when Livepatch is unhealthy, or stops being reported, for too long."""
HEALTHY = {"livepatch_state": "applied", "livepatch_check_state": "checked",
"livepatch_supported": "supported", "livepatch_upgrade_required": "2099-01-01",
"livepatch_fix_count": 2}
def setUp(self):
self.tmp = tempdir()
self.addCleanup(self.tmp.cleanup)
self.cfg = temp_config(self.tmp.name, ntfy_url="https://ntfy.example.test/fleet",
status_alert_after_hours=0, livepatch_alert_after_hours=6.0)
db.init(self.cfg.db_path)
self.conn = db.connect(self.cfg.db_path)
self.addCleanup(self.conn.close)
self.now = NOW
clock = mock.patch("kernelwatch.alerts.time.time", side_effect=lambda: self.now)
clock.start()
self.addCleanup(clock.stop)
publisher = mock.patch("kernelwatch.alerts.publish")
self.publish = publisher.start()
self.addCleanup(publisher.stop)
stack = contextlib.ExitStack()
self.addCleanup(stack.close)
stack.enter_context(contextlib.redirect_stdout(io.StringIO()))
self.errors = stack.enter_context(contextlib.redirect_stderr(io.StringIO()))
db.add_host(self.conn, "web01", auth.token_hash(auth.new_token()))
def report(self, host="web01", livepatch=True, **fields):
payload = {"kernel_running": "6.8.0-136-generic", "apt_lists_age_seconds": 60}
if livepatch:
payload.update(self.HEALTHY)
payload.update(fields)
self.conn.execute("INSERT INTO reports (host, received_at, payload) VALUES (?, ?, ?)",
(host, self.now, json.dumps(payload)))
def hours(self, n):
self.now += int(n * 3600)
def run_check(self):
self.assertEqual(alerts.check(self.cfg), 0)
def titles(self):
return [c.args[1] for c in self.publish.call_args_list]
def test_unhealthy_state_alerts_once_after_the_grace_period(self):
self.report(livepatch_state="apply-failed")
self.run_check()
self.hours(5)
self.report(livepatch_state="apply-failed")
self.run_check()
self.publish.assert_not_called()
self.hours(1.1)
self.report(livepatch_state="apply-failed")
self.run_check()
self.assertEqual(self.titles(), ["kernelwatch: web01 Livepatch problem"])
(_, _, message), kwargs = self.publish.call_args
self.assertIn("livepatch not healthy (apply-failed, supported)", message)
self.assertIn("State: apply-failed, check: checked, supported: supported.", message)
self.assertIn("canonical-livepatch status", message)
self.assertTrue(kwargs["stale"]) # high priority
for _ in range(5): # never repeated while the same episode lasts
self.hours(1)
self.report(livepatch_state="apply-failed")
self.run_check()
self.assertEqual(self.publish.call_count, 1)
def test_each_kind_of_unhealthy_counts(self):
for fields in ({"livepatch_state": "applying"}, {"livepatch_check_state": "check-failed"},
{"livepatch_supported": "unsupported"}, {"livepatch_state": "kernel-upgrade-required"}):
with self.subTest(fields=fields):
self.publish.reset_mock()
db.remove_host(self.conn, "web01")
db.add_host(self.conn, "web01", auth.token_hash(auth.new_token()))
self.report(**fields)
self.run_check()
self.hours(7)
self.report(**fields)
self.run_check()
self.assertEqual(self.publish.call_count, 1)
def test_healthy_states_never_alert(self):
for state in ("applied", "nothing-to-apply"):
self.report(livepatch_state=state)
self.run_check()
self.hours(48)
self.report(livepatch_state=state)
self.run_check()
self.publish.assert_not_called()
def test_a_brief_problem_that_clears_never_alerts_and_resets_the_clock(self):
self.report(livepatch_check_state="check-failed")
self.run_check()
self.hours(5)
self.report()
self.run_check()
self.assertEqual(db.livepatch_alerts(self.conn)["web01"], (None, False))
self.hours(5) # a new problem starts a fresh grace period, not the old one
self.report(livepatch_check_state="check-failed")
self.run_check()
self.hours(5)
self.report(livepatch_check_state="check-failed")
self.run_check()
self.publish.assert_not_called()
def test_a_later_problem_alerts_again(self):
self.report(livepatch_state="apply-failed")
self.run_check()
self.hours(7)
self.report(livepatch_state="apply-failed")
self.run_check()
self.report()
self.run_check()
self.hours(1)
self.report(livepatch_state="apply-failed")
self.run_check()
self.hours(7)
self.report(livepatch_state="apply-failed")
self.run_check()
self.assertEqual(self.publish.call_count, 2)
def test_a_host_that_stops_reporting_livepatch_alerts(self):
self.report() # healthy: now known to use Livepatch
self.run_check()
self.assertIn("web01", db.livepatch_alerts(self.conn))
self.hours(1)
self.report(livepatch=False) # the daemon died; the agent has nothing to send
self.run_check()
self.hours(5)
self.report(livepatch=False)
self.run_check()
self.publish.assert_not_called()
self.hours(1.1)
self.report(livepatch=False)
self.run_check()
self.assertEqual(self.publish.call_count, 1)
message = self.publish.call_args.args[2]
self.assertIn("no longer being reported", message)
self.assertIn("It reported Livepatch before and no longer does", message)
def test_a_blip_of_missing_data_between_good_reports_is_forgiven(self):
self.report()
self.run_check()
self.hours(1)
self.report(livepatch=False) # e.g. snapd was restarting for one report
self.run_check()
self.hours(1)
self.report()
self.run_check()
self.hours(8)
self.report()
self.run_check()
self.publish.assert_not_called()
def test_hosts_that_never_had_livepatch_never_alert(self):
for _ in range(4):
self.report(livepatch=False)
self.run_check()
self.hours(24)
self.publish.assert_not_called()
self.assertEqual(db.livepatch_alerts(self.conn), {})
def test_stale_hosts_are_skipped(self):
self.report(livepatch_state="apply-failed")
self.run_check()
self.hours(20) # no reports since: stale, so only the stale alert speaks
self.run_check()
self.assertEqual(self.titles(), ["kernelwatch: web01 is stale"])
def test_failed_delivery_is_retried_until_it_succeeds(self):
self.report(livepatch_state="apply-failed")
self.run_check()
self.hours(7)
self.report(livepatch_state="apply-failed")
self.publish.side_effect = alerts.DeliveryError("ntfy returned HTTP 503")
self.assertEqual(alerts.check(self.cfg), 1)
self.assertEqual(db.livepatch_alerts(self.conn)["web01"][1], False)
self.assertIn("notification failed for web01", self.errors.getvalue())
self.publish.side_effect = None
self.run_check()
self.assertEqual(db.livepatch_alerts(self.conn)["web01"][1], True)
self.run_check()
self.assertEqual(self.publish.call_count, 2) # the failed try and the one that landed
def test_zero_disables_it(self):
cfg = dataclasses.replace(self.cfg, livepatch_alert_after_hours=0)
self.report(livepatch_state="apply-failed")
self.assertEqual(alerts.check(cfg), 0)
self.hours(100)
self.report(livepatch_state="apply-failed")
self.assertEqual(alerts.check(cfg), 0)
self.publish.assert_not_called()
self.assertEqual(db.livepatch_alerts(self.conn), {})
def test_removing_a_host_forgets_it(self):
self.report()
self.run_check()
db.remove_host(self.conn, "web01")
self.assertEqual(db.livepatch_alerts(self.conn), {})
def test_state_is_only_written_when_it_changes(self):
self.report()
self.run_check()
with mock.patch("kernelwatch.alerts.db.save_livepatch_alert") as save:
self.hours(1)
self.report()
self.run_check()
save.assert_not_called()
class NtfyHTTPTest(unittest.TestCase): class NtfyHTTPTest(unittest.TestCase):
def setUp(self): def setUp(self):
class Sink(BaseHTTPRequestHandler): class Sink(BaseHTTPRequestHandler):
+135 -1
View File
@@ -1,14 +1,17 @@
"""kernelwatch backup: consistent copy, permissions, and refusal to clobber the live DB.""" """kernelwatch backup: consistent copy, permissions, and refusal to clobber the live DB."""
import calendar
import contextlib import contextlib
import io import io
import os import os
import sqlite3 import sqlite3
import stat import stat
import time
import unittest import unittest
from unittest import mock
from helpers import temp_config, tempdir from helpers import temp_config, tempdir
from kernelwatch import auth, cli, db from kernelwatch import auth, cli, config, db
class BackupTest(unittest.TestCase): class BackupTest(unittest.TestCase):
@@ -65,5 +68,136 @@ class BackupTest(unittest.TestCase):
self.assertFalse([n for n in os.listdir(self.tmp.name) if ".tmp-" in n]) self.assertFalse([n for n in os.listdir(self.tmp.name) if ".tmp-" in n])
NOW = calendar.timegm((2026, 11, 20, 3, 30, 0))
def day(offset):
return time.strftime("kernelwatch-%Y-%m-%d.db", time.gmtime(NOW + offset * 86400))
class RotateBackupsTest(unittest.TestCase):
def setUp(self):
self.tmp = tempdir()
self.addCleanup(self.tmp.cleanup)
self.db_path = os.path.join(self.tmp.name, "kw.db")
self.dir = os.path.join(self.tmp.name, "backups")
db.init(self.db_path)
conn = db.connect(self.db_path)
self.addCleanup(conn.close)
db.add_host(conn, "web01", auth.token_hash("tok"))
def touch(self, name):
os.makedirs(self.dir, exist_ok=True)
with open(os.path.join(self.dir, name), "w") as f:
f.write("x")
def names(self):
return sorted(os.listdir(self.dir))
def rotate(self, keep=7, now=NOW):
return db.rotate_backups(self.db_path, self.dir, keep, now)
def test_writes_a_dated_private_copy_and_creates_the_directory(self):
dest = self.rotate()
self.assertEqual(dest, os.path.join(self.dir, "kernelwatch-2026-11-20.db"))
self.assertEqual(stat.S_IMODE(os.stat(self.dir).st_mode), 0o700)
self.assertEqual(stat.S_IMODE(os.stat(dest).st_mode), 0o600)
copy = sqlite3.connect(dest)
self.addCleanup(copy.close)
self.assertEqual(copy.execute("SELECT name FROM hosts").fetchall(), [("web01",)])
def test_same_day_replaces_the_file(self):
self.rotate()
self.rotate()
self.assertEqual(self.names(), [day(0)])
def test_prunes_by_age_and_keeps_the_boundary(self):
for offset in range(-10, 0):
self.touch(day(offset))
self.rotate(keep=7)
# keep=7 keeps today and the six days before it.
self.assertEqual(self.names(), sorted(day(o) for o in range(-6, 1)))
def test_only_dated_backup_files_are_ever_deleted(self):
keepers = ["kernelwatch.db", "notes.txt", "kernelwatch-2020-01-01.db.bak",
"kernelwatch-2020-01-01.db.tmp-1", "kernelwatch-2020-13-45.db",
"other-2020-01-01.db"]
for name in keepers + [day(-30)]:
self.touch(name)
self.rotate(keep=7)
self.assertEqual(self.names(), sorted(keepers + [day(0)]))
def test_zero_keeps_everything(self):
for offset in (-400, -30, -8):
self.touch(day(offset))
self.rotate(keep=0)
self.assertEqual(len(self.names()), 4)
def test_a_failed_backup_prunes_nothing(self):
for offset in (-30, -1):
self.touch(day(offset))
with mock.patch("kernelwatch.db.backup", side_effect=sqlite3.OperationalError("disk full")):
with self.assertRaises(sqlite3.OperationalError):
self.rotate(keep=7)
self.assertEqual(self.names(), sorted([day(-30), day(-1)]))
def test_the_live_database_is_never_pruned(self):
os.makedirs(self.dir)
live = os.path.join(self.dir, "kernelwatch-2000-01-01.db")
db.init(live)
with self.assertRaisesRegex(ValueError, "live database"):
db.rotate_backups(live, self.dir, 7, calendar.timegm((2000, 1, 1, 0, 0, 0)))
self.assertTrue(os.path.exists(live))
class ScheduledBackupCommandTest(unittest.TestCase):
def setUp(self):
self.tmp = tempdir()
self.addCleanup(self.tmp.cleanup)
self.dir = os.path.join(self.tmp.name, "backups")
self.config_path = os.path.join(self.tmp.name, "server.toml")
self.write_config(f'db_path = "{self.tmp.name}/kw.db"\nbackup_dir = "{self.dir}"\nbackup_keep_days = 3\n')
def write_config(self, text):
with open(self.config_path, "w") as f:
f.write(text)
def run_cli(self):
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = cli.main(["-c", self.config_path, "scheduled-backup"])
return code, out.getvalue(), err.getvalue()
def test_backs_up_to_the_configured_directory_and_prunes_with_the_configured_age(self):
os.makedirs(self.dir)
old = os.path.join(self.dir, "kernelwatch-2020-01-01.db")
open(old, "w").close()
code, out, _ = self.run_cli()
self.assertEqual(code, 0)
today = time.strftime("kernelwatch-%Y-%m-%d.db", time.gmtime())
self.assertIn(os.path.join(self.dir, today), out)
self.assertEqual(os.listdir(self.dir), [today])
def test_failure_exits_nonzero(self):
with open(os.path.join(self.tmp.name, "blocker"), "w") as f:
f.write("a file where the directory should go")
self.write_config(f'db_path = "{self.tmp.name}/kw.db"\nbackup_dir = "{self.tmp.name}/blocker/x"\n')
code, _, err = self.run_cli()
self.assertEqual(code, 1)
self.assertIn("scheduled backup failed", err)
def test_config_defaults_and_validation(self):
cfg = config.Config()
self.assertEqual((cfg.backup_dir, cfg.backup_keep_days), ("/var/lib/kernelwatch/backups", 7))
for bad in ("backup_keep_days = -1", 'backup_dir = ""', 'backup_dir = "relative/dir"',
"backup_keep_days = 1.5", "backup_dir = 5"):
with self.subTest(bad=bad):
self.write_config(bad + "\n")
with self.assertRaises(SystemExit):
config.load(self.config_path)
self.write_config("backup_keep_days = 0\n")
self.assertEqual(config.load(self.config_path).backup_keep_days, 0)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+158
View File
@@ -0,0 +1,158 @@
"""kernelwatch status [--json]: the fleet as the dashboard sees it, for scripts."""
import calendar
import contextlib
import io
import json
import os
import unittest
from unittest import mock
from helpers import tempdir
from kernelwatch import AGENT_VERSION, auth, cli, db
from kernelwatch.status import evaluate
NOW = calendar.timegm((2026, 11, 20, 12, 0, 0))
GOOD = {"kernel_running": "6.12.57", "kernel_newest_installed": "6.12.57", "needrestart_ksta": 1,
"apt_lists_age_seconds": 60, "upgradable_count": 0, "security_count": 0,
"os_pretty_name": "Debian 13", "agent_version": AGENT_VERSION}
class StatusCommandTest(unittest.TestCase):
def setUp(self):
self.tmp = tempdir()
self.addCleanup(self.tmp.cleanup)
self.config_path = os.path.join(self.tmp.name, "server.toml")
self.db_path = os.path.join(self.tmp.name, "kw.db")
with open(self.config_path, "w") as f:
f.write(f'db_path = "{self.db_path}"\n')
db.init(self.db_path)
self.conn = db.connect(self.db_path)
self.addCleanup(self.conn.close)
self.add("app01", GOOD)
self.add("db01", dict(GOOD, security_count=3, upgradable_count=7))
self.add("web01", dict(GOOD, kernel_running="6.8.0-136", kernel_newest_installed="6.8.0-138",
needrestart_ksta=None))
self.add("old01", GOOD, age=10 * 3600)
db.add_host(self.conn, "new01", auth.token_hash("tok-new01"))
clock = mock.patch("kernelwatch.cli.time.time", return_value=NOW)
clock.start()
self.addCleanup(clock.stop)
def add(self, name, payload, age=60):
db.add_host(self.conn, name, auth.token_hash("tok-" + name))
db.add_report(self.conn, name, payload, 30)
self.conn.execute("UPDATE reports SET received_at = ? WHERE host = ?", (NOW - age, name))
def run_cli(self, *args):
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = cli.main(["-c", self.config_path, "status", *args])
return code, out.getvalue(), err.getvalue()
def fleet(self, *args):
code, out, err = self.run_cli("--json", *args)
self.assertEqual((code, err), (0, ""))
return json.loads(out)
def names(self, fleet):
return [h["name"] for h in fleet["hosts"]]
def test_worst_first_then_by_name_like_the_dashboard(self):
fleet = self.fleet()
self.assertEqual(self.names(fleet), ["new01", "old01", "web01", "db01", "app01"])
self.assertEqual([h["status"] for h in fleet["hosts"]], ["stale", "stale", "reboot", "update", "ok"])
self.assertEqual(fleet["counts"], {"stale": 2, "reboot": 1, "update": 1, "ok": 1})
self.assertEqual(fleet["generated_at"], "2026-11-20T12:00:00Z")
def test_status_and_reasons_are_exactly_what_evaluate_says(self):
from kernelwatch.config import Config
for row, entry in zip(sorted(db.latest_reports(self.conn), key=lambda r: r["host"]),
sorted(self.fleet()["hosts"], key=lambda h: h["name"])):
expected = evaluate(row["received_at"], row["report"], NOW, Config(db_path=self.db_path), row["host"])
self.assertEqual((entry["status"], entry["reasons"]), (expected.level, expected.reasons), row["host"])
def test_host_fields(self):
web = next(h for h in self.fleet()["hosts"] if h["name"] == "web01")
self.assertEqual(web["last_report_at"], "2026-11-20T11:59:00Z")
self.assertEqual(web["last_report_age_seconds"], 60)
self.assertEqual((web["kernel_running"], web["kernel_newest_installed"]), ("6.8.0-136", "6.8.0-138"))
self.assertEqual((web["os"], web["agent_version"]), ("Debian 13", AGENT_VERSION))
db_host = next(h for h in self.fleet()["hosts"] if h["name"] == "db01")
self.assertEqual((db_host["updates_pending"], db_host["security_updates"]), (7, 3))
self.assertEqual(db_host["reasons"], ["3 security updates pending"])
self.assertIsNone(db_host["livepatch"])
def test_a_host_that_never_reported_has_nulls_not_missing_keys(self):
new = next(h for h in self.fleet()["hosts"] if h["name"] == "new01")
self.assertEqual(new["reasons"], ["never reported"])
keys = set(next(h for h in self.fleet()["hosts"] if h["name"] == "app01"))
self.assertEqual(set(new), keys)
self.assertIsNone(new["last_report_at"])
self.assertIsNone(new["last_report_age_seconds"])
self.assertIsNone(new["kernel_running"])
def test_livepatch_is_included_when_reported(self):
self.add("lp01", dict(GOOD, livepatch_state="applied", livepatch_supported="supported",
livepatch_upgrade_required="2027-10-14", livepatch_fix_count=2))
lp = next(h for h in self.fleet()["hosts"] if h["name"] == "lp01")
self.assertEqual(lp["livepatch"], {"state": "applied", "supported": "supported",
"upgrade_required": "2027-10-14", "fixes": 2})
def test_hostname_mismatch_note_matches_the_dashboard(self):
self.add("iris", dict(GOOD, reported_hostname="web.beane.me"))
iris = next(h for h in self.fleet()["hosts"] if h["name"] == "iris")
self.assertTrue(any("registered as iris but reports itself as web.beane.me" in r
for r in iris["reasons"]))
def test_nothing_secret_is_printed(self):
_, out, _ = self.run_cli("--json")
text = self.run_cli()[1]
for secret in ("tok-", auth.token_hash("tok-web01"), "token_hash", "pw_hash"):
self.assertNotIn(secret, out + text)
def test_level_filter_trims_hosts_but_not_counts(self):
fleet = self.fleet("--level", "reboot")
self.assertEqual(self.names(fleet), ["web01"])
self.assertEqual(fleet["counts"], {"stale": 2, "reboot": 1, "update": 1, "ok": 1})
self.assertEqual(self.names(self.fleet("--level", "reboot", "--level", "update")), ["web01", "db01"])
self.assertEqual(self.names(self.fleet("--level", "ok")), ["app01"])
def test_host_filter(self):
self.assertEqual(self.names(self.fleet("--host", "db01")), ["db01"])
code, out, err = self.run_cli("--json", "--host", "nope")
self.assertEqual((code, out), (1, ""))
self.assertIn("no such host 'nope'", err)
def test_filters_combine(self):
self.assertEqual(self.names(self.fleet("--host", "db01", "--level", "reboot")), [])
def test_bad_arguments_are_rejected_by_argparse(self):
for args in (("--level", "broken"), ("--host", "bad host!"), ("--bogus",)):
with self.subTest(args=args), contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(SystemExit) as raised:
self.run_cli(*args)
self.assertEqual(raised.exception.code, 2)
def test_empty_fleet(self):
for table in ("reports", "hosts"):
self.conn.execute(f"DELETE FROM {table}")
fleet = self.fleet()
self.assertEqual((fleet["hosts"], sum(fleet["counts"].values())), ([], 0))
self.assertEqual(self.run_cli()[1], "0 hosts: 0 stale, 0 reboot, 0 update, 0 ok\n")
def test_text_output(self):
code, out, err = self.run_cli()
self.assertEqual((code, err), (0, ""))
lines = out.splitlines()
self.assertEqual(lines[-1], "5 hosts: 2 stale, 1 reboot, 1 update, 1 ok")
self.assertIn("reboot web01 6.8.0-136 -> 6.8.0-138 (last seen 1m ago)", lines)
self.assertIn(" - 3 security updates pending", lines)
self.assertIn("stale new01 ? (last seen never)", lines)
self.assertIn("ok app01 6.12.57 (last seen 1m ago)", lines)
self.assertEqual(self.run_cli("--host", "db01", "--level", "update")[1].count("\n"), 3)
if __name__ == "__main__":
unittest.main()
+125 -2
View File
@@ -60,7 +60,7 @@ class DeployTest(unittest.TestCase):
for name in ("deploy.sh", "kernelwatch-agent", "kernelwatch-agent.service", for name in ("deploy.sh", "kernelwatch-agent", "kernelwatch-agent.service",
"kernelwatch-agent.timer", "kernelwatch-needrestart.service", "kernelwatch-agent.timer", "kernelwatch-needrestart.service",
"kernelwatch-livepatch", "kernelwatch-livepatch.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) shutil.copy2(os.path.join(AGENT_DIR, name), self.agent)
write_exec(os.path.join(self.agent, "install.sh"), FAKE_INSTALL) write_exec(os.path.join(self.agent, "install.sh"), FAKE_INSTALL)
@@ -189,6 +189,111 @@ class DeployTest(unittest.TestCase):
self.assertNotEqual(proc.returncode, 0) self.assertNotEqual(proc.returncode, 0)
self.assertIn("deploy.conf.example", proc.stderr) 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): class PackagingTest(unittest.TestCase):
@@ -205,11 +310,29 @@ class PackagingTest(unittest.TestCase):
def test_apt_update_is_opt_in_and_runs_before_reports(self): def test_apt_update_is_opt_in_and_runs_before_reports(self):
unit = self.read("kernelwatch-apt-update.service") unit = self.read("kernelwatch-apt-update.service")
self.assertIn("ConditionPathExists=/etc/kernelwatch/apt-update", unit) 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") agent = self.read("kernelwatch-agent.service")
for key in ("Wants=", "After="): for key in ("Wants=", "After="):
line = next(l for l in agent.splitlines() if l.startswith(key)) line = next(l for l in agent.splitlines() if l.startswith(key))
self.assertIn("kernelwatch-apt-update.service", line) 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__": if __name__ == "__main__":
+71
View File
@@ -0,0 +1,71 @@
"""The README and docs/ pages link to each other; keep those links from rotting."""
import os
import re
import unittest
from helpers import REPO
PAGES = ["README.md"] + sorted(f"docs/{n}" for n in os.listdir(os.path.join(REPO, "docs"))
if n.endswith(".md"))
def read(rel):
with open(os.path.join(REPO, rel)) as f:
return f.read()
def strip_code(text):
"""Drop fenced blocks and inline code, where `[x](y)` is an example, not a link."""
text = re.sub(r"^```.*?^```", "", text, flags=re.S | re.M)
return re.sub(r"`[^`\n]*`", "", text)
def slug(heading):
"""The anchor Gitea/GitHub make for a heading."""
heading = heading.replace("`", "").strip().lower()
return re.sub(r"\s", "-", re.sub(r"[^\w\s-]", "", heading))
def anchors(rel):
text = re.sub(r"^```.*?^```", "", read(rel), flags=re.S | re.M)
return {slug(m.group(2)) for m in re.finditer(r"^(#{1,6})\s+(.*)$", text, re.M)}
def links(rel):
for m in re.finditer(r"\[[^\]]*\]\(([^)\s]+)\)", strip_code(read(rel)).replace("\n", " ")):
target = m.group(1)
if not re.match(r"[a-z]+:", target): # skip https:, mailto:
yield target
class DocsLinksTest(unittest.TestCase):
def test_relative_links_and_anchors_resolve(self):
problems = []
for page in PAGES:
for target in links(page):
path, _, fragment = target.partition("#")
dest = os.path.normpath(os.path.join(os.path.dirname(page), path)) if path else page
if not os.path.exists(os.path.join(REPO, dest)):
problems.append(f"{page}: {target} -> {dest} does not exist")
elif fragment and dest.endswith(".md") and fragment not in anchors(dest):
problems.append(f"{page}: {target} -> no heading #{fragment} in {dest}")
self.assertEqual(problems, [])
def test_every_docs_page_is_linked_from_the_readme(self):
linked = {os.path.normpath(t.partition("#")[0]) for t in links("README.md")}
self.assertEqual(sorted(set(PAGES[1:]) - linked), [])
def test_every_docs_page_links_back_to_the_readme(self):
for page in PAGES[1:]:
self.assertIn("../README.md", set(links(page)), page)
def test_slug_matches_how_gitea_names_anchors(self):
self.assertEqual(slug("Heartbeat: is kernelwatch itself running?"),
"heartbeat-is-kernelwatch-itself-running")
self.assertEqual(slug("Scripting: `kernelwatch status`"), "scripting-kernelwatch-status")
self.assertEqual(slug("Authelia (forward auth)"), "authelia-forward-auth")
if __name__ == "__main__":
unittest.main()
+194
View File
@@ -0,0 +1,194 @@
"""Heartbeat pings: real HTTP requests to a local server, and when the commands send them."""
import contextlib
import io
import os
import threading
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from unittest import mock
from helpers import tempdir
from kernelwatch import alerts, cli, config
SECRET = "0f1e2d3c-secret-uuid"
class HeartbeatCase(unittest.TestCase):
def setUp(self):
class Sink(BaseHTTPRequestHandler):
def do_GET(self):
self.server.hits.append((self.path, dict(self.headers)))
self.send_response(self.server.code)
if self.server.code in (301, 302):
self.send_header("Location", "/elsewhere")
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *args):
pass
self.server = ThreadingHTTPServer(("127.0.0.1", 0), Sink)
self.server.hits, self.server.code = [], 200
threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.01},
daemon=True).start()
self.addCleanup(self.server.server_close)
self.addCleanup(self.server.shutdown)
self.base = f"http://127.0.0.1:{self.server.server_port}"
self.hits = self.server.hits
stack = contextlib.ExitStack()
self.addCleanup(stack.close)
self.out = stack.enter_context(contextlib.redirect_stdout(io.StringIO()))
self.err = stack.enter_context(contextlib.redirect_stderr(io.StringIO()))
class PingTest(HeartbeatCase):
def test_get_with_path_and_query_intact(self):
self.assertTrue(alerts.ping(f"{self.base}/ping/{SECRET}?status=up&msg=OK"))
self.assertEqual([h[0] for h in self.hits], [f"/ping/{SECRET}?status=up&msg=OK"])
self.assertEqual(self.hits[0][1]["User-Agent"], "kernelwatch")
def test_any_2xx_is_success(self):
for code in (200, 201, 204):
self.server.code = code
self.assertTrue(alerts.ping(f"{self.base}/p"), code)
def test_other_statuses_fail_without_leaking_the_url(self):
for code in (302, 400, 404, 429, 500, 503):
with self.subTest(code=code):
self.server.code = code
self.assertFalse(alerts.ping(f"{self.base}/ping/{SECRET}"))
self.assertEqual(len(self.hits), 6, "redirects must not be followed")
self.assertIn("HTTP 503", self.err.getvalue())
self.assertNotIn(SECRET, self.err.getvalue() + self.out.getvalue())
def test_unreachable_server_fails_without_leaking_the_url(self):
self.server.shutdown()
self.server.server_close()
self.assertFalse(alerts.ping(f"{self.base}/ping/{SECRET}"))
self.assertIn("heartbeat request failed", self.err.getvalue())
self.assertNotIn(SECRET, self.err.getvalue())
def test_timeout_is_bounded(self):
with mock.patch("kernelwatch.alerts.build_opener") as opener:
opener.return_value.open.side_effect = TimeoutError(f"timed out {SECRET}")
self.assertFalse(alerts.ping(f"https://hc.example/{SECRET}"))
self.assertEqual(opener.return_value.open.call_args.kwargs["timeout"],
alerts.HEARTBEAT_TIMEOUT_SECONDS)
self.assertNotIn(SECRET, self.err.getvalue())
class CommandsTest(HeartbeatCase):
def setUp(self):
super().setUp()
self.tmp = tempdir()
self.addCleanup(self.tmp.cleanup)
self.config_path = os.path.join(self.tmp.name, "server.toml")
def configure(self, **values):
lines = [f'db_path = "{self.tmp.name}/kw.db"', f'backup_dir = "{self.tmp.name}/backups"']
lines += [f'{k} = "{v}"' for k, v in values.items()]
with open(self.config_path, "w") as f:
f.write("\n".join(lines) + "\n")
def run_cli(self, *args):
return cli.main(["-c", self.config_path, *args])
def test_check_alerts_pings_after_a_clean_run(self):
self.configure(heartbeat_url=f"{self.base}/hb")
self.assertEqual(self.run_cli("check-alerts"), 0)
self.assertEqual([h[0] for h in self.hits], ["/hb"])
def test_check_alerts_pings_even_without_ntfy(self):
# The timer is still alive, which is what the heartbeat reports.
self.configure(heartbeat_url=f"{self.base}/hb")
with mock.patch("kernelwatch.alerts.publish") as publish:
self.run_cli("check-alerts")
publish.assert_not_called()
self.assertEqual(len(self.hits), 1)
def test_no_ping_when_notifications_failed(self):
self.configure(heartbeat_url=f"{self.base}/hb")
with mock.patch("kernelwatch.cli.alerts.check", return_value=2):
self.assertEqual(self.run_cli("check-alerts"), 1)
self.assertEqual(self.hits, [])
def test_no_ping_when_the_check_crashes(self):
self.configure(heartbeat_url=f"{self.base}/hb")
with mock.patch("kernelwatch.cli.alerts.check", side_effect=RuntimeError("db locked")):
with self.assertRaises(RuntimeError):
self.run_cli("check-alerts")
self.assertEqual(self.hits, [])
def test_nothing_is_pinged_unless_configured(self):
self.configure()
self.assertEqual(self.run_cli("check-alerts"), 0)
self.assertEqual(self.run_cli("scheduled-backup"), 0)
self.assertEqual(self.hits, [])
def test_a_dead_heartbeat_never_fails_the_check(self):
self.server.code = 500
self.configure(heartbeat_url=f"{self.base}/hb")
self.assertEqual(self.run_cli("check-alerts"), 0)
self.assertIn("HTTP 500", self.err.getvalue())
def test_backup_pings_its_own_url_only_on_success(self):
self.configure(heartbeat_url=f"{self.base}/alerts", backup_heartbeat_url=f"{self.base}/backup")
self.assertEqual(self.run_cli("scheduled-backup"), 0)
self.assertEqual([h[0] for h in self.hits], ["/backup"])
del self.hits[:]
with mock.patch("kernelwatch.db.rotate_backups", side_effect=OSError("disk full")):
self.assertEqual(self.run_cli("scheduled-backup"), 1)
self.assertEqual(self.hits, [])
def test_a_dead_backup_heartbeat_never_fails_the_backup(self):
self.server.code = 503
self.configure(backup_heartbeat_url=f"{self.base}/backup")
self.assertEqual(self.run_cli("scheduled-backup"), 0)
self.assertTrue(os.listdir(os.path.join(self.tmp.name, "backups")))
def test_manual_backup_does_not_ping(self):
self.configure(backup_heartbeat_url=f"{self.base}/backup")
self.assertEqual(self.run_cli("backup", os.path.join(self.tmp.name, "manual.db")), 0)
self.assertEqual(self.hits, [])
def test_test_heartbeat_reports_each_url(self):
self.configure(heartbeat_url=f"{self.base}/a", backup_heartbeat_url=f"{self.base}/b")
self.assertEqual(self.run_cli("test-heartbeat"), 0)
self.assertEqual(self.out.getvalue().splitlines(), ["heartbeat_url: ok", "backup_heartbeat_url: ok"])
self.server.code = 404
self.assertEqual(self.run_cli("test-heartbeat"), 1)
self.assertIn("heartbeat_url: FAILED", self.out.getvalue())
def test_test_heartbeat_needs_a_url(self):
self.configure()
self.assertEqual(self.run_cli("test-heartbeat"), 1)
self.assertIn("neither heartbeat_url nor backup_heartbeat_url", self.err.getvalue())
class ConfigTest(unittest.TestCase):
def load(self, text):
with tempdir() as tmp:
path = os.path.join(tmp, "server.toml")
with open(path, "w") as f:
f.write(text)
return config.load(path)
def test_accepts_plain_and_query_urls(self):
for url in ("https://hc-ping.com/0f1e2d3c", "http://kuma.example:3001/api/push/abc?status=up&msg=OK&ping="):
cfg = self.load(f'heartbeat_url = "{url}"\nbackup_heartbeat_url = "{url}"\n')
self.assertEqual((cfg.heartbeat_url, cfg.backup_heartbeat_url), (url, url))
def test_defaults_to_disabled(self):
self.assertEqual((config.Config().heartbeat_url, config.Config().backup_heartbeat_url), ("", ""))
def test_rejects_bad_urls(self):
for key in ("heartbeat_url", "backup_heartbeat_url"):
for bad in ("hc-ping.com/x", "ftp://hc.example/x", "https://", "https://hc.example/a b",
"https://hc.example/x#frag", "https://hc.example:0/x", "https://hc.example:bad/x"):
with self.subTest(key=key, bad=bad), self.assertRaises(SystemExit):
self.load(f'{key} = "{bad}"\n')
if __name__ == "__main__":
unittest.main()
+47 -2
View File
@@ -122,7 +122,7 @@ class AgentInstallTest(InstallCase):
def test_installs_every_agent_script_and_unit(self): def test_installs_every_agent_script_and_unit(self):
self.fresh() 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) installed = self.path("usr/local/sbin", script)
self.assertEqual(read(installed), read(os.path.join(AGENT_DIR, script))) self.assertEqual(read(installed), read(os.path.join(AGENT_DIR, script)))
self.assertEqual(mode(installed), 0o755) self.assertEqual(mode(installed), 0o755)
@@ -306,7 +306,7 @@ class ServerInstallTest(InstallCase):
self.assertEqual(self.systemctl(), [ self.assertEqual(self.systemctl(), [
"daemon-reload", "enable kernelwatch.service", "restart kernelwatch.service", "daemon-reload", "enable kernelwatch.service", "restart kernelwatch.service",
"enable --now kernelwatch-alerts.timer"]) "enable --now kernelwatch-alerts.timer", "enable --now kernelwatch-backup.timer"])
self.assertIn("listen_host = \"127.0.0.1\"", proc.stdout) self.assertIn("listen_host = \"127.0.0.1\"", proc.stdout)
self.assertIn("set-password admin", proc.stdout) self.assertIn("set-password admin", proc.stdout)
@@ -317,6 +317,51 @@ class ServerInstallTest(InstallCase):
for unit in units: for unit in units:
self.assertEqual(mode(self.path("etc/systemd/system", unit)), 0o644) self.assertEqual(mode(self.path("etc/systemd/system", unit)), 0o644)
def test_unit_commands_exist_in_the_cli(self):
"""Every `kernelwatch-server <command>` a unit runs must be a real subcommand."""
help_text = subprocess.run(["python3", "-I", os.path.join(SERVER_DIR, "kernelwatch-server"), "--help"],
capture_output=True, text=True, timeout=30).stdout
commands = set()
for unit in os.listdir(SERVER_DIR):
if unit.endswith(".service"):
commands.update(re.findall(r"kernelwatch-server (\S+)$", read(os.path.join(SERVER_DIR, unit)), re.M))
self.assertTrue(commands)
for command in commands:
self.assertRegex(help_text, rf"\b{re.escape(command)}\b")
def test_units_that_send_requests_have_network_access(self):
"""These commands ping a heartbeat or send to ntfy. A unit that runs one with its
network sandboxed away fails only in a log line (the request fails, the run
doesn't), so the heartbeat monitor just goes quiet."""
outbound = {"check-alerts", "scheduled-backup", "notify-backup-failure"}
checked = set()
for unit in os.listdir(SERVER_DIR):
if not unit.endswith(".service"):
continue
text = read(os.path.join(SERVER_DIR, unit))
if not outbound & set(re.findall(r"kernelwatch-server (\S+)$", text, re.M)):
continue
checked.add(unit)
with self.subTest(unit=unit):
self.assertNotRegex(text, r"(?m)^PrivateNetwork=(yes|true|1|on)$")
self.assertNotRegex(text, r"(?m)^IPAddressDeny=")
families = re.findall(r"(?m)^RestrictAddressFamilies=(.*)$", text)
self.assertTrue(families, "set RestrictAddressFamilies= explicitly")
for line in families:
self.assertFalse(line.startswith("~"))
self.assertTrue({"AF_INET", "AF_INET6"} <= set(line.split()), line)
self.assertEqual(checked, {"kernelwatch-alerts.service", "kernelwatch-backup.service",
"kernelwatch-backup-failed.service"})
def test_on_failure_targets_are_shipped_units(self):
"""A typo'd OnFailure= is silently ignored by systemd, so check the names."""
units = {n for n in os.listdir(SERVER_DIR) if n.endswith((".service", ".timer"))}
targets = set()
for unit in units:
targets.update(re.findall(r"^OnFailure=(\S+)$", read(os.path.join(SERVER_DIR, unit)), re.M))
self.assertIn("kernelwatch-backup-failed.service", targets)
self.assertEqual(sorted(targets - units), [])
def test_existing_user_is_not_recreated(self): def test_existing_user_is_not_recreated(self):
self.install(KW_ID_RC="0") self.install(KW_ID_RC="0")
self.assertFalse([c for c in self.calls() if c.startswith("useradd")]) self.assertFalse([c for c in self.calls() if c.startswith("useradd")])
+51
View File
@@ -75,6 +75,15 @@ 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"report_min_interval_seconds = {bad}\n")) config.load(self.write(tmp, f"report_min_interval_seconds = {bad}\n"))
def test_livepatch_alert_hours_validated(self):
with tempdir() as tmp:
self.assertEqual(config.Config().livepatch_alert_after_hours, 6.0)
self.assertEqual(config.load(self.write(tmp, "livepatch_alert_after_hours = 0\n"))
.livepatch_alert_after_hours, 0)
for bad in ("-1", "inf", "nan", '"6"'):
with self.subTest(bad=bad), self.assertRaises(SystemExit):
config.load(self.write(tmp, f"livepatch_alert_after_hours = {bad}\n"))
def test_status_alert_hours_validated(self): def test_status_alert_hours_validated(self):
with tempdir() as tmp: with tempdir() as tmp:
self.assertEqual(config.load(self.write(tmp, "status_alert_after_hours = 0\n")) self.assertEqual(config.load(self.write(tmp, "status_alert_after_hours = 0\n"))
@@ -83,6 +92,48 @@ 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"status_alert_after_hours = {bad}\n")) config.load(self.write(tmp, f"status_alert_after_hours = {bad}\n"))
def test_boot_min_free_validated(self):
with tempdir() as tmp:
self.assertEqual(config.Config().boot_min_free_mb, 200)
self.assertEqual(config.load(self.write(tmp, "boot_min_free_mb = 0\n")).boot_min_free_mb, 0)
for bad in ("-1", "1.5", '"200"'):
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)
self.assertEqual(config.load(self.write(tmp, "os_eol_warn_days = 0\n")).os_eol_warn_days, 0)
for bad in ("-1", "1.5"):
with self.subTest(bad=bad), self.assertRaises(SystemExit):
config.load(self.write(tmp, f"os_eol_warn_days = {bad}\n"))
def test_unattended_upgrades_stale_days_validated(self):
with tempdir() as tmp:
self.assertEqual(config.Config().unattended_upgrades_stale_after_days, 3.0)
self.assertEqual(config.load(self.write(tmp, "unattended_upgrades_stale_after_days = 0\n"))
.unattended_upgrades_stale_after_days, 0)
for bad in ("-1", "inf", "nan", '"3"'):
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): def test_fallback_parser_matches_tomllib(self):
"""Python 3.10 has no tomllib; the fallback must read the same configs.""" """Python 3.10 has no tomllib; the fallback must read the same configs."""
if config.tomllib is None: if config.tomllib is None:
+284 -1
View File
@@ -37,6 +37,27 @@ def livepatched(days_left=300, **kw):
return report(**fields) return report(**fields)
class LivepatchProblemTest(unittest.TestCase):
def test_none_when_healthy_or_not_in_use(self):
from kernelwatch.status import livepatch_problem
self.assertIsNone(livepatch_problem(report()))
self.assertIsNone(livepatch_problem(livepatched()))
self.assertIsNone(livepatch_problem(livepatched(livepatch_state="nothing-to-apply")))
def test_describes_each_unhealthy_case(self):
from kernelwatch.status import livepatch_problem
self.assertEqual(livepatch_problem(livepatched(livepatch_state="apply-failed")),
"livepatch not healthy (apply-failed, supported)")
self.assertEqual(livepatch_problem(livepatched(livepatch_check_state="check-failed")),
"livepatch not healthy (applied, supported, check: check-failed)")
self.assertEqual(livepatch_problem(livepatched(livepatch_check_state=None)),
"livepatch not healthy (applied, supported, check: ?)")
self.assertEqual(livepatch_problem(livepatched(livepatch_supported="unsupported")),
"livepatch not healthy (applied, unsupported)")
self.assertEqual(livepatch_problem(livepatched(livepatch_supported=None)),
"livepatch not healthy (applied, ?)")
class LivepatchTest(unittest.TestCase): class LivepatchTest(unittest.TestCase):
def evaluate(self, rep): def evaluate(self, rep):
return evaluate(NOW - 60, rep, NOW, CFG) return evaluate(NOW - 60, rep, NOW, CFG)
@@ -243,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:
@@ -275,6 +297,267 @@ class EvaluateTest(unittest.TestCase):
self.assertEqual(self.level(report(apt_lists_age_seconds=5 * 86400)).level, "update") self.assertEqual(self.level(report(apt_lists_age_seconds=5 * 86400)).level, "update")
self.assertEqual(self.level(report(apt_lists_age_seconds=None)).level, "update") self.assertEqual(self.level(report(apt_lists_age_seconds=None)).level, "update")
def test_failed_apt_simulation(self):
s = self.level(report(apt_simulation_ok=False, apt_simulation_error="Unmet dependencies.",
security_count=None, upgradable_count=None, kernel_upgradable=None))
self.assertEqual(s.level, "update")
self.assertEqual(s.reasons, ["apt can't work out pending updates: Unmet dependencies."])
s = self.level(report(apt_simulation_ok=False))
self.assertEqual(s.reasons, ["apt can't work out pending updates: no error message"])
def test_apt_simulation_ok_or_unreported(self):
self.assertEqual(self.level(report(apt_simulation_ok=True)).level, "ok")
self.assertEqual(self.level(report()).level, "ok", "agents before 0.5.0 don't send it")
def test_low_boot_space(self):
s = self.level(report(boot_size_kb=487 * 1024, boot_free_kb=95 * 1024))
self.assertEqual(s.level, "update")
self.assertEqual(s.reasons, ["/boot has 95 MB free, 81% used; the next kernel may not fit"])
s = self.level(report(boot_free_kb=95 * 1024))
self.assertEqual(s.reasons, ["/boot has 95 MB free; the next kernel may not fit"], "size unknown")
def test_enough_boot_space_or_unreported(self):
self.assertEqual(self.level(report(boot_size_kb=999320, boot_free_kb=200 * 1024)).level, "ok")
self.assertEqual(self.level(report(boot_free_kb=None)).level, "ok", "df failed")
self.assertEqual(self.level(report()).level, "ok", "agents before 0.6.0 don't send it")
def test_boot_space_threshold_is_configurable(self):
rep = report(boot_size_kb=999320, boot_free_kb=300 * 1024)
self.assertEqual(evaluate(NOW, rep, NOW, Config(boot_min_free_mb=500)).level, "update")
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")
self.assertEqual(s.reasons, ["1 package not fully installed: linux-image-6.12.60+deb13-amd64; "
"run dpkg --configure -a"])
s = self.level(report(dpkg_unfinished_packages=[f"p{i}" for i in range(7)]))
self.assertEqual(s.reasons, ["7 packages not fully installed: p0, p1, p2, p3, p4, +2 more; "
"run dpkg --configure -a"])
def test_no_unfinished_dpkg_packages_or_unreported(self):
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")
self.assertIn("Debian 11 security support ended 2026-08-31", s.reasons[0])
def test_os_end_of_support_warning_is_a_note(self):
# NOW is 2027-01-15; Ubuntu 22.04 standard support ends 2027-06-01.
rep = report(os_id="ubuntu", os_version_id="22.04")
self.assertEqual(evaluate(NOW, rep, NOW, Config(os_eol_warn_days=200)).level, "ok")
self.assertIn("standard support ends 2027-06-01",
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))
def test_unattended_upgrades_healthy(self):
self.assertEqual((self.uu().level, self.uu().reasons), ("ok", []))
self.assertEqual(self.uu(success=3 * 86400, run=3 * 86400).level, "ok", "at the limit")
def test_unattended_upgrades_not_running(self):
s = self.uu(success=5 * 86400, run=5 * 86400)
self.assertEqual(s.level, "update")
self.assertEqual(s.reasons, ["unattended-upgrades hasn't run in 5d; is apt-daily-upgrade.timer enabled?"])
s = self.uu(success=5 * 86400, run=None)
self.assertIn("hasn't run in 5d", s.reasons[0], "older unattended-upgrades without its own stamp")
def test_unattended_upgrades_running_but_failing(self):
s = self.uu(success=5 * 86400, run=6 * 3600)
self.assertEqual(s.level, "update")
self.assertEqual(s.reasons, ["unattended-upgrades last succeeded 5d ago and is failing (last ran 6h ago); "
"check /var/log/unattended-upgrades/"])
def test_unattended_upgrades_never_succeeded(self):
s = self.uu(success=None, run=6 * 3600)
self.assertEqual(s.level, "update")
self.assertEqual(s.reasons, ["unattended-upgrades has never succeeded (last ran 6h ago); "
"check /var/log/unattended-upgrades/"])
def test_unattended_upgrades_not_run_yet_is_a_note(self):
s = self.uu(success=None, run=None)
self.assertEqual((s.level, s.reasons), ("ok", ["unattended-upgrades is enabled but hasn't completed a run yet"]))
def test_unattended_upgrades_off_or_unreported_is_ignored(self):
for state in ("disabled", "not-installed"):
with self.subTest(state=state):
s = self.uu(success=None, run=None, state=state, unattended_upgrades_kept_back=["openssl"])
self.assertEqual((s.level, s.reasons), ("ok", []))
self.assertEqual(self.level(report()).reasons, [], "agents before 0.8.0")
def test_unattended_upgrades_check_can_be_disabled(self):
rep = report(unattended_upgrades="enabled", unattended_upgrades_success_age_seconds=30 * 86400)
self.assertEqual(evaluate(NOW, rep, NOW, Config(unattended_upgrades_stale_after_days=0)).level, "ok")
self.assertEqual(evaluate(NOW, rep, NOW, Config(unattended_upgrades_stale_after_days=60)).level, "ok")
def test_unattended_upgrades_kept_back_is_noted(self):
s = self.uu(unattended_upgrades_kept_back=["libssl3t64", "openssl"], security_count=2)
self.assertEqual(s.level, "update")
self.assertEqual(s.reasons, ["2 security updates pending",
"unattended-upgrades is keeping back libssl3t64, openssl"])
s = self.uu(unattended_upgrades_kept_back=[f"p{i}" for i in range(7)])
self.assertEqual(s.reasons, ["unattended-upgrades is keeping back p0, p1, p2, p3, p4, +2 more"])
def test_reboot_outranks_update(self): def test_reboot_outranks_update(self):
s = self.level(report(needrestart_ksta=3, security_count=2)) s = self.level(report(needrestart_ksta=3, security_count=2))
self.assertEqual(s.level, "reboot") self.assertEqual(s.level, "reboot")
+108
View File
@@ -0,0 +1,108 @@
"""OS end-of-support: the release table and what it says about a host."""
import os
import re
import unittest
from datetime import date
from helpers import REPO
from kernelwatch import support
def host(os_id, version, **kw):
return {"os_id": os_id, "os_version_id": version, **kw}
def check(rep, today, warn_days=90):
return support.check(rep, date.fromisoformat(today), warn_days)
class ReleaseTableTest(unittest.TestCase):
def test_every_release_the_agent_installs_on_is_listed(self):
with open(os.path.join(REPO, "agent", "install.sh")) as f:
accepted = re.search(r'^case "\$ID:\$VERSION_ID" in\n(.*?)\)', f.read(), re.M | re.S).group(1)
releases = [tuple(r.strip().split(":")) for r in accepted.split("|")]
self.assertGreaterEqual(len(releases), 5)
for key in releases:
self.assertIn(key, support.RELEASES)
def test_dates_are_consistent(self):
for key, rel in support.RELEASES.items():
with self.subTest(key=key):
if key[0] == "ubuntu":
self.assertIsNotNone(rel.esm_end)
self.assertLess(rel.end, rel.esm_end)
else:
self.assertIsNone(rel.esm_end)
class DebianTest(unittest.TestCase):
def test_supported(self):
self.assertIsNone(check(host("debian", "12"), "2026-10-31"))
def test_warning_before_the_end(self):
self.assertEqual(check(host("debian", "12"), "2028-05-01"),
(False, "Debian 12 security support ends 2028-06-30 (in 60 days); plan the upgrade"))
self.assertEqual(check(host("debian", "12"), "2028-06-30"),
(False, "Debian 12 security support ends 2028-06-30 (in 0 days); plan the upgrade"))
def test_warning_disabled(self):
self.assertIsNone(check(host("debian", "12"), "2028-05-01", warn_days=0))
def test_ended(self):
self.assertEqual(check(host("debian", "11"), "2026-10-31"),
(True, "Debian 11 security support ended 2026-08-31; upgrade the release"))
self.assertEqual(check(host("debian", "11"), "2026-10-31", warn_days=0)[0], True,
"the warning setting never hides an ended release")
class UbuntuTest(unittest.TestCase):
def test_supported(self):
self.assertIsNone(check(host("ubuntu", "24.04"), "2026-10-31"))
self.assertIsNone(check(host("ubuntu", "22.04"), "2026-10-31"))
def test_standard_support_ending_without_esm(self):
why = ("Ubuntu 22.04 standard support ends 2027-06-01 (in 31 days); "
"enable ESM with Ubuntu Pro or plan the upgrade")
self.assertEqual(check(host("ubuntu", "22.04"), "2027-05-01"), (False, why))
self.assertEqual(check(host("ubuntu", "22.04", ubuntu_esm_infra="disabled"), "2027-05-01"), (False, why))
def test_standard_support_ending_with_esm_is_fine(self):
self.assertIsNone(check(host("ubuntu", "22.04", ubuntu_esm_infra="enabled"), "2027-05-01"))
def test_standard_support_ended_without_esm(self):
self.assertEqual(check(host("ubuntu", "20.04", ubuntu_pro_attached=False), "2026-10-31"),
(True, "Ubuntu 20.04 standard support ended 2025-05-31 and ESM isn't enabled; "
"enable it with Ubuntu Pro or upgrade the release"))
def test_standard_support_ended_with_esm(self):
self.assertIsNone(check(host("ubuntu", "20.04", ubuntu_esm_infra="enabled"), "2026-10-31"))
self.assertEqual(check(host("ubuntu", "20.04", ubuntu_esm_infra="enabled"), "2030-03-01"),
(False, "Ubuntu 20.04 ESM ends 2030-04-23 (in 53 days); plan the upgrade"))
def test_esm_ended(self):
self.assertEqual(check(host("ubuntu", "20.04", ubuntu_esm_infra="enabled"), "2030-04-24"),
(True, "Ubuntu 20.04 ESM ended 2030-04-23; upgrade the release"))
class OtherHostsTest(unittest.TestCase):
def test_unknown_release_is_noted(self):
self.assertEqual(check(host("ubuntu", "25.10"), "2026-10-31"),
(False, "no end-of-support date known for ubuntu 25.10"))
def test_nothing_said_without_a_release(self):
self.assertIsNone(check({}, "2026-10-31"), "agent reported no os fields")
self.assertIsNone(check(host("debian", ""), "2026-10-31"), "Debian testing/sid")
self.assertIsNone(check(host("fedora", "41"), "2026-10-31"))
def test_summary(self):
self.assertEqual(support.summary(host("debian", "13")), "until 2030-06-30")
self.assertEqual(support.summary(host("ubuntu", "24.04", ubuntu_esm_infra="enabled")),
"standard until 2029-05-31, ESM until 2034-04-25 (esm-infra: enabled)")
self.assertEqual(support.summary(host("ubuntu", "24.04")),
"standard until 2029-05-31, ESM until 2034-04-25 (esm-infra: unknown)")
self.assertIsNone(support.summary(host("ubuntu", "25.10")))
if __name__ == "__main__":
unittest.main()
+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()
+87
View File
@@ -185,6 +185,93 @@ class DashboardTest(ServerCase):
body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2] body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2]
self.assertIn("applied, 2 fixes applied, supported until 2099-09-07", body) self.assertIn("applied, 2 fixes applied, supported until 2099-09-07", body)
def test_host_page_shows_boot_space_and_unfinished_packages(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,
"boot_size_kb": 487 * 1024, "boot_free_kb": 95 * 1024,
"dpkg_unfinished_packages": ["linux-image-6.8.0-138-generic"]})
_, headers, _ = self.login("admin", "a-long-password")
body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2]
self.assertIn("95 MB of 487 MB", 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)
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")
self.post_report(token, {"kernel_running": "6.8.0-136-generic", "apt_lists_age_seconds": 60,
"unattended_upgrades": "enabled",
"unattended_upgrades_success_age_seconds": 5 * 86400 + 7200,
"unattended_upgrades_run_age_seconds": 6 * 3600,
"unattended_upgrades_kept_back": ["openssl"]})
_, headers, _ = self.login("admin", "a-long-password")
body = self.request("GET", "/host/web01", headers={"Cookie": headers["Set-Cookie"].split(";")[0]})[2]
self.assertIn("enabled, last success 5d 2h before the report, last run 6h 0m before the report", body)
self.assertIn("<code>openssl</code>", body)
self.assertIn("unattended-upgrades last succeeded 5d ago and is failing", body)
def test_host_page_shows_os_support(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,
"os_id": "ubuntu", "os_version_id": "24.04", "ubuntu_pro_attached": True,
"ubuntu_esm_infra": "enabled"})
_, headers, _ = self.login("admin", "a-long-password")
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): def test_login_dashboard_logout(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")