use std::sync::{Mutex, OnceLock};
pub(crate) struct ReapJob {
pub(crate) os: super::OsResources,
pub(crate) pid: u32,
#[cfg(test)]
pub(crate) origin: std::thread::ThreadId,
#[cfg(test)]
pub(crate) probe: Option<test_probe::DropProbe>,
#[cfg(test)]
pub(crate) force_panic: bool,
#[cfg(test)]
pub(crate) force_release_panic: bool,
#[cfg(test)]
pub(crate) force_glue_panic: bool,
}
const REAPER_POOL_THREADS: usize = 2;
const _: () = assert!(REAPER_POOL_THREADS >= 2);
struct Pool {
tx: crossbeam_channel::Sender<ReapJob>,
}
impl Pool {
fn dispatch(&self, job: ReapJob) {
let backlog = self.tx.len();
if backlog > 0 {
log::debug!(
"child {} queued behind {backlog} reaps (pool width {REAPER_POOL_THREADS})",
job.pid
);
}
if let Err(e) = self.tx.send(job) {
release(e.into_inner());
debug_assert!(false, "a published reaper pool's channel cannot disconnect");
}
}
}
struct LazyPool {
bound: usize,
cell: OnceLock<Pool>,
init: Mutex<()>,
#[cfg(test)]
inits: std::sync::atomic::AtomicUsize,
}
impl LazyPool {
const fn new(bound: usize) -> LazyPool {
LazyPool {
bound,
cell: OnceLock::new(),
init: Mutex::new(()),
#[cfg(test)]
inits: std::sync::atomic::AtomicUsize::new(0),
}
}
fn get(&self) -> Option<&Pool> {
if let Some(pool) = self.cell.get() {
return Some(pool);
}
let mut abandoned: Vec<std::thread::JoinHandle<()>> = Vec::new();
let mut failures: Vec<std::io::Error> = Vec::new();
let mut published = false;
{
let guard = match self.init.lock() {
Ok(guard) => guard,
Err(poisoned) => {
debug_assert!(false, "the reaper init lock cannot be poisoned");
poisoned.into_inner()
}
};
if self.cell.get().is_none() {
#[cfg(test)]
self.inits.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
#[cfg(test)]
let mut forced = fault::take_force_spawn_failures();
let (tx, rx) = crossbeam_channel::unbounded::<ReapJob>();
let mut started = 0usize;
for _ in 0..self.bound {
#[cfg(test)]
if forced > 0 {
forced -= 1;
failures.push(std::io::Error::other("forced reaper spawn failure (test seam)"));
continue;
}
let rx = rx.clone();
match std::thread::Builder::new()
.name("cosca-reaper".to_owned())
.spawn(move || work(rx))
{
Ok(handle) => {
started += 1;
abandoned.push(handle);
}
Err(e) => failures.push(e),
}
}
if started == self.bound {
match self.cell.set(Pool { tx }) {
Ok(()) => {
abandoned.clear();
published = true;
}
Err(_) => debug_assert!(false, "the reaper cell was set past its own in-lock re-check"),
}
}
}
drop(guard);
}
for handle in abandoned {
let _ = handle.join();
}
for e in failures {
log::error!("starting a reaper thread failed: {e}");
}
if published {
log::debug!("reaper pool started ({} threads)", self.bound);
}
self.cell.get()
}
}
fn work(rx: crossbeam_channel::Receiver<ReapJob>) {
while let Ok(job) = rx.recv() {
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run_teardown(job))).is_err() {
let _ = std::panic::catch_unwind(|| {
log::error!("a reaper teardown unwound despite its no-unwind contract");
debug_assert!(false, "run_teardown unwound despite its no-unwind contract");
});
}
}
}
fn submit_to(lazy: &LazyPool, job: ReapJob) {
#[cfg(test)]
let job = ReapJob {
force_panic: fault::take_force_teardown_panic(),
..job
};
match lazy.get() {
Some(pool) => pool.dispatch(job),
None => release(job),
}
}
pub(crate) fn submit(job: ReapJob) {
static GLOBAL: LazyPool = LazyPool::new(REAPER_POOL_THREADS);
submit_to(&GLOBAL, job);
}
fn release(job: ReapJob) {
log::error!(
"no reaper thread is available; child {} is left to the runtime's orphan handling (it is \
already signalled)",
job.pid
);
#[cfg(test)]
let probe = job.probe;
drop(job.os);
#[cfg(test)]
if let Some(p) = probe {
let _ = p.outcome.send(test_probe::ReapOutcome::Released);
}
}
pub(crate) fn run_teardown(job: ReapJob) {
#[cfg(test)]
let origin = job.origin;
#[cfg(test)]
let probe = job.probe;
#[cfg(test)]
let force_panic = job.force_panic;
#[cfg(test)]
let force_release_panic = job.force_release_panic;
#[cfg(test)]
let force_glue_panic = job.force_glue_panic;
let mut os = job.os;
let pid = job.pid;
let waited = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
#[cfg(test)]
if let Some(p) = probe.as_ref() {
let _ = p.started.send(std::thread::current().id());
}
#[cfg(test)]
if std::thread::current().id() != origin {
if let Some(p) = probe.as_ref() {
let _ = p.gate.recv(); }
}
#[cfg(test)]
if force_panic {
panic!("forced teardown panic (test seam)");
}
os.proc_mut().wait_and_reap(pid);
}));
#[cfg(test)]
if force_glue_panic {
panic!("forced glue panic (test seam)");
}
let released = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if waited.is_err() {
log::error!("reaping child {pid} panicked; releasing its resources anyway");
}
#[cfg(test)]
if force_release_panic {
panic!("forced release-region panic (test seam)");
}
drop(os); #[cfg(test)]
if let Some(p) = probe {
let _ = p.outcome.send(if waited.is_err() {
test_probe::ReapOutcome::Panicked
} else {
test_probe::ReapOutcome::Reaped(std::thread::current().id())
});
}
}));
if released.is_err() {
let _ = std::panic::catch_unwind(|| {
log::error!("releasing child {pid}'s resources panicked; its wait had already completed");
});
}
}
#[cfg(test)]
pub(crate) mod fault {
use std::cell::Cell;
thread_local! {
static FORCE_SPAWN_FAILURES: Cell<usize> = const { Cell::new(0) };
static FORCE_TEARDOWN_PANIC: Cell<bool> = const { Cell::new(false) };
static FORCE_KILL_FAILURE: Cell<bool> = const { Cell::new(false) };
}
pub(crate) fn set_force_spawn_failures(n: usize) {
FORCE_SPAWN_FAILURES.with(|f| f.set(n));
}
pub(crate) fn take_force_spawn_failures() -> usize {
FORCE_SPAWN_FAILURES.with(|f| f.replace(0))
}
pub(crate) fn set_force_teardown_panic(on: bool) {
FORCE_TEARDOWN_PANIC.with(|f| f.set(on));
}
pub(crate) fn take_force_teardown_panic() -> bool {
FORCE_TEARDOWN_PANIC.with(|f| f.replace(false))
}
pub(crate) fn set_force_kill_failure(on: bool) {
FORCE_KILL_FAILURE.with(|f| f.set(on));
}
pub(crate) fn take_force_kill_failure() -> bool {
FORCE_KILL_FAILURE.with(|f| f.replace(false))
}
}
#[cfg(test)]
pub(crate) mod test_probe {
use std::cell::RefCell;
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum ReapOutcome {
Reaped(std::thread::ThreadId),
Released,
Panicked,
}
pub(crate) struct DropProbe {
pub(crate) entered: std::sync::mpsc::Sender<std::thread::ThreadId>,
pub(crate) started: std::sync::mpsc::Sender<std::thread::ThreadId>,
pub(crate) gate: std::sync::mpsc::Receiver<()>,
pub(crate) outcome: std::sync::mpsc::Sender<ReapOutcome>,
}
thread_local! {
static PROBE: RefCell<Option<DropProbe>> = const { RefCell::new(None) };
}
pub(crate) fn arm(probe: DropProbe) {
PROBE.with(|p| *p.borrow_mut() = Some(probe));
}
pub(crate) fn take() -> Option<DropProbe> {
PROBE.with(|p| p.borrow_mut().take())
}
}
#[cfg(test)]
#[path = "reaper_tests.rs"]
mod reaper_tests;