diff --git a/Cargo.lock b/Cargo.lock
index 3262ae3..55c2eda 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -158,6 +158,7 @@ dependencies = [
"ser_nix",
"serde",
"serde_plain",
+ "systemd",
"thiserror 2.0.21",
"tokio",
"toml",
@@ -166,6 +167,12 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "build-env"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1522ac6ee801a11bf9ef3f80403f4ede6eb41291fac3dde3de09989679305f25"
+
[[package]]
name = "bumpalo"
version = "3.20.3"
@@ -365,6 +372,16 @@ dependencies = [
"phf",
]
+[[package]]
+name = "cstr-argument"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6bd9c8e659a473bce955ae5c35b116af38af11a7acb0b480e01f3ed348aeb40"
+dependencies = [
+ "cfg-if",
+ "memchr",
+]
+
[[package]]
name = "darling"
version = "0.24.1"
@@ -588,6 +605,33 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+[[package]]
+name = "foreign-types"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"
+dependencies = [
+ "foreign-types-macros",
+ "foreign-types-shared",
+]
+
+[[package]]
+name = "foreign-types-macros"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "foreign-types-shared"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
+
[[package]]
name = "futures"
version = "0.3.34"
@@ -880,6 +924,18 @@ version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
+[[package]]
+name = "libsystemd-sys"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "976306de183e6046819ef6505888d00996214766a3f4660a2ed5761c84a20aed"
+dependencies = [
+ "build-env",
+ "cfg-if",
+ "libc",
+ "pkg-config",
+]
+
[[package]]
name = "line-clipping"
version = "0.3.8"
@@ -1532,6 +1588,17 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+[[package]]
+name = "scripted-demos"
+version = "0.1.0"
+dependencies = [
+ "bootvine",
+ "futures",
+ "ratatui",
+ "tokio",
+ "zeroize",
+]
+
[[package]]
name = "semver"
version = "1.0.28"
@@ -1750,6 +1817,21 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "systemd"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01e9d1976a15b86245def55d20d52b5818e1a1e81aa030b6a608d3ce57709423"
+dependencies = [
+ "cstr-argument",
+ "foreign-types",
+ "libc",
+ "libsystemd-sys",
+ "log",
+ "memchr",
+ "utf8-cstr",
+]
+
[[package]]
name = "termina"
version = "0.3.3"
@@ -1993,6 +2075,12 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
+[[package]]
+name = "utf8-cstr"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "55bcbb425141152b10d5693095950b51c3745d019363fc2929ffd8f61449b628"
+
[[package]]
name = "utf8parse"
version = "0.2.2"
diff --git a/Cargo.toml b/Cargo.toml
index 6dbf32e..52c9239 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,18 +1,6 @@
-[package]
-categories = ["command-line-utilities", "os::linux-apis"]
-description = "Boot and shutdown progress for systemd on the console, with each job nested under the units waiting on it"
-edition = "2024"
-include = ["/src", "/examples", "/system-files", "/README.md", "/LICENSE"]
-keywords = ["systemd", "boot", "initrd", "tui", "console"]
-license = "GPL-3.0-or-later"
-name = "bootvine"
-readme = "README.md"
-repository = "https://codeberg.org/wvhulle/bootvine"
-rust-version = "1.91"
-version = "0.1.0"
-
[workspace]
-members = [".", "xtask"]
+members = ["bootvine", "scripted-demos", "xtask"]
+resolver = "3"
[workspace.lints.clippy]
absolute_paths = "warn"
@@ -20,60 +8,6 @@ missing_errors_doc = "allow"
needless_for_each = "allow"
pedantic = { priority = -1, level = "warn" }
-[lints]
-workspace = true
-
-[dependencies]
-clap = { version = "4.6.7", default-features = false, features = [
- "std",
- "derive",
- "help",
- "usage",
- "error-context",
-] }
-crossterm = "0.29.0"
-dbus = "0.9.12"
-futures = { version = "0.3.34", default-features = false, features = [
- "std",
- "async-await",
-] }
-heck = "0.5.0"
-jiff = { version = "0.2.38", default-features = false, features = [
- "serde",
- "std",
-] }
-petgraph = { version = "0.8.3", default-features = false, features = [
- "std",
- "graphmap",
-] }
-ratatui = { version = "0.30.2", features = [
- "serde",
- "unstable-rendered-line-info",
-] }
-rustix = { version = "1.1.5", features = [
- "event",
- "fs",
- "process",
- "stdio",
- "system",
- "termios",
- "time",
-] }
-ser_nix = "0.2.4"
-serde = { version = "1.0.229", features = ["derive"] }
-serde_plain = "1.0.2"
-thiserror = "2.0.12"
-tokio = { version = "1.54.0", default-features = false, features = [
- "rt",
- "time",
- "net",
- "signal",
-] }
-toml = { version = "1.1.8", features = ["preserve_order"] }
-unicode-truncate = "2.0.1"
-unicode-width = "0.2.2"
-zeroize = "1.9.1"
-
[profile.release]
codegen-units = 1
lto = "fat"
diff --git a/README.md b/README.md
index d791983..6e8433a 100644
--- a/README.md
+++ b/README.md
@@ -11,21 +11,16 @@ gave me any idea of what was going on.
-It follows shutdowns and reboots too: the units being stopped, nested under the
-units that have to stop first.
-
-
-
-Passphrase prompts, such as a
-[LUKS](https://gitlab.com/cryptsetup/cryptsetup) unlock in the initrd, are
-answered in place over the tree.
-
-
+It also follows shutdowns, answers passphrase prompts such as a
+[LUKS](https://gitlab.com/cryptsetup/cryptsetup) unlock in place, and shows why
+a unit failed with its last journal lines. The
+[guide](https://codeberg.org/wvhulle/bootvine/src/branch/main/docs/guide.md)
+walks through each part of the screen.
## Requirements
- systemd ≥ 246 as PID 1
-- [libdbus](https://www.freedesktop.org/wiki/Software/dbus/)
+- [libdbus](https://www.freedesktop.org/wiki/Software/dbus/) and libsystemd
- a virtual terminal
- a systemd initrd, to show the boot from the initrd as well as stage 2
@@ -34,33 +29,23 @@ for each distribution.
## Try it without installing
-Neither of these touches your system's boot.
-
-Play a scripted boot, poweroff and encrypted-root boot in your terminal, with
-[Rust](https://www.rust-lang.org/tools/install) installed:
+With [Nix](https://nixos.org/download/), boot a sample [NixOS](https://nixos.org) machine with slow and
+failing units in a [QEMU](https://www.qemu.org) window, without touching your
+system's boot:
```sh
-git clone https://codeberg.org/wvhulle/bootvine.git
-cd bootvine
-cargo run --example boot
-cargo run --example shutdown
-cargo run --example luks
+nix run git+https://codeberg.org/wvhulle/bootvine#sample-vm-slow-services
```
-`q` quits. The encrypted root unlocks with the passphrase `demo`; `Esc` quits
-while it asks.
-
-Or, with [Nix](https://nixos.org/download/), boot a sample [NixOS](https://nixos.org) machine with slow and
-failing units in a [QEMU](https://www.qemu.org) window:
-
-```sh
-nix run git+https://codeberg.org/wvhulle/bootvine#sample-machine-vm
-```
-
-It logs in as root; `poweroff` shows the shutdown.
+It logs in as root; `poweroff` shows the shutdown. The
+[guide](https://codeberg.org/wvhulle/bootvine/src/branch/main/docs/guide.md#trying-it)
+lists the other sample machines and the scripted demos that play in a terminal.
## Documentation
+- [Guide](https://codeberg.org/wvhulle/bootvine/src/branch/main/docs/guide.md)
+ to the screen: the tree, the timeline, failures, shutdown and passphrase
+ prompts.
- [Install](https://codeberg.org/wvhulle/bootvine/src/branch/main/docs/install.md)
on NixOS, Ubuntu and other distributions.
- [Configuration](https://codeberg.org/wvhulle/bootvine/src/branch/main/docs/configuration.md)
diff --git a/bootvine/Cargo.toml b/bootvine/Cargo.toml
new file mode 100644
index 0000000..4745a15
--- /dev/null
+++ b/bootvine/Cargo.toml
@@ -0,0 +1,69 @@
+[package]
+categories = ["command-line-utilities", "os::linux-apis"]
+description = "Boot and shutdown progress for systemd on the console, with each job nested under the units waiting on it"
+edition = "2024"
+include = ["/src", "/system-files", "/LICENSE"]
+keywords = ["systemd", "boot", "initrd", "tui", "console"]
+license = "GPL-3.0-or-later"
+name = "bootvine"
+readme = "../README.md"
+repository = "https://codeberg.org/wvhulle/bootvine"
+rust-version = "1.91"
+version = "0.1.0"
+
+[lints]
+workspace = true
+
+[dependencies]
+clap = { version = "4.6.7", default-features = false, features = [
+ "std",
+ "derive",
+ "help",
+ "usage",
+ "error-context",
+] }
+crossterm = "0.29.0"
+dbus = "0.9.12"
+futures = { version = "0.3.34", default-features = false, features = [
+ "std",
+ "async-await",
+] }
+heck = "0.5.0"
+jiff = { version = "0.2.38", default-features = false, features = [
+ "serde",
+ "std",
+] }
+petgraph = { version = "0.8.3", default-features = false, features = [
+ "std",
+ "graphmap",
+] }
+ratatui = { version = "0.30.2", features = [
+ "serde",
+ "unstable-rendered-line-info",
+] }
+rustix = { version = "1.1.5", features = [
+ "event",
+ "fs",
+ "process",
+ "stdio",
+ "system",
+ "termios",
+ "time",
+] }
+ser_nix = "0.2.4"
+serde = { version = "1.0.229", features = ["derive"] }
+serde_plain = "1.0.2"
+systemd = { version = "0.10.1", default-features = false, features = [
+ "journal",
+] }
+thiserror = "2.0.12"
+tokio = { version = "1.54.0", default-features = false, features = [
+ "rt",
+ "time",
+ "net",
+ "signal",
+] }
+toml = { version = "1.1.8", features = ["preserve_order"] }
+unicode-truncate = "2.0.1"
+unicode-width = "0.2.2"
+zeroize = "1.9.1"
diff --git a/bootvine/LICENSE b/bootvine/LICENSE
new file mode 120000
index 0000000..ea5b606
--- /dev/null
+++ b/bootvine/LICENSE
@@ -0,0 +1 @@
+../LICENSE
\ No newline at end of file
diff --git a/src/boot_model.rs b/bootvine/src/boot_model.rs
similarity index 79%
rename from src/boot_model.rs
rename to bootvine/src/boot_model.rs
index 4329907..f0628b8 100644
--- a/src/boot_model.rs
+++ b/bootvine/src/boot_model.rs
@@ -41,10 +41,44 @@ struct PendingJob {
kind: JobKind,
}
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum FailureKind {
+ Broke,
+ TimedOut,
+ DependencyFailed,
+}
+
+impl FailureKind {
+ #[must_use]
+ pub fn has_own_cause(self) -> bool {
+ self != Self::DependencyFailed
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct FailureCause {
+ pub reason: String,
+ pub log_lines: Vec,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum FailureExplanation {
+ Unexplained,
+ Explained(FailureCause),
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct FailedUnit {
+ pub unit: String,
+ pub label: String,
+ pub kind: FailureKind,
+ pub explanation: FailureExplanation,
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Outcome {
Succeeded { at: Duration },
- Failed,
+ Failed(FailureKind),
Abandoned,
}
@@ -109,7 +143,7 @@ pub struct BootState {
pub phase: Phase,
pub origin: Duration,
pub root: Root,
- pub failed: Vec,
+ pub failed: Vec,
pub finished_stages: Vec,
pub finished_runs: Vec,
pub handoff_unit: Option,
diff --git a/src/boot_model/boot_change.rs b/bootvine/src/boot_model/boot_change.rs
similarity index 91%
rename from src/boot_model/boot_change.rs
rename to bootvine/src/boot_model/boot_change.rs
index 1c63e08..84b9f49 100644
--- a/src/boot_model/boot_change.rs
+++ b/bootvine/src/boot_model/boot_change.rs
@@ -1,6 +1,6 @@
use std::time::Duration;
-use super::{Activity, BootState, JobKind, JobResult, UnitFacts};
+use super::{Activity, BootState, FailureCause, JobKind, JobResult, UnitFacts};
pub enum BootChange {
TrackUnit {
@@ -22,6 +22,10 @@ pub enum BootChange {
result: JobResult,
at: Duration,
},
+ ExplainFailure {
+ unit: String,
+ cause: FailureCause,
+ },
SetRoot(String),
SetHandoff(String),
SetOrigin(Duration),
@@ -42,6 +46,7 @@ impl BootState {
BootChange::UpdateActivity { unit, activity } => self.update_activity(&unit, activity),
BootChange::QueueJob { id, unit, kind, at } => self.queue_job(id, &unit, kind, at),
BootChange::FinishJob { id, result, at } => self.finish_job(id, result, at),
+ BootChange::ExplainFailure { unit, cause } => self.explain_failure(&unit, cause),
BootChange::SetRoot(root) => self.set_root(root),
BootChange::SetHandoff(unit) => {
if let Some(handoff) = &mut self.handoff_unit {
@@ -62,7 +67,7 @@ mod tests {
use super::*;
use crate::{
boot_model::Phase,
- demo_script::boot_test_fixtures::{MS, facts, waiting_rows},
+ boot_test_fixtures::{MS, facts, waiting_rows},
};
#[test]
diff --git a/src/boot_model/boot_origin.rs b/bootvine/src/boot_model/boot_origin.rs
similarity index 100%
rename from src/boot_model/boot_origin.rs
rename to bootvine/src/boot_model/boot_origin.rs
diff --git a/src/boot_model/job_ingestion.rs b/bootvine/src/boot_model/job_ingestion.rs
similarity index 76%
rename from src/boot_model/job_ingestion.rs
rename to bootvine/src/boot_model/job_ingestion.rs
index a5ef5f5..42266ac 100644
--- a/src/boot_model/job_ingestion.rs
+++ b/bootvine/src/boot_model/job_ingestion.rs
@@ -1,9 +1,10 @@
use std::{collections::HashMap, time::Duration};
use super::{
- ActiveState, Activity, BootState, FinishedRun, FinishedStage, HANDOFF_UNIT, HOST_MILESTONES,
- JobKind, JobResult, Outcome, PendingJob, Phase, Progress, Root, SHUTDOWN_MILESTONES, Tally,
- UnitFacts, UnitKind, UnitRecord, unit_facts::display_label,
+ ActiveState, Activity, BootState, FailedUnit, FailureCause, FailureExplanation, FailureKind,
+ FinishedRun, FinishedStage, HANDOFF_UNIT, HOST_MILESTONES, JobKind, JobResult, Outcome,
+ PendingJob, Phase, Progress, Root, SHUTDOWN_MILESTONES, Tally, UnitFacts, UnitKind, UnitRecord,
+ unit_facts::display_label,
};
impl UnitRecord {
@@ -116,11 +117,40 @@ impl BootState {
}
pub fn update_activity(&mut self, unit: &str, activity: Activity) {
- if let Some(record) = self.units.get_mut(unit) {
- record.activity = record.activity.merge(activity);
+ let Some(record) = self.units.get_mut(unit) else {
+ return;
+ };
+ record.activity = record.activity.merge(activity);
+ if activity.state == Some(ActiveState::Failed) {
+ let label = display_label(&record.facts);
+ self.record_failure(unit, label, FailureKind::Broke);
}
}
+ fn record_failure(&mut self, unit: &str, label: String, kind: FailureKind) {
+ match self.failed.iter_mut().find(|failed| failed.unit == unit) {
+ Some(known) if kind != FailureKind::Broke => known.kind = kind,
+ Some(_) => {}
+ None => self.failed.push(FailedUnit {
+ unit: unit.to_owned(),
+ label,
+ kind,
+ explanation: FailureExplanation::Unexplained,
+ }),
+ }
+ }
+
+ pub fn explain_failure(&mut self, unit: &str, cause: FailureCause) {
+ if let Some(failed) = self.failed.iter_mut().find(|failed| failed.unit == unit) {
+ failed.explanation = FailureExplanation::Explained(cause);
+ }
+ }
+
+ #[must_use]
+ pub fn has_failed(&self, unit: &str) -> bool {
+ self.failed.iter().any(|failed| failed.unit == unit)
+ }
+
pub fn queue_job(&mut self, id: u32, unit: &str, kind: JobKind, at: Duration) {
if self.enqueue(id, unit, kind, at)
&& kind == JobKind::BringsUp
@@ -150,18 +180,26 @@ impl BootState {
let Some(unit) = self.jobs.remove(&id) else {
return;
};
- let Some(record) = self.units.get_mut(&unit) else {
+ let Some(label) = self
+ .units
+ .get(&unit)
+ .map(|record| display_label(&record.facts))
+ else {
return;
};
let outcome = match result {
JobResult::Done => Outcome::Succeeded { at },
JobResult::Skipped | JobResult::Canceled => Outcome::Abandoned,
- JobResult::Failed | JobResult::Timeout | JobResult::Dependency => Outcome::Failed,
+ JobResult::Failed => Outcome::Failed(FailureKind::Broke),
+ JobResult::Timeout => Outcome::Failed(FailureKind::TimedOut),
+ JobResult::Dependency => Outcome::Failed(FailureKind::DependencyFailed),
};
- let label = display_label(&record.facts);
- if outcome == Outcome::Failed && !self.failed.contains(&label) {
- self.failed.push(label.clone());
+ if let Outcome::Failed(kind) = outcome {
+ self.record_failure(&unit, label.clone(), kind);
}
+ let Some(record) = self.units.get_mut(&unit) else {
+ return;
+ };
let job = match record.progress {
Progress::Pending(job) if job.id == id => job,
_ => return,
@@ -176,7 +214,7 @@ impl BootState {
label,
started_at,
finished_at: at,
- failed: outcome == Outcome::Failed,
+ failed: matches!(outcome, Outcome::Failed(_)),
});
}
}
@@ -193,7 +231,7 @@ impl BootState {
failed_units: self
.units
.values()
- .filter(|record| record.progress == Progress::Finished(Outcome::Failed))
+ .filter(|record| matches!(record.progress, Progress::Finished(Outcome::Failed(_))))
.count(),
started_at: self.origin,
reached_at: at,
@@ -254,7 +292,7 @@ impl BootState {
Progress::Finished(Outcome::Succeeded { .. } | Outcome::Abandoned) => {
tally.done += 1;
}
- Progress::Finished(Outcome::Failed) | Progress::Untouched => {}
+ Progress::Finished(Outcome::Failed(_)) | Progress::Untouched => {}
}
tally
})
@@ -266,17 +304,82 @@ mod tests {
use super::*;
use crate::{
boot_model::{BootChange, RowStatus, UnitTimeouts},
- demo_script::boot_test_fixtures::{
+ boot_test_fixtures::{
MS, activating, facts, nested_boot_sample as sample, queue_unit, queued_boot, running,
waiting, waiting_rows,
},
};
+ fn failure_kinds(state: &BootState) -> Vec<(&str, FailureKind)> {
+ state
+ .failed
+ .iter()
+ .map(|failed| (failed.unit.as_str(), failed.kind))
+ .collect()
+ }
+
+ #[test]
+ fn job_results_keep_their_failure_kind() {
+ let mut state = sample();
+ state.finish_job(4, JobResult::Timeout, 2000 * MS);
+ state.finish_job(3, JobResult::Dependency, 2000 * MS);
+ assert_eq!(
+ failure_kinds(&state),
+ [
+ ("nm.service", FailureKind::TimedOut),
+ ("nm-wait.service", FailureKind::DependencyFailed),
+ ]
+ );
+ }
+
+ #[test]
+ fn a_unit_entering_the_failed_state_counts_without_a_failed_job() {
+ let mut state = sample();
+ state.update_activity(
+ "nm.service",
+ Activity {
+ state: Some(ActiveState::Failed),
+ ..Activity::default()
+ },
+ );
+ assert_eq!(failure_kinds(&state), [("nm.service", FailureKind::Broke)]);
+ state.finish_job(4, JobResult::Timeout, 2000 * MS);
+ assert_eq!(
+ failure_kinds(&state),
+ [("nm.service", FailureKind::TimedOut)]
+ );
+ assert_eq!(state.tally().failed, 1);
+ }
+
+ #[test]
+ fn an_explanation_attaches_to_its_failed_unit() {
+ let mut state = sample();
+ let cause = FailureCause {
+ reason: "exited with status 1".to_owned(),
+ log_lines: vec!["no carrier".to_owned()],
+ };
+ state.explain_failure("nm.service", cause.clone());
+ assert!(state.failed.is_empty());
+ state.finish_job(4, JobResult::Failed, 2000 * MS);
+ state.explain_failure("nm.service", cause.clone());
+ assert_eq!(
+ state.failed[0].explanation,
+ FailureExplanation::Explained(cause)
+ );
+ }
+
#[test]
fn failures_are_listed_and_not_counted_as_done() {
let mut state = sample();
state.finish_job(4, JobResult::Failed, 2000 * MS);
- assert_eq!(state.failed, ["nm"]);
+ assert_eq!(
+ state
+ .failed
+ .iter()
+ .map(|failed| failed.label.as_str())
+ .collect::>(),
+ ["nm"]
+ );
let tally = state.tally();
assert_eq!(tally.failed, 1);
assert_eq!(tally.done, 0);
diff --git a/src/boot_model/reached_milestones.rs b/bootvine/src/boot_model/reached_milestones.rs
similarity index 96%
rename from src/boot_model/reached_milestones.rs
rename to bootvine/src/boot_model/reached_milestones.rs
index 48cfa16..efa0bf8 100644
--- a/src/boot_model/reached_milestones.rs
+++ b/bootvine/src/boot_model/reached_milestones.rs
@@ -23,7 +23,9 @@ impl BootState {
Progress::Untouched => record.activity.active_enter.filter(|entered| {
record.activity.state == Some(ActiveState::Active) && *entered >= self.origin
}),
- Progress::Pending(_) | Progress::Finished(Outcome::Failed | Outcome::Abandoned) => None,
+ Progress::Pending(_) | Progress::Finished(Outcome::Failed(_) | Outcome::Abandoned) => {
+ None
+ }
}
}
@@ -81,9 +83,7 @@ mod tests {
use super::*;
use crate::{
boot_model::{Activity, JobResult, Phase},
- demo_script::boot_test_fixtures::{
- MS, nested_boot_sample, queued_boot, waiting, waiting_rows,
- },
+ boot_test_fixtures::{MS, nested_boot_sample, queued_boot, waiting, waiting_rows},
};
#[test]
diff --git a/src/boot_model/unit_facts.rs b/bootvine/src/boot_model/unit_facts.rs
similarity index 98%
rename from src/boot_model/unit_facts.rs
rename to bootvine/src/boot_model/unit_facts.rs
index d986ffc..b4dc35b 100644
--- a/src/boot_model/unit_facts.rs
+++ b/bootvine/src/boot_model/unit_facts.rs
@@ -152,7 +152,7 @@ mod tests {
use serde_plain::from_str;
use super::*;
- use crate::demo_script::boot_test_fixtures::{facts, waiting};
+ use crate::boot_test_fixtures::{facts, waiting};
#[test]
fn unknown_systemd_strings_fall_back_instead_of_failing() {
diff --git a/src/boot_model/waiting_tree.rs b/bootvine/src/boot_model/waiting_tree.rs
similarity index 97%
rename from src/boot_model/waiting_tree.rs
rename to bootvine/src/boot_model/waiting_tree.rs
index 7cf6115..0cfc78a 100644
--- a/src/boot_model/waiting_tree.rs
+++ b/bootvine/src/boot_model/waiting_tree.rs
@@ -7,7 +7,7 @@ use petgraph::{
};
use super::{
- BootState, Outcome, Phase, Progress, UnitKind, UnitRecord,
+ BootState, FailureKind, Outcome, Phase, Progress, UnitKind, UnitRecord,
unit_facts::{display_label, summary},
};
@@ -31,7 +31,7 @@ pub enum RowStatus {
since: Duration,
deadline: Option,
},
- Failed,
+ Failed(FailureKind),
Done,
}
@@ -87,7 +87,7 @@ impl UnitRecord {
deadline: self.deadline(),
})
}
- Progress::Finished(Outcome::Failed) => RowStatus::Failed,
+ Progress::Finished(Outcome::Failed(kind)) => RowStatus::Failed(kind),
Progress::Finished(_) | Progress::Untouched => RowStatus::Done,
}
}
@@ -100,7 +100,7 @@ impl BootState {
self.units
.iter()
.filter(|(name, record)| match record.progress {
- Progress::Pending(_) | Progress::Finished(Outcome::Failed) => true,
+ Progress::Pending(_) | Progress::Finished(Outcome::Failed(_)) => true,
Progress::Finished(Outcome::Succeeded { at }) => {
at >= finished_since || self.is_milestone(name)
}
@@ -240,7 +240,7 @@ impl BootState {
Progress::Finished(Outcome::Succeeded { at }) => {
SiblingRank::RunningSince(record.activity.inactive_exit.unwrap_or(at))
}
- Progress::Finished(Outcome::Failed) => SiblingRank::Failed,
+ Progress::Finished(Outcome::Failed(_)) => SiblingRank::Failed,
Progress::Finished(Outcome::Abandoned) | Progress::Untouched => {
SiblingRank::Waiting
}
@@ -253,7 +253,7 @@ impl BootState {
#[cfg(test)]
mod tests {
use super::*;
- use crate::demo_script::boot_test_fixtures::{
+ use crate::boot_test_fixtures::{
nested_boot_sample, queued_boot, tree_outline, waiting, waiting_rows,
};
diff --git a/src/demo_script/boot_test_fixtures.rs b/bootvine/src/boot_test_fixtures.rs
similarity index 100%
rename from src/demo_script/boot_test_fixtures.rs
rename to bootvine/src/boot_test_fixtures.rs
diff --git a/src/boot_view.rs b/bootvine/src/boot_view.rs
similarity index 77%
rename from src/boot_view.rs
rename to bootvine/src/boot_view.rs
index 488f292..cf2bf57 100644
--- a/src/boot_view.rs
+++ b/bootvine/src/boot_view.rs
@@ -1,3 +1,4 @@
+mod failure_panel;
#[cfg(test)]
mod frame_cost_bench;
#[cfg(test)]
@@ -27,6 +28,7 @@ use unicode_width::UnicodeWidthStr;
pub use self::screen_chrome::PasswordPrompt;
use self::{
+ failure_panel::FailurePanel,
run_timeline::{RunningRun, Timeline},
screen_chrome::{FOOTER_HEIGHT, Footer, Header, PasswordPopup},
stage_summary::Stages,
@@ -46,6 +48,9 @@ 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 LAST_BRANCH: &str = "└─ ";
const PASSING_TRUNK: &str = "│ ";
@@ -75,6 +80,20 @@ pub struct BootView<'a> {
}
impl BootView<'_> {
+ fn failure_panel(&self) -> FailurePanel<'_> {
+ FailurePanel {
+ newest_first: self
+ .state
+ .failed
+ .iter()
+ .rev()
+ .filter(|failed| failed.kind.has_own_cause())
+ .collect(),
+ colors: &self.colors.failures,
+ glyphs: self.glyphs,
+ }
+ }
+
fn timeline<'a>(&'a self, rows: &'a [TreeRow]) -> Timeline<'a> {
let mut running: Vec = rows
.iter()
@@ -135,6 +154,7 @@ impl Widget for BootView<'_> {
glyphs: self.glyphs,
};
let timeline = self.timeline(&all_rows);
+ let failure_panel = self.failure_panel();
let footer = Footer {
tally: self.state.tally(),
colors: &self.colors.footer,
@@ -148,6 +168,7 @@ impl Widget for BootView<'_> {
let heights = Heights::share(
free,
UnitTree::height_of(pending_count, 0),
+ failure_panel.height(),
if fits_timeline { timeline.height() } else { 0 },
);
let budget = usize::from(heights.tree.saturating_sub(1));
@@ -168,6 +189,7 @@ impl Widget for BootView<'_> {
stage_area,
tree_area,
_,
+ failure_area,
timeline_area,
footer_area,
] = Layout::vertical([
@@ -175,6 +197,7 @@ impl Widget for BootView<'_> {
Constraint::Length(stages.height()),
Constraint::Length(tree_height),
Constraint::Fill(1),
+ Constraint::Length(heights.failures),
Constraint::Length(heights.timeline),
Constraint::Length(FOOTER_HEIGHT),
])
@@ -183,6 +206,9 @@ impl Widget for BootView<'_> {
header.render(header_area, buf);
stages.render(stage_area, buf);
tree.render(tree_area, buf);
+ if heights.failures > 0 {
+ failure_panel.render(failure_area, buf);
+ }
if heights.timeline > 0 {
timeline.render(timeline_area, buf);
}
@@ -200,19 +226,32 @@ impl Widget for BootView<'_> {
struct Heights {
tree: u16,
+ failures: u16,
timeline: u16,
}
impl Heights {
- fn share(free: u16, tree_need: u16, timeline_need: u16) -> Self {
- let leftover = free.saturating_sub(tree_need);
+ fn share(free: u16, tree_need: u16, failures_need: u16, timeline_need: u16) -> Self {
+ let reserved = RESERVED_FAILURE_PANEL_HEIGHT
+ .min(failures_need)
+ .min(free.saturating_sub(MIN_TREE_HEIGHT_BESIDE_FAILURES));
+ let failures = failures_need
+ .min(free.saturating_sub(tree_need))
+ .max(reserved);
+ let failures = if failures >= MIN_FAILURE_PANEL_HEIGHT {
+ failures
+ } else {
+ 0
+ };
+ let leftover = free.saturating_sub(tree_need).saturating_sub(failures);
let timeline = if leftover >= MIN_TIMELINE_HEIGHT {
timeline_need.min(leftover)
} else {
0
};
Self {
- tree: free - timeline,
+ tree: free - failures - timeline,
+ failures,
timeline,
}
}
@@ -264,13 +303,32 @@ mod tests {
#[test]
fn the_tree_takes_the_room_and_the_timeline_only_what_is_left() {
- let heights = Heights::share(30, 40, 50);
+ let heights = Heights::share(30, 40, 0, 50);
assert_eq!((heights.tree, heights.timeline), (30, 0));
- let heights = Heights::share(30, 12, 50);
+ let heights = Heights::share(30, 12, 0, 50);
assert_eq!((heights.tree, heights.timeline), (12, 18));
- let heights = Heights::share(30, 25, 50);
+ let heights = Heights::share(30, 25, 0, 50);
assert_eq!((heights.tree, heights.timeline), (30, 0));
- let heights = Heights::share(30, 12, 8);
+ let heights = Heights::share(30, 12, 0, 8);
assert_eq!((heights.tree, heights.timeline), (22, 8));
}
+
+ #[test]
+ fn failures_come_before_the_timeline_and_keep_a_few_rows_beside_a_full_tree() {
+ let heights = Heights::share(30, 12, 6, 50);
+ assert_eq!(
+ (heights.tree, heights.failures, heights.timeline),
+ (12, 6, 12)
+ );
+ let heights = Heights::share(30, 40, 9, 50);
+ assert_eq!(
+ (heights.tree, heights.failures, heights.timeline),
+ (26, 4, 0)
+ );
+ let heights = Heights::share(5, 40, 9, 50);
+ assert_eq!(
+ (heights.tree, heights.failures, heights.timeline),
+ (5, 0, 0)
+ );
+ }
}
diff --git a/bootvine/src/boot_view/failure_panel.rs b/bootvine/src/boot_view/failure_panel.rs
new file mode 100644
index 0000000..8b8b9b9
--- /dev/null
+++ b/bootvine/src/boot_view/failure_panel.rs
@@ -0,0 +1,227 @@
+use std::iter::once;
+
+use ratatui::{
+ buffer::Buffer,
+ layout::Rect,
+ style::Stylize,
+ text::{Line, Span},
+ widgets::{Paragraph, Widget},
+};
+use unicode_width::UnicodeWidthStr;
+
+use super::{fit_width, rule};
+use crate::{
+ boot_model::{FailedUnit, FailureExplanation},
+ 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 newest_first: Vec<&'a FailedUnit>,
+ pub colors: &'a FailureColors,
+ pub glyphs: &'a Glyphs,
+}
+
+fn log_lines(failed: &FailedUnit) -> &[String] {
+ match &failed.explanation {
+ FailureExplanation::Explained(cause) => &cause.log_lines,
+ FailureExplanation::Unexplained => &[],
+ }
+}
+
+impl FailurePanel<'_> {
+ pub fn height(&self) -> u16 {
+ if self.newest_first.is_empty() {
+ return 0;
+ }
+ let rows: usize = self
+ .newest_first
+ .iter()
+ .map(|failed| 1 + log_lines(failed).len())
+ .sum();
+ RULE_HEIGHT.saturating_add(u16::try_from(rows).unwrap_or(u16::MAX))
+ }
+
+ fn headline(&self, failed: &FailedUnit, width: usize) -> Line<'static> {
+ let marker = format!("{} ", self.glyphs.failed);
+ let label_room = width.saturating_sub(marker.width());
+ 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 = match &failed.explanation {
+ FailureExplanation::Explained(cause) if reason_room > 0 => {
+ fit_width(&cause.reason, reason_room, self.glyphs.ellipsis)
+ }
+ _ => String::new(),
+ };
+ let reason_span =
+ (!reason.is_empty()).then(|| format!("{REASON_GAP}{reason}").fg(self.colors.reason));
+ Line::from(
+ [
+ marker.fg(self.colors.unit),
+ label.fg(self.colors.unit).bold(),
+ ]
+ .into_iter()
+ .chain(reason_span)
+ .collect::>(),
+ )
+ }
+
+ fn block(&self, failed: &FailedUnit, width: usize) -> Vec> {
+ let log_room = width.saturating_sub(LOG_INDENT.width());
+ once(self.headline(failed, width))
+ .chain(log_lines(failed).iter().map(|line| {
+ format!(
+ "{LOG_INDENT}{}",
+ fit_width(line, log_room, self.glyphs.ellipsis)
+ )
+ .fg(self.colors.log)
+ .into()
+ }))
+ .collect()
+ }
+
+ fn lines_within(&self, rows: usize, width: usize) -> Vec> {
+ if self.newest_first.len() > rows {
+ return self.headlines_with_overflow(rows, width);
+ }
+ let mut spare_rows = rows - self.newest_first.len();
+ self.newest_first
+ .iter()
+ .flat_map(|failed| {
+ let mut block = self.block(failed, width);
+ let kept_log_lines = (block.len() - 1).min(spare_rows);
+ spare_rows -= kept_log_lines;
+ block.truncate(1 + kept_log_lines);
+ block
+ })
+ .collect()
+ }
+
+ fn headlines_with_overflow(&self, rows: usize, width: usize) -> Vec> {
+ let Some(headline_rows) = rows.checked_sub(1) else {
+ return Vec::new();
+ };
+ let hidden = self.newest_first.len() - headline_rows;
+ self.newest_first
+ .iter()
+ .take(headline_rows)
+ .map(|failed| self.headline(failed, width))
+ .chain(once(
+ Line::from(format!("{} {hidden} more failed", self.glyphs.ellipsis))
+ .fg(self.colors.overflow),
+ ))
+ .collect()
+ }
+}
+
+impl Widget for FailurePanel<'_> {
+ fn render(self, area: Rect, buf: &mut Buffer) {
+ let block = rule(
+ self.colors.rule,
+ Line::from(" Failures ".fg(self.colors.title)),
+ );
+ let inner = block.inner(area);
+ block.render(area, buf);
+ Paragraph::new(self.lines_within(usize::from(inner.height), usize::from(inner.width)))
+ .render(inner, buf);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::boot_model::{FailureCause, FailureKind};
+
+ fn explained(label: &str, log_lines: &[&str]) -> FailedUnit {
+ FailedUnit {
+ unit: format!("{label}.service"),
+ label: label.to_owned(),
+ kind: FailureKind::Broke,
+ explanation: FailureExplanation::Explained(FailureCause {
+ reason: "exited with status 1".to_owned(),
+ log_lines: log_lines.iter().map(ToString::to_string).collect(),
+ }),
+ }
+ }
+
+ fn panel_text(failures: &[FailedUnit], rows: usize) -> Vec {
+ FailurePanel {
+ newest_first: failures.iter().collect(),
+ colors: &FailureColors::default(),
+ glyphs: &Glyphs::fitting(|_| true),
+ }
+ .lines_within(rows, 60)
+ .iter()
+ .map(ToString::to_string)
+ .collect()
+ }
+
+ #[test]
+ fn the_newest_failure_keeps_its_lines_and_older_ones_shrink_to_a_headline() {
+ let failures = [
+ explained("web", &["bind: address in use", "giving up"]),
+ explained("db", &["disk full"]),
+ explained("cache", &["no memory"]),
+ ];
+ assert_eq!(
+ panel_text(&failures, 5),
+ [
+ "× web exited with status 1",
+ " bind: address in use",
+ " giving up",
+ "× db exited with status 1",
+ "× cache exited with status 1",
+ ]
+ );
+ }
+
+ #[test]
+ fn room_left_by_the_newest_failure_goes_to_older_ones() {
+ let failures = [
+ explained("web", &["giving up"]),
+ explained("db", &["disk full", "read-only file system"]),
+ explained("cache", &["no memory"]),
+ ];
+ assert_eq!(
+ panel_text(&failures, 6),
+ [
+ "× web exited with status 1",
+ " giving up",
+ "× db exited with status 1",
+ " disk full",
+ " read-only file system",
+ "× cache exited with status 1",
+ ]
+ );
+ }
+
+ #[test]
+ fn failures_beyond_the_room_are_counted() {
+ let failures = [
+ explained("web", &["giving up"]),
+ explained("db", &[]),
+ explained("cache", &[]),
+ explained("queue", &[]),
+ ];
+ assert_eq!(
+ panel_text(&failures, 3),
+ [
+ "× web exited with status 1",
+ "× db exited with status 1",
+ "… 2 more failed"
+ ]
+ );
+ }
+
+ #[test]
+ fn an_unexplained_failure_shows_only_its_name() {
+ let failures = [FailedUnit {
+ explanation: FailureExplanation::Unexplained,
+ ..explained("web", &[])
+ }];
+ assert_eq!(panel_text(&failures, 4), ["× web"]);
+ }
+}
diff --git a/src/boot_view/frame_cost_bench.rs b/bootvine/src/boot_view/frame_cost_bench.rs
similarity index 97%
rename from src/boot_view/frame_cost_bench.rs
rename to bootvine/src/boot_view/frame_cost_bench.rs
index f2d1efd..3b8d989 100644
--- a/src/boot_view/frame_cost_bench.rs
+++ b/bootvine/src/boot_view/frame_cost_bench.rs
@@ -9,7 +9,7 @@ use ratatui::{Terminal, backend::TestBackend};
use super::{BootProjection, BootView, project_boot, screen_render_fixtures::ryzen_origin};
use crate::{
boot_model::{BootState, JobResult, Phase, flatten_forest},
- demo_script::boot_test_fixtures::{MS, QueuedUnit, queued_boot, running, waiting},
+ boot_test_fixtures::{MS, QueuedUnit, queued_boot, running, waiting},
screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs},
};
diff --git a/src/boot_view/panel_render_tests.rs b/bootvine/src/boot_view/panel_render_tests.rs
similarity index 82%
rename from src/boot_view/panel_render_tests.rs
rename to bootvine/src/boot_view/panel_render_tests.rs
index 98193fe..a770195 100644
--- a/src/boot_view/panel_render_tests.rs
+++ b/bootvine/src/boot_view/panel_render_tests.rs
@@ -5,8 +5,8 @@ use super::{
screen_render_fixtures::{boot_in_progress, render, render_prompted, screen_lines},
};
use crate::{
- boot_model::{ActiveState, Activity, BootState, HANDOFF_UNIT, JobResult, Phase},
- demo_script::boot_test_fixtures::{MS, queue_unit, queued_boot, running, waiting},
+ boot_model::{ActiveState, Activity, BootState, FailureCause, HANDOFF_UNIT, JobResult, Phase},
+ boot_test_fixtures::{MS, queue_unit, queued_boot, running, waiting},
screen_settings::color_scheme::Colors,
};
@@ -391,3 +391,82 @@ fn the_timeline_keeps_only_the_slowest_finished_runs() {
"{screen}"
);
}
+
+fn explained_nvidia_failure() -> BootState {
+ let mut state = boot_in_progress();
+ state.explain_failure(
+ "nvidia-powerd.service",
+ FailureCause {
+ reason: "exited with status 1".to_owned(),
+ log_lines: vec![
+ "ERROR! Failed to get system power limits".to_owned(),
+ "giving up".to_owned(),
+ ],
+ },
+ );
+ state
+}
+
+#[test]
+fn failures_show_their_reason_and_journal_lines_above_the_timeline() {
+ let lines = render(&explained_nvidia_failure(), 12_400 * MS, 110, 30);
+ let screen = lines.join("\n");
+ let failures = lines
+ .iter()
+ .position(|line| line.contains(" Failures "))
+ .expect("failure panel");
+ let timeline = lines
+ .iter()
+ .position(|line| line.contains(" Timeline "))
+ .expect("timeline panel");
+ assert!(failures < timeline, "{screen}");
+ assert_eq!(
+ lines[failures + 1],
+ "× nvidia-powerd exited with status 1",
+ "{screen}"
+ );
+ assert_eq!(
+ lines[failures + 2],
+ " ERROR! Failed to get system power limits",
+ "{screen}"
+ );
+ assert_eq!(lines[failures + 3], " giving up", "{screen}");
+}
+
+#[test]
+fn failure_lines_are_cut_to_a_narrow_screen() {
+ let lines = render(&explained_nvidia_failure(), 12_400 * MS, 30, 30);
+ let screen = lines.join("\n");
+ let failures = lines
+ .iter()
+ .position(|line| line.contains(" Failures "))
+ .expect("failure panel");
+ assert_eq!(
+ lines[failures + 1],
+ "× nvidia-powerd exited with …",
+ "{screen}"
+ );
+ assert_eq!(
+ lines[failures + 2],
+ " ERROR! Failed to get syst…",
+ "{screen}"
+ );
+}
+
+#[test]
+fn dependency_failures_stay_out_of_the_failure_panel() {
+ let mut state = queued_boot(
+ Phase::Host,
+ 1000 * MS,
+ [
+ waiting("multi-user.target", &["web.service"]),
+ waiting("web.service", &[]),
+ ],
+ );
+ state.finish_job(2, JobResult::Dependency, 2000 * MS);
+ let lines = render(&state, 3000 * MS, 110, 24);
+ let screen = lines.join("\n");
+ assert!(!screen.contains(" Failures "), "{screen}");
+ assert!(screen.contains("[×] web"), "{screen}");
+ assert!(screen.contains("× 1 failed"), "{screen}");
+}
diff --git a/src/boot_view/run_timeline.rs b/bootvine/src/boot_view/run_timeline.rs
similarity index 100%
rename from src/boot_view/run_timeline.rs
rename to bootvine/src/boot_view/run_timeline.rs
diff --git a/src/boot_view/screen_chrome.rs b/bootvine/src/boot_view/screen_chrome.rs
similarity index 100%
rename from src/boot_view/screen_chrome.rs
rename to bootvine/src/boot_view/screen_chrome.rs
diff --git a/src/boot_view/screen_render_fixtures.rs b/bootvine/src/boot_view/screen_render_fixtures.rs
similarity index 98%
rename from src/boot_view/screen_render_fixtures.rs
rename to bootvine/src/boot_view/screen_render_fixtures.rs
index feff27a..ee322a1 100644
--- a/src/boot_view/screen_render_fixtures.rs
+++ b/bootvine/src/boot_view/screen_render_fixtures.rs
@@ -5,7 +5,7 @@ use ratatui::{Terminal, backend::TestBackend, buffer::Buffer};
use super::{BootView, PasswordPrompt, project_boot};
use crate::{
boot_model::{BootState, JobResult, Phase, boot_origin::BootOrigin},
- demo_script::boot_test_fixtures::{MS, queued_boot, running, waiting},
+ boot_test_fixtures::{MS, queued_boot, running, waiting},
screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs},
};
diff --git a/src/boot_view/stage_summary.rs b/bootvine/src/boot_view/stage_summary.rs
similarity index 100%
rename from src/boot_view/stage_summary.rs
rename to bootvine/src/boot_view/stage_summary.rs
diff --git a/src/boot_view/tree_height_fitting.rs b/bootvine/src/boot_view/tree_height_fitting.rs
similarity index 98%
rename from src/boot_view/tree_height_fitting.rs
rename to bootvine/src/boot_view/tree_height_fitting.rs
index f63c22e..16fe8db 100644
--- a/src/boot_view/tree_height_fitting.rs
+++ b/bootvine/src/boot_view/tree_height_fitting.rs
@@ -34,7 +34,7 @@ impl TreeNode {
fn leads_to_running(&self) -> bool {
matches!(
self.row.status,
- RowStatus::Running { .. } | RowStatus::Failed
+ RowStatus::Running { .. } | RowStatus::Failed(_)
) || self.children.iter().any(Self::leads_to_running)
}
@@ -95,7 +95,7 @@ mod tests {
use super::*;
use crate::{
boot_model::{BootState, Phase},
- demo_script::boot_test_fixtures::{
+ boot_test_fixtures::{
activating, nested_boot_sample, queued_boot, running, tree_outline, waiting,
},
};
diff --git a/src/boot_view/tree_render_tests.rs b/bootvine/src/boot_view/tree_render_tests.rs
similarity index 98%
rename from src/boot_view/tree_render_tests.rs
rename to bootvine/src/boot_view/tree_render_tests.rs
index 8990f7b..88879a8 100644
--- a/src/boot_view/tree_render_tests.rs
+++ b/bootvine/src/boot_view/tree_render_tests.rs
@@ -5,7 +5,7 @@ use unicode_width::UnicodeWidthStr;
use super::screen_render_fixtures::{boot_in_progress, chain_boot, described_boot, render};
use crate::{
boot_model::{BootState, JobResult, Phase, UnitTimeouts},
- demo_script::boot_test_fixtures::{MS, queue_unit, queued_boot, running, waiting},
+ boot_test_fixtures::{MS, queue_unit, queued_boot, running, waiting},
};
#[test]
diff --git a/src/boot_view/unit_tree.rs b/bootvine/src/boot_view/unit_tree.rs
similarity index 97%
rename from src/boot_view/unit_tree.rs
rename to bootvine/src/boot_view/unit_tree.rs
index 55389a3..c8f8dda 100644
--- a/src/boot_view/unit_tree.rs
+++ b/bootvine/src/boot_view/unit_tree.rs
@@ -166,7 +166,10 @@ impl UnitTree<'_> {
fn unit_label_style(&self, row: &TreeRow) -> Style {
match row.status {
- RowStatus::Failed => Style::from(self.colors.failed_unit).bold(),
+ RowStatus::Failed(kind) if kind.has_own_cause() => {
+ Style::from(self.colors.failed_unit).bold()
+ }
+ RowStatus::Failed(_) => Style::from(self.colors.failed_unit).dim(),
_ if row.kind == UnitKind::Target => self.colors.target.into(),
RowStatus::Running { .. } => self.colors.running_unit.into(),
RowStatus::Waiting => self.colors.waiting_unit.into(),
@@ -187,7 +190,9 @@ impl UnitTree<'_> {
fn unit_marker(&self, row: &TreeRow) -> Span<'static> {
match row.status {
- RowStatus::Failed => format!("[{}] ", self.glyphs.failed).fg(self.colors.failed_unit),
+ RowStatus::Failed(_) => {
+ format!("[{}] ", self.glyphs.failed).fg(self.colors.failed_unit)
+ }
_ if row.kind == UnitKind::Target => Span::default(),
RowStatus::Running { .. } => {
format!("[{}] ", spinner_at(self.now)).fg(self.colors.running_marker)
diff --git a/src/console_session.rs b/bootvine/src/console_session.rs
similarity index 100%
rename from src/console_session.rs
rename to bootvine/src/console_session.rs
diff --git a/src/console_session/ask_password.rs b/bootvine/src/console_session/ask_password.rs
similarity index 100%
rename from src/console_session/ask_password.rs
rename to bootvine/src/console_session/ask_password.rs
diff --git a/src/console_session/console_palette.rs b/bootvine/src/console_session/console_palette.rs
similarity index 100%
rename from src/console_session/console_palette.rs
rename to bootvine/src/console_session/console_palette.rs
diff --git a/src/console_session/console_takeover.rs b/bootvine/src/console_session/console_takeover.rs
similarity index 100%
rename from src/console_session/console_takeover.rs
rename to bootvine/src/console_session/console_takeover.rs
diff --git a/src/console_session/live_desk.rs b/bootvine/src/console_session/live_desk.rs
similarity index 100%
rename from src/console_session/live_desk.rs
rename to bootvine/src/console_session/live_desk.rs
diff --git a/src/console_session/passphrase_input.rs b/bootvine/src/console_session/passphrase_input.rs
similarity index 100%
rename from src/console_session/passphrase_input.rs
rename to bootvine/src/console_session/passphrase_input.rs
diff --git a/src/console_session/stream_sources.rs b/bootvine/src/console_session/stream_sources.rs
similarity index 100%
rename from src/console_session/stream_sources.rs
rename to bootvine/src/console_session/stream_sources.rs
diff --git a/src/console_session/watch_loop.rs b/bootvine/src/console_session/watch_loop.rs
similarity index 100%
rename from src/console_session/watch_loop.rs
rename to bootvine/src/console_session/watch_loop.rs
diff --git a/src/console_session/watch_screen.rs b/bootvine/src/console_session/watch_screen.rs
similarity index 99%
rename from src/console_session/watch_screen.rs
rename to bootvine/src/console_session/watch_screen.rs
index 270b91d..cb1c59e 100644
--- a/src/console_session/watch_screen.rs
+++ b/bootvine/src/console_session/watch_screen.rs
@@ -273,7 +273,7 @@ mod tests {
use super::*;
use crate::{
boot_model::{ActiveState, Activity, HANDOFF_UNIT},
- demo_script::boot_test_fixtures::{MS, nested_boot_sample, queue_unit, waiting},
+ boot_test_fixtures::{MS, nested_boot_sample, queue_unit, waiting},
};
#[derive(Default)]
diff --git a/src/lib.rs b/bootvine/src/lib.rs
similarity index 78%
rename from src/lib.rs
rename to bootvine/src/lib.rs
index 1a5c142..7ab6ec2 100644
--- a/src/lib.rs
+++ b/bootvine/src/lib.rs
@@ -1,7 +1,8 @@
pub mod boot_model;
+#[cfg(test)]
+mod boot_test_fixtures;
pub mod boot_view;
pub mod console_session;
-pub mod demo_script;
pub mod screen_settings;
pub mod system_install;
pub mod systemd_link;
diff --git a/src/main.rs b/bootvine/src/main.rs
similarity index 100%
rename from src/main.rs
rename to bootvine/src/main.rs
diff --git a/src/screen_settings.rs b/bootvine/src/screen_settings.rs
similarity index 100%
rename from src/screen_settings.rs
rename to bootvine/src/screen_settings.rs
diff --git a/src/screen_settings/color_scheme.rs b/bootvine/src/screen_settings/color_scheme.rs
similarity index 88%
rename from src/screen_settings/color_scheme.rs
rename to bootvine/src/screen_settings/color_scheme.rs
index 0fdbcfe..be7f0c3 100644
--- a/src/screen_settings/color_scheme.rs
+++ b/bootvine/src/screen_settings/color_scheme.rs
@@ -8,6 +8,7 @@ pub struct Colors {
pub stages: StageColors,
pub tree: TreeColors,
pub timeline: TimelineColors,
+ pub failures: FailureColors,
pub footer: FooterColors,
pub password: PasswordColors,
}
@@ -122,6 +123,30 @@ impl Default for TimelineColors {
}
}
+#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
+#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
+pub struct FailureColors {
+ pub rule: Color,
+ pub title: Color,
+ pub unit: Color,
+ pub reason: Color,
+ pub log: Color,
+ pub overflow: Color,
+}
+
+impl Default for FailureColors {
+ fn default() -> Self {
+ Self {
+ rule: Color::DarkGray,
+ title: Color::LightRed,
+ unit: Color::LightRed,
+ reason: Color::White,
+ log: Color::Gray,
+ overflow: Color::DarkGray,
+ }
+ }
+}
+
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
pub struct FooterColors {
diff --git a/src/screen_settings/config_file.rs b/bootvine/src/screen_settings/config_file.rs
similarity index 100%
rename from src/screen_settings/config_file.rs
rename to bootvine/src/screen_settings/config_file.rs
diff --git a/src/screen_settings/font_glyphs.rs b/bootvine/src/screen_settings/font_glyphs.rs
similarity index 100%
rename from src/screen_settings/font_glyphs.rs
rename to bootvine/src/screen_settings/font_glyphs.rs
diff --git a/src/system_install.rs b/bootvine/src/system_install.rs
similarity index 100%
rename from src/system_install.rs
rename to bootvine/src/system_install.rs
diff --git a/src/system_install/install_error.rs b/bootvine/src/system_install/install_error.rs
similarity index 100%
rename from src/system_install/install_error.rs
rename to bootvine/src/system_install/install_error.rs
diff --git a/src/system_install/install_files.rs b/bootvine/src/system_install/install_files.rs
similarity index 100%
rename from src/system_install/install_files.rs
rename to bootvine/src/system_install/install_files.rs
diff --git a/src/systemd_link.rs b/bootvine/src/systemd_link.rs
similarity index 85%
rename from src/systemd_link.rs
rename to bootvine/src/systemd_link.rs
index dc87d22..466b59c 100644
--- a/src/systemd_link.rs
+++ b/bootvine/src/systemd_link.rs
@@ -1,4 +1,5 @@
pub mod boot_feed;
+mod journal_tail;
pub mod link_error;
pub mod monotonic_clock;
pub mod switch_root;
diff --git a/src/systemd_link/boot_feed.rs b/bootvine/src/systemd_link/boot_feed.rs
similarity index 76%
rename from src/systemd_link/boot_feed.rs
rename to bootvine/src/systemd_link/boot_feed.rs
index 05d4625..05f3d9d 100644
--- a/src/systemd_link/boot_feed.rs
+++ b/bootvine/src/systemd_link/boot_feed.rs
@@ -1,5 +1,5 @@
use std::{
- collections::HashMap,
+ collections::{HashMap, HashSet},
iter::once,
process,
time::{Duration, Instant},
@@ -10,12 +10,16 @@ use futures::{Stream, StreamExt, stream};
use tokio::time::sleep;
use crate::{
- boot_model::{Activity, BootChange, BootState, HANDOFF_UNIT, JobKind, Phase, UnitFacts},
+ boot_model::{
+ ActiveState, Activity, BootChange, BootState, FailureCause, HANDOFF_UNIT, JobKind,
+ JobResult, Phase, UnitFacts,
+ },
console_session::{
stream_sources::{BACKGROUND_CHECK_INTERVAL, CarriedItem, unfold_carrying},
watch_screen::ScreenInput,
},
systemd_link::{
+ journal_tail::recent_unit_messages,
link_error::Error,
monotonic_clock::monotonic_now,
switch_root::Sysroot,
@@ -27,6 +31,12 @@ use crate::{
};
const RECONNECT_PATIENCE: Duration = Duration::from_secs(60);
+const JOURNAL_SETTLING_WAITS: [Duration; 3] = [
+ Duration::from_millis(200),
+ Duration::from_millis(300),
+ Duration::from_millis(500),
+];
+const LOG_LINES_KEPT: usize = 6;
const SWITCH_ROOT_UNIT: &str = "initrd-switch-root.service";
const SHUTDOWN_ROOTS: [&str; 5] = [
"poweroff.target",
@@ -108,6 +118,8 @@ struct BootTracker {
target: RootRequest,
phase: Phase,
unit_paths: HashMap, String>,
+ explained_failures: HashSet,
+ units_in_failed_state: HashSet,
root_switch: RootSwitch,
}
@@ -131,6 +143,8 @@ impl BusFeed {
target,
phase,
unit_paths: HashMap::new(),
+ explained_failures: HashSet::new(),
+ units_in_failed_state: HashSet::new(),
root_switch: RootSwitch::NotQueued,
},
}
@@ -196,6 +210,8 @@ impl BusFeed {
}
tracker.root_switch = RootSwitch::NotQueued;
tracker.unit_paths.clear();
+ tracker.explained_failures.clear();
+ tracker.units_in_failed_state.clear();
tracker.phase = Phase::Host;
self.link = Link::connecting(ConnectAttempt::Again);
vec![ScreenInput::Boot(vec![BootChange::SwitchRoot { at }])]
@@ -395,20 +411,68 @@ impl BootTracker {
Signal::JobNew { id, job, unit } => {
self.queue_new_job(connection, id, &job, unit, at).await
}
- Signal::JobRemoved { id, result } => vec![BootChange::FinishJob { id, result, at }],
- Signal::UnitChanged { path, activity } => self
- .unit_paths
- .get(&path)
- .map(|unit| BootChange::UpdateActivity {
- unit: unit.clone(),
- activity,
- })
- .into_iter()
- .collect(),
+ Signal::JobRemoved { id, unit, result } => {
+ let explanation = match result {
+ JobResult::Failed => self.explain_failure(connection, unit, "failed").await,
+ JobResult::Timeout => self.explain_failure(connection, unit, "timed out").await,
+ _ => None,
+ };
+ once(BootChange::FinishJob { id, result, at })
+ .chain(explanation)
+ .collect()
+ }
+ Signal::UnitChanged { path, activity } => {
+ let Some(unit) = self.unit_paths.get(&path).cloned() else {
+ return Vec::new();
+ };
+ let explanation = if self.enters_failed_state(&unit, activity) {
+ self.explain_failure(connection, unit.clone(), "failed")
+ .await
+ } else {
+ None
+ };
+ once(BootChange::UpdateActivity { unit, activity })
+ .chain(explanation)
+ .collect()
+ }
Signal::BootFinished => self.boot_finished(),
}
}
+ fn enters_failed_state(&mut self, unit: &str, activity: Activity) -> bool {
+ match activity.state {
+ Some(ActiveState::Failed) => self.units_in_failed_state.insert(unit.to_owned()),
+ Some(_) => {
+ self.units_in_failed_state.remove(unit);
+ false
+ }
+ None => false,
+ }
+ }
+
+ async fn explain_failure(
+ &mut self,
+ connection: &mut BusConnection,
+ unit: String,
+ fallback_reason: &str,
+ ) -> Option {
+ if !self.unit_paths.values().any(|known| *known == unit) {
+ return None;
+ }
+ self.explained_failures.insert(unit.clone());
+ let reason = connection
+ .failure_reason(&unit)
+ .await
+ .ok()
+ .flatten()
+ .unwrap_or_else(|| fallback_reason.to_owned());
+ let log_lines = settled_unit_messages(&unit).await;
+ Some(BootChange::ExplainFailure {
+ unit,
+ cause: FailureCause { reason, log_lines },
+ })
+ }
+
fn boot_finished(&self) -> Vec {
(self.phase == Phase::Host)
.then_some(BootChange::BootFinished)
@@ -440,6 +504,17 @@ impl BootTracker {
}
}
+async fn settled_unit_messages(unit: &str) -> Vec {
+ for settling in JOURNAL_SETTLING_WAITS {
+ sleep(settling).await;
+ let log_lines = recent_unit_messages(unit.to_owned(), LOG_LINES_KEPT).await;
+ if !log_lines.is_empty() {
+ return log_lines;
+ }
+ }
+ Vec::new()
+}
+
pub fn bus_inputs(
phase: Phase,
scope: Scope,
@@ -454,3 +529,38 @@ pub fn bus_inputs(
})
.flat_map(stream::iter)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn host_tracker() -> BootTracker {
+ BootTracker {
+ scope: Scope::System,
+ target: RootRequest::ManagerDefault,
+ phase: Phase::Host,
+ unit_paths: HashMap::new(),
+ explained_failures: HashSet::new(),
+ units_in_failed_state: HashSet::new(),
+ root_switch: RootSwitch::NotQueued,
+ }
+ }
+
+ fn in_state(state: ActiveState) -> Activity {
+ Activity {
+ state: Some(state),
+ ..Activity::default()
+ }
+ }
+
+ #[test]
+ fn only_entering_the_failed_state_asks_for_a_fresh_explanation() {
+ let mut tracker = host_tracker();
+ let unit = "http-listener.service";
+ assert!(tracker.enters_failed_state(unit, in_state(ActiveState::Failed)));
+ assert!(!tracker.enters_failed_state(unit, in_state(ActiveState::Failed)));
+ assert!(!tracker.enters_failed_state(unit, Activity::default()));
+ assert!(!tracker.enters_failed_state(unit, in_state(ActiveState::Activating)));
+ assert!(tracker.enters_failed_state(unit, in_state(ActiveState::Failed)));
+ }
+}
diff --git a/bootvine/src/systemd_link/journal_tail.rs b/bootvine/src/systemd_link/journal_tail.rs
new file mode 100644
index 0000000..7b871a5
--- /dev/null
+++ b/bootvine/src/systemd_link/journal_tail.rs
@@ -0,0 +1,132 @@
+use std::{io, str::Chars};
+
+use systemd::{
+ id128::Id128,
+ journal::{Journal, OpenOptions},
+};
+use tokio::task::spawn_blocking;
+
+const UNIT_FIELDS: [&str; 4] = ["_SYSTEMD_UNIT", "UNIT", "_SYSTEMD_USER_UNIT", "USER_UNIT"];
+const MANAGER_SUMMARY_MESSAGE_IDS: [&str; 10] = [
+ "7d4958e842da4a758f6c1cdc7b36dcc5",
+ "39f53479d3a045ac8e11786248231fbf",
+ "7ad2d189f7e94e70a38c781354912448",
+ "5eb03494b6584870a536b337290809b3",
+ "be02cf6855d2428ba40df7e9d022f03d",
+ "de5b426a63be47a7b6ac3eaac82e2f6f",
+ "9d1aaa27d60140bd96365438aad20286",
+ "ae8f7b866b0347b9af31fe1c80b127c0",
+ "d9b373ed55a64feb8242e02dbe79a49c",
+ "98e322203f7a4ed290d09fe03c09fe15",
+];
+const ENTRIES_SCANNED: usize = 200;
+const ESCAPE: char = '\u{1b}';
+
+pub async fn recent_unit_messages(unit: String, wanted: usize) -> Vec {
+ spawn_blocking(move || {
+ read_recent_messages(&unit, wanted).unwrap_or_else(|error| {
+ eprintln!("bootvine: reading the journal of {unit}: {error}");
+ Vec::new()
+ })
+ })
+ .await
+ .unwrap_or_default()
+}
+
+fn read_recent_messages(unit: &str, wanted: usize) -> io::Result> {
+ let mut journal = OpenOptions::default().open()?;
+ match_unit_in_this_boot(&mut journal, unit)?;
+ journal.seek_tail()?;
+ let mut newest_first = Vec::new();
+ let mut scanned = 0;
+ while newest_first.len() < wanted
+ && scanned < ENTRIES_SCANNED
+ && journal.previous().is_ok_and(|moved| moved > 0)
+ {
+ scanned += 1;
+ if is_manager_summary(&mut journal).unwrap_or(true) {
+ continue;
+ }
+ if let Ok(Some(message)) = entry_message(&mut journal) {
+ newest_first.push(message);
+ }
+ }
+ newest_first.reverse();
+ Ok(newest_first)
+}
+
+fn match_unit_in_this_boot(journal: &mut Journal, unit: &str) -> io::Result<()> {
+ UNIT_FIELDS.iter().try_for_each(|field| {
+ journal.match_add(field, unit)?.match_or()?;
+ Ok::<_, io::Error>(())
+ })?;
+ journal
+ .match_and()?
+ .match_add("_BOOT_ID", Id128::from_boot()?.to_string())?;
+ Ok(())
+}
+
+fn field_text(journal: &mut Journal, field: &str) -> io::Result