Watch
0
0
Fork
You've already forked hyperhive
0

k8s: the controller pod keeps no volume; the state gate goes

This commit is contained in:
atlas 2026-11-23 05:45:57 +01:00 • committed by maia
commit 4ea3b0e10d
9 changed files with 233 additions and 1110 deletions

View file

@ -85,6 +85,12 @@ let
in
{
imports = [
(lib.mkRemovedOptionModule [ "services" "hyperhive" "deploy" "swarm-controller" "k8s" "freshState" ]
''
The pod keeps its state directory in an emptyDir, so it starts on any
node with no state to migrate. Remove this definition.
''
)
(lib.mkRemovedOptionModule [ "services" "hyperhive" "deploy" "nats" "k8s" "freshState" ] ''
The pod mounts the host unit's own store directory, so there is no empty
volume to start on and no state gate. Remove this definition.

View file

@ -4,11 +4,8 @@
#
# The file has one entry per service that has a `runtime` option: the
# option's path, the runtime the configuration wants, the host units that run
# the service when it is on the host, and, where the service keeps state in a
# volume, that state: the claim, the mount in the pod, where the data lives
# on the host, and what a copy leaves out. Paths are computed here, never
# derived by `swarmctl`. Both exist only on a host with the node
# (./node.nix): without a cluster there is nothing to read.
# the service when it is on the host. The file and the wrapper exist only on a
# host with the node (./node.nix): without a cluster there is nothing to read.
{
lib,
pkgs,
@ -21,71 +18,22 @@ let
node = deployCfg.k8s;
controllerCfg = deployCfg.swarm-controller;
# The path of a unit's state directory in a pod, which ./render.nix mounts
# the claim at.
stateMount = unit: "/var/lib/${unit.serviceConfig.StateDirectory}";
pathsWithin = import ../lib/paths-within.nix { inherit lib; };
controllerStateDir = "/var/lib/swarm-controller";
# `option` is the service's name under `services.hyperhive.deploy`. `state`
# is null for a service with nothing to copy: no volume, an `emptyDir`, a
# volume that starts empty with no gate, or (the queue) the host unit's own
# directory, mounted into the pod.
#
# The claim is `<service>-state`, as ./render.nix names it.
stateTable = {
swarm-controller = {
option = "swarm-controller";
state = {
mount = stateMount controllerCfg.unit;
hostPath = controllerStateDir;
# The pod issues its own leaf with its own store login, so a bao
# identity an operator keeps in this directory stays behind.
excludes = pathsWithin controllerStateDir [
controllerCfg.baoClientCertFile
controllerCfg.baoClientKeyFile
];
};
};
swarm-nats = {
option = "nats";
state = null;
};
swarm-notify-router = {
option = "notify-router";
state = null;
};
swarm-stt = {
option = "stt";
state = null;
};
swarm-review-classifier = {
option = "review-classifier";
state = null;
};
swarm-claude-login = {
option = "claude-login";
state = null;
};
swarm-ci-metrics = {
option = "ci-metrics";
state = null;
};
# Each service's name under `services.hyperhive.deploy`.
optionOf = {
swarm-controller = "swarm-controller";
swarm-nats = "nats";
swarm-notify-router = "notify-router";
swarm-stt = "stt";
swarm-review-classifier = "review-classifier";
swarm-claude-login = "claude-login";
swarm-ci-metrics = "ci-metrics";
};
entry =
name: switch:
let
row = stateTable.${name};
in
{
option = "services.hyperhive.deploy.${row.option}.runtime";
inherit (switch) runtime;
hostUnits = lib.toList switch.hostUnit;
state = lib.mapNullable (s: s // { claim = "${name}-state"; }) row.state;
};
entry = name: switch: {
option = "services.hyperhive.deploy.${optionOf.${name}}.runtime";
inherit (switch) runtime;
hostUnits = lib.toList switch.hostUnit;
};
migrateJson = {
inherit (cfg) namespace;

View file

@ -128,22 +128,6 @@ let
];
};
# The state gate: one image and script for every pod that keeps state in a
# volume (./state-gate.nix).
stateGateBin = "hyperhive-state-gate";
stateGateImage = mkServiceImage {
name = "state-gate";
package = import ./state-gate.nix { inherit pkgs lib; };
bin = stateGateBin;
};
# What a service's state gate reads of the install: whether its
# `k8s.freshState` holds, and the option's path, which the refusal names.
freshOf = name: cfg: {
enabled = cfg.k8s.freshState;
option = "services.hyperhive.deploy.${name}.k8s.freshState";
};
# 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
@ -152,11 +136,9 @@ let
# 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.
# `fresh` (`freshOf`) is set on a service whose state is worth moving: the
# volume's first init container, the state gate, refuses to start the pod on
# one that holds no migrated state unless the install is fresh. A service
# without it starts on whatever volume it gets, and one with
# `ephemeralState` gets an `emptyDir` in place of a claim.
# `ephemeralState` gives a service an `emptyDir` in place of a claim for its
# state directory: what it keeps there is re-derived at start. A pod starts on
# whatever volume it gets.
# `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
@ -192,7 +174,7 @@ let
# The unit pushes to the swarm collector's route and mints its own bearer
# (../glue-controller-env.nix, `otel_http_client.rs`).
otlp = "own";
fresh = freshOf "swarm-controller" controllerCfg;
ephemeralState = true;
switch = {
inherit (controllerCfg) runtime;
hostUnit = "swarm-controller.service";
@ -776,43 +758,6 @@ let
package = leafImagePackage;
bin = leafIssueBin;
};
# The volume the state gate checks, and where it is mounted: that of a
# service with a `fresh` option, none for the rest.
stateVolume =
if svc ? fresh && stateDir != null then
{
volume = "state";
path = stateDir;
}
else
null;
stateGate = lib.optionalAttrs (stateVolume != null) {
name = "state-gate";
image = "${stateGateImage.imageName}:${stateGateImage.imageTag}";
imagePullPolicy = "Never";
command = [ "/bin/${stateGateBin}" ];
env =
lib.mapAttrsToList
(n: v: {
name = n;
value = v;
})
{
STATE_GATE_DIR = stateVolume.path;
STATE_GATE_SERVICE = name;
STATE_GATE_FRESH = lib.boolToString svc.fresh.enabled;
STATE_GATE_OPTION = svc.fresh.option;
};
volumeMounts = [
{
name = stateVolume.volume;
mountPath = stateVolume.path;
}
];
inherit (container) securityContext;
};
# What the service adds to the daemon's pod.
extra = {
containers = [ ];
@ -890,11 +835,8 @@ let
};
}
// lib.optionalAttrs baoLogin { serviceAccountName = name; }
// lib.optionalAttrs (stateVolume != null || listener != { } || extra.initContainers != [ ]) {
initContainers =
lib.optional (stateVolume != null) stateGate
++ lib.optional (listener != { }) leafContainer
++ extra.initContainers;
// lib.optionalAttrs (listener != { } || extra.initContainers != [ ]) {
initContainers = lib.optional (listener != { }) leafContainer ++ extra.initContainers;
}
// lib.optionalAttrs (extra.hostAliases != [ ]) { inherit (extra) hostAliases; }
// extra.podSpec;
@ -1014,10 +956,7 @@ let
{
inherit objects image;
# What the pod's other containers run.
extraImages =
lib.optional (stateVolume != null) stateGateImage
++ lib.optional (listener != { }) leafImage
++ extra.images;
extraImages = lib.optional (listener != { }) leafImage ++ extra.images;
};
enabled = lib.mapAttrs workload (lib.filterAttrs (_: svc: svc.enable) services);

View file

@ -1,47 +0,0 @@
# The state gate: the first init container of every pod that keeps state in a
# volume. It reads `STATE_GATE_DIR` (the volume's mount), `STATE_GATE_SERVICE`,
# `STATE_GATE_FRESH` (`true` or `false`) and `STATE_GATE_OPTION` (the option
# that sets the fresh install). It exits 0 only with `.hyperhive-migrated` in
# the volume, or on an empty volume where the install is fresh, which gets the
# marker. Any other volume stops the pod in `Init:Error`, with the reason in
# the container's termination message.
{ pkgs, lib }:
pkgs.writeShellScriptBin "hyperhive-state-gate" ''
export PATH=${lib.makeBinPath [ pkgs.coreutils ]}
set -eu
dir=''${STATE_GATE_DIR:?}
svc=''${STATE_GATE_SERVICE:?}
fresh=''${STATE_GATE_FRESH:?}
option=''${STATE_GATE_OPTION:?}
marker="$dir/.hyperhive-migrated"
refuse() {
echo "$1" >&2
echo "$1" > /dev/termination-log 2>/dev/null || true
exit 1
}
if [ -e "$marker" ]; then
echo "$svc: state volume is migrated"
exit 0
fi
empty=true
for f in "$dir"/* "$dir"/.[!.]* "$dir"/..?*; do
[ -e "$f" ] || [ -L "$f" ] || continue
case "''${f##*/}" in
lost+found | .hyperhive-migrated.new) ;;
*) empty=false ;;
esac
done
if [ "$empty" = false ]; then
refuse "$svc: state volume has not been migrated: it holds files and no .hyperhive-migrated marker, so a copy may have been cut off: run \`swarmctl migrate $svc\` again"
fi
if [ "$fresh" != true ]; then
refuse "$svc: state volume has not been migrated: run \`swarmctl migrate $svc\`, or set $option for a fresh install"
fi
printf '{"fresh": true, "at": "%s"}\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$marker.new"
mv "$marker.new" "$marker"
echo "$svc: state volume is empty and the install is fresh: marked"
''

