use crate::executor::{is_process_group_alive, DEFAULT_KILL_AFTER};
use std::io;
use std::process::{ExitStatus, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::process::{Child, Command};
#[cfg(not(unix))]
use tokio::sync::Notify;
use tokio::task::{AbortHandle, JoinHandle};
use tokio::time::{sleep, sleep_until, timeout, timeout_at, Instant};
pub const MAX_TIMER_MS: u64 = 2_147_483_647;
pub enum IsolationTarget {
Docker(String),
Screen(String),
}
impl IsolationTarget {
pub async fn signal(&self, signal: &str, env: &[(String, String)]) -> bool {
let mut command = match self {
Self::Docker(cid_file) => {
let Ok(id) = tokio::fs::read_to_string(cid_file).await else {
return false;
};
let id = id.trim();
if id.len() != 64 || !id.bytes().all(|value| value.is_ascii_hexdigit()) {
return false;
}
let mut command = Command::new("docker");
command.args(["kill", &format!("--signal={signal}"), id]);
command
}
Self::Screen(name) => {
let mut command = Command::new("screen");
command.args(["-S", name, "-X", "quit"]);
command
}
};
command
.env_clear()
.envs(env.iter().map(|(key, value)| (key, value)))
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true);
timeout(DEFAULT_KILL_AFTER, command.status())
.await
.is_ok_and(|status| status.is_ok_and(|status| status.success()))
}
}
pub struct TimedChild {
pub task: JoinHandle<io::Result<ExitStatus>>,
pub grace: Arc<Mutex<Duration>>,
expired: Arc<AtomicBool>,
#[cfg(not(unix))]
pub cancel: Arc<Notify>,
}
impl TimedChild {
pub fn new(
mut child: Child,
duration: Duration,
initial_grace: Duration,
target: Option<IsolationTarget>,
env: Vec<(String, String)>,
readers: Option<[AbortHandle; 2]>,
) -> Self {
let deadline = Instant::now() + duration;
let pid = child.id();
let grace = Arc::new(Mutex::new(initial_grace));
let current_grace = Arc::clone(&grace);
let expired = Arc::new(AtomicBool::new(false));
let mark_expired = Arc::clone(&expired);
#[cfg(not(unix))]
let cancel = Arc::new(Notify::new());
#[cfg(not(unix))]
let cancel_requested = Arc::clone(&cancel);
let task = tokio::spawn(async move {
#[cfg(unix)]
tokio::select! {
biased;
status = wait_for_completion(&mut child, readers.as_ref()) => return status,
() = sleep_until(deadline) => {}
}
#[cfg(not(unix))]
tokio::select! {
biased;
status = wait_for_completion(&mut child, readers.as_ref()) => return status,
() = cancel_requested.notified() => {
child.start_kill()?;
return child.wait().await;
}
() = sleep_until(deadline) => {}
}
mark_expired.store(true, Ordering::Relaxed);
let grace = *current_grace
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
stop_timed_out_child(&mut child, pid, grace, target.as_ref(), &env).await
});
Self {
task,
grace,
expired,
#[cfg(not(unix))]
cancel,
}
}
pub fn expired(&self) -> bool {
self.expired.load(Ordering::Relaxed)
}
}
async fn wait_for_completion(
child: &mut Child,
readers: Option<&[AbortHandle; 2]>,
) -> io::Result<ExitStatus> {
let status = child.wait().await?;
while readers.is_some_and(|readers| readers.iter().any(|reader| !reader.is_finished())) {
sleep(Duration::from_millis(10)).await;
}
Ok(status)
}
async fn stop_timed_out_child(
child: &mut Child,
pid: Option<u32>,
grace: Duration,
target: Option<&IsolationTarget>,
env: &[(String, String)],
) -> io::Result<ExitStatus> {
let force_at = Instant::now() + grace;
let sent = match target {
Some(target) => timeout_at(force_at, target.signal("TERM", env))
.await
.unwrap_or(false),
None => false,
};
if !sent {
#[cfg(unix)]
if let Some(pid) = pid {
let _ = crate::executor::kill_group(pid, "TERM").await;
}
#[cfg(not(unix))]
child.start_kill()?;
}
let status = timeout_at(force_at, child.wait()).await;
let status = match status {
Ok(status) if !group_alive(pid).await => return status,
status => status,
};
sleep_until(force_at).await;
let force_target = async {
if let Some(target) = target {
target.signal("KILL", env).await;
}
};
let force_group = async {
#[cfg(unix)]
if let Some(pid) = pid {
let _ = crate::executor::kill_group(pid, "KILL").await;
}
#[cfg(not(unix))]
let _ = child.start_kill();
};
tokio::join!(force_target, force_group);
match status {
Ok(status) => status,
Err(_) => child.wait().await,
}
}
async fn group_alive(pid: Option<u32>) -> bool {
if let Some(pid) = pid {
is_process_group_alive(pid).await
} else {
false
}
}