Watch
0
0
Fork
You've already forked hyperhive
0

k8s: the queue's pod mounts the host unit's store in place

This commit is contained in:
atlas 2026-11-23 02:58:52 +01:00 • committed by maia
commit 140ee7f38a
11 changed files with 267 additions and 155 deletions

View file

@ -43,10 +43,8 @@ A service with state moves in four steps. A service without state skips steps
2 and 3.
1. **Snapshot** (`swarmctl migrate`, before the rebuild). Records what the
service holds while its host unit still runs, for the check in step 4. For
NATS that's the stream list with message counts and last sequences, read
from the monitoring endpoint (`/jsz?streams=true`). For a state directory
it's a file list with sizes. The record goes to
service holds while its host unit still runs, for the check in step 4: a file
list with sizes of the state directory. The record goes to
`/var/lib/hyperhive-migrate/<svc>.json`.
2. **Cut-over rebuild** (the operator). The operator sets
`deploy.<svc>.runtime = "k8s"` and rebuilds. The rebuild stops the host
@ -87,20 +85,49 @@ endpoints the [services page](../../2-handbook/swarm/services.md) lists; the
| `swarm-claude-login` | none; credentials it writes go to the store | nothing; a login in progress ends | `/readyz`: queue connected | same |
| `swarm-stt` | the transcript cache, entries live 24 h; the pod keeps it in an `emptyDir` | nothing; the pod starts with an empty cache | `/readyz`: queue connected | same |
| `swarm-ci-metrics` | `cursor.json` in the state directory; losing it re-pushes every run | nothing; the pod starts on an empty PVC with no gate, and its first pass re-pushes every run as the same points | the CronJob's next Job completes | `runtime = "k8s"`, rebuild; the timer goes, the CronJob runs; back with `runtime = "host"` |
| NATS + `swarm-nats-auth` | JetStream's `store_dir`: the swarm's desired state, operator profiles, schedules and run records. `swarm-nats-auth` keeps nothing | the whole `store_dir`, to a PVC; the cut-over rebuild stops NATS, so the copy reads a quiescent tree | nats-server's `/healthz?js-enabled-only=true` and `swarm-nats-auth`'s `/readyz`; Ready when both pass | `runtime = "k8s"`, rebuild; the pod takes the same host port, so hives keep their URL. Rollback copies the PVC back |
| NATS + `swarm-nats-auth` | JetStream's `store_dir`: the swarm's desired state, operator profiles, schedules and run records. `swarm-nats-auth` keeps nothing | nothing; the pod mounts the container's `store_dir` in place | nats-server's `/healthz?js-enabled-only=true` and `swarm-nats-auth`'s `/readyz`; Ready when both pass | `runtime = "k8s"`, rebuild; the pod takes the same host port, so hives keep their URL. Rollback is `runtime = "host"` and a rebuild: the same files |
| `swarm-controller` | its state directory: the operator-admin set, the legacy `webhook-secret` fallback and the forge avatar markers. The rest sits in the queue or the store | the state directory, to a PVC | `/readyz` on the controller's plain health listener | `runtime = "k8s"`, rebuild; the same rebuild points the gateway's `/api/` and `/webhook/forge/` upstreams at the controller's TCP listener. Rollback copies the PVC back and returns the upstreams to the socket |
Two facts the table rests on:
- **The queue's store is state that must survive.** Losing it empties the
hive-status view, and it also loses the buckets that hold desired state.
`swarmctl migrate` treats the whole `store_dir` as data to keep.
It never leaves its directory on the host: the pod and the container use
the same files, so a switch in either direction copies nothing, and the
streams, consumers and acknowledgements are the ones the other side left.
See [the queue's store](#the-queues-store).
- **The webhook secret lives in the store.** The state directory's
`webhook-secret` is a fallback the controller reads only when the store
doesn't answer. The copy moves it anyway, so a pod that starts while the
store is down still verifies forge deliveries. Preflight checks that the
store holds the secret.
## The queue's store
The queue's pod uses the directory its container's `nats` unit already uses:
`/var/lib/nixos-containers/swarm-nats/var/lib/nats` on the host, `/var/lib/nats`
in both. The module renders a static `local` PersistentVolume on that path,
pinned to the node, with a storage class of its own and the `Retain` policy.
The claim `swarm-nats-store` binds it by name, so nothing else binds either.
- **One server at a time.** The prune unit stops a pod before the container
starts, and the Deployment replaces its pod rather than running two. Nothing
reads the directory while the other side writes.
- **Pod to host.** nats-server creates its files with mode `0600`, owned by the
uid it runs as. The pod runs as uid 65532, so the container's `nats` unit
runs `chown -R nats:nats` on the directory before the server starts, as root
and at every start.
- **Host to pod.** The pod's `fsGroup` makes the kubelet set the directory's
group to the pod's and add group read and write on every file at each pod
start, so the pod's uid can use files the host's `nats` user wrote.
- **No lock or identity file.** nats-server keeps none in the store, so
nothing there ties the directory to the side that wrote it.
- **A host that never ran the container.** The module makes the directory,
because the volume needs it before the pod starts.
- **An older claim.** A `swarm-nats-state` claim from an earlier shape isn't
the queue's any more: the pod mounts `swarm-nats-store`, so the old claim
stays unused and needs no step.
## Order of moves
`swarmctl migrate` moves the services in this order:
@ -111,11 +138,12 @@ Two facts the table rests on:
2. **`swarm-review-classifier`, `swarm-claude-login`, `swarm-stt`,
`swarm-ci-metrics`**, in one rebuild or one at a time. Nothing to copy, same
pattern as step 1: the pods start with no gate on an empty volume.
3. **NATS with `swarm-nats-auth`.** The riskiest move: the largest copy, every
hive and agent disconnects, and the data is the swarm's desired state.
It's the first copy `swarmctl migrate` makes. `swarm-nats-auth` moves in the
same pod, because it answers the auth callout on every connect and dials the
server by name, which the pod's host aliases map to its loopback.
3. **NATS with `swarm-nats-auth`.** The riskiest move: every hive and
agent disconnects, and the data is the swarm's desired state. Nothing is
copied, and the controller is the only service `swarmctl migrate` copies.
`swarm-nats-auth` moves in the same pod, because it answers the auth
callout on every connect and dials the server by name, which the pod's
host aliases map to its loopback.
4. **`swarm-controller` last.**
- It's the operator's view of the swarm. Kept on the host through step 3,
it reports from an unchanged place whether the hives reconnected after
@ -202,8 +230,7 @@ a snapshot, step 4 falls back to the stream names on disk and says so.
the host unit's readiness after that rebuild.
The rollback copies back because every write after the cut-over exists only
in the PVC. Rolling NATS back to the untouched host copy would lose every
desired-state change made since then.
in the PVC.
`swarmctl migrate finish` deletes the host copies, the `.pre-rollback`
directories and the PVC of any service back on the host. It runs only when
@ -219,15 +246,15 @@ A fresh install straight onto k8s has no host state to copy: with
The budget is the time from the cut-over rebuild stopping the host unit to the
pod passing step 4.
| service | budget | what hives, agents and the operator see |
| ------------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `swarm-notify-router` | 2 min | Forge events wait in the stream behind the durable consumer and arrive late |
| `swarm-review-classifier` | 2 min | A try-out request in the gap gets no answer, and its caller reports a failure |
| `swarm-claude-login` | 2 min | A login in progress fails; the operator starts it again |
| `swarm-stt` | 2 min | Transcription requests fail during the gap; the cache starts empty |
| `swarm-ci-metrics` | one 5-minute period | One pass runs late; the first pass on the pod's empty cursor pushes every run again |
| NATS + `swarm-nats-auth` | 10 min; the copy takes most of it | below |
| `swarm-controller` | 5 min | The swarm UI and API answer with gateway errors. Forge webhook deliveries in the gap fail at the forge. After the cut-over, `swarmctl` on the host needs `--swarm` |
| service | budget | what hives, agents and the operator see |
| ------------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `swarm-notify-router` | 2 min | Forge events wait in the stream behind the durable consumer and arrive late |
| `swarm-review-classifier` | 2 min | A try-out request in the gap gets no answer, and its caller reports a failure |
| `swarm-claude-login` | 2 min | A login in progress fails; the operator starts it again |
| `swarm-stt` | 2 min | Transcription requests fail during the gap; the cache starts empty |
| `swarm-ci-metrics` | one 5-minute period | One pass runs late; the first pass on the pod's empty cursor pushes every run again |
| NATS + `swarm-nats-auth` | 10 min | below |
| `swarm-controller` | 5 min | The swarm UI and API answer with gateway errors. Forge webhook deliveries in the gap fail at the forge. After the cut-over, `swarmctl` on the host needs `--swarm` |
During the NATS gap:

View file

@ -32,8 +32,8 @@ cluster follow the same pattern.
the iptables firewall (`networking.nftables.enable` off).
[The queue](#the-queue) has its own section.
- `services.hyperhive.deploy.<service>.k8s.freshState` (default `false`) for
each service whose pod keeps state worth moving in a volume:
`swarm-controller` and `nats`. It says whether the pod may start on an empty
the service whose pod keeps state worth moving in a volume:
`swarm-controller`. It says whether the pod may start on an empty
volume ([State](#state)).
With `"host"`, a host without [the cluster node](node.md) renders the same
@ -108,13 +108,13 @@ claims stay; `swarmctl migrate finish` deletes them.
## State
A pod with a state volume that holds state worth moving (`swarm-controller` and
NATS) starts only on migrated state. Its first init container, `state-gate`,
mounts the volume and exits 0 when the volume holds `.hyperhive-migrated`. A
volume with no entries besides `lost+found` gets the marker (`{"fresh": true,
"at": <time>}`) and passes where the service's `k8s.freshState` is on. Every
other volume fails the gate, including one that holds files and no marker, since
a copy may have stopped half way. The pod stays in `Init:Error`, and the
A pod with a state volume that holds state worth moving (`swarm-controller`)
starts only on migrated state. Its first init container, `state-gate`, mounts
the volume and exits 0 when the volume holds `.hyperhive-migrated`. A volume
with no entries besides `lost+found` gets the marker (`{"fresh": true, "at":
<time>}`) and passes where the service's `k8s.freshState` is on. Every other
volume fails the gate, including one that holds files and no marker, since a
copy may have stopped half way. The pod stays in `Init:Error`, and the
container's termination message and log carry one line that names the service,
the `swarmctl migrate` command and the option to set for a fresh install.
Nothing of the service runs on the empty volume. The gate doesn't decide which
@ -122,8 +122,9 @@ copy runs: the host unit stops before the pod exists. Switching a stateful
service to `"k8s"` on a live host therefore needs `swarmctl migrate`, which
copies the state and writes the marker, or the fresh flag, which is for a swarm
with no state to lose. `swarm-notify-router`, `swarm-review-classifier` and
`swarm-claude-login` have no volume and no gate, and `swarm-stt` and
`swarm-ci-metrics` have a volume that the gate doesn't check.
`swarm-claude-login` have no volume and no gate, `swarm-stt` and
`swarm-ci-metrics` have a volume that the gate doesn't check, and the queue's
volume is the host unit's own directory.
`swarm-notify-router` keeps nothing on the host. Its durable consumer on the
forge events stream and its `notify-router-state` bucket live in the queue, so a
@ -215,15 +216,14 @@ Deployment has one replica and the `Recreate` strategy, and the prune unit
holds the container back until the pod has gone.
- **Containers.** The responder is the pod's main container, `swarm-nats`,
rendered from the unit the container runs, as the other daemons are. Beside
it run `nats`, the server, `tls-renew` and `exporter`, the Prometheus
exporter. Three init containers run in order before them. `state-gate`
checks the JetStream volume. `tls-issue` issues the server's leaf.
`callout-config` creates the callout's keys if the store holds none, fetches
their public halves and writes the server's configuration. The server's
settings are the ones the container's `services.nats.settings` render, so a
change to them reaches both. Only the path of the server's key differs,
because the pod has no credential directory.
rendered from the unit the container runs, as the other daemons are. Beside it
run `nats`, the server, `tls-renew` and `exporter`, the Prometheus exporter.
Two init containers run in order before them. `tls-issue` issues the server's
leaf. `callout-config` creates the callout's keys if the store holds none,
fetches their public halves and writes the server's configuration. The
server's settings are the ones the container's `services.nats.settings`
render, so a change to them reaches both. Only the path of the server's key
differs, because the pod has no credential directory.
- **Names.** The pod's `hostAliases` map the queue's name to the pod's own
loopback, so the responder dials the server by the name its leaf carries and
verifies it, with no traffic leaving the pod. Every other client reaches the
@ -265,14 +265,15 @@ holds the container back until the pod has gone.
the leaf for the gateway's `/metrics` vhost, and with no container it has
nothing to restart. The gateway's location dials the exporter on the bridge's
address where it dialled loopback.
- **State.** The server's store directory, `/var/lib/nats`, is the
PersistentVolumeClaim `swarm-nats-state`. The claim starts empty, and a switch
copies nothing from the container's store: it holds the swarm's declared
desired state, which nothing regenerates. `state-gate` therefore stops the
pod, with a message naming `swarmctl migrate`, until the volume holds the
migration marker, unless `deploy.nats.k8s.freshState` is on. Turn it on for
a fresh install only. The claim stays after a switch back, as every claim
does, and the container's store stays too.
- **State.** The server's store directory, `/var/lib/nats`, is the container's
own on the host, `/var/lib/nixos-containers/swarm-nats/var/lib/nats`: the
PersistentVolumeClaim `swarm-nats-store` binds a static local volume on it,
so a switch moves the process and not the bytes, and the pod has no state
gate. The container's unit runs `chown -R nats:nats` on the directory before
the server starts, and the pod's `fsGroup` gives its group read and write.
[The queue's store](migrate.md#the-queues-store) has the details. The claim
and its volume stay after a switch back, as every claim does, with the
directory.
- **Readiness.** The pod is Ready when the responder's `/readyz`, on the pod's
port 8080, passes and the server's exec probe does. The probe runs
`wget` against `/healthz?js-enabled-only=true` on the server's monitor, which
@ -379,11 +380,12 @@ module renders, and its leaf's volume is a tmpfs. A client on the bridge
reaches the queue by name, and a second node outside the node reaches the
control port and not the queue's, as with the container; with `openFirewall`
it dials the pod by name and verifies the name, and the responder in the pod
admits it. A stream written before a pod delete survives it: the replacement
pod reads it from the same volume. The state gate's image refuses an empty
volume, passes a fresh one and a volume with the marker. The exporter answers
the host's own processes through the published port, and the switch back
removes the pod before the container starts.
admits it. A key written on the host before the switch is the pod's to read, a
key the pod writes is the host server's after the switch back, and a stream
written before a pod delete survives it: the replacement pod reads it from the
same directory. The exporter answers the host's own processes through the
published port, and the switch back removes the pod before the container
starts.
The VM test `k8s-controller-switch` moves the controller. It asserts one copy at
each step by the switch's own timestamps and by a sampler, that the pod is Ready

View file

@ -54,6 +54,7 @@ in
deployment-apps-v1 = "sha256-Rtx8xL7CyaYkAEkeK4BXY1r7+mg4mZxRj3vqXGIamJs=";
cronjob-batch-v1 = "sha256-324f6Z2U41lEAnt7xDFwOfIvSc/0DE6x3AtU8C/PiUA=";
persistentvolumeclaim-v1 = "sha256-YTaHGsAzfxGkjaUjGigHQHxzhpZ+NDLzRBQbkC9qU4w=";
persistentvolume-v1 = "sha256-3f9zVyvwllzs+cFglJocQW9Pnoref0amSXZ1iaHieDw=";
configmap-v1 = "sha256-4Ord69Z3wIqgkrLaImTYasT8NO7RErn6wpRbPwDB6bE=";
namespace-v1 = "sha256-Mk+uZ3uY0abVQ0DbDDNNBT6P+6/Os/czJuQd4mENWEM=";
serviceaccount-v1 = "sha256-gZPWw1YUdcbT1cROH67bHfU5BTc9kEvBcBVpQybWWc8=";

View file

@ -85,6 +85,10 @@ let
in
{
imports = [
(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.
'')
(lib.mkRemovedOptionModule [ "services" "hyperhive" "deploy" "stt" "k8s" "freshState" ] ''
The pod keeps its transcript cache in an emptyDir, so it starts on any
node with no state to migrate. Remove this definition.

View file

@ -20,7 +20,6 @@ let
deployCfg = config.services.hyperhive.deploy;
node = deployCfg.k8s;
controllerCfg = deployCfg.swarm-controller;
natsCfg = deployCfg.nats;
# The path of a unit's state directory in a pod, which ./render.nix mounts
# the claim at.
@ -31,11 +30,11 @@ let
controllerStateDir = "/var/lib/swarm-controller";
# `option` is the service's name under `services.hyperhive.deploy`. `state`
# is null for a service whose pod keeps nothing worth moving: no volume, an
# `emptyDir`, or a volume that starts empty with no gate.
# 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 and ../swarm-nats.nix name
# it.
# The claim is `<service>-state`, as ./render.nix names it.
stateTable = {
swarm-controller = {
option = "swarm-controller";
@ -52,11 +51,7 @@ let
};
swarm-nats = {
option = "nats";
state = {
mount = natsCfg.storeDir;
hostPath = "/var/lib/nixos-containers/swarm-nats${natsCfg.storeDir}";
excludes = [ ];
};
state = null;
};
swarm-notify-router = {
option = "notify-router";

View file

@ -169,8 +169,7 @@ let
# a pod holds more than the daemon, a function of the daemon's container
# (its environment, mounts and security context) giving the rest: further
# containers, init containers, volumes, host aliases, pod settings, objects and
# 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
# and images. An `otlp` of `"none"` is a daemon that pushes no telemetry of its
# own.
services = {
swarm-controller = {
@ -213,7 +212,6 @@ let
etcFiles = [ ];
publicCredentials."bao-ca.pem" = baoServerCaKey;
otlp = "none";
fresh = freshOf "nats" natsCfg;
switch = {
inherit (natsCfg) runtime;
hostUnit = "container@swarm-nats.service";
@ -779,21 +777,15 @@ let
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. A pod that makes its
# own volume names it in `state`.
# service with a `fresh` option, none for the rest.
stateVolume =
if !(svc ? fresh) then
null
if svc ? fresh && stateDir != null then
{
volume = "state";
path = stateDir;
}
else
extra.state or (
if stateDir != null then
{
volume = "state";
path = stateDir;
}
else
null
);
null;
stateGate = lib.optionalAttrs (stateVolume != null) {
name = "state-gate";

View file

@ -237,6 +237,9 @@ let
# shell variable `renderConfig` reads its value into.
calloutSubstitutions = map (k: ''-e "s|${k.placeholder}|${"$"}${k.var}|g"'') calloutPublicKeys;
# Hands the store directory back to the server's user.
chownStore = nats: "${pkgs.coreutils}/bin/chown -R ${nats.user}:${nats.group} ${nats.dataDir}";
# Renders the server's config as it starts, so the settings it includes are
# always the running system's. Exits non-zero, and so stops the server
# starting, while any of the three public keys has not been fetched: the
@ -550,7 +553,14 @@ let
# plain override conflicts rather than wins.
systemd.services.nats.serviceConfig.ExecStart =
lib.mkForce "${pkgs.nats-server}/bin/nats-server -c ${runtimeWrapper}";
systemd.services.nats.serviceConfig.ExecStartPre = "+${renderConfig}";
# The store directory is also mounted into the pod at the same path (a
# local volume, `pod` below), whose process runs as another uid and
# leaves its files owned by it. `+` since the unit's own sandbox and user
# cannot chown them back.
systemd.services.nats.serviceConfig.ExecStartPre = [
"+${renderConfig}"
"+${chownStore container.config.services.nats}"
];
# The auth-callout responder: the half that lets the server
# above say *yes*. Without it the `auth_callout` block is a
@ -764,15 +774,19 @@ let
# configuration evaluated alone.
natsSystem = if onK8s then podSystem else config.containers.${machine}.config;
# The JetStream store's directory inside the container and in the pod, and the
# container's copy of it on the host.
dataDir = natsSystem.services.nats.settings.jetstream.store_dir;
hostStoreDir = "/var/lib/nixos-containers/${machine}${dataDir}";
# What the queue's pod holds besides the responder's container
# (../k8s/render.nix gives the responder's own): the server, its exporter and
# the init containers that make the server's files, from the units and
# settings the container runs on the host.
#
# The server starts only once its files exist. The state gate
# (../k8s/render.nix) checks the JetStream volume first, then the leaf is
# issued and the callout's keys and config written, each into a volume of its
# own that the server reads.
# The server starts only once its files exist: the leaf is issued and the
# callout's keys and config written, each into a volume of its own that the
# server reads.
pod =
{
env,
@ -796,8 +810,8 @@ let
field: role:
"bao write -field=${field} auth/${podAuth.mount}/login role=${role} jwt=@${podAuth.tokenFile}";
dataDir = natsSystem.services.nats.settings.jetstream.store_dir;
stateClaim = "${machine}-state";
stateClaim = "${machine}-store";
stateClass = "${machine}-store";
leaf = pkgs.writeShellScriptBin "swarm-nats-tls-issue" ''
export PATH=${lib.makeBinPath tools}
@ -939,12 +953,6 @@ 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
# answers with its own loopback: the leaf carries the name and no IP.
podSpec.shareProcessNamespace = true;
@ -1034,12 +1042,43 @@ let
}
];
# The JetStream store is the host unit's own directory, so a switch moves
# the process and not the bytes. A claim bound by name to a static local
# volume: the class names no provisioner, so nothing else binds either.
# `Retain` keeps the directory when the claim goes.
objects."${machine}/persistentvolume" = {
apiVersion = "v1";
kind = "PersistentVolume";
# Cluster-scoped: no namespace.
metadata = removeAttrs (metaFor stateClaim) [ "namespace" ];
spec = {
capacity.storage = "10Gi";
accessModes = [ "ReadWriteOnce" ];
persistentVolumeReclaimPolicy = "Retain";
storageClassName = stateClass;
local.path = hostStoreDir;
nodeAffinity.required.nodeSelectorTerms = [
{
matchExpressions = [
{
key = "kubernetes.io/hostname";
operator = "In";
values = [ (lib.toLower config.networking.hostName) ];
}
];
}
];
};
};
objects."${machine}/persistentvolumeclaim" = {
apiVersion = "v1";
kind = "PersistentVolumeClaim";
metadata = metaFor stateClaim;
spec = {
accessModes = [ "ReadWriteOnce" ];
storageClassName = stateClass;
volumeName = stateClaim;
resources.requests.storage = "10Gi";
};
};
@ -1253,25 +1292,13 @@ in
moves it: the container goes and the pod is applied, or the pod is
deleted and the container returns.
The pod's JetStream store is its own volume, which starts empty, and
the pod refuses to start until the volume holds the migration marker
or {option}`services.hyperhive.deploy.nats.k8s.freshState` is set.
Nothing here copies the container's store into it.
'';
};
k8s.freshState = import ./lib/fresh-state-option.nix { inherit lib; } "nats";
storeDir = lib.mkOption {
type = lib.types.str;
readOnly = true;
internal = true;
default = natsSystem.services.nats.settings.jetstream.store_dir;
description = ''
The JetStream store's directory inside the container, and the path the
pod mounts its volume at. The host's copy of it is this path under
`/var/lib/nixos-containers/swarm-nats`, which
../host-modules/k8s/migrate.nix names for `swarmctl migrate`.
The pod's JetStream store is the container's own directory on the host,
mounted into the pod as a static local volume, so a switch moves the
process and not the bytes: streams, consumers and key-value buckets are
the same files on both sides. The container's unit hands the directory
back to the server's user at each start, and the pod's group gets read
and write access from the pod's `fsGroup`. At most one server holds the
directory, since a switch stops the one before it starts the other.
'';
};
@ -1542,7 +1569,13 @@ in
# The bind source has to exist before the container starts, leaf or not:
# nixos-container refuses to start over a missing one, which would take
# the whole queue down rather than only its TLS.
systemd.tmpfiles.rules = [ "d ${tlsDir} 0755 root root -" ];
#
# The pod's local volume needs its directory to exist before the pod
# starts, which on a host that never ran the container nothing else makes.
systemd.tmpfiles.rules = [
"d ${tlsDir} 0755 root root -"
]
++ lib.optional onK8s "d ${hostStoreDir} 0700 root root -";
containers.swarm-nats = lib.mkIf (!onK8s) {
autoStart = true;

View file

@ -115,7 +115,6 @@ let
config:
lib.recursiveUpdate config {
services.hyperhive.deploy = {
nats.k8s.freshState = true;
swarm-controller.k8s.freshState = true;
};
};
@ -1595,7 +1594,7 @@ let
# Everything of the pod is read off the manifest the module renders. The
# `tmp` volume is the control that the lookup of a volume's medium finds
# a plain one.
name = "the queue's pod is one replaced copy of the responder, the server and the exporter, started after the state gate, the leaf and the callout config";
name = "the queue's pod is one replaced copy of the responder, the server and the exporter, started after the leaf and the callout config, on the host unit's own store directory";
ok =
let
o = objects."swarm-nats/deployment";
@ -1603,6 +1602,8 @@ let
named = n: lib.findFirst (c: c.name == n) { } spec.containers;
volume = n: lib.findFirst (v: v.name == n) null spec.volumes;
pvc = objects."swarm-nats/persistentvolumeclaim";
pv = objects."swarm-nats/persistentvolume";
hostStore = "/var/lib/nixos-containers/swarm-nats/var/lib/nats";
env = envOf "swarm-nats";
in
o.spec.replicas == 1
@ -1624,7 +1625,6 @@ let
)
&&
map (c: c.name) spec.initContainers == [
"state-gate"
"tls-issue"
"callout-config"
]
@ -1686,6 +1686,32 @@ let
&& !((volume "tmp").emptyDir ? medium)
&& (volume "nats-data").persistentVolumeClaim.claimName == pvc.metadata.name
&& 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.
&& pvc.spec.volumeName == pv.metadata.name
&& pvc.spec.storageClassName == pv.spec.storageClassName
&& pv.spec.storageClassName != ""
&& !(objects."swarm-controller/persistentvolumeclaim".spec ? volumeName)
&& pv.spec.local.path == hostStore
&& pv.spec.persistentVolumeReclaimPolicy == "Retain"
&& !(pv.metadata ? namespace)
&&
pv.spec.nodeAffinity.required.nodeSelectorTerms == [
{
matchExpressions = [
{
key = "kubernetes.io/hostname";
operator = "In";
values = [ (lib.toLower allLocal.networking.hostName) ];
}
];
}
]
# A pod on a host that never ran the container gets the directory made;
# a host with the container needs no rule.
&& lib.any (lib.hasPrefix "d ${hostStore} ") onCluster.systemd.tmpfiles.rules
&& !(lib.any (lib.hasPrefix "d ${hostStore} ") withNode.systemd.tmpfiles.rules)
&& !(lib.any (c: c ? resources) spec.containers)
&& !(lib.any (v: v ? secret) spec.volumes);
}
@ -1713,21 +1739,19 @@ let
volume = "state";
option = "deploy.swarm-controller.k8s.freshState";
};
swarm-nats = {
path = "/var/lib/nats";
volume = "nats-data";
option = "deploy.nats.k8s.freshState";
};
};
# The poller keeps a claim for its cursor and the speech-to-text pod
# keeps none; neither is gated.
# 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 = [
"swarm-notify-router"
"swarm-review-classifier"
"swarm-claude-login"
"swarm-stt"
];
ungated = unclaimed ++ [ "swarm-ci-metrics" ];
ungated = unclaimed ++ [
"swarm-ci-metrics"
"swarm-nats"
];
one =
name: g:
let
@ -1861,9 +1885,9 @@ let
services = (migrateOf withNode).services;
stateful = [
"swarm-controller"
"swarm-nats"
];
stateless = [
"swarm-nats"
"swarm-notify-router"
"swarm-review-classifier"
"swarm-claude-login"
@ -1908,8 +1932,8 @@ let
in
(migrateOf withNode).namespace == "hyperhive"
&& host.swarm-controller.state.hostPath == "/var/lib/swarm-controller"
&& host.swarm-nats.state.hostPath == "/var/lib/nixos-containers/swarm-nats/var/lib/nats"
&& host.swarm-nats.state.mount == "/var/lib/nats"
# 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
&&
@ -1922,7 +1946,7 @@ let
&& 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-nats.state == host.swarm-nats.state;
&& cluster.swarm-controller.state == host.swarm-controller.state;
}
{
# A pure function, so the case needs no host of its own. A path inside the

View file

@ -367,7 +367,7 @@ let
# The xkey exists only at runtime, so the server's config is rendered as
# it starts: always the wrapper, and never the store-rendered settings
# alone, which carry no xkey. `+` so the render may write `runtimeDir`.
name = "the queue's server starts only through the config rendered with its xkey";
name = "the queue's server starts only through the config rendered with its xkey, then takes its store directory back";
ok =
lib.all
(
@ -375,11 +375,17 @@ let
let
c = h.containers.swarm-nats.config;
nats = c.systemd.services.nats.serviceConfig;
pre = nats.ExecStartPre or "";
pre = lib.toList (nats.ExecStartPre or [ ]);
render = lib.head pre;
in
lib.hasSuffix "/bin/nats-server -c /var/lib/nats-callout/nats.conf" nats.ExecStart
&& lib.hasPrefix "+/nix/store/" pre
&& lib.hasSuffix "-swarm-nats-render-config" pre
&& lib.hasPrefix "+/nix/store/" render
&& lib.hasSuffix "-swarm-nats-render-config" render
# Then the store directory goes back to the server's user, which the
# pod, mounting it in place, leaves owned by its own.
&& lib.length pre == 2
&& lib.hasPrefix "+/nix/store/" (lib.elemAt pre 1)
&& lib.hasSuffix "/bin/chown -R nats:nats /var/lib/nats" (lib.elemAt pre 1)
&& !(c.services.nats.settings.authorization.auth_callout ? xkey)
)
[

View file

@ -36,7 +36,10 @@ pkgs.runCommand "hyperhive-script-test-nats-render-config"
{
# `removePrefix` keeps the string context, and with it the script's store
# path among this check's inputs. The `+` is systemd's, not the path's.
RENDER = lib.removePrefix "+" queue.containers.swarm-nats.config.systemd.services.nats.serviceConfig.ExecStartPre;
# The render is the first of the unit's `ExecStartPre` entries.
RENDER = lib.removePrefix "+" (
lib.head queue.containers.swarm-nats.config.systemd.services.nats.serviceConfig.ExecStartPre
);
nativeBuildInputs = [ pkgs.jq ];
}
''

View file

@ -2,24 +2,25 @@
# between their container and the host's cluster
# (`services.hyperhive.deploy.nats.runtime`), against the real secret store.
# The host boots with the queue in its container; the `k8s` specialisation has
# it in the cluster on a fresh JetStream store, and `k8s-open` adds
# it in the cluster on the container's own JetStream store, and `k8s-open` adds
# `deploy.nats.openFirewall`. The script switches to the cluster, opens the
# port, and back, and asserts that:
#
# - at most one server and one responder run at any moment of any switch (a
# sampler counts the processes every 200 ms), and the container and the pod
# never overlap;
# - the pod is Ready by its exec probe on the server's monitor, holds the store
# guard, the leaf and the callout config as init containers, and publishes
# the client port on every address and the exporter's on the bridge's;
# - the pod is Ready by its exec probe on the server's monitor, holds the leaf
# and the callout config as init containers, and publishes the client port
# on every address and the exporter's on the bridge's;
# - a client on the hive's bridge reaches the queue by name through the
# published port, and the responder in the pod admits the router's token;
# - the port is as closed to a host outside the node as the container's is, and
# open with `openFirewall`, where a second node dials it by name and verifies
# the name. The exporter's port answers the host's own processes only;
# - a stream written before the pod is deleted is read after;
# - the pod's state gate marks the empty store as fresh, and passes the volume
# with its marker after a pod delete;
# - the store is the container's own directory: a key the host server wrote is
# read by the pod, and a key the pod wrote is read by the host server after
# the switch back, which hands the files back to the server's user;
# - the switch back leaves no pod, Deployment or AddOn, and the container
# starts after the prune unit.
#
@ -177,13 +178,9 @@ pkgs.testers.runNixOSTest {
};
system.stateVersion = "25.11";
specialisation.k8s.configuration.services.hyperhive.deploy.nats = {
runtime = "k8s";
k8s.freshState = true;
};
specialisation.k8s.configuration.services.hyperhive.deploy.nats.runtime = "k8s";
specialisation.k8s-open.configuration.services.hyperhive.deploy.nats = {
runtime = "k8s";
k8s.freshState = true;
openFirewall = true;
};
@ -367,6 +364,8 @@ pkgs.testers.runNixOSTest {
"&& systemctl --machine=swarm-nats is-active swarm-nats-auth.service "
"&& [ \"$(pgrep -cx nats-server)\" = 1 ] && [ \"$(pgrep -cx swarm-nats-auth)\" = 1 ]"
)
BUCKET = "notify-router-state"
HOST_STORE = "/var/lib/nixos-containers/swarm-nats/var/lib/nats"
SUBJECT = "$SWARM.router.todo.atlas"
INBOX = "_INBOX.client.swarm-notify-router"
@ -422,7 +421,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", "callout-config", SERVICE, "nats", "exporter"):
for container in ("tls-issue", "callout-config", SERVICE, "nats", "exporter"):
print(machine.execute(f"kubectl -n {NS} logs {name} -c {container} --tail=60")[1])
raise
return name
@ -574,6 +573,15 @@ pkgs.testers.runNixOSTest {
with subtest("the host's own processes read the exporter through the container"):
machine.succeed(f"curl -sf http://127.0.0.1:{METRICS}/metrics | grep -F gnatsd_varz_connections")
with subtest("on the host, the container's server takes a key into the router's state bucket, and the store's files belong to the server's user"):
nats(machine, f"kv add {BUCKET}")
nats(machine, f"kv put {BUCKET} host-key written-on-host")
assert "written-on-host" in nats(machine, f"kv get {BUCKET} host-key --raw")
HOST_UID = machine.succeed(f"stat -c %u {HOST_STORE}").strip()
# The control that the lookup finds files: the store is not empty.
assert int(machine.succeed(f"find {HOST_STORE} -type f | wc -l")) > 0
assert machine.succeed(f"find {HOST_STORE} ! -uid {HOST_UID} | wc -l").strip() == "0"
with subtest("the switch to the cluster stops the container before it applies the pod"):
out = switch("/run/booted-system/specialisation/k8s")
assert HOST_UNIT in out and "stopping the following units" in out, out
@ -586,9 +594,9 @@ pkgs.testers.runNixOSTest {
machine.fail("test -e /etc/nixos-containers/swarm-nats.conf")
assert counts() == (1, 1), counts()
with subtest("the pod holds the state gate, the leaf and the config as init containers, and publishes the client port on every address and the exporter's on the bridge"):
with subtest("the pod holds the leaf and the config as init containers, and publishes the client port on every address and the exporter's on the bridge"):
spec = pod(machine, pod_name)["spec"]
assert [c["name"] for c in spec["initContainers"]] == ["state-gate", "tls-issue", "callout-config"], spec["initContainers"]
assert [c["name"] for c in spec["initContainers"]] == ["tls-issue", "callout-config"], spec["initContainers"]
assert [c["name"] for c in spec["containers"]] == ["swarm-nats", "nats", "tls-renew", "exporter"], spec["containers"]
assert spec["shareProcessNamespace"] is True, spec
server = next(c for c in spec["containers"] if c["name"] == "nats")
@ -604,7 +612,7 @@ pkgs.testers.runNixOSTest {
# Ready is the exec probe's and the responder's: every container is.
statuses = {c["name"]: c["ready"] for c in pod(machine, pod_name)["status"]["containerStatuses"]}
assert statuses == {"swarm-nats": True, "nats": True, "tls-renew": True, "exporter": True}, statuses
claim = json.loads(kube(machine, f"get pvc {SERVICE}-state -o json"))
claim = json.loads(kube(machine, f"get pvc {SERVICE}-store -o json"))
assert claim["status"]["phase"] == "Bound", claim
STATE_VOLUME = claim["metadata"]["uid"]
# The leaf's key is in memory.
@ -614,8 +622,6 @@ pkgs.testers.runNixOSTest {
machine.fail(f"grep -F '{mount}/nats-config ' /proc/mounts")
issued = machine.succeed(f"kubectl -n {NS} logs {pod_name} -c tls-issue")
assert f"requesting the queue's TLS leaf for {NAME} from the store" in issued, issued
guard = machine.succeed(f"kubectl -n {NS} logs {pod_name} -c state-gate")
assert "the install is fresh: marked" in guard, guard
# The pod's server keeps the descriptors the container's did.
limits = machine.succeed("grep 'Max open files' /proc/$(pgrep -ox nats-server)/limits")
print(limits)
@ -632,6 +638,19 @@ pkgs.testers.runNixOSTest {
assert stream_messages() == 1
machine.wait_until_succeeds(f"[ \"$(grep -c '/api/oidc/introspection ${service}:{SECRET}' ${tokenLog})\" -ge 2 ]", timeout=60)
with subtest("the pod's volume is the container's own directory: it reads the host's key, writes one of its own, and leaves files the host's user does not own"):
pv = json.loads(kube(machine, f"get pv {SERVICE}-store -o json"))
assert pv["spec"]["local"]["path"] == HOST_STORE, pv["spec"]
assert pv["status"]["phase"] == "Bound" and pv["spec"]["claimRef"]["name"] == f"{SERVICE}-store", pv
assert pv["spec"]["persistentVolumeReclaimPolicy"] == "Retain", pv["spec"]
assert claim["spec"]["volumeName"] == pv["metadata"]["name"], claim["spec"]
assert "written-on-host" in nats(machine, f"kv get {BUCKET} host-key --raw")
nats(machine, f"kv put {BUCKET} pod-key written-by-pod")
assert "written-by-pod" in nats(machine, f"kv get {BUCKET} pod-key --raw")
# The stream the pod made is its own, so the host's user has to take it
# back when the container starts.
assert int(machine.succeed(f"find {HOST_STORE} ! -uid {HOST_UID} | wc -l")) > 0
with subtest("a client on the hive's bridge reaches the pod through the published port, and a host outside the node does not"):
assert machine.execute(f"ip netns exec agent nc -z -w 4 {BRIDGE} {PORT}")[0] == 0
assert machine.execute(f"ip netns exec agent nc -z -w 4 {BRIDGE} {METRICS}")[0] != 0
@ -662,11 +681,11 @@ pkgs.testers.runNixOSTest {
old_uid = pod(machine, pod_name)["metadata"]["uid"]
kube(machine, f"delete pod {pod_name} --wait=true --timeout=120s", 150)
pod_name = wait_pod_ready(old_uid)
assert json.loads(kube(machine, f"get pvc {SERVICE}-state -o json"))["metadata"]["uid"] == STATE_VOLUME
assert json.loads(kube(machine, f"get pvc {SERVICE}-store -o json"))["metadata"]["uid"] == STATE_VOLUME
machine.wait_until_succeeds(nats_cmd(SERVICES_ROOT, f"stream info {STREAM}"), timeout=120)
assert stream_messages() == 1
guard = machine.succeed(f"kubectl -n {NS} logs {pod_name} -c state-gate")
assert "state volume is migrated" in guard, guard
assert "written-on-host" in nats(machine, f"kv get {BUCKET} host-key --raw")
assert "written-by-pod" in nats(machine, f"kv get {BUCKET} pod-key --raw")
assert counts() == (1, 1), counts()
with subtest("with openFirewall a host outside the node dials the pod by name and verifies it, and is admitted"):
@ -702,9 +721,15 @@ pkgs.testers.runNixOSTest {
requires = machine.succeed(f"systemctl show -p Requires --value {HOST_UNIT}")
assert f"{PRUNE}.service" in requires, requires
# The volume is kept for the next switch.
assert json.loads(kube(machine, f"get pvc {SERVICE}-state -o json"))["metadata"]["uid"] == STATE_VOLUME
assert json.loads(kube(machine, f"get pvc {SERVICE}-store -o json"))["metadata"]["uid"] == STATE_VOLUME
settle(QUEUE_UP, 600, [HOST_UNIT])
assert counts() == (1, 1), counts()
# The container's server reads what the pod wrote: its unit took the
# files back before the server started.
machine.wait_until_succeeds(nats_cmd(SERVICES_ROOT, f"kv get {BUCKET} pod-key --raw") + " | grep -F written-by-pod", timeout=120)
assert "written-on-host" in nats(machine, f"kv get {BUCKET} host-key --raw")
assert stream_messages() == 1
assert machine.succeed(f"find {HOST_STORE} ! -uid {HOST_UID} | wc -l").strip() == "0"
# Closed to a host outside the node again, open to the node's own.
assert not reachable(outside, NODE, PORT), "the container's port is open to a host outside the node"
assert reachable(outside, NODE, CONTROL)