use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};
use process_wrap::tokio::ChildWrapper;
pub(super) const GRACE: Duration = Duration::from_secs(30);
const POLL: Duration = Duration::from_millis(50);
#[derive(Debug)]
pub(super) struct Stopping {
grace: Duration,
count: AtomicUsize,
epoch: AtomicU64,
}
type Slot = Arc<Mutex<Option<Box<dyn ChildWrapper>>>>;
impl Stopping {
pub(super) fn new(grace: Duration) -> Stopping {
Stopping {
grace,
count: AtomicUsize::new(0),
epoch: AtomicU64::new(0),
}
}
pub(super) fn stop(self: &Arc<Self>, mut child: Box<dyn ChildWrapper>) {
if !interrupt(child.as_ref()) {
end(child.as_mut());
return;
}
self.count.fetch_add(1, Ordering::SeqCst);
let since = self.epoch.load(Ordering::SeqCst);
let slot: Slot = Arc::new(Mutex::new(Some(child)));
let (stopping, theirs) = (Arc::clone(self), Arc::clone(&slot));
let spawned = std::thread::Builder::new().name("isothrum-stop".into()).spawn(move || {
if let Some(mut tool) = take(&theirs) {
stopping.end_when_stopped(tool.as_mut(), since);
}
stopping.count.fetch_sub(1, Ordering::SeqCst);
});
if let Err(e) = spawned {
tracing::warn!(error = %e, "no thread to wait for a tool to stop: it is ended at once");
if let Some(mut tool) = take(&slot) {
end(tool.as_mut());
}
self.count.fetch_sub(1, Ordering::SeqCst);
}
}
pub(super) fn any(&self) -> bool {
self.count.load(Ordering::SeqCst) > 0
}
pub(super) async fn stopped(&self) {
while self.any() {
tokio::time::sleep(POLL).await;
}
}
pub(super) fn end_now(&self) {
self.epoch.fetch_add(1, Ordering::SeqCst);
}
fn end_when_stopped(&self, child: &mut dyn ChildWrapper, since: u64) {
let deadline = Instant::now() + self.grace;
while Instant::now() < deadline && self.epoch.load(Ordering::SeqCst) == since && !exited(child) {
std::thread::sleep(POLL);
}
end(child);
}
}
fn take(slot: &Slot) -> Option<Box<dyn ChildWrapper>> {
slot.lock().unwrap_or_else(PoisonError::into_inner).take()
}
fn exited(child: &mut dyn ChildWrapper) -> bool {
!matches!(child.try_wait(), Ok(None))
}
#[cfg(unix)]
fn interrupt(child: &dyn ChildWrapper) -> bool {
const SIGINT: i32 = 2;
tracing::debug!(pid = ?child.id(), "asking a process tree cut short to stop");
match child.signal(SIGINT) {
Ok(()) => true,
Err(e) => {
tracing::debug!(error = %e, "the process tree had already ended");
false
}
}
}
#[cfg(windows)]
fn interrupt(_child: &dyn ChildWrapper) -> bool {
false
}
fn end(child: &mut dyn ChildWrapper) {
tracing::debug!(pid = ?child.id(), "ending a process tree cut short");
if let Err(e) = child.start_kill() {
tracing::debug!(error = %e, "the process tree had already ended");
}
}