refactor: drop single-use wrappers in the boot model, view and installer

This commit is contained in:
Willem Vanhulle committed 2026-10-25 13:55:27 +01:00
1 parent f8f1b54d75
commit d3fcd6f085
11 files changed
+121 -181

No files matched your search

-2
View File
@@ -1,6 +1,5 @@
mod boot_change; mod boot_change;
pub mod boot_origin; pub mod boot_origin;
mod boot_projection;
mod job_ingestion; mod job_ingestion;
mod reached_milestones; mod reached_milestones;
mod unit_facts; mod unit_facts;
@@ -10,7 +9,6 @@ use std::{collections::HashMap, time::Duration};
pub use self::{ pub use self::{
boot_change::BootChange, boot_change::BootChange,
boot_projection::BootProjection,
reached_milestones::MilestoneRow, reached_milestones::MilestoneRow,
unit_facts::{ActiveState, Activity, JobKind, JobResult, UnitFacts, UnitKind, UnitTimeouts}, unit_facts::{ActiveState, Activity, JobKind, JobResult, UnitFacts, UnitKind, UnitTimeouts},
waiting_tree::{RowStatus, TreeNode, TreeRow, flatten_forest}, waiting_tree::{RowStatus, TreeNode, TreeRow, flatten_forest},
+6 -2
View File
@@ -43,12 +43,16 @@ impl BootState {
BootChange::QueueJob { id, unit, kind, at } => self.queue_job(id, &unit, kind, at), 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::FinishJob { id, result, at } => self.finish_job(id, result, at),
BootChange::SetRoot(root) => self.set_root(root), BootChange::SetRoot(root) => self.set_root(root),
BootChange::SetHandoff(unit) => self.set_handoff(unit), BootChange::SetHandoff(unit) => {
if let Some(handoff) = &mut self.handoff_unit {
*handoff = unit;
}
}
BootChange::SetOrigin(origin) => self.origin = origin, BootChange::SetOrigin(origin) => self.origin = origin,
BootChange::SwitchRoot { at } => self.switch_root(at), BootChange::SwitchRoot { at } => self.switch_root(at),
BootChange::ForgetJobs => self.forget_jobs(), BootChange::ForgetJobs => self.forget_jobs(),
BootChange::ManagerExited { at } => self.manager_exited_at = Some(at), BootChange::ManagerExited { at } => self.manager_exited_at = Some(at),
BootChange::BootFinished => self.mark_boot_finished(), BootChange::BootFinished => self.boot_finished = true,
} }
} }
} }
-21
View File
@@ -1,21 +0,0 @@
use std::time::Duration;
use super::{BootState, MilestoneRow, Tally, TreeNode};
#[derive(Clone, Debug)]
pub struct BootProjection {
pub forest: Vec<TreeNode>,
pub milestones: Vec<MilestoneRow>,
pub tally: Tally,
}
impl BootState {
#[must_use]
pub fn project(&self, finished_since: Duration) -> BootProjection {
BootProjection {
forest: self.waiting_forest(finished_since),
milestones: self.milestones(),
tally: self.tally(),
}
}
}
+12 -27
View File
@@ -103,16 +103,6 @@ impl BootState {
} }
} }
pub fn set_handoff(&mut self, unit: String) {
if self.handoff_unit.is_some() {
self.handoff_unit = Some(unit);
}
}
pub fn mark_boot_finished(&mut self) {
self.boot_finished = true;
}
pub fn track_unit(&mut self, facts: UnitFacts, activity: Activity) { pub fn track_unit(&mut self, facts: UnitFacts, activity: Activity) {
let record = self let record = self
.units .units
@@ -133,21 +123,20 @@ impl BootState {
} }
pub fn queue_job(&mut self, id: u32, unit: &str, kind: JobKind, at: Duration) { pub fn queue_job(&mut self, id: u32, unit: &str, kind: JobKind, at: Duration) {
self.enqueue(id, unit, kind, at); if self.enqueue(id, unit, kind, at)
if kind == JobKind::BringsUp && kind == JobKind::BringsUp
&& self.jobs.get(&id).is_some_and(|tracked| tracked == unit)
&& self.root == Root::Awaiting(unit.to_owned()) && self.root == Root::Awaiting(unit.to_owned())
{ {
self.root = Root::Queued(unit.to_owned()); self.root = Root::Queued(unit.to_owned());
} }
} }
fn enqueue(&mut self, id: u32, unit: &str, kind: JobKind, at: Duration) { fn enqueue(&mut self, id: u32, unit: &str, kind: JobKind, at: Duration) -> bool {
if self.jobs.contains_key(&id) { if let Some(tracked) = self.jobs.get(&id) {
return; return tracked == unit;
} }
let Some(record) = self.units.get_mut(unit) else { let Some(record) = self.units.get_mut(unit) else {
return; return false;
}; };
record.progress = Progress::Pending(PendingJob { record.progress = Progress::Pending(PendingJob {
id, id,
@@ -155,6 +144,7 @@ impl BootState {
kind, kind,
}); });
self.jobs.insert(id, unit.to_owned()); self.jobs.insert(id, unit.to_owned());
true
} }
pub fn finish_job(&mut self, id: u32, result: JobResult, at: Duration) { pub fn finish_job(&mut self, id: u32, result: JobResult, at: Duration) {
@@ -252,11 +242,6 @@ impl BootState {
}) })
} }
#[must_use]
pub fn display_manager_started(&self) -> bool {
self.started_display_manager().is_some()
}
#[must_use] #[must_use]
pub fn tally(&self) -> Tally { pub fn tally(&self) -> Tally {
let carried = Tally { let carried = Tally {
@@ -287,7 +272,7 @@ impl BootState {
mod tests { mod tests {
use super::*; use super::*;
use crate::{ use crate::{
boot_model::{RowStatus, UnitTimeouts}, boot_model::{BootChange, RowStatus, UnitTimeouts},
demo_script::boot_test_fixtures::{ demo_script::boot_test_fixtures::{
MS, activating, facts, nested_boot_sample as sample, queue_unit, queued_boot, running, MS, activating, facts, nested_boot_sample as sample, queue_unit, queued_boot, running,
waiting, waiting_rows, waiting, waiting_rows,
@@ -335,24 +320,24 @@ mod tests {
fn display_manager_activation_does_not_complete_the_boot() { fn display_manager_activation_does_not_complete_the_boot() {
let mut state = sample(); let mut state = sample();
queue_unit(&mut state, 20, waiting(HANDOFF_UNIT, &[]), 500 * MS); queue_unit(&mut state, 20, waiting(HANDOFF_UNIT, &[]), 500 * MS);
assert!(!state.display_manager_started()); assert_eq!(state.started_display_manager(), None);
state.update_activity(HANDOFF_UNIT, activating(6000 * MS)); state.update_activity(HANDOFF_UNIT, activating(6000 * MS));
assert!(!state.is_complete()); assert!(!state.is_complete());
assert!(state.display_manager_started()); assert_eq!(state.started_display_manager(), Some(HANDOFF_UNIT));
} }
#[test] #[test]
fn boot_finished_hands_the_console_over() { fn boot_finished_hands_the_console_over() {
let mut state = sample(); let mut state = sample();
queue_unit(&mut state, 20, waiting(HANDOFF_UNIT, &[]), 500 * MS); queue_unit(&mut state, 20, waiting(HANDOFF_UNIT, &[]), 500 * MS);
state.mark_boot_finished(); state.apply(BootChange::BootFinished);
assert!(state.is_complete()); assert!(state.is_complete());
} }
#[test] #[test]
fn boot_finished_is_ignored_in_the_initrd() { fn boot_finished_is_ignored_in_the_initrd() {
let mut state = BootState::new(Phase::Initrd); let mut state = BootState::new(Phase::Initrd);
state.mark_boot_finished(); state.apply(BootChange::BootFinished);
assert!(!state.is_complete()); assert!(!state.is_complete());
} }
+28 -39
View File
@@ -10,32 +10,11 @@ pub struct MilestoneRow {
pub reached_at: Duration, pub reached_at: Duration,
} }
struct ReachedMilestone<'a> { struct MilestoneCursor {
target: &'a str,
reached_at: Duration,
}
struct MilestoneWalk {
rows: Vec<MilestoneRow>,
previous: Duration, previous: Duration,
consumed: usize, consumed: usize,
} }
impl MilestoneWalk {
fn advance(mut self, reached: &ReachedMilestone, succeeded_sorted: &[Duration]) -> Self {
let upto = succeeded_sorted.partition_point(|at| *at <= reached.reached_at);
self.rows.push(MilestoneRow {
label: reached.target.to_owned(),
finished_units: upto.saturating_sub(self.consumed),
started_at: self.previous.min(reached.reached_at),
reached_at: reached.reached_at,
});
self.consumed = self.consumed.max(upto);
self.previous = reached.reached_at;
self
}
}
impl BootState { impl BootState {
fn milestone_reached_at(&self, target: &str) -> Option<Duration> { fn milestone_reached_at(&self, target: &str) -> Option<Duration> {
let record = self.units.get(target)?; let record = self.units.get(target)?;
@@ -59,31 +38,41 @@ impl BootState {
}) })
.collect(); .collect();
succeeded.sort_unstable(); succeeded.sort_unstable();
let start = MilestoneWalk { let start = MilestoneCursor {
rows: self
.finished_stages
.iter()
.map(|stage| MilestoneRow {
label: stage.label.to_owned(),
finished_units: stage.finished_units,
started_at: stage.started_at,
reached_at: stage.reached_at,
})
.collect(),
previous: self previous: self
.finished_stages .finished_stages
.last() .last()
.map_or(self.origin, |stage| stage.reached_at), .map_or(self.origin, |stage| stage.reached_at),
consumed: 0, consumed: 0,
}; };
self.milestone_targets let reached_rows = self
.milestone_targets
.iter() .iter()
.filter_map(|target| { .scan(start, |cursor, target| {
self.milestone_reached_at(target) Some(self.milestone_reached_at(target).map(|reached_at| {
.map(|reached_at| ReachedMilestone { target, reached_at }) let upto = succeeded.partition_point(|at| *at <= reached_at);
let row = MilestoneRow {
label: target.clone(),
finished_units: upto.saturating_sub(cursor.consumed),
started_at: cursor.previous.min(reached_at),
reached_at,
};
cursor.consumed = cursor.consumed.max(upto);
cursor.previous = reached_at;
row
}))
}) })
.fold(start, |walk, reached| walk.advance(&reached, &succeeded)) .flatten();
.rows self.finished_stages
.iter()
.map(|stage| MilestoneRow {
label: stage.label.to_owned(),
finished_units: stage.finished_units,
started_at: stage.started_at,
reached_at: stage.reached_at,
})
.chain(reached_rows)
.collect()
} }
} }
+10 -15
View File
@@ -113,25 +113,20 @@ impl UnitKind {
Self::Scope => Some("Scope"), Self::Scope => Some("Scope"),
} }
} }
fn labelled_by_description(self) -> bool {
matches!(
self,
Self::Device | Self::Mount | Self::Swap | Self::Automount
)
}
} }
fn labelled_by_description(facts: &UnitFacts) -> bool { fn description_label(facts: &UnitFacts) -> Option<&String> {
facts.description.is_some() && UnitKind::of(&facts.name).labelled_by_description() facts.description.as_ref().filter(|_| {
matches!(
UnitKind::of(&facts.name),
UnitKind::Device | UnitKind::Mount | UnitKind::Swap | UnitKind::Automount
)
})
} }
pub(super) fn display_label(facts: &UnitFacts) -> String { pub(super) fn display_label(facts: &UnitFacts) -> String {
if labelled_by_description(facts) { if let Some(description) = description_label(facts) {
return facts return description.clone();
.description
.clone()
.unwrap_or_else(|| facts.name.clone());
} }
match UnitKind::of(&facts.name) { match UnitKind::of(&facts.name) {
UnitKind::Target | UnitKind::Other => facts.name.clone(), UnitKind::Target | UnitKind::Other => facts.name.clone(),
@@ -146,7 +141,7 @@ pub(super) fn summary(facts: &UnitFacts) -> Option<String> {
let repeats_the_name = facts.description.as_deref().is_some_and(|description| { let repeats_the_name = facts.description.as_deref().is_some_and(|description| {
description == facts.name || description.eq_ignore_ascii_case(&display_label(facts)) description == facts.name || description.eq_ignore_ascii_case(&display_label(facts))
}); });
if labelled_by_description(facts) || repeats_the_name { if description_label(facts).is_some() || repeats_the_name {
return None; return None;
} }
facts.description.clone() facts.description.clone()
+12 -3
View File
@@ -35,7 +35,7 @@ use self::{
}; };
use crate::{ use crate::{
boot_model::{ boot_model::{
BootProjection, BootState, RowStatus, TreeRow, UnitKind, boot_origin::BootOrigin, BootState, MilestoneRow, RowStatus, TreeNode, TreeRow, UnitKind, boot_origin::BootOrigin,
flatten_forest, flatten_forest,
}, },
screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs}, screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs},
@@ -136,7 +136,7 @@ impl Widget for BootView<'_> {
}; };
let timeline = self.timeline(&all_rows); let timeline = self.timeline(&all_rows);
let footer = Footer { let footer = Footer {
tally: self.projection.tally, tally: self.state.tally(),
colors: &self.colors.footer, colors: &self.colors.footer,
glyphs: self.glyphs, glyphs: self.glyphs,
}; };
@@ -218,9 +218,18 @@ impl Heights {
} }
} }
#[derive(Clone, Debug)]
pub struct BootProjection {
pub forest: Vec<TreeNode>,
pub milestones: Vec<MilestoneRow>,
}
#[must_use] #[must_use]
pub fn project_boot(state: &BootState, timing: &Timing, now: Duration) -> BootProjection { pub fn project_boot(state: &BootState, timing: &Timing, now: Duration) -> BootProjection {
state.project(now.saturating_sub(timing.keep_finished_units_for)) BootProjection {
forest: state.waiting_forest(now.saturating_sub(timing.keep_finished_units_for)),
milestones: state.milestones(),
}
} }
fn rule(color: Color, left: Line<'static>) -> Block<'static> { fn rule(color: Color, left: Line<'static>) -> Block<'static> {
+2 -2
View File
@@ -6,9 +6,9 @@ use std::{
use ratatui::{Terminal, backend::TestBackend}; use ratatui::{Terminal, backend::TestBackend};
use super::{BootView, project_boot, screen_render_fixtures::ryzen_origin}; use super::{BootProjection, BootView, project_boot, screen_render_fixtures::ryzen_origin};
use crate::{ use crate::{
boot_model::{BootProjection, BootState, JobResult, Phase, flatten_forest}, boot_model::{BootState, JobResult, Phase, flatten_forest},
demo_script::boot_test_fixtures::{MS, QueuedUnit, queued_boot, running, waiting}, demo_script::boot_test_fixtures::{MS, QueuedUnit, queued_boot, running, waiting},
screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs}, screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs},
}; };
+3 -8
View File
@@ -9,8 +9,8 @@ use ratatui::{
}; };
use crate::{ use crate::{
boot_model::{BootChange, BootProjection, BootState, boot_origin::BootOrigin}, boot_model::{BootChange, BootState, boot_origin::BootOrigin},
boot_view::{BootView, PasswordPrompt, project_boot}, boot_view::{BootProjection, BootView, PasswordPrompt, project_boot},
console_session::console_palette::ConsoleLook, console_session::console_palette::ConsoleLook,
screen_settings::{color_scheme::Colors, config_file::Timing}, screen_settings::{color_scheme::Colors, config_file::Timing},
systemd_link::{link_error::Error, monotonic_clock::monotonic_now}, systemd_link::{link_error::Error, monotonic_clock::monotonic_now},
@@ -162,12 +162,7 @@ impl<Desk: ConsoleDesk> WatchScreen<Desk> {
if self.state.phase != phase_before { if self.state.phase != phase_before {
self.origin = (self.read_origin)(); self.origin = (self.read_origin)();
} }
if self.state.display_manager_started() { if let Some(display_manager) = self.state.started_display_manager() {
let display_manager = self
.state
.handoff_unit
.as_deref()
.unwrap_or("display manager");
self.desk self.desk
.begin_handover(display_manager, now + self.timing.wait_for_display_manager); .begin_handover(display_manager, now + self.timing.wait_for_display_manager);
} else if self.state.is_complete() { } else if self.state.is_complete() {
+8 -25
View File
@@ -92,8 +92,14 @@ enum DefaultsFormat {
fn main() -> ExitCode { fn main() -> ExitCode {
let cli = Cli::parse(); let cli = Cli::parse();
match cli.command { match cli.command {
Some(Command::Defaults(options)) => print_defaults(options.format), Some(Command::Defaults(options)) => report_outcome(
Some(Command::Check(options)) => check_config_file(&options), render_defaults(options.format).map(|text| println!("{}", text.trim_end())),
),
Some(Command::Check(options)) => report_outcome(
read_config_file(&options.path)
.map(|_| ())
.map_err(|error| format!("{}: {error}", options.path.display())),
),
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)),
None => watch_boot(cli.watch), None => watch_boot(cli.watch),
@@ -118,29 +124,6 @@ fn render_defaults(format: DefaultsFormat) -> Result<String, Box<dyn Error>> {
}) })
} }
fn print_defaults(format: DefaultsFormat) -> ExitCode {
match render_defaults(format) {
Ok(text) => {
println!("{}", text.trim_end());
ExitCode::SUCCESS
}
Err(error) => {
eprintln!("bootvine: {error}");
ExitCode::FAILURE
}
}
}
fn check_config_file(options: &CheckOptions) -> ExitCode {
match read_config_file(&options.path) {
Ok(_) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("bootvine: {}: {error}", options.path.display());
ExitCode::FAILURE
}
}
}
fn watch_boot(options: WatchOptions) -> ExitCode { fn watch_boot(options: WatchOptions) -> ExitCode {
let config = match read_config_file(&options.config) { let config = match read_config_file(&options.config) {
Ok(config) => config, Ok(config) => config,
+40 -37
View File
@@ -38,6 +38,8 @@ 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 =
include_str!("../../system-files/mkinitcpio/install/sd-bootvine"); include_str!("../../system-files/mkinitcpio/install/sd-bootvine");
const INITRD_GENERATORS: [InitrdGenerator; 2] =
[InitrdGenerator::Dracut, InitrdGenerator::Mkinitcpio];
#[derive(Args)] #[derive(Args)]
pub struct InstallTarget { pub struct InstallTarget {
@@ -114,16 +116,41 @@ impl InstallTarget {
fn every_installed_path(&self) -> Vec<PathBuf> { fn every_installed_path(&self) -> Vec<PathBuf> {
once(self.binary_path()) once(self.binary_path())
.chain(unit_names().map(|unit| self.unit_path(unit))) .chain(unit_files(self).map(|file| file.destination))
.chain([ .chain(
Path::new(DRACUT_MODULE_DIR).join("module-setup.sh"), INITRD_GENERATORS
PathBuf::from(DRACUT_CONF), .into_iter()
PathBuf::from(MKINITCPIO_HOOK), .flat_map(initrd_hook_files)
]) .map(|file| file.destination),
)
.collect() .collect()
} }
} }
impl InitrdGenerator {
fn install_hint(self) -> Option<&'static str> {
match self {
Self::None => None,
Self::Dracut => Some("rebuild the initramfs: sudo dracut --force"),
Self::Mkinitcpio => Some(
"add sd-bootvine after systemd in HOOKS in /etc/mkinitcpio.conf, then run: sudo \
mkinitcpio -P",
),
}
}
fn removal_hint(self) -> Option<&'static str> {
match self {
Self::None => None,
Self::Dracut => Some("rebuild the initramfs without bootvine: sudo dracut --force"),
Self::Mkinitcpio => Some(
"remove sd-bootvine from HOOKS in /etc/mkinitcpio.conf, then run: sudo mkinitcpio \
-P",
),
}
}
}
fn running_binary() -> Result<PathBuf, InstallError> { fn running_binary() -> Result<PathBuf, InstallError> {
env::current_exe().map_err(|source| InstallError::File { env::current_exe().map_err(|source| InstallError::File {
path: PathBuf::from("/proc/self/exe"), path: PathBuf::from("/proc/self/exe"),
@@ -131,14 +158,10 @@ fn running_binary() -> Result<PathBuf, InstallError> {
}) })
} }
fn is_running_binary(path: &Path, running: &Path) -> bool {
fs::canonicalize(path).is_ok_and(|resolved| resolved == running)
}
fn binary_file(target: &InstallTarget) -> Result<Option<InstalledFile>, InstallError> { fn binary_file(target: &InstallTarget) -> Result<Option<InstalledFile>, InstallError> {
let running = running_binary()?; let running = running_binary()?;
let destination = target.binary_path(); let destination = target.binary_path();
if is_running_binary(&target.staged(&destination), &running) { if fs::canonicalize(target.staged(&destination)).is_ok_and(|resolved| resolved == running) {
return Ok(None); return Ok(None);
} }
let contents = fs::read(&running).map_err(|source| InstallError::File { let contents = fs::read(&running).map_err(|source| InstallError::File {
@@ -244,17 +267,6 @@ fn rerun_with_sudo() -> Result<(), InstallError> {
) )
} }
fn print_initramfs_hint(initrd: InitrdGenerator) {
match initrd {
InitrdGenerator::None => {}
InitrdGenerator::Dracut => println!("rebuild the initramfs: sudo dracut --force"),
InitrdGenerator::Mkinitcpio => println!(
"add sd-bootvine after systemd in HOOKS in /etc/mkinitcpio.conf, then run: sudo \
mkinitcpio -P"
),
}
}
pub fn install_files(options: &InstallOptions) -> Result<(), InstallError> { pub fn install_files(options: &InstallOptions) -> Result<(), InstallError> {
let target = &options.target; let target = &options.target;
if target.needs_sudo() { if target.needs_sudo() {
@@ -270,25 +282,15 @@ pub fn install_files(options: &InstallOptions) -> Result<(), InstallError> {
if !options.no_enable { if !options.no_enable {
systemctl(once("enable").chain(unit_names()))?; systemctl(once("enable").chain(unit_names()))?;
} }
print_initramfs_hint(options.initrd); if let Some(hint) = options.initrd.install_hint() {
println!("{hint}");
}
} }
Ok(()) Ok(())
} }
fn print_initramfs_removal_hint(initrd: InitrdGenerator) {
match initrd {
InitrdGenerator::None => {}
InitrdGenerator::Dracut => {
println!("rebuild the initramfs without bootvine: sudo dracut --force");
}
InitrdGenerator::Mkinitcpio => println!(
"remove sd-bootvine from HOOKS in /etc/mkinitcpio.conf, then run: sudo mkinitcpio -P"
),
}
}
fn installed_initrd_hooks(target: &InstallTarget) -> Vec<InitrdGenerator> { fn installed_initrd_hooks(target: &InstallTarget) -> Vec<InitrdGenerator> {
[InitrdGenerator::Dracut, InitrdGenerator::Mkinitcpio] INITRD_GENERATORS
.into_iter() .into_iter()
.filter(|generator| { .filter(|generator| {
initrd_hook_files(*generator) initrd_hook_files(*generator)
@@ -330,7 +332,8 @@ pub fn uninstall_files(options: &UninstallOptions) -> Result<(), InstallError> {
systemctl(["daemon-reload"])?; systemctl(["daemon-reload"])?;
removed_initrd_hooks removed_initrd_hooks
.into_iter() .into_iter()
.for_each(print_initramfs_removal_hint); .filter_map(InitrdGenerator::removal_hint)
.for_each(|hint| println!("{hint}"));
} }
Ok(()) Ok(())
} }