Skip to content

Commit 0460c4d

Browse files
committed
cli: add system-reinstall-bootc binary
# Background The current usage instructions for bootc involve a long podman invocation. # Issue It's hard to remember and type the long podman invocation, making the usage of bootc difficult for users. See https://issues.redhat.com/browse/BIFROST-610 and https://issues.redhat.com/browse/BIFROST-611 (Epic https://issues.redhat.com/browse/BIFROST-594) # Solution We want to make the usage of bootc easier by providing a new Fedora/RHEL subpackage that includes a new binary `system-reinstall-bootc`. This binary will simplify the usage of bootc by providing a simple command line interface (configured either through CLI flags or a configuration file) with an interactive prompt that allows users to reinstall the current system using bootc. The commandline will handle helping the user choose SSH keys / users, warn the user about the destructive nature of the operation, and eventually report issues they might run into in the various clouds (e.g. missing cloud agent on the target image) # Implementation Added new system-reinstall-bootc crate that outputs the new system-reinstall-bootc binary. This new crate depends on the existing utils crate. Refactored the tracing initialization from the bootc binary into the utils crate so that it can be reused by the new crate. The new CLI can either be configured through commandline flags or through a configuration file in a path set by the environment variable `BOOTC_REINSTALL_CONFIG`. The configuration file is a YAML file. # Limitations Only root SSH keys are supported. The multi user selection TUI is implemented, but if you choose anything other than root you will get an error. # TODO Missing docs, missing functionality. Everything is in alpha stage. User choice / SSH keys / prompt disabling should also eventually be supported to be configured through commandline arguments or the configuration file. Signed-off-by: Omer Tuchfeld <[email protected]>
1 parent 2fd0458 commit 0460c4d

File tree

12 files changed

+495
-0
lines changed

12 files changed

+495
-0
lines changed

Cargo.lock

