Uses SQLite's online backup API, so it is consistent while the server is writing in WAL mode. Writes mode 0600 via a temp file and rename, and refuses to overwrite the live database. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
197 lines
6.1 KiB
Python
197 lines
6.1 KiB
Python
"""Command-line interface: run the server and manage hosts and users."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import getpass
|
|
import sqlite3
|
|
import sys
|
|
import time
|
|
|
|
from . import __version__, alerts, auth, db, web
|
|
from .config import load
|
|
|
|
|
|
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:
|
|
return int(alerts.check(cfg) > 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_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_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_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)
|
|
|
|
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)
|
|
|
|
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)
|