vm-tests: a k3s node harness, and the swarm images boot as pods
This commit is contained in:
parent
352af3ea59
commit
5a884a8d09
2 changed files with 427 additions and 0 deletions
51
nix/vm-tests/lib/k3s-node.nix
Normal file
51
nix/vm-tests/lib/k3s-node.nix
Normal 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
141
nix/vm-tests/lib/k3s.py
Normal 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
|
||||
Loading…
Reference in a new issue