20 Commits
Author SHA1 Message Date
Willem Vanhulle a7e33b453a test: drop the scripted initrd sample machine now that NixOS removed it 2026-11-09 21:54:18 +01:00
release-plz f43ece2f72 chore: release v0.1.3
Signed-off-by: release-plz <willemvanhulle@protonmail.com>
2026-11-05 19:52:10 +00:00
Willem Vanhulle d41120e263 ci: sync the shared CI tasks
Make cargoToolchain optional in nix/ci-tasks.nix, so repositories without
Rust use the same file, and add a copy-build-output task that copies a build
result into the checkout as writable files. The shared files in ci/ and
nix/ci-tasks.nix stay identical across repositories.

Claude-Session: https://claude.ai/code/session_01D8dLLgYd8cfR2aQfA5eZXa
2026-11-05 20:45:36 +01:00
Willem Vanhulle f9f68b2a68 ci: move CI tasks into Nushell scripts and update dependencies weekly
Replace the shell scripts in flake.nix with Nushell scripts in ci/, exposed
as flake apps in nix/ci-tasks.nix, so every workflow command is a plain nix
call. Build the workspace dependencies in a step of their own, upload to
Cachix only after the builds, and run the formatting check through the
pre-commit hooks.

Automated pushes, tags and pull requests now use the wvhulle-bot account.
A weekly cron updates Cargo.lock and flake.lock and opens or updates one
pull request from bot/dependency-updates.

Claude-Session: https://claude.ai/code/session_01D8dLLgYd8cfR2aQfA5eZXa
2026-11-05 19:59:06 +01:00
Willem Vanhulle a81cc849b5 test: boot the sample machine into tuigreet
Log in through a full-screen greeter rather than agreety, so the checks cover
a greeter that redraws over status output.
2026-11-04 19:59:30 +01:00
Willem Vanhulle 89eec1ddaf fix: keep systemd status off the display manager until the boot finishes
bootvine restored systemd's status output as soon as a display manager took
the console. greetd's Type=idle only waits five seconds, so jobs still running
then wrote status lines over the login screen.

Restore the output when StartupFinished arrives instead, through a single
private path that owns the console watch. A quit key or stopping the service
still restores it at once, so a stuck boot stays visible.
2026-11-04 19:59:30 +01:00
Willem Vanhulle d0833ad563 fix: do not report collected systemd jobs as failed 2026-11-02 21:30:32 +01:00
release-plz 8eebf73258 chore: release v0.1.2
Signed-off-by: release-plz <willemvanhulle@protonmail.com>
2026-11-02 19:38:43 +00:00
Willem Vanhulle 16637c3b38 fix: keep the nixpkgs test import a path so the flake evaluates on upstream Nix
Interpolating pkgs.path into a string asks for a copy in the store, which
nix flake check --no-build never creates, so upstream Nix stopped with a path
that is not valid. That failed the checks on main and skipped the release.
2026-11-02 20:30:44 +01:00
Willem Vanhulle 4f83d134c1 feat: say when the screen is waiting for the system manager
Between the switch to the real root and the new manager answering, the tree
stayed empty for seconds and looked stuck. The stage line now says what it is
waiting for, and the same holds for the moment after bootvine starts.
2026-11-02 19:29:05 +01:00
Willem Vanhulle 29849c6254 test: use a plain VGA device to show the restored system
virtio-vga shows its old VGA framebuffer after a restore and never repaints,
which left a stale screen in the recording and sample machine whether or not
bootvine ran. A plain VGA device repaints, so the recording can run through to
the restored login prompt.
2026-11-02 19:29:05 +01:00
Willem Vanhulle 4e5e6d96b7 fix: finish console setup before resuming from hibernation
A font load still running when the kernel froze bootvine left the frozen frame
with the wrong glyphs for the whole image load, because bootvine had already
stopped repainting.
2026-11-02 19:29:05 +01:00
Willem Vanhulle e764c9c277 fix: repaint the whole screen while the root switches
PID 1 writes to the console and resets it while it re-executes, and bootvine
only drew the cells it believed had changed, so the switch left a garbled
screen for up to seconds. Repaint on every check from the moment the switch is
queued until the new manager answers.
2026-11-02 19:29:05 +01:00
Willem Vanhulle ebed809e43 test: record the resume itself and show it in the guide
Stop before the jump into the restored system, because the virtual GPU of the
test machine does not repaint after a restore.
2026-11-02 19:29:05 +01:00
Willem Vanhulle c1449439e8 refactor: reduce screen spacing to a small named set and declarative layouts
Replace measured column widths and ad-hoc spacing arithmetic with one list of
named values, ratatui constraints and its Table footer, Paragraph block and
Rect centring. Footer gaps and failure log indents get slightly tighter, and
the kind and timeout columns get a fixed width.
2026-11-02 19:29:04 +01:00
Willem Vanhulle 795819d5c8 feat: show the kernel's image loading progress while resuming from hibernation
The kernel freezes every process before it loads a hibernated image, so the
screen looked hung for as long as the load took. A drop-in on
systemd-hibernate-resume.service now opens the kernel console just before
resume, draws a band across the middle of tty12 and confines the kernel's
progress lines to it. The running bootvine stops drawing and stops taking the
console back meanwhile, and repaints if no image was restored.
2026-11-02 19:29:04 +01:00
Willem Vanhulle 7bcc384cfe ci: open a release pull request for every unreleased change 2026-10-30 20:09:58 +01:00
Willem Vanhulle 22e77e1340 chore: release v0.1.1 2026-10-30 20:01:38 +01:00
Willem Vanhulle daaad6771f refactor: keep recordings on an orphan branch 2026-10-30 19:59:46 +01:00
Willem Vanhulle d4bd3b4b76 refactor: read the release environment from the crate build and generate the sample machine apps 2026-10-30 15:46:26 +01:00
57 changed files with 1526 additions and 524 deletions

No files matched your search

