-
Notifications
You must be signed in to change notification settings - Fork 191
/
treefile.rs
1609 lines (1479 loc) · 51.9 KB
/
treefile.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2018 Red Hat, Inc.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*/
/* Copied and adapted from:
* https://github.com/cgwalters/coreos-assembler
* */
use anyhow::{anyhow, bail, Result};
use c_utf8::CUtf8Buf;
use openat;
use serde_derive::{Deserialize, Serialize};
use serde_json;
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, HashMap};
use std::io::prelude::*;
use std::os::unix::fs::MetadataExt;
use std::path::Path;
use std::{collections, fs, io};
use crate::utils;
const INCLUDE_MAXDEPTH: u32 = 50;
#[cfg(not(feature = "sqlite-rpmdb-default"))]
const DEFAULT_RPMDB_BACKEND: RpmdbBackend = RpmdbBackend::BDB;
#[cfg(feature = "sqlite-rpmdb-default")]
const DEFAULT_RPMDB_BACKEND: RpmdbBackend = RpmdbBackend::Sqlite;
/// This struct holds file descriptors for any external files/data referenced by
/// a TreeComposeConfig.
struct TreefileExternals {
postprocess_script: Option<fs::File>,
add_files: collections::BTreeMap<String, fs::File>,
passwd: Option<fs::File>,
group: Option<fs::File>,
}
// This type name is exposed through ffi.
pub struct Treefile {
// This one isn't used today, but we may do more in the future.
_workdir: Option<openat::Dir>,
primary_dfd: openat::Dir,
#[allow(dead_code)] // Not used in tests
parsed: TreeComposeConfig,
// This is a copy of rojig.name to avoid needing to convert to CStr when reading
rojig_name: Option<CUtf8Buf>,
rojig_spec: Option<CUtf8Buf>,
serialized: CUtf8Buf,
externals: TreefileExternals,
}
// We only use this while parsing
struct ConfigAndExternals {
config: TreeComposeConfig,
externals: TreefileExternals,
}
/// Parse a YAML treefile definition using base architecture `basearch`.
/// This does not open the externals.
fn treefile_parse_stream<R: io::Read>(
fmt: utils::InputFormat,
input: &mut R,
basearch: Option<&str>,
) -> Result<TreeComposeConfig> {
let mut treefile: TreeComposeConfig = utils::parse_stream(&fmt, input)?;
treefile.basearch = match (treefile.basearch, basearch) {
(Some(treearch), Some(arch)) => {
if treearch != arch {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"Invalid basearch {} on {}: cross-composes are not supported",
treearch, arch
),
)
.into());
} else {
Some(treearch)
}
}
(None, Some(arch)) => Some(arch.into()),
// really, only for tests do we not specify a basearch. let's just canonicalize to None
(_, None) => None,
};
// remove from packages-${arch} keys from the extra keys
let mut archful_pkgs: Option<Vec<String>> = take_archful_pkgs(basearch, &mut treefile)?;
if fmt == utils::InputFormat::YAML && !treefile.extra.is_empty() {
let keys: Vec<&str> = treefile.extra.keys().map(|k| k.as_str()).collect();
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("Unknown fields: {}", keys.join(", ")),
)
.into());
}
// Special handling for packages, since we allow whitespace within items.
// We also canonicalize bootstrap_packages to packages here so it's
// easier to append the basearch packages after.
let mut pkgs: Vec<String> = vec![];
{
if let Some(base_pkgs) = treefile.packages.take() {
pkgs.extend_from_slice(&whitespace_split_packages(&base_pkgs)?);
}
if let Some(bootstrap_pkgs) = treefile.bootstrap_packages.take() {
pkgs.extend_from_slice(&whitespace_split_packages(&bootstrap_pkgs)?);
}
if let Some(archful_pkgs) = archful_pkgs.take() {
pkgs.extend_from_slice(&whitespace_split_packages(&archful_pkgs)?);
}
}
treefile.packages = Some(pkgs);
treefile = treefile.migrate_legacy_fields()?;
Ok(treefile)
}
/// Sanity checks that the packages-${basearch} entries are well-formed, and returns the ones
/// matching the current basearch.
fn take_archful_pkgs(
basearch: Option<&str>,
treefile: &mut TreeComposeConfig,
) -> Result<Option<Vec<String>>> {
let mut archful_pkgs: Option<Vec<String>> = None;
for key in treefile.extra.keys().filter(|k| k.starts_with("packages-")) {
if !treefile.extra[key].is_array()
|| treefile.extra[key]
.as_array()
.unwrap()
.iter()
.any(|v| !v.is_string())
{
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid field {}: expected array of strings", key),
)
.into());
}
if let Some(basearch) = basearch {
if basearch == &key["packages-".len()..] {
assert!(archful_pkgs == None);
archful_pkgs = Some(
treefile.extra[key]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_str().unwrap().into())
.collect(),
);
}
}
}
// and drop it from the map
treefile
.extra
.retain(|ref k, _| !k.starts_with("packages-"));
Ok(archful_pkgs)
}
// If a passwd/group file is provided explicitly, load it as a fd
fn load_passwd_file<P: AsRef<Path>>(
basedir: P,
v: &Option<CheckPasswd>,
) -> Result<Option<fs::File>> {
if let Some(ref v) = *v {
let basedir = basedir.as_ref();
if let Some(ref path) = v.filename {
return Ok(Some(utils::open_file(basedir.join(path))?));
}
}
Ok(None)
}
type IncludeMap = collections::BTreeMap<(u64, u64), String>;
/// Given a treefile filename and an architecture, parse it and also
/// open its external files.
fn treefile_parse<P: AsRef<Path>>(
filename: P,
basearch: Option<&str>,
seen_includes: &mut IncludeMap,
) -> Result<ConfigAndExternals> {
let filename = filename.as_ref();
let f = utils::open_file(filename)?;
let meta = f.metadata()?;
let devino = (meta.dev(), meta.ino());
match seen_includes.entry(devino) {
Entry::Occupied(_) => bail!(
"Include loop detected; {} was already included",
filename.to_str().unwrap()
),
Entry::Vacant(e) => {
e.insert(filename.to_str().unwrap().to_string());
}
};
let mut f = io::BufReader::new(f);
let fmt = utils::InputFormat::detect_from_filename(filename)?;
let tf = treefile_parse_stream(fmt, &mut f, basearch).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Parsing {}: {}", filename.to_string_lossy(), e.to_string()),
)
})?;
let postprocess_script = if let Some(ref postprocess) = tf.postprocess_script.as_ref() {
Some(utils::open_file(filename.with_file_name(postprocess))?)
} else {
None
};
let mut add_files: BTreeMap<String, fs::File> = BTreeMap::new();
if let Some(ref add_file_names) = tf.add_files.as_ref() {
for (name, _) in add_file_names.iter() {
add_files.insert(
name.clone(),
utils::open_file(filename.with_file_name(name))?,
);
}
}
let parent = utils::parent_dir(filename).unwrap();
let passwd = load_passwd_file(&parent, &tf.check_passwd)?;
let group = load_passwd_file(&parent, &tf.check_groups)?;
Ok(ConfigAndExternals {
config: tf,
externals: TreefileExternals {
postprocess_script,
add_files,
passwd,
group,
},
})
}
/// Merge a "basic" or non-array field. The semantics originally defined for
/// these are that first-one wins.
fn merge_basic_field<T>(dest: &mut Option<T>, src: &mut Option<T>) {
if dest.is_some() {
return;
}
*dest = src.take()
}
/// Merge a vector field by appending. This semantic was originally designed for
/// the `packages` key.
fn merge_vec_field<T>(dest: &mut Option<Vec<T>>, src: &mut Option<Vec<T>>) {
if let Some(mut srcv) = src.take() {
if let Some(ref mut destv) = dest {
srcv.append(destv);
}
*dest = Some(srcv);
}
}
/// Merge a map field similarly to Python's `dict.update()`. In case of
/// duplicate keys, `dest` wins (`src` is the "included" config).
fn merge_map_field<T>(
dest: &mut Option<BTreeMap<String, T>>,
src: &mut Option<BTreeMap<String, T>>,
) {
if let Some(mut srcv) = src.take() {
if let Some(mut destv) = dest.take() {
srcv.append(&mut destv);
}
*dest = Some(srcv);
}
}
/// Given two configs, merge them.
fn treefile_merge(dest: &mut TreeComposeConfig, src: &mut TreeComposeConfig) {
macro_rules! merge_basics {
( $($field:ident),* ) => {{
$( merge_basic_field(&mut dest.$field, &mut src.$field); )*
}};
};
macro_rules! merge_vecs {
( $($field:ident),* ) => {{
$( merge_vec_field(&mut dest.$field, &mut src.$field); )*
}};
};
macro_rules! merge_maps {
( $($field:ident),* ) => {{
$( merge_map_field(&mut dest.$field, &mut src.$field); )*
}};
};
merge_basics!(
treeref,
basearch,
rojig,
selinux,
gpg_key,
include,
container,
recommends,
cliwrap,
readonly_executables,
documentation,
boot_location,
tmp_is_dir,
default_target,
machineid_compat,
releasever,
automatic_version_prefix,
automatic_version_suffix,
rpmdb,
mutate_os_release,
preserve_passwd,
check_passwd,
check_groups,
postprocess_script
);
merge_vecs!(
repos,
lockfile_repos,
packages,
bootstrap_packages,
exclude_packages,
ostree_layers,
ostree_override_layers,
install_langs,
initramfs_args,
units,
etc_group_members,
ignore_removed_users,
ignore_removed_groups,
postprocess,
add_files,
remove_files,
remove_from_packages
);
merge_maps!(add_commit_metadata);
}
/// Merge the treefile externals. There are currently only two keys that
/// reference external files.
fn treefile_merge_externals(dest: &mut TreefileExternals, src: &mut TreefileExternals) {
// This one, being a basic-valued field, has first-wins semantics.
if dest.postprocess_script.is_none() {
dest.postprocess_script = src.postprocess_script.take();
}
// add-files is an array and hence has append semantics.
dest.add_files.append(&mut src.add_files);
// passwd/group are basic values
if dest.passwd.is_none() {
dest.passwd = src.passwd.take();
}
if dest.group.is_none() {
dest.group = src.group.take();
}
}
/// Recursively parse a treefile, merging along the way.
fn treefile_parse_recurse<P: AsRef<Path>>(
filename: P,
basearch: Option<&str>,
depth: u32,
seen_includes: &mut IncludeMap,
) -> Result<ConfigAndExternals> {
let filename = filename.as_ref();
let mut parsed = treefile_parse(filename, basearch, seen_includes)?;
let include = parsed
.config
.include
.take()
.unwrap_or_else(|| Include::Multiple(Vec::new()));
let mut includes = match include {
Include::Single(v) => vec![v],
Include::Multiple(v) => v,
};
if let Some(mut arch_includes) = parsed.config.arch_include.take() {
if let Some(basearch) = basearch {
if let Some(arch_include_value) = arch_includes.remove(basearch) {
match arch_include_value {
Include::Single(v) => includes.push(v),
Include::Multiple(v) => includes.extend(v),
}
}
}
}
for include_path in includes.iter() {
if depth == INCLUDE_MAXDEPTH {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("Reached maximum include depth {}", INCLUDE_MAXDEPTH),
)
.into());
}
let parent = utils::parent_dir(filename).unwrap();
let include_path = parent.join(include_path);
let mut included =
treefile_parse_recurse(include_path, basearch, depth + 1, seen_includes)?;
treefile_merge(&mut parsed.config, &mut included.config);
treefile_merge_externals(&mut parsed.externals, &mut included.externals);
}
Ok(parsed)
}
// Similar to the importer check but just checks for prefixes since
// they're files, and also allows /etc since it's before conversion
fn add_files_path_is_valid(path: &str) -> bool {
let path = path.trim_start_matches('/');
(path.starts_with("usr/") && !path.starts_with("usr/local/"))
|| path.starts_with("etc/")
|| path.starts_with("bin/")
|| path.starts_with("sbin/")
|| path.starts_with("lib/")
|| path.starts_with("lib64/")
}
impl Treefile {
/// The main treefile creation entrypoint.
fn new_boxed(
filename: &Path,
basearch: Option<&str>,
workdir: Option<openat::Dir>,
) -> Result<Box<Treefile>> {
let mut seen_includes = collections::BTreeMap::new();
let mut parsed = treefile_parse_recurse(filename, basearch, 0, &mut seen_includes)?;
parsed.config = parsed.config.substitute_vars()?;
Treefile::validate_config(&parsed.config)?;
let dfd = openat::Dir::open(utils::parent_dir(filename).unwrap())?;
let (rojig_name, rojig_spec) = match (workdir.as_ref(), parsed.config.rojig.as_ref()) {
(Some(workdir), Some(rojig)) => (
Some(CUtf8Buf::from_string(rojig.name.clone())),
Some(Treefile::write_rojig_spec(workdir, rojig)?),
),
_ => (None, None),
};
let serialized = Treefile::serialize_json_string(&parsed.config)?;
Ok(Box::new(Treefile {
primary_dfd: dfd,
parsed: parsed.config,
_workdir: workdir,
rojig_name,
rojig_spec,
serialized,
externals: parsed.externals,
}))
}
/// Do some upfront semantic checks we can do beyond just the type safety serde provides.
fn validate_config(config: &TreeComposeConfig) -> Result<()> {
// check add-files
if let Some(files) = &config.add_files {
for (_, dest) in files.iter() {
if !add_files_path_is_valid(&dest) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("Unsupported path in add-files: {}", dest),
)
.into());
}
}
}
if let Some(version_suffix) = config.automatic_version_suffix.as_ref() {
if !(version_suffix.len() == 1 && version_suffix.is_ascii()) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"Invalid automatic-version-suffix, must be exactly one ASCII character: {}",
version_suffix
),
)
.into());
}
}
Ok(())
}
fn serialize_json_string(config: &TreeComposeConfig) -> Result<CUtf8Buf> {
let output = serde_json::to_string_pretty(config)?;
Ok(CUtf8Buf::from_string(output))
}
/// Given a treefile, print warnings about items which are deprecated.
fn print_deprecation_warnings(&self) {
let mut deprecated = false;
match self
.parsed
.boot_location
.as_ref()
.copied()
.unwrap_or_default()
{
BootLocation::Modules => {}
o => {
let s = serde_json::to_string(&o).expect("serialize");
deprecated = true;
eprintln!(
"warning: boot-location: {} is deprecated, use boot-location: modules",
s
)
}
}
if deprecated {
std::thread::sleep(std::time::Duration::from_secs(3));
}
}
fn get_checksum(&self, repo: &ostree::Repo) -> Result<String> {
// Notice we hash the *reserialization* of the final flattened treefile only so that e.g.
// comments/whitespace/hash table key reorderings don't trigger a respin. We could take
// this further by using a custom `serialize_with` for Vecs where ordering doesn't matter
// (or just sort the Vecs).
let mut hasher = glib::Checksum::new(glib::ChecksumType::Sha256);
self.parsed.hasher_update(&mut hasher)?;
self.externals.hasher_update(&mut hasher)?;
let it = self.parsed.ostree_layers.iter().flat_map(|x| x.iter());
let it = it.chain(
self.parsed
.ostree_override_layers
.iter()
.flat_map(|x| x.iter()),
);
for v in it {
let rev = repo.resolve_rev(v, false)?;
let rev = rev.as_str();
let (commit, _) = repo.load_commit(rev)?;
let content_checksum =
ostree::commit_get_content_checksum(&commit).expect("content checksum");
let content_checksum = content_checksum.as_str();
hasher.update(content_checksum.as_bytes());
}
Ok(hasher.get_string().expect("hash"))
}
/// Generate a rojig spec file.
fn write_rojig_spec<'a, 'b>(workdir: &'a openat::Dir, r: &'b Rojig) -> Result<CUtf8Buf> {
let description = r
.description
.as_ref()
.and_then(|v| if !v.is_empty() { Some(v.as_str()) } else { None })
.unwrap_or(r.summary.as_str());
let name: String = format!("{}.spec", r.name);
{
let mut f = workdir.write_file(name.as_str(), 0o644)?;
write!(
f,
r###"
# The canonical version of this is maintained by rpm-ostree.
# Suppress most build root processing we are just carrying
# binary data.
%global __os_install_post /usr/lib/rpm/brp-compress %{{nil}}
Name: {rpmostree_rojig_name}
Version: %{{ostree_version}}
Release: 1%{{?dist}}
Summary: {rpmostree_rojig_summary}
License: {rpmostree_rojig_license}
#@@@rpmostree_rojig_meta@@@
%description
{rpmostree_rojig_description}
%prep
%build
%install
mkdir -p %{{buildroot}}%{{_prefix}}/lib/ostree-jigdo/%{{name}}
for x in *; do mv ${{x}} %{{buildroot}}%{{_prefix}}/lib/ostree-jigdo/%{{name}}; done
%files
%{{_prefix}}/lib/ostree-jigdo/%{{name}}
"###,
rpmostree_rojig_name = r.name,
rpmostree_rojig_summary = r.summary,
rpmostree_rojig_license = r.license,
rpmostree_rojig_description = description,
)?;
}
Ok(CUtf8Buf::from_string(name))
}
}
fn hash_file(hasher: &mut glib::Checksum, mut f: &fs::File) -> Result<()> {
let mut reader = io::BufReader::with_capacity(128 * 1024, f);
loop {
// have to scope fill_buf() so we can consume() below
let n = {
let buf = reader.fill_buf()?;
hasher.update(buf);
buf.len()
};
if n == 0 {
break;
}
reader.consume(n);
}
f.seek(io::SeekFrom::Start(0))?;
Ok(())
}
impl TreefileExternals {
fn hasher_update(&self, hasher: &mut glib::Checksum) -> Result<()> {
if let Some(ref f) = self.postprocess_script {
hash_file(hasher, f)?;
}
if let Some(ref f) = self.passwd {
hash_file(hasher, f)?;
}
if let Some(ref f) = self.group {
hash_file(hasher, f)?;
}
for f in self.add_files.values() {
hash_file(hasher, f)?;
}
Ok(())
}
}
/// For increased readability in YAML/JSON, we support whitespace in individual
/// array elements.
fn whitespace_split_packages(pkgs: &[String]) -> Result<Vec<String>> {
let mut ret = vec![];
for element in pkgs.iter() {
ret.extend(split_whitespace_unless_quoted(element)?.map(String::from));
}
Ok(ret)
}
// Helper for whitespace_split_packages().
// Splits a String by whitespace unless substring is wrapped between single quotes
// and returns split &str in an Iterator.
fn split_whitespace_unless_quoted(element: &str) -> Result<impl Iterator<Item = &str>> {
let mut ret = vec![];
let mut start_index = 0;
let mut looping_over_quoted_pkg = false;
for (i, c) in element.chars().enumerate() {
if c == '\'' {
if looping_over_quoted_pkg {
ret.push(&element[start_index..i]);
looping_over_quoted_pkg = false;
} else {
ret.extend((&element[start_index..i]).split_whitespace());
looping_over_quoted_pkg = true;
}
start_index = i + 1;
}
if i == element.len() - 1 {
if looping_over_quoted_pkg {
bail!("Missing terminating quote: {}", element);
}
ret.extend((&element[start_index..]).split_whitespace());
}
}
Ok(ret.into_iter())
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Copy, Clone)]
enum BootLocation {
#[serde(rename = "new")]
New,
#[serde(rename = "modules")]
Modules,
}
impl Default for BootLocation {
fn default() -> Self {
BootLocation::New
}
}
#[derive(Serialize, Deserialize, Debug)]
enum CheckPasswdType {
#[serde(rename = "none")]
None,
#[serde(rename = "previous")]
Previous,
#[serde(rename = "file")]
File,
#[serde(rename = "data")]
Data,
}
#[derive(Serialize, Deserialize, Debug)]
struct CheckPasswd {
#[serde(rename = "type")]
variant: CheckPasswdType,
filename: Option<String>,
// Skip this for now, a separate file is easier
// and anyways we want to switch to sysusers
// entries: Option<Map<>String>,
}
#[derive(Serialize, Deserialize, Debug)]
struct Rojig {
name: String,
summary: String,
license: String,
description: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
enum Include {
Single(String),
Multiple(Vec<String>),
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
/// The database backend; see https://github.com/coreos/fedora-coreos-tracker/issues/609
/// and https://fedoraproject.org/wiki/Changes/Sqlite_Rpmdb
enum RpmdbBackend {
BDB,
Sqlite,
NDB,
}
// Because of how we handle includes, *everything* here has to be
// Option<T>. The defaults live in the code (e.g. machineid-compat defaults
// to `true`).
#[derive(Serialize, Deserialize, Debug)]
struct TreeComposeConfig {
// Compose controls
#[serde(rename = "ref")]
#[serde(skip_serializing_if = "Option::is_none")]
treeref: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
basearch: Option<String>,
// Optional rojig data
#[serde(skip_serializing_if = "Option::is_none")]
rojig: Option<Rojig>,
#[serde(skip_serializing_if = "Option::is_none")]
repos: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "lockfile-repos")]
lockfile_repos: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
selinux: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "gpg-key")]
gpg_key: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
include: Option<Include>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "arch-include")]
arch_include: Option<BTreeMap<String, Include>>,
// Core content
#[serde(skip_serializing_if = "Option::is_none")]
packages: Option<Vec<String>>,
// Deprecated option
#[serde(skip_serializing_if = "Option::is_none")]
bootstrap_packages: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "ostree-layers")]
ostree_layers: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "ostree-override-layers")]
ostree_override_layers: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "exclude-packages")]
exclude_packages: Option<Vec<String>>,
// Content installation opts
#[serde(skip_serializing_if = "Option::is_none")]
container: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
recommends: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
documentation: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "install-langs")]
install_langs: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "initramfs-args")]
initramfs_args: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
cliwrap: Option<bool>,
#[serde(rename = "readonly-executables")]
#[serde(skip_serializing_if = "Option::is_none")]
readonly_executables: Option<bool>,
// Tree layout options
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "boot-location")]
boot_location: Option<BootLocation>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "tmp-is-dir")]
tmp_is_dir: Option<bool>,
// systemd
#[serde(skip_serializing_if = "Option::is_none")]
units: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "default-target")]
default_target: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "machineid-compat")]
// Defaults to `true`
machineid_compat: Option<bool>,
// versioning
#[serde(skip_serializing_if = "Option::is_none")]
releasever: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "automatic-version-prefix")]
automatic_version_prefix: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "automatic-version-suffix")]
automatic_version_suffix: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "mutate-os-release")]
mutate_os_release: Option<String>,
// passwd-related bits
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "etc-group-members")]
etc_group_members: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "preserve-passwd")]
preserve_passwd: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "check-passwd")]
check_passwd: Option<CheckPasswd>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "check-groups")]
check_groups: Option<CheckPasswd>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "ignore-removed-users")]
ignore_removed_users: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "ignore-removed-groups")]
ignore_removed_groups: Option<Vec<String>>,
// Content manipulation
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "postprocess-script")]
// This one references an external filename
postprocess_script: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
// This one is inline, and supports multiple (hence is useful for inheritance)
postprocess: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "add-files")]
add_files: Option<Vec<(String, String)>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "remove-files")]
remove_files: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "remove-from-packages")]
remove_from_packages: Option<Vec<Vec<String>>>,
// The BTreeMap here is on purpose; it ensures we always re-serialize in sorted order so that
// checksumming is deterministic across runs. (And serde itself uses BTreeMap for child objects
// as well).
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "add-commit-metadata")]
add_commit_metadata: Option<BTreeMap<String, serde_json::Value>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "rpmdb")]
// The database backend
rpmdb: Option<RpmdbBackend>,
#[serde(flatten)]
legacy_fields: LegacyTreeComposeConfigFields,
#[serde(flatten)]
extra: HashMap<String, serde_json::Value>,
}
#[derive(Serialize, Deserialize, Debug)]
struct LegacyTreeComposeConfigFields {
#[serde(skip_serializing)]
gpg_key: Option<String>,
#[serde(skip_serializing)]
boot_location: Option<BootLocation>,
#[serde(skip_serializing)]
default_target: Option<String>,
#[serde(skip_serializing)]
automatic_version_prefix: Option<String>,
}
impl TreeComposeConfig {
/// Look for use of legacy/renamed fields and migrate them to the new field.
fn migrate_legacy_fields(mut self) -> Result<Self> {
macro_rules! migrate_field {
( $field:ident ) => {{
if self.legacy_fields.$field.is_some() && self.$field.is_some() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("Cannot use new and legacy forms of {}", stringify!($field)),
)
.into());
}
self.$field = self.$field.or(self.legacy_fields.$field.take());
}};
};
migrate_field!(gpg_key);
migrate_field!(boot_location);
migrate_field!(default_target);
migrate_field!(automatic_version_prefix);
Ok(self)
}
/// Look for use of ${variable} and replace it by its proper value
fn substitute_vars(mut self) -> Result<Self> {
let mut substvars: collections::HashMap<String, String> = collections::HashMap::new();
// Substitute ${basearch} and ${releasever}
if let Some(arch) = &self.basearch {
substvars.insert("basearch".to_string(), arch.clone());
}
if let Some(releasever) = &self.releasever {
substvars.insert("releasever".to_string(), releasever.clone());
}
envsubst::validate_vars(&substvars)?;
macro_rules! substitute_field {
( $field:ident ) => {{
if let Some(value) = self.$field.take() {
self.$field = if envsubst::is_templated(&value) {
match envsubst::substitute(value, &substvars) {
Ok(s) => Some(s),
Err(e) => return Err(anyhow!(e.to_string())),
}
} else {
Some(value)
}
}
}};
};
substitute_field!(treeref);
substitute_field!(automatic_version_prefix);
substitute_field!(mutate_os_release);
Ok(self)
}
fn hasher_update(&self, hasher: &mut glib::Checksum) -> Result<()> {
// don't use pretty mode to increase the chances of a stable serialization
// https://github.com/projectatomic/rpm-ostree/pull/1865
hasher.update(serde_json::to_vec(self)?.as_slice());
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use openat_ext::OpenatDirExt;
use tempfile;
static ARCH_X86_64: &str = "x86_64";
static VALID_PRELUDE: &str = r###"
ref: "exampleos/x86_64/blah"
packages:
- foo bar
- baz
- corge 'quuz >= 1.0'
packages-x86_64:
- grub2 grub2-tools
packages-s390x:
- zipl
"###;
// This one has "comments" (hence unknown keys)
static VALID_PRELUDE_JS: &str = r###"
{
"ref": "exampleos/${basearch}/blah",
"comment-packages": "We want baz to enable frobnication",
"packages": ["foo", "bar", "baz"],
"packages-x86_64": ["grub2", "grub2-tools"],
"comment-packages-s390x": "Note that s390x uses its own bootloader",
"packages-s390x": ["zipl"]
}
"###;
#[test]
fn basic_valid() {
let mut input = io::BufReader::new(VALID_PRELUDE.as_bytes());
let mut treefile =
treefile_parse_stream(utils::InputFormat::YAML, &mut input, Some(ARCH_X86_64)).unwrap();
treefile = treefile.substitute_vars().unwrap();
assert!(treefile.treeref.unwrap() == "exampleos/x86_64/blah");
assert!(treefile.packages.unwrap().len() == 7);
}
#[test]
fn basic_valid_add_remove_files() {
let mut buf = VALID_PRELUDE.to_string();
buf.push_str(
r###"
add-files:
- - foo