use std::path::{Path, PathBuf};
use std::process::Child;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
static SHUTDOWN: AtomicBool = AtomicBool::new(false);
static SIGNAL: AtomicU8 = AtomicU8::new(0);
static TEMPS: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
static CHILDREN: Mutex<Vec<(u64, Arc<Mutex<Child>>)>> = Mutex::new(Vec::new());
static NEXT_CHILD_ID: AtomicU64 = AtomicU64::new(0);
static EXIT_LOCK: Mutex<()> = Mutex::new(());
fn lock_through_poison<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
fn exit_interrupted() -> i32 {
i32::from(crate::error::Error::Interrupted.exit_code())
}
fn exit_terminated() -> i32 {
i32::from(crate::error::Error::Terminated.exit_code())
}
fn exit_timeout() -> i32 {
i32::from(crate::error::Error::Timeout.exit_code())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShutdownReason {
None,
Sigint,
Sigterm,
Forced,
}
pub fn reset_sigpipe() {
}
pub fn install_handlers() {
#[cfg(unix)]
{
use signal_hook::consts::{SIGINT, SIGTERM};
use signal_hook::iterator::Signals;
let Ok(mut signals) = Signals::new([SIGINT, SIGTERM]) else {
return;
};
std::thread::spawn(move || {
for sig in signals.forever() {
if SHUTDOWN.load(Ordering::SeqCst) {
SIGNAL.store(3, Ordering::SeqCst);
force_exit(sig == SIGTERM);
}
SIGNAL.store(if sig == SIGTERM { 2 } else { 1 }, Ordering::SeqCst);
SHUTDOWN.store(true, Ordering::SeqCst);
}
});
}
#[cfg(not(unix))]
{
let _ = ctrlc::set_handler(|| {
if SHUTDOWN.load(Ordering::SeqCst) {
SIGNAL.store(3, Ordering::SeqCst);
force_exit(false);
}
SIGNAL.store(1, Ordering::SeqCst);
SHUTDOWN.store(true, Ordering::SeqCst);
});
}
}
fn force_exit(terminated: bool) -> ! {
let _exit = lock_through_poison(&EXIT_LOCK);
kill_children();
cleanup_temps();
std::process::exit(if terminated {
exit_terminated()
} else {
exit_interrupted()
});
}
pub fn arm_deadline(seconds: u64, correlation_id: &str, target: Option<(String, &'static str)>) {
if seconds == 0 {
return;
}
let correlation_id = correlation_id.to_string();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_secs(seconds));
let _exit = lock_through_poison(&EXIT_LOCK);
let err = crate::error::Error::Timeout;
let designated = target
.as_ref()
.map(|(resolved, source)| crate::error::TargetRef { resolved, source });
let _ = crate::output::write_error(
&err,
&correlation_id,
&crate::surface::Surface::default(),
designated,
);
kill_children();
cleanup_temps();
std::process::exit(exit_timeout());
});
}
pub fn register_temp(path: &Path) {
lock_through_poison(&TEMPS).push(path.to_path_buf());
}
pub fn release_temp(path: &Path) {
lock_through_poison(&TEMPS).retain(|p| p != path);
}
pub fn cleanup_temps() {
let mut guard = lock_through_poison(&TEMPS);
for path in guard.drain(..) {
if path.is_dir() {
let _ = std::fs::remove_dir_all(&path);
} else {
let _ = std::fs::remove_file(&path);
}
}
}
pub fn spawn_tracked(cmd: &mut std::process::Command) -> std::io::Result<(u64, Arc<Mutex<Child>>)> {
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
let child = cmd.spawn()?;
let child = Arc::new(Mutex::new(child));
let id = register_child(Arc::clone(&child));
Ok((id, child))
}
pub fn register_child(child: Arc<Mutex<Child>>) -> u64 {
let id = NEXT_CHILD_ID.fetch_add(1, Ordering::SeqCst);
lock_through_poison(&CHILDREN).push((id, child));
id
}
pub fn release_child(id: u64) {
lock_through_poison(&CHILDREN).retain(|(known, _)| *known != id);
}
pub fn kill_children() {
let taken: Vec<_> = lock_through_poison(&CHILDREN).drain(..).collect();
for (_, child) in taken {
let mut guard = lock_through_poison(&child);
kill_child_tree(&mut guard);
}
}
pub fn kill_child_tree(child: &mut Child) {
#[cfg(unix)]
{
let pgid = child.id() as libc::pid_t;
unsafe {
libc::kill(-pgid, libc::SIGKILL);
}
}
let _ = child.kill();
let _ = child.wait();
}
static DEADLINE_MS: AtomicU64 = AtomicU64::new(0);
static START: Mutex<Option<std::time::Instant>> = Mutex::new(None);
pub fn publish_deadline(seconds: u64) {
if seconds == 0 {
return;
}
*lock_through_poison(&START) = Some(std::time::Instant::now());
DEADLINE_MS.store(seconds.saturating_mul(1000), Ordering::SeqCst);
}
pub fn deadline_exceeded() -> bool {
let ms = DEADLINE_MS.load(Ordering::SeqCst);
if ms == 0 {
return false;
}
let Some(start) = *lock_through_poison(&START) else {
return false;
};
start.elapsed().as_millis() as u64 >= ms
}
pub fn is_shutdown_requested() -> bool {
SHUTDOWN.load(Ordering::SeqCst)
}
pub fn shutdown_reason() -> ShutdownReason {
match SIGNAL.load(Ordering::SeqCst) {
1 => ShutdownReason::Sigint,
2 => ShutdownReason::Sigterm,
3 => ShutdownReason::Forced,
_ => ShutdownReason::None,
}
}
pub fn shutdown_error() -> Option<crate::error::Error> {
match shutdown_reason() {
ShutdownReason::Forced | ShutdownReason::Sigterm => Some(crate::error::Error::Terminated),
ShutdownReason::Sigint => Some(crate::error::Error::Interrupted),
ShutdownReason::None => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tracked_temp_is_removed() {
let dir = tempfile::tempdir().expect("tempdir");
let file = dir.path().join("leftover");
std::fs::write(&file, b"x").expect("write");
register_temp(&file);
cleanup_temps();
assert!(!file.exists());
}
#[test]
fn released_temp_is_not_tracked() {
let dir = tempfile::tempdir().expect("tempdir");
let file = dir.path().join("kept");
std::fs::write(&file, b"x").expect("write");
register_temp(&file);
release_temp(&file);
cleanup_temps();
assert!(file.exists());
}
#[test]
fn sigterm_maps_to_terminated() {
SIGNAL.store(2, Ordering::SeqCst);
assert_eq!(shutdown_reason(), ShutdownReason::Sigterm);
assert!(matches!(
shutdown_error(),
Some(crate::error::Error::Terminated)
));
SIGNAL.store(0, Ordering::SeqCst);
}
}