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
commit 62cc95671d
11 changed files with 255 additions and 185 deletions

View file

@ -60,7 +60,12 @@ let
# `serviceUser` is the user every image runs its daemon as. Mounted files are
# group-owned by its group through `fsGroup`.
inherit (import ../../images { inherit pkgs lib; }) mkServiceImage serviceUser;
inherit (import ../../images { inherit pkgs lib; })
mkServiceImage
serviceUser
wgetOnly
loopbackProbe
;
# `DRAIN` in swarm-secret-client/src/shutdown.rs: how long a daemon keeps
# finishing in-flight work after SIGTERM before it exits on its own. The
@ -444,7 +449,7 @@ let
# runs in the cluster, because the `hostPort` they bind is forwarded to them
# before the policy sees the packet. The policy selects every pod of the
# service for ingress too and allows none, so only the node's own traffic
# (the kubelet's probes, which the policy engine always admits) reaches it.
# (which the policy engine always admits) reaches it.
networkPolicyOf =
name: reaches:
let
@ -686,7 +691,7 @@ let
// lib.optionalAttrs (runtimeDir != null) { RUNTIME_DIRECTORY = runtimeDir; }
// lib.optionalAttrs (stateDir != null) { STATE_DIRECTORY = stateDir; }
// lib.optionalAttrs (svc.healthEnv != null) {
${svc.healthEnv} = "0.0.0.0:${toString healthPort}";
${svc.healthEnv} = "127.0.0.1:${toString healthPort}";
};
mountRoots = [
@ -713,9 +718,11 @@ let
inherit name;
inherit (svc) package;
bin = daemon;
extraContents = lib.optional (storeValues != [ ]) (
pkgs.writeTextDir "share/hyperhive/${name}.env-refs" (lib.concatLines storeValues)
);
extraContents =
lib.optional (storeValues != [ ]) (
pkgs.writeTextDir "share/hyperhive/${name}.env-refs" (lib.concatLines storeValues)
)
++ lib.optional (svc.healthEnv != null) wgetOnly;
};
# A systemd `%d` in an argument is the credential directory, as in the
@ -896,16 +903,12 @@ let
cpu = "0";
};
# The listener's Service targets this port by its name.
ports =
lib.optional (svc.healthEnv != null) {
name = "health";
containerPort = healthPort;
}
++ lib.optional (listener != { }) {
name = "api";
containerPort = listener.port;
};
# The listener's Service targets this port by its name. The health
# listener is not a port: it binds to the pod's loopback.
ports = lib.optional (listener != { }) {
name = "api";
containerPort = listener.port;
};
container = {
inherit name volumeMounts;
@ -962,20 +965,8 @@ let
};
}
// lib.optionalAttrs (svc.healthEnv != null) {
livenessProbe = {
httpGet = {
path = "/healthz";
port = "health";
};
periodSeconds = 10;
};
readinessProbe = {
httpGet = {
path = "/readyz";
port = "health";
};
periodSeconds = 10;
};
livenessProbe = loopbackProbe healthPort "/healthz";
readinessProbe = loopbackProbe healthPort "/readyz";
};
# The listener's leaf: issued before the daemon starts, renewed beside it.
@ -1253,7 +1244,7 @@ in
# anyone, so a pod is reachable from the node alone until a policy of its own
# admits more. The cluster's policy engine takes the union of the policies
# that select a pod and always admits the node's own addresses, so the
# kubelet's probes and the host's gateway still reach every pod. A port a pod
# host's gateway still reaches every pod. A port a pod
# opens later is closed to the other pods and to the hive bridge without a
# line here.
// {

View file

