From f89d289a9fefcbf9ca68056e25bb6047a16c4d57 Mon Sep 17 00:00:00 2001 From: atlas Date: Mon, 23 Nov 2026 22:57:06 +0100 Subject: [PATCH] remove swarmctl migrate, migrate.json and the migrate docs --- docs/2-handbook/swarm/swarmctl-cli.md | 34 - docs/4-implementation/k8s/migrate.md | 163 ---- docs/4-implementation/k8s/node.md | 3 +- docs/4-implementation/k8s/runtime.md | 26 +- nix/host-modules/k8s/default.nix | 4 +- nix/host-modules/k8s/migrate.nix | 73 -- nix/module-eval/k8s.nix | 58 -- swarmctl/src/main.rs | 7 - swarmctl/src/migrate.rs | 1055 ------------------------- 9 files changed, 25 insertions(+), 1398 deletions(-) delete mode 100644 docs/4-implementation/k8s/migrate.md delete mode 100644 nix/host-modules/k8s/migrate.nix delete mode 100644 swarmctl/src/migrate.rs diff --git a/docs/2-handbook/swarm/swarmctl-cli.md b/docs/2-handbook/swarm/swarmctl-cli.md index 8684d3f8d..efda870bb 100644 --- a/docs/2-handbook/swarm/swarmctl-cli.md +++ b/docs/2-handbook/swarm/swarmctl-cli.md @@ -40,8 +40,6 @@ This document contains the help content for the `swarmctl` command-line program. * [`swarmctl bao`↴](#swarmctl-bao) * [`swarmctl bao init`↴](#swarmctl-bao-init) * [`swarmctl bao grant-bootstrap`↴](#swarmctl-bao-grant-bootstrap) -* [`swarmctl migrate`↴](#swarmctl-migrate) -* [`swarmctl migrate status`↴](#swarmctl-migrate-status) * [`swarmctl login`↴](#swarmctl-login) * [`swarmctl completions`↴](#swarmctl-completions) @@ -59,7 +57,6 @@ swarm-level operator CLI * `forge` — Manage human accounts on the swarm's forge * `setup` — Walk through the first-run setup, interactively * `bao` — Initialise the swarm's secret store and bootstrap its granter -* `migrate` — Move the swarm's services from this host onto its k3s cluster * `login` — Log in to the swarm named by `--swarm` as your own SSO account * `completions` — Generate a shell completion script for `swarmctl` and print it to stdout @@ -739,37 +736,6 @@ Reads the root token from a hidden prompt, or from stdin when stdin isn't a term -## `swarmctl migrate` - -Move the swarm's services from this host onto its k3s cluster. - -`docs/4-implementation/k8s/migrate.md` describes the move. Only `status` exists yet, and it moves nothing and creates no pod. - -**Usage:** `swarmctl migrate - migrate ` - -###### **Subcommands:** - -* `status` — Report where each service stands: its runtime, its host units and its pod, and which step comes next - - - -## `swarmctl migrate status` - -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. - -Exits 0 when every check ran, whatever the answers, and 1 when a check failed to run. A script reads the report from `--json`. - -**Usage:** `swarmctl migrate status [OPTIONS]` - -###### **Options:** - -* `--json` — Print the report as JSON: the services as the module renders them, one entry per step with its status, and the next step - - - ## `swarmctl login` Log in to the swarm named by `--swarm` as your own SSO account. diff --git a/docs/4-implementation/k8s/migrate.md b/docs/4-implementation/k8s/migrate.md deleted file mode 100644 index 53ba44195..000000000 --- a/docs/4-implementation/k8s/migrate.md +++ /dev/null @@ -1,163 +0,0 @@ -# Moving an all-local swarm onto k8s: `swarmctl migrate` - -A running all-local swarm (`services.hyperhive.deploy.singleHostSwarm`) moves -onto the k3s cluster on the same host one service at a time. The operator sets -`deploy..runtime = "k8s"` and rebuilds; `swarmctl migrate status` reports -where each service stands. Nothing copies a service's state: each one's pod -re-derives what it keeps, keeps it in the service's own store, or uses the host -unit's directory in place. - -## Scope and guarantees - -The swarm's own daemons and the queue move into the cluster: -`swarm-notify-router`, `swarm-review-classifier`, `swarm-claude-login`, -`swarm-stt`, `swarm-ci-metrics`, NATS with `swarm-nats-auth`, and -`swarm-controller`. bao, the forge, authelia, the gateway, `swarm-builder`, -`swarm-matrix-ctl` and every hive keep running on the host. - -- **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 - rebuild for any move. -- **One nix option decides where a service runs.** `deploy..runtime` is - `"host"` (the default) or `"k8s"`. The cut-over is an operator rebuild, - 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 - -| name | what it names | -| ----------------------------------------- | --------------------------------------------------------------- | -| `services.hyperhive.deploy.k8s.enable` | brings up single-node k3s on the swarm host | -| `services.hyperhive.deploy..runtime` | `"host"` or `"k8s"`, per service | -| `/etc/hyperhive/migrate.json` | the module's render of each service's runtime and host units | -| `SWARMCTL_KUBECTL`, `SWARMCTL_KUBECONFIG` | the `swarmctl` wrapper's `kubectl` and the k3s admin kubeconfig | -| `swarmctl migrate status` | the one verb: a read-only report | - -## `swarmctl migrate status` - -It reads `/etc/hyperhive/migrate.json`, asks systemd whether each service's -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: - -- **runtime**: whether the host units have stopped when the configuration says - `k8s`, and whether the cluster still holds a pod of a service the - configuration puts on the host; -- **order**: whether the service moved before one that comes earlier in the - [order of moves](#order-of-moves); -- **ready**: whether the newest pod's readiness probe passes (a `CronJob`'s pod - finishes when its Job completed). - -It names the next step that isn't done, exits 0 when every check ran, and -exits 1 when a check failed to run. `--json` prints the services as the module -renders them, every step with its status, and the next step. - -## Services - -"Ready" means the pod's readiness probe passes. The probes read the `/readyz` -endpoints the [services page](../../2-handbook/swarm/services.md) lists; the -[readiness page](../swarm/readiness.md) has their mechanics. - -| 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 | 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 | 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-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 | 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 | 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 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: - -- **The queue's store is state that must survive.** Losing it empties the - hive-status view, and it also loses the buckets that hold desired state. - It never leaves its directory on the host: the pod and the container use - the same files, so a switch in either direction copies nothing, and the - streams, consumers and acknowledgements are the ones the other side left. - See [the queue's store](#the-queues-store). -- **The controller keeps no state of its own that a move could lose.** The - record of the Matrix admin grants is in the queue's key-value store, the - webhook secret is in the secret store, and the controller sets the avatar - markers again at start. The first start of the controller on the host after - 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 pod uses the directory its container's `nats` unit already uses: -`/var/lib/nixos-containers/swarm-nats/var/lib/nats` on the host, `/var/lib/nats` -in both. The module renders a static `local` PersistentVolume on that path, -pinned to the node, with a storage class of its own and the `Retain` policy. -The claim `swarm-nats-store` binds it by name, so nothing else binds either. - -- **One server at a time.** The prune unit stops a pod before the container - starts, and the Deployment replaces its pod rather than running two. Nothing - reads the directory while the other side writes. -- **Pod to host.** nats-server creates its files with mode `0600`, owned by the - uid it runs as. The pod runs as uid 65532, so the container's `nats` unit - runs `chown -R nats:nats` on the directory before the server starts, as root - and at every start. -- **Host to pod.** The pod's `fsGroup` makes the kubelet set the directory's - group to the pod's and add group read and write on every file at each pod - start, so the pod's uid can use files the host's `nats` user wrote. -- **No lock or identity file.** nats-server keeps none in the store, so - nothing there ties the directory to the side that wrote it. -- **A host that never ran the container.** The module makes the directory, - because the volume needs it before the pod starts. -- **An older claim.** A `swarm-nats-state` claim from an earlier shape isn't - the queue's any more: the pod mounts `swarm-nats-store`, so the old claim - stays unused and needs no step. - -## Order of moves - -`swarmctl migrate 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 - switch, the image, the store identity and reaching the host-run NATS by - name. -2. **`swarm-review-classifier`, `swarm-claude-login`, `swarm-stt`, - `swarm-ci-metrics`**, in one rebuild or one at a time, the same pattern as - step 1. -3. **NATS with `swarm-nats-auth`.** The riskiest move: every hive and agent - disconnects, and the data is the swarm's desired state. Nothing copies it. - `swarm-nats-auth` moves in the same pod, because it answers the auth - callout on every connect and dials the server by name, which the pod's - host aliases map to its loopback. -4. **`swarm-controller` last.** - - It's the operator's view of the swarm. Kept on the host through step 3, - it reports from an unchanged place whether the hives reconnected after - 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 - socket for `swarmctl`, the widest change to the operator's tools. - -Each step needs the previous one Ready. `swarmctl migrate status` says which -service comes next. - -## Downtime and what hives see - -The budget is the time from the cut-over rebuild stopping the host unit to the -pod being Ready. - -| service | budget | what hives, agents and the operator see | -| ------------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `swarm-notify-router` | 2 min | Forge events wait in the stream behind the durable consumer and arrive late | -| `swarm-review-classifier` | 2 min | A try-out request in the gap gets no answer, and its caller reports a failure | -| `swarm-claude-login` | 2 min | A login in progress fails; the operator starts it again | -| `swarm-stt` | 2 min | Transcription requests fail during the gap; the cache starts empty | -| `swarm-ci-metrics` | one 5-minute period | One pass runs late; the first pass on the pod's empty cursor pushes every run again | -| NATS + `swarm-nats-auth` | 10 min | below | -| `swarm-controller` | 5 min | The swarm UI and API answer with gateway errors. Forge webhook deliveries in the gap fail at the forge. After the cut-over, `swarmctl` on the host needs `--swarm` | - -During the NATS gap: - -- Every hive, agent and swarm daemon loses its connection. The queue client - retries at once, then backs off from 500 ms up to one minute. Clients - therefore return within a minute of the pod passing readiness. -- The desired-state buckets aren't readable. Hives apply no change, and - running agents keep running as they are. -- Operator input to agents and agent status in the UI stall, and the UI shows - status as stale. -- Core NATS messages published in the gap get lost. JetStream publishes fail - at the publisher. diff --git a/docs/4-implementation/k8s/node.md b/docs/4-implementation/k8s/node.md index 74bdbadd1..d7a1a9e35 100644 --- a/docs/4-implementation/k8s/node.md +++ b/docs/4-implementation/k8s/node.md @@ -42,8 +42,7 @@ The cluster starts with no hyperhive workload. Each service keeps running as its systemd unit, and nothing applies the services' manifests: two copies of `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 -cluster when its `runtime` is `"k8s"` ([the runtime switch](runtime.md), which -[`swarmctl migrate status`](migrate.md) reports). +cluster when its `runtime` is `"k8s"` ([the runtime switch](runtime.md)). With the option off, the host's configuration is the one it has without the module. diff --git a/docs/4-implementation/k8s/runtime.md b/docs/4-implementation/k8s/runtime.md index 38a73b38a..0082eb039 100644 --- a/docs/4-implementation/k8s/runtime.md +++ b/docs/4-implementation/k8s/runtime.md @@ -11,6 +11,16 @@ or two cursors that push every CI run twice. `swarm-notify-router`, (`swarm-nats`) have the option today, and the other services that run in the cluster follow the same pattern. +## Moving a service + +To move a service into the cluster, set its `runtime` to `"k8s"` and rebuild. +To move it back, set `runtime` back to `"host"` and rebuild. +No command copies data, and a move loses nothing a service holds. +The queue keeps its host store: the pod mounts the directory the container's unit uses, so a switch moves the process and not the bytes. +The controller and the other services hold nothing a move loses; [State](#state) lists what each one keeps. +Hives and agents keep the queue's URL, port, certificate name and auth callout, so no hive needs a rebuild. +The secret store, the forge, authelia, the gateway, `swarm-builder`, `swarm-matrix-ctl` and every hive stay on the host. + ## Options - `services.hyperhive.deploy.notify-router.runtime` (default `"host"`). @@ -281,9 +291,17 @@ holds the container back until the pod has gone. so a switch moves the process and not the bytes, and the pod has no state gate. The container's unit runs `chown -R nats:nats` on the directory before the server starts, and the pod's `fsGroup` gives its group read and write. - [The queue's store](migrate.md#the-queues-store) has the details. The claim - and its volume stay after a switch back, as every claim does, with the - directory. + The volume is `local`, pinned to the node, with a storage class of its own + and the `Retain` policy, and the claim binds it by name. + The prune unit stops a pod before the container starts, and the Deployment + replaces its pod rather than running two, so one server reads the directory + at a time. + nats-server keeps no lock or identity file in the store, so nothing there ties + the directory to the side that wrote it. + The module makes the directory on a host that never ran the container, + because the volume needs it before the pod starts. + The claim and its volume stay after a switch back, as every claim does, with + the directory. - **Readiness.** The pod is Ready when the responder's `/readyz`, on the pod's port 8080, passes and the server's exec probe does. The probe runs `wget` against `/healthz?js-enabled-only=true` on the server's monitor, which @@ -293,6 +311,8 @@ holds the container back until the pod has gone. up to 150 seconds to move. The pod's server gets `SIGTERM` and the pod's 15-second grace period, so every client's connection drops at once and the clients reconnect when the next pod is up. + Core NATS messages published while no server is up never arrive, and JetStream + publishes fail at the publisher. - **Limits.** None, as on the host. The pod has no memory or CPU limit, and its descriptors are the container runtime's, not the 800000 the container's unit sets. The VM test checks the runtime's is at least that. diff --git a/nix/host-modules/k8s/default.nix b/nix/host-modules/k8s/default.nix index 3c8fc1275..9f2ee3720 100644 --- a/nix/host-modules/k8s/default.nix +++ b/nix/host-modules/k8s/default.nix @@ -1,7 +1,6 @@ # Kubernetes manifests for the swarm services this host deploys, rendered by # ./render.nix from their systemd units, and the per-service switch that moves -# a service between its host unit and the cluster (./runtime.nix), and what -# `swarmctl migrate` reads of both (./migrate.nix). Rendering +# a service between its host unit and the cluster (./runtime.nix). Rendering # alone changes no unit and applies nothing. docs/4-implementation/k8s/manifests.md # and runtime.md have the design. { @@ -25,7 +24,6 @@ in { imports = [ ./host-services.nix - ./migrate.nix ./node.nix ./pod-logs.nix ./runtime.nix diff --git a/nix/host-modules/k8s/migrate.nix b/nix/host-modules/k8s/migrate.nix deleted file mode 100644 index 8270c92f5..000000000 --- a/nix/host-modules/k8s/migrate.nix +++ /dev/null @@ -1,73 +0,0 @@ -# What `swarmctl migrate` reads of this host: `/etc/hyperhive/migrate.json`, and -# the environment that tells `swarmctl` which `kubectl` and kubeconfig to use. -# Imported by ./default.nix. docs/4-implementation/k8s/migrate.md has the design. -# -# The file has one entry per service that has a `runtime` option: the -# option's path, the runtime the configuration wants, the host units that run -# the service when it is on the host. The file and the wrapper exist only on a -# host with the node (./node.nix): without a cluster there is nothing to read. -{ - lib, - pkgs, - config, - ... -}: -let - cfg = config.services.hyperhive.k8s; - deployCfg = config.services.hyperhive.deploy; - node = deployCfg.k8s; - controllerCfg = deployCfg.swarm-controller; - - # Each service's name under `services.hyperhive.deploy`. - optionOf = { - swarm-controller = "swarm-controller"; - swarm-nats = "nats"; - swarm-notify-router = "notify-router"; - swarm-stt = "stt"; - swarm-review-classifier = "review-classifier"; - swarm-claude-login = "claude-login"; - swarm-ci-metrics = "ci-metrics"; - }; - - entry = name: switch: { - option = "services.hyperhive.deploy.${optionOf.${name}}.runtime"; - inherit (switch) runtime; - hostUnits = lib.toList switch.hostUnit; - }; - - migrateJson = { - inherit (cfg) namespace; - services = lib.mapAttrs entry cfg.rendered.switches; - }; - - # The `swarmctl` wrapper's variables. The same `kubectl` that ./runtime.nix - # runs, with the cluster's admin kubeconfig. - kubeEnv = { - SWARMCTL_KUBECTL = "${pkgs.kubectl}/bin/kubectl"; - SWARMCTL_KUBECONFIG = "/etc/rancher/k3s/k3s.yaml"; - }; - - # `swarmctl` where the controller's module does not install one. - swarmctlKube = pkgs.symlinkJoin { - name = "swarmctl-kube"; - paths = [ deployCfg.swarm-controller.swarmctlPackage ]; - nativeBuildInputs = [ pkgs.makeWrapper ]; - postBuild = '' - wrapProgram $out/bin/swarmctl ${ - lib.concatStringsSep " " ( - lib.mapAttrsToList (name: value: "--set ${name} ${lib.escapeShellArg value}") kubeEnv - ) - } - ''; - }; -in -{ - config = lib.mkIf (node.enable && cfg.enable) { - environment.etc."hyperhive/migrate.json".text = builtins.toJSON migrateJson; - - # The controller module's wrapper carries these where the controller is - # enabled, which it stays at `runtime = "k8s"`. - services.hyperhive.deploy.swarm-controller.swarmctlEnvironment = kubeEnv; - environment.systemPackages = lib.mkIf (!controllerCfg.enable) [ swarmctlKube ]; - }; -} diff --git a/nix/module-eval/k8s.nix b/nix/module-eval/k8s.nix index e61f147ea..d229b0e52 100644 --- a/nix/module-eval/k8s.nix +++ b/nix/module-eval/k8s.nix @@ -247,7 +247,6 @@ let && usesSecret { projected.sources = [ { secret.name = "x"; } ]; } && !(usesSecret { projected.sources = [ { configMap.name = "x"; } ]; }); - migrateOf = c: builtins.fromJSON c.environment.etc."hyperhive/migrate.json".text; routerUnit = c: c.services.hyperhive.deploy.notify-router.unit; manifestNames = c: lib.sort lib.lessThan (lib.attrNames c.services.k3s.manifests); routerPrune = withNode.systemd.services.swarm-notify-router-k8s-prune; @@ -2182,63 +2181,6 @@ let && problems withCaps != [ ] && problems withoutSeccomp != [ ]; } - { - # The file names the runtime and the host units of every service and no - # state: nothing is copied. The units of the poller (timer and service) - # are the control for a list of more than one. - name = "migrate.json names every service with its option, host units and the runtime the configuration wants, and no state"; - ok = - let - host = (migrateOf withNode).services; - cluster = (migrateOf onCluster).services; - in - (migrateOf withNode).namespace == "hyperhive" - && - lib.sort lib.lessThan (lib.attrNames host) == [ - "swarm-ci-metrics" - "swarm-claude-login" - "swarm-controller" - "swarm-nats" - "swarm-notify-router" - "swarm-review-classifier" - "swarm-stt" - ] - && lib.all (s: !(s ? state)) (lib.attrValues host) - && lib.all (n: lib.hasPrefix "services.hyperhive.deploy." host.${n}.option) (lib.attrNames host) - && - host.swarm-ci-metrics.hostUnits == [ - "swarm-ci-metrics.timer" - "swarm-ci-metrics.service" - ] - && host.swarm-nats.hostUnits == [ "container@swarm-nats.service" ] - && host.swarm-ci-metrics.option == "services.hyperhive.deploy.ci-metrics.runtime" - && lib.all (s: s.runtime == "host") (lib.attrValues host) - # The runtime follows the option: the cluster fixture has every one on k8s. - && lib.all (s: s.runtime == "k8s") (lib.attrValues cluster); - } - { - name = "swarmctl is wrapped with kubectl and the cluster's kubeconfig, by one wrapper per host"; - ok = - let - env = c: c.services.hyperhive.deploy.swarm-controller.swarmctlEnvironment; - wrappers = - c: - map lib.getName ( - lib.filter (p: lib.hasPrefix "swarmctl-" (lib.getName p)) c.environment.systemPackages - ); - in - (env withNode).SWARMCTL_KUBECTL == "${pkgs.kubectl}/bin/kubectl" - && (env withNode).SWARMCTL_KUBECONFIG == "/etc/rancher/k3s/k3s.yaml" - # The controller's own wrapper carries them where the controller is - # enabled; elsewhere the k8s module installs one. - && wrappers withNode == [ "swarmctl-configured" ] - && wrappers nodeNoBridge == [ "swarmctl-kube" ] - # Without the node there is no cluster to name, though the manifests render. - && allLocal.services.hyperhive.k8s.enable - && !(env allLocal ? SWARMCTL_KUBECTL) - && !(allLocal.environment.etc ? "hyperhive/migrate.json") - && wrappers allLocal == [ "swarmctl-configured" ]; - } ]; in runGroup "k8s" cases diff --git a/swarmctl/src/main.rs b/swarmctl/src/main.rs index 7a8a6445a..31872f939 100644 --- a/swarmctl/src/main.rs +++ b/swarmctl/src/main.rs @@ -35,7 +35,6 @@ mod forge; mod inference; mod interactive; mod login; -mod migrate; mod permissions; mod remote; mod schedule; @@ -257,11 +256,6 @@ enum Verb { #[command(subcommand)] command: BaoVerb, }, - /// Move the swarm's services from this host onto its k3s cluster. - /// - /// `docs/4-implementation/k8s/migrate.md` describes the move. Only - /// `status` exists yet, and it moves nothing and creates no pod. - Migrate(migrate::MigrateArgs), /// Log in to the swarm named by `--swarm` as your own SSO account. /// /// With no `--swarm` or `SWARMCTL_SWARM`, logs in to @@ -890,7 +884,6 @@ fn main() -> Result<()> { command: BaoVerb::GrantBootstrap(args), } => bao::grant_bootstrap(args), // Needs none of the `SWARMCTL_AUTHELIA_*` values: it reads the cluster and systemd. - Verb::Migrate(args) => migrate::run(args), // Same socket-resolution reasoning as `Create` above. Verb::Schedule { command } => schedule(&remote, command), Verb::Setup(args) => setup_verb(paths, &remote, args), diff --git a/swarmctl/src/migrate.rs b/swarmctl/src/migrate.rs deleted file mode 100644 index 31be6d08d..000000000 --- a/swarmctl/src/migrate.rs +++ /dev/null @@ -1,1055 +0,0 @@ -//! `swarmctl migrate status` — where each service's move onto the k3s cluster -//! stands, per `docs/4-implementation/k8s/migrate.md`. -//! -//! Read-only: it never creates a pod, copies, deletes or applies anything. -//! Observing and judging are separate on purpose. [`observe`] reads -//! `/etc/hyperhive/migrate.json`, asks systemd whether each service's host -//! 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 -//! tested against hand-built observations. - -use std::collections::BTreeMap; -use std::fmt::Write as _; -use std::io; -use std::path::PathBuf; -use std::process::Command; - -use anyhow::{Context as _, Result, bail}; -use clap::{Args, Subcommand}; -use serde::{Deserialize, Serialize}; -use serde_json::Value; - -/// What the module renders for this host. -const CONFIG_PATH: &str = "/etc/hyperhive/migrate.json"; -/// 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 SERVICE_LABEL: &str = "app.kubernetes.io/name"; - -#[derive(Args)] -#[command(args_conflicts_with_subcommands = true)] -pub struct MigrateArgs { - #[command(subcommand)] - command: Option, -} - -#[derive(Subcommand)] -enum MigrateVerb { - /// 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. - /// - /// Exits 0 when every check ran, whatever the answers, and 1 when a - /// check failed to run. A script reads the report from `--json`. - Status(StatusArgs), - /// Any other word: only `status` exists. - #[command(external_subcommand)] - External(Vec), -} - -#[derive(Args)] -struct StatusArgs { - /// Print the report as JSON: the services as the module renders them, one - /// entry per step with its status, and the next step. - #[arg(long)] - json: bool, -} - -/// The programs and files this verb uses, as paths so that tests can -/// substitute stubs. -pub(crate) struct Tools { - pub(crate) kubectl: PathBuf, - pub(crate) kubeconfig: PathBuf, - pub(crate) systemctl: PathBuf, - pub(crate) config: PathBuf, -} - -impl Tools { - fn from_env() -> Result { - let var = |name: &str| { - std::env::var_os(name).map(PathBuf::from).with_context(|| { - format!( - "{name} is unset — swarmctl is wrapped with it on a host that runs the \ - cluster (services.hyperhive.deploy.k8s.enable)" - ) - }) - }; - Ok(Self { - kubectl: var("SWARMCTL_KUBECTL")?, - kubeconfig: var("SWARMCTL_KUBECONFIG")?, - systemctl: PathBuf::from("systemctl"), - config: PathBuf::from(CONFIG_PATH), - }) - } -} - -/// Where the configuration wants a service to run. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] -#[serde(rename_all = "lowercase")] -pub(crate) enum Runtime { - Host, - K8s, -} - -/// `/etc/hyperhive/migrate.json`. -#[derive(Debug, Deserialize, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct Config { - pub(crate) namespace: String, - pub(crate) services: BTreeMap, -} - -#[derive(Debug, Deserialize, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct Service { - /// The nix option that sets `runtime`. - pub(crate) option: String, - pub(crate) runtime: Runtime, - /// The units that run the service while it is on the host. - pub(crate) host_units: Vec, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct Pod { - pub(crate) name: String, - pub(crate) service: String, - pub(crate) created: String, - pub(crate) phase: String, - pub(crate) ready: bool, -} - -impl Pod { - /// A running pod's readiness probe passes; a `CronJob`'s pod is done when - /// its Job completed. - fn is_ready(&self) -> bool { - self.ready || self.phase == "Succeeded" - } -} - -/// Everything [`classify`] judges. Each field is the whole answer of one -/// check, or the reason the check failed. -#[derive(Debug)] -pub(crate) struct Observed { - pub(crate) config: Result, - /// `systemctl is-active` of each host unit named in the config. - pub(crate) units: BTreeMap>, - pub(crate) pods: Result, String>, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum Kind { - /// The configuration could not be read. - Config, - /// The runtime the configuration wants, and the host units. - Runtime, - /// The service has moved before one that comes first. - Order, - /// The pod runs. - Ready, -} - -impl Kind { - fn name(self) -> &'static str { - match self { - Self::Config => "config", - Self::Runtime => "runtime", - Self::Order => "order", - Self::Ready => "ready", - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) enum Status { - Done(String), - NotDone(String), - /// Something has to change before this can go on. - Blocked(String), - /// The check could not run, or its answer could not be read. - Unknown(String), -} - -impl Status { - fn word(&self) -> &'static str { - match self { - Self::Done(_) => "done", - Self::NotDone(_) => "not done", - Self::Blocked(_) => "blocked", - Self::Unknown(_) => "unknown", - } - } - - fn detail(&self) -> &str { - match self { - Self::Done(d) | Self::NotDone(d) | Self::Blocked(d) | Self::Unknown(d) => d, - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct Step { - /// Empty for [`Kind::Config`]. - pub(crate) service: String, - pub(crate) kind: Kind, - pub(crate) status: Status, -} - -/// The place of a service in `migrate.md`'s order of moves. Services of one -/// rank move in any order. -fn rank(service: &str) -> u8 { - match service { - "swarm-notify-router" => 1, - "swarm-review-classifier" | "swarm-claude-login" | "swarm-stt" => 2, - "swarm-ci-metrics" => 3, - "swarm-nats" => 4, - "swarm-controller" => 5, - _ => u8::MAX, - } -} - -/// What systemd says of a service's host units. -#[derive(Debug, PartialEq, Eq)] -enum HostUnits { - Stopped, - /// The first unit that is not `inactive` or `failed`, and its state. - Running(String, String), - Unknown(String), -} - -fn host_units(service: &Service, units: &BTreeMap>) -> HostUnits { - let mut unknown = None; - for unit in &service.host_units { - match units.get(unit) { - Some(Ok(state)) if state == "inactive" || state == "failed" => {} - Some(Ok(state)) => return HostUnits::Running(unit.clone(), state.clone()), - Some(Err(why)) => unknown = Some(format!("{unit}: {why}")), - None => unknown = Some(format!("{unit}: not checked")), - } - } - unknown.map_or(HostUnits::Stopped, HostUnits::Unknown) -} - -/// The service's pods, newest first. -fn pods_of<'a>(name: &str, pods: &'a [Pod]) -> Vec<&'a Pod> { - let mut mine: Vec<&Pod> = pods.iter().filter(|p| p.service == name).collect(); - mine.sort_by(|a, b| b.created.cmp(&a.created).then_with(|| b.name.cmp(&a.name))); - mine -} - -/// The service runs in the cluster as the configuration wants, and nothing -/// is left to wait for. -fn finished(name: &str, service: &Service, observed: &Observed) -> bool { - let Ok(pods) = &observed.pods else { - return false; - }; - let newest = pods_of(name, pods).first().copied().cloned(); - service.runtime == Runtime::K8s - && host_units(service, &observed.units) == HostUnits::Stopped - && newest.is_some_and(|p| p.is_ready()) -} - -/// Judge every service from what was observed, in the order of moves. -pub(crate) fn classify(observed: &Observed) -> Vec { - let config = match &observed.config { - Ok(config) => config, - Err(why) => { - return vec![Step { - service: String::new(), - kind: Kind::Config, - status: Status::Unknown(why.clone()), - }]; - } - }; - let mut order: Vec<(&String, &Service)> = config.services.iter().collect(); - order.sort_by_key(|(name, _)| (rank(name), (*name).clone())); - - let mut steps = Vec::new(); - for (name, service) in &order { - let unfinished_before: Vec<&str> = order - .iter() - .filter(|(other, s)| rank(other) < rank(name) && !finished(other, s, observed)) - .map(|(other, _)| other.as_str()) - .collect(); - let units = host_units(service, &observed.units); - let pods: Pods = observed - .pods - .as_ref() - .map(|pods| pods_of(name, pods)) - .map_err(String::as_str); - let newest = pods.as_ref().ok().and_then(|p| p.first().copied()); - - steps.push(Step { - service: (*name).clone(), - kind: Kind::Runtime, - status: runtime_status(service, &units, &pods), - }); - let moved = service.runtime == Runtime::K8s || newest.is_some(); - if moved && !unfinished_before.is_empty() && !finished(name, service, observed) { - steps.push(Step { - service: (*name).clone(), - kind: Kind::Order, - status: Status::Blocked(format!( - "out of order: {} moves first", - unfinished_before.join(", ") - )), - }); - } - steps.push(Step { - service: (*name).clone(), - kind: Kind::Ready, - status: ready_status(service, &pods, newest), - }); - } - steps -} - -/// A service's pods, newest first, or why they could not be listed. -type Pods<'a> = Result, &'a str>; - -fn runtime_status(service: &Service, units: &HostUnits, pods: &Pods) -> Status { - match (service.runtime, units) { - (Runtime::K8s, HostUnits::Running(unit, state)) => Status::NotDone(format!( - "runtime is k8s but {unit} is still {state}: the rebuild has not stopped it, or \ - something started it again" - )), - (Runtime::K8s, HostUnits::Stopped) => { - Status::Done("runtime is k8s and the host units are stopped".into()) - } - (Runtime::Host, _) if pods.as_ref().is_ok_and(|p| !p.is_empty()) => { - let names: Vec<&str> = pods.iter().flatten().map(|p| p.name.as_str()).collect(); - Status::NotDone(format!( - "wrong runtime: the configuration says host, but the cluster still has {}", - names.join(", ") - )) - } - (_, HostUnits::Unknown(why)) => Status::Unknown(format!("host units: {why}")), - (Runtime::Host, HostUnits::Running(..)) => Status::NotDone(format!( - "runs on the host: set {} = \"k8s\" and rebuild", - service.option - )), - (Runtime::Host, HostUnits::Stopped) => Status::NotDone(format!( - "runtime is host, but its host units are stopped; to move it, set {} = \"k8s\" and \ - rebuild", - service.option - )), - } -} - -fn ready_status(service: &Service, pods: &Pods, newest: Option<&Pod>) -> Status { - if service.runtime == Runtime::Host { - return Status::NotDone("not in the cluster".into()); - } - if let Err(why) = pods { - return Status::Unknown(format!("pods: {why}")); - } - match newest { - None => Status::NotDone("no pod".into()), - Some(pod) if pod.is_ready() => Status::Done(format!("{} is {}", pod.name, pod.phase)), - Some(pod) => Status::NotDone(format!("{} is {}, not Ready", pod.name, pod.phase)), - } -} - -/// The first step that is not done, in the order of moves. -pub(crate) fn next(steps: &[Step]) -> Option<&Step> { - steps.iter().find(|s| !matches!(s.status, Status::Done(_))) -} - -/// Some check could not run. -fn has_unknown(steps: &[Step]) -> bool { - steps.iter().any(|s| matches!(s.status, Status::Unknown(_))) -} - -/// Run every check once. -pub(crate) fn observe(tools: &Tools) -> Observed { - let config = std::fs::read_to_string(&tools.config) - .map_err(|e| format!("reading {}: {e}", tools.config.display())) - .and_then(|text| { - serde_json::from_str::(&text) - .map_err(|e| format!("parsing {}: {e}", tools.config.display())) - }); - let (units, pods) = match &config { - Ok(config) => ( - config - .services - .values() - .flat_map(|s| s.host_units.iter()) - .map(|unit| (unit.clone(), unit_state(tools, unit))) - .collect(), - list_pods(tools, &config.namespace), - ), - Err(_) => (BTreeMap::new(), Ok(Vec::new())), - }; - Observed { - config, - units, - pods, - } -} - -/// `systemctl is-active `, which prints the state and exits non-zero for -/// every state but `active`. -fn unit_state(tools: &Tools, unit: &str) -> Result { - let out = Command::new(&tools.systemctl) - .args(["is-active", unit]) - .output() - .map_err(|e| format!("running systemctl: {e}"))?; - let state = String::from_utf8_lossy(&out.stdout).trim().to_owned(); - if state.is_empty() { - return Err(format!( - "systemctl is-active printed nothing ({})", - out.status - )); - } - Ok(state) -} - -/// The swarm's pods in `namespace`: the only `kubectl` call, and only `get`. -fn list_pods(tools: &Tools, namespace: &str) -> Result, String> { - let out = Command::new(&tools.kubectl) - .arg("--kubeconfig") - .arg(&tools.kubeconfig) - .args(["--namespace", namespace]) - .args(["get", "pods", "--selector", PART_OF_SELECTOR]) - .args(["--output", "json"]) - .output() - .map_err(|e| format!("running kubectl: {e}"))?; - if !out.status.success() { - return Err(format!( - "kubectl get pods failed ({}): {}", - out.status, - String::from_utf8_lossy(&out.stderr).trim() - )); - } - parse_pods(&String::from_utf8_lossy(&out.stdout)) -} - -/// The pods of `kubectl get pods --output json`, whose label names a service. -pub(crate) fn parse_pods(json: &str) -> Result, String> { - let list: Value = - serde_json::from_str(json).map_err(|e| format!("kubectl printed no JSON: {e}"))?; - let items = list["items"] - .as_array() - .ok_or("kubectl's answer has no `items`")?; - Ok(items - .iter() - .filter_map(|pod| { - Some(Pod { - name: pod["metadata"]["name"].as_str()?.to_owned(), - service: pod["metadata"]["labels"][SERVICE_LABEL] - .as_str()? - .to_owned(), - created: pod["metadata"]["creationTimestamp"] - .as_str() - .unwrap_or_default() - .to_owned(), - phase: pod["status"]["phase"] - .as_str() - .unwrap_or("Unknown") - .to_owned(), - ready: pod["status"]["conditions"].as_array().is_some_and(|c| { - c.iter() - .any(|c| c["type"] == "Ready" && c["status"] == "True") - }), - }) - }) - .collect()) -} - -/// The report as text. -fn render(steps: &[Step]) -> String { - let mut out = String::new(); - let mut service = None; - for step in steps { - if service != Some(&step.service) { - service = Some(&step.service); - if !step.service.is_empty() { - let _ = writeln!(out, "{}", step.service); - } - } - let _ = writeln!( - out, - " {:<8}{:<10}{}", - step.kind.name(), - step.status.word(), - step.status.detail() - ); - } - match next(steps) { - Some(step) if step.service.is_empty() => { - let _ = writeln!(out, "next: {}", step.status.detail()); - } - Some(step) => { - let _ = writeln!( - out, - "next: {} {}: {}", - step.service, - step.kind.name(), - step.status.detail() - ); - } - None => { - let _ = writeln!(out, "every service has moved and is Ready"); - } - } - out -} - -/// The report as JSON. -fn render_json(observed: &Observed, steps: &[Step]) -> Result { - let step = |s: &Step| { - serde_json::json!({ - "service": s.service, - "step": s.kind.name(), - "status": s.status.word().replace(' ', "_"), - "detail": s.status.detail(), - }) - }; - let report = serde_json::json!({ - "namespace": observed.config.as_ref().ok().map(|c| &c.namespace), - "services": observed.config.as_ref().ok().map(|c| &c.services), - "steps": steps.iter().map(step).collect::>(), - "next": next(steps).map(step), - }); - serde_json::to_string_pretty(&report).context("rendering the report") -} - -/// `swarmctl migrate`. -/// -/// # Errors -/// Fails when not run as root, or without the wrapper's `kubectl` variables. -pub fn run(args: MigrateArgs) -> Result<()> { - match args.command { - Some(MigrateVerb::Status(status)) => { - if !rustix::process::geteuid().is_root() { - bail!( - "`swarmctl migrate` must run as root: it reads the k3s admin kubeconfig. Run it \ - with sudo" - ); - } - if !report(&Tools::from_env()?, status.json, &mut io::stdout().lock())? { - std::process::exit(1); - } - Ok(()) - } - Some(MigrateVerb::External(words)) => bail!( - "`swarmctl migrate {}` is not a verb; only `swarmctl migrate status` exists", - words.join(" ") - ), - None => bail!("`swarmctl migrate` needs a verb: only `swarmctl migrate status` exists"), - } -} - -/// Observe, judge and print; whether every check ran. -fn report(tools: &Tools, json: bool, out: &mut impl io::Write) -> Result { - let observed = observe(tools); - let steps = classify(&observed); - if json { - writeln!(out, "{}", render_json(&observed, &steps)?)?; - } else { - write!(out, "{}", render(&steps))?; - } - out.flush().context("writing the report")?; - Ok(!has_unknown(&steps)) -} - -#[cfg(test)] -mod tests { - use std::fs; - - use super::*; - use crate::tests::write_executable; - - fn service(option: &str, runtime: Runtime, units: &[&str]) -> Service { - Service { - option: format!("services.hyperhive.deploy.{option}.runtime"), - runtime, - host_units: units.iter().map(|u| (*u).to_owned()).collect(), - } - } - - fn pod(service: &str, created: &str, ready: bool) -> Pod { - Pod { - name: format!("{service}-{created}"), - service: service.into(), - created: created.into(), - phase: "Running".into(), - ready, - } - } - - fn observed( - services: Vec<(&str, Service)>, - units: &[(&str, &str)], - pods: Vec, - ) -> Observed { - Observed { - config: Ok(Config { - namespace: "hyperhive".into(), - services: services - .into_iter() - .map(|(n, s)| (n.to_owned(), s)) - .collect(), - }), - units: units - .iter() - .map(|(u, s)| ((*u).to_owned(), Ok((*s).to_owned()))) - .collect(), - pods: Ok(pods), - } - } - - fn step<'a>(steps: &'a [Step], service: &str, kind: Kind) -> Option<&'a Status> { - steps - .iter() - .find(|s| s.service == service && s.kind == kind) - .map(|s| &s.status) - } - - const CI: &str = "swarm-ci-metrics"; - const CI_UNITS: [&str; 2] = ["swarm-ci-metrics.timer", "swarm-ci-metrics.service"]; - - /// One service, ci-metrics, with its two host units and the given - /// runtime, host-unit state and pods. - fn ci(runtime: Runtime, unit_state: &str, pods: Vec) -> Vec { - classify(&observed( - vec![(CI, service("ci-metrics", runtime, &CI_UNITS))], - &[ - ("swarm-ci-metrics.timer", unit_state), - ("swarm-ci-metrics.service", "inactive"), - ], - pods, - )) - } - - fn detail(status: Option<&Status>) -> &str { - status.expect("step present").detail() - } - - #[test] - fn config_unreadable_is_the_only_step() { - let steps = classify(&Observed { - config: Err("reading /etc/hyperhive/migrate.json: not found".into()), - units: BTreeMap::new(), - pods: Ok(vec![]), - }); - assert_eq!(steps.len(), 1); - assert!(matches!(steps[0].status, Status::Unknown(_))); - assert_eq!(steps[0].kind, Kind::Config); - assert!(has_unknown(&steps)); - } - - #[test] - fn on_the_host_names_the_option_to_set() { - let steps = ci(Runtime::Host, "active", vec![]); - let runtime = step(&steps, CI, Kind::Runtime).unwrap(); - assert!(matches!(runtime, Status::NotDone(_))); - assert!( - runtime - .detail() - .contains("services.hyperhive.deploy.ci-metrics.runtime") - ); - assert!(matches!( - step(&steps, CI, Kind::Ready), - Some(Status::NotDone(_)) - )); - assert_eq!(next(&steps).unwrap().kind, Kind::Runtime); - } - - #[test] - fn host_unit_still_active_after_the_switch_is_not_a_finished_switch() { - let steps = ci(Runtime::K8s, "active", vec![]); - let runtime = step(&steps, CI, Kind::Runtime).unwrap(); - assert!(matches!(runtime, Status::NotDone(_)), "{runtime:?}"); - assert!(runtime.detail().contains("still active")); - // Control: stopped, the same observation is done. - let steps = ci(Runtime::K8s, "inactive", vec![]); - assert!(matches!( - step(&steps, CI, Kind::Runtime), - Some(Status::Done(_)) - )); - } - - #[test] - fn a_unit_that_is_activating_counts_as_running() { - let steps = ci(Runtime::K8s, "activating", vec![]); - let runtime = step(&steps, CI, Kind::Runtime).unwrap(); - assert!(matches!(runtime, Status::NotDone(_)), "{runtime:?}"); - assert!(runtime.detail().contains("still activating")); - } - - #[test] - fn rebuilt_without_a_pod_waits_for_the_workload() { - let steps = ci(Runtime::K8s, "inactive", vec![]); - assert_eq!(detail(step(&steps, CI, Kind::Ready)), "no pod"); - } - - #[test] - fn a_pod_that_is_not_ready_is_the_next_step() { - let steps = ci(Runtime::K8s, "inactive", vec![pod(CI, "1", false)]); - let ready = step(&steps, CI, Kind::Ready).unwrap(); - assert!(matches!(ready, Status::NotDone(_))); - assert!(ready.detail().contains("not Ready")); - assert_eq!(next(&steps).unwrap().kind, Kind::Ready); - } - - #[test] - fn a_ready_pod_with_the_host_units_stopped_is_everything_done() { - let steps = ci(Runtime::K8s, "inactive", vec![pod(CI, "1", true)]); - assert!( - steps.iter().all(|s| matches!(s.status, Status::Done(_))), - "{steps:?}" - ); - assert!(next(&steps).is_none()); - assert!(!has_unknown(&steps)); - } - - #[test] - fn a_completed_cronjob_pod_is_ready() { - let mut done = pod(CI, "1", false); - done.phase = "Succeeded".into(); - let steps = ci(Runtime::K8s, "inactive", vec![done]); - assert!(matches!( - step(&steps, CI, Kind::Ready), - Some(Status::Done(_)) - )); - } - - #[test] - fn the_newest_pod_decides() { - let old = pod(CI, "1", true); - let new = pod(CI, "2", false); - let steps = ci(Runtime::K8s, "inactive", vec![old, new]); - assert!(matches!( - step(&steps, CI, Kind::Ready), - Some(Status::NotDone(_)) - )); - } - - #[test] - fn a_pod_for_a_service_still_on_the_host_is_the_wrong_runtime() { - let steps = ci(Runtime::Host, "active", vec![pod(CI, "1", false)]); - let runtime = step(&steps, CI, Kind::Runtime).unwrap(); - assert!(runtime.detail().starts_with("wrong runtime"), "{runtime:?}"); - // Control: with no pod the same observation is the plain host case. - let steps = ci(Runtime::Host, "active", vec![]); - assert!(!detail(step(&steps, CI, Kind::Runtime)).contains("wrong runtime")); - } - - #[test] - fn moving_ahead_of_an_earlier_service_is_out_of_order() { - let router = "swarm-notify-router"; - let router_unit = "container@swarm-notify-router.service"; - let build = |router_runtime, router_unit_state: &str, router_pods: Vec| { - classify(&observed( - vec![ - ( - router, - service("notify-router", router_runtime, &[router_unit]), - ), - (CI, service("ci-metrics", Runtime::K8s, &CI_UNITS)), - ], - &[ - (router_unit, router_unit_state), - ("swarm-ci-metrics.timer", "inactive"), - ("swarm-ci-metrics.service", "inactive"), - ], - [router_pods, vec![pod(CI, "1", false)]].concat(), - )) - }; - let steps = build(Runtime::Host, "active", vec![]); - let order = step(&steps, CI, Kind::Order).unwrap(); - assert!(matches!(order, Status::Blocked(_))); - assert!(order.detail().contains(router), "{order:?}"); - assert!(step(&steps, router, Kind::Order).is_none()); - // Control: with the router finished, ci-metrics is in order. - let steps = build(Runtime::K8s, "inactive", vec![pod(router, "1", true)]); - assert!(step(&steps, CI, Kind::Order).is_none()); - } - - #[test] - fn a_service_that_has_not_moved_is_not_out_of_order() { - let router = "swarm-notify-router"; - let steps = classify(&observed( - vec![ - ( - router, - service("notify-router", Runtime::Host, &["a.service"]), - ), - (CI, service("ci-metrics", Runtime::Host, &CI_UNITS)), - ], - &[ - ("a.service", "active"), - ("swarm-ci-metrics.timer", "active"), - ("swarm-ci-metrics.service", "inactive"), - ], - vec![], - )); - assert!(step(&steps, CI, Kind::Order).is_none()); - // The router comes first in the report and in `next`. - assert_eq!(next(&steps).unwrap().service, router); - } - - #[test] - fn services_report_in_the_order_of_moves() { - let services = [ - "swarm-controller", - "swarm-nats", - "swarm-ci-metrics", - "swarm-stt", - "swarm-notify-router", - ]; - let steps = classify(&observed( - services - .iter() - .map(|n| (*n, service(n, Runtime::Host, &["u.service"]))) - .collect(), - &[("u.service", "active")], - vec![], - )); - let mut seen: Vec<&str> = Vec::new(); - for s in &steps { - if seen.last() != Some(&s.service.as_str()) { - seen.push(&s.service); - } - } - assert_eq!( - seen, - [ - "swarm-notify-router", - "swarm-stt", - "swarm-ci-metrics", - "swarm-nats", - "swarm-controller" - ] - ); - } - - #[test] - fn failed_checks_are_unknown_not_guessed() { - let mut o = observed( - vec![(CI, service("ci-metrics", Runtime::K8s, &CI_UNITS))], - &[ - ("swarm-ci-metrics.timer", "inactive"), - ("swarm-ci-metrics.service", "inactive"), - ], - vec![], - ); - o.pods = Err("kubectl get pods failed (exit status: 1): refused".into()); - let steps = classify(&o); - assert!(matches!( - step(&steps, CI, Kind::Ready), - Some(Status::Unknown(_)) - )); - let mut o = observed( - vec![(CI, service("ci-metrics", Runtime::K8s, &CI_UNITS))], - &[("swarm-ci-metrics.service", "inactive")], - vec![], - ); - o.units - .insert("swarm-ci-metrics.timer".into(), Err("no systemctl".into())); - let steps = classify(&o); - assert!(matches!( - step(&steps, CI, Kind::Runtime), - Some(Status::Unknown(_)) - )); - } - - /// The shape of `kubectl get pods --output json` for one pod, written from - /// the API's schema. - fn pod_json(name: &str, ready: &str) -> String { - 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"}}}}, - "spec":{{"containers":[{{"name":"swarm-ci-metrics"}}]}}, - "status":{{"phase":"Pending","conditions":[{{"type":"Ready","status":"{ready}"}}]}}}}"# - ) - } - - fn list(pods: &[String]) -> String { - format!( - r#"{{"apiVersion":"v1","kind":"List","items":[{}]}}"#, - pods.join(",") - ) - } - - #[test] - fn parses_a_pod_with_its_service_and_readiness() { - let pods = parse_pods(&list(&[pod_json("p1", "True")])).unwrap(); - assert_eq!(pods.len(), 1); - assert_eq!(pods[0].service, "swarm-ci-metrics"); - assert!(pods[0].ready); - let pods = parse_pods(&list(&[pod_json("p1", "False")])).unwrap(); - assert!(!pods[0].ready); - } - - #[test] - fn parses_no_pod_and_skips_pods_with_no_service_label() { - assert!(parse_pods(&list(&[])).unwrap().is_empty()); - let unlabelled = r#"{"metadata":{"name":"x","labels":{}},"status":{}}"#.to_owned(); - assert!(parse_pods(&list(&[unlabelled])).unwrap().is_empty()); - assert!(parse_pods("not json").is_err()); - assert!(parse_pods("{}").is_err()); - } - - /// Stand-ins for `kubectl` and `systemctl` that log every call. - const STUB: &str = r#"#!/bin/sh -D=$(dirname "$0") -echo "$(basename "$0") $*" >> "$D/log" -case "$(basename "$0")" in - kubectl) cat "$D/pods.json"; exit "$(cat "$D/kubectl_exit")" ;; - systemctl) - case "$2" in - *.timer) echo "$(cat "$D/timer_state")"; exit 3 ;; - *) echo inactive; exit 3 ;; - esac ;; -esac -"#; - - struct Fixture { - dir: PathBuf, - tools: Tools, - } - - impl Fixture { - fn new(tag: &str, pods: &str) -> Self { - let dir = - std::env::temp_dir().join(format!("swarmctl-migrate-{tag}-{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).expect("temp dir"); - write_executable(&dir.join("kubectl"), STUB); - write_executable(&dir.join("systemctl"), STUB); - fs::write(dir.join("pods.json"), pods).unwrap(); - fs::write(dir.join("kubectl_exit"), "0").unwrap(); - fs::write(dir.join("timer_state"), "inactive").unwrap(); - let config = serde_json::json!({ - "namespace": "hyperhive", - "services": { - CI: { - "option": "services.hyperhive.deploy.ci-metrics.runtime", - "runtime": "k8s", - "hostUnits": CI_UNITS, - }, - }, - }); - fs::write(dir.join("migrate.json"), config.to_string()).unwrap(); - Self { - tools: Tools { - kubectl: dir.join("kubectl"), - kubeconfig: dir.join("k3s.yaml"), - systemctl: dir.join("systemctl"), - config: dir.join("migrate.json"), - }, - dir, - } - } - - fn log(&self) -> Vec { - fs::read_to_string(self.dir.join("log")) - .unwrap_or_default() - .lines() - .map(str::to_owned) - .collect() - } - } - - impl Drop for Fixture { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.dir); - } - } - - #[test] - fn only_reads_and_only_in_the_swarms_namespace() { - let fx = Fixture::new("readonly", &list(&[pod_json("p1", "True")])); - let mut out = Vec::new(); - assert!(report(&fx.tools, false, &mut out).unwrap()); - let log = fx.log(); - let kubectl: Vec<&String> = log.iter().filter(|l| l.starts_with("kubectl")).collect(); - let systemctl: Vec<&String> = log.iter().filter(|l| l.starts_with("systemctl")).collect(); - assert_eq!(kubectl.len(), 1, "{log:?}"); - assert!( - kubectl[0].contains("--namespace hyperhive get pods"), - "{kubectl:?}" - ); - assert!( - kubectl[0].contains(&format!("--kubeconfig {}", fx.tools.kubeconfig.display())), - "{kubectl:?}" - ); - for verb in ["create", "delete", "apply", "exec", "patch", "run", "cp"] { - assert!( - !kubectl[0].split(' ').any(|w| w == verb), - "{verb} in {}", - kubectl[0] - ); - } - assert!(!kubectl[0].contains("--all-namespaces") && !kubectl[0].contains(" -A")); - assert_eq!( - systemctl, - [ - "systemctl is-active swarm-ci-metrics.timer", - "systemctl is-active swarm-ci-metrics.service", - ] - ); - // Control: the log does record calls, and the report read the stubs' - // answers (a ready pod). - let text = String::from_utf8(out).unwrap(); - assert!( - text.contains("every service has moved and is Ready"), - "{text}" - ); - } - - #[test] - fn timer_still_active_is_reported_through_the_stub() { - let fx = Fixture::new("timer", &list(&[])); - fs::write(fx.dir.join("timer_state"), "active").unwrap(); - let mut out = Vec::new(); - assert!(report(&fx.tools, false, &mut out).unwrap()); - let text = String::from_utf8(out).unwrap(); - assert!( - text.contains("swarm-ci-metrics.timer is still active"), - "{text}" - ); - } - - #[test] - fn a_failing_kubectl_makes_the_report_unknown_and_exit_one() { - let fx = Fixture::new("kubectl-fails", ""); - fs::write(fx.dir.join("kubectl_exit"), "1").unwrap(); - let mut out = Vec::new(); - assert!(!report(&fx.tools, false, &mut out).unwrap()); - assert!(String::from_utf8(out).unwrap().contains("unknown")); - } - - #[test] - fn json_report_carries_services_steps_and_next() { - let fx = Fixture::new("json", &list(&[pod_json("p1", "False")])); - let mut out = Vec::new(); - report(&fx.tools, true, &mut out).unwrap(); - let v: Value = serde_json::from_slice(&out).unwrap(); - assert_eq!(v["namespace"], "hyperhive"); - assert_eq!(v["services"][CI]["runtime"], "k8s"); - assert!(v["services"][CI].get("state").is_none()); - let steps = v["steps"].as_array().unwrap(); - let ready = steps.iter().find(|s| s["step"] == "ready").unwrap(); - assert_eq!(ready["status"], "not_done"); - assert!(ready["detail"].as_str().unwrap().contains("not Ready")); - assert_eq!(v["next"]["step"], "ready"); - } - - #[test] - fn a_missing_config_is_reported_not_a_crash() { - let fx = Fixture::new("noconfig", &list(&[])); - fs::remove_file(fx.dir.join("migrate.json")).unwrap(); - let mut out = Vec::new(); - assert!(!report(&fx.tools, false, &mut out).unwrap()); - assert!( - fx.log().is_empty(), - "no call without a config: {:?}", - fx.log() - ); - assert!(String::from_utf8(out).unwrap().contains("migrate.json")); - } -}