Watch
0
0
Fork
You've already forked hyperhive
0

vm-tests: the state gate refuses an empty volume until the marker is written

This commit is contained in:
atlas 2026-11-22 18:59:22 +01:00 • committed by maia
commit 360454958a
3 changed files with 164 additions and 69 deletions

View file

@ -181,9 +181,13 @@ pkgs.testers.runNixOSTest {
};
system.stateVersion = "25.11";
specialisation.k8s.configuration.services.hyperhive.deploy.swarm-controller.runtime = "k8s";
specialisation.k8s.configuration.services.hyperhive.deploy.swarm-controller = {
runtime = "k8s";
k8s.freshState = true;
};
specialisation.k8s-rev.configuration.services.hyperhive.deploy = {
swarm-controller.runtime = "k8s";
swarm-controller.k8s.freshState = true;
hive-controller.hyperhiveRev = lib.mkForce revB;
};
@ -390,7 +394,7 @@ pkgs.testers.runNixOSTest {
except Exception:
diagnose(["hyperhive-k8s-ca-trust.service"])
print(machine.execute(f"kubectl -n {NS} describe pod {name}")[1])
for container in ("tls-issue", "tls-renew", SERVICE):
for container in ("state-gate", "tls-issue", "tls-renew", SERVICE):
print(machine.execute(f"kubectl -n {NS} logs {name} -c {container} --tail=60")[1])
raise
return name
@ -524,7 +528,7 @@ pkgs.testers.runNixOSTest {
assert probe["path"] == "/readyz", probe
api = next(p for p in main["ports"] if p["name"] == "api")
assert api["hostPort"] == PORT and api["hostIP"] == NODE_ADDRESS, api
assert [c["name"] for c in spec["initContainers"]] == ["tls-issue"], spec["initContainers"]
assert [c["name"] for c in spec["initContainers"]] == ["state-gate", "tls-issue"], spec["initContainers"]
assert "tls-renew" in [c["name"] for c in spec["containers"]]
assert not any("secret" in v for v in spec["volumes"]), spec["volumes"]
env = {e["name"]: e.get("value") for e in main["env"]}

View file

@ -18,8 +18,8 @@
# open with `openFirewall`, where a second node dials it by name and verifies
# the name. The exporter's port answers the host's own processes only;
# - a stream written before the pod is deleted is read after;
# - the store guard refuses an empty store unless it is marked fresh, run as
# the pod's own image runs it;
# - the pod's state gate marks the empty store as fresh, and passes the volume
# with its marker after a pod delete;
# - the switch back leaves no pod, Deployment or AddOn, and the container
# starts after the prune unit.
#
@ -179,11 +179,11 @@ pkgs.testers.runNixOSTest {
specialisation.k8s.configuration.services.hyperhive.deploy.nats = {
runtime = "k8s";
k8s.freshStore = true;
k8s.freshState = true;
};
specialisation.k8s-open.configuration.services.hyperhive.deploy.nats = {
runtime = "k8s";
k8s.freshStore = true;
k8s.freshState = true;
openFirewall = true;
};
@ -422,7 +422,7 @@ pkgs.testers.runNixOSTest {
except Exception:
diagnose(["hyperhive-k8s-ca-trust.service"])
print(machine.execute(f"kubectl -n {NS} describe pod {name}")[1])
for container in ("store-guard", "tls-issue", "callout-config", SERVICE, "nats", "exporter"):
for container in ("state-gate", "tls-issue", "callout-config", SERVICE, "nats", "exporter"):
print(machine.execute(f"kubectl -n {NS} logs {name} -c {container} --tail=60")[1])
raise
return name
@ -586,9 +586,9 @@ pkgs.testers.runNixOSTest {
machine.fail("test -e /etc/nixos-containers/swarm-nats.conf")
assert counts() == (1, 1), counts()
with subtest("the pod holds the guard, the leaf and the config as init containers, and publishes the client port on every address and the exporter's on the bridge"):
with subtest("the pod holds the state gate, the leaf and the config as init containers, and publishes the client port on every address and the exporter's on the bridge"):
spec = pod(machine, pod_name)["spec"]
assert [c["name"] for c in spec["initContainers"]] == ["store-guard", "tls-issue", "callout-config"], spec["initContainers"]
assert [c["name"] for c in spec["initContainers"]] == ["state-gate", "tls-issue", "callout-config"], spec["initContainers"]
assert [c["name"] for c in spec["containers"]] == ["swarm-nats", "nats", "tls-renew", "exporter"], spec["containers"]
assert spec["shareProcessNamespace"] is True, spec
server = next(c for c in spec["containers"] if c["name"] == "nats")
@ -614,8 +614,8 @@ pkgs.testers.runNixOSTest {
machine.fail(f"grep -F '{mount}/nats-config ' /proc/mounts")
issued = machine.succeed(f"kubectl -n {NS} logs {pod_name} -c tls-issue")
assert f"requesting the queue's TLS leaf for {NAME} from the store" in issued, issued
guard = machine.succeed(f"kubectl -n {NS} logs {pod_name} -c store-guard")
assert "empty and marked fresh" in guard, guard
guard = machine.succeed(f"kubectl -n {NS} logs {pod_name} -c state-gate")
assert "the install is fresh: marked" in guard, guard
# The pod's server keeps the descriptors the container's did.
limits = machine.succeed("grep 'Max open files' /proc/$(pgrep -ox nats-server)/limits")
print(limits)
@ -665,49 +665,10 @@ pkgs.testers.runNixOSTest {
assert json.loads(kube(machine, f"get pvc {SERVICE}-state -o json"))["metadata"]["uid"] == STATE_VOLUME
machine.wait_until_succeeds(nats_cmd(SERVICES_ROOT, f"stream info {STREAM}"), timeout=120)
assert stream_messages() == 1
guard = machine.succeed(f"kubectl -n {NS} logs {pod_name} -c store-guard")
assert "holds data" in guard, guard
guard = machine.succeed(f"kubectl -n {NS} logs {pod_name} -c state-gate")
assert "state volume is migrated" in guard, guard
assert counts() == (1, 1), counts()
with subtest("the store guard refuses an empty store unless it is marked fresh, and passes one that holds data, run as the pod's own image runs it"):
image = pod(machine, pod_name)["spec"]["initContainers"][0]["image"]
def one_off(name: str, fresh: str, volume: str) -> tuple[str, str]:
manifest = {
"apiVersion": "v1",
"kind": "Pod",
"metadata": {"name": name},
"spec": {
"restartPolicy": "Never",
"securityContext": {"runAsUser": 65532, "runAsGroup": 65532, "fsGroup": 65532},
"containers": [
{
"name": "guard",
"image": image,
"imagePullPolicy": "Never",
"command": ["/bin/swarm-nats-store-guard"],
"env": [{"name": "SWARM_NATS_FRESH_STORE", "value": fresh}],
"volumeMounts": [{"name": "store", "mountPath": "/var/lib/nats", "readOnly": True}],
}
],
"volumes": [{"name": "store", **json.loads(volume)}],
},
}
machine.succeed(f"echo '{json.dumps(manifest)}' | kubectl apply -f -")
machine.wait_until_succeeds(
f"kubectl get pod {name} -o jsonpath='{{.status.phase}}' | grep -E 'Succeeded|Failed'",
timeout=120,
)
phase = machine.succeed(f"kubectl get pod {name} -o jsonpath='{{.status.phase}}'").strip()
return phase, machine.succeed(f"kubectl logs {name}")
phase, text = one_off("guard-empty", "false", '{"emptyDir": {}}')
assert phase == "Failed" and "empty JetStream store" in text and "swarmctl migrate" in text, (phase, text)
phase, text = one_off("guard-fresh", "true", '{"emptyDir": {}}')
assert phase == "Succeeded" and "marked fresh" in text, (phase, text)
phase, text = one_off("guard-data", "false", f'{{"persistentVolumeClaim": {{"claimName": "{SERVICE}-state"}}}}')
assert phase == "Succeeded" and "holds data" in text, (phase, text)
with subtest("with openFirewall a host outside the node dials the pod by name and verifies it, and is admitted"):
switch("/run/booted-system/specialisation/k8s-open")
assert len(pods()) == 1, pods()

View file

@ -3,31 +3,31 @@
# claude login minter move between their host units or containers and the host's
# cluster (`services.hyperhive.deploy.<service>.runtime`), against the real
# secret store and a real queue. The host boots with all five on the host; the
# `k8s` specialisation has them 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:
# `k8s` specialisation has them in the cluster. 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;
# switch's own timestamps and by a sampler that looks every 200 ms (the
# poller's copies: timer, service, 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, holds no Secret, and keeps
# its cursor in a volume, so a second Job pushes nothing;
# its own route of the swarm collector, holds no Secret, and keeps its cursor
# in a volume, so a second Job pushes nothing;
# - the minter's jwt token writes an agent's credentials and the classifier's
# cannot; the daemons' pods have a read-only root, and `claude` writes its
# config under `HOME` in the /tmp volume only, as the real login step does;
# - the switch back leaves no pod, Deployment, CronJob or AddOn, and the
# router's consumer is the queue's, unchanged.
# - the switch back leaves no pod, Deployment, CronJob or AddOn, and the router's
# consumer is the queue's;
# - the state gate marks an empty volume with `freshState` on, refuses it with
# the option off (`Init:Error`, host unit stopped) and a volume of files with
# no marker, and passes the marker the test writes as `swarmctl migrate`.
#
# 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. The test makes the hive's CA and the leaf of every name at boot.
# The queue is a plain nats-server with TLS, and one stub is the token endpoint,
# the forge and the swarm collector, which records what it is given. The
# speech-to-text model is a placeholder; the hive's CA and leaves come at boot.
{ pkgs, self }:
let
inherit (pkgs) lib;
@ -52,6 +52,13 @@ let
classifier = "swarm-review-classifier";
login = "swarm-claude-login";
agent = "atlas";
# A shell with the pod user's volumes, for the pods the script plays
# `swarmctl migrate` and the gate's one-off runs with.
helperImage = pkgs.dockerTools.buildLayeredImage {
name = "k8s-helper";
tag = "test";
contents = [ pkgs.busybox ];
};
pkiDir = "/var/lib/test-ca";
tlsDir = "/var/lib/hive-tls";
leaf = "swarm/services/${clientId}/oidc/client";
@ -200,7 +207,7 @@ pkgs.testers.runNixOSTest {
# 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;
globalTimeout = 3000;
nodes.machine =
{ config, ... }:
@ -242,10 +249,16 @@ pkgs.testers.runNixOSTest {
specialisation.k8s.configuration.services.hyperhive.deploy = {
notify-router.runtime = "k8s";
stt.runtime = "k8s";
stt.k8s.freshState = true;
ci-metrics.runtime = "k8s";
ci-metrics.k8s.freshState = true;
review-classifier.runtime = "k8s";
claude-login.runtime = "k8s";
};
# The speech-to-text pod alone, with no fresh install: its empty volume
# is refused.
specialisation.k8s-unmarked.configuration.services.hyperhive.deploy.stt.runtime = "k8s";
services.k3s.images = [ helperImage ];
# 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
@ -373,7 +386,7 @@ pkgs.testers.runNixOSTest {
}/store-paths";
environment.etc."k3s-node/images".text = lib.concatMapStrings (
i: "${i.imageName}:${i.imageTag}\n"
) config.system.build.k8sImages;
) (config.system.build.k8sImages ++ [ helperImage ]);
# 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" =
@ -434,6 +447,7 @@ pkgs.testers.runNixOSTest {
NATS = "--server tls://${natsName}:${toString natsPort} --tlsca ${pkiDir}/ca.pem"
AGENT = "${agent}"
SELECTOR = f"--selector app.kubernetes.io/name={SERVICE}"
HELPER = "${helperImage.imageName}:${helperImage.imageTag}"
def as_root(command: str) -> str:
@ -664,6 +678,10 @@ pkgs.testers.runNixOSTest {
for daemon, (daemon_unit, _) in CLAUDE_DAEMONS.items():
assert host_state(daemon_unit) == "inactive", host_state(daemon_unit)
machine.succeed(f"test -L {MANIFESTS}/{daemon}.yaml")
# Suspended as soon as it exists: a scheduled Job at the next five-minute
# mark would push the run before the test's own Job does.
machine.wait_until_succeeds(f"kubectl -n {NS} get cronjob {CI}", timeout=300)
kube(machine, f"patch cronjob {CI} -p '{{\"spec\":{{\"suspend\":true}}}}'")
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
@ -735,6 +753,12 @@ pkgs.testers.runNixOSTest {
claim = json.loads(kube(machine, f"get pvc {STT}-state -o json"))
assert claim["status"]["phase"] == "Bound", claim["status"]
CACHE_VOLUME = claim["metadata"]["uid"]
# The first init container is the state gate, which marked the empty
# volume because `freshState` is on.
gate_spec = json.loads(kube(machine, f"get pod {stt_pod} -o json"))["spec"]
assert [c["name"] for c in gate_spec["initContainers"]] == ["state-gate"], gate_spec["initContainers"]
gate_log = machine.succeed(f"kubectl -n {NS} logs {stt_pod} -c state-gate")
assert "the install is fresh: marked" in gate_log, gate_log
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
@ -1100,5 +1124,111 @@ pkgs.testers.runNixOSTest {
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")
GATE_REFUSAL = f"{STT}: state volume has not been migrated: run `swarmctl migrate {STT}`, or set services.hyperhive.deploy.stt.k8s.freshState for a fresh install"
def helper(name: str, script: str, claim: str | None = None, setup: str | None = None, image: str = HELPER, fresh: str | None = None) -> tuple[str, str]:
"""Runs `script` in a pod of the helper image with the volume of
`claim` (an empty one if None) at /state as the pod user, and returns
its phase and log. With `fresh`, runs the gate image as the pod's own
state gate does, after `setup` has run in the helper image."""
volume: dict[str, dict[str, str]] = {"persistentVolumeClaim": {"claimName": claim}} if claim else {"emptyDir": {}}
container: dict[str, object] = {"name": "run", "image": image, "imagePullPolicy": "Never", "volumeMounts": [{"name": "state", "mountPath": "/state"}]}
spec: dict[str, object] = {
"restartPolicy": "Never",
"securityContext": {"runAsUser": 65532, "runAsGroup": 65532, "fsGroup": 65532},
"volumes": [{"name": "state", **volume}],
"containers": [container],
}
if fresh is None:
container["command"] = ["sh", "-c", script]
else:
container["command"] = ["/bin/hyperhive-state-gate"]
container["env"] = [
{"name": "STATE_GATE_DIR", "value": "/state"},
{"name": "STATE_GATE_SERVICE", "value": "one-off"},
{"name": "STATE_GATE_FRESH", "value": fresh},
{"name": "STATE_GATE_OPTION", "value": "the.option"},
]
spec["initContainers"] = [
{"name": "setup", "image": HELPER, "imagePullPolicy": "Never", "command": ["sh", "-c", setup or "true"], "volumeMounts": container["volumeMounts"]}
]
manifest = {"apiVersion": "v1", "kind": "Pod", "metadata": {"name": name}, "spec": spec}
machine.succeed(f"echo '{json.dumps(manifest)}' | kubectl -n {NS} apply -f -")
machine.wait_until_succeeds(
f"kubectl -n {NS} get pod {name} -o jsonpath='{{.status.phase}}' | grep -E 'Succeeded|Failed'",
timeout=120,
)
phase = machine.succeed(f"kubectl -n {NS} get pod {name} -o jsonpath='{{.status.phase}}'").strip()
text = machine.succeed(f"kubectl -n {NS} logs {name} -c run")
kube(machine, f"delete pod {name} --wait=true")
return phase, text
with subtest("the gate marked the fresh volume with the time, and the marker is what the pod's gate reads"):
phase, text = helper("read-marker", "cat /state/.hyperhive-migrated", claim=f"{STT}-state")
marker = json.loads(text)
assert phase == "Succeeded" and marker["fresh"] is True and re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", marker["at"]), (phase, text)
with subtest("run as the pod's own gate image runs it: lost+found alone is empty, files with no marker are refused even on a fresh install"):
gate_image = json.loads(kube(machine, f"get pod {service_pods(STT)[0].removeprefix('pod/')} -o json"))["spec"]["initContainers"][0]["image"]
phase, text = helper("gate-lost-found", "", setup="mkdir /state/lost+found", image=gate_image, fresh="true")
assert phase == "Succeeded" and "marked" in text, (phase, text)
phase, text = helper("gate-stray", "", setup="touch /state/stray", image=gate_image, fresh="true")
assert phase == "Failed" and "holds files and no .hyperhive-migrated marker" in text and "swarmctl migrate one-off" in text, (phase, text)
phase, text = helper("gate-unmarked", "", image=gate_image, fresh="false")
assert phase == "Failed" and "run `swarmctl migrate one-off`, or set the.option for a fresh install" in text, (phase, text)
phase, text = helper("gate-marker", "", setup="touch /state/.hyperhive-migrated /state/data", image=gate_image, fresh="false")
assert phase == "Succeeded" and "state volume is migrated" in text, (phase, text)
with subtest("back on the host, the speech-to-text claim stays; it is deleted so that the next pod meets an empty volume"):
switch("/run/booted-system")
settle(f"[ \"$(systemctl is-active {STT_HOST_UNIT})\" = active ]", 600, [STT_HOST_UNIT, f"{STT_PRUNE}.service"])
assert service_pods(STT) == [], service_pods(STT)
kube(machine, f"delete pvc {STT}-state --wait=true --timeout=120s", 150)
with subtest("with freshState off, the pod of an empty volume stays in Init:Error with the reason and nothing of the service runs, and the host unit stays stopped"):
switch("/run/booted-system/specialisation/k8s-unmarked")
assert host_state(STT_HOST_UNIT) == "inactive", host_state(STT_HOST_UNIT)
machine.wait_until_succeeds(f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={STT} -o name | grep -q pod/", timeout=300)
refused_pod = service_pods(STT)[0].removeprefix("pod/")
reason = (
"{.status.initContainerStatuses[0].state.terminated.message}"
"{.status.initContainerStatuses[0].lastState.terminated.message}"
)
machine.wait_until_succeeds(f"kubectl -n {NS} get pod {refused_pod} -o jsonpath='{reason}' | grep -qF 'has not been migrated'", timeout=300)
message = machine.succeed(f"kubectl -n {NS} get pod {refused_pod} -o jsonpath='{reason}'").strip()
assert message == GATE_REFUSAL, message
# The gate retries and is refused again: the pod does not start, and
# the one-copy invariant is untouched.
machine.wait_until_succeeds(f"kubectl -n {NS} get pod {refused_pod} -o jsonpath='{{.status.initContainerStatuses[0].restartCount}}' | grep -qE '^[1-9]'", timeout=300)
refused = pod(machine, refused_pod)
assert refused["status"]["phase"] == "Pending", refused["status"]
assert [c["state"].get("waiting", {}).get("reason") for c in refused["status"]["containerStatuses"]] == ["PodInitializing"], refused["status"]
assert not is_ready(refused)
assert GATE_REFUSAL in machine.succeed(f"kubectl -n {NS} logs {refused_pod} -c state-gate")
assert host_state(STT_HOST_UNIT) == "inactive", host_state(STT_HOST_UNIT)
assert machine.execute("machinectl list --no-legend | grep -q swarm-stt")[0] != 0
# The control: the claim the pod mounts is bound, and its volume is empty.
phase, text = helper("read-empty", "ls -A /state | wc -l", claim=f"{STT}-state")
assert phase == "Succeeded" and text.strip() == "0", (phase, text)
with subtest("the marker the test writes, as the copy does, lets the same pod start"):
phase, _ = helper("play-migrate", "echo migrated > /state/.hyperhive-migrated", claim=f"{STT}-state")
assert phase == "Succeeded", phase
# The kubelet runs the gate again after its backoff, which is five
# minutes at most.
started = wait_pod_ready(STT, timeout=420)
assert started == refused_pod, (started, refused_pod)
assert "state volume is migrated" in machine.succeed(f"kubectl -n {NS} logs {started} -c state-gate")
assert host_state(STT_HOST_UNIT) == "inactive", host_state(STT_HOST_UNIT)
with subtest("a volume that holds files and no marker is refused, and the refusal says the copy may be cut off"):
phase, _ = helper("cut-off", "rm /state/.hyperhive-migrated; echo x > /state/half", claim=f"{STT}-state")
assert phase == "Succeeded", phase
kube(machine, f"delete pod {started} --wait=true --timeout=120s", 150)
machine.wait_until_succeeds(f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={STT} -o name | grep -q pod/", timeout=120)
half_pod = service_pods(STT)[0].removeprefix("pod/")
machine.wait_until_succeeds(f"kubectl -n {NS} get pod {half_pod} -o jsonpath='{reason}' | grep -qF 'holds files and no .hyperhive-migrated marker'", timeout=300)
assert not is_ready(pod(machine, half_pod))
'';
}