diff --git a/Cargo.toml b/Cargo.toml index 21bcc8005d..df22a72c5c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -108,6 +108,7 @@ tokio = { version = "1", features = [ "net", "process", "macros", + "sync", ] } tokio-serde = "0.9" tokio-util = { version = "0.7.18", features = ["codec", "io", "rt"] } diff --git a/src/jobserver.rs b/src/jobserver.rs index ba3c3cd78b..1fd9b2c35a 100644 --- a/src/jobserver.rs +++ b/src/jobserver.rs @@ -1,10 +1,11 @@ use std::io; -use std::process::Command; +use std::process::{Command, ExitStatus}; use std::sync::Arc; use futures::StreamExt; use futures::channel::mpsc; use futures::channel::oneshot; +use tokio::sync::{OwnedSemaphorePermit, Semaphore, watch}; use crate::errors::*; @@ -35,14 +36,48 @@ use crate::errors::*; #[derive(Clone)] pub struct Client { - helper: Option>, - tx: Option>>>, + fifo: Option, + current: Option>>>, + // Caps our children across pool replacements, while older pools drain. + slots: Option>, + limit: usize, +} + +struct Pool { + // Close the sender before joining a helper waiting for a request. + tx: mpsc::UnboundedSender>>, + helper: jobserver::HelperThread, inner: jobserver::Client, - fifo: bool, } pub struct Acquired { _token: Option, + pool: Option>, + client: Client, + shared: bool, + exited_on_its_own: bool, + _slot: Option, +} + +impl Pool { + fn new(num: usize) -> Result { + let inner = jobserver::Client::new(num).context("failed to create jobserver")?; + let (tx, mut rx) = mpsc::unbounded::>(); + let helper = inner + .clone() + .into_helper_thread(move |token| { + let rt = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap(); + rt.block_on(async { + if let Some(sender) = rx.next().await { + drop(sender.send(token)); + } + }); + }) + .context("failed to spawn jobserver helper thread")?; + Ok(Pool { tx, helper, inner }) + } } impl Client { @@ -63,52 +98,28 @@ impl Client { // SAFETY: a `fifo:` jobserver is opened by path; no inherited file // descriptors are taken over. let inner = unsafe { jobserver::Client::from_env() }?; - Some(Client::_new(inner, true)) + Some(Client { + fifo: Some(inner), + current: None, + slots: None, + limit: 0, + }) } pub fn new_num(num: usize) -> Client { - let inner = jobserver::Client::new(num).expect("failed to create jobserver"); - Client::_new(inner, false) - } - - fn _new(inner: jobserver::Client, fifo: bool) -> Client { - let (helper, tx) = if fifo { - (None, None) - } else { - let (tx, mut rx) = mpsc::unbounded::>(); - let helper = inner - .clone() - .into_helper_thread(move |token| { - let rt = tokio::runtime::Builder::new_current_thread() - .build() - .unwrap(); - rt.block_on(async { - if let Some(sender) = rx.next().await { - drop(sender.send(token)); - } - }); - }) - .expect("failed to spawn helper thread"); - (Some(Arc::new(helper)), Some(tx)) - }; - + let pool = Pool::new(num).expect("failed to create jobserver"); Client { - inner, - helper, - tx, - fifo, + fifo: None, + current: Some(Arc::new(watch::Sender::new(Arc::new(pool)))), + slots: Some(Arc::new(Semaphore::new(num))), + limit: num, } } /// Whether this is the build's own jobserver, opened by path (see /// [`Client::from_env_fifo`]), rather than a private pool. pub fn is_fifo(&self) -> bool { - self.fifo - } - - /// Configures this jobserver to be inherited by the specified command - pub fn configure(&self, cmd: &mut Command) { - self.inner.configure(cmd); + self.fifo.is_some() } /// Returns a future that represents an acquired jobserver token. @@ -117,22 +128,112 @@ impl Client { /// definition of "work" is) to ensure that the system is properly /// rate-limiting itself. pub async fn acquire(&self) -> Result { - let (helper, tx) = match (self.helper.as_ref(), self.tx.as_ref()) { - (Some(a), Some(b)) => (a, b), - _ => return Ok(Acquired { _token: None }), + let (Some(current), Some(slots)) = (&self.current, &self.slots) else { + return Ok(Acquired { + _token: None, + pool: None, + client: self.clone(), + shared: false, + exited_on_its_own: false, + _slot: None, + }); }; - let (mytx, myrx) = oneshot::channel(); - helper.request_token(); - tx.unbounded_send(mytx).unwrap(); - - let acquired = myrx + let slot = slots + .clone() + .acquire_owned() .await - .context("jobserver helper panicked")? - .context("failed to acquire jobserver token")?; + .context("jobserver slots closed")?; + let mut current = current.subscribe(); + loop { + let pool = current.borrow_and_update().clone(); + let (mytx, myrx) = oneshot::channel(); + pool.tx.unbounded_send(mytx).unwrap(); + pool.helper.request_token(); + tokio::select! { + acquired = myrx => { + let acquired = acquired + .context("jobserver helper panicked")? + .context("failed to acquire jobserver token")?; + if !Arc::ptr_eq(&pool, ¤t.borrow()) { + continue; + } + return Ok(Acquired { + _token: Some(acquired), + pool: Some(pool), + client: self.clone(), + shared: false, + exited_on_its_own: false, + _slot: Some(slot), + }); + } + // A retired pool may never get another token. + _ = current.changed() => {} + } + } + } - Ok(Acquired { - _token: Some(acquired), - }) + fn retire(&self, pool: &Arc) { + if let Some(current) = &self.current { + current.send_if_modified(|current| { + if !Arc::ptr_eq(current, pool) { + return false; + } + match Pool::new(self.limit) { + Ok(fresh) => { + warn!("A compiler sharing the jobserver did not exit on its own; using a fresh token pool"); + *current = Arc::new(fresh); + true + } + Err(e) => { + warn!("Keeping a jobserver that may have lost tokens: {e:?}"); + false + } + } + }); + } + } + + #[cfg(test)] + pub(crate) fn watch_pool(&self) -> impl Fn() -> bool { + let rx = self.current.as_ref().expect("private pool").subscribe(); + move || rx.has_changed().unwrap_or(false) + } +} + +impl Acquired { + pub fn configure(&self, cmd: &mut Command) { + if let Some(pool) = &self.pool { + pool.inner.configure(cmd); + } else if let Some(fifo) = &self.client.fifo { + fifo.configure(cmd); + } + } + + pub fn mark_shared(&mut self) { + if self.pool.is_some() { + self.shared = true; + } + } + + pub fn record_exit(&mut self, status: Option<&ExitStatus>) { + #[cfg(unix)] + let on_its_own = + status.is_some_and(|s| std::os::unix::process::ExitStatusExt::signal(s).is_none()); + #[cfg(not(unix))] + let on_its_own = status.is_some(); + self.exited_on_its_own = on_its_own; + } +} + +impl Drop for Acquired { + fn drop(&mut self) { + // A killed compiler may have taken tokens directly from the pipe. + if self.shared + && !self.exited_on_its_own + && let Some(pool) = &self.pool + { + self.client.retire(pool); + } } } diff --git a/src/mock_command.rs b/src/mock_command.rs index ffa19d5b96..b4976237a5 100644 --- a/src/mock_command.rs +++ b/src/mock_command.rs @@ -178,17 +178,20 @@ impl CommandChild for Child { } async fn wait(self) -> io::Result { - let Child { mut inner, token } = self; - inner.wait().await.inspect(|_ret| { - drop(token); - }) + let Child { + mut inner, + mut token, + } = self; + let ret = inner.wait().await; + token.record_exit(ret.as_ref().ok()); + ret } async fn wait_with_output(self) -> io::Result { - let Child { inner, token } = self; - inner.wait_with_output().await.inspect(|_ret| { - drop(token); - }) + let Child { inner, mut token } = self; + let ret = inner.wait_with_output().await; + token.record_exit(ret.as_ref().ok().map(|o| &o.status)); + ret } } @@ -297,10 +300,13 @@ impl RunCommand for AsyncCommand { } async fn spawn(&mut self) -> Result { let mut inner = self.inner.take().unwrap(); + // The token rate-limits our children, independently of sharing the pool. + let mut token = self.jobserver.acquire().await?; // If the build that asked for this compile named its jobserver by // path, the child keeps it and opens it the way it would have without // sccache, so it stays within that build's (or a system-wide) limit // instead of getting our private pool. + let mut shared = false; if !(self.share_jobserver && names_fifo_jobserver(&inner)) { inner.env_remove("MAKEFLAGS"); inner.env_remove("MFLAGS"); @@ -312,19 +318,19 @@ impl RunCommand for AsyncCommand { // probes and C/C++ compilers all ignore it -- so the default is // not to share, and the callers that spawn `rustc` ask for it. if self.share_jobserver { - self.jobserver.configure(&mut inner); + token.configure(&mut inner); + shared = true; } } - // The token is acquired either way: it rate-limits how many children - // *we* run, which is separate from whether the child can acquire - // tokens of its own. - let token = self.jobserver.acquire().await?; let mut inner = tokio::process::Command::from(inner); let child = inner .kill_on_drop(true) .spawn() .with_context(|| format!("failed to spawn {:?}", inner))?; + if shared { + token.mark_shared(); + } Ok(Child { inner: child, @@ -854,4 +860,85 @@ mod test { ("MAKEFLAGS", "--jobserver-auth=fifo:/dev/x"), ])); } + + #[cfg(target_os = "linux")] + const LEAK_TOKEN_AND_SIGKILL: &str = r#"a=${CARGO_MAKEFLAGS##*--jobserver-auth=}; [ "$(head -c1 /proc/self/fd/${a%,*} | wc -c)" -eq 1 ] && kill -9 $$"#; + + #[test] + #[cfg(target_os = "linux")] + fn killed_child_does_not_leak_jobserver_tokens() { + use std::os::unix::process::ExitStatusExt; + let runtime = tokio::runtime::Runtime::new().unwrap(); + runtime.block_on(async { + let client = Client::new_num(2); + let mut creator = ::new(&client); + let mut cmd = creator.new_command("/bin/sh"); + cmd.args(&["-c", LEAK_TOKEN_AND_SIGKILL]); + cmd.share_jobserver(); + let timeout = std::time::Duration::from_secs(10); + let child = async { cmd.spawn().await.unwrap().wait().await.unwrap() }; + let status = tokio::time::timeout(timeout, child) + .await + .expect("the child never got a token"); + assert_eq!(status.signal(), Some(9)); + let both = async { (client.acquire().await, client.acquire().await) }; + let (a, b) = tokio::time::timeout(timeout, both) + .await + .expect("the killed child's token was never replaced"); + a.unwrap(); + b.unwrap(); + }); + } + + #[test] + #[cfg(target_os = "linux")] + fn replaced_pool_keeps_the_child_limit() { + let runtime = tokio::runtime::Runtime::new().unwrap(); + runtime.block_on(async { + let client = Client::new_num(3); + let mut creator = ::new(&client); + let mut hold = creator.new_command("/bin/sh"); + hold.args(&["-c", "sleep 30"]); + let hold = hold.spawn().await.unwrap(); + let mut victim = creator.new_command("/bin/sh"); + victim.args(&["-c", LEAK_TOKEN_AND_SIGKILL]); + victim.share_jobserver(); + let timeout = std::time::Duration::from_secs(10); + let victim = async { victim.spawn().await.unwrap().wait().await.unwrap() }; + tokio::time::timeout(timeout, victim).await.unwrap(); + let free = async { (client.acquire().await, client.acquire().await) }; + let (a, b) = tokio::time::timeout(timeout, free).await.unwrap(); + let _held = (a.unwrap(), b.unwrap()); + let over = + tokio::time::timeout(std::time::Duration::from_millis(200), client.acquire()); + assert!( + over.await.is_err(), + "a fresh pool ignored the running child" + ); + drop(hold); + tokio::time::timeout(timeout, client.acquire()) + .await + .unwrap() + .unwrap(); + }); + } + + #[test] + fn failed_spawn_does_not_retire_jobserver_pool() { + let runtime = tokio::runtime::Runtime::new().unwrap(); + runtime.block_on(async { + let client = Client::new_num(1); + let pool_replaced = client.watch_pool(); + let mut creator = ::new(&client); + let tempdir = tempfile::tempdir().unwrap(); + let mut cmd = creator.new_command(tempdir.path().join("no-such-binary")); + cmd.share_jobserver(); + assert!(cmd.spawn().await.is_err()); + assert!( + !pool_replaced(), + "a failed spawn should not retire the jobserver pool" + ); + client.acquire().await.unwrap(); + }); + } }