perf: await systemd replies instead of blocking the screen
Calls send their message and await the reply on the registered socket while the other streams keep drawing; signals that arrive meanwhile are queued for the next receive. Restoring systemd's status output moves to a guard that reconnects on exit, so it no longer depends on where the feed was suspended. Status modes are an enum instead of raw strings.
This commit is contained in:
1 parent
cb600e0f26
commit
092ed41ffb
4 files changed
+367
-179
No files matched your search
@@ -17,7 +17,7 @@ use crate::{
|
|||||||
boot_feed::{RootRequest, bus_inputs},
|
boot_feed::{RootRequest, bus_inputs},
|
||||||
link_error::Error,
|
link_error::Error,
|
||||||
switch_root::INITRD_RELEASE,
|
switch_root::INITRD_RELEASE,
|
||||||
systemd_bus::{Scope, Session},
|
systemd_bus::{Scope, Session, StatusOutput},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -29,6 +29,20 @@ pub struct Settings {
|
|||||||
pub colors: Colors,
|
pub colors: Colors,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct ConfiguredStatusOnExit {
|
||||||
|
scope: Scope,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for ConfiguredStatusOnExit {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if self.scope == Scope::System
|
||||||
|
&& let Ok(session) = Session::open(Scope::System)
|
||||||
|
{
|
||||||
|
session.set_show_status(StatusOutput::Configured).ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn boot_already_finished(settings: &Settings) -> bool {
|
fn boot_already_finished(settings: &Settings) -> bool {
|
||||||
settings.scope == Scope::System
|
settings.scope == Scope::System
|
||||||
&& !settings.shutdown
|
&& !settings.shutdown
|
||||||
@@ -59,6 +73,9 @@ pub fn run(settings: &Settings) -> Result<(), Error> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn watch_live_boot(settings: &Settings, phase: Phase) -> Result<(), Error> {
|
async fn watch_live_boot(settings: &Settings, phase: Phase) -> Result<(), Error> {
|
||||||
|
let _restores_status = ConfiguredStatusOnExit {
|
||||||
|
scope: settings.scope,
|
||||||
|
};
|
||||||
let requests = RequestWatch::open();
|
let requests = RequestWatch::open();
|
||||||
let desk = LiveDesk::new(
|
let desk = LiveDesk::new(
|
||||||
Console::take(settings.scope == Scope::System),
|
Console::take(settings.scope == Scope::System),
|
||||||
|
|||||||
+129
-75
@@ -7,21 +7,21 @@ use std::{
|
|||||||
|
|
||||||
use dbus::Path;
|
use dbus::Path;
|
||||||
use futures::{Stream, StreamExt, stream};
|
use futures::{Stream, StreamExt, stream};
|
||||||
use tokio::{io::unix::AsyncFd, time::sleep};
|
use tokio::time::sleep;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
boot_model::{BootChange, BootState, HANDOFF_UNIT, JobKind, Phase},
|
boot_model::{BootChange, BootState, HANDOFF_UNIT, JobKind, Phase},
|
||||||
console_session::{
|
console_session::{
|
||||||
stream_sources::{
|
stream_sources::{CarriedItem, FRAME_INTERVAL, unfold_carrying},
|
||||||
CarriedItem, FRAME_INTERVAL, readable_or_timeout, readable_source, unfold_carrying,
|
|
||||||
},
|
|
||||||
watch_screen::ScreenInput,
|
watch_screen::ScreenInput,
|
||||||
},
|
},
|
||||||
systemd_link::{
|
systemd_link::{
|
||||||
link_error::Error,
|
link_error::Error,
|
||||||
monotonic_clock::monotonic_now,
|
monotonic_clock::monotonic_now,
|
||||||
switch_root::Sysroot,
|
switch_root::Sysroot,
|
||||||
systemd_bus::{FetchedUnit, JobListing, Scope, Session, Signal},
|
systemd_bus::{
|
||||||
|
BusConnection, FetchedUnit, JobListing, Scope, Session, Signal, StatusOutput,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -35,8 +35,6 @@ const SHUTDOWN_ROOTS: [&str; 5] = [
|
|||||||
"soft-reboot.target",
|
"soft-reboot.target",
|
||||||
];
|
];
|
||||||
const SHUTDOWN_FALLBACK_ROOT: &str = "shutdown.target";
|
const SHUTDOWN_FALLBACK_ROOT: &str = "shutdown.target";
|
||||||
const SILENT_STATUS: &str = "no";
|
|
||||||
const CONFIGURED_STATUS: &str = "";
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub enum RootRequest {
|
pub enum RootRequest {
|
||||||
@@ -45,7 +43,7 @@ pub enum RootRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
enum Link {
|
enum Link {
|
||||||
Connected(AsyncFd<Session>),
|
Connected(BusConnection),
|
||||||
Connecting { deadline: Instant },
|
Connecting { deadline: Instant },
|
||||||
Finished,
|
Finished,
|
||||||
}
|
}
|
||||||
@@ -79,6 +77,17 @@ struct BusFeed {
|
|||||||
gave_origin: bool,
|
gave_origin: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct FeedProgress<'feed> {
|
||||||
|
feed: &'feed mut BusFeed,
|
||||||
|
connection: &'feed mut BusConnection,
|
||||||
|
changes: Vec<BootChange>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct WatchedConnection {
|
||||||
|
connection: BusConnection,
|
||||||
|
changes: Vec<BootChange>,
|
||||||
|
}
|
||||||
|
|
||||||
fn boot_inputs(changes: Vec<BootChange>) -> Vec<ScreenInput> {
|
fn boot_inputs(changes: Vec<BootChange>) -> Vec<ScreenInput> {
|
||||||
if changes.is_empty() {
|
if changes.is_empty() {
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
@@ -104,19 +113,28 @@ impl BusFeed {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn next_inputs(&mut self) -> Option<Vec<ScreenInput>> {
|
async fn next_inputs(&mut self) -> Option<Vec<ScreenInput>> {
|
||||||
if let Link::Connected(readiness) = &self.link {
|
|
||||||
readable_or_timeout(readiness, FRAME_INTERVAL).await;
|
|
||||||
}
|
|
||||||
match mem::replace(&mut self.link, Link::Finished) {
|
match mem::replace(&mut self.link, Link::Finished) {
|
||||||
Link::Finished => None,
|
Link::Finished => None,
|
||||||
Link::Connecting { deadline } => Some(self.connect(deadline).await),
|
Link::Connecting { deadline } => Some(self.connect(deadline).await),
|
||||||
Link::Connected(readiness) => Some(self.receive(readiness)),
|
Link::Connected(connection) => Some(self.receive(connection).await),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn open_watched(&mut self) -> Result<WatchedConnection, Error> {
|
||||||
|
let mut connection = BusConnection::register(Session::open(self.scope)?)?;
|
||||||
|
let changes = self.start_watching(&mut connection).await?;
|
||||||
|
Ok(WatchedConnection {
|
||||||
|
connection,
|
||||||
|
changes,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
async fn connect(&mut self, deadline: Instant) -> Vec<ScreenInput> {
|
async fn connect(&mut self, deadline: Instant) -> Vec<ScreenInput> {
|
||||||
match self.open_session() {
|
match self.open_watched().await {
|
||||||
Ok(changes) => vec![ScreenInput::Boot(changes), ScreenInput::Reconnected],
|
Ok(watched) => {
|
||||||
|
self.link = Link::Connected(watched.connection);
|
||||||
|
vec![ScreenInput::Boot(watched.changes), ScreenInput::Reconnected]
|
||||||
|
}
|
||||||
Err(_) if Instant::now() < deadline => {
|
Err(_) if Instant::now() < deadline => {
|
||||||
sleep(FRAME_INTERVAL).await;
|
sleep(FRAME_INTERVAL).await;
|
||||||
self.link = Link::Connecting { deadline };
|
self.link = Link::Connecting { deadline };
|
||||||
@@ -126,15 +144,26 @@ impl BusFeed {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn receive(&mut self, readiness: AsyncFd<Session>) -> Vec<ScreenInput> {
|
async fn receive(&mut self, mut connection: BusConnection) -> Vec<ScreenInput> {
|
||||||
let Ok(signals) = readiness.get_ref().receive() else {
|
let Ok(signals) = connection.receive_signals(FRAME_INTERVAL).await else {
|
||||||
return self.lose_connection();
|
return self.lose_connection();
|
||||||
};
|
};
|
||||||
let changes = signals
|
let progress = stream::iter(signals)
|
||||||
.into_iter()
|
.fold(
|
||||||
.flat_map(|signal| self.changes_for(readiness.get_ref(), signal))
|
FeedProgress {
|
||||||
.collect();
|
feed: &mut *self,
|
||||||
self.link = Link::Connected(readiness);
|
connection: &mut connection,
|
||||||
|
changes: Vec::new(),
|
||||||
|
},
|
||||||
|
|mut progress, signal| async move {
|
||||||
|
let changes = progress.feed.changes_for(progress.connection, signal).await;
|
||||||
|
progress.changes.extend(changes);
|
||||||
|
progress
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let changes = progress.changes;
|
||||||
|
self.link = Link::Connected(connection);
|
||||||
boot_inputs(changes)
|
boot_inputs(changes)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,30 +185,36 @@ impl BusFeed {
|
|||||||
boot_inputs(vec![BootChange::SwitchRoot { at }])
|
boot_inputs(vec![BootChange::SwitchRoot { at }])
|
||||||
}
|
}
|
||||||
|
|
||||||
fn requested_root(&self, session: &Session, jobs: &[JobListing]) -> Result<String, Error> {
|
async fn requested_root(
|
||||||
|
&self,
|
||||||
|
connection: &mut BusConnection,
|
||||||
|
jobs: &[JobListing],
|
||||||
|
) -> Result<String, Error> {
|
||||||
let RootRequest::Named(target) = &self.target else {
|
let RootRequest::Named(target) = &self.target else {
|
||||||
return if self.phase == Phase::Shutdown {
|
if self.phase != Phase::Shutdown {
|
||||||
Ok(SHUTDOWN_ROOTS
|
return connection.default_target().await;
|
||||||
.into_iter()
|
}
|
||||||
.find(|root| {
|
return Ok(SHUTDOWN_ROOTS
|
||||||
jobs.iter()
|
.into_iter()
|
||||||
.any(|job| job.unit == *root && job.kind == JobKind::BringsUp)
|
.find(|root| {
|
||||||
})
|
jobs.iter()
|
||||||
.unwrap_or(SHUTDOWN_FALLBACK_ROOT)
|
.any(|job| job.unit == *root && job.kind == JobKind::BringsUp)
|
||||||
.to_owned())
|
})
|
||||||
} else {
|
.unwrap_or(SHUTDOWN_FALLBACK_ROOT)
|
||||||
session.default_target()
|
.to_owned());
|
||||||
};
|
|
||||||
};
|
};
|
||||||
Ok(target.clone())
|
Ok(target.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn origin_change(&mut self, session: &Session) -> Result<Option<BootChange>, Error> {
|
async fn origin_change(
|
||||||
|
&mut self,
|
||||||
|
connection: &mut BusConnection,
|
||||||
|
) -> Result<Option<BootChange>, Error> {
|
||||||
if self.gave_origin {
|
if self.gave_origin {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
self.gave_origin = true;
|
self.gave_origin = true;
|
||||||
let origin = if session.boot_in_progress()? {
|
let origin = if connection.boot_in_progress().await? {
|
||||||
Duration::ZERO
|
Duration::ZERO
|
||||||
} else {
|
} else {
|
||||||
monotonic_now()
|
monotonic_now()
|
||||||
@@ -187,48 +222,73 @@ impl BusFeed {
|
|||||||
Ok(Some(BootChange::SetOrigin(origin)))
|
Ok(Some(BootChange::SetOrigin(origin)))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn open_session(&mut self) -> Result<Vec<BootChange>, Error> {
|
async fn track_all(
|
||||||
let session = Session::open(self.scope)?;
|
&mut self,
|
||||||
session.subscribe()?;
|
connection: &mut BusConnection,
|
||||||
|
units: Vec<String>,
|
||||||
|
) -> Vec<BootChange> {
|
||||||
|
stream::iter(units)
|
||||||
|
.fold(
|
||||||
|
FeedProgress {
|
||||||
|
feed: &mut *self,
|
||||||
|
connection: &mut *connection,
|
||||||
|
changes: Vec::new(),
|
||||||
|
},
|
||||||
|
|mut progress, unit| async move {
|
||||||
|
let tracked = progress.feed.track(progress.connection, &unit).await;
|
||||||
|
progress
|
||||||
|
.changes
|
||||||
|
.extend(tracked.and_then(|tracked| tracked.change));
|
||||||
|
progress
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.changes
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn start_watching(
|
||||||
|
&mut self,
|
||||||
|
connection: &mut BusConnection,
|
||||||
|
) -> Result<Vec<BootChange>, Error> {
|
||||||
|
connection.subscribe().await?;
|
||||||
if self.scope == Scope::System {
|
if self.scope == Scope::System {
|
||||||
session.set_show_status(SILENT_STATUS).ok();
|
connection.set_show_status(StatusOutput::Silent).await.ok();
|
||||||
}
|
}
|
||||||
let shutting_down = self.phase == Phase::Shutdown;
|
let shutting_down = self.phase == Phase::Shutdown;
|
||||||
let jobs: Vec<JobListing> = session
|
let jobs: Vec<JobListing> = connection
|
||||||
.list_jobs()?
|
.list_jobs()
|
||||||
|
.await?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|job| shutting_down || job.kind == JobKind::BringsUp)
|
.filter(|job| shutting_down || job.kind == JobKind::BringsUp)
|
||||||
.collect();
|
.collect();
|
||||||
let requested_root = self.requested_root(&session, &jobs)?;
|
let requested_root = self.requested_root(connection, &jobs).await?;
|
||||||
let origin_change = self.origin_change(&session)?;
|
let origin_change = self.origin_change(connection).await?;
|
||||||
let tracked_root = self.track(&session, &requested_root);
|
let tracked_root = self.track(connection, &requested_root).await;
|
||||||
let root = tracked_root
|
let root = tracked_root
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map_or(requested_root, |tracked| tracked.name.clone());
|
.map_or(requested_root, |tracked| tracked.name.clone());
|
||||||
let tracked_handoff = self.track(&session, HANDOFF_UNIT);
|
let tracked_handoff = self.track(connection, HANDOFF_UNIT).await;
|
||||||
let handoff = tracked_handoff
|
let handoff = tracked_handoff
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|tracked| BootChange::SetHandoff(tracked.name.clone()));
|
.map(|tracked| BootChange::SetHandoff(tracked.name.clone()));
|
||||||
let milestones = BootState::new(self.phase).milestone_targets;
|
let watched_units = jobs
|
||||||
let tracked_changes: Vec<BootChange> = jobs
|
|
||||||
.iter()
|
.iter()
|
||||||
.map(|job| job.unit.as_str())
|
.map(|job| job.unit.clone())
|
||||||
.chain(milestones.iter().map(String::as_str))
|
.chain(BootState::new(self.phase).milestone_targets)
|
||||||
.filter_map(|unit| self.track(&session, unit))
|
|
||||||
.filter_map(|tracked| tracked.change)
|
|
||||||
.collect();
|
.collect();
|
||||||
|
let tracked_changes = self.track_all(connection, watched_units).await;
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"bootvine: watching {root} in {} as pid {} over {}",
|
"bootvine: watching {root} in {} as pid {} over {}",
|
||||||
self.phase.label(),
|
self.phase.label(),
|
||||||
process::id(),
|
process::id(),
|
||||||
if session.peer_to_peer {
|
if connection.peer_to_peer() {
|
||||||
"the private socket"
|
"the private socket"
|
||||||
} else {
|
} else {
|
||||||
"the bus"
|
"the bus"
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
let queued_at = monotonic_now();
|
let queued_at = monotonic_now();
|
||||||
let changes = origin_change
|
Ok(origin_change
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.chain(tracked_root.and_then(|tracked| tracked.change))
|
.chain(tracked_root.and_then(|tracked| tracked.change))
|
||||||
.chain(tracked_handoff.and_then(|tracked| tracked.change))
|
.chain(tracked_handoff.and_then(|tracked| tracked.change))
|
||||||
@@ -241,12 +301,10 @@ impl BusFeed {
|
|||||||
kind: job.kind,
|
kind: job.kind,
|
||||||
at: queued_at,
|
at: queued_at,
|
||||||
}))
|
}))
|
||||||
.collect();
|
.collect())
|
||||||
self.link = Link::Connected(readable_source(session)?);
|
|
||||||
Ok(changes)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn track(&mut self, session: &Session, unit: &str) -> Option<TrackedUnit> {
|
async fn track(&mut self, connection: &mut BusConnection, unit: &str) -> Option<TrackedUnit> {
|
||||||
if let Some(known) = self.unit_paths.values().find(|known| *known == unit) {
|
if let Some(known) = self.unit_paths.values().find(|known| *known == unit) {
|
||||||
return Some(TrackedUnit {
|
return Some(TrackedUnit {
|
||||||
name: known.clone(),
|
name: known.clone(),
|
||||||
@@ -257,7 +315,7 @@ impl BusFeed {
|
|||||||
path,
|
path,
|
||||||
facts,
|
facts,
|
||||||
activity,
|
activity,
|
||||||
} = session.fetch_unit(unit).ok()?;
|
} = connection.fetch_unit(unit).await.ok()?;
|
||||||
let name = facts.name.clone();
|
let name = facts.name.clone();
|
||||||
if self.unit_paths.values().any(|known| *known == name) {
|
if self.unit_paths.values().any(|known| *known == name) {
|
||||||
return Some(TrackedUnit { name, change: None });
|
return Some(TrackedUnit { name, change: None });
|
||||||
@@ -269,10 +327,16 @@ impl BusFeed {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn changes_for(&mut self, session: &Session, signal: Signal) -> Vec<BootChange> {
|
async fn changes_for(
|
||||||
|
&mut self,
|
||||||
|
connection: &mut BusConnection,
|
||||||
|
signal: Signal,
|
||||||
|
) -> Vec<BootChange> {
|
||||||
let at = monotonic_now();
|
let at = monotonic_now();
|
||||||
match signal {
|
match signal {
|
||||||
Signal::JobNew { id, job, unit } => self.queue_new_job(session, id, &job, unit, at),
|
Signal::JobNew { id, job, unit } => {
|
||||||
|
self.queue_new_job(connection, id, &job, unit, at).await
|
||||||
|
}
|
||||||
Signal::JobRemoved { id, result } => vec![BootChange::FinishJob { id, result, at }],
|
Signal::JobRemoved { id, result } => vec![BootChange::FinishJob { id, result, at }],
|
||||||
Signal::UnitChanged { path, activity } => self
|
Signal::UnitChanged { path, activity } => self
|
||||||
.unit_paths
|
.unit_paths
|
||||||
@@ -286,19 +350,19 @@ impl BusFeed {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn queue_new_job(
|
async fn queue_new_job(
|
||||||
&mut self,
|
&mut self,
|
||||||
session: &Session,
|
connection: &mut BusConnection,
|
||||||
id: u32,
|
id: u32,
|
||||||
job: &Path<'static>,
|
job: &Path<'static>,
|
||||||
unit: String,
|
unit: String,
|
||||||
at: Duration,
|
at: Duration,
|
||||||
) -> Vec<BootChange> {
|
) -> Vec<BootChange> {
|
||||||
let kind = session.job_kind(job).unwrap_or(JobKind::Unknown);
|
let kind = connection.job_kind(job).await.unwrap_or(JobKind::Unknown);
|
||||||
if kind == JobKind::TakesDown && self.phase != Phase::Shutdown {
|
if kind == JobKind::TakesDown && self.phase != Phase::Shutdown {
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
}
|
}
|
||||||
let tracked = self.track(session, &unit);
|
let tracked = self.track(connection, &unit).await;
|
||||||
let unit = tracked
|
let unit = tracked
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map_or(unit, |tracked| tracked.name.clone());
|
.map_or(unit, |tracked| tracked.name.clone());
|
||||||
@@ -316,16 +380,6 @@ impl BusFeed {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for BusFeed {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
if let Link::Connected(readiness) = &self.link
|
|
||||||
&& self.scope == Scope::System
|
|
||||||
{
|
|
||||||
readiness.get_ref().set_show_status(CONFIGURED_STATUS).ok();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn bus_inputs(
|
pub fn bus_inputs(
|
||||||
phase: Phase,
|
phase: Phase,
|
||||||
scope: Scope,
|
scope: Scope,
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ pub enum Error {
|
|||||||
MalformedCall,
|
MalformedCall,
|
||||||
#[error("the service manager closed the connection")]
|
#[error("the service manager closed the connection")]
|
||||||
Disconnected,
|
Disconnected,
|
||||||
|
#[error("the service manager did not answer in time")]
|
||||||
|
CallTimedOut,
|
||||||
#[error("console: {0}")]
|
#[error("console: {0}")]
|
||||||
Console(#[from] io::Error),
|
Console(#[from] io::Error),
|
||||||
#[error("entering the new root: {0}")]
|
#[error("entering the new root: {0}")]
|
||||||
|
|||||||
+218
-103
@@ -1,5 +1,6 @@
|
|||||||
use std::{
|
use std::{
|
||||||
iter,
|
future::ready,
|
||||||
|
io, iter, mem,
|
||||||
os::fd::{AsRawFd, RawFd},
|
os::fd::{AsRawFd, RawFd},
|
||||||
time::Duration,
|
time::Duration,
|
||||||
};
|
};
|
||||||
@@ -9,9 +10,12 @@ use dbus::{
|
|||||||
arg::{AppendAll, PropMap, RefArg, Variant},
|
arg::{AppendAll, PropMap, RefArg, Variant},
|
||||||
channel::{BusType, Channel},
|
channel::{BusType, Channel},
|
||||||
};
|
};
|
||||||
|
use futures::{StreamExt, stream};
|
||||||
|
use tokio::{io::unix::AsyncFd, time::timeout};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
boot_model::{Activity, JobKind, JobResult, UnitFacts},
|
boot_model::{Activity, JobKind, JobResult, UnitFacts},
|
||||||
|
console_session::stream_sources::{CarriedItem, readable_source, unfold_carrying},
|
||||||
systemd_link::link_error::Error,
|
systemd_link::link_error::Error,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -34,6 +38,21 @@ pub enum Scope {
|
|||||||
User,
|
User,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum StatusOutput {
|
||||||
|
Silent,
|
||||||
|
Configured,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StatusOutput {
|
||||||
|
fn bus_mode(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Silent => "no",
|
||||||
|
Self::Configured => "",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub enum Signal {
|
pub enum Signal {
|
||||||
JobNew {
|
JobNew {
|
||||||
id: u32,
|
id: u32,
|
||||||
@@ -79,6 +98,49 @@ pub struct Session {
|
|||||||
pub peer_to_peer: bool,
|
pub peer_to_peer: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn method_call(
|
||||||
|
destination: &str,
|
||||||
|
path: &str,
|
||||||
|
interface: &str,
|
||||||
|
member: &str,
|
||||||
|
arguments: impl AppendAll,
|
||||||
|
) -> Result<Message, Error> {
|
||||||
|
let Ok(mut call) = Message::new_method_call(destination, path, interface, member) else {
|
||||||
|
return Err(Error::MalformedCall);
|
||||||
|
};
|
||||||
|
call.append_all(arguments);
|
||||||
|
Ok(call)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn manager_call(member: &str, arguments: impl AppendAll) -> Result<Message, Error> {
|
||||||
|
method_call(
|
||||||
|
DESTINATION,
|
||||||
|
MANAGER_PATH,
|
||||||
|
MANAGER_INTERFACE,
|
||||||
|
member,
|
||||||
|
arguments,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn property_call(path: &str, interface: &str, property: &str) -> Result<Message, Error> {
|
||||||
|
method_call(
|
||||||
|
DESTINATION,
|
||||||
|
path,
|
||||||
|
PROPERTIES_INTERFACE,
|
||||||
|
"Get",
|
||||||
|
(interface, property),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn boot_in_progress_call() -> Result<Message, Error> {
|
||||||
|
property_call(MANAGER_PATH, MANAGER_INTERFACE, "FinishTimestampMonotonic")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_boot_in_progress(reply: &Message) -> Result<bool, Error> {
|
||||||
|
let finished: Variant<u64> = reply.read1()?;
|
||||||
|
Ok(finished.0 == 0)
|
||||||
|
}
|
||||||
|
|
||||||
impl Session {
|
impl Session {
|
||||||
pub fn open(scope: Scope) -> Result<Self, Error> {
|
pub fn open(scope: Scope) -> Result<Self, Error> {
|
||||||
if scope == Scope::System
|
if scope == Scope::System
|
||||||
@@ -92,13 +154,13 @@ impl Session {
|
|||||||
Scope::User => BusType::Session,
|
Scope::User => BusType::Session,
|
||||||
};
|
};
|
||||||
let session = Self::watching(Channel::get_private(bus)?, false);
|
let session = Self::watching(Channel::get_private(bus)?, false);
|
||||||
session.call(
|
session.blocking_call(method_call(
|
||||||
BUS_DESTINATION,
|
BUS_DESTINATION,
|
||||||
BUS_PATH,
|
BUS_PATH,
|
||||||
BUS_DESTINATION,
|
BUS_DESTINATION,
|
||||||
"AddMatch",
|
"AddMatch",
|
||||||
(SIGNAL_RULE,),
|
(SIGNAL_RULE,),
|
||||||
)?;
|
)?)?;
|
||||||
Ok(session)
|
Ok(session)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,139 +172,192 @@ impl Session {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(
|
fn blocking_call(&self, call: Message) -> Result<Message, Error> {
|
||||||
&self,
|
|
||||||
destination: &str,
|
|
||||||
path: &str,
|
|
||||||
interface: &str,
|
|
||||||
member: &str,
|
|
||||||
arguments: impl AppendAll,
|
|
||||||
) -> Result<Message, Error> {
|
|
||||||
let Ok(mut call) = Message::new_method_call(destination, path, interface, member) else {
|
|
||||||
return Err(Error::MalformedCall);
|
|
||||||
};
|
|
||||||
call.append_all(arguments);
|
|
||||||
Ok(self.channel.send_with_reply_and_block(call, CALL_TIMEOUT)?)
|
Ok(self.channel.send_with_reply_and_block(call, CALL_TIMEOUT)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn subscribe(&self) -> Result<(), Error> {
|
pub fn set_show_status(&self, output: StatusOutput) -> Result<(), Error> {
|
||||||
self.call(
|
self.blocking_call(manager_call("SetShowStatus", (output.bus_mode(),))?)?;
|
||||||
DESTINATION,
|
|
||||||
MANAGER_PATH,
|
|
||||||
MANAGER_INTERFACE,
|
|
||||||
"Subscribe",
|
|
||||||
(),
|
|
||||||
)?;
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_show_status(&self, mode: &str) -> Result<(), Error> {
|
|
||||||
self.call(
|
|
||||||
DESTINATION,
|
|
||||||
MANAGER_PATH,
|
|
||||||
MANAGER_INTERFACE,
|
|
||||||
"SetShowStatus",
|
|
||||||
(mode,),
|
|
||||||
)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn default_target(&self) -> Result<String, Error> {
|
|
||||||
let reply = self.call(
|
|
||||||
DESTINATION,
|
|
||||||
MANAGER_PATH,
|
|
||||||
MANAGER_INTERFACE,
|
|
||||||
"GetDefaultTarget",
|
|
||||||
(),
|
|
||||||
)?;
|
|
||||||
Ok(reply.read1()?)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn boot_in_progress(&self) -> Result<bool, Error> {
|
pub fn boot_in_progress(&self) -> Result<bool, Error> {
|
||||||
let reply = self.call(
|
read_boot_in_progress(&self.blocking_call(boot_in_progress_call()?)?)
|
||||||
DESTINATION,
|
}
|
||||||
MANAGER_PATH,
|
}
|
||||||
PROPERTIES_INTERFACE,
|
|
||||||
"Get",
|
pub struct BusConnection {
|
||||||
(MANAGER_INTERFACE, "FinishTimestampMonotonic"),
|
readiness: AsyncFd<Session>,
|
||||||
)?;
|
early_signals: Vec<Signal>,
|
||||||
let finished: Variant<u64> = reply.read1()?;
|
}
|
||||||
Ok(finished.0 == 0)
|
|
||||||
|
fn into_results(batch: Result<Vec<Message>, Error>) -> Vec<Result<Message, Error>> {
|
||||||
|
match batch {
|
||||||
|
Ok(messages) => messages.into_iter().map(Ok).collect(),
|
||||||
|
Err(error) => vec![Err(error)],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BusConnection {
|
||||||
|
pub fn register(session: Session) -> io::Result<Self> {
|
||||||
|
Ok(Self {
|
||||||
|
readiness: readable_source(session)?,
|
||||||
|
early_signals: Vec::new(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn list_jobs(&self) -> Result<Vec<JobListing>, Error> {
|
#[must_use]
|
||||||
let reply = self.call(DESTINATION, MANAGER_PATH, MANAGER_INTERFACE, "ListJobs", ())?;
|
pub fn peer_to_peer(&self) -> bool {
|
||||||
|
self.readiness.get_ref().peer_to_peer
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drain_replies(&mut self) -> Result<Vec<Message>, Error> {
|
||||||
|
let channel = &self.readiness.get_mut().channel;
|
||||||
|
if channel.read_write(Some(Duration::ZERO)).is_err() || !channel.is_connected() {
|
||||||
|
return Err(Error::Disconnected);
|
||||||
|
}
|
||||||
|
let (signals, replies): (Vec<Message>, Vec<Message>) =
|
||||||
|
iter::from_fn(|| channel.pop_message())
|
||||||
|
.partition(|message| message.msg_type() == MessageType::Signal);
|
||||||
|
self.early_signals
|
||||||
|
.extend(signals.iter().filter_map(parse_signal));
|
||||||
|
Ok(replies)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn next_replies(&mut self) -> Result<Vec<Message>, Error> {
|
||||||
|
let drained = self.drain_replies()?;
|
||||||
|
if !drained.is_empty() {
|
||||||
|
return Ok(drained);
|
||||||
|
}
|
||||||
|
self.readiness.readable_mut().await?.clear_ready();
|
||||||
|
self.drain_replies()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn reply_to(&mut self, serial: u32) -> Result<Message, Error> {
|
||||||
|
unfold_carrying(self, |connection| async move {
|
||||||
|
let replies = connection.next_replies().await;
|
||||||
|
Some(CarriedItem {
|
||||||
|
item: replies,
|
||||||
|
state: connection,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.flat_map(|replies| stream::iter(into_results(replies)))
|
||||||
|
.filter(|reply| {
|
||||||
|
ready(
|
||||||
|
reply
|
||||||
|
.as_ref()
|
||||||
|
.map_or(true, |message| message.get_reply_serial() == Some(serial)),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.take(1)
|
||||||
|
.fold(Err(Error::Disconnected), |_, reply| ready(reply))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn call(&mut self, call: Message) -> Result<Message, Error> {
|
||||||
|
let channel = &self.readiness.get_ref().channel;
|
||||||
|
let Ok(serial) = channel.send(call) else {
|
||||||
|
return Err(Error::Disconnected);
|
||||||
|
};
|
||||||
|
channel.flush();
|
||||||
|
let Ok(reply) = timeout(CALL_TIMEOUT, self.reply_to(serial)).await else {
|
||||||
|
return Err(Error::CallTimedOut);
|
||||||
|
};
|
||||||
|
let mut reply = reply?;
|
||||||
|
reply.as_result()?;
|
||||||
|
Ok(reply)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn subscribe(&mut self) -> Result<(), Error> {
|
||||||
|
self.call(manager_call("Subscribe", ())?).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn set_show_status(&mut self, output: StatusOutput) -> Result<(), Error> {
|
||||||
|
self.call(manager_call("SetShowStatus", (output.bus_mode(),))?)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn default_target(&mut self) -> Result<String, Error> {
|
||||||
|
let reply = self.call(manager_call("GetDefaultTarget", ())?).await?;
|
||||||
|
Ok(reply.read1()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn boot_in_progress(&mut self) -> Result<bool, Error> {
|
||||||
|
read_boot_in_progress(&self.call(boot_in_progress_call()?).await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list_jobs(&mut self) -> Result<Vec<JobListing>, Error> {
|
||||||
|
let reply = self.call(manager_call("ListJobs", ())?).await?;
|
||||||
let listed: Vec<ListedJob> = reply.read1()?;
|
let listed: Vec<ListedJob> = reply.read1()?;
|
||||||
Ok(listed.into_iter().map(JobListing::from).collect())
|
Ok(listed.into_iter().map(JobListing::from).collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn job_kind(&self, job: &Path) -> Result<JobKind, Error> {
|
pub async fn job_kind(&mut self, job: &Path<'_>) -> Result<JobKind, Error> {
|
||||||
let reply = self.call(
|
let reply = self
|
||||||
DESTINATION,
|
.call(property_call(job, JOB_INTERFACE, "JobType")?)
|
||||||
job,
|
.await?;
|
||||||
PROPERTIES_INTERFACE,
|
|
||||||
"Get",
|
|
||||||
(JOB_INTERFACE, "JobType"),
|
|
||||||
)?;
|
|
||||||
let kind: Variant<String> = reply.read1()?;
|
let kind: Variant<String> = reply.read1()?;
|
||||||
Ok(serde_plain::from_str(&kind.0).unwrap_or(JobKind::Unknown))
|
Ok(serde_plain::from_str(&kind.0).unwrap_or(JobKind::Unknown))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fetch_unit(&self, name: &str) -> Result<FetchedUnit, Error> {
|
pub async fn fetch_unit(&mut self, name: &str) -> Result<FetchedUnit, Error> {
|
||||||
let path: Path<'static> = self
|
let path: Path<'static> = self
|
||||||
.call(
|
.call(manager_call("GetUnit", (name,))?)
|
||||||
DESTINATION,
|
.await?
|
||||||
MANAGER_PATH,
|
|
||||||
MANAGER_INTERFACE,
|
|
||||||
"GetUnit",
|
|
||||||
(name,),
|
|
||||||
)?
|
|
||||||
.read1()?;
|
.read1()?;
|
||||||
let properties: PropMap = self
|
let properties: PropMap = self
|
||||||
.call(
|
.call(method_call(
|
||||||
DESTINATION,
|
DESTINATION,
|
||||||
&path,
|
&path,
|
||||||
PROPERTIES_INTERFACE,
|
PROPERTIES_INTERFACE,
|
||||||
"GetAll",
|
"GetAll",
|
||||||
(UNIT_INTERFACE,),
|
(UNIT_INTERFACE,),
|
||||||
)?
|
)?)
|
||||||
|
.await?
|
||||||
.read1()?;
|
.read1()?;
|
||||||
let text = |property: &str| {
|
|
||||||
properties
|
|
||||||
.get(property)
|
|
||||||
.and_then(|value| value.0.as_str())
|
|
||||||
.map(ToOwned::to_owned)
|
|
||||||
};
|
|
||||||
let names = |property: &str| {
|
|
||||||
properties
|
|
||||||
.get(property)
|
|
||||||
.and_then(|value| value.0.as_iter())
|
|
||||||
.map(|items| {
|
|
||||||
items
|
|
||||||
.filter_map(|item| item.as_str().map(ToOwned::to_owned))
|
|
||||||
.collect()
|
|
||||||
})
|
|
||||||
.unwrap_or_default()
|
|
||||||
};
|
|
||||||
Ok(FetchedUnit {
|
Ok(FetchedUnit {
|
||||||
facts: UnitFacts {
|
facts: unit_facts_from(name, &properties),
|
||||||
name: text("Id").unwrap_or_else(|| name.to_owned()),
|
|
||||||
description: text("Description").unwrap_or_default(),
|
|
||||||
after: names("After"),
|
|
||||||
before: names("Before"),
|
|
||||||
},
|
|
||||||
activity: activity_from(&properties),
|
activity: activity_from(&properties),
|
||||||
path,
|
path,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn receive(&self) -> Result<Vec<Signal>, Error> {
|
pub async fn receive_signals(&mut self, patience: Duration) -> Result<Vec<Signal>, Error> {
|
||||||
if self.channel.read_write(Some(Duration::ZERO)).is_err() || !self.channel.is_connected() {
|
if self.early_signals.is_empty()
|
||||||
return Err(Error::Disconnected);
|
&& let Ok(Ok(mut guard)) = timeout(patience, self.readiness.readable_mut()).await
|
||||||
|
{
|
||||||
|
guard.clear_ready();
|
||||||
}
|
}
|
||||||
Ok(iter::from_fn(|| self.channel.pop_message())
|
self.drain_replies()?;
|
||||||
.filter_map(|message| parse_signal(&message))
|
Ok(mem::take(&mut self.early_signals))
|
||||||
.collect())
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unit_facts_from(name: &str, properties: &PropMap) -> UnitFacts {
|
||||||
|
let text = |property: &str| {
|
||||||
|
properties
|
||||||
|
.get(property)
|
||||||
|
.and_then(|value| value.0.as_str())
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
|
};
|
||||||
|
let names = |property: &str| {
|
||||||
|
properties
|
||||||
|
.get(property)
|
||||||
|
.and_then(|value| value.0.as_iter())
|
||||||
|
.map(|items| {
|
||||||
|
items
|
||||||
|
.filter_map(|item| item.as_str().map(ToOwned::to_owned))
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
};
|
||||||
|
UnitFacts {
|
||||||
|
name: text("Id").unwrap_or_else(|| name.to_owned()),
|
||||||
|
description: text("Description").unwrap_or_default(),
|
||||||
|
after: names("After"),
|
||||||
|
before: names("Before"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user