use std::collections::BTreeMap;
use std::time::Duration;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HostResult {
pub host: String,
pub output: String,
pub exit: Option<i32>,
}
impl HostResult {
pub fn ok(&self) -> bool {
self.exit == Some(0)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FleetSummary {
pub identical: usize,
pub differ: usize,
pub failed: usize,
}
impl FleetSummary {
pub fn line(&self) -> String {
let mut parts = Vec::new();
if self.identical > 0 {
parts.push(format!("{} identical", self.identical));
}
if self.differ > 0 {
parts.push(format!("{} differ", self.differ));
}
if self.failed > 0 {
parts.push(format!("{} failed", self.failed));
}
if parts.is_empty() {
return String::from("no hosts");
}
parts.join(" \u{b7} ")
}
}
pub fn reference_output(results: &[HostResult]) -> Option<&str> {
let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
for r in results.iter().filter(|r| r.ok()) {
*counts.entry(r.output.as_str()).or_default() += 1;
}
let best = counts.values().copied().max()?;
let winners = counts.values().filter(|&&c| c == best).count();
if winners > 1 {
return None;
}
counts
.into_iter()
.find(|&(_, c)| c == best)
.map(|(out, _)| out)
}
pub fn summarise(results: &[HostResult], reference: Option<&str>) -> FleetSummary {
let mut s = FleetSummary {
identical: 0,
differ: 0,
failed: 0,
};
for r in results {
if !r.ok() {
s.failed += 1;
} else if Some(r.output.as_str()) == reference {
s.identical += 1;
} else {
s.differ += 1;
}
}
s
}
pub fn fleet_ssh_args(host: &str, command: &str) -> Vec<String> {
vec![
String::from("-n"),
String::from("-o"),
String::from("BatchMode=yes"),
String::from("-o"),
String::from("StrictHostKeyChecking=yes"),
String::from(host),
String::from("--"),
String::from(command),
]
}
pub fn parse_request_with_groups<'a>(
input: &str,
known: &'a [String],
groups: &std::collections::BTreeMap<String, Vec<String>>,
) -> Option<(Vec<&'a String>, String)> {
let (spec, command) = input.split_once(':')?;
let command = command.trim();
if command.is_empty() {
return None;
}
let spec = spec.trim();
if spec == "*" {
return Some((known.iter().collect(), command.to_string()));
}
let mut hosts = Vec::new();
for name in spec.split(',').map(str::trim).filter(|n| !n.is_empty()) {
let members: Vec<&str> = match groups.iter().find(|(g, _)| g.eq_ignore_ascii_case(name)) {
Some((_, members)) => members.iter().map(String::as_str).collect(),
None => vec![name],
};
if members.is_empty() {
return None;
}
for member in members {
let found = known.iter().find(|k| k.eq_ignore_ascii_case(member))?;
if !hosts.contains(&found) {
hosts.push(found);
}
}
}
(!hosts.is_empty()).then_some((hosts, command.to_string()))
}
pub fn run_on_hosts(hosts: &[String], command: &str, timeout: Duration) -> Vec<HostResult> {
let (tx, rx) = std::sync::mpsc::channel();
for (idx, host) in hosts.iter().enumerate() {
let tx = tx.clone();
let host = host.clone();
let command = command.to_string();
std::thread::spawn(move || {
let _ = tx.send((idx, run_one(&host, &command, timeout)));
});
}
drop(tx);
let deadline = std::time::Instant::now() + timeout + Duration::from_secs(2);
let mut got: Vec<Option<HostResult>> = (0..hosts.len()).map(|_| None).collect();
let mut filled = 0usize;
while filled < hosts.len() {
let left = deadline.saturating_duration_since(std::time::Instant::now());
if left.is_zero() {
break;
}
match rx.recv_timeout(left) {
Ok((idx, r)) => {
if got.get(idx).is_some_and(Option::is_none) {
got[idx] = Some(r);
filled += 1;
}
}
Err(_) => break,
}
}
got.into_iter()
.zip(hosts)
.map(|(r, h)| {
r.unwrap_or_else(|| HostResult {
host: h.clone(),
output: String::from("timed out"),
exit: None,
})
})
.collect()
}
fn run_one(host: &str, command: &str, timeout: Duration) -> HostResult {
let secs = timeout.as_secs().max(1);
let mut args = vec![String::from("-o"), format!("ConnectTimeout={secs}")];
args.extend(fleet_ssh_args(host, command));
let spawned = std::process::Command::new("ssh")
.args(&args)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn();
let mut child = match spawned {
Ok(c) => c,
Err(e) => {
return HostResult {
host: host.to_string(),
output: format!("could not run ssh: {e}"),
exit: None,
};
}
};
let deadline = std::time::Instant::now() + timeout;
loop {
match child.try_wait() {
Ok(Some(_)) => break,
Ok(None) if std::time::Instant::now() >= deadline => {
let _ = child.kill();
let _ = child.wait();
return HostResult {
host: host.to_string(),
output: String::from("timed out"),
exit: None,
};
}
Ok(None) => std::thread::sleep(Duration::from_millis(25)),
Err(e) => {
return HostResult {
host: host.to_string(),
output: format!("could not wait on ssh: {e}"),
exit: None,
};
}
}
}
let out = child.wait_with_output();
match out {
Ok(o) => {
let mut text = String::from_utf8_lossy(&o.stdout).trim_end().to_string();
let err = String::from_utf8_lossy(&o.stderr);
let err = err.trim_end();
if !err.is_empty() {
if !text.is_empty() {
text.push('\n');
}
text.push_str(err);
}
HostResult {
host: host.to_string(),
output: text,
exit: o.status.code(),
}
}
Err(e) => HostResult {
host: host.to_string(),
output: format!("could not run ssh: {e}"),
exit: None,
},
}
}
#[cfg(test)]
mod tests {
use super::*;
fn groups(pairs: &[(&str, &[&str])]) -> std::collections::BTreeMap<String, Vec<String>> {
pairs
.iter()
.map(|(g, m)| {
(
(*g).to_string(),
m.iter().map(|h| (*h).to_string()).collect(),
)
})
.collect()
}
#[test]
fn a_saved_group_expands_to_its_hosts_and_only_those() {
let known: Vec<String> = ["web1", "web2", "db1"]
.iter()
.map(|s| s.to_string())
.collect();
let g = groups(&[("web", &["web1", "web2"])]);
let (hosts, cmd) = parse_request_with_groups("web: uname -r", &known, &g).expect("parsed");
assert_eq!(
hosts.iter().map(|h| h.as_str()).collect::<Vec<_>>(),
vec!["web1", "web2"],
"the group's members, not the whole fleet"
);
assert_eq!(cmd, "uname -r");
}
#[test]
fn a_group_cannot_smuggle_an_unknown_host_past_the_check() {
let known: Vec<String> = ["web1"].iter().map(|s| s.to_string()).collect();
let g = groups(&[("web", &["web1", "not-configured"])]);
assert!(
parse_request_with_groups("web: uname -r", &known, &g).is_none(),
"an unknown member refuses the whole request rather than running on the rest"
);
let ok = groups(&[("web", &["web1"])]);
assert!(parse_request_with_groups("web: uname -r", &known, &ok).is_some());
}
#[test]
fn an_empty_group_refuses_rather_than_narrowing_the_fleet() {
let known: Vec<String> = ["web1", "db1"].iter().map(|s| s.to_string()).collect();
let empty = groups(&[("web", &[])]);
assert!(
parse_request_with_groups("web: uptime", &known, &empty).is_none(),
"an empty group alone refuses"
);
assert!(
parse_request_with_groups("web,db1: uptime", &known, &empty).is_none(),
"and mixed with a real host it refuses too, rather than running on db1"
);
let ok = groups(&[("web", &["web1"])]);
let (hosts, _) = parse_request_with_groups("web,db1: uptime", &known, &ok).expect("parsed");
assert_eq!(hosts.len(), 2);
}
#[test]
fn a_self_referential_group_refuses_instead_of_looping() {
let known: Vec<String> = ["web1"].iter().map(|s| s.to_string()).collect();
let looped = groups(&[("web", &["web"])]);
assert!(
parse_request_with_groups("web: uptime", &known, &looped).is_none(),
"'web' expands once to 'web', which is not a known host"
);
let mutual = groups(&[("a", &["b"]), ("b", &["a"])]);
assert!(
parse_request_with_groups("a: uptime", &known, &mutual).is_none(),
"mutual references terminate the same way"
);
}
#[test]
fn a_group_name_takes_precedence_over_a_host_of_the_same_name() {
let known: Vec<String> = ["web1", "web2"].iter().map(|s| s.to_string()).collect();
let g = groups(&[("web1", &["web1", "web2"])]);
let (hosts, _) = parse_request_with_groups("web1: uptime", &known, &g).expect("parsed");
assert_eq!(
hosts.len(),
2,
"the GROUP named web1 expanded, not the host"
);
let (one, _) =
parse_request_with_groups("web1: uptime", &known, &groups(&[])).expect("parsed");
assert_eq!(
one.iter().map(|h| h.as_str()).collect::<Vec<_>>(),
vec!["web1"]
);
}
fn r(host: &str, out: &str, exit: Option<i32>) -> HostResult {
HostResult {
host: String::from(host),
output: String::from(out),
exit,
}
}
#[test]
fn the_reference_is_the_majority_not_the_first_host() {
let results = vec![
r("odd", "6.1.0", Some(0)),
r("a", "5.15.0", Some(0)),
r("b", "5.15.0", Some(0)),
r("c", "5.15.0", Some(0)),
];
assert_eq!(
reference_output(&results),
Some("5.15.0"),
"the fleet's normal, not whichever host was listed first"
);
let s = summarise(&results, reference_output(&results));
assert_eq!(
(s.identical, s.differ, s.failed),
(3, 1, 0),
"the odd host is the one that differs"
);
assert_eq!(s.line(), "3 identical \u{b7} 1 differ");
}
#[test]
fn a_failing_host_does_not_define_the_normal() {
let results = vec![
r("bad1", "Permission denied", Some(255)),
r("bad2", "Permission denied", Some(255)),
r("bad3", "Permission denied", None),
r("good", "5.15.0", Some(0)),
];
assert_eq!(
reference_output(&results),
Some("5.15.0"),
"only successful hosts vote"
);
let s = summarise(&results, reference_output(&results));
assert_eq!((s.identical, s.differ, s.failed), (1, 0, 3));
assert_eq!(s.line(), "1 identical \u{b7} 3 failed");
}
#[test]
fn an_even_split_has_no_reference() {
let results = vec![
r("a", "x", Some(0)),
r("b", "x", Some(0)),
r("c", "y", Some(0)),
r("d", "y", Some(0)),
];
assert_eq!(reference_output(&results), None, "2-and-2 has no majority");
let s = summarise(&results, None);
assert_eq!((s.identical, s.differ, s.failed), (0, 4, 0));
assert_eq!(s.line(), "4 differ");
}
#[test]
fn an_empty_or_wholly_failed_run_says_so() {
assert_eq!(reference_output(&[]), None);
let empty = summarise(&[], None);
assert_eq!(empty.line(), "no hosts", "zero hosts is not '0 identical'");
let all_bad = vec![r("a", "boom", Some(1)), r("b", "boom", None)];
assert_eq!(
reference_output(&all_bad),
None,
"no successful host means no normal"
);
assert_eq!(summarise(&all_bad, None).line(), "2 failed");
}
#[test]
fn a_host_that_never_reports_still_gets_a_tile() {
let hosts: Vec<String> = ["no-such-host-a.invalid", "no-such-host-b.invalid"]
.iter()
.map(|s| String::from(*s))
.collect();
let started = std::time::Instant::now();
let out = run_on_hosts(&hosts, "true", Duration::from_secs(1));
assert_eq!(out.len(), hosts.len(), "one tile per host, always");
assert_eq!(out[0].host, hosts[0]);
assert_eq!(out[1].host, hosts[1]);
for r in &out {
assert!(!r.ok(), "an unreachable host must not read as success");
assert!(!r.output.is_empty(), "a failed tile must say something");
}
assert!(
started.elapsed() < Duration::from_secs(12),
"hosts ran serially: {:?}",
started.elapsed()
);
let dup = vec![
String::from("no-such-host-a.invalid"),
String::from("no-such-host-a.invalid"),
];
let out = run_on_hosts(&dup, "true", Duration::from_secs(1));
assert_eq!(
out.len(),
2,
"a host requested twice must yield two tiles, not one"
);
assert!(out.iter().all(|r| r.host == dup[0]));
assert!(
out.iter().all(|r| r.output != "timed out"),
"a duplicate lost its real result: {out:?}"
);
}
#[test]
fn a_fleet_must_be_named_rather_than_defaulted() {
let known: Vec<String> = ["web-1", "web-2", "db-1"]
.iter()
.map(|s| String::from(*s))
.collect();
let p = |input: &str| {
parse_request_with_groups(input, &known, &std::collections::BTreeMap::new())
.map(|(h, c)| (h.iter().map(|s| s.as_str()).collect::<Vec<_>>(), c))
};
assert_eq!(
p("web-1: uname -r"),
Some((vec!["web-1"], String::from("uname -r")))
);
assert_eq!(
p("web-1,db-1: uptime"),
Some((vec!["web-1", "db-1"], String::from("uptime")))
);
assert_eq!(
p(" WEB-2 , db-1 : df -h "),
Some((vec!["web-2", "db-1"], String::from("df -h")))
);
assert_eq!(
p("*: uptime").map(|(h, _)| h.len()),
Some(3),
"a deliberate broadcast is still possible"
);
assert_eq!(p("db-1,db-1: uptime").map(|(h, _)| h.len()), Some(1));
for bad in [
"uname -r", ": uname -r", "web-1:", "web-1: ", "nosuchhost: uptime", "web-1,nosuchhost: up", "",
] {
assert_eq!(p(bad), None, "must refuse: {bad:?}");
}
}
#[test]
fn the_fleet_ssh_invocation_is_non_interactive() {
let args = fleet_ssh_args("db-1", "uname -r");
assert!(
args.contains(&String::from("-n")),
"without -n the remote command reads the terminal croft is using"
);
assert!(
args.windows(2)
.any(|w| w == ["-o", "BatchMode=yes"].map(String::from)),
"a host wanting a password must fail, not hang: {args:?}"
);
assert!(
args.windows(2)
.any(|w| w == ["-o", "StrictHostKeyChecking=yes"].map(String::from)),
"a fleet must not auto-trust first-contact keys: {args:?}"
);
assert!(
!args.iter().any(|a| a.contains("accept-new")),
"accept-new trusts an unseen key with nobody watching: {args:?}"
);
let tail: Vec<&String> = args.iter().skip_while(|a| *a != "--").collect();
assert_eq!(tail.len(), 2, "exactly one command argument: {args:?}");
assert_eq!(tail[1], "uname -r");
}
}