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(sysinfo::System::new()),
77 last_full_refresh: Mutex::new(None),
78 }
79 }
80
81 fn lock_system(&self) -> std::sync::MutexGuard<'_, sysinfo::System> {
82 self.system.lock().unwrap_or_else(|poisoned| {
83 warn!("System mutex was poisoned, recovering");
84 poisoned.into_inner()
85 })
86 }
87
88 pub fn title(&self, pid: u32) -> Option<String> {
89 self.lock_system()
90 .process(sysinfo::Pid::from_u32(pid))
91 .map(|p| p.name().to_string_lossy().to_string())
92 }
93
94 pub fn boot_time(&self) -> u64 {
101 sysinfo::System::boot_time()
102 }
103
104 pub fn start_time(&self, pid: u32) -> Option<u64> {
110 process_start_token(pid)
111 }
112
113 #[cfg(not(windows))]
114 fn start_time_matches(&self, pid: u32, expected: u64) -> bool {
115 self.start_time(pid) == Some(expected)
116 }
117
118 pub fn is_running(&self, pid: u32) -> bool {
119 #[cfg(unix)]
125 {
126 unsafe {
127 if libc::kill(pid as i32, 0) == 0 {
128 return true;
129 }
130 std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
131 }
132 }
133 #[cfg(not(unix))]
134 {
135 self.refresh_pids(&[pid]);
136 self.lock_system()
137 .process(sysinfo::Pid::from_u32(pid))
138 .is_some()
139 }
140 }
141
142 #[allow(dead_code)]
145 pub fn all_children(&self, pid: u32) -> Vec<u32> {
146 let system = self.lock_system();
147 let all = system.processes();
148 let mut children = vec![];
149 for (child_pid, process) in all {
150 let mut process = process;
151 while let Some(parent) = process.parent() {
152 if parent == sysinfo::Pid::from_u32(pid) {
153 children.push(child_pid.as_u32());
154 break;
155 }
156 match system.process(parent) {
157 Some(p) => process = p,
158 None => break,
159 }
160 }
161 }
162 children
163 }
164 pub fn collect_process_tree_info(&self) -> (ParentToChildren, ProcessNames) {
169 let system = self.lock_system();
170 let all = system.processes();
171 let mut parent_to_children: ParentToChildren = HashMap::new();
172 let mut process_info: ProcessNames = HashMap::new();
173
174 for (pid, proc) in all {
175 let pid_u32 = pid.as_u32();
176 process_info.insert(
177 pid_u32,
178 (
179 proc.name().to_string_lossy().to_string(),
180 proc.exe().map(|e| e.to_string_lossy().to_string()),
181 ),
182 );
183
184 if let Some(ppid) = proc.parent() {
185 parent_to_children
186 .entry(ppid.as_u32())
187 .or_default()
188 .push(pid_u32);
189 }
190 }
191
192 (parent_to_children, process_info)
193 }
194 pub async fn kill_process_group_async(
195 &self,
196 pid: u32,
197 stop_signal: i32,
198 stop_timeout: Option<std::time::Duration>,
199 ) -> Result<bool> {
200 tokio::task::spawn_blocking(move || {
201 PROCS.kill_process_group(pid, stop_signal, stop_timeout, None)
202 })
203 .await
204 .into_diagnostic()?
205 }
206
207 pub async fn kill_process_group_if_start_time_matches_async(
217 &self,
218 pid: u32,
219 expected_start_time: Option<u64>,
220 stop_signal: i32,
221 stop_timeout: Option<std::time::Duration>,
222 ) -> Result<bool> {
223 let Some(expected_start_time) = expected_start_time else {
224 warn!(
225 "no recorded start time for pid {pid}; refusing to signal it (identity cannot be bound to a process generation)"
226 );
227 return Ok(false);
228 };
229 tokio::task::spawn_blocking(move || {
230 PROCS.kill_process_group(pid, stop_signal, stop_timeout, Some(expected_start_time))
231 })
232 .await
233 .into_diagnostic()?
234 }
235
236 pub async fn kill_if_start_time_matches_async(
256 &self,
257 pid: u32,
258 expected_start_time: Option<u64>,
259 stop_signal: i32,
260 stop_timeout: Option<std::time::Duration>,
261 ) -> Result<bool> {
262 let Some(expected_start_time) = expected_start_time else {
263 warn!(
264 "no recorded start time for pid {pid}; refusing to signal it (identity cannot be bound to a process generation)"
265 );
266 return Ok(false);
267 };
268 tokio::task::spawn_blocking(move || {
269 PROCS.kill_if_start_time_matches(pid, expected_start_time, stop_signal, stop_timeout)
270 })
271 .await
272 .into_diagnostic()?
273 }
274
275 #[cfg(target_os = "linux")]
276 fn kill_if_start_time_matches(
277 &self,
278 pid: u32,
279 expected_start_time: u64,
280 stop_signal: i32,
281 stop_timeout: Option<std::time::Duration>,
282 ) -> Result<bool> {
283 let pidfd = match open_pidfd(pid) {
284 Ok(pidfd) => pidfd,
285 Err(err) if err.raw_os_error() == Some(libc::ESRCH) => {
286 debug!("process {pid} no longer exists");
287 return Ok(false);
288 }
289 Err(err) => {
290 return Err(miette::miette!(
291 "cannot securely identify process {pid}: {err}"
292 ));
293 }
294 };
295 if !self.verify_start_time_before_signal(pid, expected_start_time)? {
300 return Ok(false);
301 }
302 let target = [(pid, pidfd)];
303 let signal_name = signal_name(stop_signal);
304 debug!("sending {signal_name} to pinned process {pid}");
305 signal_pidfds(&target, stop_signal, signal_name)?;
306
307 let stop_timeout = stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
310 let fast_ms = 10u64;
311 let slow_ms = 50u64;
312 let total_ms = stop_timeout.as_millis().max(1) as u64;
313 let fast_count = ((total_ms / fast_ms) as usize).min(10);
314 let fast_total_ms = fast_ms * fast_count as u64;
315 let slow_count = (total_ms.saturating_sub(fast_total_ms) / slow_ms) as usize;
316 for i in 0..fast_count {
317 std::thread::sleep(std::time::Duration::from_millis(fast_ms));
318 if !pidfd_is_running(&target[0].1) {
319 debug!(
320 "process {pid} terminated after {signal_name} ({} ms)",
321 (i + 1) as u64 * fast_ms
322 );
323 return Ok(true);
324 }
325 }
326 for i in 0..slow_count {
327 std::thread::sleep(std::time::Duration::from_millis(slow_ms));
328 if !pidfd_is_running(&target[0].1) {
329 debug!(
330 "process {pid} terminated after {signal_name} ({} ms)",
331 fast_total_ms + (i + 1) as u64 * slow_ms
332 );
333 return Ok(true);
334 }
335 }
336
337 warn!(
338 "process {pid} did not respond to {signal_name} after {}ms, sending SIGKILL",
339 stop_timeout.as_millis()
340 );
341 signal_pidfds(&target, libc::SIGKILL, "SIGKILL")?;
342 std::thread::sleep(std::time::Duration::from_millis(100));
344 Ok(true)
345 }
346
347 #[cfg(not(target_os = "linux"))]
348 fn kill_if_start_time_matches(
349 &self,
350 pid: u32,
351 expected_start_time: u64,
352 stop_signal: i32,
353 stop_timeout: Option<std::time::Duration>,
354 ) -> Result<bool> {
355 #[cfg(windows)]
359 let _pin = open_process_handle(pid).ok();
360
361 if !self.verify_start_time_before_signal(pid, expected_start_time)? {
362 return Ok(false);
363 }
364 self.kill(pid, stop_signal, stop_timeout, Some(expected_start_time))
365 }
366
367 fn verify_start_time_before_signal(&self, pid: u32, expected_start_time: u64) -> Result<bool> {
379 match self.start_time(pid) {
380 Some(current) if current == expected_start_time => Ok(true),
381 Some(current) => {
382 warn!(
383 "pid {pid} is not the recorded process (start time {current}, expected {expected_start_time}); not signalling it"
384 );
385 Ok(false)
386 }
387 None if self.is_running(pid) => Err(miette::miette!(
388 "cannot verify the identity of pid {pid}: its start time is unreadable; not signalling it"
389 )),
390 None => {
391 debug!("process {pid} no longer exists");
392 Ok(false)
393 }
394 }
395 }
396
397 #[cfg(unix)]
414 fn kill_process_group(
415 &self,
416 pid: u32,
417 stop_signal: i32,
418 stop_timeout: Option<std::time::Duration>,
419 expected_start_time: Option<u64>,
420 ) -> Result<bool> {
421 let pgid = pid as i32;
422 let signal_name = signal_name(stop_signal);
423
424 #[cfg(target_os = "linux")]
425 if let Some(expected) = expected_start_time {
426 return self.kill_process_group_with_pidfds(pid, expected, stop_signal, stop_timeout);
427 }
428
429 #[cfg(not(target_os = "linux"))]
441 if let Some(expected) = expected_start_time
442 && !self.start_time_matches(pid, expected)
443 {
444 debug!("process {pid} identity changed before killpg; refusing to signal it");
445 return Ok(false);
446 }
447
448 debug!("killing process group {pgid} with {signal_name}");
449
450 let ret = unsafe { libc::killpg(pgid, stop_signal) };
455 if ret == -1 {
456 let err = std::io::Error::last_os_error();
457 if err.raw_os_error() == Some(libc::ESRCH) {
458 debug!("process group {pgid} no longer exists");
459 return Ok(false);
460 }
461 if err.raw_os_error() == Some(libc::EPERM) {
462 return Err(miette::miette!(
463 "failed to send {signal_name} to process group {pgid}: permission denied"
464 ));
465 }
466 warn!("failed to send {signal_name} to process group {pgid}: {err}");
467 }
468
469 let stop_timeout = stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
479 let fast_ms = 10u64;
480 let slow_ms = 50u64;
481 let total_ms = stop_timeout.as_millis().max(1) as u64;
482 let fast_count = ((total_ms / fast_ms) as usize).min(10);
483 let fast_total_ms = fast_ms * fast_count as u64;
484 let remaining_ms = total_ms.saturating_sub(fast_total_ms);
485 let slow_count = (remaining_ms / slow_ms) as usize;
486
487 let fast_checks =
488 std::iter::repeat_n(std::time::Duration::from_millis(fast_ms), fast_count);
489 let slow_checks =
490 std::iter::repeat_n(std::time::Duration::from_millis(slow_ms), slow_count);
491 let mut elapsed_ms = 0u64;
492
493 for sleep_duration in fast_checks.chain(slow_checks) {
494 std::thread::sleep(sleep_duration);
495 elapsed_ms += sleep_duration.as_millis() as u64;
496 if process_group_terminated(pgid) {
497 debug!("process group {pgid} terminated after {signal_name} ({elapsed_ms} ms)",);
498 return Ok(true);
499 }
500 }
501
502 warn!(
504 "process group {pgid} did not respond to {signal_name} after {}ms, sending SIGKILL",
505 stop_timeout.as_millis()
506 );
507 let ret = unsafe { libc::killpg(pgid, libc::SIGKILL) };
508 if ret == -1 {
509 let err = std::io::Error::last_os_error();
510 if err.raw_os_error() != Some(libc::ESRCH) {
511 warn!("failed to send SIGKILL to process group {pgid}: {err}");
512 }
513 }
514
515 let sigkill_polls = PROCESS_GROUP_SIGKILL_WAIT.as_millis() / 50;
519 for _ in 0..sigkill_polls {
520 std::thread::sleep(std::time::Duration::from_millis(50));
521 if process_group_terminated(pgid) {
522 return Ok(true);
523 }
524 }
525 Err(miette::miette!(
528 "process group {pgid} still has members after SIGKILL \
529 (possibly stuck in uninterruptible sleep)"
530 ))
531 }
532
533 pub fn process_group_alive(&self, pid: u32) -> bool {
536 #[cfg(unix)]
537 {
538 !process_group_terminated(pid as i32)
539 }
540 #[cfg(not(unix))]
541 {
542 self.is_running(pid)
543 }
544 }
545
546 pub fn is_live(&self, pid: u32) -> bool {
550 if !self.is_running(pid) {
551 return false;
552 }
553 self.refresh_pids(&[pid]);
554 self.lock_system()
555 .process(sysinfo::Pid::from_u32(pid))
556 .is_none_or(|p| !is_exited_status(p.status()))
557 }
558
559 pub fn process_group_has_live_member(&self, pgid: u32) -> bool {
564 #[cfg(unix)]
565 {
566 if unsafe { libc::killpg(pgid as i32, 0) } != 0
569 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH)
570 {
571 return false;
572 }
573 self.refresh_processes();
574 self.lock_system().processes().iter().any(|(pid, p)| {
575 !is_exited_status(p.status())
576 && unsafe { libc::getpgid(pid.as_u32() as i32) } == pgid as i32
577 })
578 }
579 #[cfg(not(unix))]
580 {
581 self.is_live(pgid)
582 }
583 }
584
585 #[cfg(target_os = "linux")]
586 fn kill_process_group_with_pidfds(
587 &self,
588 pid: u32,
589 expected_start_time: u64,
590 _stop_signal: i32,
591 stop_timeout: Option<std::time::Duration>,
592 ) -> Result<bool> {
593 let leader = match open_pidfd(pid) {
594 Ok(pidfd) => pidfd,
595 Err(err) => {
596 warn!("cannot securely identify process group {pid}: {err}");
597 return Ok(false);
598 }
599 };
600 if !self.start_time_matches(pid, expected_start_time) {
601 debug!("process group {pid} leader identity changed before signaling");
602 return Ok(false);
603 }
604
605 let mut members = vec![(pid, leader)];
606 if let Err(err) = stop_pidfds(&members) {
607 let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
608 return Err(err);
609 }
610 if !pidfd_is_running(&members[0].1) {
611 debug!("process group {pid} leader exited before it could be frozen");
612 return Ok(false);
613 }
614
615 loop {
619 let known_members = members.len();
620 let added = match extend_process_group_pidfds(pid as i32, &mut members) {
621 Ok(added) => added,
622 Err(err) => {
623 let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
624 return Err(miette::miette!(
625 "failed to scan pinned process group {pid}: {err}"
626 ));
627 }
628 };
629 if added == 0 {
630 break;
631 }
632 if let Err(err) = stop_pidfds(&members[known_members..]) {
633 let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
634 return Err(err);
635 }
636 }
637
638 warn!(
639 "force-terminating {} pinned orphan process(es) in group {pid}",
640 members.len()
641 );
642 if let Err(err) = signal_pidfds(&members, libc::SIGKILL, "SIGKILL") {
643 let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
644 return Err(err);
645 }
646
647 let exit_timeout = stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
648 let checks = exit_timeout.as_millis().max(1).div_ceil(50) as usize;
649 for _ in 0..checks {
650 if members.iter().all(|(_, pidfd)| !pidfd_is_running(pidfd)) {
651 return Ok(true);
652 }
653 std::thread::sleep(std::time::Duration::from_millis(50));
654 }
655 if members.iter().all(|(_, pidfd)| !pidfd_is_running(pidfd)) {
656 return Ok(true);
657 }
658
659 warn!("one or more pinned processes in orphan group {pid} remained alive after SIGKILL");
660 let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
661 Ok(false)
662 }
663
664 #[cfg(not(unix))]
665 fn kill_process_group(
666 &self,
667 pid: u32,
668 stop_signal: i32,
669 stop_timeout: Option<std::time::Duration>,
670 expected_start_time: Option<u64>,
671 ) -> Result<bool> {
672 #[cfg(windows)]
675 let _identity_handle = if let Some(expected) = expected_start_time {
676 let handle = match open_process_handle(pid) {
677 Ok(handle) => handle,
678 Err(err) => {
679 warn!("cannot securely identify process {pid}: {err}");
680 return Ok(false);
681 }
682 };
683 if process_start_token_from_handle(handle.0) != Some(expected) {
684 debug!("process {pid} identity changed before taskkill");
685 return Ok(false);
686 }
687 Some(handle)
688 } else {
689 None
690 };
691
692 #[cfg(not(windows))]
693 if let Some(expected) = expected_start_time
694 && !self.start_time_matches(pid, expected)
695 {
696 debug!("process {pid} identity changed before termination");
697 return Ok(false);
698 }
699
700 self.kill(pid, stop_signal, stop_timeout, expected_start_time)
701 }
702
703 #[cfg(not(target_os = "linux"))]
721 fn kill(
722 &self,
723 pid: u32,
724 stop_signal: i32,
725 stop_timeout: Option<std::time::Duration>,
726 expected_start_time: Option<u64>,
727 ) -> Result<bool> {
728 debug!("killing process {pid}");
729
730 #[cfg(windows)]
731 {
732 let _ = expected_start_time;
735 let job = open_process_handle(pid)
744 .ok()
745 .and_then(|process| crate::win_job::DaemonJob::open(pid, process.0));
746 if stop_signal == crate::config_types::StopSignal::SIGINT {
747 let stop_timeout =
748 stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
749 if interrupt_and_wait(pid, stop_timeout) {
750 debug!("process {pid} exited after Ctrl+C");
751 if job.as_ref().is_some_and(job_outlives_termination) {
753 return Err(miette::miette!(
754 "process {pid} exited after Ctrl+C, but processes it started may \
755 still be running: its job was not terminated and emptied within {}s",
756 JOB_EXIT_WAIT.as_secs()
757 ));
758 }
759 return Ok(true);
760 }
761 }
762 debug!("forcing process tree termination for pid {pid}");
770 let output = std::process::Command::new("taskkill")
771 .args(["/F", "/T", "/PID"])
772 .arg(pid.to_string())
773 .hide_console_window()
774 .output();
775 let taskkill_succeeded = match output {
776 Ok(o) if o.status.success() => {
777 debug!("taskkill /F /T /PID {pid} succeeded");
778 true
779 }
780 Ok(o) => {
781 debug!(
782 "taskkill /F /T /PID {pid} exited with status {}: {}",
783 o.status,
784 String::from_utf8_lossy(&o.stderr).trim()
785 );
786 false
787 }
788 Err(e) => {
789 debug!("failed to spawn taskkill for pid {pid}: {e}");
790 false
791 }
792 };
793 let job_outlived = job.as_ref().is_some_and(job_outlives_termination);
796 std::thread::sleep(std::time::Duration::from_millis(200));
800 if !taskkill_succeeded && self.is_running(pid) {
801 return Err(miette::miette!(
802 "taskkill failed and process {pid} is still running"
803 ));
804 }
805 if job_outlived {
808 return Err(miette::miette!(
809 "processes of daemon {pid} may still be running: its job was not \
810 terminated and emptied within {}s",
811 JOB_EXIT_WAIT.as_secs()
812 ));
813 }
814 Ok(true)
815 }
816
817 #[cfg(unix)]
818 {
819 let sysinfo_pid = sysinfo::Pid::from_u32(pid);
820 let signal_name = signal_name(stop_signal);
821 if let Some(expected) = expected_start_time
826 && !self.verify_start_time_before_signal(pid, expected)?
827 {
828 return Ok(false);
829 }
830 debug!("sending {signal_name} to process {pid}");
834 let ret = unsafe { libc::kill(pid as i32, stop_signal) };
835 if ret == -1 {
836 let err = std::io::Error::last_os_error();
837 if err.raw_os_error() == Some(libc::ESRCH) {
838 debug!("process {pid} no longer exists");
839 return Ok(false);
840 }
841 if err.raw_os_error() == Some(libc::EPERM) {
842 return Err(miette::miette!(
843 "failed to send {signal_name} to process {pid}: permission denied"
844 ));
845 }
846 return Err(miette::miette!(
847 "failed to send {signal_name} to process {pid}: {err}"
848 ));
849 }
850
851 let stop_timeout = stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
854 let fast_ms = 10u64;
855 let slow_ms = 50u64;
856 let total_ms = stop_timeout.as_millis().max(1) as u64;
857 let fast_count = ((total_ms / fast_ms) as usize).min(10);
858 let fast_total_ms = fast_ms * fast_count as u64;
859 let remaining_ms = total_ms.saturating_sub(fast_total_ms);
860 let slow_count = (remaining_ms / slow_ms) as usize;
861
862 for i in 0..fast_count {
863 std::thread::sleep(std::time::Duration::from_millis(fast_ms));
864 self.refresh_pids(&[pid]);
865 if self.is_terminated_or_zombie(sysinfo_pid) {
866 debug!(
867 "process {pid} terminated after {signal_name} ({} ms)",
868 (i + 1) * fast_ms as usize
869 );
870 return Ok(true);
871 }
872 }
873
874 for i in 0..slow_count {
876 std::thread::sleep(std::time::Duration::from_millis(slow_ms));
877 self.refresh_pids(&[pid]);
878 if self.is_terminated_or_zombie(sysinfo_pid) {
879 debug!(
880 "process {pid} terminated after {signal_name} ({} ms)",
881 fast_total_ms + (i + 1) as u64 * slow_ms
882 );
883 return Ok(true);
884 }
885 }
886
887 if let Some(expected) = expected_start_time
892 && !self.start_time_matches(pid, expected)
893 {
894 debug!(
895 "process {pid} exited during the stop timeout and its PID was recycled; not sending SIGKILL"
896 );
897 return Ok(true);
898 }
899 warn!(
900 "process {pid} did not respond to {signal_name} after {}ms, sending SIGKILL",
901 stop_timeout.as_millis()
902 );
903 let ret = unsafe { libc::kill(pid as i32, libc::SIGKILL) };
904 if ret == -1 {
905 let err = std::io::Error::last_os_error();
906 if err.raw_os_error() != Some(libc::ESRCH) {
907 warn!("failed to send SIGKILL to process {pid}: {err}");
908 }
909 }
910
911 std::thread::sleep(std::time::Duration::from_millis(100));
913 Ok(true)
914 }
915 }
916
917 #[cfg(all(unix, not(target_os = "linux")))]
921 fn is_terminated_or_zombie(&self, sysinfo_pid: sysinfo::Pid) -> bool {
922 let system = self.lock_system();
923 match system.process(sysinfo_pid) {
924 None => true,
925 Some(process) => {
926 matches!(process.status(), sysinfo::ProcessStatus::Zombie)
927 }
928 }
929 }
930
931 pub(crate) fn refresh_processes(&self) {
932 let mut system = self.lock_system();
933 system.refresh_processes(ProcessesToUpdate::All, true);
934 #[cfg(windows)]
939 system.refresh_cpu_usage();
940 }
941
942 pub(crate) fn refresh_pids(&self, pids: &[u32]) {
945 let sysinfo_pids: Vec<sysinfo::Pid> =
946 pids.iter().map(|p| sysinfo::Pid::from_u32(*p)).collect();
947 self.lock_system()
948 .refresh_processes(ProcessesToUpdate::Some(&sysinfo_pids), true);
949 }
950
951 pub(crate) fn refresh_if_stale(&self) {
968 let mut last = self
969 .last_full_refresh
970 .lock()
971 .unwrap_or_else(|poisoned| poisoned.into_inner());
972 if last.is_none_or(|t| t.elapsed() >= FULL_REFRESH_INTERVAL) {
973 self.refresh_processes();
974 *last = Some(Instant::now());
975 }
976 }
977
978 pub fn get_batch_group_stats(&self, pids: &[u32]) -> Vec<(u32, Option<ProcessStats>)> {
984 if pids.is_empty() {
985 return Vec::new();
986 }
987
988 let system = self.lock_system();
989 let processes = system.processes();
990
991 let now = std::time::SystemTime::now()
992 .duration_since(std::time::UNIX_EPOCH)
993 .map(|d| d.as_secs())
994 .unwrap_or(0);
995
996 let mut children_map: std::collections::HashMap<sysinfo::Pid, Vec<sysinfo::Pid>> =
998 std::collections::HashMap::new();
999 for (child_pid, child) in processes {
1000 if child.thread_kind().is_some() {
1003 continue;
1004 }
1005 if let Some(ppid) = child.parent() {
1006 children_map.entry(ppid).or_default().push(*child_pid);
1007 }
1008 }
1009
1010 pids.iter()
1011 .map(|&pid| {
1012 let root_pid = sysinfo::Pid::from_u32(pid);
1013 let Some(root) = processes.get(&root_pid) else {
1014 return (pid, None);
1015 };
1016
1017 let root_disk = root.disk_usage();
1018 let mut stats = ProcessStats {
1019 cpu_percent: root.cpu_usage(),
1020 memory_bytes: root.memory(),
1021 uptime_secs: now.saturating_sub(root.start_time()),
1022 disk_read_bytes: root_disk.read_bytes,
1023 disk_write_bytes: root_disk.written_bytes,
1024 };
1025
1026 let mut queue = std::collections::VecDeque::new();
1028 if let Some(direct_children) = children_map.get(&root_pid) {
1029 queue.extend(direct_children);
1030 }
1031 while let Some(child_pid) = queue.pop_front() {
1032 if let Some(child) = processes.get(&child_pid) {
1033 let disk = child.disk_usage();
1034 stats.cpu_percent += child.cpu_usage();
1035 stats.memory_bytes += child.memory();
1036 stats.disk_read_bytes += disk.read_bytes;
1037 stats.disk_write_bytes += disk.written_bytes;
1038 }
1039 if let Some(grandchildren) = children_map.get(&child_pid) {
1040 queue.extend(grandchildren);
1041 }
1042 }
1043
1044 (pid, Some(stats))
1045 })
1046 .collect()
1047 }
1048 pub fn refresh_and_get_batch_stats(&self, pids: &[u32]) -> HashMap<u32, ProcessStats> {
1058 self.refresh_processes();
1059 self.get_batch_group_stats(pids)
1060 .into_iter()
1061 .filter_map(|(pid, stats)| stats.map(|s| (pid, s)))
1062 .collect()
1063 }
1064
1065 pub fn refresh_and_get_batch_stats_if_stale(&self, pids: &[u32]) -> HashMap<u32, ProcessStats> {
1072 self.refresh_if_stale();
1073 self.get_batch_group_stats(pids)
1074 .into_iter()
1075 .filter_map(|(pid, stats)| stats.map(|s| (pid, s)))
1076 .collect()
1077 }
1078
1079 pub fn get_batch_tree_stats_map(&self, pids: &[u32]) -> HashMap<u32, ProcessStats> {
1081 self.get_batch_group_stats(pids)
1082 .into_iter()
1083 .filter_map(|(pid, stats)| stats.map(|stats| (pid, stats)))
1084 .collect()
1085 }
1086
1087 pub fn get_stats(&self, pid: u32) -> Option<ProcessStats> {
1089 self.get_batch_group_stats(&[pid])
1090 .into_iter()
1091 .next()
1092 .and_then(|(_, stats)| stats)
1093 }
1094
1095 pub fn get_extended_stats(&self, pid: u32) -> Option<ExtendedProcessStats> {
1097 let system = self.lock_system();
1098 let processes = system.processes();
1099 let root_pid = sysinfo::Pid::from_u32(pid);
1100 let p = processes.get(&root_pid)?;
1101
1102 let now = std::time::SystemTime::now()
1103 .duration_since(std::time::UNIX_EPOCH)
1104 .map(|d| d.as_secs())
1105 .unwrap_or(0);
1106
1107 let root_disk = p.disk_usage();
1108 let mut aggregate_stats = ProcessStats {
1109 cpu_percent: p.cpu_usage(),
1110 memory_bytes: p.memory(),
1111 uptime_secs: now.saturating_sub(p.start_time()),
1112 disk_read_bytes: root_disk.read_bytes,
1113 disk_write_bytes: root_disk.written_bytes,
1114 };
1115
1116 let mut children_map: HashMap<sysinfo::Pid, Vec<sysinfo::Pid>> = HashMap::new();
1117 for (child_pid, child) in processes {
1118 if let Some(ppid) = child.parent() {
1119 children_map.entry(ppid).or_default().push(*child_pid);
1120 }
1121 }
1122
1123 let mut queue = std::collections::VecDeque::new();
1124 if let Some(direct_children) = children_map.get(&root_pid) {
1125 queue.extend(direct_children);
1126 }
1127 while let Some(child_pid) = queue.pop_front() {
1128 if let Some(child) = processes.get(&child_pid) {
1129 let disk = child.disk_usage();
1130 aggregate_stats.cpu_percent += child.cpu_usage();
1131 aggregate_stats.memory_bytes += child.memory();
1132 aggregate_stats.disk_read_bytes += disk.read_bytes;
1133 aggregate_stats.disk_write_bytes += disk.written_bytes;
1134 }
1135 if let Some(grandchildren) = children_map.get(&child_pid) {
1136 queue.extend(grandchildren);
1137 }
1138 }
1139
1140 Some(ExtendedProcessStats {
1141 name: p.name().to_string_lossy().to_string(),
1142 status: format!("{:?}", p.status()),
1143 cpu_percent: aggregate_stats.cpu_percent,
1144 memory_bytes: aggregate_stats.memory_bytes,
1145 virtual_memory_bytes: p.virtual_memory(),
1146 uptime_secs: aggregate_stats.uptime_secs,
1147 thread_count: p.tasks().map(|t| t.len()).unwrap_or(0),
1148 })
1149 }
1150}
1151
1152#[cfg(target_os = "linux")]
1153fn process_start_token(pid: u32) -> Option<u64> {
1154 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
1155 let command_end = stat.rfind(')')?;
1156 stat.get(command_end + 1..)?
1158 .split_whitespace()
1159 .nth(19)?
1160 .parse()
1161 .ok()
1162}
1163
1164#[cfg(target_os = "macos")]
1165fn process_start_token(pid: u32) -> Option<u64> {
1166 let mut info = std::mem::MaybeUninit::<libc::proc_bsdinfo>::zeroed();
1167 let size = std::mem::size_of::<libc::proc_bsdinfo>() as i32;
1168 let read = unsafe {
1169 libc::proc_pidinfo(
1170 pid as i32,
1171 libc::PROC_PIDTBSDINFO,
1172 0,
1173 info.as_mut_ptr().cast(),
1174 size,
1175 )
1176 };
1177 if read != size {
1178 return None;
1179 }
1180 let info = unsafe { info.assume_init() };
1181 info.pbi_start_tvsec
1182 .checked_mul(1_000_000)?
1183 .checked_add(info.pbi_start_tvusec)
1184}
1185
1186#[cfg(windows)]
1187fn process_start_token(pid: u32) -> Option<u64> {
1188 let handle = open_process_handle(pid).ok()?;
1189 process_start_token_from_handle(handle.0)
1190}
1191
1192#[cfg(windows)]
1193pub(crate) fn process_start_token_from_handle(handle: HANDLE) -> Option<u64> {
1194 let mut creation = FILETIME {
1195 dwLowDateTime: 0,
1196 dwHighDateTime: 0,
1197 };
1198 let mut exit = creation;
1199 let mut kernel = creation;
1200 let mut user = creation;
1201 let ok = unsafe { GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user) };
1202 if ok == 0 {
1203 return None;
1204 }
1205
1206 Some((u64::from(creation.dwHighDateTime) << 32) | u64::from(creation.dwLowDateTime))
1207}
1208
1209#[cfg(windows)]
1210struct ProcessHandle(HANDLE);
1211
1212#[cfg(windows)]
1213impl Drop for ProcessHandle {
1214 fn drop(&mut self) {
1215 unsafe {
1216 CloseHandle(self.0);
1217 }
1218 }
1219}
1220
1221#[cfg(windows)]
1222fn open_process_handle(pid: u32) -> std::io::Result<ProcessHandle> {
1223 let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
1224 if handle.is_null() {
1225 return Err(std::io::Error::last_os_error());
1226 }
1227 Ok(ProcessHandle(handle))
1228}
1229
1230#[cfg(windows)]
1233fn job_outlives_termination(job: &crate::win_job::DaemonJob) -> bool {
1234 debug!(
1237 "terminating daemon job; active_processes={:?}",
1238 job.active_processes()
1239 );
1240 let terminated = job.terminate();
1241 let emptied = job.wait_until_empty(JOB_EXIT_WAIT);
1242 debug!("terminated a daemon's job: {terminated}; emptied: {emptied}");
1243 !emptied
1244}
1245
1246#[cfg(windows)]
1252fn interrupt_and_wait(pid: u32, timeout: Duration) -> bool {
1253 use crate::console_ctrl::EXIT_SHARED_CONSOLE;
1254 use windows_sys::Win32::Foundation::{WAIT_FAILED, WAIT_OBJECT_0};
1255 use windows_sys::Win32::System::Threading::{PROCESS_SYNCHRONIZE, WaitForSingleObject};
1256
1257 let started = Instant::now();
1258 debug!("stopping process {pid} with Ctrl+C; timeout={timeout:?}");
1259
1260 let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) };
1263 if handle.is_null() {
1264 debug!(
1265 "cannot wait for process {pid}: {}",
1266 std::io::Error::last_os_error()
1267 );
1268 return false;
1269 }
1270 let handle = ProcessHandle(handle);
1271
1272 let deadline = Instant::now().checked_add(timeout);
1277 let millis_left = || {
1278 let Some(deadline) = deadline else {
1279 return u32::MAX - 1;
1280 };
1281 let left = deadline.saturating_duration_since(Instant::now());
1282 u32::try_from(left.as_millis()).unwrap_or(u32::MAX - 1)
1283 };
1284
1285 let mut helper = match std::process::Command::new(&*crate::env::PITCHFORK_BIN)
1286 .args(["interrupt", "--pid"])
1287 .arg(pid.to_string())
1288 .arg("--supervisor-pid")
1289 .arg(std::process::id().to_string())
1290 .stdin(std::process::Stdio::null())
1291 .stdout(std::process::Stdio::null())
1292 .stderr(std::process::Stdio::piped())
1293 .hide_console_window()
1294 .spawn()
1295 {
1296 Ok(helper) => helper,
1297 Err(e) => {
1298 debug!("failed to spawn pitchfork interrupt for pid {pid}: {e}");
1299 return false;
1300 }
1301 };
1302 debug!(
1303 "spawned interrupt helper {} for pid {pid} after {:?}",
1304 helper.id(),
1305 started.elapsed()
1306 );
1307 let helper_handle = std::os::windows::io::AsRawHandle::as_raw_handle(&helper);
1308 let wait = unsafe { WaitForSingleObject(helper_handle as HANDLE, millis_left()) };
1309 if wait != WAIT_OBJECT_0 {
1310 if wait == WAIT_FAILED {
1311 debug!(
1312 "interrupt helper wait for pid {pid} failed: {}",
1313 std::io::Error::last_os_error()
1314 );
1315 }
1316 debug!(
1317 "pitchfork interrupt for pid {pid} did not finish after {:?}; wait={wait:#x}",
1318 started.elapsed()
1319 );
1320 let _ = helper.kill();
1321 let _ = helper.wait();
1322 return false;
1323 }
1324 match helper.wait_with_output() {
1325 Ok(o) if o.status.success() => {
1326 debug!(
1327 "sent Ctrl+C to process {pid}; interrupt helper finished after {:?}",
1328 started.elapsed()
1329 );
1330 }
1331 Ok(o) if o.status.code() == Some(EXIT_SHARED_CONSOLE) => {
1332 debug!("process {pid} shares the supervisor's console; not sending Ctrl+C");
1333 return false;
1334 }
1335 Ok(o) => {
1336 debug!(
1337 "pitchfork interrupt for pid {pid} exited with status {}: {}",
1338 o.status,
1339 String::from_utf8_lossy(&o.stderr).trim()
1340 );
1341 return false;
1342 }
1343 Err(e) => {
1344 debug!("failed to wait for pitchfork interrupt for pid {pid}: {e}");
1345 return false;
1346 }
1347 }
1348
1349 let wait = unsafe { WaitForSingleObject(handle.0, millis_left()) };
1350 if wait == WAIT_FAILED {
1351 debug!(
1352 "process wait for pid {pid} failed: {}",
1353 std::io::Error::last_os_error()
1354 );
1355 }
1356 debug!(
1357 "process {pid} wait after Ctrl+C ended after {:?}; wait={wait:#x}",
1358 started.elapsed()
1359 );
1360 wait == WAIT_OBJECT_0
1361}
1362
1363#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
1364fn process_start_token(pid: u32) -> Option<u64> {
1365 let mut system = sysinfo::System::new();
1366 let sysinfo_pid = sysinfo::Pid::from_u32(pid);
1367 system.refresh_processes(ProcessesToUpdate::Some(&[sysinfo_pid]), true);
1368 system
1369 .process(sysinfo_pid)
1370 .map(|process| process.start_time())
1371}
1372
1373#[cfg(target_os = "linux")]
1374fn open_pidfd(pid: u32) -> std::io::Result<OwnedFd> {
1375 let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) };
1376 if fd < 0 {
1377 return Err(std::io::Error::last_os_error());
1378 }
1379 Ok(unsafe { OwnedFd::from_raw_fd(fd as i32) })
1380}
1381
1382#[cfg(target_os = "linux")]
1383fn pidfd_is_running(pidfd: &OwnedFd) -> bool {
1384 match try_pidfd_is_running(pidfd) {
1385 Ok(running) => running,
1386 Err(err) => {
1387 warn!("failed to poll pidfd {}: {err}", pidfd.as_raw_fd());
1388 true
1389 }
1390 }
1391}
1392
1393#[cfg(target_os = "linux")]
1394fn try_pidfd_is_running(pidfd: &OwnedFd) -> std::io::Result<bool> {
1395 let mut pollfd = libc::pollfd {
1396 fd: pidfd.as_raw_fd(),
1397 events: libc::POLLIN,
1398 revents: 0,
1399 };
1400 let result = unsafe { libc::poll(&mut pollfd, 1, 0) };
1401 if result < 0 {
1402 return Err(std::io::Error::last_os_error());
1403 }
1404 Ok(result == 0)
1405}
1406
1407#[cfg(target_os = "linux")]
1408fn signal_pidfds(members: &[(u32, OwnedFd)], signal: i32, signal_name: &str) -> Result<()> {
1409 for (pid, pidfd) in members {
1410 if !pidfd_is_running(pidfd) {
1411 continue;
1412 }
1413 let result = unsafe {
1414 libc::syscall(
1415 libc::SYS_pidfd_send_signal,
1416 pidfd.as_raw_fd(),
1417 signal,
1418 std::ptr::null::<libc::siginfo_t>(),
1419 0,
1420 )
1421 };
1422 if result == -1 {
1423 let err = std::io::Error::last_os_error();
1424 if err.raw_os_error() == Some(libc::ESRCH) {
1425 continue;
1426 }
1427 return Err(miette::miette!(
1428 "failed to send {signal_name} to pinned process {pid}: {err}"
1429 ));
1430 }
1431 }
1432 Ok(())
1433}
1434
1435#[cfg(target_os = "linux")]
1436fn stop_pidfds(members: &[(u32, OwnedFd)]) -> Result<()> {
1437 signal_pidfds(members, libc::SIGSTOP, "SIGSTOP")?;
1438 for _ in 0..200 {
1439 if members.iter().all(|(pid, pidfd)| {
1440 !pidfd_is_running(pidfd) || matches!(linux_process_state(*pid), Some('T' | 't'))
1441 }) {
1442 return Ok(());
1443 }
1444 std::thread::sleep(std::time::Duration::from_millis(5));
1445 }
1446 Err(miette::miette!(
1447 "timed out while freezing orphan process group"
1448 ))
1449}
1450
1451#[cfg(target_os = "linux")]
1452fn extend_process_group_pidfds(
1453 pgid: i32,
1454 members: &mut Vec<(u32, OwnedFd)>,
1455) -> std::io::Result<usize> {
1456 let entries = std::fs::read_dir("/proc")?;
1457 let mut added = 0;
1458 for entry in entries {
1459 let entry = entry?;
1460 let Some(pid) = entry
1461 .file_name()
1462 .to_str()
1463 .and_then(|name| name.parse::<u32>().ok())
1464 else {
1465 continue;
1466 };
1467 let Some(observed_identity) = linux_process_identity(pid) else {
1468 continue;
1469 };
1470 if observed_identity.0 != pgid {
1471 continue;
1472 }
1473 let mut already_pinned = false;
1474 for (known_pid, pidfd) in members.iter() {
1475 if *known_pid == pid && try_pidfd_is_running(pidfd)? {
1476 already_pinned = true;
1477 break;
1478 }
1479 }
1480 if already_pinned {
1481 continue;
1482 }
1483
1484 let pidfd = match open_pidfd(pid) {
1485 Ok(pidfd) => pidfd,
1486 Err(err) if err.raw_os_error() == Some(libc::ESRCH) => continue,
1487 Err(err) => return Err(err),
1488 };
1489 if linux_process_identity(pid) != Some(observed_identity) {
1490 return Err(std::io::Error::other(format!(
1491 "process {pid} identity changed while pinning group {pgid}"
1492 )));
1493 }
1494 members.push((pid, pidfd));
1495 added += 1;
1496 }
1497 Ok(added)
1498}
1499
1500#[cfg(target_os = "linux")]
1501fn linux_process_identity(pid: u32) -> Option<(i32, u64)> {
1502 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
1503 let command_end = stat.rfind(')')?;
1504 let fields: Vec<_> = stat.get(command_end + 1..)?.split_whitespace().collect();
1505 Some((fields.get(2)?.parse().ok()?, fields.get(19)?.parse().ok()?))
1508}
1509
1510#[cfg(target_os = "linux")]
1511fn linux_process_state(pid: u32) -> Option<char> {
1512 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
1513 let command_end = stat.rfind(')')?;
1514 stat.get(command_end + 1..)?
1515 .split_whitespace()
1516 .next()?
1517 .chars()
1518 .next()
1519}
1520
1521#[derive(Debug, Clone, Copy)]
1522pub struct ProcessStats {
1523 pub cpu_percent: f32,
1524 pub memory_bytes: u64,
1525 pub uptime_secs: u64,
1526 pub disk_read_bytes: u64,
1527 pub disk_write_bytes: u64,
1528}
1529
1530impl ProcessStats {
1531 pub fn memory_display(&self) -> String {
1532 format_bytes(self.memory_bytes)
1533 }
1534
1535 pub fn cpu_display(&self) -> String {
1536 format!("{:.1}%", self.cpu_percent)
1537 }
1538
1539 pub fn uptime_display(&self) -> String {
1540 format_duration(self.uptime_secs)
1541 }
1542
1543 pub fn disk_read_display(&self) -> String {
1544 format_bytes_per_sec(self.disk_read_bytes)
1545 }
1546
1547 pub fn disk_write_display(&self) -> String {
1548 format_bytes_per_sec(self.disk_write_bytes)
1549 }
1550}
1551
1552#[derive(Debug, Clone)]
1553pub struct ExtendedProcessStats {
1554 pub name: String,
1555 pub status: String,
1556 pub cpu_percent: f32,
1557 pub memory_bytes: u64,
1558 pub virtual_memory_bytes: u64,
1559 pub uptime_secs: u64,
1560 pub thread_count: usize,
1561}
1562
1563fn format_bytes(bytes: u64) -> String {
1564 humanbyte::to_string(bytes, humanbyte::Format::IEC)
1565}
1566
1567pub(crate) fn format_duration(secs: u64) -> String {
1568 if secs < 60 {
1569 format!("{secs}s")
1570 } else if secs < 3600 {
1571 format!("{}m {}s", secs / 60, secs % 60)
1572 } else if secs < 86400 {
1573 let hours = secs / 3600;
1574 let mins = (secs % 3600) / 60;
1575 format!("{hours}h {mins}m")
1576 } else {
1577 let days = secs / 86400;
1578 let hours = (secs % 86400) / 3600;
1579 format!("{days}d {hours}h")
1580 }
1581}
1582
1583fn format_bytes_per_sec(bytes: u64) -> String {
1584 format!("{}/s", humanbyte::to_string(bytes, humanbyte::Format::IEC))
1585}
1586
1587#[cfg(unix)]
1603fn process_group_terminated(pgid: i32) -> bool {
1604 unsafe { libc::killpg(pgid, 0) != 0 }
1605}
1606
1607#[cfg(unix)]
1608fn signal_name(sig: i32) -> &'static str {
1609 match sig {
1610 libc::SIGHUP => "SIGHUP",
1611 libc::SIGINT => "SIGINT",
1612 libc::SIGQUIT => "SIGQUIT",
1613 libc::SIGTERM => "SIGTERM",
1614 libc::SIGUSR1 => "SIGUSR1",
1615 libc::SIGUSR2 => "SIGUSR2",
1616 libc::SIGKILL => "SIGKILL",
1617 _ => "UNKNOWN",
1618 }
1619}
1620
1621fn is_exited_status(status: sysinfo::ProcessStatus) -> bool {
1623 matches!(
1624 status,
1625 sysinfo::ProcessStatus::Zombie | sysinfo::ProcessStatus::Dead
1626 )
1627}
1628
1629#[cfg(test)]
1630mod format_tests {
1631 use super::*;
1632
1633 #[test]
1634 fn process_start_time_check_rejects_mismatch() {
1635 let procs = Procs::new();
1636 let pid = std::process::id();
1637 procs.refresh_pids(&[pid]);
1638 let actual = procs
1639 .start_time(pid)
1640 .expect("current process should have a start time");
1641
1642 assert_ne!(procs.start_time(pid), Some(actual.saturating_add(1)));
1643 }
1644
1645 #[test]
1646 fn test_format_bytes() {
1647 assert_eq!(format_bytes(512), "512 B");
1648 assert_eq!(format_bytes(1024), "1.0 KiB");
1649 assert_eq!(format_bytes(1536), "1.5 KiB");
1650 assert_eq!(format_bytes(50 * 1024 * 1024), "50.0 MiB");
1651 assert_eq!(format_bytes(3 * 1024 * 1024 * 1024), "3.0 GiB");
1652 assert_eq!(format_bytes(1100 * 1024 * 1024 * 1024), "1.1 TiB");
1654 }
1655
1656 #[test]
1657 fn test_format_bytes_per_sec() {
1658 assert_eq!(format_bytes_per_sec(512), "512 B/s");
1659 assert_eq!(format_bytes_per_sec(1536), "1.5 KiB/s");
1660 assert_eq!(format_bytes_per_sec(2 * 1024 * 1024), "2.0 MiB/s");
1661 }
1662}
1663
1664#[cfg(all(test, unix))]
1665mod tests {
1666 use super::*;
1667 use std::os::unix::process::CommandExt;
1668 use std::process::{Child, Command, Stdio};
1669 use std::time::{Duration, Instant};
1670
1671 struct ChildGuard(Child);
1672
1673 impl Drop for ChildGuard {
1674 fn drop(&mut self) {
1675 let pid = self.0.id() as i32;
1676 let _ = unsafe { libc::killpg(pid, libc::SIGKILL) };
1678 let _ = self.0.wait();
1679 }
1680 }
1681
1682 #[tokio::test]
1683 async fn orphan_identity_checked_group_kill_rejects_mismatch() {
1684 let mut command = Command::new("sleep");
1685 command
1686 .arg("30")
1687 .stdin(Stdio::null())
1688 .stdout(Stdio::null())
1689 .stderr(Stdio::null());
1690 unsafe {
1691 command.pre_exec(|| {
1692 if libc::setsid() == -1 {
1693 return Err(std::io::Error::last_os_error());
1694 }
1695 Ok(())
1696 });
1697 }
1698
1699 let child = command.spawn().expect("failed to spawn test process");
1700 let pid = child.id();
1701 let _child = ChildGuard(child);
1702
1703 PROCS.refresh_pids(&[pid]);
1704 let actual_start_time = PROCS
1705 .start_time(pid)
1706 .expect("test process should have a start time");
1707
1708 let killed = PROCS
1709 .kill_process_group_if_start_time_matches_async(
1710 pid,
1711 Some(actual_start_time.saturating_add(1)),
1712 libc::SIGTERM,
1713 Some(Duration::from_millis(100)),
1714 )
1715 .await
1716 .expect("identity-checked kill should not error");
1717
1718 assert!(!killed);
1719 assert!(PROCS.is_running(pid), "mismatched process must survive");
1720 }
1721
1722 #[cfg(all(unix, not(target_os = "linux")))]
1727 #[tokio::test]
1728 async fn identity_checked_group_kill_reverifies_inside_blocking_op() {
1729 let mut command = Command::new("sleep");
1730 command
1731 .arg("30")
1732 .stdin(Stdio::null())
1733 .stdout(Stdio::null())
1734 .stderr(Stdio::null());
1735 unsafe {
1736 command.pre_exec(|| {
1737 if libc::setsid() == -1 {
1738 return Err(std::io::Error::last_os_error());
1739 }
1740 Ok(())
1741 });
1742 }
1743
1744 let child = command.spawn().expect("failed to spawn test process");
1745 let pid = child.id();
1746 let mut child = ChildGuard(child);
1747
1748 PROCS.refresh_pids(&[pid]);
1749 let actual_start_time = PROCS
1750 .start_time(pid)
1751 .expect("test process should have a start time");
1752
1753 let killed = PROCS
1754 .kill_process_group_if_start_time_matches_async(
1755 pid,
1756 Some(actual_start_time),
1757 libc::SIGTERM,
1758 Some(Duration::from_millis(100)),
1759 )
1760 .await
1761 .expect("identity-checked kill should not error");
1762
1763 assert!(killed, "matching generation must be signalled");
1764 let deadline = Instant::now() + Duration::from_secs(2);
1767 while child.0.try_wait().unwrap().is_none() {
1768 assert!(Instant::now() < deadline, "signalled child must exit");
1769 tokio::time::sleep(Duration::from_millis(10)).await;
1770 }
1771 assert!(
1772 !PROCS.is_running(pid),
1773 "signalled process group must be gone"
1774 );
1775 }
1776
1777 #[test]
1778 fn get_stats_includes_descendant_rss() {
1779 let mut command = Command::new("sh");
1780 command
1781 .args(["-c", "sleep 30 & wait"])
1782 .stdin(Stdio::null())
1783 .stdout(Stdio::null())
1784 .stderr(Stdio::null());
1785 unsafe {
1786 command.pre_exec(|| {
1787 if libc::setsid() == -1 {
1788 return Err(std::io::Error::last_os_error());
1789 }
1790 Ok(())
1791 });
1792 }
1793
1794 let parent = command.spawn().expect("failed to spawn process tree");
1795 let parent_pid = parent.id();
1796 let _parent = ChildGuard(parent);
1797
1798 let procs = Procs::new();
1799 let deadline = Instant::now() + Duration::from_secs(5);
1800 let mut child_pids = Vec::new();
1801 while Instant::now() < deadline {
1802 procs.refresh_processes();
1803 child_pids = procs.all_children(parent_pid);
1804 if !child_pids.is_empty() {
1805 break;
1806 }
1807 std::thread::sleep(Duration::from_millis(50));
1808 }
1809 assert!(
1810 !child_pids.is_empty(),
1811 "test process tree did not appear under parent pid {parent_pid}"
1812 );
1813
1814 procs.refresh_processes();
1815 child_pids = procs.all_children(parent_pid);
1816 assert!(
1817 !child_pids.is_empty(),
1818 "test process tree disappeared under parent pid {parent_pid}"
1819 );
1820 let root_pid = sysinfo::Pid::from_u32(parent_pid);
1821 let direct_memory = {
1822 let system = procs.lock_system();
1823 system
1824 .process(root_pid)
1825 .expect("parent process should exist")
1826 .memory()
1827 };
1828 let descendant_memory = {
1829 let system = procs.lock_system();
1830 child_pids
1831 .iter()
1832 .filter_map(|pid| system.process(sysinfo::Pid::from_u32(*pid)))
1833 .map(|process| process.memory())
1834 .sum::<u64>()
1835 };
1836 assert!(
1837 descendant_memory > 0,
1838 "descendants {child_pids:?} should have nonzero RSS"
1839 );
1840
1841 let stats = procs
1842 .get_stats(parent_pid)
1843 .expect("parent process should have aggregate stats");
1844
1845 assert_eq!(
1846 stats.memory_bytes,
1847 direct_memory + descendant_memory,
1848 "get_stats should include descendant RSS for parent pid {parent_pid}; \
1849 descendants: {child_pids:?}, direct RSS: {direct_memory}, \
1850 descendant RSS: {descendant_memory}, reported RSS: {}",
1851 stats.memory_bytes
1852 );
1853 }
1854
1855 #[test]
1856 fn full_refresh_is_throttled_by_ttl() {
1857 let procs = Procs::new();
1858
1859 assert!(
1861 procs.last_full_refresh.lock().unwrap().is_none(),
1862 "fresh Procs should have no recorded refresh"
1863 );
1864 procs.refresh_if_stale();
1865 let first = procs.last_full_refresh.lock().unwrap().unwrap();
1866 assert!(first.elapsed() < FULL_REFRESH_INTERVAL);
1867
1868 procs.refresh_if_stale();
1871 let second = procs.last_full_refresh.lock().unwrap().unwrap();
1872 assert_eq!(
1873 second, first,
1874 "refresh_if_stale within TTL must skip the refresh and keep the timestamp"
1875 );
1876
1877 let expired = Instant::now()
1880 .checked_sub(FULL_REFRESH_INTERVAL + Duration::from_secs(1))
1881 .expect("system has been up long enough to backdate by 6s");
1882 *procs.last_full_refresh.lock().unwrap() = Some(expired);
1883 procs.refresh_if_stale();
1884 let third = procs.last_full_refresh.lock().unwrap().unwrap();
1885 assert!(
1886 third > expired,
1887 "refresh_if_stale after expired TTL must refresh and advance the timestamp"
1888 );
1889 assert!(
1890 third.elapsed() < FULL_REFRESH_INTERVAL,
1891 "fresh timestamp after expired-TTL refresh should be recent"
1892 );
1893 }
1894}