Watch
0
0
Fork
You've already forked hyperhive
0

run the metrics store and its auth responders as pods

This commit is contained in:
atlas 2026-11-27 09:11:27 +01:00 • committed by maia
commit 681426b53b

View file

@ -11,12 +11,12 @@
# speech-to-text pod carries its limits and keeps its cache in an emptyDir,
# with no claim and no state gate, in a user namespace, and its NetworkPolicy
# lets a queue request in and only DNS and four host ports out;
# - the log store runs as a pod on the directory its old container kept, which
# a unit of this test filled before the cluster started, as another user: the
# pod reads that record and writes a new one, the gateway's own locations
# (rendered by the module, run in a nginx of their own) reach the store and the
# responders by their Services' names, a bearer is granted or refused by the
# responders with the store's answers, and no other pod reaches the store;
# - the log and metrics stores run as pods on the directories their old
# containers kept, which units of this test filled as other users: each pod
# reads that record and writes a new one, the gateway's own locations
# (rendered by the modules) reach the stores and the responders, bearers are
# granted or refused as the store says, the metrics gateway refuses the
# store's write and admin routes, and no other pod reaches either store;
# - the poller's Job completes against a forge that lists one run, pushes it to
# its own route of the swarm collector, holds no Secret, and keeps its cursor
# in a volume, so a second Job pushes nothing, and starts with no state
@ -81,15 +81,33 @@ let
legacyUser = "legacy-victorialogs";
legacyPort = 19428;
# One nginx with the log store's locations as the module renders them: the
# Services they dial, the responders they check a bearer with and the
# variables between. The identity provider's two checks are stand-ins that
# answer 200, because the VM has no login service; nothing else of the vhost.
# The metrics store, as the module names it.
vmDir = "/var/lib/nixos-containers/swarm-victoriametrics/var/lib/victoriametrics";
vmGateway = "127.0.0.1:18082";
legacyVmUser = "legacy-victoriametrics";
legacyVmPort = 19429;
# One nginx with the log and metrics stores' locations as the modules render
# them: the Services they dial, the responders they check a bearer with and
# the variables between. The identity provider's checks are stand-ins that
# answer 200, because the VM has no login service; nothing else of the vhosts.
gatewayConf =
cfg:
let
locations = cfg.services.nginx.virtualHosts."logs.t.local".locations;
served = [
block =
locations: name:
let
l = locations.${name};
in
''
location ${name} {
${lib.optionalString (l.proxyPass != null) "proxy_pass ${l.proxyPass};"}
${lib.optionalString (l.return != null) "return ${l.return};"}
${l.extraConfig}
}
'';
logs = cfg.services.nginx.virtualHosts."logs.t.local".locations;
logsServed = [
"= /insert/opentelemetry/v1/logs"
"^~ /select/logsql/"
"= /metrics"
@ -97,19 +115,18 @@ let
"= /__swarm_logs_agent_auth"
"= /__swarm_logs_grafana_auth"
];
block =
name:
let
l = locations.${name};
in
''
location ${name} {
${lib.optionalString (l.proxyPass != null) "proxy_pass ${l.proxyPass};"}
${l.extraConfig}
}
'';
# Every location of the vhost but the two that dial the identity
# provider, so a location the module adds is served here too.
metrics = cfg.services.nginx.virtualHosts."metrics.t.local".locations;
metricsServed = lib.filter (
n:
!(lib.elem n [
"= /__metrics_authelia"
"= /__metrics_ingest_authz"
])
) (lib.attrNames metrics);
in
pkgs.writeText "logs-gateway.conf" ''
pkgs.writeText "gateway.conf" ''
pid /run/logs-gateway-test/nginx.pid;
error_log stderr;
events {}
@ -120,7 +137,13 @@ let
listen ${vlGateway};
location = /__swarm_logs_ingest_authz { internal; return 200; }
location = /__hive_authelia { internal; return 200; }
${lib.concatMapStrings block served}
${lib.concatMapStrings (block logs) logsServed}
}
server {
listen ${vmGateway};
location = /__metrics_ingest_authz { internal; return 200; }
location = /__metrics_authelia { internal; return 200; }
${lib.concatMapStrings (block metrics) metricsServed}
}
}
'';
@ -251,6 +274,7 @@ pkgs.testers.runNixOSTest {
deploy.stt.settings.modelFile = sttModel;
deploy.ci-metrics.enable = true;
deploy.victorialogs.enable = true;
deploy.victoriametrics.enable = true;
deploy.hive-controller.hiveName = "h1";
swarm.domain = "t.local";
swarm.forge.domain = forgeName;
@ -418,7 +442,70 @@ pkgs.testers.runNixOSTest {
'';
};
# The log store's locations, from the active configuration's own text.
# What the metrics store's container left on the host: the directory the
# same way, holding one sample.
users.users.${legacyVmUser} = {
isSystemUser = true;
group = legacyVmUser;
};
users.groups.${legacyVmUser} = { };
systemd.services.victoriametrics-legacy = {
wantedBy = [ "multi-user.target" ];
before = [ "k3s.service" ];
path = [
pkgs.curl
pkgs.coreutils
pkgs.findutils
pkgs.gnugrep
];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
User = legacyVmUser;
# k3s waits for this unit, so a sample that never shows must fail it
# and not hold the boot.
TimeoutStartSec = 120;
UMask = "0007";
ExecStartPre = "+${pkgs.writeShellScript "victoriametrics-legacy-dir" ''
mkdir -p ${vmDir}
chown ${legacyVmUser}:${legacyVmUser} ${vmDir}
chmod 0700 ${vmDir}
''}";
};
script = ''
store=http://127.0.0.1:${toString legacyVmPort}
${config.services.hyperhive.deploy.victoriametrics.package}/bin/victoria-metrics \
-storageDataPath=${vmDir} -httpListenAddr=127.0.0.1:${toString legacyVmPort} -retentionPeriod=5y &
pid=$!
until curl -sf $store/health; do sleep 1; done
# One line of the text exposition format. Without a content type curl
# sends a form body, which a route may read as form fields and ingest
# nothing with a 200.
code=$(printf '%s\n' 'written_before_the_switch{app="legacy"} 42' | curl -s -o /dev/null -w '%{http_code}' \
-H 'Content-Type: text/plain' --data-binary @- $store/api/v1/import/prometheus)
curl -s -o /dev/null $store/internal/force_flush
found=
for _ in $(seq 60); do
if curl -s $store/api/v1/export --data-urlencode 'match[]=written_before_the_switch' | grep -q written_before_the_switch; then
found=1
break
fi
sleep 1
done
if [ -z "$found" ]; then
echo "the seeded sample is not found; the import replied $code; the store's ingest counters:"
curl -s $store/metrics | grep -E '^vm_(rows_inserted_total|rows_ignored_total|http_request_errors_total)'
echo "the store holds:"
curl -s $store/api/v1/export --data-urlencode 'match[]={__name__!=""}'
exit 1
fi
kill -TERM "$pid"
wait "$pid" || true
test -n "$(find ${vmDir} -type f | head -1)"
'';
};
# The log and metrics stores' locations, from the active configuration's own text.
systemd.services.logs-gateway = {
wantedBy = [ "multi-user.target" ];
after = [ "network.target" ];
@ -523,11 +610,16 @@ pkgs.testers.runNixOSTest {
NATS = "--server tls://${natsName}:${toString natsPort} --tlsca ${pkiDir}/ca.pem"
AGENT = "${agent}"
OTHER_AGENT = "argus"
LOGS_ONLY_AGENT = "scout"
AGENT_SECRETS: dict[str, str] = {}
VL = "swarm-victorialogs"
LOGS_AUTH = "swarm-logs-auth"
VL_DIR = "${vlDir}"
GATEWAY = "http://${vlGateway}"
VM = "swarm-victoriametrics"
METRICS_AUTH = "swarm-metrics-auth"
VM_DIR = "${vmDir}"
METRICS_GATEWAY = "http://${vmGateway}"
SELECTOR = f"--selector app.kubernetes.io/name={SERVICE}"
@ -666,10 +758,15 @@ pkgs.testers.runNixOSTest {
as_root(f"bao kv put -mount=secret ${classifierLeaf} value={CLASSIFIER_SECRET}")
LOGIN_SECRET = machine.succeed("openssl rand -hex 16").strip()
as_root(f"bao kv put -mount=secret ${loginLeaf} value={LOGIN_SECRET}")
# What the log store's responders read: an agent's queue secret and its
# mirrored grant, one agent that holds no grant, and the bearer
# Grafana's host creates. The grant is a JSON object, so it is a file.
for name, grant in ((AGENT, '{"logs": true}'), (OTHER_AGENT, '{"logs": false}')):
# What the log and metrics stores' responders read: an agent's queue
# secret and its mirrored grant, one agent that holds no grant, one that
# holds the logs grant alone, and the bearer Grafana's host creates. The
# grant is a JSON object, so it is a file.
for name, grant in (
(AGENT, '{"logs": true, "metrics": true}'),
(OTHER_AGENT, '{"logs": false, "metrics": false}'),
(LOGS_ONLY_AGENT, '{"logs": true, "metrics": false}'),
):
AGENT_SECRETS[name] = machine.succeed("openssl rand -hex 16").strip()
as_root(f"bao kv put -mount=secret swarm/agents/{name}/queue value={AGENT_SECRETS[name]} agent={name}")
machine.succeed(f"echo '{grant}' > /tmp/grant-{name}.json")
@ -720,11 +817,20 @@ pkgs.testers.runNixOSTest {
assert machine.succeed(f"kubectl -n {NS} get secrets -o name || true").strip() == ""
with subtest("a changed CA file is published again with no manual step"):
machine.succeed("echo '# refreshed' >> ${tlsDir}/trust-bundle.pem")
machine.wait_until_succeeds(
f"kubectl -n {NS} get configmap hyperhive-ca-trust -o jsonpath='{{.data.trust-bundle\\.pem}}' | grep -q refreshed",
timeout=120,
)
# `swarm-services-cert` rewrites the trust bundle once, when the store first
# answers it, and that can fall inside this wait. A line the rewrite drops
# is appended again, each time with a marker of its own.
deadline = time.monotonic() + 120
attempt = 0
while True:
attempt += 1
machine.succeed(f"echo '# refreshed {attempt}' >> ${tlsDir}/trust-bundle.pem")
published, _ = machine.execute(
f"for _ in $(seq 20); do kubectl -n {NS} get configmap hyperhive-ca-trust -o jsonpath='{{.data.trust-bundle\\.pem}}' | grep -q 'refreshed {attempt}' && exit 0; sleep 1; done; exit 1"
)
if published == 0:
break
assert time.monotonic() < deadline, f"the trust bundle's {attempt} refreshes were not published"
with subtest("the pod logged in to the store, read the client secret, and minted a token with it"):
machine.wait_until_succeeds(f"grep -F '/api/oidc/token ${clientId}:{SECRET}' ${tokenLog}", timeout=120)
@ -862,7 +968,7 @@ pkgs.testers.runNixOSTest {
def vl_query(token: str, text: str) -> tuple[int, str]:
return vl_request("/select/logsql/query", token, f"--data-urlencode 'query={text}'")
def gateway_diagnostics(token: str) -> None:
def gateway_diagnostics(token: str, responders: str = LOGS_AUTH) -> None:
"""What to read when the gateway refuses a bearer for good: the
responders' logs, the gateway's own, the claims of the account token
the responder logs in with, that login and the credential it reads,
@ -874,17 +980,17 @@ pkgs.testers.runNixOSTest {
print(machine.execute(f"{command} 2>&1")[1])
print("=== gateway diagnostics")
for pod in service_pods(LOGS_AUTH):
for pod in service_pods(responders):
show(f"{pod} logs", f"kubectl -n {NS} logs {pod} --all-containers --tail=100")
show(f"{pod} previous logs", f"kubectl -n {NS} logs {pod} --all-containers --previous --tail=100")
show("gateway nginx", "journalctl -u logs-gateway --no-pager -n 100")
sa_token = machine.execute(f"kubectl -n {NS} create token {LOGS_AUTH} --audience bao --duration 10m")[1].strip()
sa_token = machine.execute(f"kubectl -n {NS} create token {responders} --audience bao --duration 10m")[1].strip()
parts = sa_token.split(".")
if len(parts) == 3:
for name, part in zip(("header", "claims"), parts[:2]):
print(f"--- account token {name}")
print(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4)).decode(errors="replace"))
body = json.dumps({"jwt": sa_token, "role": LOGS_AUTH})
body = json.dumps({"jwt": sa_token, "role": responders})
show(
"login as the responder's role",
f"curl -sS -m 20 --cacert /var/lib/swarm-bao-pki/ca.pem -X POST -d '{body}' "
@ -893,13 +999,13 @@ pkgs.testers.runNixOSTest {
else:
print(f"--- account token: {sa_token}")
show("jwt mount config", f"BAO_TOKEN=\"$(jq -r .root_token {INIT})\" bao read -format=json auth/jwt-k8s/config")
show("responder's role", f"BAO_TOKEN=\"$(jq -r .root_token {INIT})\" bao read -format=json auth/jwt-k8s/role/{LOGS_AUTH}")
show("responder's role", f"BAO_TOKEN=\"$(jq -r .root_token {INIT})\" bao read -format=json auth/jwt-k8s/role/{responders}")
show("agent's queue credential names", f"BAO_TOKEN=\"$(jq -r .root_token {INIT})\" bao kv get -mount=secret -format=json swarm/agents/{AGENT}/queue | jq -c '.data.data | keys'")
show("responder service", f"kubectl -n {NS} get svc,endpoints {LOGS_AUTH} -o wide")
show("responder service", f"kubectl -n {NS} get svc,endpoints {responders} -o wide")
show("grafana bearer credential names", f"BAO_TOKEN=\"$(jq -r .root_token {INIT})\" bao kv get -mount=secret -format=json swarm/services/swarm-grafana/metrics/bearer | jq -c '.data.data | keys'")
show(
"each responder port asked directly",
f"pod=$(kubectl -n {NS} get pods --selector app.kubernetes.io/name={LOGS_AUTH} -o name | head -1); ip=$(kubectl -n {NS} get $pod -o jsonpath='{{.status.podIP}}'); "
f"pod=$(kubectl -n {NS} get pods --selector app.kubernetes.io/name={responders} -o name | head -1); ip=$(kubectl -n {NS} get $pod -o jsonpath='{{.status.podIP}}'); "
f"for port in $(kubectl -n {NS} get $pod -o jsonpath='{{.spec.containers[*].ports[*].containerPort}}'); do "
f"echo \"port $port\"; curl -sS -m 20 -w '\\nstatus %{{http_code}}\\n' -H 'Authorization: Bearer {token}' http://$ip:$port/; done",
)
@ -1082,6 +1188,184 @@ pkgs.testers.runNixOSTest {
machine.wait_until_fails(dial(router_ip, 8080), timeout=120)
assert machine.execute(dial(router_ip, 8080))[0] != 0, source
with subtest("the metrics store and its responders run only as pods: the host has no container, unit, timer or socket directory for them"):
machine.fail("test -e /etc/nixos-containers/swarm-victoriametrics.conf")
assert host_state("container@swarm-victoriametrics.service") == "inactive"
for unit in ("swarm-metrics-auth", "swarm-metrics-agent-auth", "swarm-victoriametrics-forwarder-oidc"):
machine.fail(f"systemctl cat {unit}.service")
machine.fail("systemctl cat swarm-victoriametrics-forwarder-oidc.timer")
machine.fail("test -e /run/swarm-victoriametrics")
machine.fail("test -e /run/swarm-victoriametrics-egress")
# 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 (VM, METRICS_AUTH):
machine.succeed(f"test -L {MANIFESTS}/{name}.yaml")
vm_pod = wait_pod_ready(VM)
metrics_auth_pod = wait_pod_ready(METRICS_AUTH)
assert machine.execute("machinectl list --no-legend | grep -q swarm-victoriametrics")[0] != 0
with subtest("the metrics store's volume is the old container's directory, whose files keep the user that wrote them, whose tree the pod's group owns, and the pod passed its startup probe"):
pv = json.loads(kube(machine, f"get pv {VM}-store -o json"))
assert pv["spec"]["local"]["path"] == VM_DIR and pv["status"]["phase"] == "Bound", pv
pvc = json.loads(kube(machine, f"get pvc {VM}-store -o json"))
assert pvc["status"]["phase"] == "Bound" and pvc["spec"]["volumeName"] == pv["metadata"]["name"], pvc
assert machine.succeed(f"stat -c %g {VM_DIR}").strip() == "65532"
assert machine.succeed(f"find {VM_DIR} -type f -user ${legacyVmUser} | head -1").strip() != ""
status = json.loads(kube(machine, f"get pod {vm_pod} -o json"))
assert status["spec"]["containers"][0]["startupProbe"]["failureThreshold"] == 60, status["spec"]
container = status["status"]["containerStatuses"][0]
assert container["started"] and container["ready"] and container["restartCount"] == 0, container
def vm_request(path: str, token: str | None, *args: str) -> tuple[int, str]:
"""One request to the metrics gateway's locations: the status and the body."""
auth = f"-H 'Authorization: Bearer {token}' " if token else ""
_, out = machine.execute(f"curl -sS --max-time 20 -w '\\n%{{http_code}}' {auth}{' '.join(args)} {METRICS_GATEWAY}{path}")
body, _, code = out.rpartition("\n")
return int(code or 0), body
def vm_export(token: str, name: str) -> tuple[int, str]:
"""The series of one metric name, through the read API's export route,
which no query offset hides recent samples from."""
return vm_request("/api/v1/export", token, f"--data-urlencode 'match[]={{__name__=~\"{name}.*\"}}'")
def wait_for_series(token: str, name: str) -> None:
"""Exports until the response holds the series, for as long as the pod
and the policy engine take to settle."""
deadline = time.monotonic() + 300
while True:
status, body = vm_export(token, name)
if status == 200 and name in body:
return
if time.monotonic() >= deadline:
metrics_diagnostics(token)
raise AssertionError((status, body))
time.sleep(3)
def metrics_diagnostics(token: str) -> None:
"""What to read when the metrics gateway answers a bearer something
other than what the store grants: the gateway's diagnostics, the store's
own logs, both responders' Services and endpoints, and each responder
asked directly with every bearer the test uses."""
gateway_diagnostics(token, METRICS_AUTH)
print("=== metrics store diagnostics")
for pod in service_pods(VM):
print(f"--- {pod} logs")
print(machine.execute(f"kubectl -n {NS} logs {pod} --tail=100 2>&1")[1])
print(f"--- {pod} previous logs")
print(machine.execute(f"kubectl -n {NS} logs {pod} --previous --tail=100 2>&1")[1])
print("--- services and endpoints")
print(machine.execute(f"kubectl -n {NS} get svc,endpoints {VM} {METRICS_AUTH} swarm-metrics-grafana-auth -o wide 2>&1")[1])
print("--- the store's counters of the push route, through the gateway")
_, body = vm_request("/metrics", None)
print("\n".join(line for line in body.splitlines() if "opentelemetry" in line and not line.startswith("#")))
if machine.execute("test -f /tmp/otlp-metrics.bin")[0] == 0:
vm_ip = kube(machine, f"get pods --selector app.kubernetes.io/name={VM} -o jsonpath='{{.items[0].status.podIP}}'").strip()
print("--- the same request, sent to the store's pod directly")
print(
machine.execute(
f"curl -sS -m 10 -w '\\nstatus %{{http_code}}\\n' -X POST -H 'Content-Type: application/x-protobuf' --data-binary @/tmp/otlp-metrics.bin http://{vm_ip}:8428/opentelemetry/api/v1/push 2>&1; "
f"curl -s http://{vm_ip}:8428/metrics | grep opentelemetry | grep -v '^#'"
)[1]
)
bearers = {
"agent": AGENT_TOKEN,
"agent without the grant": f"swarm-agent.{OTHER_AGENT}.{AGENT_SECRETS[OTHER_AGENT]}",
"agent with the logs grant only": f"swarm-agent.{LOGS_ONLY_AGENT}.{AGENT_SECRETS[LOGS_ONLY_AGENT]}",
"Grafana": GRAFANA_BEARER,
}
ip = kube(machine, f"get pods --selector app.kubernetes.io/name={METRICS_AUTH} -o jsonpath='{{.items[0].status.podIP}}'").strip()
for port in (8083, 8084):
for who, bearer in bearers.items():
print(
f"--- port {port}, {who}: "
+ machine.execute(f"curl -sS -m 10 -o /dev/null -w '%{{http_code}}' -H 'Authorization: Bearer {bearer}' http://{ip}:{port}/ 2>&1")[1]
)
def metrics_expect(label: str, got: int, want: int, token: str = "") -> None:
if got != want:
metrics_diagnostics(token or AGENT_TOKEN)
raise AssertionError(f"{label}: the gateway answered {got}, wanted {want}")
with subtest("an agent's bearer reads the sample written before the switch through the gateway, and the other bearers are granted or refused as the store says"):
wait_for_series(AGENT_TOKEN, "written_before_the_switch")
# Each responder's Service reaches its own container: the endpoint port is
# the container's, and the two differ.
for responder, port in ((METRICS_AUTH, "8083"), ("swarm-metrics-grafana-auth", "8084")):
assert machine.succeed(f"kubectl -n {NS} get endpoints {responder} -o jsonpath='{{.subsets[0].ports[0].port}}'").strip() == port, responder
# Each refusal has the answer above as its control: the same request with
# a bearer the store grants.
metrics_expect("an agent without the grant", vm_export(f"swarm-agent.{OTHER_AGENT}.{AGENT_SECRETS[OTHER_AGENT]}", "written_before_the_switch")[0], 403)
metrics_expect("a wrong agent secret", vm_export(f"swarm-agent.{AGENT}.{'0' * 32}", "written_before_the_switch")[0], 401)
# The surfaces are separate grants: this agent may read the log store and not the metrics store.
scout = f"swarm-agent.{LOGS_ONLY_AGENT}.{AGENT_SECRETS[LOGS_ONLY_AGENT]}"
metrics_expect("an agent with the logs grant only, on the metrics store", vm_export(scout, "written_before_the_switch")[0], 403)
metrics_expect("the same agent, on the log store", vl_query(scout, "switch")[0], 200)
# Grafana's bearer goes to the second responder of the same pod.
status, body = vm_export(GRAFANA_BEARER, "written_before_the_switch")
if status != 200 or "written_before_the_switch" not in body:
metrics_diagnostics(GRAFANA_BEARER)
raise AssertionError((status, body))
metrics_expect("a wrong Grafana bearer", vm_export("0" * 64, "written_before_the_switch")[0], 401)
with subtest("the gateway refuses the store's write and admin routes with a bearer that reads, and a sample pushed to the ingest route and the store's own metrics come through it, and a restarted pod still holds both samples"):
import base64
import struct
# The store serves these on the listener its queries use and
# authenticates none of them; only the locations the module names reach it.
for path in ("/api/v1/admin/tsdb/delete_series", "/api/v1/import/prometheus"):
metrics_expect(path, vm_request(path, GRAFANA_BEARER, "-X POST --data-binary 'x 1'")[0], 403)
metrics_expect("the store's export route, as the control for the refusals above", vm_export(GRAFANA_BEARER, "written_before_the_switch")[0], 200)
def varint(n: int) -> bytes:
out = b""
while n > 0x7F:
out += bytes([n & 0x7F | 0x80])
n >>= 7
return out + bytes([n])
def field(number: int, payload: bytes) -> bytes:
return varint(number << 3 | 2) + varint(len(payload)) + payload
# An OTLP metrics request with one gauge point: the name (field 1), a
# gauge (field 5) of one point with its time (field 3, fixed64) and
# value (field 4, double).
now_ns = int(machine.succeed("date +%s%N"))
point = varint(3 << 3 | 1) + now_ns.to_bytes(8, "little") + varint(4 << 3 | 1) + struct.pack("<d", 7.0)
metric = field(1, b"written_through_the_gateway") + field(5, field(1, point))
request = field(1, field(2, field(2, metric)))
machine.succeed(f"echo {base64.b64encode(request).decode()} | base64 -d > /tmp/otlp-metrics.bin")
status, body = vm_request(
"/opentelemetry/api/v1/push", None, "-X POST -H 'Content-Type: application/x-protobuf' --data-binary @/tmp/otlp-metrics.bin"
)
metrics_expect("the ingest route", status, 200)
# The sample's arrival is what counts: the series is read back below, and
# the store's counters are printed if it never shows.
wait_for_series(AGENT_TOKEN, "written_through_the_gateway")
kube(machine, f"delete pod {vm_pod} --wait=true", timeout=120)
vm_pod = wait_pod_ready(VM)
wait_for_series(AGENT_TOKEN, "written_before_the_switch")
wait_for_series(AGENT_TOKEN, "written_through_the_gateway")
with subtest("only the node reaches the metrics store's pods, and the responders' pod reaches the store's pod listener and no other port of the host"):
vm_ip = kube(machine, f"get pod {vm_pod} -o jsonpath='{{.status.podIP}}'").strip()
metrics_auth_ip = kube(machine, f"get pod {metrics_auth_pod} -o jsonpath='{{.status.podIP}}'").strip()
machine.succeed(f"curl -sf --max-time 5 http://{vm_ip}:8428/health")
# The peer pod can dial out, which is the control that the dials below
# are refused by the stores' policies.
machine.succeed(dials(router_pid, "${bridgeIp}", 9999))
for ip, port in ((vm_ip, 8428), (metrics_auth_ip, 8083), (metrics_auth_ip, 8084)):
machine.succeed(f"timeout 5 bash -c '</dev/tcp/{ip}/{port}'")
machine.wait_until_fails(dials(router_pid, ip, port), timeout=60)
for _ in range(3):
assert machine.execute(dials(router_pid, ip, port))[0] != 0
metrics_auth_pid = pod_pid(METRICS_AUTH)
machine.succeed(dials(metrics_auth_pid, "${bridgeIp}", ${toString podPort}))
machine.wait_until_fails(dials(metrics_auth_pid, "${bridgeIp}", 9999), timeout=60)
for name in (vm_pod, metrics_auth_pod):
status = json.loads(kube(machine, f"get pod {name} -o json"))["status"]
assert all(c["ready"] for c in status["containerStatuses"]), status
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")