1use std::collections::{BTreeMap, HashSet};
11use std::time::Duration;
12
13use futures_util::future::join_all;
14
15use super::*;
16
17const PEER_WAIT: Duration = Duration::from_secs(3);
19
20#[derive(Debug, Clone, PartialEq)]
22pub(super) struct PeerReply {
23 pub host: String,
24 pub state: &'static str,
26 pub detail: Option<String>,
27 pub version: Option<String>,
28 pub as_of_ms: Option<u64>,
29 pub answer: Option<Value>,
31}
32
33impl PeerReply {
34 fn failed(host: &str, state: &'static str, detail: String) -> Self {
35 Self { host: host.to_string(), state, detail: Some(detail), version: None, as_of_ms: None, answer: None }
36 }
37}
38
39fn target_of(peer: &Value) -> String {
41 let text = |key: &str| peer.get(key).and_then(Value::as_str).unwrap_or_default().trim().to_string();
42 let (name, channel, install) = (text("hostname"), text("channel"), text("install"));
43 match (channel.is_empty(), install.is_empty()) {
44 (true, _) => name,
45 (false, true) => format!("{name}/{channel}"),
46 (false, false) => format!("{name}/{channel}/{install}"),
47 }
48}
49
50fn peers_of(local: &Value) -> Vec<(String, Value)> {
52 let mut seen = HashSet::new();
53 local
54 .get("peers")
55 .and_then(Value::as_array)
56 .into_iter()
57 .flatten()
58 .filter(|p| {
59 let id = p.get("instance_id").and_then(Value::as_str).filter(|i| !i.is_empty()).map_or_else(|| target_of(p), str::to_string);
60 !target_of(p).is_empty() && seen.insert(id)
61 })
62 .map(|p| (target_of(p), p.clone()))
63 .collect()
64}
65
66fn reply_of(host: &str, answer: &Value) -> PeerReply {
68 if answer["status"].as_str() == Some("done") {
69 let result = &answer["result"];
70 return PeerReply {
71 host: host.to_string(),
72 state: "ok",
73 detail: None,
74 version: result["version"].as_str().map(str::to_string),
75 as_of_ms: result["as_of_ms"].as_u64(),
76 answer: Some(result["answer"].clone()),
77 };
78 }
79 let problem = remote_op::explain_not_done(host, "agents.status", answer).unwrap_or_else(|| format!("{host} did not run agents.status"));
80 let state = match (answer["status"].as_str(), answer["refused_reason"].as_str()) {
81 (Some("refused"), Some("unknown_op" | "peer_cannot_do_remote_ops")) => "needs_upgrade",
82 (Some("refused"), _) => "refused",
83 _ => "unreachable",
84 };
85 PeerReply::failed(host, state, problem)
86}
87
88async fn ask(cx: &ToolCtx<'_>, host: &str, params: &Value, reason: &str) -> PeerReply {
89 match tokio::time::timeout(PEER_WAIT, remote_op::remote_op_call(cx, host, "agents.status", params.clone(), reason)).await {
90 Err(_) => PeerReply::failed(host, "unreachable", format!("{host} did not answer in {} seconds", PEER_WAIT.as_secs())),
91 Ok(Err(e)) => PeerReply::failed(host, "unreachable", format!("{e:#}")),
92 Ok(Ok(answer)) => reply_of(host, &answer),
93 }
94}
95
96pub(super) async fn across(cx: &ToolCtx<'_>, args: &Value, status: bool, host: &str) -> Result<String> {
98 let (local, targets) = if host.eq_ignore_ascii_case("all") {
99 let local = fleet::discover_value(args, status, true, cx).await?;
100 let targets = peers_of(&local);
101 (Some(local), targets)
102 } else {
103 (None, vec![(host.to_string(), Value::Null)])
104 };
105 let params = Value::Object(fleet::discovery_query(args, status).into_iter().map(|(k, v)| (k.to_string(), Value::String(v))).collect());
106 let reason = args.get("reason").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| format!("Agents {}", if status { "status" } else { "list" }));
107 let replies = join_all(targets.iter().map(|(name, _)| ask(cx, name, ¶ms, &reason))).await;
108 let peers: Vec<(PeerReply, Value)> = replies.into_iter().zip(targets.into_iter().map(|(_, lan)| lan)).collect();
109 let now_ms = agentmux_common::time::now_ms_u64();
110 let merged = if status { merge_status(local, &peers, now_ms) } else { merge_list(local, &peers, now_ms) };
111 Ok(serde_json::to_string_pretty(&merged).unwrap_or_else(|_| merged.to_string()))
112}
113
114fn tagged(mut row: Value, host: &str) -> Value {
115 if let Some(fields) = row.as_object_mut() {
116 fields.insert("host".to_string(), json!(host));
117 }
118 row
119}
120
121fn liveness_rows(host: &str, lan: &Value) -> Vec<Value> {
123 lan.get("agents")
124 .and_then(Value::as_array)
125 .into_iter()
126 .flatten()
127 .filter_map(Value::as_str)
128 .map(|name| {
129 let key = name.to_lowercase();
130 let mut row = json!({ "name": name, "host": host, "facts": "liveness_only" });
131 for (field, from) in [("state", "agent_status"), ("provider", "agent_providers"), ("kind", "agent_kinds")] {
132 if let Some(value) = lan.get(from).and_then(|m| m.get(key.as_str())).filter(|v| !v.is_null()) {
133 row[field] = value.clone();
134 }
135 }
136 row
137 })
138 .collect()
139}
140
141fn host_entry(reply: &PeerReply, lan: &Value, now_ms: u64) -> Value {
143 let version = reply.version.clone().or_else(|| lan.get("version").and_then(Value::as_str).filter(|v| !v.is_empty()).map(str::to_string));
144 let mut entry = json!({ "host": reply.host, "reachable": reply.state == "ok", "state": reply.state });
145 if let Some(v) = version {
146 entry["version"] = json!(v);
147 }
148 if let Some(at) = reply.as_of_ms {
149 entry["as_of_ms"] = json!(at);
150 entry["age_ms"] = json!(now_ms.saturating_sub(at));
151 }
152 if let Some(why) = &reply.detail {
153 entry["error"] = json!(why);
154 }
155 entry
156}
157
158fn this_host_entry(local: &Value, now_ms: u64) -> Option<(String, Value)> {
160 let name = local.pointer("/host/hostname").or_else(|| local.get("host")).and_then(Value::as_str)?.to_string();
161 let version = local.pointer("/host/version").cloned();
162 let mut entry = json!({ "host": name, "reachable": true, "state": "ok", "this_machine": true, "as_of_ms": now_ms, "age_ms": 0 });
163 if let Some(v) = version.filter(|v| v.is_string()) {
164 entry["version"] = v;
165 }
166 Some((name, entry))
167}
168
169pub(super) fn merge_list(local: Option<Value>, peers: &[(PeerReply, Value)], now_ms: u64) -> Value {
171 let mut body = local.unwrap_or_else(|| json!({ "host": {} }));
172 let (mut hosts, mut rows) = (Vec::new(), Vec::new());
173 let mut total = 0u64;
174 if let Some((name, entry)) = this_host_entry(&body, now_ms) {
175 let own = body.pointer("/host/agents").and_then(Value::as_array).cloned().unwrap_or_default();
176 total += body.pointer("/host/page/total").and_then(Value::as_u64).unwrap_or(own.len() as u64);
177 rows.extend(own.into_iter().map(|r| tagged(r, &name)));
178 hosts.push(entry);
179 }
180 for (reply, lan) in peers {
181 match reply.answer.as_ref().filter(|_| reply.state == "ok") {
182 Some(answer) => {
183 let theirs = answer.get("agents").and_then(Value::as_array).cloned().unwrap_or_default();
184 total += answer.pointer("/page/total").and_then(Value::as_u64).unwrap_or(theirs.len() as u64);
185 rows.extend(theirs.into_iter().map(|r| tagged(r, &reply.host)));
186 }
187 None => {
188 let listed = liveness_rows(&reply.host, lan);
189 total += listed.len() as u64;
190 rows.extend(listed);
191 }
192 }
193 hosts.push(host_entry(reply, lan, now_ms));
194 }
195 body["host"]["page"] = json!({ "total": total, "returned": rows.len(), "note": "limit and offset apply to each machine" });
196 body["host"]["agents"] = Value::Array(rows);
197 body["hosts"] = Value::Array(hosts);
198 if let Some(fields) = body.as_object_mut() {
199 fields.remove("peers");
200 }
201 body
202}
203
204fn line_with_host(line: &str, host: &str) -> String {
206 match line.split_once(" | ") {
207 Some((name, rest)) => format!("{name} | {host} | {rest}"),
208 None => format!("{line} | {host}"),
209 }
210}
211
212fn add_counts(into: &mut BTreeMap<String, u64>, counts: Option<&Value>) {
213 for (key, n) in counts.and_then(Value::as_object).into_iter().flatten() {
214 *into.entry(key.clone()).or_default() += n.as_u64().unwrap_or(0);
215 }
216}
217
218#[derive(Default)]
220struct Tally {
221 lines: Vec<String>,
222 by_state: BTreeMap<String, u64>,
223 by_model: BTreeMap<String, u64>,
224 by_host: BTreeMap<String, u64>,
225 groups: BTreeMap<String, Vec<String>>,
226 total: u64,
227 group_by: Option<String>,
228}
229
230impl Tally {
231 fn take(&mut self, host: &str, status: &Value) {
233 let theirs: Vec<&str> = status.get("lines").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect();
234 self.total += status.get("total").and_then(Value::as_u64).unwrap_or(theirs.len() as u64);
235 self.by_host.insert(host.to_string(), theirs.len() as u64);
236 self.lines.extend(theirs.iter().map(|l| line_with_host(l, host)));
237 add_counts(&mut self.by_state, status.pointer("/counts/by_state"));
238 add_counts(&mut self.by_model, status.pointer("/counts/by_model"));
239 for group in status.get("groups").and_then(Value::as_array).into_iter().flatten() {
240 let key = group.get("key").and_then(Value::as_str).unwrap_or("unknown").to_string();
241 let members = group.get("agents").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str);
242 self.groups.entry(key).or_default().extend(members.map(|m| format!("{m}@{host}")));
243 }
244 if self.group_by.is_none() {
245 self.group_by = status.get("group_by").and_then(Value::as_str).map(str::to_string);
246 }
247 }
248
249 fn liveness(&mut self, host: &str, lan: &Value) {
251 let listed = liveness_rows(host, lan);
252 self.total += listed.len() as u64;
253 self.by_host.insert(host.to_string(), listed.len() as u64);
254 self.lines.extend(listed.iter().map(|r| {
255 let state = r.get("state").map_or_else(|| "state unknown".to_string(), |s| s.as_str().map_or_else(|| s.to_string(), str::to_string));
256 format!("{} | {host} | {state} (liveness only)", r["name"].as_str().unwrap_or_default())
257 }));
258 }
259}
260
261pub(super) fn merge_status(local: Option<Value>, peers: &[(PeerReply, Value)], now_ms: u64) -> Value {
263 let (mut tally, mut hosts) = (Tally::default(), Vec::new());
264 if let Some(local) = &local {
265 if let Some((name, entry)) = this_host_entry(local, now_ms) {
266 tally.take(&name, local);
267 hosts.push(entry);
268 }
269 }
270 for (reply, lan) in peers {
271 match reply.answer.as_ref().filter(|_| reply.state == "ok") {
272 Some(status) => tally.take(&reply.host, status),
273 None => tally.liveness(&reply.host, lan),
274 }
275 hosts.push(host_entry(reply, lan, now_ms));
276 }
277 let mut out = json!({
278 "total": tally.total,
279 "returned": tally.lines.len(),
280 "lines": tally.lines,
281 "counts": { "by_state": tally.by_state, "by_model": tally.by_model, "by_host": tally.by_host },
282 "hosts": hosts,
283 });
284 if let Some(g) = tally.group_by {
285 out["group_by"] = json!(g);
286 out["groups"] = json!(tally.groups.into_iter().map(|(k, v)| json!({ "key": k, "count": v.len(), "agents": v })).collect::<Vec<_>>());
287 }
288 out
289}
290
291#[cfg(test)]
292#[path = "agents_hosts_tests.rs"]
293mod tests;