serve.rs 6.5 KB

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