Watch
0
0
Fork
You've already forked hyperhive
0

bind health listeners to the pod's loopback and probe them by exec

This commit is contained in:
atlas 2026-11-27 23:45:00 +01:00 • committed by maia
commit 9c64b80538
5 changed files with 255 additions and 185 deletions

View file

@ -484,8 +484,9 @@ pkgs.testers.runNixOSTest {
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"]
main = next(c for c in spec["containers"] if c["name"] == SERVICE)
probe = main["readinessProbe"]["httpGet"]
assert probe["path"] == "/readyz", probe
probe = main["readinessProbe"]["exec"]["command"]
assert probe[0] == "/bin/wget" and probe[-1] == "http://127.0.0.1:8080/readyz", probe
assert not any(p["name"] == "health" for p in main["ports"]), main["ports"]
api = next(p for p in main["ports"] if p["name"] == "api")
assert api["containerPort"] == PORT and "hostPort" not in api and "hostIP" not in api, api
assert [c["name"] for c in spec["initContainers"]] == ["tls-issue"], spec["initContainers"]
@ -548,7 +549,7 @@ pkgs.testers.runNixOSTest {
for _ in range(3):
assert machine.execute(dials(other, ip, PORT))[0] != 0
with subtest("a client of the hive bridge and another pod cannot reach the controller's pod, and the node reads its health port"):
with subtest("a client of the hive bridge and another pod cannot reach the controller's pod, and the health port answers on the pod's loopback only"):
deny = json.loads(kube(machine, "get networkpolicy default-deny-ingress -o json"))["spec"]
assert deny == {"podSelector": {}, "policyTypes": ["Ingress"]}, deny
bridge_if = machine.succeed("ip -o -4 addr show | grep -F 'inet ${bridgeIp}/' | cut -d' ' -f2").strip()
@ -559,8 +560,9 @@ pkgs.testers.runNixOSTest {
"&& ip -n agent route add default via ${bridgeIp}"
)
pod_ip = kube(machine, f"get pod {pod_name} -o jsonpath='{{.status.podIP}}'").strip()
code = machine.succeed(f"curl -s -o /dev/null -w '%{{http_code}}' --max-time 5 http://{pod_ip}:8080/healthz").strip()
code = machine.succeed(f"nsenter --target {pod_pid(SERVICE)} --net -- curl -s -o /dev/null -w '%{{http_code}}' --max-time 5 http://127.0.0.1:8080/healthz").strip()
assert code == "200", code
assert machine.execute(f"curl -s -o /dev/null --max-time 5 http://{pod_ip}:8080/healthz")[0] == 7
# The listener is reached by the node's own dial, the control that the
# refusals below are the policy's.
machine.succeed(f"timeout 5 bash -c '</dev/tcp/{pod_ip}/{PORT}'")

View file

@ -799,12 +799,13 @@ pkgs.testers.runNixOSTest {
machine.wait_until_fails(dials(other, ip, METRICS), timeout=120)
for _ in range(3):
assert machine.execute(dials(other, ip, METRICS))[0] != 0
# The responder's health port answers the node with a status and is
# closed to the same two sources: the namespace's default admits the
# The responder's health port answers inside the pod only and is
# closed to the node and to the same two sources: the namespace's default admits the
# node and nobody else, and the pod's own policy names the client port
# only.
code = machine.succeed(f"curl -s -o /dev/null -w '%{{http_code}}' --max-time 5 http://{pod_ip}:8080/healthz").strip()
code = machine.succeed(f"nsenter --target {pod_pid(SERVICE)} --net -- curl -s -o /dev/null -w '%{{http_code}}' --max-time 5 http://127.0.0.1:8080/healthz").strip()
assert code == "200", code
assert machine.execute(f"curl -s -o /dev/null --max-time 5 http://{pod_ip}:8080/healthz")[0] == 7
machine.wait_until_fails(dials(other, pod_ip, 8080), timeout=120)
for port in (8080, METRICS):
assert machine.execute(dials(other, pod_ip, port))[0] != 0, port

View file

@ -918,6 +918,15 @@ pkgs.testers.runNixOSTest {
the process `pid`, as the pod in it would."""
return f"nsenter --target {pid} --net -- timeout 5 bash -c '</dev/tcp/{address}/{port}'"
def loopback_only(pid: str, ip: str, port: int) -> None:
"""The health listener answers inside the pod's network namespace and
refuses the node on the pod's IP. The first arm is the control that the
refusal is the bind and not an outage."""
code = machine.succeed(f"nsenter --target {pid} --net -- curl -s -o /dev/null -w '%{{http_code}}' --max-time 5 http://127.0.0.1:{port}/healthz").strip()
assert code == "200", (port, code)
rc = machine.execute(f"curl -s -o /dev/null --max-time 5 http://{ip}:{port}/healthz")[0]
assert rc == 7, (ip, port, rc)
with subtest("the speech-to-text pod answers a request on the queue, the path production uses, with its decoder running"):
assert json.loads(kube(machine, f"get networkpolicy {STT} -o json"))["spec"]["policyTypes"] == ["Ingress", "Egress"]
out = machine.succeed(f"nats {NATS} req '$SWARM.stt.transcribe.{AGENT}' 'OggS not really audio' --timeout 90s 2>/dev/null")
@ -949,11 +958,9 @@ pkgs.testers.runNixOSTest {
# on the way out, which the ingress policy of the peer does not decide.
assert machine.execute(dials(stt_pid, classifier_ip, 8080))[0] != 0
with subtest("no peer pod reaches the speech-to-text pod, and the kubelet's probes still do"):
with subtest("no peer pod reaches the speech-to-text pod, and its health listener answers on its loopback only"):
stt_ip = kube(machine, f"get pod {stt_pod} -o jsonpath='{{.status.podIP}}'").strip()
# The node reaches the speech-to-text pod's health port, a peer pod
# does not.
machine.succeed(f"timeout 5 bash -c '</dev/tcp/{stt_ip}/8080'")
loopback_only(stt_pid, stt_ip, 8080)
machine.wait_until_fails(dials(router_pid, stt_ip, 8080), timeout=60)
status = json.loads(kube(machine, f"get pod {stt_pod} -o json"))["status"]
assert status["containerStatuses"][0]["ready"] and status["containerStatuses"][0]["restartCount"] == 0, status
@ -1240,12 +1247,12 @@ pkgs.testers.runNixOSTest {
LOGIN: (pod_ip(DAEMON_PODS[LOGIN]), [8080]),
LOGS_AUTH: (auth_ip, [8080, 8083]),
}
# Every listener the pods open: the health ports, the store, and the
# responders' own.
health_pids = {name: pod_pid(name) for name in (SERVICE, STT, CLASSIFIER, LOGIN, LOGS_AUTH)}
# The listeners the pods open besides the health ones, which are on the
# pods' loopback: the store and the responders' own.
listeners = {
**health,
VL: (vl_ip, [9428]),
LOGS_AUTH: (auth_ip, [8080, 8081, 8082, 8083]),
LOGS_AUTH: (auth_ip, [8081, 8082]),
}
def sources(target: str):
@ -1256,12 +1263,15 @@ pkgs.testers.runNixOSTest {
"a client of the hive bridge": agent_dials,
}
# The node answers each health port with a status and no body, the
# control that every dial below refuses a port that is open.
# Each health listener answers on its pod's loopback, refuses the node,
# and none of the three sources reaches it. The listeners below are the
# control that these dials refuse only a port nothing serves to them:
# the node reaches those and the same sources do not.
for name, (ip, ports) in health.items():
for port in ports:
code = machine.succeed(f"curl -s -o /dev/null -w '%{{http_code}}' --max-time 5 http://{ip}:{port}/healthz").strip()
assert code == "200", (name, port, code)
loopback_only(health_pids[name], ip, port)
for source, dial in sources(name).items():
assert machine.execute(dial(ip, port))[0] != 0, (name, port, source)
machine.succeed(f"curl -sf --max-time 5 http://{vl_ip}:9428/health")
for name, (ip, ports) in listeners.items():
for port in ports:
@ -1274,31 +1284,30 @@ pkgs.testers.runNixOSTest {
status = json.loads(kube(machine, f"get pod {pod_name} -o json"))["status"]
assert all(c["ready"] and c["restartCount"] == 0 for c in status["containerStatuses"]), status
with subtest("a policy that admits every source opens the notify router's health port to the same sources, and removing it closes it again"):
with subtest("a policy that admits every source opens the log responder's listener to the same sources, and removing it closes it again"):
# The union of the policies that select a pod: the default admits
# nobody and this one admits everybody, so the sources that were refused
# reach the port, which is the control that the dials above fail on the
# policy and not on the path.
router_ip, _ = health[SERVICE]
allow = {
"apiVersion": "networking.k8s.io/v1",
"kind": "NetworkPolicy",
"metadata": {"name": "test-admit-router", "namespace": NS},
"metadata": {"name": "test-admit-auth", "namespace": NS},
"spec": {
"podSelector": {"matchLabels": {"app.kubernetes.io/name": SERVICE}},
"podSelector": {"matchLabels": {"app.kubernetes.io/name": LOGS_AUTH}},
"policyTypes": ["Ingress"],
"ingress": [{}],
},
}
machine.succeed(f"echo '{json.dumps(allow)}' | kubectl apply -f -")
try:
for source, dial in sources(SERVICE).items():
machine.wait_until_succeeds(dial(router_ip, 8080), timeout=120)
for source, dial in sources(LOGS_AUTH).items():
machine.wait_until_succeeds(dial(auth_ip, 8081), timeout=120)
finally:
kube(machine, "delete networkpolicy test-admit-router --ignore-not-found")
for source, dial in sources(SERVICE).items():
machine.wait_until_fails(dial(router_ip, 8080), timeout=120)
assert machine.execute(dial(router_ip, 8080))[0] != 0, source
kube(machine, "delete networkpolicy test-admit-auth --ignore-not-found")
for source, dial in sources(LOGS_AUTH).items():
machine.wait_until_fails(dial(auth_ip, 8081), timeout=120)
assert machine.execute(dial(auth_ip, 8081))[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")
@ -1553,6 +1562,8 @@ pkgs.testers.runNixOSTest {
for _ in range(3):
assert machine.execute(dials(router_pid, ip, port))[0] != 0
metrics_auth_pid = pod_pid(METRICS_AUTH)
for port in (8080, 8085):
loopback_only(metrics_auth_pid, metrics_auth_ip, port)
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):

View file

@ -5,7 +5,8 @@
#
# - the node is Ready within 300 s of boot, and containerd lists every image;
# - `swarm-logs-auth` and `swarm-metrics-auth` keep running with no restart,
# `/healthz` answers 200 and `/readyz` 503, so the pod is not Ready: the store
# `/healthz` answers 200 and `/readyz` 503 on the pod's loopback, read by
# `wget` in the container, so the pod is not Ready (its exec probe fails on the 503): the store
# address points at a closed port;
# - `swarm-notify-router` answers the same while it retries its first store
# read, and a pod delete in that retry ends it with exit 0 within 10 s;
@ -42,13 +43,10 @@ let
BAO_CLIENT_KEY = "/nonexistent/key.pem";
};
probe = path: {
httpGet = {
inherit path;
port = healthPort;
};
periodSeconds = 5;
};
# The listeners bind to the pod's loopback, so the probe is the module's own,
# run in the container.
inherit (import ../images { inherit pkgs lib; }) loopbackProbe;
probe = path: loopbackProbe healthPort path // { periodSeconds = 5; };
mkPod =
{
@ -87,7 +85,7 @@ let
args = [
"--listen=0.0.0.0:8081"
"--surface=logs"
"--health-addr=0.0.0.0:${toString healthPort}"
"--health-addr=127.0.0.1:${toString healthPort}"
];
env = storeEnv;
};
@ -96,7 +94,7 @@ let
args = [
"--listen=0.0.0.0:8081"
"--store-path=swarm/stub"
"--health-addr=0.0.0.0:${toString healthPort}"
"--health-addr=127.0.0.1:${toString healthPort}"
];
env = storeEnv;
};
@ -104,7 +102,7 @@ let
name = "swarm-notify-router";
env = storeEnv ++ [
(lib.nameValuePair "SWARM_NOTIFY_ROUTER_OIDC_CLIENT_ID" "stub")
(lib.nameValuePair "SWARM_NOTIFY_ROUTER_HEALTH_ADDR" "0.0.0.0:${toString healthPort}")
(lib.nameValuePair "SWARM_NOTIFY_ROUTER_HEALTH_ADDR" "127.0.0.1:${toString healthPort}")
];
};
}

View file

@ -3,6 +3,7 @@
# node first and fails the test through the driver (`succeed`, `wait_until_*`)
# or an `AssertionError` naming what it saw.
import json
import re
import time
from test_driver.machine import QemuMachine
@ -119,13 +120,17 @@ def wait_pod(
def http_status(node: QemuMachine, name: str, port: int, path: str) -> int:
"""The HTTP status pod `name` answers on its IP for `path`."""
ip = pod(node, name)["status"]["podIP"]
return int(
node.succeed(
f"curl -s -o /dev/null -m 5 -w '%{{http_code}}' http://{ip}:{port}{path}"
)
"""The HTTP status that pod `name` answers on its own loopback for `path`,
read by the `wget` in the container: the health listeners bind there and
nowhere else. `wget` prints no status for a 2xx, so that is 200."""
rc, out = node.execute(
f"kubectl exec {name} -- /bin/wget -O /dev/null http://127.0.0.1:{port}{path} 2>&1"
)
if rc == 0:
return 200
match = re.search(r"HTTP/1\.[01] (\d{3})", out)
assert match, f"{name}: wget exit {rc} with no status: {out}"
return int(match.group(1))
def delete_pod(node: QemuMachine, name: str, timeout: int = 60) -> tuple[dict, float]: