health.rs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. //! Cluster health — shows node status, running containers, and recipe
  2. //! deployments across all clusters.
  3. use crate::config::{Cluster, Config};
  4. use crate::home_assistant::Client as HaClient;
  5. use crate::ssh::run_ssh;
  6. use anyhow::Result;
  7. use std::collections::HashMap;
  8. use tracing::warn;
  9. /// Per-node result from the parallel SSH sweep.
  10. struct NodeHealth {
  11. name: String,
  12. ib_ip: String,
  13. online: bool,
  14. containers: Vec<String>,
  15. net_up: bool,
  16. net_details: Vec<String>,
  17. }
  18. /// Checks Docker health — shows node status and containers belonging to this cluster.
  19. pub async fn health_check(config: &Config, cluster: &Cluster, dry_run: bool) -> Result<()> {
  20. let nodes = &cluster.nodes;
  21. let cluster_label = &cluster.name;
  22. let nccl = config.nccl.get(cluster_label);
  23. // Check HA cluster-level entities (switch, etc.) in parallel.
  24. let ha_handle = if let Some(ref ha_cfg) = config.home_assistant {
  25. let ha = HaClient::new(ha_cfg).ok();
  26. let entities = cluster.extra_entities.clone();
  27. Some(crate::locale::spawn_with_locale(async move {
  28. let client = ha.as_ref()?;
  29. for e in &entities {
  30. match client.get_state(e).await {
  31. Some(ref s) if s == "on" => continue,
  32. _ => return Some(false),
  33. }
  34. }
  35. Some(true)
  36. }))
  37. } else {
  38. None
  39. };
  40. // Build the network check command snippet for this cluster's NCCL interfaces.
  41. let net_script = nccl.as_ref().and_then(|n| {
  42. let socket = &n.socket_ifname;
  43. // Validate socket interface name to prevent command injection
  44. // Must be a valid network interface name: alphanumeric, dots, underscores, hyphens
  45. let valid = socket.chars().all(|c| c.is_alphanumeric() || ".-_".contains(c));
  46. if !valid {
  47. return None;
  48. }
  49. Some(format!(
  50. "echo '---NET---'; echo -n 'socket:' && (ip -o link show dev {socket} 2>/dev/null | grep -qi 'state UP' && echo UP || echo DOWN); echo '---END---'"
  51. ))
  52. });
  53. // SSH into each node in parallel.
  54. let mut handles = Vec::new();
  55. for node in nodes {
  56. let config = config.clone();
  57. let node = node.clone();
  58. let name = node.name.clone();
  59. let ib_ip = node.effective_ib_ip().to_string();
  60. let cl = cluster_label.clone();
  61. let ns = net_script.clone();
  62. let docker_cmd = format!(
  63. "docker ps --filter label=sm121.cluster={cl} \
  64. --format '{{{{.Names}}}}\t{{{{.Status}}}}\t{{{{.Image}}}}' 2>&1"
  65. );
  66. let cmd = if let Some(ref script) = ns {
  67. format!("{docker_cmd}; {script}")
  68. } else {
  69. docker_cmd
  70. };
  71. handles.push(crate::locale::spawn_with_locale(async move {
  72. let result = run_ssh(&config, &node, cmd, dry_run).await;
  73. (name, ib_ip, result)
  74. }));
  75. }
  76. // Collect SSH node results.
  77. let mut node_health: Vec<NodeHealth> = Vec::new();
  78. for h in futures::future::join_all(handles).await {
  79. match h {
  80. Ok((name, ib_ip, Ok(output))) => {
  81. let mut net_up = true;
  82. let mut net_details = Vec::new();
  83. let mut lines: Vec<String> = Vec::new();
  84. let mut in_net = false;
  85. for line in output.lines() {
  86. let line = line.trim();
  87. if line.is_empty()
  88. || line.contains("permission denied")
  89. || line.starts_with("docker:")
  90. {
  91. continue;
  92. }
  93. if line == "---NET---" {
  94. in_net = true;
  95. continue;
  96. }
  97. if line == "---END---" {
  98. in_net = false;
  99. continue;
  100. }
  101. if in_net {
  102. net_details.push(line.to_string());
  103. if line.ends_with("DOWN")
  104. || line.ends_with("missing")
  105. || line.ends_with("error")
  106. {
  107. net_up = false;
  108. }
  109. continue;
  110. }
  111. lines.push(line.to_string());
  112. }
  113. node_health.push(NodeHealth {
  114. name,
  115. ib_ip,
  116. online: true,
  117. containers: lines,
  118. net_up,
  119. net_details,
  120. });
  121. }
  122. Ok((name, ib_ip, Err(_))) => {
  123. node_health.push(NodeHealth {
  124. name,
  125. ib_ip,
  126. online: false,
  127. containers: vec![],
  128. net_up: false,
  129. net_details: vec![],
  130. });
  131. }
  132. Err(join_err) => warn!(
  133. "{}",
  134. fluent_i18n::t!("health-task-join", { "error" => &join_err.to_string() })
  135. ),
  136. }
  137. }
  138. // Resolve HA result.
  139. let ha_ok = match ha_handle {
  140. Some(h) => h.await.unwrap_or(Some(true)).unwrap_or(true),
  141. None => true,
  142. };
  143. let total = nodes.len();
  144. let online = node_health.iter().filter(|n| n.online).count();
  145. let offline = total - online;
  146. let container_count: usize = node_health.iter().map(|n| n.containers.len()).sum();
  147. let net_ok = node_health.iter().all(|n| !n.online || n.net_up);
  148. print!(
  149. "{}",
  150. fluent_i18n::t!("health-cluster-header", { "name" => &cluster_label, "nodes" => total })
  151. );
  152. if !ha_ok && !cluster.extra_entities.is_empty() {
  153. print!(" {}", fluent_i18n::t!("health-switch-off"));
  154. } else if !net_ok {
  155. print!(" {}", fluent_i18n::t!("health-interface-down"));
  156. } else if online == total {
  157. print!(" {}", fluent_i18n::t!("health-all-online"));
  158. } else {
  159. print!(
  160. "{}",
  161. fluent_i18n::t!("health-partial-online", { "online" => online, "offline" => offline })
  162. );
  163. }
  164. if container_count > 0 {
  165. println!(
  166. "{}",
  167. fluent_i18n::t!("health-container-count", { "count" => container_count })
  168. );
  169. } else {
  170. print!("{}", fluent_i18n::t!("health-no-containers-inline"));
  171. }
  172. for nh in &node_health {
  173. if !nh.online {
  174. println!(
  175. "{}",
  176. fluent_i18n::t!("health-node-offline", { "name" => &nh.name, "ip" => &nh.ib_ip })
  177. );
  178. continue;
  179. }
  180. let net_status = if !nh.net_up {
  181. fluent_i18n::t!("health-net-status", { "details" => nh.net_details.join(", ") })
  182. } else {
  183. String::new()
  184. };
  185. if nh.containers.is_empty() {
  186. println!(
  187. "{}",
  188. fluent_i18n::t!("health-node-idle", { "name" => &nh.name, "ip" => &nh.ib_ip, "net" => &net_status })
  189. );
  190. } else {
  191. println!(
  192. "{}",
  193. fluent_i18n::t!("health-node-online", { "name" => &nh.name, "ip" => &nh.ib_ip, "net" => &net_status })
  194. );
  195. for line in &nh.containers {
  196. println!(" {line}");
  197. }
  198. }
  199. }
  200. Ok(())
  201. }
  202. /// Quick overview — recipes running on each cluster.
  203. pub async fn health_summary(config: &Config) -> Result<()> {
  204. let mut seen = std::collections::HashSet::new();
  205. let mut handles = Vec::new();
  206. for cluster in &config.clusters {
  207. for node in &cluster.nodes {
  208. if seen.contains(&node.ssh_ip) {
  209. continue;
  210. }
  211. seen.insert(node.ssh_ip.clone());
  212. let config = config.clone();
  213. let node = node.clone();
  214. let name = node.name.clone();
  215. let cmd = "docker ps --filter label=sm121.recipe \
  216. --format '{{.Label \"sm121.recipe\"}}|{{.Label \"sm121.cluster\"}}'"
  217. .to_string();
  218. handles.push(crate::locale::spawn_with_locale(async move {
  219. let out = run_ssh(&config, &node, cmd, false)
  220. .await
  221. .unwrap_or_default();
  222. (name, out)
  223. }));
  224. }
  225. }
  226. let mut recipe_nodes: HashMap<String, std::collections::HashSet<String>> = HashMap::new();
  227. for h in futures::future::join_all(handles).await {
  228. let (node_name, output) = h.unwrap_or_default();
  229. for line in output.lines() {
  230. let line = line.trim();
  231. if line.is_empty() {
  232. continue;
  233. }
  234. let mut parts = line.splitn(2, '|');
  235. let recipe = parts.next().unwrap_or("").to_string();
  236. if recipe.is_empty() {
  237. continue;
  238. }
  239. recipe_nodes
  240. .entry(recipe)
  241. .or_default()
  242. .insert(node_name.clone());
  243. }
  244. }
  245. if recipe_nodes.is_empty() {
  246. println!("\n{}", fluent_i18n::t!("health-no-recipes"));
  247. return Ok(());
  248. }
  249. println!("\n{}", fluent_i18n::t!("health-running-recipes"));
  250. for (recipe, nodes) in &recipe_nodes {
  251. let mut sorted: Vec<_> = nodes.iter().collect();
  252. sorted.sort();
  253. let node_list: Vec<&str> = sorted.iter().map(|s| s.as_str()).collect();
  254. println!(
  255. "{}",
  256. fluent_i18n::t!("health-recipe-line", { "recipe" => recipe, "nodes" => node_list.len(), "list" => &node_list.join(", ") })
  257. );
  258. }
  259. Ok(())
  260. }