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,
done: tokio::sync::Notify,
}
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),
done: tokio::sync::Notify::new(),
}
}
pub(super) fn stop(self: &Arc<Self>, mut child: Box<dyn ChildWrapper>, recorded: Option<super::ledger::Recorded>, removal: Option<Removal>) {
if cfg!(unix) && !interrupt(child.as_ref()) {
end(child.as_mut());
removal.inspect(Removal::run);
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, their_removal) = (Arc::clone(self), Arc::clone(&slot), removal.clone());
let spawned = std::thread::Builder::new().name("isothrum-stop".into()).spawn(move || {
if let Some(mut tool) = take(&theirs) {
if cfg!(unix) || interrupt(tool.as_ref()) {
stopping.end_when_stopped(tool.as_mut(), since);
} else {
end(tool.as_mut());
}
}
their_removal.inspect(Removal::run);
drop(recorded);
stopping.count.fetch_sub(1, Ordering::SeqCst);
stopping.done.notify_waiters();
});
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());
}
removal.inspect(Removal::run);
self.count.fetch_sub(1, Ordering::SeqCst);
self.done.notify_waiters();
}
}
pub(super) fn any(&self) -> bool {
self.count.load(Ordering::SeqCst) > 0
}
pub(super) async fn stopped(&self) {
loop {
let notified = self.done.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if !self.any() {
return;
}
notified.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 {
tracing::debug!(pid = ?child.id(), "asking a process tree cut short to stop");
match child.signal(nix::libc::SIGINT) {
Ok(()) => true,
Err(e) => {
tracing::debug!(error = %e, "the process tree had already ended");
false
}
}
}
#[cfg(windows)]
const HELPER_LIMIT: Duration = Duration::from_secs(20);
#[cfg(windows)]
#[expect(
clippy::disallowed_methods,
reason = "the process module's own interrupt of a child it started (a console-control helper)"
)]
fn interrupt(child: &dyn ChildWrapper) -> bool {
use std::os::windows::process::CommandExt as _;
use windows::Win32::System::Threading::CREATE_NO_WINDOW;
let Some(pid) = child.id() else { return false };
tracing::debug!(pid, "asking a process tree cut short to stop (Ctrl-C on its console)");
let helper = std::process::Command::new("powershell")
.args(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", &ctrl_c_script(pid)])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.creation_flags(CREATE_NO_WINDOW.0)
.spawn();
let mut helper = match helper {
Ok(helper) => helper,
Err(e) => {
tracing::warn!(pid, error = %e, "PowerShell couldn't run to ask a tool to stop: it is ended at once");
return false;
}
};
let deadline = Instant::now() + HELPER_LIMIT;
loop {
match helper.try_wait() {
Ok(Some(status)) if status.success() => return true,
Ok(Some(status)) => {
tracing::debug!(pid, code = ?status.code(), "the tool's console couldn't be sent Ctrl-C: it is ended at once");
return false;
}
Ok(None) if Instant::now() < deadline => std::thread::sleep(POLL),
Ok(None) | Err(_) => {
if let Err(e) = helper.kill() {
tracing::debug!(error = %e, "the Ctrl-C helper had ended");
}
tracing::warn!(pid, "the Ctrl-C helper didn't answer: the tool is ended at once");
return false;
}
}
}
}
#[cfg(any(windows, test))]
fn ctrl_c_script(pid: u32) -> String {
format!(
"$ErrorActionPreference = 'Stop'\n\
Add-Type -Namespace Isothrum -Name Ctrl -MemberDefinition @'\n\
[DllImport(\"kernel32.dll\", SetLastError = true)] public static extern bool FreeConsole();\n\
[DllImport(\"kernel32.dll\", SetLastError = true)] public static extern bool AttachConsole(uint pid);\n\
[DllImport(\"kernel32.dll\", SetLastError = true)] public static extern bool SetConsoleCtrlHandler(System.IntPtr handler, bool add);\n\
[DllImport(\"kernel32.dll\", SetLastError = true)] public static extern bool GenerateConsoleCtrlEvent(uint ctrlEvent, uint group);\n\
'@\n\
[void][Isothrum.Ctrl]::FreeConsole()\n\
if (-not [Isothrum.Ctrl]::AttachConsole({pid})) {{ exit 2 }}\n\
[void][Isothrum.Ctrl]::SetConsoleCtrlHandler([System.IntPtr]::Zero, $true)\n\
if (-not [Isothrum.Ctrl]::GenerateConsoleCtrlEvent(0, 0)) {{ exit 3 }}\n\
exit 0\n"
)
}
#[derive(Debug, Clone)]
pub(super) struct Removal {
pub(super) program: String,
pub(super) name: String,
pub(super) withheld: Vec<String>,
pub(super) env: Vec<(String, String)>,
pub(super) stripped: Vec<String>,
}
impl Removal {
#[expect(clippy::disallowed_methods, reason = "the process module's own stopping helper, started by the runner it serves")]
pub(super) fn run(&self) {
let mut cmd = std::process::Command::new(&self.program);
cmd.args(["rm", "-f", &self.name])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
for var in &self.withheld {
cmd.env_remove(var);
}
cmd.envs(self.env.iter().map(|(k, v)| (k.as_str(), v.as_str())));
for var in &self.stripped {
cmd.env_remove(var);
}
headless(&mut cmd);
match cmd.status() {
Ok(status) if status.success() => {
tracing::debug!(container = %self.name, "removed the container of a tool that was ended");
}
Ok(status) => {
tracing::debug!(container = %self.name, code = ?status.code(), "the container of a tool that was ended wasn't removed (gone already, or no engine)");
}
Err(e) => {
tracing::warn!(container = %self.name, error = %e, "the container of a tool that was ended couldn't be removed: it may still run");
}
}
}
}
#[cfg(windows)]
fn headless(cmd: &mut std::process::Command) {
use std::os::windows::process::CommandExt;
use windows::Win32::System::Threading::CREATE_NO_WINDOW;
cmd.creation_flags(CREATE_NO_WINDOW.0);
}
#[cfg(not(windows))]
fn headless(_cmd: &mut std::process::Command) {}
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");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_ctrl_c_helper_attaches_to_the_tools_console_and_ignores_the_event_itself() {
let script = ctrl_c_script(4242);
let at = |needle: &str| script.find(needle).unwrap_or_else(|| panic!("{needle} in {script}"));
assert!(at("FreeConsole()\n") < at("AttachConsole(4242)"));
assert!(at("AttachConsole(4242)") < at("SetConsoleCtrlHandler([System.IntPtr]::Zero, $true)"));
assert!(at("SetConsoleCtrlHandler([System.IntPtr]::Zero, $true)") < at("GenerateConsoleCtrlEvent(0, 0)"));
assert!(script.contains("\n'@\n"), "{script}");
}
}