Skip to content

Commit 72159e6

Browse files
cgwaltersomertuc
authored andcommitted
Add support for --replace-mode=alongside for ostree target
Ironically our support for `--replace-mode=alongside` breaks when we're targeting an already extant ostree host, because when we first blow away the `/boot` directory, this means the ostree stack loses its knowledge that we're in a booted deployment, and will attempt to GC it... ostreedev/ostree-rs-ext@8fa019b is a key part of the fix for that. However, a notable improvement we can do here is to grow this whole thing into a real "factory reset" mode, and this will be a compelling answer to coreos/fedora-coreos-tracker#399 To implement this though we need to support configuring the stateroot and not just hardcode `default`. Signed-off-by: Omer Tuchfeld <omer@tuchfeld.dev>
1 parent c1ac763 commit 72159e6

File tree

4 files changed

+145
-22
lines changed

4 files changed

+145
-22
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ lto = "yes"
2020
[workspace.dependencies]
2121
anyhow = "1.0.82"
2222
camino = "1.1.6"
23-
cap-std-ext = "4.0.2"
23+
cap-std-ext = "4.0.3"
2424
chrono = { version = "0.4.38", default-features = false }
2525
clap = "4.5.4"
2626
clap_mangen = { version = "0.2.20" }

lib/src/install.rs

Lines changed: 75 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ use std::str::FromStr;
2020
use std::sync::Arc;
2121
use std::time::Duration;
2222

23-
use anyhow::Ok;
2423
use anyhow::{anyhow, Context, Result};
24+
use anyhow::{ensure, Ok};
2525
use bootc_utils::CommandRunExt;
2626
use camino::Utf8Path;
2727
use camino::Utf8PathBuf;
@@ -576,26 +576,40 @@ pub(crate) fn print_configuration() -> Result<()> {
576576
}
577577

