Watch
0
0
Fork
You've already forked hyperhive
0

require k8s: swarm services with a pod run in the cluster only

This commit is contained in:
atlas 2026-11-26 00:36:09 +01:00 • committed by mara
commit 052b559196
5 changed files with 1044 additions and 3125 deletions

View file

@ -95,7 +95,7 @@ def create_agent(body):
# the responder run in the container; the units that fetch its keys and
# certificate run on the host.
diagnose(["nats.service", "swarm-nats-auth.service"], "swarm-nats")
diagnose(["swarm-bao-nats-tls.service", "swarm-bao-nats-callout-xkey.service"])
diagnose(["swarm-bao-nats-tls.service"])
raise Exception(
f"the controller refused to create {body['name']}: HTTP {out}: {machine.succeed('cat /root/create.out')}"
)

View file

@ -1,27 +1,22 @@
# `vmTests.<system>.k8s-controller-switch`: swarm-controller moves between its
# host unit and the host's cluster (`services.hyperhive.deploy.swarm-controller.runtime`),
# against the real secret store, a real queue and the real TCP listener. The
# host boots with the controller on the host; the `k8s` specialisation has it in
# the cluster, and `k8s-rev` is that with another hyperhive rev. The script
# switches to the cluster, to the new rev, and back, and asserts that:
# `vmTests.<system>.k8s-controller`: swarm-controller runs as a pod in the host's
# cluster, against the real secret store, a real queue and the real TCP listener.
# `k8s-rev` is the configuration with another hyperhive rev. The script asserts
# that:
#
# - exactly one controller runs at each step: by the order of the switch's own
# timestamps and by a sampler that looks every 200 ms;
# - the host has no unit for the controller, its listener leaf or a prune, and the
# controller runs once, as a pod;
# - the pod is Ready on the health listener, which depends on its store login
# and its queue connection; its listener's leaf is the one its init container
# issued from the store with its ServiceAccount token, valid as the listener's
# name against the hive's root, and a handshake with no client leaf is refused;
# - the gateway's own controller location, rendered by the module for each
# runtime and run here in a nginx of its own, reaches the controller: on the
# host by name, in the cluster by the Service's name, which the host's
# resolver answers through CoreDNS, verifying the leaf as the listener's
# name; the controller answers an unsigned webhook 401 both times;
# - the gateway's own controller location, rendered by the module and run here
# in a nginx of its own, reaches the controller by the Service's name, which
# the host's resolver answers through CoreDNS, verifying the leaf as the
# listener's name; the controller answers an unsigned webhook 401;
# - the Service is a ClusterIP the host dials and a pod can't (no `hostPort`);
# Pod Security `restricted` refuses a host port, a capability or privilege;
# - a changed hyperhive rev rolls the Deployment; the pod's state directory is
# an emptyDir, with no claim and no gate;
# - the switch back leaves no pod, Deployment, Service, NetworkPolicy or
# AddOn, and the host unit starts after the prune unit.
# an emptyDir, with no claim and no gate.
#
# The queue is a plain nats-server with TLS and one stub is the token endpoint
# and the forge; they replace services that stay host-run and unchanged. The
@ -51,7 +46,6 @@ let
controllerSecretLeaf = "swarm/controller/swarm-controller/oidc/client";
revA = lib.fixedWidthString 40 "a" "";
revB = lib.fixedWidthString 40 "b" "";
overlapLog = "/var/log/overlap.log";
tokenLog = "/var/log/stub-token.log";
# The identity provider and the forge, by name, on one listener. The token
@ -99,19 +93,7 @@ let
}
'';
# Looks every 200 ms at whether the controller's host unit runs and how many
# pods the cluster holds for it, a terminating pod included.
sampler = pkgs.writeShellScript "overlap-sampler" ''
while true; do
state="$(systemctl is-active ${hostUnit} || true)"
pods="$(kubectl --namespace ${namespace} get pods --selector app.kubernetes.io/name=${service} --no-headers 2>/dev/null | wc -l)"
echo "$(date +%s.%N) ${service} host=$state pods=$pods" >> ${overlapLog}
sleep 0.2
done
'';
# One nginx per runtime with the controller's two locations as the module
# renders them for that runtime: the upstream, the client leaf and the
# One nginx with the controller's two locations as the module renders them: the upstream, the client leaf and the
# verification of the listener's name. Nothing else of the vhost, which
# answers through a login service.
gatewayConf =
@ -143,10 +125,10 @@ let
};
in
pkgs.testers.runNixOSTest {
name = "k8s-controller-switch";
name = "k8s-controller";
# The store takes a few minutes to open its raft storage, and the script
# switches the configuration three times. Under the 1 h job bound with room
# switches the configuration once. Under the 1 h job bound with room
# for the build before the test starts.
globalTimeout = 2400;
@ -172,10 +154,6 @@ pkgs.testers.runNixOSTest {
swarm.forge.domain = forgeName;
swarm.bao.domain = baoName;
swarm.bao.port = baoPort;
swarm.controller.tcp = {
enable = true;
domain = controllerName;
};
swarm.hives.h1.domain = "h1.t.local";
# The queue, the identity provider and the forge are host-run: their
# names go to the bridge for the cluster's pods, as the hive's own do.
@ -187,15 +165,12 @@ pkgs.testers.runNixOSTest {
};
system.stateVersion = "25.11";
specialisation.k8s.configuration.services.hyperhive.deploy.swarm-controller.runtime = "k8s";
specialisation.k8s-rev.configuration.services.hyperhive.deploy = {
swarm-controller.runtime = "k8s";
hive-controller.hyperhiveRev = lib.mkForce revB;
};
specialisation.k8s-rev.configuration.services.hyperhive.deploy.hive-controller.hyperhiveRev =
lib.mkForce revB;
# The store's TLS passthrough is a stream server of the host's nginx,
# which needs certificates this host does not mint, so a second nginx
# carries the passthrough alone, as `k8s-runtime-switch` does.
# carries the passthrough alone, as `k8s-services` does.
services.nginx.enable = lib.mkForce false;
users.groups.nginx = { };
networking.hosts = {
@ -290,16 +265,6 @@ pkgs.testers.runNixOSTest {
};
};
systemd.services.overlap-sampler = {
path = [
pkgs.kubectl
pkgs.coreutils
pkgs.systemd
];
environment.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml";
serviceConfig.ExecStart = sampler;
};
environment.systemPackages = [
pkgs.kubectl
pkgs.curl
@ -340,7 +305,6 @@ pkgs.testers.runNixOSTest {
PORT = ${toString controllerPort}
BRIDGE = "${bridgeIp}"
SERVICE_HOST = "${service}.${namespace}.svc.cluster.local"
SOCKET = "/run/swarm-controller/controller.sock"
MANIFESTS = "/var/lib/rancher/k3s/server/manifests"
SERVICES_ROOT = "${tlsDir}/swarm-services-root.pem"
GATEWAY_CERT = "${tlsDir}/controller-client.pem"
@ -374,15 +338,6 @@ pkgs.testers.runNixOSTest {
return machine.execute(f"systemctl is-active {HOST_UNIT}")[1].strip()
def stopped_at(unit: str) -> int:
return int(machine.succeed(f"date -d \"$(systemctl show -p InactiveEnterTimestamp --value {unit})\" +%s"))
def created_at_of(pod_name: str) -> int:
stamp = machine.succeed(f"kubectl -n {NS} get pod {pod_name} -o jsonpath='{{.metadata.creationTimestamp}}'")
return int(machine.succeed(f"date -d \"{stamp}\" +%s"))
def wait_pod_ready(not_uid: str = "", timeout: int = 600) -> str:
"""The name of the Ready pod of the controller that is not terminating
and has a uid other than `not_uid`."""
@ -499,45 +454,28 @@ pkgs.testers.runNixOSTest {
machine.wait_until_succeeds(
"nats --server tls://${natsName}:${toString natsPort} --tlsca ${pkiDir}/ca.pem account info", timeout=120
)
machine.succeed("systemctl start overlap-sampler.service")
with subtest("the gateway's certificates exist: the store's services root, and the gateway's client leaf for the listener"):
for unit in ["swarm-services-cert.service", "swarm-controller-gateway-client.service"]:
machine.succeed(f"systemctl reset-failed {unit} || true")
machine.succeed(f"systemctl restart --no-block {unit}")
settle(f"test -s {SERVICES_ROOT} && test -s {GATEWAY_CERT} && test -s {GATEWAY_KEY}", 600, ["swarm-services-cert.service", "swarm-controller-gateway-client.service"])
settle(f"test -s {SERVICES_ROOT} && test -s {GATEWAY_KEY} && openssl verify -CAfile {SERVICES_ROOT} -purpose sslclient {GATEWAY_CERT}", 600, ["swarm-services-cert.service", "swarm-controller-gateway-client.service"])
machine.succeed(f"openssl verify -CAfile {SERVICES_ROOT} -purpose sslclient {GATEWAY_CERT}")
with subtest("on the host, the controller runs, is ready on its socket, serves its listener and answers the gateway, and the cluster holds none of it"):
machine.succeed("systemctl reset-failed swarm-controller-tls.service || true")
machine.succeed("systemctl restart --no-block swarm-controller-tls.service")
settle(f"[ \"$(systemctl is-active {HOST_UNIT})\" = active ]", 600, [HOST_UNIT, "swarm-controller-tls.service"])
settle(f"curl -sf --unix-socket {SOCKET} http://x/readyz", 300, [HOST_UNIT])
assert machine.succeed(f"systemctl is-active {PRUNE}.service").strip() == "active"
assert pods() == [], pods()
assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml")[0] != 0
assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get service {SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get networkpolicy {SERVICE}")[0] != 0
# The controller's own listener presents the leaf the host unit issued.
settle(f"echo | openssl s_client -connect 127.0.0.1:{PORT} -servername {NAME} -CAfile {SERVICES_ROOT} -verify_hostname {NAME} -verify_return_error -cert {GATEWAY_CERT} -key {GATEWAY_KEY} 2>&1 | grep -F 'Verification: OK'", 120, [HOST_UNIT])
assert gateway("gateway.service") == 401
machine.wait_until_succeeds(f"grep -F '/api/oidc/token swarm-controller:{SECRET}' ${tokenLog}", timeout=120)
with subtest("the switch to the cluster stops the unit before it applies the pod"):
TOKENS = int(machine.succeed(f"grep -c '/api/oidc/token swarm-controller:{SECRET}' ${tokenLog}"))
out = switch("/run/booted-system/specialisation/k8s")
assert HOST_UNIT in out and "stopping the following units" in out, out
assert host_state() == "inactive", host_state()
with subtest("the controller runs as a pod only: the host has no unit for it, its listener leaf or a prune"):
# The unit is disabled, so the host cannot start it: a copy beside the pod would break the one-copy rule.
assert "ExecStart" not in machine.execute(f"systemctl cat {HOST_UNIT}")[1]
machine.fail(f"systemctl start {HOST_UNIT}")
assert host_state() == "inactive", host_state()
assert "ExecStart" not in machine.execute("systemctl cat swarm-controller-tls.service")[1]
machine.fail("systemctl start swarm-controller-tls.service")
machine.fail(f"systemctl cat {PRUNE}.service")
# The gateway's client leaf unit is the control that the lookups find a unit of the listener's that is there.
machine.succeed("systemctl cat swarm-controller-gateway-client.service")
machine.succeed(f"test -L {MANIFESTS}/{SERVICE}.yaml")
pod_name = wait_pod_ready()
assert stopped_at(HOST_UNIT) <= created_at_of(pod_name)
machine.wait_until_succeeds(f"[ \"$(grep -c '/api/oidc/token swarm-controller:{SECRET}' ${tokenLog})\" -gt {TOKENS} ]", timeout=300)
assert len(pods()) == 1, pods()
machine.wait_until_succeeds(f"grep -F '/api/oidc/token swarm-controller:{SECRET}' ${tokenLog}", timeout=300)
with subtest("the pod is Ready on its health listener, has the volumes and ports the module renders, and no Secret"):
spec = pod(machine, pod_name)["spec"]
@ -618,7 +556,7 @@ pkgs.testers.runNixOSTest {
"containers": [{
"name": "c",
"image": main["image"],
"imagePullPolicy": "Never",
"imagePullPolicy": "IfNotPresent",
"securityContext": {"allowPrivilegeEscalation": False, "capabilities": {"drop": ["ALL"]}},
}],
},
@ -659,37 +597,5 @@ pkgs.testers.runNixOSTest {
assert "${revB}" in rev, rev
assert len(pods()) == 1, pods()
with subtest("the switch back removes the Deployment, pod and AddOn before the unit starts"):
switch("/run/booted-system")
machine.wait_until_succeeds(f"[ \"$(systemctl is-active {HOST_UNIT})\" = active ]", timeout=600)
assert pods() == [], pods()
assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n kube-system get addons.k3s.cattle.io {SERVICE}")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml.pruning")[0] != 0
pruned = int(machine.succeed(f"systemctl show -p ExecMainExitTimestampMonotonic --value {PRUNE}.service"))
started = int(machine.succeed(f"systemctl show -p InactiveExitTimestampMonotonic --value {HOST_UNIT}"))
assert 0 < pruned <= started, (pruned, started)
requires = machine.succeed(f"systemctl show -p Requires --value {HOST_UNIT}")
assert f"{PRUNE}.service" in requires, requires
machine.fail(f"kubectl -n {NS} get pvc {SERVICE}-state")
settle(f"curl -sf --unix-socket {SOCKET} http://x/readyz", 300, [HOST_UNIT])
assert gateway("gateway.service") == 401
with subtest("no moment of any switch had the unit and a pod together"):
machine.succeed("systemctl stop overlap-sampler.service")
lines = machine.succeed("cat ${overlapLog}").splitlines()
host_up = {"active", "activating", "deactivating", "reloading"}
samples = [
(fields[2].removeprefix("host="), int(fields[3].removeprefix("pods=")))
for fields in (line.split() for line in lines)
if len(fields) == 4
]
both = [s for s in samples if s[0] in host_up and s[1] > 0]
assert not both, both[:5]
# The controls: the sampler saw the unit alone and a pod alone.
assert any(s[0] in host_up and s[1] == 0 for s in samples), lines[:5]
assert any(s[0] not in host_up and s[1] > 0 for s in samples), lines[:5]
print(f"{SERVICE}: {len(samples)} samples, none with both")
'';
}

View file

@ -106,7 +106,6 @@ pkgs.testers.runNixOSTest {
# 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";
};

View file

@ -1,29 +1,22 @@
# `vmTests.<system>.k8s-nats-switch`: the swarm queue and its auth callout move
# between their container and the host's cluster
# (`services.hyperhive.deploy.nats.runtime`), against the real secret store.
# The host boots with the queue in its container; the `k8s` specialisation has
# it in the cluster on the container's own JetStream store, and `k8s-open` adds
# `deploy.nats.openFirewall`. The script switches to the cluster, opens the
# port, and back, and asserts that:
# `vmTests.<system>.k8s-nats`: the swarm queue and its auth callout run as a pod in
# the host's cluster, against the real secret store, on the JetStream store
# directory the host keeps (`/var/lib/nixos-containers/swarm-nats/var/lib/nats`),
# which is a static volume. `k8s-open` adds `deploy.nats.openFirewall`. The
# script asserts that:
#
# - at most one server and one responder run at any moment of any switch (a
# sampler counts the processes every 200 ms), and the container and the pod
# never overlap;
# - the host has no container, delivery unit or prune unit for the queue, and one
# server and one responder run, as the pod;
# - the pod is Ready by its exec probe on the server's monitor, holds the leaf
# and the callout config as init containers, and has no `hostPort`: the client
# port is a LoadBalancer Service with no node port, bound by the load balancer;
# - with the egress intercept on, a client on the hive's bridge reaches the
# queue by name through the published port and not by the pod's address or
# the node's, and the responder in the pod admits the router's token;
# - the port is as closed to a host outside the node as the container's is, and
# open with `openFirewall`, where a second node dials it by name and verifies
# the name. The exporter answers the host only, by its Service's name;
# - a stream written before the pod is deleted is read after;
# - the store is the container's own directory: a key the host server wrote is
# read by the pod, and a key the pod wrote is read by the host server after
# the switch back, which hands the files back to the server's user;
# - the switch back leaves no pod, Service, NetworkPolicy or AddOn, and the
# container starts after the prune unit.
# - the port is closed to a host outside the node, and open with `openFirewall`,
# where a second node dials it by name and verifies the name. The exporter
# answers the host only, by its Service's name;
# - a stream written before the pod is deleted is read after, and the files the
# pod writes are in the host directory the volume is on.
#
# One stub is the identity provider: it introspects the test's one token as the
# notification router, whose permissions create and fill a stream. The test
@ -51,7 +44,6 @@ let
tlsDir = "/var/lib/hive-tls";
oidcLeaf = "swarm/services/${service}/oidc/client";
routerToken = "test-router-token";
overlapLog = "/var/log/overlap.log";
tokenLog = "/var/log/stub-token.log";
# The identity provider, by name. The token endpoint answers every
@ -104,22 +96,6 @@ let
server.serve_forever()
'';
# Looks every 200 ms at whether the queue's container runs, how many pods
# the cluster holds for it (a terminating one included), and how many
# servers and responders the node holds: a pod's processes are the node's.
sampler = pkgs.writeShellScript "overlap-sampler" ''
while true; do
state="$(systemctl is-active ${hostUnit} || true)"
listing="$(kubectl --namespace ${namespace} get pods --selector app.kubernetes.io/name=${service} --no-headers 2>/dev/null || true)"
pods="$(printf '%s' "$listing" | grep -c . || true)"
shown="$(printf '%s' "$listing" | awk '{print $1":"$3}' | tr '\n' ',')"
servers="$(pgrep -cx nats-server || true)"
responders="$(pgrep -cx swarm-nats-auth || true)"
echo "$(date +%s.%N) ${service} host=$state pods=$pods servers=$servers responders=$responders pods-are=''${shown:--}" >> ${overlapLog}
sleep 0.2
done
'';
# What a client sees of the queue's certificate. The server speaks first
# and upgrades to TLS on the same connection, so `openssl s_client` cannot
# dial it: this reads the server's greeting, then verifies the certificate
@ -148,7 +124,7 @@ let
'';
in
pkgs.testers.runNixOSTest {
name = "k8s-nats-switch";
name = "k8s-nats";
# The store takes a few minutes to open its raft storage, and the script
# switches the configuration three times. Under the 1 h job bound with room
@ -185,15 +161,11 @@ pkgs.testers.runNixOSTest {
};
system.stateVersion = "25.11";
specialisation.k8s.configuration.services.hyperhive.deploy.nats.runtime = "k8s";
specialisation.k8s-open.configuration.services.hyperhive.deploy.nats = {
runtime = "k8s";
openFirewall = true;
};
specialisation.k8s-open.configuration.services.hyperhive.deploy.nats.openFirewall = true;
# The store's TLS passthrough is a stream server of the host's nginx,
# which needs certificates this host does not mint, so a second nginx
# carries the passthrough alone, as `k8s-runtime-switch` does.
# carries the passthrough alone, as `k8s-services` does.
services.nginx.enable = lib.mkForce false;
networking.hosts."${bridgeIp}" = [
baoName
@ -274,19 +246,6 @@ pkgs.testers.runNixOSTest {
};
networking.firewall.allowedTCPPorts = [ controlPort ];
systemd.services.overlap-sampler = {
path = [
pkgs.kubectl
pkgs.coreutils
pkgs.gnugrep
pkgs.gawk
pkgs.procps
pkgs.systemd
];
environment.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml";
serviceConfig.ExecStart = sampler;
};
networking.interfaces.eth1.ipv4.addresses = lib.mkForce [
{
address = nodeIp;
@ -408,6 +367,15 @@ pkgs.testers.runNixOSTest {
return machine.succeed(f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o name || true").split()
def live_pods() -> list[str]:
"""The pods that are not terminating: a deleted pod whose sandbox the
runtime can't remove stays in the list."""
return machine.succeed(
f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o json "
"| jq -r '.items[] | select(.metadata.deletionTimestamp == null) | .metadata.name'"
).split()
def pod_pid(container: str) -> str:
id_ = machine.succeed(f"k3s crictl ps --name '^{container}$' --state running -q").split()[0]
return machine.succeed(f"k3s crictl inspect {id_} | jq -r .info.pid").strip()
@ -423,15 +391,6 @@ pkgs.testers.runNixOSTest {
return machine.execute(f"systemctl is-active {HOST_UNIT}")[1].strip()
def stopped_at(unit: str) -> int:
return int(machine.succeed(f"date -d \"$(systemctl show -p InactiveEnterTimestamp --value {unit})\" +%s"))
def created_at_of(pod_name: str) -> int:
stamp = machine.succeed(f"kubectl -n {NS} get pod {pod_name} -o jsonpath='{{.metadata.creationTimestamp}}'")
return int(machine.succeed(f"date -d \"{stamp}\" +%s"))
def wait_pod_ready(not_uid: str = "", timeout: int = 600) -> str:
"""The name of the Ready pod of the queue that is not terminating and
has a uid other than `not_uid`."""
@ -569,37 +528,19 @@ pkgs.testers.runNixOSTest {
settle(f"test -s {SERVICES_ROOT} && grep -c BEGIN ${tlsDir}/trust-bundle.pem | grep -qx 2", 600, ["swarm-services-cert.service"])
machine.wait_for_unit("token-stub.service")
machine.wait_for_unit("control-listener.service")
machine.succeed("systemctl start overlap-sampler.service")
with subtest("on the host, the container's server and responder run, and the cluster holds none of the queue"):
# The container starts before the store has anything for it: the
# delivery units land the keys, the leaf and the identity, and restart
# the server. The container rebuilds its trust bundle by itself when the
# host's file changes, so the root the store gave is in it.
for unit in ["swarm-nats-auth-secrets", "swarm-bao-nats-callout-xkey", "swarm-bao-nats-tls"]:
machine.succeed(f"systemctl reset-failed {unit}.service || true")
settle(f"systemctl restart {unit}.service", 900, [f"{unit}.service"])
settle(QUEUE_UP, 600, [HOST_UNIT])
assert machine.succeed(f"systemctl is-active {PRUNE}.service").strip() == "active"
assert pods() == [], pods()
assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get service {METRICS_SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get networkpolicy {SERVICE}")[0] != 0
# The control for its absence under the cluster.
machine.succeed("test -e /etc/nixos-containers/swarm-nats.conf")
with subtest("the queue runs as a pod only: the host has no container, delivery unit or prune unit"):
machine.fail("test -e /etc/nixos-containers/swarm-nats.conf")
for unit in ["swarm-nats-auth-secrets", "swarm-bao-nats-callout-xkey", PRUNE]:
machine.fail(f"systemctl cat {unit}.service")
# The leaf unit that writes the gateway's copy is the control that the lookups find a unit of the queue's that is there.
machine.succeed("systemctl cat swarm-bao-nats-tls.service")
machine.succeed(f"test -L {MANIFESTS}/{SERVICE}.yaml")
pod_name = wait_pod_ready()
assert host_state() == "inactive", host_state()
assert machine.execute("machinectl list --no-legend | grep -q swarm-nats")[0] != 0
assert counts() == (1, 1), counts()
# The queue answers by name on the bridge's address, with its name
# verified against the store's root, and admits the router's token.
settle(f"python3 /etc/natstls.py {BRIDGE} {NAME} {SERVICES_ROOT}", 120, [HOST_UNIT])
machine.wait_until_succeeds(nats_cmd(SERVICES_ROOT, "account info"), timeout=120)
machine.wait_until_succeeds(f"grep -F '/api/oidc/introspection ${service}:{SECRET}' ${tokenLog}", timeout=60)
with subtest("a host outside the node cannot reach the queue's port, while it reaches a port the node opens"):
assert reachable(outside, NODE, CONTROL), "the control port is unreachable: the node cannot be told from a closed port"
assert not reachable(outside, NODE, PORT), "the container's port is open to a host outside the node"
assert machine.execute(f"nc -z -w 4 {NODE} {PORT}")[0] == 0
with subtest("a client on the hive's bridge reaches the queue by its name, as an agent does"):
# The bridge's client: an agent's network namespace on the hive's bridge.
BRIDGE_IF = machine.succeed("ip -o -4 addr show | grep -F 'inet ${bridgeIp}/' | cut -d' ' -f2").strip()
machine.succeed(
"ip netns add agent && ip link add va type veth peer name vb && ip link set vb netns agent "
@ -607,40 +548,6 @@ pkgs.testers.runNixOSTest {
"&& ip -n agent addr add ${agentIp}/24 dev vb && ip -n agent link set vb up && ip -n agent link set lo up "
"&& ip -n agent route add default via ${bridgeIp}"
)
assert machine.execute(f"ip netns exec agent nc -z -w 4 {BRIDGE} {PORT}")[0] == 0
assert machine.execute(f"ip netns exec agent nc -z -w 4 {BRIDGE} {METRICS}")[0] != 0
with subtest("the host's own processes read the exporter through the container"):
machine.succeed(f"curl -sf http://127.0.0.1:{METRICS}/metrics | grep -F gnatsd_varz_connections")
with subtest("on the host, the container's server takes a key into the router's state bucket, and the store's files belong to the server's user"):
nats(machine, f"kv add {BUCKET}")
nats(machine, f"kv put {BUCKET} host-key written-on-host")
assert "written-on-host" in nats(machine, f"kv get {BUCKET} host-key --raw")
HOST_UID = machine.succeed(f"stat -c %u {HOST_STORE}").strip()
# The control that the lookup finds files: the store is not empty.
assert int(machine.succeed(f"find {HOST_STORE} -type f | wc -l")) > 0
assert machine.succeed(f"find {HOST_STORE} ! -uid {HOST_UID} | wc -l").strip() == "0"
# The node registers with the entry labels only. The switch is the upgrade of
# a node that registered before the queue was in the cluster: it gets the
# state label at the restart of k3s, and the volume and the pod select on it.
with subtest("the node registered with the entry labels and no state label while the queue runs in its container"):
labels = node_labels()
assert all(labels.get(k) == v for k, v in ENTRY_LABELS.items()), labels
assert STATE_LABEL not in labels, labels
with subtest("the switch to the cluster stops the container before it applies the pod"):
out = switch("/run/booted-system/specialisation/k8s")
assert HOST_UNIT in out and "stopping the following units" in out, out
assert host_state() == "inactive", host_state()
machine.succeed(f"test -L {MANIFESTS}/{SERVICE}.yaml")
pod_name = wait_pod_ready()
assert stopped_at(HOST_UNIT) <= created_at_of(pod_name)
assert machine.execute("machinectl list --no-legend | grep -q swarm-nats")[0] != 0
# The configuration has no container left to start beside the pod.
machine.fail("test -e /etc/nixos-containers/swarm-nats.conf")
assert counts() == (1, 1), counts()
with subtest("the pod holds the leaf and the config as init containers, and has no hostPort on the server or the exporter"):
spec = pod(machine, pod_name)["spec"]
@ -675,7 +582,7 @@ pkgs.testers.runNixOSTest {
print(limits)
assert int(limits.split()[3]) >= 800000, limits
with subtest("the switch gave the registered node the state label, and the volume and the pod select on it"):
with subtest("the node carries the state label, and the volume and the pod select on it"):
labels = node_labels()
assert labels.get(STATE_LABEL) == "true", labels
assert all(labels.get(k) == v for k, v in ENTRY_LABELS.items()), labels
@ -693,7 +600,7 @@ pkgs.testers.runNixOSTest {
old_uid = pod(machine, pod_name)["metadata"]["uid"]
kube(machine, f"label {node} {STATE_LABEL}-")
assert STATE_LABEL not in node_labels()
kube(machine, f"delete pod {pod_name} --wait=true --timeout=120s", 150)
kube(machine, f"delete pod {pod_name} --wait=false")
unscheduled = (
f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o json "
"| jq -r '.items[].status.conditions[]? | select(.type == \"PodScheduled\" and .status == \"False\") | .message'"
@ -746,18 +653,17 @@ pkgs.testers.runNixOSTest {
assert stream_messages() == 1
machine.wait_until_succeeds(f"[ \"$(grep -c '/api/oidc/introspection ${service}:{SECRET}' ${tokenLog})\" -ge 2 ]", timeout=60)
with subtest("the pod's volume is the container's own directory: it reads the host's key, writes one of its own, and leaves files the host's user does not own"):
with subtest("the pod's volume is the host's store directory: the pod writes its keys and its files are there"):
pv = json.loads(kube(machine, f"get pv {SERVICE}-store -o json"))
assert pv["spec"]["local"]["path"] == HOST_STORE, pv["spec"]
assert pv["status"]["phase"] == "Bound" and pv["spec"]["claimRef"]["name"] == f"{SERVICE}-store", pv
assert pv["spec"]["persistentVolumeReclaimPolicy"] == "Retain", pv["spec"]
assert claim["spec"]["volumeName"] == pv["metadata"]["name"], claim["spec"]
assert "written-on-host" in nats(machine, f"kv get {BUCKET} host-key --raw")
nats(machine, f"kv add {BUCKET}")
nats(machine, f"kv put {BUCKET} pod-key written-by-pod")
assert "written-by-pod" in nats(machine, f"kv get {BUCKET} pod-key --raw")
# The stream the pod made is its own, so the host's user has to take it
# back when the container starts.
assert int(machine.succeed(f"find {HOST_STORE} ! -uid {HOST_UID} | wc -l")) > 0
# The control that the lookup finds files: the store is not empty.
assert int(machine.succeed(f"find {HOST_STORE} -type f | wc -l")) > 0
with subtest("a client on the hive's bridge reaches the pod through the published port, behind the egress chain that refuses it everything else of the cluster, and a host outside the node does not"):
assert machine.execute(f"ip netns exec agent nc -z -w 4 {BRIDGE} {PORT}")[0] == 0
@ -806,18 +712,17 @@ pkgs.testers.runNixOSTest {
with subtest("deleting the pod keeps the stream: the volume is the same and the message is read after"):
old_uid = pod(machine, pod_name)["metadata"]["uid"]
kube(machine, f"delete pod {pod_name} --wait=true --timeout=120s", 150)
kube(machine, f"delete pod {pod_name} --wait=false")
pod_name = wait_pod_ready(old_uid)
assert json.loads(kube(machine, f"get pvc {SERVICE}-store -o json"))["metadata"]["uid"] == STATE_VOLUME
machine.wait_until_succeeds(nats_cmd(SERVICES_ROOT, f"stream info {STREAM}"), timeout=120)
assert stream_messages() == 1
assert "written-on-host" in nats(machine, f"kv get {BUCKET} host-key --raw")
assert "written-by-pod" in nats(machine, f"kv get {BUCKET} pod-key --raw")
assert counts() == (1, 1), counts()
with subtest("with openFirewall a host outside the node dials the pod by name and verifies it, and is admitted"):
switch("/run/booted-system/specialisation/k8s-open")
assert len(pods()) == 1, pods()
assert len(live_pods()) == 1, live_pods()
machine.wait_until_succeeds(f"nc -z -w 4 {NODE} {PORT}", timeout=60)
assert reachable(outside, NODE, PORT), "openFirewall left the pod's port closed to a host outside the node"
root = machine.succeed(f"cat {SERVICES_ROOT}")
@ -834,66 +739,5 @@ pkgs.testers.runNixOSTest {
# The exporter's port stays closed to everyone but the host.
assert not reachable(outside, NODE, METRICS)
with subtest("the switch back removes the Deployment, pod and AddOn before the container starts"):
switch("/run/booted-system")
settle(f"[ \"$(systemctl is-active {HOST_UNIT})\" = active ]", 600, [HOST_UNIT, f"{PRUNE}.service"])
assert pods() == [], pods()
assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get service {METRICS_SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get service {SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get networkpolicy {SERVICE}")[0] != 0
# The load balancer's pod and its `hostPort` rule are gone before the
# container listens on the port.
assert machine.succeed(f"kubectl -n kube-system get pods --selector svccontroller.k3s.cattle.io/svcname={SERVICE} -o name").strip() == ""
assert f"--dport {PORT} " not in machine.succeed("iptables -t nat -S")
assert machine.execute(f"kubectl -n kube-system get addons.k3s.cattle.io {SERVICE}")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml.pruning")[0] != 0
pruned = int(machine.succeed(f"systemctl show -p ExecMainExitTimestampMonotonic --value {PRUNE}.service"))
started = int(machine.succeed(f"systemctl show -p InactiveExitTimestampMonotonic --value {HOST_UNIT}"))
assert 0 < pruned <= started, (pruned, started)
requires = machine.succeed(f"systemctl show -p Requires --value {HOST_UNIT}")
assert f"{PRUNE}.service" in requires, requires
# k3s adds labels and never takes one off: the label stays and does
# nothing while the container runs.
assert node_labels().get(STATE_LABEL) == "true", node_labels()
# The volume is kept for the next switch.
assert json.loads(kube(machine, f"get pvc {SERVICE}-store -o json"))["metadata"]["uid"] == STATE_VOLUME
settle(QUEUE_UP, 600, [HOST_UNIT])
assert counts() == (1, 1), counts()
# The container's server reads what the pod wrote: its unit took the
# files back before the server started.
machine.wait_until_succeeds(nats_cmd(SERVICES_ROOT, f"kv get {BUCKET} pod-key --raw") + " | grep -F written-by-pod", timeout=120)
assert "written-on-host" in nats(machine, f"kv get {BUCKET} host-key --raw")
assert stream_messages() == 1
assert machine.succeed(f"find {HOST_STORE} ! -uid {HOST_UID} | wc -l").strip() == "0"
# Closed to a host outside the node again, open to the node's own.
assert not reachable(outside, NODE, PORT), "the container's port is open to a host outside the node"
assert reachable(outside, NODE, CONTROL)
with subtest("no moment of any switch had two servers or two responders, or the container and a pod together"):
machine.succeed("systemctl stop overlap-sampler.service")
lines = machine.succeed("cat ${overlapLog}").splitlines()
host_up = {"active", "activating", "deactivating", "reloading"}
samples = []
for fields in (line.split() for line in lines):
if len(fields) == 7:
samples.append(
(
fields[2].removeprefix("host="),
int(fields[3].removeprefix("pods=")),
int(fields[4].removeprefix("servers=")),
int(fields[5].removeprefix("responders=")),
)
)
both = [s for s in samples if s[0] in host_up and s[1] > 0]
assert not both, [line for line in lines if "pods=0" not in line and "host=inactive" not in line][:8]
many = [s for s in samples if s[2] > 1 or s[3] > 1]
assert not many, many[:5]
# The controls: the sampler saw the container alone, a pod alone, and
# a server and a responder in each.
assert any(s[0] in host_up and s[1] == 0 and s[2] == 1 and s[3] == 1 for s in samples), lines[:5]
assert any(s[0] not in host_up and s[1] > 0 and s[2] == 1 and s[3] == 1 for s in samples), lines[:5]
print(f"${service}: {len(samples)} samples, none with two copies")
'';
}

View file

@ -1,14 +1,10 @@
# `vmTests.<system>.k8s-runtime-switch`: the notification router, the
# speech-to-text service, the CI run poller, the review classifier and the
# claude login minter move between their host units or containers and the host's
# cluster (`services.hyperhive.deploy.<service>.runtime`), against the real
# secret store and a real queue. The host boots with all five on the host; the
# `k8s` specialisation has them in the cluster. The script switches to it, back,
# and to it again, and asserts that:
# `vmTests.<system>.k8s-services`: the notification router, the speech-to-text
# service, the CI run poller, the review classifier and the claude login minter
# run as pods in the host's cluster, against the real secret store and a real
# queue. The script asserts that:
#
# - exactly one copy of each service runs at each step, by the order of the
# switch's own timestamps and by a sampler that looks every 200 ms (the
# poller's copies: timer, service, CronJob, Jobs and pods);
# - each runs once, as a pod or CronJob: the host has no container, unit, timer or
# prune unit for it;
# - each pod is Ready, so it logged in to the store with its ServiceAccount
# token, read its client secret and minted a token with it. The router
# routes an event and a deleted pod exits 0 within its grace period; the
@ -21,9 +17,7 @@
# gate;
# - the minter's jwt token writes an agent's credentials and the classifier's
# cannot; the daemons' pods have a read-only root, and `claude` writes its
# config under `HOME` in the /tmp volume only, as the real login step does;
# - the switch back leaves no pod, Deployment, CronJob or AddOn, and the router's
# consumer is the queue's.
# config under `HOME` in the /tmp volume only, as the real login step does.
#
# The queue is a plain nats-server with TLS, and one stub is the token endpoint,
# the forge and the swarm collector, which records what it is given. The
@ -72,7 +66,6 @@ let
# The model file the service is given: its path is in the pod's image, and
# nothing reads it.
sttModel = pkgs.writeText "ggml-placeholder.bin" "not a model";
overlapLog = "/var/log/overlap.log";
tokenLog = "/var/log/stub-token.log";
requestLog = "/var/log/stub-requests.log";
@ -170,32 +163,9 @@ let
}
'';
# Looks every 200 ms, for each service, at whether its host unit runs and how
# many of its objects exist in the cluster, a terminating pod included. The
# poller is on the host while its timer or its service is active, and in the
# cluster while its CronJob, a Job or a pod exists.
sampler = pkgs.writeShellScript "overlap-sampler" ''
while true; do
for svc in ${service} ${stt} ${classifier} ${login}; do
state="$(systemctl is-active container@$svc.service || true)"
pods="$(kubectl --namespace ${namespace} get pods --selector app.kubernetes.io/name=$svc --no-headers 2>/dev/null | wc -l)"
echo "$(date +%s.%N) $svc host=$state pods=$pods" >> ${overlapLog}
done
state=inactive
for unit in ${ci}.timer ${ci}.service; do
case "$(systemctl is-active $unit || true)" in
active|activating|deactivating|reloading) state=active ;;
esac
done
objects="$(kubectl --namespace ${namespace} get cronjob,pods --selector app.kubernetes.io/name=${ci} --no-headers 2>/dev/null | wc -l)"
jobs="$(kubectl --namespace ${namespace} get jobs --no-headers 2>/dev/null | grep -c "^${ci}" || true)"
echo "$(date +%s.%N) ${ci} host=$state pods=$((objects + jobs))" >> ${overlapLog}
sleep 0.2
done
'';
in
pkgs.testers.runNixOSTest {
name = "k8s-runtime-switch";
name = "k8s-services";
# The store takes a few minutes to open its raft storage, and the script
# switches the configuration three times. Under the 1 h job bound with room
@ -239,14 +209,6 @@ pkgs.testers.runNixOSTest {
};
system.stateVersion = "25.11";
specialisation.k8s.configuration.services.hyperhive.deploy = {
notify-router.runtime = "k8s";
stt.runtime = "k8s";
ci-metrics.runtime = "k8s";
review-classifier.runtime = "k8s";
claude-login.runtime = "k8s";
};
# The store's TLS passthrough is a stream server of the host's nginx,
# which needs certificates this host does not mint, so a second nginx
# carries the passthrough alone, as `k8s-bao-login` does.
@ -332,16 +294,6 @@ pkgs.testers.runNixOSTest {
};
};
systemd.services.overlap-sampler = {
path = [
pkgs.kubectl
pkgs.coreutils
pkgs.systemd
];
environment.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml";
serviceConfig.ExecStart = sampler;
};
environment.systemPackages = [
pkgs.kubectl
pkgs.curl
@ -468,12 +420,6 @@ pkgs.testers.runNixOSTest {
return machine.execute(f"systemctl is-active {unit}")[1].strip()
def ci_host_state() -> str:
"""`active` while the poller's timer or service runs on the host."""
states = [host_state(unit) for unit in CI_HOST_UNITS]
return "active" if any(s in ("active", "activating", "deactivating", "reloading") for s in states) else "inactive"
def requests() -> list[dict]:
return [json.loads(line) for line in machine.succeed("cat ${requestLog}").splitlines() if line]
@ -496,15 +442,6 @@ pkgs.testers.runNixOSTest {
return kube(machine, f"logs job/{name}")
def stopped_at(unit: str) -> int:
return int(machine.succeed(f"date -d \"$(systemctl show -p InactiveEnterTimestamp --value {unit})\" +%s"))
def created_at_of(pod_name: str) -> int:
stamp = machine.succeed(f"kubectl -n {NS} get pod {pod_name} -o jsonpath='{{.metadata.creationTimestamp}}'")
return int(machine.succeed(f"date -d \"{stamp}\" +%s"))
def consumer() -> dict:
return json.loads(machine.succeed(f"nats {NATS} consumer info SWARM_EVENTS notify-router --json"))
@ -525,20 +462,6 @@ pkgs.testers.runNixOSTest {
return name
def switch(target: str) -> str:
"""Switches to `target`. Units of this host that fail for reasons of
their own (the gateway's certificate import has no nginx group, here)
make the exit status 4; the units the switch is about must not be
among them."""
status, out = machine.execute(f"{target}/bin/switch-to-configuration test 2>&1")
print(out)
assert status in (0, 4), out
failed = next((line for line in out.splitlines() if "the following units failed" in line), "")
ours = [HOST_UNIT, STT_HOST_UNIT, CLASSIFIER_HOST_UNIT, LOGIN_HOST_UNIT, *CI_HOST_UNITS, f"{PRUNE}.service", f"{STT_PRUNE}.service", f"{CLASSIFIER_PRUNE}.service", f"{LOGIN_PRUNE}.service", f"{CI_PRUNE}.service", "hyperhive-k8s-ca-trust.service", "k3s.service"]
assert not any(unit in failed for unit in ours), failed
return out
with subtest("the node is Ready and holds every image"):
wait_node_ready(machine, timeout=300)
wait_images(machine, timeout=300)
@ -608,89 +531,33 @@ pkgs.testers.runNixOSTest {
machine.wait_until_succeeds(f"nats {NATS} account info", timeout=120)
machine.succeed(f"nats {NATS} kv add agent-status")
machine.succeed(f"nats {NATS} kv put agent-status h1.{AGENT} '{{}}'")
machine.succeed("systemctl start overlap-sampler.service")
with subtest("on the host, the containers run and the cluster holds none of the four services"):
machine.wait_until_succeeds(f"[ \"$(systemctl is-active {HOST_UNIT})\" = active ]", timeout=300)
machine.wait_until_succeeds(f"[ \"$(systemctl is-active {STT_HOST_UNIT})\" = active ]", timeout=300)
assert router_pods() == [], router_pods()
assert service_pods(STT) == [], service_pods(STT)
assert machine.execute(f"test -e {MANIFESTS}/{STT}.yaml")[0] != 0
assert machine.execute(f"kubectl -n {NS} get deployment {STT}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get pvc {STT}-state")[0] != 0
assert machine.succeed(f"systemctl is-active {STT_PRUNE}.service").strip() == "active"
assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml")[0] != 0
assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0
# The prune unit ran with the container, found no link, and needed
# nothing from the cluster.
assert machine.succeed(f"systemctl is-active {PRUNE}.service").strip() == "active"
for daemon, (daemon_unit, daemon_prune) in CLAUDE_DAEMONS.items():
machine.wait_until_succeeds(f"[ \"$(systemctl is-active {daemon_unit})\" = active ]", timeout=300)
assert service_pods(daemon) == [], service_pods(daemon)
assert machine.execute(f"test -e {MANIFESTS}/{daemon}.yaml")[0] != 0
assert machine.execute(f"kubectl -n {NS} get deployment {daemon}")[0] != 0
assert machine.succeed(f"systemctl is-active {daemon_prune}.service").strip() == "active"
with subtest("on the host, the poller's timer runs, one pass pushes the run to the poller's own route, and the cluster holds none of it"):
assert host_state(f"{CI}.timer") == "active", host_state(f"{CI}.timer")
assert machine.succeed(f"systemctl is-active {CI_PRUNE}.service").strip() == "active"
assert machine.execute(f"test -e {MANIFESTS}/{CI}.yaml")[0] != 0
assert machine.execute(f"kubectl -n {NS} get cronjob {CI}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get pvc {CI}-state")[0] != 0
# A timer pass may be running or may have failed before the store held
# the secrets; this start waits for the one that runs, or runs one.
machine.succeed(f"systemctl reset-failed {CI}.service || true")
machine.succeed(f"systemctl start {CI}.service", timeout=300)
runs = pushes(RUN_METRIC)
assert len(runs) == 1, runs
assert runs[0]["path"] == OWN_ROUTE and runs[0]["host"] == "${otelName}", runs
assert runs[0]["bearer_minted"], runs
assert runs[0]["points"] == {RUN_METRIC: 1, "hyperhive.ci.run.queue_wait": 1}, runs
# The host unit holds the store certificate, so its pass also reports
# that certificate's lifetime.
assert len(pushes(CERT_METRIC)) >= 1, requests()
machine.succeed("test -s /var/lib/swarm-ci-metrics/cursor.json")
HOST_CERT_PUSHES = len(pushes(CERT_METRIC))
with subtest("the switch to the cluster stops the container before it applies the pod"):
out = switch("/run/booted-system/specialisation/k8s")
assert all(u in out for u in [HOST_UNIT, STT_HOST_UNIT, CLASSIFIER_HOST_UNIT, LOGIN_HOST_UNIT]) and "stopping the following units" in out, out
assert host_state() == "inactive", host_state()
assert host_state(STT_HOST_UNIT) == "inactive", host_state(STT_HOST_UNIT)
machine.succeed(f"test -L {MANIFESTS}/{SERVICE}.yaml")
machine.succeed(f"test -L {MANIFESTS}/{STT}.yaml")
for daemon, (daemon_unit, _) in CLAUDE_DAEMONS.items():
assert host_state(daemon_unit) == "inactive", host_state(daemon_unit)
machine.succeed(f"test -L {MANIFESTS}/{daemon}.yaml")
with subtest("the five services run only as pods: the host has no container, unit, timer or prune unit for them"):
for unit in [HOST_UNIT, STT_HOST_UNIT, CLASSIFIER_HOST_UNIT, LOGIN_HOST_UNIT]:
assert host_state(unit) == "inactive", (unit, host_state(unit))
for name in [SERVICE, STT, CLASSIFIER, LOGIN]:
machine.fail(f"test -e /etc/nixos-containers/{name}.conf")
for prune in [PRUNE, STT_PRUNE, CI_PRUNE, CLASSIFIER_PRUNE, LOGIN_PRUNE]:
machine.fail(f"systemctl cat {prune}.service")
for unit in CI_HOST_UNITS:
machine.fail(f"systemctl cat {unit}")
# The CA publisher is the control that the lookups find a unit of the cluster's that is there.
machine.succeed("systemctl cat hyperhive-k8s-ca-trust.service")
for name in [SERVICE, STT, CLASSIFIER, LOGIN, CI]:
machine.succeed(f"test -L {MANIFESTS}/{name}.yaml")
# Suspended as soon as it exists: a scheduled Job at the next five-minute
# mark would push the run before the test's own Job does.
machine.wait_until_succeeds(f"kubectl -n {NS} get cronjob {CI}", timeout=300)
kube(machine, f"patch cronjob {CI} -p '{{\"spec\":{{\"suspend\":true}}}}'")
router = wait_pod_ready()
assert stopped_at(HOST_UNIT) <= created_at_of(router)
assert machine.execute("machinectl list --no-legend | grep -q swarm-notify-router")[0] != 0
with subtest("the speech-to-text pod is Ready after its container stopped, and the container is gone"):
stt_pod = wait_pod_ready(STT)
assert stopped_at(STT_HOST_UNIT) <= created_at_of(stt_pod)
assert machine.execute("machinectl list --no-legend | grep -q swarm-stt")[0] != 0
with subtest("the poller's timer and service are gone from the host, and its CronJob is applied"):
assert ci_host_state() == "inactive", [host_state(u) for u in CI_HOST_UNITS]
assert machine.execute(f"systemctl cat {CI}.timer")[0] != 0
assert machine.execute(f"systemctl cat {CI}.service")[0] != 0
machine.succeed(f"test -L {MANIFESTS}/{CI}.yaml")
machine.wait_until_succeeds(f"kubectl -n {NS} get cronjob {CI}", timeout=300)
cron = json.loads(kube(machine, f"get cronjob {CI} -o json"))
assert cron["spec"]["schedule"] == "*/5 * * * *", cron["spec"]
assert cron["spec"]["concurrencyPolicy"] == "Forbid", cron["spec"]
# A scheduled Job would run beside the ones this test makes.
kube(machine, f"patch cronjob {CI} -p '{{\"spec\":{{\"suspend\":true}}}}'")
with subtest("the review classifier and the claude login pods are Ready after their containers stopped, and the containers are gone"):
for daemon, (daemon_unit, _) in CLAUDE_DAEMONS.items():
router = wait_pod_ready()
stt_pod = wait_pod_ready(STT)
for daemon in CLAUDE_DAEMONS:
DAEMON_PODS[daemon] = wait_pod_ready(daemon)
assert stopped_at(daemon_unit) <= created_at_of(DAEMON_PODS[daemon])
assert machine.execute(f"machinectl list --no-legend | grep -q {daemon}")[0] != 0
for name in [SERVICE, STT, CLASSIFIER, LOGIN]:
assert machine.execute(f"machinectl list --no-legend | grep -q {name}")[0] != 0
with subtest("the host published the CA files, which are the hive's"):
trust = machine.succeed(f"kubectl -n {NS} get configmap hyperhive-ca-trust -o json")
@ -813,21 +680,22 @@ pkgs.testers.runNixOSTest {
tokens_before = int(machine.succeed(f"grep -cF '/api/oidc/token ${ci}:{CI_SECRET}' ${tokenLog} || true"))
job_log = ci_job(f"{CI}-first")
assert "pushed=1" in job_log.replace(" ", ""), job_log
# The cursor does not move with the poller: the pod starts with none
# and pushes the run the host pass pushed.
runs = pushes(RUN_METRIC)
assert len(runs) == 2, runs
assert runs[1]["path"] == OWN_ROUTE and runs[1]["host"] == "${otelName}", runs[1]
assert runs[1]["bearer_minted"], runs[1]
assert runs[1]["points"] == {RUN_METRIC: 1, "hyperhive.ci.run.queue_wait": 1}, runs[1]
# Every push of the poller, the host's and the pod's, went to its own
# route. The pod holds no client certificate, so it reports none.
assert len(runs) == 1, runs
assert runs[0]["path"] == OWN_ROUTE and runs[0]["host"] == "${otelName}", runs[0]
assert runs[0]["bearer_minted"], runs[0]
assert runs[0]["points"] == {RUN_METRIC: 1, "hyperhive.ci.run.queue_wait": 1}, runs[1]
# Every push of the poller went to its own route. The pod holds no client
# certificate, so it reports none; the run's push is the control that
# the lookup finds what is there.
assert {r["path"] for r in requests() if "points" in r} == {OWN_ROUTE}, requests()
assert len(pushes(CERT_METRIC)) == HOST_CERT_PUSHES >= 1, requests()
assert len(pushes(CERT_METRIC)) == 0, requests()
# The pod read the forge token and its client secret from the store,
# and reached the forge and the identity provider by name.
# and reached the forge and the identity provider by name. One pass
# makes two forge requests (the repository search and the run list), so
# two is the floor of this one Job.
forge = [r for r in requests() if "forge_token_ok" in r]
assert len(forge) >= 4, forge
assert len(forge) >= 2, forge
assert all(r["forge_token_ok"] and r["host"] == "${forgeName}" for r in forge), forge
tokens = int(machine.succeed(f"grep -cF '/api/oidc/token ${ci}:{CI_SECRET}' ${tokenLog}"))
assert tokens > tokens_before, (tokens, tokens_before)
@ -852,15 +720,14 @@ pkgs.testers.runNixOSTest {
assert "OTEL_EXPORTER_OTLP_ENDPOINT" in router_env, router_env
with subtest("the poller's cursor volume is bound and mounted where the unit keeps its state, and a second Job pushes nothing"):
claim = json.loads(kube(machine, f"get pvc {CI}-state -o json"))
claim = json.loads(kube(machine, f"get pvc {CI}-store -o json"))
assert claim["status"]["phase"] == "Bound", claim["status"]
CURSOR_VOLUME = claim["metadata"]["uid"]
mounts = ci_pod["spec"]["containers"][0]["volumeMounts"]
assert any(m["name"] == "state" and m["mountPath"] == "/var/lib/swarm-ci-metrics" for m in mounts), mounts
seen = len(requests())
job_log = ci_job(f"{CI}-second")
assert "pushed=0" in job_log.replace(" ", ""), job_log
assert len(pushes(RUN_METRIC)) == 2, requests()
assert len(pushes(RUN_METRIC)) == 1, requests()
# The pass ran: it listed the forge again.
assert len(requests()) > seen, requests()
def claude_of(daemon: str) -> str:
@ -1040,7 +907,6 @@ pkgs.testers.runNixOSTest {
f"nats {NATS} consumer info SWARM_EVENTS notify-router --json | jq -e '.ack_floor.stream_seq == 1'",
timeout=60,
)
created_at = consumer()["created"]
with subtest("deleting the pod ends its container with exit code 0 within the grace period, and its replacement is Ready"):
old = router_pods()[0].removeprefix("pod/")
@ -1068,110 +934,5 @@ pkgs.testers.runNixOSTest {
assert took < 15 + 5, took
assert wait_pod_ready(daemon) != old_daemon
with subtest("the switch back removes the pods and their objects before the containers start, and keeps the cache volume"):
out = switch("/run/booted-system")
print(out)
machine.wait_until_succeeds(f"[ \"$(systemctl is-active {HOST_UNIT})\" = active ]", timeout=300)
machine.wait_until_succeeds(f"[ \"$(systemctl is-active {STT_HOST_UNIT})\" = active ]", timeout=300)
assert router_pods() == [], router_pods()
assert service_pods(STT) == [], service_pods(STT)
assert machine.execute(f"kubectl -n {NS} get deployment {STT}")[0] != 0
assert machine.execute(f"kubectl -n kube-system get addons.k3s.cattle.io {STT}")[0] != 0
assert machine.execute(f"kubectl -n {NS} get networkpolicy {STT}")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{STT}.yaml")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{STT}.yaml.pruning")[0] != 0
pruned_stt = int(machine.succeed(f"systemctl show -p ExecMainExitTimestampMonotonic --value {STT_PRUNE}.service"))
started_stt = int(machine.succeed(f"systemctl show -p InactiveExitTimestampMonotonic --value {STT_HOST_UNIT}"))
assert 0 < pruned_stt <= started_stt, (pruned_stt, started_stt)
# Persistent volume claims stay, with what they hold; the speech-to-text
# pod never had one.
assert machine.execute(f"kubectl -n {NS} get pvc {STT}-state")[0] != 0
assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n kube-system get addons.k3s.cattle.io {SERVICE}")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml.pruning")[0] != 0
pruned = int(machine.succeed(f"systemctl show -p ExecMainExitTimestampMonotonic --value {PRUNE}.service"))
started = int(machine.succeed(f"systemctl show -p InactiveExitTimestampMonotonic --value {HOST_UNIT}"))
assert 0 < pruned <= started, (pruned, started)
for daemon, (daemon_unit, daemon_prune) in CLAUDE_DAEMONS.items():
machine.wait_until_succeeds(f"[ \"$(systemctl is-active {daemon_unit})\" = active ]", timeout=300)
assert service_pods(daemon) == [], service_pods(daemon)
assert machine.execute(f"kubectl -n {NS} get deployment {daemon}")[0] != 0
assert machine.execute(f"kubectl -n kube-system get addons.k3s.cattle.io {daemon}")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{daemon}.yaml")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{daemon}.yaml.pruning")[0] != 0
pruned_daemon = int(machine.succeed(f"systemctl show -p ExecMainExitTimestampMonotonic --value {daemon_prune}.service"))
started_daemon = int(machine.succeed(f"systemctl show -p InactiveExitTimestampMonotonic --value {daemon_unit}"))
assert 0 < pruned_daemon <= started_daemon, (daemon, pruned_daemon, started_daemon)
with subtest("the switch back removes the poller's CronJob, Jobs and pods before its timer starts, and keeps the cursor volume"):
machine.wait_until_succeeds(f"[ \"$(systemctl is-active {CI}.timer)\" = active ]", timeout=300)
assert machine.execute(f"kubectl -n {NS} get cronjob {CI}")[0] != 0
assert service_pods(CI) == [], service_pods(CI)
assert machine.execute(f"kubectl -n {NS} get jobs --no-headers | grep -q ^{CI}")[0] != 0
assert machine.execute(f"kubectl -n kube-system get addons.k3s.cattle.io {CI}")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{CI}.yaml")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{CI}.yaml.pruning")[0] != 0
pruned_ci = int(machine.succeed(f"systemctl show -p ExecMainExitTimestampMonotonic --value {CI_PRUNE}.service"))
started_ci = int(machine.succeed(f"systemctl show -p InactiveExitTimestampMonotonic --value {CI}.timer"))
assert 0 < pruned_ci <= started_ci, (pruned_ci, started_ci)
# Both host units wait for the prune unit, so a pass started by hand
# cannot run beside a Job either.
for unit in CI_HOST_UNITS:
requires = machine.succeed(f"systemctl show -p Requires --value {unit}")
after = machine.succeed(f"systemctl show -p After --value {unit}")
assert f"{CI_PRUNE}.service" in requires and f"{CI_PRUNE}.service" in after, (unit, requires, after)
assert json.loads(kube(machine, f"get pvc {CI}-state -o json"))["metadata"]["uid"] == CURSOR_VOLUME
with subtest("the poller on the host again finds its own cursor, and pushes no run twice"):
# The cursor on the host is the one its first pass wrote; the pod's is
# in the volume. A pass here pushes nothing but its certificate gauges.
machine.succeed(f"systemctl reset-failed {CI}.service || true")
machine.succeed(f"systemctl start {CI}.service", timeout=300)
assert len(pushes(RUN_METRIC)) == 2, requests()
assert len(pushes(CERT_METRIC)) > HOST_CERT_PUSHES, requests()
with subtest("the router's state is the queue's: the consumer is the one the pod made, with its progress"):
info = consumer()
assert info["created"] == created_at, (info["created"], created_at)
assert info["ack_floor"]["stream_seq"] == 1, info
machine.succeed(f"nats {NATS} kv get notify-router-state 1.7 >/dev/null")
with subtest("a second switch to the cluster applies the manifests again, and the speech-to-text pod finds no claim"):
switch("/run/booted-system/specialisation/k8s")
assert host_state() == "inactive", host_state()
assert host_state(STT_HOST_UNIT) == "inactive", host_state(STT_HOST_UNIT)
wait_pod_ready()
wait_pod_ready(STT)
for daemon, (daemon_unit, _) in CLAUDE_DAEMONS.items():
assert host_state(daemon_unit) == "inactive", host_state(daemon_unit)
wait_pod_ready(daemon)
assert machine.execute(f"kubectl -n {NS} get pvc {STT}-state")[0] != 0
assert ci_host_state() == "inactive", [host_state(u) for u in CI_HOST_UNITS]
machine.wait_until_succeeds(f"kubectl -n {NS} get cronjob {CI}", timeout=300)
kube(machine, f"patch cronjob {CI} -p '{{\"spec\":{{\"suspend\":true}}}}'")
# The volume the first stay left holds the cursor: nothing is pushed.
assert json.loads(kube(machine, f"get pvc {CI}-state -o json"))["metadata"]["uid"] == CURSOR_VOLUME
job_log = ci_job(f"{CI}-third")
assert "pushed=0" in job_log.replace(" ", ""), job_log
assert len(pushes(RUN_METRIC)) == 2, requests()
with subtest("no moment of any switch had a service's container and a pod together"):
machine.succeed("systemctl stop overlap-sampler.service")
lines = machine.succeed("cat ${overlapLog}").splitlines()
host_up = {"active", "activating", "deactivating", "reloading"}
for svc in (SERVICE, STT, CI, CLASSIFIER, LOGIN):
samples = [
(fields[2].removeprefix("host="), int(fields[3].removeprefix("pods=")))
for fields in (line.split() for line in lines)
if len(fields) == 4 and fields[1] == svc
]
both = [s for s in samples if s[0] in host_up and s[1] > 0]
assert not both, (svc, both[:5])
# The controls: the sampler saw the container alone and a pod alone.
assert any(s[0] in host_up and s[1] == 0 for s in samples), (svc, lines[:5])
assert any(s[0] not in host_up and s[1] > 0 for s in samples), (svc, lines[:5])
print(f"{svc}: {len(samples)} samples, none with both")
'';
}