Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/swarmctl/src/migrate.rs

1055 lines
36 KiB
Rust

//! `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<MigrateVerb>,
}
#[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<String>),
}
#[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<Self> {
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<String, Service>,
}
#[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<String>,
}
#[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<Config, String>,
/// `systemctl is-active` of each host unit named in the config.
pub(crate) units: BTreeMap<String, Result<String, String>>,
pub(crate) pods: Result<Vec<Pod>, 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<String, Result<String, String>>) -> 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<Step> {
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<Vec<&'a Pod>, &'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::<Config>(&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 <unit>`, which prints the state and exits non-zero for
/// every state but `active`.
fn unit_state(tools: &Tools, unit: &str) -> Result<String, String> {
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<Vec<Pod>, 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<Vec<Pod>, 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<String> {
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::<Vec<_>>(),
"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<bool> {
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<Pod>,
) -> 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<Pod>) -> Vec<Step> {
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<Pod>| {
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<String> {
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"));
}
}