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
14 changed files with 233 additions and 1110 deletions

View file

@ -750,13 +750,13 @@ Move the swarm's services from this host onto its k3s cluster.
###### **Subcommands:** ###### **Subcommands:**
* `status` — Report where each service stands: its runtime, its host units, its pod and the start gate's answer, and which step comes next * `status` — Report where each service stands: its runtime, its host units and its pod, and which step comes next
## `swarmctl migrate status` ## `swarmctl migrate status`
Report where each service stands: its runtime, its host units, its pod and the start gate's answer, and which step comes next. Report where each service stands: its runtime, its host units and its pod, and which step comes next.
Read-only: it creates no pod and changes nothing. Run it as root; it reads `/etc/hyperhive/migrate.json`, asks systemd about the host units and lists the pods in the swarm's namespace with the k3s admin kubeconfig. Read-only: it creates no pod and changes nothing. Run it as root; it reads `/etc/hyperhive/migrate.json`, asks systemd about the host units and lists the pods in the swarm's namespace with the k3s admin kubeconfig.

View file

@ -1,15 +1,15 @@
# Moving an all-local swarm onto k8s: `swarmctl migrate` # Moving an all-local swarm onto k8s: `swarmctl migrate`
`swarmctl migrate` moves a running all-local swarm A running all-local swarm (`services.hyperhive.deploy.singleHostSwarm`) moves
(`services.hyperhive.deploy.singleHostSwarm`) onto the k3s cluster on the onto the k3s cluster on the same host one service at a time. The operator sets
same host. It copies each service's state into a persistent volume, checks the `deploy.<svc>.runtime = "k8s"` and rebuilds; `swarmctl migrate status` reports
copy, and leaves the host copy in place until the operator finishes. It moves where each service stands. Nothing copies a service's state: each one's pod
services in dependency order, resumes after a crash, and rolls a service back re-derives what it keeps, keeps it in the service's own store, or uses the host
to the host on request. unit's directory in place.
## Scope and guarantees ## Scope and guarantees
The command moves the swarm's own daemons and the queue into the cluster: The swarm's own daemons and the queue move into the cluster:
`swarm-notify-router`, `swarm-review-classifier`, `swarm-claude-login`, `swarm-notify-router`, `swarm-review-classifier`, `swarm-claude-login`,
`swarm-stt`, `swarm-ci-metrics`, NATS with `swarm-nats-auth`, and `swarm-stt`, `swarm-ci-metrics`, NATS with `swarm-nats-auth`, and
`swarm-controller`. bao, the forge, authelia, the gateway, `swarm-builder`, `swarm-controller`. bao, the forge, authelia, the gateway, `swarm-builder`,
@ -18,59 +18,39 @@ The command moves the swarm's own daemons and the queue into the cluster:
- **The hive contract stays the same.** Hives and agents keep the NATS URL, - **The hive contract stays the same.** Hives and agents keep the NATS URL,
its port, its certificate name and its auth callout. No hive needs a its port, its certificate name and its auth callout. No hive needs a
rebuild for any move. rebuild for any move.
- **The host copy of the state stays on disk** until the operator runs
`swarmctl migrate finish`. A forward move only reads it, so a rollback
always has it to return to.
- **One nix option decides where a service runs.** `deploy.<svc>.runtime` is - **One nix option decides where a service runs.** `deploy.<svc>.runtime` is
`"host"` (the default) or `"k8s"`. The cut-over is an operator rebuild, `"host"` (the default) or `"k8s"`. The cut-over is an operator rebuild,
never a runtime toggle that `swarmctl` flips on its own. never a runtime toggle that `swarmctl` flips on its own.
- **A move leaves the host's data alone.** The host unit's directories stay
where they're, so going back is `runtime = "host"` and a rebuild.
### Names ### Names
| name | what it names | | name | what it names |
| --------------------------------------------------- | --------------------------------------------------------------- | | ----------------------------------------- | --------------------------------------------------------------- |
| `services.hyperhive.deploy.k8s.enable` | brings up single-node k3s on the swarm host | | `services.hyperhive.deploy.k8s.enable` | brings up single-node k3s on the swarm host |
| `services.hyperhive.deploy.<svc>.runtime` | `"host"` or `"k8s"`, per service | | `services.hyperhive.deploy.<svc>.runtime` | `"host"` or `"k8s"`, per service |
| `/etc/hyperhive/migrate.json` | the module's render of each service's runtime, state paths, PVC | | `/etc/hyperhive/migrate.json` | the module's render of each service's runtime and host units |
| `/var/lib/hyperhive-migrate/` | host record: pre-move snapshots and copy digests, root `0700` | | `SWARMCTL_KUBECTL`, `SWARMCTL_KUBECONFIG` | the `swarmctl` wrapper's `kubectl` and the k3s admin kubeconfig |
| `SWARMCTL_KUBECTL`, `SWARMCTL_KUBECONFIG` | the `swarmctl` wrapper's `kubectl` and the k3s admin kubeconfig | | `swarmctl migrate status` | the one verb: a read-only report |
| `.hyperhive-migrated` in a PVC | the copy marker the pod's start gate checks for |
| `swarmctl migrate` `status` / `rollback` / `finish` | the verbs |
## The move of one stateful service ## `swarmctl migrate status`
A service with state moves in four steps. A service without state skips steps It reads `/etc/hyperhive/migrate.json`, asks systemd whether each service's
2 and 3. host units run, and lists the pods of the swarm's namespace with one
`kubectl get`. It creates and changes nothing. For each service it reports:
1. **Snapshot** (`swarmctl migrate`, before the rebuild). Records what the - **runtime**: whether the host units have stopped when the configuration says
service holds while its host unit still runs, for the check in step 4: a file `k8s`, and whether the cluster still holds a pod of a service the
list with sizes of the state directory. The record goes to configuration puts on the host;
`/var/lib/hyperhive-migrate/<svc>.json`. - **order**: whether the service moved before one that comes earlier in the
2. **Cut-over rebuild** (the operator). The operator sets [order of moves](#order-of-moves);
`deploy.<svc>.runtime = "k8s"` and rebuilds. The rebuild stops the host - **ready**: whether the newest pod's readiness probe passes (a `CronJob`'s pod
unit and renders it no more, and applies the workload and its PVC. The finishes when its Job completed).
pod's first init container is the **start gate**. It exits 0 only when the
PVC holds `.hyperhive-migrated`, or when the PVC is empty and the
service's `deploy.<svc>.k8s.freshState` is on. Any other volume fails the
gate: the pod stays in `Init:Error` with one line saying to run
`swarmctl migrate <svc>` or set the option, and the kubelet runs the gate
again with a growing delay. A pod therefore never starts on an empty
volume, whatever re-applies the manifest.
3. **Copy** (`swarmctl migrate`). Refuses while the host unit runs. Streams
the host state directory as a tar archive into a copy pod that mounts the
PVC, into `.incoming/`. Checks the digest of the unpacked tree against the
source, moves `.incoming/` into place, sets ownership to the image's user,
and writes `.hyperhive-migrated` last, with the source path and digest.
The gate opens.
4. **Verify** (`swarmctl migrate`). Waits for the pod's readiness, then
compares what the service serves against the snapshot from step 1.
The copy pod runs a small `swarmctl` image with the hidden subcommand It names the next step that isn't done, exits 0 when every check ran, and
`migrate receive`. The start gate is a script in an image of its own that holds exits 1 when a check failed to run. `--json` prints the services as the module
coreutils and nothing else. The service images carry no shell and no `tar`, and renders them, every step with its status, and the next step.
this keeps them that way. The copy streams through the
k8s API instead of writing into the volume's directory on the host, so it works
for every storage class.
## Services ## Services
@ -78,15 +58,15 @@ for every storage class.
endpoints the [services page](../../2-handbook/swarm/services.md) lists; the endpoints the [services page](../../2-handbook/swarm/services.md) lists; the
[readiness page](../swarm/readiness.md) has their mechanics. [readiness page](../swarm/readiness.md) has their mechanics.
| service | state | what moves | readiness signal | cut-over and rollback | | service | state | what the pod starts with | readiness signal | cut-over and rollback |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `swarm-notify-router` | in the queue: a state bucket and a durable consumer on the forge events stream | nothing | `/readyz`: queue connected | `runtime = "k8s"`, rebuild; back with `runtime = "host"` | | `swarm-notify-router` | in the queue: a state bucket and a durable consumer on the forge events stream | the queue's | `/readyz`: queue connected | `runtime = "k8s"`, rebuild; back with `runtime = "host"` |
| `swarm-review-classifier` | none on disk; its runs and settings live in buckets the controller owns | nothing | `/readyz`: queue connected | same | | `swarm-review-classifier` | none on disk; its runs and settings live in buckets the controller owns | the queue's | `/readyz`: queue connected | same |
| `swarm-claude-login` | none; credentials it writes go to the store | nothing; a login in progress ends | `/readyz`: queue connected | same | | `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-stt` | the transcript cache, entries live 24 h; the pod keeps it in an `emptyDir` | 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"` | | `swarm-ci-metrics` | `cursor.json` in the state directory; losing it re-pushes every run | an empty claim: the 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 | 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 | | 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 host unit's own `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 | | `swarm-controller` | its state directory holds the legacy `webhook-secret` (the store has it too), the forge avatar markers and, once, a legacy operator-admin file; the grant record is in the queue's key-value store | an `emptyDir` | `/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. Back with `runtime = "host"` and a rebuild |
Two facts the table rests on: Two facts the table rests on:
@ -96,11 +76,12 @@ Two facts the table rests on:
the same files, so a switch in either direction copies nothing, and the the same files, so a switch in either direction copies nothing, and the
streams, consumers and acknowledgements are the ones the other side left. streams, consumers and acknowledgements are the ones the other side left.
See [the queue's store](#the-queues-store). See [the queue's store](#the-queues-store).
- **The webhook secret lives in the store.** The state directory's - **The controller keeps no state of its own that a move could lose.** The
`webhook-secret` is a fallback the controller reads only when the store record of the Matrix admin grants is in the queue's key-value store, the
doesn't answer. The copy moves it anyway, so a pod that starts while the webhook secret is in the secret store, and the controller sets the avatar
store is down still verifies forge deliveries. Preflight checks that the markers again at start. The first start of the controller on the host after
store holds the secret. an upgrade imports a legacy grant file into the store, so run the host
controller once before the switch.
## The queue's store ## The queue's store
@ -130,17 +111,17 @@ The claim `swarm-nats-store` binds it by name, so nothing else binds either.
## Order of moves ## Order of moves
`swarmctl migrate` moves the services in this order: `swarmctl migrate status` reports the services in this order, and flags a
service that moved ahead of an earlier one:
1. **`swarm-notify-router` alone.** The first cut-over proves the runtime 1. **`swarm-notify-router` alone.** The first cut-over proves the runtime
switch, the image, the store identity and reaching the host-run NATS by switch, the image, the store identity and reaching the host-run NATS by
name, with nothing to copy. name.
2. **`swarm-review-classifier`, `swarm-claude-login`, `swarm-stt`, 2. **`swarm-review-classifier`, `swarm-claude-login`, `swarm-stt`,
`swarm-ci-metrics`**, in one rebuild or one at a time. Nothing to copy, same `swarm-ci-metrics`**, in one rebuild or one at a time, the same pattern as
pattern as step 1: the pods start with no gate on an empty volume. step 1.
3. **NATS with `swarm-nats-auth`.** The riskiest move: every hive and 3. **NATS with `swarm-nats-auth`.** The riskiest move: every hive and agent
agent disconnects, and the data is the swarm's desired state. Nothing is disconnects, and the data is the swarm's desired state. Nothing copies it.
copied, and the controller is the only service `swarmctl migrate` copies.
`swarm-nats-auth` moves in the same pod, because it answers the auth `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 callout on every connect and dials the server by name, which the pod's
host aliases map to its loopback. host aliases map to its loopback.
@ -150,101 +131,14 @@ The claim `swarm-nats-store` binds it by name, so nothing else binds either.
the NATS move, and `swarmctl` keeps its local socket for the checks. the NATS move, and `swarmctl` keeps its local socket for the checks.
- Its cut-over also changes the gateway's upstream and ends the local - Its cut-over also changes the gateway's upstream and ends the local
socket for `swarmctl`, the widest change to the operator's tools. socket for `swarmctl`, the widest change to the operator's tools.
- Its state is small, so its rollback is cheap.
Each step needs the previous one Ready and verified. `swarmctl migrate` says Each step needs the previous one Ready. `swarmctl migrate status` says which
which service comes next, and refuses to copy a service out of order unless service comes next.
the operator passes `--out-of-order`.
## Preflight
`swarmctl migrate` runs these before its first snapshot, and again before each
copy. A failed check names what's missing and stops; it changes nothing.
| check | how | fails when |
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |
| k3s node Ready | `kubectl get nodes` with the k3s admin kubeconfig | the node is NotReady, or `deploy.k8s.enable` is off |
| images present | every image the next move needs shows in the node's image list | an image is missing |
| store login from a pod | a short-lived probe pod with the next service's identity logs in to bao and reads one path that service may read | the login or the read fails |
| host services reachable | the probe pod resolves the bao, forge, authelia and collector names to the node and completes TLS to each; while NATS runs on the host, NATS too | a name doesn't resolve, or a handshake fails |
| disk space | free space on the filesystem behind the PVCs is at least twice the sum of the state still to copy, plus 1 GiB | not enough room for the copy and a later rollback copy |
| host unit state | the service's host unit is active before the snapshot, and inactive before the copy | the order of steps doesn't hold |
| webhook secret in the store (controller only) | the controller's store path for it holds a value | the store has none; the operator restarts the host controller first, which seeds it |
| controller listener (controller only) | the controller's TCP listener answers a client holding the gateway leaf, and refuses one without | the listener is off or refuses the gateway |
## Resume and rollback
`swarmctl migrate` keeps no progress file of its own. Like `swarmctl setup`, it
observes the system, judges each step as done, not done or unknown from what it
sees, and plans again after every step. A rerun resumes where the last run
stopped, and the loop offers retry, skip or quit on a failed step.
### What's observed and what's recorded
| fact | observed from |
| ---------------------------------- | ---------------------------------------------------------- |
| where the config wants the service | `/etc/hyperhive/migrate.json`, which the rebuild renders |
| host unit active or not | `systemctl is-active` |
| workload, pod phase, Ready | `kubectl` |
| copy done | the pod's `state-gate` init container, in the pod's status |
`swarmctl migrate status` reads the gate's answer from the pod's status: the
gate exited 0 when the marker is in the volume, and a refusal puts its reason
in the container's termination message. Status never starts a pod, so it
creates nothing and reads only.
Two facts vanish once the host unit stops, so `/var/lib/hyperhive-migrate/`
records them: the step 1 snapshot, and the digest of the copied tree. Without
a snapshot, step 4 falls back to the stream names on disk and says so.
### Idempotence
- The snapshot overwrites its record while the host unit runs, and refuses to
once it stops.
- The copy starts by emptying `.incoming/`, and runs only while the marker is
absent. Rerunning it after an interrupted copy starts over.
- A rerun skips a copy whose marker exists.
- Verification only reads.
- `rollback` and `finish` check their own preconditions and skip what's done.
### Half-done migrations
| what the operator sees | resume | roll back |
| ------------------------------------------------- | --------------------------------------------------------- | ------------------------------------------------------------------- |
| rebuilt, the pod waits in its gate, no marker | `swarmctl migrate` copies | `runtime = "host"`, rebuild; the host state never changed |
| `.incoming/` in the PVC, no marker (copy cut off) | `swarmctl migrate` empties it and copies again | same as above |
| marker written, pod not Ready | read the pod's log; fix, then `swarmctl migrate` verifies | `swarmctl migrate rollback <svc>`, then `runtime = "host"`, rebuild |
| Ready, verification failed | the mismatch says what differs; the operator decides | same as above |
| verified | nothing to do | same as above |
`swarmctl migrate rollback <svc>` works in this order:
1. Removes the marker and deletes the pod. The replacement waits in the gate,
so nothing writes to the PVC from here on, whatever re-applies the
manifest.
2. Copies the PVC into `<host dir>.from-k8s` and checks its digest.
3. Renames the host directory to `<host dir>.pre-rollback` and
`<host dir>.from-k8s` to the host directory, owned by the host unit's
user. Both renames stay on one filesystem.
4. Tells the operator to set `runtime = "host"` and rebuild, then verifies
the host unit's readiness after that rebuild.
The rollback copies back because every write after the cut-over exists only
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
every service passed verification where the config wants it. A rebuild that
stops a workload leaves its PVC in place, so the data survives until `finish`.
A fresh install straight onto k8s has no host state to copy: with
`deploy.<svc>.k8s.freshState` on, the gate marks the empty volume itself
(`{"fresh": true, "at": <time>}`), and `swarmctl migrate` isn't needed.
## Downtime and what hives see ## Downtime and what hives see
The budget is the time from the cut-over rebuild stopping the host unit to the The budget is the time from the cut-over rebuild stopping the host unit to the
pod passing step 4. pod being Ready.
| service | budget | what hives, agents and the operator see | | service | budget | what hives, agents and the operator see |
| ------------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ------------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

View file

@ -39,7 +39,7 @@ its systemd unit, and nothing applies the services' manifests: two copies of
`swarm-notify-router`, `swarm-ci-metrics` or `swarm-controller` would share one `swarm-notify-router`, `swarm-ci-metrics` or `swarm-controller` would share one
queue consumer, one cursor or one swarm. A service's objects go into the queue consumer, one cursor or one swarm. A service's objects go into the
cluster when its `runtime` is `"k8s"` ([the runtime switch](runtime.md), which cluster when its `runtime` is `"k8s"` ([the runtime switch](runtime.md), which
[`swarmctl migrate`](migrate.md) drives). [`swarmctl migrate status`](migrate.md) reports).
With the option off, the host's configuration is the one it has without the With the option off, the host's configuration is the one it has without the
module. module.

View file

@ -31,10 +31,6 @@ cluster follow the same pattern.
rule. One switch covers the queue's server and its auth callout. It needs rule. One switch covers the queue's server and its auth callout. It needs
the iptables firewall (`networking.nftables.enable` off). the iptables firewall (`networking.nftables.enable` off).
[The queue](#the-queue) has its own section. [The queue](#the-queue) has its own section.
- `services.hyperhive.deploy.<service>.k8s.freshState` (default `false`) for
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 With `"host"`, a host without [the cluster node](node.md) renders the same
configuration as before the option existed. With the node on and every service configuration as before the option existed. With the node on and every service
@ -104,27 +100,14 @@ Job:
A failed step fails the unit, and the host unit doesn't start: the service stays A failed step fails the unit, and the host unit doesn't start: the service stays
down and never doubles. A rerun resumes from the renamed link. Persistent volume down and never doubles. A rerun resumes from the renamed link. Persistent volume
claims stay; `swarmctl migrate finish` deletes them. claims stay until the operator deletes them.
## State ## State
A pod with a state volume that holds state worth moving (`swarm-controller`) No pod starts behind a gate that checks its state volume: a service keeps
starts only on migrated state. Its first init container, `state-gate`, mounts nothing a switch has to copy. Each service's state is below.
the volume and exits 0 when the volume holds `.hyperhive-migrated`. A volume `swarm-notify-router`, `swarm-review-classifier` and `swarm-claude-login` have
with no entries besides `lost+found` gets the marker (`{"fresh": true, "at": no volume.
<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
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, `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 `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 forge events stream and its `notify-router-state` bucket live in the queue, so a
@ -132,22 +115,20 @@ switch in either direction copies nothing, and the router continues from the
consumer's position. consumer's position.
`swarm-stt` keeps a transcript cache, which lives 24 hours. On the host the `swarm-stt` keeps a transcript cache, which lives 24 hours. On the host the
cache sits in the container's `/var/lib/swarm-stt`. In the cluster it sits in cache sits in the container's `/var/lib/swarm-stt`. In the cluster it sits in an
an `emptyDir` at the same path, so the pod has no claim and no gate and starts `emptyDir` at the same path, so the pod has no claim and starts on an empty
on an empty cache on every start of the pod. A switch copies nothing, and the cache on every start of the pod. A switch copies nothing, and the service
service transcribes a memo that only the other side cached. The whisper model transcribes a memo that only the other side cached. The whisper model isn't
isn't state: the pod's image holds it, from the same store path the container state: the pod's image holds it, from the same store path the container reads.
reads.
`swarm-ci-metrics` keeps a cursor, `cursor.json`, which holds the run numbers `swarm-ci-metrics` keeps a cursor, `cursor.json`, which holds the run numbers
already pushed. On the host it sits in the service's state directory. In the already pushed. On the host it sits in the service's state directory. In the
cluster it sits in the PersistentVolumeClaim `swarm-ci-metrics-state`, mounted cluster it sits in the PersistentVolumeClaim `swarm-ci-metrics-state`, mounted
at the same path, and the claim binds with the first Job. A switch copies at the same path, and the claim binds with the first Job. A switch copies
neither, so each side keeps the cursor it last had, and the first pass on a side neither, so each side keeps the cursor it last had, and the first pass on a side
with none pushes every run again, as the same points. The pod starts on the with none pushes every run again, as the same points. A second Job on the same
empty claim with no gate. A second Job on the same side finds the cursor and side finds the cursor and pushes nothing. The claim stays after a switch back,
pushes nothing. The claim stays after a switch back, and so does the host's and so does the host's directory.
directory.
## The controller ## The controller
@ -192,13 +173,13 @@ controller may move there.
`/healthz` and readiness on `/readyz`. Readiness needs the queue connection `/healthz` and readiness on `/readyz`. Readiness needs the queue connection
and a fresh store login, so a store role that refuses the pod's token leaves and a fresh store login, so a store role that refuses the pod's token leaves
it NotReady. it NotReady.
- **State.** `/var/lib/swarm-controller` is the PersistentVolumeClaim - **State.** `/var/lib/swarm-controller` is an `emptyDir`. The record of the
`swarm-controller-state`. It starts empty, and nothing here copies the host's operator Matrix admin grants is in the queue's key-value store, so the pod
directory into it ([migrate](migrate.md) does). An empty claim holds no revokes the accounts the host controller granted. What the directory holds
`operator-matrix-admins.json`, which reads as an empty set: the controller starts again from nothing: the forge avatar markers and the legacy webhook
revokes nobody, and an account removed from the operator group before the secret, which the secret store also holds. The controller's first start on
copy keeps its homeserver admin. The webhook secret is in the store, so it the host imports a legacy grant file into the store, so run it there once
survives. before the switch.
- **The rev.** The unit's rev file, `/etc/hyperhive/swarm-controller.json`, is a - **The rev.** The unit's rev file, `/etc/hyperhive/swarm-controller.json`, is a
`subPath` mount of the `swarm-controller-etc` ConfigMap, which a running pod `subPath` mount of the `swarm-controller-etc` ConfigMap, which a running pod
never sees change. The Deployment's pod template carries `checksum/etc`, a never sees change. The Deployment's pod template carries `checksum/etc`, a

View file

@ -85,6 +85,12 @@ let
in in
{ {
imports = [ 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" ] '' (lib.mkRemovedOptionModule [ "services" "hyperhive" "deploy" "nats" "k8s" "freshState" ] ''
The pod mounts the host unit's own store directory, so there is no empty 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. 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 # 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 # 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 # the service when it is on the host. The file and the wrapper exist only on a
# volume, that state: the claim, the mount in the pod, where the data lives # host with the node (./node.nix): without a cluster there is nothing to read.
# 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.
{ {
lib, lib,
pkgs, pkgs,
@ -21,71 +18,22 @@ let
node = deployCfg.k8s; node = deployCfg.k8s;
controllerCfg = deployCfg.swarm-controller; controllerCfg = deployCfg.swarm-controller;
# The path of a unit's state directory in a pod, which ./render.nix mounts # Each service's name under `services.hyperhive.deploy`.
# the claim at. optionOf = {
stateMount = unit: "/var/lib/${unit.serviceConfig.StateDirectory}"; swarm-controller = "swarm-controller";
swarm-nats = "nats";
pathsWithin = import ../lib/paths-within.nix { inherit lib; }; swarm-notify-router = "notify-router";
swarm-stt = "stt";
controllerStateDir = "/var/lib/swarm-controller"; swarm-review-classifier = "review-classifier";
swarm-claude-login = "claude-login";
# `option` is the service's name under `services.hyperhive.deploy`. `state` swarm-ci-metrics = "ci-metrics";
# 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;
};
}; };
entry = entry = name: switch: {
name: switch: option = "services.hyperhive.deploy.${optionOf.${name}}.runtime";
let inherit (switch) runtime;
row = stateTable.${name}; hostUnits = lib.toList switch.hostUnit;
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;
};
migrateJson = { migrateJson = {
inherit (cfg) namespace; 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 # 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
@ -152,11 +136,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 a service whose state is worth moving: the # `ephemeralState` gives a service an `emptyDir` in place of a claim for its
# volume's first init container, the state gate, refuses to start the pod on # state directory: what it keeps there is re-derived at start. A pod starts on
# one that holds no migrated state unless the install is fresh. A service # whatever volume it gets.
# without it starts on whatever volume it gets, and one with
# `ephemeralState` gets an `emptyDir` in place of a claim.
# `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
@ -192,7 +174,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; ephemeralState = true;
switch = { switch = {
inherit (controllerCfg) runtime; inherit (controllerCfg) runtime;
hostUnit = "swarm-controller.service"; hostUnit = "swarm-controller.service";
@ -776,43 +758,6 @@ let
package = leafImagePackage; package = leafImagePackage;
bin = leafIssueBin; 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. # What the service adds to the daemon's pod.
extra = { extra = {
containers = [ ]; containers = [ ];
@ -890,11 +835,8 @@ let
}; };
} }
// lib.optionalAttrs baoLogin { serviceAccountName = name; } // lib.optionalAttrs baoLogin { serviceAccountName = name; }
// lib.optionalAttrs (stateVolume != null || listener != { } || extra.initContainers != [ ]) { // lib.optionalAttrs (listener != { } || extra.initContainers != [ ]) {
initContainers = initContainers = lib.optional (listener != { }) leafContainer ++ extra.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;
@ -1014,10 +956,7 @@ let
{ {
inherit objects image; inherit objects image;
# What the pod's other containers run. # What the pod's other containers run.
extraImages = extraImages = lib.optional (listener != { }) leafImage ++ extra.images;
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);

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 The pod needs the TCP listener
({option}`services.hyperhive.swarm.controller.tcp.enable`): the host ({option}`services.hyperhive.swarm.controller.tcp.enable`): the host
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 directory is an
volume, which starts empty: nothing moves the host's state directory `emptyDir`: the operator grant record is in the queue's key-value
into it, and the pod does not start on it until `swarmctl migrate` store, and what is left in the directory (the forge avatar markers, the
marks it or legacy webhook secret the store also holds) is made again at start. A
{option}`services.hyperhive.deploy.swarm-controller.k8s.freshState` host's legacy grant file is imported into the store by the first start
is set. 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 { unit = lib.mkOption {
type = lib.types.raw; type = lib.types.raw;
readOnly = true; readOnly = true;

View file

@ -108,16 +108,6 @@ let
inherit lib pkgs config; inherit lib pkgs config;
}).objects; }).objects;
objects = render allLocal; 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 # 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. # 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)); 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 # The images are the ones the manifests run, one per rendered service, the
# controller's listener leaf, the queue's three more (server, exporter, # controller's listener leaf, the queue's three more (server, exporter,
# init) and the one state gate every stateful pod shares: the twelve are # init): the eleven are the control that the list is not empty.
# the control that the list is not empty.
name = "the node loads the image of every service the manifests run, and k3s's own"; name = "the node loads the image of every service the manifests run, and k3s's own";
ok = ok =
let let
loaded = map toString withNode.services.k3s.images; loaded = map toString withNode.services.k3s.images;
rendered = map toString withNode.system.build.k8sImages; rendered = map toString withNode.system.build.k8sImages;
in in
lib.length rendered == 12 lib.length rendered == 11
&& lib.all (i: lib.elem i loaded) rendered && lib.all (i: lib.elem i loaded) rendered
&& lib.elem (toString withNode.services.k3s.package.airgap-images) loaded && 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' # Nothing the host already runs differs but the store's side of the pods'
@ -1448,7 +1437,6 @@ let
== [ == [
"ConfigMap" "ConfigMap"
"Deployment" "Deployment"
"PersistentVolumeClaim"
"ServiceAccount" "ServiceAccount"
]; ];
} }
@ -1506,7 +1494,7 @@ let
&& annotationOf rolled != annotationOf onCluster && annotationOf rolled != annotationOf onCluster
# A pod with no ConfigMap carries no annotation: the router is the control. # A pod with no ConfigMap carries no annotation: the router is the control.
&& !((cluster."swarm-notify-router/deployment".spec.template.metadata) ? annotations) && !((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 # The pod issues its own listener leaf with the unit's script, logging in
@ -1527,7 +1515,7 @@ let
createDir = false; createDir = false;
}; };
spec = (render onCluster)."swarm-controller/deployment".spec.template.spec; 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; renew = lib.last spec.containers;
main = lib.head spec.containers; main = lib.head spec.containers;
mountsOf = x: map (m: m.name) x.volumeMounts; mountsOf = x: map (m: m.name) x.volumeMounts;
@ -1546,11 +1534,7 @@ let
&& !(lib.hasInfix "chgrp" podScript) && !(lib.hasInfix "chgrp" podScript)
&& lib.hasInfix "-checkhost \"$name\"" podScript && lib.hasInfix "-checkhost \"$name\"" podScript
&& lib.hasInfix "issue/swarm-controller-tls" podScript && lib.hasInfix "issue/swarm-controller-tls" podScript
&& && map (c: c.name) spec.initContainers == [ "tls-issue" ]
map (c: c.name) spec.initContainers == [
"state-gate"
"tls-issue"
]
&& init.name == "tls-issue" && init.name == "tls-issue"
&& renew.name == "tls-renew" && renew.name == "tls-renew"
&& renew.command == [ "/bin/swarm-controller-tls-renew" ] && renew.command == [ "/bin/swarm-controller-tls-renew" ]
@ -1688,11 +1672,11 @@ let
&& pvc.spec.accessModes == [ "ReadWriteOnce" ] && pvc.spec.accessModes == [ "ReadWriteOnce" ]
# The claim binds by name the static local volume on the container's # 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. # 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.volumeName == pv.metadata.name
&& pvc.spec.storageClassName == pv.spec.storageClassName && pvc.spec.storageClassName == pv.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.local.path == hostStore
&& pv.spec.persistentVolumeReclaimPolicy == "Retain" && pv.spec.persistentVolumeReclaimPolicy == "Retain"
&& !(pv.metadata ? namespace) && !(pv.metadata ? namespace)
@ -1716,81 +1700,48 @@ let
&& !(lib.any (v: v ? secret) spec.volumes); && !(lib.any (v: v ? secret) spec.volumes);
} }
{ {
# The gate is the first init container of a pod whose state is worth # No pod starts on a gate: its first init container is the leaf's or
# moving, ahead of the TLS leaf. The default holds the pod back; a fresh # none. Each pod's state directory is read off the manifest: an emptyDir
# install opts in. Each arm's value is the control for the other, and the # where the service re-derives what it keeps, a claim where it does not
# gated services are the control for the ones that start with no gate. # (the poller's cursor), and the queue's claim is its own, bound to the
name = "every pod whose state is worth moving starts with the state gate on that volume, and the fresh option sets what it reads"; # 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 = ok =
let let
fresh = render (freshInstall onCluster);
specOf = specOf =
objs: name: name:
let let
o = objs."${name}/deployment" or objs."${name}/cronjob"; o = objects."${name}/deployment" or objects."${name}/cronjob";
in in
if o.kind == "CronJob" then o.spec.jobTemplate.spec.template.spec else o.spec.template.spec; if o.kind == "CronJob" then o.spec.jobTemplate.spec.template.spec else o.spec.template.spec;
inits = objs: name: (specOf objs name).initContainers or [ ]; stateVolume = name: lib.findFirst (v: v.name == "state") null (specOf name).volumes;
gate = objs: name: lib.findFirst (i: i.name == "state-gate") null (inits objs name); services = [
envOfGate = g: lib.listToAttrs (map (e: lib.nameValuePair e.name e.value) g.env); "swarm-controller"
gated = { "swarm-nats"
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 = [
"swarm-notify-router" "swarm-notify-router"
"swarm-stt"
"swarm-review-classifier" "swarm-review-classifier"
"swarm-claude-login" "swarm-claude-login"
"swarm-stt"
];
ungated = unclaimed ++ [
"swarm-ci-metrics" "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 in
lib.all (n: one n gated.${n}) (lib.attrNames gated) lib.all (n: !(lib.any (i: i.name == "state-gate") ((specOf n).initContainers or [ ]))) services
&& lib.all (n: gate objects n == null && gate fresh n == null) ungated &&
&& lib.all (n: !(objects ? "${n}/persistentvolumeclaim")) unclaimed stateVolume "swarm-controller" == {
&& lib.all (n: objects ? "${n}/persistentvolumeclaim") ( name = "state";
lib.attrNames gated ++ [ "swarm-ci-metrics" ] emptyDir = { };
) }
# One image serves every gate. &&
&& lib.length (lib.unique (map (n: (gate objects n).image) (lib.attrNames gated))) == 1; 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 # 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; && 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 file names the runtime and the host units of every service and no
# the PVC's name and the mount is where the state gate looks. The # state: nothing is copied. The units of the poller (timer and service)
# stateless services are the control that an entry can carry no state. The # are the control for a list of more than one.
# poller has a claim and no entry, since it starts without a gate. name = "migrate.json names every service with its option, host units and the runtime the configuration wants, and no state";
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";
ok = ok =
let let
host = (migrateOf withNode).services; host = (migrateOf withNode).services;
cluster = (migrateOf onCluster).services; cluster = (migrateOf onCluster).services;
in in
(migrateOf withNode).namespace == "hyperhive" (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. lib.sort lib.lessThan (lib.attrNames host) == [
&& host.swarm-nats.state == null "swarm-ci-metrics"
&& host.swarm-ci-metrics.state == null "swarm-claude-login"
&& host.swarm-stt.state == null "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 == [ host.swarm-ci-metrics.hostUnits == [
"swarm-ci-metrics.timer" "swarm-ci-metrics.timer"
@ -1945,35 +1857,7 @@ let
&& host.swarm-ci-metrics.option == "services.hyperhive.deploy.ci-metrics.runtime" && host.swarm-ci-metrics.option == "services.hyperhive.deploy.ci-metrics.runtime"
&& lib.all (s: s.runtime == "host") (lib.attrValues host) && lib.all (s: s.runtime == "host") (lib.attrValues host)
# The runtime follows the option: the cluster fixture has every one on k8s. # The runtime follows the option: the cluster fixture has every one on k8s.
&& lib.all (s: s.runtime == "k8s") (lib.attrValues cluster) && 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 == [ ];
} }
{ {
name = "swarmctl is wrapped with kubectl and the cluster's kubeconfig, by one wrapper per host"; 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 # 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 # 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; # the name; the controller answers an unsigned webhook 401 both times;
# - a changed hyperhive rev rolls the Deployment, and the state volume is the # - a changed hyperhive rev rolls the Deployment; the pod's state directory is
# one the first pod had; # an emptyDir, with no claim and no gate;
# - the switch back leaves no pod, Deployment or AddOn, and the host unit # - the switch back leaves no pod, Deployment or AddOn, and the host unit
# starts after the prune 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`.
# #
# The queue is a plain nats-server with TLS and one stub is the token endpoint # 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 # 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"; controllerSecretLeaf = "swarm/controller/swarm-controller/oidc/client";
revA = lib.fixedWidthString 40 "a" ""; revA = lib.fixedWidthString 40 "a" "";
revB = lib.fixedWidthString 40 "b" ""; 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"; overlapLog = "/var/log/overlap.log";
tokenLog = "/var/log/stub-token.log"; tokenLog = "/var/log/stub-token.log";
@ -191,18 +181,9 @@ pkgs.testers.runNixOSTest {
}; };
system.stateVersion = "25.11"; system.stateVersion = "25.11";
specialisation.k8s.configuration.services.hyperhive.deploy.swarm-controller = { specialisation.k8s.configuration.services.hyperhive.deploy.swarm-controller.runtime = "k8s";
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-rev.configuration.services.hyperhive.deploy = { specialisation.k8s-rev.configuration.services.hyperhive.deploy = {
swarm-controller.runtime = "k8s"; swarm-controller.runtime = "k8s";
swarm-controller.k8s.freshState = true;
hive-controller.hyperhiveRev = lib.mkForce revB; hive-controller.hyperhiveRev = lib.mkForce revB;
}; };
@ -323,7 +304,7 @@ pkgs.testers.runNixOSTest {
environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml"; environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml";
environment.etc."k3s-node/images".text = lib.concatMapStrings ( environment.etc."k3s-node/images".text = lib.concatMapStrings (
i: "${i.imageName}:${i.imageTag}\n" 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. # 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" = 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 + '' testScript = builtins.readFile ./lib/k3s.py + ''
import re
INIT = "/root/bao-init.json" INIT = "/root/bao-init.json"
HELPER = "${helperImage.imageName}:${helperImage.imageTag}"
NS = "${namespace}" NS = "${namespace}"
SERVICE = "${service}" SERVICE = "${service}"
HOST_UNIT = "${hostUnit}" HOST_UNIT = "${hostUnit}"
@ -412,7 +390,7 @@ pkgs.testers.runNixOSTest {
except Exception: except Exception:
diagnose(["hyperhive-k8s-ca-trust.service"]) diagnose(["hyperhive-k8s-ca-trust.service"])
print(machine.execute(f"kubectl -n {NS} describe pod {name}")[1]) 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]) print(machine.execute(f"kubectl -n {NS} logs {name} -c {container} --tail=60")[1])
raise raise
return name return name
@ -546,16 +524,15 @@ pkgs.testers.runNixOSTest {
assert probe["path"] == "/readyz", probe assert probe["path"] == "/readyz", probe
api = next(p for p in main["ports"] if p["name"] == "api") api = next(p for p in main["ports"] if p["name"] == "api")
assert api["hostPort"] == PORT and api["hostIP"] == NODE_ADDRESS, 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"] assert [c["name"] for c in spec["initContainers"]] == ["tls-issue"], spec["initContainers"]
GATE_IMAGE = spec["initContainers"][0]["image"]
assert "tls-renew" in [c["name"] for c in spec["containers"]] assert "tls-renew" in [c["name"] for c in spec["containers"]]
assert not any("secret" in v for v in spec["volumes"]), spec["volumes"] assert not any("secret" in v for v in spec["volumes"]), spec["volumes"]
env = {e["name"]: e.get("value") for e in main["env"]} env = {e["name"]: e.get("value") for e in main["env"]}
assert env["BAO_AUTH"] == "jwt" and env["BAO_JWT_ROLE"] == SERVICE, env assert env["BAO_AUTH"] == "jwt" and env["BAO_JWT_ROLE"] == SERVICE, env
assert "BAO_CLIENT_CERT" not in env, env assert "BAO_CLIENT_CERT" not in env, env
claim = json.loads(kube(machine, f"get pvc {SERVICE}-state -o json")) # The state directory is an emptyDir: no claim, no gate.
assert claim["status"]["phase"] == "Bound", claim assert [v for v in spec["volumes"] if v["name"] == "state"] == [{"name": "state", "emptyDir": {}}], spec["volumes"]
STATE_VOLUME = claim["metadata"]["uid"] 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 # 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, # 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. # 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 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_uid = pod(machine, pod_name)["metadata"]["uid"]
old_annotation = pod(machine, pod_name)["metadata"]["annotations"]["checksum/etc"] old_annotation = pod(machine, pod_name)["metadata"]["annotations"]["checksum/etc"]
switch("/run/booted-system/specialisation/k8s-rev") 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 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[]'") rev = machine.succeed(f"kubectl -n {NS} get configmap {SERVICE}-etc -o json | jq -r '.data[]'")
assert "${revB}" in rev, rev 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() assert len(pods()) == 1, pods()
with subtest("the switch back removes the Deployment, pod and AddOn before the unit starts"): 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) assert 0 < pruned <= started, (pruned, started)
requires = machine.succeed(f"systemctl show -p Requires --value {HOST_UNIT}") requires = machine.succeed(f"systemctl show -p Requires --value {HOST_UNIT}")
assert f"{PRUNE}.service" in requires, requires 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]) settle(f"curl -sf --unix-socket {SOCKET} http://x/readyz", 300, [HOST_UNIT])
assert gateway("gateway.service") == 401 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] 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] 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") 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
''; '';
} }

View file

@ -7,11 +7,6 @@
//! units run, and lists the pods in the swarm's namespace with one `kubectl //! units run, and lists the pods in the swarm's namespace with one `kubectl
//! get`; [`classify`] turns that into [`Step`]s and is pure, so every case is //! get`; [`classify`] turns that into [`Step`]s and is pure, so every case is
//! tested against hand-built observations. //! tested against hand-built observations.
//!
//! The copy marker is never read from the volume. The pod's first init
//! container, the start gate, exits 0 only with the marker present and
//! refuses otherwise with the reason in its termination message; both are in
//! the pod's status.
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::fmt::Write as _; use std::fmt::Write as _;
@ -26,13 +21,9 @@ use serde_json::Value;
/// What the module renders for this host. /// What the module renders for this host.
const CONFIG_PATH: &str = "/etc/hyperhive/migrate.json"; const CONFIG_PATH: &str = "/etc/hyperhive/migrate.json";
/// The pod's start gate: the init container that checks the copy marker.
const GATE_CONTAINER: &str = "state-gate";
/// The label every pod of the swarm carries, and the one that names its service. /// The label every pod of the swarm carries, and the one that names its service.
const PART_OF_SELECTOR: &str = "app.kubernetes.io/part-of=hyperhive"; const PART_OF_SELECTOR: &str = "app.kubernetes.io/part-of=hyperhive";
const SERVICE_LABEL: &str = "app.kubernetes.io/name"; const SERVICE_LABEL: &str = "app.kubernetes.io/name";
/// The text of the gate's refusal on a volume that holds files and no marker.
const GATE_NONEMPTY: &str = "holds files and no .hyperhive-migrated marker";
#[derive(Args)] #[derive(Args)]
#[command(args_conflicts_with_subcommands = true)] #[command(args_conflicts_with_subcommands = true)]
@ -43,8 +34,8 @@ pub struct MigrateArgs {
#[derive(Subcommand)] #[derive(Subcommand)]
enum MigrateVerb { enum MigrateVerb {
/// Report where each service stands: its runtime, its host units, its pod /// Report where each service stands: its runtime, its host units and its pod,
/// and the start gate's answer, and which step comes next. /// and which step comes next.
/// ///
/// Read-only: it creates no pod and changes nothing. Run it as root; it /// Read-only: it creates no pod and changes nothing. Run it as root; it
/// reads `/etc/hyperhive/migrate.json`, asks systemd about the host units /// reads `/etc/hyperhive/migrate.json`, asks systemd about the host units
@ -54,7 +45,7 @@ enum MigrateVerb {
/// Exits 0 when every check ran, whatever the answers, and 1 when a /// Exits 0 when every check ran, whatever the answers, and 1 when a
/// check failed to run. A script reads the report from `--json`. /// check failed to run. A script reads the report from `--json`.
Status(StatusArgs), Status(StatusArgs),
/// Moves a service. Not available yet: only `status` is. /// Any other word: only `status` exists.
#[command(external_subcommand)] #[command(external_subcommand)]
External(Vec<String>), External(Vec<String>),
} }
@ -119,33 +110,6 @@ pub(crate) struct Service {
pub(crate) runtime: Runtime, pub(crate) runtime: Runtime,
/// The units that run the service while it is on the host. /// The units that run the service while it is on the host.
pub(crate) host_units: Vec<String>, pub(crate) host_units: Vec<String>,
/// Null for a service with no state volume.
pub(crate) state: Option<State>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct State {
pub(crate) claim: String,
/// Where the pod mounts the claim.
pub(crate) mount: String,
/// Where the data lives on the host; null where nothing is copied.
pub(crate) host_path: Option<String>,
/// Paths under `host_path` a copy leaves out.
pub(crate) excludes: Vec<String>,
}
/// What the pod's start gate has answered.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Gate {
/// Exited 0: the marker is in the volume.
Passed,
/// Exited non-zero, with its termination message.
Refused(String),
/// Not finished yet.
Pending,
/// The pod has no state gate.
Absent,
} }
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
@ -155,7 +119,6 @@ pub(crate) struct Pod {
pub(crate) created: String, pub(crate) created: String,
pub(crate) phase: String, pub(crate) phase: String,
pub(crate) ready: bool, pub(crate) ready: bool,
pub(crate) gate: Gate,
} }
impl Pod { impl Pod {
@ -184,8 +147,6 @@ pub(crate) enum Kind {
Runtime, Runtime,
/// The service has moved before one that comes first. /// The service has moved before one that comes first.
Order, Order,
/// The start gate's marker.
Copy,
/// The pod runs. /// The pod runs.
Ready, Ready,
} }
@ -196,7 +157,6 @@ impl Kind {
Self::Config => "config", Self::Config => "config",
Self::Runtime => "runtime", Self::Runtime => "runtime",
Self::Order => "order", Self::Order => "order",
Self::Copy => "copy",
Self::Ready => "ready", Self::Ready => "ready",
} }
} }
@ -288,8 +248,7 @@ fn finished(name: &str, service: &Service, observed: &Observed) -> bool {
let newest = pods_of(name, pods).first().copied().cloned(); let newest = pods_of(name, pods).first().copied().cloned();
service.runtime == Runtime::K8s service.runtime == Runtime::K8s
&& host_units(service, &observed.units) == HostUnits::Stopped && host_units(service, &observed.units) == HostUnits::Stopped
&& newest && newest.is_some_and(|p| p.is_ready())
.is_some_and(|p| p.is_ready() && (service.state.is_none() || p.gate == Gate::Passed))
} }
/// Judge every service from what was observed, in the order of moves. /// Judge every service from what was observed, in the order of moves.
@ -338,13 +297,6 @@ pub(crate) fn classify(observed: &Observed) -> Vec<Step> {
)), )),
}); });
} }
if service.state.is_some() {
steps.push(Step {
service: (*name).clone(),
kind: Kind::Copy,
status: copy_status(service, &units, &pods, newest),
});
}
steps.push(Step { steps.push(Step {
service: (*name).clone(), service: (*name).clone(),
kind: Kind::Ready, kind: Kind::Ready,
@ -386,33 +338,6 @@ fn runtime_status(service: &Service, units: &HostUnits, pods: &Pods) -> Status {
} }
} }
fn copy_status(service: &Service, units: &HostUnits, pods: &Pods, newest: Option<&Pod>) -> Status {
if service.runtime == Runtime::Host {
return Status::NotDone("after the cut-over rebuild".into());
}
if let HostUnits::Running(unit, state) = units {
return Status::Blocked(format!(
"host unit {unit} is still {state}: a copy refuses until it stops"
));
}
if let Err(why) = pods {
return Status::Unknown(format!("pods: {why}"));
}
let Some(pod) = newest else {
return Status::NotDone("no pod yet: the rebuild has not applied the workload".into());
};
match &pod.gate {
Gate::Passed => Status::Done(format!("marker present ({})", pod.name)),
Gate::Refused(message) if message.contains(GATE_NONEMPTY) => Status::NotDone(format!(
"the volume holds files and no marker, so a copy was cut off or the volume was \
written to: {message}"
)),
Gate::Refused(message) => Status::NotDone(format!("waiting for the copy: {message}")),
Gate::Pending => Status::NotDone(format!("the gate of {} has not answered yet", pod.name)),
Gate::Absent => Status::Unknown(format!("{} has no {GATE_CONTAINER} container", pod.name)),
}
}
fn ready_status(service: &Service, pods: &Pods, newest: Option<&Pod>) -> Status { fn ready_status(service: &Service, pods: &Pods, newest: Option<&Pod>) -> Status {
if service.runtime == Runtime::Host { if service.runtime == Runtime::Host {
return Status::NotDone("not in the cluster".into()); return Status::NotDone("not in the cluster".into());
@ -423,9 +348,6 @@ fn ready_status(service: &Service, pods: &Pods, newest: Option<&Pod>) -> Status
match newest { match newest {
None => Status::NotDone("no pod".into()), None => Status::NotDone("no pod".into()),
Some(pod) if pod.is_ready() => Status::Done(format!("{} is {}", pod.name, pod.phase)), Some(pod) if pod.is_ready() => Status::Done(format!("{} is {}", pod.name, pod.phase)),
Some(pod) if matches!(pod.gate, Gate::Refused(_)) => {
Status::NotDone(format!("{} waits behind its start gate", pod.name))
}
Some(pod) => Status::NotDone(format!("{} is {}, not Ready", pod.name, pod.phase)), Some(pod) => Status::NotDone(format!("{} is {}, not Ready", pod.name, pod.phase)),
} }
} }
@ -531,49 +453,11 @@ pub(crate) fn parse_pods(json: &str) -> Result<Vec<Pod>, String> {
c.iter() c.iter()
.any(|c| c["type"] == "Ready" && c["status"] == "True") .any(|c| c["type"] == "Ready" && c["status"] == "True")
}), }),
gate: gate_of(pod),
}) })
}) })
.collect()) .collect())
} }
fn gate_of(pod: &Value) -> Gate {
let declared = pod["spec"]["initContainers"]
.as_array()
.is_some_and(|c| c.iter().any(|c| c["name"] == GATE_CONTAINER));
if !declared {
return Gate::Absent;
}
let Some(status) = pod["status"]["initContainerStatuses"]
.as_array()
.and_then(|c| c.iter().find(|c| c["name"] == GATE_CONTAINER))
else {
return Gate::Pending;
};
let refused = |t: &Value| {
Gate::Refused(
t["message"]
.as_str()
.map(str::trim)
.filter(|m| !m.is_empty())
.map_or_else(|| format!("exit {}", t["exitCode"]), str::to_owned),
)
};
let terminated = &status["state"]["terminated"];
if terminated.is_object() {
return if terminated["exitCode"] == 0 {
Gate::Passed
} else {
refused(terminated)
};
}
let last = &status["lastState"]["terminated"];
if status["state"]["waiting"].is_object() && last.is_object() && last["exitCode"] != 0 {
return refused(last);
}
Gate::Pending
}
/// The report as text. /// The report as text.
fn render(steps: &[Step]) -> String { fn render(steps: &[Step]) -> String {
let mut out = String::new(); let mut out = String::new();
@ -651,13 +535,10 @@ pub fn run(args: MigrateArgs) -> Result<()> {
Ok(()) Ok(())
} }
Some(MigrateVerb::External(words)) => bail!( Some(MigrateVerb::External(words)) => bail!(
"`swarmctl migrate {}` is not available yet; only `swarmctl migrate status` is", "`swarmctl migrate {}` is not a verb; only `swarmctl migrate status` exists",
words.join(" ") words.join(" ")
), ),
None => bail!( None => bail!("`swarmctl migrate` needs a verb: only `swarmctl migrate status` exists"),
"`swarmctl migrate` does not move services yet: only `swarmctl migrate status` is \
available"
),
} }
} }
@ -681,28 +562,21 @@ mod tests {
use super::*; use super::*;
use crate::tests::write_executable; use crate::tests::write_executable;
fn service(option: &str, runtime: Runtime, units: &[&str], state: bool) -> Service { fn service(option: &str, runtime: Runtime, units: &[&str]) -> Service {
Service { Service {
option: format!("services.hyperhive.deploy.{option}.runtime"), option: format!("services.hyperhive.deploy.{option}.runtime"),
runtime, runtime,
host_units: units.iter().map(|u| (*u).to_owned()).collect(), host_units: units.iter().map(|u| (*u).to_owned()).collect(),
state: state.then(|| State {
claim: "x-state".into(),
mount: "/var/lib/x".into(),
host_path: Some("/var/lib/x".into()),
excludes: vec![],
}),
} }
} }
fn pod(service: &str, created: &str, ready: bool, gate: Gate) -> Pod { fn pod(service: &str, created: &str, ready: bool) -> Pod {
Pod { Pod {
name: format!("{service}-{created}"), name: format!("{service}-{created}"),
service: service.into(), service: service.into(),
created: created.into(), created: created.into(),
phase: "Running".into(), phase: "Running".into(),
ready, ready,
gate,
} }
} }
@ -737,11 +611,11 @@ mod tests {
const CI: &str = "swarm-ci-metrics"; const CI: &str = "swarm-ci-metrics";
const CI_UNITS: [&str; 2] = ["swarm-ci-metrics.timer", "swarm-ci-metrics.service"]; const CI_UNITS: [&str; 2] = ["swarm-ci-metrics.timer", "swarm-ci-metrics.service"];
/// One stateful service, ci-metrics, with its two host units and the /// One service, ci-metrics, with its two host units and the given
/// given runtime, host-unit state and pods. /// runtime, host-unit state and pods.
fn ci(runtime: Runtime, unit_state: &str, pods: Vec<Pod>) -> Vec<Step> { fn ci(runtime: Runtime, unit_state: &str, pods: Vec<Pod>) -> Vec<Step> {
classify(&observed( classify(&observed(
vec![(CI, service("ci-metrics", runtime, &CI_UNITS, true))], vec![(CI, service("ci-metrics", runtime, &CI_UNITS))],
&[ &[
("swarm-ci-metrics.timer", unit_state), ("swarm-ci-metrics.timer", unit_state),
("swarm-ci-metrics.service", "inactive"), ("swarm-ci-metrics.service", "inactive"),
@ -777,10 +651,6 @@ mod tests {
.detail() .detail()
.contains("services.hyperhive.deploy.ci-metrics.runtime") .contains("services.hyperhive.deploy.ci-metrics.runtime")
); );
assert!(matches!(
step(&steps, CI, Kind::Copy),
Some(Status::NotDone(_))
));
assert!(matches!( assert!(matches!(
step(&steps, CI, Kind::Ready), step(&steps, CI, Kind::Ready),
Some(Status::NotDone(_)) Some(Status::NotDone(_))
@ -789,102 +659,36 @@ mod tests {
} }
#[test] #[test]
fn host_unit_still_active_after_the_switch_blocks_the_copy() { fn host_unit_still_active_after_the_switch_is_not_a_finished_switch() {
let steps = ci(Runtime::K8s, "active", vec![]); let steps = ci(Runtime::K8s, "active", vec![]);
assert!(detail(step(&steps, CI, Kind::Runtime)).contains("still active")); let runtime = step(&steps, CI, Kind::Runtime).unwrap();
let copy = step(&steps, CI, Kind::Copy).unwrap(); assert!(matches!(runtime, Status::NotDone(_)), "{runtime:?}");
assert!(matches!(copy, Status::Blocked(_)), "{copy:?}"); assert!(runtime.detail().contains("still active"));
// Control: stopped, the same observation is not blocked. // Control: stopped, the same observation is done.
let steps = ci(Runtime::K8s, "inactive", vec![]); let steps = ci(Runtime::K8s, "inactive", vec![]);
assert!(matches!( assert!(matches!(
step(&steps, CI, Kind::Runtime), step(&steps, CI, Kind::Runtime),
Some(Status::Done(_)) Some(Status::Done(_))
)); ));
assert!(!matches!(
step(&steps, CI, Kind::Copy),
Some(Status::Blocked(_))
));
} }
#[test] #[test]
fn a_unit_that_is_activating_counts_as_running() { fn a_unit_that_is_activating_counts_as_running() {
let steps = ci(Runtime::K8s, "activating", vec![]); let steps = ci(Runtime::K8s, "activating", vec![]);
assert!(matches!( let runtime = step(&steps, CI, Kind::Runtime).unwrap();
step(&steps, CI, Kind::Copy), assert!(matches!(runtime, Status::NotDone(_)), "{runtime:?}");
Some(Status::Blocked(_)) assert!(runtime.detail().contains("still activating"));
));
} }
#[test] #[test]
fn rebuilt_without_a_pod_waits_for_the_workload() { fn rebuilt_without_a_pod_waits_for_the_workload() {
let steps = ci(Runtime::K8s, "inactive", vec![]); let steps = ci(Runtime::K8s, "inactive", vec![]);
assert!(detail(step(&steps, CI, Kind::Copy)).contains("no pod yet"));
assert_eq!(detail(step(&steps, CI, Kind::Ready)), "no pod"); assert_eq!(detail(step(&steps, CI, Kind::Ready)), "no pod");
} }
#[test] #[test]
fn gate_refused_on_an_empty_volume_waits_for_the_copy() { fn a_pod_that_is_not_ready_is_the_next_step() {
let refusal = "swarm-ci-metrics: state volume has not been migrated: run `swarmctl migrate swarm-ci-metrics`"; let steps = ci(Runtime::K8s, "inactive", vec![pod(CI, "1", false)]);
let steps = ci(
Runtime::K8s,
"inactive",
vec![pod(CI, "1", false, Gate::Refused(refusal.into()))],
);
let copy = step(&steps, CI, Kind::Copy).unwrap();
assert!(matches!(copy, Status::NotDone(_)));
assert!(
copy.detail().starts_with("waiting for the copy"),
"{copy:?}"
);
assert!(copy.detail().contains(refusal));
assert!(detail(step(&steps, CI, Kind::Ready)).contains("start gate"));
}
#[test]
fn gate_refused_on_files_without_a_marker_reports_a_cut_off_copy() {
let refusal = "swarm-ci-metrics: state volume has not been migrated: it holds files and no .hyperhive-migrated marker, so a copy may have been cut off";
let steps = ci(
Runtime::K8s,
"inactive",
vec![pod(CI, "1", false, Gate::Refused(refusal.into()))],
);
let copy = detail(step(&steps, CI, Kind::Copy));
assert!(
copy.starts_with("the volume holds files and no marker"),
"{copy}"
);
}
#[test]
fn gate_that_has_not_answered_and_gate_absent() {
let steps = ci(
Runtime::K8s,
"inactive",
vec![pod(CI, "1", false, Gate::Pending)],
);
assert!(detail(step(&steps, CI, Kind::Copy)).contains("not answered"));
let steps = ci(
Runtime::K8s,
"inactive",
vec![pod(CI, "1", false, Gate::Absent)],
);
assert!(matches!(
step(&steps, CI, Kind::Copy),
Some(Status::Unknown(_))
));
}
#[test]
fn marker_present_but_pod_not_ready() {
let steps = ci(
Runtime::K8s,
"inactive",
vec![pod(CI, "1", false, Gate::Passed)],
);
assert!(matches!(
step(&steps, CI, Kind::Copy),
Some(Status::Done(_))
));
let ready = step(&steps, CI, Kind::Ready).unwrap(); let ready = step(&steps, CI, Kind::Ready).unwrap();
assert!(matches!(ready, Status::NotDone(_))); assert!(matches!(ready, Status::NotDone(_)));
assert!(ready.detail().contains("not Ready")); assert!(ready.detail().contains("not Ready"));
@ -892,12 +696,8 @@ mod tests {
} }
#[test] #[test]
fn marker_present_and_ready_is_everything_done() { fn a_ready_pod_with_the_host_units_stopped_is_everything_done() {
let steps = ci( let steps = ci(Runtime::K8s, "inactive", vec![pod(CI, "1", true)]);
Runtime::K8s,
"inactive",
vec![pod(CI, "1", true, Gate::Passed)],
);
assert!( assert!(
steps.iter().all(|s| matches!(s.status, Status::Done(_))), steps.iter().all(|s| matches!(s.status, Status::Done(_))),
"{steps:?}" "{steps:?}"
@ -908,7 +708,7 @@ mod tests {
#[test] #[test]
fn a_completed_cronjob_pod_is_ready() { fn a_completed_cronjob_pod_is_ready() {
let mut done = pod(CI, "1", false, Gate::Passed); let mut done = pod(CI, "1", false);
done.phase = "Succeeded".into(); done.phase = "Succeeded".into();
let steps = ci(Runtime::K8s, "inactive", vec![done]); let steps = ci(Runtime::K8s, "inactive", vec![done]);
assert!(matches!( assert!(matches!(
@ -919,22 +719,18 @@ mod tests {
#[test] #[test]
fn the_newest_pod_decides() { fn the_newest_pod_decides() {
let old = pod(CI, "1", true, Gate::Passed); let old = pod(CI, "1", true);
let new = pod(CI, "2", false, Gate::Refused("refused".into())); let new = pod(CI, "2", false);
let steps = ci(Runtime::K8s, "inactive", vec![old, new]); let steps = ci(Runtime::K8s, "inactive", vec![old, new]);
assert!(matches!( assert!(matches!(
step(&steps, CI, Kind::Copy), step(&steps, CI, Kind::Ready),
Some(Status::NotDone(_)) Some(Status::NotDone(_))
)); ));
} }
#[test] #[test]
fn a_pod_for_a_service_still_on_the_host_is_the_wrong_runtime() { fn a_pod_for_a_service_still_on_the_host_is_the_wrong_runtime() {
let steps = ci( let steps = ci(Runtime::Host, "active", vec![pod(CI, "1", false)]);
Runtime::Host,
"active",
vec![pod(CI, "1", false, Gate::Pending)],
);
let runtime = step(&steps, CI, Kind::Runtime).unwrap(); let runtime = step(&steps, CI, Kind::Runtime).unwrap();
assert!(runtime.detail().starts_with("wrong runtime"), "{runtime:?}"); assert!(runtime.detail().starts_with("wrong runtime"), "{runtime:?}");
// Control: with no pod the same observation is the plain host case. // Control: with no pod the same observation is the plain host case.
@ -942,30 +738,6 @@ mod tests {
assert!(!detail(step(&steps, CI, Kind::Runtime)).contains("wrong runtime")); assert!(!detail(step(&steps, CI, Kind::Runtime)).contains("wrong runtime"));
} }
#[test]
fn a_stateless_service_has_no_copy_step() {
let router = "swarm-notify-router";
let steps = classify(&observed(
vec![(
router,
service(
"notify-router",
Runtime::K8s,
&["container@swarm-notify-router.service"],
false,
),
)],
&[("container@swarm-notify-router.service", "inactive")],
vec![pod(router, "1", true, Gate::Absent)],
));
assert!(step(&steps, router, Kind::Copy).is_none());
assert!(matches!(
step(&steps, router, Kind::Ready),
Some(Status::Done(_))
));
assert!(next(&steps).is_none());
}
#[test] #[test]
fn moving_ahead_of_an_earlier_service_is_out_of_order() { fn moving_ahead_of_an_earlier_service_is_out_of_order() {
let router = "swarm-notify-router"; let router = "swarm-notify-router";
@ -975,16 +747,16 @@ mod tests {
vec![ vec![
( (
router, router,
service("notify-router", router_runtime, &[router_unit], false), service("notify-router", router_runtime, &[router_unit]),
), ),
(CI, service("ci-metrics", Runtime::K8s, &CI_UNITS, true)), (CI, service("ci-metrics", Runtime::K8s, &CI_UNITS)),
], ],
&[ &[
(router_unit, router_unit_state), (router_unit, router_unit_state),
("swarm-ci-metrics.timer", "inactive"), ("swarm-ci-metrics.timer", "inactive"),
("swarm-ci-metrics.service", "inactive"), ("swarm-ci-metrics.service", "inactive"),
], ],
[router_pods, vec![pod(CI, "1", false, Gate::Pending)]].concat(), [router_pods, vec![pod(CI, "1", false)]].concat(),
)) ))
}; };
let steps = build(Runtime::Host, "active", vec![]); let steps = build(Runtime::Host, "active", vec![]);
@ -993,11 +765,7 @@ mod tests {
assert!(order.detail().contains(router), "{order:?}"); assert!(order.detail().contains(router), "{order:?}");
assert!(step(&steps, router, Kind::Order).is_none()); assert!(step(&steps, router, Kind::Order).is_none());
// Control: with the router finished, ci-metrics is in order. // Control: with the router finished, ci-metrics is in order.
let steps = build( let steps = build(Runtime::K8s, "inactive", vec![pod(router, "1", true)]);
Runtime::K8s,
"inactive",
vec![pod(router, "1", true, Gate::Absent)],
);
assert!(step(&steps, CI, Kind::Order).is_none()); assert!(step(&steps, CI, Kind::Order).is_none());
} }
@ -1008,9 +776,9 @@ mod tests {
vec![ vec![
( (
router, router,
service("notify-router", Runtime::Host, &["a.service"], false), service("notify-router", Runtime::Host, &["a.service"]),
), ),
(CI, service("ci-metrics", Runtime::Host, &CI_UNITS, true)), (CI, service("ci-metrics", Runtime::Host, &CI_UNITS)),
], ],
&[ &[
("a.service", "active"), ("a.service", "active"),
@ -1036,7 +804,7 @@ mod tests {
let steps = classify(&observed( let steps = classify(&observed(
services services
.iter() .iter()
.map(|n| (*n, service(n, Runtime::Host, &["u.service"], false))) .map(|n| (*n, service(n, Runtime::Host, &["u.service"])))
.collect(), .collect(),
&[("u.service", "active")], &[("u.service", "active")],
vec![], vec![],
@ -1062,7 +830,7 @@ mod tests {
#[test] #[test]
fn failed_checks_are_unknown_not_guessed() { fn failed_checks_are_unknown_not_guessed() {
let mut o = observed( let mut o = observed(
vec![(CI, service("ci-metrics", Runtime::K8s, &CI_UNITS, true))], vec![(CI, service("ci-metrics", Runtime::K8s, &CI_UNITS))],
&[ &[
("swarm-ci-metrics.timer", "inactive"), ("swarm-ci-metrics.timer", "inactive"),
("swarm-ci-metrics.service", "inactive"), ("swarm-ci-metrics.service", "inactive"),
@ -1071,16 +839,12 @@ mod tests {
); );
o.pods = Err("kubectl get pods failed (exit status: 1): refused".into()); o.pods = Err("kubectl get pods failed (exit status: 1): refused".into());
let steps = classify(&o); let steps = classify(&o);
assert!(matches!(
step(&steps, CI, Kind::Copy),
Some(Status::Unknown(_))
));
assert!(matches!( assert!(matches!(
step(&steps, CI, Kind::Ready), step(&steps, CI, Kind::Ready),
Some(Status::Unknown(_)) Some(Status::Unknown(_))
)); ));
let mut o = observed( let mut o = observed(
vec![(CI, service("ci-metrics", Runtime::K8s, &CI_UNITS, true))], vec![(CI, service("ci-metrics", Runtime::K8s, &CI_UNITS))],
&[("swarm-ci-metrics.service", "inactive")], &[("swarm-ci-metrics.service", "inactive")],
vec![], vec![],
); );
@ -1093,23 +857,13 @@ mod tests {
)); ));
} }
/// The shape of `kubectl get pods --output json` for a pod behind a start /// The shape of `kubectl get pods --output json` for one pod, written from
/// gate, written from the API's schema. /// the API's schema.
fn pod_json(name: &str, gate_state: &str, ready: &str, with_gate: bool) -> String { fn pod_json(name: &str, ready: &str) -> String {
let init_spec = if with_gate {
r#","initContainers":[{"name":"state-gate"}]"#
} else {
""
};
let init_status = if with_gate {
format!(r#","initContainerStatuses":[{{"name":"state-gate",{gate_state}}}]"#)
} else {
String::new()
};
format!( format!(
r#"{{"metadata":{{"name":"{name}","creationTimestamp":"2026-11-22T20:00:00Z","labels":{{"app.kubernetes.io/name":"swarm-ci-metrics","app.kubernetes.io/part-of":"hyperhive"}}}}, r#"{{"metadata":{{"name":"{name}","creationTimestamp":"2026-11-22T20:00:00Z","labels":{{"app.kubernetes.io/name":"swarm-ci-metrics","app.kubernetes.io/part-of":"hyperhive"}}}},
"spec":{{"containers":[{{"name":"swarm-ci-metrics"}}]{init_spec}}}, "spec":{{"containers":[{{"name":"swarm-ci-metrics"}}]}},
"status":{{"phase":"Pending","conditions":[{{"type":"Ready","status":"{ready}"}}]{init_status}}}}}"# "status":{{"phase":"Pending","conditions":[{{"type":"Ready","status":"{ready}"}}]}}}}"#
) )
} }
@ -1120,48 +874,14 @@ mod tests {
) )
} }
const GATE_PASSED: &str = r#""state":{"terminated":{"exitCode":0,"reason":"Completed"}}"#;
const GATE_REFUSED_BACKOFF: &str = r#""state":{"waiting":{"reason":"PodInitializing"}},"lastState":{"terminated":{"exitCode":1,"reason":"Error","message":"swarm-ci-metrics: state volume has not been migrated: run `swarmctl migrate swarm-ci-metrics`\n"}}"#;
const GATE_REFUSED_NOW: &str =
r#""state":{"terminated":{"exitCode":1,"reason":"Error","message":"refused now"}}"#;
const GATE_RUNNING: &str = r#""state":{"running":{}}"#;
#[test] #[test]
fn parses_a_gate_that_passed() { fn parses_a_pod_with_its_service_and_readiness() {
let pods = parse_pods(&list(&[pod_json("p1", GATE_PASSED, "True", true)])).unwrap(); let pods = parse_pods(&list(&[pod_json("p1", "True")])).unwrap();
assert_eq!(pods.len(), 1); assert_eq!(pods.len(), 1);
assert_eq!(pods[0].service, "swarm-ci-metrics"); assert_eq!(pods[0].service, "swarm-ci-metrics");
assert_eq!(pods[0].gate, Gate::Passed);
assert!(pods[0].ready); assert!(pods[0].ready);
} let pods = parse_pods(&list(&[pod_json("p1", "False")])).unwrap();
#[test]
fn parses_a_gate_that_refused_with_its_message() {
let pods = parse_pods(&list(&[pod_json(
"p1",
GATE_REFUSED_BACKOFF,
"False",
true,
)]))
.unwrap();
assert_eq!(
pods[0].gate,
Gate::Refused(
"swarm-ci-metrics: state volume has not been migrated: run `swarmctl migrate swarm-ci-metrics`"
.into()
)
);
assert!(!pods[0].ready); assert!(!pods[0].ready);
let pods = parse_pods(&list(&[pod_json("p1", GATE_REFUSED_NOW, "False", true)])).unwrap();
assert_eq!(pods[0].gate, Gate::Refused("refused now".into()));
}
#[test]
fn parses_a_running_gate_and_a_pod_without_one() {
let pods = parse_pods(&list(&[pod_json("p1", GATE_RUNNING, "False", true)])).unwrap();
assert_eq!(pods[0].gate, Gate::Pending);
let pods = parse_pods(&list(&[pod_json("p1", "", "True", false)])).unwrap();
assert_eq!(pods[0].gate, Gate::Absent);
} }
#[test] #[test]
@ -1210,12 +930,6 @@ esac
"option": "services.hyperhive.deploy.ci-metrics.runtime", "option": "services.hyperhive.deploy.ci-metrics.runtime",
"runtime": "k8s", "runtime": "k8s",
"hostUnits": CI_UNITS, "hostUnits": CI_UNITS,
"state": {
"claim": "swarm-ci-metrics-state",
"mount": "/var/lib/swarm-ci-metrics",
"hostPath": "/var/lib/private/swarm-ci-metrics",
"excludes": [],
},
}, },
}, },
}); });
@ -1248,10 +962,7 @@ esac
#[test] #[test]
fn only_reads_and_only_in_the_swarms_namespace() { fn only_reads_and_only_in_the_swarms_namespace() {
let fx = Fixture::new( let fx = Fixture::new("readonly", &list(&[pod_json("p1", "True")]));
"readonly",
&list(&[pod_json("p1", GATE_PASSED, "True", true)]),
);
let mut out = Vec::new(); let mut out = Vec::new();
assert!(report(&fx.tools, false, &mut out).unwrap()); assert!(report(&fx.tools, false, &mut out).unwrap());
let log = fx.log(); let log = fx.log();
@ -1282,9 +993,8 @@ esac
] ]
); );
// Control: the log does record calls, and the report read the stubs' // Control: the log does record calls, and the report read the stubs'
// answers (a ready pod behind a passed gate). // answers (a ready pod).
let text = String::from_utf8(out).unwrap(); let text = String::from_utf8(out).unwrap();
assert!(text.contains("marker present"), "{text}");
assert!( assert!(
text.contains("every service has moved and is Ready"), text.contains("every service has moved and is Ready"),
"{text}" "{text}"
@ -1315,28 +1025,18 @@ esac
#[test] #[test]
fn json_report_carries_services_steps_and_next() { fn json_report_carries_services_steps_and_next() {
let fx = Fixture::new( let fx = Fixture::new("json", &list(&[pod_json("p1", "False")]));
"json",
&list(&[pod_json("p1", GATE_REFUSED_BACKOFF, "False", true)]),
);
let mut out = Vec::new(); let mut out = Vec::new();
report(&fx.tools, true, &mut out).unwrap(); report(&fx.tools, true, &mut out).unwrap();
let v: Value = serde_json::from_slice(&out).unwrap(); let v: Value = serde_json::from_slice(&out).unwrap();
assert_eq!(v["namespace"], "hyperhive"); assert_eq!(v["namespace"], "hyperhive");
assert_eq!( assert_eq!(v["services"][CI]["runtime"], "k8s");
v["services"][CI]["state"]["claim"], assert!(v["services"][CI].get("state").is_none());
"swarm-ci-metrics-state"
);
let steps = v["steps"].as_array().unwrap(); let steps = v["steps"].as_array().unwrap();
let copy = steps.iter().find(|s| s["step"] == "copy").unwrap(); let ready = steps.iter().find(|s| s["step"] == "ready").unwrap();
assert_eq!(copy["status"], "not_done"); assert_eq!(ready["status"], "not_done");
assert!( assert!(ready["detail"].as_str().unwrap().contains("not Ready"));
copy["detail"] assert_eq!(v["next"]["step"], "ready");
.as_str()
.unwrap()
.contains("swarmctl migrate")
);
assert_eq!(v["next"]["step"], "copy");
} }
#[test] #[test]