From cb494440fda4d711294c728bd3f1f0dc01766b73 Mon Sep 17 00:00:00 2001 From: Colin Walters Date: Sun, 12 Feb 2023 16:45:33 -0500 Subject: [PATCH] Add support for configmaps This is part of https://github.com/containers/bootc/issues/22 --- lib/Cargo.toml | 7 +- lib/src/cli.rs | 33 ++-- lib/src/config.rs | 325 +++++++++++++++++++++++++++++++++++ lib/src/deploy.rs | 146 ++++++++++++++++ lib/src/lib.rs | 7 + lib/src/lsm.rs | 14 +- lib/src/ostree_generation.rs | 95 ++++++++++ lib/src/status.rs | 9 + lib/src/utils.rs | 5 + 9 files changed, 628 insertions(+), 13 deletions(-) create mode 100644 lib/src/config.rs create mode 100644 lib/src/deploy.rs create mode 100644 lib/src/ostree_generation.rs diff --git a/lib/Cargo.toml b/lib/Cargo.toml index 040669f3..43f9d985 100644 --- a/lib/Cargo.toml +++ b/lib/Cargo.toml @@ -19,6 +19,7 @@ hex = "^0.4" fn-error-context = "0.2.0" gvariant = "0.4.0" indicatif = "0.17.0" +k8s-openapi = { version = "0.17.0", features = ["v1_25"], optional = true } libc = "^0.2" liboverdrop = "0.1.0" once_cell = "1.9" @@ -36,11 +37,15 @@ tempfile = "3.3.0" toml = "0.7.2" xshell = { version = "0.2", optional = true } uuid = { version = "1.2.2", features = ["v4"] } +reqwest = { version = "0.11.14", features = ["json"] } +serde_yaml = "0.9.17" [features] -default = ["install"] +default = ["install", "k8s-base"] # This feature enables `bootc install`. Disable if you always want to use an external installer. install = [] +# This feature enables `bootc config`. Disable if you don't want to support dynamic reconfiguration. +k8s-base = ["k8s-openapi"] # Implementation detail of man page generation. docgen = ["clap_mangen"] # This feature should only be enabled in CI environments. diff --git a/lib/src/cli.rs b/lib/src/cli.rs index bc35104f..edaed2bd 100644 --- a/lib/src/cli.rs +++ b/lib/src/cli.rs @@ -15,6 +15,7 @@ use ostree_ext::container as ostree_container; use ostree_ext::container::SignatureSource; use ostree_ext::keyfileext::KeyFileExt; use ostree_ext::ostree; +use ostree_ext::ostree::Deployment; use ostree_ext::sysroot::SysrootLock; use std::ffi::OsString; use std::os::unix::process::CommandExt; @@ -110,6 +111,9 @@ pub(crate) enum Opt { /// Add a transient writable overlayfs on `/usr` that will be discarded on reboot. #[clap(alias = "usroverlay")] UsrOverlay, + /// Manipulate configuration + #[clap(subcommand)] + Config(crate::config::ConfigOpts), /// Install to the target block device #[cfg(feature = "install")] Install(crate::install::InstallOpts), @@ -209,7 +213,7 @@ async fn pull( /// Stage (queue deployment of) a fetched container image. #[context("Staging")] -async fn stage( +pub(crate) async fn stage( sysroot: &SysrootLock, stateroot: &str, imgref: &ostree_container::OstreeImageReference, @@ -245,7 +249,7 @@ pub(crate) fn require_root() -> Result<()> { /// A few process changes that need to be made for writing. #[context("Preparing for write")] -async fn prepare_for_write() -> Result<()> { +pub(crate) async fn prepare_for_write() -> Result<()> { if ostree_ext::container_utils::is_ostree_container()? { anyhow::bail!( "Detected container (ostree base); this command requires a booted host system." @@ -258,16 +262,21 @@ async fn prepare_for_write() -> Result<()> { Ok(()) } +pub(crate) fn target_deployment(sysroot: &SysrootLock) -> Result { + let booted_deployment = sysroot.require_booted_deployment()?; + Ok(sysroot.staged_deployment().unwrap_or(booted_deployment)) +} + /// Implementation of the `bootc upgrade` CLI command. #[context("Upgrading")] async fn upgrade(opts: UpgradeOpts) -> Result<()> { prepare_for_write().await?; let sysroot = &get_locked_sysroot().await?; let repo = &sysroot.repo().unwrap(); - let booted_deployment = &sysroot.require_booted_deployment()?; - let status = crate::status::DeploymentStatus::from_deployment(booted_deployment, true)?; - let osname = booted_deployment.osname().unwrap(); - let origin = booted_deployment + let merge_deployment = &target_deployment(sysroot)?; + let status = crate::status::DeploymentStatus::from_deployment(merge_deployment, true)?; + let osname = merge_deployment.osname().unwrap(); + let origin = merge_deployment .origin() .ok_or_else(|| anyhow::anyhow!("Deployment is missing an origin"))?; let imgref = status @@ -279,7 +288,7 @@ async fn upgrade(opts: UpgradeOpts) -> Result<()> { "Booted deployment contains local rpm-ostree modifications; cannot upgrade via bootc" )); } - let commit = booted_deployment.csum().unwrap(); + let commit = merge_deployment.csum().unwrap(); let state = ostree_container::store::query_image_commit(repo, &commit)?; let digest = state.manifest_digest.as_str(); let fetched = pull(repo, &imgref, opts.quiet).await?; @@ -304,11 +313,11 @@ async fn switch(opts: SwitchOpts) -> Result<()> { prepare_for_write().await?; let cancellable = gio::Cancellable::NONE; - let sysroot = get_locked_sysroot().await?; - let booted_deployment = &sysroot.require_booted_deployment()?; - let (origin, booted_image) = crate::utils::get_image_origin(booted_deployment)?; + let sysroot = &get_locked_sysroot().await?; + let merge_deployment = &target_deployment(sysroot)?; + let (origin, booted_image) = crate::utils::get_image_origin(merge_deployment)?; let booted_refspec = origin.optional_string("origin", "refspec")?; - let osname = booted_deployment.osname().unwrap(); + let osname = merge_deployment.osname().unwrap(); let repo = &sysroot.repo().unwrap(); let transport = ostree_container::Transport::try_from(opts.transport.as_str())?; @@ -374,6 +383,8 @@ where Opt::Upgrade(opts) => upgrade(opts).await, Opt::Switch(opts) => switch(opts).await, Opt::UsrOverlay => usroverlay().await, + #[cfg(feature = "k8s-base")] + Opt::Config(opts) => crate::config::run(opts).await, #[cfg(feature = "install")] Opt::Install(opts) => crate::install::install(opts).await, #[cfg(feature = "install")] diff --git a/lib/src/config.rs b/lib/src/config.rs new file mode 100644 index 00000000..3012dd86 --- /dev/null +++ b/lib/src/config.rs @@ -0,0 +1,325 @@ +use std::collections::HashMap; + +use anyhow::{anyhow, Context, Result}; + +use camino::Utf8Path; +use cap_std::fs::Dir; +use cap_std_ext::cap_std; +use fn_error_context::context; +use k8s_openapi::{api::core::v1::ConfigMap, http::HeaderValue}; +use ostree_ext::container as ostree_container; +use ostree_ext::prelude::{Cast, FileExt, ToVariant}; +use ostree_ext::{gio, glib, ostree}; +use ostree_ext::{ostree::Deployment, sysroot::SysrootLock}; +use reqwest::StatusCode; +use rustix::fd::AsRawFd; + +/// The prefix used to store configmaps +const REF_PREFIX: &str = "bootc/config"; + +/// The key used to configure the file prefix; the default is `/etc`. +const CONFIGMAP_PREFIX_ANNOTATION_KEY: &str = "bootc.prefix"; +/// The default prefix for configmaps and secrets. +const DEFAULT_MOUNT_PREFIX: &str = "etc"; + +/// The key used to store the configmap metadata +const CONFIGMAP_METADATA_KEY: &str = "bootc.configmap.metadata"; +/// The key used to store the etag from the HTTP request +const CONFIGMAP_ETAG_KEY: &str = "bootc.configmap.etag"; + +/// Default to world-readable for configmaps +const DEFAULT_MODE: u32 = 0o644; + +const ORIGIN_BOOTC_CONFIG_PREFIX: &str = "bootc.config."; + +/// The serialized metadata about configmaps attached to a deployment +pub(crate) struct ConfigSpec { + pub(crate) name: String, + pub(crate) url: String, +} + +impl ConfigSpec { + const KEY_URL: &str = "url"; + + /// Return the keyfile group name + fn group(name: &str) -> String { + format!("{ORIGIN_BOOTC_CONFIG_PREFIX}/{name}") + } + + /// Parse a config specification from a keyfile + #[context("Parsing config spec")] + fn from_keyfile(kf: &glib::KeyFile, name: &str) -> Result { + let group = Self::group(name); + let url = kf.string(&group, Self::KEY_URL)?.to_string(); + Ok(Self { + url, + name: name.to_string(), + }) + } + + /// Serialize this config spec into the target keyfile + fn store(&self, kf: &glib::KeyFile) { + let group = &Self::group(&self.name); + // Ignore errors if the group didn't exist + let _ = kf.remove_group(group); + kf.set_string(group, Self::KEY_URL, &self.url); + } + + pub(crate) fn ostree_ref(&self) -> Result { + name_to_ostree_ref(&self.name) + } +} + +/// Options for internal testing +#[derive(Debug, clap::Subcommand)] +pub(crate) enum ConfigOpts { + /// Add a remote configmap + AddFromURL { + /// Remote URL for configmap + url: String, + + #[clap(long)] + /// Provide an explicit name for the map + name: Option, + }, + /// Add a remote configmap + Remove { + /// Name of the configmap to remove + name: String, + }, + /// List attached configmaps + List, +} + +/// Implementation of the `boot config` CLI. +pub(crate) async fn run(opts: ConfigOpts) -> Result<()> { + crate::cli::prepare_for_write().await?; + let sysroot = &crate::cli::get_locked_sysroot().await?; + match opts { + ConfigOpts::AddFromURL { url, name } => add_from_url(sysroot, &url, name.as_deref()).await, + ConfigOpts::Remove { name } => remove(sysroot, name.as_str()).await, + ConfigOpts::List => list(sysroot).await, + } +} + +#[context("Converting configmap name to ostree ref")] +fn name_to_ostree_ref(name: &str) -> Result { + ostree_ext::refescape::prefix_escape_for_ref(REF_PREFIX, name) +} + +async fn list(sysroot: &SysrootLock) -> Result<()> { + let merge_deployment = &crate::cli::target_deployment(sysroot)?; + let configs = configs_for_deployment(sysroot, merge_deployment)?; + if configs.len() == 0 { + println!("No dynamic ConfigMap objects attached"); + } else { + for config in configs { + let name = config.name; + let url = config.url; + println!("{name} {url}"); + } + } + Ok(()) +} + +async fn remove(_sysroot: &SysrootLock, _name: &str) -> Result<()> { + todo!() +} + +#[derive(Debug)] +struct HttpCachableReply { + content: T, + etag: Option, +} + +#[context("Writing configmap")] +fn write_configmap( + sysroot: &SysrootLock, + sepolicy: Option<&ostree::SePolicy>, + spec: &ConfigSpec, + map: &ConfigMap, + etag: Option<&str>, +) -> Result<()> { + let cancellable = gio::Cancellable::NONE; + use crate::ostree_generation::{create_and_commit_dirmeta, write_file}; + let name = spec.name.as_str(); + tracing::debug!("Writing configmap {name}"); + let oref = name_to_ostree_ref(&spec.name)?; + let repo = &sysroot.repo().unwrap(); + let tx = repo.auto_transaction(cancellable)?; + let tree = &ostree::MutableTree::new(); + let dirmeta = + create_and_commit_dirmeta(&repo, "/etc/some-unshipped-config-file".into(), sepolicy)?; + // Create an iterator over the string data + let string_data = map.data.iter().flatten().map(|(k, v)| (k, v.as_bytes())); + // Create an iterator over the binary data + let binary_data = map + .binary_data + .iter() + .flatten() + .map(|(k, v)| (k, v.0.as_slice())); + let prefix = map + .metadata + .annotations + .as_ref() + .and_then(|m| m.get(CONFIGMAP_PREFIX_ANNOTATION_KEY).map(|s| s.as_str())) + .unwrap_or(DEFAULT_MOUNT_PREFIX); + tracing::trace!("prefix={prefix}"); + // For each string and binary value, write a file + let mut has_content = false; + for (k, v) in string_data.chain(binary_data) { + let path = Utf8Path::new(prefix).join(k); + tracing::trace!("Writing {path}"); + write_file(repo, tree, &path, &dirmeta, v, DEFAULT_MODE, sepolicy)?; + has_content = true; + } + if !has_content { + anyhow::bail!("ConfigMap has no data"); + } + let serialized_map_metadata = + serde_json::to_string(&map.metadata).context("Serializing configmap metadata")?; + let mut metadata = HashMap::new(); + let commit_metadata = + metadata.insert(CONFIGMAP_METADATA_KEY, serialized_map_metadata.to_variant()); + if let Some(etag) = etag { + metadata.insert(CONFIGMAP_ETAG_KEY, etag.to_variant()); + } + let commit_metadata = commit_metadata.to_variant(); + let timestamp = map + .metadata + .creation_timestamp + .as_ref() + .map(|t| t.0.timestamp() as u64) + .unwrap_or_default(); + tracing::trace!("Writing commit with ts {timestamp}"); + let root = repo.write_mtree(&tree, gio::Cancellable::NONE)?; + let root = root.downcast_ref::().unwrap(); + let commit = repo.write_commit_with_time( + None, + None, + None, + Some(&commit_metadata), + root, + timestamp, + cancellable, + )?; + repo.transaction_set_ref(None, &oref, Some(commit.as_str())); + tx.commit(cancellable)?; + Ok(()) +} + +#[context("Fetching configmap from {url}")] +/// Download a configmap, honoring an optional ETag. If the server says the resource +/// is unmodified, this returns `Ok(None)`. +async fn fetch_configmap( + client: &reqwest::Client, + url: &str, + etag: Option<&str>, +) -> Result>> { + tracing::debug!("Fetching {url}"); + let mut req = client.get(url); + if let Some(etag) = etag { + tracing::trace!("Providing etag {etag}"); + let val = HeaderValue::from_str(etag).context("Parsing etag")?; + req = req.header(reqwest::header::IF_NONE_MATCH, val); + } + let reply = req.send().await?; + if reply.status() == StatusCode::NOT_MODIFIED { + tracing::debug!("Server returned NOT_MODIFIED"); + return Ok(None); + } + let etag = reply + .headers() + .get(reqwest::header::ETAG) + .map(|v| v.to_str()) + .transpose() + .context("Parsing etag")? + .map(ToOwned::to_owned); + // TODO: streaming deserialize + let buf = reply.bytes().await?; + tracing::trace!("Parsing server reply of {} bytes", buf.len()); + serde_yaml::from_slice(&buf) + .context("Deserializing configmap") + .map(|v| Some(HttpCachableReply { content: v, etag })) +} + +/// Download a configmap. +async fn fetch_required_configmap( + client: &reqwest::Client, + url: &str, +) -> Result> { + fetch_configmap(client, url, None) + .await? + .ok_or_else(|| anyhow::anyhow!("Server unexpectedly returned unmodified status")) +} + +/// Return the attached configmaps for a deployment. +#[context("Querying config names")] +pub(crate) fn configs_for_deployment( + _sysroot: &SysrootLock, + deployment: &Deployment, +) -> Result> { + let origin = deployment + .origin() + .ok_or_else(|| anyhow::anyhow!("Deployment is missing an origin"))?; + origin + .groups() + .0 + .into_iter() + .try_fold(Vec::new(), |mut acc, name| { + if let Some(name) = name.strip_prefix(ORIGIN_BOOTC_CONFIG_PREFIX) { + let spec = ConfigSpec::from_keyfile(&origin, name)?; + acc.push(spec); + } + anyhow::Ok(acc) + }) +} + +async fn add_from_url(sysroot: &SysrootLock, url: &str, name: Option<&str>) -> Result<()> { + let cancellable = gio::Cancellable::NONE; + let repo = &sysroot.repo().unwrap(); + let merge_deployment = &crate::cli::target_deployment(sysroot)?; + let stateroot = merge_deployment.osname().unwrap(); + let client = crate::utils::new_http_client().build()?; + let reply = fetch_required_configmap(&client, url).await?; + let configmap = reply.content; + let origin = merge_deployment + .origin() + .ok_or_else(|| anyhow::anyhow!("Deployment is missing an origin"))?; + let dirpath = sysroot.deployment_dirpath(merge_deployment).unwrap(); + // SAFETY: None of this should be NULL + let dirpath = sysroot.path().unwrap().path().unwrap().join(dirpath); + let deployment_fd = Dir::open_ambient_dir(&dirpath, cap_std::ambient_authority()) + .with_context(|| format!("Opening deployment directory {dirpath:?}"))?; + let sepolicy = ostree::SePolicy::new_at(deployment_fd.as_raw_fd(), cancellable)?; + let name = name + .or_else(|| configmap.metadata.name.as_deref()) + .ok_or_else(|| anyhow!("Missing metadata.name and no name provided"))?; + let configs = configs_for_deployment(sysroot, merge_deployment)?; + if configs.iter().any(|v| v.name == name) { + anyhow::bail!("Already have a config with name {name}"); + } + let spec = ConfigSpec { + name: name.to_owned(), + url: url.to_owned(), + }; + let oref = name_to_ostree_ref(name)?; + tracing::trace!("configmap {name} => {oref}"); + // TODO use ostree_ext::tokio_util::spawn_blocking_cancellable_flatten(move |cancellable| { + // once https://github.com/ostreedev/ostree/pull/2824 lands + write_configmap( + sysroot, + Some(&sepolicy), + &spec, + &configmap, + reply.etag.as_deref(), + )?; + + spec.store(&origin); + + let commit = merge_deployment.csum().unwrap(); + let state = ostree_container::store::query_image_commit(repo, &commit)?; + + crate::deploy::deploy(sysroot, Some(merge_deployment), &stateroot, state, &origin).await?; + Ok(()) +} diff --git a/lib/src/deploy.rs b/lib/src/deploy.rs new file mode 100644 index 00000000..1a37bdcb --- /dev/null +++ b/lib/src/deploy.rs @@ -0,0 +1,146 @@ +//! # Write deployments merging image with configmap +//! +//! Create a merged filesystem tree with the image and mounted configmaps. + +use anyhow::{Context, Result}; +use camino::Utf8PathBuf; +use cap_std_ext::cap_tempfile; +use cap_std_ext::rustix; +use clap::Parser; +use fn_error_context::context; +use ostree::{gio, glib}; +use ostree_container::store::LayeredImageState; +use ostree_container::store::PrepareResult; +use ostree_container::OstreeImageReference; +use ostree_ext::container as ostree_container; +use ostree_ext::container::SignatureSource; +use ostree_ext::keyfileext::KeyFileExt; +use ostree_ext::ostree; +use ostree_ext::ostree::Deployment; +use ostree_ext::prelude::Cast; +use ostree_ext::sysroot::SysrootLock; +use std::ffi::OsString; + +pub(crate) async fn deploy( + sysroot: &SysrootLock, + merge_deployment: Option<&Deployment>, + stateroot: &str, + image: Box, + origin: &glib::KeyFile, +) -> Result<()> { + let repo = sysroot.repo().unwrap(); + let configs = if let Some(merge_deployment) = merge_deployment { + crate::config::configs_for_deployment(sysroot, merge_deployment)? + } else { + Vec::new() + }; + let stateroot = Some(stateroot); + // Copy to move into thread + let base_commit = image.get_commit().to_owned(); + // If there's no configmaps, then all we need to do is deploy the commit. + if configs.is_empty() { + let cancellable = gio::Cancellable::NONE; + let _new_deployment = sysroot.stage_tree_with_options( + stateroot, + image.merge_commit.as_str(), + Some(origin), + merge_deployment, + &Default::default(), + cancellable, + )?; + // And we're done! + return Ok(()); + } + let merge_commit = + ostree_ext::tokio_util::spawn_blocking_cancellable_flatten(move |cancellable| { + use cap_std_ext::rustix::fd::AsRawFd; + let cancellable = Some(cancellable); + let repo = &repo; + let txn = repo.auto_transaction(cancellable)?; + + let devino = ostree::RepoDevInoCache::new(); + let repodir = repo.dfd_as_dir()?; + let repo_tmp = repodir.open_dir("tmp")?; + let td = cap_tempfile::TempDir::new_in(&repo_tmp)?; + + let rootpath = "root"; + let checkout_mode = if repo.mode() == ostree::RepoMode::Bare { + ostree::RepoCheckoutMode::None + } else { + ostree::RepoCheckoutMode::User + }; + let mut checkout_opts = ostree::RepoCheckoutAtOptions { + mode: checkout_mode, + overwrite_mode: ostree::RepoCheckoutOverwriteMode::UnionFiles, + devino_to_csum_cache: Some(devino.clone()), + no_copy_fallback: true, + force_copy_zerosized: true, + process_whiteouts: false, + ..Default::default() + }; + repo.checkout_at( + Some(&checkout_opts), + (*td).as_raw_fd(), + rootpath, + &base_commit, + cancellable, + ) + .context("Checking out base commit")?; + + // Layer all configmaps + checkout_opts.process_whiteouts = true; + for config in configs { + let oref = config.ostree_ref()?; + let commit = repo.require_rev(&oref)?; + repo.checkout_at( + Some(&checkout_opts), + (*td).as_raw_fd(), + rootpath, + &commit, + cancellable, + ) + .with_context(|| format!("Checking out layer {commit}"))?; + } + + let modifier = + ostree::RepoCommitModifier::new(ostree::RepoCommitModifierFlags::CONSUME, None); + modifier.set_devino_cache(&devino); + + let mt = ostree::MutableTree::new(); + repo.write_dfd_to_mtree( + (*td).as_raw_fd(), + rootpath, + &mt, + Some(&modifier), + cancellable, + ) + .context("Writing merged filesystem to mtree")?; + + let merged_root = repo + .write_mtree(&mt, cancellable) + .context("Writing mtree")?; + let merged_root = merged_root.downcast::().unwrap(); + let merged_commit = repo + .write_commit(None, None, None, None, &merged_root, cancellable) + .context("Writing commit")?; + txn.commit(cancellable)?; + + anyhow::Ok(merged_commit.to_string()) + }) + .await?; + // TODO spawn once origin files are Send + // let origin = origin.clone(); + // ostree_ext::tokio_util::spawn_blocking_cancellable_flatten(move |cancellable| { + { + let cancellable = gio::Cancellable::NONE; + let _new_deployment = sysroot.stage_tree_with_options( + stateroot, + merge_commit.as_str(), + Some(&origin), + merge_deployment, + &Default::default(), + cancellable, + )?; + anyhow::Ok(()) + } +} diff --git a/lib/src/lib.rs b/lib/src/lib.rs index d1f03152..5f9a5b34 100644 --- a/lib/src/lib.rs +++ b/lib/src/lib.rs @@ -14,11 +14,18 @@ #![deny(clippy::todo)] pub mod cli; +pub(crate) mod deploy; mod lsm; mod reexec; mod status; mod utils; +#[cfg(feature = "k8s-base")] +pub(crate) mod config; + +#[cfg(feature = "k8s-base")] +pub(crate) mod ostree_generation; + #[cfg(feature = "internal-testing-api")] mod privtests; diff --git a/lib/src/lsm.rs b/lib/src/lsm.rs index a37f8f71..774b0018 100644 --- a/lib/src/lsm.rs +++ b/lib/src/lsm.rs @@ -11,6 +11,7 @@ use fn_error_context::context; use gvariant::{aligned_bytes::TryAsAligned, Marker, Structure}; #[cfg(feature = "install")] use ostree_ext::ostree; +use ostree_ext::prelude::ToVariant; #[cfg(feature = "install")] use crate::task::Task; @@ -19,7 +20,7 @@ use crate::task::Task; #[cfg(feature = "install")] const SELINUXFS: &str = "/sys/fs/selinux"; /// The SELinux xattr -#[cfg(feature = "install")] +#[cfg(any(feature = "install", feature = "k8s-base"))] const SELINUX_XATTR: &[u8] = b"security.selinux\0"; #[context("Querying selinux availability")] @@ -171,3 +172,14 @@ pub(crate) fn xattrs_have_selinux(xattrs: &ostree::glib::Variant) -> bool { } false } + +#[allow(dead_code)] +pub(crate) fn new_xattrs_with_selinux( + policy: &ostree::SePolicy, + path: &Utf8Path, + mode: u32, +) -> Result { + let label = policy.label(path.as_str(), mode, ostree_ext::gio::Cancellable::NONE)?; + let r = vec![(SELINUX_XATTR, label.as_bytes())]; + Ok(r.to_variant()) +} diff --git a/lib/src/ostree_generation.rs b/lib/src/ostree_generation.rs new file mode 100644 index 00000000..cd665d2b --- /dev/null +++ b/lib/src/ostree_generation.rs @@ -0,0 +1,95 @@ +use anyhow::{anyhow, Result}; +use camino::{Utf8Component, Utf8Path}; +use fn_error_context::context; +use ostree_ext::{gio, glib, ostree}; + +/// The default access mode for directories: rwxr-xr-x +const DEFAULT_DIRECTORY_MODE: u32 = 0o755; + +/// Generate directory metadata variant for root/root 0755 directory with an optional SELinux label. +#[context("Creating dirmeta")] +pub(crate) fn create_dirmeta( + path: &Utf8Path, + sepolicy: Option<&ostree::SePolicy>, +) -> Result { + let finfo = gio::FileInfo::new(); + finfo.set_attribute_uint32("unix::uid", 0); + finfo.set_attribute_uint32("unix::gid", 0); + finfo.set_attribute_uint32("unix::mode", libc::S_IFDIR | DEFAULT_DIRECTORY_MODE); + let xattrs = sepolicy + .map(|policy| crate::lsm::new_xattrs_with_selinux(policy, path, 0o644)) + .transpose()?; + Ok(ostree::create_directory_metadata(&finfo, xattrs.as_ref()).unwrap()) +} + +/// Wraps [`create_dirmeta`] and commits it, returning the digest. +#[context("Committing dirmeta")] +pub(crate) fn create_and_commit_dirmeta( + repo: &ostree::Repo, + path: &Utf8Path, + sepolicy: Option<&ostree::SePolicy>, +) -> Result { + let v = create_dirmeta(path, sepolicy)?; + let r = repo.write_metadata( + ostree::ObjectType::DirMeta, + None, + &v, + gio::Cancellable::NONE, + )?; + Ok(r.to_hex()) +} + +// Drop any leading / or . from the path, +fn relative_path_components(p: &Utf8Path) -> impl Iterator { + p.components() + .filter(|p| matches!(p, Utf8Component::Normal(_))) +} + +#[context("Creating parents")] +fn ensure_parent_dirs( + mt: &ostree::MutableTree, + path: &Utf8Path, + metadata_checksum: &str, +) -> Result { + let parts = relative_path_components(path) + .map(|s| s.as_str()) + .collect::>(); + mt.ensure_parent_dirs(&parts, metadata_checksum) + .map_err(Into::into) +} + +#[context("Writing file to ostree repo")] +pub fn write_file( + repo: &ostree::Repo, + root: &ostree::MutableTree, + path: &Utf8Path, + parent_dirmeta: &str, + contents: &[u8], + mode: u32, + sepolicy: Option<&ostree::SePolicy>, +) -> Result<()> { + let name = path + .file_name() + .ok_or_else(|| anyhow!("Expecting a filename in {path}"))?; + let parent = if path.parent().is_some() { + Some(ensure_parent_dirs(root, &path, parent_dirmeta)?) + } else { + None + }; + let parent = parent.as_ref().unwrap_or(root); + let xattrs = sepolicy + .map(|policy| crate::lsm::new_xattrs_with_selinux(policy, path, 0o644)) + .transpose()?; + let xattrs = xattrs.as_ref(); + let checksum = repo.write_regfile_inline( + None, + 0, + 0, + libc::S_IFREG | mode, + xattrs, + contents, + gio::Cancellable::NONE, + )?; + parent.replace_file(name, checksum.as_str())?; + Ok(()) +} diff --git a/lib/src/status.rs b/lib/src/status.rs index 8f82a649..518bee57 100644 --- a/lib/src/status.rs +++ b/lib/src/status.rs @@ -140,6 +140,7 @@ pub(crate) async fn status(opts: super::cli::StatusOpts) -> Result<()> { let image: Option = info.image.as_ref().map(|i| i.clone().into()); let commit = info.checksum; + let configs = crate::config::configs_for_deployment(&sysroot, &deployment)?; if let Some(image) = image.as_ref() { println!("{booted_display} {image}"); if !info.supported { @@ -166,6 +167,14 @@ pub(crate) async fn status(opts: super::cli::StatusOpts) -> Result<()> { println!(); } println!(" Backend: ostree"); + if !configs.is_empty() { + println!(" Attached configmaps:"); + for config in configs { + let name = config.name; + let url = config.url; + println!(" {name}: {url}") + } + } if deployment.is_pinned() { println!(" Pinned: yes") } diff --git a/lib/src/utils.rs b/lib/src/utils.rs index 67ae9f7f..82b6d7ae 100644 --- a/lib/src/utils.rs +++ b/lib/src/utils.rs @@ -9,6 +9,11 @@ use ostree_ext::keyfileext::KeyFileExt; use ostree_ext::ostree; use serde::Serializer; +pub(crate) fn new_http_client() -> reqwest::ClientBuilder { + const USER_AGENT: &str = env!("CARGO_PKG_VERSION"); + reqwest::Client::builder().user_agent(USER_AGENT) +} + /// Parse an ostree origin file (a keyfile) and extract the targeted /// container image reference. pub(crate) fn get_image_origin(