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>,
pub elapsed: Duration,
}
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) = split_request(input)?;
let command = command.trim();
if command.is_empty() {
return None;
}
let spec = spec.trim();
if spec == "*" {
let hosts: Vec<&String> = known.iter().filter(|k| !is_local_target(k)).collect();
return Some((hosts, 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 split_request(input: &str) -> Option<(&str, &str)> {
let mut from = 0;
while let Some(i) = input[from..].find(':').map(|i| i + from) {
let token_start = input[..i].rfind(',').map_or(0, |c| c + 1);
if input[token_start..i].trim() == "docker" {
from = i + 1;
continue;
}
return Some((&input[..i], &input[i + 1..]));
}
None
}
pub fn is_local_target(target: &str) -> bool {
target == "localhost"
|| target
.strip_prefix("docker:")
.is_some_and(|n| !n.is_empty())
}
pub fn local_targets_in(
request: &str,
groups: &std::collections::BTreeMap<String, Vec<String>>,
) -> Vec<String> {
let mut out = vec![String::from("localhost")];
let spec = split_request(request).map_or("", |(spec, _)| spec);
let named = spec
.split(',')
.chain(groups.values().flatten().map(String::as_str))
.map(str::trim)
.filter(|n| n.strip_prefix("docker:").is_some_and(|c| !c.is_empty()));
for n in named {
if !out.iter().any(|o| o == n) {
out.push(n.to_string());
}
}
out
}
pub fn target_command(target: &str, command: &str) -> (String, Vec<String>) {
if target == "localhost" {
return (
String::from("sh"),
vec![String::from("-c"), command.to_string()],
);
}
if let Some(name) = target.strip_prefix("docker:").filter(|n| !n.is_empty()) {
return (
String::from("docker"),
["exec", name, "sh", "-c", command]
.into_iter()
.map(String::from)
.collect(),
);
}
(String::from("ssh"), fleet_ssh_args(target, command))
}
pub fn differing_lines(reference: &str, output: &str) -> Vec<String> {
use crate::widgets::diff::{DiffRow, build_diff_rows};
let old: Vec<String> = reference.lines().map(str::to_string).collect();
let new: Vec<String> = output.lines().map(str::to_string).collect();
let mut out = Vec::new();
for row in build_diff_rows(&old, &new) {
match row {
DiffRow::Equal { .. } => {}
DiffRow::Removed { left } => out.push(format!("- {}", old[left])),
DiffRow::Added { right } => out.push(format!("+ {}", new[right])),
DiffRow::Replaced { left, right } => {
out.push(format!("- {}", old[left]));
out.push(format!("+ {}", new[right]));
}
}
}
out
}
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,
elapsed: Duration::ZERO,
})
})
.collect()
}
fn run_one(host: &str, command: &str, timeout: Duration) -> HostResult {
let started = std::time::Instant::now();
let mut result = run_one_untimed(host, command, timeout);
result.elapsed = started.elapsed();
result
}
fn run_one_untimed(host: &str, command: &str, timeout: Duration) -> HostResult {
let (program, mut args) = target_command(host, command);
if program == "ssh" {
let secs = timeout.as_secs().max(1);
let mut with_timeout = vec![String::from("-o"), format!("ConnectTimeout={secs}")];
with_timeout.append(&mut args);
args = with_timeout;
}
let mut cmd = std::process::Command::new(&program);
cmd.args(&args);
run_killable(cmd, &program, host, timeout)
}
fn run_killable(
mut cmd: std::process::Command,
program: &str,
host: &str,
timeout: Duration,
) -> HostResult {
use std::io::Read;
let result = |output: String, exit: Option<i32>| HostResult {
host: host.to_string(),
output,
exit,
elapsed: Duration::ZERO,
};
let spawned = cmd
.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 result(format!("could not run {program}: {e}"), None),
};
let drain = |pipe: Option<Box<dyn Read + Send>>| {
let buf = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
let sink = buf.clone();
std::thread::spawn(move || {
if let Some(mut p) = pipe {
let mut chunk = [0u8; 8192];
while let Ok(n) = p.read(&mut chunk) {
if n == 0 {
break;
}
if let Ok(mut b) = sink.lock() {
b.extend_from_slice(&chunk[..n]);
}
}
}
let _ = done_tx.send(());
});
(buf, done_rx)
};
let stdout = drain(
child
.stdout
.take()
.map(|p| Box::new(p) as Box<dyn Read + Send>),
);
let stderr = drain(
child
.stderr
.take()
.map(|p| Box::new(p) as Box<dyn Read + Send>),
);
let deadline = std::time::Instant::now() + timeout;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) if std::time::Instant::now() >= deadline => {
let _ = child.kill();
let _ = child.wait();
return result(String::from("timed out"), None);
}
Ok(None) => std::thread::sleep(Duration::from_millis(25)),
Err(e) => return result(format!("could not wait on {program}: {e}"), None),
}
};
let grace = Duration::from_millis(500);
let take = |(buf, done): (
std::sync::Arc<std::sync::Mutex<Vec<u8>>>,
std::sync::mpsc::Receiver<()>,
)| {
let _ = done.recv_timeout(grace);
buf.lock().map(|b| b.clone()).unwrap_or_default()
};
let out = take(stdout);
let err = take(stderr);
let mut text = String::from_utf8_lossy(&out).trim_end().to_string();
let err = String::from_utf8_lossy(&err);
let err = err.trim_end();
if !err.is_empty() {
if !text.is_empty() {
text.push('\n');
}
text.push_str(err);
}
result(text, status.code())
}
#[cfg(test)]
mod tests {
#[test]
fn local_targets_are_localhost_and_docker_containers() {
assert!(is_local_target("localhost"));
assert!(is_local_target("docker:web"));
assert!(!is_local_target("docker:"), "a container needs a name");
assert!(!is_local_target("db-1"));
assert!(!is_local_target("localhost.example.com"));
}
#[test]
fn each_target_kind_gets_its_own_runner() {
let (p, a) = target_command("localhost", "uname -r");
assert_eq!(
(p.as_str(), a),
("sh", vec!["-c".to_string(), "uname -r".to_string()])
);
let (p, a) = target_command("docker:web", "uname -r");
assert_eq!(
(p.as_str(), a),
(
"docker",
vec!["exec", "web", "sh", "-c", "uname -r"]
.into_iter()
.map(String::from)
.collect()
)
);
let (p, a) = target_command("db-1", "uname -r");
assert_eq!((p.as_str(), a), ("ssh", fleet_ssh_args("db-1", "uname -r")));
}
#[test]
fn local_targets_are_what_the_request_or_a_group_names() {
let mut groups = std::collections::BTreeMap::new();
groups.insert(
String::from("web"),
vec![String::from("docker:front"), String::from("db-1")],
);
assert_eq!(
local_targets_in("docker:api, localhost: uptime", &groups),
vec!["localhost", "docker:api", "docker:front"]
);
assert_eq!(
local_targets_in("db-1: uptime", &std::collections::BTreeMap::new()),
vec!["localhost"]
);
assert_eq!(
local_targets_in("docker:: uptime", &std::collections::BTreeMap::new()),
vec!["localhost"],
"an empty container name is not a target"
);
}
#[test]
fn star_means_every_ssh_host_not_local_targets() {
let known: Vec<String> = ["db-1", "localhost", "docker:web", "db-2"]
.into_iter()
.map(String::from)
.collect();
let (hosts, _) =
parse_request_with_groups("*: uptime", &known, &std::collections::BTreeMap::new())
.unwrap();
let names: Vec<&str> = hosts.iter().map(|h| h.as_str()).collect();
assert_eq!(names, vec!["db-1", "db-2"]);
let (hosts, _) = parse_request_with_groups(
"localhost,docker:web: uptime",
&known,
&std::collections::BTreeMap::new(),
)
.unwrap();
assert_eq!(hosts.len(), 2);
}
#[test]
fn the_separator_skips_a_docker_prefix() {
assert_eq!(split_request("db-1: uptime"), Some(("db-1", " uptime")));
assert_eq!(
split_request("docker:web: uname -r"),
Some(("docker:web", " uname -r"))
);
assert_eq!(
split_request("db-1, docker:web ,localhost: a:b"),
Some(("db-1, docker:web ,localhost", " a:b")),
"a colon inside the command is the command's"
);
assert_eq!(split_request("docker:web"), None, "no command");
}
#[test]
fn differing_lines_show_both_what_is_extra_and_what_is_missing() {
let reference = "Linux\n6.8.0-45\nx86_64\n";
assert!(differing_lines(reference, reference).is_empty());
assert_eq!(
differing_lines(reference, "Linux\n6.8.0-31\nx86_64\n"),
vec!["- 6.8.0-45", "+ 6.8.0-31"]
);
assert_eq!(
differing_lines(reference, "Linux\n6.8.0-45\nx86_64\nextra\n"),
vec!["+ extra"]
);
assert_eq!(differing_lines("a\nb\nc\n", "a\nc\n"), vec!["- b"]);
}
#[test]
fn localhost_runs_locally_and_is_timed() {
let r = run_on_hosts(
&["localhost".to_string()],
"printf hi",
Duration::from_secs(10),
);
assert_eq!(r.len(), 1);
assert_eq!(r[0].output, "hi");
assert_eq!(r[0].exit, Some(0));
assert!(
r[0].elapsed > Duration::ZERO,
"the tile shows how long it took"
);
}
use super::*;
#[test]
fn output_is_kept_when_a_background_child_holds_the_pipe() {
let mut cmd = std::process::Command::new("sh");
cmd.args(["-c", "echo started; sleep 30 &"]);
let r = run_killable(cmd, "sh", "h", Duration::from_secs(20));
assert_eq!(r.exit, Some(0));
assert_eq!(r.output, "started");
}
#[test]
fn a_command_printing_more_than_a_pipe_buffer_completes() {
let mut cmd = std::process::Command::new("sh");
cmd.args(["-c", "head -c 300000 /dev/zero | tr '\\0' x; echo oops >&2"]);
let r = run_killable(cmd, "sh", "h", Duration::from_secs(20));
assert_eq!(
r.exit,
Some(0),
"{}",
&r.output[r.output.len().saturating_sub(80)..]
);
assert!(r.output.starts_with("xxxx"));
assert!(r.output.ends_with("\noops"));
assert_eq!(r.output.len(), 300_000 + "\noops".len());
}
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,
elapsed: Duration::ZERO,
}
}
#[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");
}
}