diff --git a/examples/boot.rs b/examples/boot.rs index 23a670c..db216bd 100644 --- a/examples/boot.rs +++ b/examples/boot.rs @@ -140,8 +140,8 @@ const HOST: &[Step] = &[ ), ]; -fn description(unit: &str) -> &'static str { - match unit { +fn description(unit: &str) -> Option<&'static str> { + let description = match unit { "initrd.target" => "Initrd Default Target", "initrd-fs.target" => "Initrd File Systems", "initrd-root-device.target" => "Initrd Root Device", @@ -168,8 +168,9 @@ fn description(unit: &str) -> &'static str { "nvidia-powerd.service" => "NVIDIA Dynamic Boost", "sys-devices-virtual-misc-rfkill.device" => "/sys/devices/virtual/misc/rfkill", "systemd-rfkill.service" => "Load/Save RF Kill Switch Status", - _ => "", - } + _ => return None, + }; + Some(description) } fn main() -> io::Result<()> { diff --git a/examples/luks.rs b/examples/luks.rs index 74a50f2..5eb859a 100644 --- a/examples/luks.rs +++ b/examples/luks.rs @@ -154,8 +154,8 @@ const HOST: &[Step] = &[ ), ]; -fn description(unit: &str) -> &'static str { - match unit { +fn description(unit: &str) -> Option<&'static str> { + let description = match unit { "initrd.target" => "Initrd Default Target", "initrd-fs.target" => "Initrd File Systems", "initrd-root-fs.target" => "Initrd Root File System", @@ -185,8 +185,9 @@ fn description(unit: &str) -> &'static str { "systemd-logind.service" => "User Login Management", "NetworkManager.service" => "Network Manager", "systemd-timesyncd.service" => "Network Time Synchronization", - _ => "", - } + _ => return None, + }; + Some(description) } fn main() -> io::Result<()> { diff --git a/examples/shutdown.rs b/examples/shutdown.rs index f1f00e5..d2a092e 100644 --- a/examples/shutdown.rs +++ b/examples/shutdown.rs @@ -64,8 +64,8 @@ const SHUTDOWN: &[Step] = &[ ), ]; -fn description(unit: &str) -> &'static str { - match unit { +fn description(unit: &str) -> Option<&'static str> { + let description = match unit { "poweroff.target" | "systemd-poweroff.service" => "System Power Off", "final.target" => "Late Shutdown Services", "umount.target" => "Unmount All Filesystems", @@ -78,8 +78,9 @@ fn description(unit: &str) -> &'static str { "NetworkManager.service" => "Network Manager", "var-lib-docker.mount" => "/var/lib/docker", "home.mount" => "/home", - _ => "", - } + _ => return None, + }; + Some(description) } fn main() -> io::Result<()> { diff --git a/src/boot_model.rs b/src/boot_model.rs index 77ce82a..cb45674 100644 --- a/src/boot_model.rs +++ b/src/boot_model.rs @@ -117,6 +117,7 @@ pub struct BootState { pub handoff_unit: Option, pub manager_exited_at: Option, pub milestone_targets: Vec, + boot_finished: bool, finished_before_reconnect: usize, units: HashMap, jobs: HashMap, diff --git a/src/boot_model/boot_change.rs b/src/boot_model/boot_change.rs index 17f0428..edbff13 100644 --- a/src/boot_model/boot_change.rs +++ b/src/boot_model/boot_change.rs @@ -32,6 +32,7 @@ pub enum BootChange { ManagerExited { at: Duration, }, + BootFinished, } impl BootState { @@ -47,6 +48,7 @@ impl BootState { BootChange::SwitchRoot { at } => self.switch_root(at), BootChange::ForgetJobs => self.forget_jobs(), BootChange::ManagerExited { at } => self.manager_exited_at = Some(at), + BootChange::BootFinished => self.mark_boot_finished(), } } } @@ -93,4 +95,12 @@ mod tests { assert_eq!(applied.is_complete(), called.is_complete()); assert_eq!(waiting_rows(&applied), waiting_rows(&called)); } + + #[test] + fn boot_finished_change_marks_the_boot_complete() { + let mut state = BootState::new(Phase::Host); + assert!(!state.is_complete()); + state.apply(BootChange::BootFinished); + assert!(state.is_complete()); + } } diff --git a/src/boot_model/boot_origin.rs b/src/boot_model/boot_origin.rs index 91e7902..a8ca441 100644 --- a/src/boot_model/boot_origin.rs +++ b/src/boot_model/boot_origin.rs @@ -1,5 +1,6 @@ use std::{ fs::{read_dir, read_link, read_to_string}, + iter::once, path::{Path, PathBuf}, }; @@ -13,8 +14,8 @@ const NIXOS_SYSTEM: &str = "nixos-system-"; #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct BootOrigin { pub host: String, - pub system: String, - pub generation: String, + pub system: Option, + pub generation: Option, pub kernel: String, } @@ -33,11 +34,9 @@ impl BootOrigin { .iter() .find_map(|path| read_to_string(path).ok()) .and_then(|release| pretty_name(&release)) - }) - .unwrap_or_default(); - let generation = system_path - .map(|path| generation_of(Path::new(path), &system_links())) - .unwrap_or_default(); + }); + let generation = + system_path.and_then(|path| generation_of(Path::new(path), &system_links())); Self { kernel: format!("Linux {}", names.release().to_string_lossy()), host, @@ -48,19 +47,15 @@ impl BootOrigin { #[must_use] pub fn parts(&self) -> Vec { - [ - self.host.clone(), - self.system.clone(), - if self.generation.is_empty() { - String::new() - } else { - format!("generation {}", self.generation) - }, - self.kernel.clone(), - ] - .into_iter() - .filter(|part| !part.is_empty()) - .collect() + once(self.host.clone()) + .chain(self.system.clone()) + .chain( + self.generation + .as_ref() + .map(|generation| format!("generation {generation}")), + ) + .chain(once(self.kernel.clone())) + .collect() } } @@ -107,12 +102,11 @@ fn system_links() -> Vec { .collect() } -fn generation_of(system_path: &Path, links: &[SystemLink]) -> String { +fn generation_of(system_path: &Path, links: &[SystemLink]) -> Option { links .iter() .find(|link| link.target == system_path) .map(|link| link.generation.clone()) - .unwrap_or_default() } #[cfg(test)] @@ -147,8 +141,11 @@ mod tests { target: system.into(), }, ]; - assert_eq!(generation_of(Path::new(system), &links), "2771"); - assert_eq!(generation_of(Path::new(system), &links[..1]), ""); + assert_eq!( + generation_of(Path::new(system), &links), + Some("2771".to_owned()) + ); + assert_eq!(generation_of(Path::new(system), &links[..1]), None); } #[test] @@ -163,8 +160,8 @@ mod tests { fn unknown_parts_are_left_out() { let origin = BootOrigin { host: "ryzen".to_owned(), - system: "NixOS 26.11".to_owned(), - generation: String::new(), + system: Some("NixOS 26.11".to_owned()), + generation: None, kernel: "Linux 7.2.9".to_owned(), }; assert_eq!(origin.parts(), ["ryzen", "NixOS 26.11", "Linux 7.2.9"]); diff --git a/src/boot_model/job_ingestion.rs b/src/boot_model/job_ingestion.rs index e57abb3..75282aa 100644 --- a/src/boot_model/job_ingestion.rs +++ b/src/boot_model/job_ingestion.rs @@ -71,6 +71,7 @@ impl BootState { handoff_unit, manager_exited_at: None, milestone_targets, + boot_finished: false, finished_before_reconnect: 0, units: HashMap::new(), jobs: HashMap::new(), @@ -92,6 +93,10 @@ impl BootState { } } + pub fn mark_boot_finished(&mut self) { + self.boot_finished = true; + } + pub fn track_unit(&mut self, facts: UnitFacts, activity: Activity) { let record = self .units @@ -212,13 +217,7 @@ impl BootState { if matches!(self.phase, Phase::Initrd | Phase::Shutdown) { return false; } - if self - .handoff_unit - .as_deref() - .and_then(|unit| self.units.get(unit)) - .and_then(|handoff| handoff.activity.state) - .is_some_and(|state| state != ActiveState::Inactive) - { + if self.boot_finished { return true; } let Root::Queued(root) = &self.root else { @@ -285,30 +284,26 @@ mod tests { } #[test] - fn display_manager_activation_hands_the_console_over() { + fn display_manager_activation_does_not_hand_the_console_over() { let mut state = sample(); queue_unit(&mut state, 20, waiting(HANDOFF_UNIT, &[]), 500 * MS); - assert!(!state.is_complete()); state.update_activity(HANDOFF_UNIT, activating(6000 * MS)); + assert!(!state.is_complete()); + } + + #[test] + fn boot_finished_hands_the_console_over() { + let mut state = sample(); + queue_unit(&mut state, 20, waiting(HANDOFF_UNIT, &[]), 500 * MS); + state.mark_boot_finished(); assert!(state.is_complete()); } #[test] - fn display_manager_started_in_one_step_hands_the_console_over() { - let mut state = sample(); - queue_unit(&mut state, 20, waiting(HANDOFF_UNIT, &[]), 500 * MS); - state.finish_job(20, JobResult::Done, 6000 * MS); + fn boot_finished_is_ignored_in_the_initrd() { + let mut state = BootState::new(Phase::Initrd); + state.mark_boot_finished(); assert!(!state.is_complete()); - state.update_activity( - HANDOFF_UNIT, - Activity { - state: Some(ActiveState::Active), - inactive_exit: Some(6000 * MS), - active_enter: Some(6000 * MS), - active_exit: None, - }, - ); - assert!(state.is_complete()); } #[test] diff --git a/src/boot_model/unit_facts.rs b/src/boot_model/unit_facts.rs index 0a08d0a..08c6721 100644 --- a/src/boot_model/unit_facts.rs +++ b/src/boot_model/unit_facts.rs @@ -29,7 +29,7 @@ pub enum JobResult { #[derive(Clone, Debug, PartialEq, Eq)] pub struct UnitFacts { pub name: String, - pub description: String, + pub description: Option, pub after: Vec, pub before: Vec, } @@ -90,18 +90,18 @@ impl UnitKind { } #[must_use] - pub fn tag(self) -> &'static str { + pub fn tag(self) -> Option<&'static str> { match self { - Self::Service | Self::Target | Self::Other => "", - Self::Socket => "Socket", - Self::Mount => "Mount", - Self::Automount => "Automount", - Self::Device => "Device", - Self::Swap => "Swap", - Self::Path => "Path", - Self::Timer => "Timer", - Self::Slice => "Slice", - Self::Scope => "Scope", + Self::Service | Self::Target | Self::Other => None, + Self::Socket => Some("Socket"), + Self::Mount => Some("Mount"), + Self::Automount => Some("Automount"), + Self::Device => Some("Device"), + Self::Swap => Some("Swap"), + Self::Path => Some("Path"), + Self::Timer => Some("Timer"), + Self::Slice => Some("Slice"), + Self::Scope => Some("Scope"), } } @@ -114,12 +114,15 @@ impl UnitKind { } fn labelled_by_description(facts: &UnitFacts) -> bool { - !facts.description.is_empty() && UnitKind::of(&facts.name).labelled_by_description() + facts.description.is_some() && UnitKind::of(&facts.name).labelled_by_description() } pub(super) fn display_label(facts: &UnitFacts) -> String { if labelled_by_description(facts) { - return facts.description.clone(); + return facts + .description + .clone() + .unwrap_or_else(|| facts.name.clone()); } match UnitKind::of(&facts.name) { UnitKind::Target | UnitKind::Other => facts.name.clone(), @@ -130,13 +133,12 @@ pub(super) fn display_label(facts: &UnitFacts) -> String { } } -pub(super) fn summary(facts: &UnitFacts) -> String { - let repeats_the_name = facts.description == facts.name - || facts - .description - .eq_ignore_ascii_case(&display_label(facts)); +pub(super) fn summary(facts: &UnitFacts) -> Option { + let repeats_the_name = facts.description.as_deref().is_some_and(|description| { + description == facts.name || description.eq_ignore_ascii_case(&display_label(facts)) + }); if labelled_by_description(facts) || repeats_the_name { - return String::new(); + return None; } facts.description.clone() } @@ -168,11 +170,11 @@ mod tests { fn kinds_with_a_tag_drop_their_suffix() { let socket = facts("docker.socket", &[]); assert_eq!(UnitKind::of(&socket.name), UnitKind::Socket); - assert_eq!(UnitKind::Socket.tag(), "Socket"); + assert_eq!(UnitKind::Socket.tag(), Some("Socket")); assert_eq!(display_label(&socket), "docker"); assert_eq!(display_label(&facts("sshd.service", &[])), "sshd"); assert_eq!(display_label(&facts("basic.target", &[])), "basic.target"); - assert_eq!(UnitKind::Target.tag(), ""); + assert_eq!(UnitKind::Target.tag(), None); } #[test] @@ -182,11 +184,11 @@ mod tests { }; assert_eq!( described("multi-user.target", "Multi-User System"), - "Multi-User System" + Some("Multi-User System".to_owned()) ); - assert_eq!(described("greetd.service", "greetd.service"), ""); - assert_eq!(described("greetd.service", "Greetd"), ""); - assert_eq!(described("dev-sda.device", "Samsung SSD"), ""); - assert_eq!(described("demo.service", ""), ""); + assert_eq!(described("greetd.service", "greetd.service"), None); + assert_eq!(described("greetd.service", "Greetd"), None); + assert_eq!(described("dev-sda.device", "Samsung SSD"), None); + assert_eq!(described("demo.service", ""), None); } } diff --git a/src/boot_model/waiting_tree.rs b/src/boot_model/waiting_tree.rs index 92f7a62..1e39720 100644 --- a/src/boot_model/waiting_tree.rs +++ b/src/boot_model/waiting_tree.rs @@ -13,6 +13,11 @@ use super::{ type WaitingGraph<'a> = DiGraphMap<&'a str, ()>; +struct WaitingEdge<'a> { + waiter: &'a str, + dependency: &'a str, +} + struct ReachableSibling<'a> { unit: &'a str, reaches: HashSet<&'a str>, @@ -33,7 +38,7 @@ pub enum RowStatus { pub struct TreeRow { pub depth: usize, pub label: String, - pub description: String, + pub description: Option, pub kind: UnitKind, pub status: RowStatus, pub chain: Vec, @@ -103,15 +108,15 @@ impl BootState { .for_each(|(name, _)| { graph.add_node(name.as_str()); }); - let edges: Vec<(&str, &str)> = graph + let edges: Vec = graph .nodes() .flat_map(|waiter| { self.waits_for(waiter, &graph) .into_iter() - .map(move |dependency| (waiter, dependency)) + .map(move |dependency| WaitingEdge { waiter, dependency }) }) .collect(); - graph.extend(edges); + graph.extend(edges.into_iter().map(|edge| (edge.waiter, edge.dependency))); let root = self.root.unit().filter(|root| graph.contains_node(root)); let stages: Vec<&str> = self .milestone_targets diff --git a/src/boot_view/panel_render_tests.rs b/src/boot_view/panel_render_tests.rs index 0f85b6b..ff336ab 100644 --- a/src/boot_view/panel_render_tests.rs +++ b/src/boot_view/panel_render_tests.rs @@ -54,7 +54,7 @@ fn tree_on_top_timeline_below() { "{screen}" ); assert!( - lines[timeline + 4].contains("·■") + lines[timeline + 4].contains("·█") && lines[timeline + 4].ends_with(['▏', '▎', '▍', '▌', '▋', '▊', '▉', '█']), "{screen}" ); diff --git a/src/boot_view/run_timeline.rs b/src/boot_view/run_timeline.rs index 485b017..0f03c06 100644 --- a/src/boot_view/run_timeline.rs +++ b/src/boot_view/run_timeline.rs @@ -75,9 +75,10 @@ impl Timeline<'_> { let bar_rows = usize::from(height.saturating_sub(CHROME_HEIGHT)); let room = bar_rows.saturating_sub(self.milestones.len() + self.running.len()); let mut longest_first = self.finished.clone(); - longest_first.sort_by_key(|run| Reverse(run.finished_at.saturating_sub(run.started_at))); + longest_first + .sort_unstable_by_key(|run| Reverse(run.finished_at.saturating_sub(run.started_at))); longest_first.truncate(room.min(SLOWEST_RUNS_SHOWN)); - longest_first.sort_by_key(|run| run.started_at); + longest_first.sort_unstable_by_key(|run| run.started_at); longest_first } @@ -143,10 +144,14 @@ impl Timeline<'_> { symbol: self.glyphs.waiting_bead, color: self.colors.queued_bar, }); + let running_bar = self + .glyphs + .growing_tip + .map_or(self.glyphs.bead, |tips| tips[7]); let ran = Segment { from: run.since, to: self.now, - symbol: self.glyphs.bead, + symbol: running_bar, color: self.colors.running, }; TimelineEntry { diff --git a/src/boot_view/screen_render_fixtures.rs b/src/boot_view/screen_render_fixtures.rs index 5084272..feff27a 100644 --- a/src/boot_view/screen_render_fixtures.rs +++ b/src/boot_view/screen_render_fixtures.rs @@ -46,8 +46,8 @@ pub fn render_prompted( pub fn ryzen_origin() -> BootOrigin { BootOrigin { host: "ryzen".to_owned(), - system: "NixOS 26.11".to_owned(), - generation: "2771".to_owned(), + system: Some("NixOS 26.11".to_owned()), + generation: Some("2771".to_owned()), kernel: "Linux 7.2.9".to_owned(), } } diff --git a/src/boot_view/tree_height_fitting.rs b/src/boot_view/tree_height_fitting.rs index 296a2f3..f63c22e 100644 --- a/src/boot_view/tree_height_fitting.rs +++ b/src/boot_view/tree_height_fitting.rs @@ -1,3 +1,5 @@ +use std::iter::successors; + use crate::boot_model::{RowStatus, TreeNode, TreeRow, UnitKind, flatten_forest}; const MIN_FOLDED_LINKS: usize = 2; @@ -55,13 +57,12 @@ impl TreeNode { } fn foldable_links(&self) -> usize { - let mut links = 0; - let mut cursor = self; - while cursor.is_chain_link() && cursor.children[0].is_chain_link() { - links += 1; - cursor = &cursor.children[0]; - } - links + successors(Some(self), |cursor| { + (cursor.is_chain_link() && cursor.children[0].is_chain_link()) + .then(|| &cursor.children[0]) + }) + .count() + .saturating_sub(1) } fn fold(mut self, may_absorb: bool) -> Self { diff --git a/src/boot_view/unit_tree.rs b/src/boot_view/unit_tree.rs index 06238b6..5ed703a 100644 --- a/src/boot_view/unit_tree.rs +++ b/src/boot_view/unit_tree.rs @@ -170,12 +170,12 @@ impl UnitTree<'_> { .iter() .zip(self.stages()) .filter(|(row, _)| { - row.chain.is_empty() && !(row.description.is_empty() && row.kind.tag().is_empty()) + row.chain.is_empty() && !(row.description.is_none() && row.kind.tag().is_none()) }) .collect(); let tag = annotated .iter() - .map(|(row, _)| width_of(row.kind.tag())) + .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); @@ -214,16 +214,23 @@ impl UnitTree<'_> { _ => String::new(), }; let style = self.label_style(row, stage); - Row::new(columns.shown([ - Line::from(vec![ - prefix.fg(self.colors.branches), - marker, - Span::styled(self.chained_label(row, room), style), + Row::new( + columns.shown([ + Line::from(vec![ + prefix.fg(self.colors.branches), + marker, + Span::styled(self.chained_label(row, room), style), + ]), + Line::from(annotation(row.kind.tag().unwrap_or_default(), columns.tag)) + .fg(self.colors.columns), + Line::from(annotation( + row.description.as_deref().unwrap_or_default(), + columns.description, + )) + .fg(self.colors.columns), + Line::from(timer).style(style).right_aligned(), ]), - Line::from(annotation(row.kind.tag(), columns.tag)).fg(self.colors.columns), - Line::from(annotation(&row.description, columns.description)).fg(self.colors.columns), - Line::from(timer).style(style).right_aligned(), - ])) + ) } } @@ -277,22 +284,21 @@ impl Widget for UnitTree<'_> { } fn tree_prefixes(rows: &[TreeRow]) -> Vec { - let mut later_sibling: Vec = Vec::new(); - let mut is_last: Vec = rows + let is_last = rows .iter() .rev() - .map(|row| { + .scan(Vec::::new(), |later_sibling, row| { let last = !later_sibling.get(row.depth).copied().unwrap_or(false); later_sibling.resize(row.depth + 1, false); later_sibling[row.depth] = true; - last + Some(last) }) - .collect(); - is_last.reverse(); - let mut trunks: Vec<&str> = Vec::new(); + .collect::>() + .into_iter() + .rev(); rows.iter() .zip(is_last) - .map(|(row, last)| { + .scan(Vec::<&str>::new(), |trunks, (row, last)| { trunks.truncate(row.depth); let connector = if last { LAST_BRANCH } else { BRANCH }; let prefix = once(ENDED_TRUNK) @@ -300,7 +306,7 @@ fn tree_prefixes(rows: &[TreeRow]) -> Vec { .chain(once(connector)) .collect(); trunks.push(if last { ENDED_TRUNK } else { PASSING_TRUNK }); - prefix + Some(prefix) }) .collect() } @@ -325,7 +331,7 @@ mod tests { TreeRow { depth, label: String::new(), - description: String::new(), + description: None, kind: UnitKind::Service, status: RowStatus::Waiting, chain: Vec::new(), diff --git a/src/console_session/console_takeover.rs b/src/console_session/console_takeover.rs index 6818655..519e840 100644 --- a/src/console_session/console_takeover.rs +++ b/src/console_session/console_takeover.rs @@ -19,6 +19,7 @@ pub struct Console { quiet_kernel: Option, foreground: Option, for_system: bool, + handing_over: bool, pub glyphs: Glyphs, pub bold_is_brightness: bool, } @@ -37,6 +38,7 @@ impl Console { ForegroundVt::take() }, for_system, + handing_over: false, glyphs: font_glyphs(), bold_is_brightness: own_vt().is_some(), } @@ -63,12 +65,30 @@ impl Console { .quiet_kernel .as_mut() .is_some_and(QuietKernelConsole::keep_quiet); - let terminal_was_taken = self.foreground.as_ref().is_some_and(ForegroundVt::insist); + let terminal_was_taken = + !self.handing_over && self.foreground.as_ref().is_some_and(ForegroundVt::insist); let glyphs = font_glyphs(); let font_changed = glyphs != self.glyphs; self.glyphs = glyphs; kernel_got_loud || terminal_was_taken || font_changed } + + pub fn begin_handover(&mut self) { + self.handing_over = true; + } + + #[must_use] + pub fn console_was_taken(&self) -> bool { + self.foreground + .as_ref() + .is_some_and(ForegroundVt::taken_away) + } + + pub fn leave_console(&mut self) { + if let Some(foreground) = &mut self.foreground { + foreground.leave = true; + } + } } struct QuietKernelConsole { @@ -162,6 +182,7 @@ struct VtState { struct ForegroundVt { own: u16, previous: u16, + leave: bool, } fn active_vt() -> Option { @@ -186,12 +207,20 @@ impl ForegroundVt { if previous != own { activate(own).ok()?; } - Some(Self { own, previous }) + Some(Self { + own, + previous, + leave: false, + }) } fn insist(&self) -> bool { active_vt().is_some_and(|active| active != self.own) && activate(self.own).is_ok() } + + fn taken_away(&self) -> bool { + active_vt().is_some_and(|active| active != self.own) + } } impl Drop for ForegroundVt { @@ -200,6 +229,9 @@ impl Drop for ForegroundVt { eprintln!("bootvine: leaving a password prompt to the console agent on this terminal"); return; } + if self.leave { + return; + } let _ = activate(self.previous); } } diff --git a/src/console_session/live_desk.rs b/src/console_session/live_desk.rs index 7008678..953b936 100644 --- a/src/console_session/live_desk.rs +++ b/src/console_session/live_desk.rs @@ -27,6 +27,7 @@ pub struct LiveDesk { entry: Option, requests_watched: bool, clear_requested: bool, + handover_deadline: Option, } impl LiveDesk { @@ -37,6 +38,7 @@ impl LiveDesk { entry: None, requests_watched, clear_requested: false, + handover_deadline: None, } } @@ -78,8 +80,21 @@ impl ConsoleDesk for LiveDesk { ControlFlow::Continue(()) } - fn frame_passed(&mut self, _state: &mut BootState, _now: Duration) -> ControlFlow { - ControlFlow::Continue(()) + fn begin_handover(&mut self, now: Duration, hold_for: Duration) { + self.console.begin_handover(); + self.handover_deadline = Some(now + hold_for); + } + + fn frame_passed(&mut self, _state: &mut BootState, now: Duration) -> ControlFlow { + let Some(deadline) = self.handover_deadline else { + return ControlFlow::Continue(()); + }; + if self.console.console_was_taken() || now >= deadline { + self.console.leave_console(); + ControlFlow::Break(WatchEnding::BootCompleted) + } else { + ControlFlow::Continue(()) + } } fn password_requests_changed(&mut self) { diff --git a/src/console_session/watch_loop.rs b/src/console_session/watch_loop.rs index c209db3..475e606 100644 --- a/src/console_session/watch_loop.rs +++ b/src/console_session/watch_loop.rs @@ -1,7 +1,7 @@ use std::{path::Path, time::Duration}; use futures::{StreamExt, stream}; -use tokio::{runtime::Builder, time::sleep}; +use tokio::runtime::Builder; use crate::{ boot_model::{BootState, Phase, boot_origin::BootOrigin}, @@ -110,9 +110,6 @@ async fn watch_live_boot(settings: &Settings, phase: Phase) -> Result<(), Error> ); let mut terminal = ratatui::try_init()?; let ending = watch_until_ending(&mut screen, &mut terminal, inputs).await; - if matches!(ending, WatchEnding::BootCompleted) { - sleep(settings.timing.keep_final_frame_for).await; - } ratatui::restore(); match ending { WatchEnding::Failed(error) => Err(error), diff --git a/src/console_session/watch_screen.rs b/src/console_session/watch_screen.rs index e4c990e..fc37dd2 100644 --- a/src/console_session/watch_screen.rs +++ b/src/console_session/watch_screen.rs @@ -59,6 +59,8 @@ pub trait ConsoleDesk { fn refreshed_origin(&self) -> Option { None } + + fn begin_handover(&mut self, _now: Duration, _hold_for: Duration) {} } struct CachedProjection { @@ -71,6 +73,7 @@ pub struct WatchScreen { pub desk: Desk, origin: BootOrigin, full_repaint_due: bool, + handover_begun: bool, colors: Colors, timing: Timing, epoch: Duration, @@ -91,6 +94,7 @@ impl WatchScreen { desk, origin, full_repaint_due: false, + handover_begun: false, colors, timing, epoch, @@ -106,7 +110,7 @@ impl WatchScreen { fn absorb(&mut self, input: ScreenInput) -> ControlFlow { let now = self.now(); match input { - ScreenInput::Boot(changes) => self.apply_boot_changes(changes), + ScreenInput::Boot(changes) => self.apply_boot_changes(changes, now), ScreenInput::Key(event) => self.desk.press_key(&event, now), ScreenInput::Frame => self.desk.frame_passed(&mut self.state, now), ScreenInput::PromptCheck => { @@ -130,7 +134,11 @@ impl WatchScreen { } } - fn apply_boot_changes(&mut self, changes: Vec) -> ControlFlow { + fn apply_boot_changes( + &mut self, + changes: Vec, + now: Duration, + ) -> ControlFlow { let phase_before = self.state.phase; changes .into_iter() @@ -144,11 +152,16 @@ impl WatchScreen { if !self.state.is_complete() { return ControlFlow::Continue(()); } - eprintln!( - "bootvine: {} reached, handing the console over", - self.state.root.unit().unwrap_or("boot") - ); - ControlFlow::Break(WatchEnding::BootCompleted) + if !self.handover_begun { + self.handover_begun = true; + eprintln!( + "bootvine: {} reached, handing the console over", + self.state.root.unit().unwrap_or("boot") + ); + self.desk + .begin_handover(now, self.timing.keep_final_frame_for); + } + ControlFlow::Continue(()) } fn absorb_batch( diff --git a/src/demo_script/boot_test_fixtures.rs b/src/demo_script/boot_test_fixtures.rs index e2433ef..3658288 100644 --- a/src/demo_script/boot_test_fixtures.rs +++ b/src/demo_script/boot_test_fixtures.rs @@ -15,7 +15,7 @@ pub struct QueuedUnit { pub fn facts(name: &str, after: &[&str]) -> UnitFacts { UnitFacts { name: name.to_owned(), - description: String::new(), + description: None, after: after.iter().map(ToString::to_string).collect(), before: Vec::new(), } @@ -58,7 +58,7 @@ impl QueuedUnit { } pub fn described(mut self, description: &str) -> Self { - description.clone_into(&mut self.facts.description); + self.facts.description = (!description.is_empty()).then(|| description.to_owned()); self } } diff --git a/src/demo_script/scripted_boot.rs b/src/demo_script/scripted_boot.rs index 071f696..b881ca3 100644 --- a/src/demo_script/scripted_boot.rs +++ b/src/demo_script/scripted_boot.rs @@ -84,7 +84,7 @@ pub struct Scenario { pub phase: Phase, pub steps: &'static [Step], pub after_switch_root: &'static [Step], - pub describe: fn(&str) -> &'static str, + pub describe: fn(&str) -> Option<&'static str>, } struct ScriptedJob { @@ -93,13 +93,13 @@ struct ScriptedJob { } impl ScriptedJob { - fn facts(&self, steps: &[Step], describe: fn(&str) -> &'static str) -> UnitFacts { + fn facts(&self, steps: &[Step], describe: fn(&str) -> Option<&'static str>) -> UnitFacts { let is_stopping = |unit: &&str| steps.iter().any(|step| step.unit == *unit && step.stops); let (before, after): (Vec<&str>, Vec<&str>) = self.step.after.iter().copied().partition(is_stopping); UnitFacts { name: self.step.unit.to_owned(), - description: describe(self.step.unit).to_owned(), + description: describe(self.step.unit).map(str::to_owned), after: after.into_iter().map(ToString::to_string).collect(), before: before.into_iter().map(ToString::to_string).collect(), } @@ -176,7 +176,7 @@ struct Answer { impl Script { fn begin( steps: &'static [Step], - describe: fn(&str) -> &'static str, + describe: fn(&str) -> Option<&'static str>, first_job: u32, state: &mut BootState, now: Duration, @@ -298,7 +298,7 @@ impl Script { struct DemoDesk { script: Script, after_switch_root: Option<&'static [Step]>, - describe: fn(&str) -> &'static str, + describe: fn(&str) -> Option<&'static str>, settled_at: Option, typed: Zeroizing, glyphs: Glyphs, @@ -354,8 +354,8 @@ impl ConsoleDesk for DemoDesk { fn demo_origin() -> BootOrigin { BootOrigin { host: "demo".to_owned(), - system: "NixOS 26.11.20261007.39ad350".to_owned(), - generation: "42".to_owned(), + system: Some("NixOS 26.11.20261007.39ad350".to_owned()), + generation: Some("42".to_owned()), kernel: "Linux 7.2.9".to_owned(), } } @@ -420,7 +420,7 @@ mod tests { fn asking_demo() -> AskingDemo { let mut state = BootState::new(Phase::Initrd); - let mut script = Script::begin(UNLOCK_ONLY, |_| "", 1, &mut state, Duration::ZERO); + let mut script = Script::begin(UNLOCK_ONLY, |_| None, 1, &mut state, Duration::ZERO); script.advance(&mut state, Duration::ZERO); AskingDemo { script, state } } diff --git a/src/systemd_link/boot_feed.rs b/src/systemd_link/boot_feed.rs index 563e6f6..216788e 100644 --- a/src/systemd_link/boot_feed.rs +++ b/src/systemd_link/boot_feed.rs @@ -209,9 +209,9 @@ impl BusFeed { async fn origin_change( &mut self, connection: &mut BusConnection, - ) -> Result, Error> { + ) -> Result, Error> { if self.gave_origin { - return Ok(None); + return Ok(Vec::new()); } self.gave_origin = true; let origin = if connection.boot_in_progress().await? { @@ -219,7 +219,9 @@ impl BusFeed { } else { monotonic_now() }; - Ok(Some(BootChange::SetOrigin(origin))) + Ok(once(BootChange::SetOrigin(origin)) + .chain(self.boot_finished()) + .collect()) } async fn track_all( @@ -347,9 +349,17 @@ impl BusFeed { }) .into_iter() .collect(), + Signal::BootFinished => self.boot_finished(), } } + fn boot_finished(&self) -> Vec { + (self.phase == Phase::Host) + .then_some(BootChange::BootFinished) + .into_iter() + .collect() + } + async fn queue_new_job( &mut self, connection: &mut BusConnection, diff --git a/src/systemd_link/systemd_bus.rs b/src/systemd_link/systemd_bus.rs index 5d65547..fdc682b 100644 --- a/src/systemd_link/systemd_bus.rs +++ b/src/systemd_link/systemd_bus.rs @@ -67,6 +67,7 @@ pub enum Signal { path: Path<'static>, activity: Activity, }, + BootFinished, } pub struct FetchedUnit { @@ -355,7 +356,7 @@ fn unit_facts_from(name: &str, properties: &PropMap) -> UnitFacts { }; UnitFacts { name: text("Id").unwrap_or_else(|| name.to_owned()), - description: text("Description").unwrap_or_default(), + description: text("Description").filter(|description| !description.is_empty()), after: names("After"), before: names("Before"), } @@ -386,9 +387,10 @@ fn parse_signal(message: &Message) -> Option { } let interface = message.interface()?; let member = message.member()?; - match &*interface { - MANAGER_INTERFACE => parse_job_signal(message, &member), - PROPERTIES_INTERFACE if &*member == "PropertiesChanged" => parse_unit_change(message), + match (&*interface, &*member) { + (MANAGER_INTERFACE, "JobNew" | "JobRemoved") => parse_job_signal(message, &member), + (MANAGER_INTERFACE, "PropertiesChanged") => parse_manager_change(message), + (PROPERTIES_INTERFACE, "PropertiesChanged") => parse_unit_change(message), _ => None, } } @@ -423,6 +425,24 @@ fn parse_unit_change(message: &Message) -> Option { }) } +fn parse_manager_change(message: &Message) -> Option { + let (changed_interface, changed, _invalidated): (String, PropMap, Vec) = + message.read3().ok()?; + if changed_interface != MANAGER_INTERFACE { + return None; + } + finish_timestamp(&changed) + .is_some() + .then_some(Signal::BootFinished) +} + +fn finish_timestamp(properties: &PropMap) -> Option { + properties + .get("FinishTimestampMonotonic") + .and_then(|value| value.0.as_u64()) + .filter(|micros| *micros != 0) +} + fn activity_from(properties: &PropMap) -> Activity { let monotonic = |property: &str| { properties