Skip to content

Commit a38da80

Browse files
alexcrichtonjrobsonchase
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 aa5f93f commit a38da80

File tree

13 files changed

+238
-111
lines changed

13 files changed

+238
-111
lines changed

Cargo.lock

+12
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+2
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 = "2.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 }

src/cache/disk.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ use cache::{
1818
CacheWrite,
1919
Storage,
2020
};
21-
use futures::Future;
2221
use futures_cpupool::CpuPool;
2322
use lru_disk_cache::LruDiskCache;
2423
use lru_disk_cache::Error as LruError;
@@ -62,7 +61,7 @@ impl Storage for DiskCache {
6261
let path = make_key_path(key);
6362
let lru = self.lru.clone();
6463
let key = key.to_owned();
65-
self.pool.spawn_fn(move || {
64+
Box::new(self.pool.spawn_fn(move || {
6665
let mut lru = lru.lock().unwrap();
6766
let f = match lru.get(&path) {
6867
Ok(f) => f,
@@ -78,7 +77,7 @@ impl Storage for DiskCache {
7877
};
7978
let hit = CacheRead::from(f)?;
8079
Ok(Cache::Hit(hit))
81-
}).boxed()
80+
}))
8281
}
8382

8483
fn put(&self, key: &str, entry: CacheWrite) -> SFuture<Duration> {
@@ -87,12 +86,12 @@ impl Storage for DiskCache {
8786
trace!("DiskCache::finish_put({})", key);
8887
let lru = self.lru.clone();
8988
let key = make_key_path(key);
90-
self.pool.spawn_fn(move || {
89+
Box::new(self.pool.spawn_fn(move || {
9190
let start = Instant::now();
9291
let v = entry.finish()?;
9392
lru.lock().unwrap().insert_bytes(key, &v)?;
9493
Ok(start.elapsed())
95-
}).boxed()
94+
}))
9695
}
9796

9897
fn location(&self) -> String {

src/commands.rs

+3-1
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

+16-28
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

+71
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

+2
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)