-
Notifications
You must be signed in to change notification settings - Fork 566
/
Copy pathconfig.rs
1663 lines (1485 loc) · 51.2 KB
/
config.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.
use crate::cache::CacheMode;
use directories::ProjectDirs;
use fs::File;
use fs_err as fs;
use once_cell::sync::Lazy;
#[cfg(any(feature = "dist-client", feature = "dist-server"))]
use serde::ser::Serializer;
use serde::{
de::{DeserializeOwned, Deserializer},
Deserialize, Serialize,
};
#[cfg(test)]
use serial_test::serial;
use std::collections::HashMap;
use std::env;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::result::Result as StdResult;
use std::str::FromStr;
use std::sync::Mutex;
pub use crate::cache::PreprocessorCacheModeConfig;
use crate::errors::*;
static CACHED_CONFIG_PATH: Lazy<PathBuf> = Lazy::new(CachedConfig::file_config_path);
static CACHED_CONFIG: Mutex<Option<CachedFileConfig>> = Mutex::new(None);
const ORGANIZATION: &str = "Mozilla";
const APP_NAME: &str = "sccache";
const DIST_APP_NAME: &str = "sccache-dist-client";
const TEN_GIGS: u64 = 10 * 1024 * 1024 * 1024;
const MOZILLA_OAUTH_PKCE_CLIENT_ID: &str = "F1VVD6nRTckSVrviMRaOdLBWIk1AvHYo";
// The sccache audience is an API set up in auth0 for sccache to allow 7 day expiry,
// the openid scope allows us to query the auth0 /userinfo endpoint which contains
// group information due to Mozilla rules.
const MOZILLA_OAUTH_PKCE_AUTH_URL: &str =
"https://auth.mozilla.auth0.com/authorize?audience=sccache&scope=openid%20profile";
const MOZILLA_OAUTH_PKCE_TOKEN_URL: &str = "https://auth.mozilla.auth0.com/oauth/token";
pub const INSECURE_DIST_CLIENT_TOKEN: &str = "dangerously_insecure_client";
// Unfortunately this means that nothing else can use the sccache cache dir as
// this top level directory is used directly to store sccache cached objects...
pub fn default_disk_cache_dir() -> PathBuf {
ProjectDirs::from("", ORGANIZATION, APP_NAME)
.expect("Unable to retrieve disk cache directory")
.cache_dir()
.to_owned()
}
// ...whereas subdirectories are used of this one
pub fn default_dist_cache_dir() -> PathBuf {
ProjectDirs::from("", ORGANIZATION, DIST_APP_NAME)
.expect("Unable to retrieve dist cache directory")
.cache_dir()
.to_owned()
}
fn default_disk_cache_size() -> u64 {
TEN_GIGS
}
fn default_toolchain_cache_size() -> u64 {
TEN_GIGS
}
pub fn parse_size(val: &str) -> Option<u64> {
let multiplier = match val.chars().last() {
Some('K') => 1024,
Some('M') => 1024 * 1024,
Some('G') => 1024 * 1024 * 1024,
Some('T') => 1024 * 1024 * 1024 * 1024,
_ => 1,
};
let val = if multiplier > 1 && !val.is_empty() {
val.split_at(val.len() - 1).0
} else {
val
};
u64::from_str(val).ok().map(|size| size * multiplier)
}
#[cfg(any(feature = "dist-client", feature = "dist-server"))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HTTPUrl(reqwest::Url);
#[cfg(any(feature = "dist-client", feature = "dist-server"))]
impl Serialize for HTTPUrl {
fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.0.as_str())
}
}
#[cfg(any(feature = "dist-client", feature = "dist-server"))]
impl<'a> Deserialize<'a> for HTTPUrl {
fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error>
where
D: Deserializer<'a>,
{
use serde::de::Error;
let helper: String = Deserialize::deserialize(deserializer)?;
let url = parse_http_url(&helper).map_err(D::Error::custom)?;
Ok(HTTPUrl(url))
}
}
#[cfg(any(feature = "dist-client", feature = "dist-server"))]
fn parse_http_url(url: &str) -> Result<reqwest::Url> {
use std::net::SocketAddr;
let url = if let Ok(sa) = url.parse::<SocketAddr>() {
warn!("Url {} has no scheme, assuming http", url);
reqwest::Url::parse(&format!("http://{}", sa))
} else {
reqwest::Url::parse(url)
}?;
if url.scheme() != "http" && url.scheme() != "https" {
bail!("url not http or https")
}
// TODO: relative url handling just hasn't been implemented and tested
if url.path() != "/" {
bail!("url has a relative path (currently unsupported)")
}
Ok(url)
}
#[cfg(any(feature = "dist-client", feature = "dist-server"))]
impl HTTPUrl {
pub fn from_url(u: reqwest::Url) -> Self {
HTTPUrl(u)
}
pub fn to_url(&self) -> reqwest::Url {
self.0.clone()
}
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AzureCacheConfig {
pub connection_string: String,
pub container: String,
pub key_prefix: String,
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(default)]
pub struct DiskCacheConfig {
pub dir: PathBuf,
// TODO: use deserialize_with to allow human-readable sizes in toml
pub size: u64,
pub preprocessor_cache_mode: PreprocessorCacheModeConfig,
pub rw_mode: CacheModeConfig,
}
impl Default for DiskCacheConfig {
fn default() -> Self {
DiskCacheConfig {
dir: default_disk_cache_dir(),
size: default_disk_cache_size(),
preprocessor_cache_mode: PreprocessorCacheModeConfig::activated(),
rw_mode: CacheModeConfig::ReadWrite,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum CacheModeConfig {
#[serde(rename = "READ_ONLY")]
ReadOnly,
#[serde(rename = "READ_WRITE")]
ReadWrite,
}
impl From<CacheModeConfig> for CacheMode {
fn from(value: CacheModeConfig) -> Self {
match value {
CacheModeConfig::ReadOnly => CacheMode::ReadOnly,
CacheModeConfig::ReadWrite => CacheMode::ReadWrite,
}
}
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GCSCacheConfig {
pub bucket: String,
pub key_prefix: String,
pub cred_path: Option<String>,
pub service_account: Option<String>,
pub rw_mode: CacheModeConfig,
pub credential_url: Option<String>,
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GHACacheConfig {
pub enabled: bool,
/// Version for gha cache is a namespace. By setting different versions,
/// we can avoid mixed caches.
pub version: String,
}
/// Memcached's default value of expiration is 10800s (3 hours), which is too
/// short for use case of sccache.
///
/// We increase the default expiration to 86400s (1 day) to balance between
/// memory consumpation and cache hit rate.
///
/// Please change this value freely if we have a better choice.
const DEFAULT_MEMCACHED_CACHE_EXPIRATION: u32 = 86400;
fn default_memcached_cache_expiration() -> u32 {
DEFAULT_MEMCACHED_CACHE_EXPIRATION
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct MemcachedCacheConfig {
#[serde(alias = "endpoint")]
pub url: String,
/// Username to authenticate with.
pub username: Option<String>,
/// Password to authenticate with.
pub password: Option<String>,
/// the expiration time in seconds.
///
/// Default to 24 hours (86400)
/// Up to 30 days (2592000)
#[serde(default = "default_memcached_cache_expiration")]
pub expiration: u32,
#[serde(default)]
pub key_prefix: String,
}
/// redis has no default TTL - all caches live forever
///
/// We keep the TTL as 0 here as redis does
///
/// Please change this value freely if we have a better choice.
const DEFAULT_REDIS_CACHE_TTL: u64 = 0;
pub const DEFAULT_REDIS_DB: u32 = 0;
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct RedisCacheConfig {
/// The single-node redis endpoint.
/// Mutually exclusive with `cluster_endpoints`.
pub endpoint: Option<String>,
/// The redis cluster endpoints.
/// Mutually exclusive with `endpoint`.
pub cluster_endpoints: Option<String>,
/// Username to authenticate with.
pub username: Option<String>,
/// Password to authenticate with.
pub password: Option<String>,
/// The redis URL.
/// Deprecated in favor of `endpoint`.
pub url: Option<String>,
/// the db number to use
///
/// Default to 0
#[serde(default)]
pub db: u32,
/// the ttl (expiration) time in seconds.
///
/// Default to infinity (0)
#[serde(default, alias = "expiration")]
pub ttl: u64,
#[serde(default)]
pub key_prefix: String,
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WebdavCacheConfig {
pub endpoint: String,
#[serde(default)]
pub key_prefix: String,
pub username: Option<String>,
pub password: Option<String>,
pub token: Option<String>,
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct S3CacheConfig {
pub bucket: String,
pub region: Option<String>,
#[serde(default)]
pub key_prefix: String,
pub no_credentials: bool,
pub endpoint: Option<String>,
pub use_ssl: Option<bool>,
pub server_side_encryption: Option<bool>,
pub enable_virtual_host_style: Option<bool>,
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OSSCacheConfig {
pub bucket: String,
#[serde(default)]
pub key_prefix: String,
pub endpoint: Option<String>,
pub no_credentials: bool,
}
#[derive(Debug, PartialEq, Eq)]
pub enum CacheType {
Azure(AzureCacheConfig),
GCS(GCSCacheConfig),
GHA(GHACacheConfig),
Memcached(MemcachedCacheConfig),
Redis(RedisCacheConfig),
S3(S3CacheConfig),
Webdav(WebdavCacheConfig),
OSS(OSSCacheConfig),
}
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct CacheConfigs {
pub azure: Option<AzureCacheConfig>,
pub disk: Option<DiskCacheConfig>,
pub gcs: Option<GCSCacheConfig>,
pub gha: Option<GHACacheConfig>,
pub memcached: Option<MemcachedCacheConfig>,
pub redis: Option<RedisCacheConfig>,
pub s3: Option<S3CacheConfig>,
pub webdav: Option<WebdavCacheConfig>,
pub oss: Option<OSSCacheConfig>,
}
impl CacheConfigs {
/// Return cache type in an arbitrary but
/// consistent ordering
fn into_fallback(self) -> (Option<CacheType>, DiskCacheConfig) {
let CacheConfigs {
azure,
disk,
gcs,
gha,
memcached,
redis,
s3,
webdav,
oss,
} = self;
let cache_type = s3
.map(CacheType::S3)
.or_else(|| redis.map(CacheType::Redis))
.or_else(|| memcached.map(CacheType::Memcached))
.or_else(|| gcs.map(CacheType::GCS))
.or_else(|| gha.map(CacheType::GHA))
.or_else(|| azure.map(CacheType::Azure))
.or_else(|| webdav.map(CacheType::Webdav))
.or_else(|| oss.map(CacheType::OSS));
let fallback = disk.unwrap_or_default();
(cache_type, fallback)
}
/// Override self with any existing fields from other
fn merge(&mut self, other: Self) {
let CacheConfigs {
azure,
disk,
gcs,
gha,
memcached,
redis,
s3,
webdav,
oss,
} = other;
if azure.is_some() {
self.azure = azure
}
if disk.is_some() {
self.disk = disk
}
if gcs.is_some() {
self.gcs = gcs
}
if gha.is_some() {
self.gha = gha
}
if memcached.is_some() {
self.memcached = memcached
}
if redis.is_some() {
self.redis = redis
}
if s3.is_some() {
self.s3 = s3
}
if webdav.is_some() {
self.webdav = webdav
}
if oss.is_some() {
self.oss = oss
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(tag = "type")]
pub enum DistToolchainConfig {
#[serde(rename = "no_dist")]
NoDist { compiler_executable: PathBuf },
#[serde(rename = "path_override")]
PathOverride {
compiler_executable: PathBuf,
archive: PathBuf,
archive_compiler_executable: String,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "type")]
pub enum DistAuth {
#[serde(rename = "token")]
Token { token: String },
#[serde(rename = "oauth2_code_grant_pkce")]
Oauth2CodeGrantPKCE {
client_id: String,
auth_url: String,
token_url: String,
},
#[serde(rename = "oauth2_implicit")]
Oauth2Implicit { client_id: String, auth_url: String },
}
// Convert a type = "mozilla" immediately into an actual oauth configuration
// https://github.com/serde-rs/serde/issues/595 could help if implemented
impl<'a> Deserialize<'a> for DistAuth {
fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error>
where
D: Deserializer<'a>,
{
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(tag = "type")]
pub enum Helper {
#[serde(rename = "token")]
Token { token: String },
#[serde(rename = "mozilla")]
Mozilla,
#[serde(rename = "oauth2_code_grant_pkce")]
Oauth2CodeGrantPKCE {
client_id: String,
auth_url: String,
token_url: String,
},
#[serde(rename = "oauth2_implicit")]
Oauth2Implicit { client_id: String, auth_url: String },
}
let helper: Helper = Deserialize::deserialize(deserializer)?;
Ok(match helper {
Helper::Token { token } => DistAuth::Token { token },
Helper::Mozilla => DistAuth::Oauth2CodeGrantPKCE {
client_id: MOZILLA_OAUTH_PKCE_CLIENT_ID.to_owned(),
auth_url: MOZILLA_OAUTH_PKCE_AUTH_URL.to_owned(),
token_url: MOZILLA_OAUTH_PKCE_TOKEN_URL.to_owned(),
},
Helper::Oauth2CodeGrantPKCE {
client_id,
auth_url,
token_url,
} => DistAuth::Oauth2CodeGrantPKCE {
client_id,
auth_url,
token_url,
},
Helper::Oauth2Implicit {
client_id,
auth_url,
} => DistAuth::Oauth2Implicit {
client_id,
auth_url,
},
})
}
}
impl Default for DistAuth {
fn default() -> Self {
DistAuth::Token {
token: INSECURE_DIST_CLIENT_TOKEN.to_owned(),
}
}
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
#[serde(deny_unknown_fields)]
pub struct DistConfig {
pub auth: DistAuth,
#[cfg(any(feature = "dist-client", feature = "dist-server"))]
pub scheduler_url: Option<HTTPUrl>,
#[cfg(not(any(feature = "dist-client", feature = "dist-server")))]
pub scheduler_url: Option<String>,
pub cache_dir: PathBuf,
pub toolchains: Vec<DistToolchainConfig>,
pub toolchain_cache_size: u64,
pub rewrite_includes_only: bool,
}
impl Default for DistConfig {
fn default() -> Self {
Self {
auth: Default::default(),
scheduler_url: Default::default(),
cache_dir: default_dist_cache_dir(),
toolchains: Default::default(),
toolchain_cache_size: default_toolchain_cache_size(),
rewrite_includes_only: false,
}
}
}
// TODO: fields only pub for tests
#[derive(Debug, Default, Serialize, Deserialize, Eq, PartialEq)]
#[serde(default)]
#[serde(deny_unknown_fields)]
pub struct FileConfig {
pub cache: CacheConfigs,
pub dist: DistConfig,
pub server_startup_timeout_ms: Option<u64>,
}
// If the file doesn't exist or we can't read it, log the issue and proceed. If the
// config exists but doesn't parse then something is wrong - return an error.
pub fn try_read_config_file<T: DeserializeOwned>(path: &Path) -> Result<Option<T>> {
debug!("Attempting to read config file at {:?}", path);
let mut file = match File::open(path) {
Ok(f) => f,
Err(e) => {
debug!("Couldn't open config file: {}", e);
return Ok(None);
}
};
let mut string = String::new();
match file.read_to_string(&mut string) {
Ok(_) => (),
Err(e) => {
warn!("Failed to read config file: {}", e);
return Ok(None);
}
}
let res = if path.extension().is_some_and(|e| e == "json") {
serde_json::from_str(&string)
.with_context(|| format!("Failed to load json config file from {}", path.display()))?
} else {
toml::from_str(&string)
.with_context(|| format!("Failed to load toml config file from {}", path.display()))?
};
Ok(Some(res))
}
#[derive(Debug)]
pub struct EnvConfig {
cache: CacheConfigs,
}
fn key_prefix_from_env_var(env_var_name: &str) -> String {
env::var(env_var_name)
.ok()
.as_ref()
.map(|s| s.trim_end_matches('/'))
.filter(|s| !s.is_empty())
.unwrap_or_default()
.to_owned()
}
fn number_from_env_var<A: std::str::FromStr>(env_var_name: &str) -> Option<Result<A>>
where
<A as FromStr>::Err: std::fmt::Debug,
{
let value = env::var(env_var_name).ok()?;
value
.parse::<A>()
.map_err(|err| anyhow!("{env_var_name} value is invalid: {err:?}"))
.into()
}
fn bool_from_env_var(env_var_name: &str) -> Result<Option<bool>> {
env::var(env_var_name)
.ok()
.map(|value| match value.to_lowercase().as_str() {
"true" | "on" | "1" => Ok(true),
"false" | "off" | "0" => Ok(false),
_ => bail!(
"{} must be 'true', 'on', '1', 'false', 'off' or '0'.",
env_var_name
),
})
.transpose()
}
fn config_from_env() -> Result<EnvConfig> {
// ======= AWS =======
let s3 = if let Ok(bucket) = env::var("SCCACHE_BUCKET") {
let region = env::var("SCCACHE_REGION").ok();
let no_credentials = bool_from_env_var("SCCACHE_S3_NO_CREDENTIALS")?.unwrap_or(false);
let use_ssl = bool_from_env_var("SCCACHE_S3_USE_SSL")?;
let server_side_encryption = bool_from_env_var("SCCACHE_S3_SERVER_SIDE_ENCRYPTION")?;
let endpoint = env::var("SCCACHE_ENDPOINT").ok();
let key_prefix = key_prefix_from_env_var("SCCACHE_S3_KEY_PREFIX");
let enable_virtual_host_style = bool_from_env_var("SCCACHE_S3_ENABLE_VIRTUAL_HOST_STYLE")?;
Some(S3CacheConfig {
bucket,
region,
no_credentials,
key_prefix,
endpoint,
use_ssl,
server_side_encryption,
enable_virtual_host_style,
})
} else {
None
};
if s3.as_ref().map(|s3| s3.no_credentials).unwrap_or_default()
&& (env::var_os("AWS_ACCESS_KEY_ID").is_some()
|| env::var_os("AWS_SECRET_ACCESS_KEY").is_some())
{
bail!("If setting S3 credentials, SCCACHE_S3_NO_CREDENTIALS must not be set.");
}
// ======= redis =======
let redis = match (
env::var("SCCACHE_REDIS").ok(),
env::var("SCCACHE_REDIS_ENDPOINT").ok(),
env::var("SCCACHE_REDIS_CLUSTER_ENDPOINTS").ok(),
) {
(None, None, None) => None,
(url, endpoint, cluster_endpoints) => {
let db = number_from_env_var("SCCACHE_REDIS_DB")
.transpose()?
.unwrap_or(DEFAULT_REDIS_DB);
let username = env::var("SCCACHE_REDIS_USERNAME").ok();
let password = env::var("SCCACHE_REDIS_PASSWORD").ok();
let ttl = number_from_env_var("SCCACHE_REDIS_EXPIRATION")
.or_else(|| number_from_env_var("SCCACHE_REDIS_TTL"))
.transpose()?
.unwrap_or(DEFAULT_REDIS_CACHE_TTL);
let key_prefix = key_prefix_from_env_var("SCCACHE_REDIS_KEY_PREFIX");
Some(RedisCacheConfig {
url,
endpoint,
cluster_endpoints,
username,
password,
db,
ttl,
key_prefix,
})
}
};
if env::var_os("SCCACHE_REDIS_EXPIRATION").is_some()
&& env::var_os("SCCACHE_REDIS_TTL").is_some()
{
bail!("You mustn't set both SCCACHE_REDIS_EXPIRATION and SCCACHE_REDIS_TTL. Use only one.");
}
// ======= memcached =======
let memcached = if let Ok(url) =
env::var("SCCACHE_MEMCACHED").or_else(|_| env::var("SCCACHE_MEMCACHED_ENDPOINT"))
{
let username = env::var("SCCACHE_MEMCACHED_USERNAME").ok();
let password = env::var("SCCACHE_MEMCACHED_PASSWORD").ok();
let expiration = number_from_env_var("SCCACHE_MEMCACHED_EXPIRATION")
.transpose()?
.unwrap_or(DEFAULT_MEMCACHED_CACHE_EXPIRATION);
let key_prefix = key_prefix_from_env_var("SCCACHE_MEMCACHED_KEY_PREFIX");
Some(MemcachedCacheConfig {
url,
username,
password,
expiration,
key_prefix,
})
} else {
None
};
if env::var_os("SCCACHE_MEMCACHED").is_some()
&& env::var_os("SCCACHE_MEMCACHED_ENDPOINT").is_some()
{
bail!("You mustn't set both SCCACHE_MEMCACHED and SCCACHE_MEMCACHED_ENDPOINT. Please, use only SCCACHE_MEMCACHED_ENDPOINT.");
}
// ======= GCP/GCS =======
if (env::var("SCCACHE_GCS_CREDENTIALS_URL").is_ok()
|| env::var("SCCACHE_GCS_OAUTH_URL").is_ok()
|| env::var("SCCACHE_GCS_KEY_PATH").is_ok())
&& env::var("SCCACHE_GCS_BUCKET").is_err()
{
bail!(
"If setting GCS credentials, SCCACHE_GCS_BUCKET and an auth mechanism need to be set."
);
}
let gcs = env::var("SCCACHE_GCS_BUCKET").ok().map(|bucket| {
let key_prefix = key_prefix_from_env_var("SCCACHE_GCS_KEY_PREFIX");
if env::var("SCCACHE_GCS_OAUTH_URL").is_ok() {
eprintln!("SCCACHE_GCS_OAUTH_URL has been deprecated");
eprintln!("if you intend to use vm metadata for auth, please set correct service account instead");
}
let credential_url = env::var("SCCACHE_GCS_CREDENTIALS_URL").ok();
let cred_path = env::var("SCCACHE_GCS_KEY_PATH").ok();
let service_account = env::var("SCCACHE_GCS_SERVICE_ACCOUNT").ok();
let rw_mode = match env::var("SCCACHE_GCS_RW_MODE").as_ref().map(String::as_str) {
Ok("READ_ONLY") => CacheModeConfig::ReadOnly,
Ok("READ_WRITE") => CacheModeConfig::ReadWrite,
// TODO: unsure if these should warn during the configuration loading
// or at the time when they're actually used to connect to GCS
Ok(_) => {
warn!("Invalid SCCACHE_GCS_RW_MODE -- defaulting to READ_ONLY.");
CacheModeConfig::ReadOnly
}
_ => {
warn!("No SCCACHE_GCS_RW_MODE specified -- defaulting to READ_ONLY.");
CacheModeConfig::ReadOnly
}
};
GCSCacheConfig {
bucket,
key_prefix,
cred_path,
service_account,
rw_mode,
credential_url,
}
});
// ======= GHA =======
let gha = if let Ok(version) = env::var("SCCACHE_GHA_VERSION") {
// If SCCACHE_GHA_VERSION has been set, we don't need to check
// SCCACHE_GHA_ENABLED's value anymore.
Some(GHACacheConfig {
enabled: true,
version,
})
} else if bool_from_env_var("SCCACHE_GHA_ENABLED")?.unwrap_or(false) {
// If only SCCACHE_GHA_ENABLED has been set to the true value, enable with
// default version.
Some(GHACacheConfig {
enabled: true,
version: "".to_string(),
})
} else {
None
};
// ======= Azure =======
let azure = if let (Ok(connection_string), Ok(container)) = (
env::var("SCCACHE_AZURE_CONNECTION_STRING"),
env::var("SCCACHE_AZURE_BLOB_CONTAINER"),
) {
let key_prefix = key_prefix_from_env_var("SCCACHE_AZURE_KEY_PREFIX");
Some(AzureCacheConfig {
connection_string,
container,
key_prefix,
})
} else {
None
};
// ======= WebDAV =======
let webdav = if let Ok(endpoint) = env::var("SCCACHE_WEBDAV_ENDPOINT") {
let key_prefix = key_prefix_from_env_var("SCCACHE_WEBDAV_KEY_PREFIX");
let username = env::var("SCCACHE_WEBDAV_USERNAME").ok();
let password = env::var("SCCACHE_WEBDAV_PASSWORD").ok();
let token = env::var("SCCACHE_WEBDAV_TOKEN").ok();
Some(WebdavCacheConfig {
endpoint,
key_prefix,
username,
password,
token,
})
} else {
None
};
// ======= OSS =======
let oss = if let Ok(bucket) = env::var("SCCACHE_OSS_BUCKET") {
let endpoint = env::var("SCCACHE_OSS_ENDPOINT").ok();
let key_prefix = key_prefix_from_env_var("SCCACHE_OSS_KEY_PREFIX");
let no_credentials = bool_from_env_var("SCCACHE_OSS_NO_CREDENTIALS")?.unwrap_or(false);
Some(OSSCacheConfig {
bucket,
endpoint,
key_prefix,
no_credentials,
})
} else {
None
};
if oss
.as_ref()
.map(|oss| oss.no_credentials)
.unwrap_or_default()
&& (env::var_os("ALIBABA_CLOUD_ACCESS_KEY_ID").is_some()
|| env::var_os("ALIBABA_CLOUD_ACCESS_KEY_SECRET").is_some())
{
bail!("If setting OSS credentials, SCCACHE_OSS_NO_CREDENTIALS must not be set.");
}
// ======= Local =======
let disk_dir = env::var_os("SCCACHE_DIR").map(PathBuf::from);
let disk_sz = env::var("SCCACHE_CACHE_SIZE")
.ok()
.and_then(|v| parse_size(&v));
let mut preprocessor_mode_config = PreprocessorCacheModeConfig::activated();
let preprocessor_mode_overridden = if let Some(value) = bool_from_env_var("SCCACHE_DIRECT")? {
preprocessor_mode_config.use_preprocessor_cache_mode = value;
true
} else {
false
};
let (disk_rw_mode, disk_rw_mode_overridden) = match env::var("SCCACHE_LOCAL_RW_MODE")
.as_ref()
.map(String::as_str)
{
Ok("READ_ONLY") => (CacheModeConfig::ReadOnly, true),
Ok("READ_WRITE") => (CacheModeConfig::ReadWrite, true),
Ok(_) => {
warn!("Invalid SCCACHE_LOCAL_RW_MODE -- defaulting to READ_WRITE.");
(CacheModeConfig::ReadWrite, false)
}
_ => (CacheModeConfig::ReadWrite, false),
};
let any_overridden = disk_dir.is_some()
|| disk_sz.is_some()
|| preprocessor_mode_overridden
|| disk_rw_mode_overridden;
let disk = if any_overridden {
Some(DiskCacheConfig {
dir: disk_dir.unwrap_or_else(default_disk_cache_dir),
size: disk_sz.unwrap_or_else(default_disk_cache_size),
preprocessor_cache_mode: preprocessor_mode_config,
rw_mode: disk_rw_mode,
})
} else {
None
};
let cache = CacheConfigs {
azure,
disk,
gcs,
gha,
memcached,
redis,
s3,
webdav,
oss,
};
Ok(EnvConfig { cache })
}
// The directories crate changed the location of `config_dir` on macos in version 3,
// so we also check the config in `preference_dir` (new in that version), which
// corresponds to the old location, for compatibility with older setups.
fn config_file(env_var: &str, leaf: &str) -> PathBuf {
if let Some(env_value) = env::var_os(env_var) {
return env_value.into();
}
let dirs =
ProjectDirs::from("", ORGANIZATION, APP_NAME).expect("Unable to get config directory");
// If the new location exists, use that.
let path = dirs.config_dir().join(leaf);
if path.exists() {
return path;
}
// If the old location exists, use that.
let path = dirs.preference_dir().join(leaf);
if path.exists() {
return path;
}
// Otherwise, use the new location.
dirs.config_dir().join(leaf)
}
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Config {
pub cache: Option<CacheType>,
pub fallback_cache: DiskCacheConfig,
pub dist: DistConfig,
pub server_startup_timeout: Option<std::time::Duration>,
}
impl Config {
pub fn load() -> Result<Self> {
let env_conf = config_from_env()?;
let file_conf_path = config_file("SCCACHE_CONF", "config");
let file_conf = try_read_config_file(&file_conf_path)
.context("Failed to load config file")?
.unwrap_or_default();
Ok(Self::from_env_and_file_configs(env_conf, file_conf))
}
fn from_env_and_file_configs(env_conf: EnvConfig, file_conf: FileConfig) -> Self {
let mut conf_caches: CacheConfigs = Default::default();
let FileConfig {
cache,
dist,
server_startup_timeout_ms,
} = file_conf;
conf_caches.merge(cache);
let server_startup_timeout =
server_startup_timeout_ms.map(std::time::Duration::from_millis);
let EnvConfig { cache } = env_conf;
conf_caches.merge(cache);
let (caches, fallback_cache) = conf_caches.into_fallback();
Self {
cache: caches,
fallback_cache,
dist,
server_startup_timeout,
}
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(default)]
#[serde(deny_unknown_fields)]
pub struct CachedDistConfig {
pub auth_tokens: HashMap<String, String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(default)]