serve.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. use anyhow::{Context, Result};
  2. use std::collections::HashSet;
  3. use std::time::Duration;
  4. use tokio::time::sleep;
  5. use tracing::{info, warn};
  6. use crate::config::{Config, Node, Recipe};
  7. use crate::tmux::TmuxManager;
  8. /// Launches a cluster via tmux sessions.
  9. /// For Ray backend: starts head node first, waits for readiness, then workers.
  10. pub async fn tmux_serve(
  11. config: &Config,
  12. recipe_name: &str,
  13. cluster_name: &str,
  14. skip_before_serve: bool,
  15. dry_run: bool,
  16. ) -> Result<()> {
  17. let recipe_path = format!("recipes/{}/recipe.toml", recipe_name);
  18. let recipe: Recipe = toml::from_str(&tokio::fs::read_to_string(&recipe_path).await?)?;
  19. // Feature gaps: tmux deployment doesn't support Docker-only features.
  20. if !recipe.mods.commands.is_empty() {
  21. anyhow::bail!(
  22. "{}",
  23. fluent_i18n::t!("tmux-mods-unsupported", { "name" => &recipe.name })
  24. );
  25. }
  26. if recipe.composed_model.is_some() {
  27. anyhow::bail!(
  28. "{}",
  29. fluent_i18n::t!("tmux-composed-model-unsupported", { "name" => &recipe.name })
  30. );
  31. }
  32. info!(
  33. "🚀 TMUX launch: {} ({}) [backend: {}] [engine: {}]",
  34. recipe.name,
  35. recipe_name,
  36. recipe
  37. .distributed_backend
  38. .map_or("none".into(), |b| b.to_string()),
  39. recipe.engine
  40. );
  41. let choice = if cluster_name != "auto" {
  42. cluster_name.to_string()
  43. } else if let Some(ref rc) = recipe.cluster {
  44. rc.clone()
  45. } else {
  46. "auto".to_string()
  47. };
  48. let (cluster, nccl) =
  49. crate::config::select_cluster(config, &choice, recipe.required_nodes, &HashSet::new())?;
  50. if let Some(required) = recipe.required_nodes {
  51. let actual = cluster.nodes.len() as u32;
  52. if actual != required {
  53. anyhow::bail!(
  54. "Recipe '{}' requires {} nodes, but cluster '{}' has {} nodes",
  55. recipe.name,
  56. required,
  57. cluster.name,
  58. actual
  59. );
  60. }
  61. }
  62. crate::before_serve::run(config, &cluster, &recipe, skip_before_serve, dry_run).await?;
  63. // Prepare the Python venv on each node if it doesn't exist yet.
  64. prepare_venv(config, &recipe, &cluster, recipe_name, dry_run).await?;
  65. let manager = TmuxManager;
  66. let is_ray = recipe.distributed_backend == Some(crate::config::DistributedBackend::Ray);
  67. if is_ray {
  68. info!("{}", fluent_i18n::t!("tmux-ray-backend"));
  69. let head_node = cluster
  70. .nodes
  71. .iter()
  72. .find(|n| n.rank == 0)
  73. .context("No head node (rank 0) in cluster")?;
  74. let head_cmds = manager.build_session_commands(head_node, &recipe, nccl, &cluster);
  75. manager
  76. .create_session(config, head_node, &head_cmds, dry_run)
  77. .await?;
  78. if !dry_run {
  79. info!("{}", fluent_i18n::t!("tmux-waiting-head"));
  80. let sess = manager.session_name(&recipe, 0);
  81. let head_ready = wait_for_head_ready(config, head_node, &sess, &recipe).await?;
  82. if head_ready {
  83. info!("{}", fluent_i18n::t!("tmux-head-ready"));
  84. } else {
  85. warn!("⚠️ Head node may not be fully ready — starting workers anyway.");
  86. }
  87. }
  88. for node in &cluster.nodes {
  89. if node.rank == 0 {
  90. continue;
  91. }
  92. let worker_cmds = manager.build_session_commands(node, &recipe, nccl, &cluster);
  93. manager
  94. .create_session(config, node, &worker_cmds, dry_run)
  95. .await?;
  96. }
  97. } else {
  98. info!("{}", fluent_i18n::t!("tmux-mp-backend"));
  99. let mut handles = Vec::new();
  100. for node in &cluster.nodes {
  101. let config = config.clone();
  102. let node = node.clone();
  103. let recipe = recipe.clone();
  104. let nccl = nccl.clone();
  105. let cluster = cluster.clone();
  106. let manager = manager.clone();
  107. let dry = dry_run;
  108. handles.push(crate::locale::spawn_with_locale(async move {
  109. let cmds = manager.build_session_commands(&node, &recipe, &nccl, &cluster);
  110. manager
  111. .create_session(&config, &node, &cmds, dry)
  112. .await
  113. .map(|_| node.name.clone())
  114. }));
  115. }
  116. let results = futures::future::join_all(handles).await;
  117. let mut failures = Vec::new();
  118. for result in results {
  119. match result {
  120. Ok(Ok(name)) => info!(
  121. "{}",
  122. fluent_i18n::t!("tmux-session-started", { "name" => &name })
  123. ),
  124. Ok(Err(e)) => failures.push(e),
  125. Err(e) => failures.push(anyhow::anyhow!("Task join: {}", e)),
  126. }
  127. }
  128. if !failures.is_empty() {
  129. for e in &failures {
  130. warn!(" ✗ {}", e);
  131. }
  132. anyhow::bail!("Failed to start sessions on {} node(s)", failures.len());
  133. }
  134. }
  135. if !dry_run {
  136. sleep(Duration::from_secs(5)).await;
  137. info!(
  138. "🎉 Cluster launched via tmux! API → http://{}:{}",
  139. cluster.master_ib_ip, recipe.port
  140. );
  141. info!(
  142. "📌 To view sessions: `cargo run tmux status --recipe {}`",
  143. recipe_name
  144. );
  145. info!(
  146. "📌 To attach: `cargo run tmux attach --recipe {}`",
  147. recipe_name
  148. );
  149. }
  150. Ok(())
  151. }
  152. /// Polls the head node until the API endpoint responds or timeout.
  153. async fn wait_for_head_ready(
  154. config: &Config,
  155. head_node: &crate::config::Node,
  156. session_name: &str,
  157. recipe: &Recipe,
  158. ) -> Result<bool> {
  159. let max_attempts = 30;
  160. for i in 0..max_attempts {
  161. let pid_cmd = format!(
  162. "tmux list-panes -t {}:0 -F '#{{pane_pid}}' | head -1",
  163. session_name
  164. );
  165. match crate::ssh::run_ssh(config, head_node, pid_cmd, false).await {
  166. Ok(pid_str) => {
  167. let pid = pid_str.trim();
  168. if pid.is_empty() || pid == "0" {
  169. sleep(Duration::from_secs(5)).await;
  170. continue;
  171. }
  172. }
  173. Err(_) => {
  174. sleep(Duration::from_secs(5)).await;
  175. continue;
  176. }
  177. }
  178. let api_check = format!(
  179. "curl -s -o /dev/null -w '%{{http_code}}' http://127.0.0.1:{}/v1/models 2>/dev/null || echo 'not_ready'",
  180. recipe.port
  181. );
  182. if let Ok(out) = crate::ssh::run_ssh(config, head_node, api_check, false).await {
  183. let code = out.trim();
  184. if code == "200" {
  185. info!(
  186. "{}",
  187. fluent_i18n::t!("tmux-head-api-ready", { "attempt" => i + 1 })
  188. );
  189. return Ok(true);
  190. }
  191. }
  192. if (i + 1) % 5 == 0 {
  193. info!(
  194. " Still waiting for head node... ({}/{})",
  195. i + 1,
  196. max_attempts
  197. );
  198. }
  199. sleep(Duration::from_secs(5)).await;
  200. }
  201. warn!(" Head node did not become ready within timeout");
  202. Ok(false)
  203. }
  204. /// Prepares the Python venv on each node if it doesn't exist.
  205. ///
  206. /// Checks `test -f <venv>/bin/activate` on each node; if absent, runs
  207. /// the setup commands in order, then re-checks. The setup commands come
  208. /// from either `recipe.venv_setup_script` (a script file read from the
  209. /// recipe directory) or `recipe.venv_setup` (inline list or multi-line
  210. /// string). A failure on any command aborts the serve. Nodes are
  211. /// prepared in parallel.
  212. async fn prepare_venv(
  213. config: &Config,
  214. recipe: &Recipe,
  215. cluster: &crate::config::Cluster,
  216. recipe_name: &str,
  217. dry_run: bool,
  218. ) -> Result<()> {
  219. let venv = match &recipe.venv {
  220. Some(v) => v,
  221. None => return Ok(()),
  222. };
  223. // Resolve setup commands: script file takes precedence over inline.
  224. let setup: Vec<String> = if let Some(script_path) = &recipe.venv_setup_script {
  225. let full_path = format!("recipes/{}/{}", recipe_name, script_path);
  226. if dry_run {
  227. info!(" read venv_setup_script: {} (dry-run)", full_path);
  228. } else {
  229. info!(" read venv_setup_script: {}", full_path);
  230. }
  231. let body = tokio::fs::read_to_string(&full_path)
  232. .await
  233. .map_err(|e| anyhow::anyhow!("Cannot read venv_setup_script '{}': {}", full_path, e))?;
  234. body.lines()
  235. .map(|l| l.trim().to_string())
  236. .filter(|l| !l.is_empty() && !l.starts_with('#'))
  237. .collect()
  238. } else {
  239. recipe.venv_setup.to_vec()
  240. };
  241. if setup.is_empty() {
  242. return Ok(());
  243. }
  244. info!("{}", fluent_i18n::t!("venv-preparing", { "venv" => venv }));
  245. let mut handles = Vec::with_capacity(cluster.nodes.len());
  246. for node in &cluster.nodes {
  247. let config = config.clone();
  248. let node = node.clone();
  249. let venv = venv.clone();
  250. let setup = setup.clone();
  251. let dry = dry_run;
  252. handles.push(crate::locale::spawn_with_locale(async move {
  253. (
  254. node.name.clone(),
  255. prepare_venv_for_node(&config, &node, &venv, &setup, dry).await,
  256. )
  257. }));
  258. }
  259. let mut any_failed = false;
  260. for h in handles {
  261. let (name, result) = h.await?;
  262. if let Err(e) = result {
  263. any_failed = true;
  264. warn!(
  265. "{}",
  266. fluent_i18n::t!("venv-prepare-failed", { "name" => &name, "error" => e.to_string() })
  267. );
  268. }
  269. }
  270. if any_failed {
  271. anyhow::bail!("Venv preparation failed on at least one node (see warnings above)");
  272. }
  273. Ok(())
  274. }
  275. /// Checks if the venv exists on a single node and creates it if not.
  276. async fn prepare_venv_for_node(
  277. config: &Config,
  278. node: &Node,
  279. venv: &str,
  280. setup: &[String],
  281. dry_run: bool,
  282. ) -> Result<()> {
  283. let check_cmd = format!("test -f {}/bin/activate", venv);
  284. if dry_run {
  285. info!(
  286. " ssh {}@{}: {} (dry-run)",
  287. config.ssh_user, node.ssh_ip, check_cmd
  288. );
  289. for cmd in setup {
  290. info!(" {} (dry-run)", cmd);
  291. }
  292. return Ok(());
  293. }
  294. // Check if venv already exists.
  295. match crate::ssh::run_ssh(config, node, check_cmd.clone(), false).await {
  296. Ok(_) => {
  297. info!(
  298. "{}",
  299. fluent_i18n::t!("venv-exists", { "name" => &node.name })
  300. );
  301. return Ok(());
  302. }
  303. Err(_) => {
  304. info!(
  305. "{}",
  306. fluent_i18n::t!("venv-creating", { "name" => &node.name })
  307. );
  308. }
  309. }
  310. // Run setup commands in order.
  311. for cmd in setup {
  312. info!(" ssh {}@{}: {}", config.ssh_user, node.ssh_ip, cmd);
  313. crate::ssh::run_ssh(config, node, cmd.clone(), false).await?;
  314. }
  315. // Re-check that the venv was created.
  316. match crate::ssh::run_ssh(config, node, check_cmd, false).await {
  317. Ok(_) => {
  318. info!(
  319. "{}",
  320. fluent_i18n::t!("venv-created", { "name" => &node.name })
  321. );
  322. Ok(())
  323. }
  324. Err(_) => {
  325. anyhow::bail!(
  326. "{}",
  327. fluent_i18n::t!("venv-not-created", { "name" => &node.name })
  328. );
  329. }
  330. }
  331. }