health.rs 8.3 KB

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