forked from PowerShell/DSC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.rs
857 lines (809 loc) · 37.3 KB
/
mod.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
use crate::configure::config_doc::{ExecutionKind, Metadata, Resource};
use crate::configure::parameters::Input;
use crate::dscerror::DscError;
use crate::dscresources::invoke_result::ExportResult;
use crate::dscresources::{
{dscresource::{Capability, Invoke, get_diff},
invoke_result::{GetResult, SetResult, TestResult, ResourceSetResponse}},
resource_manifest::Kind,
};
use crate::DscResource;
use crate::discovery::Discovery;
use crate::parser::Statement;
use crate::progress::{Failure, ProgressBar, ProgressFormat};
use self::context::Context;
use self::config_doc::{Configuration, DataType, MicrosoftDscMetadata, Operation, SecurityContextKind};
use self::depends_on::get_resource_invocation_order;
use self::config_result::{ConfigurationExportResult, ConfigurationGetResult, ConfigurationSetResult, ConfigurationTestResult};
use self::constraints::{check_length, check_number_limits, check_allowed_values};
use rust_i18n::t;
use security_context_lib::{SecurityContext, get_security_context};
use serde_json::{Map, Value};
use std::path::PathBuf;
use std::collections::HashMap;
use tracing::{debug, info, trace};
pub mod context;
pub mod config_doc;
pub mod config_result;
pub mod constraints;
pub mod depends_on;
pub mod parameters;
pub struct Configurator {
json: String,
config: Configuration,
pub context: Context,
discovery: Discovery,
statement_parser: Statement,
progress_format: ProgressFormat,
}
/// Add the results of an export operation to a configuration.
///
/// # Arguments
///
/// * `resource` - The resource to export.
/// * `conf` - The configuration to add the results to.
///
/// # Panics
///
/// Doesn't panic because there is a match/Some check before `unwrap()`; false positive.
///
/// # Errors
///
/// This function will return an error if the underlying resource fails.
pub fn add_resource_export_results_to_configuration(resource: &DscResource, adapter_resource: Option<&DscResource>, conf: &mut Configuration, input: &str) -> Result<ExportResult, DscError> {
let export_result = match adapter_resource {
Some(_) => adapter_resource.unwrap().export(input)?,
_ => resource.export(input)?
};
if resource.kind == Kind::Exporter {
for instance in &export_result.actual_state {
let resource = serde_json::from_value::<Resource>(instance.clone())?;
conf.resources.push(resource);
}
} else {
for (i, instance) in export_result.actual_state.iter().enumerate() {
let mut r = config_doc::Resource::new();
r.resource_type.clone_from(&resource.type_name);
r.name = format!("{}-{i}", r.resource_type);
let props: Map<String, Value> = serde_json::from_value(instance.clone())?;
r.properties = escape_property_values(&props)?;
conf.resources.push(r);
}
}
Ok(export_result)
}
// for values returned by resources, they may look like expressions, so we make sure to escape them in case
// they are re-used to apply configuration
fn escape_property_values(properties: &Map<String, Value>) -> Result<Option<Map<String, Value>>, DscError> {
debug!("{}", t!("configure.mod.escapePropertyValues"));
let mut result: Map<String, Value> = Map::new();
for (name, value) in properties {
match value {
Value::Object(object) => {
let value = escape_property_values(&object.clone())?;
result.insert(name.clone(), serde_json::to_value(value)?);
continue;
},
Value::Array(array) => {
let mut result_array: Vec<Value> = Vec::new();
for element in array {
match element {
Value::Object(object) => {
let value = escape_property_values(&object.clone())?;
result_array.push(serde_json::to_value(value)?);
continue;
},
Value::Array(_) => {
return Err(DscError::Parser(t!("configure.mod.nestedArraysNotSupported").to_string()));
},
Value::String(_) => {
// use as_str() so that the enclosing quotes are not included for strings
let Some(statement) = element.as_str() else {
return Err(DscError::Parser(t!("configure.mod.arrayElementCouldNotTransformAsString").to_string()));
};
if statement.starts_with('[') && statement.ends_with(']') {
result_array.push(Value::String(format!("[{statement}")));
} else {
result_array.push(element.clone());
}
}
_ => {
result_array.push(element.clone());
}
}
}
result.insert(name.clone(), serde_json::to_value(result_array)?);
},
Value::String(_) => {
// use as_str() so that the enclosing quotes are not included for strings
let Some(statement) = value.as_str() else {
return Err(DscError::Parser(t!("configure.mod.valueCouldNotBeTransformedAsString", value = value).to_string()));
};
if statement.starts_with('[') && statement.ends_with(']') {
result.insert(name.clone(), Value::String(format!("[{statement}")));
} else {
result.insert(name.clone(), value.clone());
}
},
_ => {
result.insert(name.clone(), value.clone());
},
}
}
Ok(Some(result))
}
fn add_metadata(kind: &Kind, mut properties: Option<Map<String, Value>> ) -> Result<String, DscError> {
if *kind == Kind::Adapter {
// add metadata to the properties so the adapter knows this is a config
let mut metadata = Map::new();
let mut dsc_value = Map::new();
dsc_value.insert("context".to_string(), Value::String("configuration".to_string()));
metadata.insert("Microsoft.DSC".to_string(), Value::Object(dsc_value));
if let Some(mut properties) = properties {
properties.insert("metadata".to_string(), Value::Object(metadata));
return Ok(serde_json::to_string(&properties)?);
}
properties = Some(metadata);
return Ok(serde_json::to_string(&properties)?);
}
match properties {
Some(properties) => {
Ok(serde_json::to_string(&properties)?)
},
_ => {
Ok(String::new())
}
}
}
fn check_security_context(metadata: Option<&Metadata>) -> Result<(), DscError> {
if metadata.is_none() {
return Ok(());
}
if let Some(metadata) = &metadata {
if let Some(microsoft_dsc) = &metadata.microsoft {
if let Some(required_security_context) = µsoft_dsc.security_context {
match required_security_context {
SecurityContextKind::Current => {
// no check needed
},
SecurityContextKind::Elevated => {
if get_security_context() != SecurityContext::Admin {
return Err(DscError::SecurityContext(t!("configure.mod.elevationRequired").to_string()));
}
},
SecurityContextKind::Restricted => {
if get_security_context() != SecurityContext::User {
return Err(DscError::SecurityContext(t!("configure.mod.restrictedRequired").to_string()));
}
},
}
}
}
}
Ok(())
}
impl Configurator {
/// Create a new `Configurator` instance.
///
/// # Arguments
///
/// * `config` - The configuration to use in JSON.
///
/// # Errors
///
/// This function will return an error if the configuration is invalid or the underlying discovery fails.
pub fn new(json: &str, progress_format: ProgressFormat) -> Result<Configurator, DscError> {
let discovery = Discovery::new()?;
let mut config = Configurator {
json: json.to_owned(),
config: Configuration::new(),
context: Context::new(),
discovery,
statement_parser: Statement::new()?,
progress_format,
};
config.validate_config()?;
Ok(config)
}
/// Get the configuration.
///
/// # Returns
///
/// * `&Configuration` - The configuration.
#[must_use]
pub fn get_config(&self) -> &Configuration {
&self.config
}
fn get_properties(&mut self, resource: &Resource, resource_kind: &Kind) -> Result<Option<Map<String, Value>>, DscError> {
match resource_kind {
Kind::Group => {
// if Group resource, we leave it to the resource to handle expressions
Ok(resource.properties.clone())
},
_ => {
Ok(self.invoke_property_expressions(resource.properties.as_ref())?)
},
}
}
/// Invoke the get operation on a resource.
///
/// # Returns
///
/// * `ConfigurationGetResult` - The result of the get operation.
///
/// # Errors
///
/// This function will return an error if the underlying resource fails.
pub fn invoke_get(&mut self) -> Result<ConfigurationGetResult, DscError> {
let mut result = ConfigurationGetResult::new();
let resources = get_resource_invocation_order(&self.config, &mut self.statement_parser, &self.context)?;
let mut progress = ProgressBar::new(resources.len() as u64, self.progress_format)?;
let discovery = &self.discovery.clone();
for resource in resources {
progress.set_resource(&resource.name, &resource.resource_type);
progress.write_activity(format!("Get '{}'", resource.name).as_str());
let Some(dsc_resource) = discovery.find_resource(&resource.resource_type) else {
return Err(DscError::ResourceNotFound(resource.resource_type));
};
let properties = self.get_properties(&resource, &dsc_resource.kind)?;
debug!("resource_type {}", &resource.resource_type);
let filter = add_metadata(&dsc_resource.kind, properties)?;
trace!("filter: {filter}");
let start_datetime = chrono::Local::now();
let get_result = match dsc_resource.get(&filter) {
Ok(result) => result,
Err(e) => {
progress.set_failure(get_failure_from_error(&e));
progress.write_increment(1);
return Err(e);
},
};
let end_datetime = chrono::Local::now();
match &get_result {
GetResult::Resource(resource_result) => {
self.context.references.insert(format!("{}:{}", resource.resource_type, resource.name), serde_json::to_value(&resource_result.actual_state)?);
},
GetResult::Group(group) => {
let mut results = Vec::<Value>::new();
for result in group {
results.push(serde_json::to_value(&result.result)?);
}
self.context.references.insert(format!("{}:{}", resource.resource_type, resource.name), Value::Array(results.clone()));
},
}
let resource_result = config_result::ResourceGetResult {
metadata: Some(
Metadata {
microsoft: Some(
MicrosoftDscMetadata {
duration: Some(end_datetime.signed_duration_since(start_datetime).to_string()),
..Default::default()
}
),
other: Map::new(),
}
),
name: resource.name.clone(),
resource_type: resource.resource_type.clone(),
result: get_result.clone(),
};
result.results.push(resource_result);
progress.set_result(&serde_json::to_value(get_result)?);
progress.write_increment(1);
}
result.metadata = Some(
self.get_result_metadata(Operation::Get)
);
Ok(result)
}
/// Invoke the set operation on a resource.
///
/// # Arguments
///
/// * `skip_test` - Whether to skip the test operation.
///
/// # Returns
///
/// * `ConfigurationSetResult` - The result of the set operation.
///
/// # Errors
///
/// This function will return an error if the underlying resource fails.
#[allow(clippy::too_many_lines)]
pub fn invoke_set(&mut self, skip_test: bool) -> Result<ConfigurationSetResult, DscError> {
let mut result = ConfigurationSetResult::new();
let resources = get_resource_invocation_order(&self.config, &mut self.statement_parser, &self.context)?;
let mut progress = ProgressBar::new(resources.len() as u64, self.progress_format)?;
let discovery = &self.discovery.clone();
for resource in resources {
progress.set_resource(&resource.name, &resource.resource_type);
progress.write_activity(format!("Set '{}'", resource.name).as_str());
let Some(dsc_resource) = discovery.find_resource(&resource.resource_type) else {
return Err(DscError::ResourceNotFound(resource.resource_type));
};
let properties = self.get_properties(&resource, &dsc_resource.kind)?;
debug!("resource_type {}", &resource.resource_type);
// see if the properties contains `_exist` and is false
let exist = match &properties {
Some(property_map) => {
if let Some(exist) = property_map.get("_exist") {
!matches!(exist, Value::Bool(false))
} else {
true
}
},
_ => {
true
}
};
let desired = add_metadata(&dsc_resource.kind, properties)?;
trace!("{}", t!("configure.mod.desired", state = desired));
let start_datetime;
let end_datetime;
let set_result;
if exist || dsc_resource.capabilities.contains(&Capability::SetHandlesExist) {
debug!("{}", t!("configure.mod.handlesExist"));
start_datetime = chrono::Local::now();
set_result = match dsc_resource.set(&desired, skip_test, &self.context.execution_type) {
Ok(result) => result,
Err(e) => {
progress.set_failure(get_failure_from_error(&e));
progress.write_increment(1);
return Err(e);
},
};
end_datetime = chrono::Local::now();
} else if dsc_resource.capabilities.contains(&Capability::Delete) {
if self.context.execution_type == ExecutionKind::WhatIf {
// TODO: add delete what-if support
return Err(DscError::NotSupported(t!("configure.mod.whatIfNotSupportedForDelete").to_string()));
}
debug!("{}", t!("configure.mod.implementsDelete"));
let before_result = match dsc_resource.get(&desired) {
Ok(result) => result,
Err(e) => {
progress.set_failure(get_failure_from_error(&e));
progress.write_increment(1);
return Err(e);
},
};
start_datetime = chrono::Local::now();
if let Err(e) = dsc_resource.delete(&desired) {
progress.set_failure(get_failure_from_error(&e));
progress.write_increment(1);
return Err(e);
}
let after_result = match dsc_resource.get(&desired) {
Ok(result) => result,
Err(e) => {
progress.set_failure(get_failure_from_error(&e));
progress.write_increment(1);
return Err(e);
},
};
// convert get result to set result
set_result = match before_result {
GetResult::Resource(before_response) => {
let GetResult::Resource(after_result) = after_result else {
return Err(DscError::NotSupported(t!("configure.mod.groupNotSupportedForDelete").to_string()))
};
let before_value = serde_json::to_value(&before_response.actual_state)?;
let after_value = serde_json::to_value(&after_result.actual_state)?;
SetResult::Resource(ResourceSetResponse {
before_state: before_response.actual_state,
after_state: after_result.actual_state,
changed_properties: Some(get_diff(&before_value, &after_value)),
})
},
GetResult::Group(_) => {
return Err(DscError::NotSupported(t!("configure.mod.groupNotSupportedForDelete").to_string()))
},
};
end_datetime = chrono::Local::now();
} else {
return Err(DscError::NotImplemented(t!("configure.mod.deleteNotSupported", resource = resource.resource_type).to_string()));
}
match &set_result {
SetResult::Resource(resource_result) => {
self.context.references.insert(format!("{}:{}", resource.resource_type, resource.name), serde_json::to_value(&resource_result.after_state)?);
},
SetResult::Group(group) => {
let mut results = Vec::<Value>::new();
for result in group {
results.push(serde_json::to_value(&result.result)?);
}
self.context.references.insert(format!("{}:{}", resource.resource_type, resource.name), Value::Array(results.clone()));
},
}
let resource_result = config_result::ResourceSetResult {
metadata: Some(
Metadata {
microsoft: Some(
MicrosoftDscMetadata {
duration: Some(end_datetime.signed_duration_since(start_datetime).to_string()),
..Default::default()
}
),
other: Map::new(),
}
),
name: resource.name.clone(),
resource_type: resource.resource_type.clone(),
result: set_result.clone(),
};
result.results.push(resource_result);
progress.set_result(&serde_json::to_value(set_result)?);
progress.write_increment(1);
}
result.metadata = Some(
self.get_result_metadata(Operation::Set)
);
Ok(result)
}
/// Invoke the test operation on a resource.
///
/// # Returns
///
/// * `ConfigurationTestResult` - The result of the test operation.
///
/// # Errors
///
/// This function will return an error if the underlying resource fails.
pub fn invoke_test(&mut self) -> Result<ConfigurationTestResult, DscError> {
let mut result = ConfigurationTestResult::new();
let resources = get_resource_invocation_order(&self.config, &mut self.statement_parser, &self.context)?;
let mut progress = ProgressBar::new(resources.len() as u64, self.progress_format)?;
let discovery = &self.discovery.clone();
for resource in resources {
progress.set_resource(&resource.name, &resource.resource_type);
progress.write_activity(format!("Test '{}'", resource.name).as_str());
let Some(dsc_resource) = discovery.find_resource(&resource.resource_type) else {
return Err(DscError::ResourceNotFound(resource.resource_type));
};
let properties = self.get_properties(&resource, &dsc_resource.kind)?;
debug!("resource_type {}", &resource.resource_type);
let expected = add_metadata(&dsc_resource.kind, properties)?;
trace!("{}", t!("configure.mod.expectedState", state = expected));
let start_datetime = chrono::Local::now();
let test_result = match dsc_resource.test(&expected) {
Ok(result) => result,
Err(e) => {
progress.set_failure(get_failure_from_error(&e));
progress.write_increment(1);
return Err(e);
},
};
let end_datetime = chrono::Local::now();
match &test_result {
TestResult::Resource(resource_test_result) => {
self.context.references.insert(format!("{}:{}", resource.resource_type, resource.name), serde_json::to_value(&resource_test_result.actual_state)?);
},
TestResult::Group(group) => {
let mut results = Vec::<Value>::new();
for result in group {
results.push(serde_json::to_value(&result.result)?);
}
self.context.references.insert(format!("{}:{}", resource.resource_type, resource.name), Value::Array(results.clone()));
},
}
let resource_result = config_result::ResourceTestResult {
metadata: Some(
Metadata {
microsoft: Some(
MicrosoftDscMetadata {
duration: Some(end_datetime.signed_duration_since(start_datetime).to_string()),
..Default::default()
}
),
other: Map::new(),
}
),
name: resource.name.clone(),
resource_type: resource.resource_type.clone(),
result: test_result.clone(),
};
result.results.push(resource_result);
progress.set_result( &serde_json::to_value(test_result)?);
progress.write_increment(1);
}
result.metadata = Some(
self.get_result_metadata(Operation::Test)
);
Ok(result)
}
/// Invoke the export operation on a configuration.
///
/// # Returns
///
/// * `ConfigurationExportResult` - The result of the export operation.
///
/// # Errors
///
/// This function will return an error if the underlying resource fails.
pub fn invoke_export(&mut self) -> Result<ConfigurationExportResult, DscError> {
let mut result = ConfigurationExportResult::new();
let mut conf = config_doc::Configuration::new();
conf.metadata.clone_from(&self.config.metadata);
let mut progress = ProgressBar::new(self.config.resources.len() as u64, self.progress_format)?;
let resources = self.config.resources.clone();
let discovery = &self.discovery.clone();
for resource in &resources {
progress.set_resource(&resource.name, &resource.resource_type);
progress.write_activity(format!("Export '{}'", resource.name).as_str());
let Some(dsc_resource) = discovery.find_resource(&resource.resource_type) else {
return Err(DscError::ResourceNotFound(resource.resource_type.clone()));
};
let properties = self.get_properties(resource, &dsc_resource.kind)?;
let input = add_metadata(&dsc_resource.kind, properties)?;
trace!("{}", t!("configure.mod.exportInput", input = input));
let export_result = match add_resource_export_results_to_configuration(dsc_resource, Some(dsc_resource), &mut conf, input.as_str()) {
Ok(result) => result,
Err(e) => {
progress.set_failure(get_failure_from_error(&e));
progress.write_increment(1);
return Err(e);
},
};
self.context.references.insert(format!("{}:{}", resource.resource_type, resource.name), serde_json::to_value(&export_result.actual_state)?);
progress.set_result(&serde_json::to_value(export_result)?);
progress.write_increment(1);
}
let export_metadata = self.get_result_metadata(Operation::Export);
match conf.metadata {
Some(mut metadata) => {
metadata.microsoft = export_metadata.microsoft;
conf.metadata = Some(metadata);
},
_ => {
conf.metadata = Some(export_metadata);
},
}
result.result = Some(conf);
Ok(result)
}
/// Set the mounted path for the configuration.
///
/// # Arguments
///
/// * `system_root` - The system root to set.
pub fn set_system_root(&mut self, system_root: &str) {
self.context.system_root = PathBuf::from(system_root);
}
/// Set the parameters and variables context for the configuration.
///
/// # Arguments
///
/// * `parameters_input` - The parameters to set.
///
/// # Errors
///
/// This function will return an error if the parameters are invalid.
pub fn set_context(&mut self, parameters_input: Option<&Value>) -> Result<(), DscError> {
let config = serde_json::from_str::<Configuration>(self.json.as_str())?;
self.set_parameters(parameters_input, &config)?;
self.set_variables(&config)?;
Ok(())
}
fn set_parameters(&mut self, parameters_input: Option<&Value>, config: &Configuration) -> Result<(), DscError> {
// set default parameters first
let Some(parameters) = &config.parameters else {
if parameters_input.is_none() {
info!("{}", t!("configure.mod.noParameters"));
return Ok(());
}
return Err(DscError::Validation(t!("configure.mod.noParametersDefined").to_string()));
};
for (name, parameter) in parameters {
debug!("{}", t!("configure.mod.processingParameter", name = name));
if let Some(default_value) = ¶meter.default_value {
debug!("{}", t!("configure.mod.setDefaultParameter", name = name));
// default values can be expressions
let value = if default_value.is_string() {
if let Some(value) = default_value.as_str() {
self.statement_parser.parse_and_execute(value, &self.context)?
} else {
return Err(DscError::Parser(t!("configure.mod.defaultStringNotDefined").to_string()));
}
} else {
default_value.clone()
};
Configurator::validate_parameter_type(name, &value, ¶meter.parameter_type)?;
self.context.parameters.insert(name.clone(), (value, parameter.parameter_type.clone()));
}
}
let Some(parameters_input) = parameters_input else {
debug!("{}", t!("configure.mod.noParametersInput"));
return Ok(());
};
trace!("parameters_input: {parameters_input}");
let parameters: HashMap<String, Value> = serde_json::from_value::<Input>(parameters_input.clone())?.parameters;
let Some(parameters_constraints) = &config.parameters else {
return Err(DscError::Validation(t!("configure.mod.noParametersDefined").to_string()));
};
for (name, value) in parameters {
if let Some(constraint) = parameters_constraints.get(&name) {
debug!("Validating parameter '{name}'");
check_length(&name, &value, constraint)?;
check_allowed_values(&name, &value, constraint)?;
check_number_limits(&name, &value, constraint)?;
// TODO: additional array constraints
// TODO: object constraints
Configurator::validate_parameter_type(&name, &value, &constraint.parameter_type)?;
if constraint.parameter_type == DataType::SecureString || constraint.parameter_type == DataType::SecureObject {
info!("{}", t!("configure.mod.setSecureParameter", name = name));
} else {
info!("{}", t!("configure.mod.setParameter", name = name, value = value));
}
self.context.parameters.insert(name.clone(), (value.clone(), constraint.parameter_type.clone()));
// also update the configuration with the parameter value
if let Some(parameters) = &mut self.config.parameters {
if let Some(parameter) = parameters.get_mut(&name) {
parameter.default_value = Some(value);
}
}
}
else {
return Err(DscError::Validation(t!("configure.mod.parameterNotDefined", name = name).to_string()));
}
}
Ok(())
}
fn set_variables(&mut self, config: &Configuration) -> Result<(), DscError> {
let Some(variables) = &config.variables else {
debug!("{}", t!("configure.mod.noVariables"));
return Ok(());
};
for (name, value) in variables {
let new_value = if let Some(string) = value.as_str() {
self.statement_parser.parse_and_execute(string, &self.context)?
}
else {
value.clone()
};
info!("{}", t!("configure.mod.setVariable", name = name, value = new_value));
self.context.variables.insert(name.to_string(), new_value);
}
Ok(())
}
fn get_result_metadata(&self, operation: Operation) -> Metadata {
let end_datetime = chrono::Local::now();
Metadata {
microsoft: Some(
MicrosoftDscMetadata {
context: None,
version: Some(env!("CARGO_PKG_VERSION").to_string()),
operation: Some(operation),
execution_type: Some(self.context.execution_type.clone()),
start_datetime: Some(self.context.start_datetime.to_rfc3339()),
end_datetime: Some(end_datetime.to_rfc3339()),
duration: Some(end_datetime.signed_duration_since(self.context.start_datetime).to_string()),
security_context: Some(self.context.security_context.clone()),
}
),
other: Map::new(),
}
}
fn validate_parameter_type(name: &str, value: &Value, parameter_type: &DataType) -> Result<(), DscError> {
match parameter_type {
DataType::String | DataType::SecureString => {
if !value.is_string() {
return Err(DscError::Validation(t!("configure.mod.parameterNotString", name = name).to_string()));
}
},
DataType::Int => {
if !value.is_i64() {
return Err(DscError::Validation(t!("configure.mod.parameterNotInteger", name = name).to_string()));
}
},
DataType::Bool => {
if !value.is_boolean() {
return Err(DscError::Validation(t!("configure.mod.parameterNotBoolean", name = name).to_string()));
}
},
DataType::Array => {
if !value.is_array() {
return Err(DscError::Validation(t!("configure.mod.parameterNotArray", name = name).to_string()));
}
},
DataType::Object | DataType::SecureObject => {
if !value.is_object() {
return Err(DscError::Validation(t!("configure.mod.parameterNotObject", name = name).to_string()));
}
},
}
Ok(())
}
fn validate_config(&mut self) -> Result<(), DscError> {
let config: Configuration = serde_json::from_str(self.json.as_str())?;
check_security_context(config.metadata.as_ref())?;
// Perform discovery of resources used in config
let required_resources = config.resources.iter().map(|p| p.resource_type.clone()).collect::<Vec<String>>();
self.discovery.find_resources(&required_resources, self.progress_format);
self.config = config;
Ok(())
}
fn invoke_property_expressions(&mut self, properties: Option<&Map<String, Value>>) -> Result<Option<Map<String, Value>>, DscError> {
debug!("{}", t!("configure.mod.invokePropertyExpressions"));
if properties.is_none() {
return Ok(None);
}
let mut result: Map<String, Value> = Map::new();
if let Some(properties) = properties {
for (name, value) in properties {
trace!("{}", t!("configure.mod.invokeExpression", name = name, value = value));
match value {
Value::Object(object) => {
let value = self.invoke_property_expressions(Some(object))?;
result.insert(name.clone(), serde_json::to_value(value)?);
continue;
},
Value::Array(array) => {
let mut result_array: Vec<Value> = Vec::new();
for element in array {
match element {
Value::Object(object) => {
let value = self.invoke_property_expressions(Some(object))?;
result_array.push(serde_json::to_value(value)?);
continue;
},
Value::Array(_) => {
return Err(DscError::Parser(t!("configure.mod.nestedArraysNotSupported").to_string()));
},
Value::String(_) => {
// use as_str() so that the enclosing quotes are not included for strings
let Some(statement) = element.as_str() else {
return Err(DscError::Parser(t!("configure.mod.arrayElementCouldNotTransformAsString").to_string()));
};
let statement_result = self.statement_parser.parse_and_execute(statement, &self.context)?;
let Some(string_result) = statement_result.as_str() else {
return Err(DscError::Parser(t!("configure.mod.arrayElementCouldNotTransformAsString").to_string()));
};
result_array.push(Value::String(string_result.to_string()));
}
_ => {
result_array.push(element.clone());
}
}
}
result.insert(name.clone(), serde_json::to_value(result_array)?);
},
Value::String(_) => {
// use as_str() so that the enclosing quotes are not included for strings
let Some(statement) = value.as_str() else {
return Err(DscError::Parser(t!("configure.mod.valueCouldNotBeTransformedAsString", value = value).to_string()));
};
let statement_result = self.statement_parser.parse_and_execute(statement, &self.context)?;
if let Some(string_result) = statement_result.as_str() {
result.insert(name.clone(), Value::String(string_result.to_string()));
} else {
result.insert(name.clone(), statement_result);
};
},
_ => {
result.insert(name.clone(), value.clone());
},
}
}
}
Ok(Some(result))
}
}
fn get_failure_from_error(err: &DscError) -> Option<Failure> {
match err {
DscError::CommandExit(_resource, exit_code, reason) => {
Some(Failure {
message: reason.to_string(),
exit_code: *exit_code,
})
},
DscError::CommandExitFromManifest(_resource, exit_code, reason) => {
Some(Failure {
message: reason.to_string(),
exit_code: *exit_code,
})
},
_ => None,
}
}