From d6f0b07ff1aee8d631fa8e72657ddf9e569fc964 Mon Sep 17 00:00:00 2001 From: atlas Date: Sun, 22 Nov 2026 12:28:03 +0100 Subject: [PATCH] k8s: deploy.swarm-controller.runtime moves the controller between its unit and the cluster --- nix/host-modules/k8s/render.nix | 237 +++++++++++++++--- .../lib/swarm-controller-tls-issue.nix | 86 +++++++ nix/host-modules/swarm-controller.nix | 161 ++++++++---- nix/host-modules/swarm-ui.nix | 10 +- 4 files changed, 406 insertions(+), 88 deletions(-) create mode 100644 nix/host-modules/lib/swarm-controller-tls-issue.nix diff --git a/nix/host-modules/k8s/render.nix b/nix/host-modules/k8s/render.nix index 4450f65bf..e8e1354d0 100644 --- a/nix/host-modules/k8s/render.nix +++ b/nix/host-modules/k8s/render.nix @@ -40,9 +40,20 @@ let caConfigMap = "hyperhive-ca-trust"; trustBundleKey = "trust-bundle.pem"; baoServerCaKey = "bao-server-ca.pem"; + hiveClientCaKey = "hive-client-ca.pem"; + servicesRootKey = "swarm-services-root.pem"; + controllerCfg = deployCfg.swarm-controller; + controllerOnCluster = controllerCfg.enable && controllerCfg.runtime == "k8s"; + controllerTcp = hyperhiveCfg.swarm.controller.tcp; + servicesRootPath = "${deployCfg.hive-controller.tls.stateDir}/${servicesRootKey}"; caSources = { ${trustBundleKey} = if caTrust.useSelfSigned then caTrust.caHostPath else null; ${baoServerCaKey} = baoDeployCfg.serverCaFile; + # What the controller's pod needs of the hive: the root its listener + # trusts the gateway's client leaf by, and the authority it writes into + # each hive's store role. Both are public. + ${servicesRootKey} = if controllerOnCluster && controllerTcp.enable then servicesRootPath else null; + ${hiveClientCaKey} = if controllerOnCluster then controllerCfg.hiveClientCaFile else null; }; # `serviceUser` is the user every image runs its daemon as. Mounted files are @@ -67,12 +78,63 @@ let "systemd" ]; + # The controller's listener leaf: its pod issues the leaf itself, from the + # store, with its ServiceAccount token, as the host's + # `swarm-controller-tls.service` does with its certificate + # (../lib/swarm-controller-tls-issue.nix is the one script). An init + # container writes it before the daemon starts and a second container renews + # it, both into an emptyDir only the pod holds. + tlsIssue = import ../lib/swarm-controller-tls-issue.nix { inherit lib config; }; + leafTools = [ + baoDeployCfg.package + pkgs.jq + pkgs.openssl + pkgs.coreutils + pkgs.gnugrep + ]; + leafIssueBin = "swarm-controller-tls-issue"; + leafRenewBin = "swarm-controller-tls-renew"; + leafImagePackage = + let + issue = pkgs.writeShellScriptBin leafIssueBin '' + export PATH=${lib.makeBinPath leafTools} + ${tlsIssue.script { + login = "bao write -field=token auth/${podAuth.mount}/login role=swarm-controller jwt=@${podAuth.tokenFile}"; + credential = "ServiceAccount token"; + group = null; + createDir = false; + }} + ''; + # The host's timer runs the same check daily: the script leaves a leaf + # that is within the first half of its window alone. A failed run (the + # store sealed or unreachable) is tried again sooner. + renew = pkgs.writeShellScriptBin leafRenewBin '' + export PATH=${lib.makeBinPath [ pkgs.coreutils ]} + while true; do + if ${issue}/bin/${leafIssueBin}; then + sleep 86400 + else + sleep 600 + fi + done + ''; + in + pkgs.symlinkJoin { + name = "swarm-controller-tls"; + paths = [ + issue + renew + ]; + }; + # The swarm services that run in the cluster. `unit` is the evaluated # systemd unit the host runs today; nothing reads it unless `enable` holds. # `healthEnv` names the variable that binds the daemon's /healthz and - # /readyz listener; the controller serves /readyz on its unix socket only, - # which the kubelet cannot probe. `publicCredentials` maps the ids of the - # credentials that hold a public CA file to their key in the CA ConfigMap. + # /readyz listener. `publicCredentials` maps the ids of the credentials that + # hold a public CA file to their key in the CA ConfigMap, and `publicFiles` + # the paths the unit names that hold one to theirs. `listener`, where a + # service has one, is the TCP port the pod publishes on the node + # (`hostAddress`) and the directory its init container writes the leaf to. # `switch` is null for a service that always runs on the host, and for one # with a `runtime` option names the option's value and the host unit or units # that run the service when it is `"host"`. `otlp` is where the pod pushes @@ -82,14 +144,29 @@ let # not carry one (../swarm-otel.nix, the swarm tier's own pipeline). services = { swarm-controller = { - inherit (deployCfg.swarm-controller) enable package; - unit = config.systemd.services.swarm-controller; + inherit (controllerCfg) enable package unit; kind = "Deployment"; - healthEnv = null; + healthEnv = "SWARM_CONTROLLER_HEALTH_ADDR"; etcFiles = [ "hyperhive/swarm-controller.json" ]; - publicCredentials = { }; - otlp = "hive"; - switch = null; + publicCredentials = { + "bao-ca.pem" = baoServerCaKey; + "hive-client-ca.pem" = hiveClientCaKey; + }; + publicFiles = lib.optionalAttrs controllerTcp.enable { ${servicesRootPath} = servicesRootKey; }; + # The TCP listener, as a `hostPort` on the node's address: the gateway + # on the host dials it there. + listener = lib.optionalAttrs controllerTcp.enable { + port = controllerTcp.port; + hostAddress = controllerCfg.tcp.hostAddress; + tlsDir = controllerCfg.tcp.tlsDir; + }; + # The unit pushes to the swarm collector's route and mints its own bearer + # (../glue-controller-env.nix, `otel_http_client.rs`). + otlp = "own"; + switch = { + inherit (controllerCfg) runtime; + hostUnit = "swarm-controller.service"; + }; }; swarm-notify-router = { inherit (deployCfg.notify-router) enable package; @@ -270,6 +347,9 @@ let inherit (svc) unit; sc = unit.serviceConfig; + listener = svc.listener or { }; + publicFiles = svc.publicFiles or { }; + credDir = "/run/credentials/${name}.service"; # `LoadCredential` entries are `id:source` on the host and a bare `id` # inside a container. Only the id is rendered. @@ -348,6 +428,8 @@ let ++ lib.optional baoLogin podAuth.tokenDir ++ lib.optional (runtimeDir != null) runtimeDir ++ lib.optional (stateDir != null) stateDir + ++ lib.attrNames publicFiles + ++ lib.optional (listener != { }) listener.tlsDir ++ map (f: "/etc/${f}") svc.etcFiles; under = root: v: v == root || lib.hasPrefix "${root}/" v; unmounted = lib.filterAttrs (_: v: lib.hasPrefix "/" v && !(lib.any (r: under r v) mountRoots)) env; @@ -438,10 +520,15 @@ let ]; }; } - ++ lib.optional (caFiles != [ ]) { + ++ lib.optional (!(caFiles == [ ] && publicFiles == { })) { name = "ca-trust"; configMap.name = caConfigMap; } + ++ lib.optional (listener != { }) { + name = "tls"; + # In memory: the leaf's key never reaches the node's disk. + emptyDir.medium = "Memory"; + } ++ lib.optional (runtimeDir != null) { name = "runtime"; emptyDir = { }; @@ -462,6 +549,10 @@ let ]; etcKey = f: builtins.replaceStrings [ "/" ] [ "_" ] f; + tlsMount = { + name = "tls"; + mountPath = listener.tlsDir; + }; volumeMounts = lib.optional (credIds != [ ]) { @@ -480,6 +571,13 @@ let subPath = trustBundleKey; readOnly = true; }) caFiles + ++ map (path: { + name = "ca-trust"; + mountPath = path; + subPath = publicFiles.${path}; + readOnly = true; + }) (lib.attrNames publicFiles) + ++ lib.optional (listener != { }) tlsMount ++ lib.optional (runtimeDir != null) { name = "runtime"; mountPath = runtimeDir; @@ -522,6 +620,20 @@ let cpu = "0"; }; + # `hostPort` publishes the listener on the node's address. The cluster's + # portmap plugin forwards it to the pod, so it reaches this one node. + ports = + lib.optional (svc.healthEnv != null) { + name = "health"; + containerPort = healthPort; + } + ++ lib.optional (listener != { }) { + name = "api"; + containerPort = listener.port; + hostPort = listener.port; + hostIP = listener.hostAddress; + }; + container = { inherit name volumeMounts; image = "${image.imageName}:${image.imageTag}"; @@ -545,13 +657,8 @@ let // lib.optionalAttrs (limits != { }) { inherit limits; }; } // lib.optionalAttrs (lib.tail execWords != [ ]) { args = lib.tail execWords; } + // lib.optionalAttrs (ports != [ ]) { inherit ports; } // lib.optionalAttrs (svc.healthEnv != null) { - ports = [ - { - name = "health"; - containerPort = healthPort; - } - ]; livenessProbe = { httpGet = { path = "/healthz"; @@ -568,9 +675,60 @@ let }; }; + # The listener's leaf: issued before the daemon starts, renewed beside it. + # Both log in as the pod's account, so they hold the token volume the + # daemon's login uses, and the store's CA from the credentials volume. + leafImage = mkServiceImage { + name = "${name}-tls"; + package = leafImagePackage; + bin = leafIssueBin; + }; + leafContainer = { + name = "tls-issue"; + image = "${leafImage.imageName}:${leafImage.imageTag}"; + imagePullPolicy = "Never"; + env = + lib.mapAttrsToList + (n: v: { + name = n; + value = v; + }) + ( + lib.filterAttrs ( + n: _: + lib.elem n [ + "BAO_ADDR" + "BAO_CACERT" + ] + ) env + // { + HOME = "/tmp"; + } + ); + volumeMounts = lib.filter ( + m: + lib.elem m.name [ + "credentials" + "bao-token" + "tls" + "tmp" + ] + ) volumeMounts; + inherit (container) securityContext; + }; + podSpec = { inherit terminationGracePeriodSeconds volumes; - containers = [ container ]; + containers = [ + container + ] + ++ lib.optional (listener != { }) ( + leafContainer + // { + name = "tls-renew"; + command = [ "/bin/${leafRenewBin}" ]; + } + ); # The API token is never mounted; a pod that logs in to the store gets # a token of its own, projected for the store's audience. automountServiceAccountToken = false; @@ -582,10 +740,31 @@ let seccompProfile.type = "RuntimeDefault"; }; } - // lib.optionalAttrs baoLogin { serviceAccountName = name; }; + // lib.optionalAttrs baoLogin { serviceAccountName = name; } + // lib.optionalAttrs (listener != { }) { initContainers = [ leafContainer ]; }; + + # What the `-etc` ConfigMap holds. A file mounted from it by `subPath` + # never sees a later change, so the pod template carries a hash of the + # content: a changed file changes the template, and the Deployment rolls. + etcData = lib.listToAttrs ( + map ( + f: + let + e = config.environment.etc.${f}; + in + lib.nameValuePair (etcKey f) ( + if e.text != null then e.text else fail name "/etc/${f} has no `text` to put in a ConfigMap" + ) + ) svc.etcFiles + ); podTemplate = restartPolicy: { - metadata.labels = labelsFor name; + metadata = { + labels = labelsFor name; + } + // lib.optionalAttrs (svc.etcFiles != [ ]) { + annotations."checksum/etc" = builtins.hashString "sha256" (builtins.toJSON etcData); + }; spec = podSpec // { inherit restartPolicy; }; @@ -656,17 +835,7 @@ let apiVersion = "v1"; kind = "ConfigMap"; metadata = metaFor "${name}-etc"; - data = lib.listToAttrs ( - map ( - f: - let - e = config.environment.etc.${f}; - in - lib.nameValuePair (etcKey f) ( - if e.text != null then e.text else fail name "/etc/${f} has no `text` to put in a ConfigMap" - ) - ) svc.etcFiles - ); + data = etcData; }; }; in @@ -685,7 +854,11 @@ let else if missingCreds != { } then fail name "${lib.concatStringsSep ", " (lib.attrNames missingCreds)} names a credential the unit does not load" else - { inherit objects image; }; + { + inherit objects image; + # What the pod's other containers run. + extraImages = lib.optional (listener != { }) leafImage; + }; enabled = lib.mapAttrs workload (lib.filterAttrs (_: svc: svc.enable) services); in @@ -704,7 +877,7 @@ in # The image each enabled service's pod runs: what a node has to hold, # since there is no registry to pull from. - images = lib.mapAttrsToList (_: w: w.image) enabled; + images = lib.concatMap (w: [ w.image ] ++ w.extraImages) (lib.attrValues enabled); # What ./runtime.nix moves services with. `switches` holds the services that # have a runtime option and is cheap to read: it names the units that a diff --git a/nix/host-modules/lib/swarm-controller-tls-issue.nix b/nix/host-modules/lib/swarm-controller-tls-issue.nix new file mode 100644 index 000000000..64cbf7621 --- /dev/null +++ b/nix/host-modules/lib/swarm-controller-tls-issue.nix @@ -0,0 +1,86 @@ +# The script that issues the swarm-controller's TCP listener leaf from the +# store's `pki` mount, and the two places that run it: the host's +# `swarm-controller-tls.service` (../swarm-controller.nix) and the pod's init +# and renewal containers (../k8s/render.nix). One script, so the leaf's checks +# (name, half-life, the role it is issued through) cannot differ between them. +# +# Pure function of the evaluated configuration, NOT a NixOS module. `login` +# is the command that prints a store token on stdout, `credential` names what +# it logs in with (for the error), and `group` is the group the +# key is readable by, or null where the files are already the daemon's own. +# `createDir` is false where the directory exists and belongs to another user, +# as an `emptyDir` does in a pod. +{ lib, config }: +let + deployCfg = config.services.hyperhive.deploy; + tcpCfg = config.services.hyperhive.swarm.controller.tcp; + tcpHost = deployCfg.swarm-controller.tcp; +in +{ + script = + { + login, + credential, + group, + createDir ? true, + }: + let + groupFlag = lib.optionalString (group != null) " -g ${group}"; + mkDir = lib.optionalString createDir "install -d -m 0750${groupFlag} \"$d\""; + chgrp = lib.optionalString (group != null) "chgrp ${group} \"$d/key.pem.new\" \"$d/cert.pem.new\""; + in + '' + set -euo pipefail + d=${lib.escapeShellArg tcpHost.tlsDir} + name=${lib.escapeShellArg tcpCfg.domain} + ${mkDir} + + # Missing, past half its window, or naming something other than the + # configured domain. + reissue=0 + { [ -s "$d/cert.pem" ] && [ -s "$d/key.pem" ]; } || reissue=1 + openssl x509 -in "$d/cert.pem" -noout -checkend ${ + toString (deployCfg.bao.servicesPkiLeafTtlHours * 3600 / 2) + } >/dev/null 2>&1 || reissue=1 + openssl x509 -in "$d/cert.pem" -noout -checkhost "$name" 2>/dev/null | grep -q ' does match ' || reissue=1 + if [ "$reissue" = 0 ]; then + echo "controller listener leaf valid for $name — leaving it alone" + exit 0 + fi + + err="$(mktemp)" + resp="$(mktemp "$d/issue.json.XXXXXX")" + trap 'rm -f "$err" "$resp"' EXIT + + if ! BAO_TOKEN="$(${login} 2>"$err")"; then + echo "could not log in to the swarm secret store with the controller's ${credential}." >&2 + cat "$err" >&2 + exit 1 + fi + export BAO_TOKEN + + echo "requesting the controller's listener leaf for $name from the store" + if ! bao write -format=json \ + ${lib.escapeShellArg "${deployCfg.bao.servicesPkiMountPath}/issue/${tcpCfg.serverPkiRole}"} \ + common_name="$name" > "$resp" 2>"$err"; then + echo "the store refused to issue the controller's listener certificate." >&2 + cat "$err" >&2 + exit 1 + fi + + jq -r '.data.private_key // empty' < "$resp" > "$d/key.pem.new" + jq -r '.data.certificate // empty' < "$resp" > "$d/cert.pem.new" + for f in "$d/key.pem.new" "$d/cert.pem.new"; do + if [ ! -s "$f" ]; then + echo "the store's response was missing a field: $f is empty" >&2 + exit 1 + fi + done + ${chgrp} + chmod 0640 "$d/key.pem.new" "$d/cert.pem.new" + # Key first: the daemon pairs whatever it reads, and a new key beside + # the old certificate is a pair it refuses and retries. + mv -f "$d/key.pem.new" "$d/key.pem" + mv -f "$d/cert.pem.new" "$d/cert.pem" + ''; +} diff --git a/nix/host-modules/swarm-controller.nix b/nix/host-modules/swarm-controller.nix index f9aefa306..6c3b34ee7 100644 --- a/nix/host-modules/swarm-controller.nix +++ b/nix/host-modules/swarm-controller.nix @@ -14,6 +14,10 @@ # client certificate the swarm's store issued for the gateway, with the # `clientAuth` usage. ./swarm-ui.nix still declares the vhost on the host that # runs this daemon, so the gateway stays on that host. +# +# `deploy.swarm-controller.runtime = "k8s"` runs the daemon as a pod in this +# host's cluster instead (./k8s/render.nix renders it from the unit below). The +# unit is then disabled, and the gateway dials the pod's `hostPort`. { pkgs, lib, @@ -154,6 +158,11 @@ let storeRetry = import ./lib/store-retry.nix { }; tcpOn = deployCfg.swarm-controller.enable && tcpCfg.enable; + # Where the daemon runs: its unit on this host, or a pod in this host's + # cluster, which ./k8s/render.nix renders from the same unit. + onK8s = deployCfg.swarm-controller.runtime == "k8s"; + tlsIssue = import ./lib/swarm-controller-tls-issue.nix { inherit lib config; }; + # The swarm the host's `swarmctl` talks to: this host's own, through the # gateway, as the operator's own SSO account (`swarmctl login`). The # controller socket then serves the gateway alone, which always sets @@ -609,6 +618,42 @@ in ''; }; + runtime = lib.mkOption { + type = lib.types.enum [ + "host" + "k8s" + ]; + default = "host"; + description = '' + Where the controller runs: `host` as the `swarm-controller` systemd + unit, or `k8s` as a pod in this host's cluster + ({option}`services.hyperhive.deploy.k8s.enable`), which the host's + configuration must enable. A swarm runs one controller, so a switch + moves it: the unit goes and the pod is applied, or the pod is deleted + and the unit returns. + + The pod needs the TCP listener + ({option}`services.hyperhive.swarm.controller.tcp.enable`): the host + cannot reach a unix socket inside a pod, so the gateway dials the + listener on {option}`tcp.hostAddress`. The pod's state is its own + volume, which starts empty: nothing moves the host's state directory + into it. `swarmctl` on the host dials the unix socket only, so its + socket verbs have no controller to reach while the pod runs. + ''; + }; + + unit = lib.mkOption { + type = lib.types.raw; + readOnly = true; + internal = true; + default = config.systemd.services.swarm-controller; + description = '' + The controller's evaluated systemd unit, which the cluster's manifests + are rendered from (../host-modules/k8s/render.nix). The host runs it + unless {option}`runtime` is `k8s`, and then the unit is disabled. + ''; + }; + swarmctlPackage = lib.mkOption { type = lib.types.package; defaultText = lib.literalExpression "hyperhive.packages.\${system}.swarmctl"; @@ -740,6 +785,26 @@ in IPv6 address is written in brackets. Binding a port opens nothing: {option}`openFirewall` decides who can reach it, and the TLS handshake decides who may talk once they do. + + With {option}`services.hyperhive.deploy.swarm-controller.runtime` set + to `k8s` this is the bind inside the pod, so it must stay `0.0.0.0`. + The node's address is {option}`hostAddress`. + ''; + }; + + hostAddress = lib.mkOption { + type = lib.types.str; + default = config.services.hyperhive.network.bridgeIp; + defaultText = lib.literalExpression "config.services.hyperhive.network.bridgeIp"; + description = '' + With {option}`services.hyperhive.deploy.swarm-controller.runtime` set + to `k8s`: the node address the pod's `hostPort` binds and the gateway + dials. The default is the hive bridge's address, the one the pods + already reach the host's services on. The gateway verifies the + listener's certificate as + {option}`services.hyperhive.swarm.controller.tcp.domain`, not as + this address. A `hostPort` reaches one node: a cluster of several + nodes needs a Service instead. ''; }; @@ -872,6 +937,10 @@ in users.groups.swarm-controller = { }; users.groups.${clientsGroup} = { }; + # The pod's `hostPort` is on the hive bridge's address by default, and the + # cluster's pods reach the host's services through the bridge. + services.hyperhive.network.enable = lib.mkIf onK8s (lib.mkDefault true); + # Through the unit, not `users.users.nginx.extraGroups`: systemd resolves # a unit's groups at start, and only a changed unit file makes the switch # restart nginx (it does not reload) onto the new group. @@ -943,6 +1012,33 @@ in TCP listener off. ''; } + { + assertion = !onK8s || config.services.hyperhive.deploy.k8s.enable; + message = '' + services.hyperhive.deploy.swarm-controller.runtime = "k8s" needs the + cluster: set services.hyperhive.deploy.k8s.enable on this host, or + leave the controller's runtime at "host". + ''; + } + { + assertion = !onK8s || tcpHost.listenAddress == "0.0.0.0"; + message = '' + services.hyperhive.deploy.swarm-controller.tcp.listenAddress is + "${tcpHost.listenAddress}", and with runtime = "k8s" it is the bind + inside the pod, where any address but "0.0.0.0" leaves the listener + unbound and the pod NotReady. Leave it at "0.0.0.0"; the node's + address is services.hyperhive.deploy.swarm-controller.tcp.hostAddress. + ''; + } + { + assertion = !onK8s || tcpCfg.enable; + message = '' + services.hyperhive.deploy.swarm-controller.runtime = "k8s" needs + services.hyperhive.swarm.controller.tcp.enable: the host cannot reach + a unix socket inside a pod, so the gateway dials the pod's TCP + listener. Set it, or leave the controller's runtime at "host". + ''; + } { assertion = !tcpCfg.enable || caTrust.useSelfSigned; message = '' @@ -956,6 +1052,9 @@ in ]; systemd.services.swarm-controller = { + # Disabled with the controller in the cluster, so nothing can start it; the definition stays + # because the pod is rendered from the evaluated unit. + enable = !onK8s; description = "hyperhive swarm-level controller daemon"; wantedBy = [ "multi-user.target" ]; # The listener's certificate files must exist when the daemon opens it. A @@ -1118,7 +1217,7 @@ in # Same shape as the queue's leaf unit (./swarm-nats.nix, # `swarm-bao-nats-tls`): the daemon re-reads the files, so rotating needs # no restart, which for this daemon would drop its job graph. - systemd.services.swarm-controller-tls = lib.mkIf tcpOn { + systemd.services.swarm-controller-tls = lib.mkIf (tcpOn && !onK8s) { description = "Issue the swarm-controller's TCP listener certificate from the secret store's PKI"; wantedBy = [ "multi-user.target" ]; after = [ @@ -1150,63 +1249,15 @@ in // lib.optionalAttrs (deployCfg.bao.serverCaFile != null) { BAO_CACERT = deployCfg.bao.serverCaFile; }; - script = '' - set -euo pipefail - d=${lib.escapeShellArg tcpHost.tlsDir} - name=${lib.escapeShellArg tcpCfg.domain} - install -d -m 0750 -g swarm-controller "$d" + script = tlsIssue.script { + login = "bao login -method=cert -token-only"; + credential = "certificate"; + group = "swarm-controller"; + }; - # Missing, past half its window, or naming something other than the - # configured domain. - reissue=0 - { [ -s "$d/cert.pem" ] && [ -s "$d/key.pem" ]; } || reissue=1 - openssl x509 -in "$d/cert.pem" -noout -checkend ${ - toString (deployCfg.bao.servicesPkiLeafTtlHours * 3600 / 2) - } >/dev/null 2>&1 || reissue=1 - openssl x509 -in "$d/cert.pem" -noout -checkhost "$name" 2>/dev/null | grep -q ' does match ' || reissue=1 - if [ "$reissue" = 0 ]; then - echo "controller listener leaf valid for $name — leaving it alone" - exit 0 - fi - - err="$(mktemp)" - resp="$(mktemp "$d/issue.json.XXXXXX")" - trap 'rm -f "$err" "$resp"' EXIT - - if ! BAO_TOKEN="$(bao login -method=cert -token-only 2>"$err")"; then - echo "could not log in to the swarm secret store with the controller's certificate." >&2 - cat "$err" >&2 - exit 1 - fi - export BAO_TOKEN - - echo "requesting the controller's listener leaf for $name from the store" - if ! bao write -format=json \ - ${lib.escapeShellArg "${deployCfg.bao.servicesPkiMountPath}/issue/${tcpCfg.serverPkiRole}"} \ - common_name="$name" > "$resp" 2>"$err"; then - echo "the store refused to issue the controller's listener certificate." >&2 - cat "$err" >&2 - exit 1 - fi - - jq -r '.data.private_key // empty' < "$resp" > "$d/key.pem.new" - jq -r '.data.certificate // empty' < "$resp" > "$d/cert.pem.new" - for f in "$d/key.pem.new" "$d/cert.pem.new"; do - if [ ! -s "$f" ]; then - echo "the store's response was missing a field: $f is empty" >&2 - exit 1 - fi - done - chgrp swarm-controller "$d/key.pem.new" "$d/cert.pem.new" - chmod 0640 "$d/key.pem.new" "$d/cert.pem.new" - # Key first: the daemon pairs whatever it reads, and a new key beside - # the old certificate is a pair it refuses and retries. - mv -f "$d/key.pem.new" "$d/key.pem" - mv -f "$d/cert.pem.new" "$d/cert.pem" - ''; }; - systemd.timers.swarm-controller-tls = lib.mkIf tcpOn { + systemd.timers.swarm-controller-tls = lib.mkIf (tcpOn && !onK8s) { description = "Daily renewal check for the swarm-controller's TCP listener certificate"; wantedBy = [ "timers.target" ]; timerConfig = { diff --git a/nix/host-modules/swarm-ui.nix b/nix/host-modules/swarm-ui.nix index a8a7ea5d3..049c1556f 100644 --- a/nix/host-modules/swarm-ui.nix +++ b/nix/host-modules/swarm-ui.nix @@ -107,9 +107,17 @@ let # `toString` below so an unset `domain` reaches the assertion that names it # instead of failing evaluation first. controllerTcp = swarmCfg.controller.tcp; + # In the cluster the listener is the pod's `hostPort` on the node's address. + # The name the certificate is verified as stays `tcp.domain` + # (`controllerDial`), so the address needs no certificate of its own. + controllerAddress = + if deployCfg.swarm-controller.runtime == "k8s" then + deployCfg.swarm-controller.tcp.hostAddress + else + toString controllerTcp.domain; controllerUpstream = if controllerTcp.enable then - "https://${toString controllerTcp.domain}:${toString controllerTcp.port}" + "https://${controllerAddress}:${toString controllerTcp.port}" else "http://unix:${deployCfg.swarm-controller.socketPath}:"; # `proxy_http_version` and `Connection` because `recommendedProxySettings`,