1
0
mirror of https://github.com/containers/bootc.git synced 2026-02-05 15:45:53 +01:00
Prep for potentially moving to github.com/containers/bootc
This commit is contained in:
Colin Walters
2022-11-30 13:18:17 -05:00
commit 3ab28788ce
17 changed files with 1041 additions and 0 deletions

130
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,130 @@
name: CI
permissions:
actions: read
on:
push:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch: {}
env:
CARGO_TERM_COLOR: always
# Pinned toolchain for linting
ACTION_LINTS_TOOLCHAIN: 1.63.0
jobs:
tests:
runs-on: ubuntu-latest
container: quay.io/coreos-assembler/fcos-buildroot:testing-devel
steps:
- uses: actions/checkout@v3
- name: Code lints
run: ./ci/lints.sh
- name: Install deps
run: ./ci/installdeps.sh
# xref containers/containers-image-proxy-rs
- name: Cache Dependencies
uses: Swatinem/rust-cache@v2
with:
key: "tests"
- name: Build
run: cargo test --no-run
- name: Individual checks
run: (cd cli && cargo check) && (cd lib && cargo check)
- name: Run tests
run: cargo test -- --nocapture --quiet
- name: Manpage generation
run: mkdir -p target/man && cargo run --features=docgen -- man --directory target/man
build:
runs-on: ubuntu-latest
container: quay.io/coreos-assembler/fcos-buildroot:testing-devel
steps:
- uses: actions/checkout@v3
- name: Install deps
run: ./ci/installdeps.sh
- name: Cache Dependencies
uses: Swatinem/rust-cache@v2
with:
key: "build"
- name: Build
run: cargo build --release
- name: Upload binary
uses: actions/upload-artifact@v2
with:
name: bootc
path: target/release/bootc
build-minimum-toolchain:
name: "Build using MSRV"
runs-on: ubuntu-latest
container: quay.io/coreos-assembler/fcos-buildroot:testing-devel
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Install deps
run: ./ci/installdeps.sh
- name: Detect crate MSRV
shell: bash
run: |
msrv=$(cargo metadata --format-version 1 --no-deps | \
jq -r '.packages[1].rust_version')
echo "Crate MSRV: $msrv"
echo "ACTION_MSRV_TOOLCHAIN=$msrv" >> $GITHUB_ENV
- name: Remove system Rust toolchain
run: dnf remove -y rust cargo
- uses: dtolnay/rust-toolchain@master
with:
toolchain: ${{ env['ACTION_MSRV_TOOLCHAIN'] }}
- name: Cache Dependencies
uses: Swatinem/rust-cache@v2
with:
key: "min"
- name: cargo check
run: cargo check
cargo-deny:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: EmbarkStudios/cargo-deny-action@v1
with:
log-level: warn
command: check bans sources licenses
linting:
name: "Lints, pinned toolchain"
runs-on: ubuntu-latest
container: quay.io/coreos-assembler/fcos-buildroot:testing-devel
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Install deps
run: ./ci/installdeps.sh
- name: Remove system Rust toolchain
run: dnf remove -y rust cargo
- uses: dtolnay/rust-toolchain@master
with:
toolchain: ${{ env['ACTION_LINTS_TOOLCHAIN'] }}
components: rustfmt, clippy
- name: cargo fmt (check)
run: cargo fmt -- --check -l
- name: cargo clippy (warnings)
run: cargo clippy -- -D warnings
# privtest:
# name: "Privileged testing"
# needs: build
# runs-on: ubuntu-latest
# container:
# image: quay.io/fedora/fedora-coreos:testing-devel
# options: "--privileged --pid=host -v /run/systemd:/run/systemd -v /:/run/host"
# steps:
# - name: Checkout repository
# uses: actions/checkout@v3
# - name: Download
# uses: actions/download-artifact@v2
# with:
# name: bootc
# - name: Install
# run: install bootc /usr/bin && rm -v bootc
# - name: Integration tests
# run: ./ci/priv-integration.sh

7
.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
example
# Added by cargo
/target
Cargo.lock

8
Cargo.toml Normal file
View File

@@ -0,0 +1,8 @@
[workspace]
members = ["cli", "lib"]
[profile.dev]
opt-level = 1 # No optimizations are too slow for us.
[profile.release]
lto = "thin"

202
LICENSE-APACHE Normal file
View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

19
LICENSE-MIT Normal file
View File

