Files
patrickandClaude Sonnet 5.5 63b9151b09
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
Add kernelwatch status [--json]
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

280 lines
9.8 KiB
Python

"""Command-line interface: run the server and manage hosts and users."""
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):
db.init(cfg.db_path)
return db.connect(cfg.db_path)
def _valid_host(name: str) -> str:
if not web.HOST_NAME_RE.match(name):
raise argparse.ArgumentTypeError("host names may contain letters, digits, '.', '_' and '-'")
return name
def cmd_serve(cfg, args) -> int:
web.serve(cfg)
return 0
def cmd_check_alerts(cfg, args) -> int:
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:
try:
alerts.publish(cfg, "kernelwatch: test notification",
"Stale-host and reporting-recovery notifications will be delivered to this topic.")
except alerts.DeliveryError as exc:
print(f"kernelwatch: {exc}", file=sys.stderr)
return 1
print("Test notification sent.")
return 0
def cmd_notify_backup_failure(cfg, args) -> int:
return alerts.notify_backup_failure(cfg)
def cmd_backup(cfg, args) -> int:
db.init(cfg.db_path)
try:
db.backup(cfg.db_path, args.path)
except (OSError, ValueError, sqlite3.Error) as exc:
print(f"kernelwatch: backup failed: {exc}", file=sys.stderr)
return 1
print(f"Backed up to {args.path}")
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:
token = auth.new_token()
conn = _conn(cfg)
try:
db.add_host(conn, args.name, auth.token_hash(token))
except sqlite3.IntegrityError:
print(f"host {args.name!r} already exists (use rotate-token)", file=sys.stderr)
return 1
finally:
conn.close()
if args.token_only:
print(token)
return 0
print(f"Added {args.name}. Its token (shown once):\n\n {token}\n")
print("On the host, run: sudo ./agent/install.sh --server <URL> and paste the token.")
return 0
def cmd_rotate_token(cfg, args) -> int:
token = auth.new_token()
conn = _conn(cfg)
try:
if not db.set_host_token(conn, args.name, auth.token_hash(token)):
print(f"no such host {args.name!r}", file=sys.stderr)
return 1
finally:
conn.close()
if args.token_only:
print(token)
return 0
print(f"New token for {args.name} (the old one no longer works):\n\n {token}\n")
print("On the host, run: sudo KERNELWATCH_TOKEN=... ./agent/install.sh or edit /etc/kernelwatch/agent.token")
return 0
def cmd_remove_host(cfg, args) -> int:
conn = _conn(cfg)
try:
if not db.remove_host(conn, args.name):
print(f"no such host {args.name!r}", file=sys.stderr)
return 1
finally:
conn.close()
print(f"Removed {args.name} and its reports.")
return 0
def cmd_list_hosts(cfg, args) -> int:
conn = _conn(cfg)
try:
hosts = db.list_hosts(conn)
finally:
conn.close()
now = time.time()
for h in hosts:
print(f"{h['name']:<32} last seen {web.ago(h['last_seen'], now)}")
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:
print("use at least 12 characters", file=sys.stderr)
return 1
if getpass.getpass("Again: ") != password:
print("passwords don't match", file=sys.stderr)
return 1
conn = _conn(cfg)
try:
db.set_user(conn, args.name, auth.hash_password(password))
finally:
conn.close()
print(f"Password set for {args.name}.")
return 0
def cmd_remove_user(cfg, args) -> int:
conn = _conn(cfg)
try:
if not db.remove_user(conn, args.name):
print(f"no such user {args.name!r}", file=sys.stderr)
return 1
finally:
conn.close()
print(f"Removed user {args.name}.")
return 0
def cmd_list_users(cfg, args) -> int:
conn = _conn(cfg)
try:
for name in db.list_users(conn):
print(name)
finally:
conn.close()
return 0
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="kernelwatch", description="Fleet kernel status dashboard.")
parser.add_argument("-c", "--config", help="config file (default: $KERNELWATCH_CONFIG or "
"/etc/kernelwatch/server.toml)")
parser.add_argument("--version", action="version", version=f"kernelwatch {__version__}")
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("serve", help="run the HTTP server").set_defaults(func=cmd_serve)
sub.add_parser("check-alerts", help="send stale, recovery, reboot and update notifications").set_defaults(
func=cmd_check_alerts)
sub.add_parser("test-alert", help="send a test notification to the configured ntfy topic").set_defaults(
func=cmd_test_alert)
p = sub.add_parser("backup", help="write a consistent copy of the database to PATH")
p.add_argument("path")
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 (
("add-host", cmd_add_host, "register a host and print its token"),
("rotate-token", cmd_rotate_token, "issue a new token for a host"),
("remove-host", cmd_remove_host, "delete a host and its reports"),
):
p = sub.add_parser(name, help=help_)
p.add_argument("name", type=_valid_host)
if name != "remove-host":
p.add_argument("--token-only", action="store_true",
help="print only the token (for scripts such as agent/deploy.sh)")
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"),
("remove-user", cmd_remove_user, "delete a dashboard user"),
):
p = sub.add_parser(name, help=help_)
p.add_argument("name")
p.set_defaults(func=func)
sub.add_parser("list-users", help="list dashboard users").set_defaults(func=cmd_list_users)
args = parser.parse_args(argv)
return args.func(load(args.config), args)