-
Notifications
You must be signed in to change notification settings - Fork 738
Expand file tree
/
Copy pathcompiler.rs
More file actions
3060 lines (2919 loc) · 106 KB
/
Copy pathcompiler.rs
File metadata and controls
3060 lines (2919 loc) · 106 KB
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
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
//
// 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.
use crate::cache::{Cache, CacheWrite, DecompressionFailure, FileObjectSource, Storage};
use crate::compiler::args::*;
use crate::compiler::c::{CCompiler, CCompilerKind};
use crate::compiler::clang::Clang;
use crate::compiler::diab::Diab;
use crate::compiler::gcc::Gcc;
use crate::compiler::msvc;
use crate::compiler::msvc::Msvc;
use crate::compiler::nvcc::Nvcc;
use crate::compiler::nvcc::NvccHostCompiler;
use crate::compiler::nvhpc::Nvhpc;
use crate::compiler::rust::{Rust, RustupProxy};
use crate::compiler::tasking_vx::TaskingVX;
#[cfg(feature = "dist-client")]
use crate::dist::pkg;
#[cfg(feature = "dist-client")]
use crate::lru_disk_cache;
use crate::mock_command::{exit_status, CommandChild, CommandCreatorSync, RunCommand};
use crate::util::{fmt_duration_as_secs, run_input_output};
use crate::{counted_array, dist};
use async_trait::async_trait;
use filetime::FileTime;
use fs::File;
use fs_err as fs;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::future::Future;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::process::{self, Stdio};
use std::str;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tempfile::TempDir;
use crate::errors::*;
/// Can dylibs (shared libraries or proc macros) be distributed on this platform?
#[cfg(all(
feature = "dist-client",
any(
all(target_os = "linux", target_arch = "x86_64"),
target_os = "freebsd"
)
))]
pub const CAN_DIST_DYLIBS: bool = true;
#[cfg(all(
feature = "dist-client",
not(any(
all(target_os = "linux", target_arch = "x86_64"),
target_os = "freebsd"
))
))]
pub const CAN_DIST_DYLIBS: bool = false;
#[derive(Clone, Debug)]
pub struct CompileCommand {
pub executable: PathBuf,
pub arguments: Vec<OsString>,
pub env_vars: Vec<(OsString, OsString)>,
pub cwd: PathBuf,
}
impl CompileCommand {
pub async fn execute<T>(self, creator: &T) -> Result<process::Output>
where
T: CommandCreatorSync,
{
let mut cmd = creator.clone().new_command_sync(self.executable);
cmd.args(&self.arguments)
.env_clear()
.envs(self.env_vars)
.current_dir(self.cwd);
run_input_output(cmd, None).await
}
}
/// Supported compilers.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum CompilerKind {
/// A C compiler.
C(CCompilerKind),
/// A Rust compiler.
Rust,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Language {
C,
Cxx,
GenericHeader,
CHeader,
CxxHeader,
ObjectiveC,
ObjectiveCxx,
Cuda,
Rust,
Hip,
}
impl Language {
pub fn from_file_name(file: &Path) -> Option<Self> {
match file.extension().and_then(|e| e.to_str()) {
// gcc: https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html
Some("c") => Some(Language::C),
// Could be C or C++
Some("h") => Some(Language::GenericHeader),
// TODO i
Some("C") | Some("cc") | Some("cp") | Some("cpp") | Some("CPP") | Some("cxx")
| Some("c++") => Some(Language::Cxx),
// TODO ii
Some("H") | Some("hh") | Some("hp") | Some("hpp") | Some("HPP") | Some("hxx")
| Some("h++") | Some("tcc") => Some(Language::CxxHeader),
Some("m") => Some(Language::ObjectiveC),
// TODO mi
Some("M") | Some("mm") => Some(Language::ObjectiveCxx),
// TODO mii
Some("cu") => Some(Language::Cuda),
// TODO cy
Some("rs") => Some(Language::Rust),
Some("hip") => Some(Language::Hip),
e => {
trace!("Unknown source extension: {}", e.unwrap_or("(None)"));
None
}
}
}
pub fn as_str(self) -> &'static str {
match self {
Language::C | Language::CHeader => "c",
Language::Cxx | Language::CxxHeader => "c++",
Language::GenericHeader => "c/c++",
Language::ObjectiveC => "objc",
Language::ObjectiveCxx => "objc++",
Language::Cuda => "cuda",
Language::Rust => "rust",
Language::Hip => "hip",
}
}
}
impl CompilerKind {
pub fn lang_kind(&self, lang: &Language) -> String {
match lang {
Language::C
| Language::CHeader
| Language::Cxx
| Language::CxxHeader
| Language::GenericHeader
| Language::ObjectiveC
| Language::ObjectiveCxx => "C/C++",
Language::Cuda => "CUDA",
Language::Rust => "Rust",
Language::Hip => "HIP",
}
.to_string()
}
pub fn lang_comp_kind(&self, lang: &Language) -> String {
let textual_lang = lang.as_str().to_owned();
match self {
CompilerKind::C(CCompilerKind::Clang) => textual_lang + " [clang]",
CompilerKind::C(CCompilerKind::Diab) => textual_lang + " [diab]",
CompilerKind::C(CCompilerKind::Gcc) => textual_lang + " [gcc]",
CompilerKind::C(CCompilerKind::Msvc) => textual_lang + " [msvc]",
CompilerKind::C(CCompilerKind::Nvhpc) => textual_lang + " [nvhpc]",
CompilerKind::C(CCompilerKind::Nvcc) => textual_lang + " [nvcc]",
CompilerKind::C(CCompilerKind::TaskingVX) => textual_lang + " [taskingvx]",
CompilerKind::Rust => textual_lang,
}
}
}
#[cfg(feature = "dist-client")]
pub type DistPackagers = (
Box<dyn pkg::InputsPackager>,
Box<dyn pkg::ToolchainPackager>,
Box<dyn OutputsRewriter>,
);
enum CacheLookupResult {
Success(CompileResult, process::Output),
Miss(MissType),
}
/// An interface to a compiler for argument parsing.
pub trait Compiler<T>: Send + Sync + 'static
where
T: CommandCreatorSync,
{
/// Return the kind of compiler.
fn kind(&self) -> CompilerKind;
/// Retrieve a packager
#[cfg(feature = "dist-client")]
fn get_toolchain_packager(&self) -> Box<dyn pkg::ToolchainPackager>;
/// Determine whether `arguments` are supported by this compiler.
fn parse_arguments(
&self,
arguments: &[OsString],
cwd: &Path,
env_vars: &[(OsString, OsString)],
) -> CompilerArguments<Box<dyn CompilerHasher<T> + 'static>>;
fn box_clone(&self) -> Box<dyn Compiler<T>>;
}
impl<T: CommandCreatorSync> Clone for Box<dyn Compiler<T>> {
fn clone(&self) -> Box<dyn Compiler<T>> {
self.box_clone()
}
}
pub trait CompilerProxy<T>: Send + Sync + 'static
where
T: CommandCreatorSync + Sized,
{
/// Maps the executable to be used in `cwd` to the true, proxied compiler.
///
/// Returns the absolute path to the true compiler and the timestamp of
/// timestamp of the true compiler. Iff the resolution fails,
/// the returned future resolves to an error with more information.
fn resolve_proxied_executable(
&self,
creator: T,
cwd: PathBuf,
env_vars: &[(OsString, OsString)],
) -> Pin<Box<dyn Future<Output = Result<(PathBuf, FileTime)>> + Send + 'static>>;
/// Create a clone of `Self` and puts it in a `Box`
fn box_clone(&self) -> Box<dyn CompilerProxy<T>>;
}
impl<T: CommandCreatorSync> Clone for Box<dyn CompilerProxy<T>> {
fn clone(&self) -> Box<dyn CompilerProxy<T>> {
self.box_clone()
}
}
/// An interface to a compiler for hash key generation, the result of
/// argument parsing.
#[async_trait]
pub trait CompilerHasher<T>: fmt::Debug + Send + 'static
where
T: CommandCreatorSync,
{
/// Given information about a compiler command, generate a hash key
/// that can be used for cache lookups, as well as any additional
/// information that can be reused for compilation if necessary.
#[allow(clippy::too_many_arguments)]
async fn generate_hash_key(
self: Box<Self>,
creator: &T,
cwd: PathBuf,
env_vars: Vec<(OsString, OsString)>,
may_dist: bool,
pool: &tokio::runtime::Handle,
rewrite_includes_only: bool,
storage: Arc<dyn Storage>,
cache_control: CacheControl,
) -> Result<HashResult>;
/// Return the state of any `--color` option passed to the compiler.
fn color_mode(&self) -> ColorMode;
/// Look up a cached compile result in `storage`. If not found, run the
/// compile and store the result.
#[allow(clippy::too_many_arguments)]
async fn get_cached_or_compile(
self: Box<Self>,
dist_client: Option<Arc<dyn dist::Client>>,
creator: T,
storage: Arc<dyn Storage>,
arguments: Vec<OsString>,
cwd: PathBuf,
env_vars: Vec<(OsString, OsString)>,
cache_control: CacheControl,
pool: tokio::runtime::Handle,
) -> Result<(CompileResult, process::Output)> {
let out_pretty = self.output_pretty().into_owned();
debug!("[{}]: get_cached_or_compile: {:?}", out_pretty, arguments);
let start = Instant::now();
let may_dist = dist_client.is_some();
let rewrite_includes_only = match dist_client {
Some(ref client) => client.rewrite_includes_only(),
_ => false,
};
let result = self
.generate_hash_key(
&creator,
cwd.clone(),
env_vars,
may_dist,
&pool,
rewrite_includes_only,
storage.clone(),
cache_control,
)
.await;
debug!(
"[{}]: generate_hash_key took {}",
out_pretty,
fmt_duration_as_secs(&start.elapsed())
);
let (key, compilation, weak_toolchain_key) = match result {
Err(e) => {
return match e.downcast::<ProcessError>() {
Ok(ProcessError(output)) => Ok((CompileResult::Error, output)),
Err(e) => Err(e),
};
}
Ok(HashResult {
key,
compilation,
weak_toolchain_key,
}) => (key, compilation, weak_toolchain_key),
};
debug!("[{}]: Hash key: {}", out_pretty, key);
// If `ForceRecache` is enabled, we won't check the cache.
let start = Instant::now();
let cache_status = async {
if cache_control == CacheControl::ForceRecache {
Ok(Cache::Recache)
} else {
storage.get(&key).await
}
};
// Set a maximum time limit for the cache to respond before we forge
// ahead ourselves with a compilation.
let timeout = Duration::new(60, 0);
let cache_status = async {
let res = tokio::time::timeout(timeout, cache_status).await;
let duration = start.elapsed();
(res, duration)
};
// Check the result of the cache lookup.
let outputs = compilation
.outputs()
.map(|output| FileObjectSource {
path: cwd.join(output.path),
..output
})
.collect::<Vec<_>>();
let lookup = match cache_status.await {
(Ok(Ok(Cache::Hit(mut entry))), duration) => {
debug!(
"[{}]: Cache hit in {}",
out_pretty,
fmt_duration_as_secs(&duration)
);
let stdout = entry.get_stdout();
let stderr = entry.get_stderr();
let output = process::Output {
status: exit_status(0),
stdout,
stderr,
};
let hit = CompileResult::CacheHit(duration);
match entry.extract_objects(outputs.clone(), &pool).await {
Ok(()) => Ok(CacheLookupResult::Success(hit, output)),
Err(e) => {
if e.downcast_ref::<DecompressionFailure>().is_some() {
debug!("[{}]: Failed to decompress object", out_pretty);
Ok(CacheLookupResult::Miss(MissType::CacheReadError))
} else {
Err(e)
}
}
}
}
(Ok(Ok(Cache::Miss)), duration) => {
debug!(
"[{}]: Cache miss in {}",
out_pretty,
fmt_duration_as_secs(&duration)
);
Ok(CacheLookupResult::Miss(MissType::Normal))
}
(Ok(Ok(Cache::Recache)), duration) => {
debug!(
"[{}]: Cache recache in {}",
out_pretty,
fmt_duration_as_secs(&duration)
);
Ok(CacheLookupResult::Miss(MissType::ForcedRecache))
}
(Ok(Err(err)), duration) => {
error!(
"[{}]: Cache read error: {:?} in {}",
out_pretty,
err,
fmt_duration_as_secs(&duration)
);
Ok(CacheLookupResult::Miss(MissType::CacheReadError))
}
(Err(_), duration) => {
debug!(
"[{}]: Cache timed out {}",
out_pretty,
fmt_duration_as_secs(&duration)
);
Ok(CacheLookupResult::Miss(MissType::TimedOut))
}
}?;
match lookup {
CacheLookupResult::Success(compile_result, output) => {
Ok::<_, Error>((compile_result, output))
}
CacheLookupResult::Miss(miss_type) => {
// Cache miss, so compile it.
let start = Instant::now();
let (cacheable, dist_type, compiler_result) = dist_or_local_compile(
dist_client,
creator,
cwd,
compilation,
weak_toolchain_key,
out_pretty.clone(),
)
.await?;
let duration_compilation = start.elapsed();
if !compiler_result.status.success() {
debug!(
"[{}]: Compiled in {}, but failed, not storing in cache",
out_pretty,
fmt_duration_as_secs(&duration_compilation)
);
return Ok((CompileResult::CompileFailed, compiler_result));
}
if cacheable != Cacheable::Yes {
// Not cacheable
debug!(
"[{}]: Compiled in {}, but not cacheable",
out_pretty,
fmt_duration_as_secs(&duration_compilation)
);
return Ok((CompileResult::NotCacheable, compiler_result));
}
debug!(
"[{}]: Compiled in {}, storing in cache",
out_pretty,
fmt_duration_as_secs(&duration_compilation)
);
let start_create_artifact = Instant::now();
let mut entry = CacheWrite::from_objects(outputs, &pool)
.await
.context("failed to zip up compiler outputs")?;
entry.put_stdout(&compiler_result.stdout)?;
entry.put_stderr(&compiler_result.stderr)?;
debug!(
"[{}]: Created cache artifact in {}",
out_pretty,
fmt_duration_as_secs(&start_create_artifact.elapsed())
);
let out_pretty2 = out_pretty.clone();
// Try to finish storing the newly-written cache
// entry. We'll get the result back elsewhere.
let future = async move {
let start = Instant::now();
match storage.put(&key, entry).await {
Ok(_) => {
debug!("[{}]: Stored in cache successfully!", out_pretty2);
Ok(CacheWriteInfo {
object_file_pretty: out_pretty2,
duration: start.elapsed(),
})
}
Err(e) => Err(e),
}
};
let future = Box::pin(future);
Ok((
CompileResult::CacheMiss(miss_type, dist_type, duration_compilation, future),
compiler_result,
))
}
}
.with_context(|| format!("failed to store `{}` to cache", out_pretty))
}
/// A descriptive string about the file that we're going to be producing.
///
/// This is primarily intended for debug logging and such, not for actual
/// artifact generation.
fn output_pretty(&self) -> Cow<'_, str>;
fn box_clone(&self) -> Box<dyn CompilerHasher<T>>;
fn language(&self) -> Language;
}
#[cfg(not(feature = "dist-client"))]
async fn dist_or_local_compile<T>(
_dist_client: Option<Arc<dyn dist::Client>>,
creator: T,
_cwd: PathBuf,
compilation: Box<dyn Compilation>,
_weak_toolchain_key: String,
out_pretty: String,
) -> Result<(Cacheable, DistType, process::Output)>
where
T: CommandCreatorSync,
{
let mut path_transformer = dist::PathTransformer::new();
let (compile_cmd, _dist_compile_cmd, cacheable) = compilation
.generate_compile_commands(&mut path_transformer, true)
.context("Failed to generate compile commands")?;
debug!("[{}]: Compiling locally", out_pretty);
compile_cmd
.execute(&creator)
.await
.map(move |o| (cacheable, DistType::NoDist, o))
}
#[cfg(feature = "dist-client")]
async fn dist_or_local_compile<T>(
dist_client: Option<Arc<dyn dist::Client>>,
creator: T,
cwd: PathBuf,
compilation: Box<dyn Compilation>,
weak_toolchain_key: String,
out_pretty: String,
) -> Result<(Cacheable, DistType, process::Output)>
where
T: CommandCreatorSync,
{
use std::io;
let rewrite_includes_only = match dist_client {
Some(ref client) => client.rewrite_includes_only(),
_ => false,
};
let mut path_transformer = dist::PathTransformer::new();
let (compile_cmd, dist_compile_cmd, cacheable) = compilation
.generate_compile_commands(&mut path_transformer, rewrite_includes_only)
.context("Failed to generate compile commands")?;
let dist_client = match dist_client {
Some(dc) => dc,
None => {
debug!("[{}]: Compiling locally", out_pretty);
return compile_cmd
.execute(&creator)
.await
.map(move |o| (cacheable, DistType::NoDist, o));
}
};
debug!("[{}]: Attempting distributed compilation", out_pretty);
let out_pretty2 = out_pretty.clone();
let local_executable = compile_cmd.executable.clone();
let local_executable2 = compile_cmd.executable.clone();
let do_dist_compile = async move {
let mut dist_compile_cmd =
dist_compile_cmd.context("Could not create distributed compile command")?;
debug!("[{}]: Creating distributed compile request", out_pretty);
let dist_output_paths = compilation
.outputs()
.map(|output| path_transformer.as_dist_abs(&cwd.join(output.path)))
.collect::<Option<_>>()
.context("Failed to adapt an output path for distributed compile")?;
let (inputs_packager, toolchain_packager, outputs_rewriter) =
compilation.into_dist_packagers(path_transformer)?;
debug!(
"[{}]: Identifying dist toolchain for {:?}",
out_pretty, local_executable
);
let (dist_toolchain, maybe_dist_compile_executable) = dist_client
.put_toolchain(local_executable, weak_toolchain_key, toolchain_packager)
.await?;
let mut tc_archive = None;
if let Some((dist_compile_executable, archive_path)) = maybe_dist_compile_executable {
dist_compile_cmd.executable = dist_compile_executable;
tc_archive = Some(archive_path);
}
debug!("[{}]: Requesting allocation", out_pretty);
let jares = dist_client.do_alloc_job(dist_toolchain.clone()).await?;
let job_alloc = match jares {
dist::AllocJobResult::Success {
job_alloc,
need_toolchain: true,
} => {
debug!(
"[{}]: Sending toolchain {} for job {}",
out_pretty, dist_toolchain.archive_id, job_alloc.job_id
);
match dist_client
.do_submit_toolchain(job_alloc.clone(), dist_toolchain)
.await
.map_err(|e| e.context("Could not submit toolchain"))?
{
dist::SubmitToolchainResult::Success => Ok(job_alloc),
dist::SubmitToolchainResult::JobNotFound => {
bail!("Job {} not found on server", job_alloc.job_id)
}
dist::SubmitToolchainResult::CannotCache => bail!(
"Toolchain for job {} could not be cached by server",
job_alloc.job_id
),
}
}
dist::AllocJobResult::Success {
job_alloc,
need_toolchain: false,
} => Ok(job_alloc),
dist::AllocJobResult::Fail { msg } => {
Err(anyhow!("Failed to allocate job").context(msg))
}
}?;
let job_id = job_alloc.job_id;
let server_id = job_alloc.server_id;
debug!("[{}]: Running job", out_pretty);
let ((job_id, server_id), (jres, path_transformer)) = dist_client
.do_run_job(
job_alloc,
dist_compile_cmd,
dist_output_paths,
inputs_packager,
)
.await
.map(move |res| ((job_id, server_id), res))
.with_context(|| {
format!(
"could not run distributed compilation job on {:?}",
server_id
)
})?;
let jc = match jres {
dist::RunJobResult::Complete(jc) => jc,
dist::RunJobResult::JobNotFound => bail!("Job {} not found on server", job_id),
};
info!(
"fetched {:?}",
jc.outputs
.iter()
.map(|(p, bs)| (p, bs.lens().to_string()))
.collect::<Vec<_>>()
);
let mut output_paths: Vec<PathBuf> = vec![];
macro_rules! try_or_cleanup {
($v:expr) => {{
match $v {
Ok(v) => v,
Err(e) => {
// Do our best to clear up. We may end up deleting a file that we just wrote over
// the top of, but it's better to clear up too much than too little
for local_path in output_paths.iter() {
if let Err(e) = fs::remove_file(local_path) {
if e.kind() != io::ErrorKind::NotFound {
warn!("{} while attempting to clear up {}", e, local_path.display())
}
}
}
return Err(e)
},
}
}};
}
for (path, output_data) in jc.outputs {
let len = output_data.lens().actual;
let local_path = try_or_cleanup!(path_transformer
.to_local(&path)
.with_context(|| format!("unable to transform output path {}", path)));
output_paths.push(local_path);
// Do this first so cleanup works correctly
let local_path = output_paths.last().expect("nothing in vec after push");
let mut file = try_or_cleanup!(File::create(local_path)
.with_context(|| format!("Failed to create output file {}", local_path.display())));
let count = try_or_cleanup!(io::copy(&mut output_data.into_reader(), &mut file)
.with_context(|| format!("Failed to write output to {}", local_path.display())));
assert!(count == len);
}
let extra_inputs = match tc_archive {
Some(p) => vec![p],
None => vec![],
};
try_or_cleanup!(outputs_rewriter
.handle_outputs(&path_transformer, &output_paths, &extra_inputs)
.with_context(|| "failed to rewrite outputs from compile"));
Ok((DistType::Ok(server_id), jc.output.into()))
};
use futures::TryFutureExt;
do_dist_compile
.or_else(move |e| async move {
if let Some(HttpClientError(_)) = e.downcast_ref::<HttpClientError>() {
Err(e)
} else if let Some(lru_disk_cache::Error::FileTooLarge) =
e.downcast_ref::<lru_disk_cache::Error>()
{
Err(anyhow!(
"Could not cache dist toolchain for {:?} locally.
Increase `toolchain_cache_size` or decrease the toolchain archive size.",
local_executable2
))
} else {
// `{:#}` prints the error and the causes in a single line.
let errmsg = format!("{:#}", e);
warn!(
"[{}]: Could not perform distributed compile, falling back to local: {}",
out_pretty2, errmsg
);
compile_cmd
.execute(&creator)
.await
.map(|o| (DistType::Error, o))
}
})
.map_ok(move |(dt, o)| (cacheable, dt, o))
.await
}
impl<T: CommandCreatorSync> Clone for Box<dyn CompilerHasher<T>> {
fn clone(&self) -> Box<dyn CompilerHasher<T>> {
self.box_clone()
}
}
/// An interface to a compiler for actually invoking compilation.
pub trait Compilation: Send {
/// Given information about a compiler command, generate a command that can
/// execute the compiler.
fn generate_compile_commands(
&self,
path_transformer: &mut dist::PathTransformer,
rewrite_includes_only: bool,
) -> Result<(CompileCommand, Option<dist::CompileCommand>, Cacheable)>;
/// Create a function that will create the inputs used to perform a distributed compilation
#[cfg(feature = "dist-client")]
fn into_dist_packagers(
self: Box<Self>,
_path_transformer: dist::PathTransformer,
) -> Result<DistPackagers>;
/// Returns an iterator over the results of this compilation.
///
/// Each item is a descriptive (and unique) name of the output paired with
/// the path where it'll show up.
fn outputs<'a>(&'a self) -> Box<dyn Iterator<Item = FileObjectSource> + 'a>;
}
#[cfg(feature = "dist-client")]
pub trait OutputsRewriter: Send {
/// Perform any post-compilation handling of outputs, given a Vec of the dist_path and local_path
fn handle_outputs(
self: Box<Self>,
path_transformer: &dist::PathTransformer,
output_paths: &[PathBuf],
extra_inputs: &[PathBuf],
) -> Result<()>;
}
#[cfg(feature = "dist-client")]
pub struct NoopOutputsRewriter;
#[cfg(feature = "dist-client")]
impl OutputsRewriter for NoopOutputsRewriter {
fn handle_outputs(
self: Box<Self>,
_path_transformer: &dist::PathTransformer,
_output_paths: &[PathBuf],
_extra_inputs: &[PathBuf],
) -> Result<()> {
Ok(())
}
}
/// Result of generating a hash from a compiler command.
pub struct HashResult {
/// The hash key of the inputs.
pub key: String,
/// An object to use for the actual compilation, if necessary.
pub compilation: Box<dyn Compilation + 'static>,
/// A weak key that may be used to identify the toolchain
pub weak_toolchain_key: String,
}
/// Possible results of parsing compiler arguments.
#[derive(Debug, PartialEq, Eq)]
pub enum CompilerArguments<T> {
/// Commandline can be handled.
Ok(T),
/// Cannot cache this compilation.
CannotCache(&'static str, Option<String>),
/// This commandline is not a compile.
NotCompilation,
}
macro_rules! cannot_cache {
($why:expr) => {
return CompilerArguments::CannotCache($why, None)
};
($why:expr, $extra_info:expr) => {
return CompilerArguments::CannotCache($why, Some($extra_info))
};
}
macro_rules! try_or_cannot_cache {
($arg:expr, $why:expr) => {{
match $arg {
Ok(arg) => arg,
Err(e) => cannot_cache!($why, e.to_string()),
}
}};
}
/// Specifics about distributed compilation.
#[derive(Debug, PartialEq, Eq)]
pub enum DistType {
/// Distribution was not enabled.
NoDist,
/// Distributed compile success.
Ok(dist::ServerId),
/// Distributed compile failed.
Error,
}
/// Specifics about cache misses.
#[derive(Debug, PartialEq, Eq)]
pub enum MissType {
/// The compilation was not found in the cache, nothing more.
Normal,
/// Cache lookup was overridden, recompilation was forced.
ForcedRecache,
/// Cache took too long to respond.
TimedOut,
/// Error reading from cache
CacheReadError,
}
/// Information about a successful cache write.
pub struct CacheWriteInfo {
pub object_file_pretty: String,
pub duration: Duration,
}
/// The result of a compilation or cache retrieval.
pub enum CompileResult {
/// An error made the compilation not possible.
Error,
/// Result was found in cache.
CacheHit(Duration),
/// Result was not found in cache.
///
/// The `CacheWriteFuture` will resolve when the result is finished
/// being stored in the cache.
CacheMiss(
MissType,
DistType,
Duration, // Compilation time
Pin<Box<dyn Future<Output = Result<CacheWriteInfo>> + Send>>,
),
/// Not in cache, but the compilation result was determined to be not cacheable.
NotCacheable,
/// Not in cache, but compilation failed.
CompileFailed,
}
/// The state of `--color` options passed to a compiler.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum ColorMode {
Off,
On,
#[default]
Auto,
}
/// Can't derive(Debug) because of `CacheWriteFuture`.
impl fmt::Debug for CompileResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
CompileResult::Error => write!(f, "CompileResult::Error"),
CompileResult::CacheHit(ref d) => write!(f, "CompileResult::CacheHit({:?})", d),
CompileResult::CacheMiss(ref m, ref dt, ref d, _) => {
write!(f, "CompileResult::CacheMiss({:?}, {:?}, {:?}, _)", d, m, dt)
}
CompileResult::NotCacheable => write!(f, "CompileResult::NotCacheable"),
CompileResult::CompileFailed => write!(f, "CompileResult::CompileFailed"),
}
}
}
/// Can't use derive(PartialEq) because of the `CacheWriteFuture`.
impl PartialEq<CompileResult> for CompileResult {
fn eq(&self, other: &CompileResult) -> bool {
match (self, other) {
(&CompileResult::Error, &CompileResult::Error) => true,
(&CompileResult::CacheHit(_), &CompileResult::CacheHit(_)) => true,
(CompileResult::CacheMiss(m, dt, _, _), CompileResult::CacheMiss(n, dt2, _, _)) => {
m == n && dt == dt2
}
(&CompileResult::NotCacheable, &CompileResult::NotCacheable) => true,
(&CompileResult::CompileFailed, &CompileResult::CompileFailed) => true,
_ => false,
}
}
}
/// Can this result be stored in cache?
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Cacheable {
Yes,
No,
}
/// Control of caching behavior.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum CacheControl {
/// Default caching behavior.
Default,
/// Ignore existing cache entries, force recompilation.
ForceRecache,
}
/// Creates a future that will write `contents` to `path` inside of a temporary
/// directory.
///
/// The future will resolve to the temporary directory and an absolute path
/// inside that temporary directory with a file that has the same filename as
/// `path` contains the `contents` specified.
///
/// Note that when the `TempDir` is dropped it will delete all of its contents
/// including the path returned.
pub async fn write_temp_file(
pool: &tokio::runtime::Handle,
path: &Path,
contents: Vec<u8>,
) -> Result<(TempDir, PathBuf)> {
let path = path.to_owned();
pool.spawn_blocking(move || {
let dir = tempfile::Builder::new().prefix("sccache").tempdir()?;
let src = dir.path().join(path);
let mut file = File::create(&src)?;
file.write_all(&contents)?;
Ok::<_, anyhow::Error>((dir, src))
})
.await?
.context("failed to write temporary file")
}
/// Returns true if the given path looks like a program known to have
/// a rustc compatible interface.
fn is_rustc_like<P: AsRef<Path>>(p: P) -> bool {
matches!(
p.as_ref()
.file_stem()
.map(|s| s.to_string_lossy().to_lowercase())
.as_deref(),
Some("rustc") | Some("clippy-driver")
)
}
/// Returns true if the given path looks like a c compiler program
///
/// This does not check c compilers, it only report programs that are definitely not rustc
fn is_known_c_compiler<P: AsRef<Path>>(p: P) -> bool {
matches!(
p.as_ref()
.file_stem()
.map(|s| s.to_string_lossy().to_lowercase())
.as_deref(),
Some(
"cc" | "c++"
| "gcc"
| "g++"
| "clang"