# `vmTests..k8s-runtime-switch`: the notification router, the # speech-to-text service and the CI run poller move between their host units # and the host's cluster (`services.hyperhive.deploy..runtime`), # against the real secret store and a real queue. The host boots with all three # on the host; the `k8s` specialisation has all three in the cluster. One test # holds them because the switch is one activation and a second VM would pay the # store's start-up again. The script switches to it, back, and to it again, and # asserts that: # # - exactly one copy of each service runs at each step, by the order of the # switch's own timestamps and by a sampler that looks every 200 ms. The # poller's copies are its timer and service, and its CronJob, Jobs and pods; # - each pod is Ready, so it logged in to the store with its ServiceAccount # token, read its client secret and minted a token with it. The router # routes an event and a deleted pod exits 0 within its grace period; the # speech-to-text pod carries its limits and has its cache volume bound; # - the poller's Job completes against a forge that lists one run, pushes it to # the poller's own route of the swarm collector with a bearer the stub # minted, holds no Secret, and keeps its cursor in a volume, so a second Job # pushes nothing; # - the switch back leaves no pod, Deployment, CronJob or AddOn, and the # router's consumer is the queue's, unchanged. # # The queue is a plain nats-server with TLS, and one stub is the token # endpoint, the forge and the swarm collector: it records the client # credentials it is given and each push's route. They replace services that # stay host-run and unchanged. The speech-to-text service gets a placeholder # model file, which it never loads. The test makes the hive's CA and the leaf of # every name 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"; forgeName = "forge.t.local"; otelName = "otel.t.local"; namespace = "hyperhive"; service = "swarm-notify-router"; clientId = "swarm-notify-router"; stt = "swarm-stt"; sttClientId = "swarm-stt"; ci = "swarm-ci-metrics"; # A fixed value: it is the stub's to check, not a secret. forgeToken = "test-forge-token"; agent = "atlas"; pkiDir = "/var/lib/test-ca"; tlsDir = "/var/lib/hive-tls"; leaf = "swarm/services/${clientId}/oidc/client"; sttLeaf = "swarm/services/${sttClientId}/oidc/client"; ciLeaf = "swarm/services/${ci}/oidc/client"; ciForgeLeaf = "swarm/services/ci-metrics/forge/token"; prune = "${service}-k8s-prune"; sttPrune = "${stt}-k8s-prune"; ciPrune = "${ci}-k8s-prune"; hostUnit = "container@${service}.service"; sttHostUnit = "container@${stt}.service"; # The model file the service is given: its path is in the pod's image, and # nothing reads it. sttModel = pkgs.writeText "ggml-placeholder.bin" "not a model"; overlapLog = "/var/log/overlap.log"; tokenLog = "/var/log/stub-token.log"; requestLog = "/var/log/stub-requests.log"; # The identity provider, the forge and the swarm collector, by name, on one # listener. The token endpoint answers every client-credentials request with # a token and records the client id and secret of the Basic credentials. # The forge lists one repo with one finished run. The collector's poller # route answers 200 and, with the forge, records the request: the route, the # name asked for, whether the credential is the one this stub issued or # expects, and the points the body carried. tokenStub = pkgs.writeText "token-stub.py" '' import base64 import http.server import json import secrets import ssl MINTED = set() RUN = { "index_in_repo": 1, "status": "success", "event": "pull_request", "prettyref": "#7", "workflow_id": "ci.yml", "commit_sha": "d0ab2edd05bcce7a35ea15bbc2ef5a366fc93d18", "created": "2026-10-16T16:50:38+02:00", "started": "2026-10-16T16:55:17+02:00", "stopped": "2026-10-16T17:13:30+02:00", } def record(entry): with open("${requestLog}", "a") as log: log.write(json.dumps(entry) + "\n") class Handler(http.server.BaseHTTPRequestHandler): def reply(self, payload): body = json.dumps(payload).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) def do_POST(self): raw = self.rfile.read(int(self.headers.get("Content-Length", 0))) auth = self.headers.get("Authorization", "") path = self.path.split("?")[0] if path.endswith("/v1/metrics"): metrics = json.loads(raw)["resourceMetrics"][0]["scopeMetrics"][0]["metrics"] record({ "host": self.headers.get("Host"), "path": path, "bearer_minted": auth.removeprefix("Bearer ") in MINTED, "points": {m["name"]: len(m["gauge"]["dataPoints"]) for m in metrics}, }) self.reply({}) return 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") token = secrets.token_hex(16) MINTED.add(token) self.reply({"access_token": token, "token_type": "Bearer", "expires_in": 3600}) def do_GET(self): path = self.path.split("?")[0] record({ "host": self.headers.get("Host"), "path": path, "forge_token_ok": self.headers.get("Authorization") == "token ${forgeToken}", }) if path.endswith("/repos/search"): self.reply({"ok": True, "data": [{"full_name": "o/r", "has_actions": True, "archived": False, "mirror": False}]}) elif path.endswith("/repos/o/r/actions/runs"): self.reply({"workflow_runs": [RUN], "total_count": 1}) else: self.send_error(404) server = http.server.ThreadingHTTPServer(("${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, for each service, at whether its host unit runs and how # many of its objects exist in the cluster, a terminating pod included. The # poller is on the host while its timer or its service is active, and in the # cluster while its CronJob, a Job or a pod exists. sampler = pkgs.writeShellScript "overlap-sampler" '' while true; do for svc in ${service} ${stt}; do state="$(systemctl is-active container@$svc.service || true)" pods="$(kubectl --namespace ${namespace} get pods --selector app.kubernetes.io/name=$svc --no-headers 2>/dev/null | wc -l)" echo "$(date +%s.%N) $svc host=$state pods=$pods" >> ${overlapLog} done state=inactive for unit in ${ci}.timer ${ci}.service; do case "$(systemctl is-active $unit || true)" in active|activating|deactivating|reloading) state=active ;; esac done objects="$(kubectl --namespace ${namespace} get cronjob,pods --selector app.kubernetes.io/name=${ci} --no-headers 2>/dev/null | wc -l)" jobs="$(kubectl --namespace ${namespace} get jobs --no-headers 2>/dev/null | grep -c "^${ci}" || true)" echo "$(date +%s.%N) ${ci} host=$state pods=$((objects + jobs))" >> ${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.stt.enable = true; deploy.stt.settings.modelFile = sttModel; deploy.ci-metrics.enable = true; deploy.hive-controller.hiveName = "h1"; swarm.domain = "t.local"; swarm.forge.domain = forgeName; swarm.otel.domain = otelName; swarm.bao.domain = baoName; swarm.bao.port = baoPort; swarm.hives.h1.domain = "h1.t.local"; # The queue, the identity provider, the forge and the swarm collector # are host-run: their names go to the bridge for the cluster's pods, as # the hive's own do. gateway.localNames = [ natsName authName forgeName otelName ]; }; system.stateVersion = "25.11"; specialisation.k8s.configuration.services.hyperhive.deploy = { notify-router.runtime = "k8s"; stt.runtime = "k8s"; ci-metrics.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 forgeName otelName ]; 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 names of the queue, the identity # provider, the forge and the collector, 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},DNS:${forgeName},DNS:${otelName}\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" ]; }; # The speech-to-text image carries ffmpeg and whisper. The pod's limits # (3 GiB, four cores) are as large as the node's cores, so it is # schedulable only because it requests none of them. virtualisation = { memorySize = 8192; cores = 4; diskSize = 12288; }; }; testScript = builtins.readFile ./lib/k3s.py + '' INIT = "/root/bao-init.json" NS = "${namespace}" SERVICE = "${service}" HOST_UNIT = "${hostUnit}" PRUNE = "${prune}" STT = "${stt}" STT_HOST_UNIT = "${sttHostUnit}" STT_PRUNE = "${sttPrune}" CI = "${ci}" CI_PRUNE = "${ciPrune}" CI_HOST_UNITS = ["${ci}.timer", "${ci}.service"] OWN_ROUTE = "/${ci}/v1/metrics" RUN_METRIC = "hyperhive.ci.run.duration" CERT_METRIC = "bao.client_cert.not_after" 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 service_pods(service: str) -> list[str]: out = machine.succeed(f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={service} -o name || true") return out.split() def router_pods() -> list[str]: return service_pods(SERVICE) def host_state(unit: str = HOST_UNIT) -> str: return machine.execute(f"systemctl is-active {unit}")[1].strip() def ci_host_state() -> str: """`active` while the poller's timer or service runs on the host.""" states = [host_state(unit) for unit in CI_HOST_UNITS] return "active" if any(s in ("active", "activating", "deactivating", "reloading") for s in states) else "inactive" def requests() -> list[dict]: return [json.loads(line) for line in machine.succeed("cat ${requestLog}").splitlines() if line] def pushes(metric: str) -> list[dict]: """The collector requests that carried points of `metric`.""" return [r for r in requests() if r.get("points", {}).get(metric)] def ci_job(name: str) -> str: """Runs one Job from the poller's CronJob, waits for it to complete, and answers its pod's log.""" kube(machine, f"create job {name} --from=cronjob/{CI}") try: kube(machine, f"wait --for=condition=complete job/{name} --timeout=300s", timeout=330) except Exception: print(machine.execute(f"kubectl -n {NS} describe job {name}")[1]) print(machine.execute(f"kubectl -n {NS} logs job/{name} --tail=80")[1]) raise return kube(machine, f"logs job/{name}") def stopped_at(unit: str) -> int: return int(machine.succeed(f"date -d \"$(systemctl show -p InactiveEnterTimestamp --value {unit})\" +%s")) def created_at_of(pod_name: str) -> int: stamp = machine.succeed(f"kubectl -n {NS} get pod {pod_name} -o jsonpath='{{.metadata.creationTimestamp}}'") return int(machine.succeed(f"date -d \"{stamp}\" +%s")) def consumer() -> dict: return json.loads(machine.succeed(f"nats {NATS} consumer info SWARM_EVENTS notify-router --json")) def wait_pod_ready(service: str = SERVICE, timeout: int = 600) -> str: machine.wait_until_succeeds( f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={service} -o name | grep -q pod/", timeout=timeout, ) name = service_pods(service)[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, STT_HOST_UNIT, *CI_HOST_UNITS, f"{PRUNE}.service", f"{STT_PRUNE}.service", f"{CI_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, timeout=300) 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 policies and roles of the router, the speech-to-text service and the poller, 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-stt-policy", "swarm-bao-ci-metrics-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 services' queue client secrets, 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}") STT_SECRET = machine.succeed("openssl rand -hex 16").strip() as_root(f"bao kv put -mount=secret ${sttLeaf} value={STT_SECRET}") # The poller reads its own client secret and the forge token the # controller mints in production. CI_SECRET = machine.succeed("openssl rand -hex 16").strip() as_root(f"bao kv put -mount=secret ${ciLeaf} value={CI_SECRET}") as_root("bao kv put -mount=secret ${ciForgeLeaf} value=${forgeToken} name=ci-metrics") 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 containers run and the cluster holds no router or speech-to-text service"): machine.wait_until_succeeds(f"[ \"$(systemctl is-active {HOST_UNIT})\" = active ]", timeout=300) machine.wait_until_succeeds(f"[ \"$(systemctl is-active {STT_HOST_UNIT})\" = active ]", timeout=300) assert router_pods() == [], router_pods() assert service_pods(STT) == [], service_pods(STT) assert machine.execute(f"test -e {MANIFESTS}/{STT}.yaml")[0] != 0 assert machine.execute(f"kubectl -n {NS} get deployment {STT}")[0] != 0 assert machine.execute(f"kubectl -n {NS} get pvc {STT}-state")[0] != 0 assert machine.succeed(f"systemctl is-active {STT_PRUNE}.service").strip() == "active" 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("on the host, the poller's timer runs, one pass pushes the run to the poller's own route, and the cluster holds none of it"): assert host_state(f"{CI}.timer") == "active", host_state(f"{CI}.timer") assert machine.succeed(f"systemctl is-active {CI_PRUNE}.service").strip() == "active" assert machine.execute(f"test -e {MANIFESTS}/{CI}.yaml")[0] != 0 assert machine.execute(f"kubectl -n {NS} get cronjob {CI}")[0] != 0 assert machine.execute(f"kubectl -n {NS} get pvc {CI}-state")[0] != 0 # A timer pass may be running or may have failed before the store held # the secrets; this start waits for the one that runs, or runs one. machine.succeed(f"systemctl reset-failed {CI}.service || true") machine.succeed(f"systemctl start {CI}.service", timeout=300) runs = pushes(RUN_METRIC) assert len(runs) == 1, runs assert runs[0]["path"] == OWN_ROUTE and runs[0]["host"] == "${otelName}", runs assert runs[0]["bearer_minted"], runs assert runs[0]["points"] == {RUN_METRIC: 1, "hyperhive.ci.run.queue_wait": 1}, runs # The host unit holds the store certificate, so its pass also reports # that certificate's lifetime. assert len(pushes(CERT_METRIC)) >= 1, requests() machine.succeed("test -s /var/lib/swarm-ci-metrics/cursor.json") HOST_CERT_PUSHES = len(pushes(CERT_METRIC)) 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 STT_HOST_UNIT in out and "stopping the following units" in out, out assert host_state() == "inactive", host_state() assert host_state(STT_HOST_UNIT) == "inactive", host_state(STT_HOST_UNIT) machine.succeed(f"test -L {MANIFESTS}/{SERVICE}.yaml") machine.succeed(f"test -L {MANIFESTS}/{STT}.yaml") router = wait_pod_ready() assert stopped_at(HOST_UNIT) <= created_at_of(router) assert machine.execute("machinectl list --no-legend | grep -q swarm-notify-router")[0] != 0 with subtest("the speech-to-text pod is Ready after its container stopped, and the container is gone"): stt_pod = wait_pod_ready(STT) assert stopped_at(STT_HOST_UNIT) <= created_at_of(stt_pod) assert machine.execute("machinectl list --no-legend | grep -q swarm-stt")[0] != 0 with subtest("the poller's timer and service are gone from the host, and its CronJob is applied"): assert ci_host_state() == "inactive", [host_state(u) for u in CI_HOST_UNITS] assert machine.execute(f"systemctl cat {CI}.timer")[0] != 0 assert machine.execute(f"systemctl cat {CI}.service")[0] != 0 machine.succeed(f"test -L {MANIFESTS}/{CI}.yaml") machine.wait_until_succeeds(f"kubectl -n {NS} get cronjob {CI}", timeout=300) cron = json.loads(kube(machine, f"get cronjob {CI} -o json")) assert cron["spec"]["schedule"] == "*/5 * * * *", cron["spec"] assert cron["spec"]["concurrencyPolicy"] == "Forbid", cron["spec"] # A scheduled Job would run beside the ones this test makes. kube(machine, f"patch cronjob {CI} -p '{{\"spec\":{{\"suspend\":true}}}}'") 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 speech-to-text pod logged in to the store with its token, read its client secret and minted a token with it"): machine.wait_until_succeeds(f"grep -F '/api/oidc/token ${sttClientId}:{STT_SECRET}' ${tokenLog}", timeout=120) env = {e["name"]: e.get("value") for e in json.loads(kube(machine, f"get pod {stt_pod} -o json"))["spec"]["containers"][0]["env"]} assert env["BAO_AUTH"] == "jwt" and env["BAO_JWT_ROLE"] == STT, env assert "BAO_CLIENT_CERT" not in env and "BAO_CLIENT_KEY" not in env, env volumes = json.loads(kube(machine, f"get pod {stt_pod} -o json"))["spec"]["volumes"] assert not any("secret" in v for v in volumes), volumes with subtest("the speech-to-text pod carries its unit's limits, reserves nothing, and is Burstable"): # The unit sets MemoryMax=3G and CPUQuota=400% and no MemoryMin or # MemoryLow. The API server prints 4000m as 4 and accepts the requests # of 0 the renderer sets. def pod_field(path: str) -> str: return kube(machine, f"get pod {stt_pod} -o jsonpath='{{{path}}}'") assert json.loads(pod_field(".spec.containers[0].resources.limits")) == {"cpu": "4", "memory": "3Gi"} assert json.loads(pod_field(".spec.containers[0].resources.requests")) == {"cpu": "0", "memory": "0"} assert pod_field(".status.qosClass") == "Burstable", pod_field(".status.qosClass") # A pod whose unit sets neither is the control that the field is read # from the unit: the router's has none. router_resources = json.loads(kube(machine, f"get pod {router} -o json"))["spec"]["containers"][0]["resources"] assert router_resources == {}, router_resources with subtest("the speech-to-text cache volume is bound and mounted where the unit keeps its state"): claim = json.loads(kube(machine, f"get pvc {STT}-state -o json")) assert claim["status"]["phase"] == "Bound", claim["status"] CACHE_VOLUME = claim["metadata"]["uid"] mounts = json.loads(kube(machine, f"get pod {stt_pod} -o json"))["spec"]["containers"][0]["volumeMounts"] assert any(m["name"] == "state" and m["mountPath"] == "/var/lib/swarm-stt" for m in mounts), mounts with subtest("the poller's Job completes against the forge and pushes the run to the poller's own route with a token the identity provider minted"): tokens_before = int(machine.succeed(f"grep -cF '/api/oidc/token ${ci}:{CI_SECRET}' ${tokenLog} || true")) job_log = ci_job(f"{CI}-first") assert "pushed=1" in job_log.replace(" ", ""), job_log # The cursor does not move with the poller: the pod starts with none # and pushes the run the host pass pushed. runs = pushes(RUN_METRIC) assert len(runs) == 2, runs assert runs[1]["path"] == OWN_ROUTE and runs[1]["host"] == "${otelName}", runs[1] assert runs[1]["bearer_minted"], runs[1] assert runs[1]["points"] == {RUN_METRIC: 1, "hyperhive.ci.run.queue_wait": 1}, runs[1] # Every push of the poller, the host's and the pod's, went to its own # route. The pod holds no client certificate, so it reports none. assert {r["path"] for r in requests() if "points" in r} == {OWN_ROUTE}, requests() assert len(pushes(CERT_METRIC)) == HOST_CERT_PUSHES >= 1, requests() # The pod read the forge token and its client secret from the store, # and reached the forge and the identity provider by name. forge = [r for r in requests() if "forge_token_ok" in r] assert len(forge) >= 4, forge assert all(r["forge_token_ok"] and r["host"] == "${forgeName}" for r in forge), forge tokens = int(machine.succeed(f"grep -cF '/api/oidc/token ${ci}:{CI_SECRET}' ${tokenLog}")) assert tokens > tokens_before, (tokens, tokens_before) with subtest("the poller's pod keeps the route its unit names, holds no Secret, and gets the store's CA from the ConfigMap"): ci_pod = json.loads(kube(machine, f"get pods --selector job-name={CI}-first -o json"))["items"][0] spec = ci_pod["spec"] env = {e["name"]: e.get("value") for e in spec["containers"][0]["env"]} assert env["SWARM_CI_METRICS_OTLP_ENDPOINT"] == "https://${otelName}/${ci}", env assert "OTEL_EXPORTER_OTLP_ENDPOINT" not in env, env assert env["BAO_AUTH"] == "jwt" and env["BAO_JWT_ROLE"] == CI, env assert "BAO_CLIENT_CERT" not in env and "BAO_CLIENT_KEY" not in env, env creds = next(v for v in spec["volumes"] if v["name"] == "credentials") sources = creds["projected"]["sources"] assert [src["configMap"]["name"] for src in sources] == ["hyperhive-ca-trust"], sources assert [(i["key"], i["path"]) for i in sources[0]["configMap"]["items"]] == [("bao-server-ca.pem", "bao-ca.pem")], sources assert not any("secret" in v or any("secret" in src for src in v.get("projected", {}).get("sources", [])) for v in spec["volumes"]), spec["volumes"] assert machine.succeed(f"kubectl -n {NS} get secrets -o name || true").strip() == "" # The control that the lookup finds the variable: the router's pod sets # it, and the poller's does not. router_env = {e["name"]: e.get("value") for e in json.loads(kube(machine, f"get pod {router} -o json"))["spec"]["containers"][0]["env"]} assert "OTEL_EXPORTER_OTLP_ENDPOINT" in router_env, router_env with subtest("the poller's cursor volume is bound and mounted where the unit keeps its state, and a second Job pushes nothing"): claim = json.loads(kube(machine, f"get pvc {CI}-state -o json")) assert claim["status"]["phase"] == "Bound", claim["status"] CURSOR_VOLUME = claim["metadata"]["uid"] mounts = ci_pod["spec"]["containers"][0]["volumeMounts"] assert any(m["name"] == "state" and m["mountPath"] == "/var/lib/swarm-ci-metrics" for m in mounts), mounts seen = len(requests()) job_log = ci_job(f"{CI}-second") assert "pushed=0" in job_log.replace(" ", ""), job_log assert len(pushes(RUN_METRIC)) == 2, requests() # The pass ran: it listed the forge again. assert len(requests()) > seen, requests() 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("deleting the speech-to-text pod ends its container with exit code 0 within the grace period, and its replacement is Ready"): old_stt = service_pods(STT)[0].removeprefix("pod/") terminated, took = delete_pod(machine, old_stt, timeout=60) assert terminated["exitCode"] == 0, terminated print(f"stt pod deleted in {took:.1f}s, container exit code {terminated['exitCode']}") assert took < 15 + 5, took assert wait_pod_ready(STT) != old_stt with subtest("the switch back removes the pods and their objects before the containers start, and keeps the cache volume"): out = switch("/run/booted-system") print(out) machine.wait_until_succeeds(f"[ \"$(systemctl is-active {HOST_UNIT})\" = active ]", timeout=300) machine.wait_until_succeeds(f"[ \"$(systemctl is-active {STT_HOST_UNIT})\" = active ]", timeout=300) assert router_pods() == [], router_pods() assert service_pods(STT) == [], service_pods(STT) assert machine.execute(f"kubectl -n {NS} get deployment {STT}")[0] != 0 assert machine.execute(f"kubectl -n kube-system get addons.k3s.cattle.io {STT}")[0] != 0 assert machine.execute(f"test -e {MANIFESTS}/{STT}.yaml")[0] != 0 assert machine.execute(f"test -e {MANIFESTS}/{STT}.yaml.pruning")[0] != 0 pruned_stt = int(machine.succeed(f"systemctl show -p ExecMainExitTimestampMonotonic --value {STT_PRUNE}.service")) started_stt = int(machine.succeed(f"systemctl show -p InactiveExitTimestampMonotonic --value {STT_HOST_UNIT}")) assert 0 < pruned_stt <= started_stt, (pruned_stt, started_stt) # Persistent volume claims stay, with what they hold. assert json.loads(kube(machine, f"get pvc {STT}-state -o json"))["metadata"]["uid"] == CACHE_VOLUME 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 switch back removes the poller's CronJob, Jobs and pods before its timer starts, and keeps the cursor volume"): machine.wait_until_succeeds(f"[ \"$(systemctl is-active {CI}.timer)\" = active ]", timeout=300) assert machine.execute(f"kubectl -n {NS} get cronjob {CI}")[0] != 0 assert service_pods(CI) == [], service_pods(CI) assert machine.execute(f"kubectl -n {NS} get jobs --no-headers | grep -q ^{CI}")[0] != 0 assert machine.execute(f"kubectl -n kube-system get addons.k3s.cattle.io {CI}")[0] != 0 assert machine.execute(f"test -e {MANIFESTS}/{CI}.yaml")[0] != 0 assert machine.execute(f"test -e {MANIFESTS}/{CI}.yaml.pruning")[0] != 0 pruned_ci = int(machine.succeed(f"systemctl show -p ExecMainExitTimestampMonotonic --value {CI_PRUNE}.service")) started_ci = int(machine.succeed(f"systemctl show -p InactiveExitTimestampMonotonic --value {CI}.timer")) assert 0 < pruned_ci <= started_ci, (pruned_ci, started_ci) # Both host units wait for the prune unit, so a pass started by hand # cannot run beside a Job either. for unit in CI_HOST_UNITS: requires = machine.succeed(f"systemctl show -p Requires --value {unit}") after = machine.succeed(f"systemctl show -p After --value {unit}") assert f"{CI_PRUNE}.service" in requires and f"{CI_PRUNE}.service" in after, (unit, requires, after) assert json.loads(kube(machine, f"get pvc {CI}-state -o json"))["metadata"]["uid"] == CURSOR_VOLUME with subtest("the poller on the host again finds its own cursor, and pushes no run twice"): # The cursor on the host is the one its first pass wrote; the pod's is # in the volume. A pass here pushes nothing but its certificate gauges. machine.succeed(f"systemctl reset-failed {CI}.service || true") machine.succeed(f"systemctl start {CI}.service", timeout=300) assert len(pushes(RUN_METRIC)) == 2, requests() assert len(pushes(CERT_METRIC)) > HOST_CERT_PUSHES, requests() 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, and the speech-to-text pod finds its volume"): switch("/run/booted-system/specialisation/k8s") assert host_state() == "inactive", host_state() assert host_state(STT_HOST_UNIT) == "inactive", host_state(STT_HOST_UNIT) wait_pod_ready() wait_pod_ready(STT) claim = json.loads(kube(machine, f"get pvc {STT}-state -o json")) assert claim["status"]["phase"] == "Bound" and claim["metadata"]["uid"] == CACHE_VOLUME, claim assert ci_host_state() == "inactive", [host_state(u) for u in CI_HOST_UNITS] machine.wait_until_succeeds(f"kubectl -n {NS} get cronjob {CI}", timeout=300) kube(machine, f"patch cronjob {CI} -p '{{\"spec\":{{\"suspend\":true}}}}'") # The volume the first stay left holds the cursor: nothing is pushed. assert json.loads(kube(machine, f"get pvc {CI}-state -o json"))["metadata"]["uid"] == CURSOR_VOLUME job_log = ci_job(f"{CI}-third") assert "pushed=0" in job_log.replace(" ", ""), job_log assert len(pushes(RUN_METRIC)) == 2, requests() with subtest("no moment of any switch had a service's container and a pod together"): machine.succeed("systemctl stop overlap-sampler.service") lines = machine.succeed("cat ${overlapLog}").splitlines() host_up = {"active", "activating", "deactivating", "reloading"} for svc in (SERVICE, STT, CI): samples = [ (fields[2].removeprefix("host="), int(fields[3].removeprefix("pods="))) for fields in (line.split() for line in lines) if len(fields) == 4 and fields[1] == svc ] both = [s for s in samples if s[0] in host_up and s[1] > 0] assert not both, (svc, 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), (svc, lines[:5]) assert any(s[0] not in host_up and s[1] > 0 for s in samples), (svc, lines[:5]) print(f"{svc}: {len(samples)} samples, none with both") ''; }