-
Notifications
You must be signed in to change notification settings - Fork 193
Expand file tree
/
Copy pathcli.rs
More file actions
2403 lines (2196 loc) · 87.9 KB
/
cli.rs
File metadata and controls
2403 lines (2196 loc) · 87.9 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
//! # Bootable container image CLI
//!
//! Command line tool to manage bootable ostree-based containers.
use std::ffi::{CString, OsStr, OsString};
use std::fs::File;
use std::io::{BufWriter, Seek};
use std::os::fd::AsFd;
use std::os::unix::process::CommandExt;
use std::process::Command;
use anyhow::{Context, Result, anyhow, ensure};
use camino::{Utf8Path, Utf8PathBuf};
use cap_std_ext::cap_std;
use cap_std_ext::cap_std::fs::Dir;
use cfsctl::composefs;
use cfsctl::composefs_boot;
use cfsctl::composefs_oci;
use clap::CommandFactory;
use clap::Parser;
use clap::ValueEnum;
use composefs::dumpfile;
use composefs::fsverity;
use composefs::fsverity::FsVerityHashValue;
use composefs::splitstream::SplitStreamWriter;
use composefs_boot::BootOps as _;
use etc_merge::{compute_diff, print_diff};
use fn_error_context::context;
use indoc::indoc;
use ostree::gio;
use ostree_container::store::PrepareResult;
use ostree_ext::container as ostree_container;
use ostree_ext::keyfileext::KeyFileExt;
use ostree_ext::ostree;
use ostree_ext::sysroot::SysrootLock;
use schemars::schema_for;
use serde::{Deserialize, Serialize};
use crate::bootc_composefs::delete::delete_composefs_deployment;
use crate::bootc_composefs::gc::composefs_gc;
use crate::bootc_composefs::soft_reboot::{prepare_soft_reboot_composefs, reset_soft_reboot};
use crate::bootc_composefs::{
digest::{compute_composefs_digest, new_temp_composefs_repo},
finalize::{composefs_backend_finalize, get_etc_diff},
rollback::composefs_rollback,
state::composefs_usr_overlay,
switch::switch_composefs,
update::upgrade_composefs,
};
use crate::deploy::{MergeState, RequiredHostSpec};
use crate::podstorage::set_additional_image_store;
use crate::progress_jsonl::{ProgressWriter, RawProgressFd};
use crate::spec::FilesystemOverlayAccessMode;
use crate::spec::Host;
use crate::spec::ImageReference;
use crate::status::get_host;
use crate::store::{BootedOstree, Storage};
use crate::store::{BootedStorage, BootedStorageKind};
use crate::utils::sigpolicy_from_opt;
use crate::{bootc_composefs, lints};
/// Shared progress options
#[derive(Debug, Parser, PartialEq, Eq)]
pub(crate) struct ProgressOptions {
/// File descriptor number which must refer to an open pipe.
///
/// Progress is written as JSON lines to this file descriptor.
#[clap(long, hide = true)]
pub(crate) progress_fd: Option<RawProgressFd>,
}
impl TryFrom<ProgressOptions> for ProgressWriter {
type Error = anyhow::Error;
fn try_from(value: ProgressOptions) -> Result<Self> {
let r = value
.progress_fd
.map(TryInto::try_into)
.transpose()?
.unwrap_or_default();
Ok(r)
}
}
/// Perform an upgrade operation
#[derive(Debug, Parser, PartialEq, Eq)]
pub(crate) struct UpgradeOpts {
/// Don't display progress
#[clap(long)]
pub(crate) quiet: bool,
/// Check if an update is available without applying it.
///
/// This only downloads updated metadata, not the full image layers.
#[clap(long, conflicts_with = "apply")]
pub(crate) check: bool,
/// Restart or reboot into the new target image.
///
/// Currently, this always reboots. Future versions may support userspace-only restart.
#[clap(long, conflicts_with = "check")]
pub(crate) apply: bool,
/// Configure soft reboot behavior.
///
/// 'required' fails if soft reboot unavailable, 'auto' falls back to regular reboot.
#[clap(long = "soft-reboot", conflicts_with = "check")]
pub(crate) soft_reboot: Option<SoftRebootMode>,
/// Download and stage the update without applying it.
///
/// Download the update and ensure it's retained on disk for the lifetime of this system boot,
/// but it will not be applied on reboot. If the system is rebooted without applying the update,
/// the image will be eligible for garbage collection again.
#[clap(long, conflicts_with_all = ["check", "apply"])]
pub(crate) download_only: bool,
/// Apply a staged deployment that was previously downloaded with --download-only.
///
/// This unlocks the staged deployment without fetching updates from the container image source.
/// The deployment will be applied on the next shutdown or reboot. Use with --apply to
/// reboot immediately.
#[clap(long, conflicts_with_all = ["check", "download_only"])]
pub(crate) from_downloaded: bool,
/// Upgrade to a different tag of the currently booted image.
///
/// This derives the target image by replacing the tag portion of the current
/// booted image reference.
#[clap(long)]
pub(crate) tag: Option<String>,
#[clap(flatten)]
pub(crate) progress: ProgressOptions,
}
/// Perform an switch operation
#[derive(Debug, Parser, PartialEq, Eq)]
pub(crate) struct SwitchOpts {
/// Don't display progress
#[clap(long)]
pub(crate) quiet: bool,
/// Restart or reboot into the new target image.
///
/// Currently, this always reboots. Future versions may support userspace-only restart.
#[clap(long)]
pub(crate) apply: bool,
/// Configure soft reboot behavior.
///
/// 'required' fails if soft reboot unavailable, 'auto' falls back to regular reboot.
#[clap(long = "soft-reboot")]
pub(crate) soft_reboot: Option<SoftRebootMode>,
/// The transport; e.g. registry, oci, oci-archive, docker-daemon, containers-storage. Defaults to `registry`.
#[clap(long, default_value = "registry")]
pub(crate) transport: String,
/// This argument is deprecated and does nothing.
#[clap(long, hide = true)]
pub(crate) 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)]
pub(crate) enforce_container_sigpolicy: bool,
/// Don't create a new deployment, but directly mutate the booted state.
/// This is hidden because it's not something we generally expect to be done,
/// but this can be used in e.g. Anaconda %post to fixup
#[clap(long, hide = true)]
pub(crate) mutate_in_place: bool,
/// Retain reference to currently booted image
#[clap(long)]
pub(crate) retain: 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)]
pub(crate) unified_storage_exp: bool,
/// Target image to use for the next boot.
pub(crate) target: String,
#[clap(flatten)]
pub(crate) progress: ProgressOptions,
}
/// Options controlling rollback
#[derive(Debug, Parser, PartialEq, Eq)]
pub(crate) struct RollbackOpts {
/// Restart or reboot into the rollback 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,
/// Configure soft reboot behavior.
///
/// 'required' fails if soft reboot unavailable, 'auto' falls back to regular reboot.
#[clap(long = "soft-reboot")]
pub(crate) soft_reboot: Option<SoftRebootMode>,
}
/// Perform an edit operation
#[derive(Debug, Parser, PartialEq, Eq)]
pub(crate) struct EditOpts {
/// Use filename to edit system specification
#[clap(long, short = 'f')]
pub(crate) filename: Option<String>,
/// Don't display progress
#[clap(long)]
pub(crate) quiet: bool,
}
#[derive(Debug, Clone, ValueEnum, PartialEq, Eq)]
#[clap(rename_all = "lowercase")]
pub(crate) enum OutputFormat {
/// Output in Human Readable format.
HumanReadable,
/// Output in YAML format.
Yaml,
/// Output in JSON format.
Json,
}
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
#[clap(rename_all = "lowercase")]
pub(crate) enum SoftRebootMode {
/// Require a soft reboot; fail if not possible
Required,
/// Automatically use soft reboot if possible, otherwise use regular reboot
Auto,
}
/// Perform an status operation
#[derive(Debug, Parser, PartialEq, Eq)]
pub(crate) struct StatusOpts {
/// Output in JSON format.
///
/// Superceded by the `format` option.
#[clap(long, hide = true)]
pub(crate) json: bool,
/// The output format.
#[clap(long)]
pub(crate) format: Option<OutputFormat>,
/// The desired format version. There is currently one supported
/// version, which is exposed as both `0` and `1`. Pass this
/// option to explicitly request it; it is possible that another future
/// version 2 or newer will be supported in the future.
#[clap(long)]
pub(crate) format_version: Option<u32>,
/// Only display status for the booted deployment.
#[clap(long)]
pub(crate) booted: bool,
/// Include additional fields in human readable format.
#[clap(long, short = 'v')]
pub(crate) verbose: bool,
}
/// Add a transient overlayfs on /usr
#[derive(Debug, Parser, PartialEq, Eq)]
pub(crate) struct UsrOverlayOpts {
/// Mount the overlayfs as read-only. A read-only overlayfs is useful since it may be remounted
/// as read/write in a private mount namespace and written to while the mount point remains
/// read-only to the rest of the system.
#[clap(long)]
pub(crate) read_only: bool,
}
#[derive(Debug, clap::Subcommand, PartialEq, Eq)]
pub(crate) enum InstallOpts {
/// Install to the target block device.
///
/// This command must be invoked inside of the container, which will be
/// installed. The container must be run in `--privileged` mode, and hence
/// will be able to see all block devices on the system.
///
/// The default storage layout uses the root filesystem type configured
/// in the container image, alongside any required system partitions such as
/// the EFI system partition. Use `install to-filesystem` for anything more
/// complex such as RAID, LVM, LUKS etc.
#[cfg(feature = "install-to-disk")]
ToDisk(crate::install::InstallToDiskOpts),
/// Install to an externally created filesystem structure.
///
/// In this variant of installation, the root filesystem alongside any necessary
/// platform partitions (such as the EFI system partition) are prepared and mounted by an
/// external tool or script. The root filesystem is currently expected to be empty
/// by default.
ToFilesystem(crate::install::InstallToFilesystemOpts),
/// Install to the host root filesystem.
///
/// This is a variant of `install to-filesystem` that is designed to install "alongside"
/// the running host root filesystem. Currently, the host root filesystem's `/boot` partition
/// will be wiped, but the content of the existing root will otherwise be retained, and will
/// need to be cleaned up if desired when rebooted into the new root.
ToExistingRoot(crate::install::InstallToExistingRootOpts),
/// Nondestructively create a fresh installation state inside an existing bootc system.
///
/// This is a nondestructive variant of `install to-existing-root` that works only inside
/// an existing bootc system.
#[clap(hide = true)]
Reset(crate::install::InstallResetOpts),
/// Execute this as the penultimate step of an installation using `install to-filesystem`.
///
Finalize {
/// Path to the mounted root filesystem.
root_path: Utf8PathBuf,
},
/// Intended for use in environments that are performing an ostree-based installation, not bootc.
///
/// In this scenario the installation may be missing bootc specific features such as
/// kernel arguments, logically bound images and more. This command can be used to attempt
/// to reconcile. At the current time, the only tested environment is Anaconda using `ostreecontainer`
/// and it is recommended to avoid usage outside of that environment. Instead, ensure your
/// code is using `bootc install to-filesystem` from the start.
EnsureCompletion {},
/// Output JSON to stdout that contains the merged installation configuration
/// as it may be relevant to calling processes using `install to-filesystem`
/// that in particular want to discover the desired root filesystem type from the container image.
///
/// At the current time, the only output key is `root-fs-type` which is a string-valued
/// filesystem name suitable for passing to `mkfs.$type`.
PrintConfiguration(crate::install::InstallPrintConfigurationOpts),
}
/// Subcommands which can be executed as part of a container build.
#[derive(Debug, clap::Subcommand, PartialEq, Eq)]
pub(crate) enum ContainerOpts {
/// Output information about the container image.
///
/// By default, a human-readable summary is output. Use --json or --format
/// to change the output format.
Inspect {
/// Operate on the provided rootfs.
#[clap(long, default_value = "/")]
rootfs: Utf8PathBuf,
/// Output in JSON format.
#[clap(long)]
json: bool,
/// The output format.
#[clap(long, conflicts_with = "json")]
format: Option<OutputFormat>,
},
/// Perform relatively inexpensive static analysis checks as part of a container
/// build.
///
/// This is intended to be invoked via e.g. `RUN bootc container lint` as part
/// of a build process; it will error if any problems are detected.
Lint {
/// Operate on the provided rootfs.
#[clap(long, default_value = "/")]
rootfs: Utf8PathBuf,
/// Make warnings fatal.
#[clap(long)]
fatal_warnings: bool,
/// Instead of executing the lints, just print all available lints.
/// At the current time, this will output in YAML format because it's
/// reasonably human friendly. However, there is no commitment to
/// maintaining this exact format; do not parse it via code or scripts.
#[clap(long)]
list: bool,
/// Skip checking the targeted lints, by name. Use `--list` to discover the set
/// of available lints.
///
/// Example: --skip nonempty-boot --skip baseimage-root
#[clap(long)]
skip: Vec<String>,
/// Don't truncate the output. By default, only a limited number of entries are
/// shown for each lint, followed by a count of remaining entries.
#[clap(long)]
no_truncate: bool,
},
/// Output the bootable composefs digest for a directory.
#[clap(hide = true)]
ComputeComposefsDigest {
/// Path to the filesystem root
#[clap(default_value = "/target")]
path: Utf8PathBuf,
/// Additionally generate a dumpfile written to the target path
#[clap(long)]
write_dumpfile_to: Option<Utf8PathBuf>,
},
/// Output the bootable composefs digest from container storage.
#[clap(hide = true)]
ComputeComposefsDigestFromStorage {
/// Additionally generate a dumpfile written to the target path
#[clap(long)]
write_dumpfile_to: Option<Utf8PathBuf>,
/// Identifier for image; if not provided, the running image will be used.
image: Option<String>,
},
/// Build a Unified Kernel Image (UKI) using ukify.
///
/// This command computes the necessary arguments from the container image
/// (kernel, initrd, cmdline, os-release) and invokes ukify with them.
/// Any additional arguments after `--` are passed through to ukify unchanged.
///
/// Example:
/// bootc container ukify --rootfs /target -- --output /output/uki.efi
Ukify {
/// Operate on the provided rootfs.
#[clap(long, default_value = "/")]
rootfs: Utf8PathBuf,
/// Additional kernel arguments to append to the cmdline.
/// Can be specified multiple times.
/// This is a temporary workaround and will be removed.
#[clap(long = "karg", hide = true)]
kargs: Vec<String>,
/// Make fs-verity validation optional in case the filesystem doesn't support it
#[clap(long)]
allow_missing_verity: bool,
/// Additional arguments to pass to ukify (after `--`).
#[clap(last = true)]
args: Vec<OsString>,
},
/// Export container filesystem as a tar archive.
///
/// This command exports the container filesystem in a bootable format with proper
/// SELinux labeling. The output is written to stdout by default or to a specified file.
///
/// Example:
/// bootc container export /target > output.tar
#[clap(hide = true)]
Export {
/// Format for export output
#[clap(long, default_value = "tar")]
format: ExportFormat,
/// Output file (defaults to stdout)
#[clap(long, short = 'o')]
output: Option<Utf8PathBuf>,
/// Copy kernel and initramfs from /usr/lib/modules to /boot for legacy compatibility.
/// This is useful for installers that expect the kernel in /boot.
#[clap(long)]
kernel_in_boot: bool,
/// Disable SELinux labeling in the exported archive.
#[clap(long)]
disable_selinux: bool,
/// Path to the container filesystem root
target: Utf8PathBuf,
},
}
#[derive(Debug, Clone, ValueEnum, PartialEq, Eq)]
pub(crate) enum ExportFormat {
/// Export as tar archive
Tar,
}
/// Subcommands which operate on images.
#[derive(Debug, clap::Subcommand, PartialEq, Eq)]
pub(crate) enum ImageCmdOpts {
/// Wrapper for `podman image list` in bootc storage.
List {
#[clap(allow_hyphen_values = true)]
args: Vec<OsString>,
},
/// Wrapper for `podman image build` in bootc storage.
Build {
#[clap(allow_hyphen_values = true)]
args: Vec<OsString>,
},
/// Wrapper for `podman image pull` in bootc storage.
Pull {
#[clap(allow_hyphen_values = true)]
args: Vec<OsString>,
},
/// Wrapper for `podman image push` in bootc storage.
Push {
#[clap(allow_hyphen_values = true)]
args: Vec<OsString>,
},
}
#[derive(ValueEnum, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum ImageListType {
/// List all images
#[default]
All,
/// List only logically bound images
Logical,
/// List only host images
Host,
}
impl std::fmt::Display for ImageListType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_possible_value().unwrap().get_name().fmt(f)
}
}
#[derive(ValueEnum, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum ImageListFormat {
/// Human readable table format
#[default]
Table,
/// JSON format
Json,
}
impl std::fmt::Display for ImageListFormat {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_possible_value().unwrap().get_name().fmt(f)
}
}
/// Subcommands which operate on images.
#[derive(Debug, clap::Subcommand, PartialEq, Eq)]
pub(crate) enum ImageOpts {
/// List fetched images stored in the bootc storage.
///
/// Note that these are distinct from images stored via e.g. `podman`.
List {
/// Type of image to list
#[clap(long = "type")]
#[arg(default_value_t)]
list_type: ImageListType,
#[clap(long = "format")]
#[arg(default_value_t)]
list_format: ImageListFormat,
},
/// Copy a container image from the bootc storage to `containers-storage:`.
///
/// The source and target are both optional; if both are left unspecified,
/// via a simple invocation of `bootc image copy-to-storage`, then the default is to
/// push the currently booted image to `containers-storage` (as used by podman, etc.)
/// and tagged with the image name `localhost/bootc`,
///
/// ## Copying a non-default container image
///
/// It is also possible to copy an image other than the currently booted one by
/// specifying `--source`.
///
/// ## Pulling images
///
/// At the current time there is no explicit support for pulling images other than indirectly
/// via e.g. `bootc switch` or `bootc upgrade`.
CopyToStorage {
#[clap(long)]
/// The source image; if not specified, the booted image will be used.
source: Option<String>,
#[clap(long)]
/// The destination; if not specified, then the default is to push to `containers-storage:localhost/bootc`;
/// this will make the image accessible via e.g. `podman run localhost/bootc` and for builds.
target: Option<String>,
},
/// Re-pull the currently booted image into the bootc-owned container storage.
///
/// This onboards the system to the unified storage path so that future
/// upgrade/switch operations can read from the bootc storage directly.
SetUnified,
/// Copy a container image from the default `containers-storage:` to the bootc-owned container storage.
PullFromDefaultStorage {
/// The image to pull
image: String,
},
/// Wrapper for selected `podman image` subcommands in bootc storage.
#[clap(subcommand)]
Cmd(ImageCmdOpts),
}
#[derive(Debug, Clone, clap::ValueEnum, PartialEq, Eq)]
pub(crate) enum SchemaType {
Host,
Progress,
}
/// Options for consistency checking
#[derive(Debug, clap::Subcommand, PartialEq, Eq)]
pub(crate) enum FsverityOpts {
/// Measure the fsverity digest of the target file.
Measure {
/// Path to file
path: Utf8PathBuf,
},
/// Enable fsverity on the target file.
Enable {
/// Ptah to file
path: Utf8PathBuf,
},
}
/// Hidden, internal only options
#[derive(Debug, clap::Subcommand, PartialEq, Eq)]
pub(crate) enum InternalsOpts {
SystemdGenerator {
normal_dir: Utf8PathBuf,
#[allow(dead_code)]
early_dir: Option<Utf8PathBuf>,
#[allow(dead_code)]
late_dir: Option<Utf8PathBuf>,
},
FixupEtcFstab,
/// Should only be used by `make update-generated`
PrintJsonSchema {
#[clap(long)]
of: SchemaType,
},
#[clap(subcommand)]
Fsverity(FsverityOpts),
/// Perform consistency checking.
Fsck,
/// Perform cleanup actions
Cleanup,
Relabel {
#[clap(long)]
/// Relabel using this path as root
as_path: Option<Utf8PathBuf>,
/// Relabel this path
path: Utf8PathBuf,
},
/// Proxy frontend for the `ostree-ext` CLI.
OstreeExt {
#[clap(allow_hyphen_values = true)]
args: Vec<OsString>,
},
/// Proxy frontend for the `cfsctl` CLI
Cfs {
#[clap(allow_hyphen_values = true)]
args: Vec<OsString>,
},
/// Proxy frontend for the legacy `ostree container` CLI.
OstreeContainer {
#[clap(allow_hyphen_values = true)]
args: Vec<OsString>,
},
/// Ensure that a composefs repository is initialized
TestComposefs,
/// Loopback device cleanup helper (internal use only)
LoopbackCleanupHelper {
/// Device path to clean up
#[clap(long)]
device: String,
},
/// Test loopback device allocation and cleanup (internal use only)
AllocateCleanupLoopback {
/// File path to create loopback device for
#[clap(long)]
file_path: Utf8PathBuf,
},
/// Invoked from ostree-ext to complete an installation.
BootcInstallCompletion {
/// Path to the sysroot
sysroot: Utf8PathBuf,
// The stateroot
stateroot: String,
},
/// Initiate a reboot the same way we would after --apply; intended
/// primarily for testing.
Reboot,
#[cfg(feature = "rhsm")]
/// Publish subscription-manager facts to /etc/rhsm/facts/bootc.facts
PublishRhsmFacts,
/// Internal command for testing etc-diff/etc-merge
DirDiff {
/// Directory path to the pristine_etc
pristine_etc: Utf8PathBuf,
/// Directory path to the current_etc
current_etc: Utf8PathBuf,
/// Directory path to the new_etc
new_etc: Utf8PathBuf,
/// Whether to perform the three way merge or not
#[clap(long)]
merge: bool,
},
#[cfg(feature = "docgen")]
/// Dump CLI structure as JSON for documentation generation
DumpCliJson,
PrepSoftReboot {
#[clap(required_unless_present = "reset")]
deployment: Option<String>,
#[clap(long, conflicts_with = "reset")]
reboot: bool,
#[clap(long, conflicts_with = "reboot")]
reset: bool,
},
ComposefsGC {
#[clap(long)]
dry_run: bool,
},
}
#[derive(Debug, clap::Subcommand, PartialEq, Eq)]
pub(crate) enum StateOpts {
/// Remove all ostree deployments from this system
WipeOstree,
}
impl InternalsOpts {
/// The name of the binary we inject into /usr/lib/systemd/system-generators
const GENERATOR_BIN: &'static str = "bootc-systemd-generator";
}
/// Deploy and transactionally in-place with bootable container images.
///
/// The `bootc` project currently uses ostree-containers as a backend
/// to support a model of bootable container images. Once installed,
/// whether directly via `bootc install` (executed as part of a container)
/// or via another mechanism such as an OS installer tool, further
/// updates can be pulled and `bootc upgrade`.
#[derive(Debug, Parser, PartialEq, Eq)]
#[clap(name = "bootc")]
#[clap(rename_all = "kebab-case")]
#[clap(version,long_version=clap::crate_version!())]
#[allow(clippy::large_enum_variant)]
pub(crate) enum Opt {
/// Download and queue an updated container image to apply.
///
/// This does not affect the running system; updates operate in an "A/B" style by default.
///
/// A queued update is visible as `staged` in `bootc status`.
///
/// Currently by default, the update will be applied at shutdown time via `ostree-finalize-staged.service`.
/// There is also an explicit `bootc upgrade --apply` verb which will automatically take action (rebooting)
/// if the system has changed.
///
/// However, in the future this is likely to change such that reboots outside of a `bootc upgrade --apply`
/// do *not* automatically apply the update in addition.
#[clap(alias = "update")]
Upgrade(UpgradeOpts),
/// Target a new container image reference to boot.
///
/// This is almost exactly the same operation as `upgrade`, but additionally changes the container image reference
/// instead.
///
/// ## Usage
///
/// A common pattern is to have a management agent control operating system updates via container image tags;
/// for example, `quay.io/exampleos/someuser:v1.0` and `quay.io/exampleos/someuser:v1.1` where some machines
/// are tracking `:v1.0`, and as a rollout progresses, machines can be switched to `v:1.1`.
Switch(SwitchOpts),
/// Change the bootloader entry ordering; the deployment under `rollback` will be queued for the next boot,
/// and the current will become rollback. If there is a `staged` entry (an unapplied, queued upgrade)
/// then it will be discarded.
///
/// Note that absent any additional control logic, if there is an active agent doing automated upgrades
/// (such as the default `bootc-fetch-apply-updates.timer` and associated `.service`) the
/// change here may be reverted. It's recommended to only use this in concert with an agent that
/// is in active control.
///
/// A systemd journal message will be logged with `MESSAGE_ID=26f3b1eb24464d12aa5e7b544a6b5468` in
/// order to detect a rollback invocation.
#[command(after_help = indoc! {r#"
Note on Rollbacks and the `/etc` Directory:
When you perform a rollback (e.g., with `bootc rollback`), any
changes made to files in the `/etc` directory won't carry over
to the rolled-back deployment. The `/etc` files will revert
to their state from that previous deployment instead.
This is because `bootc rollback` just reorders the existing
deployments. It doesn't create new deployments. The `/etc`
merges happen when new deployments are created.
"#})]
Rollback(RollbackOpts),
/// Apply full changes to the host specification.
///
/// This command operates very similarly to `kubectl apply`; if invoked interactively,
/// then the current host specification will be presented in the system default `$EDITOR`
/// for interactive changes.
///
/// It is also possible to directly provide new contents via `bootc edit --filename`.
///
/// Only changes to the `spec` section are honored.
Edit(EditOpts),
/// Display status.
///
/// Shows bootc system state. Outputs YAML by default, human-readable if terminal detected.
Status(StatusOpts),
/// Add a transient overlayfs on `/usr`.
///
/// Allows temporary package installation that will be discarded on reboot.
#[clap(alias = "usroverlay")]
UsrOverlay(UsrOverlayOpts),
/// Install the running container to a target.
///
/// Takes a container image and installs it to disk in a bootable format.
#[clap(subcommand)]
Install(InstallOpts),
/// Operations which can be executed as part of a container build.
#[clap(subcommand)]
Container(ContainerOpts),
/// Operations on container images.
///
/// Stability: This interface may change in the future.
#[clap(subcommand, hide = true)]
Image(ImageOpts),
/// Execute the given command in the host mount namespace
#[clap(hide = true)]
ExecInHostMountNamespace {
#[clap(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<OsString>,
},
/// Modify the state of the system
#[clap(hide = true)]
#[clap(subcommand)]
State(StateOpts),
#[clap(subcommand)]
#[clap(hide = true)]
Internals(InternalsOpts),
ComposefsFinalizeStaged,
/// Diff current /etc configuration versus default
#[clap(hide = true)]
ConfigDiff,
/// Generate shell completion script for supported shells.
///
/// Example: `bootc completion bash` prints a bash completion script to stdout.
#[clap(hide = true)]
Completion {
/// Shell type to generate (bash, zsh, fish)
#[clap(value_enum)]
shell: clap_complete::aot::Shell,
},
#[clap(hide = true)]
DeleteDeployment {
depl_id: String,
},
}
/// Ensure we've entered a mount namespace, so that we can remount
/// `/sysroot` read-write
/// TODO use <https://github.com/ostreedev/ostree/pull/2779> once
/// we can depend on a new enough ostree
#[context("Ensuring mountns")]
pub(crate) fn ensure_self_unshared_mount_namespace() -> Result<()> {
let uid = rustix::process::getuid();
if !uid.is_root() {
tracing::debug!("Not root, assuming no need to unshare");
return Ok(());
}
let recurse_env = "_ostree_unshared";
let ns_pid1 = std::fs::read_link("/proc/1/ns/mnt").context("Reading /proc/1/ns/mnt")?;
let ns_self = std::fs::read_link("/proc/self/ns/mnt").context("Reading /proc/self/ns/mnt")?;
// If we already appear to be in a mount namespace, or we're already pid1, we're done
if ns_pid1 != ns_self {
tracing::debug!("Already in a mount namespace");
return Ok(());
}
if std::env::var_os(recurse_env).is_some() {
let am_pid1 = rustix::process::getpid().is_init();
if am_pid1 {
tracing::debug!("We are pid 1");
return Ok(());
} else {
anyhow::bail!("Failed to unshare mount namespace");
}
}
bootc_utils::reexec::reexec_with_guardenv(recurse_env, &["unshare", "-m", "--"])
}
/// Load global storage state, expecting that we're booted into a bootc system.
/// This prepares the process for write operations (re-exec, mount namespace, etc).
#[context("Initializing storage")]
pub(crate) async fn get_storage() -> Result<crate::store::BootedStorage> {
let env = crate::store::Environment::detect()?;
// Always call prepare_for_write() for write operations - it checks
// for container, root privileges, mount namespace setup, etc.
prepare_for_write()?;
let r = BootedStorage::new(env)
.await?
.ok_or_else(|| anyhow!("System not booted via bootc"))?;
Ok(r)
}
#[context("Querying root privilege")]
pub(crate) fn require_root(is_container: bool) -> Result<()> {
ensure!(
rustix::process::getuid().is_root(),
if is_container {
"The user inside the container from which you are running this command must be root"
} else {
"This command must be executed as the root user"
}
);
ensure!(
rustix::thread::capability_is_in_bounding_set(rustix::thread::CapabilitySet::SYS_ADMIN)?,
if is_container {
"The container must be executed with full privileges (e.g. --privileged flag)"
} else {
"This command requires full root privileges (CAP_SYS_ADMIN)"
}
);
tracing::trace!("Verified uid 0 with CAP_SYS_ADMIN");
Ok(())
}
/// Check if a deployment has soft reboot capability
fn has_soft_reboot_capability(deployment: Option<&crate::spec::BootEntry>) -> bool {
deployment.map(|d| d.soft_reboot_capable).unwrap_or(false)
}
/// Prepare a soft reboot for the given deployment
#[context("Preparing soft reboot")]
fn prepare_soft_reboot(sysroot: &SysrootLock, deployment: &ostree::Deployment) -> Result<()> {
let cancellable = ostree::gio::Cancellable::NONE;
sysroot
.deployment_set_soft_reboot(deployment, false, cancellable)
.context("Failed to prepare soft-reboot")?;
Ok(())
}
/// Handle soft reboot based on the configured mode
#[context("Handling soft reboot")]
fn handle_soft_reboot<F>(
soft_reboot_mode: Option<SoftRebootMode>,
entry: Option<&crate::spec::BootEntry>,
deployment_type: &str,
execute_soft_reboot: F,
) -> Result<()>
where
F: FnOnce() -> Result<()>,
{
let Some(mode) = soft_reboot_mode else {
return Ok(());
};
let can_soft_reboot = has_soft_reboot_capability(entry);
match mode {
SoftRebootMode::Required => {
if can_soft_reboot {
execute_soft_reboot()?;
} else {
anyhow::bail!(
"Soft reboot was required but {} deployment is not soft-reboot capable",
deployment_type
);
}
}
SoftRebootMode::Auto => {
if can_soft_reboot {
execute_soft_reboot()?;
}
}
}
Ok(())
}
/// Handle soft reboot for staged deployments (used by upgrade and switch)
#[context("Handling staged soft reboot")]
fn handle_staged_soft_reboot(
booted_ostree: &BootedOstree<'_>,
soft_reboot_mode: Option<SoftRebootMode>,
host: &crate::spec::Host,
) -> Result<()> {
handle_soft_reboot(
soft_reboot_mode,
host.status.staged.as_ref(),
"staged",
|| soft_reboot_staged(booted_ostree.sysroot),
)
}
/// Perform a soft reboot for a staged deployment
#[context("Soft reboot staged deployment")]
fn soft_reboot_staged(sysroot: &SysrootLock) -> Result<()> {
println!("Staged deployment is soft-reboot capable, preparing for soft-reboot...");
let deployments_list = sysroot.deployments();
let staged_deployment = deployments_list
.iter()
.find(|d| d.is_staged())