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

371 lines
15 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;
# - 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";
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.ci-metrics.runtime = "k8s";
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 ];
environment.systemPackages = [
pkgs.kubectl
pkgs.jq
pkgs.openssl
];
environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml";
environment.etc = {
"k8s-join/probe-ref".text = probeRef;
"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"; }
);
};
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;
}
];
environment.systemPackages = [ pkgs.jq ];
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}"
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)
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]
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"), ("8472", "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)
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")
wait_pod(main, "on-joiner", phase="Running", ready=True, timeout=300)
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
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
'';
}