before_serve.rs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. use anyhow::Result;
  2. use tracing::{info, warn};
  3. use crate::config::{Cluster, Config, OnFailure, PreServeCommand, Recipe};
  4. /// Run pre-serve commands on every node of the cluster before launching
  5. /// containers or tmux sessions. Combines cluster-level config
  6. /// (`[before_serve."<cluster>"]`) with recipe-level overrides
  7. /// (`before_serve = [...]` in recipe.toml). Cluster-level commands run
  8. /// first, then recipe-level — each in declared order — so the resulting
  9. /// state is predictable.
  10. ///
  11. /// Per-command behaviour on a non-zero exit is controlled by
  12. /// [`PreServeCommand::on_failure`]:
  13. /// - `abort` (default) — fail-fast: abort the whole serve
  14. /// - `warn` — log warning, continue with remaining commands
  15. /// - `continue`— stay silent, continue
  16. ///
  17. /// If `skip` is true the function returns without running anything.
  18. pub async fn run(
  19. config: &Config,
  20. cluster: &Cluster,
  21. recipe: &Recipe,
  22. skip: bool,
  23. dry_run: bool,
  24. ) -> Result<()> {
  25. if skip {
  26. info!("⏭ Skipping pre-serve hooks (--skip-before-serve)");
  27. return Ok(());
  28. }
  29. let cmds = combined_commands(config, cluster, recipe);
  30. if cmds.is_empty() {
  31. return Ok(());
  32. }
  33. info!(
  34. "🔧 Pre-serve hooks: {} command(s) on {} node(s)",
  35. cmds.len(),
  36. cluster.nodes.len()
  37. );
  38. // Run all commands for one node sequentially (so order matters per
  39. // node), and the nodes in parallel.
  40. let mut handles = Vec::with_capacity(cluster.nodes.len());
  41. for node in &cluster.nodes {
  42. let config = config.clone();
  43. let node = node.clone();
  44. let cmds = cmds.clone();
  45. let dry = dry_run;
  46. handles.push(tokio::spawn(async move {
  47. (
  48. node.name.clone(),
  49. run_for_node(&config, &node, &cmds, dry).await,
  50. )
  51. }));
  52. }
  53. let mut any_failed = false;
  54. for h in handles {
  55. let (name, result) = h.await?;
  56. if let Err(e) = result {
  57. any_failed = true;
  58. warn!(
  59. "{}",
  60. fluent_i18n::t!("pre-serve-failed", { "name" => &name, "error" => e.to_string() })
  61. );
  62. }
  63. }
  64. if any_failed {
  65. anyhow::bail!("Pre-serve hooks failed on at least one node (see warnings above)");
  66. }
  67. Ok(())
  68. }
  69. /// Combine cluster-level + recipe-level commands into one ordered list.
  70. fn combined_commands(
  71. config: &Config,
  72. cluster: &Cluster,
  73. recipe: &Recipe,
  74. ) -> Vec<(&'static str, PreServeCommand)> {
  75. let mut out: Vec<(&'static str, PreServeCommand)> = Vec::new();
  76. if let Some(table) = config.before_serve.get(&cluster.name) {
  77. for c in &table.commands {
  78. out.push(("cluster", c.clone()));
  79. }
  80. }
  81. for c in &recipe.before_serve {
  82. out.push(("recipe", c.clone()));
  83. }
  84. out
  85. }
  86. /// Run a fixed list of commands on a single node, sequentially.
  87. /// Returns the first command that failed under `on_failure = abort`.
  88. async fn run_for_node(
  89. config: &Config,
  90. node: &crate::config::Node,
  91. cmds: &[(&'static str, PreServeCommand)],
  92. dry_run: bool,
  93. ) -> Result<()> {
  94. for (origin, cmd) in cmds {
  95. let command = cmd.command();
  96. let on_failure = cmd.on_failure();
  97. if dry_run {
  98. info!(
  99. "{}",
  100. fluent_i18n::t!("pre-serve-run", { "node" => &node.name, "tag" => &origin, "cmd" => truncate(command, 120) })
  101. );
  102. continue;
  103. }
  104. let result = crate::ssh::run_ssh(config, node, command.to_string(), dry_run).await;
  105. let status = match &result {
  106. Ok(_) => "ok",
  107. Err(_) => "fail",
  108. };
  109. let label = format!("[{}|{}|{}]", node.name, origin, status);
  110. info!(" {} $ {}", label, command);
  111. if let Err(ref e) = result {
  112. match on_failure {
  113. OnFailure::Abort => {
  114. return Err(anyhow::anyhow!(
  115. "pre-serve command failed on {}: {}",
  116. node.name,
  117. e
  118. ));
  119. }
  120. OnFailure::Warn => {
  121. warn!(
  122. "{}",
  123. fluent_i18n::t!("pre-serve-ignored", { "cmd" => &node.name, "error" => e.to_string() })
  124. );
  125. }
  126. OnFailure::Continue => {
  127. // silent
  128. }
  129. }
  130. }
  131. }
  132. Ok(())
  133. }
  134. fn truncate(s: &str, max: usize) -> String {
  135. if s.len() <= max {
  136. s.to_string()
  137. } else {
  138. format!("{}…", &s[..max])
  139. }
  140. }
  141. #[cfg(test)]
  142. mod tests {
  143. use super::*;
  144. use crate::config::{Node, PreServeCommand};
  145. use std::collections::HashMap;
  146. fn test_cluster() -> Cluster {
  147. Cluster {
  148. name: "c1".to_string(),
  149. master_ib_ip: "1.2.3.4".to_string(),
  150. nodes: vec![
  151. Node {
  152. name: "n0".to_string(),
  153. ssh_ip: "10.0.0.1".to_string(),
  154. ib_ip: "1.2.3.4".to_string(),
  155. rank: 0,
  156. host_key: None,
  157. entity: None,
  158. },
  159. Node {
  160. name: "n1".to_string(),
  161. ssh_ip: "10.0.0.2".to_string(),
  162. ib_ip: "1.2.3.5".to_string(),
  163. rank: 1,
  164. host_key: None,
  165. entity: None,
  166. },
  167. ],
  168. extra_entities: vec![],
  169. }
  170. }
  171. fn test_config(before_serve: HashMap<String, crate::config::BeforeServeTable>) -> Config {
  172. Config {
  173. ssh_user: "u".to_string(),
  174. ssh_key_path: "/k".into(),
  175. clusters: vec![test_cluster()],
  176. nccl: HashMap::new(),
  177. hf_cache_dir: None,
  178. init_port: 25000,
  179. before_serve,
  180. exec_aliases: HashMap::new(),
  181. home_assistant: None,
  182. }
  183. }
  184. #[test]
  185. fn combined_orders_cluster_then_recipe() {
  186. let mut bs = HashMap::new();
  187. bs.insert(
  188. "c1".to_string(),
  189. crate::config::BeforeServeTable {
  190. commands: vec![PreServeCommand::Bare("cluster_cmd_1".into())],
  191. },
  192. );
  193. let cfg = test_config(bs);
  194. let recipe = Recipe {
  195. before_serve: vec![
  196. PreServeCommand::Bare("recipe_cmd_1".into()),
  197. PreServeCommand::Bare("recipe_cmd_2".into()),
  198. ],
  199. ..test_recipe()
  200. };
  201. let cmds = combined_commands(&cfg, &test_cluster(), &recipe);
  202. let names: Vec<&str> = cmds.iter().map(|(_, c)| c.command()).collect();
  203. let origins: Vec<&str> = cmds.iter().map(|(o, _)| *o).collect();
  204. assert_eq!(names, vec!["cluster_cmd_1", "recipe_cmd_1", "recipe_cmd_2"]);
  205. assert_eq!(origins, vec!["cluster", "recipe", "recipe"]);
  206. }
  207. #[test]
  208. fn combined_empty_when_unconfigured() {
  209. let cfg = test_config(HashMap::new());
  210. let recipe = Recipe {
  211. before_serve: vec![],
  212. ..test_recipe()
  213. };
  214. assert!(combined_commands(&cfg, &test_cluster(), &recipe).is_empty());
  215. }
  216. fn test_recipe() -> Recipe {
  217. Recipe {
  218. engine: "vllm".to_string(),
  219. name: "Test".to_string(),
  220. docker_image: String::new(),
  221. model: "x".to_string(),
  222. port: 30000,
  223. required_nodes: None,
  224. pipeline_parallel_size: None,
  225. tensor_parallel_size: 1,
  226. args: vec![],
  227. env: HashMap::new(),
  228. cluster: None,
  229. entrypoint: vec![],
  230. distributed_backend: "mp".to_string(),
  231. before_serve: vec![],
  232. shm_size: String::new(),
  233. }
  234. }
  235. // ── Deserialization tests (the ones that live in this module) ──
  236. #[test]
  237. fn parses_cluster_level_before_serve() {
  238. let toml_str = r#"
  239. ssh_user = "u"
  240. ssh_key_path = "/k"
  241. [[clusters]]
  242. name = "c1"
  243. master_ib_ip = "1.1.1.1"
  244. nodes = [
  245. { name = "n0", ssh_ip = "2.2.2.2", ib_ip = "1.1.1.1", rank = 0 },
  246. ]
  247. [before_serve."c1"]
  248. commands = [
  249. "sudo nvidia-smi -lgc 300,2300",
  250. { command = "sudo nvidia-smi -pm 1", on_failure = "warn" },
  251. ]
  252. "#;
  253. let cfg: Config = toml::from_str(toml_str).unwrap();
  254. assert!(cfg.before_serve.contains_key("c1"));
  255. let list = &cfg.before_serve["c1"].commands;
  256. assert_eq!(list.len(), 2);
  257. assert_eq!(list[0].command(), "sudo nvidia-smi -lgc 300,2300");
  258. assert_eq!(list[0].on_failure(), OnFailure::Abort); // default
  259. assert_eq!(list[1].command(), "sudo nvidia-smi -pm 1");
  260. assert_eq!(list[1].on_failure(), OnFailure::Warn);
  261. }
  262. #[test]
  263. fn parses_recipe_level_before_serve() {
  264. let toml_str = r#"
  265. name = "Demo"
  266. model = "x"
  267. before_serve = [
  268. "echo a",
  269. { command = "echo b", on_failure = "continue" },
  270. ]
  271. "#;
  272. let r: Recipe = toml::from_str(toml_str).unwrap();
  273. assert_eq!(r.before_serve.len(), 2);
  274. assert_eq!(r.before_serve[0].command(), "echo a");
  275. assert_eq!(r.before_serve[0].on_failure(), OnFailure::Abort);
  276. assert_eq!(r.before_serve[1].command(), "echo b");
  277. assert_eq!(r.before_serve[1].on_failure(), OnFailure::Continue);
  278. }
  279. }