Watch
0
0
Fork
You've already forked hyperhive
0

let a second machine join the main node's k3s and run pods from images only the main node holds

This commit is contained in:
atlas 2026-11-25 22:36:35 +01:00 • committed by mara
commit 6be1b59ffc
7 changed files with 1106 additions and 96 deletions

View file

@ -24,6 +24,7 @@ in
{
imports = [
./host-services.nix
./join.nix
./node.nix
./pod-logs.nix
./runtime.nix

View file

@ -0,0 +1,142 @@
# The join token, through the swarm secret store: the main node's k3s server
# writes it, and a host that sets `deploy.k8s.join` reads it before its k3s
# agent starts. Both log in as the hive, the way `squid-selfcheck-credential`
# does (../hive-squid-credential.nix). The leaf and the file are
# ../lib/k8s-join-token.nix; ../swarm-bao.nix grants the read and, to the
# store host's own hive, the write. docs/4-implementation/k8s/node.md has the
# design.
{
pkgs,
lib,
config,
...
}:
let
hyperhiveCfg = config.services.hyperhive;
cfg = hyperhiveCfg.deploy.k8s;
hiveController = hyperhiveCfg.deploy.hive-controller;
tls = hiveController.tls;
baoCfg = hyperhiveCfg.swarm.bao;
baoDeploy = hyperhiveCfg.deploy.bao;
token = import ../lib/k8s-join-token.nix;
haveIdentity = tls.baoHiveIdentityCertFile != null && tls.baoHiveIdentityKeyFile != null;
# The file k3s's server keeps the token agents join with in.
serverTokenFile = "/var/lib/rancher/k3s/server/agent-token";
# Where the store runs on this host, the first login waits for its container.
# No `wants`: a pull would start the container mid-switch on the old closure.
storeContainer = lib.optional baoDeploy.enable "container@${baoCfg.machine}.service";
storeRetry = import ../lib/store-retry.nix { };
common = {
path = [
baoDeploy.package
pkgs.coreutils
pkgs.gnugrep
];
environment = {
BAO_ADDR = "https://${baoCfg.domain}:${toString baoCfg.port}";
BAO_CLIENT_CERT = tls.baoHiveIdentityCertFile;
BAO_CLIENT_KEY = tls.baoHiveIdentityKeyFile;
}
// lib.optionalAttrs (baoDeploy.serverCaFile != null) {
BAO_CACERT = baoDeploy.serverCaFile;
};
# ./lib/store-retry.nix: the login fails for as long as the store is
# sealed or down.
inherit (storeRetry) startLimitBurst startLimitIntervalSec;
wants = [ "network-online.target" ];
after = [ "network-online.target" ] ++ storeContainer;
};
in
{
config = lib.mkMerge [
# The main node: the token k3s generated, in the store.
(lib.mkIf (cfg.enable && haveIdentity) {
systemd.services.k3s-join-token-publish = common // {
description = "Write the k3s join token to the swarm secret store";
wantedBy = [ "k3s.service" ];
after = common.after ++ [ "k3s.service" ];
wants = common.wants ++ [ "k3s.service" ];
serviceConfig = storeRetry.serviceConfig // {
Type = "oneshot";
UMask = "0077";
SyslogIdentifier = "k3s-join-token-publish";
TimeoutStartSec = "5min";
};
script = ''
set -euo pipefail
${import ../lib/store-seeded-secret.nix { }}
# k3s writes the file as it starts.
for _ in $(seq 120); do
[ -s ${serverTokenFile} ] && break
sleep 2
done
if [ ! -s ${serverTokenFile} ]; then
echo "k3s has not written ${serverTokenFile}." >&2
exit 1
fi
value="$(< ${serverTokenFile})"
store_init
store_login
if [ "$STORE_UP" != 1 ]; then
echo "could not log in to the swarm secret store; the join token is not published." >&2
exit 1
fi
if current="$(store_bao kv get -field=value ${lib.escapeShellArg "secret/${token.leaf}"} 2>"$STORE_ERR")" \
&& [ "$current" = "$value" ]; then
exit 0
fi
printf '%s' "$value" |
store_bao kv put ${lib.escapeShellArg "secret/${token.leaf}"} value=- >/dev/null
echo "published the k3s join token at ${token.leaf}."
'';
};
})
# A node that joins: the token, in a file before k3s starts.
(lib.mkIf (cfg.join != null && haveIdentity) {
systemd.services.k3s-join-token = common // {
description = "Read the k3s join token from the swarm secret store";
wantedBy = [ "k3s.service" ];
before = [ "k3s.service" ];
serviceConfig = storeRetry.serviceConfig // {
Type = "oneshot";
UMask = "0077";
SyslogIdentifier = "k3s-join-token";
TimeoutStartSec = "5min";
};
script = ''
set -euo pipefail
${import ../lib/store-seeded-secret.nix { }}
${import ../lib/atomic-write-secret.nix { }}
${import ../lib/refresh-consumer.nix { }}
install -d -m 0700 ${builtins.dirOf token.file}
store_init
store_login
if [ "$STORE_UP" != 1 ]; then
echo "could not log in to the swarm secret store; ${token.file} stays as it is." >&2
exit 1
fi
if ! value="$(store_read ${lib.escapeShellArg "secret/${token.leaf}"})" || [ -z "$value" ]; then
cat "$STORE_ERR" >&2
echo "the swarm secret store holds no k3s join token at ${token.leaf} yet; ${token.file} stays as it is." >&2
exit 1
fi
# Written only when the value changed, so the file keeps its mtime.
if secret_differs ${token.file} "$value"; then
atomic_write_secret 0400 root:root ${token.file} "$value"
fi
'';
};
})
];
}

