agentmux_srv/bootstrap/
watchers.rs1#[cfg(any(target_os = "linux", target_os = "macos"))]
15fn start_ppid_watchdog(original_ppid: u32) {
16 std::thread::spawn(move || {
17 loop {
18 let current_ppid = unsafe { libc::getppid() } as u32;
19 if current_ppid != original_ppid {
20 eprintln_lossy!(
21 "parent process died (ppid changed {} -> {}), shutting down",
22 original_ppid, current_ppid
23 );
24 std::process::exit(0);
25 }
26 std::thread::sleep(std::time::Duration::from_secs(2));
27 }
28 });
29}
30
31#[cfg(target_os = "macos")]
35fn start_parent_watcher(parent_pid: u32) {
36 std::thread::spawn(move || {
37 unsafe {
38 let kq = libc::kqueue();
39 if kq < 0 {
40 eprintln_lossy!(
41 "kqueue() failed (errno={}), falling back to ppid watchdog",
42 *libc::__error()
43 );
44 let _ = kq;
45 start_ppid_watchdog(parent_pid);
46 return;
47 }
48
49 let mut changelist: [libc::kevent; 1] = std::mem::zeroed();
51 changelist[0] = libc::kevent {
52 ident: parent_pid as usize,
53 filter: libc::EVFILT_PROC,
54 flags: libc::EV_ADD | libc::EV_ONESHOT,
55 fflags: libc::NOTE_EXIT,
56 data: 0,
57 udata: std::ptr::null_mut(),
58 };
59
60 let ret = libc::kevent(
61 kq,
62 changelist.as_ptr(),
63 1,
64 std::ptr::null_mut(),
65 0,
66 std::ptr::null(),
67 );
68
69 if ret < 0 {
70 let errno = *libc::__error();
71 libc::close(kq);
72 if errno == libc::ESRCH {
73 eprintln_lossy!(
75 "parent process {} already exited (ESRCH during kqueue registration), shutting down",
76 parent_pid
77 );
78 std::process::exit(0);
79 }
80 eprintln_lossy!(
81 "kevent() registration failed (errno={}), falling back to ppid watchdog",
82 errno
83 );
84 start_ppid_watchdog(parent_pid);
85 return;
86 }
87
88 eprintln_lossy!("kqueue EVFILT_PROC registered for parent pid {}", parent_pid);
89
90 if libc::kill(parent_pid as i32, 0) != 0 && *libc::__error() == libc::ESRCH {
93 libc::close(kq);
94 eprintln_lossy!(
95 "parent process {} already exited (post-registration check), shutting down",
96 parent_pid
97 );
98 std::process::exit(0);
99 }
100
101 let mut eventlist: [libc::kevent; 1] = std::mem::zeroed();
105 let waited = loop {
106 let n = libc::kevent(
107 kq,
108 std::ptr::null(),
109 0,
110 eventlist.as_mut_ptr(),
111 1,
112 std::ptr::null(),
113 );
114 if n > 0 {
115 break Ok(());
116 }
117 if n == 0 {
118 continue;
119 }
120 let err = std::io::Error::last_os_error();
121 if err.raw_os_error() != Some(libc::EINTR) {
122 break Err(err);
123 }
124 };
125 libc::close(kq);
126
127 match waited {
128 Ok(()) => {
129 eprintln_lossy!(
130 "parent process {} exited (kqueue EVFILT_PROC), shutting down",
131 parent_pid
132 );
133 std::process::exit(0);
134 }
135 Err(e) => {
136 eprintln_lossy!(
139 "kevent() wait failed ({}), falling back to ppid watchdog",
140 e
141 );
142 start_ppid_watchdog(parent_pid);
143 }
144 }
145 }
146 });
147}
148
149#[cfg(target_os = "linux")]
152fn start_parent_watcher(parent_pid: u32) {
153 std::thread::spawn(move || {
154 unsafe {
155 let pidfd = libc::syscall(libc::SYS_pidfd_open, parent_pid as libc::c_int, 0 as libc::c_int);
157
158 if pidfd < 0 {
159 let errno = *libc::__errno_location();
160 if errno == libc::ESRCH {
161 eprintln_lossy!(
163 "parent process {} already exited (ESRCH from pidfd_open), shutting down",
164 parent_pid
165 );
166 std::process::exit(0);
167 }
168 eprintln_lossy!(
170 "pidfd_open() failed (errno={}), falling back to ppid watchdog",
171 errno
172 );
173 start_ppid_watchdog(parent_pid);
174 return;
175 }
176
177 let pidfd = pidfd as libc::c_int;
178
179 if libc::kill(parent_pid as i32, 0) != 0 && *libc::__errno_location() == libc::ESRCH {
181 libc::close(pidfd);
182 eprintln_lossy!(
183 "parent process {} already exited (post-pidfd check), shutting down",
184 parent_pid
185 );
186 std::process::exit(0);
187 }
188
189 let waited = wait_for_pidfd_exit(pidfd);
190 libc::close(pidfd);
191
192 match waited {
193 Ok(()) => {
194 eprintln_lossy!(
195 "parent process {} exited (pidfd poll), shutting down",
196 parent_pid
197 );
198 std::process::exit(0);
199 }
200 Err(e) => {
201 eprintln_lossy!(
204 "poll() on pidfd failed ({}), falling back to ppid watchdog",
205 e
206 );
207 start_ppid_watchdog(parent_pid);
208 }
209 }
210 }
211 });
212}
213
214#[cfg(target_os = "linux")]
221fn wait_for_pidfd_exit(pidfd: libc::c_int) -> std::io::Result<()> {
222 let mut pfd = libc::pollfd {
223 fd: pidfd,
224 events: libc::POLLIN,
225 revents: 0,
226 };
227 loop {
228 let ret = unsafe { libc::poll(&mut pfd, 1, -1) }; if ret > 0 {
230 return Ok(());
231 }
232 if ret == 0 {
233 continue;
234 }
235 let err = std::io::Error::last_os_error();
236 if err.raw_os_error() != Some(libc::EINTR) {
237 return Err(err);
238 }
239 }
240}
241
242pub fn maybe_run_crash_monitor() -> bool {
249 #[cfg(windows)]
250 {
251 let args: Vec<String> = std::env::args().collect();
252 if args.iter().any(|a| a == "--crash-monitor") {
253 let parent_pid = args
255 .iter()
256 .position(|a| a == "--parent-pid")
257 .and_then(|i| args.get(i + 1))
258 .and_then(|v| v.parse().ok());
259 crate::crash_monitor::run_monitor(parent_pid);
260 return true;
261 }
262 }
263 false
264}
265
266pub fn install_process_watchers() {
271 #[cfg(any(target_os = "linux", target_os = "macos"))]
272 {
273 let ppid = unsafe { libc::getppid() } as u32;
274 if ppid <= 1 {
275 start_ppid_watchdog(ppid);
277 } else {
278 start_parent_watcher(ppid);
279 }
280 }
281}
282
283#[cfg(windows)]
289pub fn install_crash_guard() -> Option<crate::crash_monitor::CrashHandlerGuard> {
290 crate::crash_monitor::spawn_and_attach()
291}
292
293#[cfg(all(test, target_os = "linux"))]
294mod tests {
295 use super::wait_for_pidfd_exit;
296 use std::process::Command;
297 use std::sync::mpsc;
298 use std::time::Duration;
299
300 extern "C" fn ignore_signal(_: libc::c_int) {}
301
302 #[test]
306 fn a_signal_does_not_end_the_wait_only_the_process_exiting_does() {
307 unsafe {
309 let mut action: libc::sigaction = std::mem::zeroed();
310 action.sa_sigaction = ignore_signal as *const () as usize;
311 libc::sigemptyset(&mut action.sa_mask);
312 assert_eq!(
313 libc::sigaction(libc::SIGUSR1, &action, std::ptr::null_mut()),
314 0
315 );
316 }
317
318 let mut parent = Command::new("sleep")
319 .arg("60")
320 .spawn()
321 .expect("spawn sleep");
322 let pidfd = unsafe { libc::syscall(libc::SYS_pidfd_open, parent.id() as libc::c_int, 0) };
323 if pidfd < 0 {
324 let err = std::io::Error::last_os_error();
325 parent.kill().unwrap();
326 parent.wait().unwrap();
327 if matches!(err.raw_os_error(), Some(libc::ENOSYS) | Some(libc::EPERM)) {
330 eprintln!("skipping: pidfd_open unavailable ({err})");
331 return;
332 }
333 panic!("pidfd_open: {err}");
334 }
335 let pidfd = pidfd as libc::c_int;
336
337 let (thread_tx, thread_rx) = mpsc::channel();
338 let (done_tx, done_rx) = mpsc::channel();
339 std::thread::spawn(move || {
340 thread_tx.send(unsafe { libc::pthread_self() }).unwrap();
341 done_tx
342 .send(wait_for_pidfd_exit(pidfd).map_err(|e| e.to_string()))
343 .unwrap();
344 });
345 let waiter = thread_rx.recv().unwrap();
346
347 for _ in 0..10 {
348 std::thread::sleep(Duration::from_millis(20));
349 assert_eq!(unsafe { libc::pthread_kill(waiter, libc::SIGUSR1) }, 0);
350 }
351 let early = done_rx.recv_timeout(Duration::from_millis(300));
352 assert!(
353 early.is_err(),
354 "the wait ended while the process was alive: {early:?}"
355 );
356
357 parent.kill().unwrap();
358 parent.wait().unwrap();
359 let result = done_rx
360 .recv_timeout(Duration::from_secs(5))
361 .expect("the wait never ended");
362 unsafe { libc::close(pidfd) };
363 assert_eq!(result, Ok(()));
364 }
365}