Watch
0
0
Fork
You've already forked hyperhive
0

vm-tests: a k3s node harness, and the swarm images boot as pods

This commit is contained in:
atlas 2026-11-19 09:37:34 +01:00 • committed by maia
commit aaf11a0764
6 changed files with 427 additions and 0 deletions

View file

@ -111,3 +111,12 @@ set one there and read it with `os.environ` in the script. `nix fmt` formats and
`ruff-format` and `ruff-check`, which fixes what it can), and the `formatting` `ruff-format` and `ruff-check`, which fixes what it can), and the `formatting`
flake check fails on a file `nix fmt` would change. `nix/vm-tests/ruff.toml` flake check fails on a file `nix fmt` would change. `nix/vm-tests/ruff.toml`
names the globals the test driver provides. names the globals the test driver provides.
Tests that need a k8s cluster import `nix/vm-tests/lib/k3s-node.nix`, a
single-node k3s server that loads the image tarballs it's given and pulls
nothing, and start their script with the text of `nix/vm-tests/lib/k3s.py`,
which holds the helpers: wait for the node and the images, wait for a pod's
phase or readiness, read a container's state, fetch a pod's health endpoint,
and delete a pod while recording its exit and how long the delete took.
`k8s-swarm-images` boots the swarm daemons' images as pods on it. Run a k3s
test on its own, by name: the all-tests run can pass the one-hour job limit.

View file

@ -135,6 +135,7 @@ let
full-setup full-setup
semi-spread semi-spread
swarm-builder-offline swarm-builder-offline
k8s-swarm-images
; ;
}; };
in in

View file

@ -15,5 +15,6 @@
swarm-archive = import ./vm-tests/swarm-archive.nix { inherit pkgs; }; swarm-archive = import ./vm-tests/swarm-archive.nix { inherit pkgs; };
swarm-builder-offline = import ./vm-tests/swarm-builder-offline.nix { inherit pkgs self; }; swarm-builder-offline = import ./vm-tests/swarm-builder-offline.nix { inherit pkgs self; };
full-setup = import ./vm-tests/full-setup.nix { inherit pkgs self; }; full-setup = import ./vm-tests/full-setup.nix { inherit pkgs self; };
k8s-swarm-images = import ./vm-tests/k8s-swarm-images.nix { inherit pkgs self; };
semi-spread = import ./vm-tests/semi-spread.nix { inherit pkgs self; }; semi-spread = import ./vm-tests/semi-spread.nix { inherit pkgs self; };
} }

View file