View file

@ -1,13 +1,16 @@
# The single-node k3s cluster this host runs for the swarm services that run
# in the cluster, the Kubernetes counterpart of `deploy.singleHostSwarm`'s
# all-local swarm. docs/4-implementation/k8s/node.md has the design.
# The k3s cluster this host runs, as its main node, for the swarm services that
# run in the cluster, the Kubernetes counterpart of `deploy.singleHostSwarm`'s
# all-local swarm, and the agent a host that sets `deploy.k8s.join` runs
# instead. docs/4-implementation/k8s/node.md has the design.
#
# The node holds the images of the services ./render.nix renders and has no
# registry. No service's objects are applied until its `runtime` is `k8s`
# The main node holds the images of the services ./render.nix renders and
# shares them with the nodes that join through k3s's embedded registry mirror
# of the images' registry host. No service's objects are applied until its `runtime` is `k8s`
# (./runtime.nix): until then its host unit runs.
{
config,
lib,
pkgs,
...
}:
let
@ -71,6 +74,50 @@ let
labels = import ./labels.nix;
deployCfg = config.services.hyperhive.deploy;
inherit (import ../../images { inherit pkgs lib; }) registryHost;
joinToken = import ../lib/k8s-join-token.nix;
# Mirrors the images' registry host between the nodes, which is how a node
# that holds no copy of an image gets one from a peer that does. The upstream
# `.invalid` host never resolves, so a name no peer holds fails to pull. Only
# this host is mirrored: `"*"` would also route the node's pulls of public
# images through its peers.
# https://docs.k3s.io/installation/registry-mirror
registriesYaml = ''
mirrors:
${registryHost}:
'';
# What the nodes of a cluster reach each other on, and the firewall rules
# that admit those ports from the nodes' addresses and from no others. The
# `extraCommands` run before the firewall's final refusal.
nodePorts = [
{
proto = "tcp";
port = 6443;
}
{
proto = "tcp";
port = 10250;
}
{
proto = "udp";
port = 8472;
}
{
proto = "tcp";
port = 5001;
}
];
admitNodes =
addresses:
lib.concatMapStrings (
address:
lib.concatMapStrings (p: ''
iptables -A nixos-fw -s ${address} -p ${p.proto} --dport ${toString p.port} -j nixos-fw-accept
'') nodePorts
) addresses;
# The services whose data the module keeps in the cluster: those with a
# `runtime` that is `k8s`. Each puts its state label on this node.
stateful = lib.filterAttrs (_: svc: svc.enable && svc.runtime == "k8s") {
@ -83,7 +130,7 @@ in
type = lib.types.bool;
default = false;
description = ''
Run a single-node k3s server on this host, with the images of the
Run a k3s server on this host, the cluster's main node, with the images of the
swarm services that run in the cluster loaded into it, and render
their manifests (`services.hyperhive.k8s.enable`). Set it on the host
that runs the swarm's services, which is the one
@ -216,6 +263,66 @@ in
'';
};
address = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "192.168.1.10";
description = ''
The address the other nodes of the cluster reach this node on. Set, it
is the node's IP (`--node-ip`), so flannel's tunnel endpoint and the
node's registered address are it, and a server also lists it in its API
certificate (`--tls-san`). Null leaves k3s to pick the address of the
default route.
'';
};
nodeAddresses = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
example = [
"192.168.1.11"
"192.168.1.12"
];
description = ''
The IPv4 addresses of the nodes that may join this cluster. The
firewall admits the cluster's node-to-node ports (TCP 6443 for the API
and the image mirror, TCP 10250 for the kubelet, UDP 8472 for flannel's
VXLAN tunnel, TCP 5001 for the mirror's peers) from these addresses
and from no others. Empty opens none of them. The firewall's
iptables backend is required: the rules are not written for nftables.
'';
};
join = lib.mkOption {
type = lib.types.nullOr (
lib.types.submodule {
options.server = lib.mkOption {
type = lib.types.str;
example = "192.168.1.10";
description = ''
The address of the cluster's main node, the host that sets
{option}`services.hyperhive.deploy.k8s.enable`.
'';
};
}
);
default = null;
description = ''
Make this host a k3s agent of the cluster the main node at `server`
runs, instead of a node of its own. It runs the cluster's pods and none
of the server's manifests or units. It holds no state label or entry
label, so a pod that keeps data on a node's disk does not run here.
The join token comes from the swarm secret store: the main node's
`k3s-join-token-publish` unit writes it, and this host's
`k3s-join-token` unit reads it under the hive's store identity
({option}`services.hyperhive.deploy.hive-controller.tls.baoHiveIdentityCertFile`)
before k3s starts. Set {option}`services.hyperhive.deploy.k8s.address`
to the address the main node reaches this host on, and list it in the
main node's {option}`services.hyperhive.deploy.k8s.nodeAddresses`.
'';
};
manifestDir = lib.mkOption {
type = lib.types.str;
readOnly = true;
@ -228,75 +335,132 @@ in
};
};
config = lib.mkIf cfg.enable {
assertions = [
{
assertion = config.services.hyperhive.k8s.enable;
message = ''
services.hyperhive.deploy.k8s.enable loads the images
services.hyperhive.k8s.enable renders into the node, so it needs
services.hyperhive.k8s.enable to be true.
'';
}
{
assertion =
!networkCfg.enable
|| !(lib.any (overlap networkCfg.networkCidr) [
cfg.podCidr
cfg.serviceCidr
]);
message = ''
services.hyperhive.deploy.k8s.podCidr (${cfg.podCidr}) and
services.hyperhive.deploy.k8s.serviceCidr (${cfg.serviceCidr}) must
not overlap the hive bridge's subnet (${networkCfg.networkCidr}, from
services.hyperhive.network.bridgeIp and bridgePrefixLength): the
bridge and the cluster would route the same addresses.
'';
}
{
assertion = !(overlap cfg.podCidr cfg.serviceCidr);
message = ''
services.hyperhive.deploy.k8s.podCidr (${cfg.podCidr}) and
services.hyperhive.deploy.k8s.serviceCidr (${cfg.serviceCidr}) must
not overlap each other.
'';
}
];
services.hyperhive.k8s.enable = lib.mkDefault true;
services.k3s = {
enable = true;
role = "server";
disable = [
"traefik"
"metrics-server"
config = lib.mkMerge [
(lib.mkIf cfg.enable {
assertions = [
{
assertion = cfg.join == null;
message = ''
services.hyperhive.deploy.k8s.enable runs this host as the cluster's
main node and services.hyperhive.deploy.k8s.join as a node of another
host's cluster: set one.
'';
}
{
assertion = config.services.hyperhive.k8s.enable;
message = ''
services.hyperhive.deploy.k8s.enable loads the images
services.hyperhive.k8s.enable renders into the node, so it needs
services.hyperhive.k8s.enable to be true.
'';
}
{
assertion =
!networkCfg.enable
|| !(lib.any (overlap networkCfg.networkCidr) [
cfg.podCidr
cfg.serviceCidr
]);
message = ''
services.hyperhive.deploy.k8s.podCidr (${cfg.podCidr}) and
services.hyperhive.deploy.k8s.serviceCidr (${cfg.serviceCidr}) must
not overlap the hive bridge's subnet (${networkCfg.networkCidr}, from
services.hyperhive.network.bridgeIp and bridgePrefixLength): the
bridge and the cluster would route the same addresses.
'';
}
{
assertion = !(overlap cfg.podCidr cfg.serviceCidr);
message = ''
services.hyperhive.deploy.k8s.podCidr (${cfg.podCidr}) and
services.hyperhive.deploy.k8s.serviceCidr (${cfg.serviceCidr}) must
not overlap each other.
'';
}
];
nodeLabel = lib.mapAttrsToList (k: v: "${k}=${v}") cfg.nodeLabels;
extraFlags = [
"--secrets-encryption"
"--cluster-cidr=${cfg.podCidr}"
"--service-cidr=${cfg.serviceCidr}"
"--data-dir=${dataDir}"
"--cluster-domain=${clusterDomain}"
"--cluster-dns=${clusterDns}"
services.hyperhive.k8s.enable = lib.mkDefault true;
services.k3s = {
enable = true;
role = "server";
disable = [
"traefik"
"metrics-server"
];
nodeLabel = lib.mapAttrsToList (k: v: "${k}=${v}") cfg.nodeLabels;
nodeIP = cfg.address;
extraFlags = [
"--secrets-encryption"
"--embedded-registry"
"--cluster-cidr=${cfg.podCidr}"
"--service-cidr=${cfg.serviceCidr}"
"--data-dir=${dataDir}"
"--cluster-domain=${clusterDomain}"
"--cluster-dns=${clusterDns}"
]
++ lib.optional (cfg.address != null) "--tls-san=${cfg.address}";
# k3s's own images come first: the mirror holds only the hyperhive
# images, so the node pulls nothing else, not even CoreDNS.
images = [
config.services.k3s.package.airgap-images
]
++ (config.system.build.k8sImages or [ ]);
};
networking.firewall.trustedInterfaces = cfg.cniInterfaces;
networking.firewall.extraCommands = admitNodes cfg.nodeAddresses;
environment.etc."rancher/k3s/registries.yaml".text = registriesYaml;
# The host's resolver (the hive's dnsmasq, which the host's own
# `/etc/resolv.conf` names) hands the cluster's domain to CoreDNS, so a
# Service is reachable from the host by its name. The bridge's agents ask
# the same resolver and get the same answers.
services.dnsmasq.settings.server = lib.mkIf config.services.hyperhive.gateway.dns.enable [
"/${clusterDomain}/${clusterDns}"
];
# k3s's own images come first: with no registry the node pulls nothing,
# not even CoreDNS.
images = [
config.services.k3s.package.airgap-images
]
++ (config.system.build.k8sImages or [ ]);
};
})
networking.firewall.trustedInterfaces = cfg.cniInterfaces;
# An agent of another host's cluster. The server's manifests and units are
# not here: the pods it runs come from the main node's API.
(lib.mkIf (cfg.join != null && !cfg.enable) {
assertions = [
{
assertion =
deployCfg.hive-controller.tls.baoHiveIdentityCertFile != null
&& deployCfg.hive-controller.tls.baoHiveIdentityKeyFile != null;
message = ''
services.hyperhive.deploy.k8s.join reads the join token from the
swarm secret store under the hive's identity, so
services.hyperhive.deploy.hive-controller.tls.baoHiveIdentityCertFile
and baoHiveIdentityKeyFile must name it.
'';
}
{
assertion = !config.networking.nftables.enable;
message = ''
services.hyperhive.deploy.k8s.join admits the cluster's ports with
iptables rules, which networking.nftables.enable replaces.
'';
}
];
# The host's resolver (the hive's dnsmasq, which the host's own
# `/etc/resolv.conf` names) hands the cluster's domain to CoreDNS, so a
# Service is reachable from the host by its name. The bridge's agents ask
# the same resolver and get the same answers.
services.dnsmasq.settings.server = lib.mkIf config.services.hyperhive.gateway.dns.enable [
"/${clusterDomain}/${clusterDns}"
];
};
services.k3s = {
enable = true;
role = "agent";
serverAddr = "https://${cfg.join.server}:6443";
tokenFile = joinToken.file;
nodeIP = cfg.address;
# k3s's own images first, for the reason the server's are: a node with
# no route to a public registry pulls nothing else.
images = [ config.services.k3s.package.airgap-images ];
};
networking.firewall.trustedInterfaces = cfg.cniInterfaces;
networking.firewall.extraCommands = admitNodes (
lib.unique ([ cfg.join.server ] ++ cfg.nodeAddresses)
);
environment.etc."rancher/k3s/registries.yaml".text = registriesYaml;
})
];
}

