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>
This commit is contained in:
patrickandClaude Sonnet 5.5 committed 2026-10-30 11:42:59 -04:00
1 parent 9d80d3ea4c
commit 63b9151b09
4 files changed
+295

No files matched your search

+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}