From 87567f427ec7ceb035949fa88ab26f1ab21b0f91 Mon Sep 17 00:00:00 2001 From: atlas Date: Thu, 26 Nov 2026 20:41:57 +0100 Subject: [PATCH] k8s-services: seed with the stream content type, give the grafana responder its own port name, and print gateway diagnostics on a refusal the grafana responder's service targeted the port name api, which resolves to the logs responder's container; its port is now grafana-api. the node-ready wait is raised from 300 to 600 seconds: slow k3s image imports on this test's machine kept the node from registering in vm-nightly 8992 and 8997, so the test never reached the subtests this change fixes. --- nix/host-modules/swarm-victorialogs.nix | 6 +- nix/module-eval/k8s.nix | 1 + nix/vm-tests/k8s-services.nix | 80 ++++++++++++++++++++++--- 3 files changed, 77 insertions(+), 10 deletions(-) diff --git a/nix/host-modules/swarm-victorialogs.nix b/nix/host-modules/swarm-victorialogs.nix index dbe758c95..2651fe28a 100644 --- a/nix/host-modules/swarm-victorialogs.nix +++ b/nix/host-modules/swarm-victorialogs.nix @@ -215,9 +215,11 @@ let SWARM_METRICS_AUTH_HEALTH_ADDR = "0.0.0.0:${toString grafanaAuthHealthPort}"; } ); + # Not `api`: a Service resolves a named port to the first container of the + # pod that declares the name, which is the logs responder's. ports = [ { - name = "api"; + name = "grafana-api"; containerPort = grafanaAuthPort; } { @@ -255,7 +257,7 @@ let name = "api"; protocol = "TCP"; port = grafanaAuthPort; - targetPort = "api"; + targetPort = "grafana-api"; } ]; }; diff --git a/nix/module-eval/k8s.nix b/nix/module-eval/k8s.nix index 367ca7b89..c4b93671a 100644 --- a/nix/module-eval/k8s.nix +++ b/nix/module-eval/k8s.nix @@ -2101,6 +2101,7 @@ let ] && (service "swarm-logs-grafana-auth/service").selector == podLabels && (lib.head (service "swarm-logs-grafana-auth/service").ports).port == 8082 + && (lib.head (service "swarm-logs-grafana-auth/service").ports).targetPort == "grafana-api" # One policy: nothing in but the node, and out to DNS and the store's pod # listener alone. The sibling's policy has no egress. && diff --git a/nix/vm-tests/k8s-services.nix b/nix/vm-tests/k8s-services.nix index b2db2629d..4b81dea3d 100644 --- a/nix/vm-tests/k8s-services.nix +++ b/nix/vm-tests/k8s-services.nix @@ -388,12 +388,26 @@ pkgs.testers.runNixOSTest { -storageDataPath=${vlDir} -httpListenAddr=127.0.0.1:${toString legacyPort} & pid=$! until curl -sf http://127.0.0.1:${toString legacyPort}/health; do sleep 1; done - curl -sf --data-binary \ - "{\"_msg\":\"written before the switch\",\"app\":\"legacy\",\"_time\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}" \ - 'http://127.0.0.1:${toString legacyPort}/insert/jsonline?_stream_fields=app' + # One JSON line. Without the stream content type curl sends a form body, which the store reads as form fields and ingests zero rows with a 200. + line=$(printf '{"_msg":"written before the switch","app":"legacy","_time":"%s"}' "$(date -u +%Y-%m-%dT%H:%M:%SZ)") + code=$(printf '%s\n' "$line" | curl -s -o /dev/null -w '%{http_code}' -H 'Content-Type: application/stream+json' --data-binary @- \ + 'http://127.0.0.1:${toString legacyPort}/insert/jsonline?_stream_fields=app') # A bare word matches the message field, so the query names a word of it. - until curl -s --data-urlencode 'query=switch' http://127.0.0.1:${toString legacyPort}/select/logsql/query \ - | grep -q 'written before the switch'; do sleep 1; done + found= + for _ in $(seq 60); do + if curl -s --data-urlencode 'query=switch' http://127.0.0.1:${toString legacyPort}/select/logsql/query | grep -q 'written before the switch'; then + found=1 + break + fi + sleep 1 + done + if [ -z "$found" ]; then + echo "the seeded record is not found; posted $line, insert replied $code; the store's ingest counters:" + curl -s http://127.0.0.1:${toString legacyPort}/metrics | grep -E '^vl_(rows_ingested|rows_dropped|http_errors)' + echo "the store holds:" + curl -s --data-urlencode 'query=*' http://127.0.0.1:${toString legacyPort}/select/logsql/query + exit 1 + fi kill -TERM "$pid" wait "$pid" || true test -n "$(find ${vlDir} -type f | head -1)" @@ -587,7 +601,7 @@ pkgs.testers.runNixOSTest { with subtest("the node is Ready and holds every image"): - wait_node_ready(machine, timeout=300) + wait_node_ready(machine, timeout=600) wait_images(machine, timeout=300) kube(machine, f"config set-context --current --namespace={NS}") @@ -844,6 +858,48 @@ 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: + """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, + and the responder asked directly.""" + import base64 + + def show(title: str, command: str) -> None: + print(f"--- {title}") + print(machine.execute(f"{command} 2>&1")[1]) + + print("=== gateway diagnostics") + for pod in service_pods(LOGS_AUTH): + 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() + 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}) + show( + "login as the responder's role", + f"curl -sS -m 20 --cacert /var/lib/swarm-bao-pki/ca.pem -X POST -d '{body}' " + f"https://${baoName}:${toString podPort}/v1/auth/jwt-k8s/login | jq -c 'del(.auth.client_token, .auth.accessor)'", + ) + 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("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("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"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", + ) + def wait_for_record(token: str, text: str, record: str) -> None: """Queries until the response holds `record`, for as long as the pod and the policy engine take to settle.""" @@ -852,20 +908,28 @@ pkgs.testers.runNixOSTest { status, body = vl_query(token, text) if status == 200 and record in body: return - assert time.monotonic() < deadline, (status, body) + if time.monotonic() >= deadline: + gateway_diagnostics(token) + raise AssertionError((status, body)) time.sleep(3) AGENT_TOKEN = f"swarm-agent.{AGENT}.{AGENT_SECRETS[AGENT]}" with subtest("an agent's bearer reads the record written before the switch through the gateway, and the other bearers are granted or refused as the store says"): wait_for_record(AGENT_TOKEN, "switch", "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 ((LOGS_AUTH, "8081"), ("swarm-logs-grafana-auth", "8082")): + 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. assert vl_query(f"swarm-agent.{OTHER_AGENT}.{AGENT_SECRETS[OTHER_AGENT]}", "switch")[0] == 403 assert vl_query(f"swarm-agent.{AGENT}.{'0' * 32}", "switch")[0] == 401 # Grafana's bearer goes to the second responder of the same pod. status, body = vl_query(GRAFANA_BEARER, "switch") - assert status == 200 and "written before the switch" in body, (status, body) + if status != 200 or "written before the switch" not in body: + gateway_diagnostics(GRAFANA_BEARER) + raise AssertionError((status, body)) assert vl_query("0" * 64, "switch")[0] == 401 with subtest("a record posted to the ingest route and the store's own metrics come through the gateway, and a restarted pod still holds both records"):