@ -0,0 +1,224 @@
# `vmTests.<system>.k8s-swarm-images`: the swarm daemons' images
# (`packages.<system>.image-*`) run as pods on a single-node k3s
# (`lib/k3s-node.nix`) with no store and no queue behind them. The script
# asserts:
#
# - the node is Ready within 300 s of boot, and containerd lists every image;
# - `swarm-logs-auth` and `swarm-metrics-auth` keep running with no restart,
# `/healthz` answers 200 and `/readyz` 503, so the pod is not Ready: the store
# address points at a closed port;
# - `swarm-notify-router` answers the same while it retries its first store
# read, and a pod delete in that retry ends it with exit 0 within 10 s;
# - a delete of the idle `swarm-logs-auth` ends it with exit 0 within 10 s;
# - `swarm-controller`, `swarm-nats-auth` and `swarm-ci-metrics` start their
# own binary, which prints its own error for the missing configuration and
# exits.
#
# Every pod names its image as `imageName:imageTag` with
# `imagePullPolicy: Never`. The pods are JSON files under
# `/etc/k8s-swarm-images/`, so the script has no Nix in it.
{ pkgs, self }:
let
inherit (pkgs) lib;
image = name: self.packages.${pkgs.stdenv.hostPlatform.system}."image-${name}";
daemons = [
"swarm-controller"
"swarm-nats-auth"
"swarm-logs-auth"
"swarm-metrics-auth"
"swarm-notify-router"
"swarm-ci-metrics"
];
healthPort = 8080;
# A store address where nothing listens and identity files that do not
# exist: every login fails at once.
storeEnv = lib.mapAttrsToList lib.nameValuePair {
BAO_ADDR = "https://127.0.0.1:1";
BAO_CLIENT_CERT = "/nonexistent/cert.pem";
BAO_CLIENT_KEY = "/nonexistent/key.pem";
};
probe = path: {
httpGet = {
inherit path;
port = healthPort;
};
periodSeconds = 5;
};
mkPod =
{
name,
args ? [ ],
env ? [ ],
restartPolicy ? "Always",
socketDir ? false,
}:
{
apiVersion = "v1";
kind = "Pod";
metadata = {
inherit name;
labels.app = name;
};
spec = {
inherit restartPolicy;
containers = [
(
{
inherit name args env;
image = "${(image name).imageName}:${(image name).imageTag}";
imagePullPolicy = "Never";
}
// lib.optionalAttrs (restartPolicy == "Always") {
readinessProbe = probe "/readyz";
}
// lib.optionalAttrs socketDir {
volumeMounts = [
{
name = "sock";
mountPath = "/sock";
}
];
}
)
];
volumes = lib.optional socketDir {
name = "sock";
emptyDir = { };
};
};
};
pods = {
swarm-logs-auth = mkPod {
name = "swarm-logs-auth";
args = [
"--socket=/sock/s.sock"
"--surface=logs"
"--health-addr=0.0.0.0:${toString healthPort}"
];
env = storeEnv;
socketDir = true;
};
swarm-metrics-auth = mkPod {
name = "swarm-metrics-auth";
args = [
"--socket=/sock/s.sock"
"--store-path=swarm/stub"
"--health-addr=0.0.0.0:${toString healthPort}"
];
env = storeEnv;
socketDir = true;
};
swarm-notify-router = mkPod {
name = "swarm-notify-router";
env = storeEnv ++ [
(lib.nameValuePair "SWARM_NOTIFY_ROUTER_OIDC_CLIENT_ID" "stub")
(lib.nameValuePair "SWARM_NOTIFY_ROUTER_HEALTH_ADDR" "0.0.0.0:${toString healthPort}")
];
};
}
// lib.genAttrs [ "swarm-controller" "swarm-nats-auth" "swarm-ci-metrics" ] (
name:
mkPod {
inherit name;
restartPolicy = "Never";
}
);
in
pkgs.testers.runNixOSTest {
name = "k8s-swarm-images";
# Under the 20 min budget for one dispatched run; the runner's job bound is 1 h.
globalTimeout = 1500;
nodes.machine = {
imports = [
(import ./lib/k3s-node.nix {
images = map image daemons;
memoryMiB = 4096;
})
];
environment.etc = lib.mapAttrs' (
name: p: lib.nameValuePair "k8s-swarm-images/${name}.json" { text = builtins.toJSON p; }
) pods;
};
testScript = builtins.readFile ./lib/k3s.py + ''
PODS = "/etc/k8s-swarm-images"
HEALTH = 8080
def apply(name: str) -> None:
kube(machine, f"apply -f {PODS}/{name}.json")
def assert_serving_unready(name: str) -> None:
p = wait_pod(machine, name, phase="Running", timeout=60)
assert not is_ready(p), f"{name} is Ready with no store: {p['status']}"
assert http_status(machine, name, HEALTH, "/healthz") == 200
assert http_status(machine, name, HEALTH, "/readyz") == 503
def assert_stops_cleanly(name: str) -> None:
terminated, took = delete_pod(machine, name)
print(f"{name}: deleted in {took:.1f} s, terminated {terminated}")
assert terminated.get("exitCode") == 0, f"{name}: {terminated}"
assert took <= 10, f"{name}: the delete took {took:.1f} s"
with subtest("the node is Ready and holds every image"):
wait_node_ready(machine, timeout=300)
wait_images(machine)
with subtest("the store responders serve health and stay unready"):
apply("swarm-logs-auth")
apply("swarm-metrics-auth")
for name in ["swarm-logs-auth", "swarm-metrics-auth"]:
assert_serving_unready(name)
time.sleep(30)
for name in ["swarm-logs-auth", "swarm-metrics-auth"]:
state = container_state(machine, name)
assert "running" in state["state"], f"{name}: {state}"
assert state["restartCount"] == 0, f"{name}: {state}"
assert http_status(machine, name, HEALTH, "/healthz") == 200
assert http_status(machine, name, HEALTH, "/readyz") == 503
with subtest("an idle swarm-logs-auth stops on a pod delete"):
assert_stops_cleanly("swarm-logs-auth")
with subtest("swarm-notify-router stops on a pod delete during its startup retry"):
apply("swarm-notify-router")
assert_serving_unready("swarm-notify-router")
machine.wait_until_succeeds(
"kubectl logs swarm-notify-router | grep -q 'reading the queue client secret failed'",
timeout=20,
)
state = container_state(machine, "swarm-notify-router")
assert "running" in state["state"], state
assert state["restartCount"] == 0, state
assert_stops_cleanly("swarm-notify-router")
with subtest("the remaining images start their own binary"):
expected = {
"swarm-controller": "binding",
"swarm-nats-auth": "Usage: swarm-nats-auth",
"swarm-ci-metrics": "SWARM_CI_METRICS_OIDC_CLIENT_ID is unset",
}
for name in expected:
apply(name)
for name, line in expected.items():
wait_pod(machine, name, phase="Failed", timeout=60)
terminated = container_state(machine, name)["state"]["terminated"]
assert terminated["reason"] == "Error", f"{name}: {terminated}"
logs = kube(machine, f"logs {name}")
print(f"{name}: exit {terminated['exitCode']}: {logs}")
assert line in logs, f"{name}: no {line!r} in its log"
'';
}

