Skip to content

Commit adaa4ef

Browse files
alexcrichtonluser
authored andcommitted
Add jobserver support to sccache
This commit alters the main sccache server to operate and orchestrate its own GNU make style jobserver. This is primarily intended for interoperation with rustc itself. The Rust compiler currently has a multithreaded mode where it will execute code generation and optimization on the LLVM side of things in parallel. This parallelism, however, can overload a machine quickly if not properly accounted for (e.g. if 10 rustcs all spawn 10 threads...). The usage of a GNU make style jobserver is intended to arbitrate and rate limit all these rustc instances to ensure that one build's maximal parallelism never exceeds a particular amount. Currently for Rust Cargo is the primary driver for setting up a jobserver. Cargo will create this and manage this per compilation, ensuring that any one `cargo build` invocation never exceeds a maximal parallelism. When sccache enters the picture, however, the story gets slightly more odd. The jobserver implementation on Unix relies on inheritance of file descriptors in spawned processes. With sccache, however, there's no inheritance as the actual rustc invocation is spawned by the server, not the client. In this case the env vars used to configure the jobsever are usually incorrect. To handle this problem this commit bakes a jobserver directly into sccache itself. The jobserver then overrides whatever jobserver the client has configured in its own env vars to ensure correct operation. The settings of each jobserver may be misconfigured (there's no way to configure sccache's jobserver right now), but hopefully that's not too much of a problem for the forseeable future. The implementation here was to provide a thin wrapper around the `jobserver` crate with a futures-based interface. This interface was then hooked into the mock command infrastructure to automatically acquire a jobserver token when spawning a process and automatically drop the token when the process exits. Additionally, all spawned processes will now automatically receive a configured jobserver. cc rust-lang/rust#42867, the original motivation for this commit
1 parent bda1bc2 commit adaa4ef

12 files changed

+243
-103
lines changed

Cargo.lock

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,14 @@ futures = "0.1.11"
2828
futures-cpupool = "0.1"
2929
hyper = { version = "0.11", optional = true }
3030
hyper-tls = { version = "0.1", optional = true }
31+
jobserver = "0.1"
3132
jsonwebtoken = { version = "4.0", optional = true }
3233
libc = "0.2.10"
3334
local-encoding = "0.2.0"
3435
log = "0.3.6"
3536
lru-disk-cache = { path = "lru-disk-cache", version = "0.1.0" }
3637
native-tls = "0.1"
38+
num_cpus = "1.0"
3739
number_prefix = "0.2.5"
3840
openssl = { version = "0.9", optional = true }
3941
redis = { version = "0.8.0", optional = true }

