1use std::{
3 io,
4 process::{ExitStatus, Stdio},
5 sync::{Arc, Mutex},
6 time::Duration,
7};
8use tokio::{
9 io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
10 process::{Child, ChildStdin, Command},
11 task::JoinHandle,
12 time::Instant,
13};
14
15pub const DEFAULT_KILL_AFTER: Duration = Duration::from_secs(5);
17pub const DEFAULT_PIPE_DRAIN: Duration = Duration::from_secs(5);
22
23#[derive(Debug, Clone, Default)]
25pub struct ExecutionResult {
26 pub exit_code: i32,
27 pub signal: Option<String>,
29 pub stdout: String,
30 pub stderr: String,
31 pub command: String,
32}
33
34const SIGNALS: &[(i32, &str)] = &[
35 (1, "SIGHUP"),
36 (2, "SIGINT"),
37 (3, "SIGQUIT"),
38 (4, "SIGILL"),
39 (5, "SIGTRAP"),
40 (6, "SIGABRT"),
41 (8, "SIGFPE"),
42 (9, "SIGKILL"),
43 (11, "SIGSEGV"),
44 (13, "SIGPIPE"),
45 (14, "SIGALRM"),
46 (15, "SIGTERM"),
47 #[cfg(target_os = "linux")]
48 (7, "SIGBUS"),
49 #[cfg(target_os = "linux")]
50 (10, "SIGUSR1"),
51 #[cfg(target_os = "linux")]
52 (12, "SIGUSR2"),
53];
54
55pub fn signal_name(number: i32) -> Option<&'static str> {
57 SIGNALS
58 .iter()
59 .find(|(value, _)| *value == number)
60 .map(|(_, name)| *name)
61}
62
63pub fn signal_from_exit_code(exit_code: i32) -> Option<&'static str> {
65 if exit_code > 128 {
66 signal_name(exit_code - 128)
67 } else {
68 None
69 }
70}
71
72pub fn normalize_exit(status: ExitStatus) -> (i32, Option<&'static str>) {
74 #[cfg(unix)]
75 {
76 use std::os::unix::process::ExitStatusExt;
77 if let Some(number) = status.signal() {
78 return (128 + number, signal_name(number));
79 }
80 }
81 let code = status.code().unwrap_or(1);
82 (code, signal_from_exit_code(code))
83}
84
85type Buffer = Arc<Mutex<Vec<u8>>>;
86type Reader = JoinHandle<io::Result<()>>;
87
88async fn join_readers(
91 readers: &mut [Option<Reader>],
92 deadline: Option<Instant>,
93) -> io::Result<bool> {
94 for slot in readers.iter_mut() {
95 let Some(reader) = slot.as_mut() else {
96 continue;
97 };
98 let joined = match deadline {
99 None => reader.await,
100 Some(deadline) => match tokio::time::timeout_at(deadline, reader).await {
101 Ok(joined) => joined,
102 Err(_) => return Ok(false),
103 },
104 };
105 *slot = None;
106 joined.map_err(io::Error::other)??;
107 }
108 Ok(true)
109}
110
111fn read_buffer(buffer: &Buffer) -> String {
112 let bytes = buffer.lock().unwrap_or_else(|e| e.into_inner());
113 String::from_utf8_lossy(&bytes).into_owned()
114}
115
116async fn drain<R: AsyncRead + Unpin>(
117 mut pipe: R,
118 buffer: Buffer,
119 attached: bool,
120 stderr: bool,
121) -> io::Result<()> {
122 let mut chunk = [0; 8192];
123 loop {
124 let count = pipe.read(&mut chunk).await?;
125 if count == 0 {
126 break;
127 }
128 buffer
129 .lock()
130 .unwrap_or_else(|e| e.into_inner())
131 .extend_from_slice(&chunk[..count]);
132 if attached {
133 if stderr {
134 tokio::io::stderr().write_all(&chunk[..count]).await?;
135 } else {
136 tokio::io::stdout().write_all(&chunk[..count]).await?;
137 }
138 }
139 }
140 Ok(())
141}
142
143#[cfg(unix)]
145async fn kill_group(pgid: u32, signal: &str) -> io::Result<std::process::Output> {
146 let signal = signal.trim_start_matches("SIG");
148 Command::new("bash")
149 .arg("-c")
150 .arg(format!("kill -{signal} -- -{pgid}"))
151 .stdin(Stdio::null())
152 .output()
153 .await
154}
155
156pub async fn is_process_group_alive(pgid: u32) -> bool {
161 #[cfg(unix)]
162 {
163 match kill_group(pgid, "0").await {
164 Ok(output) if output.status.success() => true,
165 Ok(output) => String::from_utf8_lossy(&output.stderr)
166 .to_lowercase()
167 .contains("not permitted"),
168 Err(_) => false,
169 }
170 }
171 #[cfg(not(unix))]
172 {
173 let _ = pgid;
174 false
175 }
176}
177
178pub async fn execute_command(
180 command: &str,
181 dry_run: bool,
182 attached: bool,
183) -> io::Result<ExecutionResult> {
184 if dry_run {
185 println!("Dry run - command that would be executed:\n{}", command);
186 return Ok(ExecutionResult {
187 command: command.into(),
188 ..Default::default()
189 });
190 }
191 let mut handle = start_command(command, attached).await?;
192 let exit_code = handle.wait_for_exit().await?;
193 let (stdout, stderr, _) = handle.get_output();
194 Ok(ExecutionResult {
195 exit_code,
196 signal: handle.signal().map(String::from),
197 stdout: stdout.into(),
198 stderr: stderr.into(),
199 command: command.into(),
200 })
201}
202
203pub struct ProcessHandle {
205 pub command: String,
206 child: Child,
207 pid: Option<u32>,
208 readers: Option<(Reader, Reader)>,
209 stdout_buffer: Buffer,
210 stderr_buffer: Buffer,
211 pipe_drain: Option<Duration>,
212 stdout: String,
213 stderr: String,
214 exit_code: Option<i32>,
215 signal: Option<&'static str>,
216 stdin: Option<ChildStdin>,
217}
218impl ProcessHandle {
219 #[must_use]
222 pub const fn with_pipe_drain(mut self, pipe_drain: Option<Duration>) -> Self {
223 self.pipe_drain = pipe_drain;
224 self
225 }
226
227 pub const fn pid(&self) -> Option<u32> {
229 self.pid
230 }
231
232 pub async fn wait_for_exit(&mut self) -> io::Result<i32> {
237 if let Some(code) = self.exit_code {
238 return Ok(code);
239 }
240 self.end_stdin();
241 let status = self.child.wait().await?;
242 if let Some((stdout, stderr)) = self.readers.take() {
243 let mut readers = [Some(stdout), Some(stderr)];
244 let deadline = self.pipe_drain.map(|limit| Instant::now() + limit);
245 if !join_readers(&mut readers, deadline).await? {
246 #[cfg(unix)]
249 if let Some(pid) = self.pid {
250 if is_process_group_alive(pid).await {
251 let _ = kill_group(pid, "KILL").await;
252 }
253 }
254 let grace = Some(Instant::now() + Duration::from_millis(500));
255 if !join_readers(&mut readers, grace).await? {
256 for reader in readers.iter().flatten() {
257 reader.abort();
258 }
259 }
260 }
261 }
262 self.stdout = read_buffer(&self.stdout_buffer);
263 self.stderr = read_buffer(&self.stderr_buffer);
264 let (code, signal) = normalize_exit(status);
265 self.exit_code = Some(code);
266 self.signal = signal;
267 Ok(code)
268 }
269
270 pub async fn terminate(&mut self) -> io::Result<()> {
273 self.terminate_with("SIGTERM", Some(DEFAULT_KILL_AFTER))
274 .await
275 .map(|_| ())
276 }
277
278 pub async fn terminate_with(
284 &mut self,
285 signal: &str,
286 kill_after: Option<Duration>,
287 ) -> io::Result<bool> {
288 #[cfg(unix)]
289 {
290 let Some(pid) = self.pid else {
291 return Ok(false);
292 };
293 if !is_process_group_alive(pid).await {
294 return Ok(false);
295 }
296 let output = kill_group(pid, signal).await?;
297 if std::env::var_os("AGENT_COMMANDER_DEBUG").is_some() {
298 eprintln!(
299 "Cancel process group {pid}: {} {}",
300 output.status,
301 String::from_utf8_lossy(&output.stderr)
302 );
303 }
304 if !output.status.success() && is_process_group_alive(pid).await {
305 return Err(io::Error::other(
306 String::from_utf8_lossy(&output.stderr).into_owned(),
307 ));
308 }
309 let is_kill = matches!(signal.trim_start_matches("SIG"), "KILL" | "9");
310 if let (Some(delay), false) = (kill_after, is_kill) {
311 tokio::spawn(async move {
312 tokio::time::sleep(delay).await;
313 if is_process_group_alive(pid).await {
314 let _ = kill_group(pid, "KILL").await;
315 }
316 });
317 }
318 Ok(true)
319 }
320 #[cfg(not(unix))]
321 {
322 let _ = (signal, kill_after);
323 if self.exit_code.is_some() || self.child.try_wait()?.is_some() {
324 return Ok(false);
325 }
326 self.child.start_kill()?;
327 Ok(true)
328 }
329 }
330
331 pub fn get_output(&self) -> (&str, &str, Option<i32>) {
333 (&self.stdout, &self.stderr, self.exit_code)
334 }
335 pub fn peek_stdout(&self) -> String {
337 read_buffer(&self.stdout_buffer)
338 }
339 pub const fn signal(&self) -> Option<&'static str> {
341 self.signal
342 }
343 pub fn try_wait(&mut self) -> io::Result<bool> {
345 Ok(self.exit_code.is_some() || self.child.try_wait()?.is_some())
346 }
347 pub const fn has_exited(&self) -> bool {
349 self.exit_code.is_some()
350 }
351 pub const fn has_stdin(&self) -> bool {
353 self.stdin.is_some()
354 }
355 pub async fn write_stdin(&mut self, data: &str) -> io::Result<()> {
360 let stdin = self
361 .stdin
362 .as_mut()
363 .ok_or_else(|| io::Error::new(io::ErrorKind::BrokenPipe, "stdin is not open"))?;
364 stdin.write_all(data.as_bytes()).await?;
365 stdin.flush().await
366 }
367 pub fn end_stdin(&mut self) -> bool {
369 self.stdin.take().is_some()
370 }
371}
372
373pub async fn start_command(command: &str, attached: bool) -> io::Result<ProcessHandle> {
375 spawn_command(command, attached, false, None)
376}
377
378pub async fn start_command_with_stdin(command: &str, attached: bool) -> io::Result<ProcessHandle> {
381 spawn_command(command, attached, true, None)
382}
383
384pub async fn start_command_with_env(
387 command: &str,
388 attached: bool,
389 pipe_stdin: bool,
390 env: &[(String, String)],
391) -> io::Result<ProcessHandle> {
392 spawn_command(command, attached, pipe_stdin, Some(env))
393}
394
395fn apply_env(command_builder: &mut Command, env: Option<&[(String, String)]>) {
396 if let Some(env) = env {
397 command_builder.env_clear();
398 command_builder.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())));
399 }
400}
401
402fn spawn_command(
403 command: &str,
404 attached: bool,
405 pipe_stdin: bool,
406 env: Option<&[(String, String)]>,
407) -> io::Result<ProcessHandle> {
408 let mut command_builder = Command::new("bash");
409 apply_env(&mut command_builder, env);
410 #[cfg(unix)]
411 {
412 use std::os::unix::process::CommandExt;
413 command_builder.as_std_mut().process_group(0);
414 }
415 let mut child = command_builder
416 .arg("-c")
417 .arg(command)
418 .stdout(Stdio::piped())
419 .stderr(Stdio::piped())
420 .stdin(if pipe_stdin {
421 Stdio::piped()
422 } else {
423 Stdio::null()
424 })
425 .kill_on_drop(true)
426 .spawn()?;
427 let stdin = child.stdin.take();
428 let stdout = child.stdout.take().expect("piped stdout");
429 let stderr = child.stderr.take().expect("piped stderr");
430 let stdout_buffer = Buffer::default();
431 let stderr_buffer = Buffer::default();
432 Ok(ProcessHandle {
433 command: command.into(),
434 pid: child.id(),
435 child,
436 readers: Some((
437 tokio::spawn(drain(stdout, Arc::clone(&stdout_buffer), attached, false)),
438 tokio::spawn(drain(stderr, Arc::clone(&stderr_buffer), attached, true)),
439 )),
440 stdout_buffer,
441 stderr_buffer,
442 pipe_drain: Some(DEFAULT_PIPE_DRAIN),
443 stdout: String::new(),
444 stderr: String::new(),
445 exit_code: None,
446 signal: None,
447 stdin,
448 })
449}
450
451pub async fn execute_detached(command: &str) -> io::Result<Option<u32>> {
454 execute_detached_with_env(command, None).await
455}
456
457pub async fn execute_detached_with_env(
459 command: &str,
460 env: Option<&[(String, String)]>,
461) -> io::Result<Option<u32>> {
462 let mut command_builder = Command::new("bash");
463 apply_env(&mut command_builder, env);
464 #[cfg(unix)]
465 {
466 use std::os::unix::process::CommandExt;
467 command_builder.as_std_mut().process_group(0);
468 }
469 let child = command_builder
470 .arg("-c")
471 .arg(command)
472 .stdout(Stdio::null())
473 .stderr(Stdio::null())
474 .stdin(Stdio::null())
475 .spawn()?;
476 Ok(child.id())
477}
478pub type CleanupFn = Box<dyn Fn() + Send + Sync>;
480
481pub fn setup_signal_handler<F>(cleanup_fn: F) -> impl Fn()
484where
485 F: Fn() + Send + Sync + 'static,
486{
487 let task = tokio::runtime::Handle::try_current().ok().map(|runtime| {
488 runtime.spawn(async move {
489 if tokio::signal::ctrl_c().await.is_ok() {
490 cleanup_fn();
491 }
492 })
493 });
494 move || {
495 if let Some(task) = &task {
496 task.abort();
497 }
498 }
499}
500
501#[cfg(test)]
502mod tests {
503 use super::*;
504
505 #[tokio::test]
506 async fn test_execute_command_dry_run() {
507 let result = execute_command("echo hello", true, false).await.unwrap();
508 assert_eq!(result.exit_code, 0);
509 assert_eq!(result.command, "echo hello");
510 }
511
512 #[tokio::test]
513 #[cfg(not(target_os = "windows"))]
514 async fn test_execute_command_real() {
515 let result = execute_command("echo hello", false, false).await.unwrap();
516 assert_eq!(result.exit_code, 0);
517 assert!(result.stdout.contains("hello"));
518 }
519
520 #[tokio::test]
521 #[cfg(not(target_os = "windows"))]
522 async fn test_start_command_and_wait() {
523 let mut handle = start_command("echo hello", false).await.unwrap();
524 let exit_code = handle.wait_for_exit().await.unwrap();
525 assert_eq!(exit_code, 0);
526
527 let (stdout, _, _) = handle.get_output();
528 assert!(stdout.contains("hello"));
529 }
530
531 #[tokio::test]
532 #[cfg(not(target_os = "windows"))]
533 async fn test_execute_detached() {
534 let pid = execute_detached("sleep 0.1").await.unwrap();
535 assert!(pid.is_some());
536 }
537
538 #[tokio::test]
539 #[cfg(unix)]
540 async fn test_execute_detached_leads_its_own_process_group() {
541 let pid = execute_detached("sleep 1").await.unwrap().unwrap();
544 let output = tokio::process::Command::new("ps")
545 .args(["-o", "pgid=", "-p", &pid.to_string()])
546 .output()
547 .await
548 .unwrap();
549 assert_eq!(
550 String::from_utf8_lossy(&output.stdout).trim(),
551 pid.to_string()
552 );
553 }
554}