Skip to main content

xtask/watchdog/
group.rs

1//! The process group a watched command runs in, and the signals aimed at it.
2//!
3//! The command is cargo, which starts nextest, which starts the test binaries,
4//! which start Postgres clients. Killing only the direct child leaves the rest
5//! running, so everything here addresses the group.
6
7use std::process::Child;
8use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
9use std::sync::{Arc, OnceLock};
10
11use anyhow::{Result, anyhow};
12use nix::sys::signal::{Signal, killpg};
13use nix::unistd::Pid;
14use signal_hook::consts::{SIGHUP, SIGINT, SIGQUIT, SIGTERM};
15
16use super::cpu;
17
18pub struct Group {
19    pgid: u32,
20}
21
22impl Group {
23    /// The child must have been started with `process_group(0)`.
24    pub fn of(child: &Child) -> Self {
25        Self { pgid: child.id() }
26    }
27
28    fn signal(&self, signal: Signal) {
29        if let Ok(pgid) = i32::try_from(self.pgid) {
30            let _ = killpg(Pid::from_raw(pgid), signal);
31        }
32    }
33
34    /// Freezes every member while keeping its sockets open, so the database
35    /// still sees the clients it is diagnosing.
36    pub fn freeze(&self) {
37        self.signal(Signal::SIGSTOP);
38    }
39
40    /// Safe to call when the group is already gone, and on every exit path:
41    /// a member can outlive the leader, and the group id stays reserved
42    /// until the last one dies.
43    pub fn kill(&self) {
44        self.signal(Signal::SIGKILL);
45    }
46
47    pub fn members(&self) -> Vec<u32> {
48        cpu::group_members(self.pgid)
49    }
50
51    /// Thread states of every member: futex_wait means a lock, epoll_wait means
52    /// a socket that will never answer. They vanish with the process, and a
53    /// stopped task reports only its stop, so read them before `freeze`.
54    pub fn thread_states(&self) -> Vec<String> {
55        self.members().into_iter().flat_map(task_states).collect()
56    }
57}
58
59fn task_states(pid: u32) -> Vec<String> {
60    std::fs::read_dir(format!("/proc/{pid}/task"))
61        .into_iter()
62        .flatten()
63        .flatten()
64        .filter_map(|entry| {
65            let wchan = std::fs::read_to_string(entry.path().join("wchan")).ok()?;
66            (!wchan.is_empty())
67                .then(|| format!("   pid {pid} tid {:?}: {wchan}", entry.file_name()))
68        })
69        .collect()
70}
71
72/// Process-wide termination state. Handlers cannot be removed again: the
73/// registry keeps its own handler installed after `unregister` and stops
74/// emulating the default action, so they are installed once and gated by `idle`.
75struct Signals {
76    requested: Arc<AtomicBool>,
77    idle: Arc<AtomicBool>,
78    holders: AtomicUsize,
79}
80
81static SIGNALS: OnceLock<Result<Signals, String>> = OnceLock::new();
82
83fn install() -> Result<Signals, String> {
84    let requested = Arc::new(AtomicBool::new(false));
85    let idle = Arc::new(AtomicBool::new(true));
86    for signal in [SIGHUP, SIGINT, SIGQUIT, SIGTERM] {
87        signal_hook::flag::register_conditional_default(signal, Arc::clone(&idle))
88            .and_then(|_| signal_hook::flag::register(signal, Arc::clone(&requested)))
89            .map_err(|err| err.to_string())?;
90    }
91    Ok(Signals {
92        requested,
93        idle,
94        holders: AtomicUsize::new(0),
95    })
96}
97
98/// Set when the xtask process is asked to stop during a watched run. The child
99/// is in its own process group, so the terminal's Ctrl-C no longer reaches it
100/// and xtask must pass it on. Outside a run the signals keep their default
101/// action, so the rest of xtask can still be interrupted.
102///
103/// Watches nest: an inner one joins the outer, which keeps the state it has
104/// seen, and the signals go back to their default action with the last drop.
105pub struct Termination {
106    signals: &'static Signals,
107}
108
109impl Termination {
110    pub fn watch() -> Result<Self> {
111        let signals = SIGNALS
112            .get_or_init(install)
113            .as_ref()
114            .map_err(|err| anyhow!("cannot watch for termination signals: {err}"))?;
115        if signals.holders.fetch_add(1, Ordering::SeqCst) == 0 {
116            signals.requested.store(false, Ordering::SeqCst);
117        }
118        signals.idle.store(false, Ordering::SeqCst);
119        Ok(Self { signals })
120    }
121
122    pub fn requested(&self) -> bool {
123        self.signals.requested.load(Ordering::SeqCst)
124    }
125}
126
127impl Drop for Termination {
128    fn drop(&mut self) {
129        if self.signals.holders.fetch_sub(1, Ordering::SeqCst) == 1 {
130            self.signals.idle.store(true, Ordering::SeqCst);
131        }
132    }
133}
134
135#[cfg(test)]
136mod tests;