Watch
0
0
Fork
You've already forked hyperhive
0

a pod with a state volume starts only on a migrated or fresh volume

This commit is contained in:
atlas 2026-11-22 18:59:22 +01:00 • committed by maia
commit 394a08d885
7 changed files with 175 additions and 46 deletions

View file

@ -128,6 +128,22 @@ 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 # 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
@ -136,6 +152,9 @@ let
# the paths the unit names that hold one to theirs. `listener`, where a # 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 # service has one, is the TCP port the pod publishes on the node
# (`hostAddress`) and the directory its init container writes the leaf to. # (`hostAddress`) and the directory its init container writes the leaf to.
# `fresh` (`freshOf`) is set on every service whose pod gets a state volume:
# 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.
# `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
@ -148,7 +167,8 @@ let
# a pod holds more than the daemon, a function of the daemon's container # a pod holds more than the daemon, a function of the daemon's container
# (its environment, mounts and security context) giving the rest: further # (its environment, mounts and security context) giving the rest: further
# containers, init containers, volumes, host aliases, pod settings, objects and # containers, init containers, volumes, host aliases, pod settings, objects and
# images. An `otlp` of `"none"` is a daemon that pushes no telemetry of its # images, and `state`, the `volume` and mount `path` of a state volume the
# pod makes itself, which the state gate checks. An `otlp` of `"none"` is a daemon that pushes no telemetry of its
# own. # own.
services = { services = {
swarm-controller = { swarm-controller = {
@ -171,6 +191,7 @@ let
# The unit pushes to the swarm collector's route and mints its own bearer # The unit pushes to the swarm collector's route and mints its own bearer
# (../glue-controller-env.nix, `otel_http_client.rs`). # (../glue-controller-env.nix, `otel_http_client.rs`).
otlp = "own"; otlp = "own";
fresh = freshOf "swarm-controller" controllerCfg;
switch = { switch = {
inherit (controllerCfg) runtime; inherit (controllerCfg) runtime;
hostUnit = "swarm-controller.service"; hostUnit = "swarm-controller.service";
@ -190,6 +211,7 @@ let
etcFiles = [ ]; etcFiles = [ ];
publicCredentials."bao-ca.pem" = baoServerCaKey; publicCredentials."bao-ca.pem" = baoServerCaKey;
otlp = "none"; otlp = "none";
fresh = freshOf "nats" natsCfg;
switch = { switch = {
inherit (natsCfg) runtime; inherit (natsCfg) runtime;
hostUnit = "container@swarm-nats.service"; hostUnit = "container@swarm-nats.service";
@ -216,6 +238,7 @@ let
etcFiles = [ ]; etcFiles = [ ];
publicCredentials.stt-bao-server-ca = baoServerCaKey; publicCredentials.stt-bao-server-ca = baoServerCaKey;
otlp = "hive"; otlp = "hive";
fresh = freshOf "stt" deployCfg.stt;
switch = { switch = {
inherit (deployCfg.stt) runtime; inherit (deployCfg.stt) runtime;
hostUnit = "container@swarm-stt.service"; hostUnit = "container@swarm-stt.service";
@ -256,6 +279,7 @@ let
etcFiles = [ ]; etcFiles = [ ];
publicCredentials."bao-ca.pem" = baoServerCaKey; publicCredentials."bao-ca.pem" = baoServerCaKey;
otlp = "own"; otlp = "own";
fresh = freshOf "ci-metrics" deployCfg.ci-metrics;
# The timer and the service both: the prune unit holds back either, and a # The timer and the service both: the prune unit holds back either, and a
# service started by hand cannot run beside the CronJob. # service started by hand cannot run beside the CronJob.
switch = { switch = {
@ -748,6 +772,45 @@ let
package = leafImagePackage; package = leafImagePackage;
bin = leafIssueBin; bin = leafIssueBin;
}; };
# The volume that holds the service's state, and where it is mounted. A
# pod that makes its own volume names it in `state`.
stateVolume =
extra.state or (
if 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. # What the service adds to the daemon's pod.
extra = { extra = {
containers = [ ]; containers = [ ];
@ -825,8 +888,11 @@ let
}; };
} }
// lib.optionalAttrs baoLogin { serviceAccountName = name; } // lib.optionalAttrs baoLogin { serviceAccountName = name; }
// lib.optionalAttrs (listener != { } || extra.initContainers != [ ]) { // lib.optionalAttrs (stateVolume != null || listener != { } || extra.initContainers != [ ]) {
initContainers = lib.optional (listener != { }) leafContainer ++ extra.initContainers; initContainers =
lib.optional (stateVolume != null) stateGate
++ lib.optional (listener != { }) leafContainer
++ extra.initContainers;
} }
// lib.optionalAttrs (extra.hostAliases != [ ]) { inherit (extra) hostAliases; } // lib.optionalAttrs (extra.hostAliases != [ ]) { inherit (extra) hostAliases; }
// extra.podSpec; // extra.podSpec;
@ -934,6 +1000,8 @@ let
fail name "the unit names no OTLP endpoint of its own, which the pod would push to" fail name "the unit names no OTLP endpoint of its own, which the pod would push to"
else if svc.healthEnv != null && unitEnv ? ${svc.healthEnv} then else if svc.healthEnv != null && unitEnv ? ${svc.healthEnv} then
fail name "the unit already sets ${svc.healthEnv}" fail name "the unit already sets ${svc.healthEnv}"
else if stateVolume != null && !(svc ? fresh) then
fail name "the pod has a state volume and the service names no `fresh` option for its state gate"
else if lib.head execWords != entrypoint then else if lib.head execWords != entrypoint then
fail name "ExecStart is not ${entrypoint} with plain arguments" fail name "ExecStart is not ${entrypoint} with plain arguments"
else if lib.any (w: lib.hasInfix "\"" w) execWords then else if lib.any (w: lib.hasInfix "\"" w) execWords then
@ -946,7 +1014,10 @@ let
{ {
inherit objects image; inherit objects image;
# What the pod's other containers run. # What the pod's other containers run.
extraImages = lib.optional (listener != { }) leafImage ++ extra.images; extraImages =
lib.optional (stateVolume != null) stateGateImage
++ lib.optional (listener != { }) leafImage
++ extra.images;
}; };
enabled = lib.mapAttrs workload (lib.filterAttrs (_: svc: svc.enable) services); enabled = lib.mapAttrs workload (lib.filterAttrs (_: svc: svc.enable) services);
@ -966,7 +1037,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.concatMap (w: [ w.image ] ++ w.extraImages) (lib.attrValues enabled); images = lib.unique (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,47 @@
# 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

@ -0,0 +1,20 @@
# 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

@ -211,13 +211,17 @@ in
service and timer return, so one poller runs at any time. Its cursor is service and timer return, so one poller runs at any time. Its cursor is
in the service's state directory on the host, and in a volume of the in the service's state directory on the host, and in a volume of the
cluster in a pod; neither moves with the poller, so the first pass after cluster in a pod; neither moves with the poller, so the first pass after
a switch pushes every run again, as the same points. a switch pushes every run again, as the same points. The pod does not
start on its empty volume until `swarmctl migrate` marks it or
{option}`services.hyperhive.deploy.ci-metrics.k8s.freshState` is set.
The poller keeps pushing to the swarm collector's route of its own, The poller keeps pushing to the swarm collector's route of its own,
not to the hive collector the cluster's other pods push to. not to the hive collector the cluster's other pods push to.
''; '';
}; };
k8s.freshState = import ./lib/fresh-state-option.nix { inherit lib; } "ci-metrics";
unit = lib.mkOption { unit = lib.mkOption {
type = lib.types.raw; type = lib.types.raw;
readOnly = true; readOnly = true;

View file

@ -637,10 +637,15 @@ in
cannot reach a unix socket inside a pod, so the gateway dials the 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 listener on {option}`tcp.hostAddress`. The pod's state is its own
volume, which starts empty: nothing moves the host's state directory volume, which starts empty: nothing moves the host's state directory
into it. 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.
''; '';
}; };
k8s.freshState = import ./lib/fresh-state-option.nix { inherit lib; } "swarm-controller";
unit = lib.mkOption { unit = lib.mkOption {
type = lib.types.raw; type = lib.types.raw;
readOnly = true; readOnly = true;

View file

@ -769,9 +769,10 @@ let
# the init containers that make the server's files, from the units and # the init containers that make the server's files, from the units and
# settings the container runs on the host. # settings the container runs on the host.
# #
# The server starts only once its files exist. The store guard checks the # The server starts only once its files exist. The state gate
# JetStream volume, then the leaf is issued and the callout's keys and # (../k8s/render.nix) checks the JetStream volume first, then the leaf is
# config written, each into a volume of its own that the server reads. # issued and the callout's keys and config written, each into a volume of its
# own that the server reads.
pod = pod =
{ {
env, env,
@ -798,22 +799,6 @@ let
dataDir = natsSystem.services.nats.settings.jetstream.store_dir; dataDir = natsSystem.services.nats.settings.jetstream.store_dir;
stateClaim = "${machine}-state"; stateClaim = "${machine}-state";
guard = pkgs.writeShellScriptBin "swarm-nats-store-guard" ''
export PATH=${lib.makeBinPath [ pkgs.coreutils ]}
set -eu
store=${lib.escapeShellArg dataDir}
if [ -d "$store/jetstream" ] && [ -n "$(ls -A "$store/jetstream")" ]; then
echo "the JetStream store at $store holds data"
exit 0
fi
if [ "''${SWARM_NATS_FRESH_STORE:-false}" = true ]; then
echo "the JetStream store at $store is empty and marked fresh: the server starts on it"
exit 0
fi
echo "empty JetStream store at $store: run \`swarmctl migrate\` first, or set services.hyperhive.deploy.nats.k8s.freshStore for a fresh install" >&2
exit 1
'';
leaf = pkgs.writeShellScriptBin "swarm-nats-tls-issue" '' leaf = pkgs.writeShellScriptBin "swarm-nats-tls-issue" ''
export PATH=${lib.makeBinPath tools} export PATH=${lib.makeBinPath tools}
${tlsIssue.script { ${tlsIssue.script {
@ -877,13 +862,12 @@ let
package = pkgs.symlinkJoin { package = pkgs.symlinkJoin {
name = "${machine}-init"; name = "${machine}-init";
paths = [ paths = [
guard
leaf leaf
keys keys
renew renew
]; ];
}; };
bin = "swarm-nats-store-guard"; bin = "swarm-nats-tls-issue";
}; };
# `renderConfig` links upstream's rendered settings into the config # `renderConfig` links upstream's rendered settings into the config
@ -955,6 +939,12 @@ let
} }
]; ];
# The JetStream volume, which the state gate checks before anything else.
state = {
volume = "nats-data";
path = dataDir;
};
# The server and the responder dial the queue by its name, which the pod # The server and the responder dial the queue by its name, which the pod
# answers with its own loopback: the leaf carries the name and no IP. # answers with its own loopback: the leaf carries the name and no IP.
podSpec.shareProcessNamespace = true; podSpec.shareProcessNamespace = true;
@ -967,9 +957,6 @@ let
]; ];
initContainers = [ initContainers = [
(fromInit "store-guard" "swarm-nats-store-guard" {
SWARM_NATS_FRESH_STORE = lib.boolToString deployCfg.nats.k8s.freshStore;
} [ "tmp" ] [ (volumeNamed "nats-data" dataDir true) ])
(fromInit "tls-issue" "swarm-nats-tls-issue" storeEnv login [ (fromInit "tls-issue" "swarm-nats-tls-issue" storeEnv login [
(volumeNamed "nats-tls" tlsDir false) (volumeNamed "nats-tls" tlsDir false)
]) ])
@ -1267,24 +1254,13 @@ in
deleted and the container returns. deleted and the container returns.
The pod's JetStream store is its own volume, which starts empty, and The pod's JetStream store is its own volume, which starts empty, and
the pod refuses to start the server on an empty store unless the pod refuses to start until the volume holds the migration marker
{option}`services.hyperhive.deploy.nats.k8s.freshStore` is set. or {option}`services.hyperhive.deploy.nats.k8s.freshState` is set.
Nothing here copies the container's store into it. Nothing here copies the container's store into it.
''; '';
}; };
k8s.freshStore = lib.mkOption { k8s.freshState = import ./lib/fresh-state-option.nix { inherit lib; } "nats";
type = lib.types.bool;
default = false;
example = true;
description = ''
With {option}`services.hyperhive.deploy.nats.runtime` set to `k8s`:
let the pod start the server on an empty JetStream store. Off, the pod
stops before the server and says so: an empty store loses every
hive's declared desired state, which nothing regenerates. Set it on a
fresh install, which has none to lose.
'';
};
unit = lib.mkOption { unit = lib.mkOption {
type = lib.types.raw; type = lib.types.raw;

View file

@ -360,10 +360,16 @@ in
objects are deleted and the container returns. The transcript cache is objects are deleted and the container returns. The transcript cache is
in the container's state directory on the host, and in a volume of the in the container's state directory on the host, and in a volume of the
cluster in a pod; neither moves with the service, so a transcript is cluster in a pod; neither moves with the service, so a transcript is
made again after a switch. made again after a switch. The pod does not start on its empty volume
until `swarmctl migrate` marks it or
{option}`services.hyperhive.deploy.stt.k8s.freshState` is set.
''; '';
}; };
options.services.hyperhive.deploy.stt.k8s.freshState = import ./lib/fresh-state-option.nix {
inherit lib;
} "stt";
options.services.hyperhive.deploy.stt.unit = lib.mkOption { options.services.hyperhive.deploy.stt.unit = lib.mkOption {
type = lib.types.raw; type = lib.types.raw;
readOnly = true; readOnly = true;