From f34b40e300acb74602e60e8b2d3e2fa1f7a4fa33 Mon Sep 17 00:00:00 2001 From: atlas Date: Sun, 22 Nov 2026 20:44:16 +0100 Subject: [PATCH] swarmctl: migrate status reads where each service's move stands --- swarmctl/src/main.rs | 8 + swarmctl/src/migrate.rs | 1355 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 1363 insertions(+) create mode 100644 swarmctl/src/migrate.rs diff --git a/swarmctl/src/main.rs b/swarmctl/src/main.rs index fc44b5671..689f5e2dc 100644 --- a/swarmctl/src/main.rs +++ b/swarmctl/src/main.rs @@ -35,6 +35,7 @@ mod forge; mod inference; mod interactive; mod login; +mod migrate; mod permissions; mod remote; mod schedule; @@ -256,6 +257,11 @@ 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 @@ -913,6 +919,8 @@ fn main() -> Result<()> { Verb::Bao { 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 new file mode 100644 index 000000000..68d82be2d --- /dev/null +++ b/swarmctl/src/migrate.rs @@ -0,0 +1,1355 @@ +//! `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. +//! +//! The copy marker is never read from the volume. The pod's first init +//! container, the start gate, exits 0 only with the marker present and +//! refuses otherwise with the reason in its termination message; both are in +//! the pod's status. + +use std::collections::BTreeMap; +use std::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 pod's start gate: the init container that checks the copy marker. +const GATE_CONTAINER: &str = "state-gate"; +/// The label every pod of the swarm carries, and the one that names its service. +const PART_OF_SELECTOR: &str = "app.kubernetes.io/part-of=hyperhive"; +const SERVICE_LABEL: &str = "app.kubernetes.io/name"; +/// The text of the gate's refusal on a volume that holds files and no marker. +const GATE_NONEMPTY: &str = "holds files and no .hyperhive-migrated marker"; + +#[derive(Args)] +#[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, its pod + /// and the start gate's answer, 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), + /// Moves a service. Not available yet: only `status` is. + #[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, + /// Null for a service with no state volume. + pub(crate) state: Option, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct State { + pub(crate) claim: String, + /// Where the pod mounts the claim. + pub(crate) mount: String, + /// Where the data lives on the host; null where nothing is copied. + pub(crate) host_path: Option, + /// Paths under `host_path` a copy leaves out. + pub(crate) excludes: Vec, +} + +/// What the pod's start gate has answered. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Gate { + /// Exited 0: the marker is in the volume. + Passed, + /// Exited non-zero, with its termination message. + Refused(String), + /// Not finished yet. + Pending, + /// The pod has no state gate. + Absent, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Pod { + pub(crate) name: String, + pub(crate) service: String, + pub(crate) created: String, + pub(crate) phase: String, + pub(crate) ready: bool, + pub(crate) gate: Gate, +} + +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 start gate's marker. + Copy, + /// The pod runs. + Ready, +} + +impl Kind { + fn name(self) -> &'static str { + match self { + Self::Config => "config", + Self::Runtime => "runtime", + Self::Order => "order", + Self::Copy => "copy", + 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() && (service.state.is_none() || p.gate == Gate::Passed)) +} + +/// 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(", ") + )), + }); + } + if service.state.is_some() { + steps.push(Step { + service: (*name).clone(), + kind: Kind::Copy, + status: copy_status(service, &units, &pods, newest), + }); + } + 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 copy_status(service: &Service, units: &HostUnits, pods: &Pods, newest: Option<&Pod>) -> Status { + if service.runtime == Runtime::Host { + return Status::NotDone("after the cut-over rebuild".into()); + } + if let HostUnits::Running(unit, state) = units { + return Status::Blocked(format!( + "host unit {unit} is still {state}: a copy refuses until it stops" + )); + } + if let Err(why) = pods { + return Status::Unknown(format!("pods: {why}")); + } + let Some(pod) = newest else { + return Status::NotDone("no pod yet: the rebuild has not applied the workload".into()); + }; + match &pod.gate { + Gate::Passed => Status::Done(format!("marker present ({})", pod.name)), + Gate::Refused(message) if message.contains(GATE_NONEMPTY) => Status::NotDone(format!( + "the volume holds files and no marker, so a copy was cut off or the volume was \ + written to: {message}" + )), + Gate::Refused(message) => Status::NotDone(format!("waiting for the copy: {message}")), + Gate::Pending => Status::NotDone(format!("the gate of {} has not answered yet", pod.name)), + Gate::Absent => Status::Unknown(format!("{} has no {GATE_CONTAINER} container", pod.name)), + } +} + +fn ready_status(service: &Service, pods: &Pods, newest: Option<&Pod>) -> Status { + 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) if matches!(pod.gate, Gate::Refused(_)) => { + Status::NotDone(format!("{} waits behind its start gate", pod.name)) + } + Some(pod) => Status::NotDone(format!("{} is {}, not Ready", pod.name, pod.phase)), + } +} + +/// 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") + }), + gate: gate_of(pod), + }) + }) + .collect()) +} + +fn gate_of(pod: &Value) -> Gate { + let declared = pod["spec"]["initContainers"] + .as_array() + .is_some_and(|c| c.iter().any(|c| c["name"] == GATE_CONTAINER)); + if !declared { + return Gate::Absent; + } + let Some(status) = pod["status"]["initContainerStatuses"] + .as_array() + .and_then(|c| c.iter().find(|c| c["name"] == GATE_CONTAINER)) + else { + return Gate::Pending; + }; + let refused = |t: &Value| { + Gate::Refused( + t["message"] + .as_str() + .map(str::trim) + .filter(|m| !m.is_empty()) + .map_or_else(|| format!("exit {}", t["exitCode"]), str::to_owned), + ) + }; + let terminated = &status["state"]["terminated"]; + if terminated.is_object() { + return if terminated["exitCode"] == 0 { + Gate::Passed + } else { + refused(terminated) + }; + } + let last = &status["lastState"]["terminated"]; + if status["state"]["waiting"].is_object() && last.is_object() && last["exitCode"] != 0 { + return refused(last); + } + Gate::Pending +} + +/// The report as text. +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 available yet; only `swarmctl migrate status` is", + words.join(" ") + ), + None => bail!( + "`swarmctl migrate` does not move services yet: only `swarmctl migrate status` is \ + available" + ), + } +} + +/// 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], state: bool) -> Service { + Service { + option: format!("services.hyperhive.deploy.{option}.runtime"), + runtime, + host_units: units.iter().map(|u| (*u).to_owned()).collect(), + state: state.then(|| State { + claim: "x-state".into(), + mount: "/var/lib/x".into(), + host_path: Some("/var/lib/x".into()), + excludes: vec![], + }), + } + } + + fn pod(service: &str, created: &str, ready: bool, gate: Gate) -> Pod { + Pod { + name: format!("{service}-{created}"), + service: service.into(), + created: created.into(), + phase: "Running".into(), + ready, + gate, + } + } + + 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 stateful 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, true))], + &[ + ("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::Copy), + Some(Status::NotDone(_)) + )); + 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_blocks_the_copy() { + let steps = ci(Runtime::K8s, "active", vec![]); + assert!(detail(step(&steps, CI, Kind::Runtime)).contains("still active")); + let copy = step(&steps, CI, Kind::Copy).unwrap(); + assert!(matches!(copy, Status::Blocked(_)), "{copy:?}"); + // Control: stopped, the same observation is not blocked. + let steps = ci(Runtime::K8s, "inactive", vec![]); + assert!(matches!( + step(&steps, CI, Kind::Runtime), + Some(Status::Done(_)) + )); + assert!(!matches!( + step(&steps, CI, Kind::Copy), + Some(Status::Blocked(_)) + )); + } + + #[test] + fn a_unit_that_is_activating_counts_as_running() { + let steps = ci(Runtime::K8s, "activating", vec![]); + assert!(matches!( + step(&steps, CI, Kind::Copy), + Some(Status::Blocked(_)) + )); + } + + #[test] + fn rebuilt_without_a_pod_waits_for_the_workload() { + let steps = ci(Runtime::K8s, "inactive", vec![]); + assert!(detail(step(&steps, CI, Kind::Copy)).contains("no pod yet")); + assert_eq!(detail(step(&steps, CI, Kind::Ready)), "no pod"); + } + + #[test] + fn gate_refused_on_an_empty_volume_waits_for_the_copy() { + let refusal = "swarm-ci-metrics: state volume has not been migrated: run `swarmctl migrate swarm-ci-metrics`"; + let steps = ci( + Runtime::K8s, + "inactive", + vec![pod(CI, "1", false, Gate::Refused(refusal.into()))], + ); + let copy = step(&steps, CI, Kind::Copy).unwrap(); + assert!(matches!(copy, Status::NotDone(_))); + assert!( + copy.detail().starts_with("waiting for the copy"), + "{copy:?}" + ); + assert!(copy.detail().contains(refusal)); + assert!(detail(step(&steps, CI, Kind::Ready)).contains("start gate")); + } + + #[test] + fn gate_refused_on_files_without_a_marker_reports_a_cut_off_copy() { + let refusal = "swarm-ci-metrics: state volume has not been migrated: it holds files and no .hyperhive-migrated marker, so a copy may have been cut off"; + let steps = ci( + Runtime::K8s, + "inactive", + vec![pod(CI, "1", false, Gate::Refused(refusal.into()))], + ); + let copy = detail(step(&steps, CI, Kind::Copy)); + assert!( + copy.starts_with("the volume holds files and no marker"), + "{copy}" + ); + } + + #[test] + fn gate_that_has_not_answered_and_gate_absent() { + let steps = ci( + Runtime::K8s, + "inactive", + vec![pod(CI, "1", false, Gate::Pending)], + ); + assert!(detail(step(&steps, CI, Kind::Copy)).contains("not answered")); + let steps = ci( + Runtime::K8s, + "inactive", + vec![pod(CI, "1", false, Gate::Absent)], + ); + assert!(matches!( + step(&steps, CI, Kind::Copy), + Some(Status::Unknown(_)) + )); + } + + #[test] + fn marker_present_but_pod_not_ready() { + let steps = ci( + Runtime::K8s, + "inactive", + vec![pod(CI, "1", false, Gate::Passed)], + ); + assert!(matches!( + step(&steps, CI, Kind::Copy), + Some(Status::Done(_)) + )); + let ready = step(&steps, CI, Kind::Ready).unwrap(); + assert!(matches!(ready, Status::NotDone(_))); + assert!(ready.detail().contains("not Ready")); + assert_eq!(next(&steps).unwrap().kind, Kind::Ready); + } + + #[test] + fn marker_present_and_ready_is_everything_done() { + let steps = ci( + Runtime::K8s, + "inactive", + vec![pod(CI, "1", true, Gate::Passed)], + ); + 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, Gate::Passed); + 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, Gate::Passed); + let new = pod(CI, "2", false, Gate::Refused("refused".into())); + let steps = ci(Runtime::K8s, "inactive", vec![old, new]); + assert!(matches!( + step(&steps, CI, Kind::Copy), + 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, Gate::Pending)], + ); + 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 a_stateless_service_has_no_copy_step() { + let router = "swarm-notify-router"; + let steps = classify(&observed( + vec![( + router, + service( + "notify-router", + Runtime::K8s, + &["container@swarm-notify-router.service"], + false, + ), + )], + &[("container@swarm-notify-router.service", "inactive")], + vec![pod(router, "1", true, Gate::Absent)], + )); + assert!(step(&steps, router, Kind::Copy).is_none()); + assert!(matches!( + step(&steps, router, Kind::Ready), + Some(Status::Done(_)) + )); + assert!(next(&steps).is_none()); + } + + #[test] + 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], false), + ), + (CI, service("ci-metrics", Runtime::K8s, &CI_UNITS, true)), + ], + &[ + (router_unit, router_unit_state), + ("swarm-ci-metrics.timer", "inactive"), + ("swarm-ci-metrics.service", "inactive"), + ], + [router_pods, vec![pod(CI, "1", false, Gate::Pending)]].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, Gate::Absent)], + ); + 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"], false), + ), + (CI, service("ci-metrics", Runtime::Host, &CI_UNITS, true)), + ], + &[ + ("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"], false))) + .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, true))], + &[ + ("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::Copy), + Some(Status::Unknown(_)) + )); + assert!(matches!( + step(&steps, CI, Kind::Ready), + Some(Status::Unknown(_)) + )); + let mut o = observed( + vec![(CI, service("ci-metrics", Runtime::K8s, &CI_UNITS, true))], + &[("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 a pod behind a start + /// gate, written from the API's schema. + fn pod_json(name: &str, gate_state: &str, ready: &str, with_gate: bool) -> String { + let init_spec = if with_gate { + r#","initContainers":[{"name":"state-gate"}]"# + } else { + "" + }; + let init_status = if with_gate { + format!(r#","initContainerStatuses":[{{"name":"state-gate",{gate_state}}}]"#) + } else { + String::new() + }; + format!( + r#"{{"metadata":{{"name":"{name}","creationTimestamp":"2026-11-22T20:00:00Z","labels":{{"app.kubernetes.io/name":"swarm-ci-metrics","app.kubernetes.io/part-of":"hyperhive"}}}}, + "spec":{{"containers":[{{"name":"swarm-ci-metrics"}}]{init_spec}}}, + "status":{{"phase":"Pending","conditions":[{{"type":"Ready","status":"{ready}"}}]{init_status}}}}}"# + ) + } + + fn list(pods: &[String]) -> String { + format!( + r#"{{"apiVersion":"v1","kind":"List","items":[{}]}}"#, + pods.join(",") + ) + } + + const GATE_PASSED: &str = r#""state":{"terminated":{"exitCode":0,"reason":"Completed"}}"#; + const GATE_REFUSED_BACKOFF: &str = r#""state":{"waiting":{"reason":"PodInitializing"}},"lastState":{"terminated":{"exitCode":1,"reason":"Error","message":"swarm-ci-metrics: state volume has not been migrated: run `swarmctl migrate swarm-ci-metrics`\n"}}"#; + const GATE_REFUSED_NOW: &str = + r#""state":{"terminated":{"exitCode":1,"reason":"Error","message":"refused now"}}"#; + const GATE_RUNNING: &str = r#""state":{"running":{}}"#; + + #[test] + fn parses_a_gate_that_passed() { + let pods = parse_pods(&list(&[pod_json("p1", GATE_PASSED, "True", true)])).unwrap(); + assert_eq!(pods.len(), 1); + assert_eq!(pods[0].service, "swarm-ci-metrics"); + assert_eq!(pods[0].gate, Gate::Passed); + assert!(pods[0].ready); + } + + #[test] + fn parses_a_gate_that_refused_with_its_message() { + let pods = parse_pods(&list(&[pod_json( + "p1", + GATE_REFUSED_BACKOFF, + "False", + true, + )])) + .unwrap(); + assert_eq!( + pods[0].gate, + Gate::Refused( + "swarm-ci-metrics: state volume has not been migrated: run `swarmctl migrate swarm-ci-metrics`" + .into() + ) + ); + assert!(!pods[0].ready); + let pods = parse_pods(&list(&[pod_json("p1", GATE_REFUSED_NOW, "False", true)])).unwrap(); + assert_eq!(pods[0].gate, Gate::Refused("refused now".into())); + } + + #[test] + fn parses_a_running_gate_and_a_pod_without_one() { + let pods = parse_pods(&list(&[pod_json("p1", GATE_RUNNING, "False", true)])).unwrap(); + assert_eq!(pods[0].gate, Gate::Pending); + let pods = parse_pods(&list(&[pod_json("p1", "", "True", false)])).unwrap(); + assert_eq!(pods[0].gate, Gate::Absent); + } + + #[test] + 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, + "state": { + "claim": "swarm-ci-metrics-state", + "mount": "/var/lib/swarm-ci-metrics", + "hostPath": "/var/lib/private/swarm-ci-metrics", + "excludes": [], + }, + }, + }, + }); + 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", GATE_PASSED, "True", 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 behind a passed gate). + let text = String::from_utf8(out).unwrap(); + assert!(text.contains("marker present"), "{text}"); + 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", GATE_REFUSED_BACKOFF, "False", true)]), + ); + 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]["state"]["claim"], + "swarm-ci-metrics-state" + ); + let steps = v["steps"].as_array().unwrap(); + let copy = steps.iter().find(|s| s["step"] == "copy").unwrap(); + assert_eq!(copy["status"], "not_done"); + assert!( + copy["detail"] + .as_str() + .unwrap() + .contains("swarmctl migrate") + ); + assert_eq!(v["next"]["step"], "copy"); + } + + #[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")); + } +}