Watch
0
0
Fork
You've already forked hyperhive
0

k8s: stt and ci-metrics start without a state gate

This commit is contained in:
atlas 2026-11-23 02:46:31 +01:00 • committed by maia
commit a793df9708
11 changed files with 296 additions and 309 deletions

View file

@ -23,7 +23,7 @@ A service gets manifests on the host whose configuration deploys it:
| ------------------------- | ---------- | ------------------------------------------------------------------------------------------------ |
| `swarm-controller` | Deployment | ServiceAccount, PersistentVolumeClaim `swarm-controller-state`, ConfigMap `swarm-controller-etc` |
| `swarm-notify-router` | Deployment | ServiceAccount |
| `swarm-stt` | Deployment | ServiceAccount, PersistentVolumeClaim `swarm-stt-state` |
| `swarm-stt` | Deployment | ServiceAccount |
| `swarm-review-classifier` | Deployment | ServiceAccount |
| `swarm-claude-login` | Deployment | ServiceAccount |
| `swarm-ci-metrics` | CronJob | ServiceAccount, PersistentVolumeClaim `swarm-ci-metrics-state` |

View file

@ -81,12 +81,12 @@ endpoints the [services page](../../2-handbook/swarm/services.md) lists; the
[readiness page](../swarm/readiness.md) has their mechanics.
| service | state | what moves | 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-review-classifier` | none on disk; its runs and settings live in buckets the controller owns | nothing | `/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 | nothing; the pod starts with an empty cache, once the gate has its marker | `/readyz`: queue connected | same |
| `swarm-ci-metrics` | `cursor.json` in the state directory; losing it re-pushes every run | the state directory, to a PVC | the CronJob's next Job completes | `runtime = "k8s"`, rebuild; the timer goes, the CronJob runs. Rollback copies the PVC back |
| `swarm-stt` | the transcript cache, entries live 24 h; the pod keeps it in an `emptyDir` | nothing; the pod starts with an empty cache | `/readyz`: queue connected | same |
| `swarm-ci-metrics` | `cursor.json` in the state directory; losing it re-pushes every run | nothing; the pod starts on an empty PVC with no gate, and its first pass re-pushes every run as the same points | the CronJob's next Job completes | `runtime = "k8s"`, rebuild; the timer goes, the CronJob runs; back with `runtime = "host"` |
| NATS + `swarm-nats-auth` | JetStream's `store_dir`: the swarm's desired state, operator profiles, schedules and run records. `swarm-nats-auth` keeps nothing | the whole `store_dir`, to a PVC; the cut-over rebuild stops NATS, so the copy reads a quiescent tree | nats-server's `/healthz?js-enabled-only=true` and `swarm-nats-auth`'s `/readyz`; Ready when both pass | `runtime = "k8s"`, rebuild; the pod takes the same host port, so hives keep their URL. Rollback copies the PVC back |
| `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 |
@ -108,18 +108,16 @@ Two facts the table rests on:
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
name, with nothing to copy.
2. **`swarm-review-classifier`, `swarm-claude-login`, `swarm-stt`**, in one
rebuild or one at a time. No state, same pattern as step 1.
3. **`swarm-ci-metrics`.** The first copy, of one small file. It exercises
the snapshot, the gate, the copy and the rollback on state whose loss
costs a re-push, not data.
4. **NATS with `swarm-nats-auth`.** The riskiest move: the largest copy, every
2. **`swarm-review-classifier`, `swarm-claude-login`, `swarm-stt`,
`swarm-ci-metrics`**, in one rebuild or one at a time. Nothing to copy, same
pattern as step 1: the pods start with no gate on an empty volume.
3. **NATS with `swarm-nats-auth`.** The riskiest move: the largest copy, every
hive and agent disconnects, and the data is the swarm's desired state.
The copy path has run once by then. `swarm-nats-auth` moves in the same
pod, because it answers the auth callout on every connect and dials the
It's the first copy `swarmctl migrate` makes. `swarm-nats-auth` moves in the
same pod, because it answers the auth callout on every connect and dials the
server by name, which the pod's host aliases map to its loopback.
5. **`swarm-controller` last.**
- It's the operator's view of the swarm. Kept on the host through step 4,
4. **`swarm-controller` last.**
- It's the operator's view of the swarm. Kept on the host through step 3,
it reports from an unchanged place whether the hives reconnected after
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
@ -214,9 +212,7 @@ 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. A
service with state that moves nothing, `swarm-stt`, still needs the marker:
`swarmctl migrate` writes one that names no source.
(`{"fresh": true, "at": <time>}`), and `swarmctl migrate` isn't needed.
## Downtime and what hives see
@ -229,7 +225,7 @@ pod passing step 4.
| `swarm-review-classifier` | 2 min | A try-out request in the gap gets no answer, and its caller reports a failure |
| `swarm-claude-login` | 2 min | A login in progress fails; the operator starts it again |
| `swarm-stt` | 2 min | Transcription requests fail during the gap; the cache starts empty |
| `swarm-ci-metrics` | one 5-minute period | One pass runs late; the copied cursor means no run gets pushed twice |
| `swarm-ci-metrics` | one 5-minute period | One pass runs late; the first pass on the pod's empty cursor pushes every run again |
| NATS + `swarm-nats-auth` | 10 min; the copy takes most of it | below |
| `swarm-controller` | 5 min | The swarm UI and API answer with gateway errors. Forge webhook deliveries in the gap fail at the forge. After the cut-over, `swarmctl` on the host needs `--swarm` |

View file

@ -32,9 +32,9 @@ cluster follow the same pattern.
the iptables firewall (`networking.nftables.enable` off).
[The queue](#the-queue) has its own section.
- `services.hyperhive.deploy.<service>.k8s.freshState` (default `false`) for
each service whose pod keeps state in a volume: `swarm-controller`, `stt`,
`ci-metrics` and `nats`. It says whether the pod may start on an empty volume
([State](#state)).
each service whose pod keeps state worth moving in a volume:
`swarm-controller` and `nats`. It says whether the pod may start on an empty
volume ([State](#state)).
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
@ -108,21 +108,22 @@ claims stay; `swarmctl migrate finish` deletes them.
## State
A pod with a state volume starts only on migrated state. Its first init
container, `state-gate`, mounts the volume and exits 0 when the volume holds
`.hyperhive-migrated`. A volume with no entries besides `lost+found` gets the
marker (`{"fresh": true, "at": <time>}`) and passes where the service's
`k8s.freshState` is on. Every other volume fails the gate, including one that
holds files and no marker, since a copy may have stopped half way. The pod stays
in `Init:Error`, and the container's termination message and log carry one
line that names the service, the `swarmctl migrate` command and the option to
set for a fresh install. Nothing of the service runs on the empty volume. The
gate doesn't decide which 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.
A pod with a state volume that holds state worth moving (`swarm-controller` and
NATS) starts only on migrated state. Its first init container, `state-gate`,
mounts the volume and exits 0 when the volume holds `.hyperhive-migrated`. A
volume with no entries besides `lost+found` gets the marker (`{"fresh": true,
"at": <time>}`) and passes where the service's `k8s.freshState` is on. Every
other volume fails the gate, including one that holds files and no marker, since
a copy may have stopped half way. The pod stays in `Init:Error`, and the
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, and `swarm-stt` and
`swarm-ci-metrics` have a volume that the gate doesn't check.
`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
@ -131,23 +132,21 @@ consumer's position.
`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
the PersistentVolumeClaim `swarm-stt-state`, mounted at the same path. A switch
copies neither: each side starts with the cache it last had, empty the first
time (the pod's gate wants the marker or `deploy.stt.k8s.freshState` for
that), and transcribes a memo that only the other side cached. The claim stays
after a switch back, as every claim does, and the container's directory stays
too. The whisper model isn't state: the pod's image holds it, from the same
store path the container reads, and the volume doesn't.
an `emptyDir` at the same path, so the pod has no claim and no gate and starts
on an empty cache on every start of the pod. A switch copies nothing, and the
service transcribes a memo that only the other side cached. The whisper model
isn't state: the pod's image holds it, from the same store path the container
reads.
`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 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 neither, so each side keeps the cursor it last had, and
the first pass on a side with none (the pod's gate wants the marker or
`deploy.ci-metrics.k8s.freshState` for that) pushes every run again, as
the same points. A second Job on the same side finds the cursor and pushes
nothing. The claim stays after a switch back, and so does the host's directory.
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
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
with none pushes every run again, as the same points. The pod starts on the
empty claim with no gate. A second Job on the same side finds the cursor and
pushes nothing. The claim stays after a switch back, and so does the host's
directory.
## The controller

