Skip to content

Commit 5f31d97

Browse files
committed
install: Add --initialize-var-mounts for separate /var filesystems
A common setup places /var, or parts of it such as /var/log, on separate filesystems (for example LVM logical volumes) so that runaway writes cannot fill the root filesystem. With `install to-filesystem` these filesystems end up empty: the deployment backend seeds the image's /var into its own state directory (`ostree/deploy/<stateroot>/var`, or the composefs shared var), and at boot the separately mounted filesystems hide that content. With the new --initialize-var-mounts option, a fresh to-filesystem installation discovers filesystems mounted at the target's /var or below. Each empty top-level mount tree, including its nested mounts, is initialized from the seeded /var with `cp --archive`, then SELinux labeled and synced. A tree that already contains data is preserved as a whole, without merging. The option is rejected for alongside and existing-deployment installs, before anything on the target is changed. Callers remain responsible for mounting these filesystems at boot. Without the option nothing changes, so callers that mount an empty /var filesystem and fill it themselves after installation are not affected. Doing this by default was considered, but would have changed behavior for them. Image builders can tell whether to pass the option from the `Features:` list that `bootc --version` now prints after the version; the first line stays the bare version for existing parsers. The feature describes the binary rather than an image, so it is not part of `container inspect`, and `--version` needs no new query interface. The seeded copy in the state directory is kept; on OSTree, emptying it would make the next deployment reseed it. Hardlinks cannot span filesystems, so trees with nested mounts are copied without preserving them. The roots of these filesystems are labeled unconditionally: without selinuxfs (e.g. in an osbuild buildroot), an inode with no label still reports the kernel's unlabeled context, which the regular relabel walk takes as already labeled. The separate /var TMT test now passes the option, checks contents, ownership, symlinks and SELinux labels on the actual volumes, including a nested one, and checks that without the option they stay empty. Related: #1615 Related: #997 Generated-by: AI
1 parent c3949f7 commit 5f31d97

5 files changed

Lines changed: 706 additions & 33 deletions

File tree

‎crates/lib/src/cli.rs‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -976,6 +976,22 @@ impl InternalsOpts {
976976
const GENERATOR_BIN: &'static str = "bootc-systemd-generator";
977977
}
978978

979+
/// The text of `bootc --version`: the version, then the optional features of
980+
/// this binary that tools driving bootc can rely on being present.
981+
fn long_version() -> &'static str {
982+
static LONG_VERSION: std::sync::OnceLock<String> = std::sync::OnceLock::new();
983+
LONG_VERSION
984+
.get_or_init(|| format_long_version(clap::crate_version!(), crate::install::FEATURES))
985+
}
986+
987+
fn format_long_version(version: &str, features: &[&str]) -> String {
988+
let features = features
989+
.iter()
990+
.map(|f| format!("\n - {f}"))
991+
.collect::<String>();
992+
format!("{version}\nFeatures:{features}")
993+
}
994+
979995
/// Deploy and transactionally in-place with bootable container images.
980996
///
981997
/// The `bootc` project currently uses ostree-containers as a backend
@@ -986,7 +1002,7 @@ impl InternalsOpts {
9861002
#[derive(Debug, Parser, PartialEq, Eq)]
9871003
#[clap(name = "bootc")]
9881004
#[clap(rename_all = "kebab-case")]
989-
#[clap(version,long_version=clap::crate_version!())]
1005+
#[clap(version, long_version = long_version())]
9901006
#[allow(clippy::large_enum_variant)]
9911007
pub(crate) enum Opt {
9921008
/// Download and queue an updated container image to apply.
@@ -3163,4 +3179,17 @@ mod tests {
31633179
}
31643180
}
31653181
}
3182+
3183+
#[test]
3184+
fn test_long_version() {
3185+
assert_eq!(
3186+
format_long_version("1.2.3", &["a", "b"]),
3187+
"1.2.3\nFeatures:\n - a\n - b"
3188+
);
3189+
// Every feature we have shows up in `bootc --version`
3190+
let long = Opt::command().render_long_version();
3191+
for f in crate::install::FEATURES {
3192+
assert!(long.contains(&format!("\n - {f}")), "{long}");
3193+
}
3194+
}
31663195
}

‎crates/lib/src/install.rs‎

Lines changed: 109 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,7 @@ pub(crate) mod completion;
146146
pub(crate) mod config;
147147
mod osbuild;
148148
pub(crate) mod osconfig;
149+
mod var_mounts;
149150

