use anyhow::{bail, Result};
pub(crate) const CANCELLED: &str = "cancelled";
pub(crate) struct Guard(());
pub(crate) fn catch() -> Guard {
#[cfg(unix)]
imp::acquire();
Guard(())
}
impl Drop for Guard {
fn drop(&mut self) {
#[cfg(unix)]
imp::release();
}
}
pub(crate) fn requested() -> bool {
#[cfg(unix)]
{
imp::requested()
}
#[cfg(not(unix))]
{
false
}
}
pub(crate) fn check() -> Result<()> {
if requested() {
bail!(CANCELLED);
}
Ok(())
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum NotCancelled {
Unknown,
Done,
Signal(String),
}
pub(crate) fn cancel_instance(
state: &crate::state::State,
instance: &str,
signal: impl FnOnce(u32) -> std::result::Result<(), String>,
) -> std::result::Result<u32, NotCancelled> {
let info = state.instances.get(instance).ok_or(NotCancelled::Unknown)?;
match (&info.progress, info.phase_view()) {
(Some(p), Some(crate::state::PhaseView::InFlight(_))) => {
signal(p.pid).map(|()| p.pid).map_err(NotCancelled::Signal)
}
_ => Err(NotCancelled::Done),
}
}
#[cfg(unix)]
pub(crate) fn interrupt(pid: u32) -> std::result::Result<(), String> {
let pid = libc::pid_t::try_from(pid).ok().filter(|&p| p > 1).ok_or(format!("bad pid {pid}"))?;
if unsafe { libc::kill(-pid, libc::SIGINT) } == 0 || unsafe { libc::kill(pid, libc::SIGINT) } == 0 {
return Ok(());
}
Err(format!("SIGINT to pid {pid}: {}", std::io::Error::last_os_error()))
}
#[cfg(not(unix))]
pub(crate) fn interrupt(_pid: u32) -> std::result::Result<(), String> {
Err("not supported on this platform".into())
}
#[cfg(unix)]
mod imp {
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use libc::c_int;
const CANCEL: [c_int; 2] = [libc::SIGINT, libc::SIGTERM];
static RAISED: [AtomicBool; 65] = [const { AtomicBool::new(false) }; 65];
static INSTALLED: Mutex<(usize, Vec<(c_int, libc::sigaction)>)> = Mutex::new((0, Vec::new()));
pub(super) fn requested() -> bool {
CANCEL.iter().any(|&sig| raised(sig))
}
fn raised(sig: c_int) -> bool {
RAISED.get(sig as usize).is_some_and(|f| f.load(Ordering::SeqCst))
}
fn clear(sig: c_int) {
if let Some(f) = RAISED.get(sig as usize) {
f.store(false, Ordering::SeqCst);
}
}
pub(super) fn acquire() {
let mut installed = INSTALLED.lock().unwrap_or_else(|e| e.into_inner());
if installed.0 == 0 {
for sig in CANCEL {
clear(sig);
match catch(sig) {
Ok(prev) => installed.1.push((sig, prev)),
Err(e) => eprintln!("warning: cannot catch signal {sig}; Ctrl-C won't roll back: {e}"),
}
}
}
installed.0 += 1;
}
pub(super) fn release() {
let mut installed = INSTALLED.lock().unwrap_or_else(|e| e.into_inner());
installed.0 = installed.0.saturating_sub(1);
if installed.0 > 0 {
return;
}
let mut terminate = false;
for (sig, prev) in installed.1.drain(..) {
terminate |= sig == libc::SIGTERM && raised(sig) && prev.sa_sigaction == libc::SIG_DFL;
restore(sig, &prev);
clear(sig);
}
drop(installed);
if terminate {
unsafe { libc::raise(libc::SIGTERM) };
}
}
extern "C" fn on_signal(sig: c_int) {
if let Some(f) = RAISED.get(sig as usize) {
f.store(true, Ordering::SeqCst);
}
if CANCEL.contains(&sig) {
for other in CANCEL {
unsafe { libc::signal(other, libc::SIG_DFL) };
}
}
}
pub(super) fn catch(sig: c_int) -> std::io::Result<libc::sigaction> {
unsafe {
let mut action: libc::sigaction = std::mem::zeroed();
action.sa_sigaction = on_signal as extern "C" fn(c_int) as libc::sighandler_t;
action.sa_flags = libc::SA_RESETHAND | libc::SA_RESTART;
libc::sigemptyset(&mut action.sa_mask);
let mut prev: libc::sigaction = std::mem::zeroed();
if libc::sigaction(sig, &action, &mut prev) != 0 {
return Err(std::io::Error::last_os_error());
}
Ok(prev)
}
}
pub(super) fn restore(sig: c_int, prev: &libc::sigaction) {
unsafe { libc::sigaction(sig, prev, std::ptr::null_mut()) };
}
#[cfg(test)]
mod tests {
use super::*;
static PREVIOUS_RAN: AtomicBool = AtomicBool::new(false);
extern "C" fn previous(_: c_int) {
PREVIOUS_RAN.store(true, Ordering::SeqCst);
}
fn current(sig: c_int) -> libc::sighandler_t {
unsafe {
let mut cur: libc::sigaction = std::mem::zeroed();
libc::sigaction(sig, std::ptr::null(), &mut cur);
cur.sa_sigaction
}
}
#[test]
fn handler_flags_once_then_the_previous_disposition_comes_back() {
let sig = libc::SIGUSR2;
let previous = previous as extern "C" fn(c_int) as libc::sighandler_t;
let original = unsafe {
let mut action: libc::sigaction = std::mem::zeroed();
action.sa_sigaction = previous;
libc::sigemptyset(&mut action.sa_mask);
let mut original: libc::sigaction = std::mem::zeroed();
assert_eq!(libc::sigaction(sig, &action, &mut original), 0);
original
};
let replaced = catch(sig).unwrap();
assert_eq!(replaced.sa_sigaction, previous);
assert!(!raised(sig));
unsafe { libc::raise(sig) };
assert!(raised(sig));
assert!(!PREVIOUS_RAN.load(Ordering::SeqCst));
assert_eq!(current(sig), libc::SIG_DFL);
restore(sig, &replaced);
clear(sig);
assert_eq!(current(sig), previous);
unsafe { libc::raise(sig) };
assert!(PREVIOUS_RAN.load(Ordering::SeqCst));
assert!(!raised(sig));
restore(sig, &original);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn state(phase: &str, pid: u32) -> crate::state::State {
toml::from_str(&format!(
"[instance.w]\nsandbox = \"web\"\ncontainer = \"devsandbox-w\"\nfolder = \"/w\"\nworkspace = \"/w\"\n\
created_unix = 1\n[instance.w.progress]\nphase = \"{phase}\"\npid = {pid}\n"
))
.unwrap()
}
#[test]
fn cancel_signals_only_an_in_flight_instance() {
let me = std::process::id();
let mut sent = Vec::new();
assert_eq!(cancel_instance(&state("building", me), "w", |p| Ok(sent.push(p))), Ok(me));
assert_eq!(sent, [me]);
let refuse = |_| -> std::result::Result<(), String> { panic!("signalled") };
assert_eq!(cancel_instance(&state("building", me), "nope", refuse), Err(NotCancelled::Unknown));
assert_eq!(cancel_instance(&state("failed", me), "w", refuse), Err(NotCancelled::Done));
assert_eq!(cancel_instance(&state("building", 999_999_999), "w", refuse), Err(NotCancelled::Done));
let failing = |_| Err("EPERM".to_string());
assert_eq!(cancel_instance(&state("creating", me), "w", failing), Err(NotCancelled::Signal("EPERM".into())));
}
}