agentmux_launcher/
upgrade.rs1use std::time::Duration;
18
19use tokio::process::Child;
20
21pub const GRACEFUL_QUIESCE_TIMEOUT: Duration = agentmux_common::process::SRV_EXIT_WAIT;
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum QuiesceOutcome {
31 AlreadyExited,
34 ExitedGracefully,
36 ExitedAfterForceKill,
38}
39
40pub async fn quiesce_srv(
51 child: &mut Child,
52 stdin: Option<tokio::process::ChildStdin>,
53 graceful_timeout: Duration,
54) -> std::io::Result<(std::process::ExitStatus, QuiesceOutcome)> {
55 if let Ok(Some(status)) = child.try_wait() {
56 return Ok((status, QuiesceOutcome::AlreadyExited));
57 }
58 drop(stdin);
59 #[cfg(not(target_os = "windows"))]
60 crate::host_spawn::terminate_child_gracefully(child);
61 match tokio::time::timeout(graceful_timeout, child.wait()).await {
62 Ok(status) => Ok((status?, QuiesceOutcome::ExitedGracefully)),
63 Err(_elapsed) => {
64 agentmux_common::process::start_kill_child_and_group(child)?;
70 let status = child.wait().await?;
71 Ok((status, QuiesceOutcome::ExitedAfterForceKill))
72 }
73 }
74}
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79 #[cfg(not(target_os = "windows"))]
80 use tokio::io::{AsyncBufReadExt, BufReader};
81
82 fn spawn_long_lived() -> Child {
88 #[cfg(not(target_os = "windows"))]
89 {
90 tokio::process::Command::new("sleep")
91 .arg("30")
92 .kill_on_drop(true)
93 .spawn()
94 .expect("spawn sleep")
95 }
96 #[cfg(target_os = "windows")]
97 {
98 tokio::process::Command::new("cmd")
99 .args(["/C", "ping", "-n", "30", "127.0.0.1"])
100 .kill_on_drop(true)
101 .spawn()
102 .expect("spawn ping")
103 }
104 }
105
106 #[cfg(not(target_os = "windows"))]
121 async fn spawn_sigterm_immune() -> Child {
122 let mut child = tokio::process::Command::new("sh")
123 .args(["-c", "trap '' TERM; echo ready; sleep 30"])
124 .stdout(std::process::Stdio::piped())
125 .kill_on_drop(true)
126 .spawn()
127 .expect("spawn sigterm-immune shell");
128
129 let stdout = child.stdout.take().expect("piped stdout");
130 let mut lines = BufReader::new(stdout).lines();
131 let line = lines
132 .next_line()
133 .await
134 .expect("read readiness line")
135 .expect("readiness line present");
136 assert_eq!(line.trim(), "ready", "trap must be installed before the test signals this child");
137
138 child
139 }
140
141 #[cfg(not(target_os = "windows"))]
144 #[tokio::test]
145 async fn the_force_kill_takes_the_childs_process_group() {
146 use std::os::unix::process::CommandExt as _;
147 let mut child = tokio::process::Command::new("sh")
148 .args(["-c", "trap '' TERM; sleep 30 & echo $!; wait"])
149 .stdout(std::process::Stdio::piped())
150 .process_group(0)
151 .kill_on_drop(true)
152 .spawn()
153 .expect("spawn a group leader that ignores SIGTERM");
154 let mut lines = BufReader::new(child.stdout.take().expect("piped stdout")).lines();
155 let helper: u32 = lines.next_line().await.unwrap().unwrap().trim().parse().unwrap();
156 assert!(agentmux_common::process::process_start_time(helper).is_some());
157
158 let (_, outcome) = quiesce_srv(&mut child, None, Duration::from_millis(300)).await.unwrap();
159 assert_eq!(outcome, QuiesceOutcome::ExitedAfterForceKill);
160 let mut gone = false;
161 for _ in 0..100 {
162 let zombie = std::fs::read_to_string(format!("/proc/{helper}/stat"))
163 .ok()
164 .and_then(|t| t.rfind(')').map(|i| t[i + 1..].trim_start().starts_with('Z')))
165 .unwrap_or(false);
166 if agentmux_common::process::process_start_time(helper).is_none() || zombie {
167 gone = true;
168 break;
169 }
170 tokio::time::sleep(Duration::from_millis(20)).await;
171 }
172 assert!(gone, "helper {helper} outlived the force-kill of its group leader");
173 }
174
175 #[tokio::test]
176 async fn already_exited_child_is_reported_without_signaling_anything() {
177 let mut child = tokio::process::Command::new(if cfg!(windows) { "cmd" } else { "true" })
178 .args(if cfg!(windows) { vec!["/C", "exit 0"] } else { vec![] })
179 .kill_on_drop(true)
180 .spawn()
181 .expect("spawn a trivially-exiting child");
182 let _ = tokio::time::timeout(Duration::from_secs(5), child.wait())
184 .await
185 .expect("child did not exit");
186
187 let (status, outcome) = quiesce_srv(&mut child, None, Duration::from_secs(1))
188 .await
189 .expect("quiesce_srv must not error on an already-exited child");
190
191 assert_eq!(outcome, QuiesceOutcome::AlreadyExited);
192 assert!(status.success());
193 }
194
195 #[tokio::test]
196 async fn a_live_child_is_actually_stopped_and_reaped() {
197 let mut child = spawn_long_lived();
202 let pid = child.id().expect("live child has a pid");
203
204 let (_status, _outcome) = tokio::time::timeout(
207 Duration::from_secs(15),
208 quiesce_srv(&mut child, None, Duration::from_secs(1)),
209 )
210 .await
211 .expect("quiesce_srv hung instead of returning once the child exited")
212 .expect("quiesce_srv errored");
213
214 assert!(
217 tokio::time::timeout(Duration::from_millis(500), child.wait())
218 .await
219 .is_ok(),
220 "pid {pid} should already be reaped after quiesce_srv returned"
221 );
222 }
223
224 #[cfg(not(target_os = "windows"))]
225 #[tokio::test]
226 async fn a_sigterm_ignoring_child_is_force_killed_after_the_timeout() {
227 use std::os::unix::process::ExitStatusExt;
228
229 let mut child = spawn_sigterm_immune().await;
230
231 let (status, outcome) = tokio::time::timeout(
232 Duration::from_secs(10),
233 quiesce_srv(&mut child, None, Duration::from_millis(300)),
236 )
237 .await
238 .expect("quiesce_srv hung past its own escalation timeout")
239 .expect("quiesce_srv errored");
240
241 assert_eq!(outcome, QuiesceOutcome::ExitedAfterForceKill);
242 assert_eq!(status.signal(), Some(libc::SIGKILL));
243 }
244
245 #[cfg(not(target_os = "windows"))]
249 #[tokio::test]
250 async fn closing_stdin_stops_a_child_that_ignores_sigterm() {
251 let mut child = tokio::process::Command::new("sh")
252 .args(["-c", "trap '' TERM; echo ready; cat >/dev/null"])
253 .stdin(std::process::Stdio::piped())
254 .stdout(std::process::Stdio::piped())
255 .kill_on_drop(true)
256 .spawn()
257 .expect("spawn stdin-reading shell");
258 let stdin = child.stdin.take();
259 let stdout = child.stdout.take().expect("piped stdout");
260 let line = BufReader::new(stdout).lines().next_line().await.expect("read").expect("line");
261 assert_eq!(line.trim(), "ready");
262
263 let (status, outcome) = tokio::time::timeout(
264 Duration::from_secs(10),
265 quiesce_srv(&mut child, stdin, Duration::from_secs(5)),
266 )
267 .await
268 .expect("quiesce_srv hung")
269 .expect("quiesce_srv errored");
270
271 assert_eq!(outcome, QuiesceOutcome::ExitedGracefully);
272 assert!(status.success());
273 }
274
275 #[cfg(not(target_os = "windows"))]
276 #[tokio::test]
277 async fn a_child_that_honors_sigterm_exits_gracefully_not_via_force_kill() {
278 let mut child = spawn_long_lived();
283
284 let (_status, outcome) = tokio::time::timeout(
285 Duration::from_secs(5),
286 quiesce_srv(&mut child, None, GRACEFUL_QUIESCE_TIMEOUT),
287 )
288 .await
289 .expect("quiesce_srv hung")
290 .expect("quiesce_srv errored");
291
292 assert_eq!(outcome, QuiesceOutcome::ExitedGracefully);
293 }
294}