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>
333 lines
14 KiB
Python
333 lines
14 KiB
Python
"""Runs agent/deploy.sh with ssh/sudo stubbed to run "remote" commands locally.
|
|
|
|
The dashboard side is the real kernelwatch CLI on a temp database; install.sh is
|
|
replaced by a recorder so we can check what each host received.
|
|
"""
|
|
|
|
import os
|
|
import re
|
|
import shutil
|
|
import stat
|
|
import subprocess
|
|
import sys
|
|
import unittest
|
|
|
|
from helpers import REPO, tempdir
|
|
from kernelwatch import auth, db
|
|
|
|
AGENT_DIR = os.path.join(REPO, "agent")
|
|
|
|
SSH_STUB = r"""#!/usr/bin/env bash
|
|
while [[ $1 == -* ]]; do
|
|
case $1 in -o) shift 2 ;; *) shift ;; esac
|
|
done
|
|
target=$1; shift
|
|
echo "$target" >> "$KW_LOG/ssh.log"
|
|
export KW_TARGET=$target
|
|
mkdir -p "$KW_HOMES/$target" && cd "$KW_HOMES/$target"
|
|
exec bash -c "$*"
|
|
"""
|
|
|
|
FAKE_INSTALL = r"""#!/usr/bin/env bash
|
|
out=$KW_LOG/install-$KW_TARGET
|
|
printf '%s\n' "$@" > "$out.args"
|
|
while (($#)); do
|
|
[[ $1 == --token-file ]] && cp "$2" "$out.token"
|
|
shift
|
|
done
|
|
"""
|
|
|
|
|
|
def write_exec(path, text):
|
|
with open(path, "w") as f:
|
|
f.write(text)
|
|
os.chmod(path, os.stat(path).st_mode | stat.S_IEXEC)
|
|
|
|
|
|
@unittest.skipUnless(shutil.which("bash") and shutil.which("tar"), "needs bash and tar")
|
|
class DeployTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self._tmp = tempdir()
|
|
t = self.tmp = self._tmp.name
|
|
self.agent = os.path.join(t, "agent")
|
|
self.log = os.path.join(t, "log")
|
|
self.homes = os.path.join(t, "homes")
|
|
self.remote_tmp = os.path.join(t, "remote-tmp")
|
|
bindir = os.path.join(t, "bin")
|
|
for d in (self.agent, self.log, self.homes, self.remote_tmp, bindir):
|
|
os.makedirs(d)
|
|
|
|
for name in ("deploy.sh", "kernelwatch-agent", "kernelwatch-agent.service",
|
|
"kernelwatch-agent.timer", "kernelwatch-needrestart.service",
|
|
"kernelwatch-livepatch", "kernelwatch-livepatch.service",
|
|
"kernelwatch-apt-update.service", "kernelwatch-unit-result"):
|
|
shutil.copy2(os.path.join(AGENT_DIR, name), self.agent)
|
|
write_exec(os.path.join(self.agent, "install.sh"), FAKE_INSTALL)
|
|
|
|
self.db_path = os.path.join(t, "kw.db")
|
|
server_conf = os.path.join(t, "server.toml")
|
|
with open(server_conf, "w") as f:
|
|
f.write(f'db_path = "{self.db_path}"\n')
|
|
|
|
write_exec(os.path.join(bindir, "ssh"), SSH_STUB)
|
|
write_exec(os.path.join(bindir, "sudo"), '#!/bin/sh\nexec "$@"\n')
|
|
write_exec(os.path.join(bindir, "hostname"),
|
|
'#!/bin/sh\nt=${KW_TARGET#*@}; echo "${t%%.*}"\n')
|
|
write_exec(os.path.join(bindir, "kernelwatch"),
|
|
f'#!/bin/sh\nexec {sys.executable} {REPO}/server/kernelwatch-server "$@"\n')
|
|
|
|
with open(os.path.join(self.agent, "deploy.conf"), "w") as f:
|
|
f.write("SERVER_URL=https://kernels.example.test\nDASHBOARD=admin@dash\n")
|
|
self.hosts_file = os.path.join(self.agent, "hosts")
|
|
with open(self.hosts_file, "w") as f:
|
|
f.write("# fleet\nweb01.example.test\npatrick@10.0.0.31 db01 # explicit name\n")
|
|
|
|
self.env = {
|
|
"PATH": f"{bindir}:{os.environ['PATH']}",
|
|
"KW_LOG": self.log,
|
|
"KW_HOMES": self.homes,
|
|
"TMPDIR": self.remote_tmp,
|
|
"KERNELWATCH_CONFIG": server_conf,
|
|
}
|
|
|
|
def tearDown(self):
|
|
self._tmp.cleanup()
|
|
|
|
def deploy(self, *args):
|
|
return subprocess.run(["bash", os.path.join(self.agent, "deploy.sh"), *args],
|
|
env=self.env, capture_output=True, text=True, timeout=60)
|
|
|
|
def installed(self, target):
|
|
base = os.path.join(self.log, f"install-{target}")
|
|
with open(base + ".args") as f:
|
|
args = f.read().split()
|
|
token = None
|
|
if os.path.exists(base + ".token"):
|
|
with open(base + ".token") as f:
|
|
token = f.read().strip()
|
|
return args, token
|
|
|
|
def host_for(self, token):
|
|
conn = db.connect(self.db_path)
|
|
try:
|
|
return db.host_for_token(conn, auth.token_hash(token))
|
|
finally:
|
|
conn.close()
|
|
|
|
def assert_clean(self):
|
|
self.assertEqual(os.listdir(self.remote_tmp), [], "remote temp dirs removed")
|
|
dash = os.path.join(self.homes, "admin@dash")
|
|
if os.path.isdir(dash):
|
|
self.assertEqual(os.listdir(dash), [], "no token left on the dashboard")
|
|
|
|
def test_register_hosts_from_file_and_cli(self):
|
|
proc = self.deploy("--register", "web01.example.test", "patrick@10.0.0.31", "new01.example.test")
|
|
self.assertEqual(proc.returncode, 0, proc.stderr)
|
|
|
|
for target, name in (("web01.example.test", "web01"), ("patrick@10.0.0.31", "db01"),
|
|
("new01.example.test", "new01")):
|
|
with self.subTest(target=target):
|
|
args, token = self.installed(target)
|
|
self.assertIn("--server", args)
|
|
self.assertIn("https://kernels.example.test", args)
|
|
self.assertEqual(self.host_for(token), name, "token authenticates as that host")
|
|
self.assertNotIn(token, proc.stdout + proc.stderr, "token never printed")
|
|
|
|
with open(self.hosts_file) as f:
|
|
self.assertIn("new01.example.test new01\n", f.read(), "new host remembered")
|
|
self.assert_clean()
|
|
|
|
def test_upgrade_all_keeps_config(self):
|
|
proc = self.deploy()
|
|
self.assertEqual(proc.returncode, 0, proc.stderr)
|
|
for target in ("web01.example.test", "patrick@10.0.0.31"):
|
|
args, token = self.installed(target)
|
|
self.assertEqual(len(args), 0, "plain install.sh: keeps existing config and token")
|
|
self.assertIsNone(token)
|
|
with open(os.path.join(self.log, "ssh.log")) as f:
|
|
self.assertNotIn("admin@dash", f.read(), "upgrades don't touch the dashboard")
|
|
self.assert_clean()
|
|
|
|
def test_install_args_passed_through(self):
|
|
proc = self.deploy("web01.example.test", "--", "--with-needrestart")
|
|
self.assertEqual(proc.returncode, 0, proc.stderr)
|
|
self.assertEqual(self.installed("web01.example.test")[0], ["--with-needrestart"])
|
|
|
|
def test_register_existing_fails_but_others_continue(self):
|
|
self.assertEqual(self.deploy("--register", "web01.example.test").returncode, 0)
|
|
proc = self.deploy("--register", "web01.example.test", "new01.example.test")
|
|
self.assertEqual(proc.returncode, 1)
|
|
self.assertIn("already exists", proc.stderr)
|
|
self.assertIn("Failed (1/2): web01.example.test", proc.stderr)
|
|
self.assertEqual(self.host_for(self.installed("new01.example.test")[1]), "new01")
|
|
self.assert_clean()
|
|
|
|
def test_rotate(self):
|
|
self.deploy("--register", "web01.example.test")
|
|
old = self.installed("web01.example.test")[1]
|
|
proc = self.deploy("--rotate", "web01.example.test")
|
|
self.assertEqual(proc.returncode, 0, proc.stderr)
|
|
new = self.installed("web01.example.test")[1]
|
|
self.assertNotEqual(old, new)
|
|
self.assertIsNone(self.host_for(old))
|
|
self.assertEqual(self.host_for(new), "web01")
|
|
|
|
def test_register_needs_explicit_hosts(self):
|
|
proc = self.deploy("--register")
|
|
self.assertNotEqual(proc.returncode, 0)
|
|
self.assertIn("name the hosts", proc.stderr)
|
|
|
|
def test_dry_run_touches_nothing(self):
|
|
proc = self.deploy("--dry-run", "--register", "new01.example.test")
|
|
self.assertEqual(proc.returncode, 0, proc.stderr)
|
|
self.assertIn("kernelwatch add-host", proc.stderr)
|
|
self.assertFalse(os.path.exists(os.path.join(self.log, "ssh.log")))
|
|
|
|
def test_missing_config(self):
|
|
os.remove(os.path.join(self.agent, "deploy.conf"))
|
|
proc = self.deploy()
|
|
self.assertNotEqual(proc.returncode, 0)
|
|
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):
|
|
def read(self, name):
|
|
with open(os.path.join(AGENT_DIR, name)) as f:
|
|
return f.read()
|
|
|
|
def test_deploy_ships_every_file_install_uses(self):
|
|
files = re.search(r"^FILES=\(([^)]*)\)", self.read("deploy.sh"), re.M).group(1).split()
|
|
used = set(re.findall(r'"\$here/([^"]+)"', self.read("install.sh")))
|
|
self.assertTrue(used)
|
|
self.assertEqual(used - set(files), set())
|
|
|
|
def test_apt_update_is_opt_in_and_runs_before_reports(self):
|
|
unit = self.read("kernelwatch-apt-update.service")
|
|
self.assertIn("ConditionPathExists=/etc/kernelwatch/apt-update", unit)
|
|
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")
|
|
for key in ("Wants=", "After="):
|
|
line = next(l for l in agent.splitlines() if l.startswith(key))
|
|
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)=")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|