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

            
7
use std::process::Child;
8
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
9
use std::sync::{Arc, OnceLock};
10

            
11
use anyhow::{Result, anyhow};
12
use nix::sys::signal::{Signal, killpg};
13
use nix::unistd::Pid;
14
use signal_hook::consts::{SIGHUP, SIGINT, SIGQUIT, SIGTERM};
15

            
16
use super::cpu;
17

            
18
pub struct Group {
19
    pgid: u32,
20
}
21

            
22
impl Group {
23
    /// The child must have been started with `process_group(0)`.
24
18
    pub fn of(child: &Child) -> Self {
25
18
        Self { pgid: child.id() }
26
18
    }
27

            
28
21
    fn signal(&self, signal: Signal) {
29
21
        if let Ok(pgid) = i32::try_from(self.pgid) {
30
21
            let _ = killpg(Pid::from_raw(pgid), signal);
31
        }
32
21
    }
33

            
34
    /// Freezes every member while keeping its sockets open, so the database
35
    /// still sees the clients it is diagnosing.
36
3
    pub fn freeze(&self) {
37
3
        self.signal(Signal::SIGSTOP);
38
3
    }
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
18
    pub fn kill(&self) {
44
18
        self.signal(Signal::SIGKILL);
45
18
    }
46

            
47
10
    pub fn members(&self) -> Vec<u32> {
48
10
        cpu::group_members(self.pgid)
49
10
    }
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
3
    pub fn thread_states(&self) -> Vec<String> {
55
3
        self.members().into_iter().flat_map(task_states).collect()
56
3
    }
57
}
58

            
59
5
fn task_states(pid: u32) -> Vec<String> {
60
5
    std::fs::read_dir(format!("/proc/{pid}/task"))
61
5
        .into_iter()
62
5
        .flatten()
63
5
        .flatten()
64
5
        .filter_map(|entry| {
65
5
            let wchan = std::fs::read_to_string(entry.path().join("wchan")).ok()?;
66
5
            (!wchan.is_empty())
67
5
                .then(|| format!("   pid {pid} tid {:?}: {wchan}", entry.file_name()))
68
5
        })
69
        .collect()
70
5
}
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`.
75
struct Signals {
76
    requested: Arc<AtomicBool>,
77
    idle: Arc<AtomicBool>,
78
    holders: AtomicUsize,
79
}
80

            
81
static SIGNALS: OnceLock<Result<Signals, String>> = OnceLock::new();
82

            
83
18
fn install() -> Result<Signals, String> {
84
18
    let requested = Arc::new(AtomicBool::new(false));
85
18
    let idle = Arc::new(AtomicBool::new(true));
86
18
    for signal in [SIGHUP, SIGINT, SIGQUIT, SIGTERM] {
87
72
        signal_hook::flag::register_conditional_default(signal, Arc::clone(&idle))
88
72
            .and_then(|_| signal_hook::flag::register(signal, Arc::clone(&requested)))
89
            .map_err(|err| err.to_string())?;
90
    }
91
18
    Ok(Signals {
92
18
        requested,
93
18
        idle,
94
18
        holders: AtomicUsize::new(0),
95
18
    })
96
18
}
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.
105
pub struct Termination {
106
    signals: &'static Signals,
107
}
108

            
109
impl Termination {
110
20
    pub fn watch() -> Result<Self> {
111
20
        let signals = SIGNALS
112
20
            .get_or_init(install)
113
20
            .as_ref()
114
            .map_err(|err| anyhow!("cannot watch for termination signals: {err}"))?;
115
20
        if signals.holders.fetch_add(1, Ordering::SeqCst) == 0 {
116
18
            signals.requested.store(false, Ordering::SeqCst);
117
2
        }
118
20
        signals.idle.store(false, Ordering::SeqCst);
119
20
        Ok(Self { signals })
120
20
    }
121

            
122
74
    pub fn requested(&self) -> bool {
123
74
        self.signals.requested.load(Ordering::SeqCst)
124
74
    }
125
}
126

            
127
impl Drop for Termination {
128
20
    fn drop(&mut self) {
129
20
        if self.signals.holders.fetch_sub(1, Ordering::SeqCst) == 1 {
130
18
            self.signals.idle.store(true, Ordering::SeqCst);
131
2
        }
132
20
    }
133
}
134

            
135
#[cfg(test)]
136
mod tests;