From 0b96c031341832fbcf79127f35f16b639bc1fbfe Mon Sep 17 00:00:00 2001 From: atlas Date: Sun, 22 Nov 2026 12:36:24 +0100 Subject: [PATCH] module-eval: the controller's runtime, hostPort hop, listener leaf and rev rollout --- nix/host-modules/k8s/runtime.nix | 4 +- nix/module-eval/k8s.nix | 277 ++++++++++++++++++++++++++++--- 2 files changed, 254 insertions(+), 27 deletions(-) diff --git a/nix/host-modules/k8s/runtime.nix b/nix/host-modules/k8s/runtime.nix index e06231f35..ef4e77070 100644 --- a/nix/host-modules/k8s/runtime.nix +++ b/nix/host-modules/k8s/runtime.nix @@ -73,7 +73,7 @@ in ${apiReady} ${waitFor 600 "the namespace" "${kubectl} get namespace ${cfg.namespace} >/dev/null 2>&1"} ${lib.concatMapStrings (path: waitFor 600 "${path}" "[ -s ${lib.escapeShellArg path} ]") ( - lib.attrValues caFiles + lib.unique (lib.attrValues caFiles) )} ${kubectl} --namespace ${cfg.namespace} create configmap ${rendered.caConfigMap} \ ${ @@ -87,7 +87,7 @@ in }; systemd.paths.hyperhive-k8s-ca-trust = { wantedBy = [ "multi-user.target" ]; - pathConfig.PathChanged = lib.attrValues caFiles; + pathConfig.PathChanged = lib.unique (lib.attrValues caFiles); }; }) diff --git a/nix/module-eval/k8s.nix b/nix/module-eval/k8s.nix index e784b0155..67baf200a 100644 --- a/nix/module-eval/k8s.nix +++ b/nix/module-eval/k8s.nix @@ -46,6 +46,12 @@ let deploy.victorialogs.grafanaAuthPackage = marker "logs-grafana"; deploy.victoriametrics.authPackage = marker "metrics"; deploy.victoriametrics.agentAuthPackage = marker "metrics-agent"; + # The controller's TCP listener, which the controller in the cluster needs + # and the one on the host serves as well. + swarm.controller.tcp = { + enable = true; + domain = "controller.t.local"; + }; }; withNode = hiveWithController nodeSettings; @@ -61,16 +67,21 @@ let deploy.ci-metrics.runtime = "k8s"; deploy.review-classifier.runtime = "k8s"; deploy.claude-login.runtime = "k8s"; + deploy.swarm-controller.runtime = "k8s"; } ); - # A host that asks for the cluster with no node. + # A host that asks for the cluster with no node, and a controller in it with + # no TCP listener. runtimeRefused = hive { deploy.notify-router.runtime = "k8s"; deploy.stt.runtime = "k8s"; deploy.ci-metrics.runtime = "k8s"; deploy.review-classifier.runtime = "k8s"; deploy.claude-login.runtime = "k8s"; + deploy.swarm-controller.enable = true; + deploy.swarm-controller.runtime = "k8s"; + deploy.swarm-controller.tcp.listenAddress = "10.0.0.5"; }; runtimeRefusals = lib.filter (a: !a.assertion) runtimeRefused.assertions; @@ -147,10 +158,11 @@ let # What the pod adds on top of the unit's own environment. added = { + # No endpoint: the controller keeps the swarm route its unit names. swarm-controller = { - OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint; RUNTIME_DIRECTORY = "/run/swarm-controller"; STATE_DIRECTORY = "/var/lib/swarm-controller"; + SWARM_CONTROLLER_HEALTH_ADDR = "0.0.0.0:8080"; }; swarm-notify-router = { OTEL_EXPORTER_OTLP_ENDPOINT = collectorEndpoint; @@ -232,6 +244,15 @@ let renders = config: (builtins.tryEval (builtins.deepSeq (builtins.toJSON (render config)) true)).success; + # Whether a volume holds a Secret, plain or among a projected volume's + # sources. The control that the lookup sees one is a literal of each shape, + # since no pod of this host mounts a Secret. + usesSecret = v: v ? secret || lib.any (src: src ? secret) (v.projected.sources or [ ]); + secretLookupWorks = + usesSecret { secret.secretName = "x"; } + && usesSecret { projected.sources = [ { secret.name = "x"; } ]; } + && !(usesSecret { projected.sources = [ { configMap.name = "x"; } ]; }); + routerUnit = c: c.services.hyperhive.deploy.notify-router.unit; manifestNames = c: lib.sort lib.lessThan (lib.attrNames c.services.k3s.manifests); routerPrune = withNode.systemd.services.swarm-notify-router-k8s-prune; @@ -269,8 +290,8 @@ let # The units load the client certificates and the pods do not. && lib.all (id: lib.elem id credentialIds && !(lib.hasInfix "\"${id}\"" rendered)) clientCertIds && !(lib.any (o: o.kind == "Secret") (lib.attrValues objects)) - && - (lib.head (podSpec "swarm-controller").volumes).secret.secretName == "swarm-controller-credentials"; + && secretLookupWorks + && !(lib.any usesSecret (podSpec "swarm-controller").volumes); } { name = "the poller's CronJob runs on its timer's interval and deadline, never overlapping"; @@ -326,18 +347,19 @@ let && !(lib.hasInfix "--disable=local-storage" start); } { - # The images are the ones the manifests run, one per rendered service: - # the six workloads are the control that the list is not empty. + # The images are the ones the manifests run, one per rendered service and + # the controller's listener leaf: the seven are the control that the list + # is not empty. name = "the node loads the image of every service the manifests run, and k3s's own"; ok = let loaded = map toString withNode.services.k3s.images; rendered = map toString withNode.system.build.k8sImages; in - lib.length rendered == 6 + lib.length rendered == 7 && lib.all (i: lib.elem i loaded) rendered && lib.elem (toString withNode.services.k3s.package.airgap-images) loaded - && lib.length loaded == 7; + && lib.length loaded == 8; } { # Nothing the host already runs differs but the store's side of the pods' @@ -345,12 +367,17 @@ let # units are k3s's and the one that writes the pods' login, every unit but # the firewall (whose rules carry the pod network's interfaces) and the # granter's role unit (which enables the login's auth mount) starts the - # same command, and the manifests are the same derivation as without the - # node. - name = "the node adds only k3s, the jwt unit and the prune units of the four daemons and the CI run poller to the all-local host, and changes no container, timer or manifest"; + # same command, and the manifests are the same as without the node. The + # fixture has the controller's TCP listener on, which `allLocal` has off: + # its units, its roles and grants, and the gateway's locations are the + # one difference, and the controller's pod differs by the listener. + name = "the node adds only k3s, the jwt unit and the prune units of the controller, the four daemons and the CI run poller to the all-local host, and changes no container, timer or manifest"; ok = let - names = a: lib.attrNames a; + # The listener's own units, which `withNode` has on and `allLocal` off. + tcpUnit = + n: lib.hasPrefix "swarm-controller-tls" n || lib.hasPrefix "swarm-controller-gateway-client" n; + names = a: lib.filter (n: !tcpUnit n) (lib.attrNames a); added = lib.subtractLists (names allLocal.systemd.services) (names withNode.systemd.services); in names allLocal.systemd.timers == names withNode.systemd.timers @@ -366,6 +393,7 @@ let || n == "swarm-ci-metrics-k8s-prune" || n == "swarm-review-classifier-k8s-prune" || n == "swarm-claude-login-k8s-prune" + || n == "swarm-controller-k8s-prune" ) added && lib.elem "swarm-bao-k8s-jwt-policy" added && lib.elem "swarm-notify-router-k8s-prune" added @@ -373,6 +401,7 @@ let && lib.elem "swarm-ci-metrics-k8s-prune" added && lib.elem "swarm-review-classifier-k8s-prune" added && lib.elem "swarm-claude-login-k8s-prune" added + && lib.elem "swarm-controller-k8s-prune" added && lib.all ( @@ -383,11 +412,22 @@ let ( lib.subtractLists [ "firewall" + "nginx" "opentelemetry-collector" + "swarm-bao-controller-policy" "swarm-bao-granter-role" + "swarm-bao-services-issuer-policy" ] (names allLocal.systemd.services) ) - && withNode.system.build.k8sManifests.drvPath == allLocal.system.build.k8sManifests.drvPath; + && ( + let + others = lib.filterAttrs (n: _: !(lib.hasPrefix "swarm-controller/" n)); + in + others (render withNode) == others (render allLocal) + ) + # `withNode` has the controller's listener on, which `allLocal` has + # off: the pod differs by it, its other objects do not. + && (render withNode)."swarm-controller/configmap" == (render allLocal)."swarm-controller/configmap"; } { # The all-local host's assertions are the control: they all hold. @@ -449,16 +489,21 @@ let { # The units' own endpoints are the control: each differs from the # collector's, so the override replaces something. The host's units keep - # theirs. The poller is a swarm-tier producer: its pod keeps the swarm - # collector's route of its own, spelled out here, and names no hive - # collector in any variable. - name = "every hive-tier pod pushes telemetry to the hive collector, the poller's pod keeps its swarm route, and the host units keep their endpoints"; + # theirs. The poller and the controller are swarm-tier producers: their + # pods keep the swarm collector's route of their own, spelled out here, and + # name no hive collector in any variable. + name = "every hive-tier pod pushes telemetry to the hive collector, the poller's and the controller's pods keep their swarm routes, and the host units keep their endpoints"; ok = let - hiveTier = lib.filter (n: n != "swarm-ci-metrics") (lib.attrNames units); + swarmTier = [ + "swarm-ci-metrics" + "swarm-controller" + ]; + hiveTier = lib.filter (n: !(lib.elem n swarmTier)) (lib.attrNames units); ownRoute = "https://${allLocal.services.hyperhive.swarm.otel.domain}/swarm-ci-metrics"; + controllerRoute = "https://${allLocal.services.hyperhive.swarm.otel.domain}/${allLocal.services.hyperhive.swarm.otel.producerName}"; in - lib.length hiveTier == 5 + lib.length hiveTier == 4 && lib.all ( name: (envOf name).OTEL_EXPORTER_OTLP_ENDPOINT == collectorEndpoint @@ -469,9 +514,12 @@ let && !((envOf "swarm-ci-metrics") ? OTEL_EXPORTER_OTLP_ENDPOINT) && !(lib.any (e: lib.hasInfix "hive-collector" (e.value or "")) (container "swarm-ci-metrics").env) && !(envOf "swarm-notify-router" ? SWARM_CI_METRICS_OTLP_ENDPOINT) + && units.swarm-controller.environment.OTEL_EXPORTER_OTLP_ENDPOINT == controllerRoute + && (envOf "swarm-controller").OTEL_EXPORTER_OTLP_ENDPOINT == controllerRoute && - allLocal.systemd.services.swarm-controller.environment.OTEL_EXPORTER_OTLP_ENDPOINT - == "https://${allLocal.services.hyperhive.swarm.otel.domain}/${allLocal.services.hyperhive.swarm.otel.producerName}"; + (envOf "swarm-controller").SWARM_CONTROLLER_OTEL_AUDIENCE + == units.swarm-controller.environment.SWARM_CONTROLLER_OTEL_AUDIENCE + && !(lib.any (e: lib.hasInfix "hive-collector" (e.value or "")) (container "swarm-controller").env); } { # The unchanged host is the control that the render itself succeeds. @@ -780,6 +828,7 @@ let "hyperhive-namespace" "swarm-ci-metrics" "swarm-claude-login" + "swarm-controller" "swarm-notify-router" "swarm-review-classifier" "swarm-stt" @@ -842,8 +891,10 @@ let ] ] && !(lib.any (v: v ? secret) volumes) - && lib.any (v: v ? secret) (podSpec "swarm-controller").volumes + && secretLookupWorks && lib.hasInfix "--from-file=bao-server-ca.pem=${serverCa}" caUnit.script + && lib.hasInfix "--from-file=hive-client-ca.pem=" caUnit.script + && lib.hasInfix "--from-file=swarm-services-root.pem=" caUnit.script && lib.hasInfix "--from-file=trust-bundle.pem=" caUnit.script && lib.elem "multi-user.target" caUnit.wantedBy # A change to either file publishes again with no manual step, and the @@ -853,6 +904,7 @@ let == lib.sort lib.lessThan [ serverCa "${onCluster.services.hyperhive.deploy.hive-controller.tls.stateDir}/trust-bundle.pem" + "${onCluster.services.hyperhive.deploy.hive-controller.tls.stateDir}/swarm-services-root.pem" ] && !(caUnit.serviceConfig ? RemainAfterExit) && !(withNode.systemd.paths ? hyperhive-k8s-ca-trust); @@ -1043,7 +1095,7 @@ let } ] ] - && lib.any (v: v ? secret) (podSpec "swarm-controller").volumes + && secretLookupWorks && c.securityContext.readOnlyRootFilesystem && c.securityContext.runAsNonRoot && c.securityContext.capabilities.drop == [ "ALL" ] @@ -1214,6 +1266,17 @@ let ) runtimeRefusals && lib.any (a: lib.hasInfix "claude-login.runtime = \"k8s\" needs the" a.message) runtimeRefusals && lib.any (a: lib.hasInfix "ci-metrics.runtime = \"k8s\" needs the" a.message) runtimeRefusals + && lib.any ( + a: lib.hasInfix "swarm-controller.runtime = \"k8s\" needs the" a.message + ) runtimeRefusals + && lib.any ( + a: lib.hasInfix "controller.tcp.enable: the host cannot reach" a.message + ) runtimeRefusals + && lib.any ( + a: lib.hasInfix "tcp.listenAddress is" a.message && lib.hasInfix "\"10.0.0.5\"" a.message + ) runtimeRefusals + # The all-local host binds the default, which the refusal lets through. + && onCluster.services.hyperhive.deploy.swarm-controller.tcp.listenAddress == "0.0.0.0" && lib.all (a: a.assertion) onCluster.assertions; } { @@ -1276,7 +1339,6 @@ let let spec = (render onCluster)."swarm-ci-metrics/cronjob".spec.jobTemplate.spec.template.spec; volumesOf = s: s.volumes; - usesSecret = v: v ? secret || lib.any (src: src ? secret) (v.projected.sources or [ ]); cred = lib.findFirst (v: v.name == "credentials") null spec.volumes; serverCa = onCluster.services.hyperhive.deploy.bao.serverCaFile; in @@ -1292,7 +1354,7 @@ let ] ] && !(lib.any usesSecret (volumesOf spec)) - && lib.any usesSecret (volumesOf (podSpec "swarm-controller")) + && secretLookupWorks && (lib.head spec.containers).env != [ ] && lib.any ( e: e.name == "BAO_CACERT" && e.value == "/run/credentials/swarm-ci-metrics.service/bao-ca.pem" @@ -1300,6 +1362,171 @@ let && lib.all (v: lib.all (e: e.name != v) (lib.head spec.containers).env) clientVars && !(lib.hasInfix "swarm-ci-metrics-credentials" rendered); } + { + # The host with the controller on it is the control for every absence + # below: it holds the unit, its listener's leaf unit and timer, and the + # prune unit that runs before the unit. + name = "the controller in the cluster leaves the host no unit, listener leaf unit or prune unit, and a controller on the host keeps all three"; + ok = + let + s = withNode.systemd; + c = onCluster.systemd; + in + s.services.swarm-controller.enable + && s.services ? swarm-controller-tls + && s.timers ? swarm-controller-tls + && s.services.swarm-controller-k8s-prune.before == [ "swarm-controller.service" ] + && s.services.swarm-controller-k8s-prune.requiredBy == [ "swarm-controller.service" ] + && lib.hasInfix "swarm-controller.yaml" s.services.swarm-controller-k8s-prune.script + && !c.services.swarm-controller.enable + && !(c.services ? swarm-controller-tls) + && !(c.timers ? swarm-controller-tls) + && !(c.services ? swarm-controller-k8s-prune) + && !(allLocal.systemd.services ? swarm-controller-k8s-prune) + && render onCluster == render withNode + && + lib.sort lib.lessThan (map (o: o.kind) onCluster.services.k3s.manifests.swarm-controller.content) + == [ + "ConfigMap" + "Deployment" + "PersistentVolumeClaim" + "ServiceAccount" + ]; + } + { + # The host with the controller on it dials the name, as it always did. + name = "the gateway dials the controller pod's hostPort and verifies its certificate as the listener's name"; + ok = + let + loc = c: path: c.services.nginx.virtualHosts."t.local".locations.${path}; + dials = + c: path: needle: + lib.hasInfix needle (loc c path).extraConfig; + verified = + c: path: + dials c path "proxy_ssl_name controller.t.local;" + && dials c path "proxy_ssl_verify on;" + && dials c path "proxy_ssl_certificate "; + in + (loc onCluster "/webhook/forge/").proxyPass == "https://10.42.0.1:9443" + && (loc onCluster "/api/").proxyPass == "https://10.42.0.1:9443" + && (loc withNode "/webhook/forge/").proxyPass == "https://controller.t.local:9443" + && (loc withNode "/api/").proxyPass == "https://controller.t.local:9443" + && verified onCluster "/webhook/forge/" + && verified onCluster "/api/" + && verified withNode "/api/"; + } + { + name = "the controller's pod publishes its listener on the node, is probed on the health listener, and rolls with its rev file"; + ok = + let + cluster = render onCluster; + deployment = cluster."swarm-controller/deployment"; + pod = deployment.spec.template; + c = lib.head pod.spec.containers; + byName = n: lib.findFirst (x: x.name == n) null; + api = byName "api" c.ports; + rolled = lib.recursiveUpdate onCluster { + environment.etc."hyperhive/swarm-controller.json".text = ''{"hyperhive_rev":"other"}''; + }; + 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 + && api.hostPort == 9443 + && api.containerPort == 9443 + && api.hostIP == "10.42.0.1" + && deployment.spec.replicas == 1 + && deployment.spec.strategy.type == "Recreate" + # The checksum is of the ConfigMap's content, and a changed rev changes it. + && + annotationOf onCluster + == builtins.hashString "sha256" (builtins.toJSON cluster."swarm-controller/configmap".data) + && annotationOf rolled != annotationOf onCluster + # A pod with no ConfigMap carries no annotation: the router is the control. + && !((cluster."swarm-notify-router/deployment".spec.template.metadata) ? annotations) + && (podSpec "swarm-controller" ? initContainers) == false; + } + { + # The pod issues its own listener leaf with the unit's script, logging in + # with its ServiceAccount token. The host's is the control: the shared + # script with the certificate login and the key's group. + name = "the controller's pod issues its listener leaf before the daemon starts and renews it beside it, with the host unit's script"; + ok = + let + shared = import ../host-modules/lib/swarm-controller-tls-issue.nix { + inherit lib; + config = withNode; + }; + hostScript = withNode.systemd.services.swarm-controller-tls.script; + podScript = shared.script { + login = "L"; + credential = "c"; + group = null; + createDir = false; + }; + spec = (render onCluster)."swarm-controller/deployment".spec.template.spec; + init = lib.head spec.initContainers; + renew = lib.last spec.containers; + main = lib.head spec.containers; + mountsOf = x: map (m: m.name) x.volumeMounts; + tlsDir = "/var/lib/swarm-controller-tls"; + servicesRoot = "${onCluster.services.hyperhive.deploy.hive-controller.tls.stateDir}/swarm-services-root.pem"; + mountPath = x: (lib.findFirst (m: m.name == "tls") null x.volumeMounts).mountPath; + in + hostScript == shared.script { + login = "bao login -method=cert -token-only"; + credential = "certificate"; + group = "swarm-controller"; + } + && lib.hasInfix "chgrp swarm-controller" hostScript + && lib.hasInfix "install -d -m 0750" hostScript + && !(lib.hasInfix "install -d" podScript) + && !(lib.hasInfix "chgrp" podScript) + && lib.hasInfix "-checkhost \"$name\"" podScript + && lib.hasInfix "issue/swarm-controller-tls" podScript + && lib.length spec.initContainers == 1 + && init.name == "tls-issue" + && renew.name == "tls-renew" + && renew.command == [ "/bin/swarm-controller-tls-renew" ] + && init.image == renew.image + && init.image != main.image + && lib.all (x: mountPath x == tlsDir) [ + init + renew + main + ] + && lib.all (x: lib.elem "bao-token" (mountsOf x)) [ + init + renew + ] + && lib.elem "bao-token" (mountsOf main) + && + # In memory, so the leaf's key never reaches the node's disk. The + # runtime volume beside it is the control that the lookup finds a + # plain one. + (lib.findFirst (v: v.name == "tls") null spec.volumes) == { + name = "tls"; + emptyDir.medium = "Memory"; + } + && + (lib.findFirst (v: v.name == "runtime") null spec.volumes) == { + name = "runtime"; + emptyDir = { }; + } + && lib.any (e: e.name == "BAO_ADDR") init.env + && !(lib.any (e: e.name == "BAO_CLIENT_CERT") init.env) + && !(lib.any (v: v ? secret) spec.volumes) + # The root the listener trusts the gateway's client leaf by comes from + # the CA ConfigMap, at the path the daemon is told. + && lib.any ( + m: m.name == "ca-trust" && m.subPath == "swarm-services-root.pem" && m.mountPath == servicesRoot + ) main.volumeMounts + && lib.any (e: e.name == "SWARM_CONTROLLER_TCP_CLIENT_CA" && e.value == servicesRoot) main.env; + } + ]; in runGroup "k8s" cases