View file

@ -0,0 +1,51 @@
# A single-node k3s server for a NixOS VM test: import it as a node module,
# `imports = [ (import ./lib/k3s-node.nix { images = [ … ]; }) ]`.
#
# - `images`: `dockerTools` image tarballs (`buildLayeredImage`), which k3s'
# containerd imports from its image directory at start. Nothing is pulled:
# the VM has no network, so a pod names one of these with
# `imagePullPolicy: Never`. `/etc/k3s-node/images` lists their references
# (`imageName:imageTag`, one per line) for `lib/k3s.py`'s `wait_images`.
# - `memoryMiB`: the VM's memory.
#
# CoreDNS and the local-path provisioner stay on, so a test can use cluster DNS
# and PersistentVolumeClaims. The firewall stays on and trusts the pod network's
# interfaces, so the node reaches pods on their IPs.
#
# `lib/k3s.py` holds the Python helpers a test script uses with this node.
{
images ? [ ],
memoryMiB ? 6144,
}:
{ config, pkgs, ... }:
{
services.k3s = {
enable = true;
role = "server";
images = [ config.services.k3s.package.airgap-images ] ++ images;
extraFlags = [
"--disable=traefik,servicelb,metrics-server"
"--write-kubeconfig-mode=644"
];
};
environment.systemPackages = [
pkgs.kubectl
pkgs.curl
];
environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml";
environment.etc."k3s-node/images".text = pkgs.lib.concatMapStrings (
i: "${i.imageName}:${i.imageTag}\n"
) images;
networking.firewall.trustedInterfaces = [
"cni0"
"flannel.1"
];
virtualisation = {
memorySize = memoryMiB;
cores = 4;
diskSize = 8192;
};
}

141
nix/vm-tests/lib/k3s.py Normal file
View file

