session.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. use anyhow::Result;
  2. use std::time::Duration;
  3. use tokio::time::sleep;
  4. use tracing::{info, warn};
  5. use crate::config::{Cluster, Config, Node, Recipe};
  6. use crate::ssh::shq;
  7. use crate::ssh::{run_ssh, run_ssh_with_retry};
  8. use crate::tmux::{SessionHealth, TmuxManager};
  9. impl TmuxManager {
  10. /// Executes a list of commands via SSH on a node to create a tmux session.
  11. pub async fn create_session(
  12. &self,
  13. config: &Config,
  14. node: &Node,
  15. commands: &[String],
  16. dry_run: bool,
  17. ) -> Result<()> {
  18. if dry_run {
  19. info!(" ssh {}@{}:", config.ssh_user, node.ssh_ip);
  20. for cmd in commands {
  21. info!(" {}", cmd);
  22. }
  23. return Ok(());
  24. }
  25. let script = commands.join(" && ");
  26. let output = run_ssh(config, node, script, dry_run).await?;
  27. if output.trim().is_empty() {
  28. info!(
  29. "{}",
  30. fluent_i18n::t!("tmux-session-created", { "name" => &node.name })
  31. );
  32. } else {
  33. info!(" tmux session output on {}: {}", node.name, output.trim());
  34. }
  35. Ok(())
  36. }
  37. /// Checks whether a tmux session exists on the given node.
  38. pub async fn check_session(
  39. &self,
  40. config: &Config,
  41. node: &Node,
  42. session_name: &str,
  43. dry_run: bool,
  44. ) -> Result<bool> {
  45. if dry_run {
  46. info!(
  47. " ssh {}@{}: tmux list-sessions 2>/dev/null | grep -F '{}'",
  48. config.ssh_user, node.ssh_ip, session_name
  49. );
  50. return Ok(true);
  51. }
  52. let cmd = format!(
  53. "tmux list-sessions 2>/dev/null | grep -Fc {}",
  54. shq(session_name)
  55. );
  56. let output = run_ssh(config, node, cmd, dry_run).await?;
  57. let found = output.trim().parse::<usize>().unwrap_or(0) > 0;
  58. if found {
  59. info!(" Session '{}' found on {}", session_name, node.name);
  60. } else {
  61. warn!(" Session '{}' NOT found on {}", session_name, node.name);
  62. }
  63. Ok(found)
  64. }
  65. /// Performs a deep health check on a tmux session.
  66. pub async fn deep_check_session(
  67. &self,
  68. config: &Config,
  69. node: &Node,
  70. _cluster: &Cluster,
  71. session_name: &str,
  72. recipe: &Recipe,
  73. dry_run: bool,
  74. ) -> Result<SessionHealth> {
  75. if dry_run {
  76. return Ok(SessionHealth {
  77. session_exists: true,
  78. process_alive: true,
  79. gpu_ok: true,
  80. api_ok: true,
  81. });
  82. }
  83. // 1. Check session exists
  84. let exists = self
  85. .check_session(config, node, session_name, dry_run)
  86. .await?;
  87. // 2. Check process is alive inside tmux
  88. let process_alive = if exists {
  89. let pid_cmd = format!(
  90. "tmux list-panes -t {}:0 -F '#{{pane_pid}}' | head -1",
  91. shq(session_name)
  92. );
  93. match run_ssh(config, node, pid_cmd, dry_run).await {
  94. Ok(pid_str) => {
  95. let pid = pid_str.trim();
  96. if !pid.is_empty() && pid != "0" {
  97. let ps_cmd = format!("ps -p {} -o pid= 2>/dev/null", shq(pid));
  98. run_ssh(config, node, ps_cmd, dry_run)
  99. .await
  100. .map(|o| !o.trim().is_empty())
  101. .unwrap_or(false)
  102. } else {
  103. false
  104. }
  105. }
  106. Err(_) => false,
  107. }
  108. } else {
  109. false
  110. };
  111. // 3. Check GPU is available
  112. let gpu_ok = match run_ssh(
  113. config,
  114. node,
  115. "nvidia-smi --query-gpu=index,utilization.gpu,memory.used --format=csv,noheader 2>&1 | head -5"
  116. .to_string(),
  117. dry_run,
  118. )
  119. .await
  120. {
  121. Ok(out) => !out.contains("failed") && !out.contains("error") && !out.trim().is_empty(),
  122. Err(_) => false,
  123. };
  124. // 4. Check API endpoint (head node only)
  125. let api_ok = if node.rank == 0 && process_alive {
  126. let api_check = format!(
  127. "curl -s -o /dev/null -w '%{{http_code}}' http://127.0.0.1:{}/v1/models 2>/dev/null || echo 'fail'",
  128. recipe.port
  129. );
  130. match run_ssh(config, node, api_check, dry_run).await {
  131. Ok(out) => {
  132. let code = out.trim();
  133. code == "200" || !code.contains("fail")
  134. }
  135. Err(_) => false,
  136. }
  137. } else {
  138. node.rank != 0 || process_alive
  139. };
  140. Ok(SessionHealth {
  141. session_exists: exists,
  142. process_alive,
  143. gpu_ok,
  144. api_ok,
  145. })
  146. }
  147. /// Gracefully stops a tmux session with timeout escalation.
  148. pub async fn graceful_stop(
  149. &self,
  150. config: &Config,
  151. node: &Node,
  152. session_name: &str,
  153. dry_run: bool,
  154. ) -> Result<()> {
  155. if dry_run {
  156. info!(
  157. " ssh {}@{}: graceful stop of session '{}'",
  158. config.ssh_user, node.ssh_ip, session_name
  159. );
  160. return Ok(());
  161. }
  162. info!(
  163. " Sending Ctrl+C to session '{}' on {}",
  164. session_name, node.name
  165. );
  166. let _ = run_ssh(
  167. config,
  168. node,
  169. format!("tmux send-keys -t {}:0 C-c", shq(session_name)),
  170. dry_run,
  171. )
  172. .await;
  173. let mut exited = false;
  174. for i in 0..15 {
  175. sleep(Duration::from_secs(2)).await;
  176. let check_cmd = format!(
  177. "tmux list-panes -t {}:0 -F '#{{pane_pid}}' 2>/dev/null | head -1",
  178. shq(session_name)
  179. );
  180. match run_ssh(config, node, check_cmd, dry_run).await {
  181. Ok(pid_str) => {
  182. let pid = pid_str.trim();
  183. if pid.is_empty() || pid == "0" || pid == "No" {
  184. exited = true;
  185. info!(
  186. " Session '{}' exited gracefully (attempt {})",
  187. session_name,
  188. i + 1
  189. );
  190. break;
  191. }
  192. let ps_cmd = format!("ps -p {} -o pid= 2>/dev/null", shq(pid));
  193. match run_ssh(config, node, ps_cmd, dry_run).await {
  194. Ok(ps_out) if ps_out.trim().is_empty() => {
  195. exited = true;
  196. info!(
  197. " Session '{}' process exited (attempt {})",
  198. session_name,
  199. i + 1
  200. );
  201. break;
  202. }
  203. _ => continue,
  204. }
  205. }
  206. Err(_) => {
  207. exited = true;
  208. break;
  209. }
  210. }
  211. }
  212. if !exited {
  213. warn!(
  214. " Session '{}' did not exit gracefully, force killing...",
  215. session_name
  216. );
  217. let _ = run_ssh(
  218. config,
  219. node,
  220. format!("tmux kill-session -t {}", shq(session_name)),
  221. dry_run,
  222. )
  223. .await;
  224. }
  225. Ok(())
  226. }
  227. /// Streams the content of a tmux pane, optionally following new output.
  228. pub async fn stream_pane(
  229. &self,
  230. config: &Config,
  231. node: &Node,
  232. session_name: &str,
  233. window: u32,
  234. follow: bool,
  235. dry_run: bool,
  236. ) -> Result<String> {
  237. if dry_run {
  238. if follow {
  239. info!(
  240. " ssh {}@{}: tail -f (streaming from session '{}' window {})",
  241. config.ssh_user, node.ssh_ip, session_name, window
  242. );
  243. } else {
  244. info!(
  245. " ssh {}@{}: tmux capture-pane -t {}:{} -p -S -100",
  246. config.ssh_user, node.ssh_ip, session_name, window
  247. );
  248. }
  249. return Ok(String::new());
  250. }
  251. let sess_q = shq(session_name);
  252. let cmd = if follow {
  253. // pipe-pane runs `cat > LOG` inside the pane's tmux shell; the
  254. // redirect target is quoted so a session name with a quote/space
  255. // can't break out. `tail -f` then streams the same file.
  256. let log_name = session_name.replace('-', "_");
  257. let log_path = format!("/tmp/sm121_pipe_{}_{}.log", log_name, window);
  258. let log_q = shq(&log_path);
  259. format!(
  260. "tmux pipe-pane -o -t {}:{} \"cat > {}\" && tail -f {}",
  261. sess_q, window, log_q, log_q
  262. )
  263. } else {
  264. format!(
  265. "tmux capture-pane -t {}:{} -p -S -200 2>/dev/null || echo 'no output'",
  266. sess_q, window
  267. )
  268. };
  269. run_ssh_with_retry(config, node, cmd, dry_run, 1).await
  270. }
  271. /// Attaches to a tmux session on a node via SSH (interactive).
  272. pub async fn attach_session(
  273. &self,
  274. config: &Config,
  275. node: &Node,
  276. session_name: &str,
  277. dry_run: bool,
  278. ) -> Result<()> {
  279. if dry_run {
  280. info!(
  281. " Would attach: ssh -t {}@{} tmux attach-session -t {}",
  282. config.ssh_user, node.ssh_ip, session_name
  283. );
  284. return Ok(());
  285. }
  286. info!(
  287. " Attaching to '{}' on {}... Press Ctrl+B D to detach.",
  288. session_name, node.name
  289. );
  290. info!(" {}", fluent_i18n::t!("tmux-no-pty"));
  291. println!(
  292. " ssh -t {}@{} tmux attach-session -t {}",
  293. config.ssh_user, node.ssh_ip, session_name
  294. );
  295. println!();
  296. info!(" Streaming pane content instead:");
  297. let output = self
  298. .stream_pane(config, node, session_name, 0, true, dry_run)
  299. .await?;
  300. println!("{}", output);
  301. Ok(())
  302. }
  303. }