| 1 |
use std::{ |
| 2 |
cell::Cell, |
| 3 |
io::{self, Write as _}, |
| 4 |
process::{Child, Command}, |
| 5 |
}; |
| 6 |
|
| 7 |
use crate::{ |
| 8 |
parallel::{ |
| 9 |
async_executor::{block_on, YieldOnce}, |
| 10 |
job_token, |
| 11 |
}, |
| 12 |
spawn, CargoOutput, Error, ErrorKind, StderrForwarder, |
| 13 |
}; |
| 14 |
|
| 15 |
struct KillOnDrop(Child, StderrForwarder); |
| 16 |
|
| 17 |
impl Drop for KillOnDrop { |
| 18 |
fn drop(&mut self) { |
| 19 |
let child = &mut self.0; |
| 20 |
|
| 21 |
child.kill().ok(); |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
fn cell_update<T, F>(cell: &Cell<T>, f: F) |
| 26 |
where |
| 27 |
T: Default, |
| 28 |
F: FnOnce(T) -> T, |
| 29 |
{ |
| 30 |
let old = cell.take(); |
| 31 |
let new = f(old); |
| 32 |
cell.set(new); |
| 33 |
} |
| 34 |
|
| 35 |
fn try_wait_on_child( |
| 36 |
cmd: &Command, |
| 37 |
child: &mut Child, |
| 38 |
mut stdout: impl io::Write, |
| 39 |
stderr_forwarder: &mut StderrForwarder, |
| 40 |
) -> Result<Option<()>, Error> { |
| 41 |
stderr_forwarder.forward_available(); |
| 42 |
|
| 43 |
match child.try_wait() { |
| 44 |
Ok(Some(status)) => { |
| 45 |
stderr_forwarder.forward_all(); |
| 46 |
|
| 47 |
let _ = writeln!(stdout, "{}", status); |
| 48 |
|
| 49 |
if status.success() { |
| 50 |
Ok(Some(())) |
| 51 |
} else { |
| 52 |
Err(Error::new( |
| 53 |
ErrorKind::ToolExecError, |
| 54 |
format!("command did not execute successfully (status code {status}): {cmd:?}"), |
| 55 |
)) |
| 56 |
} |
| 57 |
} |
| 58 |
Ok(None) => Ok(None), |
| 59 |
Err(e) => { |
| 60 |
stderr_forwarder.forward_all(); |
| 61 |
Err(Error::new( |
| 62 |
ErrorKind::ToolExecError, |
| 63 |
format!("failed to wait on spawned child process `{cmd:?}`: {e}"), |
| 64 |
)) |
| 65 |
} |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
pub(crate) fn run_commands_in_parallel( |
| 70 |
cargo_output: &CargoOutput, |
| 71 |
cmds: &mut dyn Iterator<Item = Result<Command, Error>>, |
| 72 |
) -> Result<(), Error> { |
| 73 |
// Limit our parallelism globally with a jobserver. |
| 74 |
let mut tokens = job_token::ActiveJobTokenServer::new(); |
| 75 |
|
| 76 |
// When compiling objects in parallel we do a few dirty tricks to speed |
| 77 |
// things up: |
| 78 |
// |
| 79 |
// * First is that we use the `jobserver` crate to limit the parallelism |
| 80 |
// of this build script. The `jobserver` crate will use a jobserver |
| 81 |
// configured by Cargo for build scripts to ensure that parallelism is |
| 82 |
// coordinated across C compilations and Rust compilations. Before we |
| 83 |
// compile anything we make sure to wait until we acquire a token. |
| 84 |
// |
| 85 |
// Note that this jobserver is cached globally so we only used one per |
| 86 |
// process and only worry about creating it once. |
| 87 |
// |
| 88 |
// * Next we use spawn the process to actually compile objects in |
| 89 |
// parallel after we've acquired a token to perform some work |
| 90 |
// |
| 91 |
// With all that in mind we compile all objects in a loop here, after we |
| 92 |
// acquire the appropriate tokens, Once all objects have been compiled |
| 93 |
// we wait on all the processes and propagate the results of compilation. |
| 94 |
|
| 95 |
let pendings = Cell::new(Vec::<(Command, KillOnDrop, job_token::JobToken)>::new()); |
| 96 |
let is_disconnected = Cell::new(false); |
| 97 |
let has_made_progress = Cell::new(false); |
| 98 |
|
| 99 |
let wait_future = async { |
| 100 |
let mut error = None; |
| 101 |
// Buffer the stdout |
| 102 |
let mut stdout = io::BufWriter::with_capacity(128, io::stdout()); |
| 103 |
|
| 104 |
loop { |
| 105 |
// If the other end of the pipe is already disconnected, then we're not gonna get any new jobs, |
| 106 |
// so it doesn't make sense to reuse the tokens; in fact, |
| 107 |
// releasing them as soon as possible (once we know that the other end is disconnected) is beneficial. |
| 108 |
// Imagine that the last file built takes an hour to finish; in this scenario, |
| 109 |
// by not releasing the tokens before that last file is done we would effectively block other processes from |
| 110 |
// starting sooner - even though we only need one token for that last file, not N others that were acquired. |
| 111 |
|
| 112 |
let mut pendings_is_empty = false; |
| 113 |
|
| 114 |
cell_update(&pendings, |mut pendings| { |
| 115 |
// Try waiting on them. |
| 116 |
pendings.retain_mut(|(cmd, child, _token)| { |
| 117 |
match try_wait_on_child(cmd, &mut child.0, &mut stdout, &mut child.1) { |
| 118 |
Ok(Some(())) => { |
| 119 |
// Task done, remove the entry |
| 120 |
has_made_progress.set(true); |
| 121 |
false |
| 122 |
} |
| 123 |
Ok(None) => true, // Task still not finished, keep the entry |
| 124 |
Err(err) => { |
| 125 |
// Task fail, remove the entry. |
| 126 |
// Since we can only return one error, log the error to make |
| 127 |
// sure users always see all the compilation failures. |
| 128 |
has_made_progress.set(true); |
| 129 |
|
| 130 |
if cargo_output.warnings { |
| 131 |
let _ = writeln!(stdout, "cargo:warning={}", err); |
| 132 |
} |
| 133 |
error = Some(err); |
| 134 |
|
| 135 |
false |
| 136 |
} |
| 137 |
} |
| 138 |
}); |
| 139 |
pendings_is_empty = pendings.is_empty(); |
| 140 |
pendings |
| 141 |
}); |
| 142 |
|
| 143 |
if pendings_is_empty && is_disconnected.get() { |
| 144 |
break if let Some(err) = error { |
| 145 |
Err(err) |
| 146 |
} else { |
| 147 |
Ok(()) |
| 148 |
}; |
| 149 |
} |
| 150 |
|
| 151 |
YieldOnce::default().await; |
| 152 |
} |
| 153 |
}; |
| 154 |
let spawn_future = async { |
| 155 |
for res in cmds { |
| 156 |
let mut cmd = res?; |
| 157 |
let token = tokens.acquire().await?; |
| 158 |
let mut child = spawn(&mut cmd, cargo_output)?; |
| 159 |
let mut stderr_forwarder = StderrForwarder::new(&mut child); |
| 160 |
stderr_forwarder.set_non_blocking()?; |
| 161 |
|
| 162 |
cell_update(&pendings, |mut pendings| { |
| 163 |
pendings.push((cmd, KillOnDrop(child, stderr_forwarder), token)); |
| 164 |
pendings |
| 165 |
}); |
| 166 |
|
| 167 |
has_made_progress.set(true); |
| 168 |
} |
| 169 |
is_disconnected.set(true); |
| 170 |
|
| 171 |
Ok::<_, Error>(()) |
| 172 |
}; |
| 173 |
|
| 174 |
block_on(wait_future, spawn_future, &has_made_progress) |
| 175 |
} |