Skip to main content

bootc_lib/
deploy.rs

1//! # Write deployments merging image with configmap
2//!
3//! Create a merged filesystem tree with the image and mounted configmaps.
4
5use std::collections::HashSet;
6use std::io::{BufRead, Write};
7use std::os::fd::AsFd;
8use std::process::Command;
9
10use anyhow::{Context, Result, anyhow};
11use bootc_kernel_cmdline::utf8::CmdlineOwned;
12use bootc_utils::skopeo_bin;
13use cap_std::fs::{Dir, MetadataExt};
14use cap_std_ext::cap_std;
15use cap_std_ext::dirext::CapStdExtDirExt;
16use fn_error_context::context;
17use ostree::{gio, glib};
18use ostree_container::OstreeImageReference;
19use ostree_ext::container as ostree_container;
20use ostree_ext::container::store::{ImageImporter, ImportProgress, PrepareResult, PreparedImport};
21use ostree_ext::oci_spec::image::{Descriptor, Digest};
22use ostree_ext::ostree::Deployment;
23use ostree_ext::ostree::{self, Sysroot};
24use ostree_ext::sysroot::SysrootLock;
25use ostree_ext::tokio_util::spawn_blocking_cancellable_flatten;
26
27use crate::progress_jsonl::{Event, ProgressWriter, SubTaskBytes, SubTaskStep};
28use crate::spec::ImageReference;
29use crate::spec::{BootOrder, HostSpec};
30use crate::status::labels_of_config;
31use crate::store::Storage;
32use crate::utils::async_task_with_spinner;
33
34// TODO use https://github.com/ostreedev/ostree-rs-ext/pull/493/commits/afc1837ff383681b947de30c0cefc70080a4f87a
35const BASE_IMAGE_PREFIX: &str = "ostree/container/baseimage/bootc";
36
37/// Create an ImageProxyConfig with bootc's user agent prefix set.
38///
39/// This allows registries to distinguish "image pulls for bootc client runs"
40/// from other skopeo/containers-image users.
41pub(crate) fn new_proxy_config() -> ostree_ext::containers_image_proxy::ImageProxyConfig {
42    let mut c = ostree_ext::containers_image_proxy::ImageProxyConfig::default();
43    c.user_agent_prefix = Some(format!("bootc/{}", env!("CARGO_PKG_VERSION")));
44    c
45}
46
47/// Set on an ostree commit if this is a derived commit
48const BOOTC_DERIVED_KEY: &str = "bootc.derived";
49
50/// Variant of HostSpec but required to be filled out
51pub(crate) struct RequiredHostSpec<'a> {
52    pub(crate) image: &'a ImageReference,
53}
54
55/// State of a locally fetched image
56pub(crate) struct ImageState {
57    pub(crate) manifest_digest: Digest,
58    pub(crate) version: Option<String>,
59    pub(crate) ostree_commit: String,
60}
61
62impl<'a> RequiredHostSpec<'a> {
63    /// Given a (borrowed) host specification, "unwrap" its internal
64    /// options, giving a spec that is required to have a base container image.
65    pub(crate) fn from_spec(spec: &'a HostSpec) -> Result<Self> {
66        let image = spec
67            .image
68            .as_ref()
69            .ok_or_else(|| anyhow::anyhow!("Missing image in specification"))?;
70        Ok(Self { image })
71    }
72}
73
74impl From<ostree_container::store::LayeredImageState> for ImageState {
75    fn from(value: ostree_container::store::LayeredImageState) -> Self {
76        let version = value.version().map(|v| v.to_owned());
77        let ostree_commit = value.get_commit().to_owned();
78        Self {
79            manifest_digest: value.manifest_digest,
80            version,
81            ostree_commit,
82        }
83    }
84}
85
86impl ImageState {
87    /// Fetch the manifest corresponding to this image.  May not be available in all backends.
88    pub(crate) fn get_manifest(
89        &self,
90        repo: &ostree::Repo,
91    ) -> Result<Option<ostree_ext::oci_spec::image::ImageManifest>> {
92        ostree_container::store::query_image_commit(repo, &self.ostree_commit)
93            .map(|v| Some(v.manifest))
94    }
95}
96
97/// Wrapper for pulling a container image, wiring up status output.
98pub(crate) async fn new_importer(
99    repo: &ostree::Repo,
100    imgref: &ostree_container::OstreeImageReference,
101    booted_deployment: Option<&ostree::Deployment>,
102) -> Result<ostree_container::store::ImageImporter> {
103    let config = new_proxy_config();
104    let mut imp = ostree_container::store::ImageImporter::new(repo, imgref, config).await?;
105    imp.require_bootable();
106    // We do our own GC/prune in deploy::prune(), so skip the importer's internal one.
107    imp.disable_gc();
108    if let Some(deployment) = booted_deployment {
109        imp.set_sepolicy_commit(deployment.csum().to_string());
110    }
111    Ok(imp)
112}
113
114/// Wrapper for pulling a container image with a custom proxy config (e.g. for unified storage).
115pub(crate) async fn new_importer_with_config(
116    repo: &ostree::Repo,
117    imgref: &ostree_container::OstreeImageReference,
118    config: ostree_ext::containers_image_proxy::ImageProxyConfig,
119    booted_deployment: Option<&ostree::Deployment>,
120) -> Result<ostree_container::store::ImageImporter> {
121    let mut imp = ostree_container::store::ImageImporter::new(repo, imgref, config).await?;
122    imp.require_bootable();
123    // We do our own GC/prune in deploy::prune(), so skip the importer's internal one.
124    imp.disable_gc();
125    if let Some(deployment) = booted_deployment {
126        imp.set_sepolicy_commit(deployment.csum().to_string());
127    }
128    Ok(imp)
129}
130
131pub(crate) fn check_bootc_label(config: &ostree_ext::oci_spec::image::ImageConfiguration) {
132    if let Some(label) =
133        labels_of_config(config).and_then(|labels| labels.get(crate::metadata::BOOTC_COMPAT_LABEL))
134    {
135        match label.as_str() {
136            crate::metadata::COMPAT_LABEL_V1 => {}
137            o => crate::journal::journal_print(
138                libsystemd::logging::Priority::Warning,
139                &format!(
140                    "notice: Unknown {} value {}",
141                    crate::metadata::BOOTC_COMPAT_LABEL,
142                    o
143                ),
144            ),
145        }
146    } else {
147        crate::journal::journal_print(
148            libsystemd::logging::Priority::Warning,
149            &format!(
150                "notice: Image is missing label: {}",
151                crate::metadata::BOOTC_COMPAT_LABEL
152            ),
153        )
154    }
155}
156
157fn descriptor_of_progress(p: &ImportProgress) -> &Descriptor {
158    match p {
159        ImportProgress::OstreeChunkStarted(l) => l,
160        ImportProgress::OstreeChunkCompleted(l) => l,
161        ImportProgress::DerivedLayerStarted(l) => l,
162        ImportProgress::DerivedLayerCompleted(l) => l,
163    }
164}
165
166fn prefix_of_progress(p: &ImportProgress) -> &'static str {
167    match p {
168        ImportProgress::OstreeChunkStarted(_) | ImportProgress::OstreeChunkCompleted(_) => {
169            "ostree chunk"
170        }
171        ImportProgress::DerivedLayerStarted(_) | ImportProgress::DerivedLayerCompleted(_) => {
172            "layer"
173        }
174    }
175}
176
177/// Configuration for layer progress printing
178struct LayerProgressConfig {
179    layers: tokio::sync::mpsc::Receiver<ostree_container::store::ImportProgress>,
180    layer_bytes: tokio::sync::watch::Receiver<Option<ostree_container::store::LayerProgress>>,
181    digest: Box<str>,
182    n_layers_to_fetch: usize,
183    layers_total: usize,
184    bytes_to_download: u64,
185    bytes_total: u64,
186    prog: ProgressWriter,
187    quiet: bool,
188}
189
190/// Write container fetch progress to standard output.
191async fn handle_layer_progress_print(mut config: LayerProgressConfig) -> ProgressWriter {
192    let start = std::time::Instant::now();
193    let mut total_read = 0u64;
194    let bar = indicatif::MultiProgress::new();
195    if config.quiet {
196        bar.set_draw_target(indicatif::ProgressDrawTarget::hidden());
197    }
198    let layers_bar = bar.add(indicatif::ProgressBar::new(
199        config.n_layers_to_fetch.try_into().unwrap(),
200    ));
201    let byte_bar = bar.add(indicatif::ProgressBar::new(0));
202    // let byte_bar = indicatif::ProgressBar::new(0);
203    // byte_bar.set_draw_target(indicatif::ProgressDrawTarget::hidden());
204    layers_bar.set_style(
205        indicatif::ProgressStyle::default_bar()
206            .template("{prefix} {bar} {pos}/{len} {wide_msg}")
207            .unwrap(),
208    );
209    let taskname = "Fetching layers";
210    layers_bar.set_prefix(taskname);
211    layers_bar.set_message("");
212    byte_bar.set_prefix("Fetching");
213    byte_bar.set_style(
214        indicatif::ProgressStyle::default_bar()
215                .template(
216                    " └ {prefix} {bar} {binary_bytes}/{binary_total_bytes} ({binary_bytes_per_sec}) {wide_msg}",
217                )
218                .unwrap()
219        );
220
221    let mut subtasks = vec![];
222    let mut subtask: SubTaskBytes = Default::default();
223    loop {
224        tokio::select! {
225            // Always handle layer changes first.
226            biased;
227            layer = config.layers.recv() => {
228                if let Some(l) = layer {
229                    let layer = descriptor_of_progress(&l);
230                    let layer_type = prefix_of_progress(&l);
231                    let short_digest = &layer.digest().digest()[0..21];
232                    let layer_size = layer.size();
233                    if l.is_starting() {
234                        // Reset the progress bar
235                        byte_bar.reset_elapsed();
236                        byte_bar.reset_eta();
237                        byte_bar.set_length(layer_size);
238                        byte_bar.set_message(format!("{layer_type} {short_digest}"));
239
240                        subtask = SubTaskBytes {
241                            subtask: layer_type.into(),
242                            description: format!("{layer_type}: {short_digest}").clone().into(),
243                            id: short_digest.to_string().clone().into(),
244                            bytes_cached: 0,
245                            bytes: 0,
246                            bytes_total: layer_size,
247                        };
248                    } else {
249                        // Use the bar's length (actual blob size) rather than
250                        // the manifest descriptor size for completion accounting.
251                        let actual_size = byte_bar.length().unwrap_or(layer_size);
252                        byte_bar.set_position(actual_size);
253                        layers_bar.inc(1);
254                        total_read = total_read.saturating_add(actual_size);
255                        // Emit an event where bytes == total to signal completion.
256                        subtask.bytes_total = actual_size;
257                        subtask.bytes = actual_size;
258                        subtasks.push(subtask.clone());
259                        config.prog.send(Event::ProgressBytes {
260                            task: "pulling".into(),
261                            description: format!("Pulling Image: {}", config.digest).into(),
262                            id: (*config.digest).into(),
263                            bytes_cached: config.bytes_total - config.bytes_to_download,
264                            bytes: total_read,
265                            bytes_total: config.bytes_to_download,
266                            steps_cached: (config.layers_total - config.n_layers_to_fetch) as u64,
267                            steps: layers_bar.position(),
268                            steps_total: config.n_layers_to_fetch as u64,
269                            subtasks: subtasks.clone(),
270                        }).await;
271                    }
272                } else {
273                    // If the receiver is disconnected, then we're done
274                    break
275                };
276            },
277            r = config.layer_bytes.changed() => {
278                if r.is_err() {
279                    // If the receiver is disconnected, then we're done
280                    break
281                }
282                let bytes = {
283                    let bytes = config.layer_bytes.borrow_and_update();
284                    bytes.as_ref().cloned()
285                };
286                if let Some(bytes) = bytes {
287                    // Update the bar length from the actual blob size, which
288                    // may differ from the manifest descriptor size (e.g.
289                    // containers-storage stores layers uncompressed).
290                    byte_bar.set_length(bytes.total);
291                    byte_bar.set_position(bytes.fetched);
292                    subtask.bytes_total = bytes.total;
293                    subtask.bytes = byte_bar.position();
294                    config.prog.send_lossy(Event::ProgressBytes {
295                        task: "pulling".into(),
296                        description: format!("Pulling Image: {}", config.digest).into(),
297                        id: (*config.digest).into(),
298                        bytes_cached: config.bytes_total - config.bytes_to_download,
299                        bytes: total_read + byte_bar.position(),
300                        bytes_total: config.bytes_to_download,
301                        steps_cached: (config.layers_total - config.n_layers_to_fetch) as u64,
302                        steps: layers_bar.position(),
303                        steps_total: config.n_layers_to_fetch as u64,
304                        subtasks: subtasks.clone().into_iter().chain([subtask.clone()]).collect(),
305                    }).await;
306                }
307            }
308        }
309    }
310    byte_bar.finish_and_clear();
311    layers_bar.finish_and_clear();
312    if let Err(e) = bar.clear() {
313        tracing::warn!("clearing bar: {e}");
314    }
315    let end = std::time::Instant::now();
316    let elapsed = end.duration_since(start);
317    let persec = total_read as f64 / elapsed.as_secs_f64();
318    let persec = indicatif::HumanBytes(persec as u64);
319    if let Err(e) = bar.println(&format!(
320        "Fetched layers: {} in {} ({}/s)",
321        indicatif::HumanBytes(total_read),
322        indicatif::HumanDuration(elapsed),
323        persec,
324    )) {
325        tracing::warn!("writing to stdout: {e}");
326    }
327
328    // Since the progress notifier closed, we know import has started
329    // use as a heuristic to begin import progress
330    // Cannot be lossy or it is dropped
331    config
332        .prog
333        .send(Event::ProgressSteps {
334            task: "importing".into(),
335            description: "Importing Image".into(),
336            id: (*config.digest).into(),
337            steps_cached: 0,
338            steps: 0,
339            steps_total: 1,
340            subtasks: [SubTaskStep {
341                subtask: "importing".into(),
342                description: "Importing Image".into(),
343                id: "importing".into(),
344                completed: false,
345            }]
346            .into(),
347        })
348        .await;
349
350    // Return the writer
351    config.prog
352}
353
354/// Gather all bound images in all deployments, then prune the image store,
355/// using the gathered images as the roots (that will not be GC'd).
356pub(crate) async fn prune_container_store(sysroot: &Storage) -> Result<()> {
357    let ostree = sysroot.get_ostree()?;
358    let deployments = ostree.deployments();
359    let mut all_bound_images = Vec::new();
360    for deployment in deployments {
361        let bound = crate::boundimage::query_bound_images_for_deployment(ostree, &deployment)?;
362        all_bound_images.extend(bound.into_iter());
363        // Also include the host image itself
364        // Note: Use just the image name (not the full transport:image format) because
365        // podman's image names don't include the transport prefix.
366        if let Some(host_image) = crate::status::boot_entry_from_deployment(ostree, &deployment)?
367            .image
368            .map(|i| i.image)
369        {
370            all_bound_images.push(crate::boundimage::BoundImage {
371                image: host_image.image.clone(),
372                auth_file: None,
373            });
374        }
375    }
376    // Convert to a hashset of just the image names
377    let image_names = HashSet::from_iter(all_bound_images.iter().map(|img| img.image.as_str()));
378    let pruned = sysroot
379        .get_ensure_imgstore()?
380        .prune_except_roots(&image_names)
381        .await?;
382    tracing::debug!("Pruned images: {}", pruned.len());
383    Ok(())
384}
385
386/// Core disk space check: verify that `bytes_to_fetch` fits within available space,
387/// leaving at least `min_free` bytes reserved.
388fn check_disk_space_inner(
389    fd: impl AsFd,
390    bytes_to_fetch: u64,
391    min_free: u64,
392    imgref: &ImageReference,
393) -> Result<()> {
394    let stat = rustix::fs::fstatvfs(fd)?;
395    let bytes_avail = stat.f_bsize.checked_mul(stat.f_bavail).unwrap_or(u64::MAX);
396    let usable = bytes_avail.saturating_sub(min_free);
397    tracing::trace!("bytes_avail: {bytes_avail} min_free: {min_free} usable: {usable}");
398
399    if bytes_to_fetch > usable {
400        anyhow::bail!(
401            "Insufficient free space for {image} (available: {available} required: {required})",
402            available = ostree_ext::glib::format_size(usable),
403            required = ostree_ext::glib::format_size(bytes_to_fetch),
404            image = imgref.image,
405        );
406    }
407    Ok(())
408}
409
410/// Verify there is sufficient disk space to pull an image into the ostree repo.
411/// Respects the repository's configured min-free-space threshold.
412pub(crate) fn check_disk_space_ostree(
413    repo: &ostree::Repo,
414    image_meta: &PreparedImportMeta,
415    imgref: &ImageReference,
416) -> Result<()> {
417    let min_free = repo.min_free_space_bytes().unwrap_or(0);
418    check_disk_space_inner(
419        repo.dfd_borrow(),
420        image_meta.bytes_to_fetch,
421        min_free,
422        imgref,
423    )
424}
425
426/// Verify there is sufficient disk space to pull an image into the composefs store
427/// via the ostree unified-storage path (uses `PreparedImportMeta`).
428pub(crate) fn check_disk_space_unified(
429    cfs: &crate::store::ComposefsRepository,
430    image_meta: &PreparedImportMeta,
431    imgref: &ImageReference,
432) -> Result<()> {
433    check_disk_space_inner(cfs.objects_dir()?, image_meta.bytes_to_fetch, 0, imgref)
434}
435
436/// Verify there is sufficient disk space to pull an image into the composefs store
437/// for the native composefs backend (uses a raw `ImageManifest`).
438pub(crate) fn check_disk_space_composefs(
439    cfs: &crate::store::ComposefsRepository,
440    manifest: &ostree_ext::oci_spec::image::ImageManifest,
441    imgref: &ImageReference,
442) -> Result<()> {
443    let bytes_to_fetch: u64 = manifest
444        .layers()
445        .iter()
446        .map(|l: &ostree_ext::oci_spec::image::Descriptor| l.size())
447        .sum();
448    check_disk_space_inner(cfs.objects_dir()?, bytes_to_fetch, 0, imgref)
449}
450
451pub(crate) struct PreparedImportMeta {
452    pub imp: ImageImporter,
453    pub prep: Box<PreparedImport>,
454    pub digest: Digest,
455    pub n_layers_to_fetch: usize,
456    pub layers_total: usize,
457    pub bytes_to_fetch: u64,
458    pub bytes_total: u64,
459}
460
461pub(crate) enum PreparedPullResult {
462    Ready(Box<PreparedImportMeta>),
463    AlreadyPresent(Box<ImageState>),
464}
465
466pub(crate) async fn prepare_for_pull(
467    repo: &ostree::Repo,
468    imgref: &ImageReference,
469    target_imgref: Option<&OstreeImageReference>,
470    booted_deployment: Option<&ostree::Deployment>,
471) -> Result<PreparedPullResult> {
472    let imgref_canonicalized = imgref.clone().canonicalize()?;
473    tracing::debug!("Canonicalized image reference: {imgref_canonicalized:#}");
474    let ostree_imgref = &OstreeImageReference::from(imgref_canonicalized);
475    let mut imp = new_importer(repo, ostree_imgref, booted_deployment).await?;
476    if let Some(target) = target_imgref {
477        imp.set_target(target);
478    }
479    let prep = match imp.prepare().await? {
480        PrepareResult::AlreadyPresent(c) => {
481            println!("No changes in {imgref:#} => {}", c.manifest_digest);
482            return Ok(PreparedPullResult::AlreadyPresent(Box::new((*c).into())));
483        }
484        PrepareResult::Ready(p) => p,
485    };
486    check_bootc_label(&prep.config);
487    if let Some(warning) = prep.deprecated_warning() {
488        ostree_ext::cli::print_deprecated_warning(warning).await;
489    }
490    ostree_ext::cli::print_layer_status(&prep);
491    let layers_to_fetch = prep.layers_to_fetch().collect::<Result<Vec<_>>>()?;
492
493    let prepared_image = PreparedImportMeta {
494        imp,
495        n_layers_to_fetch: layers_to_fetch.len(),
496        layers_total: prep.all_layers().count(),
497        bytes_to_fetch: layers_to_fetch.iter().map(|(l, _)| l.layer.size()).sum(),
498        bytes_total: prep.all_layers().map(|l| l.layer.size()).sum(),
499        digest: prep.manifest_digest.clone(),
500        prep,
501    };
502
503    Ok(PreparedPullResult::Ready(Box::new(prepared_image)))
504}
505
506/// Check whether the image exists in bootc's unified container storage.
507///
508/// This is used for auto-detection: if the image already exists in bootc storage
509/// (e.g., from a previous `bootc image set-unified` or LBI pull), we can use
510/// the unified storage path for faster imports.
511///
512/// Returns true if the image exists in bootc storage.
513pub(crate) async fn image_exists_in_unified_storage(
514    store: &Storage,
515    imgref: &ImageReference,
516) -> Result<bool> {
517    let imgstore = store.get_ensure_imgstore()?;
518    let image_ref_str = imgref.to_transport_image()?;
519    imgstore.exists(&image_ref_str).await
520}
521
522/// Unified approach: Use bootc's CStorage to pull the image, then prepare from containers-storage.
523/// This reuses the same infrastructure as LBIs.
524pub(crate) async fn prepare_for_pull_unified(
525    repo: &ostree::Repo,
526    imgref: &ImageReference,
527    target_imgref: Option<&OstreeImageReference>,
528    store: &Storage,
529    booted_deployment: Option<&ostree::Deployment>,
530) -> Result<PreparedPullResult> {
531    // Get or initialize the bootc container storage (same as used for LBIs)
532    let imgstore = store.get_ensure_imgstore()?;
533
534    let image_ref_str = imgref.to_transport_image()?;
535
536    // Always pull to ensure we have the latest image, whether from a remote
537    // registry or a locally rebuilt image
538    tracing::info!(
539        "Unified pull: pulling from transport '{}' to bootc storage",
540        &imgref.transport
541    );
542
543    // Pull the image into bootc containers-storage with per-layer
544    // download progress via the podman native API.
545    imgstore
546        .pull_with_progress(&image_ref_str)
547        .await
548        .context("Pulling image into bootc containers-storage")?;
549
550    // Now create a containers-storage reference to read from bootc storage
551    tracing::info!("Unified pull: now importing from containers-storage transport");
552    let containers_storage_imgref = ImageReference {
553        transport: "containers-storage".to_string(),
554        image: imgref.image.clone(),
555        signature: imgref.signature.clone(),
556    };
557    let ostree_imgref = OstreeImageReference::from(containers_storage_imgref);
558
559    // Configure the importer to use bootc storage as an additional image store
560    let mut config = new_proxy_config();
561    let mut cmd = Command::new(skopeo_bin());
562    // Use the physical path to bootc storage from the Storage struct
563    let storage_path = format!(
564        "{}/{}",
565        store.physical_root_path,
566        crate::podstorage::CStorage::subpath()
567    );
568    crate::podstorage::set_additional_image_store(&mut cmd, &storage_path);
569    config.skopeo_cmd = Some(cmd);
570
571    // Use the preparation flow with the custom config
572    let mut imp = new_importer_with_config(repo, &ostree_imgref, config, booted_deployment).await?;
573    if let Some(target) = target_imgref {
574        imp.set_target(target);
575    }
576    let prep = match imp.prepare().await? {
577        PrepareResult::AlreadyPresent(c) => {
578            println!("No changes in {imgref:#} => {}", c.manifest_digest);
579            return Ok(PreparedPullResult::AlreadyPresent(Box::new((*c).into())));
580        }
581        PrepareResult::Ready(p) => p,
582    };
583    check_bootc_label(&prep.config);
584    if let Some(warning) = prep.deprecated_warning() {
585        ostree_ext::cli::print_deprecated_warning(warning).await;
586    }
587    ostree_ext::cli::print_layer_status(&prep);
588    let layers_to_fetch = prep.layers_to_fetch().collect::<Result<Vec<_>>>()?;
589
590    // Log that we're importing a new image from containers-storage
591    const PULLING_NEW_IMAGE_ID: &str = "6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0";
592    tracing::info!(
593        message_id = PULLING_NEW_IMAGE_ID,
594        bootc.image.reference = &imgref.image,
595        bootc.image.transport = "containers-storage",
596        bootc.original_transport = &imgref.transport,
597        bootc.status = "importing_from_storage",
598        "Importing image from bootc storage: {}",
599        ostree_imgref
600    );
601
602    let prepared_image = PreparedImportMeta {
603        imp,
604        n_layers_to_fetch: layers_to_fetch.len(),
605        layers_total: prep.all_layers().count(),
606        bytes_to_fetch: layers_to_fetch.iter().map(|(l, _)| l.layer.size()).sum(),
607        bytes_total: prep.all_layers().map(|l| l.layer.size()).sum(),
608        digest: prep.manifest_digest.clone(),
609        prep,
610    };
611
612    Ok(PreparedPullResult::Ready(Box::new(prepared_image)))
613}
614
615/// Unified pull: Use podman to pull to containers-storage, then read from there
616pub(crate) async fn pull_unified(
617    repo: &ostree::Repo,
618    imgref: &ImageReference,
619    target_imgref: Option<&OstreeImageReference>,
620    quiet: bool,
621    prog: ProgressWriter,
622    store: &Storage,
623    booted_deployment: Option<&ostree::Deployment>,
624) -> Result<Box<ImageState>> {
625    match prepare_for_pull_unified(repo, imgref, target_imgref, store, booted_deployment).await? {
626        PreparedPullResult::AlreadyPresent(existing) => {
627            // Log that the image was already present (Debug level since it's not actionable)
628            const IMAGE_ALREADY_PRESENT_ID: &str = "5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9";
629            tracing::debug!(
630                message_id = IMAGE_ALREADY_PRESENT_ID,
631                bootc.image.reference = &imgref.image,
632                bootc.image.transport = &imgref.transport,
633                bootc.status = "already_present",
634                "Image already present: {}",
635                imgref
636            );
637            Ok(existing)
638        }
639        PreparedPullResult::Ready(prepared_image_meta) => {
640            check_disk_space_unified(
641                store.get_ensure_composefs()?.as_ref(),
642                &prepared_image_meta,
643                imgref,
644            )?;
645            // To avoid duplicate success logs, pass a containers-storage imgref to the importer
646            let cs_imgref = ImageReference {
647                transport: "containers-storage".to_string(),
648                image: imgref.image.clone(),
649                signature: imgref.signature.clone(),
650            };
651            pull_from_prepared(&cs_imgref, quiet, prog, *prepared_image_meta).await
652        }
653    }
654}
655
656#[context("Pulling")]
657pub(crate) async fn pull_from_prepared(
658    imgref: &ImageReference,
659    quiet: bool,
660    prog: ProgressWriter,
661    mut prepared_image: PreparedImportMeta,
662) -> Result<Box<ImageState>> {
663    let layer_progress = prepared_image.imp.request_progress();
664    let layer_byte_progress = prepared_image.imp.request_layer_progress();
665    let digest = prepared_image.digest.clone();
666    let digest_imp = prepared_image.digest.clone();
667
668    let printer = tokio::task::spawn(async move {
669        handle_layer_progress_print(LayerProgressConfig {
670            layers: layer_progress,
671            layer_bytes: layer_byte_progress,
672            digest: digest.as_ref().into(),
673            n_layers_to_fetch: prepared_image.n_layers_to_fetch,
674            layers_total: prepared_image.layers_total,
675            bytes_to_download: prepared_image.bytes_to_fetch,
676            bytes_total: prepared_image.bytes_total,
677            prog,
678            quiet,
679        })
680        .await
681    });
682    let import = prepared_image.imp.import(prepared_image.prep).await;
683    let prog = printer.await?;
684    // Both the progress and the import are done, so import is done as well
685    prog.send(Event::ProgressSteps {
686        task: "importing".into(),
687        description: "Importing Image".into(),
688        id: digest_imp.clone().as_ref().into(),
689        steps_cached: 0,
690        steps: 1,
691        steps_total: 1,
692        subtasks: [SubTaskStep {
693            subtask: "importing".into(),
694            description: "Importing Image".into(),
695            id: "importing".into(),
696            completed: true,
697        }]
698        .into(),
699    })
700    .await;
701    let import = import?;
702    let imgref_canonicalized = imgref.clone().canonicalize()?;
703    tracing::debug!("Canonicalized image reference: {imgref_canonicalized:#}");
704
705    // Log successful import completion (skip if using unified storage to avoid double logging)
706    let is_unified_path = imgref.transport == "containers-storage";
707    if !is_unified_path {
708        const IMPORT_COMPLETE_JOURNAL_ID: &str = "4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a8";
709
710        tracing::info!(
711            message_id = IMPORT_COMPLETE_JOURNAL_ID,
712            bootc.image.reference = &imgref.image,
713            bootc.image.transport = &imgref.transport,
714            bootc.manifest_digest = import.manifest_digest.as_ref(),
715            bootc.ostree_commit = &import.merge_commit,
716            "Successfully imported image: {}",
717            imgref
718        );
719    }
720
721    if let Some(msg) =
722        ostree_container::store::image_filtered_content_warning(&import.filtered_files)
723            .context("Image content warning")?
724    {
725        tracing::info!("{}", msg);
726    }
727    Ok(Box::new((*import).into()))
728}
729
730/// Wrapper for pulling a container image, wiring up status output.
731pub(crate) async fn pull(
732    repo: &ostree::Repo,
733    imgref: &ImageReference,
734    target_imgref: Option<&OstreeImageReference>,
735    quiet: bool,
736    prog: ProgressWriter,
737    booted_deployment: Option<&ostree::Deployment>,
738) -> Result<Box<ImageState>> {
739    match prepare_for_pull(repo, imgref, target_imgref, booted_deployment).await? {
740        PreparedPullResult::AlreadyPresent(existing) => {
741            // Log that the image was already present (Debug level since it's not actionable)
742            const IMAGE_ALREADY_PRESENT_ID: &str = "5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9";
743            tracing::debug!(
744                message_id = IMAGE_ALREADY_PRESENT_ID,
745                bootc.image.reference = &imgref.image,
746                bootc.image.transport = &imgref.transport,
747                bootc.status = "already_present",
748                "Image already present: {}",
749                imgref
750            );
751            Ok(existing)
752        }
753        PreparedPullResult::Ready(prepared_image_meta) => {
754            // Check disk space before attempting to pull
755            check_disk_space_ostree(repo, &prepared_image_meta, imgref)?;
756            // Log that we're pulling a new image
757            const PULLING_NEW_IMAGE_ID: &str = "6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0";
758            tracing::info!(
759                message_id = PULLING_NEW_IMAGE_ID,
760                bootc.image.reference = &imgref.image,
761                bootc.image.transport = &imgref.transport,
762                bootc.status = "pulling_new",
763                "Pulling new image: {}",
764                imgref
765            );
766            Ok(pull_from_prepared(imgref, quiet, prog, *prepared_image_meta).await?)
767        }
768    }
769}
770
771pub(crate) async fn wipe_ostree(sysroot: Sysroot) -> Result<()> {
772    tokio::task::spawn_blocking(move || {
773        sysroot
774            .write_deployments(&[], gio::Cancellable::NONE)
775            .context("removing deployments")
776    })
777    .await??;
778
779    Ok(())
780}
781
782pub(crate) async fn cleanup(sysroot: &Storage) -> Result<()> {
783    // Log the cleanup operation to systemd journal
784    const CLEANUP_JOURNAL_ID: &str = "2f1a0b9c8d7e6f5a4b3c2d1e0f9a8b7c6";
785
786    tracing::info!(
787        message_id = CLEANUP_JOURNAL_ID,
788        "Starting cleanup of old images and deployments"
789    );
790
791    let bound_prune = prune_container_store(sysroot);
792
793    // We create clones (just atomic reference bumps) here to move to the thread.
794    let ostree = sysroot.get_ostree_cloned()?;
795    let repo = ostree.repo();
796    let repo_prune =
797        ostree_ext::tokio_util::spawn_blocking_cancellable_flatten(move |cancellable| {
798            let locked_sysroot = &SysrootLock::from_assumed_locked(&ostree);
799            let cancellable = Some(cancellable);
800            let repo = &repo;
801            let txn = repo.auto_transaction(cancellable)?;
802            let repo = txn.repo();
803
804            // Regenerate our base references.  First, we delete the ones that exist
805            for ref_entry in repo
806                .list_refs_ext(
807                    Some(BASE_IMAGE_PREFIX),
808                    ostree::RepoListRefsExtFlags::NONE,
809                    cancellable,
810                )
811                .context("Listing refs")?
812                .keys()
813            {
814                repo.transaction_set_refspec(ref_entry, None);
815            }
816
817            // Then, for each deployment which is derived (e.g. has configmaps) we synthesize
818            // a base ref to ensure that it's not GC'd.
819            for (i, deployment) in ostree.deployments().into_iter().enumerate() {
820                let commit = deployment.csum();
821                if let Some(base) = get_base_commit(repo, &commit)? {
822                    repo.transaction_set_refspec(&format!("{BASE_IMAGE_PREFIX}/{i}"), Some(&base));
823                }
824            }
825
826            let pruned =
827                ostree_container::deploy::prune(locked_sysroot).context("Pruning images")?;
828            if !pruned.is_empty() {
829                let size = glib::format_size(pruned.objsize);
830                println!(
831                    "Pruned images: {} (layers: {}, objsize: {})",
832                    pruned.n_images, pruned.n_layers, size
833                );
834            } else {
835                tracing::debug!("Nothing to prune");
836            }
837
838            Ok(())
839        });
840
841    // We run these in parallel mostly because we can.
842    tokio::try_join!(repo_prune, bound_prune)?;
843    Ok(())
844}
845
846/// If commit is a bootc-derived commit (e.g. has configmaps), return its base.
847#[context("Finding base commit")]
848pub(crate) fn get_base_commit(repo: &ostree::Repo, commit: &str) -> Result<Option<String>> {
849    let commitv = repo.load_commit(commit)?.0;
850    let commitmeta = commitv.child_value(0);
851    let commitmeta = &glib::VariantDict::new(Some(&commitmeta));
852    let r = commitmeta.lookup::<String>(BOOTC_DERIVED_KEY)?;
853    Ok(r)
854}
855
856#[context("Writing deployment")]
857async fn deploy(
858    sysroot: &Storage,
859    from: MergeState,
860    image: &ImageState,
861    origin: &glib::KeyFile,
862    lock_finalization: bool,
863) -> Result<Deployment> {
864    // Compute the kernel argument overrides. In practice today this API is always expecting
865    // a merge deployment. The kargs code also always looks at the booted root (which
866    // is a distinct minor issue, but not super important as right now the install path
867    // doesn't use this API).
868    let (stateroot, override_kargs) = match &from {
869        MergeState::MergeDeployment(deployment) => {
870            let kargs = crate::bootc_kargs::get_kargs(sysroot, &deployment, image)?;
871            (deployment.stateroot().into(), Some(kargs))
872        }
873        MergeState::Reset { stateroot, kargs } => (stateroot.clone(), Some(kargs.clone())),
874    };
875    // Clone all the things to move to worker thread
876    let ostree = sysroot.get_ostree_cloned()?;
877    // ostree::Deployment is incorrectly !Send 😢 so convert it to an integer
878    let merge_deployment = from.as_merge_deployment();
879    let merge_deployment = merge_deployment.map(|d| d.index() as usize);
880    let ostree_commit = image.ostree_commit.to_string();
881    // GKeyFile also isn't Send! So we serialize that as a string...
882    let origin_data = origin.to_data();
883    let r = async_task_with_spinner(
884        "Deploying",
885        spawn_blocking_cancellable_flatten(move |cancellable| -> Result<_> {
886            let ostree = ostree;
887            let stateroot = Some(stateroot);
888            let mut opts = ostree::SysrootDeployTreeOpts::default();
889
890            // Set finalization lock if requested
891            opts.locked = lock_finalization;
892
893            // Because the C API expects a Vec<&str>, convert the Cmdline to string slices.
894            // The references borrow from the Cmdline, which outlives this usage.
895            let override_kargs_refs = override_kargs
896                .as_ref()
897                .map(|kargs| kargs.iter_str().collect::<Vec<_>>());
898            if let Some(kargs) = override_kargs_refs.as_ref() {
899                opts.override_kernel_argv = Some(kargs);
900            }
901
902            let deployments = ostree.deployments();
903            let merge_deployment = merge_deployment.map(|m| &deployments[m]);
904            let origin = glib::KeyFile::new();
905            origin.load_from_data(&origin_data, glib::KeyFileFlags::NONE)?;
906            let d = ostree.stage_tree_with_options(
907                stateroot.as_deref(),
908                &ostree_commit,
909                Some(&origin),
910                merge_deployment,
911                &opts,
912                Some(cancellable),
913            )?;
914            Ok(d.index())
915        }),
916    )
917    .await?;
918    // SAFETY: We must have a staged deployment
919    let ostree = sysroot.get_ostree()?;
920    let staged = ostree.staged_deployment().unwrap();
921    assert_eq!(staged.index(), r);
922    Ok(staged)
923}
924
925#[context("Generating origin")]
926fn origin_from_imageref(imgref: &ImageReference) -> Result<glib::KeyFile> {
927    let origin = glib::KeyFile::new();
928    let imgref = OstreeImageReference::from(imgref.clone());
929    origin.set_string(
930        "origin",
931        ostree_container::deploy::ORIGIN_CONTAINER,
932        imgref.to_string().as_str(),
933    );
934    Ok(origin)
935}
936
937/// The source of data for staging a new deployment
938#[derive(Debug)]
939pub(crate) enum MergeState {
940    /// Use the provided merge deployment
941    MergeDeployment(Deployment),
942    /// Don't use a merge deployment, but only this
943    /// provided initial state.
944    Reset {
945        stateroot: String,
946        kargs: CmdlineOwned,
947    },
948}
949impl MergeState {
950    /// Initialize using the default merge deployment for the given stateroot.
951    pub(crate) fn from_stateroot(sysroot: &Storage, stateroot: &str) -> Result<Self> {
952        let ostree = sysroot.get_ostree()?;
953        let merge_deployment = ostree.merge_deployment(Some(stateroot)).ok_or_else(|| {
954            anyhow::anyhow!("No merge deployment found for stateroot {stateroot}")
955        })?;
956        Ok(Self::MergeDeployment(merge_deployment))
957    }
958
959    /// Cast this to a merge deployment case.
960    pub(crate) fn as_merge_deployment(&self) -> Option<&Deployment> {
961        match self {
962            Self::MergeDeployment(d) => Some(d),
963            Self::Reset { .. } => None,
964        }
965    }
966}
967
968/// Stage (queue deployment of) a fetched container image.
969#[context("Staging")]
970pub(crate) async fn stage(
971    sysroot: &Storage,
972    from: MergeState,
973    image: &ImageState,
974    spec: &RequiredHostSpec<'_>,
975    prog: ProgressWriter,
976    lock_finalization: bool,
977) -> Result<()> {
978    // Log the staging operation to systemd journal with comprehensive upgrade information
979    const STAGE_JOURNAL_ID: &str = "8f7a2b1c3d4e5f6a7b8c9d0e1f2a3b4c";
980
981    tracing::info!(
982        message_id = STAGE_JOURNAL_ID,
983        bootc.image.reference = &spec.image.image,
984        bootc.image.transport = &spec.image.transport,
985        bootc.manifest_digest = image.manifest_digest.as_ref(),
986        "Staging image for deployment: {} (digest: {})",
987        spec.image,
988        image.manifest_digest
989    );
990
991    let mut subtask = SubTaskStep {
992        subtask: "merging".into(),
993        description: "Merging Image".into(),
994        id: "fetching".into(),
995        completed: false,
996    };
997    let mut subtasks = vec![];
998    prog.send(Event::ProgressSteps {
999        task: "staging".into(),
1000        description: "Deploying Image".into(),
1001        id: image.manifest_digest.clone().as_ref().into(),
1002        steps_cached: 0,
1003        steps: 0,
1004        steps_total: 3,
1005        subtasks: subtasks
1006            .clone()
1007            .into_iter()
1008            .chain([subtask.clone()])
1009            .collect(),
1010    })
1011    .await;
1012
1013    subtask.completed = true;
1014    subtasks.push(subtask.clone());
1015    subtask.subtask = "deploying".into();
1016    subtask.id = "deploying".into();
1017    subtask.description = "Deploying Image".into();
1018    subtask.completed = false;
1019    prog.send(Event::ProgressSteps {
1020        task: "staging".into(),
1021        description: "Deploying Image".into(),
1022        id: image.manifest_digest.clone().as_ref().into(),
1023        steps_cached: 0,
1024        steps: 1,
1025        steps_total: 3,
1026        subtasks: subtasks
1027            .clone()
1028            .into_iter()
1029            .chain([subtask.clone()])
1030            .collect(),
1031    })
1032    .await;
1033    let origin = origin_from_imageref(spec.image)?;
1034    let deployment =
1035        crate::deploy::deploy(sysroot, from, image, &origin, lock_finalization).await?;
1036
1037    subtask.completed = true;
1038    subtasks.push(subtask.clone());
1039    subtask.subtask = "bound_images".into();
1040    subtask.id = "bound_images".into();
1041    subtask.description = "Pulling Bound Images".into();
1042    subtask.completed = false;
1043    prog.send(Event::ProgressSteps {
1044        task: "staging".into(),
1045        description: "Deploying Image".into(),
1046        id: image.manifest_digest.clone().as_ref().into(),
1047        steps_cached: 0,
1048        steps: 1,
1049        steps_total: 3,
1050        subtasks: subtasks
1051            .clone()
1052            .into_iter()
1053            .chain([subtask.clone()])
1054            .collect(),
1055    })
1056    .await;
1057    crate::boundimage::pull_bound_images(sysroot, &deployment).await?;
1058
1059    subtask.completed = true;
1060    subtasks.push(subtask.clone());
1061    subtask.subtask = "cleanup".into();
1062    subtask.id = "cleanup".into();
1063    subtask.description = "Removing old images".into();
1064    subtask.completed = false;
1065    prog.send(Event::ProgressSteps {
1066        task: "staging".into(),
1067        description: "Deploying Image".into(),
1068        id: image.manifest_digest.clone().as_ref().into(),
1069        steps_cached: 0,
1070        steps: 2,
1071        steps_total: 3,
1072        subtasks: subtasks
1073            .clone()
1074            .into_iter()
1075            .chain([subtask.clone()])
1076            .collect(),
1077    })
1078    .await;
1079    crate::deploy::cleanup(sysroot).await?;
1080    println!("Queued for next boot: {:#}", spec.image);
1081    if let Some(version) = image.version.as_deref() {
1082        println!("  Version: {version}");
1083    }
1084    println!("  Digest: {}", image.manifest_digest);
1085
1086    subtask.completed = true;
1087    subtasks.push(subtask.clone());
1088    prog.send(Event::ProgressSteps {
1089        task: "staging".into(),
1090        description: "Deploying Image".into(),
1091        id: image.manifest_digest.clone().as_ref().into(),
1092        steps_cached: 0,
1093        steps: 3,
1094        steps_total: 3,
1095        subtasks: subtasks
1096            .clone()
1097            .into_iter()
1098            .chain([subtask.clone()])
1099            .collect(),
1100    })
1101    .await;
1102
1103    // Unconditionally create or update /run/reboot-required to signal a reboot is needed.
1104    // This is monitored by kured (Kubernetes Reboot Daemon).
1105    write_reboot_required(&image.manifest_digest.as_ref())?;
1106
1107    Ok(())
1108}
1109
1110/// Update the /run/reboot-required file with the image that will be active after a reboot.
1111fn write_reboot_required(image: &str) -> Result<()> {
1112    let reboot_message = format!("bootc: Reboot required for image: {}", image);
1113    let run_dir = Dir::open_ambient_dir("/run", cap_std::ambient_authority())?;
1114    run_dir
1115        .atomic_write("reboot-required", reboot_message.as_bytes())
1116        .context("Creating /run/reboot-required")?;
1117
1118    Ok(())
1119}
1120
1121/// Implementation of rollback functionality
1122pub(crate) async fn rollback(sysroot: &Storage) -> Result<()> {
1123    const ROLLBACK_JOURNAL_ID: &str = "26f3b1eb24464d12aa5e7b544a6b5468";
1124    let ostree = sysroot.get_ostree()?;
1125    let (booted_ostree, deployments, host) = crate::status::get_status_require_booted(ostree)?;
1126
1127    let new_spec = {
1128        let mut new_spec = host.spec.clone();
1129        new_spec.boot_order = new_spec.boot_order.swap();
1130        new_spec
1131    };
1132
1133    let repo = &booted_ostree.repo();
1134
1135    // Just to be sure
1136    host.spec.verify_transition(&new_spec)?;
1137
1138    let reverting = new_spec.boot_order == BootOrder::Default;
1139    if reverting {
1140        println!("notice: Reverting queued rollback state");
1141    }
1142    let rollback_status = host
1143        .status
1144        .rollback
1145        .ok_or_else(|| anyhow!("No rollback available"))?;
1146    let rollback_image = rollback_status
1147        .query_image(repo)?
1148        .ok_or_else(|| anyhow!("Rollback is not container image based"))?;
1149
1150    // Get current booted image for comparison
1151    let current_image = host
1152        .status
1153        .booted
1154        .as_ref()
1155        .and_then(|b| b.query_image(repo).ok()?);
1156
1157    tracing::info!(
1158        message_id = ROLLBACK_JOURNAL_ID,
1159        bootc.manifest_digest = rollback_image.manifest_digest.as_ref(),
1160        bootc.ostree_commit = &rollback_image.merge_commit,
1161        bootc.rollback_type = if reverting { "revert" } else { "rollback" },
1162        bootc.current_manifest_digest = current_image
1163            .as_ref()
1164            .map(|i| i.manifest_digest.as_ref())
1165            .unwrap_or("none"),
1166        "Rolling back to image: {}",
1167        rollback_image.manifest_digest
1168    );
1169    // SAFETY: If there's a rollback status, then there's a deployment
1170    let rollback_deployment = deployments.rollback.expect("rollback deployment");
1171    let new_deployments = if reverting {
1172        [booted_ostree.deployment, rollback_deployment]
1173    } else {
1174        [rollback_deployment, booted_ostree.deployment]
1175    };
1176    let new_deployments = new_deployments
1177        .into_iter()
1178        .chain(deployments.other)
1179        .collect::<Vec<_>>();
1180    tracing::debug!("Writing new deployments: {new_deployments:?}");
1181    booted_ostree
1182        .sysroot
1183        .write_deployments(&new_deployments, gio::Cancellable::NONE)?;
1184    if reverting {
1185        println!("Next boot: current deployment");
1186    } else {
1187        println!("Next boot: rollback deployment");
1188    }
1189
1190    write_reboot_required(rollback_image.manifest_digest.as_ref())?;
1191
1192    sysroot.update_mtime()?;
1193
1194    Ok(())
1195}
1196
1197fn find_newest_deployment_name(deploysdir: &Dir) -> Result<String> {
1198    let mut dirs = Vec::new();
1199    for ent in deploysdir.entries()? {
1200        let ent = ent?;
1201        if !ent.file_type()?.is_dir() {
1202            continue;
1203        }
1204        let name = ent.file_name();
1205        let Some(name) = name.to_str() else {
1206            continue;
1207        };
1208        dirs.push((name.to_owned(), ent.metadata()?.mtime()));
1209    }
1210    dirs.sort_unstable_by(|a, b| a.1.cmp(&b.1));
1211    if let Some((name, _ts)) = dirs.pop() {
1212        Ok(name)
1213    } else {
1214        anyhow::bail!("No deployment directory found")
1215    }
1216}
1217
1218// Implementation of `bootc switch --in-place`
1219pub(crate) fn switch_origin_inplace(root: &Dir, imgref: &ImageReference) -> Result<String> {
1220    // Log the in-place switch operation to systemd journal
1221    const SWITCH_INPLACE_JOURNAL_ID: &str = "3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a8b7";
1222
1223    tracing::info!(
1224        message_id = SWITCH_INPLACE_JOURNAL_ID,
1225        bootc.image.reference = &imgref.image,
1226        bootc.image.transport = &imgref.transport,
1227        bootc.switch_type = "in_place",
1228        "Performing in-place switch to image: {}",
1229        imgref
1230    );
1231
1232    // First, just create the new origin file
1233    let origin = origin_from_imageref(imgref)?;
1234    let serialized_origin = origin.to_data();
1235
1236    // Now, we can't rely on being officially booted (e.g. with the `ostree=` karg)
1237    // in a scenario like running in the anaconda %post.
1238    // Eventually, we should support a setup here where ostree-prepare-root
1239    // can officially be run to "enter" an ostree root in a supportable way.
1240    // Anyways for now, the brutal hack is to just scrape through the deployments
1241    // and find the newest one, which we will mutate.  If there's more than one,
1242    // ultimately the calling tooling should be fixed to set things up correctly.
1243
1244    let mut ostree_deploys = root.open_dir("sysroot/ostree/deploy")?.entries()?;
1245    let deploydir = loop {
1246        if let Some(ent) = ostree_deploys.next() {
1247            let ent = ent?;
1248            if !ent.file_type()?.is_dir() {
1249                continue;
1250            }
1251            tracing::debug!("Checking {:?}", ent.file_name());
1252            let child_dir = ent
1253                .open_dir()
1254                .with_context(|| format!("Opening dir {:?}", ent.file_name()))?;
1255            if let Some(d) = child_dir.open_dir_optional("deploy")? {
1256                break d;
1257            }
1258        } else {
1259            anyhow::bail!("Failed to find a deployment");
1260        }
1261    };
1262    let newest_deployment = find_newest_deployment_name(&deploydir)?;
1263    let origin_path = format!("{newest_deployment}.origin");
1264    if !deploydir.try_exists(&origin_path)? {
1265        tracing::warn!("No extant origin for {newest_deployment}");
1266    }
1267    deploydir
1268        .atomic_write(&origin_path, serialized_origin.as_bytes())
1269        .context("Writing origin")?;
1270    Ok(newest_deployment)
1271}
1272
1273/// A workaround for <https://github.com/ostreedev/ostree/issues/3193>
1274/// as generated by anaconda.
1275#[context("Updating /etc/fstab for anaconda+composefs")]
1276pub(crate) fn fixup_etc_fstab(root: &Dir) -> Result<()> {
1277    let fstab_path = "etc/fstab";
1278    // Read the old file
1279    let fd = root
1280        .open(fstab_path)
1281        .with_context(|| format!("Opening {fstab_path}"))
1282        .map(std::io::BufReader::new)?;
1283
1284    // Helper function to possibly change a line from /etc/fstab.
1285    // Returns Ok(true) if we made a change (and we wrote the modified line)
1286    // otherwise returns Ok(false) and the caller should write the original line.
1287    fn edit_fstab_line(line: &str, mut w: impl Write) -> Result<bool> {
1288        if line.starts_with('#') {
1289            return Ok(false);
1290        }
1291        let parts = line.split_ascii_whitespace().collect::<Vec<_>>();
1292
1293        let path_idx = 1;
1294        let options_idx = 3;
1295        let (&path, &options) = match (parts.get(path_idx), parts.get(options_idx)) {
1296            (None, _) => {
1297                tracing::debug!("No path in entry: {line}");
1298                return Ok(false);
1299            }
1300            (_, None) => {
1301                tracing::debug!("No options in entry: {line}");
1302                return Ok(false);
1303            }
1304            (Some(p), Some(o)) => (p, o),
1305        };
1306        // If this is not the root, we're not matching on it
1307        if path != "/" {
1308            return Ok(false);
1309        }
1310        // If options already contains `ro`, nothing to do
1311        if options.split(',').any(|s| s == "ro") {
1312            return Ok(false);
1313        }
1314
1315        writeln!(w, "# {}", crate::generator::BOOTC_EDITED_STAMP)?;
1316
1317        // SAFETY: we unpacked the options before.
1318        // This adds `ro` to the option list
1319        assert!(!options.is_empty()); // Split wouldn't have turned this up if it was empty
1320        let options = format!("{options},ro");
1321        for (i, part) in parts.into_iter().enumerate() {
1322            // TODO: would obviously be nicer to preserve whitespace...but...eh.
1323            if i > 0 {
1324                write!(w, " ")?;
1325            }
1326            if i == options_idx {
1327                write!(w, "{options}")?;
1328            } else {
1329                write!(w, "{part}")?
1330            }
1331        }
1332        // And add the trailing newline
1333        writeln!(w)?;
1334        Ok(true)
1335    }
1336
1337    // Read the input, and atomically write a modified version
1338    root.atomic_replace_with(fstab_path, move |mut w| -> Result<()> {
1339        for line in fd.lines() {
1340            let line = line?;
1341            if !edit_fstab_line(&line, &mut w)? {
1342                writeln!(w, "{line}")?;
1343            }
1344        }
1345        Ok(())
1346    })
1347    .context("Replacing /etc/fstab")?;
1348
1349    println!("Updated /etc/fstab to add `ro` for `/`");
1350    Ok(())
1351}
1352
1353#[cfg(test)]
1354mod tests {
1355    use super::*;
1356
1357    #[test]
1358    fn test_new_proxy_config_user_agent() {
1359        let config = new_proxy_config();
1360        let prefix = config
1361            .user_agent_prefix
1362            .expect("user_agent_prefix should be set");
1363        assert!(
1364            prefix.starts_with("bootc/"),
1365            "User agent should start with bootc/"
1366        );
1367        // Verify the version is present (not just "bootc/")
1368        assert!(
1369            prefix.len() > "bootc/".len(),
1370            "Version should be present after bootc/"
1371        );
1372    }
1373
1374    #[test]
1375    fn test_switch_inplace() -> Result<()> {
1376        use cap_std::fs::DirBuilderExt;
1377
1378        let td = cap_std_ext::cap_tempfile::TempDir::new(cap_std::ambient_authority())?;
1379        let mut builder = cap_std::fs::DirBuilder::new();
1380        let builder = builder.recursive(true).mode(0o755);
1381        let deploydir = "sysroot/ostree/deploy/default/deploy";
1382        let target_deployment =
1383            "af36eb0086bb55ac601600478c6168f834288013d60f8870b7851f44bf86c3c5.0";
1384        td.ensure_dir_with(
1385            format!("sysroot/ostree/deploy/default/deploy/{target_deployment}"),
1386            builder,
1387        )?;
1388        let deploydir = &td.open_dir(deploydir)?;
1389        let orig_imgref = ImageReference {
1390            image: "quay.io/exampleos/original:sometag".into(),
1391            transport: "registry".into(),
1392            signature: None,
1393        };
1394        {
1395            let origin = origin_from_imageref(&orig_imgref)?;
1396            deploydir.atomic_write(
1397                format!("{target_deployment}.origin"),
1398                origin.to_data().as_bytes(),
1399            )?;
1400        }
1401
1402        let target_imgref = ImageReference {
1403            image: "quay.io/someother/otherimage:latest".into(),
1404            transport: "registry".into(),
1405            signature: None,
1406        };
1407
1408        let replaced = switch_origin_inplace(&td, &target_imgref).unwrap();
1409        assert_eq!(replaced, target_deployment);
1410        Ok(())
1411    }
1412
1413    #[test]
1414    fn test_fixup_etc_fstab_default() -> Result<()> {
1415        let tempdir = cap_std_ext::cap_tempfile::tempdir(cap_std::ambient_authority())?;
1416        let default = "UUID=f7436547-20ac-43cb-aa2f-eac9632183f6 /boot auto ro 0 0\n";
1417        tempdir.create_dir_all("etc")?;
1418        tempdir.atomic_write("etc/fstab", default)?;
1419        fixup_etc_fstab(&tempdir).unwrap();
1420        assert_eq!(tempdir.read_to_string("etc/fstab")?, default);
1421        Ok(())
1422    }
1423
1424    #[test]
1425    fn test_fixup_etc_fstab_multi() -> Result<()> {
1426        let tempdir = cap_std_ext::cap_tempfile::tempdir(cap_std::ambient_authority())?;
1427        let default = "UUID=f7436547-20ac-43cb-aa2f-eac9632183f6 /boot auto ro 0 0\n\
1428UUID=6907-17CA          /boot/efi               vfat    umask=0077,shortname=winnt 0 2\n";
1429        tempdir.create_dir_all("etc")?;
1430        tempdir.atomic_write("etc/fstab", default)?;
1431        fixup_etc_fstab(&tempdir).unwrap();
1432        assert_eq!(tempdir.read_to_string("etc/fstab")?, default);
1433        Ok(())
1434    }
1435
1436    #[test]
1437    fn test_fixup_etc_fstab_ro() -> Result<()> {
1438        let tempdir = cap_std_ext::cap_tempfile::tempdir(cap_std::ambient_authority())?;
1439        let default = "UUID=f7436547-20ac-43cb-aa2f-eac9632183f6 /boot auto ro 0 0\n\
1440UUID=1eef9f42-40e3-4bd8-ae20-e9f2325f8b52 /                     xfs   ro 0 0\n\
1441UUID=6907-17CA          /boot/efi               vfat    umask=0077,shortname=winnt 0 2\n";
1442        tempdir.create_dir_all("etc")?;
1443        tempdir.atomic_write("etc/fstab", default)?;
1444        fixup_etc_fstab(&tempdir).unwrap();
1445        assert_eq!(tempdir.read_to_string("etc/fstab")?, default);
1446        Ok(())
1447    }
1448
1449    #[test]
1450    fn test_fixup_etc_fstab_rw() -> Result<()> {
1451        let tempdir = cap_std_ext::cap_tempfile::tempdir(cap_std::ambient_authority())?;
1452        // This case uses `defaults`
1453        let default = "UUID=f7436547-20ac-43cb-aa2f-eac9632183f6 /boot auto ro 0 0\n\
1454UUID=1eef9f42-40e3-4bd8-ae20-e9f2325f8b52 /                     xfs   defaults 0 0\n\
1455UUID=6907-17CA          /boot/efi               vfat    umask=0077,shortname=winnt 0 2\n";
1456        let modified = "UUID=f7436547-20ac-43cb-aa2f-eac9632183f6 /boot auto ro 0 0\n\
1457# Updated by bootc-fstab-edit.service\n\
1458UUID=1eef9f42-40e3-4bd8-ae20-e9f2325f8b52 / xfs defaults,ro 0 0\n\
1459UUID=6907-17CA          /boot/efi               vfat    umask=0077,shortname=winnt 0 2\n";
1460        tempdir.create_dir_all("etc")?;
1461        tempdir.atomic_write("etc/fstab", default)?;
1462        fixup_etc_fstab(&tempdir).unwrap();
1463        assert_eq!(tempdir.read_to_string("etc/fstab")?, modified);
1464        Ok(())
1465    }
1466    #[test]
1467    fn test_check_disk_space_inner() -> Result<()> {
1468        let td = cap_std_ext::cap_tempfile::TempDir::new(cap_std::ambient_authority())?;
1469        let imgref = ImageReference {
1470            image: "quay.io/exampleos/exampleos:latest".into(),
1471            transport: "registry".into(),
1472            signature: None,
1473        };
1474
1475        // 0 bytes needed always passes
1476        check_disk_space_inner(&*td, 0, 0, &imgref)?;
1477
1478        // u64::MAX bytes needed always fails
1479        assert!(check_disk_space_inner(&*td, u64::MAX, 0, &imgref).is_err());
1480
1481        // With min_free consuming all usable space, even a tiny fetch fails
1482        assert!(check_disk_space_inner(&*td, 1, u64::MAX, &imgref).is_err());
1483
1484        Ok(())
1485    }
1486}