Watch
0
0
Fork
You've already forked hyperhive
0

k8s: stt and ci-metrics start without a state gate

This commit is contained in:
atlas 2026-11-23 02:46:31 +01:00 • committed by maia
commit 6ac4e9b87d
2 changed files with 296 additions and 309 deletions

View file

@ -18,7 +18,10 @@
# - a changed hyperhive rev rolls the Deployment, and the state volume is the
# one the first pod had;
# - the switch back leaves no pod, Deployment or AddOn, and the host unit
# starts after the prune unit.
# starts after the prune unit;
# - 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
# and the forge; they replace services that stay host-run and unchanged. The
@ -48,6 +51,13 @@ let
controllerSecretLeaf = "swarm/controller/swarm-controller/oidc/client";
revA = lib.fixedWidthString 40 "a" "";
revB = lib.fixedWidthString 40 "b" "";
# 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 ];
};
overlapLog = "/var/log/overlap.log";
tokenLog = "/var/log/stub-token.log";
@ -185,6 +195,11 @@ pkgs.testers.runNixOSTest {
runtime = "k8s";
k8s.freshState = true;
};
# The controller in the cluster with no fresh install: its empty volume is
# refused.
specialisation.k8s-unmarked.configuration.services.hyperhive.deploy.swarm-controller.runtime =
"k8s";
services.k3s.images = [ helperImage ];
specialisation.k8s-rev.configuration.services.hyperhive.deploy = {
swarm-controller.runtime = "k8s";
swarm-controller.k8s.freshState = true;
@ -308,7 +323,7 @@ pkgs.testers.runNixOSTest {
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;
) (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" =
@ -329,7 +344,10 @@ pkgs.testers.runNixOSTest {
};
testScript = builtins.readFile ./lib/k3s.py + ''
import re
INIT = "/root/bao-init.json"
HELPER = "${helperImage.imageName}:${helperImage.imageTag}"
NS = "${namespace}"
SERVICE = "${service}"
HOST_UNIT = "${hostUnit}"
@ -529,6 +547,7 @@ pkgs.testers.runNixOSTest {
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"]] == ["state-gate", "tls-issue"], spec["initContainers"]
GATE_IMAGE = spec["initContainers"][0]["image"]
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"]}
@ -620,5 +639,130 @@ pkgs.testers.runNixOSTest {
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"{SERVICE}: {len(samples)} samples, none with both")
GATE_REFUSAL = f"{SERVICE}: state volume has not been migrated: run `swarmctl migrate {SERVICE}`, or set services.hyperhive.deploy.swarm-controller.k8s.freshState for a fresh install"
def migrate_step(step: str, service: str = SERVICE) -> dict[str, str]:
"""The `step` of `service` in `swarmctl migrate status --json`, which
reads the gate's answer from the pod's status and creates no pod."""
report = json.loads(machine.succeed("swarmctl migrate status --json"))
found = [s for s in report["steps"] if s["service"] == service and s["step"] == step]
assert len(found) == 1, (step, report["steps"])
return found[0]
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"{SERVICE}-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"):
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("the claim stays on the host; it is deleted so that the next pod meets an empty volume"):
assert host_state() == "active", host_state()
kube(machine, f"delete pvc {SERVICE}-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() == "inactive", host_state()
machine.wait_until_succeeds(f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o name | grep -q pod/", timeout=300)
refused_pod = pods()[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()
# The current and the previous attempt each leave the one line.
assert set(message.splitlines()) == {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"]
# Every container waits: the pod has the daemon and the leaf renewal.
waiting = {c["state"].get("waiting", {}).get("reason") for c in refused["status"]["containerStatuses"]}
assert waiting == {"PodInitializing"} and len(refused["status"]["containerStatuses"]) >= 1, refused["status"]
assert not is_ready(refused)
assert GATE_REFUSAL in machine.succeed(f"kubectl -n {NS} logs {refused_pod} -c state-gate")
# `swarmctl migrate status` reports the same refusal, and not as a marker.
pods_before = machine.succeed(f"kubectl -n {NS} get pods -o name").split()
copy = migrate_step("copy")
assert copy["status"] == "not_done" and GATE_REFUSAL in copy["detail"], copy
assert migrate_step("ready")["status"] == "not_done"
assert machine.succeed(f"kubectl -n {NS} get pods -o name").split() == pods_before, "status created or deleted a pod"
assert host_state() == "inactive", host_state()
# 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"{SERVICE}-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"{SERVICE}-state")
assert phase == "Succeeded", phase
# The kubelet runs the gate again after its backoff, which is five
# minutes at most.
started = wait_pod_ready(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")
copy = migrate_step("copy")
assert copy["status"] == "done" and started in copy["detail"], copy
assert migrate_step("ready")["status"] == "done", migrate_step("ready")
assert migrate_step("runtime")["status"] == "done", migrate_step("runtime")
assert host_state() == "inactive", host_state()
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"{SERVICE}-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={SERVICE} -o name | grep -q pod/", timeout=120)
half_pod = pods()[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))
copy = migrate_step("copy")
assert copy["status"] == "not_done" and "cut off" in copy["detail"], copy
'';
}

View file

@ -12,18 +12,17 @@
# - 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;
# speech-to-text pod carries its limits and keeps its cache in an emptyDir,
# with no claim and no state gate;
# - the poller's Job completes against a forge that lists one run, pushes it to
# its own route of the swarm collector, holds no Secret, and keeps its cursor
# in a volume, so a second Job pushes nothing;
# in a volume, so a second Job pushes nothing, and starts with no state
# gate;
# - 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;
# - 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`.
# consumer is the queue's.
#
# 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
@ -52,13 +51,6 @@ 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";
@ -249,16 +241,10 @@ 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
@ -386,7 +372,7 @@ pkgs.testers.runNixOSTest {
}/store-paths";
environment.etc."k3s-node/images".text = lib.concatMapStrings (
i: "${i.imageName}:${i.imageTag}\n"
) (config.system.build.k8sImages ++ [ helperImage ]);
) 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" =
@ -447,7 +433,6 @@ 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:
@ -749,17 +734,12 @@ pkgs.testers.runNixOSTest {
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"]
# 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"]
with subtest("the speech-to-text cache is an emptyDir mounted where the unit keeps its state, with no claim and no state gate"):
stt_spec = json.loads(kube(machine, f"get pod {stt_pod} -o json"))["spec"]
assert [v for v in stt_spec["volumes"] if v["name"] == "state"] == [{"name": "state", "emptyDir": {}}], stt_spec["volumes"]
assert "state-gate" not in [c["name"] for c in stt_spec.get("initContainers", [])], stt_spec.get("initContainers")
assert machine.execute(f"kubectl -n {NS} get pvc {STT}-state")[0] != 0
mounts = stt_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"):
@ -1035,8 +1015,9 @@ pkgs.testers.runNixOSTest {
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
# Persistent volume claims stay, with what they hold; the speech-to-text
# pod never had one.
assert machine.execute(f"kubectl -n {NS} get pvc {STT}-state")[0] != 0
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
@ -1088,7 +1069,7 @@ 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, and the speech-to-text pod finds its volume"):
with subtest("a second switch to the cluster applies the manifests again, and the speech-to-text pod finds no claim"):
switch("/run/booted-system/specialisation/k8s")
assert host_state() == "inactive", host_state()
assert host_state(STT_HOST_UNIT) == "inactive", host_state(STT_HOST_UNIT)
@ -1097,8 +1078,7 @@ pkgs.testers.runNixOSTest {
for daemon, (daemon_unit, _) in CLAUDE_DAEMONS.items():
assert host_state(daemon_unit) == "inactive", host_state(daemon_unit)
wait_pod_ready(daemon)
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 machine.execute(f"kubectl -n {NS} get pvc {STT}-state")[0] != 0
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}}}}'")
@ -1125,130 +1105,5 @@ pkgs.testers.runNixOSTest {
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 migrate_step(step: str, service: str = STT) -> dict[str, str]:
"""The `step` of `service` in `swarmctl migrate status --json`, which
reads the gate's answer from the pod's status and creates no pod."""
report = json.loads(machine.succeed("swarmctl migrate status --json"))
found = [s for s in report["steps"] if s["service"] == service and s["step"] == step]
assert len(found) == 1, (step, report["steps"])
return found[0]
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")
# `swarmctl migrate status` reports the same refusal, and not as a marker.
pods_before = machine.succeed(f"kubectl -n {NS} get pods -o name").split()
copy = migrate_step("copy")
assert copy["status"] == "not_done" and GATE_REFUSAL in copy["detail"], copy
assert migrate_step("ready")["status"] == "not_done"
assert machine.succeed(f"kubectl -n {NS} get pods -o name").split() == pods_before, "status created or deleted a pod"
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")
copy = migrate_step("copy")
assert copy["status"] == "done" and started in copy["detail"], copy
assert migrate_step("ready")["status"] == "done", migrate_step("ready")
assert migrate_step("runtime")["status"] == "done", migrate_step("runtime")
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))
copy = migrate_step("copy")
assert copy["status"] == "not_done" and "cut off" in copy["detail"], copy
'';
}