diff --git a/Cargo.lock b/Cargo.lock index e79a865..39a1fec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -158,7 +158,6 @@ dependencies = [ "ser_nix", "serde", "serde_plain", - "signal-hook 0.4.5", "thiserror 2.0.21", "tokio", "toml", @@ -313,7 +312,7 @@ dependencies = [ "parking_lot", "rustix 0.38.44", "serde", - "signal-hook 0.3.18", + "signal-hook", "signal-hook-mio", "winapi", ] @@ -332,7 +331,7 @@ dependencies = [ "parking_lot", "rustix 1.1.5", "serde", - "signal-hook 0.3.18", + "signal-hook", "signal-hook-mio", "winapi", ] @@ -1634,16 +1633,6 @@ dependencies = [ "signal-hook-registry", ] -[[package]] -name = "signal-hook" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b29ffa27d3d59a049bb328258de100f8012848d1b08d444e08bbc02ac468435e" -dependencies = [ - "libc", - "signal-hook-registry", -] - [[package]] name = "signal-hook-mio" version = "0.2.5" @@ -1652,7 +1641,7 @@ checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" dependencies = [ "libc", "mio", - "signal-hook 0.3.18", + "signal-hook", ] [[package]] @@ -1781,7 +1770,7 @@ dependencies = [ "bitflags 2.13.2", "parking_lot", "rustix 1.1.5", - "signal-hook 0.3.18", + "signal-hook", "windows-sys 0.61.2", ] @@ -1844,7 +1833,7 @@ dependencies = [ "phf", "serde", "sha2", - "signal-hook 0.3.18", + "signal-hook", "siphasher", "terminfo", "termios", diff --git a/Cargo.toml b/Cargo.toml index 4532570..b8b6e73 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,7 +36,6 @@ rustix = { version = "1.1.5", features = ["event", "fs", "process", "stdio", "sy ser_nix = "0.2.4" serde = { version = "1.0.229", features = ["derive"] } serde_plain = "1.0.2" -signal-hook = "0.4.5" 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"] } diff --git a/src/boot_model.rs b/src/boot_model.rs index 20c2a9f..6f92761 100644 --- a/src/boot_model.rs +++ b/src/boot_model.rs @@ -1,3 +1,4 @@ +mod boot_change; pub mod boot_origin; mod job_ingestion; mod reached_milestones; @@ -7,6 +8,7 @@ mod waiting_tree; use std::{collections::HashMap, time::Duration}; pub use self::{ + boot_change::BootChange, reached_milestones::MilestoneRow, unit_facts::{ActiveState, Activity, JobKind, JobResult, UnitFacts, UnitKind}, waiting_tree::{RowStatus, TreeNode, TreeRow, flatten_forest}, diff --git a/src/boot_model/boot_change.rs b/src/boot_model/boot_change.rs new file mode 100644 index 0000000..17f0428 --- /dev/null +++ b/src/boot_model/boot_change.rs @@ -0,0 +1,96 @@ +use std::time::Duration; + +use super::{Activity, BootState, JobKind, JobResult, UnitFacts}; + +pub enum BootChange { + TrackUnit { + facts: UnitFacts, + activity: Activity, + }, + UpdateActivity { + unit: String, + activity: Activity, + }, + QueueJob { + id: u32, + unit: String, + kind: JobKind, + at: Duration, + }, + FinishJob { + id: u32, + result: JobResult, + at: Duration, + }, + SetRoot(String), + SetHandoff(String), + SetOrigin(Duration), + SwitchRoot { + at: Duration, + }, + ForgetJobs, + ManagerExited { + at: Duration, + }, +} + +impl BootState { + pub fn apply(&mut self, change: BootChange) { + match change { + BootChange::TrackUnit { facts, activity } => self.track_unit(facts, activity), + 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::SetRoot(root) => self.set_root(root), + BootChange::SetHandoff(unit) => self.set_handoff(unit), + BootChange::SetOrigin(origin) => self.origin = origin, + BootChange::SwitchRoot { at } => self.switch_root(at), + BootChange::ForgetJobs => self.forget_jobs(), + BootChange::ManagerExited { at } => self.manager_exited_at = Some(at), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + boot_model::Phase, + demo_script::boot_test_fixtures::{MS, facts, waiting_rows}, + }; + + #[test] + fn applied_changes_match_the_direct_calls() { + let mut applied = BootState::new(Phase::Host); + [ + BootChange::SetOrigin(100 * MS), + BootChange::TrackUnit { + facts: facts("web.service", &[]), + activity: Activity::default(), + }, + BootChange::SetRoot("web.service".to_owned()), + BootChange::QueueJob { + id: 1, + unit: "web.service".to_owned(), + kind: JobKind::BringsUp, + at: 200 * MS, + }, + BootChange::FinishJob { + id: 1, + result: JobResult::Done, + at: 900 * MS, + }, + ] + .into_iter() + .for_each(|change| applied.apply(change)); + let mut called = BootState::new(Phase::Host); + called.origin = 100 * MS; + called.track_unit(facts("web.service", &[]), Activity::default()); + called.set_root("web.service".to_owned()); + called.queue_job(1, "web.service", JobKind::BringsUp, 200 * MS); + called.finish_job(1, JobResult::Done, 900 * MS); + assert_eq!(applied.tally(), called.tally()); + assert_eq!(applied.is_complete(), called.is_complete()); + assert_eq!(waiting_rows(&applied), waiting_rows(&called)); + } +} diff --git a/src/console_session.rs b/src/console_session.rs index faf49de..005afab 100644 --- a/src/console_session.rs +++ b/src/console_session.rs @@ -1,4 +1,7 @@ pub mod ask_password; pub mod console_takeover; +pub mod live_desk; pub mod passphrase_input; +pub mod stream_sources; pub mod watch_loop; +pub mod watch_screen; diff --git a/src/console_session/ask_password.rs b/src/console_session/ask_password.rs index 98c3cfd..640716e 100644 --- a/src/console_session/ask_password.rs +++ b/src/console_session/ask_password.rs @@ -1,7 +1,7 @@ use std::{ fs, io, iter, os::{ - fd::{AsFd, BorrowedFd, OwnedFd}, + fd::{AsRawFd, OwnedFd, RawFd}, unix::net::UnixDatagram, }, path::{Path, PathBuf}, @@ -61,9 +61,9 @@ impl RequestWatch { } } -impl AsFd for RequestWatch { - fn as_fd(&self) -> BorrowedFd<'_> { - self.inotify.as_fd() +impl AsRawFd for RequestWatch { + fn as_raw_fd(&self) -> RawFd { + self.inotify.as_raw_fd() } } diff --git a/src/console_session/live_desk.rs b/src/console_session/live_desk.rs new file mode 100644 index 0000000..294b9b5 --- /dev/null +++ b/src/console_session/live_desk.rs @@ -0,0 +1,114 @@ +use std::{future::ready, io, mem, ops::ControlFlow, time::Duration}; + +use crossterm::event::Event; +use futures::{Stream, StreamExt}; + +use crate::{ + boot_model::{BootState, boot_origin::BootOrigin}, + boot_view::PasswordPrompt, + console_session::{ + ask_password::{PasswordEntry, RequestWatch}, + console_takeover::Console, + passphrase_input::asks_to_quit, + stream_sources::{CarriedItem, periodic_inputs, readable_source, unfold_carrying}, + watch_screen::{ConsoleDesk, ScreenInput, WatchEnding}, + }, + screen_settings::font_glyphs::Glyphs, +}; + +const FULL_REPAINT_INTERVAL: Duration = Duration::from_secs(1); + +pub struct LiveDesk { + console: Console, + entry: Option, + requests_watched: bool, + clear_requested: bool, +} + +impl LiveDesk { + #[must_use] + pub fn new(console: Console, requests_watched: bool) -> Self { + Self { + console, + entry: None, + requests_watched, + clear_requested: false, + } + } + + fn follow_requests(&mut self, requests_changed: bool) { + self.clear_requested |= + requests_changed && self.console.come_forward_once_prompts_are_gone(); + self.entry = if self.console.answers_password_prompts() { + PasswordEntry::follow(self.entry.take(), requests_changed) + } else { + None + }; + } +} + +impl ConsoleDesk for LiveDesk { + fn glyphs(&self) -> &Glyphs { + &self.console.glyphs + } + + fn drops_bold(&self) -> bool { + self.console.bold_is_brightness + } + + fn prompt(&self, _now: Duration) -> Option> { + self.entry.as_ref().map(PasswordEntry::prompt) + } + + fn press_key(&mut self, event: &Event, _now: Duration) -> ControlFlow { + let Some(entry) = &mut self.entry else { + return if asks_to_quit(event, false) { + ControlFlow::Break(WatchEnding::ViewerLeft) + } else { + ControlFlow::Continue(()) + }; + }; + if let Err(error) = entry.type_key(event) { + eprintln!("bootvine: cannot answer the password prompt: {error}"); + } + ControlFlow::Continue(()) + } + + fn frame_passed(&mut self, _state: &mut BootState, _now: Duration) -> ControlFlow { + self.follow_requests(!self.requests_watched); + ControlFlow::Continue(()) + } + + fn password_requests_changed(&mut self) { + self.follow_requests(true); + } + + fn keep_console_up(&mut self) { + self.console.keep_up(); + } + + fn take_clear_request(&mut self) -> bool { + mem::take(&mut self.clear_requested) + } + + fn refreshed_origin(&self) -> Option { + Some(BootOrigin::read()) + } +} + +pub fn full_repaint_inputs() -> impl Stream { + periodic_inputs(FULL_REPAINT_INTERVAL, || ScreenInput::FullRepaint) +} + +pub fn password_request_inputs(watch: RequestWatch) -> io::Result> { + let readiness = readable_source(watch)?; + Ok(unfold_carrying(readiness, |readiness| async move { + readiness.readable().await.ok()?.clear_ready(); + Some(CarriedItem { + item: readiness.get_ref().changed(), + state: readiness, + }) + }) + .filter(|changed| ready(*changed)) + .map(|_| ScreenInput::PasswordRequests)) +} diff --git a/src/console_session/stream_sources.rs b/src/console_session/stream_sources.rs new file mode 100644 index 0000000..b2b0254 --- /dev/null +++ b/src/console_session/stream_sources.rs @@ -0,0 +1,101 @@ +use std::{future::Future, io, iter, os::fd::AsRawFd, time::Duration}; + +use crossterm::event::{self, Event}; +use futures::{FutureExt, Stream, StreamExt, stream}; +use tokio::{ + io::{Interest, unix::AsyncFd}, + signal::unix::{SignalKind, signal}, + time::{Interval, MissedTickBehavior, interval, timeout}, +}; + +use crate::console_session::watch_screen::ScreenInput; + +pub const FRAME_INTERVAL: Duration = Duration::from_millis(100); + +pub struct CarriedItem { + pub item: Item, + pub state: State, +} + +pub fn unfold_carrying( + initial: State, + mut next: Next, +) -> impl Stream +where + Next: FnMut(State) -> Pending, + Pending: Future>>, +{ + stream::unfold(initial, move |state| { + next(state).map(|carried| carried.map(|carried| (carried.item, carried.state))) + }) +} + +pub fn readable_source(source: Source) -> io::Result> { + Ok(unsafe { AsyncFd::register_with_interest(source, Interest::READABLE) }?) +} + +pub async fn readable_or_timeout(readiness: &AsyncFd, patience: Duration) { + if let Ok(Ok(mut guard)) = timeout(patience, readiness.readable()).await { + guard.clear_ready(); + } +} + +fn steady_interval(period: Duration) -> Interval { + let mut ticks = interval(period); + ticks.set_missed_tick_behavior(MissedTickBehavior::Delay); + ticks +} + +pub fn periodic_inputs( + period: Duration, + input: fn() -> ScreenInput, +) -> impl Stream { + unfold_carrying(steady_interval(period), move |mut ticks| async move { + ticks.tick().await; + Some(CarriedItem { + item: input(), + state: ticks, + }) + }) +} + +pub fn frame_inputs() -> impl Stream { + periodic_inputs(FRAME_INTERVAL, || ScreenInput::Frame) +} + +fn drain_terminal_events() -> io::Result> { + iter::from_fn(|| match event::poll(Duration::ZERO) { + Ok(true) => Some(event::read()), + Ok(false) => None, + Err(error) => Some(Err(error)), + }) + .collect() +} + +fn terminal_inputs(drained: io::Result>) -> Vec { + match drained { + Ok(events) => events.into_iter().map(ScreenInput::Key).collect(), + Err(error) => vec![ScreenInput::Failed(error.into())], + } +} + +pub fn key_inputs() -> io::Result> { + let readiness = readable_source(io::stdin())?; + Ok(unfold_carrying(readiness, |readiness| async move { + readiness.readable().await.ok()?.clear_ready(); + Some(CarriedItem { + item: drain_terminal_events(), + state: readiness, + }) + }) + .map(terminal_inputs) + .flat_map(stream::iter)) +} + +pub fn termination_inputs() -> io::Result> { + let mut terminate = signal(SignalKind::terminate())?; + Ok(stream::once(async move { + terminate.recv().await; + ScreenInput::Terminate + })) +} diff --git a/src/console_session/watch_loop.rs b/src/console_session/watch_loop.rs index a924b2f..14193ea 100644 --- a/src/console_session/watch_loop.rs +++ b/src/console_session/watch_loop.rs @@ -1,51 +1,26 @@ -use std::{ - io, - os::fd::{AsFd, BorrowedFd}, - path::Path, - sync::{ - Arc, - atomic::{AtomicBool, Ordering}, - }, - thread::sleep, - time::{Duration, Instant}, -}; +use std::{path::Path, time::Duration}; -use crossterm::event; -use ratatui::{ - DefaultTerminal, - backend::Backend, - buffer::{Buffer, CellDiffOption}, - style::Modifier, -}; -use rustix::{ - event::{PollFd, PollFlags, poll}, - io::Errno, - stdio::stdin, - time::Timespec, -}; -use signal_hook::{consts::SIGTERM, flag}; +use futures::{StreamExt, stream}; +use tokio::{runtime::Builder, time::sleep}; use crate::{ boot_model::{BootState, Phase, boot_origin::BootOrigin}, - boot_view::BootView, console_session::{ - ask_password::{PasswordEntry, RequestWatch}, + ask_password::RequestWatch, console_takeover::Console, - passphrase_input::asks_to_quit, + live_desk::{LiveDesk, full_repaint_inputs, password_request_inputs}, + stream_sources::{frame_inputs, key_inputs, termination_inputs}, + watch_screen::{WatchEnding, WatchScreen, watch_until_ending}, }, screen_settings::{color_scheme::Colors, config_file::Timing}, systemd_link::{ - boot_feed::{Feed, RootRequest}, + boot_feed::{RootRequest, bus_inputs}, link_error::Error, - monotonic_clock::monotonic_now, switch_root::INITRD_RELEASE, systemd_bus::{Scope, Session}, }, }; -const FRAME_INTERVAL: Duration = Duration::from_millis(100); -const FULL_REPAINT_INTERVAL: Duration = Duration::from_secs(1); - pub struct Settings { pub scope: Scope, pub shutdown: bool, @@ -54,172 +29,71 @@ pub struct Settings { pub colors: Colors, } -pub fn run(settings: &Settings) -> Result<(), Error> { - let terminate = Arc::new(AtomicBool::new(false)); - flag::register(SIGTERM, Arc::clone(&terminate))?; - if settings.scope == Scope::System +fn boot_already_finished(settings: &Settings) -> bool { + settings.scope == Scope::System && !settings.shutdown && Session::open(Scope::System) .and_then(|session| session.boot_in_progress()) .is_ok_and(|booting| !booting) - { - eprintln!("bootvine: boot already finished, leaving the console alone"); - return Ok(()); - } - let phase = match settings.scope { +} + +fn starting_phase(settings: &Settings) -> Phase { + match settings.scope { _ if settings.shutdown => Phase::Shutdown, Scope::User => Phase::User, Scope::System if Path::new(INITRD_RELEASE).exists() => Phase::Initrd, Scope::System => Phase::Host, - }; - let mut state = BootState::new(phase); - let mut feed = Feed::new(phase, settings.scope, settings.target.clone()); - let mut console = Console::take(settings.scope == Scope::System); - let mut terminal = ratatui::try_init()?; - let watched = watch( - &mut state, - &mut feed, - &mut terminal, - &terminate, - settings, - &mut console, - ); - ratatui::restore(); - watched -} - -fn sleep_until_readable<'fd>( - sources: impl IntoIterator>, - timeout: Duration, -) -> io::Result<()> { - let mut watched: Vec> = sources - .into_iter() - .map(|source| PollFd::from_borrowed_fd(source, PollFlags::IN)) - .collect(); - match poll( - &mut watched, - Some(&Timespec::try_from(timeout).unwrap_or_default()), - ) { - Ok(_) | Err(Errno::INTR) => Ok(()), - Err(error) => Err(error.into()), } } -fn overwrite_every_cell(backend: &mut B, frame: &Buffer) -> Result<(), B::Error> { - backend.draw( - frame - .content - .iter() - .enumerate() - .filter(|(_, cell)| cell.diff_option != CellDiffOption::Skip) - .map(|(index, cell)| { - let (x, y) = frame.pos_of(index); - (x, y, cell) - }), - )?; - backend.flush() +pub fn run(settings: &Settings) -> Result<(), Error> { + if boot_already_finished(settings) { + eprintln!("bootvine: boot already finished, leaving the console alone"); + return Ok(()); + } + Builder::new_current_thread() + .enable_io() + .enable_time() + .build()? + .block_on(watch_live_boot(settings, starting_phase(settings))) } -fn drop_bold(frame: &mut Buffer) { - frame - .content - .iter_mut() - .for_each(|cell| cell.modifier.remove(Modifier::BOLD)); -} - -fn watch( - state: &mut BootState, - feed: &mut Feed, - terminal: &mut DefaultTerminal, - terminate: &AtomicBool, - settings: &Settings, - console: &mut Console, -) -> Result<(), Error> { - let mut origin = BootOrigin::read(); - let mut origin_phase = state.phase; - let mut painted_connections = feed.connections; - let mut last_full_repaint = Instant::now(); - let mut next_frame = Instant::now(); +async fn watch_live_boot(settings: &Settings, phase: Phase) -> Result<(), Error> { let requests = RequestWatch::open(); - let mut password_entry: Option = None; - loop { - if state.phase != origin_phase { - origin = BootOrigin::read(); - origin_phase = state.phase; - } - let requests_changed = requests.as_ref().is_none_or(RequestWatch::changed); - if requests_changed && console.come_forward_once_prompts_are_gone() { - terminal.clear()?; - } - password_entry = if console.answers_password_prompts() { - PasswordEntry::follow(password_entry.take(), requests_changed) - } else { - None - }; - let repaint_due = feed.connections != painted_connections - || last_full_repaint.elapsed() >= FULL_REPAINT_INTERVAL; - if repaint_due { - console.keep_up(); - } - let completed = terminal.draw(|canvas| { - canvas.render_widget( - BootView { - state, - colors: &settings.colors, - timing: &settings.timing, - glyphs: &console.glyphs, - now: monotonic_now(), - origin: &origin, - password_prompt: password_entry.as_ref().map(PasswordEntry::prompt), - }, - canvas.area(), - ); - if console.bold_is_brightness { - drop_bold(canvas.buffer_mut()); - } - })?; - if repaint_due { - let painted = completed.buffer.clone(); - overwrite_every_cell(terminal.backend_mut(), &painted)?; - painted_connections = feed.connections; - last_full_repaint = Instant::now(); - } - if state.is_complete() { - eprintln!( - "bootvine: {} reached, handing the console over", - state.root.unit().unwrap_or("boot") - ); - sleep(settings.timing.keep_final_frame_for); - return Ok(()); - } - if terminate.load(Ordering::Relaxed) { - return Ok(()); - } - sleep_until_readable( - [ - Some(stdin()), - feed.session_fd(), - requests.as_ref().map(AsFd::as_fd), - ] - .into_iter() - .flatten(), - next_frame.saturating_duration_since(Instant::now()), - )?; - if Instant::now() >= next_frame { - next_frame = Instant::now() + FRAME_INTERVAL; - } - while event::poll(Duration::ZERO)? { - let event = event::read()?; - match &mut password_entry { - Some(entry) => { - if let Err(error) = entry.type_key(&event) { - eprintln!("bootvine: cannot answer the password prompt: {error}"); - } - } - None if asks_to_quit(&event, false) => return Ok(()), - None => {} - } - } - feed.pump(state)?; + let desk = LiveDesk::new( + Console::take(settings.scope == Scope::System), + requests.is_some(), + ); + let password_inputs = requests.map(password_request_inputs).transpose()?; + let inputs = stream::select( + stream::select( + bus_inputs(phase, settings.scope, settings.target.clone()), + key_inputs()?, + ), + stream::select( + stream::select(frame_inputs(), full_repaint_inputs()), + stream::select( + termination_inputs()?, + stream::iter(password_inputs).flatten(), + ), + ), + ); + let mut screen = WatchScreen::new( + BootState::new(phase), + desk, + BootOrigin::read(), + settings.colors, + settings.timing, + Duration::ZERO, + ); + 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), + WatchEnding::BootCompleted | WatchEnding::ViewerLeft => Ok(()), } } diff --git a/src/console_session/watch_screen.rs b/src/console_session/watch_screen.rs new file mode 100644 index 0000000..bd4e55a --- /dev/null +++ b/src/console_session/watch_screen.rs @@ -0,0 +1,222 @@ +use std::{future::ready, ops::ControlFlow, time::Duration}; + +use crossterm::event::Event; +use futures::{Stream, StreamExt}; +use ratatui::{ + Terminal, + backend::Backend, + buffer::{Buffer, CellDiffOption}, + style::Modifier, +}; + +use crate::{ + boot_model::{BootChange, BootState, boot_origin::BootOrigin}, + boot_view::{BootView, PasswordPrompt}, + screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs}, + systemd_link::{link_error::Error, monotonic_clock::monotonic_now}, +}; + +const INPUT_BATCH: usize = 64; + +pub enum ScreenInput { + Boot(Vec), + Reconnected, + Key(Event), + Frame, + FullRepaint, + PasswordRequests, + Terminate, + Failed(Error), +} + +pub enum WatchEnding { + BootCompleted, + ViewerLeft, + Failed(Error), +} + +pub trait ConsoleDesk { + fn glyphs(&self) -> &Glyphs; + fn drops_bold(&self) -> bool; + fn prompt(&self, now: Duration) -> Option>; + fn press_key(&mut self, event: &Event, now: Duration) -> ControlFlow; + fn frame_passed(&mut self, state: &mut BootState, now: Duration) -> ControlFlow; + + fn password_requests_changed(&mut self) {} + + fn keep_console_up(&mut self) {} + + fn take_clear_request(&mut self) -> bool { + false + } + + fn refreshed_origin(&self) -> Option { + None + } +} + +pub struct WatchScreen { + pub state: BootState, + pub desk: Desk, + origin: BootOrigin, + full_repaint_due: bool, + colors: Colors, + timing: Timing, + epoch: Duration, +} + +impl WatchScreen { + pub fn new( + state: BootState, + desk: Desk, + origin: BootOrigin, + colors: Colors, + timing: Timing, + epoch: Duration, + ) -> Self { + Self { + state, + desk, + origin, + full_repaint_due: false, + colors, + timing, + epoch, + } + } + + #[must_use] + pub fn now(&self) -> Duration { + monotonic_now().saturating_sub(self.epoch) + } + + fn absorb(&mut self, input: ScreenInput) -> ControlFlow { + let now = self.now(); + match input { + ScreenInput::Boot(changes) => self.apply_boot_changes(changes), + ScreenInput::Reconnected => { + self.full_repaint_due = true; + ControlFlow::Continue(()) + } + ScreenInput::Key(event) => self.desk.press_key(&event, now), + ScreenInput::Frame => self.desk.frame_passed(&mut self.state, now), + ScreenInput::FullRepaint => { + self.desk.keep_console_up(); + self.full_repaint_due = true; + ControlFlow::Continue(()) + } + ScreenInput::PasswordRequests => { + self.desk.password_requests_changed(); + ControlFlow::Continue(()) + } + ScreenInput::Terminate => ControlFlow::Break(WatchEnding::ViewerLeft), + ScreenInput::Failed(error) => ControlFlow::Break(WatchEnding::Failed(error)), + } + } + + fn apply_boot_changes(&mut self, changes: Vec) -> ControlFlow { + let phase_before = self.state.phase; + changes + .into_iter() + .for_each(|change| self.state.apply(change)); + if self.state.phase != phase_before + && let Some(origin) = self.desk.refreshed_origin() + { + self.origin = origin; + } + 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) + } + + fn absorb_batch( + &mut self, + batch: Vec, + terminal: &mut Terminal, + ) -> ControlFlow + where + Error: From, + { + batch.into_iter().try_for_each(|input| self.absorb(input))?; + match self.draw(terminal) { + Ok(()) => ControlFlow::Continue(()), + Err(error) => ControlFlow::Break(WatchEnding::Failed(error)), + } + } + + fn draw(&mut self, terminal: &mut Terminal) -> Result<(), Error> + where + Error: From, + { + if self.desk.take_clear_request() { + terminal.clear()?; + } + let now = self.now(); + let completed = terminal.draw(|canvas| { + canvas.render_widget( + BootView { + state: &self.state, + colors: &self.colors, + timing: &self.timing, + glyphs: self.desk.glyphs(), + now, + origin: &self.origin, + password_prompt: self.desk.prompt(now), + }, + canvas.area(), + ); + if self.desk.drops_bold() { + drop_bold(canvas.buffer_mut()); + } + })?; + if self.full_repaint_due { + let painted = completed.buffer.clone(); + overwrite_every_cell(terminal.backend_mut(), &painted)?; + self.full_repaint_due = false; + } + Ok(()) + } +} + +pub async fn watch_until_ending( + screen: &mut WatchScreen, + terminal: &mut Terminal, + inputs: impl Stream, +) -> WatchEnding +where + Error: From, +{ + inputs + .ready_chunks(INPUT_BATCH) + .filter_map(|batch| ready(screen.absorb_batch(batch, terminal).break_value())) + .take(1) + .fold(WatchEnding::ViewerLeft, |_, ending| ready(ending)) + .await +} + +fn overwrite_every_cell(backend: &mut B, frame: &Buffer) -> Result<(), B::Error> { + backend.draw( + frame + .content + .iter() + .enumerate() + .filter(|(_, cell)| cell.diff_option != CellDiffOption::Skip) + .map(|(index, cell)| { + let (x, y) = frame.pos_of(index); + (x, y, cell) + }), + )?; + backend.flush() +} + +fn drop_bold(frame: &mut Buffer) { + frame + .content + .iter_mut() + .for_each(|cell| cell.modifier.remove(Modifier::BOLD)); +} diff --git a/src/demo_script/scripted_boot.rs b/src/demo_script/scripted_boot.rs index 0001aad..2ba35be 100644 --- a/src/demo_script/scripted_boot.rs +++ b/src/demo_script/scripted_boot.rs @@ -1,25 +1,30 @@ use std::{ collections::{HashMap, HashSet}, io, - time::{Duration, Instant}, + ops::ControlFlow, + time::Duration, }; -use ratatui::{ - DefaultTerminal, - crossterm::event::{self, Event}, -}; +use futures::stream; +use ratatui::{DefaultTerminal, crossterm::event::Event}; +use tokio::runtime::Builder; +use zeroize::Zeroizing; use crate::{ boot_model::{ ActiveState, Activity, BootState, JobKind, JobResult, Phase, UnitFacts, boot_origin::BootOrigin, }, - boot_view::{BootView, PasswordPrompt}, - console_session::passphrase_input, + boot_view::PasswordPrompt, + console_session::{ + passphrase_input, + stream_sources::{frame_inputs, key_inputs}, + watch_screen::{ConsoleDesk, WatchEnding, WatchScreen, watch_until_ending}, + }, screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs}, + systemd_link::monotonic_clock::monotonic_now, }; -const FRAME_INTERVAL: Duration = Duration::from_millis(100); const FINAL_FRAME: Duration = Duration::from_secs(3); pub const DEMO_PASSPHRASE: &str = "demo"; @@ -282,70 +287,108 @@ impl Script { } } -fn next_event() -> io::Result> { - if event::poll(FRAME_INTERVAL)? { - event::read().map(Some) - } else { - Ok(None) +struct DemoDesk { + script: Script, + after_switch_root: Option<&'static [Step]>, + describe: fn(&str) -> &'static str, + settled_at: Option, + typed: Zeroizing, + glyphs: Glyphs, +} + +impl ConsoleDesk for DemoDesk { + fn frame_passed(&mut self, state: &mut BootState, now: Duration) -> ControlFlow { + self.script.advance(state, now); + if self.script.is_done() + && let Some(steps) = self.after_switch_root.take() + { + state.switch_root(now); + self.script = Script::begin(steps, self.describe, 1000, state, now); + } + if !self.script.is_done() { + return ControlFlow::Continue(()); + } + let settled_at = *self.settled_at.get_or_insert(now); + if now.saturating_sub(settled_at) >= FINAL_FRAME { + ControlFlow::Break(WatchEnding::BootCompleted) + } else { + ControlFlow::Continue(()) + } + } + + fn glyphs(&self) -> &Glyphs { + &self.glyphs + } + + fn drops_bold(&self) -> bool { + false + } + + fn prompt(&self, now: Duration) -> Option> { + self.script.prompt(&self.typed, now) + } + + fn press_key(&mut self, event: &Event, now: Duration) -> ControlFlow { + let asking = self.script.asking().is_some(); + if passphrase_input::asks_to_quit(event, asking) { + return ControlFlow::Break(WatchEnding::ViewerLeft); + } + if asking + && !self.script.is_checking(now) + && let Some(submitted) = passphrase_input::type_key(&mut self.typed, event) + { + self.script.answer(&submitted, now); + } + ControlFlow::Continue(()) } } -pub fn play(terminal: &mut DefaultTerminal, scenario: &Scenario) -> io::Result<()> { - let clock = Instant::now(); - let now = || clock.elapsed(); - let origin = BootOrigin { +fn demo_origin() -> BootOrigin { + BootOrigin { host: "demo".to_owned(), system: "NixOS 26.11.20261007.39ad350".to_owned(), generation: "42".to_owned(), kernel: "Linux 7.2.9".to_owned(), - }; - let mut state = BootState::new(scenario.phase); - let mut script = Script::begin(scenario.steps, scenario.describe, 1, &mut state, now()); - let mut switched_root = scenario.after_switch_root.is_empty(); - let mut settled_at = None; - let mut typed = passphrase_input::empty(); - loop { - script.advance(&mut state, now()); - if script.is_done() && !switched_root { - state.switch_root(now()); - script = Script::begin( - scenario.after_switch_root, - scenario.describe, - 1000, - &mut state, - now(), - ); - switched_root = true; - } - terminal.draw(|canvas| { - canvas.render_widget( - BootView { - state: &state, - colors: &Colors::default(), - timing: &Timing::default(), - glyphs: &Glyphs::default(), - now: now(), - origin: &origin, - password_prompt: script.prompt(&typed, now()), - }, - canvas.area(), - ); - })?; - if script.is_done() && settled_at.get_or_insert_with(Instant::now).elapsed() >= FINAL_FRAME - { - return Ok(()); - } - if let Some(event) = next_event()? { - let asking = script.asking().is_some(); - if passphrase_input::asks_to_quit(&event, asking) { - return Ok(()); - } - if asking - && !script.is_checking(now()) - && let Some(submitted) = passphrase_input::type_key(&mut typed, &event) - { - script.answer(&submitted, now()); - } - } } } + +async fn play_scenario(terminal: &mut DefaultTerminal, scenario: &Scenario) -> io::Result<()> { + let mut state = BootState::new(scenario.phase); + let script = Script::begin( + scenario.steps, + scenario.describe, + 1, + &mut state, + Duration::ZERO, + ); + let desk = DemoDesk { + script, + after_switch_root: (!scenario.after_switch_root.is_empty()) + .then_some(scenario.after_switch_root), + describe: scenario.describe, + settled_at: None, + typed: passphrase_input::empty(), + glyphs: Glyphs::default(), + }; + let mut screen = WatchScreen::new( + state, + desk, + demo_origin(), + Colors::default(), + Timing::default(), + monotonic_now(), + ); + let inputs = stream::select(frame_inputs(), key_inputs()?); + match watch_until_ending(&mut screen, terminal, inputs).await { + WatchEnding::Failed(error) => Err(io::Error::other(error)), + WatchEnding::BootCompleted | WatchEnding::ViewerLeft => Ok(()), + } +} + +pub fn play(terminal: &mut DefaultTerminal, scenario: &Scenario) -> io::Result<()> { + Builder::new_current_thread() + .enable_io() + .enable_time() + .build()? + .block_on(play_scenario(terminal, scenario)) +} diff --git a/src/systemd_link/boot_feed.rs b/src/systemd_link/boot_feed.rs index b1d2cb4..a2cad6c 100644 --- a/src/systemd_link/boot_feed.rs +++ b/src/systemd_link/boot_feed.rs @@ -1,20 +1,27 @@ use std::{ collections::HashMap, - mem, - os::fd::{AsFd, BorrowedFd}, - process, + iter::once, + mem, process, time::{Duration, Instant}, }; use dbus::Path; +use futures::{Stream, StreamExt, stream}; +use tokio::{io::unix::AsyncFd, time::sleep}; use crate::{ - boot_model::{BootState, HANDOFF_UNIT, JobKind, Phase}, + boot_model::{BootChange, BootState, HANDOFF_UNIT, JobKind, Phase}, + console_session::{ + stream_sources::{ + CarriedItem, FRAME_INTERVAL, readable_or_timeout, readable_source, unfold_carrying, + }, + watch_screen::ScreenInput, + }, systemd_link::{ link_error::Error, monotonic_clock::monotonic_now, switch_root::Sysroot, - systemd_bus::{Scope, Session, Signal}, + systemd_bus::{FetchedUnit, JobListing, Scope, Session, Signal}, }, }; @@ -38,8 +45,9 @@ pub enum RootRequest { } enum Link { - Connected(Session), + Connected(AsyncFd), Connecting { deadline: Instant }, + Finished, } impl Link { @@ -56,144 +64,162 @@ enum RootFs { Host, } -pub struct Feed { - pub connections: u32, +struct TrackedUnit { + name: String, + change: Option, +} + +struct BusFeed { scope: Scope, target: RootRequest, + phase: Phase, link: Link, unit_paths: HashMap, String>, root_fs: RootFs, gave_origin: bool, } -impl Feed { - #[must_use] - pub fn new(phase: Phase, scope: Scope, target: RootRequest) -> Self { +fn boot_inputs(changes: Vec) -> Vec { + if changes.is_empty() { + return Vec::new(); + } + vec![ScreenInput::Boot(changes)] +} + +impl BusFeed { + fn new(phase: Phase, scope: Scope, target: RootRequest) -> Self { Self { - connections: 0, + scope, + target, root_fs: if phase == Phase::Initrd { RootFs::Initrd } else { RootFs::Host }, - scope, - target, + phase, link: Link::connecting(), unit_paths: HashMap::new(), gave_origin: false, } } - #[must_use] - pub fn session_fd(&self) -> Option> { - match &self.link { - Link::Connected(session) => Some(session.as_fd()), - Link::Connecting { .. } => None, + async fn next_inputs(&mut self) -> Option> { + if let Link::Connected(readiness) = &self.link { + readable_or_timeout(readiness, FRAME_INTERVAL).await; + } + match mem::replace(&mut self.link, Link::Finished) { + Link::Finished => None, + Link::Connecting { deadline } => Some(self.connect(deadline).await), + Link::Connected(readiness) => Some(self.receive(readiness)), } } - pub fn pump(&mut self, state: &mut BootState) -> Result<(), Error> { - if state.manager_exited_at.is_some() { - return Ok(()); - } - match mem::replace(&mut self.link, Link::connecting()) { - Link::Connecting { deadline } => self.connect(state, deadline), - Link::Connected(session) => match session.receive() { - Ok(signals) => { - signals - .into_iter() - .for_each(|signal| self.apply(&session, state, signal)); - self.link = Link::Connected(session); - Ok(()) - } - Err(_) => self.lose_connection(state), - }, - } - } - - fn connect(&mut self, state: &mut BootState, deadline: Instant) -> Result<(), Error> { - match self.open_session(state) { - Ok(session) => { - self.link = Link::Connected(session); - self.connections += 1; - Ok(()) - } + async fn connect(&mut self, deadline: Instant) -> Vec { + match self.open_session() { + Ok(changes) => vec![ScreenInput::Boot(changes), ScreenInput::Reconnected], Err(_) if Instant::now() < deadline => { + sleep(FRAME_INTERVAL).await; self.link = Link::Connecting { deadline }; - Ok(()) + Vec::new() } - Err(_) => Err(Error::ManagerUnreachable), + Err(_) => vec![ScreenInput::Failed(Error::ManagerUnreachable)], } } - fn lose_connection(&mut self, state: &mut BootState) -> Result<(), Error> { - match &self.root_fs { - RootFs::SwitchingTo(sysroot) => { - sysroot.enter()?; - self.root_fs = RootFs::Host; - self.unit_paths.clear(); - state.switch_root(monotonic_now()); - } - RootFs::Initrd | RootFs::Host if state.phase == Phase::Shutdown => { - state.manager_exited_at = Some(monotonic_now()); - } - RootFs::Initrd | RootFs::Host => state.forget_jobs(), - } - Ok(()) + fn receive(&mut self, readiness: AsyncFd) -> Vec { + let Ok(signals) = readiness.get_ref().receive() else { + return self.lose_connection(); + }; + let changes = signals + .into_iter() + .flat_map(|signal| self.changes_for(readiness.get_ref(), signal)) + .collect(); + self.link = Link::Connected(readiness); + boot_inputs(changes) } - fn open_session(&mut self, state: &mut BootState) -> Result { + fn lose_connection(&mut self) -> Vec { + let at = monotonic_now(); + let RootFs::SwitchingTo(sysroot) = mem::replace(&mut self.root_fs, RootFs::Host) else { + if self.phase == Phase::Shutdown { + return boot_inputs(vec![BootChange::ManagerExited { at }]); + } + self.link = Link::connecting(); + return boot_inputs(vec![BootChange::ForgetJobs]); + }; + if let Err(error) = sysroot.enter() { + return vec![ScreenInput::Failed(error.into())]; + } + self.unit_paths.clear(); + self.phase = Phase::Host; + self.link = Link::connecting(); + boot_inputs(vec![BootChange::SwitchRoot { at }]) + } + + fn requested_root(&self, session: &Session, jobs: &[JobListing]) -> Result { + let RootRequest::Named(target) = &self.target else { + return if self.phase == Phase::Shutdown { + Ok(SHUTDOWN_ROOTS + .into_iter() + .find(|root| { + jobs.iter() + .any(|job| job.unit == *root && job.kind == JobKind::BringsUp) + }) + .unwrap_or(SHUTDOWN_FALLBACK_ROOT) + .to_owned()) + } else { + session.default_target() + }; + }; + Ok(target.clone()) + } + + fn origin_change(&mut self, session: &Session) -> Result, Error> { + if self.gave_origin { + return Ok(None); + } + self.gave_origin = true; + let origin = if session.boot_in_progress()? { + Duration::ZERO + } else { + monotonic_now() + }; + Ok(Some(BootChange::SetOrigin(origin))) + } + + fn open_session(&mut self) -> Result, Error> { let session = Session::open(self.scope)?; session.subscribe()?; if self.scope == Scope::System { session.set_show_status(SILENT_STATUS).ok(); } - let shutting_down = state.phase == Phase::Shutdown; - let jobs: Vec<_> = session + let shutting_down = self.phase == Phase::Shutdown; + let jobs: Vec = session .list_jobs()? .into_iter() .filter(|job| shutting_down || job.kind == JobKind::BringsUp) .collect(); - let requested_root = match &self.target { - RootRequest::Named(target) => target.clone(), - RootRequest::ManagerDefault if shutting_down => SHUTDOWN_ROOTS - .into_iter() - .find(|root| { - jobs.iter() - .any(|job| job.unit == *root && job.kind == JobKind::BringsUp) - }) - .unwrap_or(SHUTDOWN_FALLBACK_ROOT) - .to_owned(), - RootRequest::ManagerDefault => session.default_target()?, - }; - let milestones = state.milestone_targets.clone(); - if !self.gave_origin { - state.origin = if session.boot_in_progress()? { - Duration::ZERO - } else { - monotonic_now() - }; - self.gave_origin = true; - } - let root = self - .track(&session, state, &requested_root) - .unwrap_or(requested_root); - if let Some(handoff) = self.track(&session, state, HANDOFF_UNIT) { - state.set_handoff(handoff); - } - jobs.iter() + let requested_root = self.requested_root(&session, &jobs)?; + let origin_change = self.origin_change(&session)?; + let tracked_root = self.track(&session, &requested_root); + let root = tracked_root + .as_ref() + .map_or(requested_root, |tracked| tracked.name.clone()); + let tracked_handoff = self.track(&session, HANDOFF_UNIT); + let handoff = tracked_handoff + .as_ref() + .map(|tracked| BootChange::SetHandoff(tracked.name.clone())); + let milestones = BootState::new(self.phase).milestone_targets; + let tracked_changes: Vec = jobs + .iter() .map(|job| job.unit.as_str()) .chain(milestones.iter().map(String::as_str)) - .for_each(|unit| { - self.track(&session, state, unit); - }); - state.set_root(root.clone()); - let now = monotonic_now(); - jobs.iter() - .for_each(|job| state.queue_job(job.id, &job.unit, job.kind, now)); + .filter_map(|unit| self.track(&session, unit)) + .filter_map(|tracked| tracked.change) + .collect(); eprintln!( "bootvine: watching {root} in {} as pid {} over {}", - state.phase.label(), + self.phase.label(), process::id(), if session.peer_to_peer { "the private socket" @@ -201,55 +227,116 @@ impl Feed { "the bus" }, ); - Ok(session) + let queued_at = monotonic_now(); + let changes = origin_change + .into_iter() + .chain(tracked_root.and_then(|tracked| tracked.change)) + .chain(tracked_handoff.and_then(|tracked| tracked.change)) + .chain(handoff) + .chain(tracked_changes) + .chain(once(BootChange::SetRoot(root))) + .chain(jobs.into_iter().map(|job| BootChange::QueueJob { + id: job.id, + unit: job.unit, + kind: job.kind, + at: queued_at, + })) + .collect(); + self.link = Link::Connected(readable_source(session)?); + Ok(changes) } - fn track(&mut self, session: &Session, state: &mut BootState, unit: &str) -> Option { + fn track(&mut self, session: &Session, unit: &str) -> Option { if let Some(known) = self.unit_paths.values().find(|known| *known == unit) { - return Some(known.clone()); + return Some(TrackedUnit { + name: known.clone(), + change: None, + }); } - let fetched = session.fetch_unit(unit).ok()?; - let canonical = fetched.facts.name.clone(); - if self.unit_paths.values().any(|known| *known == canonical) { - return Some(canonical); + let FetchedUnit { + path, + facts, + activity, + } = session.fetch_unit(unit).ok()?; + let name = facts.name.clone(); + if self.unit_paths.values().any(|known| *known == name) { + return Some(TrackedUnit { name, change: None }); } - self.unit_paths.insert(fetched.path, canonical.clone()); - state.track_unit(fetched.facts, fetched.activity); - Some(canonical) + self.unit_paths.insert(path, name.clone()); + Some(TrackedUnit { + name, + change: Some(BootChange::TrackUnit { facts, activity }), + }) } - fn apply(&mut self, session: &Session, state: &mut BootState, signal: Signal) { + fn changes_for(&mut self, session: &Session, signal: Signal) -> Vec { + let at = monotonic_now(); match signal { - Signal::JobNew { id, job, unit } => { - let kind = session.job_kind(&job).unwrap_or(JobKind::Unknown); - if kind == JobKind::TakesDown && state.phase != Phase::Shutdown { - return; - } - let unit = self.track(session, state, &unit).unwrap_or(unit); - if matches!(self.root_fs, RootFs::Initrd) - && unit == SWITCH_ROOT_UNIT - && let Ok(sysroot) = Sysroot::hold() - { - self.root_fs = RootFs::SwitchingTo(sysroot); - } - state.queue_job(id, &unit, kind, monotonic_now()); - } - Signal::JobRemoved { id, result } => state.finish_job(id, result, monotonic_now()), - Signal::UnitChanged { path, activity } => { - if let Some(unit) = self.unit_paths.get(&path) { - state.update_activity(unit, activity); - } - } + Signal::JobNew { id, job, unit } => self.queue_new_job(session, id, &job, unit, at), + 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(), } } + + fn queue_new_job( + &mut self, + session: &Session, + id: u32, + job: &Path<'static>, + unit: String, + at: Duration, + ) -> Vec { + let kind = session.job_kind(job).unwrap_or(JobKind::Unknown); + if kind == JobKind::TakesDown && self.phase != Phase::Shutdown { + return Vec::new(); + } + let tracked = self.track(session, &unit); + let unit = tracked + .as_ref() + .map_or(unit, |tracked| tracked.name.clone()); + if matches!(self.root_fs, RootFs::Initrd) + && unit == SWITCH_ROOT_UNIT + && let Ok(sysroot) = Sysroot::hold() + { + self.root_fs = RootFs::SwitchingTo(sysroot); + } + tracked + .and_then(|tracked| tracked.change) + .into_iter() + .chain(once(BootChange::QueueJob { id, unit, kind, at })) + .collect() + } } -impl Drop for Feed { +impl Drop for BusFeed { fn drop(&mut self) { - if let Link::Connected(session) = &self.link + if let Link::Connected(readiness) = &self.link && self.scope == Scope::System { - session.set_show_status(CONFIGURED_STATUS).ok(); + readiness.get_ref().set_show_status(CONFIGURED_STATUS).ok(); } } } + +pub fn bus_inputs( + phase: Phase, + scope: Scope, + target: RootRequest, +) -> impl Stream { + unfold_carrying(BusFeed::new(phase, scope, target), |mut feed| async move { + let inputs = feed.next_inputs().await?; + Some(CarriedItem { + item: inputs, + state: feed, + }) + }) + .flat_map(stream::iter) +} diff --git a/src/systemd_link/link_error.rs b/src/systemd_link/link_error.rs index 5bbf82b..56babd2 100644 --- a/src/systemd_link/link_error.rs +++ b/src/systemd_link/link_error.rs @@ -1,4 +1,4 @@ -use std::io; +use std::{convert::Infallible, io}; use dbus::{Error as BusError, arg::TypeMismatchError}; use rustix::io::Errno; @@ -20,3 +20,9 @@ pub enum Error { #[error("the service manager did not come back")] ManagerUnreachable, } + +impl From for Error { + fn from(never: Infallible) -> Self { + match never {} + } +} diff --git a/src/systemd_link/systemd_bus.rs b/src/systemd_link/systemd_bus.rs index 26c5d3d..f31dc95 100644 --- a/src/systemd_link/systemd_bus.rs +++ b/src/systemd_link/systemd_bus.rs @@ -1,6 +1,6 @@ use std::{ iter, - os::fd::{AsFd, BorrowedFd}, + os::fd::{AsRawFd, RawFd}, time::Duration, }; @@ -246,9 +246,9 @@ impl Session { } } -impl AsFd for Session { - fn as_fd(&self) -> BorrowedFd<'_> { - unsafe { BorrowedFd::borrow_raw(self.channel.watch().fd) } +impl AsRawFd for Session { + fn as_raw_fd(&self) -> RawFd { + self.channel.watch().fd } }