use crate::context::ExecContext;
use anyhow::{bail, Context, Result};
use std::io::Read;
use std::os::fd::AsRawFd;
use std::os::unix::process::CommandExt;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
const MAX_OUTPUT: usize = 64 * 1024;
#[derive(Debug)]
pub(crate) struct CleanupIncomplete(pub(crate) String);
impl std::fmt::Display for CleanupIncomplete {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "cleanup incomplete: {}", self.0)
}
}
pub(crate) struct OwnedGroup(pub(crate) Child, pub(crate) crate::context::CancelHandle);
impl Drop for OwnedGroup {
fn drop(&mut self) {
let pid = self.0.id() as i32;
let mut state: libc::siginfo_t = unsafe { std::mem::zeroed() };
let owned = loop {
let result = unsafe {
libc::waitid(
libc::P_PID,
self.0.id(),
&mut state,
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
if result == 0 {
break true;
}
if std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted {
break false;
}
};
if pid > 1 && owned {
unsafe {
libc::killpg(pid, libc::SIGKILL);
}
if self.0.wait().is_err() {
self.1.record_native_uncertain(pid as u32);
} else {
let exists = unsafe { libc::killpg(pid, 0) };
if exists == 0
|| std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
{
self.1.record_native_uncertain(pid as u32);
}
}
} else {
self.1.record_native_uncertain(pid as u32);
}
}
}
pub(crate) fn docker_control(
ctx: &ExecContext,
args: &[&str],
timeout: Duration,
) -> Result<Vec<u8>> {
docker_with_cancel(ctx, args, timeout, true)
}
fn docker(ctx: &ExecContext, args: &[&str], timeout: Duration) -> Result<Vec<u8>> {
docker_with_cancel(ctx, args, timeout, false)
}
fn docker_with_cancel(
ctx: &ExecContext,
args: &[&str],
timeout: Duration,
stop_on_cancel: bool,
) -> Result<Vec<u8>> {
if stop_on_cancel && ctx.cancel.is_cancelled() {
bail!("control command cancelled");
}
let mut command = ctx.command("docker");
command.args(args);
bounded_command(ctx, command, timeout, stop_on_cancel)
}
pub(crate) fn bounded_command(
ctx: &ExecContext,
mut command: Command,
timeout: Duration,
stop_on_cancel: bool,
) -> Result<Vec<u8>> {
if stop_on_cancel && ctx.cancel.is_cancelled() {
bail!("control command cancelled");
}
#[cfg(test)]
let observed: Vec<String> = command
.get_args()
.map(|s| s.to_string_lossy().into_owned())
.collect();
let mut child = OwnedGroup(
command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.process_group(0)
.spawn()
.context("start control command")?,
ctx.cancel.clone(),
);
#[cfg(test)]
tests::observe_spawn(
&child.0,
&observed.iter().map(String::as_str).collect::<Vec<_>>(),
timeout,
);
let mut stdout = child.0.stdout.take().context("missing stdout")?;
let mut stderr = child.0.stderr.take().context("missing stderr")?;
for fd in [stdout.as_raw_fd(), stderr.as_raw_fd()] {
unsafe {
let flags = libc::fcntl(fd, libc::F_GETFL);
if flags < 0 || libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) < 0 {
return Err(std::io::Error::last_os_error()).context("nonblocking control pipe");
}
}
}
let started = Instant::now();
let mut output = Vec::new();
let mut errors = Vec::new();
let mut eof = [false; 2];
loop {
if stop_on_cancel && ctx.cancel.is_cancelled() {
bail!("control command cancelled");
}
if started.elapsed() >= timeout {
bail!("control command deadline exceeded");
}
for (i, (pipe, bytes)) in [
(&mut stdout as &mut dyn Read, &mut output),
(&mut stderr as &mut dyn Read, &mut errors),
]
.into_iter()
.enumerate()
{
let mut buf = [0; 4096];
match pipe.read(&mut buf) {
Ok(0) => eof[i] = true,
Ok(n) => {
if bytes.len() + n > MAX_OUTPUT {
bail!("control command output limit exceeded");
}
bytes.extend_from_slice(&buf[..n]);
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => (),
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => (),
Err(e) => return Err(e).context("read control command output"),
}
}
let mut status: libc::siginfo_t = unsafe { std::mem::zeroed() };
let rc = unsafe {
libc::waitid(
libc::P_PID,
child.0.id(),
&mut status,
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
if rc != 0 {
return Err(std::io::Error::last_os_error()).context("inspect control child");
}
if unsafe { status.si_pid() } != 0 && eof.iter().all(|v| *v) {
if status.si_code != libc::CLD_EXITED || unsafe { status.si_status() } != 0 {
bail!("control command exited unsuccessfully");
}
return Ok(output);
}
std::thread::sleep(Duration::from_millis(5));
}
}
pub(crate) fn remove_tracked_containers(
ctx: &ExecContext,
names: &[String],
) -> Vec<CleanupIncomplete> {
remove_tracked_with_timeout(ctx, names, Duration::from_secs(30))
}
fn remove_tracked_with_timeout(
ctx: &ExecContext,
names: &[String],
timeout: Duration,
) -> Vec<CleanupIncomplete> {
if names.is_empty() {
return vec![];
}
if names.iter().any(|id| !valid_container_id(id)) {
return vec![CleanupIncomplete("invalid tracked container ID".into())];
}
let deadline = Instant::now() + timeout;
for id in names {
let result = (|| -> Result<()> {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
bail!("container cleanup deadline exceeded");
}
let filter = format!("id={id}");
let bytes = docker(
ctx,
&["ps", "-aq", "--no-trunc", "--filter", &filter],
remaining.min(Duration::from_secs(5)),
)?;
let found = std::str::from_utf8(&bytes).context("invalid container ID encoding")?;
let ids: Vec<&str> = found.lines().collect();
if ids.iter().any(|other| *other != id) || ids.len() > 1 {
bail!("unexpected container ID in exact filtered query");
}
if !ids.is_empty() {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
bail!("container cleanup deadline exceeded");
}
docker(ctx, &["rm", "-f", "--", id], remaining)?;
}
Ok(())
})();
if let Err(error) = result {
return vec![CleanupIncomplete(format!(
"remove tracked containers: {error:#}"
))];
}
}
vec![]
}
pub(crate) fn valid_container_id(id: &str) -> bool {
id.len() == 64
&& id
.bytes()
.all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
}
pub(crate) fn compose_down(ctx: &ExecContext, projects: &[String]) -> Vec<CleanupIncomplete> {
compose_down_with_budgets(
ctx,
projects,
Duration::from_secs(5),
Duration::from_secs(30),
)
}
#[cfg(test)]
fn compose_down_with_timeout(
ctx: &ExecContext,
projects: &[String],
timeout: Duration,
) -> Vec<CleanupIncomplete> {
compose_down_with_budgets(ctx, projects, timeout, timeout)
}
fn compose_down_with_budgets(
ctx: &ExecContext,
projects: &[String],
query_timeout: Duration,
action_timeout: Duration,
) -> Vec<CleanupIncomplete> {
let mut failures = Vec::new();
for (index, project) in projects.iter().enumerate() {
let result = (|| -> Result<()> {
if project.is_empty()
|| project.len() > 255
|| !project.as_bytes()[0].is_ascii_lowercase()
&& !project.as_bytes()[0].is_ascii_digit()
|| !project
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
{
bail!("invalid Compose project name");
}
let label = format!("label=com.docker.compose.project={project}");
let bytes = docker(ctx, &["ps", "-aq", "--filter", &label], query_timeout)
.context("query owned Compose containers")?;
let ids = std::str::from_utf8(&bytes).context("invalid container ID encoding")?;
for id in ids.lines() {
if !matches!(id.len(), 12 | 64)
|| !id
.bytes()
.all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
{
bail!("invalid container ID list");
}
}
if !ids.is_empty() {
docker(
ctx,
&["compose", "-p", project, "down", "--remove-orphans"],
action_timeout,
)
.context("take down owned Compose project")?;
}
Ok(())
})();
if let Err(e) = result {
failures.push(CleanupIncomplete(format!("{e:#}")));
for _ in &projects[index + 1..] {
failures.push(CleanupIncomplete(
"project not attempted after an earlier cleanup failure".into(),
));
}
break;
}
}
failures
}
#[cfg(test)]
mod tests {
use super::*;
struct SpawnReceipt {
pid: i32,
args: Vec<String>,
started: Instant,
timeout: Duration,
}
type SpawnObserver = Box<dyn FnMut(&Child, &[&str], Duration)>;
std::thread_local! {
static OBSERVER: std::cell::RefCell<Option<SpawnObserver>> = const { std::cell::RefCell::new(None) };
}
pub(super) fn observe_spawn(child: &Child, args: &[&str], timeout: Duration) {
OBSERVER.with_borrow_mut(|observer| {
if let Some(observer) = observer {
observer(child, args, timeout);
}
});
}
fn observed<T>(
ready: Option<(String, std::path::PathBuf, bool)>,
run: impl FnOnce() -> T,
) -> (T, Vec<SpawnReceipt>) {
let receipts = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
let recorded = receipts.clone();
OBSERVER.with_borrow_mut(|observer| {
assert!(observer.is_none());
*observer = Some(Box::new(move |child, args, timeout| {
if let Some((phase, marker, wait_for_exit)) = &ready {
if args.first() == Some(&phase.as_str()) {
let setup = Instant::now();
while !marker.exists() {
assert!(
setup.elapsed() < Duration::from_secs(10),
"stub startup marker missing"
);
std::thread::sleep(Duration::from_millis(5));
}
}
if args.first() != Some(&phase.as_str()) || *wait_for_exit {
let setup = Instant::now();
loop {
let mut status: libc::siginfo_t = unsafe { std::mem::zeroed() };
let rc = unsafe {
libc::waitid(
libc::P_PID,
child.id(),
&mut status,
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
assert_eq!(rc, 0);
if unsafe { status.si_pid() } != 0 {
break;
}
assert!(
setup.elapsed() < Duration::from_secs(10),
"prerequisite stub did not exit"
);
std::thread::sleep(Duration::from_millis(5));
}
}
}
recorded.borrow_mut().push(SpawnReceipt {
pid: child.id() as i32,
args: args.iter().map(|arg| (*arg).to_owned()).collect(),
started: Instant::now(),
timeout,
});
}));
});
struct Reset;
impl Drop for Reset {
fn drop(&mut self) {
OBSERVER.with_borrow_mut(|observer| *observer = None);
}
}
let reset = Reset;
let result = run();
drop(reset);
(
result,
std::rc::Rc::try_unwrap(receipts).ok().unwrap().into_inner(),
)
}
fn fixture(script: &str) -> (tempfile::TempDir, ExecContext) {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("docker");
crate::fake_exec::write_executable(
&file,
format!("#!/bin/sh\necho \"$*\" >> \"$HOME/calls\"\n{script}\n"),
0o755,
);
let ctx = ExecContext::new(
[
("HOME".into(), dir.path().display().to_string()),
(
"PATH".into(),
format!("{}:/usr/bin:/bin", dir.path().display()),
),
]
.into_iter()
.collect(),
);
(dir, ctx)
}
fn run(ctx: &ExecContext) -> Vec<CleanupIncomplete> {
compose_down_with_timeout(ctx, &["owned-project".into()], Duration::from_secs(2))
}
fn calls(dir: &tempfile::TempDir) -> String {
std::fs::read_to_string(dir.path().join("calls")).unwrap_or_default()
}
#[test]
fn control_cancel_is_prompt_and_reaps_owned_child_but_cleanup_still_runs() {
let (dir, ctx) = fixture("echo $$ > \"$HOME/pid\"; exec sleep 20");
let cancel = ctx.cancel.clone();
let ready = dir.path().join("pid");
let signal = std::thread::spawn(move || {
let start = Instant::now();
while !ready.exists() {
assert!(
start.elapsed() < Duration::from_secs(10),
"stub startup marker missing"
);
std::thread::sleep(Duration::from_millis(5));
}
let cancelled = Instant::now();
cancel.cancel();
cancelled
});
let (result, receipts) = observed(None, || {
docker_control(&ctx, &["info"], Duration::from_secs(20))
});
let cancelled = signal.join().unwrap();
assert!(result.unwrap_err().to_string().contains("cancelled"));
assert!(cancelled.elapsed() < Duration::from_secs(3));
assert_eq!(receipts.len(), 1);
let pid = receipts[0].pid;
assert_eq!(
unsafe { libc::waitpid(pid, std::ptr::null_mut(), libc::WNOHANG) },
-1
);
assert_eq!(
std::io::Error::last_os_error().raw_os_error(),
Some(libc::ECHILD)
);
crate::fake_exec::write_executable(
&dir.path().join("docker"),
"#!/bin/sh\necho \"$*\" >> \"$HOME/calls\"\nif [ \"$1\" = ps ]; then for arg do case \"$arg\" in id=*) echo \"${arg#id=}\";; esac; done; fi\nexit 0\n",
0o755,
);
assert!(docker_control(&ctx, &["logs"], Duration::from_millis(250)).is_err());
assert!(!calls(&dir).lines().any(|line| line == "logs"));
assert!(run(&ctx).is_empty());
assert!(
remove_tracked_with_timeout(&ctx, &["a".repeat(64)], Duration::from_secs(2)).is_empty()
);
assert!(calls(&dir).contains(&format!("rm -f -- {}", "a".repeat(64))));
}
#[test]
fn tracked_removal_validates_scope_and_reports_blockage_and_failure() {
let (dir, ctx) = fixture("if [ \"$1\" = ps ]; then for arg do case \"$arg\" in id=*) echo \"${arg#id=}\";; esac; done; fi\nexit 0");
assert!(remove_tracked_with_timeout(&ctx, &[], Duration::from_millis(250)).is_empty());
assert!(calls(&dir).is_empty());
for name in ["", "--all", "one two", "a\n", &"a".repeat(256)] {
assert!(
!remove_tracked_with_timeout(&ctx, &[name.into()], Duration::from_millis(250))
.is_empty()
);
}
assert!(calls(&dir).is_empty());
assert!(remove_tracked_with_timeout(
&ctx,
&["a".repeat(64), "b".repeat(64)],
Duration::from_secs(2)
)
.is_empty());
assert_eq!(calls(&dir), format!("ps -aq --no-trunc --filter id={}\nrm -f -- {}\nps -aq --no-trunc --filter id={}\nrm -f -- {}\n", "a".repeat(64), "a".repeat(64), "b".repeat(64), "b".repeat(64)));
for script in ["exec sleep 20", "echo secret-daemon-error >&2; exit 1"] {
let (_dir, ctx) = fixture(script);
let errors =
remove_tracked_with_timeout(&ctx, &["a".repeat(64)], Duration::from_millis(250));
assert_eq!(errors.len(), 1);
assert!(errors[0].to_string().contains("remove tracked"));
assert!(!errors[0].to_string().contains("secret-daemon-error"));
}
}
#[test]
fn control_drains_both_pipes_and_keeps_daemon_errors_private() {
let (_dir, ctx) = fixture("(dd if=/dev/zero bs=32768 count=1 2>/dev/null) >&2\n(dd if=/dev/zero bs=32768 count=1 2>/dev/null)");
assert_eq!(
docker_control(&ctx, &["logs"], Duration::from_secs(2))
.unwrap()
.len(),
32768
);
let (_dir, ctx) = fixture("echo daemon-private >&2; echo partial; exit 1");
let error = docker_control(&ctx, &["inspect"], Duration::from_secs(2)).unwrap_err();
assert!(!format!("{error:#}").contains("daemon-private"));
let (_dir, ctx) =
fixture("while :; do printf 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' >&2; done");
assert!(docker_control(&ctx, &["logs"], Duration::from_secs(2))
.unwrap_err()
.to_string()
.contains("output limit"));
}
#[test]
fn cancellation_handle_removes_only_tracked_names_even_after_cancel() {
let (dir, ctx) = fixture("if [ \"$1\" = ps ]; then for arg do case \"$arg\" in id=*) echo \"${arg#id=}\";; esac; done; fi\nexit 0");
ctx.cancel.track_container("a".repeat(64));
ctx.cancel.track_container("b".repeat(64));
ctx.cancel.cancel();
ctx.cancel.remove_containers(&ctx);
assert_eq!(calls(&dir), format!("ps -aq --no-trunc --filter id={}\nrm -f -- {}\nps -aq --no-trunc --filter id={}\nrm -f -- {}\n", "a".repeat(64), "a".repeat(64), "b".repeat(64), "b".repeat(64)));
ctx.cancel.remove_containers(&ctx);
assert_eq!(calls(&dir).lines().count(), 4);
}
#[test]
fn cleanup_normal_and_empty() {
for ids in [
"",
"012345abcdef",
"012345abcdef\nabcdef012345",
&"a".repeat(64),
] {
let (dir, ctx) = fixture(&format!("[ \"$1\" = ps ] && printf '%s' '{ids}'\nexit 0"));
let errors = run(&ctx);
assert!(errors.is_empty(), "{errors:?}");
let log = calls(&dir);
assert!(
log.starts_with("ps -aq --filter label=com.docker.compose.project=owned-project\n")
);
assert_eq!(
log.contains("compose -p owned-project down --remove-orphans"),
!ids.is_empty()
);
}
}
#[test]
fn cleanup_refuses_bad_ids_partial_nonzero_and_excessive_output() {
for script in [
"printf '012345abcdef\n'; exit 1",
"kill -TERM $$",
"echo invalid",
"echo 012345abcdeF",
"printf '\\377'",
"printf '012345abcdef\n\n'",
"printf ' '; exit 0",
"while :; do printf 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; done",
"while :; do printf 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' >&2; done",
] {
let (dir, ctx) = fixture(script);
assert!(!run(&ctx).is_empty(), "{script}");
assert!(
!calls(&dir).lines().any(|line| line.starts_with("compose ")),
"{script}"
);
}
}
#[test]
fn cleanup_refuses_invalid_projects_without_invoking_docker() {
let (dir, ctx) = fixture("exit 0");
for project in ["", "--help", "A", "a b", "a\n", &"a".repeat(256)] {
assert!(!compose_down_with_timeout(
&ctx,
&[project.into()],
Duration::from_millis(250)
)
.is_empty());
}
assert!(calls(&dir).is_empty());
}
#[test]
fn cleanup_bounds_blocked_query_and_down_and_reaps_owned_leader() {
for phase in ["ps", "compose"] {
let (dir, ctx) = fixture(&format!(
"if [ \"$1\" = {phase} ]; then sleep 0.35; echo $$ > \"$HOME/pid\"; exec sleep 20; fi\necho 012345abcdef"));
let (errors, receipts) =
observed(Some((phase.into(), dir.path().join("pid"), false)), || {
compose_down_with_timeout(
&ctx,
&["owned-project".into()],
Duration::from_millis(250),
)
});
assert_eq!(errors.len(), 1);
assert!(errors[0].to_string().contains("deadline"));
let blocked = receipts.last().unwrap();
assert_eq!(blocked.args[0], phase);
assert!(blocked.started.elapsed() < Duration::from_secs(3));
if phase == "ps" {
assert!(!calls(&dir).lines().any(|line| line.starts_with("compose ")));
}
let pid = blocked.pid;
assert_eq!(
unsafe { libc::waitpid(pid, std::ptr::null_mut(), libc::WNOHANG) },
-1
);
assert_eq!(
std::io::Error::last_os_error().raw_os_error(),
Some(libc::ECHILD)
);
}
}
#[test]
fn cleanup_bounds_inherited_pipe_after_leader_exits() {
let (dir, ctx) = fixture("sleep 0.35; sleep 20 &\necho $! > \"$HOME/plugin\"\nexit 0");
let (errors, receipts) =
observed(Some(("ps".into(), dir.path().join("plugin"), true)), || {
compose_down_with_timeout(
&ctx,
&["owned-project".into()],
Duration::from_millis(250),
)
});
assert!(!errors.is_empty());
assert_eq!(receipts.len(), 1);
assert!(receipts[0].started.elapsed() < Duration::from_secs(3));
assert!(!calls(&dir).lines().any(|line| line.starts_with("compose ")));
let pid = std::fs::read_to_string(dir.path().join("plugin")).unwrap();
let status = ctx
.command("ps")
.args(["-p", pid.trim(), "-o", "stat="])
.output()
.unwrap();
assert!(
!status.status.success()
|| String::from_utf8_lossy(&status.stdout)
.trim()
.starts_with('Z')
);
}
#[test]
fn cleanup_output_limit_is_inclusive_on_both_streams() {
for redirect in ["", ">&2"] {
for count in [MAX_OUTPUT, MAX_OUTPUT + 1] {
let (_dir, ctx) = fixture(&format!(
"(dd if=/dev/zero bs={count} count=1 2>/dev/null) {redirect}"
));
let result = docker(&ctx, &["ps"], Duration::from_secs(2));
if count == MAX_OUTPUT {
let output = result.unwrap();
assert_eq!(output.len(), if redirect.is_empty() { count } else { 0 });
} else {
assert!(result.unwrap_err().to_string().contains("output limit"));
}
}
}
}
#[test]
fn cleanup_selects_shorter_read_only_budget_and_preserves_action_budget() {
let (_dir, ctx) = fixture("[ \"$1\" = ps ] && echo 012345abcdef; exit 0");
let (errors, receipts) = observed(None, || compose_down(&ctx, &["owned-project".into()]));
assert!(errors.is_empty());
assert_eq!(receipts.len(), 2);
assert_eq!(receipts[0].args[0], "ps");
assert_eq!(receipts[0].timeout, Duration::from_secs(5));
assert_eq!(receipts[1].args[0], "compose");
assert_eq!(receipts[1].timeout, Duration::from_secs(30));
let (errors, receipts) = observed(None, || run(&ctx));
assert!(errors.is_empty());
assert_eq!(receipts.len(), 2);
assert!(receipts
.iter()
.all(|receipt| receipt.timeout == Duration::from_secs(2)));
}
#[test]
fn cleanup_failure_marks_unattempted_projects_without_more_queries() {
let (_dir, ctx) = fixture("exit 1");
let (failures, receipts) = observed(None, || {
compose_down_with_timeout(
&ctx,
&["one".into(), "two".into(), "three".into()],
Duration::from_millis(250),
)
});
assert_eq!(failures.len(), 3);
assert!(failures[1].to_string().contains("not attempted"));
assert!(failures[2].to_string().contains("not attempted"));
assert_eq!(receipts.len(), 1);
assert_eq!(receipts[0].args[0], "ps");
}
#[test]
fn cleanup_reaps_successful_owned_child() {
let (dir, ctx) = fixture("echo $$ > \"$HOME/pid\"; exit 0");
assert!(run(&ctx).is_empty());
let pid = std::fs::read_to_string(dir.path().join("pid"))
.unwrap()
.trim()
.parse::<i32>()
.unwrap();
assert_eq!(
unsafe { libc::waitpid(pid, std::ptr::null_mut(), libc::WNOHANG) },
-1
);
assert_eq!(
std::io::Error::last_os_error().raw_os_error(),
Some(libc::ECHILD)
);
}
#[test]
fn cleanup_reports_failed_down_without_repeating_or_fallback() {
let (dir, ctx) = fixture("[ \"$1\" = ps ] && { echo 012345abcdef; exit 0; }\nexit 2");
let errors = run(&ctx);
assert_eq!(errors.len(), 1);
assert!(
errors[0].to_string().contains("take down owned"),
"{errors:?}"
);
assert_eq!(calls(&dir).lines().count(), 2);
}
#[test]
fn timed_out_creation_retains_candidate_even_after_control_child_is_reaped() {
let (dir, ctx) = fixture(
"if [ \"$1\" = run ]; then echo $$ > \"$HOME/pid\"; exec /bin/sleep 30; fi\nexit 0",
);
ctx.cancel.creation_started("ambiguous-create".into());
let (result, receipts) =
observed(Some(("run".into(), dir.path().join("pid"), false)), || {
docker_control(&ctx, &["run", "-d"], Duration::from_millis(100))
});
assert!(result.unwrap_err().to_string().contains("deadline"));
assert_eq!(receipts.len(), 1);
assert_eq!(
unsafe { libc::waitpid(receipts[0].pid, std::ptr::null_mut(), libc::WNOHANG) },
-1
);
assert_eq!(
std::io::Error::last_os_error().raw_os_error(),
Some(libc::ECHILD)
);
let cleanup = ctx.cancel.cleanup_owned(&ctx);
assert_eq!(cleanup.pending.creation_candidates, ["ambiguous-create"]);
assert!(!cleanup.pending.no_known_pending());
assert!(!calls(&dir).lines().any(|line| line.starts_with("rm ")));
}
}