Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 81 additions & 28 deletions hide-kit/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ pub fn run(
#[cfg(test)]
mod tests {
use super::*;
use hide_platform::process::start_time;
use std::process::Stdio;
use std::sync::atomic::Ordering;
use std::thread;
Expand All @@ -68,6 +69,8 @@ mod tests {
"--nocapture",
"--test-threads=1",
];
/// Only ends a wait for something that never happens.
const HANG_LIMIT: Duration = Duration::from_secs(30);

// A real portable child, as hide-platform's process contract uses. The
// assertions below are unchanged: a deadline/stop ends the whole tree,
Expand All @@ -92,10 +95,16 @@ mod tests {
grandchild.wait().unwrap();
}
"grandchild" => {
thread::sleep(Duration::from_secs(2));
std::fs::write(std::env::var_os(MARKER).unwrap(), "survived").unwrap();
// Names itself once it runs, renamed into place so a reader
// never sees half of it.
let marker = std::path::PathBuf::from(std::env::var_os(MARKER).unwrap());
let partial = marker.with_extension("partial");
let pid = std::process::id();
std::fs::write(&partial, format!("{pid} {}", start_time(pid).unwrap())).unwrap();
std::fs::rename(&partial, &marker).unwrap();
// Outlives the tests' wait, so only a kill ends it in time.
thread::sleep(HANG_LIMIT * 2);
}
"sleep" => thread::sleep(Duration::from_secs(30)),
"output" => {
println!(
"RESULT {}|{}|{}",
Expand All @@ -110,11 +119,47 @@ mod tests {
}
}

/// The grandchild's pid and start time, once it has written them.
fn grandchild(marker: &Path) -> Option<(u32, u64)> {
let named = std::fs::read_to_string(marker).ok()?;
let (pid, started) = named.split_once(' ').unwrap();
Some((pid.parse().unwrap(), started.parse().unwrap()))
}

#[allow(clippy::disallowed_methods)] // a polling helper: it sleeps between observations of a state, bounded by a deadline
fn named_grandchild(marker: &Path) -> (u32, u64) {
let started = Instant::now();
loop {
if let Some(named) = grandchild(marker) {
return named;
}
assert!(started.elapsed() < HANG_LIMIT, "the grandchild never ran");
thread::sleep(Duration::from_millis(10));
}
}

/// Whether the process `pid` that started at `started` has ended. A
/// group killed with its leader leaves an orphan for the system to reap,
/// so this waits for that.
#[allow(clippy::disallowed_methods)] // a polling helper: it sleeps between observations of a state, bounded by a deadline
fn ended(pid: u32, started: u64) -> bool {
let waited = Instant::now();
while start_time(pid).is_ok_and(|now| now == started) {
if waited.elapsed() > HANG_LIMIT {
return false;
}
thread::sleep(Duration::from_millis(10));
}
true
}

/// Whether the grandchild runs before 300 ms pass is the scheduler's
/// choice; when it does, it ends with its group. The stop test below
/// ends a tree whose grandchild is known to run.
#[test]
#[allow(clippy::disallowed_methods)] // #437 the sleep stands in for a state the test can wait for
fn a_child_past_its_deadline_is_stopped_with_its_group() {
let home = tempfile::tempdir().unwrap();
let marker = home.path().join("grandchild-survived");
let marker = home.path().join("grandchild");
let started = Instant::now();
let result = run(
&std::env::current_exe().unwrap(),
Expand All @@ -127,36 +172,44 @@ mod tests {
Duration::from_millis(300),
&AtomicBool::new(false),
);
assert!(result.unwrap_err().contains("did not finish"));
let error = result.unwrap_err();
assert!(error.contains("did not finish"), "{error}");
assert!(started.elapsed() < Duration::from_secs(5));
thread::sleep(Duration::from_millis(2500));
assert!(!marker.exists(), "the grandchild outlived the deadline");
if let Some((pid, started)) = grandchild(&marker) {
assert!(ended(pid, started), "the grandchild outlived the deadline");
}
}

/// The stop is raised once the grandchild runs, so it ends a whole tree.
#[test]
#[allow(clippy::disallowed_methods)] // #437 the sleep stands in for a state the test can wait for
fn a_raised_stop_ends_the_child_before_its_deadline() {
let home = tempfile::tempdir().unwrap();
let stop = std::sync::Arc::new(AtomicBool::new(false));
let raiser = {
let stop = stop.clone();
thread::spawn(move || {
thread::sleep(Duration::from_millis(200));
let marker = home.path().join("grandchild");
let stop = AtomicBool::new(false);
let (result, (pid, born), raised) = thread::scope(|scope| {
let raiser = scope.spawn(|| {
let named = named_grandchild(&marker);
stop.store(true, Ordering::Relaxed);
})
};
let started = Instant::now();
let result = run(
&std::env::current_exe().unwrap(),
CHILD_ARGS,
&[(ROLE.into(), "sleep".into())],
home.path(),
Duration::from_secs(60),
&stop,
);
raiser.join().unwrap();
assert!(result.unwrap_err().contains("quitting"));
assert!(started.elapsed() < Duration::from_secs(5));
(named, Instant::now())
});
let result = run(
&std::env::current_exe().unwrap(),
CHILD_ARGS,
&[
(ROLE.into(), "tree".into()),
(MARKER.into(), marker.display().to_string()),
],
home.path(),
Duration::from_secs(60),
&stop,
);
let (named, raised) = raiser.join().unwrap();
(result, named, raised)
});
let error = result.unwrap_err();
assert!(error.contains("quitting"), "{error}");
assert!(raised.elapsed() < Duration::from_secs(5));
assert!(ended(pid, born), "the grandchild outlived the stop");
}

#[test]
Expand Down
50 changes: 28 additions & 22 deletions hide-platform/tests/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -566,21 +566,33 @@ fn a_lock_on_a_file_is_taken_through_the_file_that_stays_open() {
locked(lock::lock_file(open(), Mode::Exclusive, RELEASED_WITHIN, &never).unwrap());
}

/// A wait asks `cancelled` after every try that found the lock held, so its
/// first question is the waiter's own report that it is waiting.
#[test]
#[allow(clippy::disallowed_methods)] // #437 the sleep stands in for a state the test can wait for
fn a_wait_ends_when_the_holder_lets_go_and_not_before() {
let outer = folder();
let first = open_dir(outer.path());
let second = open_dir(outer.path());
let held = locked(lock::lock_dir(&first, Mode::Exclusive, Duration::ZERO, &never).unwrap());
let releaser = thread::spawn(move || {
thread::sleep(Duration::from_millis(200));
let (waiting, heard) = std::sync::mpsc::channel();
thread::scope(|scope| {
let waiter = scope.spawn(|| {
lock::lock_dir(&second, Mode::Exclusive, Duration::from_secs(20), &|| {
let _ = waiting.send(());
false
})
.unwrap()
});
heard
.recv_timeout(Duration::from_secs(20))
.expect("the waiter never found the lock held");
assert!(
!waiter.is_finished(),
"the waiter stopped while it was held"
);
drop(held);
locked(waiter.join().unwrap());
});
let started = Instant::now();
locked(lock::lock_dir(&second, Mode::Exclusive, Duration::from_secs(20), &never).unwrap());
assert!(started.elapsed() >= Duration::from_millis(150));
releaser.join().unwrap();
}

#[test]
Expand All @@ -597,27 +609,21 @@ fn a_wait_that_is_not_answered_times_out_after_the_time_it_was_given() {
assert!(started.elapsed() >= Duration::from_millis(300));
}

/// The caller answers "go on" to the first question and "stop" to the second,
/// so the wait has gone round once before it is cancelled.
#[test]
#[allow(clippy::disallowed_methods)] // #437 the sleep stands in for a state the test can wait for
fn a_wait_stops_when_the_caller_cancels_it() {
let outer = folder();
let first = open_dir(outer.path());
let second = open_dir(outer.path());
let _held = locked(lock::lock_dir(&first, Mode::Exclusive, Duration::ZERO, &never).unwrap());
let stop = AtomicBool::new(false);
thread::scope(|scope| {
scope.spawn(|| {
thread::sleep(Duration::from_millis(100));
stop.store(true, Ordering::Relaxed);
});
let started = Instant::now();
let waited = lock::lock_dir(&second, Mode::Exclusive, Duration::from_secs(30), &|| {
stop.load(Ordering::Relaxed)
})
.unwrap();
assert!(matches!(waited, Waited::Cancelled));
assert!(started.elapsed() < Duration::from_secs(10));
});
let asked = std::sync::atomic::AtomicUsize::new(0);
let waited = lock::lock_dir(&second, Mode::Exclusive, Duration::from_secs(30), &|| {
asked.fetch_add(1, Ordering::Relaxed) == 1
})
.unwrap();
assert!(matches!(waited, Waited::Cancelled));
assert_eq!(asked.load(Ordering::Relaxed), 2);
}

/// A folder opened the way `cap-std` opens one on Linux, with `O_PATH`: the
Expand Down
58 changes: 46 additions & 12 deletions hide-platform/tests/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ const ROLE: &str = "HIDE_PLATFORM_PROC_ROLE";
const HANG_LIMIT: Duration = Duration::from_secs(30);
// Test-only handoff: arm recovery before the short-lived parent exits.
const PIPE_OWNER: &str = "HIDE_PLATFORM_PROC_PIPE_OWNER";
/// Where the `sleep` role writes its pid once it runs, for a test that cannot
/// read the child's output before the call that started it returns.
const READY_FILE: &str = "HIDE_PLATFORM_PROC_READY_FILE";

/// Windows hands a freed pid to the next process that starts, so a test that
/// asks about a pid it has finished with must not run beside one that starts
Expand Down Expand Up @@ -85,6 +88,13 @@ fn child_role() {
}
"sleep" => {
println!("READY {}", std::process::id());
if let Some(path) = std::env::var_os(READY_FILE) {
// Renamed into place, so a reader never sees half a number.
let path = PathBuf::from(path);
let partial = path.with_extension("partial");
std::fs::write(&partial, std::process::id().to_string()).unwrap();
std::fs::rename(&partial, &path).unwrap();
}
thread::sleep(Duration::from_secs(60));
}
// A child with one child of its own that has left no handle behind.
Expand Down Expand Up @@ -227,6 +237,21 @@ fn ready_number(stdout: std::process::ChildStdout) -> u32 {
.expect("the child role did not become ready")
}

/// The pid a `sleep` child wrote to `path` once it ran.
#[allow(clippy::disallowed_methods)] // a polling helper: it sleeps between observations of a state, bounded by a deadline
fn announced_pid(path: &std::path::Path) -> u32 {
let started = Instant::now();
loop {
match std::fs::read_to_string(path) {
Ok(pid) => return pid.parse().unwrap(),
Err(error) if error.kind() == ErrorKind::NotFound => {}
Err(error) => panic!("cannot read the child's pid: {error}"),
}
assert!(started.elapsed() < HANG_LIMIT, "the child never ran");
thread::sleep(Duration::from_millis(10));
}
}

#[allow(clippy::disallowed_methods)] // a polling helper: it sleeps between observations of a state, bounded by a deadline
fn gone_within(pid: u32, bound: Duration) -> bool {
let started = Instant::now();
Expand Down Expand Up @@ -827,23 +852,32 @@ fn a_child_past_its_deadline_is_ended_with_its_tree() {
assert!(started.elapsed() < Duration::from_secs(10));
}

/// The stop is raised once the child runs, so it ends a running child rather
/// than one still starting.
#[test]
#[allow(clippy::disallowed_methods)] // #437 the sleep stands in for a state the test can wait for
fn a_raised_stop_ends_the_child_before_its_deadline() {
let _serial = serial();
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let raiser = {
let stop = std::sync::Arc::clone(&stop);
thread::spawn(move || {
thread::sleep(Duration::from_millis(300));
let folder = tempfile::tempdir().unwrap();
let ready = folder.path().join("ready");
let stop = std::sync::atomic::AtomicBool::new(false);
let mut command = Command::new(std::env::current_exe().unwrap());
command
.args(["--exact", "child_role", "--nocapture", "--test-threads=1"])
.env(ROLE, "sleep")
.env(READY_FILE, &ready);
let (failure, child, raised) = thread::scope(|scope| {
let raiser = scope.spawn(|| {
let child = announced_pid(&ready);
stop.store(true, std::sync::atomic::Ordering::Relaxed);
})
};
let started = Instant::now();
let failure = run_role("sleep", Duration::from_secs(60), &stop).unwrap_err();
raiser.join().unwrap();
(child, Instant::now())
});
let failure = run_to_end(&mut command, Duration::from_secs(60), &stop).unwrap_err();
let (child, raised) = raiser.join().unwrap();
(failure, child, raised)
});
assert!(matches!(failure, RunFailure::Stopped), "{failure:?}");
assert!(started.elapsed() < Duration::from_secs(10));
assert!(raised.elapsed() < Duration::from_secs(10));
assert!(!is_alive(child), "the stopped child outlived the call");
}

/// Recovery is armed before the parent exits, so a hanging public call fails
Expand Down
Loading