View file

@ -841,8 +841,9 @@ let
container = {
inherit name volumeMounts;
image = "${image.imageName}:${image.imageTag}";
# The node imports the image tarball; there is no registry to pull from.
imagePullPolicy = "Never";
# A node without the image pulls it from a peer that holds it
# (the mirror in ./node.nix); the name's host resolves nowhere else.
imagePullPolicy = "IfNotPresent";
env = lib.mapAttrsToList (n: v: {
name = n;
value = v;
@ -907,7 +908,7 @@ let
leafContainer = {
name = "tls-issue";
image = "${leafImage.imageName}:${leafImage.imageTag}";
imagePullPolicy = "Never";
imagePullPolicy = "IfNotPresent";
env =
lib.mapAttrsToList
(n: v: {
@ -1143,8 +1144,8 @@ in
}
// lib.concatMapAttrs (_: w: w.objects) enabled;
# The image each enabled service's pod runs: what a node has to hold,
# since there is no registry to pull from.
# The image each enabled service's pod runs: what the main node imports,
# for the others to pull from it.
images = lib.unique (lib.concatMap (w: [ w.image ] ++ w.extraImages) (lib.attrValues enabled));
# What ./runtime.nix moves services with. `switches` holds the services that

View file

@ -0,0 +1,11 @@
# What the k3s server and a node that joins it agree on about the join token:
# the leaf of the swarm secret store the server's unit writes it to
# (../k8s/join.nix) and the file the joining node's unit lands it in, which k3s
# reads as its token. ../swarm-bao.nix grants the hives' identities a read of
# the leaf.
{
# Under KV v2's `secret/` mount, as `bao kv` takes it.
leaf = "swarm/services/k8s/agent-token";
# On the node that joins. A tmpfs, so the token is fetched again at boot.
file = "/run/k3s-join/token";
}

View file

@ -45,6 +45,7 @@ let
# about the pods' login.
k8sNode = deployCfg.k8s;
podAuth = import ./lib/bao-pod-auth.nix;
k8sJoinToken = import ./lib/k8s-join-token.nix;
shared = import ./lib/swarm-bao-shared.nix { inherit config lib pkgs; };
inherit (shared)
@ -920,7 +921,10 @@ let
}) hyperhiveCfg.swarm.hives;
# What a hive's gateway-leaf identity may do: issue from its own role, read
# two of its own cache facts, and read its own squid self-check credential.
# two of its own cache facts, read its own squid self-check credential, and
# read the k3s join token a node that joins fetches
# (./k8s/join.nix); the hive of this host, which runs the cluster's main
# node, also writes it.
# The root unit on the hive host (`hive-priv-cache-facts`,
# ./hive-priv-cache.nix) reads the facts under this identity: the key
# hive-priv's downloads must be signed by, and the token it pulls with. The
@ -941,6 +945,16 @@ let
"pull-token"
]
+ readStanza "${credentialMountPath}/data/swarm/hives/${obj.hiveName}/squid-selfcheck"
+ (
if k8sNode.enable && obj.hiveName == deployCfg.hive-controller.hiveName then
''
path "${credentialMountPath}/data/${k8sJoinToken.leaf}" {
capabilities = ["create", "read", "update"]
}
''
else
readStanza "${credentialMountPath}/data/${k8sJoinToken.leaf}"
)
# The archive credentials swarm-controller writes for the agents this hive
# places: the backup unit (./hive-archive-backup.nix) lists them and reads each.
+ readStanza "${credentialMountPath}/data/swarm/hives/${obj.hiveName}/archive/*"

View file

@ -925,7 +925,7 @@ let
fromInit = name: bin: extraEnv: from: extraMounts: {
inherit name securityContext;
image = ref init;
imagePullPolicy = "Never";
imagePullPolicy = "IfNotPresent";
command = [ "/bin/${bin}" ];
env = lib.mapAttrsToList (n: v: {
name = n;
@ -990,7 +990,7 @@ let
{
name = "nats";
image = ref server;
imagePullPolicy = "Never";
imagePullPolicy = "IfNotPresent";
args = lib.tail (lib.splitString " " natsSystem.systemd.services.nats.serviceConfig.ExecStart);
# The port the client Service targets.
ports = [
@ -1029,7 +1029,7 @@ let
{
name = "exporter";
image = ref exporter;
imagePullPolicy = "Never";
imagePullPolicy = "IfNotPresent";
args = [
"-addr"
"0.0.0.0"