boot-tree: live systemd boot dependency tree on a dedicated VT
This commit is contained in:
commit
097caf81a2
24 files changed
+4817
No files matched your search
@@ -0,0 +1,15 @@
|
||||
use rustix::{
|
||||
system::uname,
|
||||
time::{ClockId, clock_gettime},
|
||||
};
|
||||
|
||||
use crate::model::Micros;
|
||||
|
||||
pub fn monotonic_now() -> Micros {
|
||||
let now = clock_gettime(ClockId::Monotonic);
|
||||
now.tv_sec as Micros * 1_000_000 + now.tv_nsec as Micros / 1_000
|
||||
}
|
||||
|
||||
pub fn host_name() -> String {
|
||||
uname().nodename().to_string_lossy().into_owned()
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
use rustix::{
|
||||
io::Errno,
|
||||
ioctl::{Getter, IntegerSetter, Opcode, ioctl},
|
||||
stdio::stdin,
|
||||
termios::ttyname,
|
||||
};
|
||||
|
||||
const VT_GETSTATE: Opcode = 0x5603;
|
||||
const VT_ACTIVATE: Opcode = 0x5606;
|
||||
const VT_WAITACTIVE: Opcode = 0x5607;
|
||||
const VIRTUAL_TERMINAL_PREFIX: &str = "/dev/tty";
|
||||
|
||||
#[repr(C)]
|
||||
struct VtState {
|
||||
active: u16,
|
||||
_signal: u16,
|
||||
_state: u16,
|
||||
}
|
||||
|
||||
pub struct ForegroundVt {
|
||||
previous: u16,
|
||||
}
|
||||
|
||||
impl ForegroundVt {
|
||||
pub fn take() -> Option<Self> {
|
||||
let own = own_vt_number()?;
|
||||
let previous = active_vt().ok()?;
|
||||
if previous != own {
|
||||
activate(own).ok()?;
|
||||
}
|
||||
Some(Self { previous })
|
||||
}
|
||||
|
||||
pub fn give_back(self) {
|
||||
let _ = activate(self.previous);
|
||||
}
|
||||
}
|
||||
|
||||
fn own_vt_number() -> Option<u16> {
|
||||
let name = ttyname(stdin(), Vec::new()).ok()?;
|
||||
name.to_str()
|
||||
.ok()?
|
||||
.strip_prefix(VIRTUAL_TERMINAL_PREFIX)?
|
||||
.parse()
|
||||
.ok()
|
||||
.filter(|number| *number > 0)
|
||||
}
|
||||
|
||||
fn active_vt() -> Result<u16, Errno> {
|
||||
let state: VtState = unsafe { ioctl(stdin(), Getter::<VT_GETSTATE, VtState>::new()) }?;
|
||||
Ok(state.active)
|
||||
}
|
||||
|
||||
fn activate(number: u16) -> Result<(), Errno> {
|
||||
let number = usize::from(number);
|
||||
unsafe { ioctl(stdin(), IntegerSetter::<VT_ACTIVATE>::new_usize(number)) }?;
|
||||
unsafe { ioctl(stdin(), IntegerSetter::<VT_WAITACTIVE>::new_usize(number)) }?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
use std::{error, fmt, io};
|
||||
|
||||
use dbus::{Error as BusError, arg::TypeMismatchError};
|
||||
use rustix::io::Errno;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
Bus(BusError),
|
||||
Reply(TypeMismatchError),
|
||||
MalformedCall,
|
||||
Disconnected,
|
||||
Console(io::Error),
|
||||
RootSwitch(Errno),
|
||||
ManagerUnreachable,
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Bus(error) => write!(formatter, "systemd bus: {error}"),
|
||||
Self::Reply(error) => write!(formatter, "unexpected reply from systemd: {error}"),
|
||||
Self::MalformedCall => write!(formatter, "could not build a method call"),
|
||||
Self::Disconnected => write!(formatter, "the service manager closed the connection"),
|
||||
Self::Console(error) => write!(formatter, "console: {error}"),
|
||||
Self::RootSwitch(error) => write!(formatter, "entering the new root: {error}"),
|
||||
Self::ManagerUnreachable => write!(formatter, "the service manager did not come back"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl error::Error for Error {}
|
||||
|
||||
impl From<BusError> for Error {
|
||||
fn from(error: BusError) -> Self {
|
||||
Self::Bus(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TypeMismatchError> for Error {
|
||||
fn from(error: TypeMismatchError) -> Self {
|
||||
Self::Reply(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<io::Error> for Error {
|
||||
fn from(error: io::Error) -> Self {
|
||||
Self::Console(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Errno> for Error {
|
||||
fn from(error: Errno) -> Self {
|
||||
Self::RootSwitch(error)
|
||||
}
|
||||
}
|
||||
+254
@@ -0,0 +1,254 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
process,
|
||||
sync::mpsc::Sender,
|
||||
thread::{self, JoinHandle},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use dbus::Path;
|
||||
|
||||
use crate::{
|
||||
clock::monotonic_now,
|
||||
error::Error,
|
||||
model::{Activity, HANDOFF_UNIT, HOST_MILESTONES, JobResult, Micros, UnitFacts},
|
||||
sysroot::{Sysroot, running_in_initrd},
|
||||
systemd::{Scope, Session, Signal, brings_unit_up},
|
||||
};
|
||||
|
||||
const RECEIVE_TIMEOUT: Duration = Duration::from_millis(100);
|
||||
const RECONNECT_INTERVAL: Duration = Duration::from_millis(50);
|
||||
const RECONNECT_PATIENCE: Duration = Duration::from_secs(60);
|
||||
const SWITCH_ROOT_UNIT: &str = "initrd-switch-root.service";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum JobKind {
|
||||
BringsUp,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
pub enum Update {
|
||||
Root(String),
|
||||
Handoff(String),
|
||||
Origin(Micros),
|
||||
Unit {
|
||||
facts: UnitFacts,
|
||||
activity: Activity,
|
||||
},
|
||||
JobQueued {
|
||||
id: u32,
|
||||
unit: String,
|
||||
at: Micros,
|
||||
kind: JobKind,
|
||||
},
|
||||
JobFinished {
|
||||
id: u32,
|
||||
result: JobResult,
|
||||
at: Micros,
|
||||
},
|
||||
Activity {
|
||||
unit: String,
|
||||
activity: Activity,
|
||||
},
|
||||
RootSwitched {
|
||||
at: Micros,
|
||||
},
|
||||
Resubscribed,
|
||||
Ended(Error),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum OriginChoice {
|
||||
FromManager,
|
||||
Keep,
|
||||
}
|
||||
|
||||
pub struct FeedOptions {
|
||||
pub scope: Scope,
|
||||
pub target: Option<String>,
|
||||
}
|
||||
|
||||
pub fn spawn(options: FeedOptions, sender: Sender<Update>) -> JoinHandle<()> {
|
||||
thread::spawn(move || {
|
||||
let ended = Feed::new(options, sender.clone()).run();
|
||||
let _ = sender.send(Update::Ended(ended));
|
||||
})
|
||||
}
|
||||
|
||||
struct Feed {
|
||||
options: FeedOptions,
|
||||
sender: Sender<Update>,
|
||||
unit_paths: HashMap<Path<'static>, String>,
|
||||
in_initrd: bool,
|
||||
sysroot: Option<Sysroot>,
|
||||
}
|
||||
|
||||
impl Feed {
|
||||
fn new(options: FeedOptions, sender: Sender<Update>) -> Self {
|
||||
Self {
|
||||
in_initrd: options.scope == Scope::System && running_in_initrd(),
|
||||
options,
|
||||
sender,
|
||||
unit_paths: HashMap::new(),
|
||||
sysroot: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn send(&self, update: Update) {
|
||||
let _ = self.sender.send(update);
|
||||
}
|
||||
|
||||
fn run(mut self) -> Error {
|
||||
let mut session = match self.connect_patiently(OriginChoice::FromManager) {
|
||||
Ok(session) => session,
|
||||
Err(error) => return error,
|
||||
};
|
||||
loop {
|
||||
match session.receive(RECEIVE_TIMEOUT) {
|
||||
Ok(signals) => signals
|
||||
.into_iter()
|
||||
.for_each(|signal| self.apply(&session, signal)),
|
||||
Err(_) => match self.reconnect() {
|
||||
Ok(reconnected) => session = reconnected,
|
||||
Err(error) => return error,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn connect(&mut self, origin: OriginChoice) -> Result<Session, Error> {
|
||||
let session = Session::open(self.options.scope)?;
|
||||
session.subscribe()?;
|
||||
let requested_root = match &self.options.target {
|
||||
Some(target) => target.clone(),
|
||||
None => session.default_target()?,
|
||||
};
|
||||
if origin == OriginChoice::FromManager {
|
||||
let boot_in_progress = session.boot_in_progress()?;
|
||||
self.send(Update::Origin(if boot_in_progress {
|
||||
0
|
||||
} else {
|
||||
monotonic_now()
|
||||
}));
|
||||
}
|
||||
let root = self
|
||||
.track(&session, &requested_root)
|
||||
.unwrap_or(requested_root);
|
||||
self.send(Update::Root(root.clone()));
|
||||
if let Some(handoff) = self.track(&session, HANDOFF_UNIT) {
|
||||
self.send(Update::Handoff(handoff));
|
||||
}
|
||||
let jobs: Vec<_> = session
|
||||
.list_jobs()?
|
||||
.into_iter()
|
||||
.filter(|job| brings_unit_up(&job.kind))
|
||||
.collect();
|
||||
jobs.iter()
|
||||
.map(|job| job.unit.as_str())
|
||||
.chain(HOST_MILESTONES)
|
||||
.for_each(|unit| {
|
||||
self.track(&session, unit);
|
||||
});
|
||||
let now = monotonic_now();
|
||||
jobs.into_iter().for_each(|job| {
|
||||
self.send(Update::JobQueued {
|
||||
id: job.id,
|
||||
unit: job.unit,
|
||||
at: now,
|
||||
kind: JobKind::BringsUp,
|
||||
});
|
||||
});
|
||||
eprintln!(
|
||||
"boot-tree: watching {root} in {} as pid {} over {}",
|
||||
if self.in_initrd { "initrd" } else { "stage 2" },
|
||||
process::id(),
|
||||
if session.is_peer_to_peer() {
|
||||
"the private socket"
|
||||
} else {
|
||||
"the bus"
|
||||
},
|
||||
);
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
fn reconnect(&mut self) -> Result<Session, Error> {
|
||||
match self.sysroot.take() {
|
||||
Some(sysroot) => {
|
||||
sysroot.enter()?;
|
||||
self.in_initrd = false;
|
||||
self.unit_paths.clear();
|
||||
self.send(Update::RootSwitched {
|
||||
at: monotonic_now(),
|
||||
});
|
||||
}
|
||||
None => self.send(Update::Resubscribed),
|
||||
}
|
||||
self.connect_patiently(OriginChoice::Keep)
|
||||
}
|
||||
|
||||
fn connect_patiently(&mut self, origin: OriginChoice) -> Result<Session, Error> {
|
||||
let deadline = Instant::now() + RECONNECT_PATIENCE;
|
||||
loop {
|
||||
match self.connect(origin) {
|
||||
Ok(session) => return Ok(session),
|
||||
Err(_) if Instant::now() < deadline => thread::sleep(RECONNECT_INTERVAL),
|
||||
Err(_) => return Err(Error::ManagerUnreachable),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn track(&mut self, session: &Session, unit: &str) -> Option<String> {
|
||||
if let Some(known) = self.unit_paths.values().find(|known| *known == unit) {
|
||||
return Some(known.clone());
|
||||
}
|
||||
let fetched = session.fetch_unit(unit).ok()?;
|
||||
let canonical = fetched.facts.name.clone();
|
||||
if self.unit_paths.values().any(|known| *known == canonical) {
|
||||
return Some(canonical);
|
||||
}
|
||||
self.unit_paths.insert(fetched.path, canonical.clone());
|
||||
self.send(Update::Unit {
|
||||
facts: fetched.facts,
|
||||
activity: fetched.activity,
|
||||
});
|
||||
Some(canonical)
|
||||
}
|
||||
|
||||
fn apply(&mut self, session: &Session, signal: Signal) {
|
||||
match signal {
|
||||
Signal::JobNew { id, job, unit } => {
|
||||
let kind = session.job_kind(&job);
|
||||
if kind.as_deref().is_ok_and(|kind| !brings_unit_up(kind)) {
|
||||
return;
|
||||
}
|
||||
let unit = self.track(session, &unit).unwrap_or(unit);
|
||||
if self.in_initrd && unit == SWITCH_ROOT_UNIT {
|
||||
self.sysroot = Sysroot::hold().ok();
|
||||
}
|
||||
self.send(Update::JobQueued {
|
||||
id,
|
||||
unit,
|
||||
at: monotonic_now(),
|
||||
kind: if kind.is_ok() {
|
||||
JobKind::BringsUp
|
||||
} else {
|
||||
JobKind::Unknown
|
||||
},
|
||||
});
|
||||
}
|
||||
Signal::JobRemoved { id, result } => self.send(Update::JobFinished {
|
||||
id,
|
||||
result,
|
||||
at: monotonic_now(),
|
||||
}),
|
||||
Signal::UnitChanged { path, activity } => {
|
||||
if let Some(unit) = self.unit_paths.get(&path) {
|
||||
self.send(Update::Activity {
|
||||
unit: unit.clone(),
|
||||
activity,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
mod clock;
|
||||
mod console;
|
||||
mod error;
|
||||
mod feed;
|
||||
mod model;
|
||||
mod run;
|
||||
mod sysroot;
|
||||
mod systemd;
|
||||
mod view;
|
||||
|
||||
use std::{process::ExitCode, time::Duration};
|
||||
|
||||
use clap::Parser;
|
||||
|
||||
use crate::{
|
||||
run::{Options, run},
|
||||
systemd::Scope,
|
||||
};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(about = "Live dependency tree of systemd jobs while the system boots")]
|
||||
struct Cli {
|
||||
#[arg(long, help = "Watch the user service manager instead of PID 1")]
|
||||
user: bool,
|
||||
#[arg(
|
||||
long,
|
||||
help = "Root unit of the tree; defaults to the manager's default target"
|
||||
)]
|
||||
target: Option<String>,
|
||||
#[arg(
|
||||
long,
|
||||
default_value_t = 0,
|
||||
help = "Milliseconds to keep the final frame on screen"
|
||||
)]
|
||||
hold_ms: u64,
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let cli = Cli::parse();
|
||||
let options = Options {
|
||||
scope: if cli.user { Scope::User } else { Scope::System },
|
||||
target: cli.target,
|
||||
hold: Duration::from_millis(cli.hold_ms),
|
||||
};
|
||||
match run(options) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(error) => {
|
||||
eprintln!("boot-tree: {error}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
+860
@@ -0,0 +1,860 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
pub type Micros = u64;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Phase {
|
||||
Initrd,
|
||||
Host,
|
||||
User,
|
||||
}
|
||||
|
||||
impl Phase {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Initrd => "initrd",
|
||||
Self::Host => "stage 2",
|
||||
Self::User => "user",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ActiveState {
|
||||
Inactive,
|
||||
Activating,
|
||||
Active,
|
||||
Deactivating,
|
||||
Reloading,
|
||||
Failed,
|
||||
}
|
||||
|
||||
impl ActiveState {
|
||||
pub fn parse(raw: &str) -> Self {
|
||||
match raw {
|
||||
"activating" => Self::Activating,
|
||||
"active" => Self::Active,
|
||||
"deactivating" => Self::Deactivating,
|
||||
"reloading" => Self::Reloading,
|
||||
"failed" => Self::Failed,
|
||||
_ => Self::Inactive,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_transitioning(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Activating | Self::Deactivating | Self::Reloading
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum JobResult {
|
||||
Done,
|
||||
Skipped,
|
||||
Canceled,
|
||||
Failed,
|
||||
Timeout,
|
||||
Dependency,
|
||||
}
|
||||
|
||||
impl JobResult {
|
||||
pub fn parse(raw: &str) -> Self {
|
||||
match raw {
|
||||
"done" => Self::Done,
|
||||
"skipped" => Self::Skipped,
|
||||
"canceled" => Self::Canceled,
|
||||
"timeout" => Self::Timeout,
|
||||
"dependency" => Self::Dependency,
|
||||
_ => Self::Failed,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_failure(self) -> bool {
|
||||
matches!(self, Self::Failed | Self::Timeout | Self::Dependency)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct UnitFacts {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub after: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Activity {
|
||||
pub state: Option<ActiveState>,
|
||||
pub inactive_exit: Option<Micros>,
|
||||
pub active_enter: Option<Micros>,
|
||||
}
|
||||
|
||||
impl Activity {
|
||||
pub fn timestamp(raw: u64) -> Option<Micros> {
|
||||
(raw != 0).then_some(raw)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct PendingJob {
|
||||
id: u32,
|
||||
queued_at: Micros,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct Outcome {
|
||||
result: JobResult,
|
||||
at: Micros,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct UnitRecord {
|
||||
facts: UnitFacts,
|
||||
state: ActiveState,
|
||||
inactive_exit: Option<Micros>,
|
||||
active_enter: Option<Micros>,
|
||||
job: Option<PendingJob>,
|
||||
outcome: Option<Outcome>,
|
||||
}
|
||||
|
||||
impl UnitRecord {
|
||||
fn apply(&mut self, activity: Activity) {
|
||||
if let Some(state) = activity.state {
|
||||
self.state = state;
|
||||
}
|
||||
if activity.inactive_exit.is_some() {
|
||||
self.inactive_exit = activity.inactive_exit;
|
||||
}
|
||||
if activity.active_enter.is_some() {
|
||||
self.active_enter = activity.active_enter;
|
||||
}
|
||||
}
|
||||
|
||||
fn running_since(&self) -> Option<Micros> {
|
||||
let job = self.job?;
|
||||
if !self.state.is_transitioning() {
|
||||
return None;
|
||||
}
|
||||
Some(self.inactive_exit.unwrap_or(job.queued_at))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RowStatus {
|
||||
Waiting,
|
||||
Running,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PendingRow {
|
||||
pub depth: usize,
|
||||
pub is_last_sibling: Vec<bool>,
|
||||
pub label: String,
|
||||
pub status: RowStatus,
|
||||
pub queued_at: Micros,
|
||||
pub running_since: Option<Micros>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct MilestoneRow {
|
||||
pub label: String,
|
||||
pub finished_units: usize,
|
||||
pub started_at: Micros,
|
||||
pub reached_at: Option<Micros>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Tally {
|
||||
pub done: usize,
|
||||
pub running: usize,
|
||||
pub waiting: usize,
|
||||
pub failed: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct FrozenMilestone {
|
||||
label: String,
|
||||
finished_units: usize,
|
||||
started_at: Micros,
|
||||
reached_at: Micros,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BootState {
|
||||
phase: Phase,
|
||||
origin: Micros,
|
||||
root: Option<String>,
|
||||
root_job_seen: bool,
|
||||
handoff_unit: Option<String>,
|
||||
milestone_targets: Vec<String>,
|
||||
frozen: Vec<FrozenMilestone>,
|
||||
failed: Vec<String>,
|
||||
finished_before_switch: usize,
|
||||
units: HashMap<String, UnitRecord>,
|
||||
jobs: HashMap<u32, String>,
|
||||
}
|
||||
|
||||
pub const HOST_MILESTONES: [&str; 4] = [
|
||||
"sysinit.target",
|
||||
"basic.target",
|
||||
"multi-user.target",
|
||||
"graphical.target",
|
||||
];
|
||||
|
||||
pub const HANDOFF_UNIT: &str = "display-manager.service";
|
||||
|
||||
impl BootState {
|
||||
pub fn new(phase: Phase) -> Self {
|
||||
let (milestone_targets, handoff_unit) = match phase {
|
||||
Phase::Initrd | Phase::Host => (
|
||||
HOST_MILESTONES.iter().map(ToString::to_string).collect(),
|
||||
Some(HANDOFF_UNIT.to_owned()),
|
||||
),
|
||||
Phase::User => (Vec::new(), None),
|
||||
};
|
||||
Self {
|
||||
phase,
|
||||
origin: 0,
|
||||
root: None,
|
||||
root_job_seen: false,
|
||||
handoff_unit,
|
||||
milestone_targets,
|
||||
frozen: Vec::new(),
|
||||
failed: Vec::new(),
|
||||
finished_before_switch: 0,
|
||||
units: HashMap::new(),
|
||||
jobs: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn phase(&self) -> Phase {
|
||||
self.phase
|
||||
}
|
||||
|
||||
pub fn origin(&self) -> Micros {
|
||||
self.origin
|
||||
}
|
||||
|
||||
pub fn set_origin(&mut self, origin: Micros) {
|
||||
self.origin = origin;
|
||||
}
|
||||
|
||||
pub fn root(&self) -> Option<&str> {
|
||||
self.root.as_deref()
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
pub fn set_handoff(&mut self, unit: String) {
|
||||
if self.handoff_unit.is_some() {
|
||||
self.handoff_unit = Some(unit);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn failed_units(&self) -> &[String] {
|
||||
&self.failed
|
||||
}
|
||||
|
||||
pub fn track_unit(&mut self, facts: UnitFacts, activity: Activity) {
|
||||
let record = self
|
||||
.units
|
||||
.entry(facts.name.clone())
|
||||
.or_insert_with(|| UnitRecord {
|
||||
facts: facts.clone(),
|
||||
state: ActiveState::Inactive,
|
||||
inactive_exit: None,
|
||||
active_enter: None,
|
||||
job: None,
|
||||
outcome: None,
|
||||
});
|
||||
record.facts = facts;
|
||||
record.apply(activity);
|
||||
}
|
||||
|
||||
pub fn update_activity(&mut self, unit: &str, activity: Activity) {
|
||||
if let Some(record) = self.units.get_mut(unit) {
|
||||
record.apply(activity);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn queue_job(&mut self, id: u32, unit: &str, at: Micros) {
|
||||
self.queue_job_of_unknown_kind(id, unit, at);
|
||||
if self.jobs.get(&id).is_some_and(|tracked| tracked == unit)
|
||||
&& self.root.as_deref() == Some(unit)
|
||||
{
|
||||
self.root_job_seen = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn queue_job_of_unknown_kind(&mut self, id: u32, unit: &str, at: Micros) {
|
||||
if self.jobs.contains_key(&id) {
|
||||
return;
|
||||
}
|
||||
let Some(record) = self.units.get_mut(unit) else {
|
||||
return;
|
||||
};
|
||||
record.job = Some(PendingJob { id, queued_at: at });
|
||||
record.outcome = None;
|
||||
self.jobs.insert(id, unit.to_owned());
|
||||
}
|
||||
|
||||
pub fn finish_job(&mut self, id: u32, result: JobResult, at: Micros) {
|
||||
let Some(unit) = self.jobs.remove(&id) else {
|
||||
return;
|
||||
};
|
||||
let Some(record) = self.units.get_mut(&unit) else {
|
||||
return;
|
||||
};
|
||||
if record.job.is_some_and(|job| job.id == id) {
|
||||
record.job = None;
|
||||
}
|
||||
record.outcome = Some(Outcome { result, at });
|
||||
if result.is_failure() && !self.failed.contains(&unit) {
|
||||
self.failed.push(unit);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn switch_root(&mut self, at: Micros) {
|
||||
let started_at = self.origin;
|
||||
let finished_units = self.finished_units() + self.finished_before_switch;
|
||||
self.frozen.push(FrozenMilestone {
|
||||
label: Phase::Initrd.label().to_owned(),
|
||||
finished_units,
|
||||
started_at,
|
||||
reached_at: at,
|
||||
});
|
||||
self.phase = Phase::Host;
|
||||
self.root = None;
|
||||
self.root_job_seen = false;
|
||||
self.finished_before_switch = 0;
|
||||
self.units.clear();
|
||||
self.jobs.clear();
|
||||
}
|
||||
|
||||
pub fn forget_jobs(&mut self) {
|
||||
self.finished_before_switch += self.finished_units();
|
||||
self.jobs.clear();
|
||||
self.units.values_mut().for_each(|record| {
|
||||
record.job = None;
|
||||
record.outcome = None;
|
||||
});
|
||||
}
|
||||
|
||||
fn finished_units(&self) -> usize {
|
||||
self.units
|
||||
.values()
|
||||
.filter(|record| record.outcome.is_some())
|
||||
.count()
|
||||
}
|
||||
|
||||
pub fn is_complete(&self) -> bool {
|
||||
if self.phase == Phase::Initrd {
|
||||
return false;
|
||||
}
|
||||
if let Some(handoff) = self
|
||||
.handoff_unit
|
||||
.as_deref()
|
||||
.and_then(|unit| self.units.get(unit))
|
||||
&& handoff.job.is_some()
|
||||
&& handoff.state != ActiveState::Inactive
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let Some(root) = self.root.as_deref().and_then(|root| self.units.get(root)) else {
|
||||
return false;
|
||||
};
|
||||
self.root_job_seen && root.job.is_none()
|
||||
}
|
||||
|
||||
pub fn tally(&self) -> Tally {
|
||||
let carried = Tally {
|
||||
done: self
|
||||
.frozen
|
||||
.iter()
|
||||
.map(|frozen| frozen.finished_units)
|
||||
.sum::<usize>()
|
||||
+ self.finished_before_switch,
|
||||
failed: self.failed.len(),
|
||||
..Tally::default()
|
||||
};
|
||||
self.units.values().fold(carried, |mut tally, record| {
|
||||
if record.job.is_some() && record.running_since().is_some() {
|
||||
tally.running += 1;
|
||||
} else if record.job.is_some() {
|
||||
tally.waiting += 1;
|
||||
} else if record
|
||||
.outcome
|
||||
.is_some_and(|outcome| !outcome.result.is_failure())
|
||||
{
|
||||
tally.done += 1;
|
||||
}
|
||||
tally
|
||||
})
|
||||
}
|
||||
|
||||
fn milestone_reached_at(&self, target: &str) -> Option<Micros> {
|
||||
let record = self.units.get(target)?;
|
||||
if record.job.is_some() {
|
||||
return None;
|
||||
}
|
||||
match record.outcome {
|
||||
Some(outcome) if outcome.result == JobResult::Done => Some(outcome.at),
|
||||
Some(_) => None,
|
||||
None => record
|
||||
.active_enter
|
||||
.filter(|entered| record.state == ActiveState::Active && *entered >= self.origin),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn milestones(&self) -> Vec<MilestoneRow> {
|
||||
let mut finished: Vec<Micros> = self
|
||||
.units
|
||||
.values()
|
||||
.filter_map(|record| record.outcome)
|
||||
.filter(|outcome| !outcome.result.is_failure())
|
||||
.map(|outcome| outcome.at)
|
||||
.collect();
|
||||
finished.sort_unstable();
|
||||
let start = MilestoneWalk {
|
||||
rows: self.frozen.iter().map(FrozenMilestone::row).collect(),
|
||||
previous: self
|
||||
.frozen
|
||||
.last()
|
||||
.map_or(self.origin, |frozen| frozen.reached_at),
|
||||
consumed: 0,
|
||||
};
|
||||
let mut walk = 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, &finished));
|
||||
let remaining = finished.len() - walk.consumed + self.finished_before_switch;
|
||||
if remaining > 0 {
|
||||
walk.rows.push(MilestoneRow {
|
||||
label: "finished".to_owned(),
|
||||
finished_units: remaining,
|
||||
started_at: walk.previous,
|
||||
reached_at: None,
|
||||
});
|
||||
}
|
||||
walk.rows
|
||||
}
|
||||
|
||||
pub fn pending_rows(&self) -> Vec<PendingRow> {
|
||||
let pending: HashSet<&str> = self
|
||||
.units
|
||||
.iter()
|
||||
.filter(|(_, record)| record.job.is_some())
|
||||
.map(|(name, _)| name.as_str())
|
||||
.collect();
|
||||
let root = self.root.as_deref().filter(|root| pending.contains(root));
|
||||
let blocked_by_pending: HashSet<&str> = pending
|
||||
.iter()
|
||||
.flat_map(|name| self.units[*name].facts.after.iter())
|
||||
.map(String::as_str)
|
||||
.filter(|dependency| pending.contains(dependency))
|
||||
.collect();
|
||||
let mut unblocked: Vec<&str> = pending
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|name| !blocked_by_pending.contains(name) && Some(*name) != root)
|
||||
.collect();
|
||||
self.sort_siblings(&mut unblocked);
|
||||
let mut leftovers: Vec<&str> = pending.iter().copied().collect();
|
||||
self.sort_siblings(&mut leftovers);
|
||||
if self.phase == Phase::User {
|
||||
unblocked.clear();
|
||||
leftovers.clear();
|
||||
}
|
||||
let mut rows = Vec::new();
|
||||
let mut visited = HashSet::new();
|
||||
root.into_iter()
|
||||
.chain(unblocked)
|
||||
.chain(leftovers)
|
||||
.for_each(|top| {
|
||||
if !visited.contains(top) {
|
||||
self.emit(
|
||||
top,
|
||||
&pending,
|
||||
&mut visited,
|
||||
&mut Vec::new(),
|
||||
true,
|
||||
&mut rows,
|
||||
);
|
||||
}
|
||||
});
|
||||
rows
|
||||
}
|
||||
|
||||
fn emit<'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<PendingRow>,
|
||||
) {
|
||||
visited.insert(unit);
|
||||
let record = &self.units[unit];
|
||||
let job = record.job.expect("pending rows only hold units with a job");
|
||||
let running_since = record.running_since();
|
||||
let mut is_last_sibling = ancestry.clone();
|
||||
is_last_sibling.push(is_last);
|
||||
rows.push(PendingRow {
|
||||
depth: ancestry.len(),
|
||||
is_last_sibling,
|
||||
label: display_label(&record.facts),
|
||||
status: if running_since.is_some() {
|
||||
RowStatus::Running
|
||||
} else {
|
||||
RowStatus::Waiting
|
||||
},
|
||||
queued_at: job.queued_at,
|
||||
running_since,
|
||||
});
|
||||
let candidates: Vec<&str> = record
|
||||
.facts
|
||||
.after
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.filter(|dependency| pending.contains(dependency) && !visited.contains(dependency))
|
||||
.collect();
|
||||
let mut children: Vec<&str> = candidates
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|child| {
|
||||
!candidates.iter().any(|sibling| {
|
||||
sibling != child
|
||||
&& self.waits_on(sibling, child, pending)
|
||||
&& !self.waits_on(child, sibling, pending)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
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();
|
||||
}
|
||||
|
||||
fn waits_on(&self, waiter: &str, dependency: &str, pending: &HashSet<&str>) -> bool {
|
||||
let mut seen = HashSet::new();
|
||||
let mut frontier = vec![waiter];
|
||||
while let Some(unit) = frontier.pop() {
|
||||
if !seen.insert(unit) {
|
||||
continue;
|
||||
}
|
||||
let Some(record) = self.units.get(unit) else {
|
||||
continue;
|
||||
};
|
||||
let mut next = record
|
||||
.facts
|
||||
.after
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.filter(|after| pending.contains(after));
|
||||
if next.clone().any(|after| after == dependency) {
|
||||
return true;
|
||||
}
|
||||
frontier.extend(next.by_ref());
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn sibling_rank(&self, name: &str) -> SiblingRank {
|
||||
match self.units[name].running_since() {
|
||||
Some(since) => SiblingRank::RunningSince(since),
|
||||
None => SiblingRank::Waiting,
|
||||
}
|
||||
}
|
||||
|
||||
fn sort_siblings(&self, names: &mut [&str]) {
|
||||
names.sort_by(|left, right| {
|
||||
self.sibling_rank(left)
|
||||
.cmp(&self.sibling_rank(right))
|
||||
.then_with(|| left.cmp(right))
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum SiblingRank {
|
||||
RunningSince(Micros),
|
||||
Waiting,
|
||||
}
|
||||
|
||||
struct ReachedMilestone<'a> {
|
||||
target: &'a str,
|
||||
reached_at: Micros,
|
||||
}
|
||||
|
||||
struct MilestoneWalk {
|
||||
rows: Vec<MilestoneRow>,
|
||||
previous: Micros,
|
||||
consumed: usize,
|
||||
}
|
||||
|
||||
impl MilestoneWalk {
|
||||
fn advance(mut self, reached: &ReachedMilestone, finished_sorted: &[Micros]) -> Self {
|
||||
let upto = finished_sorted.partition_point(|at| *at <= reached.reached_at);
|
||||
self.rows.push(MilestoneRow {
|
||||
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),
|
||||
});
|
||||
self.consumed = self.consumed.max(upto);
|
||||
self.previous = reached.reached_at;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl FrozenMilestone {
|
||||
fn row(&self) -> MilestoneRow {
|
||||
MilestoneRow {
|
||||
label: self.label.clone(),
|
||||
finished_units: self.finished_units,
|
||||
started_at: self.started_at,
|
||||
reached_at: Some(self.reached_at),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn display_label(facts: &UnitFacts) -> String {
|
||||
if let Some(stem) = facts.name.strip_suffix(".service") {
|
||||
return stem.to_owned();
|
||||
}
|
||||
if facts.name.ends_with(".device") && !facts.description.is_empty() {
|
||||
return facts.description.clone();
|
||||
}
|
||||
facts.name.clone()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn facts(name: &str, after: &[&str]) -> UnitFacts {
|
||||
UnitFacts {
|
||||
name: name.to_owned(),
|
||||
description: format!("{name} description"),
|
||||
after: after.iter().map(ToString::to_string).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn activating(since: Micros) -> Activity {
|
||||
Activity {
|
||||
state: Some(ActiveState::Activating),
|
||||
inactive_exit: Some(since),
|
||||
active_enter: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn sample() -> BootState {
|
||||
let mut state = BootState::new(Phase::Host);
|
||||
state.set_root("graphical.target".to_owned());
|
||||
state.track_unit(
|
||||
facts("graphical.target", &["multi-user.target"]),
|
||||
Activity::default(),
|
||||
);
|
||||
state.track_unit(
|
||||
facts(
|
||||
"multi-user.target",
|
||||
&["docker.service", "nm-wait.service", "basic.target"],
|
||||
),
|
||||
Activity::default(),
|
||||
);
|
||||
state.track_unit(
|
||||
facts("nm-wait.service", &["nm.service"]),
|
||||
Activity::default(),
|
||||
);
|
||||
state.track_unit(facts("nm.service", &[]), activating(1_000_000));
|
||||
state.track_unit(
|
||||
facts("docker.service", &["containerd.service"]),
|
||||
activating(3_000_000),
|
||||
);
|
||||
state.track_unit(facts("containerd.service", &[]), Activity::default());
|
||||
state.track_unit(facts("basic.target", &[]), Activity::default());
|
||||
[
|
||||
"graphical.target",
|
||||
"multi-user.target",
|
||||
"nm-wait.service",
|
||||
"nm.service",
|
||||
"docker.service",
|
||||
"containerd.service",
|
||||
"basic.target",
|
||||
]
|
||||
.into_iter()
|
||||
.zip(1..)
|
||||
.for_each(|(unit, id)| state.queue_job(id, unit, 500_000));
|
||||
state
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_units_nest_under_what_waits_on_them() {
|
||||
let outline: Vec<String> = sample()
|
||||
.pending_rows()
|
||||
.into_iter()
|
||||
.map(|row| format!("{}{}", " ".repeat(row.depth), row.label))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
outline,
|
||||
[
|
||||
"graphical.target",
|
||||
" multi-user.target",
|
||||
" docker",
|
||||
" containerd",
|
||||
" basic.target",
|
||||
" nm-wait",
|
||||
" nm",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finished_jobs_leave_the_tree_and_count_toward_their_milestone() {
|
||||
let mut state = sample();
|
||||
state.finish_job(6, JobResult::Done, 3_500_000);
|
||||
state.finish_job(7, JobResult::Done, 4_000_000);
|
||||
state.update_activity(
|
||||
"basic.target",
|
||||
Activity {
|
||||
state: Some(ActiveState::Active),
|
||||
inactive_exit: None,
|
||||
active_enter: Some(4_000_000),
|
||||
},
|
||||
);
|
||||
let rows = state.pending_rows();
|
||||
assert!(
|
||||
rows.iter()
|
||||
.all(|row| row.label != "containerd" && row.label != "basic.target")
|
||||
);
|
||||
let milestones = state.milestones();
|
||||
assert_eq!(milestones.len(), 1);
|
||||
assert_eq!(milestones[0].label, "basic.target");
|
||||
assert_eq!(milestones[0].finished_units, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failures_are_listed_and_not_counted_as_done() {
|
||||
let mut state = sample();
|
||||
state.finish_job(4, JobResult::Failed, 2_000_000);
|
||||
assert_eq!(state.failed_units(), ["nm.service"]);
|
||||
let tally = state.tally();
|
||||
assert_eq!(tally.failed, 1);
|
||||
assert_eq!(tally.done, 0);
|
||||
assert_eq!(tally.running, 1);
|
||||
assert_eq!(tally.waiting, 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boot_completes_when_the_root_job_is_gone() {
|
||||
let mut state = sample();
|
||||
assert!(!state.is_complete());
|
||||
(1..=7).for_each(|id| state.finish_job(id, JobResult::Done, 5_000_000));
|
||||
assert!(state.is_complete());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_manager_activation_hands_the_console_over() {
|
||||
let mut state = sample();
|
||||
state.track_unit(facts(HANDOFF_UNIT, &[]), Activity::default());
|
||||
state.queue_job(20, HANDOFF_UNIT, 500_000);
|
||||
assert!(!state.is_complete());
|
||||
state.update_activity(HANDOFF_UNIT, activating(6_000_000));
|
||||
assert!(state.is_complete());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_root_freezes_the_initrd_summary() {
|
||||
let mut state = BootState::new(Phase::Initrd);
|
||||
state.set_root("initrd.target".to_owned());
|
||||
state.track_unit(facts("initrd.target", &[]), Activity::default());
|
||||
state.track_unit(facts("sysroot.mount", &[]), Activity::default());
|
||||
state.queue_job(1, "initrd.target", 0);
|
||||
state.queue_job(2, "sysroot.mount", 0);
|
||||
state.finish_job(2, JobResult::Done, 1_000_000);
|
||||
state.finish_job(1, JobResult::Done, 1_500_000);
|
||||
assert!(!state.is_complete());
|
||||
state.switch_root(2_000_000);
|
||||
assert_eq!(state.phase(), Phase::Host);
|
||||
let milestones = state.milestones();
|
||||
assert_eq!(milestones[0].label, "initrd");
|
||||
assert_eq!(milestones[0].finished_units, 2);
|
||||
assert_eq!(milestones[0].reached_at, Some(2_000_000));
|
||||
assert_eq!(state.tally().done, 2);
|
||||
assert!(state.pending_rows().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn devices_show_their_description() {
|
||||
let mut state = BootState::new(Phase::Host);
|
||||
state.track_unit(
|
||||
UnitFacts {
|
||||
name: "dev-nvme1n1.device".to_owned(),
|
||||
description: "Lexar SSD NM790 2TB".to_owned(),
|
||||
after: Vec::new(),
|
||||
},
|
||||
Activity::default(),
|
||||
);
|
||||
state.queue_job(1, "dev-nvme1n1.device", 0);
|
||||
assert_eq!(state.pending_rows()[0].label, "Lexar SSD NM790 2TB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn units_nest_under_the_deepest_pending_waiter() {
|
||||
let mut state = BootState::new(Phase::Host);
|
||||
state.set_root("demo.target".to_owned());
|
||||
state.track_unit(
|
||||
facts(
|
||||
"demo.target",
|
||||
&["report.service", "web.service", "db.service"],
|
||||
),
|
||||
Activity::default(),
|
||||
);
|
||||
state.track_unit(
|
||||
facts("report.service", &["web.service"]),
|
||||
Activity::default(),
|
||||
);
|
||||
state.track_unit(facts("web.service", &["db.service"]), Activity::default());
|
||||
state.track_unit(facts("db.service", &[]), Activity::default());
|
||||
["demo.target", "report.service", "web.service", "db.service"]
|
||||
.into_iter()
|
||||
.zip(1..)
|
||||
.for_each(|(unit, id)| state.queue_job(id, unit, 0));
|
||||
let outline: Vec<String> = state
|
||||
.pending_rows()
|
||||
.into_iter()
|
||||
.map(|row| format!("{}{}", " ".repeat(row.depth), row.label))
|
||||
.collect();
|
||||
assert_eq!(outline, ["demo.target", " report", " web", " db"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordering_cycles_do_not_repeat_units() {
|
||||
let mut state = BootState::new(Phase::Host);
|
||||
state.track_unit(facts("a.service", &["b.service"]), Activity::default());
|
||||
state.track_unit(facts("b.service", &["a.service"]), Activity::default());
|
||||
state.queue_job(1, "a.service", 0);
|
||||
state.queue_job(2, "b.service", 0);
|
||||
assert_eq!(state.pending_rows().len(), 2);
|
||||
}
|
||||
}
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
use std::{
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
mpsc::{Receiver, channel},
|
||||
},
|
||||
thread::sleep,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
|
||||
use ratatui::{
|
||||
DefaultTerminal,
|
||||
backend::{Backend, ClearType},
|
||||
};
|
||||
use signal_hook::{consts::SIGTERM, flag};
|
||||
|
||||
use crate::{
|
||||
clock::{host_name, monotonic_now},
|
||||
console::ForegroundVt,
|
||||
error::Error,
|
||||
feed::{self, FeedOptions, JobKind, Update},
|
||||
model::{BootState, Phase},
|
||||
sysroot::running_in_initrd,
|
||||
systemd::Scope,
|
||||
view::BootView,
|
||||
};
|
||||
|
||||
const FRAME_INTERVAL: Duration = Duration::from_millis(100);
|
||||
const FRAMES_PER_FULL_REPAINT: u64 = 20;
|
||||
|
||||
pub struct Options {
|
||||
pub scope: Scope,
|
||||
pub target: Option<String>,
|
||||
pub hold: Duration,
|
||||
}
|
||||
|
||||
pub fn run(options: Options) -> Result<(), Error> {
|
||||
let terminate = Arc::new(AtomicBool::new(false));
|
||||
flag::register(SIGTERM, Arc::clone(&terminate))?;
|
||||
let (sender, updates) = channel();
|
||||
let mut state = BootState::new(initial_phase(options.scope));
|
||||
feed::spawn(
|
||||
FeedOptions {
|
||||
scope: options.scope,
|
||||
target: options.target,
|
||||
},
|
||||
sender,
|
||||
);
|
||||
let foreground = ForegroundVt::take();
|
||||
let mut terminal = ratatui::try_init()?;
|
||||
let watched = watch(
|
||||
&mut state,
|
||||
&updates,
|
||||
&mut terminal,
|
||||
&terminate,
|
||||
options.hold,
|
||||
);
|
||||
ratatui::restore();
|
||||
if let Some(foreground) = foreground {
|
||||
foreground.give_back();
|
||||
}
|
||||
watched
|
||||
}
|
||||
|
||||
fn initial_phase(scope: Scope) -> Phase {
|
||||
match scope {
|
||||
Scope::User => Phase::User,
|
||||
Scope::System if running_in_initrd() => Phase::Initrd,
|
||||
Scope::System => Phase::Host,
|
||||
}
|
||||
}
|
||||
|
||||
fn absorb(state: &mut BootState, update: Update) -> Option<Error> {
|
||||
match update {
|
||||
Update::Root(root) => state.set_root(root),
|
||||
Update::Handoff(unit) => state.set_handoff(unit),
|
||||
Update::Origin(origin) => state.set_origin(origin),
|
||||
Update::Unit { facts, activity } => state.track_unit(facts, activity),
|
||||
Update::JobQueued {
|
||||
id,
|
||||
unit,
|
||||
at,
|
||||
kind: JobKind::BringsUp,
|
||||
} => state.queue_job(id, &unit, at),
|
||||
Update::JobQueued {
|
||||
id,
|
||||
unit,
|
||||
at,
|
||||
kind: JobKind::Unknown,
|
||||
} => state.queue_job_of_unknown_kind(id, &unit, at),
|
||||
Update::JobFinished { id, result, at } => state.finish_job(id, result, at),
|
||||
Update::Activity { unit, activity } => state.update_activity(&unit, activity),
|
||||
Update::RootSwitched { at } => state.switch_root(at),
|
||||
Update::Resubscribed => state.forget_jobs(),
|
||||
Update::Ended(error) => return Some(error),
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn draw(
|
||||
terminal: &mut DefaultTerminal,
|
||||
state: &BootState,
|
||||
host: &str,
|
||||
frame: u64,
|
||||
) -> Result<(), Error> {
|
||||
terminal.draw(|canvas| {
|
||||
canvas.render_widget(
|
||||
BootView {
|
||||
state,
|
||||
now: monotonic_now(),
|
||||
host,
|
||||
frame,
|
||||
},
|
||||
canvas.area(),
|
||||
);
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn repaint_fully(terminal: &mut DefaultTerminal) -> Result<(), Error> {
|
||||
terminal.backend_mut().clear_region(ClearType::All)?;
|
||||
terminal.swap_buffers();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn asks_to_quit(event: &Event) -> bool {
|
||||
let Event::Key(KeyEvent {
|
||||
code, modifiers, ..
|
||||
}) = event
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
*code == KeyCode::Char('q')
|
||||
|| (*code == KeyCode::Char('c') && modifiers.contains(KeyModifiers::CONTROL))
|
||||
}
|
||||
|
||||
fn watch(
|
||||
state: &mut BootState,
|
||||
updates: &Receiver<Update>,
|
||||
terminal: &mut DefaultTerminal,
|
||||
terminate: &AtomicBool,
|
||||
hold: Duration,
|
||||
) -> Result<(), Error> {
|
||||
let host = host_name();
|
||||
let mut frame: u64 = 0;
|
||||
loop {
|
||||
if let Some(error) = updates.try_iter().find_map(|update| absorb(state, update)) {
|
||||
return Err(error);
|
||||
}
|
||||
if frame.is_multiple_of(FRAMES_PER_FULL_REPAINT) {
|
||||
repaint_fully(terminal)?;
|
||||
}
|
||||
draw(terminal, state, &host, frame)?;
|
||||
if state.is_complete() {
|
||||
eprintln!(
|
||||
"boot-tree: {} reached, handing the console over",
|
||||
state.root().unwrap_or("boot")
|
||||
);
|
||||
sleep(hold);
|
||||
return Ok(());
|
||||
}
|
||||
if terminate.load(Ordering::Relaxed) {
|
||||
return Ok(());
|
||||
}
|
||||
if event::poll(FRAME_INTERVAL)? && asks_to_quit(&event::read()?) {
|
||||
return Ok(());
|
||||
}
|
||||
frame += 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
use std::{os::fd::OwnedFd, path::Path};
|
||||
|
||||
use rustix::{
|
||||
fs::{Mode, OFlags, open},
|
||||
io::Errno,
|
||||
process::{chdir, chroot, fchdir},
|
||||
};
|
||||
|
||||
const SYSROOT: &str = "/sysroot";
|
||||
const INITRD_RELEASE: &str = "/etc/initrd-release";
|
||||
|
||||
pub fn running_in_initrd() -> bool {
|
||||
Path::new(INITRD_RELEASE).exists()
|
||||
}
|
||||
|
||||
pub struct Sysroot {
|
||||
directory: OwnedFd,
|
||||
}
|
||||
|
||||
impl Sysroot {
|
||||
pub fn hold() -> Result<Self, Errno> {
|
||||
let directory = open(
|
||||
SYSROOT,
|
||||
OFlags::DIRECTORY | OFlags::RDONLY | OFlags::CLOEXEC,
|
||||
Mode::empty(),
|
||||
)?;
|
||||
Ok(Self { directory })
|
||||
}
|
||||
|
||||
pub fn enter(self) -> Result<(), Errno> {
|
||||
fchdir(&self.directory)?;
|
||||
chroot(".")?;
|
||||
chdir("/")
|
||||
}
|
||||
}
|
||||
+282
@@ -0,0 +1,282 @@
|
||||
use std::{iter, time::Duration};
|
||||
|
||||
use dbus::{
|
||||
Message, MessageType, Path,
|
||||
arg::{AppendAll, PropMap, RefArg, Variant},
|
||||
channel::{BusType, Channel},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
error::Error,
|
||||
model::{ActiveState, Activity, JobResult, Micros, UnitFacts},
|
||||
};
|
||||
|
||||
const DESTINATION: &str = "org.freedesktop.systemd1";
|
||||
const MANAGER_PATH: &str = "/org/freedesktop/systemd1";
|
||||
const MANAGER_INTERFACE: &str = "org.freedesktop.systemd1.Manager";
|
||||
const UNIT_INTERFACE: &str = "org.freedesktop.systemd1.Unit";
|
||||
const JOB_INTERFACE: &str = "org.freedesktop.systemd1.Job";
|
||||
const PROPERTIES_INTERFACE: &str = "org.freedesktop.DBus.Properties";
|
||||
const PEER_INTERFACE: &str = "org.freedesktop.DBus.Peer";
|
||||
const BUS_DESTINATION: &str = "org.freedesktop.DBus";
|
||||
const BUS_PATH: &str = "/org/freedesktop/DBus";
|
||||
const PRIVATE_SOCKET: &str = "unix:path=/run/systemd/private";
|
||||
const SIGNAL_RULE: &str = "type='signal',path_namespace='/org/freedesktop/systemd1'";
|
||||
const CALL_TIMEOUT: Duration = Duration::from_secs(1);
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Scope {
|
||||
System,
|
||||
User,
|
||||
}
|
||||
|
||||
pub enum Signal {
|
||||
JobNew {
|
||||
id: u32,
|
||||
job: Path<'static>,
|
||||
unit: String,
|
||||
},
|
||||
JobRemoved {
|
||||
id: u32,
|
||||
result: JobResult,
|
||||
},
|
||||
UnitChanged {
|
||||
path: Path<'static>,
|
||||
activity: Activity,
|
||||
},
|
||||
}
|
||||
|
||||
pub struct FetchedUnit {
|
||||
pub path: Path<'static>,
|
||||
pub facts: UnitFacts,
|
||||
pub activity: Activity,
|
||||
}
|
||||
|
||||
pub struct JobListing {
|
||||
pub id: u32,
|
||||
pub unit: String,
|
||||
pub kind: String,
|
||||
}
|
||||
|
||||
pub fn brings_unit_up(job_kind: &str) -> bool {
|
||||
job_kind != "stop"
|
||||
}
|
||||
|
||||
type ListedJob = (u32, String, String, String, Path<'static>, Path<'static>);
|
||||
|
||||
impl From<ListedJob> for JobListing {
|
||||
fn from((id, unit, kind, ..): ListedJob) -> Self {
|
||||
Self { id, unit, kind }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Session {
|
||||
channel: Channel,
|
||||
peer_to_peer: bool,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn open(scope: Scope) -> Result<Self, Error> {
|
||||
if scope == Scope::System
|
||||
&& let Ok(channel) = Channel::open_private(PRIVATE_SOCKET)
|
||||
{
|
||||
send_authentication_carrier(&channel)?;
|
||||
return Ok(Self {
|
||||
channel,
|
||||
peer_to_peer: 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,
|
||||
};
|
||||
session.call_at(
|
||||
BUS_DESTINATION,
|
||||
BUS_PATH,
|
||||
BUS_DESTINATION,
|
||||
"AddMatch",
|
||||
(SIGNAL_RULE,),
|
||||
)?;
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
pub fn is_peer_to_peer(&self) -> bool {
|
||||
self.peer_to_peer
|
||||
}
|
||||
|
||||
fn call_at(
|
||||
&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)?)
|
||||
}
|
||||
|
||||
fn call(
|
||||
&self,
|
||||
path: &str,
|
||||
interface: &str,
|
||||
member: &str,
|
||||
arguments: impl AppendAll,
|
||||
) -> Result<Message, Error> {
|
||||
self.call_at(DESTINATION, path, interface, member, arguments)
|
||||
}
|
||||
|
||||
fn call_manager(&self, member: &str) -> Result<Message, Error> {
|
||||
self.call(MANAGER_PATH, MANAGER_INTERFACE, member, ())
|
||||
}
|
||||
|
||||
pub fn subscribe(&self) -> Result<(), Error> {
|
||||
self.call_manager("Subscribe")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn default_target(&self) -> Result<String, Error> {
|
||||
Ok(self.call_manager("GetDefaultTarget")?.read1()?)
|
||||
}
|
||||
|
||||
pub fn boot_in_progress(&self) -> Result<bool, Error> {
|
||||
let reply = self.call(
|
||||
MANAGER_PATH,
|
||||
PROPERTIES_INTERFACE,
|
||||
"Get",
|
||||
(MANAGER_INTERFACE, "FinishTimestampMonotonic"),
|
||||
)?;
|
||||
let finished: Variant<u64> = reply.read1()?;
|
||||
Ok(finished.0 == 0)
|
||||
}
|
||||
|
||||
pub fn list_jobs(&self) -> Result<Vec<JobListing>, Error> {
|
||||
let listed: Vec<ListedJob> = self.call_manager("ListJobs")?.read1()?;
|
||||
Ok(listed.into_iter().map(JobListing::from).collect())
|
||||
}
|
||||
|
||||
pub fn job_kind(&self, job: &Path) -> Result<String, Error> {
|
||||
let reply = self.call(job, PROPERTIES_INTERFACE, "Get", (JOB_INTERFACE, "JobType"))?;
|
||||
let kind: Variant<String> = reply.read1()?;
|
||||
Ok(kind.0)
|
||||
}
|
||||
|
||||
pub fn fetch_unit(&self, name: &str) -> Result<FetchedUnit, Error> {
|
||||
let path: Path<'static> = self
|
||||
.call(MANAGER_PATH, MANAGER_INTERFACE, "GetUnit", (name,))?
|
||||
.read1()?;
|
||||
let properties: PropMap = self
|
||||
.call(&path, PROPERTIES_INTERFACE, "GetAll", (UNIT_INTERFACE,))?
|
||||
.read1()?;
|
||||
Ok(FetchedUnit {
|
||||
path,
|
||||
facts: UnitFacts {
|
||||
name: text_property(&properties, "Id").unwrap_or_else(|| name.to_owned()),
|
||||
description: text_property(&properties, "Description").unwrap_or_default(),
|
||||
after: list_property(&properties, "After"),
|
||||
},
|
||||
activity: activity_from(&properties),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn receive(&self, timeout: Duration) -> Result<Vec<Signal>, Error> {
|
||||
let queued = self.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);
|
||||
}
|
||||
Ok(self.drain())
|
||||
}
|
||||
|
||||
fn drain(&self) -> Vec<Signal> {
|
||||
iter::from_fn(|| self.channel.pop_message())
|
||||
.filter_map(|message| parse_signal(&message))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn send_authentication_carrier(channel: &Channel) -> Result<(), Error> {
|
||||
let Ok(mut ping) = Message::new_method_call(DESTINATION, MANAGER_PATH, PEER_INTERFACE, "Ping")
|
||||
else {
|
||||
return Err(Error::MalformedCall);
|
||||
};
|
||||
ping.set_no_reply(true);
|
||||
if channel.send(ping).is_err() {
|
||||
return Err(Error::Disconnected);
|
||||
}
|
||||
channel.flush();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_signal(message: &Message) -> Option<Signal> {
|
||||
if message.msg_type() != MessageType::Signal {
|
||||
return None;
|
||||
}
|
||||
let interface = message.interface()?;
|
||||
let member = message.member()?;
|
||||
match (&*interface, &*member) {
|
||||
(MANAGER_INTERFACE, "JobNew") => {
|
||||
let (id, job, unit): (u32, Path<'static>, String) = message.read3().ok()?;
|
||||
Some(Signal::JobNew { id, job, unit })
|
||||
}
|
||||
(MANAGER_INTERFACE, "JobRemoved") => {
|
||||
let (id, _job, _unit, result): (u32, Path<'static>, String, String) =
|
||||
message.read4().ok()?;
|
||||
Some(Signal::JobRemoved {
|
||||
id,
|
||||
result: JobResult::parse(&result),
|
||||
})
|
||||
}
|
||||
(PROPERTIES_INTERFACE, "PropertiesChanged") => {
|
||||
let (changed_interface, changed, _invalidated): (String, PropMap, Vec<String>) =
|
||||
message.read3().ok()?;
|
||||
if changed_interface != UNIT_INTERFACE {
|
||||
return None;
|
||||
}
|
||||
Some(Signal::UnitChanged {
|
||||
path: message.path()?.into_static(),
|
||||
activity: activity_from(&changed),
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn text_property(properties: &PropMap, name: &str) -> Option<String> {
|
||||
properties.get(name)?.0.as_str().map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
fn list_property(properties: &PropMap, name: &str) -> Vec<String> {
|
||||
let Some(items) = properties.get(name).and_then(|value| value.0.as_iter()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
items
|
||||
.filter_map(|item| item.as_str())
|
||||
.map(ToOwned::to_owned)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn timestamp_property(properties: &PropMap, name: &str) -> Option<Micros> {
|
||||
properties
|
||||
.get(name)?
|
||||
.0
|
||||
.as_u64()
|
||||
.and_then(Activity::timestamp)
|
||||
}
|
||||
|
||||
fn activity_from(properties: &PropMap) -> Activity {
|
||||
Activity {
|
||||
state: text_property(properties, "ActiveState").map(|raw| ActiveState::parse(&raw)),
|
||||
inactive_exit: timestamp_property(properties, "InactiveExitTimestampMonotonic"),
|
||||
active_enter: timestamp_property(properties, "ActiveEnterTimestampMonotonic"),
|
||||
}
|
||||
}
|
||||
+577
@@ -0,0 +1,577 @@
|
||||
use std::iter::repeat_n;
|
||||
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
layout::Rect,
|
||||
style::{Color, Modifier, Style},
|
||||
widgets::Widget,
|
||||
};
|
||||
|
||||
use crate::model::{BootState, Micros, MilestoneRow, PendingRow, RowStatus, Tally};
|
||||
|
||||
const SPINNER: [char; 4] = ['|', '/', '-', '\\'];
|
||||
const DONE: char = '√';
|
||||
const FAILED: char = '×';
|
||||
const RUNNING_BAR: char = '█';
|
||||
const WAITING_BAR: char = '░';
|
||||
const STILL_GOING: char = '▶';
|
||||
const ELLIPSIS: char = '…';
|
||||
const PHASE_ARROW: char = '→';
|
||||
|
||||
const MIN_BAR_WIDTH: u16 = 12;
|
||||
const DURATION_WIDTH: usize = 7;
|
||||
const MAX_FAILED_ROWS: usize = 3;
|
||||
const AXIS_STEPS_SECONDS: [u64; 12] = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 1800, 3600];
|
||||
const AXIS_LABEL_SPACING: u64 = 8;
|
||||
|
||||
pub struct BootView<'a> {
|
||||
pub state: &'a BootState,
|
||||
pub now: Micros,
|
||||
pub host: &'a str,
|
||||
pub frame: u64,
|
||||
}
|
||||
|
||||
struct Columns {
|
||||
left: u16,
|
||||
bar_x: u16,
|
||||
bar_width: u16,
|
||||
}
|
||||
|
||||
impl Columns {
|
||||
fn for_width(width: u16) -> Self {
|
||||
let left = (width * 11 / 20).clamp(40.min(width), 72);
|
||||
let bar_x = left + 1;
|
||||
let bar_width = width.saturating_sub(bar_x);
|
||||
if bar_width < MIN_BAR_WIDTH {
|
||||
return Self {
|
||||
left: width,
|
||||
bar_x: width,
|
||||
bar_width: 0,
|
||||
};
|
||||
}
|
||||
Self {
|
||||
left,
|
||||
bar_x,
|
||||
bar_width,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct TimeAxis {
|
||||
origin: Micros,
|
||||
end: Micros,
|
||||
step: Micros,
|
||||
width: u16,
|
||||
}
|
||||
|
||||
impl TimeAxis {
|
||||
fn new(origin: Micros, now: Micros, width: u16) -> Self {
|
||||
let span_seconds = now.saturating_sub(origin).div_ceil(1_000_000).max(1);
|
||||
let max_labels = (u64::from(width) / AXIS_LABEL_SPACING).max(1);
|
||||
let step_seconds = AXIS_STEPS_SECONDS
|
||||
.into_iter()
|
||||
.find(|step| span_seconds.div_ceil(*step) <= max_labels)
|
||||
.unwrap_or(*AXIS_STEPS_SECONDS.last().expect("axis steps are not empty"));
|
||||
let end_seconds = span_seconds.div_ceil(step_seconds).max(1) * step_seconds;
|
||||
Self {
|
||||
origin,
|
||||
end: origin + end_seconds * 1_000_000,
|
||||
step: step_seconds * 1_000_000,
|
||||
width,
|
||||
}
|
||||
}
|
||||
|
||||
fn column(&self, at: Micros) -> u16 {
|
||||
let clamped = at.clamp(self.origin, self.end);
|
||||
let fraction = (clamped - self.origin) as f64 / (self.end - self.origin) as f64;
|
||||
((fraction * f64::from(self.width)) as u16).min(self.width.saturating_sub(1))
|
||||
}
|
||||
|
||||
fn ticks(&self) -> impl Iterator<Item = AxisTick> + '_ {
|
||||
(0..)
|
||||
.map(|index| index * self.step)
|
||||
.take_while(|offset| self.origin + offset <= self.end)
|
||||
.map(|offset| AxisTick {
|
||||
column: self.column(self.origin + offset),
|
||||
offset,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct AxisTick {
|
||||
column: u16,
|
||||
offset: Micros,
|
||||
}
|
||||
|
||||
fn format_duration(micros: Micros) -> String {
|
||||
let tenths = micros / 100_000;
|
||||
if tenths < 600 {
|
||||
return format!("{}.{}s", tenths / 10, tenths % 10);
|
||||
}
|
||||
let seconds = micros / 1_000_000;
|
||||
if seconds < 3600 {
|
||||
return format!("{}m{:02}s", seconds / 60, seconds % 60);
|
||||
}
|
||||
format!("{}h{:02}m", seconds / 3600, seconds % 3600 / 60)
|
||||
}
|
||||
|
||||
fn format_axis_label(offset: Micros) -> String {
|
||||
let seconds = offset / 1_000_000;
|
||||
if seconds < 60 || !seconds.is_multiple_of(60) {
|
||||
format!("{seconds}s")
|
||||
} else {
|
||||
format!("{}m", seconds / 60)
|
||||
}
|
||||
}
|
||||
|
||||
fn truncate(text: &str, width: usize) -> String {
|
||||
if text.chars().count() <= width {
|
||||
return text.to_owned();
|
||||
}
|
||||
if width == 0 {
|
||||
return String::new();
|
||||
}
|
||||
let mut kept: String = text.chars().take(width - 1).collect();
|
||||
kept.push(ELLIPSIS);
|
||||
kept
|
||||
}
|
||||
|
||||
fn tree_prefix(row: &PendingRow) -> String {
|
||||
let mut prefix: String = row
|
||||
.is_last_sibling
|
||||
.iter()
|
||||
.skip(1)
|
||||
.take(row.depth.saturating_sub(1))
|
||||
.map(|ancestor_is_last| if *ancestor_is_last { " " } else { "│ " })
|
||||
.collect();
|
||||
if row.depth > 0 {
|
||||
let is_last = row.is_last_sibling.last().copied().unwrap_or(true);
|
||||
prefix.push_str(if is_last { "└─ " } else { "├─ " });
|
||||
}
|
||||
prefix
|
||||
}
|
||||
|
||||
struct Palette;
|
||||
|
||||
impl Palette {
|
||||
fn header() -> Style {
|
||||
Style::new().add_modifier(Modifier::BOLD)
|
||||
}
|
||||
|
||||
fn dim() -> Style {
|
||||
Style::new().fg(Color::DarkGray)
|
||||
}
|
||||
|
||||
fn running() -> Style {
|
||||
Style::new().fg(Color::Yellow)
|
||||
}
|
||||
|
||||
fn waiting() -> Style {
|
||||
Style::new().fg(Color::DarkGray)
|
||||
}
|
||||
|
||||
fn done() -> Style {
|
||||
Style::new().fg(Color::Green)
|
||||
}
|
||||
|
||||
fn failed() -> Style {
|
||||
Style::new().fg(Color::Red).add_modifier(Modifier::BOLD)
|
||||
}
|
||||
|
||||
fn target() -> Style {
|
||||
Style::new().fg(Color::Cyan)
|
||||
}
|
||||
}
|
||||
|
||||
struct Painter<'b> {
|
||||
buf: &'b mut Buffer,
|
||||
area: Rect,
|
||||
}
|
||||
|
||||
impl Painter<'_> {
|
||||
fn text(&mut self, x: u16, y: u16, text: &str, style: Style) {
|
||||
if y >= self.area.height || x >= self.area.width {
|
||||
return;
|
||||
}
|
||||
let room = usize::from(self.area.width - x);
|
||||
self.buf
|
||||
.set_stringn(self.area.x + x, self.area.y + y, text, room, style);
|
||||
}
|
||||
|
||||
fn right_aligned(&mut self, right_edge: u16, y: u16, text: &str, style: Style) {
|
||||
let width = text.chars().count() as u16;
|
||||
self.text(right_edge.saturating_sub(width), y, text, style);
|
||||
}
|
||||
|
||||
fn fill(&mut self, x: u16, y: u16, length: u16, symbol: char, style: Style) {
|
||||
let run: String = repeat_n(symbol, usize::from(length)).collect();
|
||||
self.text(x, y, &run, style);
|
||||
}
|
||||
}
|
||||
|
||||
impl BootView<'_> {
|
||||
fn draw_header(&self, painter: &mut Painter, columns: &Columns, axis: Option<&TimeAxis>) {
|
||||
let title = format!(
|
||||
"boot-tree {} {PHASE_ARROW} {}",
|
||||
self.host,
|
||||
self.state.phase().label()
|
||||
);
|
||||
painter.text(0, 0, &title, Palette::header());
|
||||
let elapsed = format_duration(self.now.saturating_sub(self.state.origin()));
|
||||
painter.right_aligned(columns.left, 0, &elapsed, Palette::header());
|
||||
let Some(axis) = axis else {
|
||||
return;
|
||||
};
|
||||
axis.ticks().for_each(|tick| {
|
||||
let label = format_axis_label(tick.offset);
|
||||
let label_width = label.chars().count() as u16;
|
||||
let x = columns.bar_x + tick.column.min(axis.width.saturating_sub(label_width));
|
||||
painter.text(x, 0, &label, Palette::dim());
|
||||
painter.text(columns.bar_x + tick.column, 1, "|", Palette::dim());
|
||||
});
|
||||
}
|
||||
|
||||
fn draw_pending(
|
||||
&self,
|
||||
painter: &mut Painter,
|
||||
columns: &Columns,
|
||||
axis: Option<&TimeAxis>,
|
||||
y: u16,
|
||||
row: &PendingRow,
|
||||
) {
|
||||
let is_target = row.label.ends_with(".target");
|
||||
let prefix = tree_prefix(row);
|
||||
let marker = match (is_target, row.status) {
|
||||
(true, _) => String::new(),
|
||||
(false, RowStatus::Running) => format!("[{}] ", SPINNER[(self.frame % 4) as usize]),
|
||||
(false, RowStatus::Waiting) => "[ ] ".to_owned(),
|
||||
};
|
||||
let label_style = match (is_target, row.status) {
|
||||
(true, _) => Palette::target(),
|
||||
(false, RowStatus::Running) => Style::new(),
|
||||
(false, RowStatus::Waiting) => Palette::dim(),
|
||||
};
|
||||
let since = row.running_since.unwrap_or(row.queued_at);
|
||||
let duration = format_duration(self.now.saturating_sub(since));
|
||||
let fixed = prefix.chars().count() + marker.chars().count() + DURATION_WIDTH + 1;
|
||||
let label_room = usize::from(columns.left).saturating_sub(fixed);
|
||||
let mut x = 0;
|
||||
painter.text(x, y, &prefix, Palette::dim());
|
||||
x += prefix.chars().count() as u16;
|
||||
let marker_style = if row.status == RowStatus::Running {
|
||||
Palette::running()
|
||||
} else {
|
||||
Palette::dim()
|
||||
};
|
||||
painter.text(x, y, &marker, marker_style);
|
||||
x += marker.chars().count() as u16;
|
||||
painter.text(x, y, &truncate(&row.label, label_room), label_style);
|
||||
painter.right_aligned(columns.left, y, &duration, label_style);
|
||||
let Some(axis) = axis else {
|
||||
return;
|
||||
};
|
||||
let queued = axis.column(row.queued_at);
|
||||
let now = axis.column(self.now);
|
||||
match row.running_since {
|
||||
Some(running_since) => {
|
||||
let started = axis.column(running_since);
|
||||
if started > queued {
|
||||
painter.fill(
|
||||
columns.bar_x + queued,
|
||||
y,
|
||||
started - queued,
|
||||
WAITING_BAR,
|
||||
Palette::waiting(),
|
||||
);
|
||||
}
|
||||
painter.fill(
|
||||
columns.bar_x + started,
|
||||
y,
|
||||
now.saturating_sub(started).max(1),
|
||||
RUNNING_BAR,
|
||||
Palette::running(),
|
||||
);
|
||||
}
|
||||
None => {
|
||||
painter.fill(
|
||||
columns.bar_x + queued,
|
||||
y,
|
||||
now.saturating_sub(queued).max(1),
|
||||
WAITING_BAR,
|
||||
Palette::waiting(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let arrow_x = (now + 1).min(axis.width.saturating_sub(1));
|
||||
painter.text(
|
||||
columns.bar_x + arrow_x,
|
||||
y,
|
||||
&STILL_GOING.to_string(),
|
||||
Palette::dim(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl Painter<'_> {
|
||||
fn milestone(
|
||||
&mut self,
|
||||
columns: &Columns,
|
||||
axis: Option<&TimeAxis>,
|
||||
y: u16,
|
||||
row: &MilestoneRow,
|
||||
) {
|
||||
let units = match row.finished_units {
|
||||
1 => "1 unit".to_owned(),
|
||||
count => format!("{count} units"),
|
||||
};
|
||||
let label = truncate(&row.label, 18);
|
||||
let Some(reached_at) = row.reached_at else {
|
||||
self.text(0, y, &format!(" {label:<18} {units:>10}"), Palette::dim());
|
||||
return;
|
||||
};
|
||||
self.text(
|
||||
0,
|
||||
y,
|
||||
&format!("{DONE} {label:<18} {units:>10}"),
|
||||
Palette::done(),
|
||||
);
|
||||
let duration = format_duration(reached_at.saturating_sub(row.started_at));
|
||||
self.right_aligned(columns.left, y, &duration, Palette::done());
|
||||
if let Some(axis) = axis {
|
||||
let start = axis.column(row.started_at);
|
||||
let end = axis.column(reached_at);
|
||||
self.fill(
|
||||
columns.bar_x + start,
|
||||
y,
|
||||
end.saturating_sub(start).max(1),
|
||||
RUNNING_BAR,
|
||||
Palette::done(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn footer(&mut self, tally: Tally, y: u16) {
|
||||
self.fill(0, y, self.area.width, '─', Palette::dim());
|
||||
let counts = format!(
|
||||
"{DONE} {} done {} running {} waiting {FAILED} {} failed",
|
||||
tally.done, tally.running, tally.waiting, tally.failed
|
||||
);
|
||||
let style = if tally.failed > 0 {
|
||||
Palette::failed()
|
||||
} else {
|
||||
Style::new()
|
||||
};
|
||||
self.text(0, y + 1, &counts, style);
|
||||
let legend = format!("{RUNNING_BAR} running {WAITING_BAR} waiting");
|
||||
let room_left = usize::from(self.area.width).saturating_sub(counts.chars().count());
|
||||
if room_left > legend.chars().count() + 2 {
|
||||
self.right_aligned(self.area.width, y + 1, &legend, Palette::dim());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for BootView<'_> {
|
||||
fn render(self, area: Rect, buf: &mut Buffer) {
|
||||
let mut painter = Painter { buf, area };
|
||||
let columns = Columns::for_width(area.width);
|
||||
let axis = (columns.bar_width > 0)
|
||||
.then(|| TimeAxis::new(self.state.origin(), self.now, columns.bar_width));
|
||||
self.draw_header(&mut painter, &columns, axis.as_ref());
|
||||
|
||||
let milestones = self.state.milestones();
|
||||
let failed = self.state.failed_units();
|
||||
let shown_failed = failed.len().min(MAX_FAILED_ROWS);
|
||||
let failed_lines = shown_failed + usize::from(failed.len() > MAX_FAILED_ROWS);
|
||||
let footer_height = 2;
|
||||
let bottom_height = (milestones.len() + failed_lines + footer_height) as u16;
|
||||
let tree_top = 2;
|
||||
let tree_bottom = area.height.saturating_sub(bottom_height + 1).max(tree_top);
|
||||
|
||||
let rows = self.state.pending_rows();
|
||||
let capacity = usize::from(tree_bottom - tree_top);
|
||||
let overflow = rows.len() > capacity;
|
||||
let visible = if overflow {
|
||||
capacity.saturating_sub(1)
|
||||
} else {
|
||||
rows.len()
|
||||
};
|
||||
rows.iter()
|
||||
.take(visible)
|
||||
.zip(tree_top..)
|
||||
.for_each(|(row, y)| self.draw_pending(&mut painter, &columns, axis.as_ref(), y, row));
|
||||
if overflow {
|
||||
let hidden = rows.len() - visible;
|
||||
painter.text(
|
||||
0,
|
||||
tree_top + visible as u16,
|
||||
&format!("{ELLIPSIS} {hidden} more"),
|
||||
Palette::dim(),
|
||||
);
|
||||
}
|
||||
|
||||
let milestones_top = area.height.saturating_sub(bottom_height);
|
||||
milestones
|
||||
.iter()
|
||||
.zip(milestones_top..)
|
||||
.for_each(|(milestone, y)| painter.milestone(&columns, axis.as_ref(), y, milestone));
|
||||
let failed_top = milestones_top + milestones.len() as u16;
|
||||
let hidden_failures = failed.len().saturating_sub(MAX_FAILED_ROWS);
|
||||
failed
|
||||
.iter()
|
||||
.take(shown_failed)
|
||||
.map(|unit| format!("{FAILED} {unit} failed"))
|
||||
.chain((hidden_failures > 0).then(|| format!("{FAILED} {hidden_failures} more failed")))
|
||||
.zip(failed_top..)
|
||||
.for_each(|(line, y)| painter.text(0, y, &line, Palette::failed()));
|
||||
painter.footer(self.state.tally(), failed_top + failed_lines as u16);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use ratatui::{Terminal, backend::TestBackend};
|
||||
|
||||
use super::*;
|
||||
use crate::model::{ActiveState, Activity, JobResult, Phase, UnitFacts};
|
||||
|
||||
fn facts(name: &str, after: &[&str]) -> UnitFacts {
|
||||
UnitFacts {
|
||||
name: name.to_owned(),
|
||||
description: String::new(),
|
||||
after: after.iter().map(ToString::to_string).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn render(state: &BootState, now: Micros, width: u16, height: u16) -> Vec<String> {
|
||||
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("test backend");
|
||||
terminal
|
||||
.draw(|frame| {
|
||||
frame.render_widget(
|
||||
BootView {
|
||||
state,
|
||||
now,
|
||||
host: "ryzen",
|
||||
frame: 1,
|
||||
},
|
||||
frame.area(),
|
||||
);
|
||||
})
|
||||
.expect("draw");
|
||||
let buffer = terminal.backend().buffer().clone();
|
||||
(0..height)
|
||||
.map(|y| {
|
||||
let line: String = (0..width)
|
||||
.map(|x| buffer[(x, y)].symbol().to_owned())
|
||||
.collect();
|
||||
line.trim_end().to_owned()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn boot_in_progress() -> BootState {
|
||||
let mut state = BootState::new(Phase::Host);
|
||||
state.set_root("graphical.target".to_owned());
|
||||
state.track_unit(
|
||||
facts("graphical.target", &["multi-user.target"]),
|
||||
Activity::default(),
|
||||
);
|
||||
state.track_unit(
|
||||
facts(
|
||||
"multi-user.target",
|
||||
&["docker.service", "systemd-rfkill.service"],
|
||||
),
|
||||
Activity::default(),
|
||||
);
|
||||
state.track_unit(
|
||||
facts("docker.service", &[]),
|
||||
Activity {
|
||||
state: Some(ActiveState::Activating),
|
||||
inactive_exit: Some(9_000_000),
|
||||
active_enter: None,
|
||||
},
|
||||
);
|
||||
state.track_unit(
|
||||
facts("systemd-rfkill.service", &[]),
|
||||
Activity {
|
||||
state: Some(ActiveState::Activating),
|
||||
inactive_exit: Some(6_000_000),
|
||||
active_enter: None,
|
||||
},
|
||||
);
|
||||
state.track_unit(facts("sysinit.target", &[]), Activity::default());
|
||||
state.track_unit(facts("nvidia-powerd.service", &[]), Activity::default());
|
||||
[
|
||||
"graphical.target",
|
||||
"multi-user.target",
|
||||
"docker.service",
|
||||
"systemd-rfkill.service",
|
||||
"sysinit.target",
|
||||
"nvidia-powerd.service",
|
||||
]
|
||||
.into_iter()
|
||||
.zip(1..)
|
||||
.for_each(|(unit, id)| state.queue_job(id, unit, 1_000_000));
|
||||
state.finish_job(5, JobResult::Done, 4_000_000);
|
||||
state.finish_job(6, JobResult::Failed, 5_000_000);
|
||||
state
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_tree_bars_milestones_and_footer() {
|
||||
let lines = render(&boot_in_progress(), 12_400_000, 110, 14);
|
||||
let screen = lines.join("\n");
|
||||
assert!(
|
||||
lines[0].starts_with("boot-tree ryzen → stage 2"),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(lines[0].contains("12.4s"), "{screen}");
|
||||
assert!(lines[2].starts_with("graphical.target"), "{screen}");
|
||||
assert!(lines[3].starts_with("└─ multi-user.target"), "{screen}");
|
||||
assert!(lines[4].starts_with(" ├─ [/] systemd-rfkill"), "{screen}");
|
||||
assert!(lines[5].starts_with(" └─ [/] docker"), "{screen}");
|
||||
assert!(lines[4].contains('█') && lines[4].contains('▶'), "{screen}");
|
||||
assert!(screen.contains("√ sysinit.target"), "{screen}");
|
||||
assert!(
|
||||
screen.contains("× nvidia-powerd.service failed"),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(
|
||||
screen.contains("√ 1 done 2 running 2 waiting × 1 failed"),
|
||||
"{screen}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_screens_drop_the_timeline() {
|
||||
let lines = render(&boot_in_progress(), 12_400_000, 50, 14);
|
||||
assert!(
|
||||
lines.iter().all(|line| !line.contains('█')),
|
||||
"{}",
|
||||
lines.join("\n")
|
||||
);
|
||||
assert!(lines[4].contains("systemd-rfkill"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overflowing_trees_are_cut_with_a_count() {
|
||||
let mut state = BootState::new(Phase::Host);
|
||||
(0..30).for_each(|id| {
|
||||
let name = format!("unit{id:02}.service");
|
||||
state.track_unit(facts(&name, &[]), Activity::default());
|
||||
state.queue_job(id, &name, 0);
|
||||
});
|
||||
let lines = render(&state, 1_000_000, 110, 12);
|
||||
assert!(
|
||||
lines.iter().any(|line| line.starts_with("… ")),
|
||||
"{}",
|
||||
lines.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn durations_switch_units_past_a_minute() {
|
||||
assert_eq!(format_duration(12_400_000), "12.4s");
|
||||
assert_eq!(format_duration(65_000_000), "1m05s");
|
||||
assert_eq!(format_duration(3_720_000_000), "1h02m");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user