use std::collections::BTreeSet;
use std::fs::File;
use std::io::Write;
use std::mem::ManuallyDrop;
use std::os::fd::{AsRawFd, FromRawFd};
use std::process::Child;
use std::sync::mpsc;
use std::thread;
use std::time::{Duration, Instant};
use super::tree::{self, Row, SIGKILL, SIGTERM};
use super::watch::{EXIT_LINE, GRACE};
const SIG_IGN: usize = 1;
const LATE: Duration = Duration::from_secs(20);
unsafe extern "C" {
fn signal(signum: i32, handler: usize) -> usize;
fn dup2(from: i32, to: i32) -> i32;
}
pub fn ignore_sigterm() {
unsafe {
signal(SIGTERM, SIG_IGN);
}
}
pub fn report(nonce: &str, code: u8) {
let _ = writeln!(raw(2), "\n{EXIT_LINE} {nonce} {code}");
if let Ok(null) = std::fs::OpenOptions::new().write(true).open("/dev/null") {
for fd in [1, 2] {
unsafe {
dup2(null.as_raw_fd(), fd);
}
}
}
}
pub fn raw(fd: i32) -> ManuallyDrop<File> {
ManuallyDrop::new(unsafe { File::from_raw_fd(fd) })
}
fn group(rows: &[Row], own: i32) -> BTreeSet<i32> {
let members: Vec<i32> = tree::members(rows, own)
.into_iter()
.filter(|pid| *pid != own)
.collect();
tree::descendants(rows, &members)
}
fn end(
own: i32,
rows: Vec<Row>,
first: BTreeSet<i32>,
last: Option<i32>,
grace: Duration,
done: &mut dyn FnMut() -> bool,
) {
tree::signal_all(&rows, &first, own, last, SIGTERM);
tree::signal(-own, SIGTERM);
let deadline = Instant::now() + grace;
while Instant::now() < deadline {
if done() && !first.iter().any(|pid| tree::exists(*pid)) {
break;
}
thread::sleep(Duration::from_millis(50));
}
let now = tree::table();
let mut left = tree::still(&rows, &now, &first);
left.extend(group(&now, own));
let roots: Vec<i32> = left.iter().copied().collect();
left.extend(tree::descendants(&now, &roots));
tree::signal_all(&now, &left, own, None, SIGKILL);
}
pub fn end_tree(harness: &mut Child, own: i32) {
let pid = harness.id() as i32;
let rows = tree::table();
let mut first = tree::descendants(&rows, &[pid]);
first.extend(group(&rows, own));
end(own, rows, first, Some(pid), GRACE, &mut || {
!matches!(harness.try_wait(), Ok(None))
});
let _ = harness.kill();
let _ = harness.wait();
}
pub fn leftovers(own: i32, closed: &mpsc::Receiver<()>) {
let deadline = Instant::now() + LATE;
let mut rows = tree::table();
while !group(&rows, own).is_empty() && Instant::now() < deadline {
match closed.recv_timeout(Duration::from_millis(200)) {
Err(mpsc::RecvTimeoutError::Timeout) => rows = tree::table(),
Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => break,
}
}
let rows = tree::table();
let left = group(&rows, own);
if !left.is_empty() {
end(own, rows, left, None, Duration::from_secs(1), &mut || true);
}
}