Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/nix/vm-tests/k8s-join.nix

542 lines
24 KiB
Nix

# `vmTests.<system>.k8s-join`: a second machine joins the main node's k3s
# through `services.hyperhive.deploy.k8s.join`, with the join token the main
# node wrote to its secret store. The main node runs the store and the cluster
# node (`deploy.k8s.enable`) and imports an image that the second machine does
# not hold. The script asserts that:
#
# - the main node's `k3s-join-token-publish` writes k3s's agent token to the
# store under the hive's identity, and the joining machine's
# `k3s-join-token` reads the same token under its own hive's identity;
# - the joining machine goes Ready, carries no `state-*`, `entry` or
# `enablelb` label, and the main node carries them;
# - the node-to-node ports are open on the main node from the joining
# machine's address only, and VXLAN's 8472 is open on neither node;
# - the pod network is flannel's WireGuard tunnel (`flannel-wg`, no `flannel.1`):
# each node holds the other's key and has shaken hands, a pod on the joining
# machine fetches a page from a pod on the main node through it, and a peer
# with a key of its own, sending from the main node's own address, gets no
# handshake and no answer;
# - a pod with the `state-ci-metrics` selector, the one the poller's pod
# carries, runs on the main node, and a pod forced onto the joining machine
# pulls its image from the main node through the embedded registry mirror
# and runs: the machine had none, and the image's host resolves nowhere;
# - a pod whose image no node holds fails to pull, with the images' registry
# host in the error and no request to docker.io.
#
# Both nodes' store identities are leaves the script signs with the store's
# CA: the module mints the hive's own and leaves the other hives' for an
# operator to copy, which is what the script plays.
{ pkgs, self }:
let
inherit (pkgs) lib;
images = import ../images {
inherit pkgs lib;
};
labels = import ../host-modules/k8s/labels.nix;
mainIp = "192.168.1.10";
joinIp = "192.168.1.11";
bridgeIp = "10.42.0.1";
baoName = "bao.t.local";
baoPort = 8200;
leafDir = "/var/lib/test-leaf";
pkiDir = "/var/lib/swarm-bao-pki";
# A daemon-shaped image, built the way the swarm's are, that only the main
# node imports.
probeImage = images.mkServiceImage {
name = "k8s-join-probe";
package = pkgs.coreutils;
bin = "sleep";
};
probeRef = "${probeImage.imageName}:${probeImage.imageTag}";
missingRef = "${images.registryHost}/nobody-has-this:v1";
# A shell and `wget`, in both nodes' containerd, so a pod on each node can
# talk to the other's.
netImage = pkgs.dockerTools.buildLayeredImage {
name = "k8s-join-net";
tag = "test";
contents = [ pkgs.busybox ];
};
netPort = 8080;
netPage = "page-of-the-pod-on-main";
netPod = name: node: command: {
apiVersion = "v1";
kind = "Pod";
metadata = { inherit name; };
spec = {
nodeSelector."kubernetes.io/hostname" = node;
restartPolicy = "Never";
containers = [
{
name = "net";
image = "${netImage.imageName}:${netImage.imageTag}";
imagePullPolicy = "Never";
inherit command;
}
];
};
};
pod = name: image: selector: {
apiVersion = "v1";
kind = "Pod";
metadata = { inherit name; };
spec = {
nodeSelector = selector;
restartPolicy = "Never";
containers = [
{
name = "probe";
inherit image;
imagePullPolicy = "IfNotPresent";
args = [ "3600" ];
}
];
};
};
identity = hive: {
baoHiveIdentityCertFile = "${leafDir}/${hive}.pem";
baoHiveIdentityKeyFile = "${leafDir}/${hive}-key.pem";
};
swarm = {
swarm.domain = "t.local";
swarm.bao.domain = baoName;
swarm.bao.port = baoPort;
swarm.hives.h1.domain = "h1.t.local";
swarm.hives.h2.domain = "h2.t.local";
};
in
pkgs.testers.runNixOSTest {
name = "k8s-join";
# The store takes a few minutes to open its raft storage, and a second node
# joins and pulls after it. Under the 1 h job bound with room for the build.
globalTimeout = 2700;
nodes.main =
{ config, lib, ... }:
{
imports = [ self.nixosModules.default ];
services.hyperhive = lib.recursiveUpdate swarm {
deploy.k8s = {
enable = true;
address = mainIp;
nodeAddresses = [ joinIp ];
};
network.enable = true;
network.bridgeIp = bridgeIp;
deploy.bao.enable = true;
deploy.bao.seal = "shamir";
deploy.bao.bootstrapTokenFile = "/var/lib/swarm-bao-bootstrap/grant.token";
# The joining machine reaches the store on the main node's address.
deploy.bao.extraListenAddresses = [ mainIp ];
# The poller's data is on this node's disk, so the module labels the
# node with its state label.
deploy.ci-metrics.enable = true;
deploy.hive-controller.hiveName = "h1";
deploy.hive-controller.tls = identity "h1";
};
system.stateVersion = "25.11";
# The store's name resolves to its loopback listener for this host.
services.nginx.enable = lib.mkForce false;
networking.hosts."127.0.0.1" = [ baoName ];
networking.firewall.allowedTCPPorts = [ baoPort ];
services.k3s.images = [
probeImage
netImage
];
environment.systemPackages = [
pkgs.kubectl
pkgs.jq
pkgs.openssl
pkgs.wireguard-tools
];
environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml";
environment.etc = {
"k8s-join/probe-ref".text = probeRef;
"k8s-join/flannel-port".text = toString config.services.hyperhive.deploy.k8s.flannelWgPort;
"k8s-join/pod-on-joiner.json".text = builtins.toJSON (
pod "on-joiner" probeRef { "kubernetes.io/hostname" = "joiner"; }
);
"k8s-join/pod-stateful.json".text = builtins.toJSON (
pod "stateful" probeRef (labels.stateSelector "ci-metrics")
);
"k8s-join/pod-missing.json".text = builtins.toJSON (
pod "missing" missingRef { "kubernetes.io/hostname" = "joiner"; }
);
"k8s-join/pod-net-main.json".text = builtins.toJSON (
netPod "net-main" "main" [
"sh"
"-c"
"mkdir /www && echo ${netPage} > /www/index.html && exec httpd -f -p ${toString netPort} -h /www"
]
);
"k8s-join/pod-net-joiner.json".text = builtins.toJSON (
netPod "net-joiner" "joiner" [
"sleep"
"3600"
]
);
};
networking.interfaces.eth1.ipv4.addresses = lib.mkForce [
{
address = mainIp;
prefixLength = 24;
}
];
# 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" =
{
device = "tmpfs";
fsType = "tmpfs";
options = [
"mode=0700"
"size=1G"
];
};
virtualisation = {
memorySize = 6144;
cores = 4;
diskSize = 8192;
};
};
nodes.joiner =
{ lib, ... }:
{
imports = [ self.nixosModules.default ];
services.hyperhive = lib.recursiveUpdate swarm {
deploy.k8s = {
join.server = mainIp;
address = joinIp;
};
deploy.hive-controller.hiveName = "h2";
deploy.hive-controller.tls = identity "h2";
deploy.bao.serverCaFile = "${leafDir}/ca.pem";
};
system.stateVersion = "25.11";
networking.hosts."${mainIp}" = [ baoName ];
networking.interfaces.eth1.ipv4.addresses = lib.mkForce [
{
address = joinIp;
prefixLength = 24;
}
];
services.k3s.images = [ netImage ];
environment.systemPackages = [
pkgs.jq
pkgs.wireguard-tools
];
virtualisation = {
memorySize = 3072;
cores = 2;
diskSize = 8192;
};
};
testScript = builtins.readFile ./lib/k3s.py + ''
import hashlib
INIT = "/root/bao-init.json"
LEAF_DIR = "${leafDir}"
PKI = "${pkiDir}"
TOKEN_LEAF = "swarm/services/k8s/agent-token"
SERVER_TOKEN = "/var/lib/rancher/k3s/server/agent-token"
JOIN_TOKEN = "/run/k3s-join/token"
JOINER_IP = "${joinIp}"
MAIN_IP = "${mainIp}"
FLANNEL_PORT = main.succeed("cat /etc/k8s-join/flannel-port").strip()
PROBE_REF = main.succeed("cat /etc/k8s-join/probe-ref").strip()
MISSING_REF = "${missingRef}"
HOST = "${images.registryHost}"
STATE_LABEL = "${labels.stateLabel "ci-metrics"}"
ENTRY_LABEL = "${labels.entryLabel}"
LB_LABEL = "${labels.loadBalancerLabel}"
def as_root(command: str) -> str:
return main.succeed(f'BAO_TOKEN="$(jq -r .root_token {INIT})" {command}')
def diagnose(units: list[str]) -> None:
for unit in units:
print(f"--- {unit}")
print(main.execute(f"systemctl status {unit} --no-pager -l; journalctl -u {unit} --no-pager -n 40")[1])
def settle(command: str, timeout: int, units: list[str]) -> None:
try:
main.wait_until_succeeds(command, timeout=timeout)
except Exception:
diagnose(units)
print(main.execute("kubectl get pods -o wide; kubectl logs net-main")[1])
raise
def sign(cn: str, name: str) -> None:
"""A client leaf for `cn` under the store's CA, at LEAF_DIR/<name>.pem."""
main.succeed(
f"cd {LEAF_DIR} && "
f"openssl req -newkey rsa:2048 -nodes -keyout {name}-key.pem -out {name}.csr -subj /CN={cn} && "
"printf 'basicConstraints=critical,CA:FALSE\\nkeyUsage=critical,digitalSignature,keyEncipherment\\n"
"extendedKeyUsage=clientAuth\\n' > leaf.ext && "
f"openssl x509 -req -in {name}.csr -CA {PKI}/ca.pem -CAkey {PKI}/ca-key.pem -CAcreateserial "
f"-days 30 -sha256 -extfile leaf.ext -out {name}.pem && chmod 0600 {name}-key.pem"
)
def ship(name: str) -> None:
"""Copies LEAF_DIR/<name> from the main node to the joining machine."""
data = main.succeed(f"base64 -w0 {LEAF_DIR}/{name}").strip()
joiner.succeed(f"install -d -m 0700 {LEAF_DIR} && echo {data} | base64 -d > {LEAF_DIR}/{name} && chmod 0600 {LEAF_DIR}/{name}")
def digest(node: QemuMachine, path: str) -> str:
return hashlib.sha256(node.succeed(f"cat {path}").strip().encode()).hexdigest()
def node_labels(name: str) -> dict:
return json.loads(kube(main, f"get node {name} -o json"))["metadata"]["labels"]
def first_status(name: str) -> dict:
return pod(main, name)["status"].get("containerStatuses", [{}])[0]
def wait_running(name: str, timeout: int) -> None:
"""Waits until pod `name` runs. A pull can fail before the joining machine knows
which peer holds the image, and the kubelet retries it, so those errors are
waited through."""
deadline = time.monotonic() + timeout
pull_errors: set[str] = set()
while True:
p = pod(main, name)
if p["status"].get("phase") == "Running" and is_ready(p):
print(f"{name}: running after pull errors {sorted(pull_errors)}")
return
reason = first_status(name).get("state", {}).get("waiting", {}).get("reason")
if reason in ("ErrImagePull", "ImagePullBackOff"):
pull_errors.add(reason)
else:
assert reason in (None, "ContainerCreating"), (name, first_status(name))
assert time.monotonic() < deadline, (name, p["status"])
time.sleep(3)
def dump(title: str, node: QemuMachine, command: str) -> None:
print(f"--- {title}")
print(node.execute(command)[1])
def diagnose_pull() -> None:
for node in (main, joiner):
dump(f"{node.name}: containerd config", node, "cat /var/lib/rancher/k3s/agent/etc/containerd/config.toml")
dump(f"{node.name}: registries", node, "cat /etc/rancher/k3s/registries.yaml; ls /var/lib/rancher/k3s/agent/etc/containerd/certs.d/ 2>&1")
dump(f"{node.name}: images", node, "k3s ctr images ls -q")
dump(f"{node.name}: content", node, "k3s ctr content ls | head -50")
dump("main: pod events", main, "kubectl get events --sort-by=.lastTimestamp | tail -30")
dump("joiner: pull through its own mirror", joiner, "curl -sk -o /dev/null -w '%{http_code}' https://127.0.0.1:6443/v2/ ; echo; journalctl -u k3s --no-pager -n 60 | grep -i -E 'spegel|registry|pull' | tail -30")
with subtest("the main node is Ready and holds the probe image"):
main.succeed(f"install -d -m 0755 {LEAF_DIR}")
wait_node_ready(main, timeout=300)
main.wait_until_succeeds(f"k3s ctr images ls -q | grep -qxF '{containerd_ref(PROBE_REF)}'", timeout=120)
joiner.start()
with subtest("the store is initialised, unsealed and bootstrapped"):
main.wait_until_succeeds('[ "$(bao status >/dev/null 2>&1; echo $?)" = 2 ]', timeout=900)
main.succeed(f"umask 077 && bao operator init -key-shares=1 -key-threshold=1 -format=json > {INIT}")
unseal_bao(main, INIT)
main.succeed(
"set -o pipefail; "
f'export BAO_TOKEN="$(jq -r .root_token {INIT})"; '
"bao policy write bao-bootstrap /etc/hyperhive/bao-bootstrap-policy.hcl; "
"bao token create -policy=bao-bootstrap -ttl=24h -orphan -display-name=bao-bootstrap -field=token "
"| install -D -m 0600 /dev/stdin /var/lib/swarm-bao-bootstrap/grant.token; "
"unset BAO_TOKEN; "
"systemctl restart swarm-bao-granter-role"
)
main.wait_until_succeeds(
"journalctl -u swarm-bao-granter-role --no-pager | grep -F 'Uploaded policy: bao-granter'",
timeout=300,
)
with subtest("the granting units have written the hives' policies and cert-auth roles"):
main.succeed("systemctl reset-failed 'swarm-bao-*-policy.service' swarm-bao-agent-pki.service || true")
main.succeed("systemctl restart --no-block 'swarm-bao-*-policy.service' swarm-bao-agent-pki.service")
settle('[ "$(systemctl is-active swarm-bao-agent-pki.service)" = active ]', 900, ["swarm-bao-agent-pki.service"])
# Under the shamir seal the PKI unit leaves a restart of the store to the
# operator when its listener's client CA changed.
if main.execute("journalctl -u swarm-bao-agent-pki --no-pager | grep -F 'restart openbao.service'")[0] == 0:
main.succeed("systemctl --machine=swarm-bao restart openbao.service")
main.wait_until_succeeds('[ "$(bao status >/dev/null 2>&1; echo $?)" = 2 ]', timeout=900)
unseal_bao(main, INIT)
for hive in ["h1", "h2"]:
settle(
f"systemctl restart swarm-bao-hive-leaf-policy.service; "
f'BAO_TOKEN="$(jq -r .root_token {INIT})" bao read auth/cert/certs/swarm-hive-leaf-{hive}',
600,
["swarm-bao-hive-leaf-policy.service"],
)
with subtest("the main node publishes the token k3s keeps, under its hive's identity"):
sign("swarm-bao-hive-leaf-h1", "h1")
sign("swarm-bao-hive-leaf-h2", "h2")
main.succeed("systemctl reset-failed k3s-join-token-publish.service || true; systemctl restart k3s-join-token-publish.service")
stored = as_root(f"bao kv get -mount=secret -field=value {TOKEN_LEAF}").strip()
assert hashlib.sha256(stored.encode()).hexdigest() == digest(main, SERVER_TOKEN), "the store's token is not k3s's"
with subtest("the joining machine reads the same token under its own identity, and k3s joins"):
main.succeed(f"cp {PKI}/ca.pem {LEAF_DIR}/ca.pem")
for name in ["ca.pem", "h2.pem", "h2-key.pem"]:
ship(name)
joiner.succeed("systemctl reset-failed k3s-join-token.service || true; systemctl restart k3s-join-token.service")
assert digest(joiner, JOIN_TOKEN) == digest(main, SERVER_TOKEN), "the joining machine holds another token"
assert joiner.succeed(f"stat -c %a {JOIN_TOKEN}").strip() == "400"
joiner.succeed("systemctl restart k3s.service")
main.wait_until_succeeds(
"kubectl get node joiner -o jsonpath='{.status.conditions[?(@.type==\"Ready\")].status}' | grep -qx True",
timeout=600,
)
with subtest("the main node carries the pin labels and the joined node none"):
main_labels = node_labels("main")
joined_labels = node_labels("joiner")
for label in [STATE_LABEL, ENTRY_LABEL, LB_LABEL]:
assert main_labels.get(label) == "true", (label, main_labels)
pinned = [k for k in joined_labels if k.startswith("hyperhive.darkest.space/") or k == LB_LABEL]
assert pinned == [], pinned
with subtest("the node-to-node ports are open to the joining machine's address only"):
rules = main.succeed("iptables -S nixos-fw").splitlines()
for port, proto in [("6443", "tcp"), ("10250", "tcp"), (FLANNEL_PORT, "udp"), ("5001", "tcp")]:
matching = [r for r in rules if f"--dport {port} " in r and f"-p {proto} " in r]
assert matching, (port, rules)
assert all(f"-s {JOINER_IP}/32" in r for r in matching), (port, matching)
assert not [r for r in rules if "--dport 8472" in r], rules
joiner_rules = joiner.succeed("iptables -S nixos-fw").splitlines()
assert [r for r in joiner_rules if f"--dport {FLANNEL_PORT} " in r and f"-s {MAIN_IP}/32" in r], joiner_rules
assert not [r for r in joiner_rules if "--dport 8472" in r], joiner_rules
with subtest("a pod with the poller's state selector runs on the main node"):
main.succeed("kubectl apply -f /etc/k8s-join/pod-stateful.json")
wait_pod(main, "stateful", phase="Running", ready=True, timeout=180)
assert pod(main, "stateful")["spec"]["nodeName"] == "main"
with subtest("a pod forced onto the joining machine pulls its image from the main node and runs"):
containerd_name = containerd_ref(PROBE_REF)
assert HOST in containerd_name, containerd_name
main.succeed(f"k3s ctr images ls -q | grep -qxF '{containerd_name}'")
assert joiner.execute(f"k3s ctr images ls -q | grep -qxF '{containerd_name}'")[0] != 0, "the machine held the image already"
main.succeed("kubectl apply -f /etc/k8s-join/pod-on-joiner.json")
try:
wait_running("on-joiner", 300)
except AssertionError:
diagnose_pull()
print(main.execute("kubectl get pods -o wide; kubectl logs net-main")[1])
raise
assert pod(main, "on-joiner")["spec"]["nodeName"] == "joiner"
joiner.succeed(f"k3s ctr images ls -q | grep -qxF '{containerd_name}'")
events = kube(main, "get events --field-selector involvedObject.name=on-joiner -o json")
assert any(e["reason"] == "Pulled" for e in json.loads(events)["items"]), events
def wg_transfer(node: QemuMachine, dev: str) -> tuple[int, int]:
"""Bytes received and sent over the device's only peer."""
fields = node.succeed(f"wg show {dev} transfer").split()
assert len(fields) == 3, fields
return int(fields[1]), int(fields[2])
with subtest("the pod network is flannel's WireGuard tunnel, each node holds the other's key, and VXLAN is gone"):
keys = {}
for node in [main, joiner]:
assert "wireguard" in node.succeed("ip -d link show flannel-wg")
assert node.succeed("wg show flannel-wg listen-port").strip() == FLANNEL_PORT
node.fail("ip link show flannel.1")
assert node.succeed("ss -H -lun 'sport = :8472'").strip() == "", "something listens on UDP 8472"
assert "-i flannel-wg " in node.succeed("iptables -S nixos-fw")
keys[node.name] = node.succeed("wg show flannel-wg public-key").strip()
assert keys["main"] != keys["joiner"], keys
assert main.succeed("wg show flannel-wg peers").split() == [keys["joiner"]]
assert joiner.succeed("wg show flannel-wg peers").split() == [keys["main"]]
# The endpoint is the address the nodes reach each other on, not the
# default route's: the test machines' default route is a private network
# of their own that reaches no peer.
for node, peer_key, peer_ip in [(main, keys["joiner"], JOINER_IP), (joiner, keys["main"], MAIN_IP)]:
endpoints = dict(l.split() for l in node.succeed("wg show flannel-wg endpoints").splitlines())
assert endpoints == {peer_key: f"{peer_ip}:{FLANNEL_PORT}"}, endpoints
with subtest("a pod on the joining machine fetches a page from a pod on the main node, through the tunnel"):
main.succeed("kubectl apply -f /etc/k8s-join/pod-net-main.json -f /etc/k8s-join/pod-net-joiner.json")
wait_pod(main, "net-main", phase="Running", ready=True, timeout=180)
wait_pod(main, "net-joiner", phase="Running", ready=True, timeout=180)
assert pod(main, "net-main")["spec"]["nodeName"] == "main"
assert pod(main, "net-joiner")["spec"]["nodeName"] == "joiner"
target = pod(main, "net-main")["status"]["podIP"]
url = f"http://{target}:${toString netPort}/"
# The server answers inside its own pod: the control that a failure below
# is the network's.
main.wait_until_succeeds("kubectl exec net-main -- wget -qO- -T 5 http://127.0.0.1:${toString netPort}/ | grep -qx ${netPage}", timeout=60)
before = wg_transfer(joiner, "flannel-wg")
try:
main.wait_until_succeeds(f"kubectl exec net-joiner -- wget -qO- -T 5 {url} | grep -qx ${netPage}", timeout=120)
except Exception:
for node in [main, joiner]:
print(f"--- {node.name}")
print(node.execute("wg show flannel-wg; ip -4 route; ip -s link show flannel-wg; iptables -S FORWARD; iptables -S nixos-fw")[1])
print(main.execute("kubectl get pods -o wide; kubectl logs net-main")[1])
raise
after = wg_transfer(joiner, "flannel-wg")
assert after[0] > before[0] and after[1] > before[1], (before, after)
for node in [main, joiner]:
stamps = [int(s) for s in node.succeed("wg show flannel-wg latest-handshakes").split()[1::2]]
assert stamps and all(s > 0 for s in stamps), stamps
with subtest("a peer with a key of its own, sending from the main node's address, gets no handshake and no answer"):
victim = pod(main, "net-joiner")["status"]["podIP"]
rogue_pub = main.succeed("wg genkey | tee /root/rogue.key | wg pubkey").strip()
assert rogue_pub not in keys.values()
main.succeed(
"ip link add rogue type wireguard && "
f"wg set rogue private-key /root/rogue.key listen-port 51999 peer {keys['joiner']} "
f"endpoint {JOINER_IP}:{FLANNEL_PORT} allowed-ips {victim}/32 && "
"ip addr add 10.99.0.1/32 dev rogue && ip link set rogue up && "
f"ip route add {victim}/32 dev rogue"
)
status, _ = main.execute(f"ping -I rogue -c 5 -W 2 {victim}")
assert status != 0, "a peer without a listed key got an answer"
received, sent = wg_transfer(main, "rogue")
assert sent > 0, "the control: the rogue peer sent its handshake"
assert received == 0, received
assert main.succeed("wg show rogue latest-handshakes").split()[1] == "0"
assert rogue_pub not in joiner.succeed("wg show flannel-wg peers")
main.succeed("ip link del rogue")
with subtest("an image no node holds fails to pull, naming the images' host and not docker.io"):
main.succeed("kubectl apply -f /etc/k8s-join/pod-missing.json")
main.wait_until_succeeds(
"kubectl get pod missing -o json | jq -e "
"'.status.containerStatuses[0].state.waiting.reason | IN(\"ErrImagePull\", \"ImagePullBackOff\")'",
timeout=300,
)
message = first_status("missing")["state"]["waiting"].get("message", "")
events = kube(main, "get events --field-selector involvedObject.name=missing -o json")
text = message + events
assert HOST in text, text
assert "docker.io" not in text, text
'';
}