1use crate::Result;
2use crate::settings::settings;
3#[cfg(windows)]
4use crate::shell::HideConsoleWindow;
5use miette::IntoDiagnostic;
6use once_cell::sync::Lazy;
7use std::collections::HashMap;
8#[cfg(target_os = "linux")]
9use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
10use std::sync::Mutex;
11use std::time::{Duration, Instant};
12use sysinfo::ProcessesToUpdate;
13#[cfg(windows)]
14use windows_sys::Win32::Foundation::{CloseHandle, FILETIME, HANDLE};
15#[cfg(windows)]
16use windows_sys::Win32::System::Threading::{
17 GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
18};
19
20type ParentToChildren = HashMap<u32, Vec<u32>>;
22
23type ProcessNames = HashMap<u32, (String, Option<String>)>;
25
26const FULL_REFRESH_INTERVAL: Duration = Duration::from_secs(5);
32
33pub struct Procs {
34 system: Mutex<sysinfo::System>,
35 last_full_refresh: Mutex<Option<Instant>>,
38}
39
40pub static PROCS: Lazy<Procs> = Lazy::new(Procs::new);
41
42pub const PROCESS_GROUP_SIGKILL_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
45
46pub const JOB_EXIT_WAIT: std::time::Duration = if cfg!(windows) {
50 std::time::Duration::from_secs(5)
51} else {
52 std::time::Duration::ZERO
53};
54
55impl Default for Procs {
56 fn default() -> Self {
57 Self::new()
58 }
59}
60
61impl Procs {
62 pub fn new() -> Self {
63 Self {
76 system: Mutex::new(
79 sysinfo::System::new().expect("sysinfo is supported on this platform"),
80 ),
81 last_full_refresh: Mutex::new(None),
82 }
83 }
84
85 fn lock_system(&self) -> std::sync::MutexGuard<'_, sysinfo::System> {
86 self.system.lock().unwrap_or_else(|poisoned| {
87 warn!("System mutex was poisoned, recovering");
88 poisoned.into_inner()
89 })
90 }
91
92 pub fn title(&self, pid: u32) -> Option<String> {
93 self.lock_system()
94 .process(sysinfo::Pid::from_u32(pid))
95 .map(|p| p.name().to_string_lossy().to_string())
96 }
97
98 pub fn boot_time(&self) -> u64 {
109 sysinfo::System::boot_time().unwrap_or_else(|err| {
110 warn!("could not read the system boot time: {err}");
111 0
112 })
113 }
114
115 pub fn start_time(&self, pid: u32) -> Option<u64> {
121 process_start_token(pid)
122 }
123
124 #[cfg(not(windows))]
125 fn start_time_matches(&self, pid: u32, expected: u64) -> bool {
126 self.start_time(pid) == Some(expected)
127 }
128
129 pub fn is_running(&self, pid: u32) -> bool {
130 #[cfg(unix)]
136 {
137 unsafe {
138 if libc::kill(pid as i32, 0) == 0 {
139 return true;
140 }
141 std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
142 }
143 }
144 #[cfg(not(unix))]
145 {
146 self.refresh_pids(&[pid]);
147 self.lock_system()
148 .process(sysinfo::Pid::from_u32(pid))
149 .is_some()
150 }
151 }
152
153 #[allow(dead_code)]
156 pub fn all_children(&self, pid: u32) -> Vec<u32> {
157 let system = self.lock_system();
158 let all = system.processes();
159 let mut children = vec![];
160 for (child_pid, process) in all {
161 let mut process = process;
162 while let Some(parent) = process.parent() {
163 if parent == sysinfo::Pid::from_u32(pid) {
164 children.push(child_pid.as_u32());
165 break;
166 }
167 match system.process(parent) {
168 Some(p) => process = p,
169 None => break,
170 }
171 }
172 }
173 children
174 }
175 pub fn collect_process_tree_info(&self) -> (ParentToChildren, ProcessNames) {
180 let system = self.lock_system();
181 let all = system.processes();
182 let mut parent_to_children: ParentToChildren = HashMap::new();
183 let mut process_info: ProcessNames = HashMap::new();
184
185 for (pid, proc) in all {
186 let pid_u32 = pid.as_u32();
187 process_info.insert(
188 pid_u32,
189 (
190 proc.name().to_string_lossy().to_string(),
191 proc.exe().map(|e| e.to_string_lossy().to_string()),
192 ),
193 );
194
195 if let Some(ppid) = proc.parent() {
196 parent_to_children
197 .entry(ppid.as_u32())
198 .or_default()
199 .push(pid_u32);
200 }
201 }
202
203 (parent_to_children, process_info)
204 }
205 pub async fn kill_process_group_async(
206 &self,
207 pid: u32,
208 stop_signal: i32,
209 stop_timeout: Option<std::time::Duration>,
210 ) -> Result<bool> {
211 tokio::task::spawn_blocking(move || {
212 PROCS.kill_process_group(pid, stop_signal, stop_timeout, None)
213 })
214 .await
215 .into_diagnostic()?
216 }
217
218 pub async fn kill_process_group_if_start_time_matches_async(
228 &self,
229 pid: u32,
230 expected_start_time: Option<u64>,
231 stop_signal: i32,
232 stop_timeout: Option<std::time::Duration>,
233 ) -> Result<bool> {
234 let Some(expected_start_time) = expected_start_time else {
235 warn!(
236 "no recorded start time for pid {pid}; refusing to signal it (identity cannot be bound to a process generation)"
237 );
238 return Ok(false);
239 };
240 tokio::task::spawn_blocking(move || {
241 PROCS.kill_process_group(pid, stop_signal, stop_timeout, Some(expected_start_time))
242 })
243 .await
244 .into_diagnostic()?
245 }
246
247 pub async fn kill_if_start_time_matches_async(
267 &self,
268 pid: u32,
269 expected_start_time: Option<u64>,
270 stop_signal: i32,
271 stop_timeout: Option<std::time::Duration>,
272 ) -> Result<bool> {
273 let Some(expected_start_time) = expected_start_time else {
274 warn!(
275 "no recorded start time for pid {pid}; refusing to signal it (identity cannot be bound to a process generation)"
276 );
277 return Ok(false);
278 };
279 tokio::task::spawn_blocking(move || {
280 PROCS.kill_if_start_time_matches(pid, expected_start_time, stop_signal, stop_timeout)
281 })
282 .await
283 .into_diagnostic()?
284 }
285
286 #[cfg(target_os = "linux")]
287 fn kill_if_start_time_matches(
288 &self,
289 pid: u32,
290 expected_start_time: u64,
291 stop_signal: i32,
292 stop_timeout: Option<std::time::Duration>,
293 ) -> Result<bool> {
294 let pidfd = match open_pidfd(pid) {
295 Ok(pidfd) => pidfd,
296 Err(err) if err.raw_os_error() == Some(libc::ESRCH) => {
297 debug!("process {pid} no longer exists");
298 return Ok(false);
299 }
300 Err(err) => {
301 return Err(miette::miette!(
302 "cannot securely identify process {pid}: {err}"
303 ));
304 }
305 };
306 if !self.verify_start_time_before_signal(pid, expected_start_time)? {
311 return Ok(false);
312 }
313 let target = [(pid, pidfd)];
314 let signal_name = signal_name(stop_signal);
315 debug!("sending {signal_name} to pinned process {pid}");
316 signal_pidfds(&target, stop_signal, signal_name)?;
317
318 let stop_timeout = stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
321 let fast_ms = 10u64;
322 let slow_ms = 50u64;
323 let total_ms = stop_timeout.as_millis().max(1) as u64;
324 let fast_count = ((total_ms / fast_ms) as usize).min(10);
325 let fast_total_ms = fast_ms * fast_count as u64;
326 let slow_count = (total_ms.saturating_sub(fast_total_ms) / slow_ms) as usize;
327 for i in 0..fast_count {
328 std::thread::sleep(std::time::Duration::from_millis(fast_ms));
329 if !pidfd_is_running(&target[0].1) {
330 debug!(
331 "process {pid} terminated after {signal_name} ({} ms)",
332 (i + 1) as u64 * fast_ms
333 );
334 return Ok(true);
335 }
336 }
337 for i in 0..slow_count {
338 std::thread::sleep(std::time::Duration::from_millis(slow_ms));
339 if !pidfd_is_running(&target[0].1) {
340 debug!(
341 "process {pid} terminated after {signal_name} ({} ms)",
342 fast_total_ms + (i + 1) as u64 * slow_ms
343 );
344 return Ok(true);
345 }
346 }
347
348 warn!(
349 "process {pid} did not respond to {signal_name} after {}ms, sending SIGKILL",
350 stop_timeout.as_millis()
351 );
352 signal_pidfds(&target, libc::SIGKILL, "SIGKILL")?;
353 std::thread::sleep(std::time::Duration::from_millis(100));
355 Ok(true)
356 }
357
358 #[cfg(not(target_os = "linux"))]
359 fn kill_if_start_time_matches(
360 &self,
361 pid: u32,
362 expected_start_time: u64,
363 stop_signal: i32,
364 stop_timeout: Option<std::time::Duration>,
365 ) -> Result<bool> {
366 #[cfg(windows)]
370 let _pin = open_process_handle(pid).ok();
371
372 if !self.verify_start_time_before_signal(pid, expected_start_time)? {
373 return Ok(false);
374 }
375 self.kill(pid, stop_signal, stop_timeout, Some(expected_start_time))
376 }
377
378 fn verify_start_time_before_signal(&self, pid: u32, expected_start_time: u64) -> Result<bool> {
390 match self.start_time(pid) {
391 Some(current) if current == expected_start_time => Ok(true),
392 Some(current) => {
393 warn!(
394 "pid {pid} is not the recorded process (start time {current}, expected {expected_start_time}); not signalling it"
395 );
396 Ok(false)
397 }
398 None if self.is_running(pid) => Err(miette::miette!(
399 "cannot verify the identity of pid {pid}: its start time is unreadable; not signalling it"
400 )),
401 None => {
402 debug!("process {pid} no longer exists");
403 Ok(false)
404 }
405 }
406 }
407
408 #[cfg(unix)]
425 fn kill_process_group(
426 &self,
427 pid: u32,
428 stop_signal: i32,
429 stop_timeout: Option<std::time::Duration>,
430 expected_start_time: Option<u64>,
431 ) -> Result<bool> {
432 let pgid = pid as i32;
433 let signal_name = signal_name(stop_signal);
434
435 #[cfg(target_os = "linux")]
436 if let Some(expected) = expected_start_time {
437 return self.kill_process_group_with_pidfds(pid, expected, stop_signal, stop_timeout);
438 }
439
440 #[cfg(not(target_os = "linux"))]
452 if let Some(expected) = expected_start_time
453 && !self.start_time_matches(pid, expected)
454 {
455 debug!("process {pid} identity changed before killpg; refusing to signal it");
456 return Ok(false);
457 }
458
459 debug!("killing process group {pgid} with {signal_name}");
460
461 let ret = unsafe { libc::killpg(pgid, stop_signal) };
466 if ret == -1 {
467 let err = std::io::Error::last_os_error();
468 if err.raw_os_error() == Some(libc::ESRCH) {
469 debug!("process group {pgid} no longer exists");
470 return Ok(false);
471 }
472 if err.raw_os_error() == Some(libc::EPERM) {
473 return Err(miette::miette!(
474 "failed to send {signal_name} to process group {pgid}: permission denied"
475 ));
476 }
477 warn!("failed to send {signal_name} to process group {pgid}: {err}");
478 }
479
480 let stop_timeout = stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
490 let fast_ms = 10u64;
491 let slow_ms = 50u64;
492 let total_ms = stop_timeout.as_millis().max(1) as u64;
493 let fast_count = ((total_ms / fast_ms) as usize).min(10);
494 let fast_total_ms = fast_ms * fast_count as u64;
495 let remaining_ms = total_ms.saturating_sub(fast_total_ms);
496 let slow_count = (remaining_ms / slow_ms) as usize;
497
498 let fast_checks =
499 std::iter::repeat_n(std::time::Duration::from_millis(fast_ms), fast_count);
500 let slow_checks =
501 std::iter::repeat_n(std::time::Duration::from_millis(slow_ms), slow_count);
502 let mut elapsed_ms = 0u64;
503
504 for sleep_duration in fast_checks.chain(slow_checks) {
505 std::thread::sleep(sleep_duration);
506 elapsed_ms += sleep_duration.as_millis() as u64;
507 if process_group_terminated(pgid) {
508 debug!("process group {pgid} terminated after {signal_name} ({elapsed_ms} ms)",);
509 return Ok(true);
510 }
511 }
512
513 warn!(
515 "process group {pgid} did not respond to {signal_name} after {}ms, sending SIGKILL",
516 stop_timeout.as_millis()
517 );
518 let ret = unsafe { libc::killpg(pgid, libc::SIGKILL) };
519 if ret == -1 {
520 let err = std::io::Error::last_os_error();
521 if err.raw_os_error() != Some(libc::ESRCH) {
522 warn!("failed to send SIGKILL to process group {pgid}: {err}");
523 }
524 }
525
526 let sigkill_polls = PROCESS_GROUP_SIGKILL_WAIT.as_millis() / 50;
530 for _ in 0..sigkill_polls {
531 std::thread::sleep(std::time::Duration::from_millis(50));
532 if process_group_terminated(pgid) {
533 return Ok(true);
534 }
535 }
536 Err(miette::miette!(
539 "process group {pgid} still has members after SIGKILL \
540 (possibly stuck in uninterruptible sleep)"
541 ))
542 }
543
544 pub fn process_group_alive(&self, pid: u32) -> bool {
547 #[cfg(unix)]
548 {
549 !process_group_terminated(pid as i32)
550 }
551 #[cfg(not(unix))]
552 {
553 self.is_running(pid)
554 }
555 }
556
557 pub fn is_live(&self, pid: u32) -> bool {
561 if !self.is_running(pid) {
562 return false;
563 }
564 self.refresh_pids(&[pid]);
565 self.lock_system()
566 .process(sysinfo::Pid::from_u32(pid))
567 .is_none_or(|p| !is_exited_status(p.status()))
568 }
569
570 pub fn process_group_has_live_member(&self, pgid: u32) -> bool {
575 #[cfg(unix)]
576 {
577 if unsafe { libc::killpg(pgid as i32, 0) } != 0
580 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH)
581 {
582 return false;
583 }
584 self.refresh_processes();
585 self.lock_system().processes().iter().any(|(pid, p)| {
586 !is_exited_status(p.status())
587 && unsafe { libc::getpgid(pid.as_u32() as i32) } == pgid as i32
588 })
589 }
590 #[cfg(not(unix))]
591 {
592 self.is_live(pgid)
593 }
594 }
595
596 #[cfg(target_os = "linux")]
597 fn kill_process_group_with_pidfds(
598 &self,
599 pid: u32,
600 expected_start_time: u64,
601 _stop_signal: i32,
602 stop_timeout: Option<std::time::Duration>,
603 ) -> Result<bool> {
604 let leader = match open_pidfd(pid) {
605 Ok(pidfd) => pidfd,
606 Err(err) => {
607 warn!("cannot securely identify process group {pid}: {err}");
608 return Ok(false);
609 }
610 };
611 if !self.start_time_matches(pid, expected_start_time) {
612 debug!("process group {pid} leader identity changed before signaling");
613 return Ok(false);
614 }
615
616 let mut members = vec![(pid, leader)];
617 if let Err(err) = stop_pidfds(&members) {
618 let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
619 return Err(err);
620 }
621 if !pidfd_is_running(&members[0].1) {
622 debug!("process group {pid} leader exited before it could be frozen");
623 return Ok(false);
624 }
625
626 loop {
630 let known_members = members.len();
631 let added = match extend_process_group_pidfds(pid as i32, &mut members) {
632 Ok(added) => added,
633 Err(err) => {
634 let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
635 return Err(miette::miette!(
636 "failed to scan pinned process group {pid}: {err}"
637 ));
638 }
639 };
640 if added == 0 {
641 break;
642 }
643 if let Err(err) = stop_pidfds(&members[known_members..]) {
644 let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
645 return Err(err);
646 }
647 }
648
649 warn!(
650 "force-terminating {} pinned orphan process(es) in group {pid}",
651 members.len()
652 );
653 if let Err(err) = signal_pidfds(&members, libc::SIGKILL, "SIGKILL") {
654 let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
655 return Err(err);
656 }
657
658 let exit_timeout = stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
659 let checks = exit_timeout.as_millis().max(1).div_ceil(50) as usize;
660 for _ in 0..checks {
661 if members.iter().all(|(_, pidfd)| !pidfd_is_running(pidfd)) {
662 return Ok(true);
663 }
664 std::thread::sleep(std::time::Duration::from_millis(50));
665 }
666 if members.iter().all(|(_, pidfd)| !pidfd_is_running(pidfd)) {
667 return Ok(true);
668 }
669
670 warn!("one or more pinned processes in orphan group {pid} remained alive after SIGKILL");
671 let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
672 Ok(false)
673 }
674
675 #[cfg(not(unix))]
676 fn kill_process_group(
677 &self,
678 pid: u32,
679 stop_signal: i32,
680 stop_timeout: Option<std::time::Duration>,
681 expected_start_time: Option<u64>,
682 ) -> Result<bool> {
683 #[cfg(windows)]
686 let _identity_handle = if let Some(expected) = expected_start_time {
687 let handle = match open_process_handle(pid) {
688 Ok(handle) => handle,
689 Err(err) => {
690 warn!("cannot securely identify process {pid}: {err}");
691 return Ok(false);
692 }
693 };
694 if process_start_token_from_handle(handle.0) != Some(expected) {
695 debug!("process {pid} identity changed before taskkill");
696 return Ok(false);
697 }
698 Some(handle)
699 } else {
700 None
701 };
702
703 #[cfg(not(windows))]
704 if let Some(expected) = expected_start_time
705 && !self.start_time_matches(pid, expected)
706 {
707 debug!("process {pid} identity changed before termination");
708 return Ok(false);
709 }
710
711 self.kill(pid, stop_signal, stop_timeout, expected_start_time)
712 }
713
714 #[cfg(not(target_os = "linux"))]
732 fn kill(
733 &self,
734 pid: u32,
735 stop_signal: i32,
736 stop_timeout: Option<std::time::Duration>,
737 expected_start_time: Option<u64>,
738 ) -> Result<bool> {
739 debug!("killing process {pid}");
740
741 #[cfg(windows)]
742 {
743 let _ = expected_start_time;
746 let job = open_process_handle(pid)
755 .ok()
756 .and_then(|process| crate::win_job::DaemonJob::open(pid, process.0));
757 if stop_signal == crate::config_types::StopSignal::SIGINT {
758 let stop_timeout =
759 stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
760 if interrupt_and_wait(pid, stop_timeout) {
761 debug!("process {pid} exited after Ctrl+C");
762 if job.as_ref().is_some_and(job_outlives_termination) {
764 return Err(miette::miette!(
765 "process {pid} exited after Ctrl+C, but processes it started may \
766 still be running: its job was not terminated and emptied within {}s",
767 JOB_EXIT_WAIT.as_secs()
768 ));
769 }
770 return Ok(true);
771 }
772 }
773 debug!("forcing process tree termination for pid {pid}");
781 let output = std::process::Command::new("taskkill")
782 .args(["/F", "/T", "/PID"])
783 .arg(pid.to_string())
784 .hide_console_window()
785 .output();
786 let taskkill_succeeded = match output {
787 Ok(o) if o.status.success() => {
788 debug!("taskkill /F /T /PID {pid} succeeded");
789 true
790 }
791 Ok(o) => {
792 debug!(
793 "taskkill /F /T /PID {pid} exited with status {}: {}",
794 o.status,
795 String::from_utf8_lossy(&o.stderr).trim()
796 );
797 false
798 }
799 Err(e) => {
800 debug!("failed to spawn taskkill for pid {pid}: {e}");
801 false
802 }
803 };
804 let job_outlived = job.as_ref().is_some_and(job_outlives_termination);
807 std::thread::sleep(std::time::Duration::from_millis(200));
811 if !taskkill_succeeded && self.is_running(pid) {
812 return Err(miette::miette!(
813 "taskkill failed and process {pid} is still running"
814 ));
815 }
816 if job_outlived {
819 return Err(miette::miette!(
820 "processes of daemon {pid} may still be running: its job was not \
821 terminated and emptied within {}s",
822 JOB_EXIT_WAIT.as_secs()
823 ));
824 }
825 Ok(true)
826 }
827
828 #[cfg(unix)]
829 {
830 let sysinfo_pid = sysinfo::Pid::from_u32(pid);
831 let signal_name = signal_name(stop_signal);
832 if let Some(expected) = expected_start_time
837 && !self.verify_start_time_before_signal(pid, expected)?
838 {
839 return Ok(false);
840 }
841 debug!("sending {signal_name} to process {pid}");
845 let ret = unsafe { libc::kill(pid as i32, stop_signal) };
846 if ret == -1 {
847 let err = std::io::Error::last_os_error();
848 if err.raw_os_error() == Some(libc::ESRCH) {
849 debug!("process {pid} no longer exists");
850 return Ok(false);
851 }
852 if err.raw_os_error() == Some(libc::EPERM) {
853 return Err(miette::miette!(
854 "failed to send {signal_name} to process {pid}: permission denied"
855 ));
856 }
857 return Err(miette::miette!(
858 "failed to send {signal_name} to process {pid}: {err}"
859 ));
860 }
861
862 let stop_timeout = stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
865 let fast_ms = 10u64;
866 let slow_ms = 50u64;
867 let total_ms = stop_timeout.as_millis().max(1) as u64;
868 let fast_count = ((total_ms / fast_ms) as usize).min(10);
869 let fast_total_ms = fast_ms * fast_count as u64;
870 let remaining_ms = total_ms.saturating_sub(fast_total_ms);
871 let slow_count = (remaining_ms / slow_ms) as usize;
872
873 for i in 0..fast_count {
874 std::thread::sleep(std::time::Duration::from_millis(fast_ms));
875 self.refresh_pids(&[pid]);
876 if self.is_terminated_or_zombie(sysinfo_pid) {
877 debug!(
878 "process {pid} terminated after {signal_name} ({} ms)",
879 (i + 1) * fast_ms as usize
880 );
881 return Ok(true);
882 }
883 }
884
885 for i in 0..slow_count {
887 std::thread::sleep(std::time::Duration::from_millis(slow_ms));
888 self.refresh_pids(&[pid]);
889 if self.is_terminated_or_zombie(sysinfo_pid) {
890 debug!(
891 "process {pid} terminated after {signal_name} ({} ms)",
892 fast_total_ms + (i + 1) as u64 * slow_ms
893 );
894 return Ok(true);
895 }
896 }
897
898 if let Some(expected) = expected_start_time
903 && !self.start_time_matches(pid, expected)
904 {
905 debug!(
906 "process {pid} exited during the stop timeout and its PID was recycled; not sending SIGKILL"
907 );
908 return Ok(true);
909 }
910 warn!(
911 "process {pid} did not respond to {signal_name} after {}ms, sending SIGKILL",
912 stop_timeout.as_millis()
913 );
914 let ret = unsafe { libc::kill(pid as i32, libc::SIGKILL) };
915 if ret == -1 {
916 let err = std::io::Error::last_os_error();
917 if err.raw_os_error() != Some(libc::ESRCH) {
918 warn!("failed to send SIGKILL to process {pid}: {err}");
919 }
920 }
921
922 std::thread::sleep(std::time::Duration::from_millis(100));
924 Ok(true)
925 }
926 }
927
928 #[cfg(all(unix, not(target_os = "linux")))]
932 fn is_terminated_or_zombie(&self, sysinfo_pid: sysinfo::Pid) -> bool {
933 let system = self.lock_system();
934 match system.process(sysinfo_pid) {
935 None => true,
936 Some(process) => {
937 matches!(process.status(), sysinfo::ProcessStatus::Zombie)
938 }
939 }
940 }
941
942 pub(crate) fn refresh_processes(&self) {
943 let mut system = self.lock_system();
944 system.refresh_processes(ProcessesToUpdate::All, true);
945 #[cfg(windows)]
950 system.refresh_cpu_usage();
951 }
952
953 pub(crate) fn refresh_pids(&self, pids: &[u32]) {
956 let sysinfo_pids: Vec<sysinfo::Pid> =
957 pids.iter().map(|p| sysinfo::Pid::from_u32(*p)).collect();
958 self.lock_system()
959 .refresh_processes(ProcessesToUpdate::Some(&sysinfo_pids), true);
960 }
961
962 pub(crate) fn refresh_if_stale(&self) {
979 let mut last = self
980 .last_full_refresh
981 .lock()
982 .unwrap_or_else(|poisoned| poisoned.into_inner());
983 if last.is_none_or(|t| t.elapsed() >= FULL_REFRESH_INTERVAL) {
984 self.refresh_processes();
985 *last = Some(Instant::now());
986 }
987 }
988
989 pub fn get_batch_group_stats(&self, pids: &[u32]) -> Vec<(u32, Option<ProcessStats>)> {
995 if pids.is_empty() {
996 return Vec::new();
997 }
998
999 let system = self.lock_system();
1000 let processes = system.processes();
1001
1002 let now = std::time::SystemTime::now()
1003 .duration_since(std::time::UNIX_EPOCH)
1004 .map(|d| d.as_secs())
1005 .unwrap_or(0);
1006
1007 let mut children_map: std::collections::HashMap<sysinfo::Pid, Vec<sysinfo::Pid>> =
1009 std::collections::HashMap::new();
1010 for (child_pid, child) in processes {
1011 if child.thread_kind().is_some() {
1014 continue;
1015 }
1016 if let Some(ppid) = child.parent() {
1017 children_map.entry(ppid).or_default().push(*child_pid);
1018 }
1019 }
1020
1021 pids.iter()
1022 .map(|&pid| {
1023 let root_pid = sysinfo::Pid::from_u32(pid);
1024 let Some(root) = processes.get(&root_pid) else {
1025 return (pid, None);
1026 };
1027
1028 let root_disk = root.disk_usage();
1029 let mut stats = ProcessStats {
1030 cpu_percent: root.cpu_usage(),
1031 memory_bytes: root.memory(),
1032 uptime_secs: now.saturating_sub(root.start_time()),
1033 disk_read_bytes: root_disk.read_bytes,
1034 disk_write_bytes: root_disk.written_bytes,
1035 };
1036
1037 let mut queue = std::collections::VecDeque::new();
1039 if let Some(direct_children) = children_map.get(&root_pid) {
1040 queue.extend(direct_children);
1041 }
1042 while let Some(child_pid) = queue.pop_front() {
1043 if let Some(child) = processes.get(&child_pid) {
1044 let disk = child.disk_usage();
1045 stats.cpu_percent += child.cpu_usage();
1046 stats.memory_bytes += child.memory();
1047 stats.disk_read_bytes += disk.read_bytes;
1048 stats.disk_write_bytes += disk.written_bytes;
1049 }
1050 if let Some(grandchildren) = children_map.get(&child_pid) {
1051 queue.extend(grandchildren);
1052 }
1053 }
1054
1055 (pid, Some(stats))
1056 })
1057 .collect()
1058 }
1059 pub fn refresh_and_get_batch_stats(&self, pids: &[u32]) -> HashMap<u32, ProcessStats> {
1069 self.refresh_processes();
1070 self.get_batch_group_stats(pids)
1071 .into_iter()
1072 .filter_map(|(pid, stats)| stats.map(|s| (pid, s)))
1073 .collect()
1074 }
1075
1076 pub fn refresh_and_get_batch_stats_if_stale(&self, pids: &[u32]) -> HashMap<u32, ProcessStats> {
1083 self.refresh_if_stale();
1084 self.get_batch_group_stats(pids)
1085 .into_iter()
1086 .filter_map(|(pid, stats)| stats.map(|s| (pid, s)))
1087 .collect()
1088 }
1089
1090 pub fn get_batch_tree_stats_map(&self, pids: &[u32]) -> HashMap<u32, ProcessStats> {
1092 self.get_batch_group_stats(pids)
1093 .into_iter()
1094 .filter_map(|(pid, stats)| stats.map(|stats| (pid, stats)))
1095 .collect()
1096 }
1097
1098 pub fn get_stats(&self, pid: u32) -> Option<ProcessStats> {
1100 self.get_batch_group_stats(&[pid])
1101 .into_iter()
1102 .next()
1103 .and_then(|(_, stats)| stats)
1104 }
1105
1106 pub fn get_extended_stats(&self, pid: u32) -> Option<ExtendedProcessStats> {
1108 let system = self.lock_system();
1109 let processes = system.processes();
1110 let root_pid = sysinfo::Pid::from_u32(pid);
1111 let p = processes.get(&root_pid)?;
1112
1113 let now = std::time::SystemTime::now()
1114 .duration_since(std::time::UNIX_EPOCH)
1115 .map(|d| d.as_secs())
1116 .unwrap_or(0);
1117
1118 let root_disk = p.disk_usage();
1119 let mut aggregate_stats = ProcessStats {
1120 cpu_percent: p.cpu_usage(),
1121 memory_bytes: p.memory(),
1122 uptime_secs: now.saturating_sub(p.start_time()),
1123 disk_read_bytes: root_disk.read_bytes,
1124 disk_write_bytes: root_disk.written_bytes,
1125 };
1126
1127 let mut children_map: HashMap<sysinfo::Pid, Vec<sysinfo::Pid>> = HashMap::new();
1128 for (child_pid, child) in processes {
1129 if let Some(ppid) = child.parent() {
1130 children_map.entry(ppid).or_default().push(*child_pid);
1131 }
1132 }
1133
1134 let mut queue = std::collections::VecDeque::new();
1135 if let Some(direct_children) = children_map.get(&root_pid) {
1136 queue.extend(direct_children);
1137 }
1138 while let Some(child_pid) = queue.pop_front() {
1139 if let Some(child) = processes.get(&child_pid) {
1140 let disk = child.disk_usage();
1141 aggregate_stats.cpu_percent += child.cpu_usage();
1142 aggregate_stats.memory_bytes += child.memory();
1143 aggregate_stats.disk_read_bytes += disk.read_bytes;
1144 aggregate_stats.disk_write_bytes += disk.written_bytes;
1145 }
1146 if let Some(grandchildren) = children_map.get(&child_pid) {
1147 queue.extend(grandchildren);
1148 }
1149 }
1150
1151 Some(ExtendedProcessStats {
1152 name: p.name().to_string_lossy().to_string(),
1153 status: format!("{:?}", p.status()),
1154 cpu_percent: aggregate_stats.cpu_percent,
1155 memory_bytes: aggregate_stats.memory_bytes,
1156 virtual_memory_bytes: p.virtual_memory(),
1157 uptime_secs: aggregate_stats.uptime_secs,
1158 thread_count: p.tasks().map(|t| t.len()).unwrap_or(0),
1159 })
1160 }
1161}
1162
1163#[cfg(target_os = "linux")]
1164fn process_start_token(pid: u32) -> Option<u64> {
1165 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
1166 let command_end = stat.rfind(')')?;
1167 stat.get(command_end + 1..)?
1169 .split_whitespace()
1170 .nth(19)?
1171 .parse()
1172 .ok()
1173}
1174
1175#[cfg(target_os = "macos")]
1176fn process_start_token(pid: u32) -> Option<u64> {
1177 let mut info = std::mem::MaybeUninit::<libc::proc_bsdinfo>::zeroed();
1178 let size = std::mem::size_of::<libc::proc_bsdinfo>() as i32;
1179 let read = unsafe {
1180 libc::proc_pidinfo(
1181 pid as i32,
1182 libc::PROC_PIDTBSDINFO,
1183 0,
1184 info.as_mut_ptr().cast(),
1185 size,
1186 )
1187 };
1188 if read != size {
1189 return None;
1190 }
1191 let info = unsafe { info.assume_init() };
1192 info.pbi_start_tvsec
1193 .checked_mul(1_000_000)?
1194 .checked_add(info.pbi_start_tvusec)
1195}
1196
1197#[cfg(windows)]
1198fn process_start_token(pid: u32) -> Option<u64> {
1199 let handle = open_process_handle(pid).ok()?;
1200 process_start_token_from_handle(handle.0)
1201}
1202
1203#[cfg(windows)]
1204pub(crate) fn process_start_token_from_handle(handle: HANDLE) -> Option<u64> {
1205 let mut creation = FILETIME {
1206 dwLowDateTime: 0,
1207 dwHighDateTime: 0,
1208 };
1209 let mut exit = creation;
1210 let mut kernel = creation;
1211 let mut user = creation;
1212 let ok = unsafe { GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user) };
1213 if ok == 0 {
1214 return None;
1215 }
1216
1217 Some((u64::from(creation.dwHighDateTime) << 32) | u64::from(creation.dwLowDateTime))
1218}
1219
1220#[cfg(windows)]
1221struct ProcessHandle(HANDLE);
1222
1223#[cfg(windows)]
1224impl Drop for ProcessHandle {
1225 fn drop(&mut self) {
1226 unsafe {
1227 CloseHandle(self.0);
1228 }
1229 }
1230}
1231
1232#[cfg(windows)]
1233fn open_process_handle(pid: u32) -> std::io::Result<ProcessHandle> {
1234 let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
1235 if handle.is_null() {
1236 return Err(std::io::Error::last_os_error());
1237 }
1238 Ok(ProcessHandle(handle))
1239}
1240
1241#[cfg(windows)]
1244fn job_outlives_termination(job: &crate::win_job::DaemonJob) -> bool {
1245 debug!(
1248 "terminating daemon job; active_processes={:?}",
1249 job.active_processes()
1250 );
1251 let terminated = job.terminate();
1252 let emptied = job.wait_until_empty(JOB_EXIT_WAIT);
1253 debug!("terminated a daemon's job: {terminated}; emptied: {emptied}");
1254 !emptied
1255}
1256
1257#[cfg(windows)]
1263fn interrupt_and_wait(pid: u32, timeout: Duration) -> bool {
1264 use crate::console_ctrl::EXIT_SHARED_CONSOLE;
1265 use windows_sys::Win32::Foundation::{WAIT_FAILED, WAIT_OBJECT_0};
1266 use windows_sys::Win32::System::Threading::{PROCESS_SYNCHRONIZE, WaitForSingleObject};
1267
1268 let started = Instant::now();
1269 debug!("stopping process {pid} with Ctrl+C; timeout={timeout:?}");
1270
1271 let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) };
1274 if handle.is_null() {
1275 debug!(
1276 "cannot wait for process {pid}: {}",
1277 std::io::Error::last_os_error()
1278 );
1279 return false;
1280 }
1281 let handle = ProcessHandle(handle);
1282
1283 let deadline = Instant::now().checked_add(timeout);
1288 let millis_left = || {
1289 let Some(deadline) = deadline else {
1290 return u32::MAX - 1;
1291 };
1292 let left = deadline.saturating_duration_since(Instant::now());
1293 u32::try_from(left.as_millis()).unwrap_or(u32::MAX - 1)
1294 };
1295
1296 let mut helper = match std::process::Command::new(&*crate::env::PITCHFORK_BIN)
1297 .args(["interrupt", "--pid"])
1298 .arg(pid.to_string())
1299 .arg("--supervisor-pid")
1300 .arg(std::process::id().to_string())
1301 .stdin(std::process::Stdio::null())
1302 .stdout(std::process::Stdio::null())
1303 .stderr(std::process::Stdio::piped())
1304 .hide_console_window()
1305 .spawn()
1306 {
1307 Ok(helper) => helper,
1308 Err(e) => {
1309 debug!("failed to spawn pitchfork interrupt for pid {pid}: {e}");
1310 return false;
1311 }
1312 };
1313 debug!(
1314 "spawned interrupt helper {} for pid {pid} after {:?}",
1315 helper.id(),
1316 started.elapsed()
1317 );
1318 let helper_handle = std::os::windows::io::AsRawHandle::as_raw_handle(&helper);
1319 let wait = unsafe { WaitForSingleObject(helper_handle as HANDLE, millis_left()) };
1320 if wait != WAIT_OBJECT_0 {
1321 if wait == WAIT_FAILED {
1322 debug!(
1323 "interrupt helper wait for pid {pid} failed: {}",
1324 std::io::Error::last_os_error()
1325 );
1326 }
1327 debug!(
1328 "pitchfork interrupt for pid {pid} did not finish after {:?}; wait={wait:#x}",
1329 started.elapsed()
1330 );
1331 let _ = helper.kill();
1332 let _ = helper.wait();
1333 return false;
1334 }
1335 match helper.wait_with_output() {
1336 Ok(o) if o.status.success() => {
1337 debug!(
1338 "sent Ctrl+C to process {pid}; interrupt helper finished after {:?}",
1339 started.elapsed()
1340 );
1341 }
1342 Ok(o) if o.status.code() == Some(EXIT_SHARED_CONSOLE) => {
1343 debug!("process {pid} shares the supervisor's console; not sending Ctrl+C");
1344 return false;
1345 }
1346 Ok(o) => {
1347 debug!(
1348 "pitchfork interrupt for pid {pid} exited with status {}: {}",
1349 o.status,
1350 String::from_utf8_lossy(&o.stderr).trim()
1351 );
1352 return false;
1353 }
1354 Err(e) => {
1355 debug!("failed to wait for pitchfork interrupt for pid {pid}: {e}");
1356 return false;
1357 }
1358 }
1359
1360 let wait = unsafe { WaitForSingleObject(handle.0, millis_left()) };
1361 if wait == WAIT_FAILED {
1362 debug!(
1363 "process wait for pid {pid} failed: {}",
1364 std::io::Error::last_os_error()
1365 );
1366 }
1367 debug!(
1368 "process {pid} wait after Ctrl+C ended after {:?}; wait={wait:#x}",
1369 started.elapsed()
1370 );
1371 wait == WAIT_OBJECT_0
1372}
1373
1374#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
1375fn process_start_token(pid: u32) -> Option<u64> {
1376 let mut system = sysinfo::System::new();
1377 let sysinfo_pid = sysinfo::Pid::from_u32(pid);
1378 system.refresh_processes(ProcessesToUpdate::Some(&[sysinfo_pid]), true);
1379 system
1380 .process(sysinfo_pid)
1381 .map(|process| process.start_time())
1382}
1383
1384#[cfg(target_os = "linux")]
1385fn open_pidfd(pid: u32) -> std::io::Result<OwnedFd> {
1386 let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) };
1387 if fd < 0 {
1388 return Err(std::io::Error::last_os_error());
1389 }
1390 Ok(unsafe { OwnedFd::from_raw_fd(fd as i32) })
1391}
1392
1393#[cfg(target_os = "linux")]
1394fn pidfd_is_running(pidfd: &OwnedFd) -> bool {
1395 match try_pidfd_is_running(pidfd) {
1396 Ok(running) => running,
1397 Err(err) => {
1398 warn!("failed to poll pidfd {}: {err}", pidfd.as_raw_fd());
1399 true
1400 }
1401 }
1402}
1403
1404#[cfg(target_os = "linux")]
1405fn try_pidfd_is_running(pidfd: &OwnedFd) -> std::io::Result<bool> {
1406 let mut pollfd = libc::pollfd {
1407 fd: pidfd.as_raw_fd(),
1408 events: libc::POLLIN,
1409 revents: 0,
1410 };
1411 let result = unsafe { libc::poll(&mut pollfd, 1, 0) };
1412 if result < 0 {
1413 return Err(std::io::Error::last_os_error());
1414 }
1415 Ok(result == 0)
1416}
1417
1418#[cfg(target_os = "linux")]
1419fn signal_pidfds(members: &[(u32, OwnedFd)], signal: i32, signal_name: &str) -> Result<()> {
1420 for (pid, pidfd) in members {
1421 if !pidfd_is_running(pidfd) {
1422 continue;
1423 }
1424 let result = unsafe {
1425 libc::syscall(
1426 libc::SYS_pidfd_send_signal,
1427 pidfd.as_raw_fd(),
1428 signal,
1429 std::ptr::null::<libc::siginfo_t>(),
1430 0,
1431 )
1432 };
1433 if result == -1 {
1434 let err = std::io::Error::last_os_error();
1435 if err.raw_os_error() == Some(libc::ESRCH) {
1436 continue;
1437 }
1438 return Err(miette::miette!(
1439 "failed to send {signal_name} to pinned process {pid}: {err}"
1440 ));
1441 }
1442 }
1443 Ok(())
1444}
1445
1446#[cfg(target_os = "linux")]
1447fn stop_pidfds(members: &[(u32, OwnedFd)]) -> Result<()> {
1448 signal_pidfds(members, libc::SIGSTOP, "SIGSTOP")?;
1449 for _ in 0..200 {
1450 if members.iter().all(|(pid, pidfd)| {
1451 !pidfd_is_running(pidfd) || matches!(linux_process_state(*pid), Some('T' | 't'))
1452 }) {
1453 return Ok(());
1454 }
1455 std::thread::sleep(std::time::Duration::from_millis(5));
1456 }
1457 Err(miette::miette!(
1458 "timed out while freezing orphan process group"
1459 ))
1460}
1461
1462#[cfg(target_os = "linux")]
1463fn extend_process_group_pidfds(
1464 pgid: i32,
1465 members: &mut Vec<(u32, OwnedFd)>,
1466) -> std::io::Result<usize> {
1467 let entries = std::fs::read_dir("/proc")?;
1468 let mut added = 0;
1469 for entry in entries {
1470 let entry = entry?;
1471 let Some(pid) = entry
1472 .file_name()
1473 .to_str()
1474 .and_then(|name| name.parse::<u32>().ok())
1475 else {
1476 continue;
1477 };
1478 let Some(observed_identity) = linux_process_identity(pid) else {
1479 continue;
1480 };
1481 if observed_identity.0 != pgid {
1482 continue;
1483 }
1484 let mut already_pinned = false;
1485 for (known_pid, pidfd) in members.iter() {
1486 if *known_pid == pid && try_pidfd_is_running(pidfd)? {
1487 already_pinned = true;
1488 break;
1489 }
1490 }
1491 if already_pinned {
1492 continue;
1493 }
1494
1495 let pidfd = match open_pidfd(pid) {
1496 Ok(pidfd) => pidfd,
1497 Err(err) if err.raw_os_error() == Some(libc::ESRCH) => continue,
1498 Err(err) => return Err(err),
1499 };
1500 if linux_process_identity(pid) != Some(observed_identity) {
1501 return Err(std::io::Error::other(format!(
1502 "process {pid} identity changed while pinning group {pgid}"
1503 )));
1504 }
1505 members.push((pid, pidfd));
1506 added += 1;
1507 }
1508 Ok(added)
1509}
1510
1511#[cfg(target_os = "linux")]
1512fn linux_process_identity(pid: u32) -> Option<(i32, u64)> {
1513 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
1514 let command_end = stat.rfind(')')?;
1515 let fields: Vec<_> = stat.get(command_end + 1..)?.split_whitespace().collect();
1516 Some((fields.get(2)?.parse().ok()?, fields.get(19)?.parse().ok()?))
1519}
1520
1521#[cfg(target_os = "linux")]
1522fn linux_process_state(pid: u32) -> Option<char> {
1523 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
1524 let command_end = stat.rfind(')')?;
1525 stat.get(command_end + 1..)?
1526 .split_whitespace()
1527 .next()?
1528 .chars()
1529 .next()
1530}
1531
1532#[derive(Debug, Clone, Copy)]
1533pub struct ProcessStats {
1534 pub cpu_percent: f32,
1535 pub memory_bytes: u64,
1536 pub uptime_secs: u64,
1537 pub disk_read_bytes: u64,
1538 pub disk_write_bytes: u64,
1539}
1540
1541impl ProcessStats {
1542 pub fn memory_display(&self) -> String {
1543 format_bytes(self.memory_bytes)
1544 }
1545
1546 pub fn cpu_display(&self) -> String {
1547 format!("{:.1}%", self.cpu_percent)
1548 }
1549
1550 pub fn uptime_display(&self) -> String {
1551 format_duration(self.uptime_secs)
1552 }
1553
1554 pub fn disk_read_display(&self) -> String {
1555 format_bytes_per_sec(self.disk_read_bytes)
1556 }
1557
1558 pub fn disk_write_display(&self) -> String {
1559 format_bytes_per_sec(self.disk_write_bytes)
1560 }
1561}
1562
1563#[derive(Debug, Clone)]
1564pub struct ExtendedProcessStats {
1565 pub name: String,
1566 pub status: String,
1567 pub cpu_percent: f32,
1568 pub memory_bytes: u64,
1569 pub virtual_memory_bytes: u64,
1570 pub uptime_secs: u64,
1571 pub thread_count: usize,
1572}
1573
1574fn format_bytes(bytes: u64) -> String {
1575 humanbyte::to_string(bytes, humanbyte::Format::IEC)
1576}
1577
1578pub(crate) fn format_duration(secs: u64) -> String {
1579 if secs < 60 {
1580 format!("{secs}s")
1581 } else if secs < 3600 {
1582 format!("{}m {}s", secs / 60, secs % 60)
1583 } else if secs < 86400 {
1584 let hours = secs / 3600;
1585 let mins = (secs % 3600) / 60;
1586 format!("{hours}h {mins}m")
1587 } else {
1588 let days = secs / 86400;
1589 let hours = (secs % 86400) / 3600;
1590 format!("{days}d {hours}h")
1591 }
1592}
1593
1594fn format_bytes_per_sec(bytes: u64) -> String {
1595 format!("{}/s", humanbyte::to_string(bytes, humanbyte::Format::IEC))
1596}
1597
1598#[cfg(unix)]
1614fn process_group_terminated(pgid: i32) -> bool {
1615 unsafe { libc::killpg(pgid, 0) != 0 }
1616}
1617
1618#[cfg(unix)]
1619fn signal_name(sig: i32) -> &'static str {
1620 match sig {
1621 libc::SIGHUP => "SIGHUP",
1622 libc::SIGINT => "SIGINT",
1623 libc::SIGQUIT => "SIGQUIT",
1624 libc::SIGTERM => "SIGTERM",
1625 libc::SIGUSR1 => "SIGUSR1",
1626 libc::SIGUSR2 => "SIGUSR2",
1627 libc::SIGKILL => "SIGKILL",
1628 _ => "UNKNOWN",
1629 }
1630}
1631
1632fn is_exited_status(status: sysinfo::ProcessStatus) -> bool {
1634 matches!(
1635 status,
1636 sysinfo::ProcessStatus::Zombie | sysinfo::ProcessStatus::Dead
1637 )
1638}
1639
1640#[cfg(test)]
1641mod format_tests {
1642 use super::*;
1643
1644 #[test]
1645 fn process_start_time_check_rejects_mismatch() {
1646 let procs = Procs::new();
1647 let pid = std::process::id();
1648 procs.refresh_pids(&[pid]);
1649 let actual = procs
1650 .start_time(pid)
1651 .expect("current process should have a start time");
1652
1653 assert_ne!(procs.start_time(pid), Some(actual.saturating_add(1)));
1654 }
1655
1656 #[test]
1657 fn test_format_bytes() {
1658 assert_eq!(format_bytes(512), "512 B");
1659 assert_eq!(format_bytes(1024), "1.0 KiB");
1660 assert_eq!(format_bytes(1536), "1.5 KiB");
1661 assert_eq!(format_bytes(50 * 1024 * 1024), "50.0 MiB");
1662 assert_eq!(format_bytes(3 * 1024 * 1024 * 1024), "3.0 GiB");
1663 assert_eq!(format_bytes(1100 * 1024 * 1024 * 1024), "1.1 TiB");
1665 }
1666
1667 #[test]
1668 fn test_format_bytes_per_sec() {
1669 assert_eq!(format_bytes_per_sec(512), "512 B/s");
1670 assert_eq!(format_bytes_per_sec(1536), "1.5 KiB/s");
1671 assert_eq!(format_bytes_per_sec(2 * 1024 * 1024), "2.0 MiB/s");
1672 }
1673}
1674
1675#[cfg(all(test, unix))]
1676mod tests {
1677 use super::*;
1678 use std::os::unix::process::CommandExt;
1679 use std::process::{Child, Command, Stdio};
1680 use std::time::{Duration, Instant};
1681
1682 struct ChildGuard(Child);
1683
1684 impl Drop for ChildGuard {
1685 fn drop(&mut self) {
1686 let pid = self.0.id() as i32;
1687 let _ = unsafe { libc::killpg(pid, libc::SIGKILL) };
1689 let _ = self.0.wait();
1690 }
1691 }
1692
1693 #[tokio::test]
1694 async fn orphan_identity_checked_group_kill_rejects_mismatch() {
1695 let mut command = Command::new("sleep");
1696 command
1697 .arg("30")
1698 .stdin(Stdio::null())
1699 .stdout(Stdio::null())
1700 .stderr(Stdio::null());
1701 unsafe {
1702 command.pre_exec(|| {
1703 if libc::setsid() == -1 {
1704 return Err(std::io::Error::last_os_error());
1705 }
1706 Ok(())
1707 });
1708 }
1709
1710 let child = command.spawn().expect("failed to spawn test process");
1711 let pid = child.id();
1712 let _child = ChildGuard(child);
1713
1714 PROCS.refresh_pids(&[pid]);
1715 let actual_start_time = PROCS
1716 .start_time(pid)
1717 .expect("test process should have a start time");
1718
1719 let killed = PROCS
1720 .kill_process_group_if_start_time_matches_async(
1721 pid,
1722 Some(actual_start_time.saturating_add(1)),
1723 libc::SIGTERM,
1724 Some(Duration::from_millis(100)),
1725 )
1726 .await
1727 .expect("identity-checked kill should not error");
1728
1729 assert!(!killed);
1730 assert!(PROCS.is_running(pid), "mismatched process must survive");
1731 }
1732
1733 #[cfg(all(unix, not(target_os = "linux")))]
1738 #[tokio::test]
1739 async fn identity_checked_group_kill_reverifies_inside_blocking_op() {
1740 let mut command = Command::new("sleep");
1741 command
1742 .arg("30")
1743 .stdin(Stdio::null())
1744 .stdout(Stdio::null())
1745 .stderr(Stdio::null());
1746 unsafe {
1747 command.pre_exec(|| {
1748 if libc::setsid() == -1 {
1749 return Err(std::io::Error::last_os_error());
1750 }
1751 Ok(())
1752 });
1753 }
1754
1755 let child = command.spawn().expect("failed to spawn test process");
1756 let pid = child.id();
1757 let mut child = ChildGuard(child);
1758
1759 PROCS.refresh_pids(&[pid]);
1760 let actual_start_time = PROCS
1761 .start_time(pid)
1762 .expect("test process should have a start time");
1763
1764 let killed = PROCS
1765 .kill_process_group_if_start_time_matches_async(
1766 pid,
1767 Some(actual_start_time),
1768 libc::SIGTERM,
1769 Some(Duration::from_millis(100)),
1770 )
1771 .await
1772 .expect("identity-checked kill should not error");
1773
1774 assert!(killed, "matching generation must be signalled");
1775 let deadline = Instant::now() + Duration::from_secs(2);
1778 while child.0.try_wait().unwrap().is_none() {
1779 assert!(Instant::now() < deadline, "signalled child must exit");
1780 tokio::time::sleep(Duration::from_millis(10)).await;
1781 }
1782 assert!(
1783 !PROCS.is_running(pid),
1784 "signalled process group must be gone"
1785 );
1786 }
1787
1788 #[test]
1789 fn get_stats_includes_descendant_rss() {
1790 let mut command = Command::new("sh");
1791 command
1792 .args(["-c", "sleep 30 & wait"])
1793 .stdin(Stdio::null())
1794 .stdout(Stdio::null())
1795 .stderr(Stdio::null());
1796 unsafe {
1797 command.pre_exec(|| {
1798 if libc::setsid() == -1 {
1799 return Err(std::io::Error::last_os_error());
1800 }
1801 Ok(())
1802 });
1803 }
1804
1805 let parent = command.spawn().expect("failed to spawn process tree");
1806 let parent_pid = parent.id();
1807 let _parent = ChildGuard(parent);
1808
1809 let procs = Procs::new();
1810 let deadline = Instant::now() + Duration::from_secs(5);
1811 let mut child_pids = Vec::new();
1812 while Instant::now() < deadline {
1813 procs.refresh_processes();
1814 child_pids = procs.all_children(parent_pid);
1815 if !child_pids.is_empty() {
1816 break;
1817 }
1818 std::thread::sleep(Duration::from_millis(50));
1819 }
1820 assert!(
1821 !child_pids.is_empty(),
1822 "test process tree did not appear under parent pid {parent_pid}"
1823 );
1824
1825 procs.refresh_processes();
1826 child_pids = procs.all_children(parent_pid);
1827 assert!(
1828 !child_pids.is_empty(),
1829 "test process tree disappeared under parent pid {parent_pid}"
1830 );
1831 let root_pid = sysinfo::Pid::from_u32(parent_pid);
1832 let direct_memory = {
1833 let system = procs.lock_system();
1834 system
1835 .process(root_pid)
1836 .expect("parent process should exist")
1837 .memory()
1838 };
1839 let descendant_memory = {
1840 let system = procs.lock_system();
1841 child_pids
1842 .iter()
1843 .filter_map(|pid| system.process(sysinfo::Pid::from_u32(*pid)))
1844 .map(|process| process.memory())
1845 .sum::<u64>()
1846 };
1847 assert!(
1848 descendant_memory > 0,
1849 "descendants {child_pids:?} should have nonzero RSS"
1850 );
1851
1852 let stats = procs
1853 .get_stats(parent_pid)
1854 .expect("parent process should have aggregate stats");
1855
1856 assert_eq!(
1857 stats.memory_bytes,
1858 direct_memory + descendant_memory,
1859 "get_stats should include descendant RSS for parent pid {parent_pid}; \
1860 descendants: {child_pids:?}, direct RSS: {direct_memory}, \
1861 descendant RSS: {descendant_memory}, reported RSS: {}",
1862 stats.memory_bytes
1863 );
1864 }
1865
1866 #[test]
1867 fn full_refresh_is_throttled_by_ttl() {
1868 let procs = Procs::new();
1869
1870 assert!(
1872 procs.last_full_refresh.lock().unwrap().is_none(),
1873 "fresh Procs should have no recorded refresh"
1874 );
1875 procs.refresh_if_stale();
1876 let first = procs.last_full_refresh.lock().unwrap().unwrap();
1877 assert!(first.elapsed() < FULL_REFRESH_INTERVAL);
1878
1879 procs.refresh_if_stale();
1882 let second = procs.last_full_refresh.lock().unwrap().unwrap();
1883 assert_eq!(
1884 second, first,
1885 "refresh_if_stale within TTL must skip the refresh and keep the timestamp"
1886 );
1887
1888 let expired = Instant::now()
1891 .checked_sub(FULL_REFRESH_INTERVAL + Duration::from_secs(1))
1892 .expect("system has been up long enough to backdate by 6s");
1893 *procs.last_full_refresh.lock().unwrap() = Some(expired);
1894 procs.refresh_if_stale();
1895 let third = procs.last_full_refresh.lock().unwrap().unwrap();
1896 assert!(
1897 third > expired,
1898 "refresh_if_stale after expired TTL must refresh and advance the timestamp"
1899 );
1900 assert!(
1901 third.elapsed() < FULL_REFRESH_INTERVAL,
1902 "fresh timestamp after expired-TTL refresh should be recent"
1903 );
1904 }
1905}