k8s: the controller pod keeps no volume; the state gate goes
This commit is contained in:
parent
140ee7f38a
commit
4ea3b0e10d
1 changed files with 233 additions and 1110 deletions
|
|
@ -15,13 +15,10 @@
|
|||
# runtime and run here in a nginx of its own, reaches the controller: on the
|
||||
# host by name, in the cluster by the node's address, verifying the leaf as
|
||||
# the name; the controller answers an unsigned webhook 401 both times;
|
||||
# - a changed hyperhive rev rolls the Deployment, and the state volume is the
|
||||
# one the first pod had;
|
||||
# - a changed hyperhive rev rolls the Deployment; the pod's state directory is
|
||||
# an emptyDir, with no claim and no gate;
|
||||
# - the switch back leaves no pod, Deployment or AddOn, and the host 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`.
|
||||
# starts after the prune unit.
|
||||
#
|
||||
# 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
|
||||
|
|
@ -51,13 +48,6 @@ 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";
|
||||
|
||||
|
|
@ -191,18 +181,9 @@ pkgs.testers.runNixOSTest {
|
|||
};
|
||||
system.stateVersion = "25.11";
|
||||
|
||||
specialisation.k8s.configuration.services.hyperhive.deploy.swarm-controller = {
|
||||
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.configuration.services.hyperhive.deploy.swarm-controller.runtime = "k8s";
|
||||
specialisation.k8s-rev.configuration.services.hyperhive.deploy = {
|
||||
swarm-controller.runtime = "k8s";
|
||||
swarm-controller.k8s.freshState = true;
|
||||
hive-controller.hyperhiveRev = lib.mkForce revB;
|
||||
};
|
||||
|
||||
|
|
@ -323,7 +304,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 ++ [ 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" =
|
||||
|
|
@ -344,10 +325,7 @@ 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}"
|
||||
|
|
@ -412,7 +390,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 ("state-gate", "tls-issue", "tls-renew", SERVICE):
|
||||
for container in ("tls-issue", "tls-renew", SERVICE):
|
||||
print(machine.execute(f"kubectl -n {NS} logs {name} -c {container} --tail=60")[1])
|
||||
raise
|
||||
return name
|
||||
|
|
@ -546,16 +524,15 @@ 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"]] == ["state-gate", "tls-issue"], spec["initContainers"]
|
||||
GATE_IMAGE = spec["initContainers"][0]["image"]
|
||||
assert [c["name"] for c in spec["initContainers"]] == ["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"]}
|
||||
assert env["BAO_AUTH"] == "jwt" and env["BAO_JWT_ROLE"] == SERVICE, env
|
||||
assert "BAO_CLIENT_CERT" not in env, env
|
||||
claim = json.loads(kube(machine, f"get pvc {SERVICE}-state -o json"))
|
||||
assert claim["status"]["phase"] == "Bound", claim
|
||||
STATE_VOLUME = claim["metadata"]["uid"]
|
||||
# The state directory is an emptyDir: no claim, no gate.
|
||||
assert [v for v in spec["volumes"] if v["name"] == "state"] == [{"name": "state", "emptyDir": {}}], spec["volumes"]
|
||||
machine.fail(f"kubectl -n {NS} get pvc {SERVICE}-state")
|
||||
# The listener's key is in memory: the pod's `tls` volume is a tmpfs of
|
||||
# its own, which the kubelet mounts on the node. The `runtime` volume,
|
||||
# a plain emptyDir, has no mount of its own: the lookup's control.
|
||||
|
|
@ -588,7 +565,7 @@ pkgs.testers.runNixOSTest {
|
|||
))
|
||||
assert api_status == 200, api_status
|
||||
|
||||
with subtest("a changed rev rolls the Deployment, the old pod is gone first, and the state volume is the same"):
|
||||
with subtest("a changed rev rolls the Deployment, and the old pod is gone first"):
|
||||
old_uid = pod(machine, pod_name)["metadata"]["uid"]
|
||||
old_annotation = pod(machine, pod_name)["metadata"]["annotations"]["checksum/etc"]
|
||||
switch("/run/booted-system/specialisation/k8s-rev")
|
||||
|
|
@ -604,7 +581,6 @@ pkgs.testers.runNixOSTest {
|
|||
assert machine.execute(f"kubectl -n {NS} get pod {pod_name}")[0] != 0
|
||||
rev = machine.succeed(f"kubectl -n {NS} get configmap {SERVICE}-etc -o json | jq -r '.data[]'")
|
||||
assert "${revB}" in rev, rev
|
||||
assert json.loads(kube(machine, f"get pvc {SERVICE}-state -o json"))["metadata"]["uid"] == STATE_VOLUME
|
||||
assert len(pods()) == 1, pods()
|
||||
|
||||
with subtest("the switch back removes the Deployment, pod and AddOn before the unit starts"):
|
||||
|
|
@ -620,7 +596,7 @@ pkgs.testers.runNixOSTest {
|
|||
assert 0 < pruned <= started, (pruned, started)
|
||||
requires = machine.succeed(f"systemctl show -p Requires --value {HOST_UNIT}")
|
||||
assert f"{PRUNE}.service" in requires, requires
|
||||
assert json.loads(kube(machine, f"get pvc {SERVICE}-state -o json"))["metadata"]["uid"] == STATE_VOLUME
|
||||
machine.fail(f"kubectl -n {NS} get pvc {SERVICE}-state")
|
||||
settle(f"curl -sf --unix-socket {SOCKET} http://x/readyz", 300, [HOST_UNIT])
|
||||
assert gateway("gateway.service") == 401
|
||||
|
||||
|
|
@ -639,130 +615,5 @@ 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
|
||||
'';
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue