-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathconfig.rs
1350 lines (1187 loc) · 42.6 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
use std::env;
use std::fmt;
use std::fs;
use std::io;
use std::io::Write;
use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::time::Duration;
use failure::{Backtrace, Context, Fail};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use relay_auth::{generate_key_pair, generate_relay_id, PublicKey, RelayId, SecretKey};
use relay_common::{Dsn, Uuid};
use relay_redis::RedisConfig;
use crate::types::ByteSize;
use crate::upstream::UpstreamDescriptor;
/// Defines the source of a config error
#[derive(Debug)]
enum ConfigErrorSource {
/// An error occurring independently.
None,
/// An error originating from a configuration file.
File(PathBuf),
/// An error originating in a field override (an env var, or a CLI parameter).
FieldOverride(String),
}
impl Default for ConfigErrorSource {
fn default() -> Self {
Self::None
}
}
/// Indicates config related errors.
#[derive(Debug)]
pub struct ConfigError {
source: ConfigErrorSource,
inner: Context<ConfigErrorKind>,
}
impl ConfigError {
#[inline]
fn new<C>(context: C) -> Self
where
C: Into<Context<ConfigErrorKind>>,
{
Self {
source: ConfigErrorSource::None,
inner: context.into(),
}
}
#[inline]
fn wrap<E>(inner: E, kind: ConfigErrorKind) -> Self
where
E: Fail,
{
Self::new(inner.context(kind))
}
#[inline]
fn for_field<E>(inner: E, field: &'static str) -> Self
where
E: Fail,
{
Self::wrap(inner, ConfigErrorKind::InvalidValue).field(field)
}
#[inline]
fn file<P: AsRef<Path>>(mut self, p: P) -> Self {
self.source = ConfigErrorSource::File(p.as_ref().to_path_buf());
self
}
#[inline]
fn field(mut self, name: &'static str) -> Self {
self.source = ConfigErrorSource::FieldOverride(name.to_owned());
self
}
/// Returns the error kind of the error.
pub fn kind(&self) -> ConfigErrorKind {
*self.inner.get_context()
}
}
impl Fail for ConfigError {
fn cause(&self) -> Option<&dyn Fail> {
self.inner.cause()
}
fn backtrace(&self) -> Option<&Backtrace> {
self.inner.backtrace()
}
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.source {
ConfigErrorSource::None => self.inner.fmt(f),
ConfigErrorSource::File(file_name) => {
write!(f, "{} (file {})", self.inner, file_name.display())
}
ConfigErrorSource::FieldOverride(name) => write!(f, "{} (field {})", self.inner, name),
}
}
}
/// Indicates config related errors.
#[derive(Fail, Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum ConfigErrorKind {
/// Failed to open the file.
#[fail(display = "could not open config file")]
CouldNotOpenFile,
/// Failed to save a file.
#[fail(display = "could not write config file")]
CouldNotWriteFile,
/// Parsing YAML failed.
#[fail(display = "could not parse yaml config file")]
BadYaml,
/// Parsing JSON failed.
#[fail(display = "could not parse json config file")]
BadJson,
/// Invalid config value
#[fail(display = "invalid config value")]
InvalidValue,
/// The user attempted to run Relay with processing enabled, but uses a binary that was
/// compiled without the processing feature.
#[fail(display = "was not compiled with processing, cannot enable processing")]
ProcessingNotAvailable,
}
enum ConfigFormat {
Yaml,
Json,
}
impl ConfigFormat {
pub fn extension(&self) -> &'static str {
match self {
ConfigFormat::Yaml => "yml",
ConfigFormat::Json => "json",
}
}
}
trait ConfigObject: DeserializeOwned + Serialize {
/// The format in which to serialize this configuration.
fn format() -> ConfigFormat;
/// The basename of the config file.
fn name() -> &'static str;
/// The full filename of the config file, including the file extension.
fn path(base: &Path) -> PathBuf {
base.join(format!("{}.{}", Self::name(), Self::format().extension()))
}
/// Loads the config file from a file within the given directory location.
fn load(base: &Path) -> Result<Self, ConfigError> {
let path = Self::path(base);
let f = fs::File::open(&path)
.map_err(|e| ConfigError::wrap(e, ConfigErrorKind::CouldNotOpenFile).file(&path))?;
match Self::format() {
ConfigFormat::Yaml => serde_yaml::from_reader(io::BufReader::new(f))
.map_err(|e| ConfigError::wrap(e, ConfigErrorKind::BadYaml).file(&path)),
ConfigFormat::Json => serde_json::from_reader(io::BufReader::new(f))
.map_err(|e| ConfigError::wrap(e, ConfigErrorKind::BadJson).file(&path)),
}
}
/// Writes the configuration object to the given writer.
fn write<W: Write>(&self, writer: &mut W) -> Result<(), ConfigError> {
match Self::format() {
ConfigFormat::Yaml => serde_yaml::to_writer(writer, self)
.map_err(|e| ConfigError::wrap(e, ConfigErrorKind::CouldNotWriteFile)),
ConfigFormat::Json => serde_json::to_writer_pretty(writer, self)
.map_err(|e| ConfigError::wrap(e, ConfigErrorKind::CouldNotWriteFile)),
}
}
/// Writes the configuration to a file within the given directory location.
fn save(&self, base: &Path) -> Result<(), ConfigError> {
let path = Self::path(base);
let mut options = fs::OpenOptions::new();
options.write(true).truncate(true).create(true);
// Remove all non-user permissions for the newly created file
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut f = options
.open(&path)
.map_err(|e| ConfigError::wrap(e, ConfigErrorKind::CouldNotWriteFile).file(&path))?;
self.write(&mut f).map_err(|e| e.file(&path))?;
f.write_all(b"\n").ok();
Ok(())
}
}
/// Structure used to hold information about configuration overrides via
/// CLI parameters or environment variables
#[derive(Debug, Default)]
pub struct OverridableConfig {
/// The upstream relay or sentry instance.
pub upstream: Option<String>,
/// The host the relay should bind to (network interface).
pub host: Option<String>,
/// The port to bind for the unencrypted relay HTTP server.
pub port: Option<String>,
/// "true" if processing is enabled "false" otherwise
pub processing: Option<String>,
/// the kafka bootstrap.servers configuration string
pub kafka_url: Option<String>,
/// the redis server url
pub redis_url: Option<String>,
/// The globally unique ID of the relay.
pub id: Option<String>,
/// The secret key of the relay
pub secret_key: Option<String>,
/// The public key of the relay
pub public_key: Option<String>,
}
/// The relay credentials
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct Credentials {
/// The secret key of the relay
pub secret_key: SecretKey,
/// The public key of the relay
pub public_key: PublicKey,
/// The globally unique ID of the relay.
pub id: RelayId,
}
impl Credentials {
/// Generates new random credentials.
pub fn generate() -> Self {
log::info!("generating new relay credentials");
let (sk, pk) = generate_key_pair();
Self {
secret_key: sk,
public_key: pk,
id: generate_relay_id(),
}
}
/// Serializes this configuration to JSON.
pub fn to_json_string(&self) -> Result<String, ConfigError> {
serde_json::to_string(self)
.map_err(|e| ConfigError::wrap(e, ConfigErrorKind::CouldNotWriteFile))
}
}
impl ConfigObject for Credentials {
fn format() -> ConfigFormat {
ConfigFormat::Json
}
fn name() -> &'static str {
"credentials"
}
}
/// The operation mode of a relay.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum RelayMode {
/// This relay acts as a proxy for all requests and events.
///
/// Events are normalized and rate limits from the upstream are enforced, but the relay will not
/// fetch project configurations from the upstream or perform PII stripping. All events are
/// accepted unless overridden on the file system.
Proxy,
/// This relay is configured statically in the file system.
///
/// Events are only accepted for projects configured statically in the file system. All other
/// events are rejected. If configured, PII stripping is also performed on those events.
Static,
/// Project configurations are managed by the upstream.
///
/// Project configurations are always fetched from the upstream, unless they are statically
/// overridden in the file system. This relay must be white-listed in the upstream Sentry. This
/// is only possible, if the upstream is Sentry directly, or another managed Relay.
Managed,
/// Events are held in memory for inspection only.
///
/// This mode is used for testing sentry SDKs.
Capture,
}
impl fmt::Display for RelayMode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
RelayMode::Proxy => write!(f, "proxy"),
RelayMode::Static => write!(f, "static"),
RelayMode::Managed => write!(f, "managed"),
RelayMode::Capture => write!(f, "capture"),
}
}
}
/// Checks if we are running in docker.
fn is_docker() -> bool {
if fs::metadata("/.dockerenv").is_ok() {
return true;
}
fs::read_to_string("/proc/self/cgroup")
.map(|s| s.find("/docker").is_some())
.unwrap_or(false)
}
/// Default value for the "bind" configuration.
fn default_host() -> IpAddr {
if is_docker() {
// Docker images rely on this service being exposed
"0.0.0.0".parse().unwrap()
} else {
"127.0.0.1".parse().unwrap()
}
}
/// Relay specific configuration values.
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
pub struct Relay {
/// The operation mode of this relay.
pub mode: RelayMode,
/// The upstream relay or sentry instance.
pub upstream: UpstreamDescriptor<'static>,
/// The host the relay should bind to (network interface).
pub host: IpAddr,
/// The port to bind for the unencrypted relay HTTP server.
pub port: u16,
/// Optional port to bind for the encrypted relay HTTPS server.
pub tls_port: Option<u16>,
/// The path to the identity (DER-encoded PKCS12) to use for TLS.
pub tls_identity_path: Option<PathBuf>,
/// Password for the PKCS12 archive.
pub tls_identity_password: Option<String>,
}
impl Default for Relay {
fn default() -> Self {
Relay {
mode: RelayMode::Managed,
upstream: "https://sentry.io/".parse().unwrap(),
host: default_host(),
port: 3000,
tls_port: None,
tls_identity_path: None,
tls_identity_password: None,
}
}
}
/// Controls the log format
#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum LogFormat {
/// Auto detect (pretty for tty, simplified for other)
Auto,
/// With colors
Pretty,
/// Simplified log output
Simplified,
/// Dump out JSON lines
Json,
}
/// Controls the logging system.
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
struct Logging {
/// The log level for the relay.
level: log::LevelFilter,
/// If set to true this emits log messages for failed event payloads.
log_failed_payloads: bool,
/// Controls the log format.
format: LogFormat,
/// When set to true, backtraces are forced on.
enable_backtraces: bool,
}
impl Default for Logging {
fn default() -> Self {
Logging {
level: log::LevelFilter::Info,
log_failed_payloads: false,
format: LogFormat::Auto,
enable_backtraces: false,
}
}
}
/// Control the metrics.
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
struct Metrics {
/// If set to a host/port string then metrics will be reported to this
/// statsd instance.
statsd: Option<String>,
/// The prefix that should be added to all metrics.
prefix: String,
}
impl Default for Metrics {
fn default() -> Self {
Metrics {
statsd: None,
prefix: "sentry.relay".into(),
}
}
}
/// Controls various limits
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
struct Limits {
/// How many requests can be sent concurrently from Relay to the upstream before Relay starts
/// buffering.
max_concurrent_requests: usize,
/// How many queries can be sent concurrently from Relay to the upstream before Relay starts
/// buffering.
///
/// The concurrency of queries is additionally constrained by `max_concurrent_requests`.
max_concurrent_queries: usize,
/// The maximum payload size for events.
max_event_size: ByteSize,
/// The maximum size for each attachment.
max_attachment_size: ByteSize,
/// The maximum combined size for all attachments in an envelope or request.
max_attachments_size: ByteSize,
/// The maximum payload size for an entire envelopes. Individual limits still apply.
max_envelope_size: ByteSize,
/// The maximum number of session items per envelope.
max_session_count: usize,
/// The maximum payload size for general API requests.
max_api_payload_size: ByteSize,
/// The maximum payload size for file uploads and chunks.
max_api_file_upload_size: ByteSize,
/// The maximum payload size for chunks
max_api_chunk_upload_size: ByteSize,
/// The maximum number of threads to spawn for CPU and web work, each.
///
/// The total number of threads spawned will roughly be `2 * max_thread_count + 1`. Defaults to
/// the number of logical CPU cores on the host.
max_thread_count: usize,
/// The maximum number of seconds a query is allowed to take across retries. Individual requests
/// have lower timeouts. Defaults to 30 seconds.
query_timeout: u64,
/// The maximum number of connections to Relay that can be created at once.
max_connection_rate: usize,
/// The maximum number of pending connects to Relay. This corresponds to the backlog param of
/// `listen(2)` in POSIX.
max_pending_connections: i32,
/// The maximum number of open connections to Relay.
max_connections: usize,
/// The maximum number of seconds to wait for pending events after receiving a shutdown signal.
shutdown_timeout: u64,
}
impl Default for Limits {
fn default() -> Self {
Limits {
max_concurrent_requests: 100,
max_concurrent_queries: 5,
max_event_size: ByteSize::from_megabytes(1),
max_attachment_size: ByteSize::from_megabytes(50),
max_attachments_size: ByteSize::from_megabytes(50),
max_envelope_size: ByteSize::from_megabytes(50),
max_session_count: 100,
max_api_payload_size: ByteSize::from_megabytes(20),
max_api_file_upload_size: ByteSize::from_megabytes(40),
max_api_chunk_upload_size: ByteSize::from_megabytes(100),
max_thread_count: num_cpus::get(),
query_timeout: 30,
max_connection_rate: 256,
max_pending_connections: 2048,
max_connections: 25_000,
shutdown_timeout: 10,
}
}
}
/// Controls authentication with upstream.
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
struct Http {
/// Timeout for upstream requests in seconds.
timeout: u32,
/// Maximum interval between failed request retries in seconds.
max_retry_interval: u32,
/// The custom HTTP Host header to send to the upstream.
host_header: Option<String>,
}
impl Default for Http {
fn default() -> Self {
Http {
timeout: 5,
max_retry_interval: 60,
host_header: None,
}
}
}
/// Controls internal caching behavior.
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
struct Cache {
/// The cache timeout for project configurations in seconds.
project_expiry: u32,
/// Continue using project state this many seconds after cache expiry while a new state is
/// being fetched. This is added on top of `project_expiry` and `miss_expiry`. Default is 0.
project_grace_period: u32,
/// The cache timeout for downstream relay info (public keys) in seconds.
relay_expiry: u32,
/// The cache timeout for events (store) before dropping them.
event_expiry: u32,
/// The maximum amount of events to queue before dropping them.
event_buffer_size: u32,
/// The cache timeout for non-existing entries.
miss_expiry: u32,
/// The buffer timeout for batched queries before sending them upstream in ms.
batch_interval: u32,
/// The maximum number of project configs to fetch from Sentry at once. Defaults to 500.
///
/// `cache.batch_interval` controls how quickly batches are sent, this controls the batch size.
batch_size: usize,
/// Interval for watching local cache override files in seconds.
file_interval: u32,
/// Interval for evicting outdated project configs from memory.
eviction_interval: u32,
}
impl Default for Cache {
fn default() -> Self {
Cache {
project_expiry: 300, // 5 minutes
project_grace_period: 0,
relay_expiry: 3600, // 1 hour
event_expiry: 600, // 10 minutes
event_buffer_size: 1000,
miss_expiry: 60, // 1 minute
batch_interval: 100, // 100ms
batch_size: 500,
file_interval: 10, // 10 seconds
eviction_interval: 60, // 60 seconds
}
}
}
/// Controls interal reporting to Sentry.
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
struct Sentry {
dsn: Option<Dsn>,
enabled: bool,
}
impl Default for Sentry {
fn default() -> Self {
Sentry {
dsn: "https://[email protected]/1269704"
.parse()
.ok(),
enabled: false,
}
}
}
/// Define the topics over which Relay communicates with Sentry.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum KafkaTopic {
/// Simple events (without attachments) topic.
Events,
/// Complex events (with attachments) topic.
Attachments,
/// Transaction events topic.
Transactions,
/// Shared outcomes topic for Relay and Sentry.
Outcomes,
/// Session health updates.
Sessions,
}
/// Configuration for topics.
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
pub struct TopicNames {
/// Simple events topic name.
pub events: String,
/// Events with attachments topic name.
pub attachments: String,
/// Transaction events topic name.
pub transactions: String,
/// Event outcomes topic name.
pub outcomes: String,
/// Session health topic name.
pub sessions: String,
}
impl Default for TopicNames {
fn default() -> Self {
Self {
events: "ingest-events".to_owned(),
attachments: "ingest-attachments".to_owned(),
transactions: "ingest-transactions".to_owned(),
outcomes: "outcomes".to_owned(),
sessions: "ingest-sessions".to_owned(),
}
}
}
/// A name value pair of Kafka config parameter.
#[derive(Serialize, Deserialize, Debug)]
pub struct KafkaConfigParam {
/// Name of the Kafka config parameter.
pub name: String,
/// Value of the Kafka config parameter.
pub value: String,
}
fn default_max_secs_in_future() -> u32 {
60 // 1 minute
}
fn default_max_secs_in_past() -> u32 {
30 * 24 * 3600 // 30 days
}
fn default_chunk_size() -> ByteSize {
ByteSize::from_megabytes(1)
}
fn default_projectconfig_cache_prefix() -> String {
"relayconfig".to_owned()
}
fn default_max_rate_limit() -> Option<u32> {
Some(300) // 5 minutes
}
/// Controls Sentry-internal event processing.
#[derive(Serialize, Deserialize, Debug)]
pub struct Processing {
/// True if the Relay should do processing. Defaults to `false`.
pub enabled: bool,
/// GeoIp DB file source.
#[serde(default)]
pub geoip_path: Option<PathBuf>,
/// Maximum future timestamp of ingested events.
#[serde(default = "default_max_secs_in_future")]
pub max_secs_in_future: u32,
/// Maximum age of ingested events. Older events will be adjusted to `now()`.
#[serde(default = "default_max_secs_in_past")]
pub max_secs_in_past: u32,
/// Kafka producer configurations.
pub kafka_config: Vec<KafkaConfigParam>,
/// Kafka topic names.
#[serde(default)]
pub topics: TopicNames,
/// Redis hosts to connect to for storing state for rate limits.
#[serde(default)]
pub redis: Option<RedisConfig>,
/// Maximum chunk size of attachments for Kafka.
#[serde(default = "default_chunk_size")]
pub attachment_chunk_size: ByteSize,
/// Prefix to use when looking up project configs in Redis. Defaults to "relayconfig".
#[serde(default = "default_projectconfig_cache_prefix")]
pub projectconfig_cache_prefix: String,
/// Maximum rate limit to report to clients.
#[serde(default = "default_max_rate_limit")]
pub max_rate_limit: Option<u32>,
}
impl Default for Processing {
/// Constructs a disabled processing configuration.
fn default() -> Self {
Self {
enabled: false,
geoip_path: None,
max_secs_in_future: 0,
max_secs_in_past: 0,
kafka_config: Vec::new(),
topics: TopicNames::default(),
redis: None,
attachment_chunk_size: default_chunk_size(),
projectconfig_cache_prefix: default_projectconfig_cache_prefix(),
max_rate_limit: default_max_rate_limit(),
}
}
}
/// Outcome generation specific configuration values.
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
pub struct Outcomes {
/// Controls whether outcomes will be emitted when processing is disabled.
/// Processing relays always emit outcomes (for backwards compatibility).
pub emit_outcomes: bool,
/// The maximum number of outcomes that are batched before being sent
/// via http to the upstream (only applies to non processing relays)
pub batch_size: usize,
/// The maximum time interval (in milliseconds) that an outcome may be batched
/// via http to the upstream (only applies to non processing relays)
pub batch_interval: u64,
}
impl Default for Outcomes {
fn default() -> Self {
Outcomes {
emit_outcomes: false,
batch_size: 1000,
batch_interval: 500,
}
}
}
/// Minimal version of a config for dumping out.
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct MinimalConfig {
/// The relay part of the config.
pub relay: Relay,
}
impl MinimalConfig {
/// Saves the config in the given config folder as config.yml
pub fn save_in_folder<P: AsRef<Path>>(&self, p: P) -> Result<(), ConfigError> {
let path = p.as_ref();
if fs::metadata(path).is_err() {
fs::create_dir_all(path)
.map_err(|e| ConfigError::wrap(e, ConfigErrorKind::CouldNotOpenFile).file(path))?;
}
self.save(path)
}
}
impl ConfigObject for MinimalConfig {
fn format() -> ConfigFormat {
ConfigFormat::Yaml
}
fn name() -> &'static str {
"config"
}
}
#[derive(Serialize, Deserialize, Debug, Default)]
struct ConfigValues {
#[serde(default)]
relay: Relay,
#[serde(default)]
http: Http,
#[serde(default)]
cache: Cache,
#[serde(default)]
limits: Limits,
#[serde(default)]
logging: Logging,
#[serde(default)]
metrics: Metrics,
#[serde(default)]
sentry: Sentry,
#[serde(default)]
processing: Processing,
#[serde(default)]
outcomes: Outcomes,
}
impl ConfigObject for ConfigValues {
fn format() -> ConfigFormat {
ConfigFormat::Yaml
}
fn name() -> &'static str {
"config"
}
}
/// Config struct.
pub struct Config {
values: ConfigValues,
credentials: Option<Credentials>,
path: PathBuf,
}
impl fmt::Debug for Config {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Config")
.field("path", &self.path)
.field("values", &self.values)
.finish()
}
}
impl Config {
/// Loads a config from a given config folder.
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Config, ConfigError> {
let path = env::current_dir()
.map(|x| x.join(path.as_ref()))
.unwrap_or_else(|_| path.as_ref().to_path_buf());
let config = Config {
values: ConfigValues::load(&path)?,
credentials: match fs::metadata(Credentials::path(&path)) {
Ok(_) => Some(Credentials::load(&path)?),
Err(_) => None,
},
path: path.clone(),
};
if cfg!(not(feature = "processing")) && config.processing_enabled() {
return Err(ConfigError::new(ConfigErrorKind::ProcessingNotAvailable).file(&path));
}
Ok(config)
}
/// Override configuration with values coming from other sources (e.g. env variables or
/// command line parameters)
pub fn apply_override(
&mut self,
overrides: OverridableConfig,
) -> Result<&mut Self, ConfigError> {
let relay = &mut self.values.relay;
if let Some(upstream) = overrides.upstream {
relay.upstream = upstream
.parse::<UpstreamDescriptor>()
.map_err(|err| ConfigError::for_field(err, "upstream"))?;
}
if let Some(host) = overrides.host {
relay.host = host
.parse::<IpAddr>()
.map_err(|err| ConfigError::for_field(err, "host"))?;
}
if let Some(port) = overrides.port {
relay.port = u16::from_str_radix(port.as_str(), 10)
.map_err(|err| ConfigError::for_field(err, "port"))?;
}
let processing = &mut self.values.processing;
if let Some(enabled) = overrides.processing {
match enabled.to_lowercase().as_str() {
"true" | "1" => processing.enabled = true,
"false" | "0" | "" => processing.enabled = false,
_ => {
return Err(ConfigError::new(ConfigErrorKind::InvalidValue).field("processing"));
}
}
}
if let Some(redis) = overrides.redis_url {
processing.redis = Some(RedisConfig::Single(redis))
}
if let Some(kafka_url) = overrides.kafka_url {
let existing = processing
.kafka_config
.iter_mut()
.find(|e| e.name == "bootstrap.servers");
if let Some(config_param) = existing {
config_param.value = kafka_url;
} else {
processing.kafka_config.push(KafkaConfigParam {
name: "bootstrap.servers".to_owned(),
value: kafka_url,
})
}
}
// credentials overrides
let id = if let Some(id) = overrides.id {
let id = Uuid::parse_str(&id).map_err(|err| ConfigError::for_field(err, "id"))?;
Some(id)
} else {
None
};
let public_key = if let Some(public_key) = overrides.public_key {
let public_key = public_key
.parse::<PublicKey>()
.map_err(|err| ConfigError::for_field(err, "public_key"))?;
Some(public_key)
} else {
None
};
let secret_key = if let Some(secret_key) = overrides.secret_key {
let secret_key = secret_key
.parse::<SecretKey>()
.map_err(|err| ConfigError::for_field(err, "secret_key"))?;
Some(secret_key)
} else {
None
};
if let Some(credentials) = &mut self.credentials {
//we have existing credentials we may override some entries
if let Some(id) = id {
credentials.id = id;
}
if let Some(public_key) = public_key {
credentials.public_key = public_key;
}
if let Some(secret_key) = secret_key {
credentials.secret_key = secret_key
}
} else {
//no existing credentials we may only create the full credentials
match (id, public_key, secret_key) {
(Some(id), Some(public_key), Some(secret_key)) => {
self.credentials = Some(Credentials {
id,
public_key,
secret_key,
})
}
(None, None, None) => {
// nothing provided, we'll just leave the credentials None, maybe we
// don't need them in the current command or we'll override them later
}
_ => {
return Err(ConfigError::new(ConfigErrorKind::InvalidValue)
.field("incomplete credentials"));
}
}
}
Ok(self)
}
/// Checks if the config is already initialized.
pub fn config_exists<P: AsRef<Path>>(path: P) -> bool {
fs::metadata(ConfigValues::path(path.as_ref())).is_ok()
}
/// Returns the filename of the config file.
pub fn path(&self) -> &Path {
&self.path
}
/// Dumps out a YAML string of the values.
pub fn to_yaml_string(&self) -> Result<String, ConfigError> {
serde_yaml::to_string(&self.values)
.map_err(|e| ConfigError::wrap(e, ConfigErrorKind::CouldNotWriteFile))
}
/// Regenerates the relay credentials.
///
/// This also writes the credentials back to the file.
pub fn regenerate_credentials(&mut self) -> Result<(), ConfigError> {
let creds = Credentials::generate();
creds.save(&self.path)?;
self.credentials = Some(creds);
Ok(())
}
/// Return the current credentials
pub fn credentials(&self) -> Option<&Credentials> {
self.credentials.as_ref()
}
/// Set new credentials.
///
/// This also writes the credentials back to the file.
pub fn replace_credentials(
&mut self,
credentials: Option<Credentials>,
) -> Result<bool, ConfigError> {
if self.credentials == credentials {
return Ok(false);
}
match credentials {
Some(ref creds) => {
creds.save(&self.path)?;
}
None => {
let path = Credentials::path(&self.path);
if fs::metadata(&path).is_ok() {
fs::remove_file(&path).map_err(|e| {
ConfigError::wrap(e, ConfigErrorKind::CouldNotWriteFile).file(&path)
})?;
}