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
This commit was merged in pull request #20.
This commit is contained in:
patrick committed 2026-10-30 15:46:32 +00:00
commit e7a9a49438
4 files changed
+295

No files matched your search

+49
View File
@@ -453,6 +453,54 @@ 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.
## 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. 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.
## Heartbeat: is kernelwatch itself running?
Every alert above depends on `kernelwatch-alerts.timer` running on the dashboard
@@ -500,6 +548,7 @@ sudo kernelwatch add-host NAME register a host, print its token (--token-o
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
+41
View File
@@ -4,12 +4,14 @@ from __future__ import annotations
import argparse
import getpass
import json
import sqlite3
import sys
import time
from . import __version__, alerts, auth, db, web
from .config import load
from .status import LEVELS, fleet_status
def _conn(cfg):
@@ -148,6 +150,39 @@ def cmd_list_hosts(cfg, args) -> int:
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:
password = getpass.getpass(f"Password for {args.name}: ")
if len(password) < 12:
@@ -224,6 +259,12 @@ def main(argv: list[str] | None = None) -> int:
p.set_defaults(func=func)
sub.add_parser("list-hosts", help="list hosts and when they last reported").set_defaults(
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 (
("set-password", cmd_set_password, "create a dashboard user or change their password"),
+47
View File
@@ -10,6 +10,7 @@ Levels, worst first:
from __future__ import annotations
import re
import time
from dataclasses import dataclass, field
from datetime import date, datetime, timezone
from typing import Any
@@ -208,3 +209,49 @@ def evaluate(received_at: int | None, report: dict[str, Any] | None, now: float,
"run agent/deploy.sh")
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}
+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 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": "0.4.1"}
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", "0.4.1"))
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()