150151
use std::collections::HashMap;
151152
use std::io::Write;
@@ -224,6 +225,8 @@ const ALONGSIDE_ROOT_MOUNT: &str = "/target";
224225
pub(crate) const DESTRUCTIVE_CLEANUP: &str = "etc/bootc-destructive-cleanup";
225226
/// This is an ext4 special directory we need to ignore.
226227
const LOST_AND_FOUND: &str = "lost+found";
228+
/// Optional features of this binary, listed by `bootc --version`.
229+
pub(crate) const FEATURES: &[&str] = &[var_mounts::FEATURE];
227230
/// The mount path for selinux
228231
const SELINUXFS: &str = "/sys/fs/selinux";
229232
/// The mount path for uefi
@@ -554,6 +557,14 @@ pub(crate) struct InstallTargetFilesystemOpts {
554557
#[clap(long)]
555558
pub(crate) boot_mount_spec: Option<String>,
556559

560+
/// Initialize empty filesystems mounted at or below /var in the target
561+
/// from the image's /var, including nested mounts.
562+
///
563+
/// Without this, filesystems that the caller mounted there are left alone,
564+
/// and hide the image's /var content at boot.
565+
#[clap(long)]
566+
pub(crate) initialize_var_mounts: bool,
567+
557568
/// Initialize the system in-place; at the moment, only one mode for this is implemented.
558569
/// In the future, it may also be supported to set up an explicit "dual boot" system.
559570
#[clap(long)]
@@ -2177,6 +2188,7 @@ async fn install_to_filesystem_impl(
21772188
state: &State,
21782189
rootfs: &mut RootSetup,
21792190
cleanup: Cleanup,
2191+
var_mounts: &[Utf8PathBuf],
21802192
) -> Result<()> {
21812193
if matches!(state.selinux_state, SELinuxFinalState::ForceTargetDisabled) {
21822194
rootfs.kargs.extend(&Cmdline::from("selinux=0"));
@@ -2291,6 +2303,20 @@ async fn install_to_filesystem_impl(
22912303
}
22922304
}
22932305

2306+
// The deployment backend seeds its own state directory, not the caller's
2307+
// mounted /var tree. Populate fresh external filesystems while all nested
2308+
// mounts are still visible, before labeling and finalizing the installation.
2309+
let prepared_var_mounts = if !var_mounts.is_empty() {
2310+
let source = if state.composefs_options.composefs_backend {
2311+
Utf8PathBuf::from(crate::composefs_consts::SHARED_VAR_PATH)
2312+
} else {
2313+
Utf8PathBuf::from(format!("ostree/deploy/{}/var", state.stateroot()))
2314+
};
2315+
var_mounts::populate(&rootfs.physical_root, &source, var_mounts)?
2316+
} else {
2317+
Vec::new()
2318+
};
2319+
22942320
// As the very last step before filesystem finalization, do a full SELinux
22952321
// relabel of the physical root filesystem. Any files that are already
22962322
// labeled (e.g. ostree deployment contents, composefs objects) are skipped.
@@ -2299,10 +2325,32 @@ async fn install_to_filesystem_impl(
22992325
let mut path = Utf8PathBuf::from("");
23002326
crate::lsm::ensure_dir_labeled_recurse(&rootfs.physical_root, &mut path, &policy, None)
23012327
.context("Final SELinux relabeling of physical root")?;
2328+
// The physical-root walk skips mountpoints. Label each newly
2329+
// prepared filesystem separately, using its deployed /var path.
2330+
for mount in &prepared_var_mounts {
2331+
let mut path = var_mounts::target_path(mount);
2332+
// These are fresh filesystems; label their roots unconditionally.
2333+
// Without selinuxfs (e.g. in an osbuild buildroot), an inode without
2334+
// a label still reports the kernel's unlabeled context, which the
2335+
// walk below would take as labeled.
2336+
for p in [path.clone(), path.join(LOST_AND_FOUND)] {
2337+
if let Some(meta) = rootfs.physical_root.symlink_metadata_optional(&p)? {
2338+
crate::lsm::relabel(&rootfs.physical_root, &meta, &p, None, &policy)
2339+
.with_context(|| format!("SELinux labeling of /{p}"))?;
2340+
}
2341+
}
2342+
crate::lsm::ensure_dir_labeled_recurse(&rootfs.physical_root, &mut path, &policy, None)
2343+
.with_context(|| format!("SELinux labeling of /{path}"))?;
2344+
}
23022345
} else {
23032346
tracing::debug!("Skipping final SELinux relabel (SELinux is disabled)");
23042347
}
23052348

2349+
// Flush the /var filesystems we wrote, surfacing any writeback errors.
2350+
// Unlike root and boot they are not remounted read-only or frozen: they
2351+
// may be bind mounts or lack freeze support, and callers may add content.
2352+
var_mounts::sync(&rootfs.physical_root, &prepared_var_mounts)?;
2353+
23062354
// Finalize mounted filesystems
23072355
if !rootfs.skip_finalize {
23082356
let bootfs = rootfs.boot.as_ref().map(|_| ("boot", BOOT));
@@ -2392,7 +2440,7 @@ pub(crate) async fn install_to_disk(mut opts: InstallToDiskOpts) -> Result<()> {
23922440
(rootfs, loopback_dev)
23932441
};
23942442

2395-
install_to_filesystem_impl(&state, &mut rootfs, Cleanup::Skip).await?;
2443+
install_to_filesystem_impl(&state, &mut rootfs, Cleanup::Skip, &[]).await?;
23962444

23972445
// Drop all data about the root except the bits we need to ensure any file descriptors etc. are closed.
23982446
let (root_path, luksdev) = rootfs.into_storage();
@@ -2663,6 +2711,25 @@ pub enum Cleanup {
26632711
}
26642712

26652713
/// Implementation of the `bootc install to-filesystem` CLI command.
2714+
/// Reinstalling over or alongside an existing OS must not initialize its
2715+
/// live state. Checked before anything on the target is changed.
2716+
fn check_initialize_var_mounts(
2717+
initialize_var_mounts: bool,
2718+
targeting_host_root: bool,
2719+
is_already_ostree: bool,
2720+
replace: Option<ReplaceMode>,
2721+
) -> Result<()> {
2722+
anyhow::ensure!(
2723+
!initialize_var_mounts
2724+
|| !(targeting_host_root
2725+
|| is_already_ostree
2726+
|| replace == Some(ReplaceMode::Alongside)),
2727+
"--initialize-var-mounts is not supported over an existing ostree system \
2728+
or with --replace=alongside"
2729+
);
2730+
Ok(())
2731+
}
2732+
26662733
#[context("Installing to filesystem")]
26672734
pub(crate) async fn install_to_filesystem(
26682735
opts: InstallToFilesystemOpts,
@@ -2744,6 +2811,12 @@ pub(crate) async fn install_to_filesystem(
27442811
);
27452812
fsopts.root_path = possible_physical_root;
27462813
};
2814+
check_initialize_var_mounts(
2815+
fsopts.initialize_var_mounts,
2816+
targeting_host_root,
2817+
is_already_ostree,
2818+
fsopts.replace,
2819+
)?;
27472820

27482821
// Get a file descriptor for the root path
27492822
// It will be /target/sysroot on ostree OS, or will be /target
@@ -2939,7 +3012,12 @@ pub(crate) async fn install_to_filesystem(
29393012
skip_finalize,
29403013
};
29413014

2942-
install_to_filesystem_impl(&state, &mut rootfs, cleanup).await?;
3015+
let var_mounts = if fsopts.initialize_var_mounts {
3016+
var_mounts::discover(&rootfs.physical_root_path)?
3017+
} else {
3018+
Vec::new()
3019+
};
3020+
install_to_filesystem_impl(&state, &mut rootfs, cleanup, &var_mounts).await?;
29433021

29443022
// Drop all data about the root except the path to ensure any file descriptors etc. are closed.
29453023
drop(rootfs);
@@ -2984,6 +3062,7 @@ pub(crate) async fn install_to_existing_root(opts: InstallToExistingRootOpts) ->
29843062
root_path: opts.root_path,
29853063
root_mount_spec: None,
29863064
boot_mount_spec: None,
3065+
initialize_var_mounts: false,
29873066
replace: opts.replace,
29883067
skip_finalize: true,
29893068
acknowledge_destructive: opts.acknowledge_destructive,
@@ -3301,6 +3380,34 @@ mod tests {
33013380
}
33023381
}
33033382

3383+
#[test]
3384+
fn test_check_initialize_var_mounts() {
3385+
use ReplaceMode::*;
3386+
// (initialize, host root, already ostree, replace, allowed)
3387+
let cases = [
3388+
(false, true, true, Some(Alongside), true),
3389+
(true, false, false, None, true),
3390+
(true, false, false, Some(Wipe), true),
3391+
(true, false, false, Some(Alongside), false),
3392+
(true, false, true, None, false),
3393+
(true, true, false, None, false),
3394+
];
3395+
for (init, host_root, ostree, replace, allowed) in cases {
3396+
let r = check_initialize_var_mounts(init, host_root, ostree, replace);
3397+
match r {
3398+
Ok(()) => assert!(allowed, "{init} {host_root} {ostree} {replace:?}"),
3399+
Err(e) => {
3400+
assert!(!allowed, "{init} {host_root} {ostree} {replace:?}: {e}");
3401+
assert_eq!(
3402+
e.to_string(),
3403+
"--initialize-var-mounts is not supported over an existing ostree \
3404+
system or with --replace=alongside"
3405+
);
3406+
}
3407+
}
3408+
}
3409+
}
3410+
33043411
#[test]
33053412
fn test_mountspec() {
33063413
let mut ms = MountSpec::new("/dev/vda4", "/boot");

0 commit comments

Comments
 (0)