refactor: reduce polling

This commit is contained in:
Willem Vanhulle committed 2026-10-16 11:42:52 +02:00
1 parent 589d0b7655
commit bca6637599
6 files changed
+157 -60

No files matched your search

+3 -1
View File
@@ -26,7 +26,9 @@ libraries that clash with QEMU's.
- No comments or doc comments; intent lives in names and call flow.
- Pub fields instead of getters, `Duration` instead of raw integers, crates
instead of hand-written formatting.
- One thread: the loop waits on the bus with a timeout, then draws.
- One thread: the loop sleeps in one `poll(2)` on the terminal, the bus and an
inotify watch on `/run/systemd/ask-password`, with the next frame as timeout,
then draws.
- Ratatui views are built declaratively from iterators.
## systemd's private socket
+1 -1
View File
@@ -15,7 +15,7 @@ crossterm = "0.29.0"
dbus = "0.9.12"
jiff = { version = "0.2.38", default-features = false, features = ["serde", "std"] }
ratatui = { version = "0.30.2", features = ["serde", "unstable-rendered-line-info"] }
rustix = { version = "1.1.5", features = ["fs", "process", "stdio", "system", "termios", "time"] }
rustix = { version = "1.1.5", features = ["event", "fs", "process", "stdio", "system", "termios", "time"] }
serde = { version = "1.0.229", features = ["derive"] }
signal-hook = "0.4.5"
toml = "1.1.8"
+7 -12
View File
@@ -2,7 +2,6 @@ use std::{
collections::HashMap,
path::Path as FilePath,
process,
thread::sleep,
time::{Duration, Instant},
};
@@ -58,15 +57,14 @@ impl Feed {
}
}
pub fn pump(&mut self, state: &mut BootState, wait: Duration) -> Result<(), Error> {
pub fn pump(&mut self, state: &mut BootState) -> Result<(), Error> {
if state.manager_exited_at.is_some() {
sleep(wait);
return Ok(());
}
let Some(session) = self.session.take() else {
return self.connect_or_wait(state, wait);
return self.connect(state);
};
match session.receive(wait) {
match session.receive() {
Ok(signals) => {
signals
.into_iter()
@@ -78,17 +76,14 @@ impl Feed {
Ok(())
}
fn connect_or_wait(&mut self, state: &mut BootState, wait: Duration) -> Result<(), Error> {
match self.connect(state) {
fn connect(&mut self, state: &mut BootState) -> Result<(), Error> {
match self.open_session(state) {
Ok(session) => {
self.session = Some(session);
self.connections += 1;
Ok(())
}
Err(_) if Instant::now() < self.reconnect_deadline => {
sleep(wait);
Ok(())
}
Err(_) if Instant::now() < self.reconnect_deadline => Ok(()),
Err(_) => Err(Error::ManagerUnreachable),
}
}
@@ -110,7 +105,7 @@ impl Feed {
Ok(())
}
fn connect(&mut self, state: &mut BootState) -> Result<Session, Error> {
fn open_session(&mut self, state: &mut BootState) -> Result<Session, Error> {
let session = Session::open(self.scope)?;
session.subscribe()?;
if self.scope == Scope::System {
+74 -20
View File
@@ -1,13 +1,20 @@
use std::{
fs, io,
os::unix::net::UnixDatagram,
fs, io, iter,
os::{
fd::{AsFd, BorrowedFd, OwnedFd},
unix::net::UnixDatagram,
},
path::{Path, PathBuf},
time::Duration,
};
use bootvine::{passphrase, view::PasswordPrompt};
use crossterm::event::Event;
use rustix::process::{Pid, test_kill_process};
use rustix::{
fs::inotify::{self, CreateFlags, WatchFlags},
io::read,
process::{Pid, test_kill_process},
};
use zeroize::Zeroizing;
use crate::clock::monotonic_now;
@@ -15,6 +22,46 @@ use crate::clock::monotonic_now;
const REQUESTS: &str = "/run/systemd/ask-password";
const REQUEST_PREFIX: &str = "ask.";
const ASK_SECTION: &str = "[Ask]";
const INOTIFY_BUFFER: usize = 4096;
pub struct RequestWatch {
inotify: OwnedFd,
}
impl RequestWatch {
pub fn open() -> Option<Self> {
fs::create_dir_all(REQUESTS).ok()?;
let inotify = inotify::init(CreateFlags::CLOEXEC | CreateFlags::NONBLOCK).ok()?;
inotify::add_watch(
&inotify,
REQUESTS,
WatchFlags::CLOSE_WRITE
| WatchFlags::MOVED_TO
| WatchFlags::MOVED_FROM
| WatchFlags::DELETE
| WatchFlags::ONLYDIR,
)
.ok()?;
Some(Self { inotify })
}
pub fn changed(&self) -> bool {
let mut events = [0_u8; INOTIFY_BUFFER];
iter::from_fn(|| {
read(&self.inotify, &mut events)
.ok()
.filter(|read| *read > 0)
})
.count()
> 0
}
}
impl AsFd for RequestWatch {
fn as_fd(&self) -> BorrowedFd<'_> {
self.inotify.as_fd()
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct PasswordRequest {
@@ -49,13 +96,6 @@ fn request_files() -> Vec<PathBuf> {
}
impl PasswordRequest {
fn first_live() -> Option<Self> {
request_files()
.iter()
.filter_map(|file| Self::read(file))
.find(Self::is_live)
}
fn read(file: &Path) -> Option<Self> {
Self::parse(file, &fs::read_to_string(file).ok()?)
}
@@ -92,11 +132,9 @@ impl PasswordRequest {
})
}
fn is_live(&self) -> bool {
self.file.exists()
&& self
.not_after
.is_none_or(|deadline| monotonic_now() <= deadline)
fn is_awaited(&self) -> bool {
self.not_after
.is_none_or(|deadline| monotonic_now() <= deadline)
&& self
.asker
.is_none_or(|asker| test_kill_process(asker).is_ok())
@@ -125,15 +163,27 @@ pub struct PasswordEntry {
}
impl PasswordEntry {
pub fn follow(current: Option<Self>) -> Option<Self> {
if let Some(entry) = current.filter(|entry| entry.request.is_live()) {
return Some(entry);
pub fn follow(current: Option<Self>, requests_changed: bool) -> Option<Self> {
match current {
Some(entry) if entry.is_live(requests_changed) => return Some(entry),
None if !requests_changed => return None,
_ => {}
}
let request = PasswordRequest::first_live()?;
let entry = request_files()
.iter()
.filter_map(|file| PasswordRequest::read(file))
.find_map(Self::open)?;
eprintln!(
"bootvine: asking for a password: {}",
request.file.display()
entry.request.file.display()
);
Some(entry)
}
fn open(request: PasswordRequest) -> Option<Self> {
if !request.is_awaited() {
return None;
}
Some(Self {
request,
typed: passphrase::empty(),
@@ -141,6 +191,10 @@ impl PasswordEntry {
})
}
fn is_live(&self, requests_changed: bool) -> bool {
self.request.is_awaited() && (!requests_changed || self.request.file.exists())
}
pub fn prompt(&self) -> PasswordPrompt<'_> {
let input = if self.request.silent {
String::new()
+46 -5
View File
@@ -1,4 +1,6 @@
use std::{
io,
os::fd::{AsFd, BorrowedFd},
path::Path,
sync::{
Arc,
@@ -21,6 +23,12 @@ use ratatui::{
backend::Backend,
buffer::{Buffer, CellDiffOption},
};
use rustix::{
event::{PollFd, PollFlags, poll},
io::Errno,
stdio::stdin,
time::Timespec,
};
use signal_hook::{consts::SIGTERM, flag};
use crate::{
@@ -28,7 +36,7 @@ use crate::{
console::Console,
error::Error,
feed::Feed,
password::PasswordEntry,
password::{PasswordEntry, RequestWatch},
sysroot::INITRD_RELEASE,
systemd::{Scope, Session},
};
@@ -79,6 +87,23 @@ pub fn run(options: &Options) -> Result<(), Error> {
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 asks_to_quit(event: &Event) -> bool {
let Event::Key(KeyEvent {
code, modifiers, ..
@@ -119,18 +144,21 @@ fn watch(
let mut frame: u64 = 0;
let mut painted_connections = feed.connections;
let mut last_full_repaint = Instant::now();
let mut next_frame = Instant::now() + FRAME_INTERVAL;
let requests = RequestWatch::open();
let mut password_entry: Option<PasswordEntry> = None;
loop {
feed.pump(state, FRAME_INTERVAL)?;
feed.pump(state)?;
if state.phase != origin_phase {
origin = BootOrigin::read();
origin_phase = state.phase;
}
if console.come_forward_once_prompts_are_gone() {
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())
PasswordEntry::follow(password_entry.take(), requests_changed)
} else {
None
};
@@ -171,6 +199,20 @@ fn watch(
if terminate.load(Ordering::Relaxed) {
return Ok(());
}
sleep_until_readable(
[
Some(stdin()),
feed.session.as_ref().map(AsFd::as_fd),
requests.as_ref().map(AsFd::as_fd),
]
.into_iter()
.flatten(),
next_frame.saturating_duration_since(Instant::now()),
)?;
if Instant::now() >= next_frame {
frame += 1;
next_frame = Instant::now() + FRAME_INTERVAL;
}
while event::poll(Duration::ZERO)? {
let event = event::read()?;
match &mut password_entry {
@@ -183,6 +225,5 @@ fn watch(
None => {}
}
}
frame += 1;
}
}
+26 -21
View File
@@ -1,4 +1,8 @@
use std::{iter, time::Duration};
use std::{
iter,
os::fd::{AsFd, BorrowedFd},
time::Duration,
};
use bootvine::model::{ActiveState, Activity, JobKind, JobResult, UnitFacts};
use dbus::{
@@ -88,19 +92,13 @@ impl Session {
&& let Ok(channel) = Channel::open_private(PRIVATE_SOCKET)
{
send_authentication_carrier(&channel)?;
return Ok(Self {
channel,
peer_to_peer: true,
});
return Ok(Self::watching(channel, true));
}
let bus = match scope {
Scope::System => BusType::System,
Scope::User => BusType::Session,
};
let session = Self {
channel: Channel::get_private(bus)?,
peer_to_peer: false,
};
let session = Self::watching(Channel::get_private(bus)?, false);
session.call(
BUS_DESTINATION,
BUS_PATH,
@@ -111,6 +109,14 @@ impl Session {
Ok(session)
}
fn watching(mut channel: Channel, peer_to_peer: bool) -> Self {
channel.set_watch_enabled(true);
Self {
channel,
peer_to_peer,
}
}
fn call(
&self,
destination: &str,
@@ -237,20 +243,19 @@ impl Session {
})
}
pub fn receive(&self, timeout: Duration) -> Result<Vec<Signal>, Error> {
let drain = || -> Vec<Signal> {
iter::from_fn(|| self.channel.pop_message())
.filter_map(|message| parse_signal(&message))
.collect()
};
let queued = drain();
if !queued.is_empty() {
return Ok(queued);
}
if self.channel.read_write(Some(timeout)).is_err() || !self.channel.is_connected() {
pub fn receive(&self) -> Result<Vec<Signal>, Error> {
if self.channel.read_write(Some(Duration::ZERO)).is_err() || !self.channel.is_connected() {
return Err(Error::Disconnected);
}
Ok(drain())
Ok(iter::from_fn(|| self.channel.pop_message())
.filter_map(|message| parse_signal(&message))
.collect())
}
}
impl AsFd for Session {
fn as_fd(&self) -> BorrowedFd<'_> {
unsafe { BorrowedFd::borrow_raw(self.channel.watch().fd) }
}
}