@ -774,7 +774,11 @@ let
...
}:
let
inherit (import ../images { inherit pkgs lib; }) mkServiceImage;
inherit (import ../images { inherit pkgs lib; })
mkServiceImage
wgetOnly
loopbackProbe
;
podAuth = import ./lib/bao-pod-auth.nix;
tools = [
@ -870,10 +874,7 @@ let
bin = "nats-server";
extraContents = [
(pkgs.writeTextDir "share/hyperhive/${machine}-settings.refs" "${renderedSettings}\n")
(pkgs.runCommand "wget-only" { } ''
mkdir -p $out/bin
ln -s ${pkgs.pkgsStatic.busybox}/bin/busybox $out/bin/wget
'')
wgetOnly
];
};
exporter = mkServiceImage {
@ -972,17 +973,7 @@ let
# The monitor is on the pod's loopback, so the probe runs in the
# container. A server that has not opened its JetStream store is not
# ready.
readinessProbe = {
exec.command = [
"/bin/wget"
"-q"
"-O"
"/dev/null"
"http://127.0.0.1:${toString deployCfg.nats.monitorPort}/healthz?js-enabled-only=true"
];
periodSeconds = 10;
timeoutSeconds = 5;
};
readinessProbe = loopbackProbe deployCfg.nats.monitorPort "/healthz?js-enabled-only=true";
volumeMounts = [
(volumeNamed "nats-tls" tlsDir true)
(volumeNamed "nats-config" runtimeDir true)

View file

@ -41,7 +41,11 @@ let
hyperhiveCfg = config.services.hyperhive;
gatewayCfg = hyperhiveCfg.gateway;
k8sCfg = hyperhiveCfg.k8s;
inherit (import ../images { inherit pkgs lib; }) mkServiceImage;
inherit (import ../images { inherit pkgs lib; })
mkServiceImage
wgetOnly
loopbackProbe
;
storeAuth = import ./lib/store-auth.nix;
# Copy of `swarm-ui.nix`'s own `swarmAuthRequest` — not shared code because
@ -199,13 +203,7 @@ let
name = grafanaAuthService;
package = deployCfg.victorialogs.grafanaAuthPackage;
bin = "swarm-metrics-auth";
};
probe = path: {
httpGet = {
inherit path;
port = "health";
};
periodSeconds = 10;
extraContents = [ wgetOnly ];
};
in
{
@ -225,7 +223,7 @@ let
env = lib.mapAttrsToList (name: value: { inherit name value; }) (
lib.filterAttrs (n: _: lib.hasPrefix "BAO_" n) env
// {
SWARM_METRICS_AUTH_HEALTH_ADDR = "0.0.0.0:${toString grafanaAuthHealthPort}";
SWARM_METRICS_AUTH_HEALTH_ADDR = "127.0.0.1:${toString grafanaAuthHealthPort}";
}
);
# Not `api`: a Service resolves a named port to the first container of the
@ -235,13 +233,9 @@ let
name = "grafana-api";
containerPort = grafanaAuthPort;
}
{
name = "health";
containerPort = grafanaAuthHealthPort;
}
];
livenessProbe = probe "/healthz";
readinessProbe = probe "/readyz";
livenessProbe = loopbackProbe grafanaAuthHealthPort "/healthz";
readinessProbe = loopbackProbe grafanaAuthHealthPort "/readyz";
volumeMounts = lib.filter (
m:
lib.elem m.name [

View file

@ -31,7 +31,11 @@ let
networkCfg = hyperhiveCfg.network;
k8sCfg = hyperhiveCfg.k8s;
baoCfg = hyperhiveCfg.swarm.bao;
inherit (import ../images { inherit pkgs lib; }) mkServiceImage;
inherit (import ../images { inherit pkgs lib; })
mkServiceImage
wgetOnly
loopbackProbe
;
storeAuth = import ./lib/store-auth.nix;
# The workloads, as the cluster names them: the store, and the one pod that
@ -254,13 +258,7 @@ let
name = grafanaAuthService;
package = deployCfg.victoriametrics.authPackage;
bin = "swarm-metrics-auth";
};
probe = path: {
httpGet = {
inherit path;
port = "grafana-health";
};
periodSeconds = 10;
extraContents = [ wgetOnly ];
};
in
{
@ -280,10 +278,10 @@ let
env = lib.mapAttrsToList (name: value: { inherit name value; }) (
lib.filterAttrs (n: _: lib.hasPrefix "BAO_" n) env
// {
SWARM_METRICS_AUTH_HEALTH_ADDR = "0.0.0.0:${toString grafanaAuthHealthPort}";
SWARM_METRICS_AUTH_HEALTH_ADDR = "127.0.0.1:${toString grafanaAuthHealthPort}";
}
);
# Not `api` and `health`: a Service resolves a named port to the first
# Not `api`: a Service resolves a named port to the first
# container of the pod that declares the name, which is the agents'
# responder's.
ports = [
@ -291,13 +289,9 @@ let
name = "grafana-api";
containerPort = grafanaAuthPort;
}
{
name = "grafana-health";
containerPort = grafanaAuthHealthPort;
}
];
livenessProbe = probe "/healthz";
readinessProbe = probe "/readyz";
livenessProbe = loopbackProbe grafanaAuthHealthPort "/healthz";
readinessProbe = loopbackProbe grafanaAuthHealthPort "/readyz";
volumeMounts = lib.filter (
m:
lib.elem m.name [

View file

@ -53,22 +53,51 @@ let
};
};
# `wget` and nothing else of busybox: the smallest HTTP client an image can
# hold. A health listener binds to the pod's loopback, so the kubelet probes
# it from inside the container with this.
wgetOnly = pkgs.runCommand "wget-only" { } ''
mkdir -p $out/bin
ln -s ${pkgs.pkgsStatic.busybox}/bin/busybox $out/bin/wget
'';
# An `exec` probe that GETs `path` on the loopback `port`. `wget` exits
# non-zero on any non-2xx status, so a 503 fails the probe.
loopbackProbe = port: path: {
exec.command = [
"/bin/wget"
"-q"
"-O"
"/dev/null"
"http://127.0.0.1:${toString port}${path}"
];
periodSeconds = 10;
timeoutSeconds = 5;
};
daemon =
name:
extraContents: name:
mkServiceImage {
inherit name;
inherit name extraContents;
package = packages.${name};
};
in
{
inherit mkServiceImage registryHost serviceUser;
inherit
mkServiceImage
registryHost
serviceUser
wgetOnly
loopbackProbe
;
images = lib.genAttrs [
"swarm-controller"
"swarm-nats-auth"
"swarm-logs-auth"
"swarm-metrics-auth"
"swarm-notify-router"
"swarm-ci-metrics"
] daemon;
images =
lib.genAttrs [
"swarm-controller"
"swarm-nats-auth"
"swarm-logs-auth"
"swarm-metrics-auth"
"swarm-notify-router"
] (daemon [ wgetOnly ])
// lib.genAttrs [ "swarm-ci-metrics" ] (daemon [ ]);
}

