-
Notifications
You must be signed in to change notification settings - Fork 219
Expand file tree
/
Copy pathstatus.rs
More file actions
1371 lines (1238 loc) · 47.1 KB
/
Copy pathstatus.rs
File metadata and controls
1371 lines (1238 loc) · 47.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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::borrow::Cow;
use std::collections::VecDeque;
use std::io::IsTerminal;
use std::io::Read;
use std::io::Write;
use anyhow::{Context, Result};
use canon_json::CanonJsonSerialize;
use fn_error_context::context;
use ostree::glib;
use ostree_container::OstreeImageReference;
use ostree_ext::container as ostree_container;
use ostree_ext::keyfileext::KeyFileExt;
use ostree_ext::oci_spec;
use ostree_ext::oci_spec::image::Digest;
use ostree_ext::oci_spec::image::ImageConfiguration;
use ostree_ext::sysroot::SysrootLock;
use unicode_width::UnicodeWidthStr;
use ostree_ext::ostree;
use crate::cli::OutputFormat;
use crate::spec::BootEntryComposefs;
use crate::spec::ImageStatus;
use crate::spec::{BootEntry, BootOrder, Host, HostSpec, HostStatus, HostType};
use crate::spec::{ImageReference, ImageSignature};
use crate::store::BootedStorage;
use crate::store::BootedStorageKind;
use crate::store::CachedImageStatus;
impl From<ostree_container::SignatureSource> for ImageSignature {
fn from(sig: ostree_container::SignatureSource) -> Self {
use ostree_container::SignatureSource;
match sig {
SignatureSource::OstreeRemote(r) => Self::OstreeRemote(r),
SignatureSource::ContainerPolicy => Self::ContainerPolicy,
SignatureSource::ContainerPolicyAllowInsecure => Self::Insecure,
}
}
}
impl From<ImageSignature> for ostree_container::SignatureSource {
fn from(sig: ImageSignature) -> Self {
use ostree_container::SignatureSource;
match sig {
ImageSignature::OstreeRemote(r) => SignatureSource::OstreeRemote(r),
ImageSignature::ContainerPolicy => Self::ContainerPolicy,
ImageSignature::Insecure => Self::ContainerPolicyAllowInsecure,
}
}
}
/// Fixme lower serializability into ostree-ext
fn transport_to_string(transport: ostree_container::Transport) -> String {
match transport {
// Canonicalize to registry for our own use
ostree_container::Transport::Registry => "registry".to_string(),
o => {
let mut s = o.to_string();
s.truncate(s.rfind(':').unwrap());
s
}
}
}
impl From<OstreeImageReference> for ImageReference {
fn from(imgref: OstreeImageReference) -> Self {
let signature = match imgref.sigverify {
ostree_container::SignatureSource::ContainerPolicyAllowInsecure => None,
v => Some(v.into()),
};
Self {
signature,
transport: transport_to_string(imgref.imgref.transport),
image: imgref.imgref.name,
}
}
}
impl From<ImageReference> for OstreeImageReference {
fn from(img: ImageReference) -> Self {
let sigverify = match img.signature {
Some(v) => v.into(),
None => ostree_container::SignatureSource::ContainerPolicyAllowInsecure,
};
Self {
sigverify,
imgref: ostree_container::ImageReference {
// SAFETY: We validated the schema in kube-rs
transport: img.transport.as_str().try_into().unwrap(),
name: img.image,
},
}
}
}
/// Check if SELinux policies are compatible between booted and target deployments.
/// Returns false if SELinux is enabled and the policies differ or have mismatched presence.
fn check_selinux_policy_compatible(
sysroot: &SysrootLock,
booted_deployment: &ostree::Deployment,
target_deployment: &ostree::Deployment,
) -> Result<bool> {
// Only check if SELinux is enabled
if !crate::lsm::selinux_enabled()? {
return Ok(true);
}
let booted_fd = crate::utils::deployment_fd(sysroot, booted_deployment)
.context("Failed to get file descriptor for booted deployment")?;
let booted_policy = crate::lsm::new_sepolicy_at(&booted_fd)
.context("Failed to load SELinux policy from booted deployment")?;
let target_fd = crate::utils::deployment_fd(sysroot, target_deployment)
.context("Failed to get file descriptor for target deployment")?;
let target_policy = crate::lsm::new_sepolicy_at(&target_fd)
.context("Failed to load SELinux policy from target deployment")?;
let booted_csum = booted_policy.and_then(|p| p.csum());
let target_csum = target_policy.and_then(|p| p.csum());
match (booted_csum, target_csum) {
(None, None) => Ok(true), // Both absent, compatible
(Some(_), None) | (None, Some(_)) => {
// Incompatible: one has policy, other doesn't
Ok(false)
}
(Some(booted_csum), Some(target_csum)) => {
// Both have policies, checksums must match
Ok(booted_csum == target_csum)
}
}
}
/// Check if a deployment has soft reboot capability
// TODO: Lower SELinux policy check into ostree's deployment_can_soft_reboot API
fn has_soft_reboot_capability(sysroot: &SysrootLock, deployment: &ostree::Deployment) -> bool {
if !ostree_ext::systemd_has_soft_reboot() {
return false;
}
// When the ostree version is < 2025.7 and the deployment is
// missing the ostree= karg (happens during a factory reset),
// there is a bug that causes deployment_can_soft_reboot to crash.
// So in this case default to disabling soft reboot.
let has_ostree_karg = deployment
.bootconfig()
.and_then(|bootcfg| bootcfg.get("options"))
.map(|options| options.contains("ostree="))
.unwrap_or(false);
if !ostree::check_version(2025, 7) && !has_ostree_karg {
return false;
}
if !sysroot.deployment_can_soft_reboot(deployment) {
return false;
}
// Check SELinux policy compatibility with booted deployment
// Block soft reboot if SELinux policies differ, as policy is not reloaded across soft reboots
if let Some(booted_deployment) = sysroot.booted_deployment() {
// deployment_fd should not fail for valid deployments
if !check_selinux_policy_compatible(sysroot, &booted_deployment, deployment)
.expect("deployment_fd should not fail for valid deployments")
{
return false;
}
}
true
}
/// Parse an ostree origin file (a keyfile) and extract the targeted
/// container image reference.
fn get_image_origin(origin: &glib::KeyFile) -> Result<Option<OstreeImageReference>> {
origin
.optional_string("origin", ostree_container::deploy::ORIGIN_CONTAINER)
.context("Failed to load container image from origin")?
.map(|v| ostree_container::OstreeImageReference::try_from(v.as_str()))
.transpose()
}
pub(crate) struct Deployments {
pub(crate) staged: Option<ostree::Deployment>,
pub(crate) rollback: Option<ostree::Deployment>,
#[allow(dead_code)]
pub(crate) other: VecDeque<ostree::Deployment>,
}
pub(crate) fn labels_of_config(
config: &oci_spec::image::ImageConfiguration,
) -> Option<&std::collections::HashMap<String, String>> {
config.config().as_ref().and_then(|c| c.labels().as_ref())
}
/// Convert between a subset of ostree-ext metadata and the exposed spec API.
fn create_imagestatus(
image: ImageReference,
manifest_digest: &Digest,
config: &ImageConfiguration,
) -> ImageStatus {
let labels = labels_of_config(config);
let timestamp = labels
.and_then(|l| {
l.get(oci_spec::image::ANNOTATION_CREATED)
.map(|s| s.as_str())
})
.or_else(|| config.created().as_deref())
.and_then(bootc_utils::try_deserialize_timestamp);
let version = ostree_container::version_for_config(config).map(ToOwned::to_owned);
let architecture = config.architecture().to_string();
ImageStatus {
image,
version,
timestamp,
image_digest: manifest_digest.to_string(),
architecture,
}
}
fn imagestatus(
sysroot: &SysrootLock,
deployment: &ostree::Deployment,
image: ostree_container::OstreeImageReference,
) -> Result<CachedImageStatus> {
let repo = &sysroot.repo();
let imgstate = ostree_container::store::query_image_commit(repo, &deployment.csum())?;
let image = ImageReference::from(image);
let cached = imgstate
.cached_update
.map(|cached| create_imagestatus(image.clone(), &cached.manifest_digest, &cached.config));
let imagestatus = create_imagestatus(image, &imgstate.manifest_digest, &imgstate.configuration);
Ok(CachedImageStatus {
image: Some(imagestatus),
cached_update: cached,
})
}
/// Given an OSTree deployment, parse out metadata into our spec.
#[context("Reading deployment metadata")]
pub(crate) fn boot_entry_from_deployment(
sysroot: &SysrootLock,
deployment: &ostree::Deployment,
) -> Result<BootEntry> {
let (
CachedImageStatus {
image,
cached_update,
},
incompatible,
) = if let Some(origin) = deployment.origin().as_ref() {
let incompatible = crate::utils::origin_has_rpmostree_stuff(origin);
let cached_imagestatus = if incompatible {
// If there are local changes, we can't represent it as a bootc compatible image.
CachedImageStatus::default()
} else if let Some(image) = get_image_origin(origin)? {
imagestatus(sysroot, deployment, image)?
} else {
// The deployment isn't using a container image
CachedImageStatus::default()
};
(cached_imagestatus, incompatible)
} else {
// The deployment has no origin at all (this generally shouldn't happen)
(CachedImageStatus::default(), false)
};
let soft_reboot_capable = has_soft_reboot_capability(sysroot, deployment);
let download_only = deployment.is_staged() && deployment.is_finalization_locked();
let store = Some(crate::spec::Store::OstreeContainer);
let r = BootEntry {
image,
cached_update,
incompatible,
soft_reboot_capable,
download_only,
store,
pinned: deployment.is_pinned(),
ostree: Some(crate::spec::BootEntryOstree {
checksum: deployment.csum().into(),
// SAFETY: The deployserial is really unsigned
deploy_serial: deployment.deployserial().try_into().unwrap(),
stateroot: deployment.stateroot().into(),
}),
composefs: None,
};
Ok(r)
}
impl BootEntry {
/// Given a boot entry, find its underlying ostree container image
pub(crate) fn query_image(
&self,
repo: &ostree::Repo,
) -> Result<Option<Box<ostree_container::store::LayeredImageState>>> {
if self.image.is_none() {
return Ok(None);
}
if let Some(checksum) = self.ostree.as_ref().map(|c| c.checksum.as_str()) {
ostree_container::store::query_image_commit(repo, checksum).map(Some)
} else {
Ok(None)
}
}
pub(crate) fn require_composefs(&self) -> Result<&BootEntryComposefs> {
self.composefs.as_ref().ok_or(anyhow::anyhow!(
"BootEntry is not a composefs native boot entry"
))
}
/// Get the boot digest for this deployment
/// This is the
/// - SHA256SUM of kernel + initrd for Type1 booted deployments
/// - SHA256SUM of UKI for Type2 booted deployments
pub(crate) fn composefs_boot_digest(&self) -> Result<&String> {
self.require_composefs()?
.boot_digest
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Could not find boot digest for deployment"))
}
}
/// A variant of [`get_status`] that requires a booted deployment.
pub(crate) fn get_status_require_booted(
sysroot: &SysrootLock,
) -> Result<(crate::store::BootedOstree<'_>, Deployments, Host)> {
let booted_deployment = sysroot.require_booted_deployment()?;
let booted_ostree = crate::store::BootedOstree {
sysroot,
deployment: booted_deployment,
};
let (deployments, host) = get_status(&booted_ostree)?;
Ok((booted_ostree, deployments, host))
}
/// Gather the ostree deployment objects, but also extract metadata from them into
/// a more native Rust structure.
#[context("Computing status")]
pub(crate) fn get_status(
booted_ostree: &crate::store::BootedOstree<'_>,
) -> Result<(Deployments, Host)> {
let sysroot = booted_ostree.sysroot;
let booted_deployment = Some(&booted_ostree.deployment);
let stateroot = booted_deployment.as_ref().map(|d| d.osname());
let (mut related_deployments, other_deployments) = sysroot
.deployments()
.into_iter()
.partition::<VecDeque<_>, _>(|d| Some(d.osname()) == stateroot);
let staged = related_deployments
.iter()
.position(|d| d.is_staged())
.map(|i| related_deployments.remove(i).unwrap());
tracing::debug!("Staged: {staged:?}");
// Filter out the booted, the caller already found that
if let Some(booted) = booted_deployment.as_ref() {
related_deployments.retain(|f| !f.equal(booted));
}
let rollback = related_deployments.pop_front();
let rollback_queued = match (booted_deployment.as_ref(), rollback.as_ref()) {
(Some(booted), Some(rollback)) => rollback.index() < booted.index(),
_ => false,
};
let boot_order = if rollback_queued {
BootOrder::Rollback
} else {
BootOrder::Default
};
tracing::debug!("Rollback queued={rollback_queued:?}");
let other = {
related_deployments.extend(other_deployments);
related_deployments
};
let deployments = Deployments {
staged,
rollback,
other,
};
let staged = deployments
.staged
.as_ref()
.map(|d| boot_entry_from_deployment(sysroot, d))
.transpose()
.context("Staged deployment")?;
let booted = booted_deployment
.as_ref()
.map(|d| boot_entry_from_deployment(sysroot, d))
.transpose()
.context("Booted deployment")?;
let rollback = deployments
.rollback
.as_ref()
.map(|d| boot_entry_from_deployment(sysroot, d))
.transpose()
.context("Rollback deployment")?;
let other_deployments = deployments
.other
.iter()
.map(|d| boot_entry_from_deployment(sysroot, d))
.collect::<Result<Vec<_>>>()
.context("Other deployments")?;
let spec = staged
.as_ref()
.or(booted.as_ref())
.and_then(|entry| entry.image.as_ref())
.map(|img| HostSpec {
image: Some(img.image.clone()),
boot_order,
})
.unwrap_or_default();
let ty = if booted
.as_ref()
.map(|b| b.image.is_some())
.unwrap_or_default()
{
// We're only of type BootcHost if we booted via container image
Some(HostType::BootcHost)
} else {
None
};
let usr_overlay = booted_deployment
.as_ref()
.map(|d| d.unlocked())
.and_then(crate::spec::deployment_unlocked_state_to_usr_overlay);
let mut host = Host::new(spec);
host.status = HostStatus {
staged,
booted,
rollback,
other_deployments,
rollback_queued,
ty,
usr_overlay,
// Set by callers that have storage context (e.g. get_host).
read_only: false,
};
Ok((deployments, host))
}
pub(crate) async fn get_host() -> Result<Host> {
let env = crate::store::Environment::detect()?;
if env.needs_mount_namespace() {
crate::cli::prepare_for_write()?;
}
let Some(storage) = BootedStorage::new(env).await? else {
// If we're not booted, then return a default.
return Ok(Host::default());
};
let mut host = match storage.kind() {
Ok(kind) => match kind {
BootedStorageKind::Ostree(booted_ostree) => {
let (_deployments, host) = get_status(&booted_ostree)?;
host
}
BootedStorageKind::Composefs(booted_cfs) => {
crate::bootc_composefs::status::get_composefs_status(&storage, &booted_cfs).await?
}
},
Err(_) => {
// If determining storage kind fails (e.g., no booted deployment),
// return a default host indicating the system is not deployed via bootc
Host::default()
}
};
// Surface whether the physical root is on a read-only medium (e.g. a live
// ISO), so consumers know mutating operations are unavailable.
host.status.read_only = storage.is_ro;
Ok(host)
}
/// Implementation of the `bootc status` CLI command.
#[context("Status")]
pub(crate) async fn status(opts: super::cli::StatusOpts) -> Result<()> {
match opts.format_version.unwrap_or_default() {
// For historical reasons, both 0 and 1 mean "v1".
0 | 1 => {}
o => anyhow::bail!("Unsupported format version: {o}"),
};
let mut host = get_host().await?;
// We could support querying the staged or rollback deployments
// here too, but it's not a common use case at the moment.
if opts.booted {
host.filter_to_slot(Slot::Booted);
}
// If we're in JSON mode, then convert the ostree data into Rust-native
// structures that can be serialized.
// Filter to just the serializable status structures.
let out = std::io::stdout();
let mut out = out.lock();
let legacy_opt = if opts.json {
OutputFormat::Json
} else if std::io::stdout().is_terminal() {
OutputFormat::HumanReadable
} else {
OutputFormat::Yaml
};
let format = opts.format.unwrap_or(legacy_opt);
match format {
OutputFormat::Json => host
.to_canon_json_writer(&mut out)
.map_err(anyhow::Error::new),
OutputFormat::Yaml => serde_yaml::to_writer(&mut out, &host).map_err(anyhow::Error::new),
OutputFormat::HumanReadable => human_readable_output(&mut out, &host, opts.verbose),
}
.context("Writing to stdout")?;
Ok(())
}
#[derive(Debug, Clone, Copy)]
pub enum Slot {
Staged,
Booted,
Rollback,
}
impl std::fmt::Display for Slot {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
Slot::Staged => "staged",
Slot::Booted => "booted",
Slot::Rollback => "rollback",
};
f.write_str(s)
}
}
/// Output a row title, prefixed by spaces
fn write_row_name(mut out: impl Write, s: &str, prefix_len: usize) -> Result<()> {
let n = prefix_len.saturating_sub(s.chars().count());
let mut spaces = std::io::repeat(b' ').take(n as u64);
std::io::copy(&mut spaces, &mut out)?;
write!(out, "{s}: ")?;
Ok(())
}
/// Format a timestamp for human display, without nanoseconds.
///
/// Nanoseconds are irrelevant noise for container build timestamps;
/// this produces the same format as RFC3339 but truncated to seconds.
fn format_timestamp(t: &chrono::DateTime<chrono::Utc>) -> impl std::fmt::Display {
t.format("%Y-%m-%dT%H:%M:%SZ")
}
/// Helper function to render verbose ostree information
fn render_verbose_ostree_info(
mut out: impl Write,
ostree: &crate::spec::BootEntryOstree,
slot: Option<Slot>,
prefix_len: usize,
) -> Result<()> {
write_row_name(&mut out, "StateRoot", prefix_len)?;
writeln!(out, "{}", ostree.stateroot)?;
// Show deployment serial (similar to Index in rpm-ostree)
write_row_name(&mut out, "Deploy serial", prefix_len)?;
writeln!(out, "{}", ostree.deploy_serial)?;
// Show if this is staged
let is_staged = matches!(slot, Some(Slot::Staged));
write_row_name(&mut out, "Staged", prefix_len)?;
writeln!(out, "{}", if is_staged { "yes" } else { "no" })?;
Ok(())
}
/// Helper function to render if soft-reboot capable
fn write_soft_reboot(
mut out: impl Write,
entry: &crate::spec::BootEntry,
prefix_len: usize,
) -> Result<()> {
// Show soft-reboot capability
write_row_name(&mut out, "Soft-reboot", prefix_len)?;
writeln!(
out,
"{}",
if entry.soft_reboot_capable {
"yes"
} else {
"no"
}
)?;
Ok(())
}
/// Helper function to render download-only lock status
fn write_download_only(
mut out: impl Write,
slot: Option<Slot>,
entry: &crate::spec::BootEntry,
prefix_len: usize,
) -> Result<()> {
// Only staged deployments can have download-only status
if matches!(slot, Some(Slot::Staged)) {
write_row_name(&mut out, "Download-only", prefix_len)?;
writeln!(out, "{}", if entry.download_only { "yes" } else { "no" })?;
}
Ok(())
}
fn write_fsverity_enforcement(
mut out: impl Write,
entry: &crate::spec::BootEntry,
prefix_len: usize,
) -> Result<()> {
if let Some(cfs) = &entry.composefs {
write_row_name(&mut out, "FsVerity", prefix_len)?;
writeln!(
out,
"{}",
if cfs.missing_verity_allowed {
"Not Enforced"
} else {
"Enforced"
}
)?;
};
Ok(())
}
/// Render cached update information, showing what update is available.
///
/// This is populated by a previous `bootc upgrade --check` that found
/// a newer image in the registry. We only display it when the cached
/// digest differs from the currently deployed image.
fn render_cached_update(
mut out: impl Write,
cached: &crate::spec::ImageStatus,
current: &crate::spec::ImageStatus,
prefix_len: usize,
) -> Result<()> {
if cached.image_digest == current.image_digest {
return Ok(());
}
if let Some(version) = cached.version.as_deref() {
write_row_name(&mut out, "UpdateVersion", prefix_len)?;
let timestamp_str = cached
.timestamp
.as_ref()
.map(|t| format!(" ({})", format_timestamp(t)))
.unwrap_or_default();
writeln!(out, "{version}{timestamp_str}")?;
} else {
write_row_name(&mut out, "Update", prefix_len)?;
writeln!(out, "Available")?;
}
write_row_name(&mut out, "UpdateDigest", prefix_len)?;
writeln!(out, "{}", cached.image_digest)?;
Ok(())
}
/// Write the data for a container image based status.
fn human_render_slot(
mut out: impl Write,
slot: Option<Slot>,
entry: &crate::spec::BootEntry,
image: &crate::spec::ImageStatus,
host_status: &crate::spec::HostStatus,
verbose: bool,
) -> Result<()> {
let transport = &image.image.transport;
let imagename = &image.image.image;
// Registry is the default, so don't show that
let imageref = if transport == "registry" {
Cow::Borrowed(imagename)
} else {
// But for non-registry we include the transport
Cow::Owned(format!("{transport}:{imagename}"))
};
let prefix = match slot {
Some(Slot::Staged) => " Staged image".into(),
Some(Slot::Booted) => format!("{} Booted image", crate::glyph::Glyph::BlackCircle),
Some(Slot::Rollback) => " Rollback image".into(),
_ => " Other image".into(),
};
let prefix_len = prefix.chars().count();
writeln!(out, "{prefix}: {imageref}")?;
let arch = image.architecture.as_str();
write_row_name(&mut out, "Digest", prefix_len)?;
let digest = &image.image_digest;
writeln!(out, "{digest} ({arch})")?;
// Write the EROFS verity if present
if let Some(composefs) = &entry.composefs {
write_row_name(&mut out, "Verity", prefix_len)?;
writeln!(out, "{}", composefs.verity)?;
}
let timestamp = image.timestamp.as_ref().map(format_timestamp);
// If we have a version, combine with timestamp
if let Some(version) = image.version.as_deref() {
write_row_name(&mut out, "Version", prefix_len)?;
if let Some(timestamp) = timestamp {
writeln!(out, "{version} ({timestamp})")?;
} else {
writeln!(out, "{version}")?;
}
} else if let Some(timestamp) = timestamp {
// Otherwise just output timestamp
write_row_name(&mut out, "Timestamp", prefix_len)?;
writeln!(out, "{timestamp}")?;
}
if entry.pinned {
write_row_name(&mut out, "Pinned", prefix_len)?;
writeln!(out, "yes")?;
}
// Show cached update information when available (from a previous `bootc upgrade --check`)
if let Some(cached) = &entry.cached_update {
render_cached_update(&mut out, cached, image, prefix_len)?;
}
// Show /usr overlay status
write_usr_overlay(&mut out, slot, host_status, prefix_len)?;
if verbose {
// Show additional information in verbose mode similar to rpm-ostree
if let Some(ostree) = &entry.ostree {
render_verbose_ostree_info(&mut out, ostree, slot, prefix_len)?;
// Show the commit (equivalent to Base Commit in rpm-ostree)
write_row_name(&mut out, "Commit", prefix_len)?;
writeln!(out, "{}", ostree.checksum)?;
}
// Show signature information if available
if let Some(signature) = &image.image.signature {
write_row_name(&mut out, "Signature", prefix_len)?;
match signature {
crate::spec::ImageSignature::OstreeRemote(remote) => {
writeln!(out, "ostree-remote:{remote}")?;
}
crate::spec::ImageSignature::ContainerPolicy => {
writeln!(out, "container-policy")?;
}
crate::spec::ImageSignature::Insecure => {
writeln!(out, "insecure")?;
}
}
}
// Show soft-reboot capability
write_soft_reboot(&mut out, entry, prefix_len)?;
write_fsverity_enforcement(&mut out, entry, prefix_len)?;
// Show download-only lock status
write_download_only(&mut out, slot, entry, prefix_len)?;
}
tracing::debug!("pinned={}", entry.pinned);
Ok(())
}
/// Helper function to render usr overlay status
fn write_usr_overlay(
mut out: impl Write,
slot: Option<Slot>,
host_status: &crate::spec::HostStatus,
prefix_len: usize,
) -> Result<()> {
// Only booted deployments can have /usr overlay status
if matches!(slot, Some(Slot::Booted)) {
// Only print row if overlay is present
if let Some(ref overlay) = host_status.usr_overlay {
write_row_name(&mut out, "/usr overlay", prefix_len)?;
writeln!(out, "{}", overlay)?;
}
}
Ok(())
}
/// Output a rendering of a non-container boot entry.
fn human_render_slot_ostree(
mut out: impl Write,
slot: Option<Slot>,
entry: &crate::spec::BootEntry,
ostree_commit: &str,
host_status: &crate::spec::HostStatus,
verbose: bool,
) -> Result<()> {
// TODO consider rendering more ostree stuff here like rpm-ostree status does
let prefix = match slot {
Some(Slot::Staged) => " Staged ostree".into(),
Some(Slot::Booted) => format!("{} Booted ostree", crate::glyph::Glyph::BlackCircle),
Some(Slot::Rollback) => " Rollback ostree".into(),
_ => " Other ostree".into(),
};
let prefix_len = prefix.len();
writeln!(out, "{prefix}")?;
write_row_name(&mut out, "Commit", prefix_len)?;
writeln!(out, "{ostree_commit}")?;
if entry.pinned {
write_row_name(&mut out, "Pinned", prefix_len)?;
writeln!(out, "yes")?;
}
// Show /usr overlay status
write_usr_overlay(&mut out, slot, host_status, prefix_len)?;
if verbose {
// Show additional information in verbose mode similar to rpm-ostree
if let Some(ostree) = &entry.ostree {
render_verbose_ostree_info(&mut out, ostree, slot, prefix_len)?;
}
// Show soft-reboot capability
write_soft_reboot(&mut out, entry, prefix_len)?;
// Show download-only lock status
write_download_only(&mut out, slot, entry, prefix_len)?;
}
tracing::debug!("pinned={}", entry.pinned);
Ok(())
}
/// Output a rendering of a non-container composefs boot entry.
fn human_render_slot_composefs(
mut out: impl Write,
slot: Slot,
entry: &crate::spec::BootEntry,
erofs_verity: &str,
) -> Result<()> {
// TODO consider rendering more ostree stuff here like rpm-ostree status does
let prefix = match slot {
Slot::Staged => " Staged composefs".into(),
Slot::Booted => format!("{} Booted composefs", crate::glyph::Glyph::BlackCircle),
Slot::Rollback => " Rollback composefs".into(),
};
let prefix_len = prefix.len();
writeln!(out, "{prefix}")?;
write_row_name(&mut out, "Commit", prefix_len)?;
writeln!(out, "{erofs_verity}")?;
tracing::debug!("pinned={}", entry.pinned);
Ok(())
}
fn human_readable_output_booted(mut out: impl Write, host: &Host, verbose: bool) -> Result<()> {
let mut first = true;
for (slot_name, status) in [
(Slot::Staged, &host.status.staged),
(Slot::Booted, &host.status.booted),
(Slot::Rollback, &host.status.rollback),
] {
if let Some(host_status) = status {
if first {
first = false;
} else {
writeln!(out)?;
}
if let Some(image) = &host_status.image {
human_render_slot(
&mut out,
Some(slot_name),
host_status,
image,
&host.status,
verbose,
)?;
} else if let Some(ostree) = host_status.ostree.as_ref() {
human_render_slot_ostree(
&mut out,
Some(slot_name),
host_status,
&ostree.checksum,
&host.status,
verbose,
)?;
} else if let Some(composefs) = &host_status.composefs {
human_render_slot_composefs(&mut out, slot_name, host_status, &composefs.verity)?;
} else {
writeln!(out, "Current {slot_name} state is unknown")?;
}
}
}
if !host.status.other_deployments.is_empty() {
for entry in &host.status.other_deployments {
writeln!(out)?;
if let Some(image) = &entry.image {
human_render_slot(&mut out, None, entry, image, &host.status, verbose)?;
} else if let Some(ostree) = entry.ostree.as_ref() {
human_render_slot_ostree(
&mut out,
None,
entry,
&ostree.checksum,
&host.status,
verbose,
)?;
}
}
}
Ok(())
}
/// Implementation of rendering our host structure in a "human readable" way.
fn human_readable_output(mut out: impl Write, host: &Host, verbose: bool) -> Result<()> {
if host.status.booted.is_some() {
human_readable_output_booted(out, host, verbose)?;
} else {
writeln!(out, "System is not deployed via bootc.")?;
}
Ok(())
}
/// Output container inspection in human-readable format
fn container_inspect_print_human(
inspect: &crate::spec::ContainerInspect,
mut out: impl Write,
) -> Result<()> {
// Collect rows to determine the max label width
let mut rows: Vec<(&str, String)> = Vec::new();
if let Some(kernel) = &inspect.kernel {
rows.push(("Kernel", kernel.version.clone()));
let kernel_type = if kernel.unified { "UKI" } else { "vmlinuz" };
rows.push(("Type", kernel_type.to_string()));
} else {
rows.push(("Kernel", "<none>".to_string()));
}
let kargs = if inspect.kargs.is_empty() {
"<none>".to_string()
} else {
inspect.kargs.join(" ")
};
rows.push(("Kargs", kargs));
// Find the max label width for right-alignment
let max_label_len = rows
.iter()
.map(|(label, _)| label.width())
.max()
.unwrap_or(0);
for (label, value) in rows {
write_row_name(&mut out, label, max_label_len)?;
writeln!(out, "{value}")?;
}
Ok(())
}
/// Inspect a container image and output information about it.
pub(crate) fn container_inspect(
rootfs: &camino::Utf8Path,
json: bool,
format: Option<OutputFormat>,
) -> Result<()> {
let root = cap_std_ext::cap_std::fs::Dir::open_ambient_dir(
rootfs,
cap_std_ext::cap_std::ambient_authority(),
)?;
let kargs = crate::bootc_kargs::get_kargs_in_root(&root, std::env::consts::ARCH)?;
let kargs: Vec<String> = kargs.iter_str().map(|s| s.to_owned()).collect();
let kernel = crate::kernel::find_kernel(&root)?.map(Into::into);
let inspect = crate::spec::ContainerInspect { kargs, kernel };
// Determine output format: explicit --format wins, then --json, then default to human-readable
let format = format.unwrap_or(if json {
OutputFormat::Json
} else {
OutputFormat::HumanReadable
});
let mut out = std::io::stdout().lock();
match format {
OutputFormat::Json => {
serde_json::to_writer_pretty(&mut out, &inspect)?;
}
OutputFormat::Yaml => {
serde_yaml::to_writer(&mut out, &inspect)?;
}
OutputFormat::HumanReadable => {