# `vmTests..k8s-runtime-switch`: the notification router and the # speech-to-text service move between their host containers and pods in the # host's cluster (`services.hyperhive.deploy..runtime`), against the # real secret store and a real queue. The host boots with both in their # containers; the `k8s` specialisation is the same host with both in the # cluster. One test holds both services 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 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 speech-to-text pod is Ready, logged in to the store with its # ServiceAccount token, carries its unit's memory and CPU limits, and has its # cache volume bound, which the switch back leaves in place; # - 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 services take their production path otherwise. # The speech-to-text service gets a placeholder model file, which it never # loads, and no transcription runs. 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"; stt = "swarm-stt"; sttClientId = "swarm-stt"; agent = "atlas"; pkiDir = "/var/lib/test-ca"; tlsDir = "/var/lib/hive-tls"; leaf = "swarm/services/${clientId}/oidc/client"; sttLeaf = "swarm/services/${sttClientId}/oidc/client"; prune = "${service}-k8s-prune"; sttPrune = "${stt}-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"; # 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, for each service, at whether its container runs and how # many of its pods exist, a terminating pod included. 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 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.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"; stt.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" ]; }; # 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}" 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 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, f"{PRUNE}.service", f"{STT_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 and the speech-to-text service, 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-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}") 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("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 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 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 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 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): 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") ''; }