| 1 |
//! An implementation of the GNU make jobserver. |
| 2 |
//! |
| 3 |
//! This crate is an implementation, in Rust, of the GNU `make` jobserver for |
| 4 |
//! CLI tools that are interoperating with make or otherwise require some form |
| 5 |
//! of parallelism limiting across process boundaries. This was originally |
| 6 |
//! written for usage in Cargo to both (a) work when `cargo` is invoked from |
| 7 |
//! `make` (using `make`'s jobserver) and (b) work when `cargo` invokes build |
| 8 |
//! scripts, exporting a jobserver implementation for `make` processes to |
| 9 |
//! transitively use. |
| 10 |
//! |
| 11 |
//! The jobserver implementation can be found in [detail online][docs] but |
| 12 |
//! basically boils down to a cross-process semaphore. On Unix this is |
| 13 |
//! implemented with the `pipe` syscall and read/write ends of a pipe and on |
| 14 |
//! Windows this is implemented literally with IPC semaphores. Starting from |
| 15 |
//! GNU `make` version 4.4, named pipe becomes the default way in communication |
| 16 |
//! on Unix. This crate also supports that feature in the sense of inheriting |
| 17 |
//! and forwarding the correct environment. |
| 18 |
//! |
| 19 |
//! The jobserver protocol in `make` also dictates when tokens are acquired to |
| 20 |
//! run child work, and clients using this crate should take care to implement |
| 21 |
//! such details to ensure correct interoperation with `make` itself. |
| 22 |
//! |
| 23 |
//! ## Examples |
| 24 |
//! |
| 25 |
//! Connect to a jobserver that was set up by `make` or a different process: |
| 26 |
//! |
| 27 |
//! ```no_run |
| 28 |
//! use jobserver::Client; |
| 29 |
//! |
| 30 |
//! // See API documentation for why this is `unsafe` |
| 31 |
//! let client = match unsafe { Client::from_env() } { |
| 32 |
//! Some(client) => client, |
| 33 |
//! None => panic!("client not configured"), |
| 34 |
//! }; |
| 35 |
//! ``` |
| 36 |
//! |
| 37 |
//! Acquire and release token from a jobserver: |
| 38 |
//! |
| 39 |
//! ```no_run |
| 40 |
//! use jobserver::Client; |
| 41 |
//! |
| 42 |
//! let client = unsafe { Client::from_env().unwrap() }; |
| 43 |
//! let token = client.acquire().unwrap(); // blocks until it is available |
| 44 |
//! drop(token); // releases the token when the work is done |
| 45 |
//! ``` |
| 46 |
//! |
| 47 |
//! Create a new jobserver and configure a child process to have access: |
| 48 |
//! |
| 49 |
//! ``` |
| 50 |
//! use std::process::Command; |
| 51 |
//! use jobserver::Client; |
| 52 |
//! |
| 53 |
//! let client = Client::new(4).expect("failed to create jobserver"); |
| 54 |
//! let mut cmd = Command::new("make"); |
| 55 |
//! client.configure(&mut cmd); |
| 56 |
//! ``` |
| 57 |
//! |
| 58 |
//! ## Caveats |
| 59 |
//! |
| 60 |
//! This crate makes no attempt to release tokens back to a jobserver on |
| 61 |
//! abnormal exit of a process. If a process which acquires a token is killed |
| 62 |
//! with ctrl-c or some similar signal then tokens will not be released and the |
| 63 |
//! jobserver may be in a corrupt state. |
| 64 |
//! |
| 65 |
//! Note that this is typically ok as ctrl-c means that an entire build process |
| 66 |
//! is being torn down, but it's worth being aware of at least! |
| 67 |
//! |
| 68 |
//! ## Windows caveats |
| 69 |
//! |
| 70 |
//! There appear to be two implementations of `make` on Windows. On MSYS2 one |
| 71 |
//! typically comes as `mingw32-make` and the other as `make` itself. I'm not |
| 72 |
//! personally too familiar with what's going on here, but for jobserver-related |
| 73 |
//! information the `mingw32-make` implementation uses Windows semaphores |
| 74 |
//! whereas the `make` program does not. The `make` program appears to use file |
| 75 |
//! descriptors and I'm not really sure how it works, so this crate is not |
| 76 |
//! compatible with `make` on Windows. It is, however, compatible with |
| 77 |
//! `mingw32-make`. |
| 78 |
//! |
| 79 |
//! [docs]: https://make.mad-scientist.net/papers/jobserver-implementation/ |
| 80 |
|
| 81 |
#![deny(missing_docs, missing_debug_implementations)] |
| 82 |
#![doc(html_root_url = "https://docs.rs/jobserver/0.1")] |
| 83 |
|
| 84 |
use std::env; |
| 85 |
use std::ffi::OsString; |
| 86 |
use std::io; |
| 87 |
use std::process::Command; |
| 88 |
use std::sync::{Arc, Condvar, Mutex, MutexGuard}; |
| 89 |
|
| 90 |
mod error; |
| 91 |
#[cfg(unix)] |
| 92 |
#[path = "unix.rs"] |
| 93 |
mod imp; |
| 94 |
#[cfg(windows)] |
| 95 |
#[path = "windows.rs"] |
| 96 |
mod imp; |
| 97 |
#[cfg(not(any(unix, windows)))] |
| 98 |
#[path = "wasm.rs"] |
| 99 |
mod imp; |
| 100 |
|
| 101 |
/// A client of a jobserver |
| 102 |
/// |
| 103 |
/// This structure is the main type exposed by this library, and is where |
| 104 |
/// interaction to a jobserver is configured through. Clients are either created |
| 105 |
/// from scratch in which case the internal semphore is initialied on the spot, |
| 106 |
/// or a client is created from the environment to connect to a jobserver |
| 107 |
/// already created. |
| 108 |
/// |
| 109 |
/// Some usage examples can be found in the crate documentation for using a |
| 110 |
/// client. |
| 111 |
/// |
| 112 |
/// Note that a [`Client`] implements the [`Clone`] trait, and all instances of |
| 113 |
/// a [`Client`] refer to the same jobserver instance. |
| 114 |
#[derive(Clone, Debug)] |
| 115 |
pub struct Client { |
| 116 |
inner: Arc<imp::Client>, |
| 117 |
} |
| 118 |
|
| 119 |
/// An acquired token from a jobserver. |
| 120 |
/// |
| 121 |
/// This token will be released back to the jobserver when it is dropped and |
| 122 |
/// otherwise represents the ability to spawn off another thread of work. |
| 123 |
#[derive(Debug)] |
| 124 |
pub struct Acquired { |
| 125 |
client: Arc<imp::Client>, |
| 126 |
data: imp::Acquired, |
| 127 |
disabled: bool, |
| 128 |
} |
| 129 |
|
| 130 |
impl Acquired { |
| 131 |
/// This drops the [`Acquired`] token without releasing the associated token. |
| 132 |
/// |
| 133 |
/// This is not generally useful, but can be helpful if you do not have the |
| 134 |
/// ability to store an Acquired token but need to not yet release it. |
| 135 |
/// |
| 136 |
/// You'll typically want to follow this up with a call to |
| 137 |
/// [`Client::release_raw`] or similar to actually release the token later on. |
| 138 |
pub fn drop_without_releasing(mut self) { |
| 139 |
self.disabled = true; |
| 140 |
} |
| 141 |
} |
| 142 |
|
| 143 |
#[derive(Default, Debug)] |
| 144 |
struct HelperState { |
| 145 |
lock: Mutex<HelperInner>, |
| 146 |
cvar: Condvar, |
| 147 |
} |
| 148 |
|
| 149 |
#[derive(Default, Debug)] |
| 150 |
struct HelperInner { |
| 151 |
requests: usize, |
| 152 |
producer_done: bool, |
| 153 |
consumer_done: bool, |
| 154 |
} |
| 155 |
|
| 156 |
use error::FromEnvErrorInner; |
| 157 |
pub use error::{FromEnvError, FromEnvErrorKind}; |
| 158 |
|
| 159 |
/// Return type for [`Client::from_env_ext`] function. |
| 160 |
#[derive(Debug)] |
| 161 |
pub struct FromEnv { |
| 162 |
/// Result of trying to get jobserver client from env. |
| 163 |
pub client: Result<Client, FromEnvError>, |
| 164 |
/// Name and value of the environment variable. |
| 165 |
/// `None` if no relevant environment variable is found. |
| 166 |
pub var: Option<(&'static str, OsString)>, |
| 167 |
} |
| 168 |
|
| 169 |
impl FromEnv { |
| 170 |
fn new_ok(client: Client, var_name: &'static str, var_value: OsString) -> FromEnv { |
| 171 |
FromEnv { |
| 172 |
client: Ok(client), |
| 173 |
var: Some((var_name, var_value)), |
| 174 |
} |
| 175 |
} |
| 176 |
fn new_err(kind: FromEnvErrorInner, var_name: &'static str, var_value: OsString) -> FromEnv { |
| 177 |
FromEnv { |
| 178 |
client: Err(FromEnvError { inner: kind }), |
| 179 |
var: Some((var_name, var_value)), |
| 180 |
} |
| 181 |
} |
| 182 |
} |
| 183 |
|
| 184 |
impl Client { |
| 185 |
/// Creates a new jobserver initialized with the given parallelism limit. |
| 186 |
/// |
| 187 |
/// A client to the jobserver created will be returned. This client will |
| 188 |
/// allow at most `limit` tokens to be acquired from it in parallel. More |
| 189 |
/// calls to [`Client::acquire`] will cause the calling thread to block. |
| 190 |
/// |
| 191 |
/// Note that the created [`Client`] is not automatically inherited into |
| 192 |
/// spawned child processes from this program. Manual usage of the |
| 193 |
/// [`Client::configure`] function is required for a child process to have |
| 194 |
/// access to a job server. |
| 195 |
/// |
| 196 |
/// # Examples |
| 197 |
/// |
| 198 |
/// ``` |
| 199 |
/// use jobserver::Client; |
| 200 |
/// |
| 201 |
/// let client = Client::new(4).expect("failed to create jobserver"); |
| 202 |
/// ``` |
| 203 |
/// |
| 204 |
/// # Errors |
| 205 |
/// |
| 206 |
/// Returns an error if any I/O error happens when attempting to create the |
| 207 |
/// jobserver client. |
| 208 |
pub fn new(limit: usize) -> io::Result<Client> { |
| 209 |
Ok(Client { |
| 210 |
inner: Arc::new(imp::Client::new(limit)?), |
| 211 |
}) |
| 212 |
} |
| 213 |
|
| 214 |
/// Attempts to connect to the jobserver specified in this process's |
| 215 |
/// environment. |
| 216 |
/// |
| 217 |
/// When the a `make` executable calls a child process it will configure the |
| 218 |
/// environment of the child to ensure that it has handles to the jobserver |
| 219 |
/// it's passing down. This function will attempt to look for these details |
| 220 |
/// and connect to the jobserver. |
| 221 |
/// |
| 222 |
/// Note that the created [`Client`] is not automatically inherited into |
| 223 |
/// spawned child processes from this program. Manual usage of the |
| 224 |
/// [`Client::configure`] function is required for a child process to have |
| 225 |
/// access to a job server. |
| 226 |
/// |
| 227 |
/// # Return value |
| 228 |
/// |
| 229 |
/// [`FromEnv`] contains result and relevant environment variable. |
| 230 |
/// If a jobserver was found in the environment and it looks correct then |
| 231 |
/// result with the connected client will be returned. In other cases |
| 232 |
/// result will contain `Err(FromEnvErr)`. |
| 233 |
/// |
| 234 |
/// Additionally on Unix this function will configure the file descriptors |
| 235 |
/// with `CLOEXEC` so they're not automatically inherited by spawned |
| 236 |
/// children. |
| 237 |
/// |
| 238 |
/// On unix if `check_pipe` enabled this function will check if provided |
| 239 |
/// files are actually pipes. |
| 240 |
/// |
| 241 |
/// # Safety |
| 242 |
/// |
| 243 |
/// This function is `unsafe` to call on Unix specifically as it |
| 244 |
/// transitively requires usage of the `from_raw_fd` function, which is |
| 245 |
/// itself unsafe in some circumstances. |
| 246 |
/// |
| 247 |
/// It's recommended to call this function very early in the lifetime of a |
| 248 |
/// program before any other file descriptors are opened. That way you can |
| 249 |
/// make sure to take ownership properly of the file descriptors passed |
| 250 |
/// down, if any. |
| 251 |
/// |
| 252 |
/// It is ok to call this function any number of times. |
| 253 |
pub unsafe fn from_env_ext(check_pipe: bool) -> FromEnv { |
| 254 |
let (env, var_os) = match ["CARGO_MAKEFLAGS", "MAKEFLAGS", "MFLAGS"] |
| 255 |
.iter() |
| 256 |
.map(|&env| env::var_os(env).map(|var| (env, var))) |
| 257 |
.find_map(|p| p) |
| 258 |
{ |
| 259 |
Some((env, var_os)) => (env, var_os), |
| 260 |
None => return FromEnv::new_err(FromEnvErrorInner::NoEnvVar, "", Default::default()), |
| 261 |
}; |
| 262 |
|
| 263 |
let var = match var_os.to_str() { |
| 264 |
Some(var) => var, |
| 265 |
None => { |
| 266 |
let err = FromEnvErrorInner::CannotParse("not valid UTF-8".to_string()); |
| 267 |
return FromEnv::new_err(err, env, var_os); |
| 268 |
} |
| 269 |
}; |
| 270 |
|
| 271 |
let s = match find_jobserver_auth(var) { |
| 272 |
Some(s) => s, |
| 273 |
None => return FromEnv::new_err(FromEnvErrorInner::NoJobserver, env, var_os), |
| 274 |
}; |
| 275 |
match imp::Client::open(s, check_pipe) { |
| 276 |
Ok(c) => FromEnv::new_ok(Client { inner: Arc::new(c) }, env, var_os), |
| 277 |
Err(err) => FromEnv::new_err(err, env, var_os), |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
/// Attempts to connect to the jobserver specified in this process's |
| 282 |
/// environment. |
| 283 |
/// |
| 284 |
/// Wraps [`Client::from_env_ext`] and discards error details. |
| 285 |
/// |
| 286 |
/// # Safety |
| 287 |
/// |
| 288 |
/// This function is `unsafe` to call on Unix specifically as it |
| 289 |
/// transitively requires usage of the `from_raw_fd` function, which is |
| 290 |
/// itself unsafe in some circumstances. |
| 291 |
/// |
| 292 |
/// It's recommended to call this function very early in the lifetime of a |
| 293 |
/// program before any other file descriptors are opened. That way you can |
| 294 |
/// make sure to take ownership properly of the file descriptors passed |
| 295 |
/// down, if any. |
| 296 |
/// |
| 297 |
/// It is ok to call this function any number of times. |
| 298 |
pub unsafe fn from_env() -> Option<Client> { |
| 299 |
Self::from_env_ext(false).client.ok() |
| 300 |
} |
| 301 |
|
| 302 |
/// Acquires a token from this jobserver client. |
| 303 |
/// |
| 304 |
/// This function will block the calling thread until a new token can be |
| 305 |
/// acquired from the jobserver. |
| 306 |
/// |
| 307 |
/// # Return value |
| 308 |
/// |
| 309 |
/// On successful acquisition of a token an instance of [`Acquired`] is |
| 310 |
/// returned. This structure, when dropped, will release the token back to |
| 311 |
/// the jobserver. It's recommended to avoid leaking this value. |
| 312 |
/// |
| 313 |
/// # Errors |
| 314 |
/// |
| 315 |
/// If an I/O error happens while acquiring a token then this function will |
| 316 |
/// return immediately with the error. If an error is returned then a token |
| 317 |
/// was not acquired. |
| 318 |
pub fn acquire(&self) -> io::Result<Acquired> { |
| 319 |
let data = self.inner.acquire()?; |
| 320 |
Ok(Acquired { |
| 321 |
client: self.inner.clone(), |
| 322 |
data, |
| 323 |
disabled: false, |
| 324 |
}) |
| 325 |
} |
| 326 |
|
| 327 |
/// Acquires a token from this jobserver client in a non-blocking way. |
| 328 |
/// |
| 329 |
/// # Return value |
| 330 |
/// |
| 331 |
/// On successful acquisition of a token an instance of [`Acquired`] is |
| 332 |
/// returned. This structure, when dropped, will release the token back to |
| 333 |
/// the jobserver. It's recommended to avoid leaking this value. |
| 334 |
/// |
| 335 |
/// # Errors |
| 336 |
/// |
| 337 |
/// If an I/O error happens while acquiring a token then this function will |
| 338 |
/// return immediately with the error. If an error is returned then a token |
| 339 |
/// was not acquired. |
| 340 |
/// |
| 341 |
/// If non-blocking acquire is not supported, the return error will have its `kind()` |
| 342 |
/// set to [`io::ErrorKind::Unsupported`]. |
| 343 |
pub fn try_acquire(&self) -> io::Result<Option<Acquired>> { |
| 344 |
let ret = self.inner.try_acquire()?; |
| 345 |
|
| 346 |
Ok(ret.map(|data| Acquired { |
| 347 |
client: self.inner.clone(), |
| 348 |
data, |
| 349 |
disabled: false, |
| 350 |
})) |
| 351 |
} |
| 352 |
|
| 353 |
/// Returns amount of tokens in the read-side pipe. |
| 354 |
/// |
| 355 |
/// # Return value |
| 356 |
/// |
| 357 |
/// Number of bytes available to be read from the jobserver pipe |
| 358 |
/// |
| 359 |
/// # Errors |
| 360 |
/// |
| 361 |
/// Underlying errors from the ioctl will be passed up. |
| 362 |
pub fn available(&self) -> io::Result<usize> { |
| 363 |
self.inner.available() |
| 364 |
} |
| 365 |
|
| 366 |
/// Configures a child process to have access to this client's jobserver as |
| 367 |
/// well. |
| 368 |
/// |
| 369 |
/// This function is required to be called to ensure that a jobserver is |
| 370 |
/// properly inherited to a child process. If this function is *not* called |
| 371 |
/// then this [`Client`] will not be accessible in the child process. In |
| 372 |
/// other words, if not called, then [`Client::from_env`] will return `None` |
| 373 |
/// in the child process (or the equivalent of [`Client::from_env`] that |
| 374 |
/// `make` uses). |
| 375 |
/// |
| 376 |
/// ## Platform-specific behavior |
| 377 |
/// |
| 378 |
/// On Unix and Windows this will clobber the `CARGO_MAKEFLAGS` environment |
| 379 |
/// variables for the child process, and on Unix this will also allow the |
| 380 |
/// two file descriptors for this client to be inherited to the child. |
| 381 |
/// |
| 382 |
/// On platforms other than Unix and Windows this panics. |
| 383 |
pub fn configure(&self, cmd: &mut Command) { |
| 384 |
cmd.env("CARGO_MAKEFLAGS", &self.mflags_env()); |
| 385 |
self.inner.configure(cmd); |
| 386 |
} |
| 387 |
|
| 388 |
/// Configures a child process to have access to this client's jobserver as |
| 389 |
/// well. |
| 390 |
/// |
| 391 |
/// This function is required to be called to ensure that a jobserver is |
| 392 |
/// properly inherited to a child process. If this function is *not* called |
| 393 |
/// then this [`Client`] will not be accessible in the child process. In |
| 394 |
/// other words, if not called, then [`Client::from_env`] will return `None` |
| 395 |
/// in the child process (or the equivalent of [`Client::from_env`] that |
| 396 |
/// `make` uses). |
| 397 |
/// |
| 398 |
/// ## Platform-specific behavior |
| 399 |
/// |
| 400 |
/// On Unix and Windows this will clobber the `CARGO_MAKEFLAGS`, |
| 401 |
/// `MAKEFLAGS` and `MFLAGS` environment variables for the child process, |
| 402 |
/// and on Unix this will also allow the two file descriptors for |
| 403 |
/// this client to be inherited to the child. |
| 404 |
/// |
| 405 |
/// On platforms other than Unix and Windows this panics. |
| 406 |
pub fn configure_make(&self, cmd: &mut Command) { |
| 407 |
let value = self.mflags_env(); |
| 408 |
cmd.env("CARGO_MAKEFLAGS", &value); |
| 409 |
cmd.env("MAKEFLAGS", &value); |
| 410 |
cmd.env("MFLAGS", &value); |
| 411 |
self.inner.configure(cmd); |
| 412 |
} |
| 413 |
|
| 414 |
fn mflags_env(&self) -> String { |
| 415 |
let arg = self.inner.string_arg(); |
| 416 |
// Older implementations of make use `--jobserver-fds` and newer |
| 417 |
// implementations use `--jobserver-auth`, pass both to try to catch |
| 418 |
// both implementations. |
| 419 |
format!("-j --jobserver-fds={0} --jobserver-auth={0}", arg) |
| 420 |
} |
| 421 |
|
| 422 |
/// Converts this [`Client`] into a helper thread to deal with a blocking |
| 423 |
/// [`Client::acquire`] function a little more easily. |
| 424 |
/// |
| 425 |
/// The fact that the [`Client::acquire`] isn't always the easiest to work |
| 426 |
/// with. Typically you're using a jobserver to manage running other events |
| 427 |
/// in parallel! This means that you need to either (a) wait for an existing |
| 428 |
/// job to finish or (b) wait for a new token to become available. |
| 429 |
/// |
| 430 |
/// Unfortunately the blocking in [`Client::acquire`] happens at the |
| 431 |
/// implementation layer of jobservers. On Unix this requires a blocking |
| 432 |
/// call to `read` and on Windows this requires one of the `WaitFor*` |
| 433 |
/// functions. Both of these situations aren't the easiest to deal with: |
| 434 |
/// |
| 435 |
/// * On Unix there's basically only one way to wake up a `read` early, and |
| 436 |
/// that's through a signal. This is what the `make` implementation |
| 437 |
/// itself uses, relying on `SIGCHLD` to wake up a blocking acquisition |
| 438 |
/// of a new job token. Unfortunately nonblocking I/O is not an option |
| 439 |
/// here, so it means that "waiting for one of two events" means that |
| 440 |
/// the latter event must generate a signal! This is not always the case |
| 441 |
/// on unix for all jobservers. |
| 442 |
/// |
| 443 |
/// * On Windows you'd have to basically use the `WaitForMultipleObjects` |
| 444 |
/// which means that you've got to canonicalize all your event sources |
| 445 |
/// into a `HANDLE` which also isn't the easiest thing to do |
| 446 |
/// unfortunately. |
| 447 |
/// |
| 448 |
/// This function essentially attempts to ease these limitations by |
| 449 |
/// converting this [`Client`] into a helper thread spawned into this |
| 450 |
/// process. The application can then request that the helper thread |
| 451 |
/// acquires tokens and the provided closure will be invoked for each token |
| 452 |
/// acquired. |
| 453 |
/// |
| 454 |
/// The intention is that this function can be used to translate the event |
| 455 |
/// of a token acquisition into an arbitrary user-defined event. |
| 456 |
/// |
| 457 |
/// # Arguments |
| 458 |
/// |
| 459 |
/// This function will consume the [`Client`] provided to be transferred to |
| 460 |
/// the helper thread that is spawned. Additionally a closure `f` is |
| 461 |
/// provided to be invoked whenever a token is acquired. |
| 462 |
/// |
| 463 |
/// This closure is only invoked after calls to |
| 464 |
/// [`HelperThread::request_token`] have been made and a token itself has |
| 465 |
/// been acquired. If an error happens while acquiring the token then |
| 466 |
/// an error will be yielded to the closure as well. |
| 467 |
/// |
| 468 |
/// # Return Value |
| 469 |
/// |
| 470 |
/// This function will return an instance of the [`HelperThread`] structure |
| 471 |
/// which is used to manage the helper thread associated with this client. |
| 472 |
/// Through the [`HelperThread`] you'll request that tokens are acquired. |
| 473 |
/// When acquired, the closure provided here is invoked. |
| 474 |
/// |
| 475 |
/// When the [`HelperThread`] structure is returned it will be gracefully |
| 476 |
/// torn down, and the calling thread will be blocked until the thread is |
| 477 |
/// torn down (which should be prompt). |
| 478 |
/// |
| 479 |
/// # Errors |
| 480 |
/// |
| 481 |
/// This function may fail due to creation of the helper thread or |
| 482 |
/// auxiliary I/O objects to manage the helper thread. In any of these |
| 483 |
/// situations the error is propagated upwards. |
| 484 |
/// |
| 485 |
/// # Platform-specific behavior |
| 486 |
/// |
| 487 |
/// On Windows this function behaves pretty normally as expected, but on |
| 488 |
/// Unix the implementation is... a little heinous. As mentioned above |
| 489 |
/// we're forced into blocking I/O for token acquisition, namely a blocking |
| 490 |
/// call to `read`. We must be able to unblock this, however, to tear down |
| 491 |
/// the helper thread gracefully! |
| 492 |
/// |
| 493 |
/// Essentially what happens is that we'll send a signal to the helper |
| 494 |
/// thread spawned and rely on `EINTR` being returned to wake up the helper |
| 495 |
/// thread. This involves installing a global `SIGUSR1` handler that does |
| 496 |
/// nothing along with sending signals to that thread. This may cause |
| 497 |
/// odd behavior in some applications, so it's recommended to review and |
| 498 |
/// test thoroughly before using this. |
| 499 |
pub fn into_helper_thread<F>(self, f: F) -> io::Result<HelperThread> |
| 500 |
where |
| 501 |
F: FnMut(io::Result<Acquired>) + Send + 'static, |
| 502 |
{ |
| 503 |
let state = Arc::new(HelperState::default()); |
| 504 |
Ok(HelperThread { |
| 505 |
inner: Some(imp::spawn_helper(self, state.clone(), Box::new(f))?), |
| 506 |
state, |
| 507 |
}) |
| 508 |
} |
| 509 |
|
| 510 |
/// Blocks the current thread until a token is acquired. |
| 511 |
/// |
| 512 |
/// This is the same as [`Client::acquire`], except that it doesn't return |
| 513 |
/// an RAII helper. If successful the process will need to guarantee that |
| 514 |
/// [`Client::release_raw`] is called in the future. |
| 515 |
pub fn acquire_raw(&self) -> io::Result<()> { |
| 516 |
self.inner.acquire()?; |
| 517 |
Ok(()) |
| 518 |
} |
| 519 |
|
| 520 |
/// Releases a jobserver token back to the original jobserver. |
| 521 |
/// |
| 522 |
/// This is intended to be paired with [`Client::acquire_raw`] if it was |
| 523 |
/// called, but in some situations it could also be called to relinquish a |
| 524 |
/// process's implicit token temporarily which is then re-acquired later. |
| 525 |
pub fn release_raw(&self) -> io::Result<()> { |
| 526 |
self.inner.release(None)?; |
| 527 |
Ok(()) |
| 528 |
} |
| 529 |
} |
| 530 |
|
| 531 |
impl Drop for Acquired { |
| 532 |
fn drop(&mut self) { |
| 533 |
if !self.disabled { |
| 534 |
drop(self.client.release(Some(&self.data))); |
| 535 |
} |
| 536 |
} |
| 537 |
} |
| 538 |
|
| 539 |
/// Structure returned from [`Client::into_helper_thread`] to manage the lifetime |
| 540 |
/// of the helper thread returned, see those associated docs for more info. |
| 541 |
#[derive(Debug)] |
| 542 |
pub struct HelperThread { |
| 543 |
inner: Option<imp::Helper>, |
| 544 |
state: Arc<HelperState>, |
| 545 |
} |
| 546 |
|
| 547 |
impl HelperThread { |
| 548 |
/// Request that the helper thread acquires a token, eventually calling the |
| 549 |
/// original closure with a token when it's available. |
| 550 |
/// |
| 551 |
/// For more information, see the docs on [`Client::into_helper_thread`]. |
| 552 |
pub fn request_token(&self) { |
| 553 |
// Indicate that there's one more request for a token and then wake up |
| 554 |
// the helper thread if it's sleeping. |
| 555 |
self.state.lock().requests += 1; |
| 556 |
self.state.cvar.notify_one(); |
| 557 |
} |
| 558 |
} |
| 559 |
|
| 560 |
impl Drop for HelperThread { |
| 561 |
fn drop(&mut self) { |
| 562 |
// Flag that the producer half is done so the helper thread should exit |
| 563 |
// quickly if it's waiting. Wake it up if it's actually waiting |
| 564 |
self.state.lock().producer_done = true; |
| 565 |
self.state.cvar.notify_one(); |
| 566 |
|
| 567 |
// ... and afterwards perform any thread cleanup logic |
| 568 |
self.inner.take().unwrap().join(); |
| 569 |
} |
| 570 |
} |
| 571 |
|
| 572 |
impl HelperState { |
| 573 |
fn lock(&self) -> MutexGuard<'_, HelperInner> { |
| 574 |
self.lock.lock().unwrap_or_else(|e| e.into_inner()) |
| 575 |
} |
| 576 |
|
| 577 |
/// Executes `f` for each request for a token, where `f` is expected to |
| 578 |
/// block and then provide the original closure with a token once it's |
| 579 |
/// acquired. |
| 580 |
/// |
| 581 |
/// This is an infinite loop until the helper thread is dropped, at which |
| 582 |
/// point everything should get interrupted. |
| 583 |
fn for_each_request(&self, mut f: impl FnMut(&HelperState)) { |
| 584 |
let mut lock = self.lock(); |
| 585 |
|
| 586 |
// We only execute while we could receive requests, but as soon as |
| 587 |
// that's `false` we're out of here. |
| 588 |
while !lock.producer_done { |
| 589 |
// If no one's requested a token then we wait for someone to |
| 590 |
// request a token. |
| 591 |
if lock.requests == 0 { |
| 592 |
lock = self.cvar.wait(lock).unwrap_or_else(|e| e.into_inner()); |
| 593 |
continue; |
| 594 |
} |
| 595 |
|
| 596 |
// Consume the request for a token, and then actually acquire a |
| 597 |
// token after unlocking our lock (not that acquisition happens in |
| 598 |
// `f`). This ensures that we don't actually hold the lock if we |
| 599 |
// wait for a long time for a token. |
| 600 |
lock.requests -= 1; |
| 601 |
drop(lock); |
| 602 |
f(self); |
| 603 |
lock = self.lock(); |
| 604 |
} |
| 605 |
lock.consumer_done = true; |
| 606 |
self.cvar.notify_one(); |
| 607 |
} |
| 608 |
} |
| 609 |
|
| 610 |
/// Finds and returns the value of `--jobserver-auth=<VALUE>` in the given |
| 611 |
/// environment variable. |
| 612 |
/// |
| 613 |
/// Precedence rules: |
| 614 |
/// |
| 615 |
/// * The last instance wins [^1]. |
| 616 |
/// * `--jobserver-fds=` as a fallback when no `--jobserver-auth=` is present [^2]. |
| 617 |
/// |
| 618 |
/// [^1]: See ["GNU `make` manual: Sharing Job Slots with GNU `make`"](https://www.gnu.org/software/make/manual/make.html#Job-Slots) |
| 619 |
/// _"Be aware that the `MAKEFLAGS` variable may contain multiple instances of |
| 620 |
/// the `--jobserver-auth=` option. Only the last instance is relevant."_ |
| 621 |
/// |
| 622 |
/// [^2]: Refer to [the release announcement](https://git.savannah.gnu.org/cgit/make.git/tree/NEWS?h=4.2#n31) |
| 623 |
/// of GNU Make 4.2, which states that `--jobserver-fds` was initially an |
| 624 |
/// internal-only flag and was later renamed to `--jobserver-auth`. |
| 625 |
fn find_jobserver_auth(var: &str) -> Option<&str> { |
| 626 |
["--jobserver-auth=", "--jobserver-fds="] |
| 627 |
.iter() |
| 628 |
.find_map(|&arg| var.rsplit_once(arg).map(|(_, s)| s)) |
| 629 |
.and_then(|s| s.split(' ').next()) |
| 630 |
} |
| 631 |
|
| 632 |
#[cfg(test)] |
| 633 |
mod test { |
| 634 |
use super::*; |
| 635 |
|
| 636 |
pub(super) fn run_named_fifo_try_acquire_tests(client: &Client) { |
| 637 |
assert!(client.try_acquire().unwrap().is_none()); |
| 638 |
client.release_raw().unwrap(); |
| 639 |
|
| 640 |
let acquired = client.try_acquire().unwrap().unwrap(); |
| 641 |
assert!(client.try_acquire().unwrap().is_none()); |
| 642 |
|
| 643 |
drop(acquired); |
| 644 |
client.try_acquire().unwrap().unwrap(); |
| 645 |
} |
| 646 |
|
| 647 |
#[cfg(windows)] |
| 648 |
#[test] |
| 649 |
fn test_try_acquire() { |
| 650 |
let client = Client::new(0).unwrap(); |
| 651 |
|
| 652 |
run_named_fifo_try_acquire_tests(&client); |
| 653 |
} |
| 654 |
|
| 655 |
#[test] |
| 656 |
fn no_helper_deadlock() { |
| 657 |
let x = crate::Client::new(32).unwrap(); |
| 658 |
let _y = x.clone(); |
| 659 |
std::mem::drop(x.into_helper_thread(|_| {}).unwrap()); |
| 660 |
} |
| 661 |
|
| 662 |
#[test] |
| 663 |
fn test_find_jobserver_auth() { |
| 664 |
let cases = [ |
| 665 |
("", None), |
| 666 |
("-j2", None), |
| 667 |
("-j2 --jobserver-auth=3,4", Some("3,4")), |
| 668 |
("--jobserver-auth=3,4 -j2", Some("3,4")), |
| 669 |
("--jobserver-auth=3,4", Some("3,4")), |
| 670 |
("--jobserver-auth=fifo:/myfifo", Some("fifo:/myfifo")), |
| 671 |
("--jobserver-auth=", Some("")), |
| 672 |
("--jobserver-auth", None), |
| 673 |
("--jobserver-fds=3,4", Some("3,4")), |
| 674 |
("--jobserver-fds=fifo:/myfifo", Some("fifo:/myfifo")), |
| 675 |
("--jobserver-fds=", Some("")), |
| 676 |
("--jobserver-fds", None), |
| 677 |
( |
| 678 |
"--jobserver-auth=auth-a --jobserver-auth=auth-b", |
| 679 |
Some("auth-b"), |
| 680 |
), |
| 681 |
( |
| 682 |
"--jobserver-auth=auth-b --jobserver-auth=auth-a", |
| 683 |
Some("auth-a"), |
| 684 |
), |
| 685 |
("--jobserver-fds=fds-a --jobserver-fds=fds-b", Some("fds-b")), |
| 686 |
("--jobserver-fds=fds-b --jobserver-fds=fds-a", Some("fds-a")), |
| 687 |
( |
| 688 |
"--jobserver-auth=auth-a --jobserver-fds=fds-a --jobserver-auth=auth-b", |
| 689 |
Some("auth-b"), |
| 690 |
), |
| 691 |
( |
| 692 |
"--jobserver-fds=fds-a --jobserver-auth=auth-a --jobserver-fds=fds-b", |
| 693 |
Some("auth-a"), |
| 694 |
), |
| 695 |
]; |
| 696 |
for (var, expected) in cases { |
| 697 |
let actual = find_jobserver_auth(var); |
| 698 |
assert_eq!( |
| 699 |
actual, expected, |
| 700 |
"expect {expected:?}, got {actual:?}, input `{var:?}`" |
| 701 |
); |
| 702 |
} |
| 703 |
} |
| 704 |
} |