View file

@ -201,24 +201,24 @@ let
swarm-controller = {
RUNTIME_DIRECTORY = "/run/swarm-controller";
STATE_DIRECTORY = "/var/lib/swarm-controller";
SWARM_CONTROLLER_HEALTH_ADDR = "0.0.0.0:8080";
SWARM_CONTROLLER_HEALTH_ADDR = "127.0.0.1:8080";
};
swarm-notify-router = {
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
SWARM_NOTIFY_ROUTER_HEALTH_ADDR = "0.0.0.0:8080";
SWARM_NOTIFY_ROUTER_HEALTH_ADDR = "127.0.0.1:8080";
};
swarm-stt = {
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
SWARM_STT_HEALTH_ADDR = "0.0.0.0:8080";
SWARM_STT_HEALTH_ADDR = "127.0.0.1:8080";
STATE_DIRECTORY = "/var/lib/swarm-stt";
};
swarm-review-classifier = {
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
SWARM_REVIEW_CLASSIFIER_HEALTH_ADDR = "0.0.0.0:8080";
SWARM_REVIEW_CLASSIFIER_HEALTH_ADDR = "127.0.0.1:8080";
};
swarm-claude-login = {
OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint;
SWARM_CLAUDE_LOGIN_HEALTH_ADDR = "0.0.0.0:8080";
SWARM_CLAUDE_LOGIN_HEALTH_ADDR = "127.0.0.1:8080";
};
# No endpoint: the poller keeps the route its unit names.
swarm-ci-metrics = {
@ -347,11 +347,52 @@ let
let
c = container "swarm-notify-router";
in
(lib.head c.ports).containerPort == 8080
&& c.readinessProbe.httpGet.path == "/readyz"
&& c.livenessProbe.httpGet.path == "/healthz"
!(c ? ports)
&& lib.last c.readinessProbe.exec.command == "http://127.0.0.1:8080/readyz"
&& lib.last c.livenessProbe.exec.command == "http://127.0.0.1:8080/healthz"
&& lib.all (name: (podSpec name).terminationGracePeriodSeconds > 10) (lib.attrNames units);
}
{
# The presence arms are the controls: the listener's variables, the probes
# and the VictoriaLogs/Metrics `api` probes are found, so an empty list
# cannot pass.
name = "every health listener binds to the pod's loopback and is probed by exec, and no pod declares a port for it";
ok =
let
workloads = lib.filter (o: o.kind == "Deployment" || o.kind == "CronJob") (lib.attrValues objects);
podOf =
o: if o.kind == "CronJob" then o.spec.jobTemplate.spec.template.spec else o.spec.template.spec;
cs = lib.concatMap (o: (podOf o).containers) workloads;
env = c: lib.listToAttrs (map (e: lib.nameValuePair e.name e.value) (c.env or [ ]));
healthAddrs = lib.concatMap (
c: lib.attrValues (lib.filterAttrs (n: _: lib.hasSuffix "_HEALTH_ADDR" n) (env c))
) cs;
probes = lib.concatMap (
c:
lib.filter (p: p != null) [
(c.livenessProbe or null)
(c.readinessProbe or null)
(c.startupProbe or null)
]
) cs;
httpProbes = lib.filter (p: p ? httpGet) probes;
execProbes = lib.filter (p: p ? exec) probes;
in
lib.length healthAddrs == 10
&& lib.all (a: lib.hasPrefix "127.0.0.1:" a) healthAddrs
&& lib.length execProbes >= 20
&& lib.all (p: lib.hasPrefix "http://127.0.0.1:" (lib.last p.exec.command)) execProbes
&& lib.all (p: p.timeoutSeconds == 5) execProbes
&& httpProbes != [ ]
&& lib.all (p: p.httpGet.port == "api") httpProbes
&& !(lib.any (
p:
lib.elem p.name [
"health"
"grafana-health"
]
) (lib.concatMap (c: c.ports or [ ]) cs));
}
{
# The unchanged host is the control that the render itself succeeds.
name = "a unit variable naming a path the pod does not mount fails the render";
@ -1287,9 +1328,9 @@ let
spec = podSpec "swarm-stt";
cred = lib.findFirst (v: v.name == "credentials") null spec.volumes;
in
(lib.head c.ports).containerPort == 8080
&& c.readinessProbe.httpGet.path == "/readyz"
&& c.livenessProbe.httpGet.path == "/healthz"
!(c ? ports)
&& lib.last c.readinessProbe.exec.command == "http://127.0.0.1:8080/readyz"
&& lib.last c.livenessProbe.exec.command == "http://127.0.0.1:8080/healthz"
&& lib.any (m: m.name == "state" && m.mountPath == "/var/lib/swarm-stt") c.volumeMounts
# The cache needs no claim, and is no state to gate. The poller beside
# it, whose cursor is kept, is the control that a claim renders.
@ -1342,10 +1383,10 @@ let
"Deployment"
"ServiceAccount"
]
&& (lib.head c.ports).containerPort == 8080
&& c.readinessProbe.httpGet.path == "/readyz"
&& c.livenessProbe.httpGet.path == "/healthz"
&& (envOf name)."${prefix}_HEALTH_ADDR" == "0.0.0.0:8080"
&& !(c ? ports)
&& lib.last c.readinessProbe.exec.command == "http://127.0.0.1:8080/readyz"
&& lib.last c.livenessProbe.exec.command == "http://127.0.0.1:8080/healthz"
&& (envOf name)."${prefix}_HEALTH_ADDR" == "127.0.0.1:8080"
&& lib.any (m: m.name == "tmp" && m.mountPath == "/tmp") c.volumeMounts
&& (lib.findFirst (v: v.name == "tmp") null spec.volumes).emptyDir == { }
&& !(lib.any (v: v ? persistentVolumeClaim) spec.volumes)
@ -1565,9 +1606,9 @@ let
annotationOf =
o: (render o)."swarm-controller/deployment".spec.template.metadata.annotations."checksum/etc";
in
c.readinessProbe.httpGet.path == "/readyz"
&& c.livenessProbe.httpGet.path == "/healthz"
&& (byName "health" c.ports).containerPort == 8080
lib.last c.readinessProbe.exec.command == "http://127.0.0.1:8080/readyz"
&& lib.last c.livenessProbe.exec.command == "http://127.0.0.1:8080/healthz"
&& byName "health" c.ports == null
&& api.containerPort == 9443
&& !(api ? hostPort)
&& !(api ? hostIP)
@ -1728,8 +1769,8 @@ let
"http://127.0.0.1:8222/healthz?js-enabled-only=true"
]
# The responder's own probes, on an address of the pod's own.
&& env.SWARM_NATS_AUTH_HEALTH_ADDR == "0.0.0.0:8080"
&& (named "swarm-nats").readinessProbe.httpGet.path == "/readyz"
&& env.SWARM_NATS_AUTH_HEALTH_ADDR == "127.0.0.1:8080"
&& lib.last (named "swarm-nats").readinessProbe.exec.command == "http://127.0.0.1:8080/readyz"
&& env.BAO_JWT_ROLE == "swarm-nats-auth"
&& !(env ? BAO_CLIENT_CERT)
# The per-agent subjects keep their `$`: a pod's arguments are not
@ -1981,7 +2022,6 @@ let
&&
lib.sort lib.lessThan (map (p: p.name) ports) == [
"client"
"health"
"metrics"
]
&& (render withNode)."swarm-nats/loadbalancer" == svc;
@ -2444,7 +2484,8 @@ let
(lib.listToAttrs (map (e: lib.nameValuePair e.name e.value) grafana.env)).BAO_JWT_ROLE
== "swarm-logs-auth"
&& !(lib.any (e: lib.hasPrefix "BAO_CLIENT" e.name) (logs.env ++ grafana.env))
&& grafana.livenessProbe.httpGet.port == "health"
&& lib.last grafana.livenessProbe.exec.command == "http://127.0.0.1:8083/healthz"
&& !(lib.any (p: p.name == "health") grafana.ports)
&& spec.serviceAccountName == "swarm-logs-auth"
&& objects."swarm-logs-auth/serviceaccount".metadata.name == "swarm-logs-auth"
&& hasInfix "bound_subject=system:serviceaccount:hyperhive:swarm-logs-auth" script
@ -2641,7 +2682,8 @@ let
&& (envOfC agents).BAO_JWT_ROLE == "swarm-metrics-auth"
&& (envOfC grafana).BAO_JWT_ROLE == "swarm-metrics-auth"
&& !(lib.any (e: lib.hasPrefix "BAO_CLIENT" e.name) (agents.env ++ grafana.env))
&& grafana.livenessProbe.httpGet.port == "grafana-health"
&& lib.last grafana.livenessProbe.exec.command == "http://127.0.0.1:8085/healthz"
&& !(lib.any (p: p.name == "grafana-health") grafana.ports)
&& spec.serviceAccountName == "swarm-metrics-auth"
&& objects."swarm-metrics-auth/serviceaccount".metadata.name == "swarm-metrics-auth"
&& hasInfix "bound_subject=system:serviceaccount:hyperhive:swarm-metrics-auth" script

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]: