351 lines
16 KiB
Nix
351 lines
16 KiB
Nix
# `vmTests.<system>.k8s-node`: a host with `services.hyperhive.deploy.k8s.enable`
|
|
# (../host-modules/k8s/node.nix) boots a single-node k3s. The node is the
|
|
# module's own configuration, not a hand-written one, and its one in-cluster
|
|
# service is the CI run poller, whose image the module loads. The script
|
|
# asserts:
|
|
#
|
|
# - the node is Ready within 300 s of boot, and containerd lists every image
|
|
# the module loads (`system.build.k8sImages`);
|
|
# - the cluster encrypts its Secrets, runs CoreDNS, and runs neither traefik
|
|
# nor metrics-server;
|
|
# - the cluster holds no hyperhive workload: its namespace does not exist and
|
|
# no pod runs one of the images;
|
|
# - the node takes pod and service addresses from the module's ranges and the
|
|
# hive bridge keeps its own, so the two do not share a subnet;
|
|
# - the firewall trusts `cni0`, and still guards the other interfaces;
|
|
# - a pod resolves the swarm's bao name and the hive collector's name to the
|
|
# hive bridge's address, completes TLS to a listener there that requires a
|
|
# client certificate (refused without one), and POSTs one OTLP record to
|
|
# another that receives it. The first listener stands in for the store's
|
|
# passthrough; the second is the collector as the node module configures it,
|
|
# writing to a file;
|
|
# - the collector runs as a static user that reads a pod's log file under
|
|
# /var/log/pods and nothing else, a pod's WARN line in hive-log's text format
|
|
# reaches the collector's output with WARN severity under the container's
|
|
# name without its `swarm-` prefix, and so does a metric a pod pushes.
|
|
#
|
|
# The poller's own host unit and its trust bundle unit stay as they are on the
|
|
# host and fail here, which nothing in this test reads.
|
|
{ pkgs, self }:
|
|
let
|
|
inherit (pkgs) lib;
|
|
|
|
# What the node's configuration and the script agree on. The collector's name
|
|
# is a literal of `services.hyperhive.otel.collector.host`.
|
|
bridgeIp = "10.42.0.1";
|
|
baoName = "bao.t.local";
|
|
baoPort = 8200;
|
|
collectorName = "hive-collector.hive";
|
|
collectorOut = "/var/lib/opentelemetry-collector/out.json";
|
|
collectorUser = "opentelemetry-collector";
|
|
|
|
# The pod the script execs into: a shell, `nslookup` and `curl`, no more.
|
|
probeImage = pkgs.dockerTools.buildLayeredImage {
|
|
name = "k8s-probe";
|
|
tag = "test";
|
|
contents = [
|
|
pkgs.busybox
|
|
pkgs.curl
|
|
];
|
|
};
|
|
|
|
in
|
|
pkgs.testers.runNixOSTest {
|
|
name = "k8s-node";
|
|
|
|
# Under the 20 min budget for one dispatched run; the runner's job bound is 1 h.
|
|
globalTimeout = 1500;
|
|
|
|
nodes.machine =
|
|
{ config, ... }:
|
|
{
|
|
imports = [ self.nixosModules.default ];
|
|
|
|
services.hyperhive = {
|
|
deploy.k8s.enable = true;
|
|
network.enable = true;
|
|
deploy.ci-metrics.enable = true;
|
|
deploy.bao.ciMetricsClientCertFile = "/var/lib/ci-metrics/client.pem";
|
|
deploy.bao.ciMetricsClientKeyFile = "/var/lib/ci-metrics/client-key.pem";
|
|
deploy.hive-controller.hiveName = "h1";
|
|
swarm.domain = "t.local";
|
|
network.bridgeIp = bridgeIp;
|
|
swarm.bao.domain = baoName;
|
|
swarm.bao.port = baoPort;
|
|
swarm.hives.h1.domain = "h1.t.local";
|
|
};
|
|
system.stateVersion = "25.11";
|
|
|
|
environment.systemPackages = [
|
|
pkgs.kubectl
|
|
pkgs.curl
|
|
];
|
|
environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml";
|
|
|
|
# What the standing pod reaches: the names the node's CoreDNS answers
|
|
# are `gateway.localNames` plus the hive domain, and a pod gets the
|
|
# hive bridge's address for each.
|
|
services.hyperhive.gateway.localNames = [
|
|
baoName
|
|
config.services.hyperhive.otel.collector.host
|
|
];
|
|
services.k3s.images = [ probeImage ];
|
|
|
|
# A TLS listener that requires a client certificate where the store's
|
|
# passthrough listens, on a throwaway CA the unit mints for itself.
|
|
systemd.services.bao-standin = {
|
|
wantedBy = [ "multi-user.target" ];
|
|
path = [ pkgs.openssl ];
|
|
serviceConfig = {
|
|
StateDirectory = "bao-standin";
|
|
WorkingDirectory = "/var/lib/bao-standin";
|
|
Restart = "always";
|
|
RestartSec = 2;
|
|
};
|
|
script = ''
|
|
set -eu
|
|
if [ ! -f client.pem ]; then
|
|
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
|
|
-keyout ca.key -out ca.pem -subj /CN=standin-ca -days 2
|
|
for n in server client; do
|
|
openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
|
|
-keyout $n.key -out $n.csr -subj /CN=$n
|
|
done
|
|
echo 'subjectAltName=DNS:${baoName}' > server.ext
|
|
openssl x509 -req -in server.csr -CA ca.pem -CAkey ca.key -CAcreateserial \
|
|
-out server.pem -days 2 -extfile server.ext
|
|
openssl x509 -req -in client.csr -CA ca.pem -CAkey ca.key -CAcreateserial \
|
|
-out client.pem -days 2
|
|
fi
|
|
exec openssl s_server -accept ${bridgeIp}:${toString baoPort} \
|
|
-cert server.pem -key server.key -CAfile ca.pem -Verify 1 -verify_return_error -www
|
|
'';
|
|
};
|
|
|
|
# The hive collector as far as the pods go: its receiver on the bridge,
|
|
# the cursor store the pod logs receiver names, and a file where the real
|
|
# one has the swarm's collector. The pod logs pipeline, the collector's
|
|
# user and its access to /var/log/pods come from the node module.
|
|
services.opentelemetry-collector = {
|
|
enable = true;
|
|
package = pkgs.opentelemetry-collector-contrib;
|
|
settings = {
|
|
extensions.file_storage = {
|
|
directory = "/var/lib/opentelemetry-collector";
|
|
create_directory = true;
|
|
};
|
|
receivers.otlp.protocols.http.endpoint = "${bridgeIp}:4318";
|
|
exporters.file.path = collectorOut;
|
|
service.extensions = [ "file_storage" ];
|
|
service.pipelines.logs = {
|
|
receivers = [ "otlp" ];
|
|
exporters = [ "file" ];
|
|
};
|
|
service.pipelines.metrics = {
|
|
receivers = [ "otlp" ];
|
|
exporters = [ "file" ];
|
|
};
|
|
};
|
|
};
|
|
services.hyperhive.deploy.k8s.podLogsExporters = [ "file" ];
|
|
# The receiver binds the bridge address, which can come up after the
|
|
# unit's first start.
|
|
systemd.services.opentelemetry-collector = {
|
|
startLimitIntervalSec = 0;
|
|
serviceConfig.RestartSec = 2;
|
|
};
|
|
|
|
# The references `lib/k3s.py`'s `wait_images` looks for.
|
|
environment.etc."k3s-node/images".text = lib.concatMapStrings (
|
|
i: "${i.imageName}:${i.imageTag}\n"
|
|
) config.system.build.k8sImages;
|
|
|
|
virtualisation = {
|
|
memorySize = 4096;
|
|
cores = 4;
|
|
diskSize = 8192;
|
|
};
|
|
};
|
|
|
|
testScript = builtins.readFile ./lib/k3s.py + ''
|
|
import shlex
|
|
|
|
with subtest("the node is Ready and holds every image the module loads"):
|
|
wait_node_ready(machine, timeout=300)
|
|
refs = image_refs(machine)
|
|
assert refs == ["hyperhive/swarm-ci-metrics:" + refs[0].split(":", 1)[1]], refs
|
|
wait_images(machine)
|
|
|
|
with subtest("the cluster encrypts its secrets and runs CoreDNS but neither traefik nor metrics-server"):
|
|
status = machine.succeed("k3s secrets-encrypt status")
|
|
assert "Encryption Status: Enabled" in status, status
|
|
machine.wait_until_succeeds(
|
|
"kubectl -n kube-system rollout status deployment/coredns --timeout=5s", timeout=120
|
|
)
|
|
deployments = kube(machine, "-n kube-system get deployments -o name").split()
|
|
assert "deployment.apps/coredns" in deployments, deployments
|
|
for name in ["traefik", "metrics-server"]:
|
|
assert f"deployment.apps/{name}" not in deployments, deployments
|
|
|
|
with subtest("the cluster holds no hyperhive workload"):
|
|
machine.fail("kubectl get namespace hyperhive")
|
|
pods = json.loads(kube(machine, "get pods -A -o json"))["items"]
|
|
images = [c["image"] for p in pods for c in p["spec"]["containers"]]
|
|
assert images, "no pod runs: the lookup finds nothing"
|
|
assert not [i for i in images if "hyperhive/" in i], images
|
|
|
|
with subtest("the pods and services use the module's ranges, apart from the hive bridge"):
|
|
pod_cidr = kube(machine, "get node -o jsonpath='{.items[0].spec.podCIDR}'")
|
|
assert pod_cidr == "10.200.0.0/24", pod_cidr
|
|
svc_ip = kube(machine, "get service kubernetes -o jsonpath='{.spec.clusterIP}'")
|
|
assert svc_ip == "10.201.0.1", svc_ip
|
|
dns_ip = kube(machine, "-n kube-system get service kube-dns -o jsonpath='{.spec.clusterIP}'")
|
|
assert dns_ip == "10.201.0.10", dns_ip
|
|
cni = machine.wait_until_succeeds("ip -4 -o addr show dev cni0", timeout=60)
|
|
assert "10.200.0.1/24" in cni, cni
|
|
bridge = machine.succeed("ip -4 -o addr show dev hive-br0")
|
|
assert "${bridgeIp}/24" in bridge, bridge
|
|
assert "${bridgeIp}" not in cni, cni
|
|
|
|
with subtest("the firewall trusts the pod network and guards the other interfaces"):
|
|
rules = machine.succeed("iptables -S nixos-fw")
|
|
assert "-i cni0 " in rules, rules
|
|
assert "-i flannel.1 " in rules, rules
|
|
assert "-i lo " in rules, rules
|
|
assert "-i eth0 " not in rules, rules
|
|
|
|
with subtest("a pod resolves the swarm names to the hive bridge and reaches the listeners there"):
|
|
bridge_ip = "${bridgeIp}"
|
|
bao = "${baoName}"
|
|
collector = "${collectorName}"
|
|
for unit in ["bao-standin", "opentelemetry-collector"]:
|
|
machine.wait_for_unit(unit)
|
|
machine.wait_until_succeeds("test -f /var/lib/bao-standin/client.pem")
|
|
kube(
|
|
machine,
|
|
"create configmap probe-tls --from-file=/var/lib/bao-standin/ca.pem "
|
|
"--from-file=/var/lib/bao-standin/client.pem --from-file=/var/lib/bao-standin/client.key",
|
|
)
|
|
spec = {
|
|
"apiVersion": "v1",
|
|
"kind": "Pod",
|
|
"metadata": {"name": "probe"},
|
|
"spec": {
|
|
"containers": [
|
|
{
|
|
"name": "probe",
|
|
"image": "k8s-probe:test",
|
|
"imagePullPolicy": "Never",
|
|
"command": ["sleep", "3600"],
|
|
"volumeMounts": [{"name": "tls", "mountPath": "/tls"}],
|
|
}
|
|
],
|
|
"volumes": [{"name": "tls", "configMap": {"name": "probe-tls"}}],
|
|
},
|
|
}
|
|
machine.succeed(f"echo {shlex.quote(json.dumps(spec))} | kubectl apply -f -")
|
|
wait_pod(machine, "probe", phase="Running", ready=True, timeout=180)
|
|
|
|
def probe(cmd: str) -> tuple[int, str]:
|
|
return machine.execute(f"kubectl exec probe -- sh -c {shlex.quote(cmd + ' 2>&1')}")
|
|
|
|
# The names the table holds answer with the bridge's address. Cluster
|
|
# names still answer, and a name outside the table does not get it.
|
|
for name in [bao, collector]:
|
|
machine.wait_until_succeeds(
|
|
f"kubectl exec probe -- nslookup {name} | grep -F {bridge_ip}", timeout=120
|
|
)
|
|
machine.succeed(
|
|
"kubectl exec probe -- nslookup kubernetes.default.svc.cluster.local "
|
|
"| grep -E '10[.]201[.]0[.]1([^0-9]|$)'"
|
|
)
|
|
_, unlisted = probe("timeout 30 nslookup unlisted.t.local")
|
|
assert bridge_ip not in unlisted, unlisted
|
|
|
|
# TLS completes on the name, with the client certificate, and is
|
|
# refused without it.
|
|
curl_tls = f"curl -sS -m 10 --cacert /tls/ca.pem https://{bao}:${toString baoPort}/"
|
|
status, out = probe(f"{curl_tls} --cert /tls/client.pem --key /tls/client.key")
|
|
assert status == 0 and "Cipher" in out, (status, out)
|
|
status, out = probe(curl_tls)
|
|
assert status != 0 and "Cipher" not in out and "certificate" in out.lower(), (status, out)
|
|
|
|
# One OTLP record arrives.
|
|
status, out = probe(
|
|
"curl -sS -m 10 -X POST -H 'Content-Type: application/json' "
|
|
"-d '{\"resourceLogs\":[{\"scopeLogs\":[{\"logRecords\":[{\"body\":{\"stringValue\":\"from-the-pod\"}}]}]}]}' "
|
|
f"http://{collector}:4318/v1/logs"
|
|
)
|
|
assert status == 0, (status, out)
|
|
machine.wait_until_succeeds("grep -F from-the-pod ${collectorOut}", timeout=60)
|
|
|
|
with subtest("the collector runs as a static user with an ACL on the pod logs and nowhere else"):
|
|
show = machine.succeed("systemctl show -p User -p DynamicUser opentelemetry-collector")
|
|
assert "User=${collectorUser}" in show and "DynamicUser=no" in show, show
|
|
pods_acl = machine.succeed("getfacl -p /var/log/pods")
|
|
assert "user:${collectorUser}:r-x" in pods_acl, pods_acl
|
|
assert "default:user:${collectorUser}:r-x" in pods_acl, pods_acl
|
|
assert "${collectorUser}" not in machine.succeed("getfacl -p /var/log")
|
|
|
|
with subtest("a pod's log lines reach the collector's output with their severity and the container's name"):
|
|
logger = {
|
|
"apiVersion": "v1",
|
|
"kind": "Pod",
|
|
"metadata": {"name": "logprobe"},
|
|
"spec": {
|
|
"containers": [
|
|
{
|
|
"name": "swarm-logprobe",
|
|
"image": "k8s-probe:test",
|
|
"imagePullPolicy": "Never",
|
|
"command": [
|
|
"sh",
|
|
"-c",
|
|
"echo '2026-11-21T10:00:00.000000Z WARN logprobe: warn-line-from-pod'; "
|
|
"echo '2026-11-21T10:00:01.000000Z INFO logprobe: info-line-from-pod'; "
|
|
"sleep 3600",
|
|
],
|
|
}
|
|
],
|
|
},
|
|
}
|
|
machine.succeed(f"echo {shlex.quote(json.dumps(logger))} | kubectl apply -f -")
|
|
wait_pod(machine, "logprobe", phase="Running", ready=True, timeout=180)
|
|
|
|
# The file kubelet's runtime wrote, its owner and mode as containerd
|
|
# made them, and the collector's user reading it through the ACL.
|
|
log_file = machine.succeed("ls /var/log/pods/default_logprobe_*/swarm-logprobe/0.log").strip()
|
|
print(machine.succeed(f"stat -c '%U:%G %a' {log_file}"))
|
|
status, out = machine.execute(f"runuser -u ${collectorUser} -- cat {log_file}")
|
|
assert status == 0 and "warn-line-from-pod" in out, (status, out)
|
|
status, out = machine.execute("runuser -u ${collectorUser} -- cat /etc/shadow")
|
|
assert status != 0, out
|
|
|
|
machine.wait_until_succeeds("grep -F info-line-from-pod ${collectorOut}", timeout=90)
|
|
records = []
|
|
for line in machine.succeed("cat ${collectorOut}").splitlines():
|
|
for rl in json.loads(line).get("resourceLogs", []):
|
|
res = {a["key"]: a["value"].get("stringValue") for a in rl["resource"].get("attributes", [])}
|
|
for sl in rl["scopeLogs"]:
|
|
records += [(res, r) for r in sl["logRecords"]]
|
|
by_body = {r["body"].get("stringValue", ""): (res, r) for res, r in records}
|
|
warn_res, warn = next(v for k, v in by_body.items() if "warn-line-from-pod" in k)
|
|
info_res, info = next(v for k, v in by_body.items() if "info-line-from-pod" in k)
|
|
assert (warn["severityText"], warn["severityNumber"]) == ("WARN", 13), warn
|
|
assert (info["severityText"], info["severityNumber"]) == ("INFO", 9), info
|
|
for res in [warn_res, info_res]:
|
|
assert res["service.name"] == "logprobe", res
|
|
assert res["k8s.namespace.name"] == "default", res
|
|
assert res["k8s.container.name"] == "swarm-logprobe", res
|
|
|
|
with subtest("a metric a pod pushes to the collector arrives"):
|
|
status, out = probe(
|
|
"curl -sS -m 10 -X POST -H 'Content-Type: application/json' "
|
|
"-d '{\"resourceMetrics\":[{\"scopeMetrics\":[{\"metrics\":[{\"name\":\"probe.gauge\","
|
|
"\"gauge\":{\"dataPoints\":[{\"asDouble\":1,\"timeUnixNano\":\"1\"}]}}]}]}]}' "
|
|
f"http://{collector}:4318/v1/metrics"
|
|
)
|
|
assert status == 0, (status, out)
|
|
machine.wait_until_succeeds("grep -F probe.gauge ${collectorOut}", timeout=60)
|
|
'';
|
|
}
|