serve.rs 12 KB

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