+1
View File
@@ -1,2 +1,3 @@
target target
result* result*
/recordings/
+85
View File
@@ -0,0 +1,85 @@
when:
- repo: wvhulle/bootvine
event: [pull_request, push, manual]
variables:
- &nix_config
NIX_CONFIG: |
experimental-features = nix-command flakes
build-users-group =
accept-flake-config = true
- &after_dependency_step
- status: [success, failure]
steps:
- name: prepare-build-dependencies
image: nixos/nix:latest
depends_on: []
environment: *nix_config
commands:
- nix run --quiet .#build-unless-cached -- .#packages.x86_64-linux.workspace-dependencies
- name: build-and-test-bootvine
image: nixos/nix:latest
depends_on: [prepare-build-dependencies]
when: *after_dependency_step
environment: *nix_config
commands:
- nix run --quiet .#import-exported-paths
- nix run --quiet .#build-and-export-paths -- .#checks.x86_64-linux.bootvine-build
- name: build-repo-tasks
image: nixos/nix:latest
depends_on: [prepare-build-dependencies]
when: *after_dependency_step
environment: *nix_config
commands:
- nix run --quiet .#import-exported-paths
- nix run --quiet .#build-and-export-paths -- .#checks.x86_64-linux.repo-tasks-build
- name: lint-with-clippy
image: nixos/nix:latest
depends_on: [prepare-build-dependencies]
when: *after_dependency_step
environment: *nix_config
commands:
- nix run --quiet .#import-exported-paths
- nix build --quiet --print-build-logs .#checks.x86_64-linux.clippy-lints
- name: upload-builds-to-cachix
image: nixos/nix:latest
depends_on: [build-and-test-bootvine, build-repo-tasks]
when:
- event: [push, manual]
branch: main
status: [success, failure]
environment:
<<: *nix_config
CACHIX_AUTH_TOKEN:
from_secret: cachix_auth_token
commands:
- nix run --quiet .#upload-exported-paths
- name: run-pre-commit-hooks
image: nixos/nix:latest
depends_on: [prepare-build-dependencies]
when: *after_dependency_step
environment: *nix_config
commands:
- nix run --quiet .#run-pre-commit-hooks
- name: evaluate-flake-outputs
image: nixos/nix:latest
depends_on: []
environment: *nix_config
commands:
- nix flake check --quiet --no-build
- name: check-commit-messages
image: nixos/nix:latest
depends_on: []
when:
- event: pull_request
environment: *nix_config
commands:
- nix run --quiet .#check-commit-messages -- --fetch-target-branch FETCH_HEAD..HEAD
+28
View File
@@ -0,0 +1,28 @@
when:
- repo: wvhulle/bootvine
event: cron
cron: weekly-dependency-update
clone:
- name: clone-with-history
image: woodpeckerci/plugin-git
settings:
depth: 0
partial: false
steps:
- name: open-dependency-update-pr
image: nixos/nix:latest
environment:
NIX_CONFIG: |
experimental-features = nix-command flakes
build-users-group =
accept-flake-config = true
GIT_AUTHOR_NAME: wvhulle-bot
GIT_AUTHOR_EMAIL: willemvanhulle@protonmail.com
GIT_COMMITTER_NAME: wvhulle-bot
GIT_COMMITTER_EMAIL: willemvanhulle@protonmail.com
CODEBERG_TOKEN:
from_secret: bot_token
commands:
- nix run --quiet .#open-dependency-update-pr -- --cargo-lock --flake-lock
@@ -4,10 +4,10 @@ when:
branch: main branch: main
depends_on: depends_on:
- rust-and-flake-checks - checks
clone: clone:
- name: clone-with-history-and-tags - name: clone-with-history
image: woodpeckerci/plugin-git image: woodpeckerci/plugin-git
settings: settings:
depth: 0 depth: 0
@@ -25,21 +25,19 @@ variables:
GIT_COMMITTER_NAME: release-plz GIT_COMMITTER_NAME: release-plz
GIT_COMMITTER_EMAIL: willemvanhulle@protonmail.com GIT_COMMITTER_EMAIL: willemvanhulle@protonmail.com
CODEBERG_TOKEN: CODEBERG_TOKEN:
from_secret: codeberg_token from_secret: bot_token
CARGO_REGISTRY_TOKEN: CARGO_REGISTRY_TOKEN:
from_secret: cargo_registry_token from_secret: cargo_registry_token
steps: steps:
- name: publish-crate-and-tag-release - name: publish-unreleased-crate-version
image: nixos/nix:latest image: nixos/nix:latest
environment: *release_env environment: *release_env
commands: commands:
- git remote set-url origin "https://wvhulle:$${CODEBERG_TOKEN}@codeberg.org/$${CI_REPO}.git" - nix run --quiet .#publish-unreleased-crate-version
- git checkout -B main "$${CI_COMMIT_SHA}"
- nix run .#release-plz-release
- name: update-release-pr - name: open-or-update-release-pr
image: nixos/nix:latest image: nixos/nix:latest
environment: *release_env environment: *release_env
commands: commands:
- nix run .#release-plz-release-pr - nix run --quiet .#open-or-update-release-pr
-87
View File
@@ -1,87 +0,0 @@
when:
- repo: wvhulle/bootvine
event: [pull_request, push, manual]
variables:
- &nix_config
NIX_CONFIG: |
experimental-features = nix-command flakes
build-users-group =
accept-flake-config = true
- &cache_writing_env
<<: *nix_config
CACHIX_AUTH_TOKEN:
from_secret: cachix_auth_token
- &on_main_branch
- event: [push, manual]
branch: main
- &off_main_branch
- event: pull_request
- event: [push, manual]
branch:
exclude: main
- &on_pull_requests
- event: pull_request
steps:
- name: build-test-and-cache-bootvine
image: nixos/nix:latest
depends_on: []
when: *on_main_branch
environment: *cache_writing_env
commands:
- nix run .#build-and-push-to-cachix -- .#checks.x86_64-linux.bootvine-build
- name: build-and-test-bootvine
image: nixos/nix:latest
depends_on: []
when: *off_main_branch
environment: *nix_config
commands:
- nix build --print-build-logs .#checks.x86_64-linux.bootvine-build
- name: build-and-cache-repo-tasks
image: nixos/nix:latest
depends_on: []
when: *on_main_branch
environment: *cache_writing_env
commands:
- nix run .#build-and-push-to-cachix -- .#checks.x86_64-linux.repo-tasks-build
- name: build-repo-tasks
image: nixos/nix:latest
depends_on: []
when: *off_main_branch
environment: *nix_config
commands:
- nix build --print-build-logs .#checks.x86_64-linux.repo-tasks-build
- name: lint-rust-with-clippy
image: nixos/nix:latest
depends_on: []
environment: *nix_config
commands:
- nix build --print-build-logs .#checks.x86_64-linux.clippy-lints
- name: check-rust-formatting
image: nixos/nix:latest
depends_on: []
environment: *nix_config
commands:
- nix build --print-build-logs .#checks.x86_64-linux.rustfmt-formatting
- name: evaluate-flake-outputs
image: nixos/nix:latest
depends_on: []
environment: *nix_config
commands:
- nix flake check --no-build
- name: check-conventional-commit-messages
image: nixos/nix:latest
depends_on: []
when: *on_pull_requests
environment: *nix_config
commands:
- git fetch --quiet origin "$${CI_COMMIT_TARGET_BRANCH}"
- nix run .#check-conventional-commits -- FETCH_HEAD..HEAD
+30
View File
@@ -7,6 +7,36 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased] ## [Unreleased]
## [0.1.3](https://codeberg.org/wvhulle/bootvine/compare/v0.1.2...v0.1.3) - 2026-11-05
### Fixed
- do not report collected systemd jobs as failed
- keep systemd status off the display manager until the boot finishes
## [0.1.2](https://codeberg.org/wvhulle/bootvine/compare/v0.1.1...v0.1.2) - 2026-11-02
### Added
- show the kernel's image loading progress while resuming from hibernation
- say when the screen is waiting for the system manager
### Changed
- reduce screen spacing to a small named set and declarative layouts
### Fixed
- repaint the whole screen while the root switches
- finish console setup before resuming from hibernation
## [0.1.1](https://codeberg.org/wvhulle/bootvine/compare/v0.1.0...v0.1.1) - 2026-10-30
### Changed
- read the release environment from the crate build and generate the sample machine apps
- keep recordings on an orphan branch
## [0.1.0](https://codeberg.org/wvhulle/bootvine/releases/tag/v0.1.0) - 2026-10-25 ## [0.1.0](https://codeberg.org/wvhulle/bootvine/releases/tag/v0.1.0) - 2026-10-25
### Added ### Added
Generated
+1 -1
View File
@@ -144,7 +144,7 @@ dependencies = [
[[package]] [[package]]
name = "bootvine" name = "bootvine"
version = "0.1.0" version = "0.1.3"
dependencies = [ dependencies = [
"clap", "clap",
"crossterm 0.29.0", "crossterm 0.29.0",
+1 -1
View File
@@ -9,7 +9,7 @@ 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 distributions: a wall of log lines scrolling past too fast to read, which never
gave me any idea of what was going on. 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/recordings/boot.gif" width="691" alt="A boot through the initrd into stage 2, with one failed unit">
It also follows shutdowns, answers passphrase prompts such as a It also follows shutdowns, answers passphrase prompts such as a
[LUKS](https://gitlab.com/cryptsetup/cryptsetup) unlock in place, and shows why [LUKS](https://gitlab.com/cryptsetup/cryptsetup) unlock in place, and shows why
+1 -1
View File
@@ -9,7 +9,7 @@ name = "bootvine"
readme = "../README.md" readme = "../README.md"
repository = "https://codeberg.org/wvhulle/bootvine" repository = "https://codeberg.org/wvhulle/bootvine"
rust-version = "1.91" rust-version = "1.91"
version = "0.1.0" version = "0.1.3"
[lints] [lints]
workspace = true workspace = true
+20 -1
View File
@@ -94,6 +94,11 @@ impl BootState {
} }
} }
#[must_use]
pub fn awaits_manager(&self) -> bool {
self.root == Root::Unresolved
}
pub fn set_root(&mut self, root: String) { pub fn set_root(&mut self, root: String) {
if self.phase == Phase::User && !self.milestone_targets.contains(&root) { if self.phase == Phase::User && !self.milestone_targets.contains(&root) {
self.milestone_targets.push(root.clone()); self.milestone_targets.push(root.clone());
@@ -189,7 +194,7 @@ impl BootState {
}; };
let outcome = match result { let outcome = match result {
JobResult::Done => Outcome::Succeeded { at }, JobResult::Done => Outcome::Succeeded { at },
JobResult::Skipped | JobResult::Canceled => Outcome::Abandoned, JobResult::Skipped | JobResult::Canceled | JobResult::Collected => Outcome::Abandoned,
JobResult::Failed => Outcome::Failed(FailureKind::Broke), JobResult::Failed => Outcome::Failed(FailureKind::Broke),
JobResult::Timeout => Outcome::Failed(FailureKind::TimedOut), JobResult::Timeout => Outcome::Failed(FailureKind::TimedOut),
JobResult::Dependency => Outcome::Failed(FailureKind::DependencyFailed), JobResult::Dependency => Outcome::Failed(FailureKind::DependencyFailed),
@@ -332,6 +337,20 @@ mod tests {
); );
} }
#[test]
fn a_collected_job_on_a_multi_device_mount_source_is_not_a_failure() {
let mut state = BootState::new(Phase::Initrd);
queue_unit(
&mut state,
1,
waiting("dev-nvme0n1p1:-dev-nvme1n1p3.device", &[]),
500 * MS,
);
state.finish_job(1, JobResult::Collected, 2000 * MS);
assert!(state.failed.is_empty());
assert_eq!(state.tally().failed, 0);
}
#[test] #[test]
fn a_unit_entering_the_failed_state_counts_without_a_failed_job() { fn a_unit_entering_the_failed_state_counts_without_a_failed_job() {
let mut state = sample(); let mut state = sample();
+2
View File
@@ -20,6 +20,7 @@ pub enum JobResult {
Done, Done,
Skipped, Skipped,
Canceled, Canceled,
Collected,
Timeout, Timeout,
Dependency, Dependency,
#[serde(other)] #[serde(other)]
@@ -162,6 +163,7 @@ mod tests {
); );
assert_eq!(from_str("maintenance").ok(), Some(ActiveState::Inactive)); assert_eq!(from_str("maintenance").ok(), Some(ActiveState::Inactive));
assert_eq!(from_str("dependency").ok(), Some(JobResult::Dependency)); assert_eq!(from_str("dependency").ok(), Some(JobResult::Dependency));
assert_eq!(from_str("collected").ok(), Some(JobResult::Collected));
assert_eq!(from_str("frozen").ok(), Some(JobResult::Failed)); assert_eq!(from_str("frozen").ok(), Some(JobResult::Failed));
assert_eq!(from_str("stop").ok(), Some(JobKind::TakesDown)); assert_eq!(from_str("stop").ok(), Some(JobKind::TakesDown));
assert_eq!(from_str("restart").ok(), Some(JobKind::BringsUp)); assert_eq!(from_str("restart").ok(), Some(JobKind::BringsUp));
+31 -40
View File
@@ -7,6 +7,7 @@ mod run_timeline;
mod screen_chrome; mod screen_chrome;
#[cfg(test)] #[cfg(test)]
mod screen_render_fixtures; mod screen_render_fixtures;
mod screen_spacing;
mod stage_summary; mod stage_summary;
mod tree_height_fitting; mod tree_height_fitting;
#[cfg(test)] #[cfg(test)]
@@ -18,7 +19,10 @@ use std::time::Duration;
use jiff::fmt::friendly::{Designator, FractionalUnit, Spacing, SpanPrinter}; use jiff::fmt::friendly::{Designator, FractionalUnit, Spacing, SpanPrinter};
use ratatui::{ use ratatui::{
buffer::Buffer, buffer::Buffer,
layout::{Constraint, Layout, Rect}, layout::{
Constraint::{Fill, Length},
Layout, Rect,
},
style::Color, style::Color,
text::Line, text::Line,
widgets::{Block, Borders, Widget}, widgets::{Block, Borders, Widget},
@@ -29,8 +33,9 @@ use unicode_width::UnicodeWidthStr;
pub use self::screen_chrome::PasswordPrompt; pub use self::screen_chrome::PasswordPrompt;
use self::{ use self::{
failure_panel::FailurePanel, failure_panel::FailurePanel,
run_timeline::{RunningRun, Timeline}, run_timeline::{RunningRun, Timeline, timeline_fits},
screen_chrome::{FOOTER_HEIGHT, Footer, Header, PasswordPopup}, screen_chrome::{Footer, Header, PasswordPopup},
screen_spacing::{PANEL_MINIMUM_HEIGHT, RULED_ROW_HEIGHT, TEXT_ROW_HEIGHT},
stage_summary::Stages, stage_summary::Stages,
tree_height_fitting::rows_within_height, tree_height_fitting::rows_within_height,
unit_tree::UnitTree, unit_tree::UnitTree,
@@ -43,14 +48,7 @@ use crate::{
screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs}, screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs},
}; };
const DURATION_WIDTH: u16 = 9; const MIN_TIMELINE_HEIGHT: u16 = RULED_ROW_HEIGHT + PANEL_MINIMUM_HEIGHT;
const MIN_BAR_WIDTH: u16 = 12;
const MIN_HEIGHT_FOR_TIMELINE: u16 = 12;
const MIN_TIMELINE_HEIGHT: u16 = run_timeline::CHROME_HEIGHT + 4;
const HEADER_HEIGHT: u16 = 1;
const MIN_FAILURE_PANEL_HEIGHT: u16 = failure_panel::RULE_HEIGHT + 1;
const RESERVED_FAILURE_PANEL_HEIGHT: u16 = failure_panel::RULE_HEIGHT + 3;
const MIN_TREE_HEIGHT_BESIDE_FAILURES: u16 = 4;
const BRANCH: &str = "├─ "; const BRANCH: &str = "├─ ";
const LAST_BRANCH: &str = "└─ "; const LAST_BRANCH: &str = "└─ ";
const PASSING_TRUNK: &str = "│ "; const PASSING_TRUNK: &str = "│ ";
@@ -160,18 +158,23 @@ impl Widget for BootView<'_> {
colors: &self.colors.footer, colors: &self.colors.footer,
glyphs: self.glyphs, glyphs: self.glyphs,
}; };
let fits_timeline = area.width >= run_timeline::LABEL_WIDTH + 1 + MIN_BAR_WIDTH let [header_area, stage_area, body_area, footer_area] = area.layout(&Layout::vertical([
&& area.height >= MIN_HEIGHT_FOR_TIMELINE; Length(TEXT_ROW_HEIGHT),
let free = area Length(stages.height()),
.height Fill(1),
.saturating_sub(HEADER_HEIGHT + stages.height() + FOOTER_HEIGHT); Length(RULED_ROW_HEIGHT),
]));
let heights = Heights::share( let heights = Heights::share(
free, body_area.height,
UnitTree::height_of(pending_count, 0), UnitTree::height_of(pending_count, 0),
failure_panel.height(), failure_panel.height(),
if fits_timeline { timeline.height() } else { 0 }, if timeline_fits(body_area) {
timeline.height()
} else {
0
},
); );
let budget = usize::from(heights.tree.saturating_sub(1)); let budget = usize::from(heights.tree.saturating_sub(TEXT_ROW_HEIGHT));
let rows = rows_within_height(forest, budget); let rows = rows_within_height(forest, budget);
let tree = UnitTree { let tree = UnitTree {
phase: stages.current_phase(), phase: stages.current_phase(),
@@ -184,24 +187,12 @@ impl Widget for BootView<'_> {
}; };
let tree_height = tree.height().min(heights.tree); let tree_height = tree.height().min(heights.tree);
let [ let [tree_area, _, failure_area, timeline_area] = body_area.layout(&Layout::vertical([
header_area, Length(tree_height),
stage_area, Fill(1),
tree_area, Length(heights.failures),
_, Length(heights.timeline),
failure_area, ]));
timeline_area,
footer_area,
] = Layout::vertical([
Constraint::Length(HEADER_HEIGHT),
Constraint::Length(stages.height()),
Constraint::Length(tree_height),
Constraint::Fill(1),
Constraint::Length(heights.failures),
Constraint::Length(heights.timeline),
Constraint::Length(FOOTER_HEIGHT),
])
.areas(area);
header.render(header_area, buf); header.render(header_area, buf);
stages.render(stage_area, buf); stages.render(stage_area, buf);
@@ -232,13 +223,13 @@ struct Heights {
impl Heights { impl Heights {
fn share(free: u16, tree_need: u16, failures_need: u16, timeline_need: u16) -> Self { fn share(free: u16, tree_need: u16, failures_need: u16, timeline_need: u16) -> Self {
let reserved = RESERVED_FAILURE_PANEL_HEIGHT let reserved = PANEL_MINIMUM_HEIGHT
.min(failures_need) .min(failures_need)
.min(free.saturating_sub(MIN_TREE_HEIGHT_BESIDE_FAILURES)); .min(free.saturating_sub(PANEL_MINIMUM_HEIGHT));
let failures = failures_need let failures = failures_need
.min(free.saturating_sub(tree_need)) .min(free.saturating_sub(tree_need))
.max(reserved); .max(reserved);
let failures = if failures >= MIN_FAILURE_PANEL_HEIGHT { let failures = if failures >= RULED_ROW_HEIGHT {
failures failures
} else { } else {
0 0
+14 -15
View File
@@ -9,16 +9,15 @@ use ratatui::{
}; };
use unicode_width::UnicodeWidthStr; use unicode_width::UnicodeWidthStr;
use super::{fit_width, rule}; use super::{
fit_width, rule,
screen_spacing::{TEXT_GAP, TEXT_INDENT, TEXT_ROW_HEIGHT},
};
use crate::{ use crate::{
boot_model::{FailedUnit, FailureExplanation}, boot_model::{FailedUnit, FailureExplanation},
screen_settings::{color_scheme::FailureColors, font_glyphs::Glyphs}, screen_settings::{color_scheme::FailureColors, font_glyphs::Glyphs},
}; };
pub const RULE_HEIGHT: u16 = 1;
const LOG_INDENT: &str = " ";
const REASON_GAP: &str = " ";
pub struct FailurePanel<'a> { pub struct FailurePanel<'a> {
pub newest_first: Vec<&'a FailedUnit>, pub newest_first: Vec<&'a FailedUnit>,
pub colors: &'a FailureColors, pub colors: &'a FailureColors,
@@ -42,14 +41,14 @@ impl FailurePanel<'_> {
.iter() .iter()
.map(|failed| 1 + log_lines(failed).len()) .map(|failed| 1 + log_lines(failed).len())
.sum(); .sum();
RULE_HEIGHT.saturating_add(u16::try_from(rows).unwrap_or(u16::MAX)) TEXT_ROW_HEIGHT.saturating_add(u16::try_from(rows).unwrap_or(u16::MAX))
} }
fn headline(&self, failed: &FailedUnit, width: usize) -> Line<'static> { fn headline(&self, failed: &FailedUnit, width: usize) -> Line<'static> {
let marker = format!("{} ", self.glyphs.failed); let marker = format!("{} ", self.glyphs.failed);
let label_room = width.saturating_sub(marker.width()); let label_room = width.saturating_sub(marker.width());
let label = fit_width(&failed.label, label_room, self.glyphs.ellipsis); let label = fit_width(&failed.label, label_room, self.glyphs.ellipsis);
let reason_room = label_room.saturating_sub(label.width() + REASON_GAP.width()); let reason_room = label_room.saturating_sub(label.width() + TEXT_GAP.width());
let reason = match &failed.explanation { let reason = match &failed.explanation {
FailureExplanation::Explained(cause) if reason_room > 0 => { FailureExplanation::Explained(cause) if reason_room > 0 => {
fit_width(&cause.reason, reason_room, self.glyphs.ellipsis) fit_width(&cause.reason, reason_room, self.glyphs.ellipsis)
@@ -57,7 +56,7 @@ impl FailurePanel<'_> {
_ => String::new(), _ => String::new(),
}; };
let reason_span = let reason_span =
(!reason.is_empty()).then(|| format!("{REASON_GAP}{reason}").fg(self.colors.reason)); (!reason.is_empty()).then(|| format!("{TEXT_GAP}{reason}").fg(self.colors.reason));
Line::from( Line::from(
[ [
marker.fg(self.colors.unit), marker.fg(self.colors.unit),
@@ -70,11 +69,11 @@ impl FailurePanel<'_> {
} }
fn block(&self, failed: &FailedUnit, width: usize) -> Vec<Line<'static>> { fn block(&self, failed: &FailedUnit, width: usize) -> Vec<Line<'static>> {
let log_room = width.saturating_sub(LOG_INDENT.width()); let log_room = width.saturating_sub(TEXT_INDENT.width());
once(self.headline(failed, width)) once(self.headline(failed, width))
.chain(log_lines(failed).iter().map(|line| { .chain(log_lines(failed).iter().map(|line| {
format!( format!(
"{LOG_INDENT}{}", "{TEXT_INDENT}{}",
fit_width(line, log_room, self.glyphs.ellipsis) fit_width(line, log_room, self.glyphs.ellipsis)
) )
.fg(self.colors.log) .fg(self.colors.log)
@@ -170,8 +169,8 @@ mod tests {
panel_text(&failures, 5), panel_text(&failures, 5),
[ [
"× web exited with status 1", "× web exited with status 1",
" bind: address in use", " bind: address in use",
" giving up", " giving up",
"× db exited with status 1", "× db exited with status 1",
"× cache exited with status 1", "× cache exited with status 1",
] ]
@@ -189,10 +188,10 @@ mod tests {
panel_text(&failures, 6), panel_text(&failures, 6),
[ [
"× web exited with status 1", "× web exited with status 1",
" giving up", " giving up",
"× db exited with status 1", "× db exited with status 1",
" disk full", " disk full",
" read-only file system", " read-only file system",
"× cache exited with status 1", "× cache exited with status 1",
] ]
); );
+24 -6
View File
@@ -13,6 +13,24 @@ use crate::{
const CRYPTSETUP_MESSAGE: &str = const CRYPTSETUP_MESSAGE: &str =
"Please enter passphrase for disk Samsung SSD 980 PRO 1TB (cryptroot):"; "Please enter passphrase for disk Samsung SSD 980 PRO 1TB (cryptroot):";
#[test]
fn the_stage_says_when_the_manager_has_not_answered_yet() {
let mut state = BootState::new(Phase::Host);
let lines = render(&state, 500 * MS, 110, 24);
assert!(
lines[1].contains("Stage 2") && lines[1].contains("waiting for the system manager"),
"{}",
lines.join("\n")
);
state.set_root("graphical.target".to_owned());
let lines = render(&state, 500 * MS, 110, 24);
assert!(
lines.iter().all(|line| !line.contains("system manager")),
"{}",
lines.join("\n")
);
}
#[test] #[test]
fn tree_on_top_timeline_below() { fn tree_on_top_timeline_below() {
let lines = render(&boot_in_progress(), 12_400 * MS, 110, 24); let lines = render(&boot_in_progress(), 12_400 * MS, 110, 24);
@@ -65,7 +83,7 @@ fn tree_on_top_timeline_below() {
); );
assert!(!screen.contains("root switch"), "{screen}"); assert!(!screen.contains("root switch"), "{screen}");
assert!( assert!(
lines[23].starts_with("√ 2 done 2 running 3 waiting × 1 failed"), lines[23].starts_with("√ 2 done 2 running 3 waiting × 1 failed"),
"{screen}" "{screen}"
); );
} }
@@ -99,7 +117,7 @@ fn password_prompt_floats_over_a_dimmed_view() {
assert!(lines[title_row + 3].contains("│ > ***_"), "{screen}"); assert!(lines[title_row + 3].contains("│ > ***_"), "{screen}");
assert!(lines[title_row + 4].contains("Enter unlock"), "{screen}"); assert!(lines[title_row + 4].contains("Enter unlock"), "{screen}");
assert!( assert!(
lines[23].starts_with("√ 2 done 2 running 3 waiting × 1 failed"), lines[23].starts_with("√ 2 done 2 running 3 waiting × 1 failed"),
"{screen}" "{screen}"
); );
assert_eq!( assert_eq!(
@@ -239,7 +257,7 @@ fn long_timeline_labels_end_in_an_ellipsis() {
#[test] #[test]
fn narrow_screens_drop_the_timeline() { fn narrow_screens_drop_the_timeline() {
let lines = render(&boot_in_progress(), 12_400 * MS, 40, 24); let lines = render(&boot_in_progress(), 12_400 * MS, 37, 24);
assert!( assert!(
lines.iter().all(|line| !line.contains('■')), lines.iter().all(|line| !line.contains('■')),
"{}", "{}",
@@ -427,10 +445,10 @@ fn failures_show_their_reason_and_journal_lines_above_the_timeline() {
); );
assert_eq!( assert_eq!(
lines[failures + 2], lines[failures + 2],
" ERROR! Failed to get system power limits", " ERROR! Failed to get system power limits",
"{screen}" "{screen}"
); );
assert_eq!(lines[failures + 3], " giving up", "{screen}"); assert_eq!(lines[failures + 3], " giving up", "{screen}");
} }
#[test] #[test]
@@ -448,7 +466,7 @@ fn failure_lines_are_cut_to_a_narrow_screen() {
); );
assert_eq!( assert_eq!(
lines[failures + 2], lines[failures + 2],
" ERROR! Failed to get syst…", " ERROR! Failed to get syste…",
"{screen}" "{screen}"
); );
} }
+34 -16
View File
@@ -2,7 +2,10 @@ use std::{cmp::Reverse, iter::once, time::Duration};
use ratatui::{ use ratatui::{
buffer::Buffer, buffer::Buffer,
layout::{Constraint, Layout, Rect}, layout::{
Constraint::{Fill, Length},
Layout, Rect,
},
style::{Color, Stylize}, style::{Color, Stylize},
symbols::Marker, symbols::Marker,
text::{Line, Span}, text::{Line, Span},
@@ -12,18 +15,22 @@ use ratatui::{
}, },
}; };
use super::{WHOLE_UNITS, fit_width, rule, unit_count}; use super::{
WHOLE_UNITS, fit_width, rule,
screen_spacing::{
ANNOTATION_COLUMN_WIDTH, COLUMN_GAP_WIDTH, RULED_ROW_HEIGHT, TEXT_ROW_HEIGHT,
TIMELINE_LABEL_WIDTH,
},
unit_count,
};
use crate::{ use crate::{
boot_model::{FinishedRun, MilestoneRow}, boot_model::{FinishedRun, MilestoneRow},
screen_settings::{color_scheme::TimelineColors, font_glyphs::Glyphs}, screen_settings::{color_scheme::TimelineColors, font_glyphs::Glyphs},
}; };
pub const LABEL_WIDTH: u16 = 28;
pub const CHROME_HEIGHT: u16 = 2;
const MARK_WIDTH: u16 = 2; const MARK_WIDTH: u16 = 2;
const SLOWEST_RUNS_SHOWN: usize = 5; const SLOWEST_RUNS_SHOWN: usize = 5;
const KERNEL_ORIGIN_LABEL: &str = "Kernel"; const KERNEL_ORIGIN_LABEL: &str = "Kernel";
const AXIS_LABEL_SPACING: u16 = 8;
const AXIS_STEPS: [Duration; 12] = [ const AXIS_STEPS: [Duration; 12] = [
Duration::from_secs(1), Duration::from_secs(1),
Duration::from_secs(2), Duration::from_secs(2),
@@ -56,6 +63,17 @@ pub struct RunningRun<'a> {
pub since: Duration, pub since: Duration,
} }
fn label_and_bar_areas(area: Rect) -> [Rect; 2] {
area.layout(
&Layout::horizontal([Length(TIMELINE_LABEL_WIDTH), Fill(1)]).spacing(COLUMN_GAP_WIDTH),
)
}
pub fn timeline_fits(area: Rect) -> bool {
let [_, bar_area] = label_and_bar_areas(area);
bar_area.width >= ANNOTATION_COLUMN_WIDTH
}
impl Timeline<'_> { impl Timeline<'_> {
pub fn height(&self) -> u16 { pub fn height(&self) -> u16 {
let entries = self.milestones.len() let entries = self.milestones.len()
@@ -64,11 +82,11 @@ impl Timeline<'_> {
if entries == 0 { if entries == 0 {
return 0; return 0;
} }
CHROME_HEIGHT.saturating_add(u16::try_from(entries).unwrap_or(u16::MAX)) RULED_ROW_HEIGHT.saturating_add(u16::try_from(entries).unwrap_or(u16::MAX))
} }
fn finished_that_fit(&self, height: u16) -> Vec<&FinishedRun> { fn finished_that_fit(&self, height: u16) -> Vec<&FinishedRun> {
let bar_rows = usize::from(height.saturating_sub(CHROME_HEIGHT)); let bar_rows = usize::from(height.saturating_sub(RULED_ROW_HEIGHT));
let room = bar_rows.saturating_sub(self.milestones.len() + self.running.len()); let room = bar_rows.saturating_sub(self.milestones.len() + self.running.len());
let mut longest_first = self.finished.clone(); let mut longest_first = self.finished.clone();
longest_first longest_first
@@ -128,7 +146,7 @@ impl Timeline<'_> {
fn fitted(&self, label: &str) -> String { fn fitted(&self, label: &str) -> String {
fit_width( fit_width(
label, label,
usize::from(LABEL_WIDTH - MARK_WIDTH), usize::from(TIMELINE_LABEL_WIDTH - MARK_WIDTH),
self.glyphs.ellipsis, self.glyphs.ellipsis,
) )
} }
@@ -169,10 +187,7 @@ impl Widget for Timeline<'_> {
); );
let inner = block.inner(area); let inner = block.inner(area);
block.render(area, buf); block.render(area, buf);
let [label_area, bar_area] = let [label_area, bar_area] = label_and_bar_areas(inner);
Layout::horizontal([Constraint::Length(LABEL_WIDTH), Constraint::Fill(1)])
.spacing(1)
.areas(inner);
let entries: Vec<TimelineEntry> = self let entries: Vec<TimelineEntry> = self
.milestones .milestones
.iter() .iter()
@@ -184,12 +199,15 @@ impl Widget for Timeline<'_> {
) )
.chain(self.running.iter().map(|row| self.running_entry(row))) .chain(self.running.iter().map(|row| self.running_entry(row)))
.collect(); .collect();
let [_, entry_labels_area] =
label_area.layout(&Layout::vertical([Length(TEXT_ROW_HEIGHT), Fill(1)]));
Paragraph::new( Paragraph::new(
once(Line::default()) entries
.chain(entries.iter().map(|entry| entry.label.clone())) .iter()
.map(|entry| entry.label.clone())
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
) )
.render(label_area, buf); .render(entry_labels_area, buf);
let axis = TimeAxis::new(self.origin, self.now, bar_area.width); let axis = TimeAxis::new(self.origin, self.now, bar_area.width);
let label_row = f64::from(bar_area.height.saturating_sub(1).max(1)); let label_row = f64::from(bar_area.height.saturating_sub(1).max(1));
let axis_color = self.colors.axis; let axis_color = self.colors.axis;
@@ -265,7 +283,7 @@ struct TimeAxis {
impl TimeAxis { impl TimeAxis {
fn new(origin: Duration, now: Duration, width: u16) -> Self { fn new(origin: Duration, now: Duration, width: u16) -> Self {
let elapsed = now.saturating_sub(origin).max(AXIS_STEPS[0]); let elapsed = now.saturating_sub(origin).max(AXIS_STEPS[0]);
let max_labels = u128::from((width / AXIS_LABEL_SPACING).max(1)); let max_labels = u128::from((width / ANNOTATION_COLUMN_WIDTH).max(1));
let step = AXIS_STEPS let step = AXIS_STEPS
.into_iter() .into_iter()
.find(|step| elapsed.as_nanos().div_ceil(step.as_nanos()) <= max_labels) .find(|step| elapsed.as_nanos().div_ceil(step.as_nanos()) <= max_labels)
+25 -23
View File
@@ -2,13 +2,19 @@ use std::{iter::once, time::Duration};
use ratatui::{ use ratatui::{
buffer::Buffer, buffer::Buffer,
layout::{Constraint, Rect}, layout::{
Constraint::{self, Fill, Length},
Layout, Rect,
},
style::{Style, Stylize}, style::{Style, Stylize},
text::{Line, Span}, text::{Line, Span},
widgets::{Block, Borders, Clear, Padding, Paragraph, Widget, Wrap}, widgets::{Block, Clear, Padding, Paragraph, Widget, Wrap},
}; };
use super::{DURATION_WIDTH, ELAPSED}; use super::{
ELAPSED, rule,
screen_spacing::{ANNOTATION_COLUMN_WIDTH, TEXT_GAP},
};
use crate::{ use crate::{
boot_model::{Tally, boot_origin::BootOrigin}, boot_model::{Tally, boot_origin::BootOrigin},
screen_settings::{ screen_settings::{
@@ -17,7 +23,6 @@ use crate::{
}, },
}; };
pub const FOOTER_HEIGHT: u16 = 2;
const SEPARATOR: &str = " · "; const SEPARATOR: &str = " · ";
const REJECTED_PASSPHRASE: &str = "Wrong passphrase, try again"; const REJECTED_PASSPHRASE: &str = "Wrong passphrase, try again";
@@ -47,19 +52,17 @@ impl Header<'_> {
impl Widget for Header<'_> { impl Widget for Header<'_> {
fn render(self, area: Rect, buf: &mut Buffer) { fn render(self, area: Rect, buf: &mut Buffer) {
self.origin().render( let [origin_area, total_area] = area.layout(&Layout::horizontal([
Rect { Fill(1),
width: area.width.saturating_sub(DURATION_WIDTH), Length(ANNOTATION_COLUMN_WIDTH),
..area ]));
}, self.origin().render(origin_area, buf);
buf,
);
if let Some(total) = self.total { if let Some(total) = self.total {
Line::from(ELAPSED.unsigned_duration_to_string(&total)) Line::from(ELAPSED.unsigned_duration_to_string(&total))
.fg(self.colors.total_time) .fg(self.colors.total_time)
.bold() .bold()
.right_aligned() .right_aligned()
.render(area, buf); .render(total_area, buf);
} }
} }
} }
@@ -72,24 +75,23 @@ pub struct Footer<'a> {
impl Widget for Footer<'_> { impl Widget for Footer<'_> {
fn render(self, area: Rect, buf: &mut Buffer) { fn render(self, area: Rect, buf: &mut Buffer) {
let failed = format!(" {} {} failed", self.glyphs.failed, self.tally.failed); let failed = format!(
"{TEXT_GAP}{} {} failed",
self.glyphs.failed, self.tally.failed
);
let failed = if self.tally.failed > 0 { let failed = if self.tally.failed > 0 {
failed.fg(self.colors.failed).bold() failed.fg(self.colors.failed).bold()
} else { } else {
failed.fg(self.colors.no_failures) failed.fg(self.colors.no_failures)
}; };
let block = Block::new() Paragraph::new(Line::from(vec![
.borders(Borders::TOP)
.border_style(self.colors.rule);
let inner = block.inner(area);
block.render(area, buf);
Line::from(vec![
format!("{} {} done", self.glyphs.done, self.tally.done).fg(self.colors.done), format!("{} {} done", self.glyphs.done, self.tally.done).fg(self.colors.done),
format!(" {} running", self.tally.running).fg(self.colors.running), format!("{TEXT_GAP}{} running", self.tally.running).fg(self.colors.running),
format!(" {} waiting", self.tally.waiting).fg(self.colors.waiting), format!("{TEXT_GAP}{} waiting", self.tally.waiting).fg(self.colors.waiting),
failed, failed,
]) ]))
.render(inner, buf); .block(rule(self.colors.rule, Line::default()))
.render(area, buf);
} }
} }
+8
View File
@@ -0,0 +1,8 @@
pub const TEXT_ROW_HEIGHT: u16 = 1;
pub const RULED_ROW_HEIGHT: u16 = 2;
pub const PANEL_MINIMUM_HEIGHT: u16 = 4;
pub const COLUMN_GAP_WIDTH: u16 = 1;
pub const ANNOTATION_COLUMN_WIDTH: u16 = 9;
pub const TIMELINE_LABEL_WIDTH: u16 = 28;
pub const TEXT_GAP: &str = " ";
pub const TEXT_INDENT: &str = " ";
+16 -4
View File
@@ -8,14 +8,21 @@ use ratatui::{
widgets::{Paragraph, Widget}, widgets::{Paragraph, Widget},
}; };
use super::{BRANCH, ELAPSED, LAST_BRANCH, unit_count}; use super::{BRANCH, ELAPSED, LAST_BRANCH, screen_spacing::ANNOTATION_COLUMN_WIDTH, unit_count};
use crate::{ use crate::{
boot_model::BootState, boot_model::BootState,
screen_settings::{color_scheme::StageColors, font_glyphs::Glyphs}, screen_settings::{color_scheme::StageColors, font_glyphs::Glyphs},
}; };
const SHUTDOWN_SUCCESSOR: &str = "systemd-shutdown"; const SHUTDOWN_SUCCESSOR: &str = "systemd-shutdown";
const PHASE_WIDTH: usize = 9; const AWAITING_MANAGER: &str = " · waiting for the system manager";
fn padded_phase_label(label: &str) -> String {
format!(
"{label:phase_width$}",
phase_width = usize::from(ANNOTATION_COLUMN_WIDTH)
)
}
pub struct Stages<'a> { pub struct Stages<'a> {
pub state: &'a BootState, pub state: &'a BootState,
@@ -57,7 +64,7 @@ impl Stages<'_> {
self.state.finished_stages.iter().map(|stage| { self.state.finished_stages.iter().map(|stage| {
Line::from(vec![ Line::from(vec![
BRANCH.fg(self.colors.branches), BRANCH.fg(self.colors.branches),
format!("{:PHASE_WIDTH$}", stage.label).fg(self.colors.finished_label), padded_phase_label(stage.label).fg(self.colors.finished_label),
format!( format!(
"{} done in {}", "{} done in {}",
self.glyphs.bead, self.glyphs.bead,
@@ -105,10 +112,15 @@ impl Stages<'_> {
let elapsed = ELAPSED.unsigned_duration_to_string(&self.now.saturating_sub(started_at)); let elapsed = ELAPSED.unsigned_duration_to_string(&self.now.saturating_sub(started_at));
Line::from(vec![ Line::from(vec![
LAST_BRANCH.fg(self.colors.branches), LAST_BRANCH.fg(self.colors.branches),
format!("{:PHASE_WIDTH$}", self.state.phase.label()) padded_phase_label(self.state.phase.label())
.fg(self.colors.current) .fg(self.colors.current)
.bold(), .bold(),
elapsed.fg(self.colors.current), elapsed.fg(self.colors.current),
if self.state.awaits_manager() {
AWAITING_MANAGER.fg(self.colors.current)
} else {
Span::default()
},
]) ])
} }
} }
+1 -1
View File
@@ -109,7 +109,7 @@ fn slow_runs_show_their_timeout_in_a_column() {
"{screen}" "{screen}"
); );
assert!( assert!(
line_with(&lines, "slow").ends_with("6.40s 1m30s"), line_with(&lines, "slow").ends_with("6.40s 1m30s"),
"{screen}" "{screen}"
); );
assert!(line_with(&lines, "quick").ends_with("2.40s"), "{screen}"); assert!(line_with(&lines, "quick").ends_with("2.40s"), "{screen}");
+73 -79
View File
@@ -2,7 +2,10 @@ use std::{iter::once, time::Duration};
use ratatui::{ use ratatui::{
buffer::Buffer, buffer::Buffer,
layout::{Constraint, Rect}, layout::{
Constraint::{self, Fill, Length},
Layout, Rect,
},
style::{Style, Stylize}, style::{Style, Stylize},
text::{Line, Span}, text::{Line, Span},
widgets::{Row, Table, Widget}, widgets::{Row, Table, Widget},
@@ -10,8 +13,8 @@ use ratatui::{
use unicode_width::UnicodeWidthStr; use unicode_width::UnicodeWidthStr;
use super::{ use super::{
BRANCH, DURATION_WIDTH, ENDED_TRUNK, LAST_BRANCH, PASSING_TRUNK, RUNNING_ELAPSED, WHOLE_UNITS, BRANCH, ENDED_TRUNK, LAST_BRANCH, PASSING_TRUNK, RUNNING_ELAPSED, WHOLE_UNITS, fit_width,
fit_width, screen_spacing::{ANNOTATION_COLUMN_WIDTH, COLUMN_GAP_WIDTH, TEXT_ROW_HEIGHT},
}; };
use crate::{ use crate::{
boot_model::{RowStatus, TreeRow, UnitKind}, boot_model::{RowStatus, TreeRow, UnitKind},
@@ -20,10 +23,8 @@ use crate::{
const SPINNER: [char; 4] = ['|', '/', '-', '\\']; const SPINNER: [char; 4] = ['|', '/', '-', '\\'];
const SPINNER_STEP: Duration = Duration::from_millis(100); const SPINNER_STEP: Duration = Duration::from_millis(100);
const MIN_DESCRIPTION_WIDTH: u16 = 12; const LABEL_SHARE: u16 = 3;
const MIN_TAG_WIDTH: u16 = 6; const DESCRIPTION_SHARE: u16 = 2;
const MIN_LABEL_WIDTH: u16 = 24;
const HEADER_ROWS: u16 = 1;
const SHOW_TIMEOUT_AFTER: Duration = Duration::from_secs(5); const SHOW_TIMEOUT_AFTER: Duration = Duration::from_secs(5);
const TIMEOUT_HEADER: &str = "Timeout"; const TIMEOUT_HEADER: &str = "Timeout";
@@ -43,10 +44,11 @@ pub struct UnitTree<'a> {
} }
struct Columns { struct Columns {
constraints: Vec<Constraint>,
label: u16, label: u16,
tag: u16,
description: u16, description: u16,
timeout: u16, shows_annotations: bool,
shows_timeout: bool,
} }
#[derive(Clone, Copy, PartialEq, Eq)] #[derive(Clone, Copy, PartialEq, Eq)]
@@ -66,15 +68,42 @@ fn spinner_at(now: Duration) -> char {
SPINNER[usize::try_from(steps % 4).unwrap_or_default()] SPINNER[usize::try_from(steps % 4).unwrap_or_default()]
} }
fn width_of(text: &str) -> u16 { fn solved_columns(width: u16, shows_annotations: bool, shows_timeout: bool) -> Columns {
u16::try_from(text.width()).unwrap_or(u16::MAX) let leading = if shows_annotations {
vec![
Fill(LABEL_SHARE),
Length(ANNOTATION_COLUMN_WIDTH),
Fill(DESCRIPTION_SHARE),
]
} else {
vec![Fill(1)]
};
let constraints: Vec<Constraint> = leading
.into_iter()
.chain(once(Length(ANNOTATION_COLUMN_WIDTH)))
.chain(shows_timeout.then_some(Length(ANNOTATION_COLUMN_WIDTH)))
.collect();
let solved = Layout::horizontal(constraints.clone())
.spacing(COLUMN_GAP_WIDTH)
.split(Rect::new(0, 0, width, TEXT_ROW_HEIGHT));
Columns {
label: solved[0].width,
description: if shows_annotations {
solved[2].width
} else {
0
},
constraints,
shows_annotations,
shows_timeout,
}
} }
impl UnitTree<'_> { impl UnitTree<'_> {
pub fn height_of(rows: usize, hidden: usize) -> u16 { pub fn height_of(rows: usize, hidden: usize) -> u16 {
u16::try_from(rows + usize::from(hidden > 0)) u16::try_from(rows + usize::from(hidden > 0))
.unwrap_or(u16::MAX) .unwrap_or(u16::MAX)
.saturating_add(HEADER_ROWS) .saturating_add(TEXT_ROW_HEIGHT)
} }
pub fn height(&self) -> u16 { pub fn height(&self) -> u16 {
@@ -87,7 +116,7 @@ impl UnitTree<'_> {
fn header(&self, columns: &Columns) -> Row<'static> { fn header(&self, columns: &Columns) -> Row<'static> {
if !self.phase_fits_its_column(columns) { if !self.phase_fits_its_column(columns) {
return Row::default().height(HEADER_ROWS); return Row::default().height(TEXT_ROW_HEIGHT);
} }
let name = |text: &'static str| Line::from(text).fg(self.colors.columns); let name = |text: &'static str| Line::from(text).fg(self.colors.columns);
Row::new(columns.shown([ Row::new(columns.shown([
@@ -116,15 +145,6 @@ impl UnitTree<'_> {
}) })
} }
fn timeout_width(&self) -> u16 {
self.rows
.iter()
.filter_map(|row| self.run_timeout(row))
.map(|timeout| width_of(&WHOLE_UNITS.unsigned_duration_to_string(&timeout.limit)))
.max()
.map_or(0, |widest| widest.max(width_of(TIMEOUT_HEADER)))
}
fn timeout_cell(&self, row: &TreeRow) -> Line<'static> { fn timeout_cell(&self, row: &TreeRow) -> Line<'static> {
self.run_timeout(row) self.run_timeout(row)
.map_or_else(Line::default, |timeout| { .map_or_else(Line::default, |timeout| {
@@ -218,39 +238,16 @@ impl UnitTree<'_> {
} }
fn columns(&self, width: u16) -> Columns { fn columns(&self, width: u16) -> Columns {
let timeout = self.timeout_width(); let shows_timeout = self.rows.iter().any(|row| self.run_timeout(row).is_some());
let timeout_room = if timeout > 0 { timeout + 1 } else { 0 }; let has_annotated_rows = self.rows.iter().any(|row| {
let unannotated = width.saturating_sub(DURATION_WIDTH + 1 + timeout_room); row.chain.is_empty() && !(row.description.is_none() && row.kind.tag().is_none())
let annotated: Vec<(&TreeRow, Stage)> = self });
.rows let annotated = solved_columns(width, true, shows_timeout);
.iter() if has_annotated_rows && annotated.description >= ANNOTATION_COLUMN_WIDTH {
.zip(self.stages()) annotated
.filter(|(row, _)| { } else {
row.chain.is_empty() && !(row.description.is_none() && row.kind.tag().is_none()) solved_columns(width, false, shows_timeout)
}) }
.collect();
let tag = annotated
.iter()
.map(|(row, _)| width_of(row.kind.tag().unwrap_or_default()))
.fold(MIN_TAG_WIDTH, u16::max);
let content = unannotated.saturating_sub(2);
let label = (content * 3 / 5).max(MIN_LABEL_WIDTH);
let fits_annotations =
!annotated.is_empty() && label + tag + MIN_DESCRIPTION_WIDTH <= content;
fits_annotations.then_some(label).map_or(
Columns {
label: unannotated,
tag: 0,
description: 0,
timeout,
},
|label| Columns {
label,
tag,
description: content - label - tag,
timeout,
},
)
} }
fn row(&self, row: &TreeRow, stage: Stage, prefix: String, columns: &Columns) -> Row<'static> { fn row(&self, row: &TreeRow, stage: Stage, prefix: String, columns: &Columns) -> Row<'static> {
@@ -279,8 +276,11 @@ impl UnitTree<'_> {
marker, marker,
Span::styled(self.chained_label(row, room), style), Span::styled(self.chained_label(row, room), style),
]), ]),
Line::from(annotation(row.kind.tag().unwrap_or_default(), columns.tag)) Line::from(annotation(
.fg(self.colors.columns), row.kind.tag().unwrap_or_default(),
ANNOTATION_COLUMN_WIDTH,
))
.fg(self.colors.columns),
Line::from(annotation( Line::from(annotation(
row.description.as_deref().unwrap_or_default(), row.description.as_deref().unwrap_or_default(),
columns.description, columns.description,
@@ -297,33 +297,22 @@ impl Columns {
fn shown<T>(&self, cells: [T; 5]) -> impl Iterator<Item = T> { fn shown<T>(&self, cells: [T; 5]) -> impl Iterator<Item = T> {
let present = [ let present = [
true, true,
self.tag > 0, self.shows_annotations,
self.description > 0, self.shows_annotations,
true, true,
self.timeout > 0, self.shows_timeout,
]; ];
cells cells
.into_iter() .into_iter()
.zip(present) .zip(present)
.filter_map(|(cell, present)| present.then_some(cell)) .filter_map(|(cell, present)| present.then_some(cell))
} }
fn widths(&self) -> impl Iterator<Item = Constraint> {
self.shown([
self.label,
self.tag,
self.description,
DURATION_WIDTH,
self.timeout,
])
.map(Constraint::Length)
}
} }
impl Widget for UnitTree<'_> { impl Widget for UnitTree<'_> {
fn render(self, area: Rect, buf: &mut Buffer) { fn render(self, area: Rect, buf: &mut Buffer) {
let capacity = usize::from(area.height.saturating_sub(HEADER_ROWS)); let capacity = usize::from(area.height.saturating_sub(TEXT_ROW_HEIGHT));
let shown = if usize::from(self.height() - HEADER_ROWS) > capacity { let shown = if usize::from(self.height() - TEXT_ROW_HEIGHT) > capacity {
capacity.saturating_sub(1).min(self.rows.len()) capacity.saturating_sub(1).min(self.rows.len())
} else { } else {
self.rows.len() self.rows.len()
@@ -336,20 +325,25 @@ impl Widget for UnitTree<'_> {
]) ])
}); });
let columns = self.columns(area.width); let columns = self.columns(area.width);
Table::new( let table = Table::new(
self.rows self.rows
.iter() .iter()
.zip(self.stages()) .zip(self.stages())
.zip(tree_prefixes(self.rows)) .zip(tree_prefixes(self.rows))
.take(shown) .take(shown)
.map(|((row, stage), prefix)| self.row(row, stage, prefix, &columns)) .map(|((row, stage), prefix)| self.row(row, stage, prefix, &columns)),
.chain(overflow), columns.constraints.clone(),
columns.widths(),
) )
.header(self.header(&columns)) .column_spacing(COLUMN_GAP_WIDTH)
.header(self.header(&columns));
match overflow {
Some(overflow_row) => table.footer(overflow_row),
None => table,
}
.render(area, buf); .render(area, buf);
if !self.phase_fits_its_column(&columns) { if !self.phase_fits_its_column(&columns) {
self.phase.render(Rect { height: 1, ..area }, buf); let [phase_row, _] = area.layout(&Layout::vertical([Length(TEXT_ROW_HEIGHT), Fill(1)]));
self.phase.render(phase_row, buf);
} }
} }
} }
+1
View File
@@ -3,6 +3,7 @@ pub mod console_palette;
pub mod console_takeover; pub mod console_takeover;
pub mod live_desk; pub mod live_desk;
pub mod passphrase_input; pub mod passphrase_input;
pub mod resume_console;
pub mod stream_sources; pub mod stream_sources;
pub mod watch_loop; pub mod watch_loop;
pub mod watch_screen; pub mod watch_screen;
+54 -2
View File
@@ -1,4 +1,4 @@
use std::{future::ready, io, ops::ControlFlow, time::Duration}; use std::{future::ready, io, mem, ops::ControlFlow, path::PathBuf, time::Duration};
use crossterm::event::Event; use crossterm::event::Event;
use futures::{Stream, StreamExt}; use futures::{Stream, StreamExt};
@@ -11,6 +11,7 @@ use crate::{
console_palette::ConsoleLook, console_palette::ConsoleLook,
console_takeover::{ForegroundVt, QuietKernelConsole, console_look, vt_of_stdin}, console_takeover::{ForegroundVt, QuietKernelConsole, console_look, vt_of_stdin},
passphrase_input::asks_to_quit, passphrase_input::asks_to_quit,
resume_console::{RESUME_CONSOLE_MARKER, resume_console_is_open},
stream_sources::items_when_readable, stream_sources::items_when_readable,
watch_screen::{ConsoleDesk, Refresh, ScreenInput, WatchEnding}, watch_screen::{ConsoleDesk, Refresh, ScreenInput, WatchEnding},
}, },
@@ -24,6 +25,8 @@ pub struct LiveDesk {
look: ConsoleLook, look: ConsoleLook,
entry: Option<PasswordEntry>, entry: Option<PasswordEntry>,
handover_deadline: Option<Duration>, handover_deadline: Option<Duration>,
resume_marker: PathBuf,
console_was_lent: bool,
} }
impl LiveDesk { impl LiveDesk {
@@ -44,6 +47,8 @@ impl LiveDesk {
look: console_look(own_vt), look: console_look(own_vt),
entry: None, entry: None,
handover_deadline: None, handover_deadline: None,
resume_marker: PathBuf::from(RESUME_CONSOLE_MARKER),
console_was_lent: false,
} }
} }
@@ -134,7 +139,17 @@ impl ConsoleDesk for LiveDesk {
self.follow_requests(false); self.follow_requests(false);
} }
fn lends_console(&mut self) -> bool {
let lent = resume_console_is_open(&self.resume_marker);
self.console_was_lent |= lent;
lent
}
fn keep_console_up(&mut self) -> Refresh { fn keep_console_up(&mut self) -> Refresh {
if self.lends_console() {
return Refresh::Steady;
}
let console_returned = mem::take(&mut self.console_was_lent);
let kernel_got_loud = self let kernel_got_loud = self
.quiet_kernel .quiet_kernel
.as_mut() .as_mut()
@@ -144,7 +159,7 @@ impl ConsoleDesk for LiveDesk {
let look = console_look(self.own_vt); let look = console_look(self.own_vt);
let restyled = look != self.look; let restyled = look != self.look;
self.look = look; self.look = look;
if kernel_got_loud || terminal_was_taken || restyled { if console_returned || kernel_got_loud || terminal_was_taken || restyled {
Refresh::Repaint Refresh::Repaint
} else { } else {
Refresh::Steady Refresh::Steady
@@ -157,3 +172,40 @@ pub fn password_request_inputs(watch: RequestWatch) -> io::Result<impl Stream<It
.filter(|changed| ready(*changed)) .filter(|changed| ready(*changed))
.map(|_| ScreenInput::PasswordRequests)) .map(|_| ScreenInput::PasswordRequests))
} }
#[cfg(test)]
mod tests {
use std::{env, fs, process};
use super::*;
fn desk_watching(resume_marker: PathBuf) -> LiveDesk {
LiveDesk {
quiet_kernel: None,
foreground: None,
for_system: true,
own_vt: None,
look: console_look(None),
entry: None,
handover_deadline: None,
resume_marker,
console_was_lent: false,
}
}
#[test]
fn the_console_is_repainted_only_after_it_was_lent_for_resume() {
let marker = env::temp_dir().join(format!("bootvine-resume-marker-{}", process::id()));
let mut desk = desk_watching(marker.clone());
assert!(!desk.lends_console());
fs::write(&marker, "1").expect("create the marker");
assert!(desk.lends_console());
assert_eq!(desk.keep_console_up(), Refresh::Steady);
fs::remove_file(&marker).expect("remove the marker");
assert!(!desk.lends_console());
assert_eq!(desk.keep_console_up(), Refresh::Repaint);
assert_eq!(desk.keep_console_up(), Refresh::Steady);
}
}
@@ -0,0 +1,162 @@
use std::{
fmt,
fs::{self, File, OpenOptions},
io::{self, Write},
path::Path,
thread,
};
use crossterm::{
Command,
cursor::MoveTo,
queue,
style::{Attribute, Color as ConsoleColor, SetAttribute, SetForegroundColor},
};
use ratatui::{
backend::CrosstermBackend,
buffer::Buffer,
layout::{Constraint, Rect},
style::{Color, Style},
widgets::{Block, Borders, Widget},
};
use rustix::termios::tcgetwinsize;
use crate::console_session::{stream_sources::FRAME_INTERVAL, watch_screen::overwrite_every_cell};
pub const RESUME_CONSOLE_MARKER: &str = "/run/bootvine/resume-console-open";
const BOOTVINE_TERMINAL: &str = "/dev/tty12";
const KERNEL_PRINTK: &str = "/proc/sys/kernel/printk";
const KERNEL_TIMESTAMPS: &str = "/sys/module/printk/parameters/time";
const KERNEL_INFO_VISIBLE: &str = "7";
const TIMESTAMPS_HIDDEN: &str = "N";
const FRAMES_TO_SETTLE: u32 = 2;
const BAND_HEIGHT: u16 = 4;
const BAND_TITLE: &str = " Looking for a hibernated session ";
struct ConfineScrolling(Rect);
impl Command for ConfineScrolling {
fn write_ansi(&self, sequence: &mut impl fmt::Write) -> fmt::Result {
write!(sequence, "\x1b[{};{}r", self.0.top() + 1, self.0.bottom())
}
}
struct ReleaseScrolling;
impl Command for ReleaseScrolling {
fn write_ansi(&self, sequence: &mut impl fmt::Write) -> fmt::Result {
sequence.write_str("\x1b[r")
}
}
#[must_use]
pub fn resume_console_is_open(marker: &Path) -> bool {
marker.exists()
}
fn band_area(screen: Rect) -> Rect {
screen.centered_vertically(Constraint::Length(BAND_HEIGHT))
}
fn band_frame() -> Block<'static> {
Block::new()
.borders(Borders::TOP | Borders::BOTTOM)
.border_style(Style::new().fg(Color::Yellow))
.title(BAND_TITLE)
}
fn open_bootvine_terminal() -> io::Result<File> {
OpenOptions::new().write(true).open(BOOTVINE_TERMINAL)
}
fn draw_progress_band() -> io::Result<()> {
let terminal = open_bootvine_terminal()?;
let window = tcgetwinsize(&terminal)?;
let band = band_area(Rect::new(0, 0, window.ws_col, window.ws_row));
let progress_rows = band_frame().inner(band);
if progress_rows.is_empty() {
return Ok(());
}
let mut painted = Buffer::empty(band);
band_frame().render(band, &mut painted);
let mut backend = CrosstermBackend::new(terminal);
overwrite_every_cell(&mut backend, &painted)?;
queue!(
backend,
SetAttribute(Attribute::Bold),
SetForegroundColor(ConsoleColor::DarkYellow),
ConfineScrolling(progress_rows),
MoveTo(progress_rows.x, progress_rows.y),
)?;
Write::flush(&mut backend)
}
fn restore_bootvine_terminal() -> io::Result<()> {
let mut terminal = open_bootvine_terminal()?;
queue!(terminal, SetAttribute(Attribute::Reset), ReleaseScrolling)?;
terminal.flush()
}
pub fn open_resume_console() -> io::Result<()> {
let printk_levels = fs::read_to_string(KERNEL_PRINTK)?;
let previous_level = printk_levels.split_whitespace().next().unwrap_or_default();
let previous_timestamps = fs::read_to_string(KERNEL_TIMESTAMPS).unwrap_or_default();
let marker = Path::new(RESUME_CONSOLE_MARKER);
if let Some(directory) = marker.parent() {
fs::create_dir_all(directory)?;
}
fs::write(
marker,
format!("{previous_level}\n{}\n", previous_timestamps.trim()),
)?;
thread::sleep(FRAME_INTERVAL * FRAMES_TO_SETTLE);
let _ = fs::write(KERNEL_TIMESTAMPS, TIMESTAMPS_HIDDEN);
fs::write(KERNEL_PRINTK, KERNEL_INFO_VISIBLE)?;
draw_progress_band()
}
pub fn close_resume_console() -> io::Result<()> {
let marker = Path::new(RESUME_CONSOLE_MARKER);
let recorded = fs::read_to_string(marker)?;
let mut recorded_lines = recorded.lines();
let previous_level = recorded_lines.next().unwrap_or_default();
let previous_timestamps = recorded_lines.next().unwrap_or_default();
let terminal_restored = restore_bootvine_terminal();
if !previous_timestamps.is_empty() {
let _ = fs::write(KERNEL_TIMESTAMPS, previous_timestamps);
}
let level_restored = fs::write(KERNEL_PRINTK, previous_level);
fs::remove_file(marker)?;
terminal_restored.and(level_restored)
}
#[cfg(test)]
mod tests {
use super::*;
fn screen_with_rows(rows: u16) -> Rect {
Rect::new(0, 0, 80, rows)
}
#[test]
fn the_band_sits_in_the_middle_with_two_rows_for_the_kernel() {
let band = band_area(screen_with_rows(50));
assert_eq!(band, Rect::new(0, 23, 80, BAND_HEIGHT));
assert_eq!(band_frame().inner(band), Rect::new(0, 24, 80, 2));
}
#[test]
fn the_scroll_region_counts_rows_from_one() {
let mut sequence = String::new();
ConfineScrolling(Rect::new(0, 24, 80, 2))
.write_ansi(&mut sequence)
.expect("writing to a string");
assert_eq!(sequence, "\x1b[25;26r");
}
#[test]
fn a_screen_without_room_for_the_band_leaves_the_kernel_no_rows() {
let band = band_area(screen_with_rows(2));
assert!(band_frame().inner(band).is_empty());
}
}
+10 -13
View File
@@ -19,7 +19,7 @@ use crate::{
boot_feed::{RootRequest, bus_inputs}, boot_feed::{RootRequest, bus_inputs},
link_error::Error, link_error::Error,
switch_root::INITRD_RELEASE, switch_root::INITRD_RELEASE,
systemd_bus::{Scope, Session, StatusOutput}, systemd_bus::{Scope, Session, StatusRelease, restore_status_after_watch},
}, },
}; };
@@ -33,16 +33,6 @@ pub struct Settings {
const FULL_REPAINT_INTERVAL: Duration = Duration::from_secs(5); const FULL_REPAINT_INTERVAL: Duration = Duration::from_secs(5);
struct ConfiguredStatusOnExit;
impl Drop for ConfiguredStatusOnExit {
fn drop(&mut self) {
if let Ok(session) = Session::open(Scope::System) {
session.set_show_status(StatusOutput::Configured).ok();
}
}
}
fn boot_already_finished(settings: &Settings) -> bool { fn boot_already_finished(settings: &Settings) -> bool {
settings.scope == Scope::System settings.scope == Scope::System
&& !settings.shutdown && !settings.shutdown
@@ -73,8 +63,14 @@ pub fn run(settings: &Settings) -> Result<(), Error> {
} }
async fn watch_live_boot(settings: &Settings, phase: Phase) -> Result<(), Error> { async fn watch_live_boot(settings: &Settings, phase: Phase) -> Result<(), Error> {
match settings.scope {
Scope::System => restore_status_after_watch(watch_on_console(settings, phase)).await,
Scope::User => watch_on_console(settings, phase).await.map(drop),
}
}
async fn watch_on_console(settings: &Settings, phase: Phase) -> Result<StatusRelease, Error> {
let for_system = settings.scope == Scope::System; let for_system = settings.scope == Scope::System;
let _restores_status = for_system.then_some(ConfiguredStatusOnExit);
let requests = RequestWatch::open(); let requests = RequestWatch::open();
let prompt_check: fn() -> ScreenInput = if requests.is_some() { let prompt_check: fn() -> ScreenInput = if requests.is_some() {
|| ScreenInput::PromptCheck || ScreenInput::PromptCheck
@@ -117,6 +113,7 @@ async fn watch_live_boot(settings: &Settings, phase: Phase) -> Result<(), Error>
ratatui::restore(); ratatui::restore();
match ending { match ending {
WatchEnding::Failed(error) => Err(error), WatchEnding::Failed(error) => Err(error),
WatchEnding::BootCompleted | WatchEnding::ViewerLeft => Ok(()), WatchEnding::BootCompleted => Ok(StatusRelease::AfterBoot),
WatchEnding::ViewerLeft => Ok(StatusRelease::Immediately),
} }
} }
+11 -1
View File
@@ -64,6 +64,10 @@ pub trait ConsoleDesk {
} }
fn begin_handover(&mut self, _reached: &str, _deadline: Duration) {} fn begin_handover(&mut self, _reached: &str, _deadline: Duration) {}
fn lends_console(&mut self) -> bool {
false
}
} }
struct CachedProjection { struct CachedProjection {
@@ -183,6 +187,9 @@ impl<Desk: ConsoleDesk> WatchScreen<Desk> {
Error: From<B::Error>, Error: From<B::Error>,
{ {
batch.into_iter().try_for_each(|input| self.absorb(input))?; batch.into_iter().try_for_each(|input| self.absorb(input))?;
if self.desk.lends_console() {
return ControlFlow::Continue(());
}
match self.draw(terminal) { match self.draw(terminal) {
Ok(()) => ControlFlow::Continue(()), Ok(()) => ControlFlow::Continue(()),
Err(error) => ControlFlow::Break(WatchEnding::Failed(error)), Err(error) => ControlFlow::Break(WatchEnding::Failed(error)),
@@ -253,7 +260,10 @@ where
.await .await
} }
fn overwrite_every_cell<B: Backend>(backend: &mut B, frame: &Buffer) -> Result<(), B::Error> { pub(super) fn overwrite_every_cell<B: Backend>(
backend: &mut B,
frame: &Buffer,
) -> Result<(), B::Error> {
backend.draw( backend.draw(
frame frame
.content .content
+13 -1
View File
@@ -3,7 +3,10 @@ use std::{
}; };
use bootvine::{ use bootvine::{
console_session::watch_loop::{Settings, run}, console_session::{
resume_console::{close_resume_console, open_resume_console},
watch_loop::{Settings, run},
},
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,
}, },
@@ -69,6 +72,13 @@ enum Command {
Install(InstallOptions), Install(InstallOptions),
#[command(about = "Disable and remove what install put in place")] #[command(about = "Disable and remove what install put in place")]
Uninstall(UninstallOptions), Uninstall(UninstallOptions),
#[command(
about = "Let the kernel's image loading progress reach the console; started before \
systemd-hibernate-resume.service"
)]
OpenResumeConsole,
#[command(about = "Undo open-resume-console when no hibernated image was restored")]
CloseResumeConsole,
} }
#[derive(Args)] #[derive(Args)]
@@ -102,6 +112,8 @@ fn main() -> ExitCode {
), ),
Some(Command::Install(options)) => report_outcome(install_files(&options)), Some(Command::Install(options)) => report_outcome(install_files(&options)),
Some(Command::Uninstall(options)) => report_outcome(uninstall_files(&options)), Some(Command::Uninstall(options)) => report_outcome(uninstall_files(&options)),
Some(Command::OpenResumeConsole) => report_outcome(open_resume_console()),
Some(Command::CloseResumeConsole) => report_outcome(close_resume_console()),
None => watch_boot(cli.watch), None => watch_boot(cli.watch),
} }
} }
+19 -8
View File
@@ -34,6 +34,13 @@ const PACKAGED_UNITS: [PackagedUnit; 2] = [
contents: include_str!("../../system-files/systemd/bootvine-shutdown.service"), contents: include_str!("../../system-files/systemd/bootvine-shutdown.service"),
}, },
]; ];
const RESUME_DROP_IN_DIR: &str = "systemd-hibernate-resume.service.d";
const RESUME_DROP_IN: PackagedUnit = PackagedUnit {
name: "systemd-hibernate-resume.service.d/bootvine.conf",
contents: include_str!(
"../../system-files/systemd/systemd-hibernate-resume.service.d/bootvine.conf"
),
};
const DRACUT_MODULE_SETUP: &str = const DRACUT_MODULE_SETUP: &str =
include_str!("../../system-files/dracut/90bootvine/module-setup.sh"); include_str!("../../system-files/dracut/90bootvine/module-setup.sh");
const MKINITCPIO_INSTALL_HOOK: &str = const MKINITCPIO_INSTALL_HOOK: &str =
@@ -177,14 +184,17 @@ fn binary_file(target: &InstallTarget) -> Result<Option<InstalledFile>, InstallE
fn unit_files(target: &InstallTarget) -> impl Iterator<Item = InstalledFile> { fn unit_files(target: &InstallTarget) -> impl Iterator<Item = InstalledFile> {
let binary_path = target.binary_path(); let binary_path = target.binary_path();
PACKAGED_UNITS.iter().map(move |unit| InstalledFile { PACKAGED_UNITS
destination: target.unit_path(unit.name), .iter()
contents: unit .chain(once(&RESUME_DROP_IN))
.contents .map(move |unit| InstalledFile {
.replace(PACKAGED_BINARY_PATH, &binary_path.to_string_lossy()) destination: target.unit_path(unit.name),
.into_bytes(), contents: unit
mode: 0o644, .contents
}) .replace(PACKAGED_BINARY_PATH, &binary_path.to_string_lossy())
.into_bytes(),
mode: 0o644,
})
} }
fn initrd_hook_files(initrd: InitrdGenerator) -> Vec<InstalledFile> { fn initrd_hook_files(initrd: InitrdGenerator) -> Vec<InstalledFile> {
@@ -318,6 +328,7 @@ pub fn uninstall_files(options: &UninstallOptions) -> Result<(), InstallError> {
.every_installed_path() .every_installed_path()
.into_iter() .into_iter()
.try_for_each(|path| remove_if_present(target.staged(&path)))?; .try_for_each(|path| remove_if_present(target.staged(&path)))?;
let _ = fs::remove_dir(target.staged(&target.unit_path(RESUME_DROP_IN_DIR)));
let dracut_module_dir = target.staged(Path::new(DRACUT_MODULE_DIR)); let dracut_module_dir = target.staged(Path::new(DRACUT_MODULE_DIR));
match fs::remove_dir(&dracut_module_dir) { match fs::remove_dir(&dracut_module_dir) {
Err(error) if error.kind() == ErrorKind::DirectoryNotEmpty => { Err(error) if error.kind() == ErrorKind::DirectoryNotEmpty => {
+29 -5
View File
@@ -25,7 +25,6 @@ use crate::{
switch_root::Sysroot, switch_root::Sysroot,
systemd_bus::{ systemd_bus::{
BusConnection, FetchedUnit, JobListing, Scope, Session, Signal, SignalBatch, BusConnection, FetchedUnit, JobListing, Scope, Session, Signal, SignalBatch,
StatusOutput,
}, },
}, },
}; };
@@ -113,6 +112,14 @@ fn queued_units(signals: &[Signal]) -> impl Iterator<Item = &str> {
}) })
} }
fn connected_inputs(changes: Vec<BootChange>, switching_root: bool) -> Vec<ScreenInput> {
(!changes.is_empty())
.then_some(ScreenInput::Boot(changes))
.into_iter()
.chain(switching_root.then_some(ScreenInput::FullRepaint))
.collect()
}
struct BootTracker { struct BootTracker {
scope: Scope, scope: Scope,
target: RootRequest, target: RootRequest,
@@ -160,9 +167,9 @@ impl BusFeed {
} }
Link::Connected(connection) => { Link::Connected(connection) => {
let received = self.tracker.receive(connection).await; let received = self.tracker.receive(connection).await;
let switching_root = matches!(self.tracker.root_switch, RootSwitch::Queued(_));
Some(match received { Some(match received {
Ok(changes) if changes.is_empty() => Vec::new(), Ok(changes) => connected_inputs(changes, switching_root),
Ok(changes) => vec![ScreenInput::Boot(changes)],
Err(_) => self.lose_connection(), Err(_) => self.lose_connection(),
}) })
} }
@@ -184,7 +191,7 @@ impl BusFeed {
Ok(changes) => vec![ScreenInput::Boot(changes), ScreenInput::FullRepaint], Ok(changes) => vec![ScreenInput::Boot(changes), ScreenInput::FullRepaint],
Err(_) if Instant::now() < deadline => { Err(_) if Instant::now() < deadline => {
sleep(BACKGROUND_CHECK_INTERVAL).await; sleep(BACKGROUND_CHECK_INTERVAL).await;
Vec::new() vec![ScreenInput::FullRepaint]
} }
Err(_) => { Err(_) => {
self.link = Link::Finished; self.link = Link::Finished;
@@ -319,7 +326,7 @@ impl BootTracker {
) -> Result<Vec<BootChange>, Error> { ) -> Result<Vec<BootChange>, Error> {
connection.subscribe().await?; connection.subscribe().await?;
if self.scope == Scope::System { if self.scope == Scope::System {
connection.set_show_status(StatusOutput::Silent).await.ok(); connection.silence_status_output().await.ok();
} }
let shutting_down = self.phase == Phase::Shutdown; let shutting_down = self.phase == Phase::Shutdown;
let jobs: Vec<JobListing> = connection let jobs: Vec<JobListing> = connection
@@ -546,6 +553,23 @@ mod tests {
} }
} }
#[test]
fn the_screen_is_repainted_only_while_the_root_switches() {
assert!(connected_inputs(Vec::new(), false).is_empty());
assert!(matches!(
connected_inputs(Vec::new(), true).as_slice(),
[ScreenInput::FullRepaint]
));
assert!(matches!(
connected_inputs(vec![BootChange::ForgetJobs], true).as_slice(),
[ScreenInput::Boot(_), ScreenInput::FullRepaint]
));
assert!(matches!(
connected_inputs(vec![BootChange::ForgetJobs], false).as_slice(),
[ScreenInput::Boot(_)]
));
}
fn in_state(state: ActiveState) -> Activity { fn in_state(state: ActiveState) -> Activity {
Activity { Activity {
state: Some(state), state: Some(state),
+78 -19
View File
@@ -1,5 +1,5 @@
use std::{ use std::{
future::ready, future::{Future, pending, ready},
io, iter, mem, io, iter, mem,
os::fd::{AsFd, AsRawFd, BorrowedFd, RawFd}, os::fd::{AsFd, AsRawFd, BorrowedFd, RawFd},
pin::pin, pin::pin,
@@ -11,9 +11,13 @@ use dbus::{
arg::{AppendAll, PropMap, RefArg, Variant}, arg::{AppendAll, PropMap, RefArg, Variant},
channel::{BusType, Channel}, channel::{BusType, Channel},
}; };
use futures::{TryStreamExt, stream}; use futures::{Stream, StreamExt, TryStreamExt, future::select, stream};
use rustix::event::{PollFd, PollFlags, Timespec, poll}; use rustix::event::{PollFd, PollFlags, Timespec, poll};
use tokio::{io::unix::AsyncFd, time::timeout}; use tokio::{
io::unix::AsyncFd,
signal::unix::{Signal as OsSignal, SignalKind, signal},
time::timeout,
};
use crate::{ use crate::{
boot_model::{Activity, JobKind, JobResult, UnitFacts, UnitKind, UnitTimeouts}, boot_model::{Activity, JobKind, JobResult, UnitFacts, UnitKind, UnitTimeouts},
@@ -40,6 +44,8 @@ const PRIVATE_SOCKET: &str = "unix:path=/run/systemd/private";
const SIGNAL_RULE: &str = "type='signal',path_namespace='/org/freedesktop/systemd1'"; const SIGNAL_RULE: &str = "type='signal',path_namespace='/org/freedesktop/systemd1'";
const CALL_TIMEOUT: Duration = Duration::from_secs(1); const CALL_TIMEOUT: Duration = Duration::from_secs(1);
const UNLIMITED: Duration = Duration::from_micros(u64::MAX); const UNLIMITED: Duration = Duration::from_micros(u64::MAX);
const STATUS_SILENT_MODE: &str = "no";
const STATUS_RESET_MODE: &str = "";
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Scope { pub enum Scope {
@@ -48,18 +54,9 @@ pub enum Scope {
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StatusOutput { pub enum StatusRelease {
Silent, AfterBoot,
Configured, Immediately,
}
impl StatusOutput {
fn bus_mode(self) -> &'static str {
match self {
Self::Silent => "no",
Self::Configured => "",
}
}
} }
pub enum SignalBatch { pub enum SignalBatch {
@@ -157,6 +154,41 @@ fn read_boot_in_progress(reply: &Message) -> Result<bool, Error> {
Ok(finished.0 == 0) Ok(finished.0 == 0)
} }
async fn boot_finish_or_lost_connection() -> Result<(), Error> {
let mut connection = BusConnection::register(Session::open(Scope::System)?)?;
connection.subscribe().await?;
if connection.boot_in_progress().await? {
connection
.into_signals()
.any(|signal| ready(matches!(signal, Signal::BootFinished)))
.await;
}
Ok(())
}
async fn termination_request(listener: io::Result<OsSignal>) {
match listener {
Ok(mut listener) => {
listener.recv().await;
}
Err(_) => pending().await,
}
}
pub async fn restore_status_after_watch(
watch: impl Future<Output = Result<StatusRelease, Error>>,
) -> Result<(), Error> {
let terminated = termination_request(signal(SignalKind::terminate()));
let watched = watch.await;
if !matches!(watched, Ok(StatusRelease::Immediately)) {
select(pin!(terminated), pin!(boot_finish_or_lost_connection())).await;
}
if let Ok(session) = Session::open(Scope::System) {
session.restore_configured_status().ok();
}
watched.map(drop)
}
impl Session { impl Session {
pub fn open(scope: Scope) -> Result<Self, Error> { pub fn open(scope: Scope) -> Result<Self, Error> {
if scope == Scope::System if scope == Scope::System
@@ -193,8 +225,8 @@ impl Session {
Ok(self.channel.send_with_reply_and_block(call, CALL_TIMEOUT)?) Ok(self.channel.send_with_reply_and_block(call, CALL_TIMEOUT)?)
} }
pub fn set_show_status(&self, output: StatusOutput) -> Result<(), Error> { fn restore_configured_status(&self) -> Result<(), Error> {
self.blocking_call(manager_call("SetShowStatus", (output.bus_mode(),))?)?; self.blocking_call(manager_call("SetShowStatus", (STATUS_RESET_MODE,))?)?;
Ok(()) Ok(())
} }
@@ -297,8 +329,8 @@ impl BusConnection {
Ok(()) Ok(())
} }
pub async fn set_show_status(&mut self, output: StatusOutput) -> Result<(), Error> { pub async fn silence_status_output(&mut self) -> Result<(), Error> {
self.call(manager_call("SetShowStatus", (output.bus_mode(),))?) self.call(manager_call("SetShowStatus", (STATUS_SILENT_MODE,))?)
.await?; .await?;
Ok(()) Ok(())
} }
@@ -372,6 +404,10 @@ impl BusConnection {
if self.early_signals.is_empty() { if self.early_signals.is_empty() {
readable_or_timeout(&self.session, patience).await; readable_or_timeout(&self.session, patience).await;
} }
self.take_signals()
}
fn take_signals(&mut self) -> SignalBatch {
let still_connected = self.drain_replies().is_ok(); let still_connected = self.drain_replies().is_ok();
let signals = mem::take(&mut self.early_signals); let signals = mem::take(&mut self.early_signals);
if still_connected { if still_connected {
@@ -380,6 +416,29 @@ impl BusConnection {
SignalBatch::Closed(signals) SignalBatch::Closed(signals)
} }
} }
async fn next_signals(&mut self) -> SignalBatch {
if self.early_signals.is_empty() {
let Ok(mut readiness) = self.session.readable().await else {
return SignalBatch::Closed(Vec::new());
};
readiness.clear_ready();
}
self.take_signals()
}
fn into_signals(self) -> impl Stream<Item = Signal> {
unfold_carrying(self, |mut connection| async move {
match connection.next_signals().await {
SignalBatch::Open(signals) => Some(CarriedItem {
item: signals,
state: connection,
}),
SignalBatch::Closed(_) => None,
}
})
.flat_map(stream::iter)
}
} }
fn text_property(properties: &PropMap, property: &str) -> Option<String> { fn text_property(properties: &PropMap, property: &str) -> Option<String> {
@@ -12,6 +12,7 @@ depends() {
install() { install() {
inst_binary bootvine inst_binary bootvine
inst_simple "$systemdsystemunitdir/bootvine.service" inst_simple "$systemdsystemunitdir/bootvine.service"
inst_simple "$systemdsystemunitdir/systemd-hibernate-resume.service.d/bootvine.conf"
if [[ -f /etc/bootvine.toml ]]; then if [[ -f /etc/bootvine.toml ]]; then
inst_simple /etc/bootvine.toml inst_simple /etc/bootvine.toml
fi fi
@@ -3,6 +3,7 @@
build() { build() {
add_binary bootvine add_binary bootvine
add_systemd_unit bootvine.service add_systemd_unit bootvine.service
add_file /usr/lib/systemd/system/systemd-hibernate-resume.service.d/bootvine.conf
if [[ -f /etc/bootvine.toml ]]; then if [[ -f /etc/bootvine.toml ]]; then
add_file /etc/bootvine.toml add_file /etc/bootvine.toml
fi fi
@@ -0,0 +1,6 @@
[Unit]
After=systemd-vconsole-setup.service
[Service]
ExecStartPre=-/usr/bin/bootvine open-resume-console
ExecStopPost=-/usr/bin/bootvine close-resume-console
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env nu
const CODEBERG_USER = "wvhulle-bot"
const TEA_LOGIN_NAME = "codeberg"
const UPDATE_BRANCH = "bot/dependency-updates"
const UPDATE_COMMIT_MESSAGE = "chore(deps): update lock files"
const PULL_REQUEST_DESCRIPTION = "Opened by the weekly dependency update job. The checks on this pull request are the trial build. Commits pushed to this branch by hand stop further automatic updates until it is merged."
def open-pull-request-heads []: nothing -> list<string> {
^tea pulls list --login $TEA_LOGIN_NAME --repo $env.CI_REPO --state open --fields head --output simple
| lines
| str trim
}
def remote-update-branch-commits []: nothing -> list<string> {
^git ls-remote --heads origin $"refs/heads/($UPDATE_BRANCH)"
| parse "{commit_id}\t{ref_name}"
| get commit_id
}
def update-branch-has-hand-written-commits []: nothing -> bool {
^git fetch --quiet origin $"+refs/heads/($UPDATE_BRANCH):refs/remotes/origin/($UPDATE_BRANCH)"
^git log --format=%an $"origin/main..origin/($UPDATE_BRANCH)"
| lines
| any {|commit_author| $commit_author != $env.GIT_AUTHOR_NAME }
}
def "main open-dependency-update-pr" [
--cargo-lock
--flake-lock
]: nothing -> nothing {
^git remote set-url origin $"https://($CODEBERG_USER):($env.CODEBERG_TOKEN)@codeberg.org/($env.CI_REPO).git"
^tea login add --name $TEA_LOGIN_NAME --url $env.CI_FORGE_URL --token $env.CODEBERG_TOKEN
^git fetch --quiet origin +refs/heads/main:refs/remotes/origin/main
let remote_commits = remote-update-branch-commits
let remote_commit = $remote_commits | str join
let pull_request_is_open = $UPDATE_BRANCH in (open-pull-request-heads)
if ($remote_commits | is-not-empty) and $pull_request_is_open and (update-branch-has-hand-written-commits) {
print $"Leaving ($UPDATE_BRANCH) alone because it contains hand-written commits"
return
}
^git checkout -B $UPDATE_BRANCH origin/main
if $cargo_lock {
^cargo update
}
if $flake_lock {
^nix flake update
}
if (^git diff --name-only | is-empty) {
print "Dependencies are up to date"
return
}
^git commit --all --message $UPDATE_COMMIT_MESSAGE
^git push $"--force-with-lease=($UPDATE_BRANCH):($remote_commit)" origin $UPDATE_BRANCH
if $pull_request_is_open {
print $"Updated the open pull request from ($UPDATE_BRANCH)"
} else {
^tea pulls create --login $TEA_LOGIN_NAME --repo $env.CI_REPO --head $UPDATE_BRANCH --base main --title $UPDATE_COMMIT_MESSAGE --description $PULL_REQUEST_DESCRIPTION
}
}
def main []: nothing -> nothing {
print "Run a subcommand, for example: open-dependency-update-pr --cargo-lock --flake-lock"
}
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env nu
const EXPORT_DIRECTORY_NAME = ".nix-built-paths"
const PATH_LIST_FILE_NAME = "paths.txt"
const CACHIX_CACHE_NAME = "wvhulle"
const CACHIX_CACHE_URL = "https://wvhulle.cachix.org"
def export-directory []: nothing -> path {
$env.CI_WORKSPACE | path join $EXPORT_DIRECTORY_NAME
}
def store-paths-from-lines []: string -> list<string> {
lines | compact --empty
}
def exported-store-paths []: nothing -> list<string> {
let path_list_file = export-directory | path join $PATH_LIST_FILE_NAME
if ($path_list_file | path exists) {
open --raw $path_list_file | store-paths-from-lines
} else {
[]
}
}
def nix-config-with-hook [existing_config: string, hook_program: string]: nothing -> string {
$"($existing_config)\npost-build-hook = ($hook_program)"
}
def "main export-built-paths-hook" []: nothing -> nothing {
let built_paths = $env.OUT_PATHS | split row " " | compact --empty
let directory = export-directory
mkdir $directory
^nix copy --quiet --to $"file://($directory)?compression=zstd" ...$built_paths
$built_paths | each {|built_path| $"($built_path)\n" } | str join | save --append ($directory | path join $PATH_LIST_FILE_NAME)
}
def --wrapped "main build-and-export-paths" [
...build_arguments: string
]: nothing -> nothing {
let hook_config = nix-config-with-hook ($env.NIX_CONFIG? | default "") $env.EXPORT_HOOK_PROGRAM
with-env {NIX_CONFIG: $hook_config} {
^nix build --quiet --print-build-logs ...$build_arguments
}
}
def "main build-unless-cached" [
installable: string
]: nothing -> nothing {
let built_output = ^nix eval --quiet --raw $"($installable).outPath"
let cache_lookup = do { ^nix path-info --quiet --store $CACHIX_CACHE_URL $built_output } | complete
if $cache_lookup.exit_code == 0 {
print $"($built_output) is already in Cachix"
} else {
main build-and-export-paths $installable
}
}
def "main import-exported-paths" []: nothing -> nothing {
let exported_paths = exported-store-paths
if ($exported_paths | is-empty) {
print "No exported paths to import"
} else {
^nix copy --quiet --no-check-sigs --from $"file://(export-directory)" ...$exported_paths
}
}
def "main upload-exported-paths" []: nothing -> nothing {
let exported_paths = exported-store-paths
if ($exported_paths | is-empty) {
print "No newly built paths to upload"
} else {
main import-exported-paths
^cachix push $CACHIX_CACHE_NAME ...$exported_paths
}
}
def "main copy-build-output" [
build_output: path
destination: path
]: nothing -> nothing {
if ($build_output | path expand | path type) == dir {
mkdir $destination
for output_entry in (ls $build_output | get name) {
cp --recursive --preserve [] $output_entry $destination
}
} else {
cp --preserve [] $build_output $destination
}
}
def main []: nothing -> nothing {
print "Run a subcommand, for example: build-and-export-paths"
}
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env nu
const CODEBERG_USER = "wvhulle-bot"
const TEA_LOGIN_NAME = "codeberg"
const RELEASE_ARCHIVE_PATTERN = "*.tar.gz"
const CHECKSUM_FILE_NAME = "sha256sum.txt"
def checksum-line [archive_digest: string, archive_name: string]: nothing -> string {
$"($archive_digest) ($archive_name)\n"
}
def run-release-plz [subcommand: string]: nothing -> nothing {
^release-plz $subcommand --forge gitea --git-token $env.CODEBERG_TOKEN
}
def "main authenticate-git-origin" []: nothing -> nothing {
^git remote set-url origin $"https://($CODEBERG_USER):($env.CODEBERG_TOKEN)@codeberg.org/($env.CI_REPO).git"
}
def "main publish-unreleased-crate-version" []: nothing -> nothing {
main authenticate-git-origin
^git checkout -B main $env.CI_COMMIT_SHA
^git fetch origin main:refs/remotes/origin/main
^git branch --set-upstream-to=origin/main main
run-release-plz release
}
def "main open-or-update-release-pr" []: nothing -> nothing {
run-release-plz release-pr
}
def "main collect-release-archives" [
build_result: path
dist_directory: path
]: nothing -> nothing {
mkdir $dist_directory
for archive_path in (glob ($build_result | path join $RELEASE_ARCHIVE_PATTERN)) {
cp $archive_path $dist_directory
}
}
def "main upload-release-assets" [
dist_directory: path
]: nothing -> nothing {
let archive_paths = glob ($dist_directory | path join $RELEASE_ARCHIVE_PATTERN) | sort
let checksum_file = $dist_directory | path join $CHECKSUM_FILE_NAME
$archive_paths
| each {|archive_path|
checksum-line (open --raw $archive_path | hash sha256) ($archive_path | path basename)
}
| str join
| save --force $checksum_file
^tea login add --name $TEA_LOGIN_NAME --url $env.CI_FORGE_URL --token $env.CODEBERG_TOKEN
^tea releases assets create --login $TEA_LOGIN_NAME --repo $env.CI_REPO $env.CI_COMMIT_TAG ...$archive_paths $checksum_file
}
def "main check-commit-messages" [
--fetch-target-branch
...revision_ranges: string
]: nothing -> nothing {
if $fetch_target_branch {
^git fetch --quiet origin $env.CI_COMMIT_TARGET_BRANCH
}
^convco check ...$revision_ranges
}
def main []: nothing -> nothing {
print "Run a subcommand, for example: check-commit-messages"
}
+32 -3
View File
@@ -270,12 +270,41 @@ While it runs, bootvine:
`/proc/sys/kernel/printk` to 1, so only emergency messages reach the `/proc/sys/kernel/printk` to 1, so only emergency messages reach the
screen, and sets it again if something raises it; screen, and sets it again if something raises it;
- **silences systemd's status output** with the manager's `SetShowStatus` - **silences systemd's status output** with the manager's `SetShowStatus`
call. call;
- **repaints every cell every 100 ms during a root switch**, because PID 1
writes to the console and resets it while it re-executes, and drawing only
the cells that changed would leave that on screen.
It restores the log level and the status output when it hands the console It restores the log level when it hands the console back. It keeps running
back. Kernel messages from before it starts are already on screen; see without touching the console until the boot finishes and only then restores the
status output, so jobs still running cannot write over a display manager that
started before them. This holds for a handover and for an error. Pressing a
[quit key](guide.md#leaving-the-tree) or stopping the service restores the
output at once, so a stuck boot stays visible; status lines can then reach a
display manager that starts before the boot finishes. Kernel messages from before it starts are already on screen; see
[early kernel messages](configuration.md#early-kernel-messages). [early kernel messages](configuration.md#early-kernel-messages).
### Resuming from hibernation
The kernel freezes all processes before it loads a hibernated image, so
bootvine cannot draw during the load. A drop-in on
`systemd-hibernate-resume.service` runs `bootvine open-resume-console` first,
which:
- creates `/run/bootvine/resume-console-open`, so the running bootvine stops
drawing, stops resetting the log level and stops taking `tty12` back;
- raises the console log level to 7, so the kernel's `pr_info` progress lines
reach the screen, and hides their timestamps;
- draws a band across the middle of `tty12`, limits scrolling to the two rows
inside it, and sets the colour and cursor there. The kernel console writes at
the cursor in the terminal's current colour, always from column 0, so it
stays inside the band without knowing about it.
If an image is restored, none of this needs undoing: the boot kernel's memory
is replaced, and the restored system keeps its own log level and terminals. If
not, `bootvine close-resume-console` runs as `ExecStopPost`, restoring what
the marker recorded, the colour and the scrolling, and bootvine repaints.
### Passphrase prompts ### Passphrase prompts
bootvine acts as a systemd bootvine acts as a systemd
+25 -11
View File
@@ -9,7 +9,7 @@
| `xtask/` | repository tasks run with `cargo xtask` | | `xtask/` | repository tasks run with `cargo xtask` |
| `vm-tests/` | the sample NixOS machines, one folder each with its VM check | | `vm-tests/` | the sample NixOS machines, one folder each with its VM check |
| `nix/` | the crane builds and the NixOS module | | `nix/` | the crane builds and the NixOS module |
| `recordings/` | the scripted demo GIFs and the sample machine WebP recordings the README and the [guide](guide.md) show | | `recordings/` | ignored output of `record-screencasts`: the scripted demo GIFs and the sample machine WebP recordings, published on the `recordings` branch for the README and the [guide](guide.md) |
`cargo build` and `cargo test` act on every crate. `cargo run` needs the binary: `cargo build` and `cargo test` act on every crate. `cargo run` needs the binary:
`--bin bootvine`, `--bin scripted-boot` and so on. `--bin bootvine`, `--bin scripted-boot` and so on.
@@ -34,25 +34,26 @@ Commit messages follow [Conventional Commits](https://www.conventionalcommits.or
jj does not run git hooks, so check the commits you are about to push with: jj does not run git hooks, so check the commits you are about to push with:
```sh ```sh
nix run .#check-conventional-commits -- origin/main..HEAD nix run .#check-commit-messages -- 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` ([prek](https://github.com/j178/prek), from the dev hooks with `prek install` ([prek](https://github.com/j178/prek), from the dev
shell) or `pre-commit install` ([pre-commit](https://pre-commit.com)). shell) or `pre-commit install` ([pre-commit](https://pre-commit.com)). CI runs
the formatting hook with `nix run .#run-pre-commit-hooks`.
## Continuous integration ## Continuous integration
`.woodpecker/rust-and-flake-checks.yaml` runs on Codeberg's `.woodpecker/checks.yaml` runs on Codeberg's
[Woodpecker CI](https://woodpecker-ci.org) for every push and 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 the pre-commit hooks, an evaluation of every flake output, and the commit-message check on
pull requests. Builds on `main` are pushed to the `wvhulle` [Cachix](https://www.cachix.org) cache, which pull requests. The workspace dependencies are built or fetched in a step of their own. 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. CI tasks are Nushell scripts in `ci/`, exposed as flake apps in `nix/ci-tasks.nix`. 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.
## Releases ## Releases
`.woodpecker/release-pr-and-publish.yaml` runs `.woodpecker/publish-release-and-update-pr.yaml` runs
[release-plz](https://release-plz.dev) after the checks pass on `main`. It [release-plz](https://release-plz.dev) after the checks pass on `main`. It
keeps a pull request labelled `release` open on Codeberg that bumps the version keeps a pull request labelled `release` open on Codeberg that bumps the version
in `Cargo.toml` and adds the new commits to `CHANGELOG.md`. Only `feat`, `fix` in `Cargo.toml` and adds the new commits to `CHANGELOG.md`. Only `feat`, `fix`
@@ -61,11 +62,20 @@ minor version while bootvine is below 1.0. Merging that pull request publishes
the crate to crates.io, tags the merge `v<version>` and creates a Codeberg the crate to crates.io, tags the merge `v<version>` and creates a Codeberg
release with the changelog. Settings are in `release-plz.toml`. release with the changelog. Settings are in `release-plz.toml`.
The pipeline needs two Woodpecker secrets: `codeberg_token`, a Codeberg access The pipeline needs two Woodpecker secrets: `bot_token`, an access token of the
token with repository write access, and `cargo_registry_token`, a crates.io `wvhulle-bot` Codeberg account, which has write access to the repository, and
token that may publish new crates and updates. Preview the next release `cargo_registry_token`, a crates.io token that may publish new crates and updates. Preview the next release
locally from the dev shell with `release-plz update`. locally from the dev shell with `release-plz update`.
## Dependency updates
The `weekly-dependency-update` cron runs `.woodpecker/dependency-update-pr.yaml`,
which updates `Cargo.lock` and `flake.lock` and opens or updates one pull request
from the `bot/dependency-updates` branch as `wvhulle-bot`. The checks on that pull
request are the trial build. Commits pushed to the branch by hand stop further
automatic updates until it is merged. Updates that need changes to `Cargo.toml`
stay manual.
## Testing ## Testing
| What | Command | | What | Command |
@@ -109,6 +119,10 @@ exports libraries that clash with [QEMU](https://www.qemu.org) or Chromium.
- `nix run .#record-screencasts` re-records the animations from the scripted - `nix run .#record-screencasts` re-records the animations from the scripted
demos and turns the frames each VM check captured into demos and turns the frames each VM check captured into
`recordings/<machine>.webp`, for the README and the [guide](guide.md). `recordings/<machine>.webp`, for the README and the [guide](guide.md).
- `nix run .#publish-recordings` force-pushes `recordings/` as the single,
parentless commit of the `recordings` branch, which the README and the guide
link to. Keeping the recordings off `main` keeps them out of every clone and
flake fetch.
- `cargo xtask sync-default-config` rewrites the defaults block in - `cargo xtask sync-default-config` rewrites the defaults block in
[configuration](configuration.md#defaults) from `bootvine defaults`. [configuration](configuration.md#defaults) from `bootvine defaults`.
- `cargo run --bin bootvine -- install --destdir <dir> --initrd dracut` stages an install - `cargo run --bin bootvine -- install --destdir <dir> --initrd dracut` stages an install
+55 -14
View File
@@ -7,7 +7,7 @@ by their [VM checks](development.md#testing).
## Reading the screen ## Reading the screen
<img src="../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/recordings/boot.gif" width="691" alt="A boot through the initrd into stage 2, with one failed unit">
From top to bottom: From top to bottom:
@@ -47,10 +47,10 @@ From top to bottom:
## Booting through the initrd ## Booting through the initrd
<img src="../recordings/slow-services.webp" width="640" alt="A NixOS machine booting through the initrd into stage 2, handing over to a greetd login, then powering off"> <img src="https://codeberg.org/wvhulle/bootvine/raw/branch/recordings/slow-services.webp" width="640" alt="A NixOS machine booting through the initrd into stage 2, handing over to a tuigreet login, then powering off">
The `slow-services` machine boots with a held hardware probe in the initrd, The `slow-services` machine boots with a held hardware probe in the initrd,
slow units in stage 2 and one failing unit, hands over to its greetd login slow units in stage 2 and one failing unit, hands over to its tuigreet login
and powers off. With a systemd initrd, bootvine starts about a second after and powers off. With a systemd initrd, bootvine starts about a second after
the kernel: the kernel:
@@ -58,7 +58,8 @@ the kernel:
under `initrd.target`. under `initrd.target`.
- **The switch to the real root**: the initrd moves into the stages at the - **The switch to the real root**: the initrd moves into the stages at the
top, with its time and unit count, and the tree starts again under the top, with its time and unit count, and the tree starts again under the
default target. The timeline keeps the initrd's runs, left of the `│`. default target. Until the new manager answers, the stage line says it is
waiting for it. The timeline keeps the initrd's runs, left of the `│`.
- **Stage 2** up to `graphical.target`. - **Stage 2** up to `graphical.target`.
- **The handover**: bootvine hands the console back once the default target is - **The handover**: bootvine hands the console back once the default target is
reached, or earlier, once the display manager has switched to its own reached, or earlier, once the display manager has switched to its own
@@ -69,7 +70,7 @@ How bootvine gets in that early and survives the switch is in
### Without a display manager ### Without a display manager
<img src="../recordings/text-console.webp" width="640" alt="The same boot on a machine without a display manager, ending at a text login"> <img src="https://codeberg.org/wvhulle/bootvine/raw/branch/recordings/text-console.webp" width="640" alt="The same boot on a machine without a display manager, ending at a text login">
The `text-console` machine boots the same units without greetd. With no The `text-console` machine boots the same units without greetd. With no
display manager to wait for, bootvine hands the console back as soon as the display manager to wait for, bootvine hands the console back as soon as the
@@ -77,15 +78,45 @@ default target is reached, and the text login on `tty1` comes forward.
### Without a systemd initrd ### Without a systemd initrd
<img src="../recordings/scripted-initrd.webp" width="640" alt="The same boot with NixOS's scripted initrd: the kernel and initrd lines scroll past before bootvine starts in stage 2"> An initrd without systemd, such as one built by initramfs-tools, has no units
for bootvine to follow. The initrd's lines scroll past as usual, and bootvine
The `scripted-initrd` machine uses NixOS's older scripted initrd, which has no starts in
systemd. The initrd's lines scroll past as usual, and bootvine starts in
stage 2, from `sysinit.target` on. stage 2, from `sysinit.target` on.
## Resuming from hibernation
<img src="https://codeberg.org/wvhulle/bootvine/raw/branch/recordings/hibernate-resume.webp" width="640" alt="The tree held still during a resume, with the kernel's image loading progress in a band across the middle of the screen">
Resuming from hibernation looks different from a boot, because the kernel
freezes every process before it loads the image, bootvine included. The tree
stops moving, and a band across the middle of the screen shows the kernel's own
progress:
```
─── Looking for a hibernated session ─────────────────────────────
PM: Image loading progress: 60%
──────────────────────────────────────────────────────────────────
```
The text comes straight from the kernel, which is why it is a line of text and
not a bar. The screen stays like this until the restored system takes over.
Bootvine does not draw again, because the restore replaces it along with the
rest of the boot kernel's memory.
The last lines show how the time was spent. `Read ... in N seconds` is the
image load. `Suspending console(s)` means the load has finished and the kernel
is about to jump into the restored system. If the screen stays on that line for
a long time, the wait is the restored kernel bringing devices back up, not the
disk.
With no image to restore, `systemd-hibernate-resume` finishes at once and the
band disappears. Some kernel console setups
switch to a blank terminal for the load; the same lines then appear there.
## Shutdown ## Shutdown
<img src="../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/recordings/shutdown.gif" width="691" alt="A poweroff: units stopping under the targets waiting on them">
On a poweroff, reboot or halt the tree turns around: On a poweroff, reboot or halt the tree turns around:
@@ -97,7 +128,7 @@ On a poweroff, reboot or halt the tree turns around:
## Passphrase prompts ## Passphrase prompts
<img src="../recordings/encrypted-volume.webp" width="640" alt="A LUKS passphrase prompt floating over the initrd tree, a wrong answer, then the unlock"> <img src="https://codeberg.org/wvhulle/bootvine/raw/branch/recordings/encrypted-volume.webp" width="640" alt="A LUKS passphrase prompt floating over the initrd tree, a wrong answer, then the unlock">
The `encrypted-volume` machine asks for a LUKS passphrase in the initrd; its The `encrypted-volume` machine asks for a LUKS passphrase in the initrd; its
recording shows a wrong answer, then the right one. recording shows a wrong answer, then the right one.
@@ -118,7 +149,7 @@ bootvine started, bootvine waits behind it.
## Failures ## Failures
<img src="../recordings/failures.webp" width="640" alt="Units failing one after another, each landing in the failure panel with its reason and last journal lines"> <img src="https://codeberg.org/wvhulle/bootvine/raw/branch/recordings/failures.webp" width="640" alt="Units failing one after another, each landing in the failure panel with its reason and last journal lines">
A unit that broke or timed out gets an entry in the failure panel, newest A unit that broke or timed out gets an entry in the failure panel, newest
first: first:
@@ -141,6 +172,16 @@ Failures from the initrd stay in the panel after the switch to the real root.
The recording is the `failures` machine, where every kind of failure systemd The recording is the `failures` machine, where every kind of failure systemd
reports happens one after another. reports happens one after another.
## Leaving the tree
`q`, `Ctrl-C` or `Esc` closes the tree during a boot or shutdown and gives the
console back with systemd's status lines, for when bootvine misbehaves or you
want to see what a stuck boot is doing. While a passphrase prompt is open, keys
go to the prompt instead.
These keys cannot help if bootvine itself has hung, because it reads them in
the same loop that draws the screen.
## Trying it ## Trying it
Neither of these touches your system's boot. Neither of these touches your system's boot.
@@ -170,10 +211,10 @@ shows the shutdown.
| Run | Shows | Recording | | Run | Shows | Recording |
| --- | --- | --- | | --- | --- | --- |
| `nix run .#sample-vm-slow-services` | slow units in the initrd and stage 2, one failing unit, and the handover to a greetd login | [booting through the initrd](#booting-through-the-initrd) | | `nix run .#sample-vm-slow-services` | slow units in the initrd and stage 2, one failing unit, and the handover to a tuigreet login | [booting through the initrd](#booting-through-the-initrd) |
| `nix run .#sample-vm-text-console` | the same units without a display manager, handing over at the default target | [without a display manager](#without-a-display-manager) | | `nix run .#sample-vm-text-console` | the same units without a display manager, handing over at the default target | [without a display manager](#without-a-display-manager) |
| `nix run .#sample-vm-scripted-initrd` | the same units with NixOS's scripted initrd, so bootvine starts in stage 2 only | [without a systemd initrd](#without-a-systemd-initrd) |
| `nix run .#sample-vm-encrypted-volume` | a LUKS volume unlocked in the initrd; the passphrase is `sample passphrase` | [passphrase prompts](#passphrase-prompts) | | `nix run .#sample-vm-encrypted-volume` | a LUKS volume unlocked in the initrd; the passphrase is `sample passphrase` | [passphrase prompts](#passphrase-prompts) |
| `nix run .#sample-vm-hibernate-resume` | a swap disk to hibernate to; run `systemctl hibernate`, then start the machine again | [resuming from hibernation](#resuming-from-hibernation) |
| `nix run .#sample-vm-failures` | a firmware failure in the initrd, then units that exit with an error, crash, time out, cannot be run, restart too often, report a status, die after starting, and one that fails only through its dependency | [failures](#failures) | | `nix run .#sample-vm-failures` | a firmware failure in the initrd, then units that exit with an error, crash, time out, cannot be run, restart too often, report a status, die after starting, and one that fails only through its dependency | [failures](#failures) |
Each machine keeps its disk in `~/.cache/bootvine-<machine>.qcow2`; delete it Each machine keeps its disk in `~/.cache/bootvine-<machine>.qcow2`; delete it
+70 -84
View File
@@ -61,6 +61,7 @@
{ {
default = builds.bootvine; default = builds.bootvine;
inherit (builds) bootvine scripted-demos repo-tasks; inherit (builds) bootvine scripted-demos repo-tasks;
workspace-dependencies = builds.cargoArtifacts;
sample-unit-files = pkgs.callPackage ./vm-tests/slow-services/sample-unit-files.nix { sample-unit-files = pkgs.callPackage ./vm-tests/slow-services/sample-unit-files.nix {
inherit (vmTests) sampleUnits; inherit (vmTests) sampleUnits;
}; };
@@ -86,103 +87,88 @@
... ...
}: }:
let let
runSampleMachine = machineName: description: { mkApp = drv: {
type = "app"; type = "app";
meta.description = "Boot the ${machineName} sample machine in QEMU: ${description}"; program = lib.getExe drv;
program = lib.getExe (vmTests.nixosSystemFor system machineName).config.system.build.vm;
}; };
runReleasePlzOnCodeberg = subcommand: description: {
type = "app"; repoTaskApp =
meta.description = description; name: description: xtaskArguments: runtimeInputs:
program = lib.getExe ( mkApp (
pkgs.writeShellApplication { pkgs.runCommand name
name = "release-plz-${subcommand}"; {
runtimeInputs = [ nativeBuildInputs = [ pkgs.makeBinaryWrapper ];
pkgs.release-plz meta.mainProgram = name;
pkgs.gitMinimal }
pkgs.pkg-config ''
pkgs.stdenv.cc makeWrapper ${lib.getExe builds.repo-tasks} $out/bin/${name} \
rustToolchain --add-flags ${lib.escapeShellArg xtaskArguments} \
]; --prefix PATH : ${lib.makeBinPath runtimeInputs}
text = '' ''
export PKG_CONFIG_PATH="${ )
lib.makeSearchPathOutput "dev" "lib/pkgconfig" [ // {
pkgs.dbus meta.description = description;
pkgs.systemd };
]
}" sampleMachineApps = lib.mapAttrs' (
exec release-plz ${subcommand} --forge gitea --git-token "$CODEBERG_TOKEN" machineName: machineDescription:
''; lib.nameValuePair "sample-vm-${machineName}" {
} type = "app";
); meta.description = "Boot the ${machineName} sample machine in QEMU: ${machineDescription}";
program = lib.getExe (vmTests.nixosSystemFor system machineName).config.system.build.vm;
}
) vmTests.machineDescriptions;
ciTaskApps = import ./nix/ci-tasks.nix {
inherit pkgs mkApp;
cargoToolchain = rustToolchain;
preCommitInputs = [ rustToolchain ];
extraReleaseInputs = [
pkgs.pkg-config
pkgs.stdenv.cc
];
releaseWrapperArgs = [
"--set"
"PKG_CONFIG_PATH"
(lib.makeSearchPathOutput "dev" "lib/pkgconfig" builds.bootvine.buildInputs)
];
}; };
in in
{ sampleMachineApps
release-plz-release = runReleasePlzOnCodeberg "release" "Publish unpublished versions to crates.io and tag them with a Codeberg release"; // ciTaskApps
release-plz-release-pr = runReleasePlzOnCodeberg "release-pr" "Open or update the Codeberg pull request that bumps the version and changelog"; // {
sample-vm-slow-services = runSampleMachine "slow-services" "slow and failing units, a held initrd probe and a greetd login"; record-screencasts =
sample-vm-text-console = runSampleMachine "text-console" "the slow units without a display manager, handing over at the default target"; repoTaskApp "record-screencasts"
sample-vm-scripted-initrd = runSampleMachine "scripted-initrd" "the slow units with the scripted initrd, so bootvine starts in stage 2"; "Re-record the scripted demo animations and the sample machine recordings into recordings/; publish them with publish-recordings"
sample-vm-encrypted-volume = runSampleMachine "encrypted-volume" "a LUKS volume unlocked in the initrd with the passphrase 'sample passphrase'"; "record-screencasts --vm-check-outputs ${
sample-vm-failures = runSampleMachine "failures" "units that fail in every way systemd reports, each with journal messages"; pkgs.linkFarm "vm-check-outputs" (
record-screencasts = { lib.mapAttrs (machineName: _: self.checks.${system}."vm-${machineName}") vmTests.machines
type = "app"; )
meta.description = "Re-record the scripted demo animations and the sample machine recordings into recordings/"; }"
program = lib.getExe ( [
pkgs.writeShellApplication { pkgs.vhs
name = "record-screencasts"; pkgs.libwebp
runtimeInputs = [ builds.scripted-demos
pkgs.vhs ];
pkgs.libwebp
builds.scripted-demos publish-recordings =
builds.repo-tasks repoTaskApp "publish-recordings"
]; "Replace the recordings branch on origin with a single commit holding recordings/"
text = "exec xtask record-screencasts --vm-check-outputs ${ "publish-recordings"
pkgs.linkFarm "vm-check-outputs" ( [ pkgs.gitMinimal ];
lib.mapAttrs (machineName: _: self.checks.${system}."vm-${machineName}") vmTests.machines
)
}";
}
);
};
build-and-push-to-cachix = {
type = "app";
meta.description = "Build flake outputs and push everything built to the wvhulle Cachix cache";
program = lib.getExe (
pkgs.writeShellApplication {
name = "build-and-push-to-cachix";
runtimeInputs = [ pkgs.cachix ];
text = ''exec cachix watch-exec wvhulle -- nix build --print-build-logs "$@"'';
}
);
};
check-conventional-commits = {
type = "app";
meta.description = "Check that the commit messages in a git revision range are conventional commits";
program = lib.getExe (
pkgs.writeShellApplication {
name = "check-conventional-commits";
runtimeInputs = [
pkgs.convco
pkgs.gitMinimal
];
text = ''exec convco check "$@"'';
}
);
};
} }
); );
checks = forEachSystem ( checks = forEachSystem (
{ pkgs, builds, ... }: { pkgs, builds, ... }:
{ {
inherit (builds) rustfmt-formatting clippy-lints; inherit (builds) clippy-lints;
bootvine-build = builds.bootvine; bootvine-build = builds.bootvine;
repo-tasks-build = builds.repo-tasks; repo-tasks-build = builds.repo-tasks;
} }
// lib.mapAttrs' ( // lib.mapAttrs' (machineName: check: lib.nameValuePair "vm-${machineName}" check) (
machineName: check: lib.nameValuePair "vm-${machineName}" check vmTests.checksFor pkgs
) (vmTests.checksFor pkgs) )
); );
devShells = forEachSystem ( devShells = forEachSystem (
+120
View File
@@ -0,0 +1,120 @@
{
pkgs,
mkApp,
cargoToolchain ? null,
preCommitInputs ? [ ],
extraReleaseInputs ? [ ],
releaseWrapperArgs ? [ ],
}:
let
inherit (pkgs) lib;
cargoInputs = lib.optional (cargoToolchain != null) cargoToolchain;
nuScriptTool =
{
script,
name,
runtimeInputs ? [ ],
wrapperArgs ? [ ],
}:
pkgs.runCommand name
{
nativeBuildInputs = [ pkgs.makeBinaryWrapper ];
meta.mainProgram = name;
}
''
makeWrapper ${lib.getExe pkgs.nushell} $out/bin/${name} \
--add-flags ${script} \
--add-flags ${name} \
${lib.optionalString (runtimeInputs != [ ]) "--prefix PATH : ${lib.makeBinPath runtimeInputs}"} \
${lib.escapeShellArgs wrapperArgs}
'';
nixBuiltPathsTool = toolArgs: nuScriptTool (toolArgs // { script = ../ci/nix-built-paths.nu; });
exportBuiltPathsHook = nixBuiltPathsTool { name = "export-built-paths-hook"; };
exportingBuildApp =
name:
mkApp (nixBuiltPathsTool {
inherit name;
wrapperArgs = [
"--set"
"EXPORT_HOOK_PROGRAM"
(lib.getExe exportBuiltPathsHook)
];
});
releasePlzApp =
name:
mkApp (nuScriptTool {
inherit name;
script = ../ci/release-tasks.nu;
runtimeInputs =
cargoInputs
++ [
pkgs.release-plz
pkgs.gitMinimal
]
++ extraReleaseInputs;
wrapperArgs = releaseWrapperArgs;
});
releaseTaskApps =
lib.mapAttrs
(
name: runtimeInputs:
mkApp (nuScriptTool {
inherit name runtimeInputs;
script = ../ci/release-tasks.nu;
})
)
{
authenticate-git-origin = [ pkgs.gitMinimal ];
collect-release-archives = [ ];
upload-release-assets = [ pkgs.tea ];
check-commit-messages = [
pkgs.convco
pkgs.gitMinimal
];
};
preCommitHooksTool =
pkgs.runCommand "run-pre-commit-hooks"
{
nativeBuildInputs = [ pkgs.makeBinaryWrapper ];
meta.mainProgram = "run-pre-commit-hooks";
}
''
makeWrapper ${lib.getExe pkgs.prek} $out/bin/run-pre-commit-hooks \
--add-flags "run --all-files --show-diff-on-failure" \
--prefix PATH : ${lib.makeBinPath ([ pkgs.gitMinimal ] ++ preCommitInputs)}
'';
in
releaseTaskApps
// {
publish-unreleased-crate-version = releasePlzApp "publish-unreleased-crate-version";
open-or-update-release-pr = releasePlzApp "open-or-update-release-pr";
open-dependency-update-pr = mkApp (nuScriptTool {
name = "open-dependency-update-pr";
script = ../ci/dependency-updates.nu;
runtimeInputs = cargoInputs ++ [
pkgs.gitMinimal
pkgs.tea
];
});
run-pre-commit-hooks = mkApp preCommitHooksTool;
build-and-export-paths = exportingBuildApp "build-and-export-paths";
build-unless-cached = exportingBuildApp "build-unless-cached";
import-exported-paths = mkApp (nixBuiltPathsTool {
name = "import-exported-paths";
});
copy-build-output = mkApp (nixBuiltPathsTool {
name = "copy-build-output";
});
upload-exported-paths = mkApp (nixBuiltPathsTool {
name = "upload-exported-paths";
runtimeInputs = [ pkgs.cachix ];
});
}
+5 -4
View File
@@ -30,10 +30,7 @@ let
args: craneLib.buildPackage (commonArgs // { inherit cargoArtifacts; } // args); args: craneLib.buildPackage (commonArgs // { inherit cargoArtifacts; } // args);
in in
{ {
rustfmt-formatting = craneLib.cargoFmt { inherit cargoArtifacts;
inherit (commonArgs) src pname version;
cargoExtraArgs = "--all";
};
clippy-lints = craneLib.cargoClippy ( clippy-lints = craneLib.cargoClippy (
commonArgs commonArgs
@@ -51,6 +48,10 @@ in
substituteInPlace $out/lib/systemd/system/$unit \ substituteInPlace $out/lib/systemd/system/$unit \
--replace-fail /usr/bin/bootvine $out/bin/bootvine --replace-fail /usr/bin/bootvine $out/bin/bootvine
done done
resume_drop_in=systemd-hibernate-resume.service.d/bootvine.conf
install -Dm644 bootvine/system-files/systemd/$resume_drop_in $out/lib/systemd/system/$resume_drop_in
substituteInPlace $out/lib/systemd/system/$resume_drop_in \
--replace-fail /usr/bin/bootvine $out/bin/bootvine
install -Dm755 bootvine/system-files/dracut/90bootvine/module-setup.sh \ install -Dm755 bootvine/system-files/dracut/90bootvine/module-setup.sh \
$out/lib/dracut/modules.d/90bootvine/module-setup.sh $out/lib/dracut/modules.d/90bootvine/module-setup.sh
install -Dm644 bootvine/system-files/mkinitcpio/install/sd-bootvine \ install -Dm644 bootvine/system-files/mkinitcpio/install/sd-bootvine \
-1
View File
@@ -2,7 +2,6 @@
release_always = true release_always = true
semver_check = false semver_check = false
git_release_type = "prod" git_release_type = "prod"
release_commits = "^(feat|fix|perf)[(:!]"
pr_labels = ["release"] pr_labels = ["release"]
pr_body = """ pr_body = """
{% for release in releases %} {% for release in releases %}
+9 -9
View File
@@ -9,18 +9,18 @@ let
networking.hostName = "bootvine-${machineName}"; networking.hostName = "bootvine-${machineName}";
}; };
machineNames = [ machineDescriptions = {
"slow-services" slow-services = "slow and failing units, a held initrd probe and a tuigreet login";
"text-console" text-console = "the slow units without a display manager, handing over at the default target";
"scripted-initrd" encrypted-volume = "a LUKS volume unlocked in the initrd with the passphrase 'sample passphrase'";
"encrypted-volume" failures = "units that fail in every way systemd reports, each with journal messages";
"failures" hibernate-resume = "a swap disk to hibernate to, showing the kernel's image loading progress on resume";
]; };
machines = lib.genAttrs machineNames machineModule; machines = lib.mapAttrs (machineName: _: machineModule machineName) machineDescriptions;
in in
{ {
inherit machines; inherit machines machineDescriptions;
sampleUnits = import ./slow-services/sample-units.nix; sampleUnits = import ./slow-services/sample-units.nix;
+41
View File
@@ -0,0 +1,41 @@
{ machine, pkgs, ... }:
{
name = "bootvine-hibernate-resume";
nodes.machine =
{ lib, ... }:
{
imports = [ machine ];
boot.resumeDevice = "/dev/vdc";
swapDevices = lib.mkOverride 0 [
{
device = "/dev/vdc";
options = [ "x-systemd.makefs" ];
}
];
powerManagement = {
powerDownCommands = "systemctl --no-block stop backdoor.service";
resumeCommands = "systemctl --no-block restart backdoor.service";
};
virtualisation = {
memorySize = 2048;
qemu.options = [
"-vga none"
"-device VGA,xres=1280,yres=800"
"-chardev socket,id=recording-monitor,path=recording-monitor,server=on,wait=off"
"-mon chardev=recording-monitor,mode=readline"
];
emptyDiskImages = [ 4096 ];
useNixStoreImage = true;
useEFIBoot = true;
};
};
testScript =
builtins.readFile ../shared/console.py
+ builtins.readFile ../shared/screen_recording.py
+ builtins.readFile ./check.py;
}
+52
View File
@@ -0,0 +1,52 @@
RESUME_MARKER = "/run/bootvine/resume-console-open"
BOOT_CONSOLE_LEVEL = "3"
SENTINEL_TEXT = "held only in memory"
def console_level():
return machine.succeed("cut -f1 /proc/sys/kernel/printk").strip()
def assert_console_returned():
machine.wait_until_fails("systemctl is-active bootvine")
machine.fail(f"test -e {RESUME_MARKER}")
assert console_level() == BOOT_CONSOLE_LEVEL, f"kernel console level was not restored: {console_level()}"
machine.start()
machine.wait_for_unit("default.target")
assert_console_returned()
machine.succeed("swapon --show=NAME --noheadings | grep -q .")
machine.succeed(
"mkdir /run/test",
"mount -t ramfs ramfs /run/test",
f"echo '{SENTINEL_TEXT}' > /run/test/sentinel",
"dd if=/dev/urandom of=/run/test/ballast bs=1M count=500",
)
machine.execute("systemctl hibernate >&2 &", check_return=False)
machine.wait_for_shutdown()
resume_recording = ScreenRecording(machine)
resume_recording.frame_seconds = 0.1
machine.start()
resume_recording.start()
machine.wait_for_console_text("Image loading progress")
machine.wait_for_console_text("Image loading done")
machine.succeed(f"grep '{SENTINEL_TEXT}' /run/test/sentinel")
assert console_level() == BOOT_CONSOLE_LEVEL, f"the restored system kept the opened level: {console_level()}"
assert foreground_terminal() != f"tty{BOOTVINE_TERMINAL}", "the restored system came back on bootvine's terminal"
machine.fail("systemctl is-active bootvine")
machine.sleep(1)
resume_recording.stop()
machine.crash()
machine.start()
machine.wait_for_unit("default.target")
machine.fail("test -e /run/test/sentinel")
assert_console_returned()
journal = bootvine_journal()
print(journal)
assert " in Initrd " in journal, "bootvine did not run in the initrd of the boot without an image"
machine.succeed('test "$(systemctl show -p Result --value bootvine)" = success')
+21
View File
@@ -0,0 +1,21 @@
{ lib, ... }:
{
boot.initrd.availableKernelModules = [ "bochs" ];
virtualisation.vmVariant = {
boot.resumeDevice = "/dev/vdb";
swapDevices = lib.mkOverride 0 [
{
device = "/dev/vdb";
options = [ "x-systemd.makefs" ];
}
];
virtualisation = {
emptyDiskImages = [ 4096 ];
qemu.options = lib.mkForce [
"-vga none"
"-device VGA,xres=1920,yres=1080"
];
};
};
}
-25
View File
@@ -1,25 +0,0 @@
{ machine, ... }:
{
name = "bootvine-scripted-initrd";
nodes.machine =
{ lib, ... }:
let
waitFor = flag: "/bin/sh -c 'until [ -e /run/${flag} ]; do sleep 0.1; done'";
in
{
imports = [
machine
../shared/recorded-display.nix
];
systemd.services = {
sample-database.serviceConfig.ExecStop = lib.mkForce (waitFor "release-sample-database");
backdoor.before = [ "sample-database.service" ];
};
};
testScript =
builtins.readFile ../shared/console.py
+ builtins.readFile ../shared/screen_recording.py
+ builtins.readFile ./check.py;
}
-28
View File
@@ -1,28 +0,0 @@
def unit_state(unit):
return machine.succeed(f"systemctl is-active {unit} || true").strip()
recording = ScreenRecording(machine)
machine.start()
recording.start()
wait_for_screen("Stage 2", "sample-database")
assert_bootvine_in_front()
assert_text_visible(font_has_512_glyphs=True)
machine.wait_for_unit("greetd.service")
retry(lambda _: unit_state("bootvine") == "inactive", timeout_seconds=60)
journal = bootvine_journal()
print(journal)
watched = [line for line in journal.splitlines() if line.startswith("bootvine: watching")]
assert watched, "bootvine never started"
assert not any(" in Initrd " in line for line in watched), "bootvine ran in a scripted initrd"
assert "handing the console over" in journal, "never handed the console over"
machine.succeed("systemctl poweroff --no-block")
retry(lambda _: unit_state("sample-database") == "deactivating", timeout_seconds=60)
wait_for_screen("Shutdown", "sample-database")
assert_bootvine_in_front()
machine.succeed("touch /run/release-sample-database")
machine.wait_for_shutdown()
recording.stop()
-6
View File
@@ -1,6 +0,0 @@
{ lib, ... }:
{
imports = [ ../slow-services/machine.nix ];
boot.initrd.systemd.enable = lib.mkForce false;
}
+2 -1
View File
@@ -14,6 +14,7 @@ class ScreenRecording:
self.recorded_machine = recorded_machine self.recorded_machine = recorded_machine
self.frames_directory = os.path.join(recorded_machine.out_dir, "recording") self.frames_directory = os.path.join(recorded_machine.out_dir, "recording")
self.raw_frame = os.path.join(recorded_machine.state_dir, "recording-frame.ppm") self.raw_frame = os.path.join(recorded_machine.state_dir, "recording-frame.ppm")
self.frame_seconds = RECORDING_FRAME_SECONDS
self.stopping = threading.Event() self.stopping = threading.Event()
self.thread = threading.Thread(target=self.record_frames, daemon=True) self.thread = threading.Thread(target=self.record_frames, daemon=True)
@@ -64,7 +65,7 @@ class ScreenRecording:
while not self.stopping.is_set(): while not self.stopping.is_set():
self.save_frame(monitor, frame_number) self.save_frame(monitor, frame_number)
frame_number += 1 frame_number += 1
self.stopping.wait(RECORDING_FRAME_SECONDS) self.stopping.wait(self.frame_seconds)
except (OSError, ConnectionError, subprocess.CalledProcessError): except (OSError, ConnectionError, subprocess.CalledProcessError):
pass pass
finally: finally:
+1
View File
@@ -13,6 +13,7 @@
../shared/recorded-display.nix ../shared/recorded-display.nix
]; ];
testing.initrdBackdoor = true; testing.initrdBackdoor = true;
boot.kernelParams = lib.mkAfter [ "console=tty0" ];
boot.initrd.systemd.services.initrd-hardware-probe.serviceConfig.ExecStart = lib.mkForce ( boot.initrd.systemd.services.initrd-hardware-probe.serviceConfig.ExecStart = lib.mkForce (
waitFor "release-initrd-hardware-probe" waitFor "release-initrd-hardware-probe"
); );
+25 -1
View File
@@ -6,6 +6,17 @@ def unit_state(unit):
return machine.succeed(f"systemctl is-active {unit} || true").strip() return machine.succeed(f"systemctl is-active {unit} || true").strip()
def foreground_console_text():
terminal_number = foreground_terminal().removeprefix("tty")
return machine.succeed(f"tr -cd '[:print:]' < /dev/vcs{terminal_number}")
def assert_unit_start_stays_off_console(description):
machine.succeed(f"systemd-run --wait --description='{description}' /run/current-system/sw/bin/true")
console_text = foreground_console_text()
assert description not in console_text, f"systemd status reached the login screen:\n{console_text}"
recording = ScreenRecording(machine) recording = ScreenRecording(machine)
machine.start() machine.start()
recording.start() recording.start()
@@ -24,11 +35,17 @@ assert_text_visible(font_has_512_glyphs=True)
assert console_level() == "1", f"stage 2 sysctl reopened the kernel console: {console_level()}" assert console_level() == "1", f"stage 2 sysctl reopened the kernel console: {console_level()}"
machine.wait_for_unit("greetd.service") machine.wait_for_unit("greetd.service")
retry(lambda _: unit_state("bootvine") == "inactive", timeout_seconds=60) retry(lambda _: "another program took the console" in bootvine_journal(), timeout_seconds=60)
assert unit_state("late-sensor-probe") == "activating", "the boot finished before the display manager took over" assert unit_state("late-sensor-probe") == "activating", "the boot finished before the display manager took over"
assert foreground_terminal() != f"tty{BOOTVINE_TERMINAL}", "bootvine took the console back from the display manager" assert foreground_terminal() != f"tty{BOOTVINE_TERMINAL}", "bootvine took the console back from the display manager"
machine.wait_until_tty_matches("1", "Username:")
assert_unit_start_stays_off_console("Mid boot status probe")
show_status = machine.succeed("systemctl show -p ShowStatus --value").strip()
assert show_status == "no", f"systemd status output came back before the boot finished: {show_status}"
assert unit_state("bootvine") == "active", "bootvine left before the boot finished"
machine.succeed("touch /run/release-late-sensor-probe") machine.succeed("touch /run/release-late-sensor-probe")
machine.wait_for_unit("graphical.target") machine.wait_for_unit("graphical.target")
retry(lambda _: unit_state("bootvine") == "inactive", timeout_seconds=60)
journal = bootvine_journal() journal = bootvine_journal()
print(journal) print(journal)
@@ -43,6 +60,13 @@ machine.succeed('test "$(systemctl show -p Result --value bootvine)" = success')
assert console_level() != "1", f"kernel console level was not restored: {console_level()}" assert console_level() != "1", f"kernel console level was not restored: {console_level()}"
show_status = machine.succeed("systemctl show -p ShowStatus --value").strip() show_status = machine.succeed("systemctl show -p ShowStatus --value").strip()
assert show_status == "yes", f"systemd status output was not restored: {show_status}" assert show_status == "yes", f"systemd status output was not restored: {show_status}"
assert_unit_start_stays_off_console("Post boot status probe")
machine.wait_until_tty_matches("1", "Username:")
machine.send_chars("sample-user\n")
machine.wait_until_tty_matches("1", "Password:")
machine.send_chars("sample-user\n")
machine.wait_until_succeeds("pgrep -u sample-user bash", timeout=30)
foreground = foreground_terminal() foreground = foreground_terminal()
assert foreground != f"tty{BOOTVINE_TERMINAL}", "bootvine kept the console after handing it over" assert foreground != f"tty{BOOTVINE_TERMINAL}", "bootvine kept the console after handing it over"
+1 -1
View File
@@ -37,6 +37,6 @@ in
services.greetd = { services.greetd = {
enable = true; enable = true;
settings.default_session.command = "${pkgs.greetd}/bin/agreety --cmd ${pkgs.bashInteractive}/bin/bash"; settings.default_session.command = "${pkgs.tuigreet}/bin/tuigreet --time --cmd ${pkgs.bashInteractive}/bin/bash";
}; };
} }
+6
View File
@@ -1,3 +1,4 @@
mod publish_recordings;
mod record_screencasts; mod record_screencasts;
mod sync_default_config; mod sync_default_config;
mod task_error; mod task_error;
@@ -20,6 +21,10 @@ enum Task {
screenshots to WebP in recordings/" screenshots to WebP in recordings/"
)] )]
RecordScreencasts(RecordScreencastsOptions), RecordScreencasts(RecordScreencastsOptions),
#[command(
about = "Replace the recordings branch on origin with a single commit holding recordings/"
)]
PublishRecordings,
#[command( #[command(
about = "Rewrite the defaults block in docs/configuration.md from `bootvine defaults`" about = "Rewrite the defaults block in docs/configuration.md from `bootvine defaults`"
)] )]
@@ -41,6 +46,7 @@ fn main() -> ExitCode {
Task::RecordScreencasts(options) => { Task::RecordScreencasts(options) => {
record_screencasts::record_screencasts(&options.vm_check_outputs) record_screencasts::record_screencasts(&options.vm_check_outputs)
} }
Task::PublishRecordings => publish_recordings::publish_recordings(),
Task::SyncDefaultConfig => sync_default_config::sync_default_config(), Task::SyncDefaultConfig => sync_default_config::sync_default_config(),
}; };
match outcome { match outcome {
+38
View File
@@ -0,0 +1,38 @@
use std::path::Path;
use xshell::{Shell, cmd};
use crate::{record_screencasts::RECORDINGS_DIRECTORY, task_error::TaskError};
const RECORDINGS_BRANCH: &str = "refs/heads/recordings";
pub fn publish_recordings() -> Result<(), TaskError> {
if !Path::new(RECORDINGS_DIRECTORY).is_dir() {
return Err(TaskError::RecordingsMissing);
}
let shell = Shell::new()?;
let git_directory = cmd!(shell, "git rev-parse --absolute-git-dir").read()?;
let temporary_directory = shell.create_temp_dir()?;
let _index_override = shell.push_env(
"GIT_INDEX_FILE",
temporary_directory.path().join("recordings-index"),
);
let _git_directory_override = shell.push_env("GIT_DIR", &git_directory);
let _recordings_directory = shell.push_dir(RECORDINGS_DIRECTORY);
cmd!(shell, "git --work-tree=. add --all --force .")
.quiet()
.run()?;
let recordings_tree = cmd!(shell, "git write-tree").read()?;
let recordings_commit = cmd!(
shell,
"git commit-tree {recordings_tree} -m 'chore: sample recordings [skip ci]'"
)
.read()?;
let branch = RECORDINGS_BRANCH;
cmd!(
shell,
"git push --force origin {recordings_commit}:{branch}"
)
.run()?;
Ok(())
}
+7 -2
View File
@@ -13,6 +13,7 @@ const TAPES: [&str; 2] = [
"scripted-demos/tapes/scripted-shutdown.tape", "scripted-demos/tapes/scripted-shutdown.tape",
]; ];
const RECORDING_FRAME_MILLISECONDS: &str = "500"; const RECORDING_FRAME_MILLISECONDS: &str = "500";
pub const RECORDINGS_DIRECTORY: &str = "recordings";
fn sorted_entries(directory: &Path) -> Result<Vec<PathBuf>, TaskError> { fn sorted_entries(directory: &Path) -> Result<Vec<PathBuf>, TaskError> {
let read_failure = |source| TaskError::File { let read_failure = |source| TaskError::File {
@@ -106,10 +107,14 @@ fn encode_machine_recording(
} }
pub fn record_screencasts(vm_check_outputs: &Path) -> Result<(), TaskError> { pub fn record_screencasts(vm_check_outputs: &Path) -> Result<(), TaskError> {
let recordings = Path::new("recordings"); if !TAPES.iter().all(|tape| Path::new(tape).is_file()) {
if !recordings.is_dir() {
return Err(TaskError::NotInRepositoryRoot); return Err(TaskError::NotInRepositoryRoot);
} }
let recordings = Path::new(RECORDINGS_DIRECTORY);
fs::create_dir_all(recordings).map_err(|source| TaskError::File {
path: recordings.to_path_buf(),
source,
})?;
let shell = Shell::new()?; let shell = Shell::new()?;
TAPES.iter().try_for_each(|tape| { TAPES.iter().try_for_each(|tape| {
let tape_path = Path::new(tape); let tape_path = Path::new(tape);
+3 -1
View File
@@ -10,8 +10,10 @@ pub enum TaskError {
File { path: PathBuf, source: io::Error }, File { path: PathBuf, source: io::Error },
#[error("{} has no recording frames", .0.display())] #[error("{} has no recording frames", .0.display())]
NoRecordingFrames(PathBuf), NoRecordingFrames(PathBuf),
#[error("no recordings directory here; run from the repository root")] #[error("no VHS tapes here; run from the repository root")]
NotInRepositoryRoot, NotInRepositoryRoot,
#[error("no recordings/ directory here; run record-screencasts from the repository root first")]
RecordingsMissing,
#[error("{0} has no ```toml block under its Defaults heading")] #[error("{0} has no ```toml block under its Defaults heading")]
DefaultsBlockMissing(&'static str), DefaultsBlockMissing(&'static str),
} }