refactor: reduce polling
This commit is contained in:
1 parent
589d0b7655
commit
bca6637599
6 files changed
+157
-60
No files matched your search
+3
-1
@@ -26,7 +26,9 @@ libraries that clash with QEMU's.
|
|||||||
- No comments or doc comments; intent lives in names and call flow.
|
- No comments or doc comments; intent lives in names and call flow.
|
||||||
- Pub fields instead of getters, `Duration` instead of raw integers, crates
|
- Pub fields instead of getters, `Duration` instead of raw integers, crates
|
||||||
instead of hand-written formatting.
|
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.
|
- Ratatui views are built declaratively from iterators.
|
||||||
|
|
||||||
## systemd's private socket
|
## systemd's private socket
|
||||||
|
|||||||
+1
-1
@@ -15,7 +15,7 @@ crossterm = "0.29.0"
|
|||||||
dbus = "0.9.12"
|
dbus = "0.9.12"
|
||||||
jiff = { version = "0.2.38", default-features = false, features = ["serde", "std"] }
|
jiff = { version = "0.2.38", default-features = false, features = ["serde", "std"] }
|
||||||
ratatui = { version = "0.30.2", features = ["serde", "unstable-rendered-line-info"] }
|
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"] }
|
serde = { version = "1.0.229", features = ["derive"] }
|
||||||
signal-hook = "0.4.5"
|
signal-hook = "0.4.5"
|
||||||
toml = "1.1.8"
|
toml = "1.1.8"
|
||||||
|
|||||||
+7
-12
@@ -2,7 +2,6 @@ use std::{
|
|||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
path::Path as FilePath,
|
path::Path as FilePath,
|
||||||
process,
|
process,
|
||||||
thread::sleep,
|
|
||||||
time::{Duration, Instant},
|
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() {
|
if state.manager_exited_at.is_some() {
|
||||||
sleep(wait);
|
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let Some(session) = self.session.take() else {
|
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) => {
|
Ok(signals) => {
|
||||||
signals
|
signals
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -78,17 +76,14 @@ impl Feed {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn connect_or_wait(&mut self, state: &mut BootState, wait: Duration) -> Result<(), Error> {
|
fn connect(&mut self, state: &mut BootState) -> Result<(), Error> {
|
||||||
match self.connect(state) {
|
match self.open_session(state) {
|
||||||
Ok(session) => {
|
Ok(session) => {
|
||||||
self.session = Some(session);
|
self.session = Some(session);
|
||||||
self.connections += 1;
|
self.connections += 1;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Err(_) if Instant::now() < self.reconnect_deadline => {
|
Err(_) if Instant::now() < self.reconnect_deadline => Ok(()),
|
||||||
sleep(wait);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
Err(_) => Err(Error::ManagerUnreachable),
|
Err(_) => Err(Error::ManagerUnreachable),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -110,7 +105,7 @@ impl Feed {
|
|||||||
Ok(())
|
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)?;
|
let session = Session::open(self.scope)?;
|
||||||
session.subscribe()?;
|
session.subscribe()?;
|
||||||
if self.scope == Scope::System {
|
if self.scope == Scope::System {
|
||||||
|
|||||||
+74
-20
@@ -1,13 +1,20 @@
|
|||||||
use std::{
|
use std::{
|
||||||
fs, io,
|
fs, io, iter,
|
||||||
os::unix::net::UnixDatagram,
|
os::{
|
||||||
|
fd::{AsFd, BorrowedFd, OwnedFd},
|
||||||
|
unix::net::UnixDatagram,
|
||||||
|
},
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
time::Duration,
|
time::Duration,
|
||||||
};
|
};
|
||||||
|
|
||||||
use bootvine::{passphrase, view::PasswordPrompt};
|
use bootvine::{passphrase, view::PasswordPrompt};
|
||||||
use crossterm::event::Event;
|
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 zeroize::Zeroizing;
|
||||||
|
|
||||||
use crate::clock::monotonic_now;
|
use crate::clock::monotonic_now;
|
||||||
@@ -15,6 +22,46 @@ use crate::clock::monotonic_now;
|
|||||||
const REQUESTS: &str = "/run/systemd/ask-password";
|
const REQUESTS: &str = "/run/systemd/ask-password";
|
||||||
const REQUEST_PREFIX: &str = "ask.";
|
const REQUEST_PREFIX: &str = "ask.";
|
||||||
const ASK_SECTION: &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)]
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
pub struct PasswordRequest {
|
pub struct PasswordRequest {
|
||||||
@@ -49,13 +96,6 @@ fn request_files() -> Vec<PathBuf> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PasswordRequest {
|
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> {
|
fn read(file: &Path) -> Option<Self> {
|
||||||
Self::parse(file, &fs::read_to_string(file).ok()?)
|
Self::parse(file, &fs::read_to_string(file).ok()?)
|
||||||
}
|
}
|
||||||
@@ -92,11 +132,9 @@ impl PasswordRequest {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_live(&self) -> bool {
|
fn is_awaited(&self) -> bool {
|
||||||
self.file.exists()
|
self.not_after
|
||||||
&& self
|
.is_none_or(|deadline| monotonic_now() <= deadline)
|
||||||
.not_after
|
|
||||||
.is_none_or(|deadline| monotonic_now() <= deadline)
|
|
||||||
&& self
|
&& self
|
||||||
.asker
|
.asker
|
||||||
.is_none_or(|asker| test_kill_process(asker).is_ok())
|
.is_none_or(|asker| test_kill_process(asker).is_ok())
|
||||||
@@ -125,15 +163,27 @@ pub struct PasswordEntry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PasswordEntry {
|
impl PasswordEntry {
|
||||||
pub fn follow(current: Option<Self>) -> Option<Self> {
|
pub fn follow(current: Option<Self>, requests_changed: bool) -> Option<Self> {
|
||||||
if let Some(entry) = current.filter(|entry| entry.request.is_live()) {
|
match current {
|
||||||
return Some(entry);
|
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!(
|
eprintln!(
|
||||||
"bootvine: asking for a password: {}",
|
"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 {
|
Some(Self {
|
||||||
request,
|
request,
|
||||||
typed: passphrase::empty(),
|
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<'_> {
|
pub fn prompt(&self) -> PasswordPrompt<'_> {
|
||||||
let input = if self.request.silent {
|
let input = if self.request.silent {
|
||||||
String::new()
|
String::new()
|
||||||
|
|||||||
+46
-5
@@ -1,4 +1,6 @@
|
|||||||
use std::{
|
use std::{
|
||||||
|
io,
|
||||||
|
os::fd::{AsFd, BorrowedFd},
|
||||||
path::Path,
|
path::Path,
|
||||||
sync::{
|
sync::{
|
||||||
Arc,
|
Arc,
|
||||||
@@ -21,6 +23,12 @@ use ratatui::{
|
|||||||
backend::Backend,
|
backend::Backend,
|
||||||
buffer::{Buffer, CellDiffOption},
|
buffer::{Buffer, CellDiffOption},
|
||||||
};
|
};
|
||||||
|
use rustix::{
|
||||||
|
event::{PollFd, PollFlags, poll},
|
||||||
|
io::Errno,
|
||||||
|
stdio::stdin,
|
||||||
|
time::Timespec,
|
||||||
|
};
|
||||||
use signal_hook::{consts::SIGTERM, flag};
|
use signal_hook::{consts::SIGTERM, flag};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -28,7 +36,7 @@ use crate::{
|
|||||||
console::Console,
|
console::Console,
|
||||||
error::Error,
|
error::Error,
|
||||||
feed::Feed,
|
feed::Feed,
|
||||||
password::PasswordEntry,
|
password::{PasswordEntry, RequestWatch},
|
||||||
sysroot::INITRD_RELEASE,
|
sysroot::INITRD_RELEASE,
|
||||||
systemd::{Scope, Session},
|
systemd::{Scope, Session},
|
||||||
};
|
};
|
||||||
@@ -79,6 +87,23 @@ pub fn run(options: &Options) -> Result<(), Error> {
|
|||||||
watched
|
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 {
|
fn asks_to_quit(event: &Event) -> bool {
|
||||||
let Event::Key(KeyEvent {
|
let Event::Key(KeyEvent {
|
||||||
code, modifiers, ..
|
code, modifiers, ..
|
||||||
@@ -119,18 +144,21 @@ fn watch(
|
|||||||
let mut frame: u64 = 0;
|
let mut frame: u64 = 0;
|
||||||
let mut painted_connections = feed.connections;
|
let mut painted_connections = feed.connections;
|
||||||
let mut last_full_repaint = Instant::now();
|
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;
|
let mut password_entry: Option<PasswordEntry> = None;
|
||||||
loop {
|
loop {
|
||||||
feed.pump(state, FRAME_INTERVAL)?;
|
feed.pump(state)?;
|
||||||
if state.phase != origin_phase {
|
if state.phase != origin_phase {
|
||||||
origin = BootOrigin::read();
|
origin = BootOrigin::read();
|
||||||
origin_phase = state.phase;
|
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()?;
|
terminal.clear()?;
|
||||||
}
|
}
|
||||||
password_entry = if console.answers_password_prompts() {
|
password_entry = if console.answers_password_prompts() {
|
||||||
PasswordEntry::follow(password_entry.take())
|
PasswordEntry::follow(password_entry.take(), requests_changed)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
@@ -171,6 +199,20 @@ fn watch(
|
|||||||
if terminate.load(Ordering::Relaxed) {
|
if terminate.load(Ordering::Relaxed) {
|
||||||
return Ok(());
|
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)? {
|
while event::poll(Duration::ZERO)? {
|
||||||
let event = event::read()?;
|
let event = event::read()?;
|
||||||
match &mut password_entry {
|
match &mut password_entry {
|
||||||
@@ -183,6 +225,5 @@ fn watch(
|
|||||||
None => {}
|
None => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
frame += 1;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+26
-21
@@ -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 bootvine::model::{ActiveState, Activity, JobKind, JobResult, UnitFacts};
|
||||||
use dbus::{
|
use dbus::{
|
||||||
@@ -88,19 +92,13 @@ impl Session {
|
|||||||
&& let Ok(channel) = Channel::open_private(PRIVATE_SOCKET)
|
&& let Ok(channel) = Channel::open_private(PRIVATE_SOCKET)
|
||||||
{
|
{
|
||||||
send_authentication_carrier(&channel)?;
|
send_authentication_carrier(&channel)?;
|
||||||
return Ok(Self {
|
return Ok(Self::watching(channel, true));
|
||||||
channel,
|
|
||||||
peer_to_peer: true,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
let bus = match scope {
|
let bus = match scope {
|
||||||
Scope::System => BusType::System,
|
Scope::System => BusType::System,
|
||||||
Scope::User => BusType::Session,
|
Scope::User => BusType::Session,
|
||||||
};
|
};
|
||||||
let session = Self {
|
let session = Self::watching(Channel::get_private(bus)?, false);
|
||||||
channel: Channel::get_private(bus)?,
|
|
||||||
peer_to_peer: false,
|
|
||||||
};
|
|
||||||
session.call(
|
session.call(
|
||||||
BUS_DESTINATION,
|
BUS_DESTINATION,
|
||||||
BUS_PATH,
|
BUS_PATH,
|
||||||
@@ -111,6 +109,14 @@ impl Session {
|
|||||||
Ok(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(
|
fn call(
|
||||||
&self,
|
&self,
|
||||||
destination: &str,
|
destination: &str,
|
||||||
@@ -237,20 +243,19 @@ impl Session {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn receive(&self, timeout: Duration) -> Result<Vec<Signal>, Error> {
|
pub fn receive(&self) -> Result<Vec<Signal>, Error> {
|
||||||
let drain = || -> Vec<Signal> {
|
if self.channel.read_write(Some(Duration::ZERO)).is_err() || !self.channel.is_connected() {
|
||||||
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() {
|
|
||||||
return Err(Error::Disconnected);
|
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) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user