-
Notifications
You must be signed in to change notification settings - Fork 192
Expand file tree
/
Copy pathinstall.rs
More file actions
3096 lines (2746 loc) · 112 KB
/
install.rs
File metadata and controls
3096 lines (2746 loc) · 112 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
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
//! # Writing a container to a block device in a bootable way
//!
//! This module implements the core installation logic for bootc, enabling a container
//! image to be written to storage in a bootable form. It bridges the gap between
//! OCI container images and traditional bootable Linux systems.
//!
//! ## Overview
//!
//! The installation process transforms a container image into a bootable system by:
//!
//! 1. **Preparing the environment**: Validating we're running in a privileged container,
//! handling SELinux re-execution if needed, and loading configuration.
//!
//! 2. **Setting up storage**: Either creating partitions (`to-disk`) or using
//! externally-prepared filesystems (`to-filesystem`).
//!
//! 3. **Deploying the image**: Pulling the container image into an ostree repository
//! and creating a deployment, or setting up a composefs-based root.
//!
//! 4. **Installing the bootloader**: Using bootupd, systemd-boot, or zipl depending
//! on architecture and configuration.
//!
//! 5. **Finalizing**: Trimming the filesystem, flushing writes, and freezing/thawing
//! the journal.
//!
//! ## Installation Modes
//!
//! ### `bootc install to-disk`
//!
//! Creates a complete bootable system on a block device. This is the simplest path
//! and handles partitioning automatically using the Discoverable Partitions
//! Specification (DPS). The partition layout includes:
//!
//! - **ESP** (EFI System Partition): Required for UEFI boot
//! - **BIOS boot partition**: For legacy boot on x86_64
//! - **Boot partition**: Optional, used when LUKS encryption is enabled
//! - **Root partition**: Uses architecture-specific DPS type GUIDs for auto-discovery
//!
//! ### `bootc install to-filesystem`
//!
//! Installs to a pre-mounted filesystem, allowing external tools to handle complex
//! storage layouts (RAID, LVM, custom LUKS configurations). The caller is responsible
//! for creating and mounting the filesystem, then providing appropriate `--karg`
//! options or mount specifications.
//!
//! ### `bootc install to-existing-root`
//!
//! "Alongside" installation mode that converts an existing Linux system. The boot
//! partition is wiped and replaced, but the root filesystem content is preserved
//! until reboot. Post-reboot, the old system is accessible at `/sysroot` for
//! data migration.
//!
//! ### `bootc install reset`
//!
//! Creates a new stateroot within an existing bootc system, effectively providing
//! a factory-reset capability without touching other stateroots.
//!
//! ## Storage Backends
//!
//! ### OSTree Backend (Default)
//!
//! Uses ostree-ext to convert container layers into an ostree repository. The
//! deployment is created via `ostree admin deploy`, and bootloader entries are
//! managed via BLS (Boot Loader Specification) files.
//!
//! ### Composefs Backend (Experimental)
//!
//! Alternative backend using composefs overlayfs for the root filesystem. Provides
//! stronger integrity guarantees via fs-verity and supports UKI (Unified Kernel
//! Images) for measured boot scenarios.
//!
//! ## Discoverable Partitions Specification (DPS)
//!
//! As of bootc 1.11, partitions are created with DPS type GUIDs from the
//! [UAPI Group specification](https://uapi-group.org/specifications/specs/discoverable_partitions_specification/).
//! This enables:
//!
//! - **Auto-discovery**: systemd-gpt-auto-generator can mount partitions without
//! explicit configuration
//! - **Architecture awareness**: Root partition types are architecture-specific,
//! preventing cross-architecture boot issues
//! - **Future extensibility**: Enables systemd-repart for declarative partition
//! management
//!
//! See [`crate::discoverable_partition_specification`] for the partition type GUIDs.
//!
//! ## Installation Flow
//!
//! The high-level flow is:
//!
//! 1. **CLI entry** → [`install_to_disk`], [`install_to_filesystem`], or [`install_to_existing_root`]
//! 2. **Preparation** → [`prepare_install`] validates environment, handles SELinux, loads config
//! 3. **Storage setup** → (to-disk only) [`baseline::install_create_rootfs`] partitions and formats
//! 4. **Deployment** → [`install_to_filesystem_impl`] branches to OSTree or Composefs backend
//! 5. **Bootloader** → [`crate::bootloader::install_via_bootupd`] or architecture-specific installer
//! 6. **Finalization** → [`finalize_filesystem`] trims, flushes, and freezes the filesystem
//!
//! For a visual diagram of this flow, see the bootc documentation.
//!
//! ## Key Types
//!
//! - [`State`]: Immutable global state for the installation, including source image
//! info, SELinux state, configuration, and composefs options.
//!
//! - [`RootSetup`]: Represents the prepared root filesystem, including mount paths,
//! device information, boot partition specs, and kernel arguments.
//!
//! - [`SourceInfo`]: Information about the source container image, including the
//! ostree-container reference and whether SELinux labels are present.
//!
//! - [`SELinuxFinalState`]: Tracks SELinux handling during installation (enabled,
//! disabled, host-disabled, or force-disabled).
//!
//! ## Configuration
//!
//! Installation is configured via TOML files loaded from multiple paths in
//! systemd-style priority order:
//!
//! - `/usr/lib/bootc/install/*.toml` - Distribution/image defaults
//! - `/etc/bootc/install/*.toml` - Local overrides
//!
//! Files are merged alphanumerically, with higher-numbered files taking precedence.
//! See [`config::InstallConfiguration`] for the schema.
//!
//! Key configurable options include:
//! - Root filesystem type (xfs, ext4, btrfs)
//! - Allowed block setups (direct, tpm2-luks)
//! - Default kernel arguments
//! - Architecture-specific overrides
//!
//! ## Submodules
//!
//! - [`baseline`]: The "baseline" installer for simple partitioning (to-disk)
//! - [`config`]: TOML configuration parsing and merging
//! - [`completion`]: Post-installation hooks for external installers (Anaconda)
//! - [`osconfig`]: SSH key injection and OS configuration
//! - [`aleph`]: Installation provenance tracking (.bootc-aleph.json)
//! - `osbuild`: Helper APIs for bootc-image-builder integration
// This sub-module is the "basic" installer that handles creating basic block device
// and filesystem setup.
mod aleph;
#[cfg(feature = "install-to-disk")]
pub(crate) mod baseline;
pub(crate) mod completion;
pub(crate) mod config;
mod osbuild;
pub(crate) mod osconfig;
use std::collections::HashMap;
use std::io::Write;
use std::os::fd::{AsFd, AsRawFd};
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process;
use std::process::Command;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use aleph::InstallAleph;
use anyhow::{Context, Result, anyhow, ensure};
use bootc_kernel_cmdline::utf8::{Cmdline, CmdlineOwned};
use bootc_utils::CommandRunExt;
use camino::Utf8Path;
use camino::Utf8PathBuf;
use canon_json::CanonJsonSerialize;
use cap_std::fs::{Dir, MetadataExt};
use cap_std_ext::cap_std;
use cap_std_ext::cap_std::fs::FileType;
use cap_std_ext::cap_std::fs_utf8::DirEntry as DirEntryUtf8;
use cap_std_ext::cap_tempfile::TempDir;
use cap_std_ext::cmdext::CapStdExtCommandExt;
use cap_std_ext::prelude::CapStdExtDirExt;
use clap::ValueEnum;
use fn_error_context::context;
use ostree::gio;
use ostree_ext::ostree;
use ostree_ext::ostree_prepareroot::{ComposefsState, Tristate};
use ostree_ext::prelude::Cast;
use ostree_ext::sysroot::{SysrootLock, allocate_new_stateroot, list_stateroots};
use ostree_ext::{container as ostree_container, ostree_prepareroot};
#[cfg(feature = "install-to-disk")]
use rustix::fs::FileTypeExt;
use rustix::fs::MetadataExt as _;
use serde::{Deserialize, Serialize};
#[cfg(feature = "install-to-disk")]
use self::baseline::InstallBlockDeviceOpts;
use crate::bootc_composefs::status::ComposefsCmdline;
use crate::bootc_composefs::{
boot::setup_composefs_boot,
repo::{get_imgref, initialize_composefs_repository, open_composefs_repo},
status::get_container_manifest_and_config,
};
use crate::boundimage::{BoundImage, ResolvedBoundImage};
use crate::containerenv::ContainerExecutionInfo;
use crate::deploy::{MergeState, PreparedPullResult, prepare_for_pull, pull_from_prepared};
use crate::install::config::Filesystem as FilesystemEnum;
use crate::lsm;
use crate::progress_jsonl::ProgressWriter;
use crate::spec::{Bootloader, ImageReference};
use crate::store::Storage;
use crate::task::Task;
use crate::utils::sigpolicy_from_opt;
use bootc_kernel_cmdline::{INITRD_ARG_PREFIX, ROOTFLAGS, bytes, utf8};
use bootc_mount::Filesystem;
use cfsctl::composefs;
use composefs::fsverity::FsVerityHashValue;
/// The toplevel boot directory
pub(crate) const BOOT: &str = "boot";
/// Directory for transient runtime state
#[cfg(feature = "install-to-disk")]
const RUN_BOOTC: &str = "/run/bootc";
/// The default path for the host rootfs
const ALONGSIDE_ROOT_MOUNT: &str = "/target";
/// Global flag to signal the booted system was provisioned via an alongside bootc install
pub(crate) const DESTRUCTIVE_CLEANUP: &str = "etc/bootc-destructive-cleanup";
/// This is an ext4 special directory we need to ignore.
const LOST_AND_FOUND: &str = "lost+found";
/// The filename of the composefs EROFS superblock; TODO move this into ostree
const OSTREE_COMPOSEFS_SUPER: &str = ".ostree.cfs";
/// The mount path for selinux
const SELINUXFS: &str = "/sys/fs/selinux";
/// The mount path for uefi
pub(crate) const EFIVARFS: &str = "/sys/firmware/efi/efivars";
pub(crate) const ARCH_USES_EFI: bool = cfg!(any(target_arch = "x86_64", target_arch = "aarch64"));
pub(crate) const EFI_LOADER_INFO: &str = "LoaderInfo-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f";
const DEFAULT_REPO_CONFIG: &[(&str, &str)] = &[
// Default to avoiding grub2-mkconfig etc.
("sysroot.bootloader", "none"),
// Always flip this one on because we need to support alongside installs
// to systems without a separate boot partition.
("sysroot.bootprefix", "true"),
("sysroot.readonly", "true"),
];
/// Kernel argument used to specify we want the rootfs mounted read-write by default
pub(crate) const RW_KARG: &str = "rw";
#[derive(clap::Args, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub(crate) struct InstallTargetOpts {
// TODO: A size specifier which allocates free space for the root in *addition* to the base container image size
// pub(crate) root_additional_size: Option<String>
/// The transport; e.g. oci, oci-archive, containers-storage. Defaults to `registry`.
#[clap(long, default_value = "registry")]
#[serde(default)]
pub(crate) target_transport: String,
/// Specify the image to fetch for subsequent updates
#[clap(long)]
pub(crate) target_imgref: Option<String>,
/// This command line argument does nothing; it exists for compatibility.
///
/// As of newer versions of bootc, this value is enabled by default,
/// i.e. it is not enforced that a signature
/// verification policy is enabled. Hence to enable it, one can specify
/// `--target-no-signature-verification=false`.
///
/// It is likely that the functionality here will be replaced with a different signature
/// enforcement scheme in the future that integrates with `podman`.
#[clap(long, hide = true)]
#[serde(default)]
pub(crate) target_no_signature_verification: bool,
/// This is the inverse of the previous `--target-no-signature-verification` (which is now
/// a no-op). Enabling this option enforces that `/etc/containers/policy.json` includes a
/// default policy which requires signatures.
#[clap(long)]
#[serde(default)]
pub(crate) enforce_container_sigpolicy: bool,
/// Verify the image can be fetched from the bootc image. Updates may fail when the installation
/// host is authenticated with the registry but the pull secret is not in the bootc image.
#[clap(long)]
#[serde(default)]
pub(crate) run_fetch_check: bool,
/// Verify the image can be fetched from the bootc image. Updates may fail when the installation
/// host is authenticated with the registry but the pull secret is not in the bootc image.
#[clap(long)]
#[serde(default)]
pub(crate) skip_fetch_check: bool,
/// Use unified storage path to pull images (experimental)
///
/// When enabled, this uses bootc's container storage (/usr/lib/bootc/storage) to pull
/// the image first, then imports it from there. This is the same approach used for
/// logically bound images.
#[clap(long = "experimental-unified-storage", hide = true)]
#[serde(default)]
pub(crate) unified_storage_exp: bool,
}
#[derive(clap::Args, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub(crate) struct InstallSourceOpts {
/// Install the system from an explicitly given source.
///
/// By default, bootc install and install-to-filesystem assumes that it runs in a podman container, and
/// it takes the container image to install from the podman's container registry.
/// If --source-imgref is given, bootc uses it as the installation source, instead of the behaviour explained
/// in the previous paragraph. See skopeo(1) for accepted formats.
#[clap(long)]
pub(crate) source_imgref: Option<String>,
}
#[derive(ValueEnum, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum BoundImagesOpt {
/// Bound images must exist in the source's root container storage (default)
#[default]
Stored,
#[clap(hide = true)]
/// Do not resolve any "logically bound" images at install time.
Skip,
// TODO: Once we implement https://github.com/bootc-dev/bootc/issues/863 update this comment
// to mention source's root container storage being used as lookaside cache
/// Bound images will be pulled and stored directly in the target's bootc container storage
Pull,
}
impl std::fmt::Display for BoundImagesOpt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_possible_value().unwrap().get_name().fmt(f)
}
}
#[derive(clap::Args, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub(crate) struct InstallConfigOpts {
/// Disable SELinux in the target (installed) system.
///
/// This is currently necessary to install *from* a system with SELinux disabled
/// but where the target does have SELinux enabled.
#[clap(long)]
#[serde(default)]
pub(crate) disable_selinux: bool,
/// Add a kernel argument. This option can be provided multiple times.
///
/// Example: --karg=nosmt --karg=console=ttyS0,115200n8
#[clap(long)]
pub(crate) karg: Option<Vec<CmdlineOwned>>,
/// The path to an `authorized_keys` that will be injected into the `root` account.
///
/// The implementation of this uses systemd `tmpfiles.d`, writing to a file named
/// `/etc/tmpfiles.d/bootc-root-ssh.conf`. This will have the effect that by default,
/// the SSH credentials will be set if not present. The intention behind this
/// is to allow mounting the whole `/root` home directory as a `tmpfs`, while still
/// getting the SSH key replaced on boot.
#[clap(long)]
root_ssh_authorized_keys: Option<Utf8PathBuf>,
/// Perform configuration changes suitable for a "generic" disk image.
/// At the moment:
///
/// - All bootloader types will be installed
/// - Changes to the system firmware will be skipped
#[clap(long)]
#[serde(default)]
pub(crate) generic_image: bool,
/// How should logically bound images be retrieved.
#[clap(long)]
#[serde(default)]
#[arg(default_value_t)]
pub(crate) bound_images: BoundImagesOpt,
/// The stateroot name to use. Defaults to `default`.
#[clap(long)]
pub(crate) stateroot: Option<String>,
/// Don't pass --write-uuid to bootupd during bootloader installation.
#[clap(long)]
#[serde(default)]
pub(crate) bootupd_skip_boot_uuid: bool,
/// The bootloader to use.
#[clap(long)]
#[serde(default)]
pub(crate) bootloader: Option<Bootloader>,
}
#[derive(Debug, Default, Clone, clap::Parser, Serialize, Deserialize, PartialEq, Eq)]
pub(crate) struct InstallComposefsOpts {
/// If true, composefs backend is used, else ostree backend is used
#[clap(long, default_value_t)]
#[serde(default)]
pub(crate) composefs_backend: bool,
/// Make fs-verity validation optional in case the filesystem doesn't support it
#[clap(long, default_value_t, requires = "composefs_backend")]
#[serde(default)]
pub(crate) allow_missing_verity: bool,
/// Name of the UKI addons to install without the ".efi.addon" suffix.
/// This option can be provided multiple times if multiple addons are to be installed.
#[clap(long, requires = "composefs_backend")]
#[serde(default)]
pub(crate) uki_addon: Option<Vec<String>>,
}
#[cfg(feature = "install-to-disk")]
#[derive(Debug, Clone, clap::Parser, Serialize, Deserialize, PartialEq, Eq)]
pub(crate) struct InstallToDiskOpts {
#[clap(flatten)]
#[serde(flatten)]
pub(crate) block_opts: InstallBlockDeviceOpts,
#[clap(flatten)]
#[serde(flatten)]
pub(crate) source_opts: InstallSourceOpts,
#[clap(flatten)]
#[serde(flatten)]
pub(crate) target_opts: InstallTargetOpts,
#[clap(flatten)]
#[serde(flatten)]
pub(crate) config_opts: InstallConfigOpts,
/// Instead of targeting a block device, write to a file via loopback.
#[clap(long)]
#[serde(default)]
pub(crate) via_loopback: bool,
#[clap(flatten)]
#[serde(flatten)]
pub(crate) composefs_opts: InstallComposefsOpts,
}
#[derive(ValueEnum, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum ReplaceMode {
/// Completely wipe the contents of the target filesystem. This cannot
/// be done if the target filesystem is the one the system is booted from.
Wipe,
/// This is a destructive operation in the sense that the bootloader state
/// will have its contents wiped and replaced. However,
/// the running system (and all files) will remain in place until reboot.
///
/// As a corollary to this, you will also need to remove all the old operating
/// system binaries after the reboot into the target system; this can be done
/// with code in the new target system, or manually.
Alongside,
}
impl std::fmt::Display for ReplaceMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_possible_value().unwrap().get_name().fmt(f)
}
}
/// Options for installing to a filesystem
#[derive(Debug, Clone, clap::Args, PartialEq, Eq)]
pub(crate) struct InstallTargetFilesystemOpts {
/// Path to the mounted root filesystem.
///
/// By default, the filesystem UUID will be discovered and used for mounting.
/// To override this, use `--root-mount-spec`.
pub(crate) root_path: Utf8PathBuf,
/// Source device specification for the root filesystem. For example, `UUID=2e9f4241-229b-4202-8429-62d2302382e1`.
/// If not provided, the UUID of the target filesystem will be used. This option is provided
/// as some use cases might prefer to mount by a label instead via e.g. `LABEL=rootfs`.
#[clap(long)]
pub(crate) root_mount_spec: Option<String>,
/// Mount specification for the /boot filesystem.
///
/// This is optional. If `/boot` is detected as a mounted partition, then
/// its UUID will be used.
#[clap(long)]
pub(crate) boot_mount_spec: Option<String>,
/// Initialize the system in-place; at the moment, only one mode for this is implemented.
/// In the future, it may also be supported to set up an explicit "dual boot" system.
#[clap(long)]
pub(crate) replace: Option<ReplaceMode>,
/// If the target is the running system's root filesystem, this will skip any warnings.
#[clap(long)]
pub(crate) acknowledge_destructive: bool,
/// The default mode is to "finalize" the target filesystem by invoking `fstrim` and similar
/// operations, and finally mounting it readonly. This option skips those operations. It
/// is then the responsibility of the invoking code to perform those operations.
#[clap(long)]
pub(crate) skip_finalize: bool,
}
#[derive(Debug, Clone, clap::Parser, PartialEq, Eq)]
pub(crate) struct InstallToFilesystemOpts {
#[clap(flatten)]
pub(crate) filesystem_opts: InstallTargetFilesystemOpts,
#[clap(flatten)]
pub(crate) source_opts: InstallSourceOpts,
#[clap(flatten)]
pub(crate) target_opts: InstallTargetOpts,
#[clap(flatten)]
pub(crate) config_opts: InstallConfigOpts,
#[clap(flatten)]
pub(crate) composefs_opts: InstallComposefsOpts,
}
#[derive(Debug, Clone, clap::Parser, PartialEq, Eq)]
pub(crate) struct InstallToExistingRootOpts {
/// Configure how existing data is treated.
#[clap(long, default_value = "alongside")]
pub(crate) replace: Option<ReplaceMode>,
#[clap(flatten)]
pub(crate) source_opts: InstallSourceOpts,
#[clap(flatten)]
pub(crate) target_opts: InstallTargetOpts,
#[clap(flatten)]
pub(crate) config_opts: InstallConfigOpts,
/// Accept that this is a destructive action and skip a warning timer.
#[clap(long)]
pub(crate) acknowledge_destructive: bool,
/// Add the bootc-destructive-cleanup systemd service to delete files from
/// the previous install on first boot
#[clap(long)]
pub(crate) cleanup: bool,
/// Path to the mounted root; this is now not necessary to provide.
/// Historically it was necessary to ensure the host rootfs was mounted at here
/// via e.g. `-v /:/target`.
#[clap(default_value = ALONGSIDE_ROOT_MOUNT)]
pub(crate) root_path: Utf8PathBuf,
#[clap(flatten)]
pub(crate) composefs_opts: InstallComposefsOpts,
}
#[derive(Debug, clap::Parser, PartialEq, Eq)]
pub(crate) struct InstallResetOpts {
/// Acknowledge that this command is experimental.
#[clap(long)]
pub(crate) experimental: bool,
#[clap(flatten)]
pub(crate) source_opts: InstallSourceOpts,
#[clap(flatten)]
pub(crate) target_opts: InstallTargetOpts,
/// Name of the target stateroot. If not provided, one will be automatically
/// generated of the form `s<year>-<serial>` where `<serial>` starts at zero and
/// increments automatically.
#[clap(long)]
pub(crate) stateroot: Option<String>,
/// Don't display progress
#[clap(long)]
pub(crate) quiet: bool,
#[clap(flatten)]
pub(crate) progress: crate::cli::ProgressOptions,
/// Restart or reboot into the new target image.
///
/// Currently, this option always reboots. In the future this command
/// will detect the case where no kernel changes are queued, and perform
/// a userspace-only restart.
#[clap(long)]
pub(crate) apply: bool,
/// Skip inheriting any automatically discovered root file system kernel arguments.
#[clap(long)]
no_root_kargs: bool,
/// Add a kernel argument. This option can be provided multiple times.
///
/// Example: --karg=nosmt --karg=console=ttyS0,115200n8
#[clap(long)]
karg: Option<Vec<CmdlineOwned>>,
}
#[derive(Debug, clap::Parser, PartialEq, Eq)]
pub(crate) struct InstallPrintConfigurationOpts {
/// Print all configuration.
///
/// Print configuration that is usually handled internally, like kargs.
#[clap(long)]
pub(crate) all: bool,
}
/// Global state captured from the container.
#[derive(Debug, Clone)]
pub(crate) struct SourceInfo {
/// Image reference we'll pull from (today always containers-storage: type)
pub(crate) imageref: ostree_container::ImageReference,
/// The digest to use for pulls
pub(crate) digest: Option<String>,
/// Whether or not SELinux appears to be enabled in the source commit
pub(crate) selinux: bool,
/// Whether the source is available in the host mount namespace
pub(crate) in_host_mountns: bool,
}
// Shared read-only global state
#[derive(Debug)]
pub(crate) struct State {
pub(crate) source: SourceInfo,
/// Force SELinux off in target system
pub(crate) selinux_state: SELinuxFinalState,
#[allow(dead_code)]
pub(crate) config_opts: InstallConfigOpts,
pub(crate) target_opts: InstallTargetOpts,
pub(crate) target_imgref: ostree_container::OstreeImageReference,
#[allow(dead_code)]
pub(crate) prepareroot_config: HashMap<String, String>,
pub(crate) install_config: Option<config::InstallConfiguration>,
/// The parsed contents of the authorized_keys (not the file path)
pub(crate) root_ssh_authorized_keys: Option<String>,
#[allow(dead_code)]
pub(crate) host_is_container: bool,
/// The root filesystem of the running container
pub(crate) container_root: Dir,
pub(crate) tempdir: TempDir,
/// Set if we have determined that composefs is required
#[allow(dead_code)]
pub(crate) composefs_required: bool,
// If Some, then --composefs_native is passed
pub(crate) composefs_options: InstallComposefsOpts,
}
// Shared read-only global state
#[derive(Debug)]
pub(crate) struct PostFetchState {
/// Detected bootloader type for the target system
pub(crate) detected_bootloader: crate::spec::Bootloader,
}
impl InstallTargetOpts {
pub(crate) fn imageref(&self) -> Result<Option<ostree_container::OstreeImageReference>> {
let Some(target_imgname) = self.target_imgref.as_deref() else {
return Ok(None);
};
let target_transport =
ostree_container::Transport::try_from(self.target_transport.as_str())?;
let target_imgref = ostree_container::OstreeImageReference {
sigverify: ostree_container::SignatureSource::ContainerPolicyAllowInsecure,
imgref: ostree_container::ImageReference {
transport: target_transport,
name: target_imgname.to_string(),
},
};
Ok(Some(target_imgref))
}
}
impl State {
#[context("Loading SELinux policy")]
pub(crate) fn load_policy(&self) -> Result<Option<ostree::SePolicy>> {
if !self.selinux_state.enabled() {
return Ok(None);
}
// We always use the physical container root to bootstrap policy
let r = lsm::new_sepolicy_at(&self.container_root)?
.ok_or_else(|| anyhow::anyhow!("SELinux enabled, but no policy found in root"))?;
// SAFETY: Policy must have a checksum here
tracing::debug!("Loaded SELinux policy: {}", r.csum().unwrap());
Ok(Some(r))
}
#[context("Finalizing state")]
#[allow(dead_code)]
pub(crate) fn consume(self) -> Result<()> {
self.tempdir.close()?;
// If we had invoked `setenforce 0`, then let's re-enable it.
if let SELinuxFinalState::Enabled(Some(guard)) = self.selinux_state {
guard.consume()?;
}
Ok(())
}
/// Return an error if kernel arguments are provided, intended to be used for UKI paths
pub(crate) fn require_no_kargs_for_uki(&self) -> Result<()> {
if self
.config_opts
.karg
.as_ref()
.map(|v| !v.is_empty())
.unwrap_or_default()
{
anyhow::bail!("Cannot use externally specified kernel arguments with UKI");
}
Ok(())
}
fn stateroot(&self) -> &str {
// CLI takes precedence over config file
self.config_opts
.stateroot
.as_deref()
.or_else(|| {
self.install_config
.as_ref()
.and_then(|c| c.stateroot.as_deref())
})
.unwrap_or(ostree_ext::container::deploy::STATEROOT_DEFAULT)
}
}
/// A mount specification is a subset of a line in `/etc/fstab`.
///
/// There are 3 (ASCII) whitespace separated values:
///
/// `SOURCE TARGET [OPTIONS]`
///
/// Examples:
/// - /dev/vda3 /boot ext4 ro
/// - /dev/nvme0n1p4 /
/// - /dev/sda2 /var/mnt xfs
#[derive(Debug, Clone)]
pub(crate) struct MountSpec {
pub(crate) source: String,
pub(crate) target: String,
pub(crate) fstype: String,
pub(crate) options: Option<String>,
}
impl MountSpec {
const AUTO: &'static str = "auto";
pub(crate) fn new(src: &str, target: &str) -> Self {
MountSpec {
source: src.to_string(),
target: target.to_string(),
fstype: Self::AUTO.to_string(),
options: None,
}
}
/// Construct a new mount that uses the provided uuid as a source.
pub(crate) fn new_uuid_src(uuid: &str, target: &str) -> Self {
Self::new(&format!("UUID={uuid}"), target)
}
pub(crate) fn get_source_uuid(&self) -> Option<&str> {
if let Some((t, rest)) = self.source.split_once('=') {
if t.eq_ignore_ascii_case("uuid") {
return Some(rest);
}
}
None
}
pub(crate) fn to_fstab(&self) -> String {
let options = self.options.as_deref().unwrap_or("defaults");
format!(
"{} {} {} {} 0 0",
self.source, self.target, self.fstype, options
)
}
/// Append a mount option
pub(crate) fn push_option(&mut self, opt: &str) {
let options = self.options.get_or_insert_with(Default::default);
if !options.is_empty() {
options.push(',');
}
options.push_str(opt);
}
}
impl FromStr for MountSpec {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self> {
let mut parts = s.split_ascii_whitespace().fuse();
let source = parts.next().unwrap_or_default();
if source.is_empty() {
tracing::debug!("Empty mount specification");
return Ok(Self {
source: String::new(),
target: String::new(),
fstype: Self::AUTO.into(),
options: None,
});
}
let target = parts
.next()
.ok_or_else(|| anyhow!("Missing target in mount specification {s}"))?;
let fstype = parts.next().unwrap_or(Self::AUTO);
let options = parts.next().map(ToOwned::to_owned);
Ok(Self {
source: source.to_string(),
fstype: fstype.to_string(),
target: target.to_string(),
options,
})
}
}
impl SourceInfo {
// Inspect container information and convert it to an ostree image reference
// that pulls from containers-storage.
#[context("Gathering source info from container env")]
pub(crate) fn from_container(
root: &Dir,
container_info: &ContainerExecutionInfo,
) -> Result<Self> {
if !container_info.engine.starts_with("podman") {
anyhow::bail!("Currently this command only supports being executed via podman");
}
if container_info.imageid.is_empty() {
anyhow::bail!("Invalid empty imageid");
}
let imageref = ostree_container::ImageReference {
transport: ostree_container::Transport::ContainerStorage,
name: container_info.image.clone(),
};
tracing::debug!("Finding digest for image ID {}", container_info.imageid);
let digest = crate::podman::imageid_to_digest(&container_info.imageid)?;
Self::new(imageref, Some(digest), root, true)
}
#[context("Creating source info from a given imageref")]
pub(crate) fn from_imageref(imageref: &str, root: &Dir) -> Result<Self> {
let imageref = ostree_container::ImageReference::try_from(imageref)?;
Self::new(imageref, None, root, false)
}
fn have_selinux_from_repo(root: &Dir) -> Result<bool> {
let cancellable = ostree::gio::Cancellable::NONE;
let commit = Command::new("ostree")
.args(["--repo=/ostree/repo", "rev-parse", "--single"])
.run_get_string()?;
let repo = ostree::Repo::open_at_dir(root.as_fd(), "ostree/repo")?;
let root = repo
.read_commit(commit.trim(), cancellable)
.context("Reading commit")?
.0;
let root = root.downcast_ref::<ostree::RepoFile>().unwrap();
let xattrs = root.xattrs(cancellable)?;
Ok(crate::lsm::xattrs_have_selinux(&xattrs))
}
/// Construct a new source information structure
fn new(
imageref: ostree_container::ImageReference,
digest: Option<String>,
root: &Dir,
in_host_mountns: bool,
) -> Result<Self> {
let selinux = if Path::new("/ostree/repo").try_exists()? {
Self::have_selinux_from_repo(root)?
} else {
lsm::have_selinux_policy(root)?
};
Ok(Self {
imageref,
digest,
selinux,
in_host_mountns,
})
}
}
pub(crate) fn print_configuration(opts: InstallPrintConfigurationOpts) -> Result<()> {
let mut install_config = config::load_config()?.unwrap_or_default();
if !opts.all {
install_config.filter_to_external();
}
let stdout = std::io::stdout().lock();
anyhow::Ok(install_config.to_canon_json_writer(stdout)?)
}
#[context("Creating ostree deployment")]
async fn initialize_ostree_root(state: &State, root_setup: &RootSetup) -> Result<(Storage, bool)> {
let sepolicy = state.load_policy()?;
let sepolicy = sepolicy.as_ref();
// Load a fd for the mounted target physical root
let rootfs_dir = &root_setup.physical_root;
let cancellable = gio::Cancellable::NONE;
let stateroot = state.stateroot();
let has_ostree = rootfs_dir.try_exists("ostree/repo")?;
if !has_ostree {
Task::new("Initializing ostree layout", "ostree")
.args(["admin", "init-fs", "--modern", "."])
.cwd(rootfs_dir)?
.run()?;
} else {
println!("Reusing extant ostree layout");
let path = ".".into();
let _ = crate::utils::open_dir_remount_rw(rootfs_dir, path)
.context("remounting target as read-write")?;
crate::utils::remove_immutability(rootfs_dir, path)?;
}
// Ensure that the physical root is labeled.
// Another implementation: https://github.com/coreos/coreos-assembler/blob/3cd3307904593b3a131b81567b13a4d0b6fe7c90/src/create_disk.sh#L295
crate::lsm::ensure_dir_labeled(rootfs_dir, "", Some("/".into()), 0o755.into(), sepolicy)?;
// If we're installing alongside existing ostree and there's a separate boot partition,
// we need to mount it to the sysroot's /boot so ostree can write bootloader entries there
if has_ostree && root_setup.boot.is_some() {
if let Some(boot) = &root_setup.boot {
let source_boot = &boot.source;
let target_boot = root_setup.physical_root_path.join(BOOT);
tracing::debug!("Mount {source_boot} to {target_boot} on ostree");
bootc_mount::mount(source_boot, &target_boot)?;
}
}
// And also label /boot AKA xbootldr, if it exists
if rootfs_dir.try_exists("boot")? {
crate::lsm::ensure_dir_labeled(rootfs_dir, "boot", None, 0o755.into(), sepolicy)?;
}
// Build the list of ostree repo config options: defaults + install config
let ostree_opts = state
.install_config
.as_ref()
.and_then(|c| c.ostree.as_ref())
.into_iter()
.flat_map(|o| o.to_config_tuples());
let repo_config: Vec<_> = DEFAULT_REPO_CONFIG
.iter()
.copied()
.chain(ostree_opts)
.collect();
for (k, v) in repo_config.iter() {
Command::new("ostree")
.args(["config", "--repo", "ostree/repo", "set", k, v])
.cwd_dir(rootfs_dir.try_clone()?)
.run_capture_stderr()?;
}
let sysroot = {
let path = format!(
"/proc/{}/fd/{}",
process::id(),
rootfs_dir.as_fd().as_raw_fd()
);
ostree::Sysroot::new(Some(&gio::File::for_path(path)))
};
sysroot.load(cancellable)?;
let repo = &sysroot.repo();
let repo_verity_state = ostree_ext::fsverity::is_verity_enabled(&repo)?;
let prepare_root_composefs = state
.prepareroot_config
.get("composefs.enabled")
.map(|v| ComposefsState::from_str(&v))
.transpose()?
.unwrap_or(ComposefsState::default());
if prepare_root_composefs.requires_fsverity() || repo_verity_state.desired == Tristate::Enabled
{
ostree_ext::fsverity::ensure_verity(repo).await?;
}
if let Some(booted) = sysroot.booted_deployment() {
if stateroot == booted.stateroot() {
anyhow::bail!("Cannot redeploy over booted stateroot {stateroot}");
}
}
let sysroot_dir = crate::utils::sysroot_dir(&sysroot)?;
// init_osname fails when ostree/deploy/{stateroot} already exists
// the stateroot directory can be left over after a failed install attempt,
// so only create it via init_osname if it doesn't exist
// (ideally this would be handled by init_osname)
let stateroot_path = format!("ostree/deploy/{stateroot}");
if !sysroot_dir.try_exists(stateroot_path)? {
sysroot
.init_osname(stateroot, cancellable)
.context("initializing stateroot")?;
}
state.tempdir.create_dir("temp-run")?;
let temp_run = state.tempdir.open_dir("temp-run")?;
// Bootstrap the initial labeling of the /ostree directory as usr_t
// and create the imgstorage with the same labels as /var/lib/containers