578578
#[context("Creating ostree deployment")]
579-
async fn initialize_ostree_root(state: &State, root_setup: &RootSetup) -> Result<Storage> {
579+
async fn initialize_ostree_root(state: &State, root_setup: &RootSetup) -> Result<(Storage, bool)> {
580580
let sepolicy = state.load_policy()?;
581581
let sepolicy = sepolicy.as_ref();
582582
// Load a fd for the mounted target physical root
583583
let rootfs_dir = &root_setup.rootfs_fd;
584584
let rootfs = root_setup.rootfs.as_path();
585585
let cancellable = gio::Cancellable::NONE;
586586

587+
let stateroot = state.stateroot();
588+
589+
let has_ostree = rootfs_dir.try_exists("ostree/repo")?;
590+
if !has_ostree {
591+
Task::new_and_run(
592+
"Initializing ostree layout",
593+
"ostree",
594+
["admin", "init-fs", "--modern", rootfs.as_str()],
595+
)?;
596+
} else {
597+
println!("Reusing extant ostree layout");
598+
599+
let path = ".".into();
600+
let _ = crate::utils::open_dir_remount_rw(rootfs_dir, path)
601+
.context("remounting target as read-write")?;
602+
crate::utils::remove_immutability(rootfs_dir, path)?;
603+
604+
let path = "sysroot".into();
605+
let _ = crate::utils::open_dir_remount_rw(rootfs_dir, path)
606+
.context("remounting target sysroot as read-write")?;
607+
}
608+
587609
// Ensure that the physical root is labeled.
588610
// Another implementation: https://github.com/coreos/coreos-assembler/blob/3cd3307904593b3a131b81567b13a4d0b6fe7c90/src/create_disk.sh#L295
589611
crate::lsm::ensure_dir_labeled(rootfs_dir, "", Some("/".into()), 0o755.into(), sepolicy)?;
590612

591-
let stateroot = state.stateroot();
592-
593-
Task::new_and_run(
594-
"Initializing ostree layout",
595-
"ostree",
596-
["admin", "init-fs", "--modern", rootfs.as_str()],
597-
)?;
598-
599613
// And also label /boot AKA xbootldr, if it exists
600614
let bootdir = rootfs.join("boot");
601615
if bootdir.try_exists()? {
@@ -619,6 +633,11 @@ async fn initialize_ostree_root(state: &State, root_setup: &RootSetup) -> Result
619633
let sysroot = ostree::Sysroot::new(Some(&gio::File::for_path(rootfs)));
620634
sysroot.load(cancellable)?;
621635

636+
let stateroot_exists = rootfs_dir.try_exists(format!("ostree/deploy/{stateroot}"))?;
637+
ensure!(
638+
!stateroot_exists,
639+
"Cannot redeploy over extant stateroot {stateroot}"
640+
);
622641
sysroot
623642
.init_osname(stateroot, cancellable)
624643
.context("initializing stateroot")?;
@@ -649,14 +668,15 @@ async fn initialize_ostree_root(state: &State, root_setup: &RootSetup) -> Result
649668
let sysroot = ostree::Sysroot::new(Some(&gio::File::for_path(rootfs)));
650669
sysroot.load(cancellable)?;
651670
let sysroot = SysrootLock::new_from_sysroot(&sysroot).await?;
652-
Storage::new(sysroot, &temp_run)
671+
Ok((Storage::new(sysroot, &temp_run)?, has_ostree))
653672
}
654673

655674
#[context("Creating ostree deployment")]
656675
async fn install_container(
657676
state: &State,
658677
root_setup: &RootSetup,
659678
sysroot: &ostree::Sysroot,
679+
has_ostree: bool,
660680
) -> Result<(ostree::Deployment, InstallAleph)> {
661681
let sepolicy = state.load_policy()?;
662682
let sepolicy = sepolicy.as_ref();
@@ -749,6 +769,7 @@ async fn install_container(
749769
options.kargs = Some(kargs.as_slice());
750770
options.target_imgref = Some(&state.target_imgref);
751771
options.proxy_cfg = proxy_cfg;
772+
options.no_clean = has_ostree;
752773
let imgstate = crate::utils::async_task_with_spinner(
753774
"Deploying container image",
754775
ostree_container::deploy::deploy(&sysroot, stateroot, &src_imageref, Some(options)),
@@ -1295,10 +1316,11 @@ async fn install_with_sysroot(
12951316
sysroot: &Storage,
12961317
boot_uuid: &str,
12971318
bound_images: &[crate::boundimage::ResolvedBoundImage],
1319+
has_ostree: bool,
12981320
) -> Result<()> {
12991321
// And actually set up the container in that root, returning a deployment and
13001322
// the aleph state (see below).
1301-
let (_deployment, aleph) = install_container(state, rootfs, &sysroot).await?;
1323+
let (_deployment, aleph) = install_container(state, rootfs, &sysroot, has_ostree).await?;
13021324
// Write the aleph data that captures the system state at the time of provisioning for aid in future debugging.
13031325
rootfs
13041326
.rootfs_fd
@@ -1359,6 +1381,12 @@ async fn install_to_filesystem_impl(state: &State, rootfs: &mut RootSetup) -> Re
13591381
.ok_or_else(|| anyhow!("No uuid for boot/root"))?;
13601382
tracing::debug!("boot uuid={boot_uuid}");
13611383

1384+
// If we're doing an alongside install, then the /dev bootupd sees needs to be the host's.
1385+
ensure!(
1386+
crate::mount::is_same_as_host(Utf8Path::new("/dev"))?,
1387+
"Missing /dev mount to host /dev"
1388+
);
1389+
13621390
let bound_images = if state.config_opts.skip_bound_images {
13631391
Vec::new()
13641392
} else {
@@ -1379,8 +1407,16 @@ async fn install_to_filesystem_impl(state: &State, rootfs: &mut RootSetup) -> Re
13791407

13801408
// Initialize the ostree sysroot (repo, stateroot, etc.)
13811409
{
1382-
let sysroot = initialize_ostree_root(state, rootfs).await?;
1383-
install_with_sysroot(state, rootfs, &sysroot, &boot_uuid, &bound_images).await?;
1410+
let (sysroot, has_ostree) = initialize_ostree_root(state, rootfs).await?;
1411+
install_with_sysroot(
1412+
state,
1413+
rootfs,
1414+
&sysroot,
1415+
&boot_uuid,
1416+
&bound_images,
1417+
has_ostree,
1418+
)
1419+
.await?;
13841420
// We must drop the sysroot here in order to close any open file
13851421
// descriptors.
13861422
}
@@ -1521,7 +1557,8 @@ fn remove_all_in_dir_no_xdev(d: &Dir) -> Result<()> {
15211557

15221558
#[context("Removing boot directory content")]
15231559
fn clean_boot_directories(rootfs: &Dir) -> Result<()> {
1524-
let bootdir = rootfs.open_dir(BOOT).context("Opening /boot")?;
1560+
let bootdir =
1561+
crate::utils::open_dir_remount_rw(rootfs, BOOT.into()).context("Opening /boot")?;
15251562
// This should not remove /boot/efi note.
15261563
remove_all_in_dir_no_xdev(&bootdir)?;
15271564
if ARCH_USES_EFI {
@@ -1612,12 +1649,35 @@ pub(crate) async fn install_to_filesystem(
16121649
if !st.is_dir() {
16131650
anyhow::bail!("Not a directory: {root_path}");
16141651
}
1652+
1653+
let inspect = crate::mount::inspect_filesystem(&fsopts.root_path)?;
1654+
1655+
let alternative_root = fsopts.root_path.join("sysroot");
1656+
let root_path = match inspect.fstype.as_str() {
1657+
// Our target filesystem is an overlay, the true root is in `/sysroot`
1658+
"overlay" => {
1659+
tracing::debug!(
1660+
"Overlay filesystem detected, using {alternative_root} instead of {root_path} as target root"
1661+
);
1662+
&alternative_root
1663+
}
1664+
_ => root_path,
1665+
};
16151666
let rootfs_fd = Dir::open_ambient_dir(root_path, cap_std::ambient_authority())
16161667
.with_context(|| format!("Opening target root directory {root_path}"))?;
1668+
1669+
tracing::debug!("Root filesystem: {root_path}");
1670+
16171671
if let Some(false) = ostree_ext::mountutil::is_mountpoint(&rootfs_fd, ".")? {
16181672
anyhow::bail!("Not a mountpoint: {root_path}");
16191673
}
16201674

1675+
let fsopts = {
1676+
let mut fsopts = fsopts.clone();
1677+
fsopts.root_path = root_path.clone();
1678+
fsopts
1679+
};
1680+
16211681
// Gather global state, destructuring the provided options.
16221682
// IMPORTANT: We might re-execute the current process in this function (for SELinux among other things)
16231683
// IMPORTANT: and hence anything that is done before MUST BE IDEMPOTENT.

lib/src/utils.rs

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@ use std::process::Command;
55
use std::time::Duration;
66

77
use anyhow::{Context, Result};
8-
use cap_std_ext::cap_std::fs::Dir;
8+
use camino::Utf8Path;
9+
use cap_std_ext::dirext::CapStdExtDirExt;
10+
use cap_std_ext::{cap_std::fs::Dir, prelude::CapStdExtCommandExt};
11+
use fn_error_context::context;
912
use indicatif::HumanDuration;
1013
use libsystemd::logging::journal_print;
1114
use ostree::glib;
@@ -57,6 +60,39 @@ pub(crate) fn find_mount_option<'a>(
5760
.next()
5861
}
5962

63+
/// Given a target directory, if it's a read-only mount, then remount it writable
64+
#[context("Opening {target} with writable mount")]
65+
#[cfg(feature = "install")]
66+
pub(crate) fn open_dir_remount_rw(root: &Dir, target: &Utf8Path) -> Result<Dir> {
67+
if matches!(root.is_mountpoint(target), Ok(Some(true))) {
68+
tracing::debug!("Target {target} is a mountpoint, remounting rw");
69+
let st = Command::new("mount")
70+
.args(["-o", "remount,rw", target.as_str()])
71+
.cwd_dir(root.try_clone()?)
72+
.status()?;
73+
74+
anyhow::ensure!(st.success(), "Failed to remount: {st:?}");
75+
}
76+
root.open_dir(target).map_err(anyhow::Error::new)
77+
}
78+
79+
/// Given a target path, remove its immutability if present
80+
#[context("Removing immutable flag from {target}")]
81+
#[cfg(feature = "install")]
82+
pub(crate) fn remove_immutability(root: &Dir, target: &Utf8Path) -> Result<()> {
83+
use anyhow::ensure;
84+
85+
tracing::debug!("Target {target} is a mountpoint, remounting rw");
86+
let st = Command::new("chattr")
87+
.args(["-i", target.as_str()])
88+
.cwd_dir(root.try_clone()?)
89+
.status()?;
90+
91+
ensure!(st.success(), "Failed to remove immutability: {st:?}");
92+
93+
Ok(())
94+
}
95+
6096
pub(crate) fn spawn_editor(tmpf: &tempfile::NamedTempFile) -> Result<()> {
6197
let editor_variables = ["EDITOR"];
6298
// These roughly match https://github.com/systemd/systemd/blob/769ca9ab557b19ee9fb5c5106995506cace4c68f/src/shared/edit-util.c#L275

tests-integration/src/install.rs

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,24 +27,34 @@ pub(crate) const BASE_ARGS: &[&str] = &[
2727

2828
// Arbitrary
2929
const NON_DEFAULT_STATEROOT: &str = "foo";
30+
const SOME_OTHER_STATEROOT: &str = "bar";
3031

3132
/// Clear out and delete any ostree roots, leverage bootc hidden wipe-ostree command to get rid of
3233
/// otherwise hard to delete deployment files
3334
fn reset_root(sh: &Shell, image: &str) -> Result<()> {
34-
if !Path::new("/ostree/deploy/").exists() {
35+
delete_ostree_deployments(sh, image)?;
36+
delete_ostree_repo(sh)?;
37+
Ok(())
38+
}
39+
40+
fn delete_ostree_repo(sh: &Shell) -> Result<(), anyhow::Error> {
41+
if !Path::new("/ostree/repo").exists() {
3542
return Ok(());
3643
}
44+
cmd!(sh, "sudo /bin/sh -c 'rm -rf /ostree/repo'").run()?;
45+
Ok(())
46+
}
3747

38-
// Without /boot ostree will not delete anything
48+
fn delete_ostree_deployments(sh: &Shell, image: &str) -> Result<(), anyhow::Error> {
49+
if !Path::new("/ostree/deploy/").exists() {
50+
return Ok(());
51+
}
3952
let mounts = &["-v", "/ostree:/ostree", "-v", "/boot:/boot"];
40-
4153
cmd!(
4254
sh,
4355
"sudo {BASE_ARGS...} {mounts...} {image} bootc state wipe-ostree"
4456
)
4557
.run()?;
46-
47-
// Now that the hard to delete files are gone, we can just rm -rf the rest
4858
cmd!(sh, "sudo /bin/sh -c 'rm -rf /ostree/deploy/*'").run()?;
4959
Ok(())
5060
}
@@ -166,6 +176,23 @@ pub(crate) fn run_alongside(image: &str, mut testargs: libtest_mimic::Arguments)
166176
generic_post_install_verification()?;
167177
Ok(())
168178
}),
179+
Trial::test("Install on already ostree target", move || {
180+
// Do an initial install just to get ostree on our system
181+
let sh = &xshell::Shell::new()?;
182+
reset_root(sh, image)?;
183+
cmd!(sh, "sudo {BASE_ARGS...} {target_args...} {image} bootc install to-existing-root --stateroot {NON_DEFAULT_STATEROOT} --acknowledge-destructive {generic_inst_args...}").run()?;
184+
generic_post_install_verification()?;
185+
assert!(
186+
Utf8Path::new(&format!("/ostree/deploy/{NON_DEFAULT_STATEROOT}")).try_exists()?
187+
);
188+
189+
// Now try again to a different stateroot
190+
let sh = &xshell::Shell::new()?;
191+
cmd!(sh, "sudo {BASE_ARGS...} {target_args...} {image} bootc install to-existing-root --replace alongside --stateroot {SOME_OTHER_STATEROOT} --acknowledge-destructive {generic_inst_args...}").run()?;
192+
generic_post_install_verification()?;
193+
assert!(Utf8Path::new(&format!("/ostree/deploy/{SOME_OTHER_STATEROOT}")).try_exists()?);
194+
Ok(())
195+
}),
169196
];
170197

171198
libtest_mimic::run(&testargs, tests.into()).exit()

0 commit comments

Comments
 (0)