-
Notifications
You must be signed in to change notification settings - Fork 525
/
Copy pathcommon_migrations.rs
2143 lines (1983 loc) · 78.2 KB
/
common_migrations.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 crate::{error, Migration, MigrationData, Result};
use schnauzer::import::{json_settings::JsonSettingsResolver, StaticHelperResolver};
use serde::Serialize;
use serde_json::Value;
use shlex::Shlex;
use snafu::{OptionExt, ResultExt};
use std::collections::{HashMap, HashSet};
/// We use this migration when we add settings and want to make sure they're removed before we go
/// back to old versions that don't understand them.
pub struct AddSettingsMigration<'a>(pub &'a [&'static str]);
impl Migration for AddSettingsMigration<'_> {
/// New versions must either have a default for the settings or generate them; we don't need to
/// do anything.
fn forward(&mut self, input: MigrationData) -> Result<MigrationData> {
println!(
"AddSettingsMigration({:?}) has no work to do on upgrade.",
self.0
);
Ok(input)
}
/// Older versions don't know about the settings; we remove them so that old versions don't see
/// them and fail deserialization. (The settings must be defaulted or generated in new versions,
/// and safe to remove.)
fn backward(&mut self, mut input: MigrationData) -> Result<MigrationData> {
for setting in self.0 {
if let Some(data) = input.data.remove(*setting) {
println!("Removed {}, which was set to '{}'", setting, data);
} else {
println!("Found no {} to remove", setting);
}
}
Ok(input)
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// We use this migration when we add a cluster of settings under known prefixes and want to make
/// sure they're removed before we go back to old versions that don't understand them. Normally
/// you'd use AddSettingsMigration since you know the key names, but this is useful for
/// user-defined keys, for example in a map like settings.kernel.sysctl or
/// settings.host-containers.
pub struct AddPrefixesMigration(pub Vec<&'static str>);
impl Migration for AddPrefixesMigration {
/// New versions must either have a default for the settings or generate them; we don't need to
/// do anything.
fn forward(&mut self, input: MigrationData) -> Result<MigrationData> {
println!(
"AddPrefixesMigration({:?}) has no work to do on upgrade.",
self.0
);
Ok(input)
}
/// Older versions don't know about the settings; we remove them so that old versions don't see
/// them and fail deserialization. (The settings must be defaulted or generated in new versions,
/// and safe to remove.)
fn backward(&mut self, mut input: MigrationData) -> Result<MigrationData> {
let settings = input
.data
.keys()
.filter(|k| self.0.iter().any(|prefix| k.starts_with(prefix)))
.cloned()
.collect::<Vec<_>>();
for setting in settings {
if let Some(data) = input.data.remove(&setting) {
println!("Removed {}, which was set to '{}'", setting, data);
}
}
Ok(input)
}
}
#[cfg(test)]
mod test_add_prefixes_migration {
use super::AddPrefixesMigration;
use crate::{Migration, MigrationData};
use maplit::hashmap;
use std::collections::HashMap;
#[test]
fn single() {
let data = MigrationData {
data: hashmap! {
"keep.me.a".into() => 0.into(),
"remove.me.b".into() => 0.into(),
"keep.this.c".into() => 0.into(),
"remove.me.d.e".into() => 0.into(),
},
metadata: HashMap::new(),
};
// Run backward, e.g. downgrade, to test that the right keys are removed
let result = AddPrefixesMigration(vec!["remove.me"])
.backward(data)
.unwrap();
assert_eq!(
result.data,
hashmap! {
"keep.me.a".into() => 0.into(),
"keep.this.c".into() => 0.into(),
}
);
}
#[test]
fn multiple() {
let data = MigrationData {
data: hashmap! {
"keep.me.a".into() => 0.into(),
"remove.me.b".into() => 0.into(),
"keep.this.c".into() => 0.into(),
"remove.this.d.e".into() => 0.into(),
},
metadata: HashMap::new(),
};
// Run backward, e.g. downgrade, to test that the right keys are removed
let result = AddPrefixesMigration(vec!["remove.me", "remove.this"])
.backward(data)
.unwrap();
assert_eq!(
result.data,
hashmap! {
"keep.me.a".into() => 0.into(),
"keep.this.c".into() => 0.into(),
}
);
}
#[test]
fn no_match() {
let data = MigrationData {
data: hashmap! {
"keep.me.a".into() => 0.into(),
"remove.me.b".into() => 0.into(),
"keep.this.c".into() => 0.into(),
"remove.this.d.e".into() => 0.into(),
},
metadata: HashMap::new(),
};
// Run backward, e.g. downgrade, to test that the right keys are removed
let result = AddPrefixesMigration(vec!["not.found", "nor.this"])
.backward(data)
.unwrap();
assert_eq!(
result.data,
hashmap! {
"keep.me.a".into() => 0.into(),
"remove.me.b".into() => 0.into(),
"keep.this.c".into() => 0.into(),
"remove.this.d.e".into() => 0.into(),
}
);
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// We use this migration when we remove settings from the model, so the new version doesn't see
/// them and error.
pub struct RemoveSettingsMigration<'a>(pub &'a [&'static str]);
impl Migration for RemoveSettingsMigration<'_> {
/// Newer versions don't know about the settings; we remove them so that new versions don't see
/// them and fail deserialization. (The settings must be defaulted or generated in old versions,
/// and safe to remove.)
fn forward(&mut self, mut input: MigrationData) -> Result<MigrationData> {
for setting in self.0 {
if let Some(data) = input.data.remove(*setting) {
println!("Removed {}, which was set to '{}'", setting, data);
} else {
println!("Found no {} to remove", setting);
}
}
Ok(input)
}
/// Old versions must either have a default for the settings or generate it; we don't need to
/// do anything.
fn backward(&mut self, input: MigrationData) -> Result<MigrationData> {
println!(
"RemoveSettingsMigration({:?}) has no work to do on downgrade.",
self.0
);
Ok(input)
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// We use this migration when we replace a setting's old string value with a new string value.
pub struct ReplaceStringMigration {
pub setting: &'static str,
pub old_val: &'static str,
pub new_val: &'static str,
}
impl Migration for ReplaceStringMigration {
fn forward(&mut self, mut input: MigrationData) -> Result<MigrationData> {
if let Some(data) = input.data.get_mut(self.setting) {
match data {
serde_json::Value::String(data) => {
if data == self.old_val {
self.new_val.clone_into(data);
println!(
"Changed value of '{}' from '{}' to '{}' on upgrade",
self.setting, self.old_val, self.new_val
);
} else {
println!(
"'{}' is not set to '{}', leaving alone",
self.setting, self.old_val
);
}
}
_ => {
println!(
"'{}' is set to non-string value '{}'; ReplaceStringMigration only handles strings",
self.setting, data
);
}
}
} else {
println!("Found no '{}' to change on upgrade", self.setting);
}
Ok(input)
}
fn backward(&mut self, mut input: MigrationData) -> Result<MigrationData> {
if let Some(data) = input.data.get_mut(self.setting) {
match data {
serde_json::Value::String(data) => {
if data == self.new_val {
self.old_val.clone_into(data);
println!(
"Changed value of '{}' from '{}' to '{}' on downgrade",
self.setting, self.new_val, self.old_val
);
} else {
println!(
"'{}' is not set to '{}', leaving alone",
self.setting, self.new_val
);
}
}
_ => {
println!(
"'{}' is set to non-string value '{}'; ReplaceStringMigration only handles strings",
self.setting, data
);
}
}
} else {
println!("Found no '{}' to change on downgrade", self.setting);
}
Ok(input)
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// We use this migration when we need to replace settings that contain lists of string values;
/// for example, when a release changes the list of configuration-files associated with a service.
// String is the only type we use today, and handling multiple value types is more complicated than
// we need at the moment. Allowing &[serde_json::Value] seems nice, but it would allow arbitrary
// data transformations that the API model would then fail to load.
pub struct ListReplacement {
pub setting: &'static str,
pub old_vals: &'static [&'static str],
pub new_vals: &'static [&'static str],
}
pub struct ReplaceListsMigration(pub Vec<ListReplacement>);
impl Migration for ReplaceListsMigration {
fn forward(&mut self, mut input: MigrationData) -> Result<MigrationData> {
for replacement in &self.0 {
if let Some(data) = input.data.get_mut(replacement.setting) {
match data {
serde_json::Value::Array(data) => {
// We only handle string lists; convert each value to a str we can compare.
let list: Vec<&str> = data
.iter()
.map(|v| v.as_str())
.collect::<Option<Vec<&str>>>()
.with_context(|| error::ReplaceListContentsSnafu {
setting: replacement.setting,
data: data.clone(),
})?;
if list == replacement.old_vals {
// Convert back to the original type so we can store it.
*data = replacement.new_vals.iter().map(|s| (*s).into()).collect();
println!(
"Changed value of '{}' from {:?} to {:?} on upgrade",
replacement.setting, replacement.old_vals, replacement.new_vals
);
} else {
println!(
"'{}' is not set to {:?}, leaving alone",
replacement.setting, list
);
}
}
_ => {
println!(
"'{}' is set to non-list value '{}'; ReplaceListsMigration only handles lists",
replacement.setting, data
);
}
}
} else {
println!("Found no '{}' to change on upgrade", replacement.setting);
}
}
Ok(input)
}
fn backward(&mut self, mut input: MigrationData) -> Result<MigrationData> {
for replacement in &self.0 {
if let Some(data) = input.data.get_mut(replacement.setting) {
match data {
serde_json::Value::Array(data) => {
// We only handle string lists; convert each value to a str we can compare.
let list: Vec<&str> = data
.iter()
.map(|v| v.as_str())
.collect::<Option<Vec<&str>>>()
.with_context(|| error::ReplaceListContentsSnafu {
setting: replacement.setting,
data: data.clone(),
})?;
if list == replacement.new_vals {
// Convert back to the original type so we can store it.
*data = replacement.old_vals.iter().map(|s| (*s).into()).collect();
println!(
"Changed value of '{}' from {:?} to {:?} on downgrade",
replacement.setting, replacement.new_vals, replacement.old_vals
);
} else {
println!(
"'{}' is not set to {:?}, leaving alone",
replacement.setting, list
);
}
}
_ => {
println!(
"'{}' is set to non-list value '{}'; ReplaceListsMigration only handles lists",
replacement.setting, data
);
}
}
} else {
println!("Found no '{}' to change on downgrade", replacement.setting);
}
}
Ok(input)
}
}
#[cfg(test)]
mod test_replace_list {
use super::{ListReplacement, ReplaceListsMigration};
use crate::{Migration, MigrationData};
use maplit::hashmap;
use std::collections::HashMap;
#[test]
fn single() {
let data = MigrationData {
data: hashmap! {
"hi".into() => vec!["there"].into(),
},
metadata: HashMap::new(),
};
let result = ReplaceListsMigration(vec![ListReplacement {
setting: "hi",
old_vals: &["there"],
new_vals: &["sup"],
}])
.forward(data)
.unwrap();
assert_eq!(
result.data,
hashmap! {
"hi".into() => vec!["sup"].into(),
}
);
}
#[test]
fn backward() {
let data = MigrationData {
data: hashmap! {
"hi".into() => vec!["there"].into(),
},
metadata: HashMap::new(),
};
let result = ReplaceListsMigration(vec![ListReplacement {
setting: "hi",
old_vals: &["sup"],
new_vals: &["there"],
}])
.backward(data)
.unwrap();
assert_eq!(
result.data,
hashmap! {
"hi".into() => vec!["sup"].into(),
}
);
}
#[test]
fn multiple() {
let data = MigrationData {
data: hashmap! {
"hi".into() => vec!["there", "you"].into(),
"hi2".into() => vec!["hey", "listen"].into(),
"ignored".into() => vec!["no", "change"].into(),
},
metadata: HashMap::new(),
};
let result = ReplaceListsMigration(vec![
ListReplacement {
setting: "hi",
old_vals: &["there", "you"],
new_vals: &["sup", "hey"],
},
ListReplacement {
setting: "hi2",
old_vals: &["hey", "listen"],
new_vals: &["look", "watch out"],
},
])
.forward(data)
.unwrap();
assert_eq!(
result.data,
hashmap! {
"hi".into() => vec!["sup", "hey"].into(),
"hi2".into() => vec!["look", "watch out"].into(),
"ignored".into() => vec!["no", "change"].into(),
}
);
}
#[test]
fn no_match() {
let data = MigrationData {
data: hashmap! {
"hi".into() => vec!["no", "change"].into(),
"hi2".into() => vec!["no", "change"].into(),
},
metadata: HashMap::new(),
};
let result = ReplaceListsMigration(vec![ListReplacement {
setting: "hi",
old_vals: &["there"],
new_vals: &["sup", "hey"],
}])
.forward(data)
.unwrap();
// No change
assert_eq!(
result.data,
hashmap! {
"hi".into() => vec!["no", "change"].into(),
"hi2".into() => vec!["no", "change"].into(),
}
);
}
#[test]
fn not_list() {
let data = MigrationData {
data: hashmap! {
"hi".into() => "just a string, not a list".into(),
},
metadata: HashMap::new(),
};
let result = ReplaceListsMigration(vec![ListReplacement {
setting: "hi",
old_vals: &["there"],
new_vals: &["sup", "hey"],
}])
.forward(data)
.unwrap();
// No change
assert_eq!(
result.data,
hashmap! {
"hi".into() => "just a string, not a list".into(),
}
);
}
#[test]
fn not_string() {
let data = MigrationData {
data: hashmap! {
"hi".into() => vec![0].into(),
},
metadata: HashMap::new(),
};
ReplaceListsMigration(vec![ListReplacement {
setting: "hi",
old_vals: &["there"],
new_vals: &["sup", "hey"],
}])
.forward(data)
.unwrap_err();
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// We used this migration when we replaced an existing template for generating some setting.
///
/// With schnauzer-v2, we now use `ReplaceSchnauzerMigration.` This code remains to build historical
/// migrations until they have been archived.
#[deprecated(note = "Please use `ReplaceSchnauzerMigration`")]
pub struct ReplaceTemplateMigration {
pub setting: &'static str,
pub old_template: &'static str,
pub new_template: &'static str,
}
#[allow(deprecated)]
impl ReplaceTemplateMigration {
/// Helper to retrieve a setting's template
fn get_setting_template(&self, input: &MigrationData) -> Option<String> {
if let Some(metadata) = input.metadata.get(self.setting) {
if let Some(template) = metadata.get("template") {
if let Some(template) = template.as_str() {
return Some(template.to_owned());
} else {
eprintln!(
"'{}' has non-string template value '{}'",
self.setting, template
)
}
} else {
eprintln!("'{}' has no 'template' key in metadata", self.setting);
}
} else {
eprintln!("'{}' has no metadata", self.setting);
}
None
}
/// This handles the common behavior of the forward and backward migrations.
/// We get the setting's template and generate the old value to be sure the user hasn't changed
/// it, then generate the new value for our output.
fn update_template_and_data(
&self,
outgoing_setting_data: &str,
outgoing_template: &str,
incoming_template: &str,
input: &mut MigrationData,
) -> Result<()> {
if let Some(template) = &self.get_setting_template(input) {
if template == outgoing_template {
println!(
"Changing template of '{}' from '{}' to '{}'",
self.setting, outgoing_template, incoming_template
);
// Update the setting's template
let metadata = input.metadata.entry(self.setting.to_string()).or_default();
metadata.insert(
"template".to_string(),
serde_json::Value::String(incoming_template.to_string()),
);
let registry = schnauzer::v1::build_template_registry()
.context(error::BuildTemplateRegistrySnafu)?;
// Structure the input migration data into its hierarchical representation needed by render_template
let input_data = structure_migration_data_for_templates(&input.data)?;
// Generate settings data using the setting's outgoing template so we can confirm
// it matches our expected value; if not, the user has changed it and we should stop.
let generated_old_data = registry
.render_template(template, &input_data)
.context(error::RenderTemplateSnafu { template })?;
if generated_old_data == *outgoing_setting_data {
// Generate settings data using the setting's incoming template
let generated_new_data = registry
.render_template(incoming_template, &input_data)
.context(error::RenderTemplateSnafu { template })?;
println!(
"Changing value of '{}' from '{}' to '{}'",
self.setting, outgoing_setting_data, generated_new_data
);
// Update settings value with new generated value
input.data.insert(
self.setting.to_string(),
serde_json::Value::String(generated_new_data),
);
} else {
println!(
"'{}' is not set to '{}', leaving alone",
self.setting, generated_old_data
);
}
} else {
println!(
"Template for '{}' is not set to '{}', leaving alone",
self.setting, outgoing_template
);
}
}
Ok(())
}
}
#[allow(deprecated)]
impl Migration for ReplaceTemplateMigration {
fn forward(&mut self, mut input: MigrationData) -> Result<MigrationData> {
if let Some(input_value) = input.data.get(self.setting) {
let data = input_value
.as_str()
.context(error::NonStringSettingDataTypeSnafu {
setting: self.setting,
})?;
println!(
"Updating template and value of '{}' on upgrade",
self.setting
);
self.update_template_and_data(
// Clone the input string; we need to give the function mutable access to
// the structure that contains the string, so we can't pass a reference into the structure.
#[allow(clippy::unnecessary_to_owned)]
&data.to_owned(),
self.old_template,
self.new_template,
&mut input,
)?;
} else {
println!("Found no '{}' to change on upgrade", self.setting);
}
Ok(input)
}
fn backward(&mut self, mut input: MigrationData) -> Result<MigrationData> {
if let Some(input_value) = input.data.get(self.setting) {
let data = input_value
.as_str()
.context(error::NonStringSettingDataTypeSnafu {
setting: self.setting,
})?;
println!(
"Updating template and value of '{}' on downgrade",
self.setting
);
self.update_template_and_data(
// Clone the input string; we need to give the function mutable access to
// the structure that contains the string, so we can't pass a reference into the structure.
#[allow(clippy::unnecessary_to_owned)]
&data.to_owned(),
self.new_template,
self.old_template,
&mut input,
)?;
} else {
println!("Found no '{}' to change on downgrade", self.setting);
}
Ok(input)
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// We use this migration when we replace an existing template for generating some setting.
pub struct ReplaceSchnauzerMigration {
pub setting: &'static str,
pub old_schnauzer_cmdline: &'static str,
pub new_schnauzer_cmdline: &'static str,
}
/// This helper function takes `MigrationData.data`, which is a mapping of dotted keys ->
/// scalar values, and converts it into the hierarchical representation needed by handlebars templates.
fn structure_migration_data_for_templates(
input: &HashMap<String, serde_json::Value>,
) -> Result<impl Serialize> {
let mut datastore: HashMap<datastore::Key, String> = HashMap::new();
for (k, v) in input.iter() {
// The prefixes we want to make available; these each have to be deserialized below.
if k.starts_with("settings.") || k.starts_with("os.") {
datastore.insert(
datastore::Key::new(datastore::KeyType::Data, k).context(error::NewKeySnafu)?,
// We want the serialized form here, to work with the datastore deserialization code.
// to_string on a Value gives the serialized form.
v.to_string(),
);
}
}
// Note this is a workaround because we don't have a top level model structure that encompasses 'settings'.
// We need to use `from_map_with_prefix` because we don't have a struct; it strips away the
// "settings" layer, which we then add back on with a wrapping HashMap.
let settings_data: HashMap<String, serde_json::Value> =
datastore::deserialization::from_map_with_prefix(Some("settings".to_string()), &datastore)
.context(error::DeserializeDatastoreSnafu)?;
// Same for "os.*"
let os_data: HashMap<String, serde_json::Value> =
datastore::deserialization::from_map_with_prefix(Some("os".to_string()), &datastore)
.context(error::DeserializeDatastoreSnafu)?;
let mut structured_data = HashMap::new();
structured_data.insert("settings", settings_data);
structured_data.insert("os", os_data);
Ok(structured_data)
}
/// Schnauzer's renderer requires a `TemplateImporter` which tells the renderer how to find settings
/// and helpers. We define our own importer which uses our in-memory copy of the datastore to find
/// settings, and the current static set of helpers.
#[derive(Debug, Clone)]
struct SchnauzerMigrationTemplateImporter {
settings_resolver: JsonSettingsResolver,
helper_resolver: StaticHelperResolver,
}
impl SchnauzerMigrationTemplateImporter {
fn new(settings: serde_json::Value) -> Self {
Self {
settings_resolver: JsonSettingsResolver::new(settings),
helper_resolver: StaticHelperResolver,
}
}
}
schnauzer::impl_template_importer!(
SchnauzerMigrationTemplateImporter,
JsonSettingsResolver,
StaticHelperResolver
);
impl ReplaceSchnauzerMigration {
fn get_setting_schnauzer_cmdline(&self, input: &MigrationData) -> Option<String> {
input
.metadata
.get(self.setting)
.or_else(|| {
eprintln!("'{}' has no metadata", self.setting);
None
})
.and_then(|metadata| {
let setting_generator = metadata.get("setting-generator");
if setting_generator.is_none() {
eprintln!(
"'{}' has no 'setting-generator' key in metadata",
self.setting
);
}
setting_generator
})
.and_then(|setting_generator_value| {
let setting_generator = setting_generator_value.as_str();
if setting_generator.is_none() {
eprintln!(
"'{}' has non-string setting-generator value '{}'",
self.setting, setting_generator_value
);
}
setting_generator
})
.and_then(|schnauzer_cmdline| {
if !schnauzer_cmdline.trim().starts_with("schnauzer-v2") {
eprintln!(
"'{}' has non-schnauzer setting-generator value '{}'",
self.setting, schnauzer_cmdline
);
None
} else {
Some(schnauzer_cmdline.to_string())
}
})
}
fn update_schnauzer_cmdline_and_data(
&self,
current_schnauzer_cmdline: &str,
outgoing_setting_data: &str,
outgoing_schnauzer_cmdline: &str,
incoming_schnauzer_cmdline: &str,
input: &mut MigrationData,
) -> Result<()> {
if current_schnauzer_cmdline == outgoing_schnauzer_cmdline {
println!(
"Updating schnauzer cmdline of '{}' from '{}' to '{}'",
self.setting, outgoing_schnauzer_cmdline, incoming_schnauzer_cmdline
);
// Update the schnauzer cmdline
let metadata = input.metadata.entry(self.setting.to_string()).or_default();
metadata.insert(
"setting-generator".to_string(),
serde_json::Value::String(incoming_schnauzer_cmdline.to_string()),
);
let input_data = structure_migration_data_for_templates(&input.data)?;
let input_data =
serde_json::to_value(input_data).context(error::SerializeTemplateDataSnafu)?;
// Generate settings data using the setting's outgoing template so we can confirm
// it matches our expected value; if not, the user has changed it and we should stop.
let template_importer = SchnauzerMigrationTemplateImporter::new(input_data);
let outgoing_command_args = Shlex::new(outgoing_schnauzer_cmdline);
let tokio_runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.context(error::CreateTokioRuntimeSnafu)?;
let generated_old_data = tokio_runtime
.block_on(async {
schnauzer::v2::cli::run_with_args(outgoing_command_args, &template_importer)
.await
})
.with_context(|_| error::RenderSchnauzerV2TemplateSnafu {
cmdline: outgoing_schnauzer_cmdline.to_string(),
})?;
if generated_old_data == *outgoing_setting_data {
// Generate settings data using the setting's incoming template
let incoming_command_args = Shlex::new(incoming_schnauzer_cmdline);
let generated_new_data = tokio_runtime
.block_on(async {
schnauzer::v2::cli::run_with_args(incoming_command_args, &template_importer)
.await
})
.with_context(|_| error::RenderSchnauzerV2TemplateSnafu {
cmdline: incoming_schnauzer_cmdline.to_string(),
})?;
println!(
"Changing value of '{}' from '{}' to '{}'",
self.setting, outgoing_setting_data, generated_new_data
);
// Update settings value with new generated value
input.data.insert(
self.setting.to_string(),
serde_json::Value::String(generated_new_data),
);
} else {
println!(
"'{}' is not set to '{}', leaving alone",
self.setting, generated_old_data
);
}
}
Ok(())
}
}
impl Migration for ReplaceSchnauzerMigration {
fn forward(&mut self, mut input: MigrationData) -> Result<MigrationData> {
if let Some(input_value) = input.data.get(self.setting) {
let data = input_value
.as_str()
.context(error::NonStringSettingDataTypeSnafu {
setting: self.setting,
})?;
println!(
"Updating schnauzer template and value of '{}' on upgrade",
self.setting
);
if let Some(schnauzer_cmdline) = &self.get_setting_schnauzer_cmdline(&input) {
if schnauzer_cmdline == self.old_schnauzer_cmdline {
self.update_schnauzer_cmdline_and_data(
schnauzer_cmdline,
// Clone the input string; we need to give the function mutable access to
// the structure that contains the string, so we can't pass a reference into the
// structure.
#[allow(clippy::unnecessary_to_owned)]
&data.to_owned(),
self.old_schnauzer_cmdline,
self.new_schnauzer_cmdline,
&mut input,
)?;
} else {
println!(
"Generator for '{}' is not set to '{}', leaving alone",
self.setting, self.old_schnauzer_cmdline
);
}
}
} else {
println!("Found no '{}' to change on upgrade", self.setting);
}
Ok(input)
}
fn backward(&mut self, mut input: MigrationData) -> Result<MigrationData> {
if let Some(input_value) = input.data.get(self.setting) {
let data = input_value
.as_str()
.context(error::NonStringSettingDataTypeSnafu {
setting: self.setting,
})?;
println!(
"Updating schnauzer template and value of '{}' on downgrade",
self.setting
);
if let Some(schnauzer_cmdline) = &self.get_setting_schnauzer_cmdline(&input) {
self.update_schnauzer_cmdline_and_data(
schnauzer_cmdline,
// Clone the input string; we need to give the function mutable access to
// the structure that contains the string, so we can't pass a reference into the
// structure.
#[allow(clippy::unnecessary_to_owned)]
&data.to_owned(),
self.new_schnauzer_cmdline,
self.old_schnauzer_cmdline,
&mut input,
)?;
}
} else {
println!("Found no '{}' to change on downgrade", self.setting);
}
Ok(input)
}
}
#[cfg(test)]
mod test_replace_schnauzer_migration {
use super::ReplaceSchnauzerMigration;
use crate::{Migration, MigrationData};
use maplit::hashmap;
use serde_json::json;
#[test]
fn test_replaces_data_and_generator() {
// Given a schnauzer migration where the settings generator and generated data are both set
// to the input values,
// When the ReplaceSchnauzerMigration is performed,
// Both the generator and data are updated.
let mut migration = ReplaceSchnauzerMigration {
setting: "settings.output",
old_schnauzer_cmdline:
"schnauzer-v2 render --requires 'input@v1' --template '{{ settings.input }}'",
new_schnauzer_cmdline:
"schnauzer-v2 render --requires 'input@v1' --template '{{ settings.input }}, world'",
};
let input = MigrationData {
data: hashmap! {
"settings.input".into() => json!("hello"),
"settings.output".into() => json!("hello"),
"os".into() => json!({}),
},
metadata: hashmap! {
"settings.output".into() => hashmap!{"setting-generator".into() => migration.old_schnauzer_cmdline.into()}
},
};
let forward_result = migration.forward(input.clone());
println!("{:?}", forward_result);
let forward_result = forward_result.unwrap();
assert_eq!(
forward_result
.data
.get("settings.output")
.unwrap()
.as_str()
.unwrap(),
"hello, world"
);
assert_eq!(
forward_result
.metadata
.get("settings.output")
.unwrap()
.get("setting-generator")
.unwrap(),
migration.new_schnauzer_cmdline
);
let backward_result = migration.backward(forward_result);
println!("{:?}", backward_result);
let backward_result = backward_result.unwrap();
assert_eq!(
backward_result
.data
.get("settings.output")
.unwrap()
.as_str()
.unwrap(),
"hello"
);
assert_eq!(
backward_result