before_serve.rs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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!("{}", fluent_i18n::t!("pre-serve-skip"));
  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. global_mods_dir: None,
  183. drop_caches: true,
  184. }
  185. }
  186. #[test]
  187. fn combined_orders_cluster_then_recipe() {
  188. let mut bs = HashMap::new();
  189. bs.insert(
  190. "c1".to_string(),
  191. crate::config::BeforeServeTable {
  192. commands: vec![PreServeCommand::Bare("cluster_cmd_1".into())],
  193. },
  194. );
  195. let cfg = test_config(bs);
  196. let recipe = Recipe {
  197. before_serve: vec![
  198. PreServeCommand::Bare("recipe_cmd_1".into()),
  199. PreServeCommand::Bare("recipe_cmd_2".into()),
  200. ],
  201. ..test_recipe()
  202. };
  203. let cmds = combined_commands(&cfg, &test_cluster(), &recipe);
  204. let names: Vec<&str> = cmds.iter().map(|(_, c)| c.command()).collect();
  205. let origins: Vec<&str> = cmds.iter().map(|(o, _)| *o).collect();
  206. assert_eq!(names, vec!["cluster_cmd_1", "recipe_cmd_1", "recipe_cmd_2"]);
  207. assert_eq!(origins, vec!["cluster", "recipe", "recipe"]);
  208. }
  209. #[test]
  210. fn combined_empty_when_unconfigured() {
  211. let cfg = test_config(HashMap::new());
  212. let recipe = Recipe {
  213. before_serve: vec![],
  214. ..test_recipe()
  215. };
  216. assert!(combined_commands(&cfg, &test_cluster(), &recipe).is_empty());
  217. }
  218. fn test_recipe() -> Recipe {
  219. Recipe {
  220. engine: "vllm".to_string(),
  221. name: "Test".to_string(),
  222. docker_image: String::new(),
  223. model: "x".to_string(),
  224. port: 30000,
  225. required_nodes: None,
  226. pipeline_parallel_size: None,
  227. tensor_parallel_size: 1,
  228. args: crate::config::RecipeArgs::default(),
  229. env: HashMap::new(),
  230. cluster: None,
  231. entrypoint: vec![],
  232. distributed_backend: Some(crate::config::DistributedBackend::Mp),
  233. before_serve: vec![],
  234. mods: Default::default(),
  235. sync_image: true,
  236. docker_image_dir: None,
  237. shm_size: String::new(),
  238. volumes: HashMap::new(),
  239. }
  240. }
  241. // ── Deserialization tests (the ones that live in this module) ──
  242. #[test]
  243. fn parses_cluster_level_before_serve() {
  244. let toml_str = r#"
  245. ssh_user = "u"
  246. ssh_key_path = "/k"
  247. [[clusters]]
  248. name = "c1"
  249. master_ib_ip = "1.1.1.1"
  250. nodes = [
  251. { name = "n0", ssh_ip = "2.2.2.2", ib_ip = "1.1.1.1", rank = 0 },
  252. ]
  253. [before_serve."c1"]
  254. commands = [
  255. "sudo nvidia-smi -lgc 300,2300",
  256. { command = "sudo nvidia-smi -pm 1", on_failure = "warn" },
  257. ]
  258. "#;
  259. let cfg: Config = toml::from_str(toml_str).unwrap();
  260. assert!(cfg.before_serve.contains_key("c1"));
  261. let list = &cfg.before_serve["c1"].commands;
  262. assert_eq!(list.len(), 2);
  263. assert_eq!(list[0].command(), "sudo nvidia-smi -lgc 300,2300");
  264. assert_eq!(list[0].on_failure(), OnFailure::Abort); // default
  265. assert_eq!(list[1].command(), "sudo nvidia-smi -pm 1");
  266. assert_eq!(list[1].on_failure(), OnFailure::Warn);
  267. }
  268. #[test]
  269. fn parses_recipe_level_before_serve() {
  270. let toml_str = r#"
  271. name = "Demo"
  272. model = "x"
  273. before_serve = [
  274. "echo a",
  275. { command = "echo b", on_failure = "continue" },
  276. ]
  277. "#;
  278. let r: Recipe = toml::from_str(toml_str).unwrap();
  279. assert_eq!(r.before_serve.len(), 2);
  280. assert_eq!(r.before_serve[0].command(), "echo a");
  281. assert_eq!(r.before_serve[0].on_failure(), OnFailure::Abort);
  282. assert_eq!(r.before_serve[1].command(), "echo b");
  283. assert_eq!(r.before_serve[1].on_failure(), OnFailure::Continue);
  284. }
  285. }