use std::sync::atomic::AtomicPtr;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use hermit::Error;
use hermit::HERMIT_DEADLINE_EXIT;
use nix::sys::signal::SaFlags;
use nix::sys::signal::SigAction;
use nix::sys::signal::SigHandler;
use nix::sys::signal::SigSet;
use nix::sys::signal::Signal;
use nix::sys::signal::sigaction;
pub(super) const RUN_TIMEOUT_UNWIND_GRACE: Duration = Duration::from_secs(10);
pub(super) fn stall_the_unwind_if_asked() {
const STALL_ENV: &str = "HERMIT_INTERNAL_RUN_TIMEOUT_STALL_UNWIND";
if std::env::var_os(STALL_ENV).as_deref() != Some(std::ffi::OsStr::new("1")) {
return;
}
std::thread::sleep(RUN_TIMEOUT_UNWIND_GRACE + Duration::from_secs(5));
}
static RUN_TIMEOUT_MESSAGE: AtomicPtr<u8> = AtomicPtr::new(std::ptr::null_mut());
static RUN_TIMEOUT_MESSAGE_LEN: AtomicUsize = AtomicUsize::new(0);
extern "C" fn run_timeout_fallback_handler(_signal: libc::c_int) {
let len = RUN_TIMEOUT_MESSAGE_LEN.load(Ordering::Acquire);
let message = RUN_TIMEOUT_MESSAGE.load(Ordering::Acquire);
if !message.is_null() && len != 0 {
unsafe {
let flags = libc::fcntl(libc::STDERR_FILENO, libc::F_GETFL);
if flags != -1 {
libc::fcntl(libc::STDERR_FILENO, libc::F_SETFL, flags | libc::O_NONBLOCK);
}
libc::write(libc::STDERR_FILENO, message.cast(), len);
}
}
unsafe { libc::_exit(HERMIT_DEADLINE_EXIT) }
}
pub(super) struct RunTimeoutFallback {
previous_handler: SigAction,
reblock_sigalrm: bool,
}
impl RunTimeoutFallback {
pub(super) fn arm(after: Duration) -> Result<Self, Error> {
let seconds: libc::c_uint = after
.as_secs()
.try_into()
.map_err(|_| Error::msg("--timeout exceeds the platform alarm limit"))?;
let message = Box::leak(
format!(
"HERMIT_RUN_TIMEOUT_FALLBACK: the --timeout unwind did not complete within {} seconds; \
the container was terminated without a clean teardown\n",
RUN_TIMEOUT_UNWIND_GRACE.as_secs()
)
.into_boxed_str(),
);
RUN_TIMEOUT_MESSAGE.store(message.as_mut_ptr(), Ordering::Release);
RUN_TIMEOUT_MESSAGE_LEN.store(message.len(), Ordering::Release);
let action = SigAction::new(
SigHandler::Handler(run_timeout_fallback_handler),
SaFlags::SA_RESETHAND,
SigSet::empty(),
);
let previous_handler = unsafe { sigaction(Signal::SIGALRM, &action) }?;
let mut alarm = SigSet::empty();
alarm.add(Signal::SIGALRM);
let reblock_sigalrm = SigSet::thread_get_mask()
.map(|mask| mask.contains(Signal::SIGALRM))
.unwrap_or(false);
if reblock_sigalrm {
let _ = alarm.thread_unblock();
}
unsafe { libc::alarm(seconds) };
Ok(Self {
previous_handler,
reblock_sigalrm,
})
}
}
impl Drop for RunTimeoutFallback {
fn drop(&mut self) {
unsafe {
libc::alarm(0);
let _ = sigaction(Signal::SIGALRM, &self.previous_handler);
}
if self.reblock_sigalrm {
let mut alarm = SigSet::empty();
alarm.add(Signal::SIGALRM);
let _ = alarm.thread_block();
}
RUN_TIMEOUT_MESSAGE_LEN.store(0, Ordering::Release);
RUN_TIMEOUT_MESSAGE.store(std::ptr::null_mut(), Ordering::Release);
}
}