@ -0,0 +1,141 @@
# Helpers for a test script whose node imports `lib/k3s-node.nix`. A test's
# `testScript` is this file's text followed by its own. Every helper takes the
# node first and fails the test through the driver (`succeed`, `wait_until_*`)
# or an `AssertionError` naming what it saw.
import json
import time
from test_driver.machine import QemuMachine
# Container states that never turn into a running container on their own.
STUCK_WAITING = {
"ErrImageNeverPull",
"ErrImagePull",
"ImagePullBackOff",
"InvalidImageName",
"CreateContainerError",
"CreateContainerConfigError",
}
def kube(node: QemuMachine, args: str, timeout: int = 60) -> str:
return node.succeed(f"kubectl {args}", timeout=timeout)
def wait_node_ready(node: QemuMachine, timeout: int = 300) -> None:
"""Starts the node and waits until its k8s Node is Ready and the `default`
namespace has its ServiceAccount, which a pod there needs, at most
`timeout` seconds from the start."""
start = time.monotonic()
node.start()
node.wait_until_succeeds(
"kubectl get node -o jsonpath="
"'{.items[0].status.conditions[?(@.type==\"Ready\")].status}' | grep -qx True",
timeout=timeout,
)
left = max(1, int(timeout - (time.monotonic() - start)))
node.wait_until_succeeds("kubectl get serviceaccount default", timeout=left)
def containerd_ref(ref: str) -> str:
"""The name containerd lists an image under: a reference without a
registry is on docker.io, and a one-part name under `library/`."""
first = ref.split("/", 1)[0]
if "/" in ref and ("." in first or ":" in first or first == "localhost"):
return ref
return "docker.io/" + (ref if "/" in ref else "library/" + ref)
def image_refs(node: QemuMachine) -> list[str]:
"""The references of the images the node module was given."""
return node.succeed("cat /etc/k3s-node/images").split()
def wait_images(node: QemuMachine, timeout: int = 120) -> None:
"""Waits until containerd lists every image the node module was given."""
for ref in image_refs(node):
node.wait_until_succeeds(
f"k3s ctr images ls -q | grep -qxF '{containerd_ref(ref)}'",
timeout=timeout,
)
def pod(node: QemuMachine, name: str) -> dict:
return json.loads(kube(node, f"get pod {name} -o json"))
def container_state(node: QemuMachine, name: str) -> dict:
"""The first container's status of pod `name`, `{}` before it has one."""
statuses = pod(node, name)["status"].get("containerStatuses") or [{}]
return statuses[0]
def is_ready(p: dict) -> bool:
return any(
c["type"] == "Ready" and c["status"] == "True"
for c in p["status"].get("conditions", [])
)
def wait_pod(
node: QemuMachine,
name: str,
phase: str | None = None,
ready: bool | None = None,
timeout: int = 120,
) -> dict:
"""Waits until pod `name` is in `phase` and its Ready condition is `ready`
(each when given), and answers the pod. Fails at once on a container that
cannot start (`STUCK_WAITING`)."""
deadline = time.monotonic() + timeout
while True:
p = pod(node, name)
state = (p["status"].get("containerStatuses") or [{}])[0].get("state", {})
reason = state.get("waiting", {}).get("reason")
assert reason not in STUCK_WAITING, f"{name}: container cannot start: {state}"
if (phase is None or p["status"].get("phase") == phase) and (
ready is None or is_ready(p) == ready
):
return p
assert time.monotonic() < deadline, (
f"{name}: not phase={phase} ready={ready} after {timeout} s: {p['status']}"
)
time.sleep(2)
def http_status(node: QemuMachine, name: str, port: int, path: str) -> int:
"""The HTTP status pod `name` answers on its IP for `path`."""
ip = pod(node, name)["status"]["podIP"]
return int(
node.succeed(
f"curl -s -o /dev/null -m 5 -w '%{{http_code}}' http://{ip}:{port}{path}"
)
)
def delete_pod(node: QemuMachine, name: str, timeout: int = 60) -> tuple[dict, float]:
"""Deletes pod `name` and answers its container's final `terminated` state
and the seconds the delete took until the pod was gone."""
watch = f"/tmp/watch-{name}.json"
node.succeed(
f"timeout {timeout + 30} kubectl get pod {name} --watch --output-watch-events "
f"-o json > {watch} 2>&1 &"
)
node.wait_until_succeeds(f"test -s {watch}", timeout=30)
start = time.monotonic()
kube(node, f"delete pod {name} --wait=true --timeout={timeout}s", timeout + 10)
took = time.monotonic() - start
node.wait_until_succeeds(f"grep -q DELETED {watch}", timeout=30)
text = node.succeed(f"cat {watch}")
decoder = json.JSONDecoder()
terminated: dict = {}
i = 0
while i < len(text):
if text[i].isspace():
i += 1
continue
event, i = decoder.raw_decode(text, i)
for c in event["object"]["status"].get("containerStatuses", []):
terminated = c.get("state", {}).get("terminated") or terminated
assert terminated, f"{name}: no terminated state seen while deleting: {text}"
return terminated, took