1use std::net::SocketAddr;
2use std::path::PathBuf;
3use std::sync::Arc;
4#[cfg(feature = "profile-folding")]
5use std::sync::OnceLock;
6use std::time::Duration;
7
8use anyhow::{Context as _, Result};
9use async_ssh2_russh::russh::client::{Config, Handler};
10use async_ssh2_russh::russh::{Disconnect, compression};
11use async_ssh2_russh::russh_sftp::protocol::{Status, StatusCode};
12use async_ssh2_russh::sftp::SftpError;
13use async_ssh2_russh::{AsyncChannel, AsyncSession, NoCheckHandler};
14use async_trait::async_trait;
15use hydro_deploy_integration::ServerBindConfig;
16#[cfg(feature = "profile-folding")]
17use inferno::collapse::Collapse;
18#[cfg(feature = "profile-folding")]
19use inferno::collapse::perf::Folder;
20use nanoid::nanoid;
21use tokio::fs::File;
22#[cfg(feature = "profile-folding")]
23use tokio::io::BufReader;
24use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
25use tokio::net::TcpListener;
26use tokio::sync::{mpsc, oneshot};
27use tokio_stream::StreamExt;
28use tokio_stream::wrappers::LinesStream;
29#[cfg(feature = "profile-folding")]
30use tokio_util::io::SyncIoBridge;
31
32#[cfg(feature = "profile-folding")]
33use crate::TracingResults;
34use crate::progress::ProgressTracker;
35use crate::rust_crate::build::BuildOutput;
36#[cfg(feature = "profile-folding")]
37use crate::rust_crate::flamegraph::handle_fold_data;
38use crate::rust_crate::tracing_options::TracingOptions;
39use crate::util::{PriorityBroadcast, async_retry, prioritized_broadcast};
40use crate::{BaseServerStrategy, LaunchedBinary, LaunchedHost, ResourceResult};
41
42const PERF_OUTFILE: &str = "__profile.perf.data";
43
44struct LaunchedSshBinary {
45 _resource_result: Arc<ResourceResult>,
46 session: Option<AsyncSession<NoCheckHandler>>,
50 channel: AsyncChannel,
51 stdin_sender: mpsc::UnboundedSender<String>,
52 stdout_broadcast: PriorityBroadcast,
53 stderr_broadcast: PriorityBroadcast,
54 tracing: Option<TracingOptions>,
55 #[cfg(feature = "profile-folding")]
56 tracing_results: OnceLock<TracingResults>,
57}
58
59#[async_trait]
60impl LaunchedBinary for LaunchedSshBinary {
61 fn stdin(&self) -> mpsc::UnboundedSender<String> {
62 self.stdin_sender.clone()
63 }
64
65 fn deploy_stdout(&self) -> oneshot::Receiver<String> {
66 self.stdout_broadcast.receive_priority()
67 }
68
69 fn stdout(&self) -> mpsc::UnboundedReceiver<String> {
70 self.stdout_broadcast.receive(None)
71 }
72
73 fn stderr(&self) -> mpsc::UnboundedReceiver<String> {
74 self.stderr_broadcast.receive(None)
75 }
76
77 fn stdout_filter(&self, prefix: String) -> mpsc::UnboundedReceiver<String> {
78 self.stdout_broadcast.receive(Some(prefix))
79 }
80
81 fn stderr_filter(&self, prefix: String) -> mpsc::UnboundedReceiver<String> {
82 self.stderr_broadcast.receive(Some(prefix))
83 }
84
85 #[cfg(feature = "profile-folding")]
86 fn tracing_results(&self) -> Option<&TracingResults> {
87 self.tracing_results.get()
88 }
89
90 fn exit_code(&self) -> Option<i32> {
91 self.channel
93 .recv_exit_status()
94 .try_get()
95 .map(|&ec| ec as _)
96 .ok()
97 }
98
99 async fn wait(&self) -> Result<i32> {
100 let _ = self.channel.closed().wait().await;
101 Ok(*self.channel.recv_exit_status().try_get()? as _)
102 }
103
104 async fn stop(&self) -> Result<()> {
105 if !self.channel.closed().is_done() {
106 ProgressTracker::leaf("force stopping", async {
107 self.channel.eof().await?; self.channel.close().await?; self.channel.closed().wait().await;
111 Result::<_>::Ok(())
112 })
113 .await?;
114 }
115
116 if let Some(tracing) = self.tracing.as_ref() {
118 #[cfg(feature = "profile-folding")]
119 assert!(
120 self.tracing_results.get().is_none(),
121 "`tracing_results` already set! Was `stop()` called twice? This is a bug."
122 );
123
124 let session = self.session.as_ref().unwrap();
125 if let Some(local_raw_perf) = tracing.perf_raw_outfile.as_ref() {
126 ProgressTracker::progress_leaf("downloading perf data", |progress, _| async move {
127 let sftp =
128 async_retry(&|| session.open_sftp(), 10, Duration::from_secs(1)).await?;
129
130 let mut remote_raw_perf = sftp.open(PERF_OUTFILE).await?;
131 let mut local_raw_perf = File::create(local_raw_perf).await?;
132
133 let total_size = remote_raw_perf.metadata().await?.size.unwrap();
134
135 use tokio::io::AsyncWriteExt;
136 let mut index = 0;
137 loop {
138 let mut buffer = [0; 16 * 1024];
139 let n = remote_raw_perf.read(&mut buffer).await?;
140 if n == 0 {
141 break;
142 }
143 local_raw_perf.write_all(&buffer[..n]).await?;
144 index += n;
145 progress(((index as f64 / total_size as f64) * 100.0) as u64);
146 }
147
148 Ok::<(), anyhow::Error>(())
149 })
150 .await?;
151 }
152
153 #[cfg(feature = "profile-folding")]
154 let script_channel = session.open_channel().await?;
155 #[cfg(feature = "profile-folding")]
156 let mut fold_er = Folder::from(tracing.fold_perf_options.clone().unwrap_or_default());
157
158 #[cfg(feature = "profile-folding")]
159 let fold_data = ProgressTracker::leaf("perf script & folding", async move {
160 let mut stderr_lines = script_channel.stderr().lines();
161 let stdout = script_channel.stdout();
162
163 let ((), fold_data, ()) = tokio::try_join!(
165 async move {
166 while let Ok(Some(s)) = stderr_lines.next_line().await {
168 ProgressTracker::eprintln(format!("[perf stderr] {s}"));
169 }
170 Result::<_>::Ok(())
171 },
172 async move {
173 tokio::task::spawn_blocking(move || {
175 let mut fold_data = Vec::new();
176 fold_er.collapse(
177 SyncIoBridge::new(BufReader::new(stdout)),
178 &mut fold_data,
179 )?;
180 Ok(fold_data)
181 })
182 .await?
183 },
184 async move {
185 script_channel
187 .exec(false, format!("perf script --symfs=/ -i {PERF_OUTFILE}"))
188 .await?;
189 Ok(())
190 },
191 )?;
192 Result::<_>::Ok(fold_data)
193 })
194 .await?;
195
196 #[cfg(feature = "profile-folding")]
197 self.tracing_results
198 .set(TracingResults {
199 folded_data: fold_data.clone(),
200 })
201 .expect("`tracing_results` already set! This is a bug.");
202
203 #[cfg(feature = "profile-folding")]
204 handle_fold_data(tracing, fold_data).await?;
205 };
206
207 Ok(())
208 }
209}
210
211impl Drop for LaunchedSshBinary {
212 fn drop(&mut self) {
213 if let Some(session) = self.session.take() {
214 tokio::task::block_in_place(|| {
215 tokio::runtime::Handle::current().block_on(session.disconnect(
216 Disconnect::ByApplication,
217 "",
218 "",
219 ))
220 })
221 .unwrap();
222 }
223 }
224}
225
226#[async_trait]
227pub trait LaunchedSshHost: Send + Sync {
228 fn get_internal_ip(&self) -> &str;
229 fn get_external_ip(&self) -> Option<&str>;
230 fn get_cloud_provider(&self) -> &'static str;
231 fn resource_result(&self) -> &Arc<ResourceResult>;
232 fn ssh_user(&self) -> &str;
233
234 fn ssh_key_path(&self) -> PathBuf {
235 self.resource_result()
236 .terraform
237 .deployment_folder
238 .as_ref()
239 .unwrap()
240 .path()
241 .join(".ssh")
242 .join("vm_instance_ssh_key_pem")
243 }
244
245 async fn open_ssh_session(&self) -> Result<AsyncSession<NoCheckHandler>> {
246 let target_addr = SocketAddr::new(
247 self.get_external_ip()
248 .context(format!(
249 "{} host must be configured with an external IP to launch binaries",
250 self.get_cloud_provider()
251 ))?
252 .parse()
253 .unwrap(),
254 22,
255 );
256
257 let res = ProgressTracker::leaf(
258 format!("connecting to host @ {}", self.get_external_ip().unwrap()),
259 async_retry(
260 &|| async {
261 let mut config = Config::default();
262 config.preferred.compression = (&[
263 compression::ZLIB,
264 compression::ZLIB_LEGACY,
265 compression::NONE,
266 ])
267 .into();
268 AsyncSession::connect_publickey(
269 config,
270 target_addr,
271 self.ssh_user(),
272 self.ssh_key_path(),
273 )
274 .await
275 },
276 10,
277 Duration::from_secs(1),
278 ),
279 )
280 .await?;
281
282 Ok(res)
283 }
284}
285
286async fn create_channel<H>(session: &AsyncSession<H>) -> Result<AsyncChannel>
287where
288 H: 'static + Handler,
289{
290 async_retry(
291 &|| async {
292 Ok(tokio::time::timeout(Duration::from_secs(60), session.open_channel()).await??)
293 },
294 10,
295 Duration::from_secs(1),
296 )
297 .await
298}
299
300#[async_trait]
301impl<T: LaunchedSshHost> LaunchedHost for T {
302 fn base_server_config(&self, bind_type: &BaseServerStrategy) -> ServerBindConfig {
303 match bind_type {
304 BaseServerStrategy::UnixSocket => ServerBindConfig::UnixSocket,
305 BaseServerStrategy::InternalTcpPort(hint) => {
306 ServerBindConfig::TcpPort(self.get_internal_ip().to_owned(), *hint)
307 }
308 BaseServerStrategy::ExternalTcpPort(_) => todo!(),
309 }
310 }
311
312 async fn copy_binary(&self, binary: &BuildOutput) -> Result<()> {
313 let session = self.open_ssh_session().await?;
314
315 let sftp = async_retry(&|| session.open_sftp(), 10, Duration::from_secs(1)).await?;
316
317 let user = self.ssh_user();
318 let binary_path = format!("/home/{user}/hydro-{}", binary.unique_id());
320
321 if sftp.metadata(&binary_path).await.is_err() {
322 let random = nanoid!(8);
323 let temp_path = format!("/home/{user}/hydro-{random}");
324 let sftp = &sftp;
325
326 ProgressTracker::progress_leaf(
327 format!("uploading binary to {}", binary_path),
328 |set_progress, _| {
329 async move {
330 let mut created_file = sftp.create(&temp_path).await?;
331
332 let mut index = 0;
333 while index < binary.bin_data.len() {
334 let written = created_file
335 .write(
336 &binary.bin_data[index
337 ..std::cmp::min(index + 128 * 1024, binary.bin_data.len())],
338 )
339 .await?;
340 index += written;
341 set_progress(
342 ((index as f64 / binary.bin_data.len() as f64) * 100.0) as u64,
343 );
344 }
345 let mut orig_file_stat = sftp.metadata(&temp_path).await?;
346 orig_file_stat.permissions = Some(0o755); created_file.set_metadata(orig_file_stat).await?;
348 created_file.sync_all().await?;
349 drop(created_file);
350
351 match sftp.rename(&temp_path, binary_path).await {
352 Ok(_) => {}
353 Err(SftpError::Status(Status {
354 status_code: StatusCode::Failure, ..
356 })) => {
357 sftp.remove_file(temp_path).await?;
359 }
360 Err(e) => return Err(e.into()),
361 }
362
363 anyhow::Ok(())
364 }
365 },
366 )
367 .await?;
368 }
369 sftp.close().await?;
370
371 Ok(())
372 }
373
374 async fn launch_binary(
375 &self,
376 id: String,
377 binary: &BuildOutput,
378 args: &[String],
379 tracing: Option<TracingOptions>,
380 ) -> Result<Box<dyn LaunchedBinary>> {
381 let session = self.open_ssh_session().await?;
382
383 let user = self.ssh_user();
384 let binary_path = PathBuf::from(format!("/home/{user}/hydro-{}", binary.unique_id()));
385
386 let mut command = binary_path.to_str().unwrap().to_owned();
387 for arg in args {
388 command.push(' ');
389 command.push_str(&shell_escape::unix::escape(arg.into()))
390 }
391
392 if let Some(TracingOptions {
394 frequency,
395 setup_command,
396 ..
397 }) = tracing.clone()
398 {
399 let id_clone = id.clone();
400 ProgressTracker::leaf("install perf", async {
401 if let Some(setup_command) = setup_command {
403 let setup_channel = create_channel(&session).await?;
404 let (setup_stdout, setup_stderr) =
405 (setup_channel.stdout(), setup_channel.stderr());
406 setup_channel.exec(false, &*setup_command).await?;
407
408 let mut output_lines = LinesStream::new(setup_stdout.lines())
410 .merge(LinesStream::new(setup_stderr.lines()));
411 while let Some(line) = output_lines.next().await {
412 ProgressTracker::eprintln(format!(
413 "[{} install perf] {}",
414 id_clone,
415 line.unwrap()
416 ));
417 }
418
419 setup_channel.closed().wait().await;
420 let exit_code = setup_channel.recv_exit_status().try_get();
421 if Ok(&0) != exit_code {
422 anyhow::bail!("Failed to install perf on remote host");
423 }
424 }
425 Ok(())
426 })
427 .await?;
428
429 command = format!(
432 "perf record -F {frequency} -e cycles:u --call-graph dwarf,65528 -o {PERF_OUTFILE} {command}",
433 );
434 }
435
436 let (channel, stdout, stderr) = ProgressTracker::leaf(
437 format!("launching binary {}", binary_path.display()),
438 async {
439 let channel = create_channel(&session).await?;
440 let (stdout, stderr) = (channel.stdout(), channel.stderr());
442 channel.exec(false, command).await?;
443 anyhow::Ok((channel, stdout, stderr))
444 },
445 )
446 .await?;
447
448 let (stdin_sender, mut stdin_receiver) = mpsc::unbounded_channel::<String>();
449 let mut stdin = channel.stdin();
450
451 tokio::spawn(async move {
452 while let Some(line) = stdin_receiver.recv().await {
453 if stdin.write_all(line.as_bytes()).await.is_err() {
454 break;
455 }
456 stdin.flush().await.unwrap();
457 }
458 });
459
460 let id_clone = id.clone();
461 let stdout_broadcast = prioritized_broadcast(LinesStream::new(stdout.lines()), move |s| {
462 ProgressTracker::println(format!("[{id_clone}] {s}"));
463 });
464 let stderr_broadcast = prioritized_broadcast(LinesStream::new(stderr.lines()), move |s| {
465 ProgressTracker::println(format!("[{id} stderr] {s}"));
466 });
467
468 Ok(Box::new(LaunchedSshBinary {
469 _resource_result: self.resource_result().clone(),
470 session: Some(session),
471 channel,
472 stdin_sender,
473 stdout_broadcast,
474 stderr_broadcast,
475 tracing,
476 #[cfg(feature = "profile-folding")]
477 tracing_results: OnceLock::new(),
478 }))
479 }
480
481 async fn forward_port(&self, addr: &SocketAddr) -> Result<SocketAddr> {
482 let session = self.open_ssh_session().await?;
483
484 let local_port = TcpListener::bind("127.0.0.1:0").await?;
485 let local_addr = local_port.local_addr()?;
486
487 let internal_ip = addr.ip().to_string();
488 let port = addr.port();
489
490 tokio::spawn(async move {
491 #[expect(clippy::never_loop, reason = "tcp accept loop pattern")]
492 while let Ok((mut local_stream, _)) = local_port.accept().await {
493 let mut channel = session
494 .channel_open_direct_tcpip(internal_ip, port.into(), "127.0.0.1", 22)
495 .await
496 .unwrap()
497 .into_stream();
498 let _ = tokio::io::copy_bidirectional(&mut local_stream, &mut channel).await;
499 break;
500 }
503
504 ProgressTracker::println("[hydro] closing forwarded port");
505 });
506
507 Ok(local_addr)
508 }
509}