1use anyhow::{Context, Result};
7use std::io;
8use std::process::{Child, Command, Stdio};
9use std::thread;
10use std::time::{Duration, Instant};
11
12#[allow(dead_code)]
14pub fn run_with_timeout(mut cmd: Command, timeout_secs: u64) -> Result<String> {
15 let timeout_duration = Duration::from_secs(timeout_secs);
16
17 cmd.stdout(Stdio::piped());
19 cmd.stderr(Stdio::piped());
20
21 let child = cmd.spawn().context("Failed to spawn command")?;
22
23 let result = wait_with_timeout(child, timeout_duration);
25
26 match result {
27 TimeoutResult::Completed(output) => {
28 let stdout = String::from_utf8_lossy(&output.stdout).to_string();
29 let stderr = String::from_utf8_lossy(&output.stderr).to_string();
30
31 if output.status.success() {
32 Ok(stdout)
33 } else {
34 Err(anyhow::anyhow!(
35 "Command failed with exit code {:?}. Stderr: {}",
36 output.status.code(),
37 stderr
38 ))
39 }
40 }
41 TimeoutResult::Timeout => Err(anyhow::anyhow!(
42 "Command timed out after {} seconds",
43 timeout_secs
44 )),
45 TimeoutResult::Error(e) => Err(anyhow::anyhow!("Error waiting for command: {}", e)),
46 }
47}
48
49#[allow(dead_code)]
51enum TimeoutResult {
52 Completed(std::process::Output),
53 Timeout,
54 Error(io::Error),
55}
56
57#[allow(dead_code)]
59fn wait_with_timeout(mut child: Child, timeout: Duration) -> TimeoutResult {
60 let start_time = Instant::now();
61
62 loop {
63 match child.try_wait() {
64 Ok(Some(_)) => {
65 match child.wait_with_output() {
67 Ok(output) => return TimeoutResult::Completed(output),
68 Err(e) => return TimeoutResult::Error(e),
69 }
70 }
71 Ok(None) => {
72 if start_time.elapsed() >= timeout {
74 return TimeoutResult::Timeout;
75 }
76 thread::sleep(Duration::from_millis(100));
78 }
79 Err(e) => return TimeoutResult::Error(e),
80 }
81 }
82}
83
84#[cfg(unix)]
86#[allow(dead_code)]
87fn kill_child_process(child: &mut Child) -> Result<()> {
88 if child.try_wait().ok().is_some_and(|status| status.is_none()) {
90 let pid = child.id();
91 unsafe {
93 libc::kill(pid as libc::pid_t, libc::SIGTERM);
94 }
95
96 thread::sleep(Duration::from_millis(1000));
98
99 match child.try_wait() {
101 Ok(Some(_)) => {
102 Ok(())
104 }
105 Ok(None) => {
106 unsafe {
108 libc::kill(pid as libc::pid_t, libc::SIGKILL);
109 }
110 child.wait()?;
111 Ok(())
112 }
113 Err(e) => Err(anyhow::anyhow!("Failed to kill process: {}", e)),
114 }
115 } else {
116 Ok(())
117 }
118}
119
120#[cfg(windows)]
122#[allow(dead_code)]
123fn kill_child_process(child: &mut Child) -> Result<()> {
124 if child.try_wait().ok().is_some_and(|status| status.is_none()) {
127 let pid = child.id();
128 let mut kill_cmd = Command::new("taskkill");
130 kill_cmd.args(["/F", "/PID", &pid.to_string()]);
131 let _ = kill_cmd.output();
132
133 let _ = child.wait();
135 } else {
136 }
138 Ok(())
139}
140
141#[allow(dead_code)]
143pub fn execute_with_timeout(shell_cmd: &str, timeout_secs: u64) -> Result<String> {
144 let (shell, shell_arg) = if cfg!(target_os = "windows") {
145 ("cmd", "/C")
146 } else {
147 ("sh", "-c")
148 };
149
150 let mut cmd = Command::new(shell);
151 cmd.arg(shell_arg);
152 cmd.arg(shell_cmd);
153
154 run_with_timeout(cmd, timeout_secs)
155}
156
157#[allow(dead_code)]
159pub fn with_timeout<F, T>(timeout_secs: u64, operation: F) -> Result<T>
160where
161 F: FnOnce() -> Result<T> + std::marker::Send + 'static,
162 T: Send + 'static,
163{
164 let timeout_duration = Duration::from_secs(timeout_secs);
165
166 let (sender, receiver) = std::sync::mpsc::channel();
168
169 thread::spawn(move || match operation() {
171 Ok(result) => {
172 let _ = sender.send(Ok(result));
173 }
174 Err(e) => {
175 let _ = sender.send(Err(e));
176 }
177 });
178
179 match receiver.recv_timeout(timeout_duration) {
181 Ok(result) => result,
182 Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Err(anyhow::anyhow!(
183 "Operation timed out after {} seconds",
184 timeout_secs
185 )),
186 Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
187 Err(anyhow::anyhow!("Operation thread panicked"))
188 }
189 }
190}