forked from Normation/rudder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
654 lines (583 loc) · 19.1 KB
/
main.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
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2019-2020 Normation SAS
use crate::{configuration::Secret, data::node::NodeId};
use anyhow::Error;
use serde::{
de::{Deserializer, Error as SerdeError, Unexpected, Visitor},
Deserialize,
};
use std::{
collections::HashSet,
convert::TryFrom,
fmt,
fs::read_to_string,
path::{Path, PathBuf},
str::FromStr,
time::Duration,
};
use tracing::debug;
use tracing::warn;
pub type BaseDirectory = PathBuf;
pub type WatchedDirectory = PathBuf;
pub type NodesListFile = PathBuf;
pub type NodesCertsFile = PathBuf;
// For compatibility with int fields containing an integer
fn compat_humantime<'de, D>(d: D) -> Result<Duration, D::Error>
where
D: Deserializer<'de>,
{
struct V;
impl<'de2> Visitor<'de2> for V {
type Value = Duration;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("a duration")
}
fn visit_i64<E>(self, v: i64) -> Result<Duration, E>
where
E: SerdeError,
{
u64::try_from(v)
.map(Duration::from_secs)
.map_err(|_| E::invalid_value(Unexpected::Signed(v), &self))
}
fn visit_str<E>(self, v: &str) -> Result<Duration, E>
where
E: SerdeError,
{
humantime::parse_duration(v).map_err(|_| E::invalid_value(Unexpected::Str(v), &self))
}
}
d.deserialize_str(V)
}
#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
// Default can be implemented in serde using the Default trait
pub struct Configuration {
#[serde(default)]
pub general: GeneralConfig,
#[serde(default)]
pub processing: ProcessingConfig,
#[serde(default)]
pub output: OutputConfig,
#[serde(default)]
pub remote_run: RemoteRun,
#[serde(default)]
pub shared_files: SharedFiles,
#[serde(default)]
pub shared_folder: SharedFolder,
}
impl Configuration {
pub fn new<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
let res = read_to_string(path.as_ref().join("main.conf"))?.parse::<Self>();
if let Ok(ref cfg) = res {
debug!("Parsed main configuration:\n{:#?}", &cfg);
}
res
}
/// Read current node_id, and handle override by node_id
/// Can be removed once node_id is removed
pub fn read_node_id(&self) -> Result<NodeId, Error> {
Ok(match &self.general.node_id {
Some(id) => {
warn!("node_id setting is deprecated, use node_id_file instead");
id.clone()
}
None => read_to_string(&self.general.node_id_file)?,
})
}
}
impl FromStr for Configuration {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(toml::from_str(s)?)
}
}
/// Strategy for default values:
///
/// * `#[serde(default)]` when section is not there
/// * `#[serde(default)]` or `#[serde(default = ...)]` when a value is missing in a section
#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct GeneralConfig {
#[serde(default = "GeneralConfig::default_nodes_list_file")]
pub nodes_list_file: NodesListFile,
#[serde(default = "GeneralConfig::default_nodes_certs_file")]
pub nodes_certs_file: NodesCertsFile,
#[serde(default = "GeneralConfig::default_node_id_file")]
node_id_file: PathBuf,
/// DEPRECATED: Has priority over node_id_file, use the
/// `Configuration::node_id()` method to get correct value
node_id: Option<NodeId>,
#[serde(default = "GeneralConfig::default_listen")]
pub listen: String,
/// None means using the number of available CPUs
pub core_threads: Option<usize>,
/// Deprecated in 7.0, tokio changed the way it counts threads
pub blocking_threads: Option<usize>,
/// Total number of threads used by tokio
// Take default from tokio, currently 512
// https://docs.rs/tokio/0.2.23/tokio/runtime/struct.Builder.html#method.max_threads
pub max_threads: Option<usize>,
}
impl GeneralConfig {
fn default_nodes_list_file() -> PathBuf {
PathBuf::from("/var/rudder/lib/relay/nodeslist.json")
}
fn default_nodes_certs_file() -> PathBuf {
PathBuf::from("/var/rudder/lib/ssl/allnodescerts.pem")
}
fn default_listen() -> String {
"127.0.0.1:3030".to_string()
}
fn default_node_id_file() -> PathBuf {
PathBuf::from("/opt/rudder/etc/uuid.hive")
}
}
#[derive(Deserialize, Debug, PartialEq, Eq, Copy, Clone)]
pub struct CatchupConfig {
#[serde(deserialize_with = "compat_humantime")]
#[serde(default = "CatchupConfig::default_catchup_frequency")]
pub frequency: Duration,
#[serde(default = "CatchupConfig::default_catchup_limit")]
pub limit: u64,
}
impl CatchupConfig {
fn default_catchup_frequency() -> Duration {
Duration::from_secs(10)
}
fn default_catchup_limit() -> u64 {
50
}
}
impl Default for CatchupConfig {
fn default() -> Self {
Self {
frequency: Self::default_catchup_frequency(),
limit: Self::default_catchup_limit(),
}
}
}
#[derive(Deserialize, Debug, PartialEq, Eq, Copy, Clone)]
pub struct CleanupConfig {
#[serde(deserialize_with = "compat_humantime")]
#[serde(default = "CleanupConfig::default_cleanup_frequency")]
pub frequency: Duration,
#[serde(deserialize_with = "compat_humantime")]
#[serde(default = "CleanupConfig::default_cleanup_retention")]
pub retention: Duration,
}
impl CleanupConfig {
/// 1 hour
fn default_cleanup_frequency() -> Duration {
Duration::from_secs(3600)
}
/// 1 week
fn default_cleanup_retention() -> Duration {
Duration::from_secs(3600 * 24 * 7)
}
}
impl Default for CleanupConfig {
fn default() -> Self {
Self {
frequency: Self::default_cleanup_frequency(),
retention: Self::default_cleanup_retention(),
}
}
}
#[derive(Deserialize, Debug, PartialEq, Eq, Clone, Default)]
pub struct ProcessingConfig {
#[serde(default)]
pub inventory: InventoryConfig,
#[serde(default)]
pub reporting: ReportingConfig,
}
#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct InventoryConfig {
#[serde(default = "InventoryConfig::default_directory")]
pub directory: BaseDirectory,
#[serde(default)]
pub output: InventoryOutputSelect,
#[serde(default)]
pub catchup: CatchupConfig,
#[serde(default)]
pub cleanup: CleanupConfig,
}
impl InventoryConfig {
fn default_directory() -> PathBuf {
PathBuf::from("/var/rudder/inventories/")
}
}
impl Default for InventoryConfig {
fn default() -> Self {
Self {
directory: Self::default_directory(),
output: InventoryOutputSelect::default(),
catchup: Default::default(),
cleanup: Default::default(),
}
}
}
#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum InventoryOutputSelect {
Upstream,
Disabled,
}
impl Default for InventoryOutputSelect {
fn default() -> Self {
Self::Disabled
}
}
#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct ReportingConfig {
#[serde(default = "ReportingConfig::default_directory")]
pub directory: BaseDirectory,
#[serde(default)]
pub output: ReportingOutputSelect,
#[serde(default)]
pub catchup: CatchupConfig,
#[serde(default)]
pub cleanup: CleanupConfig,
#[serde(default)]
pub skip_event_types: HashSet<String>,
}
impl ReportingConfig {
fn default_directory() -> PathBuf {
PathBuf::from("/var/rudder/reports/")
}
}
impl Default for ReportingConfig {
fn default() -> Self {
Self {
directory: Self::default_directory(),
output: ReportingOutputSelect::default(),
catchup: Default::default(),
cleanup: Default::default(),
skip_event_types: Default::default(),
}
}
}
#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum ReportingOutputSelect {
Database,
Upstream,
Disabled,
}
impl Default for ReportingOutputSelect {
fn default() -> Self {
Self::Disabled
}
}
pub trait OutputSelect {
fn is_enabled(&self) -> bool;
}
impl OutputSelect for ReportingOutputSelect {
fn is_enabled(&self) -> bool {
*self != ReportingOutputSelect::Disabled
}
}
impl OutputSelect for InventoryOutputSelect {
fn is_enabled(&self) -> bool {
*self != InventoryOutputSelect::Disabled
}
}
#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct RemoteRun {
#[serde(default = "RemoteRun::default_command")]
pub command: PathBuf,
#[serde(default = "RemoteRun::default_use_sudo")]
pub use_sudo: bool,
}
impl RemoteRun {
fn default_command() -> PathBuf {
PathBuf::from("/opt/rudder/bin/rudder")
}
fn default_use_sudo() -> bool {
true
}
}
impl Default for RemoteRun {
fn default() -> Self {
Self {
command: Self::default_command(),
use_sudo: Self::default_use_sudo(),
}
}
}
#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct SharedFiles {
#[serde(default = "SharedFiles::default_path")]
pub path: PathBuf,
}
impl SharedFiles {
fn default_path() -> PathBuf {
PathBuf::from("/var/rudder/shared-files/")
}
}
impl Default for SharedFiles {
fn default() -> Self {
Self {
path: Self::default_path(),
}
}
}
#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct SharedFolder {
#[serde(default = "SharedFolder::default_path")]
pub path: PathBuf,
}
impl SharedFolder {
fn default_path() -> PathBuf {
PathBuf::from("/var/rudder/configuration-repository/shared-files/")
}
}
impl Default for SharedFolder {
fn default() -> Self {
Self {
path: Self::default_path(),
}
}
}
#[derive(Deserialize, Debug, PartialEq, Eq, Clone, Default)]
pub struct OutputConfig {
#[serde(default)]
pub database: DatabaseConfig,
#[serde(default)]
pub upstream: UpstreamConfig,
}
#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct DatabaseConfig {
/// URL without the password
#[serde(default = "DatabaseConfig::default_url")]
pub url: String,
/// When the section is there, password is mandatory
pub password: Secret,
#[serde(default = "DatabaseConfig::default_max_pool_size")]
pub max_pool_size: u32,
}
impl DatabaseConfig {
fn default_url() -> String {
"postgres://rudder@127.0.0.1/rudder".to_string()
}
fn default_max_pool_size() -> u32 {
10
}
}
impl Default for DatabaseConfig {
fn default() -> Self {
Self {
url: Self::default_url(),
password: Default::default(),
max_pool_size: Self::default_max_pool_size(),
}
}
}
#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct UpstreamConfig {
// TODO better URL type
/// When the section is there, url is mandatory
pub url: String,
#[serde(default = "UpstreamConfig::default_user")]
pub user: String,
/// When the section is there, password is mandatory
pub password: Secret,
/// Default password, to be used for new inventories
#[serde(default = "UpstreamConfig::default_default_password")]
pub default_password: Secret,
#[serde(default = "UpstreamConfig::default_verify_certificates")]
pub verify_certificates: bool,
// TODO timeout?
}
impl UpstreamConfig {
fn default_user() -> String {
"rudder".to_string()
}
fn default_verify_certificates() -> bool {
true
}
fn default_default_password() -> Secret {
Secret::new("rudder".into())
}
}
impl Default for UpstreamConfig {
fn default() -> Self {
Self {
url: Default::default(),
user: Self::default_user(),
password: Default::default(),
default_password: Default::default(),
verify_certificates: Self::default_verify_certificates(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_parses_deprecated_node_id() {
let default = "[general]\n\
node_id = \"test\"\n";
let config = default.parse::<Configuration>().unwrap();
assert_eq!(config.read_node_id().unwrap(), "test".to_string());
}
#[test]
fn it_parses_listen_with_hostname() {
let default = "[general]\n\
node_id = \"root\"\n\
listen = \"relayd:3030\"";
let _ = default.parse::<Configuration>().unwrap();
}
#[test]
fn it_parses_empty_main_configuration() {
let empty = "";
let config = empty.parse::<Configuration>().unwrap();
let reference = Configuration {
general: GeneralConfig {
nodes_list_file: PathBuf::from("/var/rudder/lib/relay/nodeslist.json"),
nodes_certs_file: PathBuf::from("/var/rudder/lib/ssl/allnodescerts.pem"),
node_id: None,
node_id_file: PathBuf::from("/opt/rudder/etc/uuid.hive"),
listen: "127.0.0.1:3030".parse().unwrap(),
core_threads: None,
max_threads: None,
blocking_threads: None,
},
processing: ProcessingConfig {
inventory: InventoryConfig {
directory: PathBuf::from("/var/rudder/inventories/"),
output: InventoryOutputSelect::Disabled,
catchup: CatchupConfig {
frequency: Duration::from_secs(10),
limit: 50,
},
cleanup: CleanupConfig {
frequency: Duration::from_secs(3600),
retention: Duration::from_secs(3600 * 24 * 7),
},
},
reporting: ReportingConfig {
directory: PathBuf::from("/var/rudder/reports/"),
output: ReportingOutputSelect::Disabled,
catchup: CatchupConfig {
frequency: Duration::from_secs(10),
limit: 50,
},
cleanup: CleanupConfig {
frequency: Duration::from_secs(3600),
retention: Duration::from_secs(3600 * 24 * 7),
},
skip_event_types: HashSet::new(),
},
},
output: OutputConfig {
upstream: UpstreamConfig {
url: "".to_string(),
user: "rudder".to_string(),
password: Secret::new("".to_string()),
default_password: Secret::new("".to_string()),
verify_certificates: true,
},
database: DatabaseConfig {
url: "postgres://rudder@127.0.0.1/rudder".to_string(),
password: Secret::new("".to_string()),
max_pool_size: 10,
},
},
remote_run: RemoteRun {
command: PathBuf::from("/opt/rudder/bin/rudder"),
use_sudo: true,
},
shared_files: SharedFiles {
path: PathBuf::from("/var/rudder/shared-files/"),
},
shared_folder: SharedFolder {
path: PathBuf::from("/var/rudder/configuration-repository/shared-files/"),
},
};
assert_eq!(config, reference);
}
#[test]
fn it_fails_when_password_is_missing() {
let default = "[general]\n\
node_id = \"root\"\n\
[output.database]\n";
let with_password = format!("{}\npassword = \"test\"", default);
assert!(default.parse::<Configuration>().is_err());
assert!(with_password.parse::<Configuration>().is_ok());
}
#[test]
fn it_works_with_unknown_entries() {
let default = "[general]\n\
node_id = \"root\"\n\
unknown = \"entry\"";
assert!(default.parse::<Configuration>().is_ok());
}
#[test]
fn it_parses_main_configuration() {
let config = Configuration::new("tests/files/config/").unwrap();
let reference = Configuration {
general: GeneralConfig {
nodes_list_file: PathBuf::from("tests/files/nodeslist.json"),
nodes_certs_file: PathBuf::from("tests/files/keys/nodescerts.pem"),
node_id: None,
node_id_file: PathBuf::from("tests/files/config/uuid.hive"),
listen: "127.0.0.1:3030".parse().unwrap(),
core_threads: None,
max_threads: Some(512),
blocking_threads: None,
},
processing: ProcessingConfig {
inventory: InventoryConfig {
directory: PathBuf::from("target/tmp/inventories/"),
output: InventoryOutputSelect::Upstream,
catchup: CatchupConfig {
frequency: Duration::from_secs(10),
limit: 50,
},
cleanup: CleanupConfig {
frequency: Duration::from_secs(10),
retention: Duration::from_secs(10),
},
},
reporting: ReportingConfig {
directory: PathBuf::from("target/tmp/reporting/"),
output: ReportingOutputSelect::Database,
catchup: CatchupConfig {
frequency: Duration::from_secs(10),
limit: 50,
},
cleanup: CleanupConfig {
frequency: Duration::from_secs(30),
retention: Duration::from_secs(30 * 60 + 20),
},
skip_event_types: HashSet::new(),
},
},
output: OutputConfig {
upstream: UpstreamConfig {
url: "https://127.0.0.1:8080".to_string(),
user: "rudder".to_string(),
password: Secret::new("password".to_string()),
default_password: Secret::new("rudder".to_string()),
verify_certificates: false,
},
database: DatabaseConfig {
url: "postgres://rudderreports@127.0.0.1/rudder".to_string(),
password: Secret::new("PASSWORD".to_string()),
max_pool_size: 5,
},
},
remote_run: RemoteRun {
command: PathBuf::from("tests/api_remote_run/fake_agent.sh"),
use_sudo: false,
},
shared_files: SharedFiles {
path: PathBuf::from("tests/api_shared_files"),
},
shared_folder: SharedFolder {
path: PathBuf::from("tests/api_shared_folder"),
},
};
assert_eq!(config, reference);
assert_eq!(config.read_node_id().unwrap(), "root".to_string());
}
}