feat: move install commands from xtask into clap subcommands

This commit is contained in:
Willem Vanhulle committed 2026-10-25 12:03:39 +01:00
1 parent 4dad85473b
commit 3acc577aac
15 files changed
+463 -381

No files matched your search

Generated
-1
View File
@@ -2303,7 +2303,6 @@ name = "xtask"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"clap", "clap",
"rustix 1.1.5",
"thiserror 2.0.21", "thiserror 2.0.21",
"xshell", "xshell",
] ]
+15 -9
View File
@@ -1,9 +1,13 @@
# bootvine # bootvine
A live tree of systemd jobs on the boot console, in the spirit of A live tree of systemd jobs on the boot console, in the spirit of
nix-output-monitor. It replaces the scrolling kernel and systemd lines with the [nix-output-monitor](https://github.com/maralorn/nix-output-monitor). It
units still pending and, in the room the tree leaves, a timeline of the slowest replaces the scrolling kernel and systemd lines with the units still pending
ones that ran. and, in the room the tree leaves, a timeline of the slowest ones that ran.
I started bootvine out of frustration with the boot screen of most Linux
distributions: a wall of log lines scrolling past too fast to read, which never
gave me any idea of what was going on.
<img src="https://codeberg.org/wvhulle/bootvine/raw/branch/main/recordings/boot.gif" width="691" alt="A boot through the initrd into stage 2, with one failed unit"> <img src="https://codeberg.org/wvhulle/bootvine/raw/branch/main/recordings/boot.gif" width="691" alt="A boot through the initrd into stage 2, with one failed unit">
@@ -12,12 +16,14 @@ units that have to stop first.
<img src="https://codeberg.org/wvhulle/bootvine/raw/branch/main/recordings/shutdown.gif" width="691" alt="A poweroff: units stopping under the targets waiting on them"> <img src="https://codeberg.org/wvhulle/bootvine/raw/branch/main/recordings/shutdown.gif" width="691" alt="A poweroff: units stopping under the targets waiting on them">
Passphrase prompts, such as a LUKS unlock in the initrd, are answered in place Passphrase prompts, such as a
over the tree. [LUKS](https://gitlab.com/cryptsetup/cryptsetup) unlock in the initrd, are
answered in place over the tree.
<img src="https://codeberg.org/wvhulle/bootvine/raw/branch/main/recordings/passphrase.png" width="640" alt="A LUKS passphrase prompt floating over the initrd tree"> <img src="https://codeberg.org/wvhulle/bootvine/raw/branch/main/recordings/passphrase.png" width="640" alt="A LUKS passphrase prompt floating over the initrd tree">
It needs systemd ≥ 246 as PID 1, libdbus and a virtual terminal. With a It needs systemd ≥ 246 as PID 1,
[libdbus](https://www.freedesktop.org/wiki/Software/dbus/) and a virtual terminal. With a
systemd initrd it shows the boot from about a second after the kernel starts. systemd initrd it shows the boot from about a second after the kernel starts.
## Try it without installing ## Try it without installing
@@ -25,7 +31,7 @@ systemd initrd it shows the boot from about a second after the kernel starts.
Neither of these touches your system's boot. Neither of these touches your system's boot.
Play a scripted boot, poweroff and encrypted-root boot in your terminal, with Play a scripted boot, poweroff and encrypted-root boot in your terminal, with
Rust installed: [Rust](https://www.rust-lang.org/tools/install) installed:
```sh ```sh
git clone https://codeberg.org/wvhulle/bootvine.git git clone https://codeberg.org/wvhulle/bootvine.git
@@ -38,8 +44,8 @@ cargo run --example luks
`q` quits. The encrypted root unlocks with the passphrase `demo`; `Esc` quits `q` quits. The encrypted root unlocks with the passphrase `demo`; `Esc` quits
while it asks. while it asks.
Or, with Nix, boot a sample NixOS machine with slow and failing units in a Or, with [Nix](https://nixos.org/download/), boot a sample [NixOS](https://nixos.org) machine with slow and
QEMU window: failing units in a [QEMU](https://www.qemu.org) window:
```sh ```sh
nix run git+https://codeberg.org/wvhulle/bootvine#sample-machine-vm nix run git+https://codeberg.org/wvhulle/bootvine#sample-machine-vm
+7 -4
View File
@@ -7,8 +7,9 @@ while it does. None of this is needed to install or configure it.
- **systemd ≥ 246 as PID 1.** bootvine reads the jobs and units from the - **systemd ≥ 246 as PID 1.** bootvine reads the jobs and units from the
service manager over D-Bus. service manager over D-Bus.
- **libdbus.** It talks to PID 1 over systemd's private socket, which zbus - **[libdbus](https://www.freedesktop.org/wiki/Software/dbus/).** It talks to
cannot use; see [systemd's private socket](#systemds-private-socket). PID 1 over systemd's private socket, which
[zbus](https://github.com/dbus2/zbus) cannot use; see [systemd's private socket](#systemds-private-socket).
- **A virtual terminal.** It draws on `tty12` and switches the console to it. - **A virtual terminal.** It draws on `tty12` and switches the console to it.
## Lifecycle ## Lifecycle
@@ -52,8 +53,10 @@ back. Kernel messages from before it starts are already on screen; see
### Passphrase prompts ### Passphrase prompts
bootvine acts as a systemd password agent: it watches bootvine acts as a systemd
`/run/systemd/ask-password` and answers requests, such as a LUKS unlock, in a [password agent](https://systemd.io/PASSWORD_AGENTS/): it watches
`/run/systemd/ask-password` and answers requests, such as a
[LUKS](https://gitlab.com/cryptsetup/cryptsetup) unlock, in a
popup over the tree. If another agent's prompt is already showing when it popup over the tree. If another agent's prompt is already showing when it
starts, it stays behind it and comes forward once the prompt is answered. starts, it stays behind it and comes forward once the prompt is answered.
+3 -2
View File
@@ -3,7 +3,7 @@
Every setting has a default, so bootvine needs no configuration. To change Every setting has a default, so bootvine needs no configuration. To change
some, write only those keys: some, write only those keys:
- **On NixOS**, under `services.bootvine.settings`. The module writes them to - **On [NixOS](https://nixos.org)**, under `services.bootvine.settings`. The module writes them to
`/etc/bootvine.toml` in the real root and the initrd, and the rebuild fails `/etc/bootvine.toml` in the real root and the initrd, and the rebuild fails
if `bootvine check` rejects them. if `bootvine check` rejects them.
@@ -25,7 +25,8 @@ some, write only those keys:
``` ```
Then check the file and, if bootvine runs in your initrd, rebuild the Then check the file and, if bootvine runs in your initrd, rebuild the
initramfs, since the dracut and mkinitcpio hooks copy the file into it: initramfs, since the [dracut](https://github.com/dracut-ng/dracut-ng) and
[mkinitcpio](https://wiki.archlinux.org/title/Mkinitcpio) hooks copy the file into it:
```sh ```sh
bootvine check /etc/bootvine.toml bootvine check /etc/bootvine.toml
+11 -9
View File
@@ -2,8 +2,9 @@
## Setup ## Setup
Work inside the dev shell (`direnv allow` once). Version control is jj, not Work inside the dev shell (`direnv allow` once, with
the `git` CLI. [direnv](https://direnv.net)). Version control is
[jj](https://github.com/jj-vcs/jj), not the `git` CLI.
## Before committing ## Before committing
@@ -23,14 +24,15 @@ nix run .#check-conventional-commits -- origin/main..HEAD
``` ```
Git users can install the same commit-message check and a formatting check as Git users can install the same commit-message check and a formatting check as
hooks with `prek install` (from the dev shell) or `pre-commit install`. hooks with `prek install` ([prek](https://github.com/j178/prek), from the dev
shell) or `pre-commit install` ([pre-commit](https://pre-commit.com)).
## Continuous integration ## Continuous integration
`.woodpecker/rust-and-flake-checks.yaml` runs on Codeberg for every push and `.woodpecker/rust-and-flake-checks.yaml` runs on Codeberg's
pull request: the bootvine build with its tests, the xtask build, clippy, [Woodpecker CI](https://woodpecker-ci.org) for every push and pull request: the bootvine build with its tests, the xtask build, clippy,
rustfmt, an evaluation of every flake output, and the commit-message check on rustfmt, an evaluation of every flake output, and the commit-message check on
pull requests. Builds on `main` are pushed to the `wvhulle` Cachix cache, which pull requests. Builds on `main` are pushed to the `wvhulle` [Cachix](https://www.cachix.org) cache, which
`nixConfig` in `flake.nix` offers as a substituter. The two VM checks need KVM, `nixConfig` in `flake.nix` offers as a substituter. The two VM checks need KVM,
which Codeberg's runners lack, so they only run locally. which Codeberg's runners lack, so they only run locally.
@@ -61,14 +63,14 @@ on marker files instead of sleeping. To step through one by hand, run
call `test_script()`. call `test_script()`.
Prefix VM and recording commands with `env -u LD_LIBRARY_PATH` when your shell Prefix VM and recording commands with `env -u LD_LIBRARY_PATH` when your shell
exports libraries that clash with QEMU or Chromium. exports libraries that clash with [QEMU](https://www.qemu.org) or Chromium.
## Repository tasks ## Repository tasks
- `nix run .#record-screencasts` re-records the README animations from the - `nix run .#record-screencasts` re-records the README animations from the
scripted demos and copies the passphrase screenshot from the VM check. scripted demos and copies the passphrase screenshot from the VM check.
- `cargo xtask install --destdir <dir> --initrd dracut` stages an install - `cargo run -- install --destdir <dir> --initrd dracut` stages an install
without touching the system; `cargo xtask uninstall --destdir <dir>` removes without touching the system; `cargo run -- uninstall --destdir <dir>` removes
it again. it again.
## Code style and design ## Code style and design
+29 -22
View File
@@ -45,54 +45,58 @@ as well, the initrd has to run systemd.
## Ubuntu ## Ubuntu
1. Install the build dependencies and Rust. The repository pins a nightly 1. Install the build dependencies and Rust:
toolchain in `rust-toolchain.toml`, which rustup fetches on the first
build:
```sh ```sh
sudo apt install build-essential pkg-config libdbus-1-dev git curl sudo apt install build-essential pkg-config libdbus-1-dev git curl
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
``` ```
2. Clone, build and install the binary and the systemd units, and enable 2. Build bootvine into `~/.cargo/bin`:
them. `cargo xtask install` builds as you and asks `sudo` only for the
copying and `systemctl enable`:
```sh ```sh
git clone https://codeberg.org/wvhulle/bootvine.git cargo install --locked --git https://codeberg.org/wvhulle/bootvine bootvine
cd bootvine
cargo xtask install
``` ```
This installs `/usr/bin/bootvine`, and `bootvine.service` and 3. Install it for the system and enable its units. It asks `sudo` itself for
`bootvine-shutdown.service` in `/usr/lib/systemd/system`, which is enough the copying and `systemctl enable`:
for stage 2 and shutdown.
3. Optionally, show the boot from the initrd. This needs a dracut initramfs ```sh
with systemd in it; initramfs-tools has no systemd, so on releases that use bootvine install
```
This copies the binary to `/usr/bin/bootvine`, and `bootvine.service` and
`bootvine-shutdown.service` to `/usr/lib/systemd/system`, which is enough
for stage 2 and shutdown. The copy in `~/.cargo/bin` is no longer needed;
`cargo uninstall bootvine` removes it.
4. Optionally, show the boot from the initrd. This needs a
[dracut](https://github.com/dracut-ng/dracut-ng) initramfs with systemd in
it; initramfs-tools has no systemd, so on releases that use
it bootvine starts in stage 2 only. it bootvine starts in stage 2 only.
```sh ```sh
cargo xtask install --initrd dracut bootvine install --initrd dracut
sudo dracut --force sudo dracut --force
``` ```
This adds the dracut module in `/usr/lib/dracut/modules.d/90bootvine` and This adds the dracut module in `/usr/lib/dracut/modules.d/90bootvine` and
enables it in `/etc/dracut.conf.d/bootvine.conf`. enables it in `/etc/dracut.conf.d/bootvine.conf`.
4. Reboot. 5. Reboot.
## Other distributions ## Other distributions
Install as in the Ubuntu steps, with your distribution's packages for a C Install as in the Ubuntu steps, with your distribution's packages for a C
toolchain, `pkg-config` and the libdbus headers. toolchain, `pkg-config` and the libdbus headers.
For the initrd, use the dracut module as above, or on mkinitcpio: For the initrd, use the dracut module as above, or on
[mkinitcpio](https://wiki.archlinux.org/title/Mkinitcpio):
1. Install the hook in `/usr/lib/initcpio/install/sd-bootvine`: 1. Install the hook in `/usr/lib/initcpio/install/sd-bootvine`:
```sh ```sh
cargo xtask install --initrd mkinitcpio bootvine install --initrd mkinitcpio
``` ```
2. Add `sd-bootvine` after `systemd` in `HOOKS` in `/etc/mkinitcpio.conf`. 2. Add `sd-bootvine` after `systemd` in `HOOKS` in `/etc/mkinitcpio.conf`.
@@ -105,10 +109,13 @@ For the initrd, use the dracut module as above, or on mkinitcpio:
## Packaging ## Packaging
`cargo xtask install --destdir <dir>` stages the files under `<dir>` instead of `bootvine install --destdir <dir>` stages the files under `<dir>` instead of
the root, and combines with `--initrd`. the root, without `sudo` or `systemctl`, and combines with `--initrd` and
`--prefix`. The units' `ExecStart` follows `--prefix`. The initrd hooks expect
the default `/usr`.
## Uninstall ## Uninstall
`cargo xtask uninstall` removes everything `cargo xtask install` put in place. `bootvine uninstall` disables and removes everything `bootvine install` put in
On NixOS, remove `services.bootvine.enable` and rebuild. place, with the same `--prefix` and `--destdir`. On NixOS, remove
`services.bootvine.enable` and rebuild.
+1
View File
@@ -3,4 +3,5 @@ pub mod boot_view;
pub mod console_session; pub mod console_session;
pub mod demo_script; pub mod demo_script;
pub mod screen_settings; pub mod screen_settings;
pub mod system_install;
pub mod systemd_link; pub mod systemd_link;
+61 -31
View File
@@ -1,9 +1,5 @@
use std::{ use std::{
error::Error, error::Error, fmt::Display, io::ErrorKind, path::PathBuf, process::ExitCode, time::Duration,
io::ErrorKind,
path::{Path, PathBuf},
process::ExitCode,
time::Duration,
}; };
use bootvine::{ use bootvine::{
@@ -11,9 +7,12 @@ use bootvine::{
screen_settings::config_file::{ screen_settings::config_file::{
Config, ConfigError, Timing, default_config_table, read_config_file, Config, ConfigError, Timing, default_config_table, read_config_file,
}, },
system_install::install_files::{
InstallOptions, UninstallOptions, install_files, uninstall_files,
},
systemd_link::{boot_feed::RootRequest, systemd_bus::Scope}, systemd_link::{boot_feed::RootRequest, systemd_bus::Scope},
}; };
use clap::{Parser, Subcommand, ValueEnum}; use clap::{Args, Parser, Subcommand, ValueEnum};
use jiff::fmt::friendly::SpanParser; use jiff::fmt::friendly::SpanParser;
#[derive(Parser)] #[derive(Parser)]
@@ -25,6 +24,12 @@ use jiff::fmt::friendly::SpanParser;
struct Cli { struct Cli {
#[command(subcommand)] #[command(subcommand)]
command: Option<Command>, command: Option<Command>,
#[command(flatten)]
watch: WatchOptions,
}
#[derive(Args)]
struct WatchOptions {
#[arg(long, help = "Watch the user service manager instead of PID 1")] #[arg(long, help = "Watch the user service manager instead of PID 1")]
user: bool, user: bool,
#[arg( #[arg(
@@ -55,12 +60,27 @@ struct Cli {
#[derive(Subcommand)] #[derive(Subcommand)]
enum Command { enum Command {
#[command(about = "Print every setting with its default value")] #[command(about = "Print every setting with its default value")]
Defaults { Defaults(DefaultsOptions),
#[arg(long, value_enum, default_value_t = DefaultsFormat::Toml)]
format: DefaultsFormat,
},
#[command(about = "Exit with an error if a config file is unreadable or invalid")] #[command(about = "Exit with an error if a config file is unreadable or invalid")]
Check { path: PathBuf }, Check(CheckOptions),
#[command(
about = "Install this binary and the systemd units, and enable them; asks sudo when needed"
)]
Install(InstallOptions),
#[command(about = "Disable and remove what install put in place")]
Uninstall(UninstallOptions),
}
#[derive(Args)]
struct DefaultsOptions {
#[arg(long, value_enum, default_value_t = DefaultsFormat::Toml)]
format: DefaultsFormat,
}
#[derive(Args)]
struct CheckOptions {
#[arg(help = "Config file to check, such as /etc/bootvine.toml")]
path: PathBuf,
} }
#[derive(Clone, Copy, ValueEnum)] #[derive(Clone, Copy, ValueEnum)]
@@ -72,9 +92,21 @@ enum DefaultsFormat {
fn main() -> ExitCode { fn main() -> ExitCode {
let cli = Cli::parse(); let cli = Cli::parse();
match cli.command { match cli.command {
Some(Command::Defaults { format }) => print_defaults(format), Some(Command::Defaults(options)) => print_defaults(options.format),
Some(Command::Check { ref path }) => check_config_file(path), Some(Command::Check(options)) => check_config_file(&options),
None => watch_boot(cli), Some(Command::Install(options)) => report_outcome(install_files(&options)),
Some(Command::Uninstall(options)) => report_outcome(uninstall_files(&options)),
None => watch_boot(cli.watch),
}
}
fn report_outcome(outcome: Result<(), impl Display>) -> ExitCode {
match outcome {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("bootvine: {error}");
ExitCode::FAILURE
}
} }
} }
@@ -99,44 +131,42 @@ fn print_defaults(format: DefaultsFormat) -> ExitCode {
} }
} }
fn check_config_file(path: &Path) -> ExitCode { fn check_config_file(options: &CheckOptions) -> ExitCode {
match read_config_file(path) { match read_config_file(&options.path) {
Ok(_) => ExitCode::SUCCESS, Ok(_) => ExitCode::SUCCESS,
Err(error) => { Err(error) => {
eprintln!("bootvine: {}: {error}", path.display()); eprintln!("bootvine: {}: {error}", options.path.display());
ExitCode::FAILURE ExitCode::FAILURE
} }
} }
} }
fn watch_boot(cli: Cli) -> ExitCode { fn watch_boot(options: WatchOptions) -> ExitCode {
let config = match read_config_file(&cli.config) { let config = match read_config_file(&options.config) {
Ok(config) => config, Ok(config) => config,
Err(ConfigError::Unreadable(error)) if error.kind() == ErrorKind::NotFound => { Err(ConfigError::Unreadable(error)) if error.kind() == ErrorKind::NotFound => {
Config::default() Config::default()
} }
Err(error) => { Err(error) => {
eprintln!("bootvine: ignoring {}: {error}", cli.config.display()); eprintln!("bootvine: ignoring {}: {error}", options.config.display());
Config::default() Config::default()
} }
}; };
let settings = Settings { let settings = Settings {
scope: if cli.user { Scope::User } else { Scope::System }, scope: if options.user {
shutdown: cli.shutdown, Scope::User
target: cli } else {
Scope::System
},
shutdown: options.shutdown,
target: options
.target .target
.map_or(RootRequest::ManagerDefault, RootRequest::Named), .map_or(RootRequest::ManagerDefault, RootRequest::Named),
timing: Timing { timing: Timing {
keep_final_frame_for: cli.hold.unwrap_or(config.timing.keep_final_frame_for), keep_final_frame_for: options.hold.unwrap_or(config.timing.keep_final_frame_for),
..config.timing ..config.timing
}, },
colors: config.colors, colors: config.colors,
}; };
match run(&settings) { report_outcome(run(&settings))
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("bootvine: {error}");
ExitCode::FAILURE
}
}
} }
+2
View File
@@ -0,0 +1,2 @@
pub mod install_error;
pub mod install_files;
+11
View File
@@ -0,0 +1,11 @@
use std::{io, path::PathBuf, process::ExitStatus};
#[derive(Debug, thiserror::Error)]
pub enum InstallError {
#[error("{}: {source}", path.display())]
File { path: PathBuf, source: io::Error },
#[error("could not run {program}: {source}")]
Spawn { program: String, source: io::Error },
#[error("{program} failed: {status}")]
Failed { program: String, status: ExitStatus },
}
+309
View File
@@ -0,0 +1,309 @@
use std::{
env,
ffi::OsString,
fs::{self, Permissions},
io::ErrorKind,
iter::once,
os::unix::fs::PermissionsExt,
path::{Path, PathBuf},
process::Command,
};
use clap::{Args, ValueEnum};
use rustix::process::geteuid;
use crate::system_install::install_error::InstallError;
const DRACUT_MODULE_DIR: &str = "/usr/lib/dracut/modules.d/90bootvine";
const DRACUT_CONF: &str = "/etc/dracut.conf.d/bootvine.conf";
const MKINITCPIO_HOOK: &str = "/usr/lib/initcpio/install/sd-bootvine";
const PACKAGED_BINARY_PATH: &str = "/usr/bin/bootvine";
struct PackagedUnit {
name: &'static str,
contents: &'static str,
}
const PACKAGED_UNITS: [PackagedUnit; 2] = [
PackagedUnit {
name: "bootvine.service",
contents: include_str!("../../system-files/systemd/bootvine.service"),
},
PackagedUnit {
name: "bootvine-shutdown.service",
contents: include_str!("../../system-files/systemd/bootvine-shutdown.service"),
},
];
const DRACUT_MODULE_SETUP: &str =
include_str!("../../system-files/dracut/90bootvine/module-setup.sh");
const MKINITCPIO_INSTALL_HOOK: &str =
include_str!("../../system-files/mkinitcpio/install/sd-bootvine");
#[derive(Args)]
pub struct InstallTarget {
#[arg(
long,
default_value = "/usr",
help = "Prefix for bin/bootvine and lib/systemd/system"
)]
prefix: PathBuf,
#[arg(
long,
help = "Stage the files under this directory instead of /; skips sudo and systemctl"
)]
destdir: Option<PathBuf>,
}
#[derive(Args)]
pub struct InstallOptions {
#[command(flatten)]
target: InstallTarget,
#[arg(
long,
value_enum,
default_value_t = InitrdGenerator::None,
help = "Also install the hook that adds bootvine to this initramfs generator"
)]
initrd: InitrdGenerator,
#[arg(long, help = "Leave the units disabled")]
no_enable: bool,
}
#[derive(Args)]
pub struct UninstallOptions {
#[command(flatten)]
target: InstallTarget,
}
#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum InitrdGenerator {
None,
Dracut,
Mkinitcpio,
}
struct InstalledFile {
destination: PathBuf,
contents: Vec<u8>,
mode: u32,
}
impl InstallTarget {
fn staged(&self, path: &Path) -> PathBuf {
match &self.destdir {
Some(root) => root.join(path.strip_prefix("/").unwrap_or(path)),
None => path.to_owned(),
}
}
fn changes_live_system(&self) -> bool {
self.destdir.is_none()
}
fn needs_sudo(&self) -> bool {
self.changes_live_system() && !geteuid().is_root()
}
fn binary_path(&self) -> PathBuf {
self.prefix.join("bin/bootvine")
}
fn unit_path(&self, unit: &str) -> PathBuf {
self.prefix.join("lib/systemd/system").join(unit)
}
fn every_installed_path(&self) -> Vec<PathBuf> {
once(self.binary_path())
.chain(unit_names().map(|unit| self.unit_path(unit)))
.chain([
Path::new(DRACUT_MODULE_DIR).join("module-setup.sh"),
PathBuf::from(DRACUT_CONF),
PathBuf::from(MKINITCPIO_HOOK),
])
.collect()
}
}
fn running_binary() -> Result<PathBuf, InstallError> {
env::current_exe().map_err(|source| InstallError::File {
path: PathBuf::from("/proc/self/exe"),
source,
})
}
fn is_running_binary(path: &Path, running: &Path) -> bool {
fs::canonicalize(path).is_ok_and(|resolved| resolved == running)
}
fn binary_file(target: &InstallTarget) -> Result<Option<InstalledFile>, InstallError> {
let running = running_binary()?;
let destination = target.binary_path();
if is_running_binary(&target.staged(&destination), &running) {
return Ok(None);
}
let contents = fs::read(&running).map_err(|source| InstallError::File {
path: running,
source,
})?;
Ok(Some(InstalledFile {
destination,
contents,
mode: 0o755,
}))
}
fn unit_files(target: &InstallTarget) -> impl Iterator<Item = InstalledFile> {
let binary_path = target.binary_path();
PACKAGED_UNITS.iter().map(move |unit| InstalledFile {
destination: target.unit_path(unit.name),
contents: unit
.contents
.replace(PACKAGED_BINARY_PATH, &binary_path.to_string_lossy())
.into_bytes(),
mode: 0o644,
})
}
fn initrd_hook_files(initrd: InitrdGenerator) -> Vec<InstalledFile> {
match initrd {
InitrdGenerator::None => Vec::new(),
InitrdGenerator::Dracut => vec![
InstalledFile {
destination: Path::new(DRACUT_MODULE_DIR).join("module-setup.sh"),
contents: DRACUT_MODULE_SETUP.as_bytes().to_vec(),
mode: 0o755,
},
InstalledFile {
destination: PathBuf::from(DRACUT_CONF),
contents: b"add_dracutmodules+=\" bootvine \"\n".to_vec(),
mode: 0o644,
},
],
InitrdGenerator::Mkinitcpio => vec![InstalledFile {
destination: PathBuf::from(MKINITCPIO_HOOK),
contents: MKINITCPIO_INSTALL_HOOK.as_bytes().to_vec(),
mode: 0o644,
}],
}
}
fn sibling_for_replacement(path: &Path) -> PathBuf {
let mut file_name = OsString::from(".");
file_name.push(path.file_name().unwrap_or_default());
file_name.push(".bootvine-new");
path.with_file_name(file_name)
}
fn write_installed_file(target: &InstallTarget, file: &InstalledFile) -> Result<(), InstallError> {
let path = target.staged(&file.destination);
let replacement = sibling_for_replacement(&path);
path.parent()
.map_or(Ok(()), fs::create_dir_all)
.and_then(|()| fs::write(&replacement, &file.contents))
.and_then(|()| fs::set_permissions(&replacement, Permissions::from_mode(file.mode)))
.and_then(|()| fs::rename(&replacement, &path))
.map_err(|source| InstallError::File { path, source })
}
fn remove_if_present(path: PathBuf) -> Result<(), InstallError> {
match fs::remove_file(&path) {
Err(error) if error.kind() != ErrorKind::NotFound => Err(InstallError::File {
path,
source: error,
}),
_ => Ok(()),
}
}
fn run_command(command: &mut Command) -> Result<(), InstallError> {
let program = command.get_program().to_string_lossy().into_owned();
let status = command.status().map_err(|source| InstallError::Spawn {
program: program.clone(),
source,
})?;
if status.success() {
Ok(())
} else {
Err(InstallError::Failed { program, status })
}
}
fn systemctl<'a>(arguments: impl IntoIterator<Item = &'a str>) -> Result<(), InstallError> {
run_command(Command::new("systemctl").args(arguments))
}
fn unit_names() -> impl Iterator<Item = &'static str> {
PACKAGED_UNITS.iter().map(|unit| unit.name)
}
fn rerun_with_sudo() -> Result<(), InstallError> {
run_command(
Command::new("sudo")
.arg(running_binary()?)
.args(env::args_os().skip(1)),
)
}
fn print_initramfs_hint(initrd: InitrdGenerator) {
match initrd {
InitrdGenerator::None => {}
InitrdGenerator::Dracut => println!("rebuild the initramfs: sudo dracut --force"),
InitrdGenerator::Mkinitcpio => println!(
"add sd-bootvine after systemd in HOOKS in /etc/mkinitcpio.conf, then run: sudo \
mkinitcpio -P"
),
}
}
pub fn install_files(options: &InstallOptions) -> Result<(), InstallError> {
let target = &options.target;
if target.needs_sudo() {
return rerun_with_sudo();
}
binary_file(target)?
.into_iter()
.chain(unit_files(target))
.chain(initrd_hook_files(options.initrd))
.try_for_each(|file| write_installed_file(target, &file))?;
if target.changes_live_system() {
systemctl(["daemon-reload"])?;
if !options.no_enable {
systemctl(once("enable").chain(unit_names()))?;
}
print_initramfs_hint(options.initrd);
}
Ok(())
}
pub fn uninstall_files(options: &UninstallOptions) -> Result<(), InstallError> {
let target = &options.target;
if target.needs_sudo() {
return rerun_with_sudo();
}
if target.changes_live_system() {
let installed_units: Vec<&str> = unit_names()
.filter(|unit| target.unit_path(unit).exists())
.collect();
if !installed_units.is_empty() {
systemctl(once("disable").chain(installed_units))?;
}
}
target
.every_installed_path()
.into_iter()
.try_for_each(|path| remove_if_present(target.staged(&path)))?;
let dracut_module_dir = target.staged(Path::new(DRACUT_MODULE_DIR));
match fs::remove_dir(&dracut_module_dir) {
Err(error) if error.kind() == ErrorKind::DirectoryNotEmpty => {
return Err(InstallError::File {
path: dracut_module_dir,
source: error,
});
}
_ => {}
}
if target.changes_live_system() {
systemctl(["daemon-reload"])?;
}
Ok(())
}
+4 -6
View File
@@ -214,12 +214,10 @@ impl BusFeed {
return Ok(Vec::new()); return Ok(Vec::new());
} }
self.gave_origin = true; self.gave_origin = true;
let origin = if connection.boot_in_progress().await? { if connection.boot_in_progress().await? {
Duration::ZERO return Ok(vec![BootChange::SetOrigin(Duration::ZERO)]);
} else { }
monotonic_now() Ok(once(BootChange::SetOrigin(monotonic_now()))
};
Ok(once(BootChange::SetOrigin(origin))
.chain(self.boot_finished()) .chain(self.boot_finished())
.collect()) .collect())
} }
-1
View File
@@ -7,7 +7,6 @@ publish = false
[dependencies] [dependencies]
clap = { version = "4.6.7", features = ["derive"] } clap = { version = "4.6.7", features = ["derive"] }
rustix = { version = "1.1.5", features = ["process"] }
thiserror = "2.0.12" thiserror = "2.0.12"
xshell = "0.2.7" xshell = "0.2.7"
-280
View File
@@ -1,280 +0,0 @@
use std::{
env,
ffi::OsString,
fs::{self, Permissions},
io::ErrorKind,
iter::once,
os::unix::fs::PermissionsExt,
path::{Path, PathBuf},
};
use clap::{Args, ValueEnum};
use rustix::process::geteuid;
use xshell::{Shell, cmd};
use crate::task_error::TaskError;
const UNIT_NAMES: [&str; 2] = ["bootvine.service", "bootvine-shutdown.service"];
const DRACUT_MODULE_DIR: &str = "/usr/lib/dracut/modules.d/90bootvine";
const DRACUT_CONF: &str = "/etc/dracut.conf.d/bootvine.conf";
const MKINITCPIO_HOOK: &str = "/usr/lib/initcpio/install/sd-bootvine";
const PACKAGED_BINARY_PATH: &str = "/usr/bin/bootvine";
#[derive(Args)]
pub struct InstallTarget {
#[arg(
long,
default_value = "/usr",
help = "Prefix for bin/bootvine and lib/systemd/system"
)]
prefix: PathBuf,
#[arg(
long,
help = "Stage the files under this directory instead of /; skips sudo and systemctl"
)]
destdir: Option<PathBuf>,
}
#[derive(Args)]
pub struct InstallOptions {
#[command(flatten)]
target: InstallTarget,
#[arg(long, value_enum, default_value_t = InitrdGenerator::None)]
initrd: InitrdGenerator,
#[arg(long, help = "Leave the units disabled")]
no_enable: bool,
#[arg(long, hide = true)]
built_binary: Option<PathBuf>,
}
#[derive(Args)]
pub struct UninstallOptions {
#[command(flatten)]
target: InstallTarget,
}
#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum InitrdGenerator {
None,
Dracut,
Mkinitcpio,
}
struct InstalledFile {
destination: PathBuf,
contents: Vec<u8>,
mode: u32,
}
impl InstallTarget {
fn staged(&self, path: &Path) -> PathBuf {
match &self.destdir {
Some(root) => root.join(path.strip_prefix("/").unwrap_or(path)),
None => path.to_owned(),
}
}
fn changes_live_system(&self) -> bool {
self.destdir.is_none()
}
fn needs_sudo(&self) -> bool {
self.changes_live_system() && !geteuid().is_root()
}
fn binary_path(&self) -> PathBuf {
self.prefix.join("bin/bootvine")
}
fn unit_path(&self, unit: &str) -> PathBuf {
self.prefix.join("lib/systemd/system").join(unit)
}
fn every_installed_path(&self) -> Vec<PathBuf> {
once(self.binary_path())
.chain(UNIT_NAMES.iter().map(|unit| self.unit_path(unit)))
.chain([
Path::new(DRACUT_MODULE_DIR).join("module-setup.sh"),
PathBuf::from(DRACUT_CONF),
PathBuf::from(MKINITCPIO_HOOK),
])
.collect()
}
}
fn workspace_root() -> &'static Path {
let xtask_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
xtask_dir.parent().unwrap_or(xtask_dir)
}
fn release_binary() -> PathBuf {
env::var_os("CARGO_TARGET_DIR")
.map_or_else(|| workspace_root().join("target"), PathBuf::from)
.join("release/bootvine")
}
fn read_file(path: &Path) -> Result<Vec<u8>, TaskError> {
fs::read(path).map_err(|source| TaskError::File {
path: path.to_owned(),
source,
})
}
fn read_system_file(relative: &str) -> Result<Vec<u8>, TaskError> {
read_file(&workspace_root().join("system-files").join(relative))
}
fn unit_files(target: &InstallTarget) -> Result<Vec<InstalledFile>, TaskError> {
UNIT_NAMES
.iter()
.map(|unit| {
let packaged = read_system_file(&format!("systemd/{unit}"))?;
let rewritten = String::from_utf8_lossy(&packaged).replace(
PACKAGED_BINARY_PATH,
&target.binary_path().to_string_lossy(),
);
Ok(InstalledFile {
destination: target.unit_path(unit),
contents: rewritten.into_bytes(),
mode: 0o644,
})
})
.collect()
}
fn initrd_hook_files(initrd: InitrdGenerator) -> Result<Vec<InstalledFile>, TaskError> {
Ok(match initrd {
InitrdGenerator::None => Vec::new(),
InitrdGenerator::Dracut => vec![
InstalledFile {
destination: Path::new(DRACUT_MODULE_DIR).join("module-setup.sh"),
contents: read_system_file("dracut/90bootvine/module-setup.sh")?,
mode: 0o755,
},
InstalledFile {
destination: PathBuf::from(DRACUT_CONF),
contents: b"add_dracutmodules+=\" bootvine \"\n".to_vec(),
mode: 0o644,
},
],
InitrdGenerator::Mkinitcpio => vec![InstalledFile {
destination: PathBuf::from(MKINITCPIO_HOOK),
contents: read_system_file("mkinitcpio/install/sd-bootvine")?,
mode: 0o644,
}],
})
}
fn write_installed_file(target: &InstallTarget, file: &InstalledFile) -> Result<(), TaskError> {
let path = target.staged(&file.destination);
path.parent()
.map_or(Ok(()), fs::create_dir_all)
.and_then(|()| fs::write(&path, &file.contents))
.and_then(|()| fs::set_permissions(&path, Permissions::from_mode(file.mode)))
.map_err(|source| TaskError::File { path, source })
}
fn remove_if_present(path: PathBuf) -> Result<(), TaskError> {
match fs::remove_file(&path) {
Err(error) if error.kind() != ErrorKind::NotFound => Err(TaskError::File {
path,
source: error,
}),
_ => Ok(()),
}
}
fn rerun_with_sudo(shell: &Shell, extra_arguments: &[OsString]) -> Result<(), TaskError> {
let this_task = env::current_exe().map_err(|source| TaskError::File {
path: PathBuf::from("/proc/self/exe"),
source,
})?;
let task_arguments = env::args_os().skip(1);
cmd!(
shell,
"sudo {this_task} {task_arguments...} {extra_arguments...}"
)
.run()?;
Ok(())
}
fn print_initramfs_hint(initrd: InitrdGenerator) {
match initrd {
InitrdGenerator::None => {}
InitrdGenerator::Dracut => println!("rebuild the initramfs: sudo dracut --force"),
InitrdGenerator::Mkinitcpio => println!(
"add sd-bootvine after systemd in HOOKS in /etc/mkinitcpio.conf, then run: sudo \
mkinitcpio -P"
),
}
}
fn build_release_binary(shell: &Shell) -> Result<PathBuf, TaskError> {
let cargo = env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
let _in_workspace = shell.push_dir(workspace_root());
cmd!(shell, "{cargo} build --release --package bootvine").run()?;
Ok(release_binary())
}
pub fn install_files(options: &InstallOptions) -> Result<(), TaskError> {
let shell = Shell::new()?;
let target = &options.target;
let binary = match &options.built_binary {
Some(built) => built.clone(),
None => build_release_binary(&shell)?,
};
if target.needs_sudo() {
return rerun_with_sudo(&shell, &["--built-binary".into(), binary.into_os_string()]);
}
let binary_file = InstalledFile {
destination: target.binary_path(),
contents: read_file(&binary)?,
mode: 0o755,
};
once(binary_file)
.chain(unit_files(target)?)
.chain(initrd_hook_files(options.initrd)?)
.try_for_each(|file| write_installed_file(target, &file))?;
if target.changes_live_system() {
cmd!(shell, "systemctl daemon-reload").run()?;
if !options.no_enable {
cmd!(shell, "systemctl enable {UNIT_NAMES...}").run()?;
}
print_initramfs_hint(options.initrd);
}
Ok(())
}
pub fn uninstall_files(options: &UninstallOptions) -> Result<(), TaskError> {
let shell = Shell::new()?;
let target = &options.target;
if target.needs_sudo() {
return rerun_with_sudo(&shell, &[]);
}
if target.changes_live_system() {
let enabled_units: Vec<&str> = UNIT_NAMES
.into_iter()
.filter(|unit| target.unit_path(unit).exists())
.collect();
if !enabled_units.is_empty() {
cmd!(shell, "systemctl disable {enabled_units...}").run()?;
}
}
target
.every_installed_path()
.iter()
.try_for_each(|path| remove_if_present(target.staged(path)))?;
match fs::remove_dir(target.staged(Path::new(DRACUT_MODULE_DIR))) {
Err(error) if error.kind() == ErrorKind::DirectoryNotEmpty => {
return Err(TaskError::File {
path: target.staged(Path::new(DRACUT_MODULE_DIR)),
source: error,
});
}
_ => {}
}
if target.changes_live_system() {
cmd!(shell, "systemctl daemon-reload").run()?;
}
Ok(())
}
+10 -16
View File
@@ -1,12 +1,9 @@
mod install_files;
mod record_screencasts; mod record_screencasts;
mod task_error; mod task_error;
use std::{path::PathBuf, process::ExitCode}; use std::{path::PathBuf, process::ExitCode};
use clap::{Parser, Subcommand}; use clap::{Args, Parser, Subcommand};
use crate::install_files::{InstallOptions, UninstallOptions, install_files, uninstall_files};
#[derive(Parser)] #[derive(Parser)]
#[command(about = "Repository tasks for bootvine")] #[command(about = "Repository tasks for bootvine")]
@@ -21,23 +18,20 @@ enum Task {
about = "Record the README screencasts with vhs and copy the passphrase screenshot into \ about = "Record the README screencasts with vhs and copy the passphrase screenshot into \
recordings/" recordings/"
)] )]
RecordScreencasts { RecordScreencasts(RecordScreencastsOptions),
#[arg(long, help = "passphrase.png produced by the vm-luks-passphrase check")] }
passphrase_png: PathBuf,
}, #[derive(Args)]
#[command(about = "Build bootvine and install the binary, units and initrd hook")] struct RecordScreencastsOptions {
Install(InstallOptions), #[arg(long, help = "passphrase.png produced by the vm-luks-passphrase check")]
#[command(about = "Remove what install put in place")] passphrase_png: PathBuf,
Uninstall(UninstallOptions),
} }
fn main() -> ExitCode { fn main() -> ExitCode {
let outcome = match RepoTasks::parse().task { let outcome = match RepoTasks::parse().task {
Task::RecordScreencasts { passphrase_png } => { Task::RecordScreencasts(options) => {
record_screencasts::record_screencasts(&passphrase_png) record_screencasts::record_screencasts(&options.passphrase_png)
} }
Task::Install(options) => install_files(&options),
Task::Uninstall(options) => uninstall_files(&options),
}; };
match outcome { match outcome {
Ok(()) => ExitCode::SUCCESS, Ok(()) => ExitCode::SUCCESS,