diff --git a/docs/4-implementation/k8s/images.md b/docs/4-implementation/k8s/images.md index b1a928961..664e1519b 100644 --- a/docs/4-implementation/k8s/images.md +++ b/docs/4-implementation/k8s/images.md @@ -10,9 +10,12 @@ One image runs one daemon. Its contents are: - the daemon's per-bin package from `nix/packages/default.nix`, - the CA roots from `pkgs.cacert`, with `SSL_CERT_FILE` pointing at them, -- the binary's own closure, which is glibc and libgcc. +- the binary's own closure, which is glibc and libgcc, +- for a daemon with a health listener, `wgetOnly` (`wget` and nothing else of + busybox): the listener binds to the pod's loopback, and the pod's `exec` + probes run it against `http://127.0.0.1:`. -The image has no shell and no init. The kubelet restarts a crashed container, so a +The image has no shell and no init (`wget` is the one tool it may add). The kubelet restarts a crashed container, so a service manager inside it would only disagree with the kubelet. A missing shell also leaves nothing to `exec` into. The entrypoint is `/bin/`, and the process runs as the `serviceUser` uid and gid that `nix/images/default.nix` @@ -36,12 +39,13 @@ Each of these is a flake package named `image-`, and the image name is - `swarm-ci-metrics` `nix flake check` evaluates all six and builds none of them, so the workspace -compile stays out of CI. `swarm-claude-login`, `swarm-review-classifier` and +compile stays out of CI. All but `swarm-ci-metrics`, which has no health +listener, hold `wgetOnly`. `swarm-claude-login`, `swarm-review-classifier` and `swarm-stt` aren't in the set: [the manifest renderer](manifests.md#pods) builds their images, with the paths their units' environments name (claude-code and opencode, ffmpeg, whisper-cli and the model). It builds three more for the -queue's pod ([runtime](runtime.md#the-queue)): the NATS server, which also -holds `wget`, the one tool of busybox its readiness probe needs; the +queue's pod ([runtime](runtime.md#the-queue)): the NATS server, which holds +`wgetOnly` for its readiness probe, as the daemons' images do; the Prometheus exporter; and an image of the queue's init and renewal scripts. ## Tags diff --git a/docs/4-implementation/k8s/manifests.md b/docs/4-implementation/k8s/manifests.md index 67f513c2e..190aaf1fc 100644 --- a/docs/4-implementation/k8s/manifests.md +++ b/docs/4-implementation/k8s/manifests.md @@ -142,18 +142,24 @@ credential directory. a listener and `egress` (`swarm-logs-auth`, `swarm-metrics-auth`) has the one policy: it admits the node to the listener and nothing else, and allows the egress above. - **Probes:** a service with an opt-in health listener gets its variable set to - `0.0.0.0:8080`, with liveness on `/healthz` and readiness on `/readyz` - (see [Readiness checks](../swarm/readiness.md)). `swarm-controller` is one of + `127.0.0.1:8080`, with liveness on `/healthz` and readiness on `/readyz` + (see [Readiness checks](../swarm/readiness.md)). The kubelet's `httpGet` + probes dial the pod's IP, so these are `exec` probes: each runs `wget` from + the image (`wgetOnly`, in `nix/images/default.nix`) against the loopback URL + in the container, with a 5-second timeout, and a 503 fails it. The pod + declares no port for the listener. `swarm-controller` is one of them, with `SWARM_CONTROLLER_HEALTH_ADDR`. A third-party daemon with no health variable, `victoria-logs` and `victoria-metrics`, names a `probe` path instead (`/health`), which both probes request on its listener. A `startupFailureThreshold` in it (`victoria-metrics`, 60) adds a - startup probe on the same path, tried every ten seconds, before the other two begin. The health port takes no credential, because the - kubelet's probes carry none and the routes answer a status code with no body. - Only the node reaches it, through the namespace's default-deny - ingress policy and the pod's own policy, which admit no other pod and no - client of the bridge. The port is an exception to mara's ruling ("if you can reach - it, even just in the cluster, it needs auth"): the kubelet has no credential - to send. + startup probe on the same path, tried every ten seconds, before the other two begin. + The health listener of our own daemons is unreachable from outside the pod: the + node, other pods and the bridge get a refusal, so it needs no credential. + The one health route outside the pod is the `/health` of `victoria-logs` and + `victoria-metrics` on their main port. Upstream answers `/health`, `/ping`, + `/-/healthy` and `/-/ready` before it checks `-httpAuth`, and the gateway needs + the main port on the pod's IP, so no bind or probe can close it. It's + reachable from the node only, through the default-deny ingress policy, and it + returns a status and no data. - **Listener and init container:** a service with a TCP `listener` (`swarm-controller`, with `swarm.controller.tcp.enable`) publishes its port with a ClusterIP Service, admits only the node to it with a NetworkPolicy, and diff --git a/docs/4-implementation/k8s/runtime.md b/docs/4-implementation/k8s/runtime.md index bee7d5a90..fe6309a4c 100644 --- a/docs/4-implementation/k8s/runtime.md +++ b/docs/4-implementation/k8s/runtime.md @@ -166,7 +166,7 @@ of more than one node needs one before the controller may run there. the controller on the host the locations dial that name. The Service has a NetworkPolicy that selects the pod for ingress and allows nothing: the cluster's policy engine always admits traffic from an address of the node, so - the gateway's connection and the kubelet's probes reach the pod, and no other + the gateway's connection reaches the pod, and no other pod does. A Service works on a cluster of more than one node, but the controller's Deployment still has the one replica. - **The listener's leaf.** The pod issues its own, from the store's @@ -186,8 +186,9 @@ of more than one node needs one before the controller may run there. `swarmctl` reaches the controller only through the gateway: run `swarmctl login` once. The host's wrapper defaults `--swarm` to the host's own swarm and sets no socket path, since a socket path on the host serves nothing. -- **Probes.** The pod binds `SWARM_CONTROLLER_HEALTH_ADDR`, with liveness on - `/healthz` and readiness on `/readyz`. Readiness needs the queue connection +- **Probes.** The pod binds `SWARM_CONTROLLER_HEALTH_ADDR` on the pod's + loopback, with liveness on `/healthz` and readiness on `/readyz`, both `exec` + probes of `wget` in the container. Readiness needs the queue connection and a fresh store login, so a store role that refuses the pod's token leaves it NotReady. - **State.** `/var/lib/swarm-controller` is an `emptyDir`. The record of the @@ -254,7 +255,7 @@ strategy, and the removed container stops before the pod can start. client, and only the node may read it. The pod's NetworkPolicy selects it for ingress and allows the client port from any source and nothing else. The cluster's policy engine always admits traffic from an address of the node, so - the gateway and the kubelet's probes reach the pod, and a pod of the cluster, + the gateway reaches the pod, and a pod of the cluster, or a client of the bridge that the host forwards, doesn't reach the exporter. - **The exporter's login.** The node's processes reach the exporter too, so it asks every request for a login. The exporter's container runs with @@ -321,7 +322,7 @@ strategy, and the removed container stops before the pod can start. The claim and its volume stay until the operator deletes them, as every claim does, with the directory. - **Readiness.** The pod is Ready when the responder's `/readyz`, on the pod's - port 8080, passes and the server's exec probe does. The probe runs + loopback port 8080, passes and the server's exec probe does. The probe runs `wget` against `/healthz?js-enabled-only=true` on the server's monitor, which stays on the pod's loopback; the server's image holds `wget` and nothing else of busybox. @@ -423,7 +424,7 @@ writes to the store and Grafana that reads it. Security `restricted` refuses a `hostPath` for it. - **Who reaches what.** Both pods have a NetworkPolicy that selects them for ingress and allows none, so only the node's own traffic reaches them: the - host's nginx, which dials the Services, and the kubelet's probes. The policy + host's nginx, which dials the Services, and the kubelet's `/health` probe. The policy refuses a pod of the cluster. The log store asks for its credential on every route, so a process on the host that dials the Service gets 401: see [the stores' listener credential](#the-stores-listener-credential). The responders' policy @@ -507,13 +508,14 @@ pushes to the store and Grafana that reads it. the pod has one ServiceAccount and one jwt role of that name, and both read the store with the pod's token. They hold no state, so the pod has no node label and runs on any node. Each serves TCP (`--listen`) on 8083 and 8084 behind a - Service of its own. The second container names its ports `grafana-api` and - `grafana-health`: a Service resolves a named port to the first container of the - pod that declares the name, so a shared name would send Grafana's bearer to the - agents' responder. + Service of its own. The second container names its port `grafana-api`: a Service + resolves a named port to the first container of the pod that declares the + name, so a shared name would send Grafana's bearer to the agents' responder. + Each container's health listener (8085 on the second) binds to the pod's + loopback, and the kubelet runs `wget` in the container against it. - **Who reaches what.** Both pods have a NetworkPolicy that selects them for ingress and allows none, so only the node's own traffic reaches them: the - host's nginx, which dials the Services, and the kubelet's probes. The store + host's nginx, which dials the Services. The store asks for its credential on every route, so a process on the host that dials the Service gets 401: see [the stores' listener credential](#the-stores-listener-credential). The responders' policy also lets the pod reach cluster DNS and the secret @@ -557,8 +559,8 @@ seccomp profile and no API token. The pod has a NetworkPolicy (`swarm-stt`, rendered with the pod): it may reach cluster DNS, and on the node's bridge address the store's pod listener, the identity provider, the queue and the hive collector, each on its one port. It -admits no ingress. The kubelet's probes still reach the pod, because the node's -own traffic to a pod is always admitted, and the pod doesn't serve anything +admits no ingress. The pod's health listener binds to its loopback and the +kubelet probes it from inside the container, and the pod doesn't serve anything else: requests reach it as queue messages, over the connection it opens. The policy also allows the pods of the queue's load balancer, in `kube-system`, on the queue's port, because the node forwards diff --git a/nix/host-modules/k8s/render.nix b/nix/host-modules/k8s/render.nix index 8a64ca978..763417497 100644 --- a/nix/host-modules/k8s/render.nix +++ b/nix/host-modules/k8s/render.nix @@ -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. // { diff --git a/nix/host-modules/swarm-nats.nix b/nix/host-modules/swarm-nats.nix index db2112eb5..bffe4334c 100644 --- a/nix/host-modules/swarm-nats.nix +++ b/nix/host-modules/swarm-nats.nix @@ -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) diff --git a/nix/host-modules/swarm-victorialogs.nix b/nix/host-modules/swarm-victorialogs.nix index 2d38db6e8..fe35626fc 100644 --- a/nix/host-modules/swarm-victorialogs.nix +++ b/nix/host-modules/swarm-victorialogs.nix @@ -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 [ diff --git a/nix/host-modules/swarm-victoriametrics.nix b/nix/host-modules/swarm-victoriametrics.nix index 141474ba3..a138a1b80 100644 --- a/nix/host-modules/swarm-victoriametrics.nix +++ b/nix/host-modules/swarm-victoriametrics.nix @@ -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 [ diff --git a/nix/images/default.nix b/nix/images/default.nix index f31a9cc02..5b4171c03 100644 --- a/nix/images/default.nix +++ b/nix/images/default.nix @@ -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 [ ]); } diff --git a/nix/module-eval/k8s.nix b/nix/module-eval/k8s.nix index f7b9bd220..a159068db 100644 --- a/nix/module-eval/k8s.nix +++ b/nix/module-eval/k8s.nix @@ -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 diff --git a/nix/vm-tests/k8s-controller.nix b/nix/vm-tests/k8s-controller.nix index 6ac151c64..8b3e69894 100644 --- a/nix/vm-tests/k8s-controller.nix +++ b/nix/vm-tests/k8s-controller.nix @@ -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 ' 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 ' 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]: