Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions crates/etc-merge/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ use cap_std_ext::dirext::CapStdExtDirExt;
use composefs::fsverity::{FsVerityHashValue, Sha256HashValue, Sha512HashValue};
use composefs::generic_tree::{Directory, Inode, Leaf, LeafContent, Stat};
use composefs::tree::ImageError;
use rustix::fs::{AtFlags, Gid, Uid, XattrFlags, lgetxattr, llistxattr, lsetxattr, readlinkat};
use rustix::fs::{
AtFlags, Gid, Uid, XattrFlags, lgetxattr, llistxattr, lsetxattr, readlinkat, symlinkat,
};

/// Metadata associated with a file, directory, or symlink entry.
#[derive(Debug)]
Expand Down Expand Up @@ -627,9 +629,8 @@ fn merge_leaf(
.context(format!("Deleting {file:?}"))?;

if let Some(target) = symlink {
new_etc_fd
.symlink(target.as_ref(), &file)
.context(format!("Creating symlink {file:?}"))?;
// Using rustix's symlinkat here as we might have absolute symlinks which clash with ambient_authority
symlinkat(&**target, new_etc_fd, file).context(format!("Creating symlink {file:?}"))?;
} else {
current_etc_fd
.copy(&file, new_etc_fd, &file)
Expand Down
3 changes: 2 additions & 1 deletion crates/initramfs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,9 @@ pub fn mount_at_wrapper(
.with_context(|| format!("Mounting at path {path:?}"))
}

/// Wrapper around [`rustix::openat`]
#[context("Opening dir {name:?}")]
fn open_dir(dirfd: impl AsFd, name: impl AsRef<Path> + Debug) -> Result<OwnedFd> {
pub fn open_dir(dirfd: impl AsFd, name: impl AsRef<Path> + Debug) -> Result<OwnedFd> {
let res = openat(
dirfd,
name.as_ref(),
Expand Down
35 changes: 17 additions & 18 deletions crates/lib/src/bootc_composefs/boot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,19 @@ pub fn get_esp_partition(device: &str) -> Result<(String, Option<String>)> {
Ok((esp.node, esp.uuid))
}

pub fn get_sysroot_parent_dev() -> Result<String> {
let sysroot = Utf8PathBuf::from("/sysroot");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This relates to #1190 (comment) in that what I think would help us overall is to pass around a Storage instance that has a canonical opened fd for the sysroot instead of having a lot of places that load it ambiently.

The biggest reason to do this is that it will work the same way at install time, where we're actually operating on a different mount point and not /sysroot.


let fsinfo = inspect_filesystem(&sysroot)?;
let parent_devices = find_parent_devices(&fsinfo.source)?;

let Some(parent) = parent_devices.into_iter().next() else {
anyhow::bail!("Could not find parent device for mountpoint /sysroot");
};

return Ok(parent);
}

/// Compute SHA256Sum of VMlinuz + Initrd
///
/// # Arguments
Expand Down Expand Up @@ -310,20 +323,12 @@ pub(crate) fn setup_composefs_bls_boot(
}

BootSetupType::Upgrade((fs, host)) => {
let sysroot = Utf8PathBuf::from("/sysroot");

let fsinfo = inspect_filesystem(&sysroot)?;
let parent_devices = find_parent_devices(&fsinfo.source)?;

let Some(parent) = parent_devices.into_iter().next() else {
anyhow::bail!("Could not find parent device for mountpoint /sysroot");
};

let sysroot_parent = get_sysroot_parent_dev()?;
let bootloader = host.require_composefs_booted()?.bootloader.clone();

(
Utf8PathBuf::from("/sysroot"),
get_esp_partition(&parent)?.0,
get_esp_partition(&sysroot_parent)?.0,
[
format!("root=UUID={DPS_UUID}"),
RW_KARG.to_string(),
Expand Down Expand Up @@ -554,15 +559,9 @@ pub(crate) fn setup_composefs_uki_boot(

BootSetupType::Upgrade(..) => {
let sysroot = Utf8PathBuf::from("/sysroot");
let sysroot_parent = get_sysroot_parent_dev()?;

let fsinfo = inspect_filesystem(&sysroot)?;
let parent_devices = find_parent_devices(&fsinfo.source)?;

let Some(parent) = parent_devices.into_iter().next() else {
anyhow::bail!("Could not find parent device for mountpoint /sysroot");
};

(sysroot, get_esp_partition(&parent)?.0, None)
(sysroot, get_esp_partition(&sysroot_parent)?.0, None)
}
};

Expand Down
129 changes: 129 additions & 0 deletions crates/lib/src/bootc_composefs/finalize.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
use std::path::Path;

use crate::bootc_composefs::boot::{get_esp_partition, get_sysroot_parent_dev, BootType};
use crate::bootc_composefs::rollback::{rename_exchange_bls_entries, rename_exchange_user_cfg};
use crate::spec::Bootloader;
use crate::{
bootc_composefs::status::composefs_deployment_status, composefs_consts::STATE_DIR_ABS,
};
use anyhow::{Context, Result};
use bootc_initramfs_setup::{mount_composefs_image, open_dir};
use bootc_mount::tempmount::TempMount;
use cap_std_ext::cap_std::{ambient_authority, fs::Dir};
use cap_std_ext::dirext::CapStdExtDirExt;
use etc_merge::{compute_diff, merge, traverse_etc};
use rustix::fs::{fsync, renameat, CWD};
use rustix::path::Arg;

use fn_error_context::context;

pub(crate) async fn composefs_native_finalize() -> Result<()> {
let host = composefs_deployment_status().await?;

let booted_composefs = host.require_composefs_booted()?;

let Some(staged_depl) = host.status.staged.as_ref() else {
tracing::debug!("No staged deployment found");
return Ok(());
};

let staged_composefs = staged_depl.composefs.as_ref().ok_or(anyhow::anyhow!(
"Staged deployment is not a composefs deployment"
))?;

// Mount the booted EROFS image to get pristine etc
let sysroot = open_dir(CWD, "/sysroot")?;
let composefs_fd = mount_composefs_image(&sysroot, &booted_composefs.verity, false)?;

let erofs_tmp_mnt = TempMount::mount_fd(&composefs_fd)?;

// Perform the /etc merge
let pristine_etc =
Dir::open_ambient_dir(erofs_tmp_mnt.dir.path().join("etc"), ambient_authority())?;
let current_etc = Dir::open_ambient_dir("/etc", ambient_authority())?;

let new_etc_path = Path::new(STATE_DIR_ABS)
.join(&staged_composefs.verity)
.join("etc");

let new_etc = Dir::open_ambient_dir(new_etc_path, ambient_authority())?;

let (pristine_files, current_files, new_files) =
traverse_etc(&pristine_etc, &current_etc, &new_etc)?;

let diff = compute_diff(&pristine_files, &current_files)?;
merge(&current_etc, &current_files, &new_etc, &new_files, diff)?;

// Unmount EROFS
drop(erofs_tmp_mnt);

let sysroot_parent = get_sysroot_parent_dev()?;
// NOTE: Assumption here that ESP will always be present
let (esp_part, ..) = get_esp_partition(&sysroot_parent)?;

let esp_mount = TempMount::mount_dev(&esp_part)?;
let boot_dir = Dir::open_ambient_dir("/sysroot/boot", ambient_authority())
.context("Opening sysroot/boot")?;

// NOTE: Assuming here we won't have two bootloaders at the same time
match booted_composefs.bootloader {
Bootloader::Grub => match staged_composefs.boot_type {
BootType::Bls => {
let entries_dir = boot_dir.open_dir("loader")?;
rename_exchange_bls_entries(&entries_dir)?;
}
BootType::Uki => finalize_staged_grub_uki(&esp_mount.fd, &boot_dir)?,
},

Bootloader::Systemd => match staged_composefs.boot_type {
BootType::Bls => {
let entries_dir = esp_mount.fd.open_dir("loader")?;
rename_exchange_bls_entries(&entries_dir)?;
}
BootType::Uki => rename_staged_uki_entries(&esp_mount.fd)?,
},
};

Ok(())
}

#[context("Grub: Finalizing staged UKI")]
fn finalize_staged_grub_uki(esp_mount: &Dir, boot_fd: &Dir) -> Result<()> {
rename_staged_uki_entries(esp_mount)?;

let entries_dir = boot_fd.open_dir("grub2")?;
rename_exchange_user_cfg(&entries_dir)?;

let entries_dir = entries_dir.reopen_as_ownedfd()?;
fsync(entries_dir).context("fsync")?;

Ok(())
}

#[context("Renaming staged UKI entries")]
fn rename_staged_uki_entries(esp_mount: &Dir) -> Result<()> {
for entry in esp_mount.entries()? {
let entry = entry?;

let filename = entry.file_name();
let filename = filename.as_str()?;

if !filename.ends_with(".staged") {
continue;
}

renameat(
&esp_mount,
filename,
&esp_mount,
// SAFETY: We won't reach here if not for the above condition
filename.strip_suffix(".staged").unwrap(),
)
.context("Renaming {filename}")?;
}

let esp_mount = esp_mount.reopen_as_ownedfd()?;
fsync(esp_mount).context("fsync")?;

Ok(())
}
1 change: 1 addition & 0 deletions crates/lib/src/bootc_composefs/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub(crate) mod boot;
pub(crate) mod finalize;
pub(crate) mod repo;
pub(crate) mod rollback;
pub(crate) mod state;
Expand Down
107 changes: 55 additions & 52 deletions crates/lib/src/bootc_composefs/rollback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,60 @@ use crate::bootc_composefs::status::{composefs_deployment_status, get_sorted_bls
use crate::{
bootc_composefs::{boot::get_efi_uuid_source, status::get_sorted_uki_boot_entries},
composefs_consts::{
BOOT_LOADER_ENTRIES, ROLLBACK_BOOT_LOADER_ENTRIES, USER_CFG, USER_CFG_ROLLBACK,
BOOT_LOADER_ENTRIES, STAGED_BOOT_LOADER_ENTRIES, USER_CFG, USER_CFG_STAGED,
},
spec::BootOrder,
};

pub(crate) fn rename_exchange_user_cfg(entries_dir: &Dir) -> Result<()> {
tracing::debug!("Atomically exchanging {USER_CFG_STAGED} and {USER_CFG}");
renameat_with(
&entries_dir,
USER_CFG_STAGED,
&entries_dir,
USER_CFG,
RenameFlags::EXCHANGE,
)
.context("renameat")?;

tracing::debug!("Removing {USER_CFG_STAGED}");
rustix::fs::unlinkat(&entries_dir, USER_CFG_STAGED, AtFlags::empty()).context("unlinkat")?;

tracing::debug!("Syncing to disk");
let entries_dir = entries_dir
.reopen_as_ownedfd()
.context(format!("Reopening entries dir as owned fd"))?;

fsync(entries_dir).context(format!("fsync entries dir"))?;

Ok(())
}

pub(crate) fn rename_exchange_bls_entries(entries_dir: &Dir) -> Result<()> {
tracing::debug!("Atomically exchanging {STAGED_BOOT_LOADER_ENTRIES} and {BOOT_LOADER_ENTRIES}");
renameat_with(
&entries_dir,
STAGED_BOOT_LOADER_ENTRIES,
&entries_dir,
BOOT_LOADER_ENTRIES,
RenameFlags::EXCHANGE,
)
.context("renameat")?;

tracing::debug!("Removing {STAGED_BOOT_LOADER_ENTRIES}");
rustix::fs::unlinkat(&entries_dir, STAGED_BOOT_LOADER_ENTRIES, AtFlags::REMOVEDIR)
.context("unlinkat")?;

tracing::debug!("Syncing to disk");
let entries_dir = entries_dir
.reopen_as_ownedfd()
.with_context(|| format!("Reopening /sysroot/boot/loader as owned fd"))?;

fsync(entries_dir).context("fsync")?;

Ok(())
}

#[context("Rolling back UKI")]
pub(crate) fn rollback_composefs_uki() -> Result<()> {
let user_cfg_path = PathBuf::from("/sysroot/boot/grub2");
Expand Down Expand Up @@ -45,31 +94,10 @@ pub(crate) fn rollback_composefs_uki() -> Result<()> {
.with_context(|| format!("Opening {user_cfg_path:?}"))?;

entries_dir
.atomic_write(USER_CFG_ROLLBACK, buffer)
.with_context(|| format!("Writing to {USER_CFG_ROLLBACK}"))?;

tracing::debug!("Atomically exchanging for {USER_CFG_ROLLBACK} and {USER_CFG}");
renameat_with(
&entries_dir,
USER_CFG_ROLLBACK,
&entries_dir,
USER_CFG,
RenameFlags::EXCHANGE,
)
.context("renameat")?;

tracing::debug!("Removing {USER_CFG_ROLLBACK}");
rustix::fs::unlinkat(&entries_dir, USER_CFG_ROLLBACK, AtFlags::empty()).context("unlinkat")?;

tracing::debug!("Syncing to disk");
fsync(
entries_dir
.reopen_as_ownedfd()
.with_context(|| format!("Reopening {user_cfg_path:?} as owned fd"))?,
)
.with_context(|| format!("fsync {user_cfg_path:?}"))?;
.atomic_write(USER_CFG_STAGED, buffer)
.with_context(|| format!("Writing to {USER_CFG_STAGED}"))?;

Ok(())
rename_exchange_user_cfg(&entries_dir)
}

#[context("Rolling back BLS")]
Expand All @@ -93,9 +121,7 @@ pub(crate) fn rollback_composefs_bls() -> Result<()> {
assert!(all_configs.len() == 2);

// Write these
let dir_path = PathBuf::from(format!(
"/sysroot/boot/loader/{ROLLBACK_BOOT_LOADER_ENTRIES}",
));
let dir_path = PathBuf::from(format!("/sysroot/boot/loader/{STAGED_BOOT_LOADER_ENTRIES}",));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not new but we should centralize boot/loader path handling at some point

create_dir_all(&dir_path).with_context(|| format!("Failed to create dir: {dir_path:?}"))?;

let rollback_entries_dir =
Expand Down Expand Up @@ -124,30 +150,7 @@ pub(crate) fn rollback_composefs_bls() -> Result<()> {
let dir = Dir::open_ambient_dir("/sysroot/boot/loader", cap_std::ambient_authority())
.context("Opening loader dir")?;

tracing::debug!(
"Atomically exchanging for {ROLLBACK_BOOT_LOADER_ENTRIES} and {BOOT_LOADER_ENTRIES}"
);
renameat_with(
&dir,
ROLLBACK_BOOT_LOADER_ENTRIES,
&dir,
BOOT_LOADER_ENTRIES,
RenameFlags::EXCHANGE,
)
.context("renameat")?;

tracing::debug!("Removing {ROLLBACK_BOOT_LOADER_ENTRIES}");
rustix::fs::unlinkat(&dir, ROLLBACK_BOOT_LOADER_ENTRIES, AtFlags::empty())
.context("unlinkat")?;

tracing::debug!("Syncing to disk");
fsync(
dir.reopen_as_ownedfd()
.with_context(|| format!("Reopening /sysroot/boot/loader as owned fd"))?,
)
.context("fsync")?;

Ok(())
rename_exchange_bls_entries(&dir)
}

#[context("Rolling back composefs")]
Expand Down
Loading