forked from mozilla/sccache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.rs
2238 lines (2018 loc) · 78 KB
/
server.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 Mozilla Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.SCCACHE_MAX_FRAME_LENGTH
use crate::cache::readonly::ReadOnlyStorage;
use crate::cache::{storage_from_config, CacheMode, Storage};
use crate::compiler::{
get_compiler_info, CacheControl, CompileResult, Compiler, CompilerArguments, CompilerHasher,
CompilerKind, CompilerProxy, DistType, Language, MissType,
};
#[cfg(feature = "dist-client")]
use crate::config;
use crate::config::Config;
use crate::dist;
use crate::jobserver::Client;
use crate::mock_command::{CommandCreatorSync, ProcessCommandCreator};
use crate::protocol::{Compile, CompileFinished, CompileResponse, Request, Response};
use crate::util;
#[cfg(feature = "dist-client")]
use anyhow::Context as _;
use bytes::{buf::BufMut, Bytes, BytesMut};
use filetime::FileTime;
use fs::metadata;
use fs_err as fs;
use futures::channel::mpsc;
use futures::future::FutureExt;
use futures::{future, stream, Sink, SinkExt, Stream, StreamExt, TryFutureExt};
use number_prefix::NumberPrefix;
use serde::{Deserialize, Serialize};
use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::env;
use std::ffi::{OsStr, OsString};
use std::future::Future;
use std::io::{self, Write};
use std::marker::Unpin;
#[cfg(feature = "dist-client")]
use std::mem;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
use std::path::PathBuf;
use std::pin::Pin;
use std::process::{ExitStatus, Output};
use std::sync::Arc;
use std::task::{Context, Poll, Waker};
use std::time::Duration;
#[cfg(feature = "dist-client")]
use std::time::Instant;
use tokio::sync::Mutex;
use tokio::sync::RwLock;
use tokio::{
io::{AsyncRead, AsyncWrite},
net::TcpListener,
runtime::Runtime,
time::{self, sleep, Sleep},
};
use tokio_serde::Framed;
use tokio_util::codec::{length_delimited, LengthDelimitedCodec};
use tower::Service;
use crate::errors::*;
/// If the server is idle for this many seconds, shut down.
const DEFAULT_IDLE_TIMEOUT: u64 = 600;
/// If the dist client couldn't be created, retry creation at this number
/// of seconds from now (or later)
#[cfg(feature = "dist-client")]
const DIST_CLIENT_RECREATE_TIMEOUT: Duration = Duration::from_secs(30);
/// Result of background server startup.
#[derive(Debug, Serialize, Deserialize)]
pub enum ServerStartup {
/// Server started successfully on `port`.
Ok { port: u16 },
/// Server Addr already in suse
AddrInUse,
/// Timed out waiting for server startup.
TimedOut,
/// Server encountered an error.
Err { reason: String },
}
/// Get the time the server should idle for before shutting down, in seconds.
fn get_idle_timeout() -> u64 {
// A value of 0 disables idle shutdown entirely.
env::var("SCCACHE_IDLE_TIMEOUT")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(DEFAULT_IDLE_TIMEOUT)
}
fn notify_server_startup_internal<W: Write>(mut w: W, status: ServerStartup) -> Result<()> {
util::write_length_prefixed_bincode(&mut w, status)
}
#[cfg(unix)]
fn notify_server_startup(name: &Option<OsString>, status: ServerStartup) -> Result<()> {
use std::os::unix::net::UnixStream;
let name = match *name {
Some(ref s) => s,
None => return Ok(()),
};
debug!("notify_server_startup({:?})", status);
let stream = UnixStream::connect(name)?;
notify_server_startup_internal(stream, status)
}
#[cfg(windows)]
fn notify_server_startup(name: &Option<OsString>, status: ServerStartup) -> Result<()> {
use fs::OpenOptions;
let name = match *name {
Some(ref s) => s,
None => return Ok(()),
};
let pipe = OpenOptions::new().write(true).read(true).open(name)?;
notify_server_startup_internal(pipe, status)
}
#[cfg(unix)]
fn get_signal(status: ExitStatus) -> i32 {
use std::os::unix::prelude::*;
status.signal().expect("must have signal")
}
#[cfg(windows)]
fn get_signal(_status: ExitStatus) -> i32 {
panic!("no signals on windows")
}
pub struct DistClientContainer {
// The actual dist client state
#[cfg(feature = "dist-client")]
state: futures::lock::Mutex<DistClientState>,
}
#[cfg(feature = "dist-client")]
pub struct DistClientConfig {
// Reusable items tied to an SccacheServer instance
pool: tokio::runtime::Handle,
// From the static dist configuration
scheduler_url: Option<config::HTTPUrl>,
auth: config::DistAuth,
cache_dir: PathBuf,
toolchain_cache_size: u64,
toolchains: Vec<config::DistToolchainConfig>,
rewrite_includes_only: bool,
}
#[cfg(feature = "dist-client")]
pub enum DistClientState {
#[cfg(feature = "dist-client")]
Some(Box<DistClientConfig>, Arc<dyn dist::Client>),
#[cfg(feature = "dist-client")]
FailWithMessage(Box<DistClientConfig>, String),
#[cfg(feature = "dist-client")]
RetryCreateAt(Box<DistClientConfig>, Instant),
Disabled,
}
#[cfg(not(feature = "dist-client"))]
impl DistClientContainer {
#[cfg(not(feature = "dist-client"))]
fn new(config: &Config, _: &tokio::runtime::Handle) -> Self {
if config.dist.scheduler_url.is_some() {
warn!("Scheduler address configured but dist feature disabled, disabling distributed sccache")
}
Self {}
}
pub fn new_disabled() -> Self {
Self {}
}
#[cfg(feature = "dist-client")]
pub fn new_with_state(_: DistClientState) -> Self {
Self {}
}
pub async fn reset_state(&self) {}
pub async fn get_status(&self) -> DistInfo {
DistInfo::Disabled("dist-client feature not selected".to_string())
}
async fn get_client(&self) -> Result<Option<Arc<dyn dist::Client>>> {
Ok(None)
}
}
#[cfg(feature = "dist-client")]
impl DistClientContainer {
fn new(config: &Config, pool: &tokio::runtime::Handle) -> Self {
let config = DistClientConfig {
pool: pool.clone(),
scheduler_url: config.dist.scheduler_url.clone(),
auth: config.dist.auth.clone(),
cache_dir: config.dist.cache_dir.clone(),
toolchain_cache_size: config.dist.toolchain_cache_size,
toolchains: config.dist.toolchains.clone(),
rewrite_includes_only: config.dist.rewrite_includes_only,
};
let state = Self::create_state(config);
let state = pool.block_on(state);
Self {
state: futures::lock::Mutex::new(state),
}
}
#[cfg(feature = "dist-client")]
pub fn new_with_state(state: DistClientState) -> Self {
Self {
state: futures::lock::Mutex::new(state),
}
}
pub fn new_disabled() -> Self {
Self {
state: futures::lock::Mutex::new(DistClientState::Disabled),
}
}
pub async fn reset_state(&self) {
let mut guard = self.state.lock().await;
let state = &mut *guard;
match mem::replace(state, DistClientState::Disabled) {
DistClientState::Some(cfg, _)
| DistClientState::FailWithMessage(cfg, _)
| DistClientState::RetryCreateAt(cfg, _) => {
warn!("State reset. Will recreate");
*state = DistClientState::RetryCreateAt(
cfg,
Instant::now().checked_sub(Duration::from_secs(1)).unwrap(),
);
}
DistClientState::Disabled => (),
}
}
pub async fn get_status(&self) -> DistInfo {
let mut guard = self.state.lock().await;
let state = &mut *guard;
let (client, scheduler_url) = match state {
DistClientState::Disabled => return DistInfo::Disabled("disabled".to_string()),
DistClientState::FailWithMessage(cfg, _) => {
return DistInfo::NotConnected(
cfg.scheduler_url.clone(),
"enabled, auth not configured".to_string(),
)
}
DistClientState::RetryCreateAt(cfg, _) => {
return DistInfo::NotConnected(
cfg.scheduler_url.clone(),
"enabled, not connected, will retry".to_string(),
)
}
DistClientState::Some(cfg, client) => (Arc::clone(client), cfg.scheduler_url.clone()),
};
match client.do_get_status().await {
Ok(res) => DistInfo::SchedulerStatus(scheduler_url.clone(), res),
Err(_) => DistInfo::NotConnected(
scheduler_url.clone(),
"could not communicate with scheduler".to_string(),
),
}
}
async fn get_client(&self) -> Result<Option<Arc<dyn dist::Client>>> {
let mut guard = self.state.lock().await;
let state = &mut *guard;
Self::maybe_recreate_state(state).await;
let res = match state {
DistClientState::Some(_, dc) => Ok(Some(dc.clone())),
DistClientState::Disabled | DistClientState::RetryCreateAt(_, _) => Ok(None),
DistClientState::FailWithMessage(_, msg) => Err(anyhow!(msg.clone())),
};
if res.is_err() {
let config = match mem::replace(state, DistClientState::Disabled) {
DistClientState::FailWithMessage(config, _) => config,
_ => unreachable!(),
};
// The client is most likely mis-configured, make sure we
// re-create on our next attempt.
*state = DistClientState::RetryCreateAt(
config,
Instant::now().checked_sub(Duration::from_secs(1)).unwrap(),
);
}
res
}
async fn maybe_recreate_state(state: &mut DistClientState) {
if let DistClientState::RetryCreateAt(_, instant) = *state {
if instant > Instant::now() {
return;
}
let config = match mem::replace(state, DistClientState::Disabled) {
DistClientState::RetryCreateAt(config, _) => config,
_ => unreachable!(),
};
info!("Attempting to recreate the dist client");
*state = Self::create_state(*config).await
}
}
// Attempt to recreate the dist client
async fn create_state(config: DistClientConfig) -> DistClientState {
macro_rules! try_or_retry_later {
($v:expr) => {{
match $v {
Ok(v) => v,
Err(e) => {
// `{:?}` prints the full cause chain and backtrace.
error!("{:?}", e);
return DistClientState::RetryCreateAt(
Box::new(config),
Instant::now() + DIST_CLIENT_RECREATE_TIMEOUT,
);
}
}
}};
}
macro_rules! try_or_fail_with_message {
($v:expr) => {{
match $v {
Ok(v) => v,
Err(e) => {
// `{:?}` prints the full cause chain and backtrace.
let errmsg = format!("{:?}", e);
error!("{}", errmsg);
return DistClientState::FailWithMessage(
Box::new(config),
errmsg.to_string(),
);
}
}
}};
}
match config.scheduler_url {
Some(ref addr) => {
let url = addr.to_url();
info!("Enabling distributed sccache to {}", url);
let auth_token = match &config.auth {
config::DistAuth::Token { token } => Ok(token.to_owned()),
config::DistAuth::Oauth2CodeGrantPKCE { auth_url, .. }
| config::DistAuth::Oauth2Implicit { auth_url, .. } => {
Self::get_cached_config_auth_token(auth_url)
}
};
let auth_token = try_or_fail_with_message!(auth_token
.context("could not load client auth token, run |sccache --dist-auth|"));
let dist_client = dist::http::Client::new(
&config.pool,
url,
&config.cache_dir.join("client"),
config.toolchain_cache_size,
&config.toolchains,
auth_token,
config.rewrite_includes_only,
);
let dist_client =
try_or_retry_later!(dist_client.context("failure during dist client creation"));
use crate::dist::Client;
match dist_client.do_get_status().await {
Ok(res) => {
info!(
"Successfully created dist client with {:?} cores across {:?} servers",
res.num_cpus, res.num_servers
);
DistClientState::Some(Box::new(config), Arc::new(dist_client))
}
Err(_) => {
warn!("Scheduler address configured, but could not communicate with scheduler");
DistClientState::RetryCreateAt(
Box::new(config),
Instant::now() + DIST_CLIENT_RECREATE_TIMEOUT,
)
}
}
}
None => {
info!("No scheduler address configured, disabling distributed sccache");
DistClientState::Disabled
}
}
}
fn get_cached_config_auth_token(auth_url: &str) -> Result<String> {
let cached_config = config::CachedConfig::reload()?;
cached_config
.with(|c| c.dist.auth_tokens.get(auth_url).map(String::to_owned))
.with_context(|| format!("token for url {} not present in cached config", auth_url))
}
}
thread_local! {
/// catch_unwind doesn't provide panic location, so we store that
/// information via a panic hook to be used when catch_unwind
/// catches a panic.
static PANIC_LOCATION: Cell<Option<(String, u32, u32)>> = const { Cell::new(None) };
}
/// Start an sccache server, listening on `port`.
///
/// Spins an event loop handling client connections until a client
/// requests a shutdown.
pub fn start_server(config: &Config, port: u16) -> Result<()> {
info!("start_server: port: {}", port);
let panic_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
PANIC_LOCATION.with(|l| {
l.set(
info.location()
.map(|loc| (loc.file().to_string(), loc.line(), loc.column())),
)
});
panic_hook(info)
}));
let client = unsafe { Client::new() };
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.worker_threads(std::cmp::max(20, 2 * num_cpus::get()))
.build()?;
let pool = runtime.handle().clone();
let dist_client = DistClientContainer::new(config, &pool);
let notify = env::var_os("SCCACHE_STARTUP_NOTIFY");
let raw_storage = match storage_from_config(config, &pool) {
Ok(storage) => storage,
Err(err) => {
error!("storage init failed for: {err:?}");
notify_server_startup(
¬ify,
ServerStartup::Err {
reason: err.to_string(),
},
)?;
return Err(err);
}
};
let cache_mode = runtime.block_on(async {
match raw_storage.check().await {
Ok(mode) => Ok(mode),
Err(err) => {
error!("storage check failed for: {err:?}");
notify_server_startup(
¬ify,
ServerStartup::Err {
reason: err.to_string(),
},
)?;
Err(err)
}
}
})?;
info!("server has setup with {cache_mode:?}");
let storage = match cache_mode {
CacheMode::ReadOnly => Arc::new(ReadOnlyStorage(raw_storage)),
_ => raw_storage,
};
let res =
SccacheServer::<ProcessCommandCreator>::new(port, runtime, client, dist_client, storage);
match res {
Ok(srv) => {
let port = srv.port();
info!("server started, listening on port {}", port);
notify_server_startup(¬ify, ServerStartup::Ok { port })?;
srv.run(future::pending::<()>())?;
Ok(())
}
Err(e) => {
error!("failed to start server: {}", e);
match e.downcast_ref::<io::Error>() {
Some(io_err) if io::ErrorKind::AddrInUse == io_err.kind() => {
notify_server_startup(¬ify, ServerStartup::AddrInUse)?;
}
Some(io_err) if cfg!(windows) && Some(10013) == io_err.raw_os_error() => {
// 10013 is the "WSAEACCES" error, which can occur if the requested port
// has been allocated for other purposes, such as winNAT or Hyper-V.
let windows_help_message =
"A Windows port exclusion is blocking use of the configured port.\nTry setting SCCACHE_SERVER_PORT to a new value.";
let reason: String = format!("{windows_help_message}\n{e}");
notify_server_startup(¬ify, ServerStartup::Err { reason })?;
}
_ => {
let reason = e.to_string();
notify_server_startup(¬ify, ServerStartup::Err { reason })?;
}
};
Err(e)
}
}
}
pub struct SccacheServer<C: CommandCreatorSync> {
runtime: Runtime,
listener: TcpListener,
rx: mpsc::Receiver<ServerMessage>,
timeout: Duration,
service: SccacheService<C>,
wait: WaitUntilZero,
}
impl<C: CommandCreatorSync> SccacheServer<C> {
pub fn new(
port: u16,
runtime: Runtime,
client: Client,
dist_client: DistClientContainer,
storage: Arc<dyn Storage>,
) -> Result<SccacheServer<C>> {
let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port);
let listener = runtime.block_on(TcpListener::bind(&SocketAddr::V4(addr)))?;
Ok(Self::with_listener(
listener,
runtime,
client,
dist_client,
storage,
))
}
pub fn with_listener(
listener: TcpListener,
runtime: Runtime,
client: Client,
dist_client: DistClientContainer,
storage: Arc<dyn Storage>,
) -> SccacheServer<C> {
// Prepare the service which we'll use to service all incoming TCP
// connections.
let (tx, rx) = mpsc::channel(1);
let (wait, info) = WaitUntilZero::new();
let pool = runtime.handle().clone();
let service = SccacheService::new(dist_client, storage, &client, pool, tx, info);
SccacheServer {
runtime,
listener,
rx,
service,
timeout: Duration::from_secs(get_idle_timeout()),
wait,
}
}
/// Configures how long this server will be idle before shutting down.
#[allow(dead_code)]
pub fn set_idle_timeout(&mut self, timeout: Duration) {
self.timeout = timeout;
}
/// Set the storage this server will use.
#[allow(dead_code)]
pub fn set_storage(&mut self, storage: Arc<dyn Storage>) {
self.service.storage = storage;
}
/// Returns a reference to a thread pool to run work on
#[allow(dead_code)]
pub fn pool(&self) -> &tokio::runtime::Handle {
&self.service.rt
}
/// Returns a reference to the command creator this server will use
#[allow(dead_code)]
pub fn command_creator(&self) -> &C {
&self.service.creator
}
/// Returns the port that this server is bound to
#[allow(dead_code)]
pub fn port(&self) -> u16 {
self.listener.local_addr().unwrap().port()
}
/// Runs this server to completion.
///
/// If the `shutdown` future resolves then the server will be shut down,
/// otherwise the server may naturally shut down if it becomes idle for too
/// long anyway.
pub fn run<F>(self, shutdown: F) -> io::Result<()>
where
F: Future,
C: Send,
{
let SccacheServer {
runtime,
listener,
rx,
service,
timeout,
wait,
} = self;
// Create our "server future" which will simply handle all incoming
// connections in separate tasks.
let server = async move {
loop {
let (socket, _) = listener.accept().await?;
trace!("incoming connection");
let conn = service.clone().bind(socket).map_err(|res| {
error!("Failed to bind socket: {}", res);
});
// We're not interested if the task panicked; immediately process
// another connection
#[allow(clippy::let_underscore_future)]
let _ = tokio::spawn(conn);
}
};
// Right now there's a whole bunch of ways to shut down this server for
// various purposes. These include:
//
// 1. The `shutdown` future above.
// 2. An RPC indicating the server should shut down
// 3. A period of inactivity (no requests serviced)
//
// These are all encapsulated with the future that we're creating below.
// The `ShutdownOrInactive` indicates the RPC or the period of
// inactivity, and this is then select'd with the `shutdown` future
// passed to this function.
let shutdown = shutdown.map(|_| {
info!("shutting down due to explicit signal");
});
let shutdown_idle = async {
ShutdownOrInactive {
rx,
timeout: if timeout != Duration::new(0, 0) {
Some(Box::pin(sleep(timeout)))
} else {
None
},
timeout_dur: timeout,
}
.await;
info!("shutting down due to being idle or request");
};
runtime.block_on(async {
futures::select! {
server = server.fuse() => server,
_res = shutdown.fuse() => Ok(()),
_res = shutdown_idle.fuse() => Ok::<_, io::Error>(()),
}
})?;
const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10);
info!(
"moving into the shutdown phase now, waiting at most {} seconds \
for all client requests to complete",
SHUTDOWN_TIMEOUT.as_secs()
);
// Once our server has shut down either due to inactivity or a manual
// request we still need to give a bit of time for all active
// connections to finish. This `wait` future will resolve once all
// instances of `SccacheService` have been dropped.
//
// Note that we cap the amount of time this can take, however, as we
// don't want to wait *too* long.
runtime.block_on(async { time::timeout(SHUTDOWN_TIMEOUT, wait).await })?;
info!("ok, fully shutting down now");
Ok(())
}
}
/// Maps a compiler proxy path to a compiler proxy and it's last modification time
type CompilerProxyMap<C> = HashMap<PathBuf, (Box<dyn CompilerProxy<C>>, FileTime)>;
type CompilerMap<C> = HashMap<PathBuf, Option<CompilerCacheEntry<C>>>;
/// entry of the compiler cache
struct CompilerCacheEntry<C> {
/// compiler argument trait obj
pub compiler: Box<dyn Compiler<C>>,
/// modification time of the compilers executable file
pub mtime: FileTime,
/// distributed compilation extra info
pub dist_info: Option<(PathBuf, FileTime)>,
}
impl<C> CompilerCacheEntry<C> {
fn new(
compiler: Box<dyn Compiler<C>>,
mtime: FileTime,
dist_info: Option<(PathBuf, FileTime)>,
) -> Self {
Self {
compiler,
mtime,
dist_info,
}
}
}
/// Service implementation for sccache
#[derive(Clone)]
pub struct SccacheService<C>
where
C: Send,
{
/// Server statistics.
stats: Arc<Mutex<ServerStats>>,
/// Distributed sccache client
dist_client: Arc<DistClientContainer>,
/// Cache storage.
storage: Arc<dyn Storage>,
/// A cache of known compiler info.
compilers: Arc<RwLock<CompilerMap<C>>>,
/// map the cwd with compiler proxy path to a proxy resolver, which
/// will dynamically resolve the input compiler for the current context
/// (usually file or current working directory)
/// the associated `FileTime` is the modification time of
/// the compiler proxy, in order to track updates of the proxy itself
compiler_proxies: Arc<RwLock<CompilerProxyMap<C>>>,
/// Task pool for blocking (used mostly for disk I/O-bound tasks) and
// non-blocking tasks
rt: tokio::runtime::Handle,
/// An object for creating commands.
///
/// This is mostly useful for unit testing, where we
/// can mock this out.
creator: C,
/// Message channel used to learn about requests received by this server.
///
/// Note that messages sent along this channel will keep the server alive
/// (reset the idle timer) and this channel can also be used to shut down
/// the entire server immediately via a message.
tx: mpsc::Sender<ServerMessage>,
/// Information tracking how many services (connected clients) are active.
/// This field causes [WaitUntilZero] to wait until this struct drops.
#[allow(dead_code)]
info: ActiveInfo,
}
type SccacheRequest = Message<Request, Body<()>>;
type SccacheResponse = Message<Response, Pin<Box<dyn Future<Output = Result<Response>> + Send>>>;
/// Messages sent from all services to the main event loop indicating activity.
///
/// Whenever a request is receive a `Request` message is sent which will reset
/// the idle shutdown timer, and otherwise a `Shutdown` message indicates that
/// a server shutdown was requested via an RPC.
pub enum ServerMessage {
/// A message sent whenever a request is received.
Request,
/// Message sent whenever a shutdown request is received.
Shutdown,
}
impl<C> Service<SccacheRequest> for Arc<SccacheService<C>>
where
C: CommandCreatorSync + Send + Sync + 'static,
{
type Response = SccacheResponse;
type Error = Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response>> + Send + 'static>>;
fn call(&mut self, req: SccacheRequest) -> Self::Future {
trace!("handle_client");
// Opportunistically let channel know that we've received a request. We
// ignore failures here as well as backpressure as it's not imperative
// that every message is received.
drop(self.tx.clone().start_send(ServerMessage::Request));
let me = self.clone();
Box::pin(async move {
match req.into_inner() {
Request::Compile(compile) => {
debug!("handle_client: compile");
me.stats.lock().await.compile_requests += 1;
me.handle_compile(compile).await
}
Request::GetStats => {
debug!("handle_client: get_stats");
me.get_info()
.await
.map(|i| Response::Stats(Box::new(i)))
.map(Message::WithoutBody)
}
Request::DistStatus => {
debug!("handle_client: dist_status");
me.get_dist_status()
.await
.map(Response::DistStatus)
.map(Message::WithoutBody)
}
Request::ZeroStats => {
debug!("handle_client: zero_stats");
me.zero_stats().await;
Ok(Message::WithoutBody(Response::ZeroStats))
}
Request::Shutdown => {
debug!("handle_client: shutdown");
let mut tx = me.tx.clone();
future::try_join(
async {
let _ = tx.send(ServerMessage::Shutdown).await;
Ok(())
},
me.get_info(),
)
.await
.map(move |(_, info)| {
Message::WithoutBody(Response::ShuttingDown(Box::new(info)))
})
}
}
})
}
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<()>> {
Poll::Ready(Ok(()))
}
}
use futures::future::Either;
use futures::TryStreamExt;
impl<C> SccacheService<C>
where
C: CommandCreatorSync + Clone + Send + Sync + 'static,
{
pub fn new(
dist_client: DistClientContainer,
storage: Arc<dyn Storage>,
client: &Client,
rt: tokio::runtime::Handle,
tx: mpsc::Sender<ServerMessage>,
info: ActiveInfo,
) -> SccacheService<C> {
SccacheService {
stats: Arc::default(),
dist_client: Arc::new(dist_client),
storage,
compilers: Arc::default(),
compiler_proxies: Arc::default(),
rt,
creator: C::new(client),
tx,
info,
}
}
pub fn mock_with_storage(
storage: Arc<dyn Storage>,
rt: tokio::runtime::Handle,
) -> SccacheService<C> {
let (tx, _) = mpsc::channel(1);
let (_, info) = WaitUntilZero::new();
let client = Client::new_num(1);
let dist_client = DistClientContainer::new_disabled();
SccacheService {
stats: Arc::default(),
dist_client: Arc::new(dist_client),
storage,
compilers: Arc::default(),
compiler_proxies: Arc::default(),
rt,
creator: C::new(&client),
tx,
info,
}
}
#[cfg(feature = "dist-client")]
pub fn mock_with_dist_client(
dist_client: Arc<dyn dist::Client>,
storage: Arc<dyn Storage>,
rt: tokio::runtime::Handle,
) -> SccacheService<C> {
let (tx, _) = mpsc::channel(1);
let (_, info) = WaitUntilZero::new();
let client = Client::new_num(1);
SccacheService {
stats: Arc::default(),
dist_client: Arc::new(DistClientContainer::new_with_state(DistClientState::Some(
Box::new(DistClientConfig {
pool: rt.clone(),
scheduler_url: None,
auth: config::DistAuth::Token { token: "".into() },
cache_dir: "".into(),
toolchain_cache_size: 0,
toolchains: vec![],
rewrite_includes_only: false,
}),
dist_client,
))),
storage,
compilers: Arc::default(),
compiler_proxies: Arc::default(),
rt: rt.clone(),
creator: C::new(&client),
tx,
info,
}
}
fn bind<T>(self, socket: T) -> impl Future<Output = Result<()>> + Send + Sized + 'static
where
T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
let mut builder = length_delimited::Builder::new();
if let Ok(max_frame_length_str) = env::var("SCCACHE_MAX_FRAME_LENGTH") {
if let Ok(max_frame_length) = max_frame_length_str.parse::<usize>() {
builder.max_frame_length(max_frame_length);
} else {
warn!("Content of SCCACHE_MAX_FRAME_LENGTH is not a valid number, using default");
}
}
let io = builder.new_framed(socket);
let (sink, stream) = SccacheTransport {
inner: Framed::new(io.sink_err_into().err_into(), BincodeCodec),
}
.split();
let sink = sink.sink_err_into::<Error>();
let me = Arc::new(self);
stream
.err_into::<Error>()
.and_then(move |input| me.clone().call(input))
.and_then(move |response| async move {
let fut = match response {
Message::WithoutBody(message) => {
let stream = stream::once(async move { Ok(Frame::Message { message }) });
Either::Left(stream)
}
Message::WithBody(message, body) => {
let stream = stream::once(async move { Ok(Frame::Message { message }) })
.chain(
body.into_stream()
.map_ok(|chunk| Frame::Body { chunk: Some(chunk) }),
)
.chain(stream::once(async move { Ok(Frame::Body { chunk: None }) }));
Either::Right(stream)
}
};
Ok(Box::pin(fut))
})
.try_flatten()
.forward(sink)
}
/// Get dist status.
async fn get_dist_status(&self) -> Result<DistInfo> {
Ok(self.dist_client.get_status().await)
}
/// Get info and stats about the cache.
async fn get_info(&self) -> Result<ServerInfo> {
let stats = self.stats.lock().await.clone();
ServerInfo::new(stats, Some(&*self.storage)).await
}
/// Zero stats about the cache.
async fn zero_stats(&self) {
*self.stats.lock().await = ServerStats::default();
}
/// Handle a compile request from a client.
///
/// This will handle a compile request entirely, generating a response with
/// the initial information and an optional body which will eventually
/// contain the results of the compilation.
async fn handle_compile(&self, compile: Compile) -> Result<SccacheResponse> {