-
Notifications
You must be signed in to change notification settings - Fork 192
Expand file tree
/
Copy pathconfig.rs
More file actions
575 lines (544 loc) · 19.1 KB
/
config.rs
File metadata and controls
575 lines (544 loc) · 19.1 KB
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
//! # Configuration for `bootc install`
//!
//! This module handles the TOML configuration file for `bootc install`.
use anyhow::{Context, Result};
use clap::ValueEnum;
use fn_error_context::context;
use serde::{Deserialize, Serialize};
#[cfg(feature = "install-to-disk")]
use super::baseline::BlockSetup;
/// Properties of the environment, such as the system architecture
/// Left open for future properties such as `platform.id`
pub(crate) struct EnvProperties {
pub(crate) sys_arch: String,
}
/// A well known filesystem type.
#[derive(clap::ValueEnum, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum Filesystem {
Xfs,
Ext4,
Btrfs,
}
impl std::fmt::Display for Filesystem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_possible_value().unwrap().get_name().fmt(f)
}
}
/// The toplevel config entry for installation configs stored
/// in bootc/install (e.g. /etc/bootc/install/05-custom.toml)
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub(crate) struct InstallConfigurationToplevel {
pub(crate) install: Option<InstallConfiguration>,
}
/// Configuration for a filesystem
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub(crate) struct RootFS {
#[serde(rename = "type")]
pub(crate) fstype: Option<Filesystem>,
}
/// This structure should only define "system" or "basic" filesystems; we are
/// not trying to generalize this into e.g. supporting `/var` or other ones.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub(crate) struct BasicFilesystems {
pub(crate) root: Option<RootFS>,
// TODO allow configuration of these other filesystems too
// pub(crate) xbootldr: Option<FilesystemCustomization>,
// pub(crate) esp: Option<FilesystemCustomization>,
}
/// The serialized [install] section
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename = "install", rename_all = "kebab-case", deny_unknown_fields)]
pub(crate) struct InstallConfiguration {
/// Root filesystem type
pub(crate) root_fs_type: Option<Filesystem>,
/// Enabled block storage configurations
#[cfg(feature = "install-to-disk")]
pub(crate) block: Option<Vec<BlockSetup>>,
pub(crate) filesystem: Option<BasicFilesystems>,
/// Kernel arguments, applied at installation time
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) kargs: Option<Vec<String>>,
/// Supported architectures for this configuration
pub(crate) match_architectures: Option<Vec<String>>,
}
fn merge_basic<T>(s: &mut Option<T>, o: Option<T>, _env: &EnvProperties) {
if let Some(o) = o {
*s = Some(o);
}
}
trait Mergeable {
fn merge(&mut self, other: Self, env: &EnvProperties)
where
Self: Sized;
}
impl<T> Mergeable for Option<T>
where
T: Mergeable,
{
fn merge(&mut self, other: Self, env: &EnvProperties)
where
Self: Sized,
{
if let Some(other) = other {
if let Some(s) = self.as_mut() {
s.merge(other, env)
} else {
*self = Some(other);
}
}
}
}
impl Mergeable for RootFS {
/// Apply any values in other, overriding any existing values in `self`.
fn merge(&mut self, other: Self, env: &EnvProperties) {
merge_basic(&mut self.fstype, other.fstype, env)
}
}
impl Mergeable for BasicFilesystems {
/// Apply any values in other, overriding any existing values in `self`.
fn merge(&mut self, other: Self, env: &EnvProperties) {
self.root.merge(other.root, env)
}
}
impl Mergeable for InstallConfiguration {
/// Apply any values in other, overriding any existing values in `self`.
fn merge(&mut self, other: Self, env: &EnvProperties) {
// if arch is specified, only merge config if it matches the current arch
// if arch is not specified, merge config unconditionally
if other
.match_architectures
.map(|a| a.contains(&env.sys_arch))
.unwrap_or(true)
{
merge_basic(&mut self.root_fs_type, other.root_fs_type, env);
#[cfg(feature = "install-to-disk")]
merge_basic(&mut self.block, other.block, env);
self.filesystem.merge(other.filesystem, env);
if let Some(other_kargs) = other.kargs {
self.kargs
.get_or_insert_with(Default::default)
.extend(other_kargs)
}
}
}
}
impl InstallConfiguration {
/// Set defaults (e.g. `block`), and also handle fields that can be specified multiple ways
/// by synchronizing the values of the fields to ensure they're the same.
///
/// - install.root-fs-type is synchronized with install.filesystems.root.type; if
/// both are set, then the latter takes precedence
pub(crate) fn canonicalize(&mut self) {
// New canonical form wins.
if let Some(rootfs_type) = self.filesystem_root().and_then(|f| f.fstype.as_ref()) {
self.root_fs_type = Some(*rootfs_type)
} else if let Some(rootfs) = self.root_fs_type.as_ref() {
let fs = self.filesystem.get_or_insert_with(Default::default);
let root = fs.root.get_or_insert_with(Default::default);
root.fstype = Some(*rootfs);
}
#[cfg(feature = "install-to-disk")]
if self.block.is_none() {
self.block = Some(vec![BlockSetup::Direct]);
}
}
/// Convenience helper to access the root filesystem
pub(crate) fn filesystem_root(&self) -> Option<&RootFS> {
self.filesystem.as_ref().and_then(|fs| fs.root.as_ref())
}
// Remove all configuration which is handled by `install to-filesystem`.
pub(crate) fn filter_to_external(&mut self) {
self.kargs.take();
}
#[cfg(feature = "install-to-disk")]
pub(crate) fn get_block_setup(&self, default: Option<BlockSetup>) -> Result<BlockSetup> {
let valid_block_setups = self.block.as_deref().unwrap_or_default();
let default_block = valid_block_setups.iter().next().ok_or_else(|| {
anyhow::anyhow!("Empty block storage configuration in install configuration")
})?;
let block_setup = default.as_ref().unwrap_or(default_block);
if !valid_block_setups.contains(block_setup) {
anyhow::bail!("Block setup {block_setup:?} is not enabled in installation config");
}
Ok(*block_setup)
}
}
#[context("Loading configuration")]
/// Load the install configuration, merging all found configuration files.
pub(crate) fn load_config() -> Result<Option<InstallConfiguration>> {
let env = EnvProperties {
sys_arch: std::env::consts::ARCH.to_string(),
};
const SYSTEMD_CONVENTIONAL_BASES: &[&str] = &["/usr/lib", "/usr/local/lib", "/etc", "/run"];
let fragments = liboverdrop::scan(SYSTEMD_CONVENTIONAL_BASES, "bootc/install", &["toml"], true);
let mut config: Option<InstallConfiguration> = None;
for (_name, path) in fragments {
let buf = std::fs::read_to_string(&path)?;
let mut unused = std::collections::HashSet::new();
let de = toml::Deserializer::parse(&buf).with_context(|| format!("Parsing {path:?}"))?;
let mut c: InstallConfigurationToplevel = serde_ignored::deserialize(de, |path| {
unused.insert(path.to_string());
})
.with_context(|| format!("Parsing {path:?}"))?;
for key in unused {
eprintln!("warning: {path:?}: Unknown key {key}");
}
if let Some(config) = config.as_mut() {
if let Some(install) = c.install {
tracing::debug!("Merging install config: {install:?}");
config.merge(install, &env);
}
} else {
// Only set the config if it matches the current arch
// If no arch is specified, set the config unconditionally
if let Some(ref mut install) = c.install {
if install
.match_architectures
.as_ref()
.map(|a| a.contains(&env.sys_arch))
.unwrap_or(true)
{
config = c.install;
}
}
}
}
if let Some(config) = config.as_mut() {
config.canonicalize();
}
Ok(config)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
/// Verify that we can parse our default config file
fn test_parse_config() {
let env = EnvProperties {
sys_arch: "x86_64".to_string(),
};
let c: InstallConfigurationToplevel = toml::from_str(
r##"[install]
root-fs-type = "xfs"
"##,
)
.unwrap();
let mut install = c.install.unwrap();
assert_eq!(install.root_fs_type.unwrap(), Filesystem::Xfs);
let other = InstallConfigurationToplevel {
install: Some(InstallConfiguration {
root_fs_type: Some(Filesystem::Ext4),
..Default::default()
}),
};
install.merge(other.install.unwrap(), &env);
assert_eq!(
install.root_fs_type.as_ref().copied().unwrap(),
Filesystem::Ext4
);
// This one shouldn't have been set
assert!(install.filesystem_root().is_none());
install.canonicalize();
assert_eq!(install.root_fs_type.as_ref().unwrap(), &Filesystem::Ext4);
assert_eq!(
install.filesystem_root().unwrap().fstype.unwrap(),
Filesystem::Ext4
);
let c: InstallConfigurationToplevel = toml::from_str(
r##"[install]
root-fs-type = "ext4"
kargs = ["console=ttyS0", "foo=bar"]
"##,
)
.unwrap();
let mut install = c.install.unwrap();
assert_eq!(install.root_fs_type.unwrap(), Filesystem::Ext4);
let other = InstallConfigurationToplevel {
install: Some(InstallConfiguration {
kargs: Some(
["console=tty0", "nosmt"]
.into_iter()
.map(ToOwned::to_owned)
.collect(),
),
..Default::default()
}),
};
install.merge(other.install.unwrap(), &env);
assert_eq!(install.root_fs_type.unwrap(), Filesystem::Ext4);
assert_eq!(
install.kargs,
Some(
["console=ttyS0", "foo=bar", "console=tty0", "nosmt"]
.into_iter()
.map(ToOwned::to_owned)
.collect()
)
)
}
#[test]
fn test_parse_filesystems() {
let env = EnvProperties {
sys_arch: "x86_64".to_string(),
};
let c: InstallConfigurationToplevel = toml::from_str(
r##"[install.filesystem.root]
type = "xfs"
"##,
)
.unwrap();
let mut install = c.install.unwrap();
assert_eq!(
install.filesystem_root().unwrap().fstype.unwrap(),
Filesystem::Xfs
);
let other = InstallConfigurationToplevel {
install: Some(InstallConfiguration {
filesystem: Some(BasicFilesystems {
root: Some(RootFS {
fstype: Some(Filesystem::Ext4),
}),
}),
..Default::default()
}),
};
install.merge(other.install.unwrap(), &env);
assert_eq!(
install.filesystem_root().unwrap().fstype.unwrap(),
Filesystem::Ext4
);
}
#[test]
fn test_parse_block() {
let env = EnvProperties {
sys_arch: "x86_64".to_string(),
};
let c: InstallConfigurationToplevel = toml::from_str(
r##"[install.filesystem.root]
type = "xfs"
"##,
)
.unwrap();
let mut install = c.install.unwrap();
// Verify the default (but note canonicalization mutates)
{
let mut install = install.clone();
install.canonicalize();
assert_eq!(install.get_block_setup(None).unwrap(), BlockSetup::Direct);
}
let other = InstallConfigurationToplevel {
install: Some(InstallConfiguration {
block: Some(vec![]),
..Default::default()
}),
};
install.merge(other.install.unwrap(), &env);
// Should be set, but zero length
assert_eq!(install.block.as_ref().unwrap().len(), 0);
assert!(install.get_block_setup(None).is_err());
let c: InstallConfigurationToplevel = toml::from_str(
r##"[install]
block = ["tpm2-luks"]"##,
)
.unwrap();
let mut install = c.install.unwrap();
install.canonicalize();
assert_eq!(install.block.as_ref().unwrap().len(), 1);
assert_eq!(install.get_block_setup(None).unwrap(), BlockSetup::Tpm2Luks);
// And verify passing a disallowed config is an error
assert!(install.get_block_setup(Some(BlockSetup::Direct)).is_err());
}
#[test]
/// Verify that kargs are only applied to supported architectures
fn test_arch() {
// no arch specified, kargs ensure that kargs are applied unconditionally
let env = EnvProperties {
sys_arch: "x86_64".to_string(),
};
let c: InstallConfigurationToplevel = toml::from_str(
r##"[install]
root-fs-type = "xfs"
"##,
)
.unwrap();
let mut install = c.install.unwrap();
let other = InstallConfigurationToplevel {
install: Some(InstallConfiguration {
kargs: Some(
["console=tty0", "nosmt"]
.into_iter()
.map(ToOwned::to_owned)
.collect(),
),
..Default::default()
}),
};
install.merge(other.install.unwrap(), &env);
assert_eq!(
install.kargs,
Some(
["console=tty0", "nosmt"]
.into_iter()
.map(ToOwned::to_owned)
.collect()
)
);
let env = EnvProperties {
sys_arch: "aarch64".to_string(),
};
let c: InstallConfigurationToplevel = toml::from_str(
r##"[install]
root-fs-type = "xfs"
"##,
)
.unwrap();
let mut install = c.install.unwrap();
let other = InstallConfigurationToplevel {
install: Some(InstallConfiguration {
kargs: Some(
["console=tty0", "nosmt"]
.into_iter()
.map(ToOwned::to_owned)
.collect(),
),
..Default::default()
}),
};
install.merge(other.install.unwrap(), &env);
assert_eq!(
install.kargs,
Some(
["console=tty0", "nosmt"]
.into_iter()
.map(ToOwned::to_owned)
.collect()
)
);
// one arch matches and one doesn't, ensure that kargs are only applied for the matching arch
let env = EnvProperties {
sys_arch: "aarch64".to_string(),
};
let c: InstallConfigurationToplevel = toml::from_str(
r##"[install]
root-fs-type = "xfs"
"##,
)
.unwrap();
let mut install = c.install.unwrap();
let other = InstallConfigurationToplevel {
install: Some(InstallConfiguration {
kargs: Some(
["console=ttyS0", "foo=bar"]
.into_iter()
.map(ToOwned::to_owned)
.collect(),
),
match_architectures: Some(["x86_64"].into_iter().map(ToOwned::to_owned).collect()),
..Default::default()
}),
};
install.merge(other.install.unwrap(), &env);
assert_eq!(install.kargs, None);
let other = InstallConfigurationToplevel {
install: Some(InstallConfiguration {
kargs: Some(
["console=tty0", "nosmt"]
.into_iter()
.map(ToOwned::to_owned)
.collect(),
),
match_architectures: Some(["aarch64"].into_iter().map(ToOwned::to_owned).collect()),
..Default::default()
}),
};
install.merge(other.install.unwrap(), &env);
assert_eq!(
install.kargs,
Some(
["console=tty0", "nosmt"]
.into_iter()
.map(ToOwned::to_owned)
.collect()
)
);
// multiple arch specified, ensure that kargs are applied to both archs
let env = EnvProperties {
sys_arch: "x86_64".to_string(),
};
let c: InstallConfigurationToplevel = toml::from_str(
r##"[install]
root-fs-type = "xfs"
"##,
)
.unwrap();
let mut install = c.install.unwrap();
let other = InstallConfigurationToplevel {
install: Some(InstallConfiguration {
kargs: Some(
["console=tty0", "nosmt"]
.into_iter()
.map(ToOwned::to_owned)
.collect(),
),
match_architectures: Some(
["x86_64", "aarch64"]
.into_iter()
.map(ToOwned::to_owned)
.collect(),
),
..Default::default()
}),
};
install.merge(other.install.unwrap(), &env);
assert_eq!(
install.kargs,
Some(
["console=tty0", "nosmt"]
.into_iter()
.map(ToOwned::to_owned)
.collect()
)
);
let env = EnvProperties {
sys_arch: "aarch64".to_string(),
};
let c: InstallConfigurationToplevel = toml::from_str(
r##"[install]
root-fs-type = "xfs"
"##,
)
.unwrap();
let mut install = c.install.unwrap();
let other = InstallConfigurationToplevel {
install: Some(InstallConfiguration {
kargs: Some(
["console=tty0", "nosmt"]
.into_iter()
.map(ToOwned::to_owned)
.collect(),
),
match_architectures: Some(
["x86_64", "aarch64"]
.into_iter()
.map(ToOwned::to_owned)
.collect(),
),
..Default::default()
}),
};
install.merge(other.install.unwrap(), &env);
assert_eq!(
install.kargs,
Some(
["console=tty0", "nosmt"]
.into_iter()
.map(ToOwned::to_owned)
.collect()
)
);
}
}