refactor: reorganise flake, tests and repo tasks

This commit is contained in:
Willem Vanhulle committed 2026-10-21 12:12:49 +02:00
1 parent b93147c7a6
commit 794ca5a086
34 files changed
+670 -220

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
[alias]
xtask = "run --quiet --package xtask --"
-1
View File
@@ -1,3 +1,2 @@
target target
result* result*
*.qcow2
View File
File renamed without changes.
+42 -20
View File
@@ -2,30 +2,52 @@
## Workflow ## Workflow
Work inside the dev shell (`direnv allow` once). Run `cargo clippy Work inside the dev shell (`direnv allow` once). Run `cargo clippy --workspace
--all-targets` before committing (the crate warns on clippy pedantic plus --all-targets` before committing (the workspace warns on clippy pedantic plus
`absolute_paths`) and `cargo fmt`, which needs the nightly toolchain for `absolute_paths`) and `cargo fmt --all`, which needs the nightly toolchain for
`rustfmt.toml`. Version control is jj, not the `git` CLI. `.rustfmt.toml`. Version control is jj, not the `git` CLI.
The workspace has two crates: `bootvine` itself and `xtask`, the repository
tasks behind `cargo xtask` (`record-screencasts`, `install`, `uninstall`).
## Testing ## Testing
- `cargo test`: model and render snapshot tests. Everything that boots a machine or a service manager lives under `tests/`:
- `nix run .#demo-units -- start`, then `tests/sample-machine/` holds the sample host, its slow and failing sample units
`cargo run -- --user --target bootvine-demo.target --hold 3s`: live against and the interactive VM; `tests/vm-checks/` holds the NixOS tests that boot it.
your user manager.
- `nix build .#checks.x86_64-linux.<name>`: each `tests/<name>.nix` boots a VM
and runs `tests/console.py` followed by `tests/<name>.py`. `boot` follows
the initrd, stage 2 and a poweroff; `luks` answers a passphrase prompt in
the initrd. They read tty12 as text from `/dev/vcsu12`, hold the boot with
the initrd backdoor and gate files under `/run` instead of sleeping. Run one
by hand with `nix run .#checks.x86_64-linux.boot.driverInteractive`, then
`test_script()`.
- `nix run .#docs`, from the repository root: renders `docs/boot.tape` and
`docs/shutdown.tape` with VHS against the scripted examples into the README
GIFs, and copies the passphrase screenshot from the `luks` check.
Prefix the VM commands with `env -u LD_LIBRARY_PATH` when the shell exports - `cargo test --workspace`: model and render snapshot tests.
libraries that clash with QEMU's. - Live against your user manager, with the sample units:
```sh
units=$(nix build --no-link --print-out-paths .#sample-unit-files)
systemctl --user link --runtime $units/*
systemctl --user start --no-block bootvine-demo.target
cargo run -- --user --target bootvine-demo.target --hold 3s
systemctl --user stop $(ls $units)
systemctl --user disable --runtime $(ls $units)
```
- `nix run .#sample-machine-vm`: the sample host in a QEMU window. Its disk
image goes to `~/.cache/bootvine-sample-machine.qcow2`.
- `nix build .#checks.x86_64-linux.<name>`: each `tests/vm-checks/<test>.nix`
boots a VM and runs `console.py` followed by `<test>.py`.
`vm-boot-and-shutdown` follows the initrd, stage 2 and a poweroff;
`vm-luks-passphrase` answers a passphrase prompt in the initrd. They read
tty12 as text from `/dev/vcsu12`, hold the boot with the initrd backdoor and
gate files under `/run` instead of sleeping. Run one by hand with
`nix run .#checks.x86_64-linux.vm-boot-and-shutdown.driverInteractive`, then
`test_script()`.
- `nix run .#record-screencasts`, from the repository root: runs
`cargo xtask record-screencasts`, which records `recordings/boot.tape` and
`recordings/shutdown.tape` with VHS against the scripted examples into the README
GIFs and copies the passphrase screenshot from the `vm-luks-passphrase` check.
- `cargo xtask install --destdir <dir> --initrd dracut`: stages an install
without touching the system; `cargo xtask uninstall --destdir <dir>` empties
it again.
Prefix the VM and VHS commands with `env -u LD_LIBRARY_PATH` when the shell
exports libraries that clash with QEMU's or Chromium's.
## Conventions ## Conventions
Generated
+25
View File
@@ -2227,6 +2227,31 @@ version = "0.57.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
[[package]]
name = "xshell"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e7290c623014758632efe00737145b6867b66292c42167f2ec381eb566a373d"
dependencies = [
"xshell-macros",
]
[[package]]
name = "xshell-macros"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32ac00cd3f8ec9c1d33fb3e7958a82df6989c42d747bd326c822b1d625283547"
[[package]]
name = "xtask"
version = "0.1.0"
dependencies = [
"clap",
"rustix 1.1.5",
"thiserror 2.0.21",
"xshell",
]
[[package]] [[package]]
name = "zeroize" name = "zeroize"
version = "1.9.1" version = "1.9.1"
+8 -2
View File
@@ -9,14 +9,20 @@ readme = "README.md"
keywords = ["systemd", "boot", "initrd", "tui", "console"] keywords = ["systemd", "boot", "initrd", "tui", "console"]
categories = ["command-line-utilities", "os::linux-apis"] categories = ["command-line-utilities", "os::linux-apis"]
rust-version = "1.91" rust-version = "1.91"
include = ["/src", "/examples", "/packaging", "/README.md", "/LICENSE"] include = ["/src", "/examples", "/system-files", "/README.md", "/LICENSE"]
[lints.clippy] [workspace]
members = [".", "xtask"]
[workspace.lints.clippy]
absolute_paths = "warn" absolute_paths = "warn"
pedantic = { priority = -1, level = "warn" } pedantic = { priority = -1, level = "warn" }
needless_for_each = "allow" needless_for_each = "allow"
missing_errors_doc = "allow" missing_errors_doc = "allow"
[lints]
workspace = true
[dependencies] [dependencies]
clap = { version = "4.6.7", features = ["derive"] } clap = { version = "4.6.7", features = ["derive"] }
crossterm = "0.29.0" crossterm = "0.29.0"
+48 -30
View File
@@ -5,7 +5,7 @@ nix-output-monitor. It replaces the scrolling kernel and systemd lines with the
units still pending and, in the room the tree leaves, a timeline of the slowest units still pending and, in the room the tree leaves, a timeline of the slowest
ones that ran. ones that ran.
<img src="https://codeberg.org/wvhulle/bootvine/raw/branch/main/docs/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">
It needs systemd ≥ 246 as PID 1, libdbus and a virtual terminal (it draws on It needs systemd ≥ 246 as PID 1, libdbus and a virtual terminal (it draws on
tty12). With a systemd initrd it starts about a second after the kernel and tty12). With a systemd initrd it starts about a second after the kernel and
@@ -19,25 +19,45 @@ It also follows shutdowns and reboots: the units being stopped, nested under
the units that have to stop first, until systemd hands over to the units that have to stop first, until systemd hands over to
`systemd-shutdown`. `systemd-shutdown`.
<img src="https://codeberg.org/wvhulle/bootvine/raw/branch/main/docs/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 LUKS unlock in the initrd, are answered in place
over the tree. over the tree.
<img src="https://codeberg.org/wvhulle/bootvine/raw/branch/main/docs/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">
## Try ## Try it without installing
Neither of these touches your system's boot.
### Scripted boots in your terminal
From a clone, with Rust installed (see step 1 of the Ubuntu install below):
```sh ```sh
git clone https://codeberg.org/wvhulle/bootvine.git
cd bootvine
cargo run --example boot cargo run --example boot
cargo run --example shutdown cargo run --example shutdown
cargo run --example luks cargo run --example luks
``` ```
play a scripted boot, poweroff or boot from an encrypted root without systemd; These play a scripted boot, a poweroff and a boot from an encrypted root, with
`q` quits. The encrypted root unlocks with the passphrase `demo`; `Esc` quits no systemd involved. `q` quits. The encrypted root unlocks with the passphrase
while it asks. `nix run .#vm` boots a demo `demo`; `Esc` quits while it asks.
VM in a window.
### A sample machine in a VM
With Nix, and no clone needed:
```sh
nix run git+https://codeberg.org/wvhulle/bootvine#sample-machine-vm
```
This boots a NixOS machine with bootvine and a set of slow and failing sample
units in a QEMU window, from the initrd through stage 2. It logs in as root;
`poweroff` shows the shutdown. Its disk image is kept in
`~/.cache/bootvine-sample-machine.qcow2`.
## Install ## Install
@@ -98,45 +118,43 @@ VM in a window.
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
``` ```
2. Build: 2. Clone, build and install the binary and the systemd units, and enable
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 git clone https://codeberg.org/wvhulle/bootvine.git
cd bootvine cd bootvine
cargo build --release cargo xtask install
``` ```
3. Install the binary and the systemd units, and enable them: This is enough for bootvine to show stage 2 and shutdown. It installs
`/usr/bin/bootvine` and `bootvine.service` and `bootvine-shutdown.service`
in `/usr/lib/systemd/system`.
```sh 3. Optionally, follow the boot from the initrd. This needs a dracut initramfs
sudo install -Dm755 target/release/bootvine /usr/bin/bootvine
sudo install -Dm644 -t /usr/lib/systemd/system \
packaging/systemd/bootvine.service packaging/systemd/bootvine-shutdown.service
sudo systemctl enable bootvine.service bootvine-shutdown.service
```
This is enough for bootvine to show stage 2 and shutdown.
4. Optionally, follow the boot from the initrd. This needs a dracut initramfs
with systemd in it; initramfs-tools has no systemd, so on releases that use 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
sudo install -Dm755 packaging/dracut/90bootvine/module-setup.sh \ cargo xtask install --initrd dracut
/usr/lib/dracut/modules.d/90bootvine/module-setup.sh
echo 'add_dracutmodules+=" bootvine "' | sudo tee /etc/dracut.conf.d/bootvine.conf
sudo dracut --force sudo dracut --force
``` ```
5. Reboot. This adds the dracut module in `/usr/lib/dracut/modules.d/90bootvine` and
enables it in `/etc/dracut.conf.d/bootvine.conf`.
4. Reboot.
`cargo xtask uninstall` removes all of it again.
### Other distributions ### Other distributions
Install the binary and units as in the Ubuntu steps. For the initrd, use the Install as in the Ubuntu steps. For the initrd, use the dracut module as above,
dracut module as above, or on mkinitcpio install or on mkinitcpio run `cargo xtask install --initrd mkinitcpio`, which installs
`packaging/mkinitcpio/install/sd-bootvine` to `/usr/lib/initcpio/install/`, add `/usr/lib/initcpio/install/sd-bootvine`, then add `sd-bootvine` after `systemd`
`sd-bootvine` after `systemd` in `HOOKS` in `/etc/mkinitcpio.conf`, and run in `HOOKS` in `/etc/mkinitcpio.conf` and run `sudo mkinitcpio -P`.
`sudo mkinitcpio -P`. `--destdir <dir>` stages the files under `<dir>` instead, for packaging.
## Configure ## Configure
+63
View File
@@ -0,0 +1,63 @@
{
lib,
pkgs,
craneLib,
}:
let
commonArgs = {
src = lib.fileset.toSource {
root = ./.;
fileset = lib.fileset.unions [
(craneLib.fileset.commonCargoSources ./.)
./system-files
];
};
strictDeps = true;
nativeBuildInputs = [ pkgs.pkg-config ];
buildInputs = [ pkgs.dbus ];
};
cargoArtifacts = craneLib.buildDepsOnly (commonArgs // { pname = "bootvine-workspace"; });
buildWorkspaceMember =
args: craneLib.buildPackage (commonArgs // { inherit cargoArtifacts; } // args);
in
{
bootvine = buildWorkspaceMember {
cargoExtraArgs = "-p bootvine";
postInstall = ''
for unit in bootvine.service bootvine-shutdown.service; do
install -Dm644 system-files/systemd/$unit $out/lib/systemd/system/$unit
substituteInPlace $out/lib/systemd/system/$unit \
--replace-fail /usr/bin/bootvine $out/bin/bootvine
done
install -Dm755 system-files/dracut/90bootvine/module-setup.sh \
$out/lib/dracut/modules.d/90bootvine/module-setup.sh
install -Dm644 system-files/mkinitcpio/install/sd-bootvine \
$out/lib/initcpio/install/sd-bootvine
'';
meta = {
mainProgram = "bootvine";
platforms = lib.platforms.linux;
license = lib.getLicenseFromSpdxId (lib.importTOML ./Cargo.toml).package.license;
};
};
scripted-boot-examples = buildWorkspaceMember {
pname = "bootvine-scripted-boot-examples";
cargoExtraArgs = "-p bootvine --examples";
doCheck = false;
installPhaseCommand = ''
for example in boot shutdown; do
install -Dm755 target/release/examples/$example $out/bin/bootvine-$example-example
done
'';
};
repo-tasks = buildWorkspaceMember {
pname = "xtask";
cargoExtraArgs = "-p xtask";
doCheck = false;
meta.mainProgram = "xtask";
};
}
-38
View File
@@ -1,38 +0,0 @@
#!/usr/bin/env nu
def user-unit-dir []: nothing -> path {
$env.XDG_RUNTIME_DIR | path join systemd user
}
def unit-names [units: path]: nothing -> list<string> {
ls $units | get name | path basename
}
def install-units [units: path] {
let target_dir = user-unit-dir
mkdir $target_dir
unit-names $units | each {|name| ^ln -sfn ($units | path join $name) ($target_dir | path join $name) } | ignore
^systemctl --user daemon-reload
}
def "main start" [--units: path, --target: string] {
install-units $units
^systemctl --user stop ...(unit-names $units)
^systemctl --user start --no-block $target
print $"started ($target); watch it with: bootvine --user --target ($target) --hold 3s"
}
def "main stop" [--units: path, --target: string] {
^systemctl --user stop --no-block ...(unit-names $units)
print $"stopping ($target); watch it with: bootvine --user --shutdown --target ($target)"
}
def "main remove" [--units: path, --target: string] {
^systemctl --user stop ...(unit-names $units)
unit-names $units | each {|name| rm -f (user-unit-dir | path join $name) } | ignore
^systemctl --user daemon-reload
}
def main [--units: path, --target: string] {
print "usage: bootvine-demo-units (start | stop | remove)"
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.7 KiB

+46 -102
View File
@@ -24,8 +24,7 @@
f: f:
lib.genAttrs [ "x86_64-linux" "aarch64-linux" ] ( lib.genAttrs [ "x86_64-linux" "aarch64-linux" ] (
system: system:
f rec { let
inherit system;
pkgs = import nixpkgs { pkgs = import nixpkgs {
inherit system; inherit system;
overlays = [ (import rust-overlay) ]; overlays = [ (import rust-overlay) ];
@@ -33,120 +32,64 @@
craneLib = (crane.mkLib pkgs).overrideToolchain ( craneLib = (crane.mkLib pkgs).overrideToolchain (
p: p.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml p: p.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml
); );
in
f {
inherit system pkgs craneLib;
builds = import ./crane-builds.nix { inherit lib pkgs craneLib; };
} }
); );
buildInputsFor = pkgs: { sampleMachine = import ./tests/sample-machine {
nativeBuildInputs = [ pkgs.pkg-config ]; inherit lib;
buildInputs = [ pkgs.dbus ]; bootvineModule = self.nixosModules.bootvine;
}; };
demoUnits = import ./demo/units.nix;
demoHost = {
imports = [
self.nixosModules.default
./demo/host.nix
];
_module.args = { inherit demoUnits; };
};
demoSystem =
system:
lib.nixosSystem {
inherit system;
modules = [
demoHost
./demo/interactive.nix
];
};
in in
{ {
packages = forEachSystem ( packages = forEachSystem (
{ pkgs, craneLib, ... }: { pkgs, builds, ... }:
let
commonArgs = {
inherit (buildInputsFor pkgs) nativeBuildInputs buildInputs;
src = lib.fileset.toSource {
root = ./.;
fileset = lib.fileset.unions [
(craneLib.fileset.commonCargoSources ./.)
./packaging
];
};
strictDeps = true;
};
in
{ {
examples = craneLib.buildPackage ( default = builds.bootvine;
commonArgs inherit (builds) bootvine scripted-boot-examples repo-tasks;
// { sample-unit-files = pkgs.callPackage ./tests/sample-machine/sample-unit-files.nix {
pname = "bootvine-examples"; inherit (sampleMachine) sampleUnits;
cargoExtraArgs = "--examples"; };
doCheck = false;
installPhaseCommand = ''
for example in boot shutdown; do
install -Dm755 target/release/examples/$example $out/bin/bootvine-$example-example
done
'';
}
);
default = craneLib.buildPackage (
commonArgs
// {
postInstall = ''
for unit in bootvine.service bootvine-shutdown.service; do
install -Dm644 packaging/systemd/$unit $out/lib/systemd/system/$unit
substituteInPlace $out/lib/systemd/system/$unit \
--replace-fail /usr/bin/bootvine $out/bin/bootvine
done
install -Dm755 packaging/dracut/90bootvine/module-setup.sh \
$out/lib/dracut/modules.d/90bootvine/module-setup.sh
install -Dm644 packaging/mkinitcpio/install/sd-bootvine \
$out/lib/initcpio/install/sd-bootvine
'';
meta.mainProgram = "bootvine";
meta.platforms = lib.platforms.linux;
meta.license = lib.getLicenseFromSpdxId (lib.importTOML ./Cargo.toml).package.license;
}
);
demo-units = pkgs.callPackage ./demo/user-units.nix { inherit demoUnits; };
} }
); );
nixosModules.default = import ./nixos-module.nix { inherit self; }; nixosModules = {
default = self.nixosModules.bootvine;
bootvine = import ./nixos-module.nix { inherit self; };
};
nixosConfigurations.demo = demoSystem "x86_64-linux"; nixosConfigurations.sample-machine = sampleMachine.nixosSystemFor "x86_64-linux";
apps = forEachSystem ( apps = forEachSystem (
{ pkgs, system, ... }:
{ {
vm = { pkgs,
system,
builds,
...
}:
{
sample-machine-vm = {
type = "app"; type = "app";
program = lib.getExe (demoSystem system).config.system.build.vm; meta.description = "Boot a sample machine with bootvine and slow sample units in QEMU";
program = lib.getExe (sampleMachine.nixosSystemFor system).config.system.build.vm;
}; };
demo-units = { record-screencasts = {
type = "app";
program = lib.getExe self.packages.${system}.demo-units;
};
docs = {
type = "app"; type = "app";
meta.description = "Re-record the README screencasts and passphrase screenshot into recordings/";
program = lib.getExe ( program = lib.getExe (
pkgs.writeShellApplication { pkgs.writeShellApplication {
name = "bootvine-docs"; name = "record-screencasts";
runtimeInputs = [ runtimeInputs = [
pkgs.vhs pkgs.vhs
self.packages.${system}.examples builds.scripted-boot-examples
builds.repo-tasks
]; ];
text = '' text = "exec xtask record-screencasts --passphrase-png ${
if [ ! -d docs ]; then self.checks.${system}.vm-luks-passphrase
echo "no docs directory here; run from the repository root" >&2 }/passphrase.png";
exit 1
fi
vhs ${./docs/boot.tape}
vhs ${./docs/shutdown.tape}
install -m644 -t docs ${self.checks.${system}.luks}/passphrase.png
'';
} }
); );
}; };
@@ -154,22 +97,23 @@
); );
checks = forEachSystem ( checks = forEachSystem (
{ pkgs, system, ... }: { pkgs, builds, ... }:
{ {
package = self.packages.${system}.default; bootvine-build = builds.bootvine;
boot = pkgs.testers.runNixOSTest (import ./tests/boot.nix { inherit demoHost; }); repo-tasks-build = builds.repo-tasks;
luks = pkgs.testers.runNixOSTest ( vm-boot-and-shutdown = pkgs.testers.runNixOSTest (
import ./tests/luks.nix { bootvineModule = self.nixosModules.default; } import ./tests/vm-checks/boot.nix { sampleMachine = sampleMachine.machine; }
);
vm-luks-passphrase = pkgs.testers.runNixOSTest (
import ./tests/vm-checks/luks.nix { bootvineModule = self.nixosModules.bootvine; }
); );
} }
); );
devShells = forEachSystem ( devShells = forEachSystem (
{ pkgs, craneLib, ... }: { craneLib, builds, ... }:
{ {
default = craneLib.devShell { default = craneLib.devShell { inputsFrom = [ builds.bootvine ]; };
packages = with buildInputsFor pkgs; nativeBuildInputs ++ buildInputs;
};
} }
); );
}; };
+1 -1
View File
@@ -1,4 +1,4 @@
Output docs/boot.gif Output recordings/boot.gif
Require bootvine-boot-example Require bootvine-boot-example
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

@@ -1,4 +1,4 @@
Output docs/shutdown.gif Output recordings/shutdown.gif
Require bootvine-shutdown-example Require bootvine-shutdown-example
File renamed without changes.
File renamed without changes.
+25
View File
@@ -0,0 +1,25 @@
{ lib, bootvineModule }:
let
sampleUnits = import ./sample-units.nix;
machine = {
imports = [
bootvineModule
./machine.nix
];
_module.args = { inherit sampleUnits; };
};
in
{
inherit sampleUnits machine;
nixosSystemFor =
system:
lib.nixosSystem {
inherit system;
modules = [
machine
./interactive-vm.nix
];
};
}
@@ -1,7 +1,8 @@
{ {
boot.loader.grub.enable = false; boot.loader.grub.enable = false;
services.getty.autologinUser = "root"; fileSystems."/" = { services.getty.autologinUser = "root";
fileSystems."/" = {
device = "/dev/disk/by-label/nixos"; device = "/dev/disk/by-label/nixos";
fsType = "ext4"; fsType = "ext4";
}; };
@@ -10,6 +11,7 @@
memorySize = 2048; memorySize = 2048;
cores = 2; cores = 2;
graphics = true; graphics = true;
diskImage = "\${XDG_CACHE_HOME:-$HOME/.cache}/bootvine-sample-machine.qcow2";
qemu.options = [ qemu.options = [
"-vga none" "-vga none"
"-device virtio-vga,xres=1920,yres=1080" "-device virtio-vga,xres=1920,yres=1080"
@@ -1,11 +1,11 @@
{ {
demoUnits, sampleUnits,
lib, lib,
pkgs, pkgs,
... ...
}: }:
let let
demoService = spec: { sampleService = spec: {
inherit (spec) description; inherit (spec) description;
after = map (dependency: "${dependency}.service") (spec.after or [ ]); after = map (dependency: "${dependency}.service") (spec.after or [ ]);
wantedBy = [ "multi-user.target" ]; wantedBy = [ "multi-user.target" ];
@@ -37,7 +37,7 @@ in
unitConfig.DefaultDependencies = false; unitConfig.DefaultDependencies = false;
serviceConfig = { serviceConfig = {
Type = "oneshot"; Type = "oneshot";
ExecStart = "/bin/sleep ${demoUnits.initrdProbeSeconds}"; ExecStart = "/bin/sleep ${sampleUnits.initrdProbeSeconds}";
}; };
}; };
}; };
@@ -76,7 +76,7 @@ in
font = "${pkgs.terminus_font}/share/consolefonts/ter-v20n.psf.gz"; font = "${pkgs.terminus_font}/share/consolefonts/ter-v20n.psf.gz";
}; };
systemd.services = lib.mapAttrs (_: demoService) demoUnits.services // { systemd.services = lib.mapAttrs (_: sampleService) sampleUnits.services // {
greetd.after = [ "multi-user.target" ]; greetd.after = [ "multi-user.target" ];
}; };
@@ -1,10 +1,8 @@
{ {
demoUnits, sampleUnits,
lib, lib,
coreutils, coreutils,
linkFarm, runCommand,
nushell,
writeShellApplication,
writeText, writeText,
}: }:
let let
@@ -30,30 +28,27 @@ let
}; };
}); });
serviceNames = map (name: "${name}.service") (lib.attrNames demoUnits.services); serviceNames = map (name: "${name}.service") (lib.attrNames sampleUnits.services);
targetFile = writeText "${demoUnits.target}.target" (toUnitFile { targetFile = writeText "${sampleUnits.target}.target" (toUnitFile {
Unit = { Unit = {
Description = "bootvine demo services"; Description = "bootvine demo services";
Wants = serviceNames; Wants = serviceNames;
After = serviceNames; After = serviceNames;
}; };
}); });
unitFiles =
units = linkFarm "bootvine-demo-units" (
lib.mapAttrsToList (name: spec: { lib.mapAttrsToList (name: spec: {
name = "${name}.service"; name = "${name}.service";
path = serviceFile name spec; path = serviceFile name spec;
}) demoUnits.services }) sampleUnits.services
++ [ ++ [
{ {
name = "${demoUnits.target}.target"; name = "${sampleUnits.target}.target";
path = targetFile; path = targetFile;
} }
] ];
);
in in
writeShellApplication { runCommand "bootvine-sample-unit-files" { } (
name = "bootvine-demo-units"; lib.concatMapStringsSep "\n" (unit: "install -Dm644 ${unit.path} $out/${unit.name}") unitFiles
text = ''exec ${lib.getExe nushell} ${./demo-units.nu} "$@" --units ${units} --target ${demoUnits.target}.target''; )
}
File renamed without changes.
+3 -3
View File
@@ -1,6 +1,6 @@
{ demoHost }: { sampleMachine }:
{ {
name = "bootvine"; name = "bootvine-boot-and-shutdown";
nodes.machine = nodes.machine =
{ lib, ... }: { lib, ... }:
@@ -8,7 +8,7 @@
waitFor = flag: "/bin/sh -c 'until [ -e /run/${flag} ]; do sleep 0.1; done'"; waitFor = flag: "/bin/sh -c 'until [ -e /run/${flag} ]; do sleep 0.1; done'";
in in
{ {
imports = [ demoHost ]; imports = [ sampleMachine ];
testing.initrdBackdoor = true; testing.initrdBackdoor = true;
boot.initrd.systemd.services.demo-initrd-probe.serviceConfig.ExecStart = lib.mkForce ( boot.initrd.systemd.services.demo-initrd-probe.serviceConfig.ExecStart = lib.mkForce (
waitFor "release-initrd-probe" waitFor "release-initrd-probe"
File renamed without changes.
File renamed without changes.
+1 -1
View File
@@ -3,7 +3,7 @@ let
passphrase = "quietly unlocked"; passphrase = "quietly unlocked";
in in
{ {
name = "bootvine-luks"; name = "bootvine-luks-passphrase";
nodes.machine = nodes.machine =
{ lib, pkgs, ... }: { lib, pkgs, ... }:
let let
File renamed without changes.
+15
View File
@@ -0,0 +1,15 @@
[package]
edition = "2024"
name = "xtask"
version = "0.1.0"
license = "GPL-3.0-or-later"
publish = false
[dependencies]
clap = { version = "4.6.7", features = ["derive"] }
rustix = { version = "1.1.5", features = ["process"] }
thiserror = "2.0.12"
xshell = "0.2.7"
[lints]
workspace = true
+280
View File
@@ -0,0 +1,280 @@
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(())
}
+49
View File
@@ -0,0 +1,49 @@
mod install_files;
mod record_screencasts;
mod task_error;
use std::{path::PathBuf, process::ExitCode};
use clap::{Parser, Subcommand};
use crate::install_files::{InstallOptions, UninstallOptions, install_files, uninstall_files};
#[derive(Parser)]
#[command(about = "Repository tasks for bootvine")]
struct RepoTasks {
#[command(subcommand)]
task: Task,
}
#[derive(Subcommand)]
enum Task {
#[command(
about = "Record the README screencasts with vhs and copy the passphrase screenshot into \
recordings/"
)]
RecordScreencasts {
#[arg(long, help = "passphrase.png produced by the vm-luks-passphrase check")]
passphrase_png: PathBuf,
},
#[command(about = "Build bootvine and install the binary, units and initrd hook")]
Install(InstallOptions),
#[command(about = "Remove what install put in place")]
Uninstall(UninstallOptions),
}
fn main() -> ExitCode {
let outcome = match RepoTasks::parse().task {
Task::RecordScreencasts { passphrase_png } => {
record_screencasts::record_screencasts(&passphrase_png)
}
Task::Install(options) => install_files(&options),
Task::Uninstall(options) => uninstall_files(&options),
};
match outcome {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("xtask: {error}");
ExitCode::FAILURE
}
}
}
+30
View File
@@ -0,0 +1,30 @@
use std::{
fs::{self, Permissions},
os::unix::fs::PermissionsExt,
path::Path,
};
use xshell::{Shell, cmd};
use crate::task_error::TaskError;
const TAPES: [&str; 2] = ["boot.tape", "shutdown.tape"];
pub fn record_screencasts(passphrase_png: &Path) -> Result<(), TaskError> {
let recordings = Path::new("recordings");
if !recordings.is_dir() {
return Err(TaskError::NotInRepositoryRoot);
}
let shell = Shell::new()?;
TAPES.iter().try_for_each(|tape| {
let tape_path = recordings.join(tape);
cmd!(shell, "vhs {tape_path}").run()
})?;
let copied_png = recordings.join("passphrase.png");
fs::copy(passphrase_png, &copied_png)
.and_then(|_| fs::set_permissions(&copied_png, Permissions::from_mode(0o644)))
.map_err(|source| TaskError::File {
path: copied_png,
source,
})
}
+13
View File
@@ -0,0 +1,13 @@
use std::{io, path::PathBuf};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum TaskError {
#[error(transparent)]
Shell(#[from] xshell::Error),
#[error("{}: {source}", path.display())]
File { path: PathBuf, source: io::Error },
#[error("no recordings directory here; run from the repository root")]
NotInRepositoryRoot,
}