serve.rs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. use anyhow::{Context, Result};
  2. use std::time::Duration;
  3. use tokio::time::sleep;
  4. use tracing::{info, warn};
  5. use crate::config::{Config, Recipe};
  6. use crate::tmux::TmuxManager;
  7. /// Launches a cluster via tmux sessions.
  8. /// For Ray backend: starts head node first, waits for readiness, then workers.
  9. pub async fn tmux_serve(
  10. config: &Config,
  11. recipe_name: &str,
  12. cluster_name: &str,
  13. skip_before_serve: bool,
  14. dry_run: bool,
  15. ) -> Result<()> {
  16. let recipe_path = format!("recipes/{}/recipe.toml", recipe_name);
  17. let recipe: Recipe = toml::from_str(&tokio::fs::read_to_string(&recipe_path).await?)?;
  18. info!(
  19. "🚀 TMUX launch: {} ({}) [backend: {}] [engine: {}]",
  20. recipe.name,
  21. recipe_name,
  22. recipe
  23. .distributed_backend
  24. .map_or("none".into(), |b| b.to_string()),
  25. recipe.engine
  26. );
  27. let choice = if cluster_name != "auto" {
  28. cluster_name.to_string()
  29. } else if let Some(ref rc) = recipe.cluster {
  30. rc.clone()
  31. } else {
  32. "auto".to_string()
  33. };
  34. let (cluster, nccl) = crate::config::select_cluster(config, &choice, recipe.required_nodes)?;
  35. if let Some(required) = recipe.required_nodes {
  36. let actual = cluster.nodes.len() as u32;
  37. if actual != required {
  38. anyhow::bail!(
  39. "Recipe '{}' requires {} nodes, but cluster '{}' has {} nodes",
  40. recipe.name,
  41. required,
  42. cluster.name,
  43. actual
  44. );
  45. }
  46. }
  47. crate::before_serve::run(config, &cluster, &recipe, skip_before_serve, dry_run).await?;
  48. let manager = TmuxManager {
  49. session_prefix: recipe_name.to_string(),
  50. };
  51. let is_ray = recipe.distributed_backend == Some(crate::config::DistributedBackend::Ray);
  52. if is_ray {
  53. info!("🐍 Ray backend detected — starting head node first...");
  54. let head_node = cluster
  55. .nodes
  56. .iter()
  57. .find(|n| n.rank == 0)
  58. .context("No head node (rank 0) in cluster")?;
  59. let head_cmds = manager.build_session_commands(head_node, &recipe, nccl, &cluster);
  60. manager
  61. .create_session(config, head_node, &head_cmds, dry_run)
  62. .await?;
  63. if !dry_run {
  64. info!("⏳ Waiting for head node to be ready...");
  65. let sess = manager.session_name(&recipe, 0);
  66. let head_ready = wait_for_head_ready(config, head_node, &sess, &recipe).await?;
  67. if head_ready {
  68. info!("✅ Head node ready. Starting worker nodes...");
  69. } else {
  70. warn!("⚠️ Head node may not be fully ready — starting workers anyway.");
  71. }
  72. }
  73. for node in &cluster.nodes {
  74. if node.rank == 0 {
  75. continue;
  76. }
  77. let worker_cmds = manager.build_session_commands(node, &recipe, nccl, &cluster);
  78. manager
  79. .create_session(config, node, &worker_cmds, dry_run)
  80. .await?;
  81. }
  82. } else {
  83. info!("🔗 MP backend detected — starting all nodes in parallel...");
  84. let mut handles = Vec::new();
  85. for node in &cluster.nodes {
  86. let config = config.clone();
  87. let node = node.clone();
  88. let recipe = recipe.clone();
  89. let nccl = nccl.clone();
  90. let cluster = cluster.clone();
  91. let manager = manager.clone();
  92. let dry = dry_run;
  93. handles.push(tokio::spawn(async move {
  94. let cmds = manager.build_session_commands(&node, &recipe, &nccl, &cluster);
  95. manager
  96. .create_session(&config, &node, &cmds, dry)
  97. .await
  98. .map(|_| node.name.clone())
  99. }));
  100. }
  101. let results = futures::future::join_all(handles).await;
  102. let mut failures = Vec::new();
  103. for result in results {
  104. match result {
  105. Ok(Ok(name)) => info!(" ✅ Session started on {}", name),
  106. Ok(Err(e)) => failures.push(e),
  107. Err(e) => failures.push(anyhow::anyhow!("Task join: {}", e)),
  108. }
  109. }
  110. if !failures.is_empty() {
  111. for e in &failures {
  112. warn!(" ✗ {}", e);
  113. }
  114. anyhow::bail!("Failed to start sessions on {} node(s)", failures.len());
  115. }
  116. }
  117. if !dry_run {
  118. sleep(Duration::from_secs(5)).await;
  119. info!(
  120. "🎉 Cluster launched via tmux! API → http://{}:{}",
  121. cluster.master_ib_ip, recipe.port
  122. );
  123. info!(
  124. "📌 To view sessions: `cargo run tmux status --recipe {}`",
  125. recipe_name
  126. );
  127. info!(
  128. "📌 To attach: `cargo run tmux attach --recipe {}`",
  129. recipe_name
  130. );
  131. }
  132. Ok(())
  133. }
  134. /// Polls the head node until the API endpoint responds or timeout.
  135. async fn wait_for_head_ready(
  136. config: &Config,
  137. head_node: &crate::config::Node,
  138. session_name: &str,
  139. recipe: &Recipe,
  140. ) -> Result<bool> {
  141. let max_attempts = 30;
  142. for i in 0..max_attempts {
  143. let pid_cmd = format!(
  144. "tmux list-panes -t {}:0 -F '#{{pane_pid}}' | head -1",
  145. session_name
  146. );
  147. match crate::ssh::run_ssh(config, head_node, pid_cmd, false).await {
  148. Ok(pid_str) => {
  149. let pid = pid_str.trim();
  150. if pid.is_empty() || pid == "0" {
  151. sleep(Duration::from_secs(5)).await;
  152. continue;
  153. }
  154. }
  155. Err(_) => {
  156. sleep(Duration::from_secs(5)).await;
  157. continue;
  158. }
  159. }
  160. let api_check = format!(
  161. "curl -s -o /dev/null -w '%{{http_code}}' http://127.0.0.1:{}/v1/models 2>/dev/null || echo 'not_ready'",
  162. recipe.port
  163. );
  164. if let Ok(out) = crate::ssh::run_ssh(config, head_node, api_check, false).await {
  165. let code = out.trim();
  166. if code == "200" {
  167. info!(" Head node API ready (attempt {})", i + 1);
  168. return Ok(true);
  169. }
  170. }
  171. if (i + 1) % 5 == 0 {
  172. info!(
  173. " Still waiting for head node... ({}/{})",
  174. i + 1,
  175. max_attempts
  176. );
  177. }
  178. sleep(Duration::from_secs(5)).await;
  179. }
  180. warn!(" Head node did not become ready within timeout");
  181. Ok(false)
  182. }