refactor: drive the watch loop with async streams in the Elm style
Every source is a stream of ScreenInput values: the systemd bus (resolved into BootChange values), keys, frame ticks, full repaints, password requests and SIGTERM. They are merged with stream::select and folded by one owned WatchScreen, drawing once per ready batch. The live boot and the scripted demo share the fold and differ only in their console desk. tokio current-thread replaces poll(2) and signal-hook. Release binary: 1.74 MB -> 1.86 MB.
This commit is contained in:
1 parent
ba6e934412
commit
d0063c2371
14 files changed
+948
-412
No files matched your search
@@ -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<Item = BorrowedFd<'fd>>,
|
||||
timeout: Duration,
|
||||
) -> io::Result<()> {
|
||||
let mut watched: Vec<PollFd<'fd>> = 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<B: Backend>(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<PasswordEntry> = 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(()),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user