View file

@ -1,20 +0,0 @@
# The `k8s.freshState` option of a service whose pod keeps state in a volume.
# `name` is the service's key under `services.hyperhive.deploy`. ../k8s/render.nix
# reads it into the pod's state gate.
{ lib }:
name:
lib.mkOption {
type = lib.types.bool;
default = false;
example = true;
description = ''
With {option}`services.hyperhive.deploy.${name}.runtime` set to `k8s`: let
the pod start on an empty state volume. Off, the pod's first init container
stops it before the service starts and says so, until the volume holds
the `.hyperhive-migrated` marker that `swarmctl migrate` writes after it
copies the host's state in. On, an empty volume gets the marker at once
and the service starts with no state. Set it on a fresh install, which
has no state to lose. A volume that holds files and no marker is refused
either way, since a copy may have been cut off.
'';
}

View file

@ -1,11 +0,0 @@
# `pathsWithin dir paths`: the entries of `paths` that sit under `dir`, relative
# to it. A null entry, and a path elsewhere (or `dir` itself), is left out.
{ lib }:
dir: paths:
lib.concatMap (
path:
let
prefix = "${dir}/";
in
lib.optional (path != null && lib.hasPrefix prefix path) (lib.removePrefix prefix path)
) paths

View file

@ -635,17 +635,15 @@ in
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, and the pod does not start on it until `swarmctl migrate`
marks it or
{option}`services.hyperhive.deploy.swarm-controller.k8s.freshState`
is set.
listener on {option}`tcp.hostAddress`. The pod's state directory is an
`emptyDir`: the operator grant record is in the queue's key-value
store, and what is left in the directory (the forge avatar markers, the
legacy webhook secret the store also holds) is made again at start. A
host's legacy grant file is imported into the store by the first start
of the controller on the host, so run it there once before the switch.
'';
};
k8s.freshState = import ./lib/fresh-state-option.nix { inherit lib; } "swarm-controller";
unit = lib.mkOption {
type = lib.types.raw;
readOnly = true;

View file

@ -108,16 +108,6 @@ let
inherit lib pkgs config;
}).objects;
objects = render allLocal;
# The same configuration with every state gate on a fresh install. The
# fixtures leave the option off, so the cases that compare two hosts'
# manifests differ only by where a unit comes from.
freshInstall =
config:
lib.recursiveUpdate config {
services.hyperhive.deploy = {
swarm-controller.k8s.freshState = true;
};
};
# The queue's pod reads the settings of the system it runs from, which differ
# in the path of the server's key: what a switch must leave alone is the rest.
notQueue = lib.filterAttrs (n: _: !(lib.hasPrefix "swarm-nats/" n));
@ -365,18 +355,17 @@ let
{
# The images are the ones the manifests run, one per rendered service, the
# controller's listener leaf, the queue's three more (server, exporter,
# init) and the one state gate every stateful pod shares: the twelve are
# the control that the list is not empty.
# init): the eleven 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 == 12
lib.length rendered == 11
&& lib.all (i: lib.elem i loaded) rendered
&& lib.elem (toString withNode.services.k3s.package.airgap-images) loaded
&& lib.length loaded == 13;
&& lib.length loaded == 12;
}
{
# Nothing the host already runs differs but the store's side of the pods'
@ -1448,7 +1437,6 @@ let
== [
"ConfigMap"
"Deployment"
"PersistentVolumeClaim"
"ServiceAccount"
];
}
@ -1506,7 +1494,7 @@ let
&& 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)
&& map (c: c.name) (podSpec "swarm-controller").initContainers == [ "state-gate" ];
&& !((podSpec "swarm-controller") ? initContainers);
}
{
# The pod issues its own listener leaf with the unit's script, logging in
@ -1527,7 +1515,7 @@ let
createDir = false;
};
spec = (render onCluster)."swarm-controller/deployment".spec.template.spec;
init = lib.elemAt spec.initContainers 1;
init = lib.head spec.initContainers;
renew = lib.last spec.containers;
main = lib.head spec.containers;
mountsOf = x: map (m: m.name) x.volumeMounts;
@ -1546,11 +1534,7 @@ let
&& !(lib.hasInfix "chgrp" podScript)
&& lib.hasInfix "-checkhost \"$name\"" podScript
&& lib.hasInfix "issue/swarm-controller-tls" podScript
&&
map (c: c.name) spec.initContainers == [
"state-gate"
"tls-issue"
]
&& map (c: c.name) spec.initContainers == [ "tls-issue" ]
&& init.name == "tls-issue"
&& renew.name == "tls-renew"
&& renew.command == [ "/bin/swarm-controller-tls-renew" ]
@ -1688,11 +1672,11 @@ let
&& pvc.spec.accessModes == [ "ReadWriteOnce" ]
# The claim binds by name the static local volume on the container's
# store directory, on this node, and only that: its class is its own.
# The controller's claim is the control that a claim does not.
# The poller's claim is the control that a claim does not.
&& pvc.spec.volumeName == pv.metadata.name
&& pvc.spec.storageClassName == pv.spec.storageClassName
&& pv.spec.storageClassName != ""
&& !(objects."swarm-controller/persistentvolumeclaim".spec ? volumeName)
&& !(objects."swarm-ci-metrics/persistentvolumeclaim".spec ? volumeName)
&& pv.spec.local.path == hostStore
&& pv.spec.persistentVolumeReclaimPolicy == "Retain"
&& !(pv.metadata ? namespace)
@ -1716,81 +1700,48 @@ let
&& !(lib.any (v: v ? secret) spec.volumes);
}
{
# The gate is the first init container of a pod whose state is worth
# moving, ahead of the TLS leaf. The default holds the pod back; a fresh
# install opts in. Each arm's value is the control for the other, and the
# gated services are the control for the ones that start with no gate.
name = "every pod whose state is worth moving starts with the state gate on that volume, and the fresh option sets what it reads";
# No pod starts on a gate: its first init container is the leaf's or
# none. Each pod's state directory is read off the manifest: an emptyDir
# where the service re-derives what it keeps, a claim where it does not
# (the poller's cursor), and the queue's claim is its own, bound to the
# host's directory. The claims are the control for the emptyDirs.
name = "no pod starts on a state gate, and the state directories are emptyDirs except the poller's claim and the queue's volume";
ok =
let
fresh = render (freshInstall onCluster);
specOf =
objs: name:
name:
let
o = objs."${name}/deployment" or objs."${name}/cronjob";
o = objects."${name}/deployment" or objects."${name}/cronjob";
in
if o.kind == "CronJob" then o.spec.jobTemplate.spec.template.spec else o.spec.template.spec;
inits = objs: name: (specOf objs name).initContainers or [ ];
gate = objs: name: lib.findFirst (i: i.name == "state-gate") null (inits objs name);
envOfGate = g: lib.listToAttrs (map (e: lib.nameValuePair e.name e.value) g.env);
gated = {
swarm-controller = {
path = "/var/lib/swarm-controller";
volume = "state";
option = "deploy.swarm-controller.k8s.freshState";
};
};
# The poller keeps a claim for its cursor and the queue one on the host's
# directory; the speech-to-text pod keeps none. None is gated.
unclaimed = [
stateVolume = name: lib.findFirst (v: v.name == "state") null (specOf name).volumes;
services = [
"swarm-controller"
"swarm-nats"
"swarm-notify-router"
"swarm-stt"
"swarm-review-classifier"
"swarm-claude-login"
"swarm-stt"
];
ungated = unclaimed ++ [
"swarm-ci-metrics"
"swarm-nats"
];
one =
name: g:
let
held = gate objects name;
open = gate fresh name;
full = "services.hyperhive.${g.option}";
in
(lib.head (inits objects name)).name == "state-gate"
&& (lib.head (inits fresh name)).name == "state-gate"
&& (envOfGate held).STATE_GATE_DIR == g.path
&& (envOfGate held).STATE_GATE_SERVICE == name
&& (envOfGate held).STATE_GATE_FRESH == "false"
&& (envOfGate open).STATE_GATE_FRESH == "true"
&& (envOfGate held).STATE_GATE_OPTION == full
# The option the refusal names exists, and is the one that is set.
&& lib.hasAttrByPath (lib.splitString "." full) onCluster
&& lib.attrByPath (lib.splitString "." full) null (freshInstall onCluster) == true
&& lib.attrByPath (lib.splitString "." full) null onCluster == false
&& lib.attrByPath (lib.splitString "." full) null allLocal == false
# The gate mounts the volume the daemon's pod claims, writable.
&&
held.volumeMounts == [
{
name = g.volume;
mountPath = g.path;
}
]
&& lib.any (v: v.name == g.volume && v ? persistentVolumeClaim) (specOf objects name).volumes
&& held.image == open.image
&& !(held ? resources);
in
lib.all (n: one n gated.${n}) (lib.attrNames gated)
&& lib.all (n: gate objects n == null && gate fresh n == null) ungated
&& lib.all (n: !(objects ? "${n}/persistentvolumeclaim")) unclaimed
&& lib.all (n: objects ? "${n}/persistentvolumeclaim") (
lib.attrNames gated ++ [ "swarm-ci-metrics" ]
)
# One image serves every gate.
&& lib.length (lib.unique (map (n: (gate objects n).image) (lib.attrNames gated))) == 1;
lib.all (n: !(lib.any (i: i.name == "state-gate") ((specOf n).initContainers or [ ]))) services
&&
stateVolume "swarm-controller" == {
name = "state";
emptyDir = { };
}
&&
stateVolume "swarm-stt" == {
name = "state";
emptyDir = { };
}
&& !(objects ? "swarm-controller/persistentvolumeclaim")
&& !(objects ? "swarm-stt/persistentvolumeclaim")
&& (stateVolume "swarm-ci-metrics").persistentVolumeClaim.claimName == "swarm-ci-metrics-state"
&& objects ? "swarm-ci-metrics/persistentvolumeclaim"
&& !(lib.any (n: lib.hasInfix "state-gate" n) (map toString withNode.system.build.k8sImages))
&& objects ? "swarm-nats/persistentvolumeclaim";
}
{
# The responder's unit is the container's on the host and the
@ -1875,67 +1826,28 @@ let
&& has "-t raw -F nixos-fw-nats" onCluster.networking.firewall.extraStopCommands;
}
{
# Each state block is read against what the render makes: the claim is
# the PVC's name and the mount is where the state gate looks. The
# stateless services are the control that an entry can carry no state. The
# poller has a claim and no entry, since it starts without a gate.
name = "migrate.json names every service, with a state block exactly for the ones whose state is gated";
ok =
let
services = (migrateOf withNode).services;
stateful = [
"swarm-controller"
];
stateless = [
"swarm-nats"
"swarm-notify-router"
"swarm-review-classifier"
"swarm-claude-login"
"swarm-stt"
"swarm-ci-metrics"
];
objs = render withNode;
gateDir =
n:
let
o = objs."${n}/deployment" or objs."${n}/cronjob";
spec = if o.kind == "CronJob" then o.spec.jobTemplate.spec.template.spec else o.spec.template.spec;
gate = lib.head (lib.filter (c: c.name == "state-gate") spec.initContainers);
in
(lib.head (lib.filter (e: e.name == "STATE_GATE_DIR") gate.env)).value;
in
lib.sort lib.lessThan (lib.attrNames services) == lib.sort lib.lessThan (stateful ++ stateless)
&& lib.all (
n:
let
s = services.${n}.state;
in
s != null
&& s.claim == objs."${n}/persistentvolumeclaim".metadata.name
&& s.mount == gateDir n
&& s ? hostPath
&& s ? excludes
) stateful
&& lib.all (n: services.${n}.state == null) stateless
# The poller's claim is the control that a state of null is no claim's absence.
&& objs ? "swarm-ci-metrics/persistentvolumeclaim"
&& lib.all (n: lib.hasPrefix "services.hyperhive.deploy." services.${n}.option) (
lib.attrNames services
);
}
{
name = "migrate.json gives the host path of each state, the host units of each service and the runtime the configuration wants";
# The file names the runtime and the host units of every service and no
# state: nothing is copied. The units of the poller (timer and service)
# are the control for a list of more than one.
name = "migrate.json names every service with its option, host units and the runtime the configuration wants, and no state";
ok =
let
host = (migrateOf withNode).services;
cluster = (migrateOf onCluster).services;
in
(migrateOf withNode).namespace == "hyperhive"
&& host.swarm-controller.state.hostPath == "/var/lib/swarm-controller"
# The queue's store is mounted in place, so nothing is copied.
&& host.swarm-nats.state == null
&& host.swarm-ci-metrics.state == null
&& host.swarm-stt.state == null
&&
lib.sort lib.lessThan (lib.attrNames host) == [
"swarm-ci-metrics"
"swarm-claude-login"
"swarm-controller"
"swarm-nats"
"swarm-notify-router"
"swarm-review-classifier"
"swarm-stt"
]
&& lib.all (s: !(s ? state)) (lib.attrValues host)
&& lib.all (n: lib.hasPrefix "services.hyperhive.deploy." host.${n}.option) (lib.attrNames host)
&&
host.swarm-ci-metrics.hostUnits == [
"swarm-ci-metrics.timer"
@ -1945,35 +1857,7 @@ let
&& host.swarm-ci-metrics.option == "services.hyperhive.deploy.ci-metrics.runtime"
&& lib.all (s: s.runtime == "host") (lib.attrValues host)
# The runtime follows the option: the cluster fixture has every one on k8s.
&& lib.all (s: s.runtime == "k8s") (lib.attrValues cluster)
&& cluster.swarm-controller.state == host.swarm-controller.state;
}
{
# A pure function, so the case needs no host of its own. A path inside the
# directory is the presence control; a path elsewhere, a null and the
# directory itself are left out.
name = "the controller's bao identity is excluded from its copy only where it sits in the state directory";
ok =
let
within = import ../host-modules/lib/paths-within.nix { inherit lib; };
dir = "/var/lib/swarm-controller";
in
within dir [
"/var/lib/swarm-controller/bao-client.pem"
"/var/lib/swarm-controller/sub/key.pem"
] == [
"bao-client.pem"
"sub/key.pem"
]
&&
within dir [
"/var/lib/swarm-bao-pki/controller.pem"
null
dir
"/var/lib/swarm-controller-tls/x.pem"
] == [ ]
# The module's own default puts them outside it.
&& (migrateOf withNode).services.swarm-controller.state.excludes == [ ];
&& lib.all (s: s.runtime == "k8s") (lib.attrValues cluster);
}
{
name = "swarmctl is wrapped with kubectl and the cluster's kubeconfig, by one wrapper per host";

View file

@ -15,13 +15,10 @@
# runtime and run here in a nginx of its own, reaches the controller: on the
# host by name, in the cluster by the node's address, verifying the leaf as
# the name; the controller answers an unsigned webhook 401 both times;
# - a changed hyperhive rev rolls the Deployment, and the state volume is the
# one the first pod had;
# - a changed hyperhive rev rolls the Deployment; the pod's state directory is
# an emptyDir, with no claim and no gate;
# - the switch back leaves no pod, Deployment or AddOn, and the host unit
# starts after the prune unit;
# - the state gate marks an empty volume with `freshState` on, refuses it with
# the option off (`Init:Error`, host unit stopped) and a volume of files with
# no marker, and passes the marker the test writes as `swarmctl migrate`.
# starts after the prune unit.
#
# The queue is a plain nats-server with TLS and one stub is the token endpoint
# and the forge; they replace services that stay host-run and unchanged. The
@ -51,13 +48,6 @@ let
controllerSecretLeaf = "swarm/controller/swarm-controller/oidc/client";
revA = lib.fixedWidthString 40 "a" "";
revB = lib.fixedWidthString 40 "b" "";
# A shell with the pod user's volumes, for the pods the script plays
# `swarmctl migrate` and the gate's one-off runs with.
helperImage = pkgs.dockerTools.buildLayeredImage {
name = "k8s-helper";
tag = "test";
contents = [ pkgs.busybox ];
};
overlapLog = "/var/log/overlap.log";
tokenLog = "/var/log/stub-token.log";
@ -191,18 +181,9 @@ pkgs.testers.runNixOSTest {
};
system.stateVersion = "25.11";
specialisation.k8s.configuration.services.hyperhive.deploy.swarm-controller = {
runtime = "k8s";
k8s.freshState = true;
};
# The controller in the cluster with no fresh install: its empty volume is
# refused.
specialisation.k8s-unmarked.configuration.services.hyperhive.deploy.swarm-controller.runtime =
"k8s";
services.k3s.images = [ helperImage ];
specialisation.k8s.configuration.services.hyperhive.deploy.swarm-controller.runtime = "k8s";
specialisation.k8s-rev.configuration.services.hyperhive.deploy = {
swarm-controller.runtime = "k8s";
swarm-controller.k8s.freshState = true;
hive-controller.hyperhiveRev = lib.mkForce revB;
};
@ -323,7 +304,7 @@ pkgs.testers.runNixOSTest {
environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml";
environment.etc."k3s-node/images".text = lib.concatMapStrings (
i: "${i.imageName}:${i.imageTag}\n"
) (config.system.build.k8sImages ++ [ helperImage ]);
) config.system.build.k8sImages;
# The store's raft data is on a tmpfs, for the reason `full-setup` gives.
fileSystems."/var/lib/nixos-containers/${config.services.hyperhive.swarm.bao.machine}/var/lib/private" =
@ -344,10 +325,7 @@ pkgs.testers.runNixOSTest {
};
testScript = builtins.readFile ./lib/k3s.py + ''
import re
INIT = "/root/bao-init.json"
HELPER = "${helperImage.imageName}:${helperImage.imageTag}"
NS = "${namespace}"
SERVICE = "${service}"
HOST_UNIT = "${hostUnit}"
@ -412,7 +390,7 @@ pkgs.testers.runNixOSTest {
except Exception:
diagnose(["hyperhive-k8s-ca-trust.service"])
print(machine.execute(f"kubectl -n {NS} describe pod {name}")[1])
for container in ("state-gate", "tls-issue", "tls-renew", SERVICE):
for container in ("tls-issue", "tls-renew", SERVICE):
print(machine.execute(f"kubectl -n {NS} logs {name} -c {container} --tail=60")[1])
raise
return name
@ -546,16 +524,15 @@ pkgs.testers.runNixOSTest {
assert probe["path"] == "/readyz", probe
api = next(p for p in main["ports"] if p["name"] == "api")
assert api["hostPort"] == PORT and api["hostIP"] == NODE_ADDRESS, api
assert [c["name"] for c in spec["initContainers"]] == ["state-gate", "tls-issue"], spec["initContainers"]
GATE_IMAGE = spec["initContainers"][0]["image"]
assert [c["name"] for c in spec["initContainers"]] == ["tls-issue"], spec["initContainers"]
assert "tls-renew" in [c["name"] for c in spec["containers"]]
assert not any("secret" in v for v in spec["volumes"]), spec["volumes"]
env = {e["name"]: e.get("value") for e in main["env"]}
assert env["BAO_AUTH"] == "jwt" and env["BAO_JWT_ROLE"] == SERVICE, env
assert "BAO_CLIENT_CERT" not in env, env
claim = json.loads(kube(machine, f"get pvc {SERVICE}-state -o json"))
assert claim["status"]["phase"] == "Bound", claim
STATE_VOLUME = claim["metadata"]["uid"]
# The state directory is an emptyDir: no claim, no gate.
assert [v for v in spec["volumes"] if v["name"] == "state"] == [{"name": "state", "emptyDir": {}}], spec["volumes"]
machine.fail(f"kubectl -n {NS} get pvc {SERVICE}-state")
# The listener's key is in memory: the pod's `tls` volume is a tmpfs of
# its own, which the kubelet mounts on the node. The `runtime` volume,
# a plain emptyDir, has no mount of its own: the lookup's control.
@ -588,7 +565,7 @@ pkgs.testers.runNixOSTest {
))
assert api_status == 200, api_status
with subtest("a changed rev rolls the Deployment, the old pod is gone first, and the state volume is the same"):
with subtest("a changed rev rolls the Deployment, and the old pod is gone first"):
old_uid = pod(machine, pod_name)["metadata"]["uid"]
old_annotation = pod(machine, pod_name)["metadata"]["annotations"]["checksum/etc"]
switch("/run/booted-system/specialisation/k8s-rev")
@ -604,7 +581,6 @@ pkgs.testers.runNixOSTest {
assert machine.execute(f"kubectl -n {NS} get pod {pod_name}")[0] != 0
rev = machine.succeed(f"kubectl -n {NS} get configmap {SERVICE}-etc -o json | jq -r '.data[]'")
assert "${revB}" in rev, rev
assert json.loads(kube(machine, f"get pvc {SERVICE}-state -o json"))["metadata"]["uid"] == STATE_VOLUME
assert len(pods()) == 1, pods()
with subtest("the switch back removes the Deployment, pod and AddOn before the unit starts"):
@ -620,7 +596,7 @@ pkgs.testers.runNixOSTest {
assert 0 < pruned <= started, (pruned, started)
requires = machine.succeed(f"systemctl show -p Requires --value {HOST_UNIT}")
assert f"{PRUNE}.service" in requires, requires
assert json.loads(kube(machine, f"get pvc {SERVICE}-state -o json"))["metadata"]["uid"] == STATE_VOLUME
machine.fail(f"kubectl -n {NS} get pvc {SERVICE}-state")
settle(f"curl -sf --unix-socket {SOCKET} http://x/readyz", 300, [HOST_UNIT])
assert gateway("gateway.service") == 401
@ -639,130 +615,5 @@ pkgs.testers.runNixOSTest {
assert any(s[0] in host_up and s[1] == 0 for s in samples), lines[:5]
assert any(s[0] not in host_up and s[1] > 0 for s in samples), lines[:5]
print(f"{SERVICE}: {len(samples)} samples, none with both")
GATE_REFUSAL = f"{SERVICE}: state volume has not been migrated: run `swarmctl migrate {SERVICE}`, or set services.hyperhive.deploy.swarm-controller.k8s.freshState for a fresh install"
def migrate_step(step: str, service: str = SERVICE) -> dict[str, str]:
"""The `step` of `service` in `swarmctl migrate status --json`, which
reads the gate's answer from the pod's status and creates no pod."""
report = json.loads(machine.succeed("swarmctl migrate status --json"))
found = [s for s in report["steps"] if s["service"] == service and s["step"] == step]
assert len(found) == 1, (step, report["steps"])
return found[0]
def helper(name: str, script: str, claim: str | None = None, setup: str | None = None, image: str = HELPER, fresh: str | None = None) -> tuple[str, str]:
"""Runs `script` in a pod of the helper image with the volume of
`claim` (an empty one if None) at /state as the pod user, and returns
its phase and log. With `fresh`, runs the gate image as the pod's own
state gate does, after `setup` has run in the helper image."""
volume: dict[str, dict[str, str]] = {"persistentVolumeClaim": {"claimName": claim}} if claim else {"emptyDir": {}}
container: dict[str, object] = {"name": "run", "image": image, "imagePullPolicy": "Never", "volumeMounts": [{"name": "state", "mountPath": "/state"}]}
spec: dict[str, object] = {
"restartPolicy": "Never",
"securityContext": {"runAsUser": 65532, "runAsGroup": 65532, "fsGroup": 65532},
"volumes": [{"name": "state", **volume}],
"containers": [container],
}
if fresh is None:
container["command"] = ["sh", "-c", script]
else:
container["command"] = ["/bin/hyperhive-state-gate"]
container["env"] = [
{"name": "STATE_GATE_DIR", "value": "/state"},
{"name": "STATE_GATE_SERVICE", "value": "one-off"},
{"name": "STATE_GATE_FRESH", "value": fresh},
{"name": "STATE_GATE_OPTION", "value": "the.option"},
]
spec["initContainers"] = [
{"name": "setup", "image": HELPER, "imagePullPolicy": "Never", "command": ["sh", "-c", setup or "true"], "volumeMounts": container["volumeMounts"]}
]
manifest = {"apiVersion": "v1", "kind": "Pod", "metadata": {"name": name}, "spec": spec}
machine.succeed(f"echo '{json.dumps(manifest)}' | kubectl -n {NS} apply -f -")
machine.wait_until_succeeds(
f"kubectl -n {NS} get pod {name} -o jsonpath='{{.status.phase}}' | grep -E 'Succeeded|Failed'",
timeout=120,
)
phase = machine.succeed(f"kubectl -n {NS} get pod {name} -o jsonpath='{{.status.phase}}'").strip()
text = machine.succeed(f"kubectl -n {NS} logs {name} -c run")
kube(machine, f"delete pod {name} --wait=true")
return phase, text
with subtest("the gate marked the fresh volume with the time, and the marker is what the pod's gate reads"):
phase, text = helper("read-marker", "cat /state/.hyperhive-migrated", claim=f"{SERVICE}-state")
marker = json.loads(text)
assert phase == "Succeeded" and marker["fresh"] is True and re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", marker["at"]), (phase, text)
with subtest("run as the pod's own gate image runs it: lost+found alone is empty, files with no marker are refused even on a fresh install"):
phase, text = helper("gate-lost-found", "", setup="mkdir /state/lost+found", image=GATE_IMAGE, fresh="true")
assert phase == "Succeeded" and "marked" in text, (phase, text)
phase, text = helper("gate-stray", "", setup="touch /state/stray", image=GATE_IMAGE, fresh="true")
assert phase == "Failed" and "holds files and no .hyperhive-migrated marker" in text and "swarmctl migrate one-off" in text, (phase, text)
phase, text = helper("gate-unmarked", "", image=GATE_IMAGE, fresh="false")
assert phase == "Failed" and "run `swarmctl migrate one-off`, or set the.option for a fresh install" in text, (phase, text)
phase, text = helper("gate-marker", "", setup="touch /state/.hyperhive-migrated /state/data", image=GATE_IMAGE, fresh="false")
assert phase == "Succeeded" and "state volume is migrated" in text, (phase, text)
with subtest("the claim stays on the host; it is deleted so that the next pod meets an empty volume"):
assert host_state() == "active", host_state()
kube(machine, f"delete pvc {SERVICE}-state --wait=true --timeout=120s", 150)
with subtest("with freshState off, the pod of an empty volume stays in Init:Error with the reason and nothing of the service runs, and the host unit stays stopped"):
switch("/run/booted-system/specialisation/k8s-unmarked")
assert host_state() == "inactive", host_state()
machine.wait_until_succeeds(f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o name | grep -q pod/", timeout=300)
refused_pod = pods()[0].removeprefix("pod/")
reason = (
"{.status.initContainerStatuses[0].state.terminated.message}"
"{.status.initContainerStatuses[0].lastState.terminated.message}"
)
machine.wait_until_succeeds(f"kubectl -n {NS} get pod {refused_pod} -o jsonpath='{reason}' | grep -qF 'has not been migrated'", timeout=300)
message = machine.succeed(f"kubectl -n {NS} get pod {refused_pod} -o jsonpath='{reason}'").strip()
# The current and the previous attempt each leave the one line.
assert set(message.splitlines()) == {GATE_REFUSAL}, message
# The gate retries and is refused again: the pod does not start, and
# the one-copy invariant is untouched.
machine.wait_until_succeeds(f"kubectl -n {NS} get pod {refused_pod} -o jsonpath='{{.status.initContainerStatuses[0].restartCount}}' | grep -qE '^[1-9]'", timeout=300)
refused = pod(machine, refused_pod)
assert refused["status"]["phase"] == "Pending", refused["status"]
# Every container waits: the pod has the daemon and the leaf renewal.
waiting = {c["state"].get("waiting", {}).get("reason") for c in refused["status"]["containerStatuses"]}
assert waiting == {"PodInitializing"} and len(refused["status"]["containerStatuses"]) >= 1, refused["status"]
assert not is_ready(refused)
assert GATE_REFUSAL in machine.succeed(f"kubectl -n {NS} logs {refused_pod} -c state-gate")
# `swarmctl migrate status` reports the same refusal, and not as a marker.
pods_before = machine.succeed(f"kubectl -n {NS} get pods -o name").split()
copy = migrate_step("copy")
assert copy["status"] == "not_done" and GATE_REFUSAL in copy["detail"], copy
assert migrate_step("ready")["status"] == "not_done"
assert machine.succeed(f"kubectl -n {NS} get pods -o name").split() == pods_before, "status created or deleted a pod"
assert host_state() == "inactive", host_state()
# The control: the claim the pod mounts is bound, and its volume is empty.
phase, text = helper("read-empty", "ls -A /state | wc -l", claim=f"{SERVICE}-state")
assert phase == "Succeeded" and text.strip() == "0", (phase, text)
with subtest("the marker the test writes, as the copy does, lets the same pod start"):
phase, _ = helper("play-migrate", "echo migrated > /state/.hyperhive-migrated", claim=f"{SERVICE}-state")
assert phase == "Succeeded", phase
# The kubelet runs the gate again after its backoff, which is five
# minutes at most.
started = wait_pod_ready(timeout=420)
assert started == refused_pod, (started, refused_pod)
assert "state volume is migrated" in machine.succeed(f"kubectl -n {NS} logs {started} -c state-gate")
copy = migrate_step("copy")
assert copy["status"] == "done" and started in copy["detail"], copy
assert migrate_step("ready")["status"] == "done", migrate_step("ready")
assert migrate_step("runtime")["status"] == "done", migrate_step("runtime")
assert host_state() == "inactive", host_state()
with subtest("a volume that holds files and no marker is refused, and the refusal says the copy may be cut off"):
phase, _ = helper("cut-off", "rm /state/.hyperhive-migrated; echo x > /state/half", claim=f"{SERVICE}-state")
assert phase == "Succeeded", phase
kube(machine, f"delete pod {started} --wait=true --timeout=120s", 150)
machine.wait_until_succeeds(f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o name | grep -q pod/", timeout=120)
half_pod = pods()[0].removeprefix("pod/")
machine.wait_until_succeeds(f"kubectl -n {NS} get pod {half_pod} -o jsonpath='{reason}' | grep -qF 'holds files and no .hyperhive-migrated marker'", timeout=300)
assert not is_ready(pod(machine, half_pod))
copy = migrate_step("copy")
assert copy["status"] == "not_done" and "cut off" in copy["detail"], copy
'';
}