README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ Table of Contents (ToC)
2222
* [Usage](#usage)
2323
* [Storage Options](#storage-options)
2424
* [Debugging](#debugging)
25+
* [Interaction with GNU `make` jobserver](#interaction-with-gnu-make-jobserver)
2526
* [Known Caveats](#known-caveats)
2627

2728
---
@@ -94,6 +95,15 @@ You can set the `SCCACHE_ERROR_LOG` environment variable to a path to cause the
9495

9596
---
9697

98+
Interaction with GNU `make` jobserver
99+
-------------------------------------
100+
101+
Sccache provides support for a [GNU make jobserver](https://www.gnu.org/software/make/manual/html_node/Job-Slots.html). When the server is started from a process that provides a jobserver, sccache will use that jobserver and provide it to any processes it spawns. (If you are running sccache from a GNU make recipe, you will need to prefix the command with `+` to get this behavior.) If the sccache server is started without a jobserver present it will create its own with the number of slots equal to the number of available CPU cores.
102+
103+
This is most useful when using sccache for Rust compilation, as rustc supports using a jobserver for parallel codegen, so this ensures that rustc will not overwhelm the system with codegen tasks. Cargo implements its own jobserver ([see the information on `NUM_JOBS` in the cargo documentation](https://doc.rust-lang.org/stable/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts)) for rustc to use, so using sccache for Rust compilation in cargo via `RUSTC_WRAPPER` should do the right thing automatically.
104+
105+
---
106+
97107
Known caveats
98108
-------------
99109

src/commands.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ use client::{
1818
ServerConnection,
1919
};
2020
use cmdline::{Command, StatsFormat};
21+
use jobserver::Client;
2122
use log::LogLevel::Trace;
2223
use mock_command::{
2324
CommandCreatorSync,
@@ -601,9 +602,10 @@ pub fn run_command(cmd: Command) -> Result<i32> {
601602
}
602603
Command::Compile { exe, cmdline, cwd, env_vars } => {
603604
trace!("Command::Compile {{ {:?}, {:?}, {:?} }}", exe, cmdline, cwd);
605+
let jobserver = unsafe { Client::new() };
604606
let conn = connect_or_start_server(get_port())?;
605607
let mut core = Core::new()?;
606-
let res = do_compile(ProcessCommandCreator::new(&core.handle()),
608+
let res = do_compile(ProcessCommandCreator::new(&core.handle(), &jobserver),
607609
&mut core,
608610
conn,
609611
exe.as_ref(),

src/compiler/compiler.rs

Lines changed: 16 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -470,14 +470,13 @@ fn detect_compiler<T>(creator: &T, executable: &Path, pool: &CpuPool)
470470
};
471471
let is_rustc = if filename.to_string_lossy().to_lowercase() == "rustc" {
472472
// Sanity check that it's really rustc.
473+
let executable = executable.to_path_buf();
473474
let child = creator.clone().new_command_sync(&executable)
474475
.stdout(Stdio::piped())
475476
.stderr(Stdio::null())
476477
.args(&["--version"])
477-
.spawn().chain_err(|| {
478-
format!("failed to execute {:?}", executable)
479-
});
480-
let output = child.into_future().and_then(move |child| {
478+
.spawn();
479+
let output = child.and_then(move |child| {
481480
child.wait_with_output()
482481
.chain_err(|| "failed to read child output")
483482
});
@@ -530,10 +529,7 @@ gcc
530529
let output = write.and_then(move |(tempdir, src)| {
531530
cmd.arg("-E").arg(src);
532531
trace!("compiler {:?}", cmd);
533-
let child = cmd.spawn().chain_err(|| {
534-
format!("failed to execute {:?}", cmd)
535-
});
536-
child.into_future().and_then(|child| {
532+
cmd.spawn().and_then(|child| {
537533
child.wait_with_output().chain_err(|| "failed to read child output")
538534
}).map(|e| {
539535
drop(tempdir);
@@ -724,11 +720,9 @@ mod test {
724720
let o = obj.clone();
725721
next_command_calls(&creator, move |_| {
726722
// Pretend to compile something.
727-
match File::create(&o)
728-
.and_then(|mut f| f.write_all(b"file contents")) {
729-
Ok(_) => Ok(MockChild::new(exit_status(0), COMPILER_STDOUT, COMPILER_STDERR)),
730-
Err(e) => Err(e),
731-
}
723+
let mut f = File::create(&o)?;
724+
f.write_all(b"file contents")?;
725+
Ok(MockChild::new(exit_status(0), COMPILER_STDOUT, COMPILER_STDERR))
732726
});
733727
let cwd = f.tempdir.path();
734728
let arguments = ovec!["-c", "foo.c", "-o", "foo.o"];
@@ -805,11 +799,9 @@ mod test {
805799
let o = obj.clone();
806800
next_command_calls(&creator, move |_| {
807801
// Pretend to compile something.
808-
match File::create(&o)
809-
.and_then(|mut f| f.write_all(b"file contents")) {
810-
Ok(_) => Ok(MockChild::new(exit_status(0), COMPILER_STDOUT, COMPILER_STDERR)),
811-
Err(e) => Err(e),
812-
}
802+
let mut f = File::create(&o)?;
803+
f.write_all(b"file contents")?;
804+
Ok(MockChild::new(exit_status(0), COMPILER_STDOUT, COMPILER_STDERR))
813805
});
814806
let cwd = f.tempdir.path();
815807
let arguments = ovec!["-c", "foo.c", "-o", "foo.o"];
@@ -887,11 +879,9 @@ mod test {
887879
let o = obj.clone();
888880
next_command_calls(&creator, move |_| {
889881
// Pretend to compile something.
890-
match File::create(&o)
891-
.and_then(|mut f| f.write_all(b"file contents")) {
892-
Ok(_) => Ok(MockChild::new(exit_status(0), COMPILER_STDOUT, COMPILER_STDERR)),
893-
Err(e) => Err(e),
894-
}
882+
let mut f = File::create(&o)?;
883+
f.write_all(b"file contents")?;
884+
Ok(MockChild::new(exit_status(0), COMPILER_STDOUT, COMPILER_STDERR))
895885
});
896886
let cwd = f.tempdir.path();
897887
let arguments = ovec!["-c", "foo.c", "-o", "foo.o"];
@@ -954,11 +944,9 @@ mod test {
954944
let o = obj.clone();
955945
next_command_calls(&creator, move |_| {
956946
// Pretend to compile something.
957-
match File::create(&o)
958-
.and_then(|mut f| f.write_all(b"file contents")) {
959-
Ok(_) => Ok(MockChild::new(exit_status(0), COMPILER_STDOUT, COMPILER_STDERR)),
960-
Err(e) => Err(e),
961-
}
947+
let mut f = File::create(&o)?;
948+
f.write_all(b"file contents")?;
949+
Ok(MockChild::new(exit_status(0), COMPILER_STDOUT, COMPILER_STDERR))
962950
});
963951
}
964952
let cwd = f.tempdir.path();

src/jobserver.rs

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
extern crate jobserver;
2+
3+
use std::io;
4+
use std::process::Command;
5+
use std::sync::Arc;
6+
7+
use futures::prelude::*;
8+
use futures::sync::mpsc;
9+
use futures::sync::oneshot;
10+
use num_cpus;
11+
12+
use errors::*;
13+
14+
pub use self::jobserver::Acquired;
15+
16+
#[derive(Clone)]
17+
pub struct Client {
18+
helper: Arc<jobserver::HelperThread>,
19+
inner: jobserver::Client,
20+
tx: mpsc::UnboundedSender<oneshot::Sender<io::Result<Acquired>>>
21+
}
22+
23+
impl Client {
24+
// unsafe because `from_env` is unsafe (can use the wrong fds)
25+
pub unsafe fn new() -> Client {
26+
match jobserver::Client::from_env() {
27+
Some(c) => Client::_new(c),
28+
None => Client::new_num(num_cpus::get()),
29+
}
30+
}
31+
32+
pub fn new_num(num: usize) -> Client {
33+
let inner = jobserver::Client::new(num)
34+
.expect("failed to create jobserver");
35+
Client::_new(inner)
36+
}
37+
38+
fn _new(inner: jobserver::Client) -> Client {
39+
let (tx, rx) = mpsc::unbounded::<oneshot::Sender<_>>();
40+
let mut rx = rx.wait();
41+
let helper = inner.clone().into_helper_thread(move |token| {
42+
if let Some(Ok(sender)) = rx.next() {
43+
drop(sender.send(token));
44+
}
45+
}).expect("failed to spawn helper thread");
46+
47+
Client {
48+
inner: inner,
49+
helper: Arc::new(helper),
50+
tx: tx,
51+
}
52+
}
53+
54+
/// Configures this jobserver to be inherited by the specified command
55+
pub fn configure(&self, cmd: &mut Command) {
56+
self.inner.configure(cmd)
57+
}
58+
59+
/// Returns a future that represents an acquired jobserver token.
60+
///
61+
/// This should be invoked before any "work" is spawend (for whatever the
62+
/// defnition of "work" is) to ensure that the system is properly
63+
/// rate-limiting itself.
64+
pub fn acquire(&self) -> SFuture<Acquired> {
65+
let (tx, rx) = oneshot::channel();
66+
self.helper.request_token();
67+
self.tx.unbounded_send(tx).unwrap();
68+
Box::new(rx.chain_err(|| "jobserver helper panicked")
69+
.and_then(|t| t.chain_err(|| "failed to acquire jobserver token")))
70+
}
71+
}

src/main.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ extern crate libc;
5252
#[cfg(windows)]
5353
extern crate mio_named_pipes;
5454
extern crate native_tls;
55+
extern crate num_cpus;
5556
extern crate number_prefix;
5657
#[cfg(feature = "openssl")]
5758
extern crate openssl;
@@ -93,6 +94,7 @@ mod client;
9394
mod cmdline;
9495
mod commands;
9596
mod compiler;
97+
mod jobserver;
9698
mod mock_command;
9799
mod protocol;
98100
mod server;

0 commit comments

Comments
 (0)