use std::time::Duration;
use tokio::task::JoinHandle;
use tracing::{debug, info, warn};
use super::engine_command::EngineCommand;
use super::engine_command::EngineCommandSender;
use crate::request::request_group::HaltReason;
const PROCESS_POLL_INTERVAL: Duration = Duration::from_secs(1);
fn send_halt(tx: &EngineCommandSender, force: bool, reason: HaltReason) -> bool {
let cmd = if force {
EngineCommand::ForceHaltAll { reason }
} else {
EngineCommand::HaltAll { reason }
};
tx.send(cmd).is_ok()
}
pub fn spawn_timed_halt<T: Into<EngineCommandSender>>(
cmd_tx: T,
duration: Duration,
force: bool,
) -> JoinHandle<()> {
let cmd_tx = cmd_tx.into();
tokio::spawn(async move {
debug!(?duration, force, "Timed halt watcher armed");
tokio::select! {
_ = tokio::time::sleep(duration) => {}
_ = cmd_tx.closed() => {
debug!("Timed halt watcher exiting: engine channel closed");
return;
}
}
info!(
seconds = duration.as_secs(),
force, "Time has passed, commencing shutdown"
);
if !send_halt(&cmd_tx, force, HaltReason::ShutdownSignal) {
warn!("Timed halt fired but the engine channel was already closed");
}
})
}
pub fn spawn_process_watch<T: Into<EngineCommandSender>>(
cmd_tx: T,
pid: u32,
force: bool,
) -> JoinHandle<()> {
let cmd_tx = cmd_tx.into();
tokio::spawn(async move {
debug!(pid, force, "Process watcher armed");
loop {
if !is_process_alive(pid) {
info!(pid, force, "Watched process is gone, commencing shutdown");
if !send_halt(&cmd_tx, force, HaltReason::ShutdownSignal) {
warn!("Process watch fired but the engine channel was already closed");
}
return;
}
tokio::select! {
_ = tokio::time::sleep(PROCESS_POLL_INTERVAL) => {}
_ = cmd_tx.closed() => {
debug!(pid, "Process watcher exiting: engine channel closed");
return;
}
}
}
})
}
pub fn is_process_alive(pid: u32) -> bool {
#[cfg(windows)]
{
use windows_sys::Win32::Foundation::{CloseHandle, WAIT_TIMEOUT};
use windows_sys::Win32::System::Threading::{OpenProcess, PROCESS_SYNCHRONIZE};
unsafe {
let handle = OpenProcess(PROCESS_SYNCHRONIZE, 0, pid);
if handle.is_null() {
return false;
}
let wait = windows_sys::Win32::System::Threading::WaitForSingleObject(handle, 0);
CloseHandle(handle);
wait == WAIT_TIMEOUT
}
}
#[cfg(unix)]
{
if pid == 0 || pid > libc::pid_t::MAX as u32 {
return false;
}
let rc = unsafe { libc::kill(pid as libc::pid_t, 0) };
if rc == 0 {
return true;
}
std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}
#[cfg(not(any(windows, unix)))]
{
let _ = pid;
true
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::sync::mpsc;
#[test]
fn current_process_is_alive() {
assert!(is_process_alive(std::process::id()));
}
#[test]
fn implausible_pid_is_not_alive() {
assert!(!is_process_alive(0));
assert!(!is_process_alive(u32::MAX));
}
#[tokio::test(start_paused = true)]
async fn timed_halt_sends_graceful_halt_after_duration() {
let (tx, mut rx) = mpsc::unbounded_channel();
let handle = spawn_timed_halt(tx, Duration::from_secs(30), false);
assert!(rx.try_recv().is_err());
tokio::time::advance(Duration::from_secs(31)).await;
handle.await.unwrap();
match rx.try_recv() {
Ok(EngineCommand::HaltAll { reason }) => {
assert_eq!(reason, HaltReason::ShutdownSignal);
}
other => panic!("expected HaltAll, got {:?}", other.is_ok()),
}
}
#[tokio::test(start_paused = true)]
async fn timed_halt_honours_force_flag() {
let (tx, mut rx) = mpsc::unbounded_channel();
let handle = spawn_timed_halt(tx, Duration::from_secs(5), true);
tokio::time::advance(Duration::from_secs(6)).await;
handle.await.unwrap();
assert!(matches!(
rx.try_recv(),
Ok(EngineCommand::ForceHaltAll { .. })
));
}
#[tokio::test(start_paused = true)]
async fn timed_halt_exits_when_engine_channel_closes() {
let (tx, rx) = mpsc::unbounded_channel();
let handle = spawn_timed_halt(tx, Duration::from_secs(3600), false);
drop(rx);
handle.await.unwrap();
}
#[tokio::test]
async fn process_watch_halts_immediately_for_dead_pid() {
let (tx, mut rx) = mpsc::unbounded_channel();
let handle = spawn_process_watch(tx, u32::MAX, false);
handle.await.unwrap();
assert!(matches!(rx.try_recv(), Ok(EngineCommand::HaltAll { .. })));
}
#[tokio::test(start_paused = true)]
async fn process_watch_keeps_running_while_process_lives() {
let (tx, mut rx) = mpsc::unbounded_channel();
let handle = spawn_process_watch(tx, std::process::id(), false);
tokio::time::advance(Duration::from_secs(10)).await;
tokio::task::yield_now().await;
assert!(rx.try_recv().is_err(), "must not halt while alive");
handle.abort();
}
#[tokio::test(start_paused = true)]
async fn process_watch_exits_when_engine_channel_closes() {
let (tx, rx) = mpsc::unbounded_channel();
let handle = spawn_process_watch(tx, std::process::id(), false);
tokio::task::yield_now().await;
drop(rx);
handle.await.unwrap();
}
}