use std::net::TcpStream;
use std::time::Duration;
use super::fault as term_fault;
use crate::containment::Containment;
use crate::error::Error;
use crate::stop::proxy::protocol::{CtrlEvent, ProxyAnswer};
use crate::stop::proxy::proxy_tests::Fixture;
use crate::test_child::ctrl_break::{
self, assert_acked, assert_in_our_console, assert_proxy_answered, kill_release_reap, Grandchild, Handler,
STATUS_CONTROL_C_EXIT,
};
use crate::StopTarget;
fn spawn_root(handler: Handler, mode: crate::ContainMode) -> (crate::Child, TcpStream) {
spawn_root_configured(handler, mode, |_| {})
}
fn spawn_root_configured(
handler: Handler,
mode: crate::ContainMode,
configure: impl FnOnce(&mut crate::Command),
) -> (crate::Child, TcpStream) {
let (child, sock, _) = spawn(handler, None, mode, configure);
(child, sock)
}
fn spawn_tree(root: Handler, grandchild: Handler, mode: crate::ContainMode) -> (crate::Child, TcpStream, Grandchild) {
let (child, sock, grand) = spawn(root, Some(grandchild), mode, |_| {});
(child, sock, grand.expect("a grandchild was asked for"))
}
fn spawn(
handler: Handler,
grandchild: Option<Handler>,
mode: crate::ContainMode,
configure: impl FnOnce(&mut crate::Command),
) -> (crate::Child, TcpStream, Option<Grandchild>) {
ctrl_break::spawn_member(handler, grandchild, mode, configure)
}
#[skuld::test]
fn child_terminate_delivers_ctrl_break_to_a_contained_root() {
let _warns = crate::log_capture::warn_watch();
let (child, mut sock) = spawn_root(Handler::Ack, crate::ContainMode::Strongest);
assert!(StopTarget::from(&child).leads_group_on_our_console());
assert_in_our_console(child.pid(), "the root");
child.terminate().expect("terminate a console-group child");
ctrl_break::assert_break_sent_to(child.pid());
assert_acked(&mut sock, "the root");
assert_eq!(
child.is_alive(),
crate::identity::Liveness::Alive,
"the root handles the break and keeps running"
);
kill_release_reap(&child, sock, false);
}
#[skuld::test]
fn a_plain_contained_root_really_receives_the_break() {
let (child, mut sock) = spawn_root(Handler::Ack, crate::ContainMode::Strongest);
assert_eq!(child.containment(), Containment::JobObject);
assert!(StopTarget::from(&child).leads_group_on_our_console());
assert_in_our_console(child.pid(), "the root");
child.terminate_tree().expect("terminate_tree on a contained root");
ctrl_break::assert_break_sent_to(child.pid());
assert_acked(&mut sock, "the root");
kill_release_reap(&child, sock, true);
}
#[skuld::test]
fn an_uncontained_child_given_a_group_is_stopped_directly() {
let (child, mut sock) = ctrl_break::spawn_uncontained_member(Handler::Ack, |cmd| _ = cmd.new_process_group(true));
assert_eq!(child.containment(), Containment::None);
assert!(StopTarget::from(&child).leads_group_on_our_console());
assert_in_our_console(child.pid(), "the child");
child.terminate().expect("terminate a child created in a group");
ctrl_break::assert_break_sent_to(child.pid());
assert_acked(&mut sock, "the child");
kill_release_reap(&child, sock, false);
}
#[skuld::test]
fn child_graceful_shutdown_exits_via_ctrl_break_on_windows() {
let _warns = crate::log_capture::warn_watch();
let (child, _sock) = spawn_root(Handler::Default, crate::ContainMode::Strongest);
let pid = child.pid();
assert_in_our_console(pid, "the child");
let check = term_fault::at_checked(term_fault::HookPoint::AfterTerminate, move || {
ctrl_break::assert_break_sent_to(pid)
});
let status = child
.graceful_shutdown(Duration::from_secs(30))
.expect("graceful_shutdown on a console-group child");
check.assert_fired();
assert_eq!(
status.code(),
Some(STATUS_CONTROL_C_EXIT),
"the child must die to the console event, got {status:?}"
);
}
#[skuld::test]
fn child_graceful_shutdown_signals_the_group_but_only_kills_the_child() {
let _warns = crate::log_capture::warn_watch();
let (child, root_sock, mut grand) = spawn_tree(Handler::Ignore, Handler::Ack, crate::ContainMode::Strongest);
assert_in_our_console(child.pid(), "the root");
let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, root_sock);
let status = child
.graceful_shutdown(Duration::ZERO)
.expect("graceful_shutdown on a console-group root");
assert_eq!(
status.code(),
Some(1),
"the root ignores the break, so only the escalation can have ended it, got {status:?}"
);
assert_eq!(
child.is_alive(),
crate::identity::Liveness::Dead,
"the escalation really ended the root"
);
ctrl_break::assert_break_sent_to(child.pid());
assert_acked(&mut grand.sock, "the grandchild");
assert_eq!(
child.wait_tree_timeout(Duration::ZERO).expect("drain verdict"),
crate::containment::TreeDrain::MembersRemain,
"the escalation must not have reached the group"
);
child.kill_tree().expect("kill_tree");
let Grandchild { sock, exit } = grand;
drop(sock);
assert_eq!(exit.wait_for_exit_code(), 1, "kill_tree must kill the grandchild");
}
#[skuld::test]
fn windows_terminate_tree_reaps_the_grandchild() {
let (child, _root_sock, grand) = spawn_tree(Handler::Default, Handler::Default, crate::ContainMode::Strongest);
assert_eq!(child.containment(), Containment::JobObject);
assert_in_our_console(child.pid(), "the root");
child.terminate_tree().expect("terminate_tree");
ctrl_break::assert_break_sent_to(child.pid());
assert_eq!(
grand.exit.wait_for_exit_code(),
STATUS_CONTROL_C_EXIT,
"the grandchild must die to the break"
);
let status = child.wait().expect("reap the root");
assert_eq!(
status.code(),
Some(STATUS_CONTROL_C_EXIT),
"the root must die to the break"
);
}
#[skuld::test]
fn child_graceful_shutdown_tree_tears_down_tree_on_windows() {
let _warns = crate::log_capture::warn_watch();
let (child, _root_sock, grand) = spawn_tree(Handler::Default, Handler::Default, crate::ContainMode::Strongest);
assert_eq!(child.containment(), Containment::JobObject);
let pid = child.pid();
assert_in_our_console(pid, "the root");
let check = term_fault::at_checked(term_fault::HookPoint::AfterTerminate, move || {
ctrl_break::assert_break_sent_to(pid)
});
let status = child
.graceful_shutdown_tree(Duration::from_secs(30))
.expect("graceful_shutdown_tree on a console-group root");
check.assert_fired();
assert_eq!(
status.code(),
Some(STATUS_CONTROL_C_EXIT),
"the root must die to the break, got {status:?}"
);
assert_eq!(
grand.exit.wait_for_exit_code(),
STATUS_CONTROL_C_EXIT,
"the grandchild must die to the break"
);
}
#[skuld::test]
fn treewalk_terminate_tree_reaps_the_grandchild() {
let (child, _root_sock, grand) = spawn_tree(Handler::Default, Handler::Default, crate::ContainMode::TreeWalk);
assert_eq!(child.containment(), Containment::TreeWalk);
assert_in_our_console(child.pid(), "the root");
child.terminate_tree().expect("terminate_tree");
ctrl_break::assert_break_sent_to(child.pid());
assert_eq!(
grand.exit.wait_for_exit_code(),
STATUS_CONTROL_C_EXIT,
"the grandchild must die to the break"
);
let status = child.wait().expect("reap the root");
assert_eq!(
status.code(),
Some(STATUS_CONTROL_C_EXIT),
"the root must die to the break"
);
}
#[skuld::test]
fn graceful_shutdown_tree_with_no_grace_sends_its_break_and_escalates() {
let (child, sock) = spawn_root(Handler::Ack, crate::ContainMode::Strongest);
let pid = child.pid();
let check = term_fault::at_checked(term_fault::HookPoint::AfterTerminate, move || {
ctrl_break::assert_break_sent_to(pid)
});
let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, sock);
let status = child
.graceful_shutdown_tree(Duration::ZERO)
.expect("graceful_shutdown_tree");
check.assert_fired();
assert_eq!(
status.code(),
Some(1),
"the escalation's kill ends the root, got {status:?}"
);
assert_eq!(
child.is_alive(),
crate::identity::Liveness::Dead,
"a successful graceful_shutdown_tree must leave nothing alive"
);
}
#[skuld::test]
fn graceful_shutdown_with_no_grace_sends_its_break_and_escalates() {
let (child, sock) = spawn_root(Handler::Ack, crate::ContainMode::Strongest);
let pid = child.pid();
let check = term_fault::at_checked(term_fault::HookPoint::AfterTerminate, move || {
ctrl_break::assert_break_sent_to(pid)
});
let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, sock);
let status = child.graceful_shutdown(Duration::ZERO).expect("graceful_shutdown");
check.assert_fired();
assert_eq!(status.code(), Some(1), "the escalation's kill, got {status:?}");
assert_eq!(child.is_alive(), crate::identity::Liveness::Dead);
child.kill().expect("killing a dead child is Ok");
}
#[skuld::test]
fn graceful_shutdown_tree_sweep_is_load_bearing_on_windows() {
let _warns = crate::log_capture::warn_watch();
let (child, root_sock, grand) = spawn_tree(Handler::Ignore, Handler::Ignore, crate::ContainMode::Strongest);
assert_in_our_console(child.pid(), "the root");
let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, root_sock);
let status = child.graceful_shutdown_tree(Duration::ZERO).expect("tree escalates");
assert_eq!(status.code(), Some(1), "the sweep ends the root, got {status:?}");
assert_eq!(
child.is_alive(),
crate::identity::Liveness::Dead,
"the sweep really ended the root"
);
let Grandchild { sock, exit } = grand;
drop(sock);
assert_eq!(exit.wait_for_exit_code(), 1, "the sweep must kill the grandchild");
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum Call {
Terminate,
TerminateTree,
GracefulShutdown,
GracefulShutdownTree,
}
pub(crate) const CALLS: [Call; 4] = [
Call::Terminate,
Call::TerminateTree,
Call::GracefulShutdown,
Call::GracefulShutdownTree,
];
impl Call {
pub(crate) fn run(self, child: &crate::Child, grace: Duration) -> Result<Option<std::process::ExitStatus>, Error> {
match self {
Call::Terminate => child.terminate().map(|()| None),
Call::TerminateTree => child.terminate_tree().map(|()| None),
Call::GracefulShutdown => child.graceful_shutdown(grace).map(Some),
Call::GracefulShutdownTree => child.graceful_shutdown_tree(grace).map(Some),
}
}
pub(crate) fn escalates(self) -> bool {
matches!(self, Call::GracefulShutdown | Call::GracefulShutdownTree)
}
}
fn root_stopping_through(
fixture: &Fixture,
mode: crate::ContainMode,
configure: impl FnOnce(&mut crate::Command),
) -> (crate::Child, TcpStream) {
spawn_root_configured(Handler::Ignore, mode, |cmd| {
cmd.ctrl_proxy(fixture.setting());
configure(cmd);
})
}
fn unsupported_detail(err: &Error) -> &str {
match err {
Error::Unsupported { detail, .. } => detail,
other => panic!("expected Unsupported, got {other:?}"),
}
}
#[skuld::test]
fn the_default_asks_the_proxy_for_a_no_window_contained_root() {
for (mode, expected) in [
(crate::ContainMode::Strongest, Containment::JobObject),
(crate::ContainMode::TreeWalk, Containment::TreeWalk),
] {
for call in CALLS {
let fixture = Fixture::answering(ProxyAnswer::Sent.code());
let (child, sock) = root_stopping_through(&fixture, mode, |cmd| _ = cmd.no_window());
assert_own_console_route(&child, expected);
if call.escalates() {
let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, sock);
let status = call
.run(&child, Duration::ZERO)
.unwrap_or_else(|e| panic!("{mode:?} {call:?}: {e:?}"))
.expect("a graceful call answers a status");
assert_proxy_answered(child.pid(), CtrlEvent::CtrlBreak, ProxyAnswer::Sent);
assert_eq!(
status.code(),
Some(1),
"{mode:?} {call:?}: the escalation's kill: {status:?}"
);
} else {
call.run(&child, Duration::ZERO)
.unwrap_or_else(|e| panic!("{mode:?} {call:?}: {e:?}"));
assert_proxy_answered(child.pid(), CtrlEvent::CtrlBreak, ProxyAnswer::Sent);
kill_release_reap(&child, sock, false);
}
}
}
}
#[skuld::test]
fn the_default_asks_the_proxy_for_an_uncontained_no_window_child() {
let fixture = Fixture::answering(ProxyAnswer::Sent.code());
let (child, sock) = ctrl_break::spawn_uncontained_member(Handler::Ignore, |cmd| {
cmd.ctrl_proxy(fixture.setting());
cmd.no_window();
});
assert_eq!(child.containment(), Containment::None);
assert!(!StopTarget::from(&child).leads_group_on_our_console());
child.terminate().expect("the proxy answered Sent");
assert_proxy_answered(child.pid(), CtrlEvent::CtrlBreak, ProxyAnswer::Sent);
kill_release_reap(&child, sock, false);
}
#[skuld::test]
fn a_detached_contained_root_is_refused_for_having_no_console() {
for call in CALLS {
let fixture = Fixture::answering(ProxyAnswer::TargetHasNoConsole.code());
let (child, sock) = root_stopping_through(&fixture, crate::ContainMode::Strongest, |cmd| _ = cmd.detached());
let err = call.run(&child, Duration::ZERO).expect_err("the call is refused");
let detail = unsupported_detail(&err);
assert!(detail.contains("answer TargetHasNoConsole"), "{call:?}: {detail}");
let (kill, graceful_stop) = (detail.find("Child::kill"), detail.find("Command::graceful_stop"));
assert!(
matches!((kill, graceful_stop), (Some(k), Some(g)) if k < g),
"{call:?}: the remedies, in order: {detail}"
);
assert_proxy_answered(child.pid(), CtrlEvent::CtrlBreak, ProxyAnswer::TargetHasNoConsole);
assert_eq!(
child.is_alive(),
crate::identity::Liveness::Alive,
"{call:?}: the call ended with the root running"
);
kill_release_reap(&child, sock, false);
}
}
#[skuld::test]
fn a_child_on_our_console_without_a_group_is_refused_by_the_direct_send_without_the_proxy() {
for call in CALLS {
let fixture = Fixture::answering(ProxyAnswer::Sent.code());
let (child, sock) = root_stopping_through(&fixture, crate::ContainMode::Strongest, |cmd| {
_ = cmd.new_process_group(false)
});
assert_eq!(
child.containment(),
Containment::JobObject,
"the job does not depend on the group"
);
assert_in_our_console(child.pid(), "the contained member");
assert!(!StopTarget::from(&child).leads_group_on_our_console());
let err = call.run(&child, Duration::ZERO).expect_err("the call is refused");
ctrl_break::assert_refused_by_the_direct_send_for_no_group(&err);
assert!(fixture.ran().is_none(), "{call:?}: the proxy was started");
assert_eq!(
child.is_alive(),
crate::identity::Liveness::Alive,
"{call:?}: the call ended with the root running"
);
kill_release_reap(&child, sock, false);
}
}
#[skuld::test]
fn an_uncontained_child_on_our_console_is_refused_by_the_direct_send_without_the_proxy() {
for call in [Call::Terminate, Call::GracefulShutdown] {
let fixture = Fixture::answering(ProxyAnswer::Sent.code());
let (child, sock) = ctrl_break::spawn_uncontained_member(Handler::Ignore, |cmd| {
cmd.ctrl_proxy(fixture.setting());
});
assert_eq!(child.containment(), Containment::None);
assert_in_our_console(child.pid(), "the uncontained member");
assert!(!StopTarget::from(&child).leads_group_on_our_console());
let err = call.run(&child, Duration::ZERO).expect_err("the call is refused");
ctrl_break::assert_refused_by_the_direct_send_for_no_group(&err);
assert!(fixture.ran().is_none(), "{call:?}: the proxy was started");
assert_eq!(
child.is_alive(),
crate::identity::Liveness::Alive,
"{call:?}: the call ended with the root running"
);
kill_release_reap(&child, sock, false);
}
}
#[skuld::test]
fn an_explicit_direct_send_answers_ok_for_a_child_outside_our_console_and_reaches_nobody() {
use std::io::Write as _;
for detached in [false, true] {
let (child, mut sock) = spawn_root_configured(Handler::Default, crate::ContainMode::Strongest, |cmd| {
if detached {
cmd.detached();
} else {
cmd.no_window();
}
cmd.graceful_stop(crate::stop::send_ctrl_break_to_group);
});
child
.terminate()
.unwrap_or_else(|e| panic!("detached {detached}: the documented false success: {e:?}"));
ctrl_break::assert_break_sent_to(child.pid());
assert_eq!(
child.is_alive(),
crate::identity::Liveness::Alive,
"detached {detached}: nothing was delivered, so the root must still be running"
);
sock.write_all(b"x").expect("release the root through its own socket");
let status = child.wait().expect("reap");
assert_eq!(
status.code(),
Some(0),
"detached {detached}: the root exited on OUR release byte, so the direct send delivered nothing; \
a delivered break would have ended it with STATUS_CONTROL_C_EXIT ({STATUS_CONTROL_C_EXIT:#x}), \
got {status:?}"
);
}
}
fn assert_own_console_route(child: &crate::Child, expected_containment: Containment) {
assert_eq!(
child.containment(),
expected_containment,
"this test is about the wrong thing if containment did not take"
);
let console = child.console;
assert!(
console.group && console.own_console_flags && !StopTarget::from(child).leads_group_on_our_console(),
"cosca's honest report of the route: a group in a console of its own, {console:?}"
);
}
#[skuld::test]
fn child_graceful_ops_report_success_for_a_child_that_shares_no_console() {
let _warns = crate::log_capture::warn_watch();
let (child, sock) = ctrl_break::spawn_consoleless_root();
let pid = child.pid();
assert!(
StopTarget::from(&child).leads_group_on_our_console(),
"the flags do not exclude delivery: that is exactly what makes this a gap"
);
child.terminate().expect("the documented false success");
ctrl_break::assert_break_sent_to(pid);
assert_eq!(
child.is_alive(),
crate::identity::Liveness::Alive,
"nothing was delivered, so the child must still be running"
);
let check = term_fault::at_checked(term_fault::HookPoint::AfterTerminate, move || {
ctrl_break::assert_break_sent_to(pid)
});
let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, sock);
let status = child
.graceful_shutdown(Duration::ZERO)
.expect("the forced half needs no console");
check.assert_fired();
assert_eq!(status.code(), Some(1), "escalation's kill, got {status:?}");
}
#[skuld::test]
fn drop_kills_a_job_object_tree() {
let (child, root_sock, grand) = spawn_tree(Handler::Default, Handler::Default, crate::ContainMode::Strongest);
assert_eq!(child.containment(), Containment::JobObject);
let Grandchild { sock, exit } = grand;
let teardown = crate::child::spawn::fault::release_at_drop_kill((root_sock, sock));
drop(child);
teardown.assert_reaps_killed();
assert_eq!(exit.wait_for_exit_code(), 1, "the drop must kill the grandchild");
}
#[skuld::test]
fn nested_delegated_child_can_be_gracefully_terminated() {
ctrl_break::drive_reporter(ctrl_break::nested::REPORTER_TEST, ctrl_break::nested::ADDR_ENV, |cmd| {
_ = cmd.contain()
});
}
#[skuld::test]
fn a_nested_contained_child_without_a_group_is_refused_by_the_direct_send() {
ctrl_break::drive_reporter(
ctrl_break::nested::NO_GROUP_REPORTER_TEST,
ctrl_break::nested::NO_GROUP_ADDR_ENV,
|cmd| _ = cmd.contain(),
);
}
#[skuld::test]
fn a_console_less_callers_default_asks_the_proxy_and_its_direct_send_has_no_console() {
ctrl_break::drive_reporter(
ctrl_break::console_less::REPORTER_TEST,
ctrl_break::console_less::ADDR_ENV,
|cmd| _ = cmd.detached(),
);
}