config.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. pub use crate::pre_serve::{BeforeServeTable, ModsTable, OnFailure, PreServeCommand};
  2. use anyhow::{Context, Result};
  3. use serde::Deserialize;
  4. use std::collections::HashMap;
  5. use tracing::info;
  6. #[derive(Clone, Deserialize)]
  7. pub struct Node {
  8. pub name: String,
  9. pub ssh_ip: String,
  10. pub ib_ip: String,
  11. pub rank: u32,
  12. #[serde(default)]
  13. pub host_key: Option<String>,
  14. #[serde(default)]
  15. pub entity: Option<String>,
  16. }
  17. #[derive(Clone, Deserialize)]
  18. pub struct NcclConfig {
  19. pub ib_hca: String,
  20. pub socket_ifname: String,
  21. pub ib_gid_index: u32,
  22. pub ib_disable: u32,
  23. }
  24. #[derive(Clone, Deserialize)]
  25. pub struct Cluster {
  26. pub name: String,
  27. pub master_ib_ip: String,
  28. pub nodes: Vec<Node>,
  29. /// Extra Home Assistant switches to toggle alongside the nodes during power on/off.
  30. #[serde(default)]
  31. pub extra_entities: Vec<String>,
  32. }
  33. /// Top-level config (clusters + per-cluster pre-serve commands).
  34. #[derive(Clone, Deserialize)]
  35. pub struct Config {
  36. pub ssh_user: String,
  37. pub ssh_key_path: std::path::PathBuf,
  38. pub clusters: Vec<Cluster>,
  39. #[serde(default)]
  40. pub nccl: HashMap<String, NcclConfig>,
  41. #[serde(default)]
  42. pub hf_cache_dir: Option<String>,
  43. /// TCP port for cluster init (vLLM/SGLang)
  44. #[serde(default = "default_init_port")]
  45. pub init_port: u16,
  46. /// Per-cluster pre-serve commands, command aliases, HA config
  47. #[serde(default)]
  48. pub before_serve: HashMap<String, BeforeServeTable>, // <-- move here
  49. #[serde(default)]
  50. pub exec_aliases: HashMap<String, String>,
  51. #[serde(default)]
  52. pub home_assistant: Option<HomeAssistantConfig>,
  53. /// Global mods directory — script files merged with recipe mods/ into
  54. /// the container's /mods/. Recipe-level [mods] commands explicitly
  55. /// reference files from either source via /mods/<file>.
  56. #[serde(default)]
  57. pub global_mods_dir: Option<std::path::PathBuf>,
  58. }
  59. /// Home Assistant config for `power on`/`power off`.
  60. #[derive(Clone, Deserialize)]
  61. pub struct HomeAssistantConfig {
  62. pub url: String,
  63. pub token: String,
  64. #[serde(default = "default_shutdown_delay")]
  65. pub shutdown_delay_seconds: u64,
  66. }
  67. fn default_shutdown_delay() -> u64 {
  68. 30
  69. }
  70. fn default_init_port() -> u16 {
  71. 25000
  72. }
  73. fn default_port() -> u16 {
  74. 30000
  75. }
  76. impl Config {
  77. pub fn resolved_hf_cache_dir(&self) -> std::path::PathBuf {
  78. if let Some(ref dir) = self.hf_cache_dir {
  79. return std::path::PathBuf::from(dir);
  80. }
  81. let home = if self.ssh_user == "root" {
  82. "/root"
  83. } else {
  84. // Safe to return a temporary String; PathBuf::from copies it
  85. return std::path::PathBuf::from(format!("/home/{}/.cache/huggingface", self.ssh_user));
  86. };
  87. std::path::PathBuf::from(format!("{}/.cache/huggingface", home))
  88. }
  89. }
  90. #[derive(Clone, Deserialize)]
  91. pub struct Recipe {
  92. #[serde(default = "default_engine")]
  93. pub engine: String,
  94. pub name: String,
  95. #[serde(default)]
  96. pub docker_image: String,
  97. #[serde(default)]
  98. pub model: String,
  99. #[serde(default = "default_port")]
  100. pub port: u16,
  101. #[serde(default)]
  102. pub required_nodes: Option<u32>,
  103. #[serde(default)]
  104. pub pipeline_parallel_size: Option<u32>,
  105. #[serde(default = "default_tensor_parallel_size")]
  106. pub tensor_parallel_size: u32,
  107. #[serde(default)]
  108. pub args: Vec<String>,
  109. #[serde(default)]
  110. pub env: HashMap<String, String>,
  111. #[serde(default)]
  112. pub cluster: Option<String>,
  113. #[serde(default)]
  114. pub entrypoint: Vec<String>,
  115. #[serde(default = "default_distributed_backend")]
  116. pub distributed_backend: String,
  117. /// Shared memory size for the container (e.g. "64gb"). Omitted when empty.
  118. #[serde(default = "default_shm_size")]
  119. pub shm_size: String,
  120. /// Recipe-level pre-serve commands (appended after cluster-level).
  121. #[serde(default)]
  122. pub before_serve: Vec<PreServeCommand>,
  123. /// Mods: commands that run *inside* the container via entrypoint wrapping
  124. /// before the engine process starts. Requires `entrypoint` to be set.
  125. #[serde(default)]
  126. pub mods: ModsTable,
  127. }
  128. /// Resolves cluster by exact name, then unique prefix. Errors if none or ambiguous.
  129. fn resolve_cluster_name<'a>(clusters: &'a [Cluster], name: &str) -> Result<&'a Cluster> {
  130. if let Some(c) = clusters.iter().find(|c| c.name == name) {
  131. return Ok(c);
  132. }
  133. let matches: Vec<&Cluster> = clusters
  134. .iter()
  135. .filter(|c| c.name.starts_with(name))
  136. .collect();
  137. match matches.len() {
  138. 0 => anyhow::bail!(fluent_i18n::t!("cluster-not-found", { "name" => name.to_string() })),
  139. 1 => Ok(matches[0]),
  140. n => anyhow::bail!(
  141. "Pref '{}' matches {} clusters: {}",
  142. name,
  143. n,
  144. matches
  145. .iter()
  146. .map(|c| c.name.as_str())
  147. .collect::<Vec<_>>()
  148. .join(", ")
  149. ),
  150. }
  151. }
  152. fn default_engine() -> String {
  153. "vllm".to_string()
  154. }
  155. fn default_distributed_backend() -> String {
  156. "mp".to_string()
  157. }
  158. fn default_shm_size() -> String {
  159. String::new()
  160. }
  161. fn default_tensor_parallel_size() -> u32 {
  162. 1
  163. }
  164. /// Selects a cluster + NCCL config by name or auto-picks the smallest
  165. /// cluster with NCCL config satisfying `required_nodes`.
  166. pub fn select_cluster<'c>(
  167. config: &'c Config,
  168. cluster_name: &str,
  169. required_nodes: Option<u32>,
  170. ) -> Result<(Cluster, &'c NcclConfig)> {
  171. if cluster_name != "auto" {
  172. let cluster = resolve_cluster_name(&config.clusters, cluster_name)?;
  173. let nccl = config
  174. .nccl
  175. .get(&cluster.name)
  176. .context(fluent_i18n::t!("nccl-config-missing"))?;
  177. return Ok((cluster.clone(), nccl));
  178. }
  179. let mut candidates: Vec<(&Cluster, &NcclConfig)> = config
  180. .clusters
  181. .iter()
  182. .filter_map(|c| Some((c, config.nccl.get(&c.name)?)))
  183. .filter(|(c, _)| required_nodes.is_none_or(|r| (c.nodes.len() as u32) == r))
  184. .collect();
  185. candidates.sort_by_key(|(c, _)| c.nodes.len());
  186. if let Some((cluster, nccl)) = candidates.into_iter().next() {
  187. info!(
  188. "{}",
  189. fluent_i18n::t!("cluster-selected", {
  190. "name" => cluster.name.to_string(),
  191. "nodes" => cluster.nodes.len(),
  192. })
  193. );
  194. return Ok((cluster.clone(), nccl));
  195. }
  196. anyhow::bail!(fluent_i18n::t!("cluster-auto-fail"));
  197. }
  198. /// Looks up a cluster by name (or unique prefix) without requiring NCCL config.
  199. pub fn select_cluster_by_name(config: &Config, cluster_name: &str) -> Result<Cluster> {
  200. Ok(resolve_cluster_name(&config.clusters, cluster_name)?.clone())
  201. }
  202. /// Resolves the cluster for a recipe, applying recipe-level cluster pinning.
  203. pub fn resolve_cluster<'c>(
  204. config: &'c Config,
  205. recipe: &Recipe,
  206. cluster_name: &str,
  207. ) -> Result<(Cluster, &'c NcclConfig)> {
  208. let choice = if cluster_name != "auto" {
  209. cluster_name.to_string()
  210. } else if let Some(ref rc) = recipe.cluster {
  211. rc.clone()
  212. } else {
  213. "auto".to_string()
  214. };
  215. select_cluster(config, &choice, recipe.required_nodes)
  216. }
  217. /// Resolve the path to a recipe's `mods/` directory, if it exists.
  218. /// Checks cwd first, then the default config dir.
  219. pub async fn resolve_mods_dir(name: &str) -> Option<std::path::PathBuf> {
  220. let cwd = std::path::PathBuf::from(format!("recipes/{name}/mods"));
  221. if cwd.is_dir() {
  222. return Some(cwd);
  223. }
  224. let cfg = default_config_dir()?
  225. .join("recipes")
  226. .join(name)
  227. .join("mods");
  228. cfg.is_dir().then_some(cfg)
  229. }
  230. /// Loads a recipe (cwd first, then `<default_config_dir>/recipes/<name>/recipe.toml`,
  231. /// falling back to cwd for the error).
  232. pub async fn load_recipe(recipe_name: &str) -> Result<Recipe> {
  233. let cwd_path = format!("recipes/{}/recipe.toml", recipe_name);
  234. if let Ok(content) = tokio::fs::read_to_string(&cwd_path).await {
  235. return Ok(toml::from_str(&content)?);
  236. }
  237. if let Some(dir) = default_config_dir() {
  238. let in_default = dir.join("recipes").join(recipe_name).join("recipe.toml");
  239. if let Ok(content) = tokio::fs::read_to_string(&in_default).await {
  240. return Ok(toml::from_str(&content)?);
  241. }
  242. }
  243. // Neither found — let the cwd path produce a clean error.
  244. let content = tokio::fs::read_to_string(&cwd_path).await?;
  245. Ok(toml::from_str(&content)?)
  246. }
  247. /// OS-appropriate default config dir (e.g. `~/.config/sm121-launcher`),
  248. /// or `None` for sandboxes with no known config dir.
  249. pub fn default_config_dir() -> Option<std::path::PathBuf> {
  250. dirs::config_dir().map(|p| p.join("sm121-launcher"))
  251. }
  252. #[cfg(test)]
  253. mod tests {
  254. use super::*;
  255. fn test_cluster() -> Cluster {
  256. Cluster {
  257. name: "test-cluster".to_string(),
  258. master_ib_ip: "192.168.1.1".to_string(),
  259. nodes: vec![
  260. Node {
  261. name: "node0".to_string(),
  262. ssh_ip: "10.0.0.1".to_string(),
  263. ib_ip: "192.168.1.1".to_string(),
  264. rank: 0,
  265. host_key: None,
  266. entity: None,
  267. },
  268. Node {
  269. name: "node1".to_string(),
  270. ssh_ip: "10.0.0.2".to_string(),
  271. ib_ip: "192.168.1.2".to_string(),
  272. rank: 1,
  273. host_key: None,
  274. entity: None,
  275. },
  276. ],
  277. extra_entities: vec![],
  278. }
  279. }
  280. fn test_config() -> Config {
  281. Config {
  282. ssh_user: "u".to_string(),
  283. ssh_key_path: "/k".into(),
  284. clusters: vec![test_cluster()],
  285. nccl: HashMap::new(),
  286. hf_cache_dir: None,
  287. init_port: 25000,
  288. before_serve: HashMap::new(),
  289. exec_aliases: HashMap::new(),
  290. home_assistant: None,
  291. global_mods_dir: None,
  292. }
  293. }
  294. fn test_nccl() -> NcclConfig {
  295. NcclConfig {
  296. ib_hca: "rocep1s0f0".to_string(),
  297. socket_ifname: "enp1s0f0np0".to_string(),
  298. ib_gid_index: 3,
  299. ib_disable: 0,
  300. }
  301. }
  302. #[test]
  303. fn test_recipe_deserialize_minimal() {
  304. let toml_str = "\nname = \"Minimal\"\nmodel = \"test/model\"\n";
  305. let recipe: Recipe = toml::from_str(toml_str).unwrap();
  306. assert_eq!(recipe.name, "Minimal");
  307. assert_eq!(recipe.model, "test/model");
  308. assert_eq!(recipe.engine, "vllm");
  309. assert_eq!(recipe.port, 30000);
  310. assert!(recipe.args.is_empty());
  311. assert!(recipe.env.is_empty());
  312. assert_eq!(recipe.distributed_backend, "mp");
  313. assert_eq!(recipe.tensor_parallel_size, 1);
  314. }
  315. #[test]
  316. fn test_recipe_deserialize_full() {
  317. let toml_str = r#"
  318. engine = "sglang"
  319. name = "Full Recipe"
  320. docker_image = "org/image:tag"
  321. model = "org/model"
  322. port = 30000
  323. required_nodes = 4
  324. pipeline_parallel_size = 2
  325. distributed_backend = "ray"
  326. cluster = "my-cluster"
  327. args = ["--arg1", "val1", "--arg2"]
  328. [env]
  329. KEY = "value"
  330. OTHER = "123"
  331. "#;
  332. let recipe: Recipe = toml::from_str(toml_str).unwrap();
  333. assert_eq!(recipe.engine, "sglang");
  334. assert_eq!(recipe.name, "Full Recipe");
  335. assert_eq!(recipe.docker_image, "org/image:tag");
  336. assert_eq!(recipe.model, "org/model");
  337. assert_eq!(recipe.port, 30000);
  338. assert_eq!(recipe.required_nodes, Some(4));
  339. assert_eq!(recipe.pipeline_parallel_size, Some(2));
  340. assert_eq!(recipe.distributed_backend, "ray");
  341. assert_eq!(recipe.cluster, Some("my-cluster".to_string()));
  342. assert_eq!(recipe.args, vec!["--arg1", "val1", "--arg2"]);
  343. assert_eq!(recipe.env.get("KEY").unwrap(), "value");
  344. assert_eq!(recipe.env.get("OTHER").unwrap(), "123");
  345. }
  346. #[test]
  347. fn test_recipe_deserialize_no_required_nodes() {
  348. let toml_str = r#"
  349. name = "Flexible"
  350. model = "test/model"
  351. "#;
  352. let recipe: Recipe = toml::from_str(toml_str).unwrap();
  353. assert_eq!(recipe.required_nodes, None);
  354. assert_eq!(recipe.pipeline_parallel_size, None);
  355. }
  356. #[test]
  357. fn test_config_deserialize() {
  358. let toml_str = r#"
  359. ssh_user = "admin"
  360. ssh_key_path = "/home/admin/.ssh/id_rsa"
  361. [[clusters]]
  362. name = "prod"
  363. master_ib_ip = "10.0.0.1"
  364. nodes = [
  365. { name = "node1", ssh_ip = "10.0.0.10", ib_ip = "10.0.0.1", rank = 0 },
  366. { name = "node2", ssh_ip = "10.0.0.11", ib_ip = "10.0.0.2", rank = 1 },
  367. ]
  368. [nccl."prod"]
  369. ib_hca = "mlx5_0"
  370. socket_ifname = "eth0"
  371. ib_gid_index = 3
  372. ib_disable = 0
  373. "#;
  374. let config: Config = toml::from_str(toml_str).unwrap();
  375. assert_eq!(config.ssh_user, "admin");
  376. assert_eq!(config.clusters.len(), 1);
  377. assert_eq!(config.clusters[0].nodes.len(), 2);
  378. assert_eq!(config.clusters[0].nodes[0].host_key, None);
  379. assert!(config.nccl.contains_key("prod") && config.nccl["prod"].ib_hca == "mlx5_0");
  380. }
  381. #[test]
  382. fn test_config_deserialize_with_host_key() {
  383. let toml_str = "\nssh_user = \"admin\"\nssh_key_path = \"/path/to/key\"\n[[clusters]]\nname = \"secure\"\nmaster_ib_ip = \"1.1.1.1\"\nnodes = [\n { name = \"n1\", ssh_ip = \"2.2.2.2\", ib_ip = \"1.1.1.1\", rank = 0, host_key = \"SHA256:abc123\" },\n]\n";
  384. let config: Config = toml::from_str(toml_str).unwrap();
  385. assert_eq!(
  386. config.clusters[0].nodes[0].host_key,
  387. Some("SHA256:abc123".into())
  388. );
  389. }
  390. #[test]
  391. fn test_select_cluster_by_name() {
  392. let mut config = Config {
  393. ssh_user: "user".to_string(),
  394. ssh_key_path: "/path/to/key".into(),
  395. clusters: vec![test_cluster()],
  396. nccl: HashMap::new(),
  397. hf_cache_dir: None,
  398. init_port: 25000,
  399. before_serve: HashMap::new(),
  400. exec_aliases: HashMap::new(),
  401. home_assistant: None,
  402. global_mods_dir: None,
  403. };
  404. config.nccl.insert("test-cluster".to_string(), test_nccl());
  405. let (cluster, nccl) = select_cluster(&config, "test-cluster", None).unwrap();
  406. assert_eq!(cluster.name, "test-cluster");
  407. assert_eq!(nccl.ib_hca, "rocep1s0f0");
  408. }
  409. #[test]
  410. fn test_select_cluster_auto() {
  411. let mut config = Config {
  412. ssh_user: "user".to_string(),
  413. ssh_key_path: "/path/to/key".into(),
  414. clusters: vec![test_cluster()],
  415. nccl: HashMap::new(),
  416. hf_cache_dir: None,
  417. init_port: 25000,
  418. before_serve: HashMap::new(),
  419. exec_aliases: HashMap::new(),
  420. home_assistant: None,
  421. global_mods_dir: None,
  422. };
  423. config.nccl.insert("test-cluster".to_string(), test_nccl());
  424. let (cluster, nccl) = select_cluster(&config, "auto", None).unwrap();
  425. assert_eq!(cluster.name, "test-cluster");
  426. assert_eq!(nccl.ib_hca, "rocep1s0f0");
  427. }
  428. #[test]
  429. fn test_select_cluster_auto_no_match() {
  430. let config = test_config();
  431. let result = select_cluster(&config, "auto", None);
  432. assert!(result.is_err());
  433. }
  434. #[test]
  435. fn test_select_cluster_not_found() {
  436. let mut config = test_config();
  437. config.clusters = vec![];
  438. let result = select_cluster(&config, "nonexistent", None);
  439. assert!(result.is_err());
  440. }
  441. #[test]
  442. fn test_select_cluster_by_name_found() {
  443. let mut nccl_map = HashMap::new();
  444. nccl_map.insert("test-cluster".to_string(), test_nccl());
  445. let mut config = test_config();
  446. config.nccl = nccl_map;
  447. let cluster = select_cluster_by_name(&config, "test-cluster").unwrap();
  448. assert_eq!(cluster.name, "test-cluster");
  449. assert_eq!(cluster.nodes.len(), 2);
  450. }
  451. #[test]
  452. fn test_select_cluster_by_name_not_found() {
  453. let config = test_config();
  454. let result = select_cluster_by_name(&config, "no-such-cluster");
  455. assert!(result.is_err());
  456. }
  457. #[test]
  458. fn test_select_cluster_by_prefix() {
  459. let mut config = test_config();
  460. config.nccl.insert("test-cluster".to_string(), test_nccl());
  461. // Unique prefix works
  462. let cluster = select_cluster_by_name(&config, "test-c").unwrap();
  463. assert_eq!(cluster.name, "test-cluster");
  464. // No match errors
  465. let result = select_cluster_by_name(&config, "no-such");
  466. assert!(result.is_err());
  467. }
  468. #[test]
  469. fn test_russian_pluralization() {
  470. let _prev = fluent_i18n::set_locale(Some("ru")).ok();
  471. let s1 = fluent_i18n::t!("cluster-selected", { "name" => "c", "nodes" => 1u64 });
  472. assert!(s1.contains("1 узел"), "got: {}", s1);
  473. let s2 = fluent_i18n::t!("cluster-selected", { "name" => "c", "nodes" => 2u64 });
  474. assert!(s2.contains("2 узла"), "got: {}", s2);
  475. let s5 = fluent_i18n::t!("cluster-selected", { "name" => "c", "nodes" => 5u64 });
  476. assert!(s5.contains("5 узлов"), "got: {}", s5);
  477. }
  478. #[test]
  479. fn test_default_engine_is_vllm() {
  480. let recipe: Recipe = toml::from_str("name = \"x\"\nmodel = \"m\"").unwrap();
  481. assert_eq!(recipe.engine, "vllm");
  482. }
  483. #[test]
  484. fn test_default_distributed_backend_is_mp() {
  485. let recipe: Recipe = toml::from_str("name = \"x\"\nmodel = \"m\"").unwrap();
  486. assert_eq!(recipe.distributed_backend, "mp");
  487. }
  488. #[test]
  489. fn default_config_dir_appends_sm121_launcher() {
  490. let Some(dir) = default_config_dir() else {
  491. return;
  492. };
  493. assert!(dir.ends_with("sm121-launcher") && dir.parent().is_some());
  494. }
  495. }