refactor: build graph first and then render

This commit is contained in:
Willem Vanhulle committed 2026-10-16 11:42:53 +02:00
1 parent 2da498c268
commit 196356ba0b
9 files changed
+401 -361

No files matched your search

+76 -37
View File
@@ -1,5 +1,7 @@
use std::{
collections::HashMap,
mem,
os::fd::{AsFd, BorrowedFd},
path::Path as FilePath,
process,
time::{Duration, Instant},
@@ -30,30 +32,62 @@ const SHUTDOWN_FALLBACK_ROOT: &str = "shutdown.target";
const SILENT_STATUS: &str = "no";
const CONFIGURED_STATUS: &str = "";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RootRequest {
Named(String),
ManagerDefault,
}
enum Link {
Connected(Session),
Connecting { deadline: Instant },
}
impl Link {
fn connecting() -> Self {
Self::Connecting {
deadline: Instant::now() + RECONNECT_PATIENCE,
}
}
}
enum RootFs {
Initrd,
SwitchingTo(Sysroot),
Host,
}
pub struct Feed {
pub connections: u32,
scope: Scope,
target: Option<String>,
pub session: Option<Session>,
target: RootRequest,
link: Link,
unit_paths: HashMap<Path<'static>, String>,
in_initrd: bool,
sysroot: Option<Sysroot>,
root_fs: RootFs,
gave_origin: bool,
reconnect_deadline: Instant,
}
impl Feed {
pub fn new(scope: Scope, target: Option<String>) -> Self {
pub fn new(scope: Scope, target: RootRequest) -> Self {
Self {
connections: 0,
in_initrd: scope == Scope::System && FilePath::new(INITRD_RELEASE).exists(),
root_fs: if scope == Scope::System && FilePath::new(INITRD_RELEASE).exists() {
RootFs::Initrd
} else {
RootFs::Host
},
scope,
target,
session: None,
link: Link::connecting(),
unit_paths: HashMap::new(),
sysroot: None,
gave_origin: false,
reconnect_deadline: Instant::now() + RECONNECT_PATIENCE,
}
}
pub fn session_fd(&self) -> Option<BorrowedFd<'_>> {
match &self.link {
Link::Connected(session) => Some(session.as_fd()),
Link::Connecting { .. } => None,
}
}
@@ -61,47 +95,49 @@ impl Feed {
if state.manager_exited_at.is_some() {
return Ok(());
}
let Some(session) = self.session.take() else {
return self.connect(state);
};
match session.receive() {
Ok(signals) => {
signals
.into_iter()
.for_each(|signal| self.apply(&session, state, signal));
self.session = Some(session);
}
Err(_) => self.lose_connection(state)?,
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),
},
}
Ok(())
}
fn connect(&mut self, state: &mut BootState) -> Result<(), Error> {
fn connect(&mut self, state: &mut BootState, deadline: Instant) -> Result<(), Error> {
match self.open_session(state) {
Ok(session) => {
self.session = Some(session);
self.link = Link::Connected(session);
self.connections += 1;
Ok(())
}
Err(_) if Instant::now() < self.reconnect_deadline => Ok(()),
Err(_) if Instant::now() < deadline => {
self.link = Link::Connecting { deadline };
Ok(())
}
Err(_) => Err(Error::ManagerUnreachable),
}
}
fn lose_connection(&mut self, state: &mut BootState) -> Result<(), Error> {
match self.sysroot.take() {
Some(sysroot) => {
match &self.root_fs {
RootFs::SwitchingTo(sysroot) => {
sysroot.enter()?;
self.in_initrd = false;
self.root_fs = RootFs::Host;
self.unit_paths.clear();
state.switch_root(monotonic_now());
}
None if state.phase == Phase::Shutdown => {
RootFs::Initrd | RootFs::Host if state.phase == Phase::Shutdown => {
state.manager_exited_at = Some(monotonic_now());
}
None => state.forget_jobs(),
RootFs::Initrd | RootFs::Host => state.forget_jobs(),
}
self.reconnect_deadline = Instant::now() + RECONNECT_PATIENCE;
Ok(())
}
@@ -118,8 +154,8 @@ impl Feed {
.filter(|job| shutting_down || job.kind == JobKind::BringsUp)
.collect();
let requested_root = match &self.target {
Some(target) => target.clone(),
None if shutting_down => SHUTDOWN_ROOTS
RootRequest::Named(target) => target.clone(),
RootRequest::ManagerDefault if shutting_down => SHUTDOWN_ROOTS
.into_iter()
.find(|root| {
jobs.iter()
@@ -127,7 +163,7 @@ impl Feed {
})
.unwrap_or(SHUTDOWN_FALLBACK_ROOT)
.to_owned(),
None => session.default_target()?,
RootRequest::ManagerDefault => session.default_target()?,
};
let milestones: &[&str] = if shutting_down {
&SHUTDOWN_MILESTONES
@@ -193,8 +229,11 @@ impl Feed {
return;
}
let unit = self.track(session, state, &unit).unwrap_or(unit);
if self.in_initrd && unit == SWITCH_ROOT_UNIT {
self.sysroot = Sysroot::hold().ok();
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());
}
@@ -210,7 +249,7 @@ impl Feed {
impl Drop for Feed {
fn drop(&mut self) {
if let Some(session) = &self.session
if let Link::Connected(session) = &self.link
&& self.scope == Scope::System
{
session.set_show_status(CONFIGURED_STATUS).ok();
+7 -4
View File
@@ -14,7 +14,8 @@ use clap::Parser;
use jiff::fmt::friendly::SpanParser;
use crate::{
run::{Options, run},
feed::RootRequest,
run::{Settings, run},
systemd::Scope,
};
@@ -61,17 +62,19 @@ fn main() -> ExitCode {
Config::default()
}
};
let options = Options {
let settings = Settings {
scope: if cli.user { Scope::User } else { Scope::System },
shutdown: cli.shutdown,
target: cli.target,
target: cli
.target
.map_or(RootRequest::ManagerDefault, RootRequest::Named),
timing: Timing {
keep_final_frame_for: cli.hold.unwrap_or(config.timing.keep_final_frame_for),
..config.timing
},
palette: config.palette,
};
match run(&options) {
match run(&settings) {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("bootvine: {error}");
+171 -198
View File
@@ -110,6 +110,13 @@ enum Outcome {
Abandoned,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Progress {
Untouched,
Pending(PendingJob),
Finished(Outcome),
}
#[derive(Clone, Debug)]
struct UnitRecord {
facts: UnitFacts,
@@ -117,8 +124,7 @@ struct UnitRecord {
inactive_exit: Option<Duration>,
active_enter: Option<Duration>,
active_exit: Option<Duration>,
job: Option<PendingJob>,
outcome: Option<Outcome>,
progress: Progress,
}
impl UnitRecord {
@@ -145,7 +151,9 @@ impl UnitRecord {
}
fn running_since(&self) -> Option<Duration> {
let job = self.job?;
let Progress::Pending(job) = self.progress else {
return None;
};
let transitioning = matches!(
self.state,
ActiveState::Activating | ActiveState::Deactivating | ActiveState::Reloading
@@ -153,8 +161,36 @@ impl UnitRecord {
transitioning.then(|| self.transition_started(job.kind).unwrap_or(job.queued_at))
}
fn row_status(&self) -> RowStatus {
match self.progress {
Progress::Pending(job) => {
self.running_since()
.map_or(RowStatus::Waiting, |since| RowStatus::Running {
queued_at: job.queued_at,
since,
})
}
Progress::Finished(Outcome::Failed) => RowStatus::Failed,
Progress::Finished(_) | Progress::Untouched => RowStatus::Done,
}
}
fn is_pending(&self) -> bool {
matches!(self.progress, Progress::Pending(_))
}
fn is_finished(&self) -> bool {
matches!(self.progress, Progress::Finished(_))
}
fn takes_down(&self) -> bool {
self.job.is_some_and(|job| job.kind == JobKind::TakesDown)
matches!(
self.progress,
Progress::Pending(PendingJob {
kind: JobKind::TakesDown,
..
})
)
}
}
@@ -220,7 +256,10 @@ impl UnitKind {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RowStatus {
Waiting,
Running,
Running {
queued_at: Duration,
since: Duration,
},
Failed,
Done,
}
@@ -228,13 +267,10 @@ pub enum RowStatus {
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TreeRow {
pub depth: usize,
pub is_last_sibling: Vec<bool>,
pub label: String,
pub description: String,
pub kind: UnitKind,
pub status: RowStatus,
pub queued_at: Duration,
pub running_since: Option<Duration>,
pub chain: Vec<String>,
}
@@ -243,7 +279,7 @@ pub struct MilestoneRow {
pub label: String,
pub finished_units: usize,
pub started_at: Duration,
pub reached_at: Option<Duration>,
pub reached_at: Duration,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -271,17 +307,33 @@ pub struct FinishedStage {
pub reached_at: Duration,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Root {
Unresolved,
Awaiting(String),
Queued(String),
}
impl Root {
#[must_use]
pub fn unit(&self) -> Option<&str> {
match self {
Self::Unresolved => None,
Self::Awaiting(unit) | Self::Queued(unit) => Some(unit),
}
}
}
#[derive(Clone, Debug)]
pub struct BootState {
pub phase: Phase,
pub origin: Duration,
pub root: Option<String>,
pub root: Root,
pub failed: Vec<String>,
pub finished_stages: Vec<FinishedStage>,
pub finished_runs: Vec<FinishedRun>,
pub handoff_unit: Option<String>,
pub manager_exited_at: Option<Duration>,
root_job_seen: bool,
milestone_targets: Vec<String>,
finished_before_reconnect: usize,
units: HashMap<String, UnitRecord>,
@@ -319,11 +371,10 @@ impl BootState {
Self {
phase,
origin: Duration::ZERO,
root: None,
root: Root::Unresolved,
failed: Vec::new(),
finished_stages: Vec::new(),
finished_runs: Vec::new(),
root_job_seen: false,
handoff_unit,
manager_exited_at: None,
milestone_targets,
@@ -334,13 +385,12 @@ impl BootState {
}
pub fn set_root(&mut self, root: String) {
if self.root.as_ref() != Some(&root) {
self.root_job_seen = false;
}
if self.phase == Phase::User && !self.milestone_targets.contains(&root) {
self.milestone_targets.push(root.clone());
}
self.root = Some(root);
if self.root.unit() != Some(&root) {
self.root = Root::Awaiting(root);
}
}
pub fn set_handoff(&mut self, unit: String) {
@@ -359,8 +409,7 @@ impl BootState {
inactive_exit: None,
active_enter: None,
active_exit: None,
job: None,
outcome: None,
progress: Progress::Untouched,
});
record.facts = facts;
record.apply(activity);
@@ -376,9 +425,9 @@ impl BootState {
self.enqueue(id, unit, kind, at);
if kind == JobKind::BringsUp
&& self.jobs.get(&id).is_some_and(|tracked| tracked == unit)
&& self.root.as_deref() == Some(unit)
&& self.root == Root::Awaiting(unit.to_owned())
{
self.root_job_seen = true;
self.root = Root::Queued(unit.to_owned());
}
}
@@ -389,12 +438,11 @@ impl BootState {
let Some(record) = self.units.get_mut(unit) else {
return;
};
record.job = Some(PendingJob {
record.progress = Progress::Pending(PendingJob {
id,
queued_at: at,
kind,
});
record.outcome = None;
self.jobs.insert(id, unit.to_owned());
}
@@ -405,36 +453,31 @@ impl BootState {
let Some(record) = self.units.get_mut(&unit) else {
return;
};
let started_at = record
.job
.filter(|job| job.id == id && job.kind != JobKind::Unknown)
.and_then(|job| record.transition_started(job.kind))
.filter(|started| *started >= self.origin && *started <= at);
if record.job.is_some_and(|job| job.id == id) {
record.job = None;
}
if let Some(started_at) = started_at
&& UnitKind::of(&record.facts.name) != UnitKind::Target
{
self.finished_runs.push(FinishedRun {
label: display_label(&record.facts),
started_at,
finished_at: at,
failed: matches!(
result,
JobResult::Failed | JobResult::Timeout | JobResult::Dependency
),
});
}
let outcome = match result {
JobResult::Done => Outcome::Succeeded { at },
JobResult::Skipped | JobResult::Canceled => Outcome::Abandoned,
JobResult::Failed | JobResult::Timeout | JobResult::Dependency => Outcome::Failed,
};
record.outcome = Some(outcome);
let label = display_label(&record.facts);
if outcome == Outcome::Failed && !self.failed.contains(&label) {
self.failed.push(label);
self.failed.push(label.clone());
}
let job = match record.progress {
Progress::Pending(job) if job.id == id => job,
_ => return,
};
record.progress = Progress::Finished(outcome);
if let Some(started_at) = record
.transition_started(job.kind)
.filter(|started| job.kind != JobKind::Unknown && (self.origin..=at).contains(started))
&& UnitKind::of(&record.facts.name) != UnitKind::Target
{
self.finished_runs.push(FinishedRun {
label,
started_at,
finished_at: at,
failed: outcome == Outcome::Failed,
});
}
}
@@ -442,7 +485,7 @@ impl BootState {
let finished_here = self
.units
.values()
.filter(|record| record.outcome.is_some())
.filter(|record| record.is_finished())
.count();
self.finished_stages.push(FinishedStage {
label: Phase::Initrd.label(),
@@ -450,14 +493,13 @@ impl BootState {
failed_units: self
.units
.values()
.filter(|record| record.outcome == Some(Outcome::Failed))
.filter(|record| record.progress == Progress::Finished(Outcome::Failed))
.count(),
started_at: self.origin,
reached_at: at,
});
self.phase = Phase::Host;
self.root = None;
self.root_job_seen = false;
self.root = Root::Unresolved;
self.finished_before_reconnect = 0;
self.units.clear();
self.jobs.clear();
@@ -467,13 +509,12 @@ impl BootState {
self.finished_before_reconnect += self
.units
.values()
.filter(|record| record.outcome.is_some())
.filter(|record| record.is_finished())
.count();
self.jobs.clear();
self.units.values_mut().for_each(|record| {
record.job = None;
record.outcome = None;
});
self.units
.values_mut()
.for_each(|record| record.progress = Progress::Untouched);
}
#[must_use]
@@ -489,10 +530,10 @@ impl BootState {
{
return true;
}
let Some(root) = self.root.as_deref().and_then(|root| self.units.get(root)) else {
let Root::Queued(root) = &self.root else {
return false;
};
self.root_job_seen && root.job.is_none()
self.units.get(root).is_some_and(|root| !root.is_pending())
}
#[must_use]
@@ -508,17 +549,13 @@ impl BootState {
..Tally::default()
};
self.units.values().fold(carried, |mut tally, record| {
if record.job.is_some() {
if record.running_since().is_some() {
tally.running += 1;
} else {
tally.waiting += 1;
match record.progress {
Progress::Pending(_) if record.running_since().is_some() => tally.running += 1,
Progress::Pending(_) => tally.waiting += 1,
Progress::Finished(Outcome::Succeeded { .. } | Outcome::Abandoned) => {
tally.done += 1;
}
} else if matches!(
record.outcome,
Some(Outcome::Succeeded { .. } | Outcome::Abandoned)
) {
tally.done += 1;
Progress::Finished(Outcome::Failed) | Progress::Untouched => {}
}
tally
})
@@ -526,15 +563,12 @@ impl BootState {
fn milestone_reached_at(&self, target: &str) -> Option<Duration> {
let record = self.units.get(target)?;
if record.job.is_some() {
return None;
}
match record.outcome {
Some(Outcome::Succeeded { at }) => Some(at),
Some(_) => None,
None => record
match record.progress {
Progress::Finished(Outcome::Succeeded { at }) => Some(at),
Progress::Untouched => record
.active_enter
.filter(|entered| record.state == ActiveState::Active && *entered >= self.origin),
Progress::Pending(_) | Progress::Finished(Outcome::Failed | Outcome::Abandoned) => None,
}
}
@@ -543,8 +577,8 @@ impl BootState {
let mut succeeded: Vec<Duration> = self
.units
.values()
.filter_map(|record| match record.outcome {
Some(Outcome::Succeeded { at }) => Some(at),
.filter_map(|record| match record.progress {
Progress::Finished(Outcome::Succeeded { at }) => Some(at),
_ => None,
})
.collect();
@@ -557,7 +591,7 @@ impl BootState {
label: stage.label.to_owned(),
finished_units: stage.finished_units,
started_at: stage.started_at,
reached_at: Some(stage.reached_at),
reached_at: stage.reached_at,
})
.collect(),
previous: self
@@ -566,24 +600,14 @@ impl BootState {
.map_or(self.origin, |stage| stage.reached_at),
consumed: 0,
};
let mut walk = self
.milestone_targets
self.milestone_targets
.iter()
.filter_map(|target| {
self.milestone_reached_at(target)
.map(|reached_at| ReachedMilestone { target, reached_at })
})
.fold(start, |walk, reached| walk.advance(&reached, &succeeded));
let remaining = succeeded.len() - walk.consumed + self.finished_before_reconnect;
if remaining > 0 {
walk.rows.push(MilestoneRow {
label: "Finished".to_owned(),
finished_units: remaining,
started_at: walk.previous,
reached_at: None,
});
}
walk.rows
.fold(start, |walk, reached| walk.advance(&reached, &succeeded))
.rows
}
#[must_use]
@@ -591,19 +615,17 @@ impl BootState {
let pending: HashSet<&str> = self
.units
.iter()
.filter(|(name, record)| {
let finished_recently = matches!(
record.outcome,
Some(Outcome::Succeeded { at }) if at >= finished_since
);
record.job.is_some()
|| finished_recently
|| record.outcome == Some(Outcome::Failed)
|| (self.is_milestone(name) && record.outcome.is_some())
.filter(|(name, record)| match record.progress {
Progress::Pending(_) | Progress::Finished(Outcome::Failed) => true,
Progress::Finished(Outcome::Succeeded { at }) => {
at >= finished_since || self.is_milestone(name)
}
Progress::Finished(Outcome::Abandoned) => self.is_milestone(name),
Progress::Untouched => false,
})
.map(|(name, _)| name.as_str())
.collect();
let root = self.root.as_deref().filter(|root| pending.contains(root));
let root = self.root.unit().filter(|root| pending.contains(root));
let stages: Vec<&str> = self
.milestone_targets
.iter()
@@ -627,64 +649,41 @@ impl BootState {
unblocked.clear();
leftovers.clear();
}
let mut rows = Vec::new();
let mut visited = HashSet::new();
let mut rows = Vec::new();
stages
.iter()
.copied()
.chain(unblocked)
.chain(leftovers)
.for_each(|top| {
if !visited.contains(top) {
self.emit(
top,
&pending,
&mut visited,
&mut Vec::new(),
true,
&mut rows,
);
if visited.contains(top) {
return;
}
let stage = self.grow(top, &pending, &mut visited);
if stage.row.status != RowStatus::Done || !stage.children.is_empty() {
stage.flatten_into(0, &mut rows);
}
});
let mut kept = Vec::new();
grow_forest(&mut rows.into_iter().peekable(), 0)
.into_iter()
.filter(|stage| stage.row.status != RowStatus::Done || !stage.children.is_empty())
.for_each(|stage| stage.flatten_into(0, &mut kept));
relink_siblings(kept)
rows
}
fn emit<'a>(
fn grow<'a>(
&'a self,
unit: &'a str,
pending: &HashSet<&'a str>,
visited: &mut HashSet<&'a str>,
ancestry: &mut Vec<bool>,
is_last: bool,
rows: &mut Vec<TreeRow>,
) {
) -> TreeNode {
visited.insert(unit);
let record = &self.units[unit];
let running_since = record.running_since();
let status = match (record.job, running_since, record.outcome) {
(Some(_), Some(_), _) => RowStatus::Running,
(Some(_), None, _) => RowStatus::Waiting,
(None, _, Some(Outcome::Failed)) => RowStatus::Failed,
(None, ..) => RowStatus::Done,
};
let mut is_last_sibling = ancestry.clone();
is_last_sibling.push(is_last);
rows.push(TreeRow {
depth: ancestry.len(),
is_last_sibling,
let row = TreeRow {
depth: 0,
label: display_label(&record.facts),
description: summary(&record.facts),
kind: UnitKind::of(&record.facts.name),
status,
queued_at: record.job.map(|job| job.queued_at).unwrap_or_default(),
running_since,
status: record.row_status(),
chain: Vec::new(),
});
};
let candidates: Vec<&str> = self
.waits_for(unit, pending)
.into_iter()
@@ -704,13 +703,16 @@ impl BootState {
self.sort_siblings(&mut children);
children.dedup();
visited.extend(children.iter().copied());
ancestry.push(is_last);
let count = children.len();
children.into_iter().enumerate().for_each(|(index, child)| {
visited.remove(child);
self.emit(child, pending, visited, ancestry, index + 1 == count, rows);
});
ancestry.pop();
TreeNode {
row,
children: children
.into_iter()
.map(|child| {
visited.remove(child);
self.grow(child, pending, visited)
})
.collect(),
}
}
fn is_milestone(&self, unit: &str) -> bool {
@@ -754,13 +756,17 @@ impl BootState {
fn sort_siblings(&self, names: &mut [&str]) {
let rank = |name: &str| {
let record = &self.units[name];
match (record.running_since(), record.outcome) {
(Some(since), _) => SiblingRank::RunningSince(since),
(None, Some(Outcome::Succeeded { at })) => {
match record.progress {
Progress::Pending(_) => record
.running_since()
.map_or(SiblingRank::Waiting, SiblingRank::RunningSince),
Progress::Finished(Outcome::Succeeded { at }) => {
SiblingRank::RunningSince(record.inactive_exit.unwrap_or(at))
}
(None, Some(Outcome::Failed)) => SiblingRank::Failed,
(None, _) => SiblingRank::Waiting,
Progress::Finished(Outcome::Failed) => SiblingRank::Failed,
Progress::Finished(Outcome::Abandoned) | Progress::Untouched => {
SiblingRank::Waiting
}
}
};
names.sort_by(|left, right| rank(left).cmp(&rank(right)).then_with(|| left.cmp(right)));
@@ -792,7 +798,7 @@ impl MilestoneWalk {
label: reached.target.to_owned(),
finished_units: upto.saturating_sub(self.consumed),
started_at: self.previous.min(reached.reached_at),
reached_at: Some(reached.reached_at),
reached_at: reached.reached_at,
});
self.consumed = self.consumed.max(upto);
self.previous = reached.reached_at;
@@ -809,7 +815,7 @@ fn on_paths_to_running(rows: &[TreeRow]) -> Vec<bool> {
let descendant_kept = kept_below.iter().skip(row.depth + 1).any(|kept| *kept);
kept_below.resize(row.depth + 1, false);
let anchors_the_tree = row.depth == 0 && row.kind == UnitKind::Target;
let keep = matches!(row.status, RowStatus::Running | RowStatus::Failed)
let keep = matches!(row.status, RowStatus::Running { .. } | RowStatus::Failed)
|| descendant_kept
|| anchors_the_tree;
kept_below[row.depth] |= keep;
@@ -838,15 +844,13 @@ fn with_spare_rows(essential: &[bool], budget: usize) -> Vec<bool> {
#[must_use]
pub fn fit_to_height(rows: Vec<TreeRow>, budget: usize) -> Vec<TreeRow> {
if rows.len() <= budget {
return relink_siblings(rows);
return rows;
}
let kept = with_spare_rows(&on_paths_to_running(&rows), budget);
let survivors: Vec<TreeRow> = rows
.into_iter()
rows.into_iter()
.zip(kept)
.filter_map(|(row, keep)| keep.then_some(row))
.collect();
relink_siblings(survivors)
.collect()
}
const MIN_FOLDED_LINKS: usize = 2;
@@ -918,34 +922,7 @@ pub fn fold_chains(rows: Vec<TreeRow>) -> Vec<TreeRow> {
grow_forest(&mut rows.into_iter().peekable(), 0)
.into_iter()
.for_each(|root| root.fold(false).flatten_into(0, &mut flattened));
relink_siblings(flattened)
}
fn relink_siblings(rows: Vec<TreeRow>) -> Vec<TreeRow> {
let mut later_sibling: Vec<bool> = Vec::new();
let mut is_last: Vec<bool> = rows
.iter()
.rev()
.map(|row| {
let last = !later_sibling.get(row.depth).copied().unwrap_or(false);
later_sibling.resize(row.depth + 1, false);
later_sibling[row.depth] = true;
last
})
.collect();
is_last.reverse();
let mut ancestry: Vec<bool> = Vec::new();
rows.into_iter()
.zip(is_last)
.map(|(row, last)| {
ancestry.truncate(row.depth);
ancestry.push(last);
TreeRow {
is_last_sibling: ancestry.clone(),
..row
}
})
.collect()
flattened
}
fn labelled_by_description(facts: &UnitFacts) -> bool {
@@ -1078,11 +1055,6 @@ mod tests {
"graphical.target",
]
);
let lasts: Vec<bool> = rows
.iter()
.map(|row| *row.is_last_sibling.last().unwrap())
.collect();
assert_eq!(lasts, [false, false, false, true, true, true]);
}
#[test]
@@ -1244,12 +1216,10 @@ mod tests {
folded_outline(&state),
["root.target", " a", " b", " d"]
);
let rows = fold_chains(fit_to_height(both.tree_rows(Duration::MAX), 0));
let lasts: Vec<bool> = rows
.iter()
.map(|row| *row.is_last_sibling.last().unwrap())
.collect();
assert_eq!(lasts, [true, true, false, true]);
assert_eq!(
folded_outline(&both),
["root.target", " a", " b", " c"]
);
}
#[test]
@@ -1362,7 +1332,7 @@ mod tests {
reached_at: 2000 * MS,
}]
);
assert_eq!(state.milestones()[0].reached_at, Some(2000 * MS));
assert_eq!(state.milestones()[0].reached_at, 2000 * MS);
assert_eq!(state.tally().done, 2);
assert!(state.tree_rows(Duration::MAX).is_empty());
}
@@ -1508,8 +1478,11 @@ mod tests {
},
);
assert_eq!(
state.tree_rows(Duration::MAX)[0].running_since,
Some(1200 * MS)
state.tree_rows(Duration::MAX)[0].status,
RowStatus::Running {
queued_at: 1000 * MS,
since: 1200 * MS
}
);
state.finish_job(1, JobResult::Done, 1700 * MS);
assert_eq!(
+17 -19
View File
@@ -36,7 +36,7 @@ use crate::{
clock::monotonic_now,
console::Console,
error::Error,
feed::Feed,
feed::{Feed, RootRequest},
password::{PasswordEntry, RequestWatch},
sysroot::INITRD_RELEASE,
systemd::{Scope, Session},
@@ -45,19 +45,19 @@ use crate::{
const FRAME_INTERVAL: Duration = Duration::from_millis(100);
const FULL_REPAINT_INTERVAL: Duration = Duration::from_secs(1);
pub struct Options {
pub struct Settings {
pub scope: Scope,
pub shutdown: bool,
pub target: Option<String>,
pub target: RootRequest,
pub timing: Timing,
pub palette: Palette,
}
pub fn run(options: &Options) -> Result<(), Error> {
pub fn run(settings: &Settings) -> Result<(), Error> {
let terminate = Arc::new(AtomicBool::new(false));
flag::register(SIGTERM, Arc::clone(&terminate))?;
if options.scope == Scope::System
&& !options.shutdown
if settings.scope == Scope::System
&& !settings.shutdown
&& Session::open(Scope::System)
.and_then(|session| session.boot_in_progress())
.is_ok_and(|booting| !booting)
@@ -65,24 +65,23 @@ pub fn run(options: &Options) -> Result<(), Error> {
eprintln!("bootvine: boot already finished, leaving the console alone");
return Ok(());
}
let phase = match options.scope {
_ if options.shutdown => Phase::Shutdown,
let 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(options.scope, options.target.clone());
let mut console = Console::take(options.scope == Scope::System);
let mut feed = Feed::new(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,
&options.palette,
settings,
&mut console,
&options.timing,
);
ratatui::restore();
watched
@@ -143,9 +142,8 @@ fn watch(
feed: &mut Feed,
terminal: &mut DefaultTerminal,
terminate: &AtomicBool,
palette: &Palette,
settings: &Settings,
console: &mut Console,
timing: &Timing,
) -> Result<(), Error> {
let mut origin = BootOrigin::read();
let mut origin_phase = state.phase;
@@ -178,8 +176,8 @@ fn watch(
canvas.render_widget(
BootView {
state,
palette,
timing,
palette: &settings.palette,
timing: &settings.timing,
glyphs: &console.glyphs,
now: monotonic_now(),
origin: &origin,
@@ -201,9 +199,9 @@ fn watch(
if state.is_complete() {
eprintln!(
"bootvine: {} reached, handing the console over",
state.root.as_deref().unwrap_or("boot")
state.root.unit().unwrap_or("boot")
);
sleep(timing.keep_final_frame_for);
sleep(settings.timing.keep_final_frame_for);
return Ok(());
}
if terminate.load(Ordering::Relaxed) {
@@ -212,7 +210,7 @@ fn watch(
sleep_until_readable(
[
Some(stdin()),
feed.session.as_ref().map(AsFd::as_fd),
feed.session_fd(),
requests.as_ref().map(AsFd::as_fd),
]
.into_iter()
+1 -1
View File
@@ -23,7 +23,7 @@ impl Sysroot {
Ok(Self { directory })
}
pub fn enter(self) -> Result<(), Errno> {
pub fn enter(&self) -> Result<(), Errno> {
fchdir(&self.directory)?;
chroot(".")?;
chdir("/")
+23 -34
View File
@@ -19,7 +19,7 @@ pub use self::chrome::PasswordPrompt;
use self::{
chrome::{FOOTER_HEIGHT, Footer, Header, PasswordPopup},
stages::Stages,
timeline::Timeline,
timeline::{RunningRun, Timeline},
tree::UnitTree,
};
use crate::{
@@ -59,11 +59,19 @@ pub struct BootView<'a> {
impl BootView<'_> {
fn timeline<'a>(&'a self, rows: &'a [TreeRow]) -> Timeline<'a> {
let mut running: Vec<&TreeRow> = rows
let mut running: Vec<RunningRun> = rows
.iter()
.filter(|row| row.kind != UnitKind::Target && row.status == RowStatus::Running)
.filter(|row| row.kind != UnitKind::Target)
.filter_map(|row| match row.status {
RowStatus::Running { queued_at, since } => Some(RunningRun {
label: &row.label,
queued_at,
since,
}),
_ => None,
})
.collect();
running.sort_by_key(|row| row.running_since);
running.sort_by_key(|run| run.since);
Timeline {
origin: self.state.origin,
now: self.now,
@@ -73,12 +81,7 @@ impl BootView<'_> {
.iter()
.map(|stage| stage.reached_at)
.collect(),
milestones: self
.state
.milestones()
.into_iter()
.filter(|row| row.reached_at.is_some())
.collect(),
milestones: self.state.milestones(),
finished: self
.state
.finished_runs
@@ -101,7 +104,6 @@ impl Widget for BootView<'_> {
.state
.tree_rows(self.now.saturating_sub(self.timing.keep_finished_units_for));
let pending_count = all_rows.len();
let pruned_rows = fold_chains(fit_to_height(all_rows.clone(), 0));
let header = Header {
origin: self.origin,
total: (!self.state.finished_stages.is_empty())
@@ -114,17 +116,7 @@ impl Widget for BootView<'_> {
palette: self.palette,
glyphs: self.glyphs,
};
let pruned = UnitTree {
phase: stages.current_phase(),
rows: &pruned_rows,
hidden: pending_count - shown_units(&pruned_rows),
now: self.now,
hide_runs_shorter_than: self.timing.hide_runs_shorter_than,
frame: self.frame,
palette: self.palette,
glyphs: self.glyphs,
};
let timeline = self.timeline(&pruned_rows);
let timeline = self.timeline(&all_rows);
let footer = Footer {
tally: self.state.tally(),
palette: self.palette,
@@ -135,28 +127,25 @@ impl Widget for BootView<'_> {
let free = area
.height
.saturating_sub(HEADER_HEIGHT + stages.height() + FOOTER_HEIGHT);
let whole_tree = fit_to_height(all_rows.clone(), usize::MAX);
let whole_tree_height = UnitTree {
phase: pruned.phase.clone(),
rows: &whole_tree,
hidden: 0,
..pruned
}
.height();
let heights = Heights::share(
free,
whole_tree_height,
UnitTree::height_of(pending_count, 0),
if fits_timeline { timeline.height() } else { 0 },
);
let budget = usize::from(heights.tree.saturating_sub(1));
let rows = [whole_tree.clone(), fold_chains(whole_tree)]
let rows = [all_rows.clone(), fold_chains(all_rows.clone())]
.into_iter()
.find(|rows| rows.len() <= budget)
.unwrap_or_else(|| fold_chains(fit_to_height(all_rows, budget)));
.unwrap_or_else(|| fold_chains(fit_to_height(all_rows.clone(), budget)));
let tree = UnitTree {
phase: stages.current_phase(),
rows: &rows,
hidden: pending_count - shown_units(&rows),
..pruned
now: self.now,
hide_runs_shorter_than: self.timing.hide_runs_shorter_than,
frame: self.frame,
palette: self.palette,
glyphs: self.glyphs,
};
let tree_height = tree.height().min(heights.tree);
+3 -7
View File
@@ -29,7 +29,7 @@ struct Conclusion<'a> {
impl Stages<'_> {
pub fn height(&self) -> u16 {
u16::try_from(self.lines().len()).unwrap_or(u16::MAX)
u16::try_from(self.state.finished_stages.len()).unwrap_or(u16::MAX)
}
fn conclusion(&self) -> Option<Conclusion<'_>> {
@@ -47,7 +47,7 @@ impl Stages<'_> {
.state
.handoff_unit
.as_deref()
.or(self.state.root.as_deref())
.or(self.state.root.unit())
.unwrap_or("the console"),
})
}
@@ -110,14 +110,10 @@ impl Stages<'_> {
elapsed.fg(self.palette.text),
])
}
fn lines(&self) -> Vec<Line<'static>> {
self.finished_phases().collect()
}
}
impl Widget for Stages<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
Paragraph::new(self.lines()).render(area, buf);
Paragraph::new(self.finished_phases().collect::<Vec<_>>()).render(area, buf);
}
}
+26 -25
View File
@@ -16,7 +16,7 @@ use ratatui::{
use super::{fit_width, rule, unit_count};
use crate::{
glyphs::Glyphs,
model::{FinishedRun, MilestoneRow, TreeRow},
model::{FinishedRun, MilestoneRow},
palette::Palette,
};
@@ -50,11 +50,17 @@ pub struct Timeline<'a> {
pub root_switches: Vec<Duration>,
pub milestones: Vec<MilestoneRow>,
pub finished: Vec<&'a FinishedRun>,
pub running: Vec<&'a TreeRow>,
pub running: Vec<RunningRun<'a>>,
pub palette: &'a Palette,
pub glyphs: &'a Glyphs,
}
pub struct RunningRun<'a> {
pub label: &'a str,
pub queued_at: Duration,
pub since: Duration,
}
impl Timeline<'_> {
pub fn height(&self) -> u16 {
let entries = self.milestones.len()
@@ -87,17 +93,13 @@ impl Timeline<'_> {
),
self.palette.done,
),
segments: row
.reached_at
.map(|reached_at| Segment {
from: row.started_at,
to: reached_at,
symbol: self.glyphs.bead,
color: self.palette.done,
})
.into_iter()
.collect(),
still_going_at: None,
segments: vec![Segment {
from: row.started_at,
to: row.reached_at,
symbol: self.glyphs.bead,
color: self.palette.done,
}],
still_going: false,
}
}
@@ -123,7 +125,7 @@ impl Timeline<'_> {
symbol: self.glyphs.bead,
color: outcome,
}],
still_going_at: None,
still_going: false,
}
}
@@ -135,16 +137,15 @@ impl Timeline<'_> {
)
}
fn running_entry<'a>(&self, row: &'a TreeRow) -> TimelineEntry<'a> {
let since = row.running_since.unwrap_or(row.queued_at);
let waited = (since > row.queued_at).then_some(Segment {
from: row.queued_at,
to: since,
fn running_entry(&self, run: &RunningRun) -> TimelineEntry<'static> {
let waited = (run.since > run.queued_at).then_some(Segment {
from: run.queued_at,
to: run.since,
symbol: self.glyphs.waiting_bead,
color: self.palette.waiting,
});
let ran = Segment {
from: since,
from: run.since,
to: self.now,
symbol: self.glyphs.bead,
color: self.palette.running,
@@ -152,10 +153,10 @@ impl Timeline<'_> {
TimelineEntry {
label: Line::from(vec![
format!("{} ", self.glyphs.running_mark).fg(self.palette.running),
self.fitted(&row.label).fg(self.palette.text),
self.fitted(run.label).fg(self.palette.text),
]),
segments: waited.into_iter().chain(once(ran)).collect(),
still_going_at: Some(self.now),
still_going: true,
}
}
}
@@ -208,9 +209,9 @@ impl Widget for Timeline<'_> {
segment.color,
));
});
if let Some(now) = entry.still_going_at {
if entry.still_going {
ctx.marker(Marker::Custom(self.glyphs.still_going));
ctx.draw(&Points::new(&[(now.as_secs_f64(), y)], muted));
ctx.draw(&Points::new(&[(self.now.as_secs_f64(), y)], muted));
}
});
ctx.marker(Marker::Custom(self.glyphs.root_switch_mark));
@@ -233,7 +234,7 @@ impl Widget for Timeline<'_> {
struct TimelineEntry<'a> {
label: Line<'a>,
segments: Vec<Segment>,
still_going_at: Option<Duration>,
still_going: bool,
}
struct Segment {
+77 -36
View File
@@ -56,12 +56,16 @@ fn width_of(text: &str) -> u16 {
}
impl UnitTree<'_> {
pub fn height(&self) -> u16 {
u16::try_from(self.rows.len() + usize::from(self.hidden > 0))
pub fn height_of(rows: usize, hidden: usize) -> u16 {
u16::try_from(rows + usize::from(hidden > 0))
.unwrap_or(u16::MAX)
.saturating_add(HEADER_ROWS)
}
pub fn height(&self) -> u16 {
Self::height_of(self.rows.len(), self.hidden)
}
fn phase_fits_its_column(&self, columns: &Columns) -> bool {
self.phase.width() <= usize::from(columns.label)
}
@@ -103,7 +107,7 @@ impl UnitTree<'_> {
(Stage::Reached, ..) => self.palette.done.into(),
(_, _, RowStatus::Failed) => Style::from(self.palette.failed).bold(),
(_, UnitKind::Target, _) => self.palette.target.into(),
(_, _, RowStatus::Running) => self.palette.text.into(),
(_, _, RowStatus::Running { .. }) => self.palette.text.into(),
(_, _, RowStatus::Waiting) => self.palette.waiting.into(),
(_, _, RowStatus::Done) => self.palette.muted.into(),
}
@@ -122,7 +126,7 @@ impl UnitTree<'_> {
format!("[{}] ", self.glyphs.failed).fg(self.palette.failed)
}
(_, UnitKind::Target, _) => Span::default(),
(_, _, RowStatus::Running) => {
(_, _, RowStatus::Running { .. }) => {
let spinner = SPINNER[usize::try_from(self.frame % 4).unwrap_or_default()];
format!("[{spinner}] ").fg(self.palette.running)
}
@@ -131,10 +135,6 @@ impl UnitTree<'_> {
}
}
fn lead_width(&self, row: &TreeRow, stage: Stage) -> usize {
tree_prefix(row).width() + self.status_marker(row, stage).width()
}
fn chained_label(&self, row: &TreeRow, room: usize) -> String {
let link = format!(" {} ", self.glyphs.chain_link);
let full: String = once(row.label.as_str())
@@ -182,10 +182,9 @@ impl UnitTree<'_> {
)
}
fn row(&self, row: &TreeRow, stage: Stage, columns: &Columns) -> Row<'static> {
let prefix = tree_prefix(row);
fn row(&self, row: &TreeRow, stage: Stage, prefix: String, columns: &Columns) -> Row<'static> {
let marker = self.status_marker(row, stage);
let room = usize::from(columns.label).saturating_sub(self.lead_width(row, stage));
let room = usize::from(columns.label).saturating_sub(prefix.width() + marker.width());
let annotation = |text: &str, width: u16| {
if row.chain.is_empty() {
fit_width(text, usize::from(width), self.glyphs.ellipsis)
@@ -193,12 +192,14 @@ impl UnitTree<'_> {
String::new()
}
};
let timer = row
.running_since
.map(|since| self.now.saturating_sub(since))
.filter(|running_for| *running_for >= self.hide_runs_shorter_than)
.map(|running_for| ELAPSED.unsigned_duration_to_string(&running_for))
.unwrap_or_default();
let timer = match row.status {
RowStatus::Running { since, .. }
if self.now.saturating_sub(since) >= self.hide_runs_shorter_than =>
{
ELAPSED.unsigned_duration_to_string(&self.now.saturating_sub(since))
}
_ => String::new(),
};
let style = self.label_style(row, stage);
Row::new(columns.shown([
Line::from(vec![
@@ -248,8 +249,9 @@ impl Widget for UnitTree<'_> {
self.rows
.iter()
.zip(self.stages())
.zip(tree_prefixes(self.rows))
.take(shown)
.map(|(row, stage)| self.row(row, stage, &columns))
.map(|((row, stage), prefix)| self.row(row, stage, prefix, &columns))
.chain(overflow),
columns.widths(),
)
@@ -261,24 +263,63 @@ impl Widget for UnitTree<'_> {
}
}
fn tree_prefix(row: &TreeRow) -> String {
let ancestors = row
.is_last_sibling
fn tree_prefixes(rows: &[TreeRow]) -> Vec<String> {
let mut later_sibling: Vec<bool> = Vec::new();
let mut is_last: Vec<bool> = rows
.iter()
.take(row.depth)
.map(|ancestor_is_last| {
if *ancestor_is_last {
ENDED_TRUNK
} else {
PASSING_TRUNK
}
});
let connector = match row.is_last_sibling.last() {
Some(false) => BRANCH,
_ => LAST_BRANCH,
};
once(ENDED_TRUNK)
.chain(ancestors)
.chain(once(connector))
.rev()
.map(|row| {
let last = !later_sibling.get(row.depth).copied().unwrap_or(false);
later_sibling.resize(row.depth + 1, false);
later_sibling[row.depth] = true;
last
})
.collect();
is_last.reverse();
let mut trunks: Vec<&str> = Vec::new();
rows.iter()
.zip(is_last)
.map(|(row, last)| {
trunks.truncate(row.depth);
let connector = if last { LAST_BRANCH } else { BRANCH };
let prefix = once(ENDED_TRUNK)
.chain(trunks.iter().copied())
.chain(once(connector))
.collect();
trunks.push(if last { ENDED_TRUNK } else { PASSING_TRUNK });
prefix
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn at_depth(depth: usize) -> TreeRow {
TreeRow {
depth,
label: String::new(),
description: String::new(),
kind: UnitKind::Service,
status: RowStatus::Waiting,
chain: Vec::new(),
}
}
#[test]
fn prefixes_close_each_branch_at_its_last_sibling() {
let rows: Vec<TreeRow> = [0, 0, 1, 1, 2, 0].into_iter().map(at_depth).collect();
assert_eq!(
tree_prefixes(&rows),
[
" ├─ ",
" ├─ ",
" │ ├─ ",
" │ └─ ",
" │ └─ ",
" └─ ",
]
);
}
}