@@ -0,0 +1,19 @@
Copyright (c) 2016 The openat Developers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

11
README.md Normal file
View File

@@ -0,0 +1,11 @@
# bootc
In place operating system updates via OCI/Docker container images.
## ostree
This project currently leverages significant work done in
[the ostree project](https://github.com/ostreedev/ostree-rs-ext/).
In the future, there may be non-ostree backends.

25
ci/installdeps.sh Executable file
View File

@@ -0,0 +1,25 @@
#!/bin/bash
set -xeuo pipefail
# For some reason dnf copr enable -y says there are no builds?
cat >/etc/yum.repos.d/coreos-continuous.repo << 'EOF'
[copr:copr.fedorainfracloud.org:group_CoreOS:continuous]
name=Copr repo for continuous owned by @CoreOS
baseurl=https://download.copr.fedorainfracloud.org/results/@CoreOS/continuous/fedora-$releasever-$basearch/
type=rpm-md
skip_if_unavailable=True
gpgcheck=1
gpgkey=https://download.copr.fedorainfracloud.org/results/@CoreOS/continuous/pubkey.gpg
repo_gpgcheck=0
enabled=1
enabled_metadata=1
EOF
# Pull skopeo and ostree from updates-testing, since we depend on new features in our git main
dnf config-manager --set-enabled updates-testing
# Our tests depend on this
dnf -y install skopeo
# Always pull ostree from updates-testing to avoid the bodhi wait
dnf -y update ostree

9
ci/lints.sh Executable file
View File

@@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -xeuo pipefail
tmpf=$(mktemp)
git grep 'dbg!' '*.rs' > ${tmpf} || true
if test -s ${tmpf}; then
echo "Found dbg!" 1>&2
cat "${tmpf}"
exit 1
fi

28
ci/priv-integration.sh Executable file
View File

@@ -0,0 +1,28 @@
#!/bin/bash
# Assumes that the current environment is a privileged container
# with the host mounted at /run/host. We can basically write
# whatever we want, however we can't actually *reboot* the host.
set -euo pipefail
# https://github.com/ostreedev/ostree-rs-ext/issues/417
mkdir -p /var/tmp
sysroot=/run/host
# Current stable image fixture
image=quay.io/fedora/fedora-coreos:testing-devel
old_image=quay.io/cgwalters/fcos:unchunked
imgref=ostree-unverified-registry:${image}
stateroot=testos
set -x
if test '!' -e "${sysroot}/ostree"; then
ostree admin init-fs --modern "${sysroot}"
ostree config --repo $sysroot/ostree/repo set sysroot.bootloader none
fi
if test '!' -d "${sysroot}/ostree/deploy/${stateroot}"; then
ostree admin os-init "${stateroot}" --sysroot "${sysroot}"
fi
ostree-ext-cli container image deploy --sysroot "${sysroot}" \
--stateroot "${stateroot}" --imgref "${imgref}"
chroot /run/host bootc status > status.txt

19
cli/Cargo.toml Normal file
View File

@@ -0,0 +1,19 @@
[package]
name = "bootc"
version = "0.1.0"
edition = "2021"
license = "MIT OR Apache-2.0"
repository = "https://github.com/cgwalters/bootc"
readme = "README.md"
publish = false
rust-version = "1.63.0"
[dependencies]
anyhow = "1.0"
bootc-lib = { path = "../lib" }
clap = "3.2"
libc = "0.2.92"
tokio = { version = "1", features = ["macros"] }
log = "0.4.0"
tracing = "0.1"
tracing-subscriber = "0.2.17"

19
cli/src/main.rs Normal file
View File

@@ -0,0 +1,19 @@
// Good defaults
#![forbid(unused_must_use)]
#![deny(unsafe_code)]
use anyhow::Result;
async fn run() -> Result<()> {
tracing_subscriber::fmt::init();
tracing::trace!("starting");
bootc_lib::cli::run_from_iter(std::env::args()).await
}
#[tokio::main(flavor = "current_thread")]
async fn main() {
if let Err(e) = run().await {
eprintln!("error: {:#}", e);
std::process::exit(1);
}
}

10
deny.toml Normal file
View File

@@ -0,0 +1,10 @@
[licenses]
unlicensed = "deny"
allow = ["Apache-2.0", "Apache-2.0 WITH LLVM-exception", "MIT", "BSD-3-Clause", "BSD-2-Clause", "Unicode-DFS-2016"]
[bans]
[sources]
unknown-registry = "deny"
unknown-git = "deny"
allow-git = []

27
lib/Cargo.toml Normal file
View File

@@ -0,0 +1,27 @@
[package]
description = "bootc implementation"
edition = "2021"
license = "MIT OR Apache-2.0"
name = "bootc-lib"
readme = "README.md"
repository = "https://github.com/cgwalters/bootc"
version = "0.1.0"
rust-version = "1.63.0"
[dependencies]
anyhow = "1.0"
camino = "1.0.4"
ostree-ext = { git = "https://github.com/ostreedev/ostree-rs-ext" }
clap = { version= "3.2", features = ["derive"] }
clap_mangen = { version = "0.1", optional = true }
cap-std-ext = "1.0.1"
indicatif = "0.17.0"
serde = { features = ["derive"], version = "1.0.125" }
serde_json = "1.0.64"
tokio = { features = ["io-std", "time", "process", "rt", "net"], version = ">= 1.13.0" }
tokio-util = { features = ["io-util"], version = "0.7" }
tracing = "0.1"
[features]
docgen = ["clap_mangen"]

1
lib/README.md Symbolic link
View File

@@ -0,0 +1 @@
../README.md

465
lib/src/cli.rs Normal file
View File

@@ -0,0 +1,465 @@
//! # Bootable container image CLI
//!
//! Command line tool to manage bootable ostree-based containers.
use anyhow::{Context, Result};
use camino::Utf8PathBuf;
use clap::Parser;
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::keyfileext::KeyFileExt;
use ostree_ext::ostree;
use std::ffi::OsString;
use std::ops::Deref;
use std::os::unix::process::CommandExt;
use tokio::sync::mpsc::Receiver;
/// Perform an upgrade operation
#[derive(Debug, Parser)]
pub(crate) struct UpgradeOpts {
/// Don't display progress
#[clap(long)]
quiet: bool,
#[clap(long)]
touch_if_changed: Option<Utf8PathBuf>,
}
/// Perform an upgrade operation
#[derive(Debug, Parser)]
pub(crate) struct SwitchOpts {
/// Don't display progress
#[clap(long)]
quiet: bool,
/// The transport; e.g. oci, oci-archive. Defaults to `registry`.
#[clap(long, default_value = "registry")]
transport: String,
/// Explicitly opt-out of requiring any form of signature verification.
#[clap(long)]
no_signature_verification: bool,
/// Enable verification via an ostree remote
#[clap(long)]
ostree_remote: Option<String>,
/// Retain reference to currently booted image
#[clap(long)]
retain: bool,
/// Target image to use for the next boot.
target: String,
}
/// Perform an upgrade operation
#[derive(Debug, Parser)]
pub(crate) struct StatusOpts {
/// Output in JSON format.
#[clap(long)]
json: bool,
/// Only display status for the booted deployment.
#[clap(long)]
booted: bool,
}
/// Options for man page generation
#[derive(Debug, Parser)]
pub(crate) struct ManOpts {
#[clap(long)]
/// Output to this directory
directory: Utf8PathBuf,
}
/// Deploy and upgrade via bootable container images.
#[derive(Debug, Parser)]
#[clap(name = "bootc")]
#[clap(rename_all = "kebab-case")]
#[allow(clippy::large_enum_variant)]
pub(crate) enum Opt {
/// Look for updates to the booted container image.
Upgrade(UpgradeOpts),
/// Target a new container image reference to boot.
Switch(SwitchOpts),
/// Display status
Status(StatusOpts),
#[clap(hide(true))]
#[cfg(feature = "docgen")]
Man(ManOpts),
}
async fn ensure_self_unshared_mount_namespace() -> Result<()> {
let uid = cap_std_ext::rustix::process::getuid();
if !uid.is_root() {
return Ok(());
}
let recurse_env = "_ostree_unshared";
let ns_pid1 = std::fs::read_link("/proc/1/ns/mnt").context("Reading /proc/1/ns/mnt")?;
let ns_self = std::fs::read_link("/proc/self/ns/mnt").context("Reading /proc/self/ns/mnt")?;
// If we already appear to be in a mount namespace, we're done
if ns_pid1 != ns_self {
return Ok(());
}
if std::env::var_os(recurse_env).is_some() {
anyhow::bail!("Failed to unshare mount namespace");
}
let self_exe = std::fs::read_link("/proc/self/exe")?;
let mut cmd = std::process::Command::new("unshare");
cmd.env(recurse_env, "1");
cmd.args(["-m", "--"])
.arg(self_exe)
.args(std::env::args_os().skip(1));
Err(cmd.exec().into())
}
async fn get_locked_sysroot() -> Result<ostree_ext::sysroot::SysrootLock> {
let sysroot = ostree::Sysroot::new_default();
sysroot.set_mount_namespace_in_use();
let sysroot = ostree_ext::sysroot::SysrootLock::new_from_sysroot(&sysroot).await?;
sysroot.load(gio::Cancellable::NONE)?;
Ok(sysroot)
}
pub(crate) async fn handle_layer_progress_print(
mut layers: Receiver<ostree_container::store::ImportProgress>,
mut layer_bytes: tokio::sync::watch::Receiver<Option<ostree_container::store::LayerProgress>>,
) {
let style = indicatif::ProgressStyle::default_bar();
let pb = indicatif::ProgressBar::new(100);
pb.set_style(
style
.template("{prefix} {bytes} [{bar:20}] ({eta}) {msg}")
.unwrap(),
);
loop {
tokio::select! {
// Always handle layer changes first.
biased;
layer = layers.recv() => {
if let Some(l) = layer {
if l.is_starting() {
pb.set_position(0);
} else {
pb.finish();
}
pb.set_message(ostree_ext::cli::layer_progress_format(&l));
} else {
// If the receiver is disconnected, then we're done
break
};
},
r = layer_bytes.changed() => {
if r.is_err() {
// If the receiver is disconnected, then we're done
break
}
let bytes = layer_bytes.borrow();
if let Some(bytes) = &*bytes {
pb.set_length(bytes.total);
pb.set_position(bytes.fetched);
}
}
}
}
}
async fn pull(
repo: &ostree::Repo,
imgref: &OstreeImageReference,
quiet: bool,
) -> Result<Box<LayeredImageState>> {
let config = Default::default();
let mut imp = ostree_container::store::ImageImporter::new(repo, imgref, config).await?;
let prep = match imp.prepare().await? {
PrepareResult::AlreadyPresent(c) => {
println!("No changes in {} => {}", imgref, c.manifest_digest);
return Ok(c);
}
PrepareResult::Ready(p) => p,
};
if let Some(warning) = prep.deprecated_warning() {
crate::cli::print_deprecated_warning(warning);
}
crate::cli::print_layer_status(&prep);
let printer = (!quiet).then(|| {
let layer_progress = imp.request_progress();
let layer_byte_progress = imp.request_layer_progress();
tokio::task::spawn(async move {
handle_layer_progress_print(layer_progress, layer_byte_progress).await
})
});
let import = imp.import(prep).await;
if let Some(printer) = printer {
let _ = printer.await;
}
let import = import?;
if let Some(msg) =
ostree_container::store::image_filtered_content_warning(repo, &imgref.imgref)?
{
eprintln!("{msg}")
}
Ok(import)
}
fn get_image_origin(
deployment: &ostree::Deployment,
) -> Result<(glib::KeyFile, Option<OstreeImageReference>)> {
let origin = deployment
.origin()
.ok_or_else(|| anyhow::anyhow!("Missing origin"))?;
let imgref = origin
.optional_string("origin", ostree_container::deploy::ORIGIN_CONTAINER)
.context("Failed to load container image from origin")?
.map(|v| ostree_container::OstreeImageReference::try_from(v.as_str()))
.transpose()?;
Ok((origin, imgref))
}
fn print_staged(deployment: &ostree::Deployment) -> Result<()> {
let (_origin, imgref) = get_image_origin(deployment)?;
let imgref = imgref.ok_or_else(|| {
anyhow::anyhow!("Internal error: expected a container deployment to be staged")
})?;
println!("Queued for next boot: {imgref}");
Ok(())
}
pub(crate) fn print_layer_status(prep: &ostree_container::store::PreparedImport) {
let (stored, to_fetch, to_fetch_size) =
prep.all_layers()
.fold((0u32, 0u32, 0u64), |(stored, to_fetch, sz), v| {
if v.commit.is_some() {
(stored + 1, to_fetch, sz)
} else {
(stored, to_fetch + 1, sz + v.size())
}
});
if to_fetch > 0 {
let size = glib::format_size(to_fetch_size);
println!("layers stored: {stored} needed: {to_fetch} ({size})")
}
}
pub(crate) fn print_deprecated_warning(msg: &str) {
eprintln!("warning: {msg}");
std::thread::sleep(std::time::Duration::from_secs(3));
}
async fn upgrade(opts: UpgradeOpts) -> Result<()> {
let cancellable = gio::Cancellable::NONE;
let sysroot = &get_locked_sysroot().await?;
let repo = &sysroot.repo().unwrap();
let booted_deployment = &sysroot.require_booted_deployment()?;
let osname = booted_deployment.osname().unwrap();
let osname_v = Some(osname.as_str());
let (origin, imgref) = get_image_origin(booted_deployment)?;
let imgref =
imgref.ok_or_else(|| anyhow::anyhow!("Booted deployment is not container image based"))?;
let commit = booted_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?;
if fetched.merge_commit.as_str() == commit.as_str() {
println!("Already queued: {digest}");
return Ok(());
}
let merge_deployment = sysroot.merge_deployment(osname_v);
let new_deployment = sysroot.stage_tree(
osname_v,
fetched.merge_commit.as_str(),
Some(&origin),
merge_deployment.as_ref(),
&[],
cancellable,
)?;
print_staged(&new_deployment)?;
if let Some(path) = opts.touch_if_changed {
std::fs::write(&path, "").with_context(|| format!("Writing {path}"))?;
}
Ok(())
}
async fn switch(opts: SwitchOpts) -> Result<()> {
let cancellable = gio::Cancellable::NONE;
let l = get_locked_sysroot().await?;
let sysroot = l.deref();
let booted_deployment = &sysroot.require_booted_deployment()?;
let (origin, booted_image) = get_image_origin(booted_deployment)?;
let booted_refspec = origin.optional_string("origin", "refspec")?;
let osname = booted_deployment.osname().unwrap();
let osname_v = Some(osname.as_str());
let repo = &sysroot.repo().unwrap();
let transport = ostree_container::Transport::try_from(opts.transport.as_str())?;
let imgref = ostree_container::ImageReference {
transport,
name: opts.target.to_string(),
};
use ostree_container::SignatureSource;
let sigverify = if opts.no_signature_verification {
SignatureSource::ContainerPolicyAllowInsecure
} else if let Some(remote) = opts.ostree_remote.as_ref() {
SignatureSource::OstreeRemote(remote.to_string())
} else {
SignatureSource::ContainerPolicy
};
let target = ostree_container::OstreeImageReference { sigverify, imgref };
let fetched = pull(repo, &target, opts.quiet).await?;
let merge_deployment = sysroot.merge_deployment(osname_v);
origin.set_string(
"origin",
ostree_container::deploy::ORIGIN_CONTAINER,
target.to_string().as_str(),
);
if !opts.retain {
// By default, we prune the previous ostree ref or container image
if let Some(ostree_ref) = booted_refspec {
repo.set_ref_immediate(None, &ostree_ref, None, cancellable)?;
origin.remove_key("origin", "refspec")?;
} else if let Some(booted_image) = booted_image.as_ref() {
ostree_container::store::remove_image(repo, &booted_image.imgref)?;
let _nlayers: u32 = ostree_container::store::gc_image_layers(repo)?;
}
}
let new_deployment = sysroot.stage_tree(
osname_v,
fetched.merge_commit.as_str(),
Some(&origin),
merge_deployment.as_ref(),
&[],
cancellable,
)?;
print_staged(&new_deployment)?;
Ok(())
}
fn serialize_image_reference<S>(
txn: &Option<ostree_container::OstreeImageReference>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match txn {
Some(v) => serializer.serialize_some(v.to_string().as_str()),
None => serializer.serialize_none(),
}
}
#[derive(serde::Serialize)]
struct DeploymentStatus {
pinned: bool,
booted: bool,
staged: bool,
#[serde(serialize_with = "serialize_image_reference")]
image: Option<ostree_container::OstreeImageReference>,
checksum: String,
#[serde(skip_serializing_if = "Option::is_none")]
deploy_serial: Option<u32>,
}
async fn status(opts: StatusOpts) -> Result<()> {
let l = get_locked_sysroot().await?;
let sysroot = l.deref();
let repo = &sysroot.repo().unwrap();
let booted_deployment = &sysroot.require_booted_deployment()?;
if opts.json {
let deployments = sysroot
.deployments()
.into_iter()
.filter(|deployment| !opts.booted || deployment.equal(booted_deployment))
.map(|deployment| -> Result<DeploymentStatus> {
let booted = deployment.equal(booted_deployment);
let staged = deployment.is_staged();
let pinned = deployment.is_pinned();
let image = get_image_origin(&deployment)?.1;
let checksum = deployment.csum().unwrap().to_string();
let deploy_serial = (!staged).then(|| deployment.bootserial().try_into().unwrap());
Ok(DeploymentStatus {
staged,
pinned,
booted,
image,
checksum,
deploy_serial,
})
})
.collect::<Result<Vec<_>>>()?;
let out = std::io::stdout();
let mut out = out.lock();
serde_json::to_writer(&mut out, &deployments).context("Writing to stdout")?;
return Ok(());
}
for deployment in sysroot.deployments() {
let booted = deployment.equal(booted_deployment);
let booted_display = booted.then(|| "* ").unwrap_or(" ");
let image = get_image_origin(&deployment)?.1;
let commit = deployment.csum().unwrap();
let serial = deployment.deployserial();
if let Some(image) = image.as_ref() {
println!("{booted_display} {image}");
let state = ostree_container::store::query_image_commit(repo, &commit)?;
println!(" Digest: {}", state.manifest_digest.as_str());
let config = state.configuration.as_ref();
let cconfig = config.and_then(|c| c.config().as_ref());
let labels = cconfig.and_then(|c| c.labels().as_ref());
if let Some(labels) = labels {
if let Some(version) = labels.get("version") {
println!(" Version: {version}");
}
}
} else {
println!("{booted_display} {commit}.{serial}");
println!(" (Non-container origin type)");
println!();
}
if deployment.is_pinned() {
println!(" Pinned: yes")
}
if booted {
println!(" Booted: yes")
} else if deployment.is_staged() {
println!(" Staged: yes");
}
println!();
}
Ok(())
}
/// Parse the provided arguments and execute.
/// Calls [`structopt::clap::Error::exit`] on failure, printing the error message and aborting the program.
pub async fn run_from_iter<I>(args: I) -> Result<()>
where
I: IntoIterator,
I::Item: Into<OsString> + Clone,
{
ensure_self_unshared_mount_namespace().await?;
let opt = Opt::parse_from(args);
match opt {
Opt::Upgrade(opts) => upgrade(opts).await,
Opt::Switch(opts) => switch(opts).await,
Opt::Status(opts) => status(opts).await,
#[cfg(feature = "docgen")]
Opt::Man(manopts) => crate::docgen::generate_manpages(&manopts.directory),
}
}

42
lib/src/docgen.rs Normal file
View File

@@ -0,0 +1,42 @@
// Copyright 2022 Red Hat, Inc.
//
// SPDX-License-Identifier: Apache-2.0 OR MIT
use anyhow::{Context, Result};
use camino::Utf8Path;
use clap::{Command, CommandFactory};
use std::fs::OpenOptions;
use std::io::Write;
pub fn generate_manpages(directory: &Utf8Path) -> Result<()> {
generate_one(directory, crate::cli::Opt::command())
}
fn generate_one(directory: &Utf8Path, cmd: Command) -> Result<()> {
let version = env!("CARGO_PKG_VERSION");
let name = cmd.get_name();
let path = directory.join(format!("{name}.8"));
println!("Generating {path}...");
let mut out = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(&path)
.with_context(|| format!("opening {path}"))
.map(std::io::BufWriter::new)?;
clap_mangen::Man::new(cmd.clone())
.title("bootc")
.section("8")
.source(format!("bootc {version}"))
.render(&mut out)
.with_context(|| format!("rendering {name}.8"))?;
out.flush().context("flushing man page")?;
drop(out);
for subcmd in cmd.get_subcommands().filter(|c| !c.is_hide_set()) {
let subname = format!("{}-{}", name, subcmd.get_name());
generate_one(directory, subcmd.clone().name(subname).version(version))?;
}
Ok(())
}

19
lib/src/lib.rs Normal file
View File

@@ -0,0 +1,19 @@
//! # Bootable container tool
//!
//! This crate builds on top of ostree's container functionality
//! to provide a fully "container native" tool for using
//! bootable container images.
// See https://doc.rust-lang.org/rustc/lints/listing/allowed-by-default.html
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![forbid(unused_must_use)]
#![deny(unsafe_code)]
#![cfg_attr(feature = "dox", feature(doc_cfg))]
#![deny(clippy::dbg_macro)]
#![deny(clippy::todo)]
pub mod cli;
#[cfg(feature = "docgen")]
mod docgen;