use super::teardown::{exit, fake, fire_on_block, id, PID};
use crate::child::owned::unreaped::{DropKind, Unreaped};
use crate::elevation::front::TrackedKind;
use crate::error::Error;
use crate::os_process::child::Foreign;
use crate::os_process::fake::{FakeProcess, ReapAnswer};
use crate::os_process::PIDLESS_CHILD;
use crate::test_child::over_fake::unreaped_over as unreaped;
static_assertions::assert_impl_all!(Unreaped: Send, Sync);
fn dropped_when_the_reap_answers(
fake: FakeProcess,
reap: ReapAnswer,
) -> (Vec<(log::Level, String)>, Vec<Option<std::time::Duration>>) {
crate::log_capture::install();
let fake = fake.reaps([ReapAnswer::Running, reap]);
let _fire = fire_on_block(&fake);
let child = unreaped(&fake, Some(id()));
let mark = crate::log_capture::mark();
drop(child);
(
crate::log_capture::records_since_on_current_thread(mark, ""),
crate::wait::block_probe::take(),
)
}
#[skuld::test]
fn wait_blocks_until_the_child_exits_and_returns_its_status() {
crate::log_capture::install();
let fake = fake().reaps([ReapAnswer::Running, ReapAnswer::Exited(exit())]);
let _fire = fire_on_block(&fake);
let child = unreaped(&fake, Some(id()));
let mark = crate::log_capture::mark();
let status = child.wait().expect("the child exits");
assert!(status.success());
assert_eq!(crate::wait::block_probe::take(), [None], "one unbounded block");
assert_eq!(crate::log_capture::records_since_on_current_thread(mark, ""), []);
}
#[skuld::test]
fn a_failed_wait_is_returned_once_and_the_drop_does_not_wait_again() {
crate::log_capture::install();
let fake = fake().reaps([ReapAnswer::Err(std::io::ErrorKind::Other)]);
let child = unreaped(&fake, Some(id()));
let mark = crate::log_capture::mark();
let result = child.wait();
assert!(
matches!(result, Err(Error::Io(ref e)) if e.kind() == std::io::ErrorKind::Other),
"{result:?}"
);
assert_eq!(crate::log_capture::records_since_on_current_thread(mark, ""), []);
}
#[skuld::test]
fn a_wait_on_a_child_reaped_elsewhere_is_an_error_and_does_not_hang() {
let fake = fake().reaps([ReapAnswer::Foreign(Foreign::Gone)]);
let result = unreaped(&fake, Some(id())).wait();
assert!(matches!(result, Err(Error::Io(_))), "{result:?}");
}
#[skuld::test]
fn a_wait_on_a_zombie_launchd_holds_is_an_error_and_warns_once() {
crate::log_capture::install();
let fake = fake().reaps([ReapAnswer::Foreign(Foreign::Orphaned)]);
let child = unreaped(&fake, Some(id()));
let mark = crate::log_capture::mark();
let result = child.wait();
assert!(matches!(result, Err(Error::Io(_))), "{result:?}");
let records = crate::log_capture::records_since_on_current_thread(mark, "");
assert!(
matches!(
records.as_slice(),
[(log::Level::Warn, text)] if text.contains(&PID.to_string()) && text.contains("launchd")
),
"{records:?}"
);
}
#[skuld::test]
fn dropping_waits_for_the_child_and_logs_one_warn_naming_it() {
let (records, blocks) = dropped_when_the_reap_answers(fake(), ReapAnswer::Exited(exit()));
assert_eq!(blocks, [None], "one unbounded block");
assert!(
matches!(records.as_slice(), [(log::Level::Warn, text)] if text.contains(&PID.to_string())),
"{records:?}"
);
}
#[skuld::test]
fn a_drop_that_meets_a_foreign_reap_logs_one_debug_line() {
let (records, _) = dropped_when_the_reap_answers(fake(), ReapAnswer::Foreign(Foreign::Gone));
assert!(
matches!(records.as_slice(), [(log::Level::Debug, text)] if text.contains(&PID.to_string())),
"{records:?}"
);
}
#[skuld::test]
fn a_drop_that_meets_launchd_logs_one_warn_saying_so() {
let (records, _) = dropped_when_the_reap_answers(fake(), ReapAnswer::Foreign(Foreign::Orphaned));
assert!(
matches!(
records.as_slice(),
[(log::Level::Warn, text)] if text.contains(&PID.to_string()) && text.contains("launchd")
),
"{records:?}"
);
}
#[skuld::test]
fn a_drop_whose_wait_fails_logs_one_warn_with_the_failure() {
let (records, _) = dropped_when_the_reap_answers(fake(), ReapAnswer::Err(std::io::ErrorKind::Other));
assert!(
matches!(
records.as_slice(),
[(log::Level::Warn, text)] if text.contains(&PID.to_string()) && text.contains("failed")
),
"{records:?}"
);
}
#[skuld::test]
fn leak_calls_nothing_and_logs_nothing() {
crate::log_capture::install();
let child = unreaped(&fake(), Some(id()));
let mark = crate::log_capture::mark();
child.leak();
assert_eq!(crate::log_capture::records_since_on_current_thread(mark, ""), []);
}
#[skuld::test]
fn a_pidless_child_is_named_without_a_number() {
crate::log_capture::install();
let fake = FakeProcess::new([]).reaps([ReapAnswer::Exited(exit())]);
let child = unreaped(&fake, None);
assert_eq!(child.pid(), None);
let mark = crate::log_capture::mark();
drop(child);
let records = crate::log_capture::records_since_on_current_thread(mark, "");
assert!(
matches!(records.as_slice(), [(log::Level::Warn, text)] if text.contains(PIDLESS_CHILD)),
"{records:?}"
);
}
#[skuld::test]
fn pid_comes_from_the_child_and_id_from_the_spawn() {
let with_id = unreaped(&fake(), Some(id()));
assert_eq!(with_id.pid(), Some(PID));
assert_eq!(with_id.id(), Some(id()));
with_id.leak();
let without_id = unreaped(&fake(), None);
assert_eq!(without_id.pid(), Some(PID));
assert_eq!(without_id.id(), None);
without_id.leak();
}
#[skuld::test]
fn dropping_an_unreaped_while_panicking_gives_the_child_up_without_waiting() {
use std::cell::RefCell;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::rc::Rc;
use super::fixtures::identity_of;
use crate::child::owned::OwnedChild;
use crate::identity::Liveness;
crate::log_capture::install();
let (child, stdin) = crate::test_child::blocker().into_parts();
let blocker_id = identity_of(&child);
let owned = OwnedChild::adopt(child, blocker_id, TrackedKind::Own).unwrap_or_else(|(e, _)| panic!("adopt: {e}"));
let unreaped = Unreaped::new(owned, Some(blocker_id), DropKind::Wait);
let stdin = Rc::new(RefCell::new(Some(stdin)));
crate::wait::block_probe::take();
let _end = crate::wait::block_probe::on_blocking({
let stdin = Rc::clone(&stdin);
move || drop(stdin.borrow_mut().take())
});
let mark = crate::log_capture::mark();
let outcome = catch_unwind(AssertUnwindSafe(move || {
let _held = unreaped;
panic!("the thread panics while it holds the Unreaped");
}));
assert!(outcome.is_err());
assert_eq!(crate::wait::block_probe::take(), [], "the drop did not block");
let records = crate::log_capture::records_since_on_current_thread(mark, "");
assert!(
matches!(
records.as_slice(),
[(log::Level::Warn, text)]
if text.contains(&blocker_id.pid().to_string()) && text.contains("panicking")
),
"{records:?}"
);
assert_eq!(blocker_id.is_alive(), Liveness::Alive, "the child was given up running");
drop(stdin.borrow_mut().take());
}
#[skuld::test]
fn dropping_an_unreaped_blocker_waits_for_it_and_reaps_it() {
use super::fixtures::identity_of;
use crate::child::owned::OwnedChild;
let (child, stdin) = crate::test_child::blocker().into_parts();
let blocker_id = identity_of(&child);
let owned = OwnedChild::adopt(child, blocker_id, TrackedKind::Own).unwrap_or_else(|(e, _)| panic!("adopt: {e}"));
let unreaped = Unreaped::new(owned, Some(blocker_id), DropKind::Wait);
crate::wait::block_probe::take();
let _end = crate::wait::block_probe::on_blocking(move || drop(stdin));
drop(unreaped);
#[cfg(unix)]
assert_eq!(
blocker_id.exists(),
crate::identity::Existence::Gone,
"the drop reaped the child"
);
#[cfg(windows)]
assert_eq!(
blocker_id.is_alive(),
crate::identity::Liveness::Dead,
"the drop waited for the child"
);
}
#[cfg(feature = "tokio")]
fn drop_records(mark: usize) -> Vec<(log::Level, String)> {
crate::log_capture::records_since_on_current_thread(mark, "")
.into_iter()
.filter(|(_, line)| !line.starts_with("second reap of pid"))
.collect()
}
#[cfg(feature = "tokio")]
#[skuld::test]
async fn wait_async_returns_the_status_wait_would() {
use super::wait_async::exits_three_on_eof;
use crate::tokio::drive::drive_tests::poll_once;
crate::log_capture::install();
let (owned, stdin) = exits_three_on_eof();
let child = Unreaped::new(owned, None, DropKind::Wait);
let mark = crate::log_capture::mark();
let mut wait = std::pin::pin!(child.wait_async());
assert!(poll_once(wait.as_mut()).is_pending(), "a running child is waited for");
drop(stdin);
assert_eq!(wait.await.expect("the child exits").code(), Some(3));
assert_eq!(drop_records(mark), [], "the settled value's drop is silent");
}
#[cfg(feature = "tokio")]
#[skuld::test]
async fn wait_async_on_a_child_reaped_elsewhere_is_the_error_wait_gives() {
crate::log_capture::install();
let gone = || fake().reaps([ReapAnswer::Foreign(Foreign::Gone)]);
let sync = unreaped(&gone(), Some(id())).wait().expect_err("reaped elsewhere");
let fake = gone();
let mark = crate::log_capture::mark();
let asynchronous = unreaped(&fake, Some(id()))
.wait_async()
.await
.expect_err("reaped elsewhere");
assert_eq!(
crate::log_capture::records_since_on_current_thread(mark, ""),
[],
"the settled value's drop is silent"
);
assert_eq!(fake.looks(), 1, "the drop made no further look");
let (Error::Io(sync), Error::Io(asynchronous)) = (&sync, &asynchronous) else {
panic!("{sync:?} / {asynchronous:?}");
};
assert_eq!(asynchronous.kind(), sync.kind());
assert_eq!(asynchronous.raw_os_error(), sync.raw_os_error());
}
#[cfg(feature = "tokio")]
#[skuld::test]
async fn a_cancelled_wait_async_lets_a_real_child_go_without_blocking() {
use crate::child::owned::OwnedChild;
use crate::os_process::child::adopted_blocker;
use crate::signal::Sig;
use crate::tokio::drive::drive_tests::poll_once;
crate::log_capture::install();
let (os, blocker_id, stdin) = adopted_blocker();
let fake = FakeProcess::over(os);
let child = Unreaped::new(
OwnedChild::new(Box::new(fake.clone()), TrackedKind::Own),
Some(blocker_id),
DropKind::Wait,
);
let mark = crate::log_capture::mark();
{
let mut wait = std::pin::pin!(child.wait_async());
assert!(poll_once(wait.as_mut()).is_pending(), "a running child is waited for");
assert_eq!(fake.looks(), 1);
}
assert_eq!(fake.signal_calls(), [Sig::Kill], "one kill");
assert_eq!(fake.looks(), 2, "one look");
let records = drop_records(mark);
let [(log::Level::Warn, said)] = records.as_slice() else {
panic!("the drop warns once: {records:?}");
};
assert!(said.contains(&blocker_id.pid().to_string()), "{said}");
#[cfg(unix)]
{
let pid = blocker_id.pid() as libc::pid_t;
let mut status = 0;
match unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) } {
0 => {
assert_eq!(unsafe { libc::waitpid(pid, &mut status, 0) }, pid);
}
-1 => assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::ECHILD)),
reaped => assert_eq!(reaped, pid),
}
}
drop(stdin);
}
#[skuld::test]
fn the_let_go_line_is_pinned_for_every_kill_and_look() {
use crate::child::lifecycle::Settlement;
use crate::child::owned::teardown::{LEAVING_RUNNING, LEFT};
use crate::child::owned::unreaped::let_go_line;
use crate::child::owned::ChildWaitOutcome;
use crate::signal::Sent;
use log::Level::{Debug, Warn};
type Kill = Option<Result<Sent, Error>>;
type Look = Result<ChildWaitOutcome, Error>;
type KillCase<'a> = (
fn() -> Kill,
&'a str,
&'static [&'static str],
Vec<&'static str>,
&'static [&'static str],
);
type LookCase<'a> = (fn() -> Look, log::Level, Vec<&'a str>);
let status = std::process::ExitStatus::default().to_string();
let denied = format!("could not be terminated ({})", crate::error::io_said("denied"));
let boom = format!("the wait failed: {}", crate::error::io_said("boom"));
let kills: [KillCase<'_>; 5] = [
(|| None, "", &["kill"], vec![LEAVING_RUNNING], &["kill"]),
(
|| Some(Ok(Sent::Delivered)),
"(killed it)",
&["refused", "terminated"],
vec!["it had not exited yet", LEFT],
&["refused", "terminated", LEAVING_RUNNING],
),
(
|| Some(Ok(Sent::Gone)),
"its kill found nothing to signal",
&["killed it"],
vec!["the look saw no exit yet", LEFT],
&["killed it", "running", LEAVING_RUNNING],
),
(
|| Some(Ok(Sent::Unverified)),
"its kill was not sent: the child could not be verified",
&["killed it"],
vec![LEAVING_RUNNING],
&["killed it"],
),
(
|| Some(Err(Error::Io(std::io::Error::other("denied")))),
denied.as_str(),
&["killed it"],
vec![LEAVING_RUNNING],
&["killed it"],
),
];
let looks: [LookCase; 4] = [
(
|| Ok(ChildWaitOutcome::Exited(exit())),
Warn,
vec!["reaped it", &status],
),
(
|| Ok(ChildWaitOutcome::Foreign(Foreign::Gone)),
Debug,
vec!["reaped by someone else"],
),
(
|| Ok(ChildWaitOutcome::Foreign(Foreign::Orphaned)),
Warn,
vec!["launchd"],
),
(
|| Err(Error::Io(std::io::Error::other("boom"))),
Warn,
vec![boom.as_str(), LEFT],
),
];
let running = || -> Look { Ok(ChildWaitOutcome::DeadlinePassed) };
let mut cases = Vec::new();
for (kill, said, never, running_says, running_never) in &kills {
let said: Vec<&str> = (!said.is_empty()).then_some(*said).into_iter().collect();
for (look, level, says) in &looks {
let level = if matches!(kill(), Some(Err(_))) { Warn } else { *level };
let says: Vec<&str> = [said.clone(), says.clone()].concat();
cases.push((kill(), look(), level, says, never.to_vec()));
}
let says: Vec<&str> = [said, running_says.clone()].concat();
cases.push((kill(), running(), Warn, says, running_never.to_vec()));
}
for (kill, look, level, says, never) in cases {
let look = Settlement::new(look, false);
let (got, line) = let_go_line(Some(PID), kill.as_ref(), &look);
let case = format!("{kill:?} / {look:?}: {line}");
assert_eq!(got, level, "{case}");
assert!(line.contains("child 4242") && !line.contains('\n'), "{case}");
for phrase in &says {
assert!(line.contains(phrase), "missing {phrase:?}: {case}");
}
for phrase in never {
assert!(!line.contains(phrase), "claims {phrase:?}: {case}");
}
assert!(line.matches("unreaped").count() <= 1, "{case}");
let ours = matches!(
look.fate(None),
crate::error::ChildFate::Running { .. } | crate::error::ChildFate::Unknown
);
if cfg!(windows) && ours {
assert!(!line.contains("reap"), "{case}");
}
}
}
#[cfg(feature = "tokio")]
fn let_go(fake: &FakeProcess, front: bool, polls: usize) -> Vec<(log::Level, String)> {
use crate::child::owned::OwnedChild;
use crate::tokio::drive::drive_tests::poll_once;
crate::log_capture::install();
let kind = if front {
TrackedKind::Front(crate::elevation::front::Front::Sudo)
} else {
TrackedKind::Own
};
let child = Unreaped::new(
OwnedChild::new(Box::new(fake.clone()), kind),
Some(id()),
DropKind::Wait,
);
let mark = crate::log_capture::mark();
{
let mut wait = std::pin::pin!(child.wait_async());
for _ in 0..polls {
assert!(poll_once(wait.as_mut()).is_pending(), "a running child is waited for");
}
}
crate::log_capture::records_since_on_current_thread(mark, "")
}
#[cfg(feature = "tokio")]
#[skuld::test]
async fn a_polled_then_cancelled_front_is_sent_nothing_and_looked_at_once_more() {
let fake = fake().reaps([ReapAnswer::Running, ReapAnswer::Running]);
let records = let_go(&fake, true, 1);
assert_eq!(fake.signal_calls(), [], "a front is sent nothing");
assert_eq!(fake.looks(), 2, "the poll's look, and the drop's one");
let [(log::Level::Warn, said)] = records.as_slice() else {
panic!("one warn: {records:?}");
};
assert!(
said.contains("child 4242") && said.contains("leaving it running"),
"{said}"
);
}
#[cfg(feature = "tokio")]
#[skuld::test]
async fn a_let_go_of_a_child_someone_else_reaped_logs_one_debug_line() {
use crate::signal::{Sent, Sig};
let fake = fake()
.signals([Ok(Sent::Gone)])
.reaps([ReapAnswer::Foreign(Foreign::Gone)]);
let records = let_go(&fake, false, 0);
assert_eq!(fake.signal_calls(), [Sig::Kill]);
assert_eq!(fake.looks(), 1, "one look, which does not wait");
assert!(
matches!(
records.as_slice(),
[(log::Level::Debug, said)] if said.contains("child 4242") && said.contains("reaped by someone else")
),
"{records:?}"
);
}