Watch
0
0
Fork
You've already forked hyperhive
0

vm-tests: k8s-runtime-switch moves the speech-to-text service with the router

This commit is contained in:
atlas 2026-11-21 23:21:01 +01:00 • committed by maia
commit 6665567826

View file

@ -1,25 +1,32 @@
# `vmTests.<system>.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:
# `vmTests.<system>.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.<service>.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 runs at each step, by the order of the switch's own
# timestamps and by a sampler that looks every 200 ms;
# - 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 router takes its production path otherwise. The
# test makes the hive's CA and the leaf of both names at boot.
# 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;
@ -34,12 +41,20 @@ let
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";
@ -84,13 +99,15 @@ let
}
'';
# Looks every 200 ms at whether the container runs and how many router pods
# exist, a terminating pod included.
# 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
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}
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
'';
@ -116,6 +133,8 @@ pkgs.testers.runNixOSTest {
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;
@ -130,7 +149,10 @@ pkgs.testers.runNixOSTest {
};
system.stateVersion = "25.11";
specialisation.k8s.configuration.services.hyperhive.deploy.notify-router.runtime = "k8s";
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
@ -248,10 +270,12 @@ pkgs.testers.runNixOSTest {
];
};
# The speech-to-text pod has no requests, so the node reserves its limits
# (3 GiB, four cores), and its image carries ffmpeg and whisper.
virtualisation = {
memorySize = 8192;
cores = 4;
diskSize = 8192;
memorySize = 10240;
cores = 6;
diskSize = 12288;
};
};
@ -261,6 +285,9 @@ pkgs.testers.runNixOSTest {
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}"
@ -285,22 +312,38 @@ pkgs.testers.runNixOSTest {
raise
def router_pods() -> list[str]:
out = machine.succeed(f"kubectl -n {NS} get pods {SELECTOR} -o name || true")
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 host_state() -> str:
return machine.execute(f"systemctl is-active {HOST_UNIT}")[1].strip()
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(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/")
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:
@ -320,14 +363,14 @@ pkgs.testers.runNixOSTest {
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"]
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)
wait_images(machine, timeout=300)
kube(machine, f"config set-context --current --namespace={NS}")
with subtest("the store is initialised, unsealed and bootstrapped"):
@ -350,7 +393,7 @@ pkgs.testers.runNixOSTest {
timeout=300,
)
with subtest("the granting units have written the router's policy and role, and the jwt mount"):
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"])
@ -361,16 +404,18 @@ pkgs.testers.runNixOSTest {
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"]:
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 router's queue client secret, which the identity provider's mint
# 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")
@ -381,9 +426,15 @@ pkgs.testers.runNixOSTest {
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"):
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
@ -392,15 +443,20 @@ pkgs.testers.runNixOSTest {
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_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")
stopped = int(machine.succeed(f"date -d \"$(systemctl show -p InactiveEnterTimestamp --value {HOST_UNIT})\" +%s"))
machine.succeed(f"test -L {MANIFESTS}/{STT}.yaml")
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 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"]
@ -419,6 +475,32 @@ pkgs.testers.runNixOSTest {
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, and no requests of its own"):
# The unit sets MemoryMax=3G and CPUQuota=400%. The API server prints
# 4000m as 4. Kubernetes fills the requests in from the limits.
spec = json.loads(kube(machine, f"get pod {stt_pod} -o json"))["spec"]["containers"][0]["resources"]
assert spec["limits"] == {"cpu": "4", "memory": "3Gi"}, spec
assert spec["requests"] == spec["limits"], spec
# 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",
@ -452,11 +534,30 @@ pkgs.testers.runNixOSTest {
new = wait_pod_ready()
assert new != old, (new, old)
with subtest("the switch back removes the pod and its objects before the container starts"):
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
@ -471,21 +572,30 @@ pkgs.testers.runNixOSTest {
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"):
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 the container and a pod together"):
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"}
samples = [(line.split()[1].removeprefix("host="), int(line.split()[2].removeprefix("pods="))) for line in lines]
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, both[:5]
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), 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")
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")
'';
}