From 38adddaf4a31aeb5bb0f02f9f376b5473810b6b6 Mon Sep 17 00:00:00 2001 From: atlas Date: Sat, 21 Nov 2026 15:21:50 +0100 Subject: [PATCH] vm-tests: k8s-runtime-switch moves the router between its container and the cluster and back --- .forgejo/workflows/vm-nightly.yml | 1 + nix/vm-test-typecheck.nix | 1 + nix/vm-tests.nix | 1 + nix/vm-tests/k8s-runtime-switch.nix | 491 ++++++++++++++++++++++++++++ 4 files changed, 494 insertions(+) create mode 100644 nix/vm-tests/k8s-runtime-switch.nix diff --git a/.forgejo/workflows/vm-nightly.yml b/.forgejo/workflows/vm-nightly.yml index 1137a460c..8f142159a 100644 --- a/.forgejo/workflows/vm-nightly.yml +++ b/.forgejo/workflows/vm-nightly.yml @@ -58,6 +58,7 @@ jobs: - k8s-node - k8s-collector-switch - k8s-bao-login + - k8s-runtime-switch steps: - uses: actions/checkout@v3 if: inputs.test == '' || inputs.test == matrix.test diff --git a/nix/vm-test-typecheck.nix b/nix/vm-test-typecheck.nix index d5f92f2e4..eccf84ca7 100644 --- a/nix/vm-test-typecheck.nix +++ b/nix/vm-test-typecheck.nix @@ -140,6 +140,7 @@ let k8s-node k8s-collector-switch k8s-bao-login + k8s-runtime-switch ; }; in diff --git a/nix/vm-tests.nix b/nix/vm-tests.nix index 2ff3050db..e80dc94cc 100644 --- a/nix/vm-tests.nix +++ b/nix/vm-tests.nix @@ -20,5 +20,6 @@ k8s-node = import ./vm-tests/k8s-node.nix { inherit pkgs self; }; k8s-collector-switch = import ./vm-tests/k8s-collector-switch.nix { inherit pkgs self; }; k8s-bao-login = import ./vm-tests/k8s-bao-login.nix { inherit pkgs self; }; + k8s-runtime-switch = import ./vm-tests/k8s-runtime-switch.nix { inherit pkgs self; }; semi-spread = import ./vm-tests/semi-spread.nix { inherit pkgs self; }; } diff --git a/nix/vm-tests/k8s-runtime-switch.nix b/nix/vm-tests/k8s-runtime-switch.nix new file mode 100644 index 000000000..f1e258555 --- /dev/null +++ b/nix/vm-tests/k8s-runtime-switch.nix @@ -0,0 +1,491 @@ +# `vmTests..k8s-runtime-switch`: the notification router moves between +# its host container and a pod in the host's cluster +# (`services.hyperhive.deploy.notify-router.runtime`), against the real secret +# store and a real queue. The host boots with the router in its container; the +# `k8s` specialisation is the same host with the router in the cluster. The +# script switches to it, back, and to it again, and asserts that: +# +# - exactly one copy runs at each step, by the order of the switch's own +# timestamps and by a sampler that looks every 200 ms; +# - the pod is Ready, so it logged in to the store with its ServiceAccount +# token, read the queue's client secret, minted a token with it and connected +# to the queue with the hive's CA, which the host published as a ConfigMap; +# - the pod routes one forge event, and a deleted pod exits 0 within its grace +# period with its replacement Ready; +# - the switch back leaves no pod, Deployment or AddOn, and the router's +# consumer is the queue's, unchanged. +# +# The queue is a plain nats-server with JetStream and TLS, and the token +# endpoint is a stub that records the client credentials it is given. They +# replace the identity provider and the queue's auth callout, which stay +# host-run and unchanged; the router takes its production path otherwise. The +# test makes the hive's CA and the leaf of both names at boot. +{ pkgs, self }: +let + inherit (pkgs) lib; + + bridgeIp = "10.42.0.1"; + baoName = "bao.t.local"; + baoPort = 8200; + podPort = 8208; + natsName = "nats.t.local"; + natsPort = 4222; + authName = "auth.t.local"; + namespace = "hyperhive"; + service = "swarm-notify-router"; + clientId = "swarm-notify-router"; + agent = "atlas"; + pkiDir = "/var/lib/test-ca"; + tlsDir = "/var/lib/hive-tls"; + leaf = "swarm/services/${clientId}/oidc/client"; + prune = "${service}-k8s-prune"; + hostUnit = "container@${service}.service"; + overlapLog = "/var/log/overlap.log"; + tokenLog = "/var/log/stub-token.log"; + + # The token endpoint: it answers every client-credentials request with a + # token and records the client id and secret of the Basic credentials. + tokenStub = pkgs.writeText "token-stub.py" '' + import base64 + import http.server + import json + import secrets + import ssl + + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", 0))) + auth = self.headers.get("Authorization", "") + who = base64.b64decode(auth.removeprefix("Basic ")).decode() if auth.startswith("Basic ") else "none" + with open("${tokenLog}", "a") as log: + log.write(f"{self.path} {who}\n") + body = json.dumps({"access_token": secrets.token_hex(16), "token_type": "Bearer", "expires_in": 3600}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + + server = http.server.HTTPServer(("${bridgeIp}", 443), Handler) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain("${pkiDir}/svc.pem", "${pkiDir}/svc-key.pem") + server.socket = context.wrap_socket(server.socket, server_side=True) + server.serve_forever() + ''; + + natsConf = pkgs.writeText "nats.conf" '' + listen: "${bridgeIp}:${toString natsPort}" + jetstream { store_dir: "/var/lib/nats-test" } + tls { + cert_file: "${pkiDir}/svc.pem" + key_file: "${pkiDir}/svc-key.pem" + } + ''; + + # Looks every 200 ms at whether the container runs and how many router pods + # exist, a terminating pod included. + sampler = pkgs.writeShellScript "overlap-sampler" '' + while true; do + state="$(systemctl is-active ${hostUnit} || true)" + pods="$(kubectl --namespace ${namespace} get pods --selector app.kubernetes.io/name=${service} --no-headers 2>/dev/null | wc -l)" + echo "$(date +%s.%N) host=$state pods=$pods" >> ${overlapLog} + sleep 0.2 + done + ''; +in +pkgs.testers.runNixOSTest { + name = "k8s-runtime-switch"; + + # The store takes a few minutes to open its raft storage, and the script + # switches the configuration three times. Under the 1 h job bound with room + # for the build before the test starts. + globalTimeout = 2400; + + nodes.machine = + { config, ... }: + { + imports = [ self.nixosModules.default ]; + + services.hyperhive = { + deploy.k8s.enable = true; + network.enable = true; + network.bridgeIp = bridgeIp; + deploy.bao.enable = true; + deploy.bao.seal = "shamir"; + deploy.bao.bootstrapTokenFile = "/var/lib/swarm-bao-bootstrap/grant.token"; + deploy.notify-router.enable = true; + deploy.hive-controller.hiveName = "h1"; + swarm.domain = "t.local"; + swarm.bao.domain = baoName; + swarm.bao.port = baoPort; + swarm.hives.h1.domain = "h1.t.local"; + # The queue and the identity provider are host-run: their names go to + # the bridge for the cluster's pods, as the hive's own do. + gateway.localNames = [ + natsName + authName + ]; + }; + system.stateVersion = "25.11"; + + specialisation.k8s.configuration.services.hyperhive.deploy.notify-router.runtime = "k8s"; + + # The store's TLS passthrough is a stream server of the host's nginx, + # which needs certificates this host does not mint, so a second nginx + # carries the passthrough alone, as `k8s-bao-login` does. + services.nginx.enable = lib.mkForce false; + networking.hosts."${bridgeIp}" = [ + baoName + natsName + authName + ]; + systemd.services.bao-stream = { + wantedBy = [ "multi-user.target" ]; + after = [ "network.target" ]; + serviceConfig = { + RuntimeDirectory = "bao-stream"; + Restart = "always"; + RestartSec = 2; + ExecStart = + let + conf = pkgs.writeText "bao-stream.conf" '' + pid /run/bao-stream/nginx.pid; + error_log stderr; + events {} + stream { + ${config.services.nginx.streamConfig} + } + ''; + in + "${pkgs.nginx}/bin/nginx -c ${conf} -g 'daemon off;'"; + }; + }; + + # The hive's CA, and one leaf for the queue's and the identity + # provider's names, which this test makes. The trust bundle is the unit + # `hive-tls-ca`'s, and the store's services-root unit reloads that unit + # when it has fetched the store's root, so the test's own script is the + # one the unit runs on every reload. + systemd.services.hive-tls-ca = { + path = [ + pkgs.openssl + pkgs.coreutils + ]; + script = lib.mkForce '' + set -euo pipefail + install -d -m 0755 ${pkiDir} ${tlsDir} + cd ${pkiDir} + if [ ! -s ca.pem ]; then + openssl req -x509 -newkey rsa:2048 -nodes -keyout ca-key.pem -out ca.pem \ + -subj "/CN=test-ca" -days 3650 \ + -addext basicConstraints=critical,CA:TRUE -addext keyUsage=critical,keyCertSign + openssl req -newkey rsa:2048 -nodes -keyout svc-key.pem -out svc.csr -subj "/CN=${natsName}" + printf 'subjectAltName=DNS:${natsName},DNS:${authName}\n' > svc.ext + openssl x509 -req -in svc.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial \ + -days 3650 -extfile svc.ext -out svc.pem + chmod 0644 ca.pem svc.pem svc-key.pem + fi + cat ca.pem > ${tlsDir}/trust-bundle.pem + chmod 0644 ${tlsDir}/trust-bundle.pem + ''; + }; + + systemd.services.nats-test = { + wantedBy = [ "multi-user.target" ]; + after = [ "hive-tls-ca.service" ]; + requires = [ "hive-tls-ca.service" ]; + serviceConfig = { + ExecStart = "${pkgs.nats-server}/bin/nats-server -c ${natsConf}"; + StateDirectory = "nats-test"; + Restart = "always"; + RestartSec = 2; + }; + }; + + systemd.services.token-stub = { + wantedBy = [ "multi-user.target" ]; + after = [ "hive-tls-ca.service" ]; + requires = [ "hive-tls-ca.service" ]; + serviceConfig = { + ExecStart = "${pkgs.python3}/bin/python3 ${tokenStub}"; + Restart = "always"; + RestartSec = 2; + }; + }; + + systemd.services.overlap-sampler = { + path = [ + pkgs.kubectl + pkgs.coreutils + pkgs.systemd + ]; + environment.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml"; + serviceConfig.ExecStart = sampler; + }; + + environment.systemPackages = [ + pkgs.kubectl + pkgs.curl + pkgs.jq + pkgs.openssl + pkgs.natscli + ]; + environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml"; + environment.etc."k3s-node/images".text = lib.concatMapStrings ( + i: "${i.imageName}:${i.imageTag}\n" + ) config.system.build.k8sImages; + + # The store's raft data is on a tmpfs, for the reason `full-setup` gives. + fileSystems."/var/lib/nixos-containers/${config.services.hyperhive.swarm.bao.machine}/var/lib/private" = + { + device = "tmpfs"; + fsType = "tmpfs"; + options = [ + "mode=0700" + "size=1G" + ]; + }; + + virtualisation = { + memorySize = 8192; + cores = 4; + diskSize = 8192; + }; + }; + + testScript = builtins.readFile ./lib/k3s.py + '' + INIT = "/root/bao-init.json" + NS = "${namespace}" + SERVICE = "${service}" + HOST_UNIT = "${hostUnit}" + PRUNE = "${prune}" + MANIFESTS = "/var/lib/rancher/k3s/server/manifests" + NATS = "--server tls://${natsName}:${toString natsPort} --tlsca ${pkiDir}/ca.pem" + AGENT = "${agent}" + SELECTOR = f"--selector app.kubernetes.io/name={SERVICE}" + + + def as_root(command: str) -> str: + return machine.succeed(f'BAO_TOKEN="$(jq -r .root_token {INIT})" {command}') + + + def diagnose(units: list[str]) -> None: + for unit in units: + print(f"--- {unit}") + print(machine.execute(f"systemctl status {unit} --no-pager -l; journalctl -u {unit} --no-pager -n 60")[1]) + + + def settle(command: str, timeout: int, units: list[str]) -> None: + try: + machine.wait_until_succeeds(command, timeout=timeout) + except Exception: + diagnose(units) + raise + + + def router_pods() -> list[str]: + out = machine.succeed(f"kubectl -n {NS} get pods {SELECTOR} -o name || true") + return out.split() + + + def host_state() -> str: + return machine.execute(f"systemctl is-active {HOST_UNIT}")[1].strip() + + + def consumer() -> dict: + return json.loads(machine.succeed(f"nats {NATS} consumer info SWARM_EVENTS notify-router --json")) + + + def wait_pod_ready(timeout: int = 600) -> str: + machine.wait_until_succeeds(f"kubectl -n {NS} get pods {SELECTOR} -o name | grep -q pod/", timeout=timeout) + name = router_pods()[0].removeprefix("pod/") + try: + wait_pod(machine, name, phase="Running", ready=True, timeout=timeout) + except Exception: + diagnose(["hyperhive-k8s-ca-trust.service"]) + print(machine.execute(f"kubectl -n {NS} describe pod {name}")[1]) + print(machine.execute(f"kubectl -n {NS} logs {name} --tail=60")[1]) + raise + return name + + + def switch(target: str) -> str: + """Switches to `target`. Units of this host that fail for reasons of + their own (the gateway's certificate import has no nginx group, here) + make the exit status 4; the units the switch is about must not be + among them.""" + status, out = machine.execute(f"{target}/bin/switch-to-configuration test 2>&1") + print(out) + assert status in (0, 4), out + failed = next((line for line in out.splitlines() if "the following units failed" in line), "") + ours = [HOST_UNIT, f"{PRUNE}.service", "hyperhive-k8s-ca-trust.service", "k3s.service"] + assert not any(unit in failed for unit in ours), failed + return out + + + with subtest("the node is Ready and holds every image"): + wait_node_ready(machine, timeout=300) + wait_images(machine) + kube(machine, f"config set-context --current --namespace={NS}") + + with subtest("the store is initialised, unsealed and bootstrapped"): + machine.wait_until_succeeds('[ "$(bao status >/dev/null 2>&1; echo $?)" = 2 ]', timeout=900) + machine.succeed(f"umask 077 && bao operator init -key-shares=1 -key-threshold=1 -format=json > {INIT}") + machine.succeed(f"bao operator unseal \"$(jq -r '.unseal_keys_b64[0]' {INIT})\"") + # Right after the unseal the store has no active node for a moment. + machine.wait_until_succeeds("bao status", timeout=120) + machine.succeed( + "set -o pipefail; " + f'export BAO_TOKEN="$(jq -r .root_token {INIT})"; ' + "bao policy write bao-bootstrap /etc/hyperhive/bao-bootstrap-policy.hcl; " + "bao token create -policy=bao-bootstrap -ttl=24h -orphan -display-name=bao-bootstrap -field=token " + "| install -D -m 0600 /dev/stdin /var/lib/swarm-bao-bootstrap/grant.token; " + "unset BAO_TOKEN; " + "systemctl restart swarm-bao-granter-role" + ) + machine.wait_until_succeeds( + "journalctl -u swarm-bao-granter-role --no-pager | grep -F 'Uploaded policy: bao-granter'", + timeout=300, + ) + + with subtest("the granting units have written the router's policy and role, and the jwt mount"): + machine.succeed("systemctl reset-failed 'swarm-bao-*-policy.service' swarm-bao-agent-pki.service || true") + machine.succeed("systemctl restart --no-block 'swarm-bao-*-policy.service' swarm-bao-agent-pki.service") + settle('[ "$(systemctl is-active swarm-bao-agent-pki.service)" = active ]', 900, ["swarm-bao-agent-pki.service"]) + # Under the shamir seal the PKI unit leaves a restart of the store to the + # operator when its listener's client CA changed. + if machine.execute("journalctl -u swarm-bao-agent-pki --no-pager | grep -F 'restart openbao.service'")[0] == 0: + machine.succeed("systemctl --machine=swarm-bao restart openbao.service") + machine.wait_until_succeeds('[ "$(bao status >/dev/null 2>&1; echo $?)" = 2 ]', timeout=900) + machine.succeed(f"bao operator unseal \"$(jq -r '.unseal_keys_b64[0]' {INIT})\"") + machine.wait_until_succeeds("bao status", timeout=120) + for unit in ["swarm-bao-notify-router-policy", "swarm-bao-k8s-jwt-policy"]: + settle(f'[ "$(systemctl is-active {unit}.service)" = active ]', 900, [f"{unit}.service"]) + machine.wait_until_succeeds( + "journalctl -u swarm-bao-k8s-jwt-policy --no-pager | grep -F 'Success! Data written to: auth/jwt-k8s/config'", + timeout=300, + ) + # The router's queue client secret, which the identity provider's mint + # stores in production. + SECRET = machine.succeed("openssl rand -hex 16").strip() + as_root(f"bao kv put -mount=secret ${leaf} value={SECRET}") + + with subtest("the queue and the token stub run, and the queue holds the roster the router reads"): + machine.wait_for_unit("hive-tls-ca.service") + machine.wait_for_unit("nats-test.service") + machine.wait_for_unit("token-stub.service") + machine.wait_until_succeeds(f"nats {NATS} account info", timeout=120) + machine.succeed(f"nats {NATS} kv add agent-status") + machine.succeed(f"nats {NATS} kv put agent-status h1.{AGENT} '{{}}'") + machine.succeed("systemctl start overlap-sampler.service") + + with subtest("on the host, the container runs and the cluster holds no router"): + machine.wait_until_succeeds(f"[ \"$(systemctl is-active {HOST_UNIT})\" = active ]", timeout=300) + assert router_pods() == [], router_pods() + assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml")[0] != 0 + assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0 + # The prune unit ran with the container, found no link, and needed + # nothing from the cluster. + assert machine.succeed(f"systemctl is-active {PRUNE}.service").strip() == "active" + + with subtest("the switch to the cluster stops the container before it applies the pod"): + out = switch("/run/booted-system/specialisation/k8s") + assert HOST_UNIT in out and "stopping the following units" in out, out + assert host_state() == "inactive", host_state() + machine.succeed(f"test -L {MANIFESTS}/{SERVICE}.yaml") + stopped = int(machine.succeed(f"date -d \"$(systemctl show -p InactiveEnterTimestamp --value {HOST_UNIT})\" +%s")) + router = wait_pod_ready() + created = int(machine.succeed(f"date -d \"$(kubectl -n {NS} get pod {router} -o jsonpath='{{.metadata.creationTimestamp}}')\" +%s")) + assert stopped <= created, (stopped, created) + assert machine.execute("machinectl list --no-legend | grep -q swarm-notify-router")[0] != 0 + + with subtest("the host published the CA files, which are the hive's"): + trust = machine.succeed(f"kubectl -n {NS} get configmap hyperhive-ca-trust -o json") + data = json.loads(trust)["data"] + assert data["trust-bundle.pem"] == machine.succeed("cat ${tlsDir}/trust-bundle.pem"), data + assert data["bao-server-ca.pem"] == machine.succeed("cat /var/lib/swarm-bao-pki/ca.pem"), data + assert machine.succeed(f"kubectl -n {NS} get secrets -o name || true").strip() == "" + + with subtest("a changed CA file is published again with no manual step"): + machine.succeed("echo '# refreshed' >> ${tlsDir}/trust-bundle.pem") + machine.wait_until_succeeds( + f"kubectl -n {NS} get configmap hyperhive-ca-trust -o jsonpath='{{.data.trust-bundle\\.pem}}' | grep -q refreshed", + timeout=120, + ) + + with subtest("the pod logged in to the store, read the client secret, and minted a token with it"): + machine.wait_until_succeeds(f"grep -F '/api/oidc/token ${clientId}:{SECRET}' ${tokenLog}", timeout=120) + machine.wait_until_succeeds(f"nats {NATS} consumer info SWARM_EVENTS notify-router >/dev/null", timeout=120) + + with subtest("the pod routes a forge event: the agent's todo is queued and the event acknowledged"): + event = json.dumps({ + "action": "assigned", + "repository": {"id": 1, "full_name": "o/r"}, + "issue": { + "number": 7, + "title": "t", + "html_url": "https://forge.t.local/o/r/7", + "assignees": [{"login": AGENT}], + "user": {"login": "mara"}, + }, + "sender": {"login": "mara"}, + }) + machine.succeed(f"nats {NATS} pub '$SWARM.events.forge.issue_assign' '{event}'") + machine.wait_until_succeeds( + f"nats {NATS} stream get ROUTER_TODOS --last-for '$SWARM.router.todo.{AGENT}'", + timeout=180, + ) + machine.wait_until_succeeds( + f"nats {NATS} consumer info SWARM_EVENTS notify-router --json | jq -e '.ack_floor.stream_seq == 1'", + timeout=60, + ) + created_at = consumer()["created"] + + with subtest("deleting the pod ends its container with exit code 0 within the grace period, and its replacement is Ready"): + old = router_pods()[0].removeprefix("pod/") + terminated, took = delete_pod(machine, old, timeout=60) + assert terminated["exitCode"] == 0, terminated + print(f"pod deleted in {took:.1f}s, container exit code {terminated['exitCode']}") + assert took < 15 + 5, took + new = wait_pod_ready() + assert new != old, (new, old) + + with subtest("the switch back removes the pod and its objects before the container starts"): + out = switch("/run/booted-system") + print(out) + machine.wait_until_succeeds(f"[ \"$(systemctl is-active {HOST_UNIT})\" = active ]", timeout=300) + assert router_pods() == [], router_pods() + assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0 + assert machine.execute(f"kubectl -n kube-system get addons.k3s.cattle.io {SERVICE}")[0] != 0 + assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml")[0] != 0 + assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml.pruning")[0] != 0 + pruned = int(machine.succeed(f"systemctl show -p ExecMainExitTimestampMonotonic --value {PRUNE}.service")) + started = int(machine.succeed(f"systemctl show -p InactiveExitTimestampMonotonic --value {HOST_UNIT}")) + assert 0 < pruned <= started, (pruned, started) + + with subtest("the router's state is the queue's: the consumer is the one the pod made, with its progress"): + info = consumer() + assert info["created"] == created_at, (info["created"], created_at) + assert info["ack_floor"]["stream_seq"] == 1, info + machine.succeed(f"nats {NATS} kv get notify-router-state 1.7 >/dev/null") + + with subtest("a second switch to the cluster applies the manifests again"): + switch("/run/booted-system/specialisation/k8s") + assert host_state() == "inactive", host_state() + wait_pod_ready() + + with subtest("no moment of any switch had the container and a pod together"): + machine.succeed("systemctl stop overlap-sampler.service") + lines = machine.succeed("cat ${overlapLog}").splitlines() + host_up = {"active", "activating", "deactivating", "reloading"} + samples = [(line.split()[1].removeprefix("host="), int(line.split()[2].removeprefix("pods="))) for line in lines] + both = [s for s in samples if s[0] in host_up and s[1] > 0] + assert not both, both[:5] + # The controls: the sampler saw the container alone and a pod alone. + assert any(s[0] in host_up and s[1] == 0 for s in samples), lines[:5] + assert any(s[0] not in host_up and s[1] > 0 for s in samples), lines[:5] + print(f"{len(lines)} samples, none with both") + ''; +}