cluster_state.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. //! Cluster state — tracks which nodes are reachable and occupied,
  2. //! separate from the SSH probing that collects it. This split lets
  3. //! the cluster-selection logic be tested without real hardware.
  4. //!
  5. //! State collection (the "control" side) lives in [`ClusterState::probe`].
  6. //! Selection logic (the "state" side) lives on [`ClusterState`] methods.
  7. use anyhow::{Context, Result};
  8. use std::collections::{HashMap, HashSet};
  9. use tracing::info;
  10. use crate::config::{Cluster, Config, NcclConfig};
  11. use crate::ssh::run_ssh;
  12. /// Per-node state gathered during a probe.
  13. #[derive(Clone, Debug, Default)]
  14. pub struct NodeState {
  15. /// SSH connection succeeded (node is at least booted and reachable).
  16. pub reachable: bool,
  17. /// Node has at least one running sm121 container.
  18. pub occupied: bool,
  19. }
  20. /// Aggregate view of the cluster fleet — built by [`probe`].
  21. #[derive(Clone, Debug, Default)]
  22. pub struct ClusterState {
  23. /// Node name → state. Absence means the node was not probed.
  24. pub nodes: HashMap<String, NodeState>,
  25. }
  26. impl ClusterState {
  27. /// Probe all unique nodes across the config and collect their state.
  28. /// This is the only function that touches SSH (the "control" side).
  29. pub async fn probe(config: &Config) -> Self {
  30. let mut seen = HashSet::new();
  31. let mut handles = Vec::new();
  32. for cluster in &config.clusters {
  33. for node in &cluster.nodes {
  34. if seen.contains(&node.ssh_ip) {
  35. continue;
  36. }
  37. seen.insert(node.ssh_ip.clone());
  38. let config = config.clone();
  39. let node = node.clone();
  40. let name = node.name.clone();
  41. let cmd =
  42. "docker ps -q --filter label=sm121.cluster --format '{{.Names}}' | head -1"
  43. .to_string();
  44. handles.push(tokio::spawn(async move {
  45. (name, run_ssh(&config, &node, cmd, false).await)
  46. }));
  47. }
  48. }
  49. let mut nodes: HashMap<String, NodeState> = HashMap::new();
  50. for h in futures::future::join_all(handles).await {
  51. match h {
  52. Ok((name, Ok(output))) => {
  53. let occupied = !output.trim().is_empty();
  54. nodes.insert(
  55. name,
  56. NodeState {
  57. reachable: true,
  58. occupied,
  59. },
  60. );
  61. }
  62. Ok((name, Err(_))) => {
  63. // SSH failure → unreachable, cannot be deployed on
  64. nodes.insert(
  65. name,
  66. NodeState {
  67. reachable: false,
  68. occupied: false,
  69. },
  70. );
  71. }
  72. _ => {}
  73. }
  74. }
  75. Self { nodes }
  76. }
  77. /// Nodes in `cluster` that are reachable AND not occupied.
  78. pub fn free_nodes<'c>(&self, cluster: &'c Cluster) -> Vec<&'c crate::config::Node> {
  79. cluster.nodes.iter().filter(|n| self.free(n)).collect()
  80. }
  81. /// Number of free nodes in `cluster`.
  82. pub fn free_count(&self, cluster: &Cluster) -> u32 {
  83. self.free_nodes(cluster).len() as u32
  84. }
  85. /// Whether a single node is free (reachable + not occupied).
  86. fn free(&self, node: &crate::config::Node) -> bool {
  87. self.nodes
  88. .get(&node.name)
  89. .is_some_and(|s| s.reachable && !s.occupied)
  90. }
  91. }
  92. /// Select a cluster given the current cluster state.
  93. pub fn select_cluster<'c>(
  94. config: &'c Config,
  95. cluster_name: &str,
  96. required_nodes: Option<u32>,
  97. state: &ClusterState,
  98. ) -> Result<(Cluster, &'c NcclConfig)> {
  99. if cluster_name != "auto" {
  100. let cluster = crate::config::resolve_cluster_name(&config.clusters, cluster_name)?;
  101. let nccl = config
  102. .nccl
  103. .get(&cluster.name)
  104. .context("no NCCL config for cluster")?;
  105. return Ok((cluster.clone(), nccl));
  106. }
  107. let mut candidates: Vec<(&Cluster, &NcclConfig)> = config
  108. .clusters
  109. .iter()
  110. .filter_map(|c| Some((c, config.nccl.get(&c.name)?)))
  111. .filter(|(c, _)| required_nodes.is_none_or(|r| state.free_count(c) >= r))
  112. .collect();
  113. candidates.sort_by_key(|(c, _)| c.nodes.len());
  114. if let Some((cluster, nccl)) = candidates.into_iter().next() {
  115. let avail = state.free_count(cluster);
  116. info!(
  117. "{}",
  118. fluent_i18n::t!("cluster-selected", {
  119. "name" => cluster.name.to_string(),
  120. "nodes" => avail,
  121. })
  122. );
  123. return Ok((cluster.clone(), nccl));
  124. }
  125. anyhow::bail!(fluent_i18n::t!("cluster-auto-fail"));
  126. }
  127. #[cfg(test)]
  128. mod tests {
  129. use super::*;
  130. use crate::config::{Config, NcclConfig, Node};
  131. fn test_node(name: &str) -> Node {
  132. Node {
  133. name: name.to_string(),
  134. ssh_ip: format!("10.0.0.{}", name.chars().last().unwrap_or('0')),
  135. ib_ip: "10.0.1.1".to_string(),
  136. rank: 0,
  137. host_key: None,
  138. entity: None,
  139. }
  140. }
  141. fn test_cluster(name: &str, node_names: &[&str]) -> Cluster {
  142. Cluster {
  143. name: name.to_string(),
  144. master_ib_ip: "10.0.1.1".to_string(),
  145. nodes: node_names.iter().map(|n| test_node(n)).collect(),
  146. extra_entities: vec![],
  147. }
  148. }
  149. fn test_nccl() -> NcclConfig {
  150. NcclConfig {
  151. ib_hca: "r".to_string(),
  152. socket_ifname: "e".to_string(),
  153. ib_gid_index: 3,
  154. ib_disable: 0,
  155. gloo_socket_ifname: None,
  156. ucx_net_devices: None,
  157. nccl_cross_nic: None,
  158. nccl_proto: None,
  159. nccl_p2p_level: None,
  160. }
  161. }
  162. #[test]
  163. fn free_count_all_reachable() {
  164. let mut state = ClusterState::default();
  165. state.nodes.insert(
  166. "n1".into(),
  167. NodeState {
  168. reachable: true,
  169. occupied: false,
  170. },
  171. );
  172. state.nodes.insert(
  173. "n2".into(),
  174. NodeState {
  175. reachable: true,
  176. occupied: false,
  177. },
  178. );
  179. let c = test_cluster("c", &["n1", "n2"]);
  180. assert_eq!(state.free_count(&c), 2);
  181. }
  182. #[test]
  183. fn free_count_occupied_excluded() {
  184. let mut state = ClusterState::default();
  185. state.nodes.insert(
  186. "n1".into(),
  187. NodeState {
  188. reachable: true,
  189. occupied: true,
  190. },
  191. );
  192. state.nodes.insert(
  193. "n2".into(),
  194. NodeState {
  195. reachable: true,
  196. occupied: false,
  197. },
  198. );
  199. let c = test_cluster("c", &["n1", "n2"]);
  200. assert_eq!(state.free_count(&c), 1);
  201. }
  202. #[test]
  203. fn free_count_unreachable_excluded() {
  204. let mut state = ClusterState::default();
  205. state.nodes.insert(
  206. "n1".into(),
  207. NodeState {
  208. reachable: false,
  209. occupied: false,
  210. },
  211. );
  212. state.nodes.insert(
  213. "n2".into(),
  214. NodeState {
  215. reachable: true,
  216. occupied: false,
  217. },
  218. );
  219. let c = test_cluster("c", &["n1", "n2"]);
  220. assert_eq!(state.free_count(&c), 1);
  221. }
  222. #[test]
  223. fn free_count_missing_node_not_free() {
  224. let mut state = ClusterState::default();
  225. state.nodes.insert(
  226. "n1".into(),
  227. NodeState {
  228. reachable: true,
  229. occupied: false,
  230. },
  231. );
  232. // n2 not probed — absent is treated as not free
  233. let c = test_cluster("c", &["n1", "n2"]);
  234. assert_eq!(state.free_count(&c), 1);
  235. }
  236. #[test]
  237. fn select_smallest_with_enough_free() {
  238. let mut state = ClusterState::default();
  239. // big cluster: 4 nodes, 2 free
  240. state.nodes.insert(
  241. "n1".into(),
  242. NodeState {
  243. reachable: true,
  244. occupied: true,
  245. },
  246. );
  247. state.nodes.insert(
  248. "n2".into(),
  249. NodeState {
  250. reachable: true,
  251. occupied: true,
  252. },
  253. );
  254. state.nodes.insert(
  255. "n3".into(),
  256. NodeState {
  257. reachable: true,
  258. occupied: false,
  259. },
  260. );
  261. state.nodes.insert(
  262. "n4".into(),
  263. NodeState {
  264. reachable: true,
  265. occupied: false,
  266. },
  267. );
  268. // small cluster: 2 nodes, 1 free
  269. state.nodes.insert(
  270. "n5".into(),
  271. NodeState {
  272. reachable: true,
  273. occupied: true,
  274. },
  275. );
  276. state.nodes.insert(
  277. "n6".into(),
  278. NodeState {
  279. reachable: true,
  280. occupied: false,
  281. },
  282. );
  283. let cfg = Config {
  284. ssh_user: "u".to_string(),
  285. ssh_key_path: "/k".into(),
  286. clusters: vec![
  287. test_cluster("big", &["n1", "n2", "n3", "n4"]),
  288. test_cluster("small", &["n5", "n6"]),
  289. ],
  290. nccl: {
  291. let mut m = HashMap::new();
  292. m.insert("big".into(), test_nccl());
  293. m.insert("small".into(), test_nccl());
  294. m
  295. },
  296. hf_cache_dir: None,
  297. init_port: 25000,
  298. before_serve: HashMap::new(),
  299. exec_aliases: HashMap::new(),
  300. home_assistant: None,
  301. drop_caches: true,
  302. mount_aliases: HashMap::new(),
  303. global_mods_dir: None,
  304. };
  305. // Request 1 node — small cluster is smallest with free >= 1
  306. let (c, _) = select_cluster(&cfg, "auto", Some(1), &state).unwrap();
  307. assert_eq!(c.name, "small");
  308. // Request 2 nodes — only big cluster has 2 free
  309. let (c, _) = select_cluster(&cfg, "auto", Some(2), &state).unwrap();
  310. assert_eq!(c.name, "big");
  311. }
  312. #[test]
  313. fn select_cluster_not_found_errors() {
  314. let state = ClusterState::default();
  315. let cfg = Config {
  316. ssh_user: "u".to_string(),
  317. ssh_key_path: "/k".into(),
  318. clusters: vec![],
  319. nccl: HashMap::new(),
  320. hf_cache_dir: None,
  321. init_port: 25000,
  322. before_serve: HashMap::new(),
  323. exec_aliases: HashMap::new(),
  324. home_assistant: None,
  325. drop_caches: true,
  326. mount_aliases: HashMap::new(),
  327. global_mods_dir: None,
  328. };
  329. assert!(select_cluster(&cfg, "nonexistent", None, &state).is_err());
  330. }
  331. #[test]
  332. fn no_cluster_has_enough_free_errors() {
  333. let mut state = ClusterState::default();
  334. state.nodes.insert(
  335. "n1".into(),
  336. NodeState {
  337. reachable: true,
  338. occupied: true,
  339. },
  340. );
  341. let cfg = Config {
  342. ssh_user: "u".to_string(),
  343. ssh_key_path: "/k".into(),
  344. clusters: vec![test_cluster("c", &["n1"])],
  345. nccl: {
  346. let mut m = HashMap::new();
  347. m.insert("c".into(), test_nccl());
  348. m
  349. },
  350. hf_cache_dir: None,
  351. init_port: 25000,
  352. before_serve: HashMap::new(),
  353. exec_aliases: HashMap::new(),
  354. home_assistant: None,
  355. drop_caches: true,
  356. mount_aliases: HashMap::new(),
  357. global_mods_dir: None,
  358. };
  359. assert!(select_cluster(&cfg, "auto", Some(1), &state).is_err());
  360. }
  361. }