Lines changed: 52 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
[workspace]
22
members = [
33
"cli",
4+
"system-reinstall-bootc",
45
"lib",
56
"ostree-ext",
67
"utils",

Makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ all:
99

1010
install:
1111
install -D -m 0755 -t $(DESTDIR)$(prefix)/bin target/release/bootc
12+
install -D -m 0755 -t $(DESTDIR)$(prefix)/bin target/release/system-reinstall-bootc
1213
install -d -m 0755 $(DESTDIR)$(prefix)/lib/bootc/bound-images.d
1314
install -d -m 0755 $(DESTDIR)$(prefix)/lib/bootc/kargs.d
1415
ln -s /sysroot/ostree/bootc/storage $(DESTDIR)$(prefix)/lib/bootc/storage

system-reinstall-bootc/Cargo.toml

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
[package]
2+
name = "system-reinstall-bootc"
3+
version = "0.1.9"
4+
edition = "2021"
5+
license = "MIT OR Apache-2.0"
6+
repository = "https://github.com/containers/bootc"
7+
readme = "README.md"
8+
publish = false
9+
# For now don't bump this above what is currently shipped in RHEL9.
10+
rust-version = "1.75.0"
11+
12+
# See https://github.com/coreos/cargo-vendor-filterer
13+
[package.metadata.vendor-filter]
14+
# For now we only care about tier 1+2 Linux. (In practice, it's unlikely there is a tier3-only Linux dependency)
15+
platforms = ["*-unknown-linux-gnu"]
16+
17+
[dependencies]
18+
anyhow = { workspace = true }
19+
bootc-utils = { path = "../utils" }
20+
clap = { workspace = true, features = ["derive"] }
21+
dialoguer = "0.11.0"
22+
log = "0.4.21"
23+
rustix = { workspace = true }
24+
serde = { workspace = true, features = ["derive"] }
25+
serde_json = { workspace = true }
26+
serde_yaml = "0.9.22"
27+
tracing = { workspace = true }
28+
uzers = "0.12.1"
29+
30+
[lints]
31+
workspace = true
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# The bootc container image to install
2+
bootc_image: quay.io/fedora/fedora-bootc:41
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
use clap::Parser;
2+
3+
#[derive(Parser)]
4+
pub(crate) struct Cli {
5+
/// The bootc container image to install, e.g. quay.io/fedora/fedora-bootc:41
6+
pub(crate) bootc_image: String,
7+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
use anyhow::{ensure, Context, Result};
2+
use clap::Parser;
3+
use serde::{Deserialize, Serialize};
4+
5+
mod cli;
6+
7+
#[derive(Debug, Deserialize, Serialize)]
8+
#[serde(deny_unknown_fields)]
9+
pub(crate) struct ReinstallConfig {
10+
/// The bootc image to install on the system.
11+
pub(crate) bootc_image: String,
12+
13+
/// The raw CLI arguments that were used to invoke the program. None if the config was loaded
14+
/// from a file.
15+
#[serde(skip_deserializing)]
16+
cli_flags: Option<Vec<String>>,
17+
}
18+
19+
impl ReinstallConfig {
20+
pub fn parse_from_cli(cli: cli::Cli) -> Self {
21+
Self {
22+
bootc_image: cli.bootc_image,
23+
cli_flags: Some(std::env::args().collect::<Vec<String>>()),
24+
}
25+
}
26+
27+
pub fn load() -> Result<Self> {
28+
Ok(match std::env::var("BOOTC_REINSTALL_CONFIG") {
29+
Ok(config_path) => {
30+
ensure_no_cli_args()?;
31+
32+
serde_yaml::from_slice(
33+
&std::fs::read(&config_path)
34+
.context("reading BOOTC_REINSTALL_CONFIG file {config_path}")?,
35+
)
36+
.context("parsing BOOTC_REINSTALL_CONFIG file {config_path}")?
37+
}
38+
Err(_) => ReinstallConfig::parse_from_cli(cli::Cli::parse()),
39+
})
40+
}
41+
}
42+
43+
fn ensure_no_cli_args() -> Result<()> {
44+
let num_args = std::env::args().len();
45+
46+
ensure!(
47+
num_args == 1,
48+
"BOOTC_REINSTALL_CONFIG is set, but there are {num_args} CLI arguments. BOOTC_REINSTALL_CONFIG is meant to be used with no arguments."
49+
);
50+
51+
Ok(())
52+
}

system-reinstall-bootc/src/main.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
//! The main entrypoint for the bootc system reinstallation CLI
2+
3+
use anyhow::{ensure, Context, Result};
4+
use bootc_utils::CommandRunExt;
5+
use rustix::process::getuid;
6+
7+
mod config;
8+
mod podman;
9+
mod prompt;
10+
pub(crate) mod users;
11+
12+
const ROOT_KEY_MOUNT_POINT: &str = "/bootc_authorized_ssh_keys/root";
13+
14+
fn run() -> Result<()> {
15+
bootc_utils::initialize_tracing();
16+
tracing::trace!("starting {}", env!("CARGO_PKG_NAME"));
17+
18+
// Rootless podman is not supported by bootc
19+
ensure!(getuid().is_root(), "Must run as the root user");
20+
21+
let config = config::ReinstallConfig::load().context("loading config")?;
22+
23+
let mut reinstall_podman_command =
24+
podman::command(&config.bootc_image, &prompt::get_root_key()?);
25+
26+
println!();
27+
28+
println!("Going to run command {:?}", reinstall_podman_command);
29+
30+
prompt::temporary_developer_protection_prompt()?;
31+
32+
reinstall_podman_command
33+
.run_with_cmd_context()
34+
.context("running reinstall command")?;
35+
36+
Ok(())
37+
}
38+
39+
fn main() {
40+
// In order to print the error in a custom format (with :#) our
41+
// main simply invokes a run() where all the work is done.
42+
// This code just captures any errors.
43+
if let Err(e) = run() {
44+
tracing::error!("{:#}", e);
45+
std::process::exit(1);
46+
}
47+
}

system-reinstall-bootc/src/podman.rs

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
use std::process::Command;
2+
3+
use super::ROOT_KEY_MOUNT_POINT;
4+
use crate::users::UserKeys;
5+
6+
pub(crate) fn command(image: &str, root_key: &Option<UserKeys>) -> Command {
7+
let mut podman_command_and_args = [
8+
// We use podman to run the bootc container. This might change in the future to remove the
9+
// podman dependency.
10+
"podman",
11+
"run",
12+
// The container needs to be privileged, as it heavily modifies the host
13+
"--privileged",
14+
// The container needs to access the host's PID namespace to mount host directories
15+
"--pid=host",
16+
// Since https://github.com/containers/bootc/pull/919 this mount should not be needed, but
17+
// some reason with e.g. quay.io/fedora/fedora-bootc:41 it is still needed.
18+
"-v",
19+
"/var/lib/containers:/var/lib/containers",
20+
]
21+
.map(String::from)
22+
.to_vec();
23+
24+
let mut bootc_command_and_args = [
25+
"bootc",
26+
"install",
27+
// We're replacing the current root
28+
"to-existing-root",
29+
// The user already knows they're reinstalling their machine, that's the entire purpose of
30+
// this binary. Since this is no longer an "arcane" bootc command, we can safely avoid this
31+
// timed warning prompt. TODO: Discuss in https://github.com/containers/bootc/discussions/1060
32+
"--acknowledge-destructive",
33+
]
34+
.map(String::from)
35+
.to_vec();
36+
37+
if let Some(root_key) = root_key.as_ref() {
38+
let root_authorized_keys_path = root_key.authorized_keys_path.clone();
39+
40+
podman_command_and_args.push("-v".to_string());
41+
podman_command_and_args.push(format!(
42+
"{root_authorized_keys_path}:{ROOT_KEY_MOUNT_POINT}"
43+
));
44+
45+
bootc_command_and_args.push("--root-ssh-authorized-keys".to_string());
46+
bootc_command_and_args.push(ROOT_KEY_MOUNT_POINT.to_string());
47+
}
48+
49+
let all_args = [
50+
podman_command_and_args,
51+
vec![image.to_string()],
52+
bootc_command_and_args,
53+
]
54+
.concat();
55+
56+
let mut command = Command::new(&all_args[0]);
57+
command.args(&all_args[1..]);
58+
59+
command
60+
}

system-reinstall-bootc/src/prompt.rs

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
use crate::users::{get_all_users_keys, UserKeys};
2+
use anyhow::{ensure, Context, Result};
3+
4+
fn prompt_single_user(user: &crate::users::UserKeys) -> Result<Vec<&crate::users::UserKeys>> {
5+
let prompt = format!(
6+
"Found only one user ({}) with {} SSH authorized keys. Would you like to install this user in the system?",
7+
user.user,
8+
user.num_keys(),
9+
);
10+
let answer = ask_yes_no(&prompt, true)?;
11+
Ok(if answer { vec![&user] } else { vec![] })
12+
}
13+
14+
fn prompt_user_selection(
15+
all_users: &[crate::users::UserKeys],
16+
) -> Result<Vec<&crate::users::UserKeys>> {
17+
let keys: Vec<String> = all_users.iter().map(|x| x.user.clone()).collect();
18+
19+
// TODO: Handle https://github.com/console-rs/dialoguer/issues/77
20+
let selected_user_indices: Vec<usize> = dialoguer::MultiSelect::new()
21+
.with_prompt("Select the users you want to install in the system (along with their authorized SSH keys)")
22+
.items(&keys)
23+
.interact()?;
24+
25+
Ok(selected_user_indices
26+
.iter()
27+
// Safe unwrap because we know the index is valid
28+
.map(|x| all_users.get(*x).unwrap())
29+
.collect())
30+
}
31+
32+
/// Temporary safety mechanism to stop devs from running it on their dev machine. TODO: Discuss
33+
/// final prompting UX in https://github.com/containers/bootc/discussions/1060
34+
pub(crate) fn temporary_developer_protection_prompt() -> Result<()> {
35+
// Print an empty line so that the warning stands out from the rest of the output
36+
println!();
37+
38+
let prompt = "THIS WILL REINSTALL YOUR SYSTEM! Are you sure you want to continue?";
39+
let answer = ask_yes_no(prompt, false)?;
40+
41+
if !answer {
42+
println!("Exiting without reinstalling the system.");
43+
std::process::exit(0);
44+
}
45+
46+
Ok(())
47+
}
48+
49+
pub(crate) fn ask_yes_no(prompt: &str, default: bool) -> Result<bool> {
50+
dialoguer::Confirm::new()
51+
.with_prompt(prompt)
52+
.default(default)
53+
.wait_for_newline(true)
54+
.interact()
55+
.context("prompting")
56+
}
57+
58+
/// For now we only support the root user. This function returns the root user's SSH
59+
/// authorized_keys. In the future, when bootc supports multiple users, this function will need to
60+
/// be updated to return the SSH authorized_keys for all the users selected by the user.
61+
pub(crate) fn get_root_key() -> Result<Option<UserKeys>> {
62+
let users = get_all_users_keys()?;
63+
if users.is_empty() {
64+
return Ok(None);
65+
}
66+
67+
let selected_users = if users.len() == 1 {
68+
prompt_single_user(&users[0])?
69+
} else {
70+
prompt_user_selection(&users)?
71+
};
72+
73+
ensure!(
74+
selected_users.iter().all(|x| x.user == "root"),
75+
"Only importing the root user keys is supported for now"
76+
);
77+
78+
let root_key = selected_users.into_iter().find(|x| x.user == "root");
79+
80+
Ok(root_key.cloned())
81+
}

0 commit comments

Comments
 (0)