View file

@ -85,6 +85,14 @@ let
in
{
imports = [
(lib.mkRemovedOptionModule [ "services" "hyperhive" "deploy" "stt" "k8s" "freshState" ] ''
The pod keeps its transcript cache in an emptyDir, so it starts on any
node with no state to migrate. Remove this definition.
'')
(lib.mkRemovedOptionModule [ "services" "hyperhive" "deploy" "ci-metrics" "k8s" "freshState" ] ''
The pod starts on an empty volume without a gate: the cursor it loses is
one backfill pass. Remove this definition.
'')
(lib.mkRemovedOptionModule [ "services" "hyperhive" "swarm" "victorialogs" "port" ] ''
VictoriaLogs listens on a unix socket in a network namespace of its own,
and the gateway reaches it there, so it binds no host port. Remove this

View file

@ -31,9 +31,8 @@ let
controllerStateDir = "/var/lib/swarm-controller";
# `option` is the service's name under `services.hyperhive.deploy`. `state`
# is null for a service with no state volume. `hostPath` is null where the
# copy has no source: the speech-to-text cache is not moved, and the pod
# starts with an empty one.
# is null for a service whose pod keeps nothing worth moving: no volume, an
# `emptyDir`, or a volume that starts empty with no gate.
#
# The claim is `<service>-state`, as ./render.nix and ../swarm-nats.nix name
# it.
@ -65,11 +64,7 @@ let
};
swarm-stt = {
option = "stt";
state = {
mount = stateMount deployCfg.stt.unit;
hostPath = null;
excludes = [ ];
};
state = null;
};
swarm-review-classifier = {
option = "review-classifier";
@ -81,13 +76,7 @@ let
};
swarm-ci-metrics = {
option = "ci-metrics";
state = {
mount = stateMount deployCfg.ci-metrics.unit;
# A DynamicUser unit's state directory is under `private`, behind a
# symlink at the path the unit names.
hostPath = "/var/lib/private/swarm-ci-metrics";
excludes = [ ];
};
state = null;
};
};

View file

@ -152,9 +152,11 @@ let
# the paths the unit names that hold one to theirs. `listener`, where a
# service has one, is the TCP port the pod publishes on the node
# (`hostAddress`) and the directory its init container writes the leaf to.
# `fresh` (`freshOf`) is set on every service whose pod gets a state volume:
# the volume's first init container, the state gate, refuses to start the pod
# on one that holds no migrated state unless the install is fresh.
# `fresh` (`freshOf`) is set on a service whose state is worth moving: the
# volume's first init container, the state gate, refuses to start the pod on
# one that holds no migrated state unless the install is fresh. A service
# without it starts on whatever volume it gets, and one with
# `ephemeralState` gets an `emptyDir` in place of a claim.
# `switch` is null for a service that always runs on the host, and for one
# with a `runtime` option names the option's value and the host unit or units
# that run the service when it is `"host"`. `otlp` is where the pod pushes
@ -238,7 +240,7 @@ let
etcFiles = [ ];
publicCredentials.stt-bao-server-ca = baoServerCaKey;
otlp = "hive";
fresh = freshOf "stt" deployCfg.stt;
ephemeralState = true;
switch = {
inherit (deployCfg.stt) runtime;
hostUnit = "container@swarm-stt.service";
@ -279,7 +281,6 @@ let
etcFiles = [ ];
publicCredentials."bao-ca.pem" = baoServerCaKey;
otlp = "own";
fresh = freshOf "ci-metrics" deployCfg.ci-metrics;
# The timer and the service both: the prune unit holds back either, and a
# service started by hand cannot run beside the CronJob.
switch = {
@ -445,6 +446,7 @@ let
runtimeDir = if sc ? RuntimeDirectory then "/run/${sc.RuntimeDirectory}" else null;
stateDir = if sc ? StateDirectory then "/var/lib/${sc.StateDirectory}" else null;
ephemeral = svc.ephemeralState or false;
# PATH holds only NixOS's default tools (checked below), which the image
# does not carry. `%d` is systemd's specifier for the credential
@ -622,10 +624,14 @@ let
name = "runtime";
emptyDir = { };
}
++ lib.optional (stateDir != null) {
++ lib.optional (stateDir != null) (
{
name = "state";
persistentVolumeClaim.claimName = "${name}-state";
}
// (
if ephemeral then { emptyDir = { }; } else { persistentVolumeClaim.claimName = "${name}-state"; }
)
)
++ lib.optional (svc.etcFiles != [ ]) {
name = "etc";
configMap.name = "${name}-etc";
@ -772,9 +778,13 @@ let
package = leafImagePackage;
bin = leafIssueBin;
};
# The volume that holds the service's state, and where it is mounted. A
# pod that makes its own volume names it in `state`.
# The volume the state gate checks, and where it is mounted: that of a
# service with a `fresh` option, none for the rest. A pod that makes its
# own volume names it in `state`.
stateVolume =
if !(svc ? fresh) then
null
else
extra.state or (
if stateDir != null then
{
@ -974,7 +984,7 @@ let
automountServiceAccountToken = false;
};
}
// lib.optionalAttrs (stateDir != null) {
// lib.optionalAttrs (stateDir != null && !ephemeral) {
"${name}/persistentvolumeclaim" = {
apiVersion = "v1";
kind = "PersistentVolumeClaim";
@ -1000,8 +1010,6 @@ let
fail name "the unit names no OTLP endpoint of its own, which the pod would push to"
else if svc.healthEnv != null && unitEnv ? ${svc.healthEnv} then
fail name "the unit already sets ${svc.healthEnv}"
else if stateVolume != null && !(svc ? fresh) then
fail name "the pod has a state volume and the service names no `fresh` option for its state gate"
else if lib.head execWords != entrypoint then
fail name "ExecStart is not ${entrypoint} with plain arguments"
else if lib.any (w: lib.hasInfix "\"" w) execWords then

View file

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

View file

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

View file

@ -116,8 +116,6 @@ let
lib.recursiveUpdate config {
services.hyperhive.deploy = {
nats.k8s.freshState = true;
stt.k8s.freshState = true;
ci-metrics.k8s.freshState = true;
swarm-controller.k8s.freshState = true;
};
};
@ -902,7 +900,6 @@ let
&&
lib.sort lib.lessThan (map (o: o.kind) onCluster.services.k3s.manifests.swarm-stt.content) == [
"Deployment"
"PersistentVolumeClaim"
"ServiceAccount"
]
&&
@ -1124,23 +1121,26 @@ let
}));
}
{
name = "the speech-to-text pod has probes on its health listener, keeps its cache in a volume, mounts no Secret, and runs as every pod does";
name = "the speech-to-text pod has probes on its health listener, keeps its cache in an emptyDir with no claim, mounts no Secret, and runs as every pod does";
ok =
let
c = container "swarm-stt";
spec = podSpec "swarm-stt";
pvc = objects."swarm-stt/persistentvolumeclaim";
cred = lib.findFirst (v: v.name == "credentials") null spec.volumes;
in
(lib.head c.ports).containerPort == 8080
&& c.readinessProbe.httpGet.path == "/readyz"
&& c.livenessProbe.httpGet.path == "/healthz"
&& pvc.metadata.name == "swarm-stt-state"
&& pvc.spec.resources.requests.storage == "1Gi"
&& lib.any (m: m.name == "state" && m.mountPath == "/var/lib/swarm-stt") c.volumeMounts
# The cache needs no claim, and is no state to gate. The poller beside
# it, whose cursor is kept, is the control that a claim renders.
&&
(lib.findFirst (v: v.name == "state") null spec.volumes).persistentVolumeClaim.claimName
== "swarm-stt-state"
(lib.findFirst (v: v.name == "state") null spec.volumes) == {
name = "state";
emptyDir = { };
}
&& !(objects ? "swarm-stt/persistentvolumeclaim")
&& objects ? "swarm-ci-metrics/persistentvolumeclaim"
# The one credential the pod holds is the store's public CA, from the
# ConfigMap. The controller's pod is the control for the lookup.
&& cred != null
@ -1690,12 +1690,11 @@ let
&& !(lib.any (v: v ? secret) spec.volumes);
}
{
# The gate is the pod's first init container wherever the pod has a
# state volume, ahead of the TLS leaf. The default holds the pod back; a
# fresh install opts in. Each arm's value is the control for the other,
# and the list of gated services is the control for the services with no
# volume.
name = "every pod with a state volume starts with the state gate on that volume, and the fresh option sets what it reads";
# The gate is the first init container of a pod whose state is worth
# moving, ahead of the TLS leaf. The default holds the pod back; a fresh
# install opts in. Each arm's value is the control for the other, and the
# gated services are the control for the ones that start with no gate.
name = "every pod whose state is worth moving starts with the state gate on that volume, and the fresh option sets what it reads";
ok =
let
fresh = render (freshInstall onCluster);
@ -1714,27 +1713,21 @@ let
volume = "state";
option = "deploy.swarm-controller.k8s.freshState";
};
swarm-stt = {
path = "/var/lib/swarm-stt";
volume = "state";
option = "deploy.stt.k8s.freshState";
};
swarm-ci-metrics = {
path = "/var/lib/swarm-ci-metrics";
volume = "state";
option = "deploy.ci-metrics.k8s.freshState";
};
swarm-nats = {
path = "/var/lib/nats";
volume = "nats-data";
option = "deploy.nats.k8s.freshState";
};
};
ungated = [
# The poller keeps a claim for its cursor and the speech-to-text pod
# keeps none; neither is gated.
unclaimed = [
"swarm-notify-router"
"swarm-review-classifier"
"swarm-claude-login"
"swarm-stt"
];
ungated = unclaimed ++ [ "swarm-ci-metrics" ];
one =
name: g:
let
@ -1768,8 +1761,10 @@ let
in
lib.all (n: one n gated.${n}) (lib.attrNames gated)
&& lib.all (n: gate objects n == null && gate fresh n == null) ungated
&& lib.all (n: !(objects ? "${n}/persistentvolumeclaim")) ungated
&& lib.all (n: objects ? "${n}/persistentvolumeclaim") (lib.attrNames gated)
&& lib.all (n: !(objects ? "${n}/persistentvolumeclaim")) unclaimed
&& lib.all (n: objects ? "${n}/persistentvolumeclaim") (
lib.attrNames gated ++ [ "swarm-ci-metrics" ]
)
# One image serves every gate.
&& lib.length (lib.unique (map (n: (gate objects n).image) (lib.attrNames gated))) == 1;
}
@ -1858,21 +1853,22 @@ let
{
# Each state block is read against what the render makes: the claim is
# the PVC's name and the mount is where the state gate looks. The
# stateless services are the control that an entry can carry no state.
name = "migrate.json names every service, with a state block exactly for the ones whose pod has a state volume";
# stateless services are the control that an entry can carry no state. The
# poller has a claim and no entry, since it starts without a gate.
name = "migrate.json names every service, with a state block exactly for the ones whose state is gated";
ok =
let
services = (migrateOf withNode).services;
stateful = [
"swarm-controller"
"swarm-nats"
"swarm-stt"
"swarm-ci-metrics"
];
stateless = [
"swarm-notify-router"
"swarm-review-classifier"
"swarm-claude-login"
"swarm-stt"
"swarm-ci-metrics"
];
objs = render withNode;
gateDir =
@ -1896,7 +1892,9 @@ let
&& s ? hostPath
&& s ? excludes
) stateful
&& lib.all (n: services.${n}.state == null && !(objs ? "${n}/persistentvolumeclaim")) stateless
&& 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
);
@ -1912,9 +1910,8 @@ let
&& host.swarm-controller.state.hostPath == "/var/lib/swarm-controller"
&& host.swarm-nats.state.hostPath == "/var/lib/nixos-containers/swarm-nats/var/lib/nats"
&& host.swarm-nats.state.mount == "/var/lib/nats"
# A DynamicUser unit's data is under `private`.
&& host.swarm-ci-metrics.state.hostPath == "/var/lib/private/swarm-ci-metrics"
&& host.swarm-stt.state.hostPath == null
&& host.swarm-ci-metrics.state == null
&& host.swarm-stt.state == null
&&
host.swarm-ci-metrics.hostUnits == [
"swarm-ci-metrics.timer"

View file

@ -18,7 +18,10 @@
# - a changed hyperhive rev rolls the Deployment, and the state volume is the
# one the first pod had;
# - 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
# and the forge; they replace services that stay host-run and unchanged. The
@ -48,6 +51,13 @@ let
controllerSecretLeaf = "swarm/controller/swarm-controller/oidc/client";
revA = lib.fixedWidthString 40 "a" "";
revB = lib.fixedWidthString 40 "b" "";
# A shell with the pod user's volumes, for the pods the script plays
# `swarmctl migrate` and the gate's one-off runs with.
helperImage = pkgs.dockerTools.buildLayeredImage {
name = "k8s-helper";
tag = "test";
contents = [ pkgs.busybox ];
};
overlapLog = "/var/log/overlap.log";
tokenLog = "/var/log/stub-token.log";
@ -185,6 +195,11 @@ pkgs.testers.runNixOSTest {
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 = {
swarm-controller.runtime = "k8s";
swarm-controller.k8s.freshState = true;
@ -308,7 +323,7 @@ pkgs.testers.runNixOSTest {
environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml";
environment.etc."k3s-node/images".text = lib.concatMapStrings (
i: "${i.imageName}:${i.imageTag}\n"
) config.system.build.k8sImages;
) (config.system.build.k8sImages ++ [ helperImage ]);
# 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" =
@ -329,7 +344,10 @@ pkgs.testers.runNixOSTest {
};
testScript = builtins.readFile ./lib/k3s.py + ''
import re
INIT = "/root/bao-init.json"
HELPER = "${helperImage.imageName}:${helperImage.imageTag}"
NS = "${namespace}"
SERVICE = "${service}"
HOST_UNIT = "${hostUnit}"
@ -529,6 +547,7 @@ pkgs.testers.runNixOSTest {
api = next(p for p in main["ports"] if p["name"] == "api")
assert api["hostPort"] == PORT and api["hostIP"] == NODE_ADDRESS, api
assert [c["name"] for c in spec["initContainers"]] == ["state-gate", "tls-issue"], spec["initContainers"]
GATE_IMAGE = spec["initContainers"][0]["image"]
assert "tls-renew" in [c["name"] for c in spec["containers"]]
assert not any("secret" in v for v in spec["volumes"]), spec["volumes"]
env = {e["name"]: e.get("value") for e in main["env"]}
@ -620,5 +639,130 @@ pkgs.testers.runNixOSTest {
assert any(s[0] in host_up and s[1] == 0 for s in samples), lines[:5]
assert any(s[0] not in host_up and s[1] > 0 for s in samples), lines[:5]
print(f"{SERVICE}: {len(samples)} samples, none with both")
GATE_REFUSAL = f"{SERVICE}: state volume has not been migrated: run `swarmctl migrate {SERVICE}`, or set services.hyperhive.deploy.swarm-controller.k8s.freshState for a fresh install"
def migrate_step(step: str, service: str = SERVICE) -> dict[str, str]:
"""The `step` of `service` in `swarmctl migrate status --json`, which
reads the gate's answer from the pod's status and creates no pod."""
report = json.loads(machine.succeed("swarmctl migrate status --json"))
found = [s for s in report["steps"] if s["service"] == service and s["step"] == step]
assert len(found) == 1, (step, report["steps"])
return found[0]
def helper(name: str, script: str, claim: str | None = None, setup: str | None = None, image: str = HELPER, fresh: str | None = None) -> tuple[str, str]:
"""Runs `script` in a pod of the helper image with the volume of
`claim` (an empty one if None) at /state as the pod user, and returns
its phase and log. With `fresh`, runs the gate image as the pod's own
state gate does, after `setup` has run in the helper image."""
volume: dict[str, dict[str, str]] = {"persistentVolumeClaim": {"claimName": claim}} if claim else {"emptyDir": {}}
container: dict[str, object] = {"name": "run", "image": image, "imagePullPolicy": "Never", "volumeMounts": [{"name": "state", "mountPath": "/state"}]}
spec: dict[str, object] = {
"restartPolicy": "Never",
"securityContext": {"runAsUser": 65532, "runAsGroup": 65532, "fsGroup": 65532},
"volumes": [{"name": "state", **volume}],
"containers": [container],
}
if fresh is None:
container["command"] = ["sh", "-c", script]
else:
container["command"] = ["/bin/hyperhive-state-gate"]
container["env"] = [
{"name": "STATE_GATE_DIR", "value": "/state"},
{"name": "STATE_GATE_SERVICE", "value": "one-off"},
{"name": "STATE_GATE_FRESH", "value": fresh},
{"name": "STATE_GATE_OPTION", "value": "the.option"},
]
spec["initContainers"] = [
{"name": "setup", "image": HELPER, "imagePullPolicy": "Never", "command": ["sh", "-c", setup or "true"], "volumeMounts": container["volumeMounts"]}
]
manifest = {"apiVersion": "v1", "kind": "Pod", "metadata": {"name": name}, "spec": spec}
machine.succeed(f"echo '{json.dumps(manifest)}' | kubectl -n {NS} apply -f -")
machine.wait_until_succeeds(
f"kubectl -n {NS} get pod {name} -o jsonpath='{{.status.phase}}' | grep -E 'Succeeded|Failed'",
timeout=120,
)
phase = machine.succeed(f"kubectl -n {NS} get pod {name} -o jsonpath='{{.status.phase}}'").strip()
text = machine.succeed(f"kubectl -n {NS} logs {name} -c run")
kube(machine, f"delete pod {name} --wait=true")
return phase, text
with subtest("the gate marked the fresh volume with the time, and the marker is what the pod's gate reads"):
phase, text = helper("read-marker", "cat /state/.hyperhive-migrated", claim=f"{SERVICE}-state")
marker = json.loads(text)
assert phase == "Succeeded" and marker["fresh"] is True and re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", marker["at"]), (phase, text)
with subtest("run as the pod's own gate image runs it: lost+found alone is empty, files with no marker are refused even on a fresh install"):
phase, text = helper("gate-lost-found", "", setup="mkdir /state/lost+found", image=GATE_IMAGE, fresh="true")
assert phase == "Succeeded" and "marked" in text, (phase, text)
phase, text = helper("gate-stray", "", setup="touch /state/stray", image=GATE_IMAGE, fresh="true")
assert phase == "Failed" and "holds files and no .hyperhive-migrated marker" in text and "swarmctl migrate one-off" in text, (phase, text)
phase, text = helper("gate-unmarked", "", image=GATE_IMAGE, fresh="false")
assert phase == "Failed" and "run `swarmctl migrate one-off`, or set the.option for a fresh install" in text, (phase, text)
phase, text = helper("gate-marker", "", setup="touch /state/.hyperhive-migrated /state/data", image=GATE_IMAGE, fresh="false")
assert phase == "Succeeded" and "state volume is migrated" in text, (phase, text)
with subtest("the claim stays on the host; it is deleted so that the next pod meets an empty volume"):
assert host_state() == "active", host_state()
kube(machine, f"delete pvc {SERVICE}-state --wait=true --timeout=120s", 150)
with subtest("with freshState off, the pod of an empty volume stays in Init:Error with the reason and nothing of the service runs, and the host unit stays stopped"):
switch("/run/booted-system/specialisation/k8s-unmarked")
assert host_state() == "inactive", host_state()
machine.wait_until_succeeds(f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o name | grep -q pod/", timeout=300)
refused_pod = pods()[0].removeprefix("pod/")
reason = (
"{.status.initContainerStatuses[0].state.terminated.message}"
"{.status.initContainerStatuses[0].lastState.terminated.message}"
)
machine.wait_until_succeeds(f"kubectl -n {NS} get pod {refused_pod} -o jsonpath='{reason}' | grep -qF 'has not been migrated'", timeout=300)
message = machine.succeed(f"kubectl -n {NS} get pod {refused_pod} -o jsonpath='{reason}'").strip()
# The current and the previous attempt each leave the one line.
assert set(message.splitlines()) == {GATE_REFUSAL}, message
# The gate retries and is refused again: the pod does not start, and
# the one-copy invariant is untouched.
machine.wait_until_succeeds(f"kubectl -n {NS} get pod {refused_pod} -o jsonpath='{{.status.initContainerStatuses[0].restartCount}}' | grep -qE '^[1-9]'", timeout=300)
refused = pod(machine, refused_pod)
assert refused["status"]["phase"] == "Pending", refused["status"]
# Every container waits: the pod has the daemon and the leaf renewal.
waiting = {c["state"].get("waiting", {}).get("reason") for c in refused["status"]["containerStatuses"]}
assert waiting == {"PodInitializing"} and len(refused["status"]["containerStatuses"]) >= 1, refused["status"]
assert not is_ready(refused)
assert GATE_REFUSAL in machine.succeed(f"kubectl -n {NS} logs {refused_pod} -c state-gate")
# `swarmctl migrate status` reports the same refusal, and not as a marker.
pods_before = machine.succeed(f"kubectl -n {NS} get pods -o name").split()
copy = migrate_step("copy")
assert copy["status"] == "not_done" and GATE_REFUSAL in copy["detail"], copy
assert migrate_step("ready")["status"] == "not_done"
assert machine.succeed(f"kubectl -n {NS} get pods -o name").split() == pods_before, "status created or deleted a pod"
assert host_state() == "inactive", host_state()
# The control: the claim the pod mounts is bound, and its volume is empty.
phase, text = helper("read-empty", "ls -A /state | wc -l", claim=f"{SERVICE}-state")
assert phase == "Succeeded" and text.strip() == "0", (phase, text)
with subtest("the marker the test writes, as the copy does, lets the same pod start"):
phase, _ = helper("play-migrate", "echo migrated > /state/.hyperhive-migrated", claim=f"{SERVICE}-state")
assert phase == "Succeeded", phase
# The kubelet runs the gate again after its backoff, which is five
# minutes at most.
started = wait_pod_ready(timeout=420)
assert started == refused_pod, (started, refused_pod)
assert "state volume is migrated" in machine.succeed(f"kubectl -n {NS} logs {started} -c state-gate")
copy = migrate_step("copy")
assert copy["status"] == "done" and started in copy["detail"], copy
assert migrate_step("ready")["status"] == "done", migrate_step("ready")
assert migrate_step("runtime")["status"] == "done", migrate_step("runtime")
assert host_state() == "inactive", host_state()
with subtest("a volume that holds files and no marker is refused, and the refusal says the copy may be cut off"):
phase, _ = helper("cut-off", "rm /state/.hyperhive-migrated; echo x > /state/half", claim=f"{SERVICE}-state")
assert phase == "Succeeded", phase
kube(machine, f"delete pod {started} --wait=true --timeout=120s", 150)
machine.wait_until_succeeds(f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={SERVICE} -o name | grep -q pod/", timeout=120)
half_pod = pods()[0].removeprefix("pod/")
machine.wait_until_succeeds(f"kubectl -n {NS} get pod {half_pod} -o jsonpath='{reason}' | grep -qF 'holds files and no .hyperhive-migrated marker'", timeout=300)
assert not is_ready(pod(machine, half_pod))
copy = migrate_step("copy")
assert copy["status"] == "not_done" and "cut off" in copy["detail"], copy
'';
}

View file

@ -12,18 +12,17 @@
# - each pod is Ready, so it logged in to the store with its ServiceAccount
# token, read its client secret and minted a token with it. The router
# routes an event and a deleted pod exits 0 within its grace period; the
# speech-to-text pod carries its limits and has its cache volume bound;
# speech-to-text pod carries its limits and keeps its cache in an emptyDir,
# with no claim and no state gate;
# - the poller's Job completes against a forge that lists one run, pushes it to
# its own route of the swarm collector, holds no Secret, and keeps its cursor
# in a volume, so a second Job pushes nothing;
# in a volume, so a second Job pushes nothing, and starts with no state
# gate;
# - the minter's jwt token writes an agent's credentials and the classifier's
# cannot; the daemons' pods have a read-only root, and `claude` writes its
# config under `HOME` in the /tmp volume only, as the real login step does;
# - the switch back leaves no pod, Deployment, CronJob or AddOn, and the router's
# consumer is the queue's;
# - 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`.
# consumer is the queue's.
#
# The queue is a plain nats-server with TLS, and one stub is the token endpoint,
# the forge and the swarm collector, which records what it is given. The
@ -52,13 +51,6 @@ let
classifier = "swarm-review-classifier";
login = "swarm-claude-login";
agent = "atlas";
# 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 ];
};
pkiDir = "/var/lib/test-ca";
tlsDir = "/var/lib/hive-tls";
leaf = "swarm/services/${clientId}/oidc/client";
@ -249,16 +241,10 @@ pkgs.testers.runNixOSTest {
specialisation.k8s.configuration.services.hyperhive.deploy = {
notify-router.runtime = "k8s";
stt.runtime = "k8s";
stt.k8s.freshState = true;
ci-metrics.runtime = "k8s";
ci-metrics.k8s.freshState = true;
review-classifier.runtime = "k8s";
claude-login.runtime = "k8s";
};
# The speech-to-text pod alone, with no fresh install: its empty volume
# is refused.
specialisation.k8s-unmarked.configuration.services.hyperhive.deploy.stt.runtime = "k8s";
services.k3s.images = [ helperImage ];
# The store's TLS passthrough is a stream server of the host's nginx,
# which needs certificates this host does not mint, so a second nginx
@ -386,7 +372,7 @@ pkgs.testers.runNixOSTest {
}/store-paths";
environment.etc."k3s-node/images".text = lib.concatMapStrings (
i: "${i.imageName}:${i.imageTag}\n"
) (config.system.build.k8sImages ++ [ helperImage ]);
) config.system.build.k8sImages;
# The store's raft data is on a tmpfs, for the reason `full-setup` gives.
fileSystems."/var/lib/nixos-containers/${config.services.hyperhive.swarm.bao.machine}/var/lib/private" =
@ -447,7 +433,6 @@ pkgs.testers.runNixOSTest {
NATS = "--server tls://${natsName}:${toString natsPort} --tlsca ${pkiDir}/ca.pem"
AGENT = "${agent}"
SELECTOR = f"--selector app.kubernetes.io/name={SERVICE}"
HELPER = "${helperImage.imageName}:${helperImage.imageTag}"
def as_root(command: str) -> str:
@ -749,17 +734,12 @@ pkgs.testers.runNixOSTest {
router_resources = json.loads(kube(machine, f"get pod {router} -o json"))["spec"]["containers"][0]["resources"]
assert router_resources == {}, router_resources
with subtest("the speech-to-text cache volume is bound and mounted where the unit keeps its state"):
claim = json.loads(kube(machine, f"get pvc {STT}-state -o json"))
assert claim["status"]["phase"] == "Bound", claim["status"]
CACHE_VOLUME = claim["metadata"]["uid"]
# The first init container is the state gate, which marked the empty
# volume because `freshState` is on.
gate_spec = json.loads(kube(machine, f"get pod {stt_pod} -o json"))["spec"]
assert [c["name"] for c in gate_spec["initContainers"]] == ["state-gate"], gate_spec["initContainers"]
gate_log = machine.succeed(f"kubectl -n {NS} logs {stt_pod} -c state-gate")
assert "the install is fresh: marked" in gate_log, gate_log
mounts = json.loads(kube(machine, f"get pod {stt_pod} -o json"))["spec"]["containers"][0]["volumeMounts"]
with subtest("the speech-to-text cache is an emptyDir mounted where the unit keeps its state, with no claim and no state gate"):
stt_spec = json.loads(kube(machine, f"get pod {stt_pod} -o json"))["spec"]
assert [v for v in stt_spec["volumes"] if v["name"] == "state"] == [{"name": "state", "emptyDir": {}}], stt_spec["volumes"]
assert "state-gate" not in [c["name"] for c in stt_spec.get("initContainers", [])], stt_spec.get("initContainers")
assert machine.execute(f"kubectl -n {NS} get pvc {STT}-state")[0] != 0
mounts = stt_spec["containers"][0]["volumeMounts"]
assert any(m["name"] == "state" and m["mountPath"] == "/var/lib/swarm-stt" for m in mounts), mounts
with subtest("the poller's Job completes against the forge and pushes the run to the poller's own route with a token the identity provider minted"):
@ -1035,8 +1015,9 @@ pkgs.testers.runNixOSTest {
pruned_stt = int(machine.succeed(f"systemctl show -p ExecMainExitTimestampMonotonic --value {STT_PRUNE}.service"))
started_stt = int(machine.succeed(f"systemctl show -p InactiveExitTimestampMonotonic --value {STT_HOST_UNIT}"))
assert 0 < pruned_stt <= started_stt, (pruned_stt, started_stt)
# Persistent volume claims stay, with what they hold.
assert json.loads(kube(machine, f"get pvc {STT}-state -o json"))["metadata"]["uid"] == CACHE_VOLUME
# Persistent volume claims stay, with what they hold; the speech-to-text
# pod never had one.
assert machine.execute(f"kubectl -n {NS} get pvc {STT}-state")[0] != 0
assert machine.execute(f"kubectl -n {NS} get deployment {SERVICE}")[0] != 0
assert machine.execute(f"kubectl -n kube-system get addons.k3s.cattle.io {SERVICE}")[0] != 0
assert machine.execute(f"test -e {MANIFESTS}/{SERVICE}.yaml")[0] != 0
@ -1088,7 +1069,7 @@ pkgs.testers.runNixOSTest {
assert info["ack_floor"]["stream_seq"] == 1, info
machine.succeed(f"nats {NATS} kv get notify-router-state 1.7 >/dev/null")
with subtest("a second switch to the cluster applies the manifests again, and the speech-to-text pod finds its volume"):
with subtest("a second switch to the cluster applies the manifests again, and the speech-to-text pod finds no claim"):
switch("/run/booted-system/specialisation/k8s")
assert host_state() == "inactive", host_state()
assert host_state(STT_HOST_UNIT) == "inactive", host_state(STT_HOST_UNIT)
@ -1097,8 +1078,7 @@ pkgs.testers.runNixOSTest {
for daemon, (daemon_unit, _) in CLAUDE_DAEMONS.items():
assert host_state(daemon_unit) == "inactive", host_state(daemon_unit)
wait_pod_ready(daemon)
claim = json.loads(kube(machine, f"get pvc {STT}-state -o json"))
assert claim["status"]["phase"] == "Bound" and claim["metadata"]["uid"] == CACHE_VOLUME, claim
assert machine.execute(f"kubectl -n {NS} get pvc {STT}-state")[0] != 0
assert ci_host_state() == "inactive", [host_state(u) for u in CI_HOST_UNITS]
machine.wait_until_succeeds(f"kubectl -n {NS} get cronjob {CI}", timeout=300)
kube(machine, f"patch cronjob {CI} -p '{{\"spec\":{{\"suspend\":true}}}}'")
@ -1125,130 +1105,5 @@ pkgs.testers.runNixOSTest {
assert any(s[0] not in host_up and s[1] > 0 for s in samples), (svc, lines[:5])
print(f"{svc}: {len(samples)} samples, none with both")
GATE_REFUSAL = f"{STT}: state volume has not been migrated: run `swarmctl migrate {STT}`, or set services.hyperhive.deploy.stt.k8s.freshState for a fresh install"
def migrate_step(step: str, service: str = STT) -> 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"{STT}-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"):
gate_image = json.loads(kube(machine, f"get pod {service_pods(STT)[0].removeprefix('pod/')} -o json"))["spec"]["initContainers"][0]["image"]
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("back on the host, the speech-to-text claim stays; it is deleted so that the next pod meets an empty volume"):
switch("/run/booted-system")
settle(f"[ \"$(systemctl is-active {STT_HOST_UNIT})\" = active ]", 600, [STT_HOST_UNIT, f"{STT_PRUNE}.service"])
assert service_pods(STT) == [], service_pods(STT)
kube(machine, f"delete pvc {STT}-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(STT_HOST_UNIT) == "inactive", host_state(STT_HOST_UNIT)
machine.wait_until_succeeds(f"kubectl -n {NS} get pods --selector app.kubernetes.io/name={STT} -o name | grep -q pod/", timeout=300)
refused_pod = service_pods(STT)[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()
assert message == 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"]
assert [c["state"].get("waiting", {}).get("reason") for c in refused["status"]["containerStatuses"]] == ["PodInitializing"], 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(STT_HOST_UNIT) == "inactive", host_state(STT_HOST_UNIT)
assert machine.execute("machinectl list --no-legend | grep -q swarm-stt")[0] != 0
# 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"{STT}-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"{STT}-state")
assert phase == "Succeeded", phase
# The kubelet runs the gate again after its backoff, which is five
# minutes at most.
started = wait_pod_ready(STT, 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(STT_HOST_UNIT) == "inactive", host_state(STT_HOST_UNIT)
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"{STT}-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={STT} -o name | grep -q pod/", timeout=120)
half_pod = service_pods(STT)[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
'';
}