Lines
95.24 %
Functions
68.75 %
Branches
100 %
//! The process group a watched command runs in, and the signals aimed at it.
//!
//! The command is cargo, which starts nextest, which starts the test binaries,
//! which start Postgres clients. Killing only the direct child leaves the rest
//! running, so everything here addresses the group.
use std::process::Child;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, OnceLock};
use anyhow::{Result, anyhow};
use nix::sys::signal::{Signal, killpg};
use nix::unistd::Pid;
use signal_hook::consts::{SIGHUP, SIGINT, SIGQUIT, SIGTERM};
use super::cpu;
pub struct Group {
pgid: u32,
}
impl Group {
/// The child must have been started with `process_group(0)`.
pub fn of(child: &Child) -> Self {
Self { pgid: child.id() }
fn signal(&self, signal: Signal) {
if let Ok(pgid) = i32::try_from(self.pgid) {
let _ = killpg(Pid::from_raw(pgid), signal);
/// Freezes every member while keeping its sockets open, so the database
/// still sees the clients it is diagnosing.
pub fn freeze(&self) {
self.signal(Signal::SIGSTOP);
/// Safe to call when the group is already gone, and on every exit path:
/// a member can outlive the leader, and the group id stays reserved
/// until the last one dies.
pub fn kill(&self) {
self.signal(Signal::SIGKILL);
pub fn members(&self) -> Vec<u32> {
cpu::group_members(self.pgid)
/// Thread states of every member: futex_wait means a lock, epoll_wait means
/// a socket that will never answer. They vanish with the process, and a
/// stopped task reports only its stop, so read them before `freeze`.
pub fn thread_states(&self) -> Vec<String> {
self.members().into_iter().flat_map(task_states).collect()
fn task_states(pid: u32) -> Vec<String> {
std::fs::read_dir(format!("/proc/{pid}/task"))
.into_iter()
.flatten()
.filter_map(|entry| {
let wchan = std::fs::read_to_string(entry.path().join("wchan")).ok()?;
(!wchan.is_empty())
.then(|| format!(" pid {pid} tid {:?}: {wchan}", entry.file_name()))
})
.collect()
/// Process-wide termination state. Handlers cannot be removed again: the
/// registry keeps its own handler installed after `unregister` and stops
/// emulating the default action, so they are installed once and gated by `idle`.
struct Signals {
requested: Arc<AtomicBool>,
idle: Arc<AtomicBool>,
holders: AtomicUsize,
static SIGNALS: OnceLock<Result<Signals, String>> = OnceLock::new();
fn install() -> Result<Signals, String> {
let requested = Arc::new(AtomicBool::new(false));
let idle = Arc::new(AtomicBool::new(true));
for signal in [SIGHUP, SIGINT, SIGQUIT, SIGTERM] {
signal_hook::flag::register_conditional_default(signal, Arc::clone(&idle))
.and_then(|_| signal_hook::flag::register(signal, Arc::clone(&requested)))
.map_err(|err| err.to_string())?;
Ok(Signals {
requested,
idle,
holders: AtomicUsize::new(0),
/// Set when the xtask process is asked to stop during a watched run. The child
/// is in its own process group, so the terminal's Ctrl-C no longer reaches it
/// and xtask must pass it on. Outside a run the signals keep their default
/// action, so the rest of xtask can still be interrupted.
///
/// Watches nest: an inner one joins the outer, which keeps the state it has
/// seen, and the signals go back to their default action with the last drop.
pub struct Termination {
signals: &'static Signals,
impl Termination {
pub fn watch() -> Result<Self> {
let signals = SIGNALS
.get_or_init(install)
.as_ref()
.map_err(|err| anyhow!("cannot watch for termination signals: {err}"))?;
if signals.holders.fetch_add(1, Ordering::SeqCst) == 0 {
signals.requested.store(false, Ordering::SeqCst);
signals.idle.store(false, Ordering::SeqCst);
Ok(Self { signals })
pub fn requested(&self) -> bool {
self.signals.requested.load(Ordering::SeqCst)
impl Drop for Termination {
fn drop(&mut self) {
if self.signals.holders.fetch_sub(1, Ordering::SeqCst) == 1 {
self.signals.idle.store(true, Ordering::SeqCst);
#[cfg(test)]
mod tests;