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 mut children_map: ParentToChildren = HashMap::new();
159 for (child_pid, process) in system.processes() {
160 if let Some(parent) = process.parent() {
161 children_map
162 .entry(parent.as_u32())
163 .or_default()
164 .push(child_pid.as_u32());
165 }
166 }
167 drop(system);
168 descendant_pids(pid, &children_map)
169 }
170 pub fn collect_process_tree_info(&self) -> (ParentToChildren, ProcessNames) {
175 let system = self.lock_system();
176 let all = system.processes();
177 let mut parent_to_children: ParentToChildren = HashMap::new();
178 let mut process_info: ProcessNames = HashMap::new();
179
180 for (pid, proc) in all {
181 let pid_u32 = pid.as_u32();
182 process_info.insert(
183 pid_u32,
184 (
185 proc.name().to_string_lossy().to_string(),
186 proc.exe().map(|e| e.to_string_lossy().to_string()),
187 ),
188 );
189
190 if let Some(ppid) = proc.parent() {
191 parent_to_children
192 .entry(ppid.as_u32())
193 .or_default()
194 .push(pid_u32);
195 }
196 }
197
198 (parent_to_children, process_info)
199 }
200 pub async fn kill_process_group_async(
201 &self,
202 pid: u32,
203 stop_signal: i32,
204 stop_timeout: Option<std::time::Duration>,
205 ) -> Result<bool> {
206 tokio::task::spawn_blocking(move || {
207 PROCS.kill_process_group(pid, stop_signal, stop_timeout, None)
208 })
209 .await
210 .into_diagnostic()?
211 }
212
213 pub async fn kill_process_group_if_start_time_matches_async(
223 &self,
224 pid: u32,
225 expected_start_time: Option<u64>,
226 stop_signal: i32,
227 stop_timeout: Option<std::time::Duration>,
228 ) -> Result<bool> {
229 let Some(expected_start_time) = expected_start_time else {
230 warn!(
231 "no recorded start time for pid {pid}; refusing to signal it (identity cannot be bound to a process generation)"
232 );
233 return Ok(false);
234 };
235 tokio::task::spawn_blocking(move || {
236 PROCS.kill_process_group(pid, stop_signal, stop_timeout, Some(expected_start_time))
237 })
238 .await
239 .into_diagnostic()?
240 }
241
242 pub async fn kill_if_start_time_matches_async(
262 &self,
263 pid: u32,
264 expected_start_time: Option<u64>,
265 stop_signal: i32,
266 stop_timeout: Option<std::time::Duration>,
267 ) -> Result<bool> {
268 let Some(expected_start_time) = expected_start_time else {
269 warn!(
270 "no recorded start time for pid {pid}; refusing to signal it (identity cannot be bound to a process generation)"
271 );
272 return Ok(false);
273 };
274 tokio::task::spawn_blocking(move || {
275 PROCS.kill_if_start_time_matches(pid, expected_start_time, stop_signal, stop_timeout)
276 })
277 .await
278 .into_diagnostic()?
279 }
280
281 #[cfg(target_os = "linux")]
282 fn kill_if_start_time_matches(
283 &self,
284 pid: u32,
285 expected_start_time: u64,
286 stop_signal: i32,
287 stop_timeout: Option<std::time::Duration>,
288 ) -> Result<bool> {
289 let pidfd = match open_pidfd(pid) {
290 Ok(pidfd) => pidfd,
291 Err(err) if err.raw_os_error() == Some(libc::ESRCH) => {
292 debug!("process {pid} no longer exists");
293 return Ok(false);
294 }
295 Err(err) => {
296 return Err(miette::miette!(
297 "cannot securely identify process {pid}: {err}"
298 ));
299 }
300 };
301 if !self.verify_start_time_before_signal(pid, expected_start_time)? {
306 return Ok(false);
307 }
308 let target = [(pid, pidfd)];
309 let signal_name = signal_name(stop_signal);
310 debug!("sending {signal_name} to pinned process {pid}");
311 signal_pidfds(&target, stop_signal, signal_name)?;
312
313 let stop_timeout = stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
316 let fast_ms = 10u64;
317 let slow_ms = 50u64;
318 let total_ms = stop_timeout.as_millis().max(1) as u64;
319 let fast_count = ((total_ms / fast_ms) as usize).min(10);
320 let fast_total_ms = fast_ms * fast_count as u64;
321 let slow_count = (total_ms.saturating_sub(fast_total_ms) / slow_ms) as usize;
322 for i in 0..fast_count {
323 std::thread::sleep(std::time::Duration::from_millis(fast_ms));
324 if !pidfd_is_running(&target[0].1) {
325 debug!(
326 "process {pid} terminated after {signal_name} ({} ms)",
327 (i + 1) as u64 * fast_ms
328 );
329 return Ok(true);
330 }
331 }
332 for i in 0..slow_count {
333 std::thread::sleep(std::time::Duration::from_millis(slow_ms));
334 if !pidfd_is_running(&target[0].1) {
335 debug!(
336 "process {pid} terminated after {signal_name} ({} ms)",
337 fast_total_ms + (i + 1) as u64 * slow_ms
338 );
339 return Ok(true);
340 }
341 }
342
343 warn!(
344 "process {pid} did not respond to {signal_name} after {}ms, sending SIGKILL",
345 stop_timeout.as_millis()
346 );
347 signal_pidfds(&target, libc::SIGKILL, "SIGKILL")?;
348 std::thread::sleep(std::time::Duration::from_millis(100));
350 Ok(true)
351 }
352
353 #[cfg(not(target_os = "linux"))]
354 fn kill_if_start_time_matches(
355 &self,
356 pid: u32,
357 expected_start_time: u64,
358 stop_signal: i32,
359 stop_timeout: Option<std::time::Duration>,
360 ) -> Result<bool> {
361 #[cfg(windows)]
365 let _pin = open_process_handle(pid).ok();
366
367 if !self.verify_start_time_before_signal(pid, expected_start_time)? {
368 return Ok(false);
369 }
370 self.kill(pid, stop_signal, stop_timeout, Some(expected_start_time))
371 }
372
373 fn verify_start_time_before_signal(&self, pid: u32, expected_start_time: u64) -> Result<bool> {
385 match self.start_time(pid) {
386 Some(current) if current == expected_start_time => Ok(true),
387 Some(current) => {
388 warn!(
389 "pid {pid} is not the recorded process (start time {current}, expected {expected_start_time}); not signalling it"
390 );
391 Ok(false)
392 }
393 None if self.is_running(pid) => Err(miette::miette!(
394 "cannot verify the identity of pid {pid}: its start time is unreadable; not signalling it"
395 )),
396 None => {
397 debug!("process {pid} no longer exists");
398 Ok(false)
399 }
400 }
401 }
402
403 #[cfg(unix)]
420 fn kill_process_group(
421 &self,
422 pid: u32,
423 stop_signal: i32,
424 stop_timeout: Option<std::time::Duration>,
425 expected_start_time: Option<u64>,
426 ) -> Result<bool> {
427 let pgid = pid as i32;
428 let signal_name = signal_name(stop_signal);
429
430 #[cfg(target_os = "linux")]
431 if let Some(expected) = expected_start_time {
432 return self.kill_process_group_with_pidfds(pid, expected, stop_signal, stop_timeout);
433 }
434
435 #[cfg(not(target_os = "linux"))]
447 if let Some(expected) = expected_start_time
448 && !self.start_time_matches(pid, expected)
449 {
450 debug!("process {pid} identity changed before killpg; refusing to signal it");
451 return Ok(false);
452 }
453
454 debug!("killing process group {pgid} with {signal_name}");
455
456 let ret = unsafe { libc::killpg(pgid, stop_signal) };
461 if ret == -1 {
462 let err = std::io::Error::last_os_error();
463 if err.raw_os_error() == Some(libc::ESRCH) {
464 debug!("process group {pgid} no longer exists");
465 return Ok(false);
466 }
467 if err.raw_os_error() == Some(libc::EPERM) {
468 return Err(miette::miette!(
469 "failed to send {signal_name} to process group {pgid}: permission denied"
470 ));
471 }
472 warn!("failed to send {signal_name} to process group {pgid}: {err}");
473 }
474
475 let stop_timeout = stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
485 let fast_ms = 10u64;
486 let slow_ms = 50u64;
487 let total_ms = stop_timeout.as_millis().max(1) as u64;
488 let fast_count = ((total_ms / fast_ms) as usize).min(10);
489 let fast_total_ms = fast_ms * fast_count as u64;
490 let remaining_ms = total_ms.saturating_sub(fast_total_ms);
491 let slow_count = (remaining_ms / slow_ms) as usize;
492
493 let fast_checks =
494 std::iter::repeat_n(std::time::Duration::from_millis(fast_ms), fast_count);
495 let slow_checks =
496 std::iter::repeat_n(std::time::Duration::from_millis(slow_ms), slow_count);
497 let mut elapsed_ms = 0u64;
498
499 for sleep_duration in fast_checks.chain(slow_checks) {
500 std::thread::sleep(sleep_duration);
501 elapsed_ms += sleep_duration.as_millis() as u64;
502 if process_group_terminated(pgid) {
503 debug!("process group {pgid} terminated after {signal_name} ({elapsed_ms} ms)",);
504 return Ok(true);
505 }
506 }
507
508 warn!(
510 "process group {pgid} did not respond to {signal_name} after {}ms, sending SIGKILL",
511 stop_timeout.as_millis()
512 );
513 let ret = unsafe { libc::killpg(pgid, libc::SIGKILL) };
514 if ret == -1 {
515 let err = std::io::Error::last_os_error();
516 if err.raw_os_error() != Some(libc::ESRCH) {
517 warn!("failed to send SIGKILL to process group {pgid}: {err}");
518 }
519 }
520
521 let sigkill_polls = PROCESS_GROUP_SIGKILL_WAIT.as_millis() / 50;
525 for _ in 0..sigkill_polls {
526 std::thread::sleep(std::time::Duration::from_millis(50));
527 if process_group_terminated(pgid) {
528 return Ok(true);
529 }
530 }
531 Err(miette::miette!(
534 "process group {pgid} still has members after SIGKILL \
535 (possibly stuck in uninterruptible sleep)"
536 ))
537 }
538
539 pub fn process_group_alive(&self, pid: u32) -> bool {
542 #[cfg(unix)]
543 {
544 !process_group_terminated(pid as i32)
545 }
546 #[cfg(not(unix))]
547 {
548 self.is_running(pid)
549 }
550 }
551
552 pub fn is_live(&self, pid: u32) -> bool {
556 if !self.is_running(pid) {
557 return false;
558 }
559 self.refresh_pids(&[pid]);
560 self.lock_system()
561 .process(sysinfo::Pid::from_u32(pid))
562 .is_none_or(|p| !is_exited_status(p.status()))
563 }
564
565 pub fn process_group_has_live_member(&self, pgid: u32) -> bool {
570 #[cfg(unix)]
571 {
572 if unsafe { libc::killpg(pgid as i32, 0) } != 0
575 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH)
576 {
577 return false;
578 }
579 self.refresh_processes();
580 self.lock_system().processes().iter().any(|(pid, p)| {
581 !is_exited_status(p.status())
582 && unsafe { libc::getpgid(pid.as_u32() as i32) } == pgid as i32
583 })
584 }
585 #[cfg(not(unix))]
586 {
587 self.is_live(pgid)
588 }
589 }
590
591 #[cfg(target_os = "linux")]
592 fn kill_process_group_with_pidfds(
593 &self,
594 pid: u32,
595 expected_start_time: u64,
596 _stop_signal: i32,
597 stop_timeout: Option<std::time::Duration>,
598 ) -> Result<bool> {
599 let leader = match open_pidfd(pid) {
600 Ok(pidfd) => pidfd,
601 Err(err) => {
602 warn!("cannot securely identify process group {pid}: {err}");
603 return Ok(false);
604 }
605 };
606 if !self.start_time_matches(pid, expected_start_time) {
607 debug!("process group {pid} leader identity changed before signaling");
608 return Ok(false);
609 }
610
611 let mut members = vec![(pid, leader)];
612 if let Err(err) = stop_pidfds(&members) {
613 let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
614 return Err(err);
615 }
616 if !pidfd_is_running(&members[0].1) {
617 debug!("process group {pid} leader exited before it could be frozen");
618 return Ok(false);
619 }
620
621 loop {
625 let known_members = members.len();
626 let added = match extend_process_group_pidfds(pid as i32, &mut members) {
627 Ok(added) => added,
628 Err(err) => {
629 let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
630 return Err(miette::miette!(
631 "failed to scan pinned process group {pid}: {err}"
632 ));
633 }
634 };
635 if added == 0 {
636 break;
637 }
638 if let Err(err) = stop_pidfds(&members[known_members..]) {
639 let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
640 return Err(err);
641 }
642 }
643
644 warn!(
645 "force-terminating {} pinned orphan process(es) in group {pid}",
646 members.len()
647 );
648 if let Err(err) = signal_pidfds(&members, libc::SIGKILL, "SIGKILL") {
649 let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
650 return Err(err);
651 }
652
653 let exit_timeout = stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
654 let checks = exit_timeout.as_millis().max(1).div_ceil(50) as usize;
655 for _ in 0..checks {
656 if members.iter().all(|(_, pidfd)| !pidfd_is_running(pidfd)) {
657 return Ok(true);
658 }
659 std::thread::sleep(std::time::Duration::from_millis(50));
660 }
661 if members.iter().all(|(_, pidfd)| !pidfd_is_running(pidfd)) {
662 return Ok(true);
663 }
664
665 warn!("one or more pinned processes in orphan group {pid} remained alive after SIGKILL");
666 let _ = signal_pidfds(&members, libc::SIGCONT, "SIGCONT");
667 Ok(false)
668 }
669
670 #[cfg(not(unix))]
671 fn kill_process_group(
672 &self,
673 pid: u32,
674 stop_signal: i32,
675 stop_timeout: Option<std::time::Duration>,
676 expected_start_time: Option<u64>,
677 ) -> Result<bool> {
678 #[cfg(windows)]
681 let _identity_handle = if let Some(expected) = expected_start_time {
682 let handle = match open_process_handle(pid) {
683 Ok(handle) => handle,
684 Err(err) => {
685 warn!("cannot securely identify process {pid}: {err}");
686 return Ok(false);
687 }
688 };
689 if process_start_token_from_handle(handle.0) != Some(expected) {
690 debug!("process {pid} identity changed before taskkill");
691 return Ok(false);
692 }
693 Some(handle)
694 } else {
695 None
696 };
697
698 #[cfg(not(windows))]
699 if let Some(expected) = expected_start_time
700 && !self.start_time_matches(pid, expected)
701 {
702 debug!("process {pid} identity changed before termination");
703 return Ok(false);
704 }
705
706 self.kill(pid, stop_signal, stop_timeout, expected_start_time)
707 }
708
709 #[cfg(not(target_os = "linux"))]
727 fn kill(
728 &self,
729 pid: u32,
730 stop_signal: i32,
731 stop_timeout: Option<std::time::Duration>,
732 expected_start_time: Option<u64>,
733 ) -> Result<bool> {
734 debug!("killing process {pid}");
735
736 #[cfg(windows)]
737 {
738 let _ = expected_start_time;
741 let job = open_process_handle(pid)
750 .ok()
751 .and_then(|process| crate::win_job::DaemonJob::open(pid, process.0));
752 if stop_signal == crate::config_types::StopSignal::SIGINT {
753 let stop_timeout =
754 stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
755 if interrupt_and_wait(pid, stop_timeout) {
756 debug!("process {pid} exited after Ctrl+C");
757 if job.as_ref().is_some_and(job_outlives_termination) {
759 return Err(miette::miette!(
760 "process {pid} exited after Ctrl+C, but processes it started may \
761 still be running: its job was not terminated and emptied within {}s",
762 JOB_EXIT_WAIT.as_secs()
763 ));
764 }
765 return Ok(true);
766 }
767 }
768 debug!("forcing process tree termination for pid {pid}");
776 let output = std::process::Command::new("taskkill")
777 .args(["/F", "/T", "/PID"])
778 .arg(pid.to_string())
779 .hide_console_window()
780 .output();
781 let taskkill_succeeded = match output {
782 Ok(o) if o.status.success() => {
783 debug!("taskkill /F /T /PID {pid} succeeded");
784 true
785 }
786 Ok(o) => {
787 debug!(
788 "taskkill /F /T /PID {pid} exited with status {}: {}",
789 o.status,
790 String::from_utf8_lossy(&o.stderr).trim()
791 );
792 false
793 }
794 Err(e) => {
795 debug!("failed to spawn taskkill for pid {pid}: {e}");
796 false
797 }
798 };
799 let job_outlived = job.as_ref().is_some_and(job_outlives_termination);
802 std::thread::sleep(std::time::Duration::from_millis(200));
806 if !taskkill_succeeded && self.is_running(pid) {
807 return Err(miette::miette!(
808 "taskkill failed and process {pid} is still running"
809 ));
810 }
811 if job_outlived {
814 return Err(miette::miette!(
815 "processes of daemon {pid} may still be running: its job was not \
816 terminated and emptied within {}s",
817 JOB_EXIT_WAIT.as_secs()
818 ));
819 }
820 Ok(true)
821 }
822
823 #[cfg(unix)]
824 {
825 let sysinfo_pid = sysinfo::Pid::from_u32(pid);
826 let signal_name = signal_name(stop_signal);
827 if let Some(expected) = expected_start_time
832 && !self.verify_start_time_before_signal(pid, expected)?
833 {
834 return Ok(false);
835 }
836 debug!("sending {signal_name} to process {pid}");
840 let ret = unsafe { libc::kill(pid as i32, stop_signal) };
841 if ret == -1 {
842 let err = std::io::Error::last_os_error();
843 if err.raw_os_error() == Some(libc::ESRCH) {
844 debug!("process {pid} no longer exists");
845 return Ok(false);
846 }
847 if err.raw_os_error() == Some(libc::EPERM) {
848 return Err(miette::miette!(
849 "failed to send {signal_name} to process {pid}: permission denied"
850 ));
851 }
852 return Err(miette::miette!(
853 "failed to send {signal_name} to process {pid}: {err}"
854 ));
855 }
856
857 let stop_timeout = stop_timeout.unwrap_or_else(|| settings().supervisor_stop_timeout());
860 let fast_ms = 10u64;
861 let slow_ms = 50u64;
862 let total_ms = stop_timeout.as_millis().max(1) as u64;
863 let fast_count = ((total_ms / fast_ms) as usize).min(10);
864 let fast_total_ms = fast_ms * fast_count as u64;
865 let remaining_ms = total_ms.saturating_sub(fast_total_ms);
866 let slow_count = (remaining_ms / slow_ms) as usize;
867
868 for i in 0..fast_count {
869 std::thread::sleep(std::time::Duration::from_millis(fast_ms));
870 self.refresh_pids(&[pid]);
871 if self.is_terminated_or_zombie(sysinfo_pid) {
872 debug!(
873 "process {pid} terminated after {signal_name} ({} ms)",
874 (i + 1) * fast_ms as usize
875 );
876 return Ok(true);
877 }
878 }
879
880 for i in 0..slow_count {
882 std::thread::sleep(std::time::Duration::from_millis(slow_ms));
883 self.refresh_pids(&[pid]);
884 if self.is_terminated_or_zombie(sysinfo_pid) {
885 debug!(
886 "process {pid} terminated after {signal_name} ({} ms)",
887 fast_total_ms + (i + 1) as u64 * slow_ms
888 );
889 return Ok(true);
890 }
891 }
892
893 if let Some(expected) = expected_start_time
898 && !self.start_time_matches(pid, expected)
899 {
900 debug!(
901 "process {pid} exited during the stop timeout and its PID was recycled; not sending SIGKILL"
902 );
903 return Ok(true);
904 }
905 warn!(
906 "process {pid} did not respond to {signal_name} after {}ms, sending SIGKILL",
907 stop_timeout.as_millis()
908 );
909 let ret = unsafe { libc::kill(pid as i32, libc::SIGKILL) };
910 if ret == -1 {
911 let err = std::io::Error::last_os_error();
912 if err.raw_os_error() != Some(libc::ESRCH) {
913 warn!("failed to send SIGKILL to process {pid}: {err}");
914 }
915 }
916
917 std::thread::sleep(std::time::Duration::from_millis(100));
919 Ok(true)
920 }
921 }
922
923 #[cfg(all(unix, not(target_os = "linux")))]
927 fn is_terminated_or_zombie(&self, sysinfo_pid: sysinfo::Pid) -> bool {
928 let system = self.lock_system();
929 match system.process(sysinfo_pid) {
930 None => true,
931 Some(process) => {
932 matches!(process.status(), sysinfo::ProcessStatus::Zombie)
933 }
934 }
935 }
936
937 pub(crate) fn refresh_processes(&self) {
938 let mut system = self.lock_system();
939 system.refresh_processes(ProcessesToUpdate::All, true);
940 #[cfg(windows)]
945 system.refresh_cpu_usage();
946 }
947
948 pub(crate) fn refresh_pids(&self, pids: &[u32]) {
951 let sysinfo_pids: Vec<sysinfo::Pid> =
952 pids.iter().map(|p| sysinfo::Pid::from_u32(*p)).collect();
953 self.lock_system()
954 .refresh_processes(ProcessesToUpdate::Some(&sysinfo_pids), true);
955 }
956
957 pub(crate) fn refresh_if_stale(&self) {
974 let mut last = self
975 .last_full_refresh
976 .lock()
977 .unwrap_or_else(|poisoned| poisoned.into_inner());
978 if last.is_none_or(|t| t.elapsed() >= FULL_REFRESH_INTERVAL) {
979 self.refresh_processes();
980 *last = Some(Instant::now());
981 }
982 }
983
984 pub fn get_batch_group_stats(&self, pids: &[u32]) -> Vec<(u32, Option<ProcessStats>)> {
990 if pids.is_empty() {
991 return Vec::new();
992 }
993
994 let system = self.lock_system();
995 let processes = system.processes();
996
997 let now = std::time::SystemTime::now()
998 .duration_since(std::time::UNIX_EPOCH)
999 .map(|d| d.as_secs())
1000 .unwrap_or(0);
1001
1002 let mut children_map: ParentToChildren = HashMap::new();
1004 for (child_pid, child) in processes {
1005 if child.thread_kind().is_some() {
1008 continue;
1009 }
1010 if let Some(ppid) = child.parent() {
1011 children_map
1012 .entry(ppid.as_u32())
1013 .or_default()
1014 .push(child_pid.as_u32());
1015 }
1016 }
1017
1018 pids.iter()
1019 .map(|&pid| {
1020 let root_pid = sysinfo::Pid::from_u32(pid);
1021 let Some(root) = processes.get(&root_pid) else {
1022 return (pid, None);
1023 };
1024
1025 let root_disk = root.disk_usage();
1026 let mut stats = ProcessStats {
1027 cpu_percent: root.cpu_usage(),
1028 memory_bytes: root.memory(),
1029 uptime_secs: now.saturating_sub(root.start_time()),
1030 disk_read_bytes: root_disk.read_bytes,
1031 disk_write_bytes: root_disk.written_bytes,
1032 };
1033
1034 for child_pid in descendant_pids(pid, &children_map) {
1035 if let Some(child) = processes.get(&sysinfo::Pid::from_u32(child_pid)) {
1036 let disk = child.disk_usage();
1037 stats.cpu_percent += child.cpu_usage();
1038 stats.memory_bytes += child.memory();
1039 stats.disk_read_bytes += disk.read_bytes;
1040 stats.disk_write_bytes += disk.written_bytes;
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
1521fn descendant_pids(root: u32, children_map: &ParentToChildren) -> Vec<u32> {
1528 let mut seen = std::collections::HashSet::from([root]);
1529 let mut queue = std::collections::VecDeque::from([root]);
1530 let mut descendants = Vec::new();
1531
1532 while let Some(parent) = queue.pop_front() {
1533 if let Some(children) = children_map.get(&parent) {
1534 for &child in children {
1535 if seen.insert(child) {
1536 descendants.push(child);
1537 queue.push_back(child);
1538 }
1539 }
1540 }
1541 }
1542
1543 descendants
1544}
1545
1546#[derive(Debug, Clone, Copy)]
1547pub struct ProcessStats {
1548 pub cpu_percent: f32,
1549 pub memory_bytes: u64,
1550 pub uptime_secs: u64,
1551 pub disk_read_bytes: u64,
1552 pub disk_write_bytes: u64,
1553}
1554
1555impl ProcessStats {
1556 pub fn memory_display(&self) -> String {
1557 format_bytes(self.memory_bytes)
1558 }
1559
1560 pub fn cpu_display(&self) -> String {
1561 format!("{:.1}%", self.cpu_percent)
1562 }
1563
1564 pub fn uptime_display(&self) -> String {
1565 format_duration(self.uptime_secs)
1566 }
1567
1568 pub fn disk_read_display(&self) -> String {
1569 format_bytes_per_sec(self.disk_read_bytes)
1570 }
1571
1572 pub fn disk_write_display(&self) -> String {
1573 format_bytes_per_sec(self.disk_write_bytes)
1574 }
1575}
1576
1577#[derive(Debug, Clone)]
1578pub struct ExtendedProcessStats {
1579 pub name: String,
1580 pub status: String,
1581 pub cpu_percent: f32,
1582 pub memory_bytes: u64,
1583 pub virtual_memory_bytes: u64,
1584 pub uptime_secs: u64,
1585 pub thread_count: usize,
1586}
1587
1588fn format_bytes(bytes: u64) -> String {
1589 humanbyte::to_string(bytes, humanbyte::Format::IEC)
1590}
1591
1592pub(crate) fn format_duration(secs: u64) -> String {
1593 if secs < 60 {
1594 format!("{secs}s")
1595 } else if secs < 3600 {
1596 format!("{}m {}s", secs / 60, secs % 60)
1597 } else if secs < 86400 {
1598 let hours = secs / 3600;
1599 let mins = (secs % 3600) / 60;
1600 format!("{hours}h {mins}m")
1601 } else {
1602 let days = secs / 86400;
1603 let hours = (secs % 86400) / 3600;
1604 format!("{days}d {hours}h")
1605 }
1606}
1607
1608fn format_bytes_per_sec(bytes: u64) -> String {
1609 format!("{}/s", humanbyte::to_string(bytes, humanbyte::Format::IEC))
1610}
1611
1612#[cfg(unix)]
1628fn process_group_terminated(pgid: i32) -> bool {
1629 unsafe { libc::killpg(pgid, 0) != 0 }
1630}
1631
1632#[cfg(unix)]
1633fn signal_name(sig: i32) -> &'static str {
1634 match sig {
1635 libc::SIGHUP => "SIGHUP",
1636 libc::SIGINT => "SIGINT",
1637 libc::SIGQUIT => "SIGQUIT",
1638 libc::SIGTERM => "SIGTERM",
1639 libc::SIGUSR1 => "SIGUSR1",
1640 libc::SIGUSR2 => "SIGUSR2",
1641 libc::SIGKILL => "SIGKILL",
1642 _ => "UNKNOWN",
1643 }
1644}
1645
1646fn is_exited_status(status: sysinfo::ProcessStatus) -> bool {
1648 matches!(
1649 status,
1650 sysinfo::ProcessStatus::Zombie | sysinfo::ProcessStatus::Dead
1651 )
1652}
1653
1654#[cfg(test)]
1655mod format_tests {
1656 use super::*;
1657
1658 #[test]
1659 fn process_start_time_check_rejects_mismatch() {
1660 let procs = Procs::new();
1661 let pid = std::process::id();
1662 procs.refresh_pids(&[pid]);
1663 let actual = procs
1664 .start_time(pid)
1665 .expect("current process should have a start time");
1666
1667 assert_ne!(procs.start_time(pid), Some(actual.saturating_add(1)));
1668 }
1669
1670 #[test]
1671 fn test_format_bytes() {
1672 assert_eq!(format_bytes(512), "512 B");
1673 assert_eq!(format_bytes(1024), "1.0 KiB");
1674 assert_eq!(format_bytes(1536), "1.5 KiB");
1675 assert_eq!(format_bytes(50 * 1024 * 1024), "50.0 MiB");
1676 assert_eq!(format_bytes(3 * 1024 * 1024 * 1024), "3.0 GiB");
1677 assert_eq!(format_bytes(1100 * 1024 * 1024 * 1024), "1.1 TiB");
1679 }
1680
1681 #[test]
1682 fn test_format_bytes_per_sec() {
1683 assert_eq!(format_bytes_per_sec(512), "512 B/s");
1684 assert_eq!(format_bytes_per_sec(1536), "1.5 KiB/s");
1685 assert_eq!(format_bytes_per_sec(2 * 1024 * 1024), "2.0 MiB/s");
1686 }
1687}
1688
1689#[cfg(test)]
1690mod process_tree_tests {
1691 use super::{ParentToChildren, descendant_pids};
1692 use std::time::Duration;
1693
1694 fn assert_descendant_walk(root: u32, edges: &[(u32, &[u32])], expected: &[u32]) {
1696 let children: ParentToChildren = edges
1697 .iter()
1698 .map(|&(pid, children)| (pid, children.to_vec()))
1699 .collect();
1700 let (send, recv) = std::sync::mpsc::channel();
1701 std::thread::spawn(move || {
1702 let _ = send.send(descendant_pids(root, &children));
1703 });
1704 let mut actual = recv
1705 .recv_timeout(Duration::from_secs(10))
1706 .expect("process snapshot traversal must terminate even when parent PIDs cycle");
1707 actual.sort_unstable();
1708 assert_eq!(actual, expected);
1709 }
1710
1711 #[test]
1712 fn descendants_ignore_unrelated_parent_cycles() {
1713 assert_descendant_walk(
1714 1,
1715 &[(1, &[2, 3]), (2, &[4]), (9, &[10]), (10, &[9])],
1716 &[2, 3, 4],
1717 );
1718 }
1719
1720 #[test]
1721 fn descendants_do_not_include_the_root_when_parent_pids_cycle() {
1722 assert_descendant_walk(1, &[(1, &[2]), (2, &[3]), (3, &[1])], &[2, 3]);
1723 }
1724
1725 #[test]
1726 fn descendants_visit_each_pid_once_for_self_links_and_duplicate_edges() {
1727 assert_descendant_walk(1, &[(1, &[1, 2, 2]), (2, &[3]), (3, &[3])], &[2, 3]);
1728 }
1729
1730 #[test]
1731 fn descendants_keep_live_children_of_an_absent_parent() {
1732 assert_descendant_walk(1, &[(1, &[2]), (2, &[3]), (8, &[9])], &[2, 3]);
1733 assert_descendant_walk(7, &[(1, &[2])], &[]);
1734 }
1735}
1736
1737#[cfg(all(test, unix))]
1738mod tests {
1739 use super::*;
1740
1741 use std::os::unix::process::CommandExt;
1742 use std::process::{Child, Command, Stdio};
1743 use std::time::{Duration, Instant};
1744
1745 struct ChildGuard(Child);
1746
1747 impl Drop for ChildGuard {
1748 fn drop(&mut self) {
1749 let pid = self.0.id() as i32;
1750 let _ = unsafe { libc::killpg(pid, libc::SIGKILL) };
1752 let _ = self.0.wait();
1753 }
1754 }
1755
1756 #[tokio::test]
1757 async fn orphan_identity_checked_group_kill_rejects_mismatch() {
1758 let mut command = Command::new("sleep");
1759 command
1760 .arg("30")
1761 .stdin(Stdio::null())
1762 .stdout(Stdio::null())
1763 .stderr(Stdio::null());
1764 unsafe {
1765 command.pre_exec(|| {
1766 if libc::setsid() == -1 {
1767 return Err(std::io::Error::last_os_error());
1768 }
1769 Ok(())
1770 });
1771 }
1772
1773 let child = command.spawn().expect("failed to spawn test process");
1774 let pid = child.id();
1775 let _child = ChildGuard(child);
1776
1777 PROCS.refresh_pids(&[pid]);
1778 let actual_start_time = PROCS
1779 .start_time(pid)
1780 .expect("test process should have a start time");
1781
1782 let killed = PROCS
1783 .kill_process_group_if_start_time_matches_async(
1784 pid,
1785 Some(actual_start_time.saturating_add(1)),
1786 libc::SIGTERM,
1787 Some(Duration::from_millis(100)),
1788 )
1789 .await
1790 .expect("identity-checked kill should not error");
1791
1792 assert!(!killed);
1793 assert!(PROCS.is_running(pid), "mismatched process must survive");
1794 }
1795
1796 #[cfg(all(unix, not(target_os = "linux")))]
1801 #[tokio::test]
1802 async fn identity_checked_group_kill_reverifies_inside_blocking_op() {
1803 let mut command = Command::new("sleep");
1804 command
1805 .arg("30")
1806 .stdin(Stdio::null())
1807 .stdout(Stdio::null())
1808 .stderr(Stdio::null());
1809 unsafe {
1810 command.pre_exec(|| {
1811 if libc::setsid() == -1 {
1812 return Err(std::io::Error::last_os_error());
1813 }
1814 Ok(())
1815 });
1816 }
1817
1818 let child = command.spawn().expect("failed to spawn test process");
1819 let pid = child.id();
1820 let mut child = ChildGuard(child);
1821
1822 PROCS.refresh_pids(&[pid]);
1823 let actual_start_time = PROCS
1824 .start_time(pid)
1825 .expect("test process should have a start time");
1826
1827 let killed = PROCS
1828 .kill_process_group_if_start_time_matches_async(
1829 pid,
1830 Some(actual_start_time),
1831 libc::SIGTERM,
1832 Some(Duration::from_millis(100)),
1833 )
1834 .await
1835 .expect("identity-checked kill should not error");
1836
1837 assert!(killed, "matching generation must be signalled");
1838 let deadline = Instant::now() + Duration::from_secs(2);
1841 while child.0.try_wait().unwrap().is_none() {
1842 assert!(Instant::now() < deadline, "signalled child must exit");
1843 tokio::time::sleep(Duration::from_millis(10)).await;
1844 }
1845 assert!(
1846 !PROCS.is_running(pid),
1847 "signalled process group must be gone"
1848 );
1849 }
1850
1851 #[test]
1852 fn get_stats_includes_descendant_rss() {
1853 let mut command = Command::new("sh");
1854 command
1855 .args(["-c", "sleep 30 & wait"])
1856 .stdin(Stdio::null())
1857 .stdout(Stdio::null())
1858 .stderr(Stdio::null());
1859 unsafe {
1860 command.pre_exec(|| {
1861 if libc::setsid() == -1 {
1862 return Err(std::io::Error::last_os_error());
1863 }
1864 Ok(())
1865 });
1866 }
1867
1868 let parent = command.spawn().expect("failed to spawn process tree");
1869 let parent_pid = parent.id();
1870 let _parent = ChildGuard(parent);
1871
1872 let procs = Procs::new();
1873 let deadline = Instant::now() + Duration::from_secs(5);
1874 let mut child_pids = Vec::new();
1875 while Instant::now() < deadline {
1876 procs.refresh_processes();
1877 child_pids = procs.all_children(parent_pid);
1878 if !child_pids.is_empty() {
1879 break;
1880 }
1881 std::thread::sleep(Duration::from_millis(50));
1882 }
1883 assert!(
1884 !child_pids.is_empty(),
1885 "test process tree did not appear under parent pid {parent_pid}"
1886 );
1887
1888 procs.refresh_processes();
1889 child_pids = procs.all_children(parent_pid);
1890 assert!(
1891 !child_pids.is_empty(),
1892 "test process tree disappeared under parent pid {parent_pid}"
1893 );
1894 let root_pid = sysinfo::Pid::from_u32(parent_pid);
1895 let direct_memory = {
1896 let system = procs.lock_system();
1897 system
1898 .process(root_pid)
1899 .expect("parent process should exist")
1900 .memory()
1901 };
1902 let descendant_memory = {
1903 let system = procs.lock_system();
1904 child_pids
1905 .iter()
1906 .filter_map(|pid| system.process(sysinfo::Pid::from_u32(*pid)))
1907 .map(|process| process.memory())
1908 .sum::<u64>()
1909 };
1910 assert!(
1911 descendant_memory > 0,
1912 "descendants {child_pids:?} should have nonzero RSS"
1913 );
1914
1915 let stats = procs
1916 .get_stats(parent_pid)
1917 .expect("parent process should have aggregate stats");
1918
1919 assert_eq!(
1920 stats.memory_bytes,
1921 direct_memory + descendant_memory,
1922 "get_stats should include descendant RSS for parent pid {parent_pid}; \
1923 descendants: {child_pids:?}, direct RSS: {direct_memory}, \
1924 descendant RSS: {descendant_memory}, reported RSS: {}",
1925 stats.memory_bytes
1926 );
1927 }
1928
1929 #[test]
1930 fn full_refresh_is_throttled_by_ttl() {
1931 let procs = Procs::new();
1932
1933 assert!(
1935 procs.last_full_refresh.lock().unwrap().is_none(),
1936 "fresh Procs should have no recorded refresh"
1937 );
1938 procs.refresh_if_stale();
1939 let first = procs.last_full_refresh.lock().unwrap().unwrap();
1940 assert!(first.elapsed() < FULL_REFRESH_INTERVAL);
1941
1942 procs.refresh_if_stale();
1945 let second = procs.last_full_refresh.lock().unwrap().unwrap();
1946 assert_eq!(
1947 second, first,
1948 "refresh_if_stale within TTL must skip the refresh and keep the timestamp"
1949 );
1950
1951 let expired = Instant::now()
1954 .checked_sub(FULL_REFRESH_INTERVAL + Duration::from_secs(1))
1955 .expect("system has been up long enough to backdate by 6s");
1956 *procs.last_full_refresh.lock().unwrap() = Some(expired);
1957 procs.refresh_if_stale();
1958 let third = procs.last_full_refresh.lock().unwrap().unwrap();
1959 assert!(
1960 third > expired,
1961 "refresh_if_stale after expired TTL must refresh and advance the timestamp"
1962 );
1963 assert!(
1964 third.elapsed() < FULL_REFRESH_INTERVAL,
1965 "fresh timestamp after expired-TTL refresh should be recent"
1966 );
1967 }
1968}