Watch
0
0
Fork
You've already forked hyperhive
0

vm-tests: k8s-runtime-switch moves the CI run poller with the router and the speech-to-text service

This commit is contained in:
atlas 2026-11-22 03:05:43 +01:00 • committed by maia
commit b0f81028c2

View file

@ -1,32 +1,32 @@
# `vmTests.<system>.k8s-runtime-switch`: the notification router and the
# speech-to-text service move between their host containers and pods in the
# host's cluster (`services.hyperhive.deploy.<service>.runtime`), against the
# real secret store and a real queue. The host boots with both in their
# containers; the `k8s` specialisation is the same host with both in the
# cluster. One test holds both services because the switch is one activation
# and a second VM would pay the store's start-up again. The script switches to
# it, back, and to it again, and asserts that:
# `vmTests.<system>.k8s-runtime-switch`: the notification router, the
# speech-to-text service and the CI run poller move between their host units
# and the host's cluster (`services.hyperhive.deploy.<service>.runtime`),
# against the real secret store and a real queue. The host boots with all three
# on the host; the `k8s` specialisation has all three in the cluster. One test
# holds them because the switch is one activation and a second VM would pay the
# store's start-up again. The script switches to it, back, and to it again, and
# 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 pod is Ready, so it logged in to the store with its ServiceAccount
# token, read the queue's client secret, minted a token with it and connected
# to the queue with the hive's CA, which the host published as a ConfigMap;
# - the pod routes one forge event, and a deleted pod exits 0 within its grace
# period with its replacement Ready;
# - the speech-to-text pod is Ready, logged in to the store with its
# ServiceAccount token, carries its unit's memory and CPU limits, and has its
# cache volume bound, which the switch back leaves in place;
# - the switch back leaves no pod, Deployment or AddOn, and the router's
# consumer is the queue's, unchanged.
# switch's own timestamps and by a sampler that looks every 200 ms. The
# poller's copies are its timer and service, and its CronJob, Jobs and pods;
# - 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
# speech-to-text pod carries its limits and has its cache volume bound;
# - the poller's Job completes against a forge that lists one run, pushes it to
# the poller's own route of the swarm collector with a bearer the stub
# minted, holds no Secret, and keeps its cursor in a volume, so a second Job
# pushes nothing;
# - the switch back leaves no pod, Deployment, CronJob or AddOn, and the
# router's consumer is the queue's, unchanged.
#
# The queue is a plain nats-server with JetStream and TLS, and the token
# endpoint is a stub that records the client credentials it is given. They
# replace the identity provider and the queue's auth callout, which stay
# host-run and unchanged; the services take their production path otherwise.
# The speech-to-text service gets a placeholder model file, which it never
# loads, and no transcription runs. The test makes the hive's CA and the leaf of
# both names at boot.
# The queue is a plain nats-server with TLS, and one stub is the token
# endpoint, the forge and the swarm collector: it records the client
# credentials it is given and each push's route. They replace services that
# stay host-run and unchanged. The speech-to-text service gets a placeholder
# model file, which it never loads. The test makes the hive's CA and the leaf of
# every name at boot.
{ pkgs, self }:
let
inherit (pkgs) lib;
@ -38,18 +38,26 @@ let
natsName = "nats.t.local";
natsPort = 4222;
authName = "auth.t.local";
forgeName = "forge.t.local";
otelName = "otel.t.local";
namespace = "hyperhive";
service = "swarm-notify-router";
clientId = "swarm-notify-router";
stt = "swarm-stt";
sttClientId = "swarm-stt";
ci = "swarm-ci-metrics";
# A fixed value: it is the stub's to check, not a secret.
forgeToken = "test-forge-token";
agent = "atlas";
pkiDir = "/var/lib/test-ca";
tlsDir = "/var/lib/hive-tls";
leaf = "swarm/services/${clientId}/oidc/client";
sttLeaf = "swarm/services/${sttClientId}/oidc/client";
ciLeaf = "swarm/services/${ci}/oidc/client";
ciForgeLeaf = "swarm/services/ci-metrics/forge/token";
prune = "${service}-k8s-prune";
sttPrune = "${stt}-k8s-prune";
ciPrune = "${ci}-k8s-prune";
hostUnit = "container@${service}.service";
sttHostUnit = "container@${stt}.service";
# The model file the service is given: its path is in the pod's image, and
@ -57,9 +65,15 @@ let
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";
# The token endpoint: it answers every client-credentials request with a
# token and records the client id and secret of the Basic credentials.
# The identity provider, the forge and the swarm collector, by name, on one
# listener. The token endpoint answers every client-credentials request with
# a token and records the client id and secret of the Basic credentials.
# The forge lists one repo with one finished run. The collector's poller
# route answers 200 and, with the forge, records the request: the route, the
# name asked for, whether the credential is the one this stub issued or
# expects, and the points the body carried.
tokenStub = pkgs.writeText "token-stub.py" ''
import base64
import http.server
@ -67,23 +81,71 @@ let
import secrets
import ssl
MINTED = set()
RUN = {
"index_in_repo": 1,
"status": "success",
"event": "pull_request",
"prettyref": "#7",
"workflow_id": "ci.yml",
"commit_sha": "d0ab2edd05bcce7a35ea15bbc2ef5a366fc93d18",
"created": "2026-10-16T16:50:38+02:00",
"started": "2026-10-16T16:55:17+02:00",
"stopped": "2026-10-16T17:13:30+02:00",
}
def record(entry):
with open("${requestLog}", "a") as log:
log.write(json.dumps(entry) + "\n")
class Handler(http.server.BaseHTTPRequestHandler):
def do_POST(self):
self.rfile.read(int(self.headers.get("Content-Length", 0)))
auth = self.headers.get("Authorization", "")
who = base64.b64decode(auth.removeprefix("Basic ")).decode() if auth.startswith("Basic ") else "none"
with open("${tokenLog}", "a") as log:
log.write(f"{self.path} {who}\n")
body = json.dumps({"access_token": secrets.token_hex(16), "token_type": "Bearer", "expires_in": 3600}).encode()
def reply(self, payload):
body = json.dumps(payload).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
raw = self.rfile.read(int(self.headers.get("Content-Length", 0)))
auth = self.headers.get("Authorization", "")
path = self.path.split("?")[0]
if path.endswith("/v1/metrics"):
metrics = json.loads(raw)["resourceMetrics"][0]["scopeMetrics"][0]["metrics"]
record({
"host": self.headers.get("Host"),
"path": path,
"bearer_minted": auth.removeprefix("Bearer ") in MINTED,
"points": {m["name"]: len(m["gauge"]["dataPoints"]) for m in metrics},
})
self.reply({})
return
who = base64.b64decode(auth.removeprefix("Basic ")).decode() if auth.startswith("Basic ") else "none"
with open("${tokenLog}", "a") as log:
log.write(f"{self.path} {who}\n")
token = secrets.token_hex(16)
MINTED.add(token)
self.reply({"access_token": token, "token_type": "Bearer", "expires_in": 3600})
server = http.server.HTTPServer(("${bridgeIp}", 443), Handler)
def do_GET(self):
path = self.path.split("?")[0]
record({
"host": self.headers.get("Host"),
"path": path,
"forge_token_ok": self.headers.get("Authorization") == "token ${forgeToken}",
})
if path.endswith("/repos/search"):
self.reply({"ok": True, "data": [{"full_name": "o/r", "has_actions": True, "archived": False, "mirror": False}]})
elif path.endswith("/repos/o/r/actions/runs"):
self.reply({"workflow_runs": [RUN], "total_count": 1})
else:
self.send_error(404)
server = http.server.ThreadingHTTPServer(("${bridgeIp}", 443), Handler)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain("${pkiDir}/svc.pem", "${pkiDir}/svc-key.pem")
server.socket = context.wrap_socket(server.socket, server_side=True)
@ -99,8 +161,10 @@ let
}
'';
# Looks every 200 ms, for each service, at whether its container runs and how
# many of its pods exist, a terminating pod included.
# 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}; do
@ -108,6 +172,15 @@ let
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
'';
@ -135,16 +208,22 @@ pkgs.testers.runNixOSTest {
deploy.notify-router.enable = true;
deploy.stt.enable = true;
deploy.stt.settings.modelFile = sttModel;
deploy.ci-metrics.enable = true;
deploy.hive-controller.hiveName = "h1";
swarm.domain = "t.local";
swarm.forge.domain = forgeName;
swarm.otel.domain = otelName;
swarm.bao.domain = baoName;
swarm.bao.port = baoPort;
swarm.hives.h1.domain = "h1.t.local";
# The queue and the identity provider are host-run: their names go to
# the bridge for the cluster's pods, as the hive's own do.
# The queue, the identity provider, the forge and the swarm collector
# are host-run: their names go to the bridge for the cluster's pods, as
# the hive's own do.
gateway.localNames = [
natsName
authName
forgeName
otelName
];
};
system.stateVersion = "25.11";
@ -152,6 +231,7 @@ pkgs.testers.runNixOSTest {
specialisation.k8s.configuration.services.hyperhive.deploy = {
notify-router.runtime = "k8s";
stt.runtime = "k8s";
ci-metrics.runtime = "k8s";
};
# The store's TLS passthrough is a stream server of the host's nginx,
@ -162,6 +242,8 @@ pkgs.testers.runNixOSTest {
baoName
natsName
authName
forgeName
otelName
];
systemd.services.bao-stream = {
wantedBy = [ "multi-user.target" ];
@ -185,11 +267,11 @@ pkgs.testers.runNixOSTest {
};
};
# The hive's CA, and one leaf for the queue's and the identity
# provider's names, which this test makes. The trust bundle is the unit
# `hive-tls-ca`'s, and the store's services-root unit reloads that unit
# when it has fetched the store's root, so the test's own script is the
# one the unit runs on every reload.
# The hive's CA, and one leaf for the names of the queue, the identity
# provider, the forge and the collector, which this test makes. The trust
# bundle is the unit `hive-tls-ca`'s, and the store's services-root unit
# reloads that unit when it has fetched the store's root, so the test's
# own script is the one the unit runs on every reload.
systemd.services.hive-tls-ca = {
path = [
pkgs.openssl
@ -204,7 +286,7 @@ pkgs.testers.runNixOSTest {
-subj "/CN=test-ca" -days 3650 \
-addext basicConstraints=critical,CA:TRUE -addext keyUsage=critical,keyCertSign
openssl req -newkey rsa:2048 -nodes -keyout svc-key.pem -out svc.csr -subj "/CN=${natsName}"
printf 'subjectAltName=DNS:${natsName},DNS:${authName}\n' > svc.ext
printf 'subjectAltName=DNS:${natsName},DNS:${authName},DNS:${forgeName},DNS:${otelName}\n' > svc.ext
openssl x509 -req -in svc.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial \
-days 3650 -extfile svc.ext -out svc.pem
chmod 0644 ca.pem svc.pem svc-key.pem
@ -289,6 +371,12 @@ pkgs.testers.runNixOSTest {
STT = "${stt}"
STT_HOST_UNIT = "${sttHostUnit}"
STT_PRUNE = "${sttPrune}"
CI = "${ci}"
CI_PRUNE = "${ciPrune}"
CI_HOST_UNITS = ["${ci}.timer", "${ci}.service"]
OWN_ROUTE = "/${ci}/v1/metrics"
RUN_METRIC = "hyperhive.ci.run.duration"
CERT_METRIC = "bao.client_cert.not_after"
MANIFESTS = "/var/lib/rancher/k3s/server/manifests"
NATS = "--server tls://${natsName}:${toString natsPort} --tlsca ${pkiDir}/ca.pem"
AGENT = "${agent}"
@ -326,6 +414,34 @@ 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]
def pushes(metric: str) -> list[dict]:
"""The collector requests that carried points of `metric`."""
return [r for r in requests() if r.get("points", {}).get(metric)]
def ci_job(name: str) -> str:
"""Runs one Job from the poller's CronJob, waits for it to complete, and
answers its pod's log."""
kube(machine, f"create job {name} --from=cronjob/{CI}")
try:
kube(machine, f"wait --for=condition=complete job/{name} --timeout=300s", timeout=330)
except Exception:
print(machine.execute(f"kubectl -n {NS} describe job {name}")[1])
print(machine.execute(f"kubectl -n {NS} logs job/{name} --tail=80")[1])
raise
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"))
@ -364,7 +480,7 @@ pkgs.testers.runNixOSTest {
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, f"{PRUNE}.service", f"{STT_PRUNE}.service", "hyperhive-k8s-ca-trust.service", "k3s.service"]
ours = [HOST_UNIT, STT_HOST_UNIT, *CI_HOST_UNITS, f"{PRUNE}.service", f"{STT_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
@ -394,7 +510,7 @@ pkgs.testers.runNixOSTest {
timeout=300,
)
with subtest("the granting units have written the policies and roles of the router and the speech-to-text service, and the jwt mount"):
with subtest("the granting units have written the policies and roles of the router, the speech-to-text service and the poller, and the jwt mount"):
machine.succeed("systemctl reset-failed 'swarm-bao-*-policy.service' swarm-bao-agent-pki.service || true")
machine.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"])
@ -405,7 +521,7 @@ pkgs.testers.runNixOSTest {
machine.wait_until_succeeds('[ "$(bao status >/dev/null 2>&1; echo $?)" = 2 ]', timeout=900)
machine.succeed(f"bao operator unseal \"$(jq -r '.unseal_keys_b64[0]' {INIT})\"")
machine.wait_until_succeeds("bao status", timeout=120)
for unit in ["swarm-bao-notify-router-policy", "swarm-bao-stt-policy", "swarm-bao-k8s-jwt-policy"]:
for unit in ["swarm-bao-notify-router-policy", "swarm-bao-stt-policy", "swarm-bao-ci-metrics-policy", "swarm-bao-k8s-jwt-policy"]:
settle(f'[ "$(systemctl is-active {unit}.service)" = active ]', 900, [f"{unit}.service"])
machine.wait_until_succeeds(
"journalctl -u swarm-bao-k8s-jwt-policy --no-pager | grep -F 'Success! Data written to: auth/jwt-k8s/config'",
@ -417,6 +533,11 @@ pkgs.testers.runNixOSTest {
as_root(f"bao kv put -mount=secret ${leaf} value={SECRET}")
STT_SECRET = machine.succeed("openssl rand -hex 16").strip()
as_root(f"bao kv put -mount=secret ${sttLeaf} value={STT_SECRET}")
# The poller reads its own client secret and the forge token the
# controller mints in production.
CI_SECRET = machine.succeed("openssl rand -hex 16").strip()
as_root(f"bao kv put -mount=secret ${ciLeaf} value={CI_SECRET}")
as_root("bao kv put -mount=secret ${ciForgeLeaf} value=${forgeToken} name=ci-metrics")
with subtest("the queue and the token stub run, and the queue holds the roster the router reads"):
machine.wait_for_unit("hive-tls-ca.service")
@ -442,6 +563,27 @@ pkgs.testers.runNixOSTest {
# nothing from the cluster.
assert machine.succeed(f"systemctl is-active {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 HOST_UNIT in out and STT_HOST_UNIT in out and "stopping the following units" in out, out
@ -458,6 +600,18 @@ pkgs.testers.runNixOSTest {
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 host published the CA files, which are the hive's"):
trust = machine.succeed(f"kubectl -n {NS} get configmap hyperhive-ca-trust -o json")
data = json.loads(trust)["data"]
@ -506,6 +660,61 @@ pkgs.testers.runNixOSTest {
mounts = json.loads(kube(machine, f"get pod {stt_pod} -o json"))["spec"]["containers"][0]["volumeMounts"]
assert any(m["name"] == "state" and m["mountPath"] == "/var/lib/swarm-stt" for m in mounts), mounts
with subtest("the poller's Job completes against the forge and pushes the run to the poller's own route with a token the identity provider minted"):
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 {r["path"] for r in requests() if "points" in r} == {OWN_ROUTE}, requests()
assert len(pushes(CERT_METRIC)) == HOST_CERT_PUSHES >= 1, requests()
# The pod read the forge token and its client secret from the store,
# and reached the forge and the identity provider by name.
forge = [r for r in requests() if "forge_token_ok" in r]
assert len(forge) >= 4, 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)
with subtest("the poller's pod keeps the route its unit names, holds no Secret, and gets the store's CA from the ConfigMap"):
ci_pod = json.loads(kube(machine, f"get pods --selector job-name={CI}-first -o json"))["items"][0]
spec = ci_pod["spec"]
env = {e["name"]: e.get("value") for e in spec["containers"][0]["env"]}
assert env["SWARM_CI_METRICS_OTLP_ENDPOINT"] == "https://${otelName}/${ci}", env
assert "OTEL_EXPORTER_OTLP_ENDPOINT" not in env, env
assert env["BAO_AUTH"] == "jwt" and env["BAO_JWT_ROLE"] == CI, env
assert "BAO_CLIENT_CERT" not in env and "BAO_CLIENT_KEY" not in env, env
creds = next(v for v in spec["volumes"] if v["name"] == "credentials")
sources = creds["projected"]["sources"]
assert [src["configMap"]["name"] for src in sources] == ["hyperhive-ca-trust"], sources
assert [(i["key"], i["path"]) for i in sources[0]["configMap"]["items"]] == [("bao-server-ca.pem", "bao-ca.pem")], sources
assert not any("secret" in v or any("secret" in src for src in v.get("projected", {}).get("sources", [])) for v in spec["volumes"]), spec["volumes"]
assert machine.succeed(f"kubectl -n {NS} get secrets -o name || true").strip() == ""
# The control that the lookup finds the variable: the router's pod sets
# it, and the poller's does not.
router_env = {e["name"]: e.get("value") for e in json.loads(kube(machine, f"get pod {router} -o json"))["spec"]["containers"][0]["env"]}
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"))
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()
# The pass ran: it listed the forge again.
assert len(requests()) > seen, requests()
with subtest("the pod routes a forge event: the agent's todo is queued and the event acknowledged"):
event = json.dumps({
"action": "assigned",
@ -571,6 +780,33 @@ pkgs.testers.runNixOSTest {
started = int(machine.succeed(f"systemctl show -p InactiveExitTimestampMonotonic --value {HOST_UNIT}"))
assert 0 < pruned <= started, (pruned, started)
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)
@ -585,12 +821,20 @@ pkgs.testers.runNixOSTest {
wait_pod_ready(STT)
claim = json.loads(kube(machine, f"get pvc {STT}-state -o json"))
assert claim["status"]["phase"] == "Bound" and claim["metadata"]["uid"] == CACHE_VOLUME, claim
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):
for svc in (SERVICE, STT, CI):
samples = [
(fields[2].removeprefix("host="), int(fields[3].removeprefix("pods=")))
for fields in (line.split() for line in lines)