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
42 changes: 15 additions & 27 deletions cli/adopt/src/launcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -902,29 +902,13 @@ mod tests {
const RUN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// Runs `cmd` and returns its exit code, stdout and untrimmed stderr.
///
/// A script written just before the run can still be open for writing in
/// another test's forked child, so `ExecutableFileBusy` is retried.
fn run_captured(cmd: &mut std::process::Command) -> (Option<i32>, String, String) {
let mut tries = 0;
loop {
match dx_process::capture::run_captured(cmd, RUN_TIMEOUT) {
Err(dx_process::capture::RunError::Spawn { source, .. })
if source.kind() == std::io::ErrorKind::ExecutableFileBusy && tries < 50 =>
{
tries += 1;
std::thread::sleep(std::time::Duration::from_millis(20));
}
other => {
let run = other.expect("launcher runs");
return (
run.code,
run.stdout_text(),
String::from_utf8_lossy(&run.stderr).into_owned(),
);
}
}
}
let run = dx_process::capture::run_captured(cmd, RUN_TIMEOUT).expect("launcher runs");
(
run.code,
run.stdout_text(),
String::from_utf8_lossy(&run.stderr).into_owned(),
)
}

fn pinned(sha: &str) -> LauncherPins {
Expand Down Expand Up @@ -1605,8 +1589,9 @@ mod tests {
}

fn run(&self, env: &[(&str, &str)], args: &[&str]) -> (Option<i32>, String, String) {
let mut cmd = std::process::Command::new(self.path(BAZEL_WRAPPER_SH_REL));
cmd.args(args)
let mut cmd = std::process::Command::new("/bin/sh");
cmd.arg(self.path(BAZEL_WRAPPER_SH_REL))
.args(args)
.current_dir(self.dir.path())
.env_remove("DX_BAZEL_CHILD")
.env("BAZEL_REAL", self.path("real"));
Expand Down Expand Up @@ -1680,7 +1665,8 @@ mod tests {
#[test]
fn without_bazelisk_the_wrapper_names_what_is_missing() {
let wrapped = Wrapped::new(0);
let mut cmd = std::process::Command::new(wrapped.path(BAZEL_WRAPPER_SH_REL));
let mut cmd = std::process::Command::new("/bin/sh");
cmd.arg(wrapped.path(BAZEL_WRAPPER_SH_REL));
let (code, _, err) = run_captured(cmd.arg("info").env_remove("BAZEL_REAL"));
assert_ne!(code, Some(0));
assert!(err.contains("Bazelisk"), "{err}");
Expand Down Expand Up @@ -1800,7 +1786,8 @@ mod tests {
) -> (Option<i32>, String, String) {
let base = &self.base;
run_captured(
Command::new(base.join("repo/tools/dx"))
Command::new("/bin/sh")
.arg(base.join("repo/tools/dx"))
.current_dir(cwd)
.args(args)
.env_clear()
Expand Down Expand Up @@ -1978,7 +1965,8 @@ mod tests {
let home = fx.base.join("home");
let wrapper = |envs: &[(&str, &std::path::Path)]| {
run_captured(
Command::new(repo.join(BAZEL_WRAPPER_SH_REL))
Command::new("/bin/sh")
.arg(repo.join(BAZEL_WRAPPER_SH_REL))
.current_dir(&repo)
.arg("info")
.env_clear()
Expand Down
19 changes: 14 additions & 5 deletions cli/adopt/src/watch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -817,18 +817,27 @@ mod tests {
fn session_merges_a_burst_split_across_debounce_batches() {
let scratch = dx_test_scratch::scratch("dx-watch-split-").unwrap();
let root = scratch.path().to_path_buf();
let session = WatchSession::start(&root, &[], false).expect("session starts");
std::fs::write(root.join("a.txt"), "first").expect("first write");
std::thread::sleep(Duration::from_millis(120));
std::fs::write(root.join("b.txt"), "second").expect("second write");
let mut session = WatchSession::start(&root, &[], false).expect("session starts");
let (batches, events) = std::sync::mpsc::channel();
session.events = events;
let batch = |name: &str| -> notify_debouncer_mini::DebounceEventResult {
let path = root.join(name);
std::fs::write(&path, name).expect("write");
Ok(vec![notify_debouncer_mini::DebouncedEvent::new(
path,
notify_debouncer_mini::DebouncedEventKind::Any,
)])
};
batches.send(batch("a.txt")).expect("first batch");
batches.send(batch("b.txt")).expect("second batch");
let trigger = session.wait(Duration::from_secs(5)).expect("wait");
for name in ["a.txt", "b.txt"] {
assert!(
trigger.iter().any(|path| path.ends_with(name)),
"{name} must be in the one trigger: {trigger:?}"
);
}
std::fs::write(root.join("sentinel.txt"), "done").expect("sentinel");
batches.send(batch("sentinel.txt")).expect("sentinel batch");
let rest = wait_for(&session, "sentinel.txt");
for name in ["a.txt", "b.txt"] {
assert!(
Expand Down
48 changes: 27 additions & 21 deletions cli/cli/src/adopt/watch_probe_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,25 +146,33 @@ impl Probe {
}

fn until(&mut self, what: &str, done: impl Fn(&Probe) -> bool) {
let deadline = Instant::now() + Duration::from_secs(30);
while !done(self) {
if let Ok(Some(status)) = self.child.try_wait() {
panic!(
"dx exited ({status:?}) before {what}\nlog:\n{}\nstdout:\n{}\nstderr:\n{}",
self.log(),
self.stdout(),
self.stderr()
);
}
assert!(
Instant::now() < deadline,
"timed out waiting for {what}\nlog:\n{}\nstdout:\n{}\nstderr:\n{}",
let log = self.log.clone();
let mut exited = None;
let waited = {
let this = &mut *self;
dx_test_scratch::wait::watch_until(&log, what, Duration::from_secs(30), || {
if done(this) {
return true;
}
exited = this.child.try_wait().ok().flatten();
exited.is_some()
})
};
if let Some(status) = exited.filter(|_| !done(self)) {
panic!(
"dx exited ({status:?}) before {what}\nlog:\n{}\nstdout:\n{}\nstderr:\n{}",
self.log(),
self.stdout(),
self.stderr()
);
std::thread::sleep(Duration::from_millis(20));
}
assert!(
waited.is_ok(),
"{waited:?}\nlog:\n{}\nstdout:\n{}\nstderr:\n{}",
self.log(),
self.stdout(),
self.stderr()
);
}

fn idle(&mut self, ends: usize) {
Expand All @@ -181,27 +189,25 @@ impl Probe {
}

fn exit(&mut self) -> ExitStatus {
let deadline = Instant::now() + Duration::from_secs(30);
loop {
if let Some(status) = self.child.try_wait().expect("wait") {
match dx_test_scratch::wait::child_exits(&mut self.child, Duration::from_secs(30)) {
Ok(status) => {
self.exited = self.signalled.map(|at| at.elapsed());
return status;
status
}
if Instant::now() >= deadline {
Err(error) => {
if let Err(e) = self.child.kill() {
eprintln!("kill dx: {e}");
}
if let Err(e) = self.child.wait() {
eprintln!("wait dx: {e}");
}
panic!(
"dx did not exit\nlog:\n{}\nstdout:\n{}\nstderr:\n{}",
"dx did not exit: {error}\nlog:\n{}\nstdout:\n{}\nstderr:\n{}",
self.log(),
self.stdout(),
self.stderr()
);
}
std::thread::sleep(Duration::from_millis(20));
}
}

Expand Down
54 changes: 27 additions & 27 deletions cli/cli/src/adopt/watch_relaunch_tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
use std::time::Duration;

const MODULE: &str = "module(name = \"sample\", version = \"0.0.0\")\nbazel_dep(name = \"rules_dx\", version = \"0.0.0\")\n";

Expand Down Expand Up @@ -85,22 +85,30 @@ impl Watch {
}

fn until(&mut self, what: &str, done: impl Fn(&Path) -> bool) {
let deadline = Instant::now() + Duration::from_secs(30);
while !done(&self.state) {
if let Ok(Some(status)) = self.child.try_wait() {
panic!("dx exited ({status:?}) before {what}");
}
assert!(
Instant::now() < deadline,
"timed out waiting for {what}\n{}\nstate: {:?}",
self.stderr(),
fs::read_dir(&self.state).map(|dir| dir
.filter_map(Result::ok)
.map(|entry| entry.file_name())
.collect::<Vec<_>>())
);
std::thread::sleep(Duration::from_millis(20));
let state = self.state.clone();
let child = &mut self.child;
let mut exited = None;
let waited = dx_test_scratch::wait::watch_until(
&state.join("event"),
what,
Duration::from_secs(30),
|| {
exited = child.try_wait().ok().flatten();
done(&state) || exited.is_some()
},
);
if let Some(status) = exited.filter(|_| !done(&self.state)) {
panic!("dx exited ({status:?}) before {what}");
}
assert!(
waited.is_ok(),
"{waited:?}\n{}\nstate: {:?}",
self.stderr(),
fs::read_dir(&self.state).map(|dir| dir
.filter_map(Result::ok)
.map(|entry| entry.file_name())
.collect::<Vec<_>>())
);
}

fn stderr(&self) -> String {
Expand Down Expand Up @@ -178,17 +186,9 @@ fn ctrl_c_stops_the_watch(app_args: &str) {
.status()
.expect("helper runs");
assert!(sent.success(), "the Ctrl-C helper failed: {sent:?}");
let deadline = Instant::now() + Duration::from_secs(30);
let status = loop {
if let Some(status) = watch.child.try_wait().expect("wait for dx") {
break status;
}
assert!(
Instant::now() < deadline,
"dx did not stop\n{}",
watch.stderr()
);
std::thread::sleep(Duration::from_millis(20));
let stopped = dx_test_scratch::wait::child_exits(&mut watch.child, Duration::from_secs(30));
let Ok(status) = stopped else {
panic!("dx did not stop: {stopped:?}\n{}", watch.stderr());
};
assert_eq!(status.code(), Some(130), "{}", watch.stderr());
assert!(watch.stderr().contains("stopped"), "{}", watch.stderr());
Expand Down
28 changes: 10 additions & 18 deletions cli/cli/src/exec/error_boundary_launcher_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ use std::io::{BufRead, BufReader};
use std::os::unix::process::{CommandExt, ExitStatusExt};
use std::path::PathBuf;
use std::process::{Command, ExitStatus, Stdio};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use std::time::Duration;

const MODULE: &str = "module(name = \"acme_renamed\", version = \"1.2.3\")\nbazel_dep(name = \"rules_dx\", version = \"0.0.0\")\nbazel_dep(name = \"rules_dx_rust\", version = \"0.0.0\")\n";

Expand Down Expand Up @@ -226,11 +224,11 @@ impl Consumer {
.spawn()
.expect("dx starts");
let pgid = i32::try_from(child.id()).expect("pid fits i32");
let done = Arc::new(AtomicBool::new(false));
let watchdog = Arc::clone(&done);
let (done, watchdog) = std::sync::mpsc::channel::<()>();
std::thread::spawn(move || {
std::thread::sleep(Duration::from_secs(90));
if !watchdog.load(Ordering::SeqCst) {
if watchdog.recv_timeout(Duration::from_secs(90))
== Err(std::sync::mpsc::RecvTimeoutError::Timeout)
{
drop(dx_os_sys::process::signal(-pgid, SIGKILL));
}
});
Expand All @@ -245,15 +243,12 @@ impl Consumer {
break;
}
}
let deadline = Instant::now() + Duration::from_secs(20);
while !started.exists() {
assert!(Instant::now() < deadline, "bazel never reached the gate");
std::thread::sleep(Duration::from_millis(20));
}
let reached = dx_test_scratch::wait::path_appears(&started, Duration::from_secs(20));
assert!(reached.is_ok(), "bazel never reached the gate: {reached:?}");
hang_up(reader.into_inner(), &probe);
fs::write(self.base.join("bazel.log.gate"), "").expect("gate");
let output = child.wait_with_output().expect("dx stops");
done.store(true, Ordering::SeqCst);
drop(done.send(()));
drop(dx_os_sys::process::signal(-pgid, SIGKILL));
Outcome {
status: output.status,
Expand All @@ -273,11 +268,8 @@ impl Consumer {
.process_group(0)
.spawn()
.expect("dx starts");
let deadline = Instant::now() + Duration::from_secs(20);
while !started.exists() {
assert!(Instant::now() < deadline, "bazel never started");
std::thread::sleep(Duration::from_millis(20));
}
let reached = dx_test_scratch::wait::path_appears(&started, Duration::from_secs(20));
assert!(reached.is_ok(), "bazel never started: {reached:?}");
let pgid = i32::try_from(child.id()).expect("pid fits i32");
dx_os_sys::process::signal(-pgid, signo).expect("signal delivered");
let output = child.wait_with_output().expect("dx stops");
Expand Down
17 changes: 7 additions & 10 deletions cli/cli/src/exec/managed_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,20 +173,17 @@ mod tests {
"staging holds the generation lease so cleanup cannot prune mid-stage"
);
drop(lease);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while dx_atomic_fs::lease::shared_held(
let path = dx_atomic_fs::lease::lease_path(
&dx_path::state::local_dir(&workspace),
dx_atomic_fs::lease::GenerationUse::Environment,
id.as_str(),
)
.expect("reprobe")
{
assert!(
std::time::Instant::now() < deadline,
"releasing the staging lease makes the generation prunable again"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
.expect("lease path");
let freed = dx_test_scratch::wait::lock_free(&path, std::time::Duration::from_secs(5));
assert!(
freed.is_ok(),
"releasing the staging lease makes the generation prunable again: {freed:?}"
);
}

#[test]
Expand Down
Loading
Loading