diff --git a/apps/origin-ci/src/runner.rs b/apps/origin-ci/src/runner.rs index e0e426c1..11009d09 100644 --- a/apps/origin-ci/src/runner.rs +++ b/apps/origin-ci/src/runner.rs @@ -36,6 +36,7 @@ use std::fmt; use std::io::{self, Read}; use std::panic; use std::process::{Command, ExitStatus, Stdio}; +use std::sync::mpsc::{self, RecvTimeoutError}; use std::sync::{Arc, Mutex, PoisonError}; use std::thread; use std::time::{Duration, Instant}; @@ -491,8 +492,10 @@ impl Runner { /// exited and what `read` makes of the pipe `reader` reads. The pipe is /// read on a thread until the command exits and what it left running /// is stopped, which closes their copies of it: so nothing it left - /// running keeps the runner waiting, unless it escaped being stopped - /// (see [`state`](crate::state)). + /// running keeps the runner waiting. One that escaped being stopped + /// (see [`state`](crate::state)) and keeps the pipe open past + /// [`Checkout::GRACE`] fails the command, leaving the thread to it, + /// rather than give output it may have cut short. fn collect( checkout: &Checkout, shell: Command, @@ -504,12 +507,19 @@ impl Runner { // the pipe. let mut child = checkout.spawn(shell)?; let group = child.id(); - let output = thread::spawn(move || read(reader)); + let (sender, received) = mpsc::channel(); + // The receiver is gone if it gave up waiting. + let reading = thread::spawn(move || drop(sender.send(read(reader)))); let status = child.wait(); checkout.stop(group)?; - let output = output - .join() - .unwrap_or_else(|panic| panic::resume_unwind(panic)); + let output = match received.recv_timeout(Checkout::GRACE) { + Ok(output) => output, + Err(RecvTimeoutError::Timeout) => return Err(RunError::OutputHeld(kind.clone())), + // It panicked before sending. + Err(RecvTimeoutError::Disconnected) => { + panic::resume_unwind(reading.join().expect_err("the reader sent nothing")) + } + }; let failed = |source| RunError::command(kind, source); Ok((status.map_err(failed)?, output.map_err(failed)?)) } @@ -651,6 +661,10 @@ pub enum RunError { /// What went wrong. source: io::Error, }, + /// A process a command started escaped being stopped, and keeps its + /// output open. + #[error("a process the command of `{0}` started still holds its output open")] + OutputHeld(Kind), /// A toolchain command failed. #[error("the toolchain command of `{kind}`, `{command}`, failed: {status}")] Toolchain { @@ -690,3 +704,27 @@ impl RunError { } } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Something keeps a command's output open past the grace, as a + /// process that escaped being stopped would: the command fails, rather + /// than wait for it. + #[test] + fn a_command_never_waits_past_the_grace_for_its_output() { + let base = tempfile::tempdir().unwrap(); + let checkout = Checkout::empty(base.path()); + let (reader, writer) = io::pipe().unwrap(); + let mut shell = Runner::shell("true"); + shell.stdout(writer.try_clone().unwrap()); + let kind = Kind::new("ci.test").unwrap(); + let collected = Runner::collect(&checkout, shell, reader, Runner::read_output, &kind); + drop(writer); + assert!( + matches!(collected, Err(RunError::OutputHeld(_))), + "{collected:?}" + ); + } +} diff --git a/apps/origin-ci/src/state.rs b/apps/origin-ci/src/state.rs index f8a03ea9..39105629 100644 --- a/apps/origin-ci/src/state.rs +++ b/apps/origin-ci/src/state.rs @@ -21,7 +21,9 @@ //! the lock. Such a process escapes, and so does one that closed the files //! it inherited, as processes Python's `subprocess` starts do, and every //! leftover where the platform can't tell which files a group holds, as on -//! macOS: leaking a process beats killing someone else's. A command a +//! macOS: leaking a process beats killing someone else's. One that keeps +//! the lock fails the next command started in the checkout, which waits +//! for it only [`Checkout::GRACE`]. A command a //! worker killed with `kill -9` left running still runs until the next //! sweep: dying with the worker would need code run between `fork` and //! `exec`, which takes `unsafe`. @@ -38,6 +40,8 @@ use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; use std::process::{self, Child, Command}; use std::sync::atomic::{AtomicU64, Ordering}; +use std::thread; +use std::time::{Duration, Instant}; use origin_platform::{LockMode, LockedFile, Native, Processes}; use origin_shared::object::DecodeError; @@ -272,6 +276,10 @@ impl State { } impl Checkout { + /// How long the processes [`Checkout::stop`] killed may take to die, + /// releasing what they held: the lock, and the command's output. + pub const GRACE: Duration = Duration::from_secs(5); + /// The directory holding the files. #[must_use] pub fn path(&self) -> &Path { @@ -303,15 +311,27 @@ impl Checkout { /// Starts `command` in the checkout, in a process group of its own, /// which inherits the checkout's `held` file, locked: so its processes /// hold the lock while any of them lives (see the module). Commands - /// must start one at a time, as others would inherit it too. + /// must start one at a time, as others would inherit it too. It waits + /// up to [`Checkout::GRACE`] for the processes of the last command, + /// which [`Checkout::stop`] killed, to release the lock. /// /// # Errors /// - /// Fails if the lock or the group's file cannot be written, or the - /// command cannot be started. + /// Fails if a process of an earlier command, which escaped being + /// stopped, still holds the lock after that, if the lock or the group's + /// file cannot be written, or if the command cannot be started. pub fn spawn(&self, mut command: Command) -> Result { let path = self.held(); - let held = LockedFile::open(&self.platform, &path, LockMode::Exclusive)?; + let deadline = Instant::now() + Self::GRACE; + let held = loop { + if let Some(held) = LockedFile::try_open(&self.platform, &path, LockMode::Exclusive)? { + break held; + } + if Instant::now() >= deadline { + return Err(StateError::Held(path)); + } + thread::sleep(Duration::from_millis(10)); + }; self.platform .inherit(&held) .map_err(|source| StateError::io(&path, source))?; @@ -379,6 +399,25 @@ impl Checkout { } } +#[cfg(test)] +impl Checkout { + /// An empty snapshot checked out in a new state, kept in `base`. + pub(crate) fn empty(base: &Path) -> Self { + use origin_shared::Record; + + let url = RemoteUrl::parse(base.join("repo").to_str().unwrap()).unwrap(); + let state = State::new(base, &url).unwrap(); + let root = Tree::default().encode(); + let snapshot = Snapshot::new( + root.id().into(), + Pack { + objects: vec![root], + }, + ); + state.checkout(&snapshot).unwrap() + } +} + impl Drop for Checkout { fn drop(&mut self) { // Best effort: the next run sweeps what's left. @@ -400,6 +439,10 @@ pub enum StateError { /// What went wrong. source: io::Error, }, + /// A process an earlier command started escaped being stopped, and + /// still holds the checkout's lock. + #[error("a process an earlier command started still holds {}", .0.display())] + Held(PathBuf), /// A file holds something unexpected. #[error("{} is malformed", .0.display())] Malformed(PathBuf), @@ -432,8 +475,6 @@ impl StateError { mod tests { use std::process::Stdio; - use origin_shared::Record; - use super::*; /// A command's group ended, but a process it started in a session of @@ -442,16 +483,7 @@ mod tests { #[test] fn stopping_a_command_never_kills_a_group_that_took_its_number() { let base = tempfile::tempdir().unwrap(); - let url = RemoteUrl::parse(base.path().join("repo").to_str().unwrap()).unwrap(); - let state = State::new(base.path(), &url).unwrap(); - let root = Tree::default().encode(); - let snapshot = Snapshot::new( - root.id().into(), - Pack { - objects: vec![root], - }, - ); - let checkout = state.checkout(&snapshot).unwrap(); + let checkout = Checkout::empty(base.path()); let mut escaped = Command::new("sleep"); escaped.arg("60"); let mut escaped = checkout.spawn(escaped).unwrap(); @@ -473,4 +505,20 @@ mod tests { child.wait().unwrap(); } } + + /// A process of a command that escaped being stopped still holds the + /// lock: the next command fails once the grace is over, rather than + /// wait for it. + #[test] + fn a_command_never_waits_past_the_grace_for_one_that_escaped() { + let base = tempfile::tempdir().unwrap(); + let checkout = Checkout::empty(base.path()); + let mut escaped = Command::new("sleep"); + escaped.arg("60"); + let mut escaped = checkout.spawn(escaped).unwrap(); + let next = checkout.spawn(Command::new("true")); + escaped.kill().unwrap(); + escaped.wait().unwrap(); + assert!(matches!(next, Err(StateError::Held(_))), "{next:?}"); + } } diff --git a/apps/origin-ci/tests/ci.rs b/apps/origin-ci/tests/ci.rs index 81da6a91..ef89ca3c 100644 --- a/apps/origin-ci/tests/ci.rs +++ b/apps/origin-ci/tests/ci.rs @@ -622,17 +622,15 @@ fn checks_leave_nothing_running_once_they_end_or_their_run_is_killed() { // What a check leaves running is killed once it ends, without waiting // for it to close the output it holds; where the platform can't tell // which group still holds what it started, it escapes instead, and the - // run waits for it to close that output. + // check fails once it has held that output open a few seconds. check("sleep 60 & echo $! > {started}"); let ran = Instant::now(); let output = repo.run(repo.root(), &["ci", "run"]); - assert!(output.status.success()); - if Native::SEES_HELD_FILES { - assert!( - ran.elapsed() < Duration::from_secs(30), - "it waited for sleep" - ); - } + assert_eq!(output.status.success(), Native::SEES_HELD_FILES); + assert!( + ran.elapsed() < Duration::from_secs(30), + "it waited for sleep" + ); ended(&written(&started)); // A run killed while its check runs leaves it running, until the next