Watch
0
0
Fork
You've already forked hyperhive
0

k8s: deploy.swarm-controller.runtime moves the controller between its unit and the cluster

This commit is contained in:
atlas 2026-11-22 12:28:03 +01:00 • committed by maia
commit a801c0d0e6
4 changed files with 407 additions and 89 deletions

View file

@ -40,9 +40,20 @@ let
caConfigMap = "hyperhive-ca-trust"; caConfigMap = "hyperhive-ca-trust";
trustBundleKey = "trust-bundle.pem"; trustBundleKey = "trust-bundle.pem";
baoServerCaKey = "bao-server-ca.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 = { caSources = {
${trustBundleKey} = if caTrust.useSelfSigned then caTrust.caHostPath else null; ${trustBundleKey} = if caTrust.useSelfSigned then caTrust.caHostPath else null;
${baoServerCaKey} = baoDeployCfg.serverCaFile; ${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 # `serviceUser` is the user every image runs its daemon as. Mounted files are
@ -67,12 +78,63 @@ let
"systemd" "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 # The swarm services that run in the cluster. `unit` is the evaluated
# systemd unit the host runs today; nothing reads it unless `enable` holds. # systemd unit the host runs today; nothing reads it unless `enable` holds.
# `healthEnv` names the variable that binds the daemon's /healthz and # `healthEnv` names the variable that binds the daemon's /healthz and
# /readyz listener; the controller serves /readyz on its unix socket only, # /readyz listener. `publicCredentials` maps the ids of the credentials that
# which the kubelet cannot probe. `publicCredentials` maps the ids of the # hold a public CA file to their key in the CA ConfigMap, and `publicFiles`
# credentials that hold a public CA file to their key in the CA ConfigMap. # 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 # `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 # 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 # 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). # not carry one (../swarm-otel.nix, the swarm tier's own pipeline).
services = { services = {
swarm-controller = { swarm-controller = {
inherit (deployCfg.swarm-controller) enable package; inherit (controllerCfg) enable package unit;
unit = config.systemd.services.swarm-controller;
kind = "Deployment"; kind = "Deployment";
healthEnv = null; healthEnv = "SWARM_CONTROLLER_HEALTH_ADDR";
etcFiles = [ "hyperhive/swarm-controller.json" ]; etcFiles = [ "hyperhive/swarm-controller.json" ];
publicCredentials = { }; publicCredentials = {
otlp = "hive"; "bao-ca.pem" = baoServerCaKey;
switch = null; "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 = { swarm-notify-router = {
inherit (deployCfg.notify-router) enable package; inherit (deployCfg.notify-router) enable package;
@ -270,6 +347,9 @@ let
inherit (svc) unit; inherit (svc) unit;
sc = unit.serviceConfig; sc = unit.serviceConfig;
listener = svc.listener or { };
publicFiles = svc.publicFiles or { };
credDir = "/run/credentials/${name}.service"; credDir = "/run/credentials/${name}.service";
# `LoadCredential` entries are `id:source` on the host and a bare `id` # `LoadCredential` entries are `id:source` on the host and a bare `id`
# inside a container. Only the id is rendered. # inside a container. Only the id is rendered.
@ -348,6 +428,8 @@ let
++ lib.optional baoLogin podAuth.tokenDir ++ lib.optional baoLogin podAuth.tokenDir
++ lib.optional (runtimeDir != null) runtimeDir ++ lib.optional (runtimeDir != null) runtimeDir
++ lib.optional (stateDir != null) stateDir ++ lib.optional (stateDir != null) stateDir
++ lib.attrNames publicFiles
++ lib.optional (listener != { }) listener.tlsDir
++ map (f: "/etc/${f}") svc.etcFiles; ++ map (f: "/etc/${f}") svc.etcFiles;
under = root: v: v == root || lib.hasPrefix "${root}/" v; under = root: v: v == root || lib.hasPrefix "${root}/" v;
unmounted = lib.filterAttrs (_: v: lib.hasPrefix "/" v && !(lib.any (r: under r v) mountRoots)) env; 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"; name = "ca-trust";
configMap.name = caConfigMap; 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) { ++ lib.optional (runtimeDir != null) {
name = "runtime"; name = "runtime";
emptyDir = { }; emptyDir = { };
@ -462,6 +549,10 @@ let
]; ];
etcKey = f: builtins.replaceStrings [ "/" ] [ "_" ] f; etcKey = f: builtins.replaceStrings [ "/" ] [ "_" ] f;
tlsMount = {
name = "tls";
mountPath = listener.tlsDir;
};
volumeMounts = volumeMounts =
lib.optional (credIds != [ ]) { lib.optional (credIds != [ ]) {
@ -480,6 +571,13 @@ let
subPath = trustBundleKey; subPath = trustBundleKey;
readOnly = true; readOnly = true;
}) caFiles }) caFiles
++ map (path: {
name = "ca-trust";
mountPath = path;
subPath = publicFiles.${path};
readOnly = true;
}) (lib.attrNames publicFiles)
++ lib.optional (listener != { }) tlsMount
++ lib.optional (runtimeDir != null) { ++ lib.optional (runtimeDir != null) {
name = "runtime"; name = "runtime";
mountPath = runtimeDir; mountPath = runtimeDir;
@ -522,6 +620,20 @@ let
cpu = "0"; 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 = { container = {
inherit name volumeMounts; inherit name volumeMounts;
image = "${image.imageName}:${image.imageTag}"; image = "${image.imageName}:${image.imageTag}";
@ -545,13 +657,8 @@ let
// lib.optionalAttrs (limits != { }) { inherit limits; }; // lib.optionalAttrs (limits != { }) { inherit limits; };
} }
// lib.optionalAttrs (lib.tail execWords != [ ]) { args = lib.tail execWords; } // lib.optionalAttrs (lib.tail execWords != [ ]) { args = lib.tail execWords; }
// lib.optionalAttrs (ports != [ ]) { inherit ports; }
// lib.optionalAttrs (svc.healthEnv != null) { // lib.optionalAttrs (svc.healthEnv != null) {
ports = [
{
name = "health";
containerPort = healthPort;
}
];
livenessProbe = { livenessProbe = {
httpGet = { httpGet = {
path = "/healthz"; 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 = { podSpec = {
inherit terminationGracePeriodSeconds volumes; 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 # 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. # a token of its own, projected for the store's audience.
automountServiceAccountToken = false; automountServiceAccountToken = false;
@ -582,10 +740,31 @@ let
seccompProfile.type = "RuntimeDefault"; 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: { 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 // { spec = podSpec // {
inherit restartPolicy; inherit restartPolicy;
}; };
@ -656,17 +835,7 @@ let
apiVersion = "v1"; apiVersion = "v1";
kind = "ConfigMap"; kind = "ConfigMap";
metadata = metaFor "${name}-etc"; metadata = metaFor "${name}-etc";
data = lib.listToAttrs ( data = etcData;
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
);
}; };
}; };
in in
@ -685,7 +854,11 @@ let
else if missingCreds != { } then else if missingCreds != { } then
fail name "${lib.concatStringsSep ", " (lib.attrNames missingCreds)} names a credential the unit does not load" fail name "${lib.concatStringsSep ", " (lib.attrNames missingCreds)} names a credential the unit does not load"
else 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); enabled = lib.mapAttrs workload (lib.filterAttrs (_: svc: svc.enable) services);
in in
@ -704,7 +877,7 @@ in
# The image each enabled service's pod runs: what a node has to hold, # The image each enabled service's pod runs: what a node has to hold,
# since there is no registry to pull from. # 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 # 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 # have a runtime option and is cheap to read: it names the units that a

View file

@ -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"
'';
}

View file

@ -14,6 +14,10 @@
# client certificate the swarm's store issued for the gateway, with the # 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 # `clientAuth` usage. ./swarm-ui.nix still declares the vhost on the host that
# runs this daemon, so the gateway stays on that host. # 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, pkgs,
lib, lib,
@ -154,6 +158,11 @@ let
storeRetry = import ./lib/store-retry.nix { }; storeRetry = import ./lib/store-retry.nix { };
tcpOn = deployCfg.swarm-controller.enable && tcpCfg.enable; 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 # 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 # gateway, as the operator's own SSO account (`swarmctl login`). The
# controller socket then serves the gateway alone, which always sets # 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 { swarmctlPackage = lib.mkOption {
type = lib.types.package; type = lib.types.package;
defaultText = lib.literalExpression "hyperhive.packages.\${system}.swarmctl"; defaultText = lib.literalExpression "hyperhive.packages.\${system}.swarmctl";
@ -740,6 +785,26 @@ in
IPv6 address is written in brackets. Binding a port opens nothing: IPv6 address is written in brackets. Binding a port opens nothing:
{option}`openFirewall` decides who can reach it, and the TLS {option}`openFirewall` decides who can reach it, and the TLS
handshake decides who may talk once they do. 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.swarm-controller = { };
users.groups.${clientsGroup} = { }; 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 # 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 # 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. # restart nginx (it does not reload) onto the new group.
@ -943,6 +1012,33 @@ in
TCP listener off. 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; assertion = !tcpCfg.enable || caTrust.useSelfSigned;
message = '' message = ''
@ -956,6 +1052,9 @@ in
]; ];
systemd.services.swarm-controller = { 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"; description = "hyperhive swarm-level controller daemon";
wantedBy = [ "multi-user.target" ]; wantedBy = [ "multi-user.target" ];
# The listener's certificate files must exist when the daemon opens it. A # 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, # Same shape as the queue's leaf unit (./swarm-nats.nix,
# `swarm-bao-nats-tls`): the daemon re-reads the files, so rotating needs # `swarm-bao-nats-tls`): the daemon re-reads the files, so rotating needs
# no restart, which for this daemon would drop its job graph. # 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"; description = "Issue the swarm-controller's TCP listener certificate from the secret store's PKI";
wantedBy = [ "multi-user.target" ]; wantedBy = [ "multi-user.target" ];
after = [ after = [
@ -1150,63 +1249,15 @@ in
// lib.optionalAttrs (deployCfg.bao.serverCaFile != null) { // lib.optionalAttrs (deployCfg.bao.serverCaFile != null) {
BAO_CACERT = deployCfg.bao.serverCaFile; BAO_CACERT = deployCfg.bao.serverCaFile;
}; };
script = '' script = tlsIssue.script {
set -euo pipefail login = "bao login -method=cert -token-only";
d=${lib.escapeShellArg tcpHost.tlsDir} credential = "certificate";
name=${lib.escapeShellArg tcpCfg.domain} group = "swarm-controller";
install -d -m 0750 -g swarm-controller "$d" };
# 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"; description = "Daily renewal check for the swarm-controller's TCP listener certificate";
wantedBy = [ "timers.target" ]; wantedBy = [ "timers.target" ];
timerConfig = { timerConfig = {

View file

@ -107,9 +107,17 @@ let
# `toString` below so an unset `domain` reaches the assertion that names it # `toString` below so an unset `domain` reaches the assertion that names it
# instead of failing evaluation first. # instead of failing evaluation first.
controllerTcp = swarmCfg.controller.tcp; 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 = controllerUpstream =
if controllerTcp.enable then if controllerTcp.enable then
"https://${toString controllerTcp.domain}:${toString controllerTcp.port}" "https://${controllerAddress}:${toString controllerTcp.port}"
else else
"http://unix:${deployCfg.swarm-controller.socketPath}:"; "http://unix:${deployCfg.swarm-controller.socketPath}:";
# `proxy_http_version` and `Connection` because `recommendedProxySettings`, # `proxy_http_version` and `Connection` because `recommendedProxySettings`,