boot-tree: single-threaded feed, Duration timestamps, fields over getters, jiff formatting

This commit is contained in:
Willem Vanhulle committed 2026-10-11 15:54:28 +02:00
1 parent 63743d8807
commit 2b1447965a
11 files changed
+714 -757

No files matched your search

Generated
+78
View File
@@ -146,6 +146,7 @@ dependencies = [
"clap",
"crossterm",
"dbus",
"jiff",
"ratatui",
"rustix",
"signal-hook 0.4.5",
@@ -376,6 +377,37 @@ dependencies = [
"windows-sys",
]
[[package]]
name = "defmt"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1"
dependencies = [
"bitflags 1.3.2",
"defmt-macros",
]
[[package]]
name = "defmt-macros"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8"
dependencies = [
"defmt-parser",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "defmt-parser"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "deltae"
version = "0.3.2"
@@ -651,6 +683,43 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "jiff"
version = "0.2.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383"
dependencies = [
"defmt",
"jiff-core",
"jiff-static",
"log",
"portable-atomic",
"portable-atomic-util",
"serde_core",
]
[[package]]
name = "jiff-core"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c"
dependencies = [
"defmt",
"log",
]
[[package]]
name = "jiff-static"
version = "0.2.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c"
dependencies = [
"jiff-core",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "js-sys"
version = "0.3.106"
@@ -1061,6 +1130,15 @@ version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
[[package]]
name = "portable-atomic-util"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"
dependencies = [
"portable-atomic",
]
[[package]]
name = "powerfmt"
version = "0.2.1"
+1 -3
View File
@@ -6,15 +6,13 @@ version = "0.1.0"
[lints.clippy]
absolute_paths = "warn"
pedantic = { priority = -1, level = "warn" }
cast_possible_truncation = "allow"
cast_precision_loss = "allow"
cast_sign_loss = "allow"
needless_for_each = "allow"
[dependencies]
clap = { version = "4.5", features = ["derive"] }
crossterm = "0.29"
dbus = "0.9"
jiff = { version = "0.2", default-features = false, features = ["std"] }
ratatui = "0.30"
rustix = { version = "1", features = ["fs", "process", "stdio", "system", "termios", "time"] }
signal-hook = "0.4"
+81 -41
View File
@@ -5,7 +5,7 @@ use std::{
};
use boot_tree::{
model::{ActiveState, Activity, BootState, JobResult, Micros, Phase, UnitFacts},
model::{ActiveState, Activity, BootState, JobResult, Phase, UnitFacts},
view::BootView,
};
use ratatui::{
@@ -19,24 +19,24 @@ const FINAL_FRAME: Duration = Duration::from_secs(3);
struct Step {
unit: &'static str,
after: &'static [&'static str],
work_ms: u64,
work: Duration,
fails: bool,
}
const fn step(unit: &'static str, after: &'static [&'static str], work_ms: u64) -> Step {
const fn step(unit: &'static str, after: &'static [&'static str], work: Duration) -> Step {
Step {
unit,
after,
work_ms,
work,
fails: false,
}
}
const fn failing(unit: &'static str, after: &'static [&'static str], work_ms: u64) -> Step {
const fn failing(unit: &'static str, after: &'static [&'static str], work: Duration) -> Step {
Step {
unit,
after,
work_ms,
work,
fails: true,
}
}
@@ -45,32 +45,48 @@ const INITRD: &[Step] = &[
step(
"initrd.target",
&["initrd-fs.target", "initrd-root-device.target"],
0,
Duration::ZERO,
),
step("initrd-fs.target", &["sysroot.mount"], 0),
step("initrd-fs.target", &["sysroot.mount"], Duration::ZERO),
step(
"initrd-root-device.target",
&["dev-disk-by\\x2dlabel-nixos.device"],
0,
Duration::ZERO,
),
step(
"sysroot.mount",
&["systemd-fsck-root.service"],
Duration::from_millis(300),
),
step("sysroot.mount", &["systemd-fsck-root.service"], 300),
step(
"systemd-fsck-root.service",
&["dev-disk-by\\x2dlabel-nixos.device"],
500,
Duration::from_millis(500),
),
step(
"dev-disk-by\\x2dlabel-nixos.device",
&[],
Duration::from_millis(1200),
),
step("systemd-udevd.service", &[], Duration::from_millis(400)),
step(
"demo-initrd-probe.service",
&[],
Duration::from_millis(2500),
),
step("dev-disk-by\\x2dlabel-nixos.device", &[], 1200),
step("systemd-udevd.service", &[], 400),
step("demo-initrd-probe.service", &[], 2500),
];
const HOST: &[Step] = &[
step(
"graphical.target",
&["multi-user.target", "display-manager.service"],
0,
Duration::ZERO,
),
step(
"display-manager.service",
&["multi-user.target"],
Duration::from_millis(400),
),
step("display-manager.service", &["multi-user.target"], 400),
step(
"multi-user.target",
&[
@@ -81,43 +97,71 @@ const HOST: &[Step] = &[
"nvidia-powerd.service",
"systemd-rfkill.service",
],
0,
Duration::ZERO,
),
step("basic.target", &["sysinit.target"], 0),
step("basic.target", &["sysinit.target"], Duration::ZERO),
step(
"sysinit.target",
&[
"systemd-tmpfiles-setup.service",
"systemd-udev-trigger.service",
],
0,
Duration::ZERO,
),
step(
"systemd-tmpfiles-setup.service",
&[],
Duration::from_millis(600),
),
step(
"systemd-udev-trigger.service",
&[],
Duration::from_millis(900),
),
step(
"NetworkManager.service",
&["basic.target"],
Duration::from_millis(1500),
),
step("systemd-tmpfiles-setup.service", &[], 600),
step("systemd-udev-trigger.service", &[], 900),
step("NetworkManager.service", &["basic.target"], 1500),
step(
"NetworkManager-wait-online.service",
&["NetworkManager.service"],
3500,
Duration::from_millis(3500),
),
step(
"network-online.target",
&["NetworkManager-wait-online.service"],
0,
Duration::ZERO,
),
step(
"tailscaled.service",
&["network-online.target"],
Duration::from_millis(1200),
),
step(
"containerd.service",
&["basic.target"],
Duration::from_millis(800),
),
step("tailscaled.service", &["network-online.target"], 1200),
step("containerd.service", &["basic.target"], 800),
step(
"docker.service",
&["containerd.service", "network-online.target"],
1500,
Duration::from_millis(1500),
),
failing(
"nvidia-powerd.service",
&["basic.target"],
Duration::from_millis(700),
),
step(
"sys-devices-virtual-misc-rfkill.device",
&[],
Duration::from_millis(4000),
),
failing("nvidia-powerd.service", &["basic.target"], 700),
step("sys-devices-virtual-misc-rfkill.device", &[], 4000),
step(
"systemd-rfkill.service",
&["sys-devices-virtual-misc-rfkill.device"],
300,
Duration::from_millis(300),
),
];
@@ -154,12 +198,12 @@ impl ScriptedJob {
struct Script {
jobs: Vec<ScriptedJob>,
started: HashMap<&'static str, Micros>,
started: HashMap<&'static str, Duration>,
finished: HashSet<&'static str>,
}
impl Script {
fn begin(steps: &'static [Step], first_job: u32, state: &mut BootState, now: Micros) -> Self {
fn begin(steps: &'static [Step], first_job: u32, state: &mut BootState, now: Duration) -> Self {
let jobs: Vec<ScriptedJob> = steps
.iter()
.zip(first_job..)
@@ -177,10 +221,6 @@ impl Script {
}
}
fn is_finished(&self) -> bool {
self.finished.len() == self.jobs.len()
}
fn is_ready(&self, job: &ScriptedJob) -> bool {
!self.started.contains_key(job.step.unit)
&& job
@@ -190,15 +230,15 @@ impl Script {
.all(|dependency| self.finished.contains(dependency))
}
fn is_due(&self, job: &ScriptedJob, now: Micros) -> bool {
fn is_due(&self, job: &ScriptedJob, now: Duration) -> bool {
!self.finished.contains(job.step.unit)
&& self
.started
.get(job.step.unit)
.is_some_and(|started| now >= started + job.step.work_ms * 1_000)
.is_some_and(|started| now >= *started + job.step.work)
}
fn advance(&mut self, state: &mut BootState, now: Micros) {
fn advance(&mut self, state: &mut BootState, now: Duration) {
let starting: Vec<&'static str> = self
.jobs
.iter()
@@ -251,14 +291,14 @@ fn wants_to_quit() -> io::Result<bool> {
fn play(terminal: &mut DefaultTerminal) -> io::Result<()> {
let clock = Instant::now();
let now = || clock.elapsed().as_micros() as Micros;
let now = || clock.elapsed();
let mut state = BootState::new(Phase::Initrd);
let mut script = Script::begin(INITRD, 1, &mut state, now());
let mut frame = 0;
let mut completed_at = None;
loop {
script.advance(&mut state, now());
if state.phase() == Phase::Initrd && script.is_finished() {
if state.phase == Phase::Initrd && script.finished.len() == script.jobs.len() {
state.switch_root(now());
script = Script::begin(HOST, 1000, &mut state, now());
}
+8 -11
View File
@@ -1,14 +1,11 @@
use boot_tree::model::Micros;
use rustix::{
system::uname,
time::{ClockId, clock_gettime},
};
use std::time::Duration;
pub fn monotonic_now() -> Micros {
use rustix::time::{ClockId, clock_gettime};
pub fn monotonic_now() -> Duration {
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()
Duration::new(
now.tv_sec.cast_unsigned(),
u32::try_from(now.tv_nsec).unwrap_or_default(),
)
}
+17 -20
View File
@@ -23,34 +23,31 @@ pub struct ForegroundVt {
impl ForegroundVt {
pub fn take() -> Option<Self> {
let own = own_vt_number()?;
let previous = active_vt().ok()?;
if previous != own {
let name = ttyname(stdin(), Vec::new()).ok()?;
let own: u16 = name
.to_str()
.ok()?
.strip_prefix(VIRTUAL_TERMINAL_PREFIX)?
.parse()
.ok()
.filter(|number| *number > 0)?;
let state: VtState =
unsafe { ioctl(stdin(), Getter::<VT_GETSTATE, VtState>::new()) }.ok()?;
if state.active != own {
activate(own).ok()?;
}
Some(Self { previous })
Some(Self {
previous: state.active,
})
}
}
pub fn give_back(self) {
impl Drop for ForegroundVt {
fn drop(&mut 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)) }?;
+85 -161
View File
@@ -1,168 +1,134 @@
use std::{
collections::HashMap,
path::Path as FilePath,
process,
sync::mpsc::Sender,
thread::{self, JoinHandle},
thread::sleep,
time::{Duration, Instant},
};
use boot_tree::model::{Activity, HANDOFF_UNIT, HOST_MILESTONES, JobResult, Micros, UnitFacts};
use boot_tree::model::{BootState, HANDOFF_UNIT, HOST_MILESTONES};
use dbus::Path;
use crate::{
clock::monotonic_now,
error::Error,
sysroot::{Sysroot, running_in_initrd},
systemd::{Scope, Session, Signal, brings_unit_up},
sysroot::{INITRD_RELEASE, Sysroot},
systemd::{Scope, Session, Signal},
};
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>,
pub struct Feed {
scope: Scope,
target: Option<String>,
session: Option<Session>,
unit_paths: HashMap<Path<'static>, String>,
in_initrd: bool,
sysroot: Option<Sysroot>,
gave_origin: bool,
reconnect_deadline: Instant,
}
impl Feed {
fn new(options: FeedOptions, sender: Sender<Update>) -> Self {
pub fn new(scope: Scope, target: Option<String>) -> Self {
Self {
in_initrd: options.scope == Scope::System && running_in_initrd(),
options,
sender,
in_initrd: scope == Scope::System && FilePath::new(INITRD_RELEASE).exists(),
scope,
target,
session: None,
unit_paths: HashMap::new(),
sysroot: None,
gave_origin: false,
reconnect_deadline: Instant::now() + RECONNECT_PATIENCE,
}
}
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,
pub fn pump(&mut self, state: &mut BootState, wait: Duration) -> Result<(), Error> {
let Some(session) = self.session.take() else {
return self.connect_or_wait(state, wait);
};
loop {
match session.receive(RECEIVE_TIMEOUT) {
Ok(signals) => signals
match session.receive(wait) {
Ok(signals) => {
signals
.into_iter()
.for_each(|signal| self.apply(&session, signal)),
Err(_) => match self.reconnect() {
Ok(reconnected) => session = reconnected,
Err(error) => return error,
},
.for_each(|signal| self.apply(&session, state, signal));
self.session = Some(session);
}
Err(_) => self.lose_connection(state)?,
}
Ok(())
}
fn connect_or_wait(&mut self, state: &mut BootState, wait: Duration) -> Result<(), Error> {
match self.connect(state) {
Ok(session) => {
self.session = Some(session);
Ok(())
}
Err(_) if Instant::now() < self.reconnect_deadline => {
sleep(wait);
Ok(())
}
Err(_) => Err(Error::ManagerUnreachable),
}
}
fn connect(&mut self, origin: OriginChoice) -> Result<Session, Error> {
let session = Session::open(self.options.scope)?;
fn lose_connection(&mut self, state: &mut BootState) -> Result<(), Error> {
match self.sysroot.take() {
Some(sysroot) => {
sysroot.enter()?;
self.in_initrd = false;
self.unit_paths.clear();
state.switch_root(monotonic_now());
}
None => state.forget_jobs(),
}
self.reconnect_deadline = Instant::now() + RECONNECT_PATIENCE;
Ok(())
}
fn connect(&mut self, state: &mut BootState) -> Result<Session, Error> {
let session = Session::open(self.scope)?;
session.subscribe()?;
let requested_root = match &self.options.target {
let requested_root = match &self.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
if !self.gave_origin {
state.origin = if session.boot_in_progress()? {
Duration::ZERO
} else {
monotonic_now()
}));
};
self.gave_origin = true;
}
let root = self
.track(&session, &requested_root)
.track(&session, state, &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));
if let Some(handoff) = self.track(&session, state, HANDOFF_UNIT) {
state.set_handoff(handoff);
}
let jobs: Vec<_> = session
.list_jobs()?
.into_iter()
.filter(|job| brings_unit_up(&job.kind))
.filter(|job| job.brings_unit_up)
.collect();
jobs.iter()
.map(|job| job.unit.as_str())
.chain(HOST_MILESTONES)
.for_each(|unit| {
self.track(&session, unit);
self.track(&session, state, unit);
});
state.set_root(root.clone());
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,
});
});
jobs.iter()
.for_each(|job| state.queue_job(job.id, &job.unit, now));
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() {
if session.peer_to_peer {
"the private socket"
} else {
"the bus"
@@ -171,33 +137,7 @@ impl Feed {
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> {
fn track(&mut self, session: &Session, state: &mut BootState, unit: &str) -> Option<String> {
if let Some(known) = self.unit_paths.values().find(|known| *known == unit) {
return Some(known.clone());
}
@@ -207,46 +147,30 @@ impl Feed {
return Some(canonical);
}
self.unit_paths.insert(fetched.path, canonical.clone());
self.send(Update::Unit {
facts: fetched.facts,
activity: fetched.activity,
});
state.track_unit(fetched.facts, fetched.activity);
Some(canonical)
}
fn apply(&mut self, session: &Session, signal: Signal) {
fn apply(&mut self, session: &Session, state: &mut BootState, 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)) {
let brings_unit_up = session.job_brings_unit_up(&job);
if brings_unit_up.as_ref().is_ok_and(|up| !up) {
return;
}
let unit = self.track(session, &unit).unwrap_or(unit);
let unit = self.track(session, state, &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
},
});
match brings_unit_up {
Ok(_) => state.queue_job(id, &unit, monotonic_now()),
Err(_) => state.queue_job_of_unknown_kind(id, &unit, monotonic_now()),
}
}
Signal::JobRemoved { id, result } => self.send(Update::JobFinished {
id,
result,
at: monotonic_now(),
}),
Signal::JobRemoved { id, result } => state.finish_job(id, result, monotonic_now()),
Signal::UnitChanged { path, activity } => {
if let Some(unit) = self.unit_paths.get(&path) {
self.send(Update::Activity {
unit: unit.clone(),
activity,
});
state.update_activity(unit, activity);
}
}
}
+182 -219
View File
@@ -1,6 +1,7 @@
use std::collections::{HashMap, HashSet};
pub type Micros = u64;
use std::{
collections::{HashMap, HashSet},
time::Duration,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Phase {
@@ -10,6 +11,7 @@ pub enum Phase {
}
impl Phase {
#[must_use]
pub fn label(self) -> &'static str {
match self {
Self::Initrd => "initrd",
@@ -30,6 +32,7 @@ pub enum ActiveState {
}
impl ActiveState {
#[must_use]
pub fn parse(raw: &str) -> Self {
match raw {
"activating" => Self::Activating,
@@ -40,13 +43,6 @@ impl ActiveState {
_ => Self::Inactive,
}
}
fn is_transitioning(self) -> bool {
matches!(
self,
Self::Activating | Self::Deactivating | Self::Reloading
)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -60,6 +56,7 @@ pub enum JobResult {
}
impl JobResult {
#[must_use]
pub fn parse(raw: &str) -> Self {
match raw {
"done" => Self::Done,
@@ -70,10 +67,6 @@ impl JobResult {
_ => Self::Failed,
}
}
pub fn is_failure(self) -> bool {
matches!(self, Self::Failed | Self::Timeout | Self::Dependency)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -86,34 +79,29 @@ pub struct UnitFacts {
#[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)
}
pub inactive_exit: Option<Duration>,
pub active_enter: Option<Duration>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct PendingJob {
id: u32,
queued_at: Micros,
queued_at: Duration,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Outcome {
result: JobResult,
at: Micros,
enum Outcome {
Succeeded { at: Duration },
Failed,
Abandoned,
}
#[derive(Clone, Debug)]
struct UnitRecord {
facts: UnitFacts,
state: ActiveState,
inactive_exit: Option<Micros>,
active_enter: Option<Micros>,
inactive_exit: Option<Duration>,
active_enter: Option<Duration>,
job: Option<PendingJob>,
outcome: Option<Outcome>,
}
@@ -131,12 +119,13 @@ impl UnitRecord {
}
}
fn running_since(&self) -> Option<Micros> {
fn running_since(&self) -> Option<Duration> {
let job = self.job?;
if !self.state.is_transitioning() {
return None;
}
Some(self.inactive_exit.unwrap_or(job.queued_at))
let transitioning = matches!(
self.state,
ActiveState::Activating | ActiveState::Deactivating | ActiveState::Reloading
);
transitioning.then(|| self.inactive_exit.unwrap_or(job.queued_at))
}
}
@@ -151,17 +140,18 @@ pub struct PendingRow {
pub depth: usize,
pub is_last_sibling: Vec<bool>,
pub label: String,
pub is_target: bool,
pub status: RowStatus,
pub queued_at: Micros,
pub running_since: Option<Micros>,
pub queued_at: Duration,
pub running_since: Option<Duration>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MilestoneRow {
pub label: String,
pub finished_units: usize,
pub started_at: Micros,
pub reached_at: Option<Micros>,
pub started_at: Duration,
pub reached_at: Option<Duration>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -172,25 +162,25 @@ pub struct Tally {
pub failed: usize,
}
#[derive(Clone, Debug)]
struct FrozenMilestone {
label: String,
finished_units: usize,
started_at: Micros,
reached_at: Micros,
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FinishedStage {
pub label: &'static str,
pub finished_units: usize,
pub started_at: Duration,
pub reached_at: Duration,
}
#[derive(Clone, Debug)]
pub struct BootState {
phase: Phase,
origin: Micros,
root: Option<String>,
pub phase: Phase,
pub origin: Duration,
pub root: Option<String>,
pub failed: Vec<String>,
pub finished_stages: Vec<FinishedStage>,
root_job_seen: bool,
handoff_unit: Option<String>,
milestone_targets: Vec<String>,
frozen: Vec<FrozenMilestone>,
failed: Vec<String>,
finished_before_switch: usize,
finished_before_reconnect: usize,
units: HashMap<String, UnitRecord>,
jobs: HashMap<u32, String>,
}
@@ -205,6 +195,7 @@ pub const HOST_MILESTONES: [&str; 4] = [
pub const HANDOFF_UNIT: &str = "display-manager.service";
impl BootState {
#[must_use]
pub fn new(phase: Phase) -> Self {
let (milestone_targets, handoff_unit) = match phase {
Phase::Initrd | Phase::Host => (
@@ -215,35 +206,19 @@ impl BootState {
};
Self {
phase,
origin: 0,
origin: Duration::ZERO,
root: None,
failed: Vec::new(),
finished_stages: Vec::new(),
root_job_seen: false,
handoff_unit,
milestone_targets,
frozen: Vec::new(),
failed: Vec::new(),
finished_before_switch: 0,
finished_before_reconnect: 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;
@@ -260,10 +235,6 @@ impl BootState {
}
}
pub fn failed_units(&self) -> &[String] {
&self.failed
}
pub fn track_unit(&mut self, facts: UnitFacts, activity: Activity) {
let record = self
.units
@@ -286,7 +257,7 @@ impl BootState {
}
}
pub fn queue_job(&mut self, id: u32, unit: &str, at: Micros) {
pub fn queue_job(&mut self, id: u32, unit: &str, at: Duration) {
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)
@@ -295,7 +266,7 @@ impl BootState {
}
}
pub fn queue_job_of_unknown_kind(&mut self, id: u32, unit: &str, at: Micros) {
pub fn queue_job_of_unknown_kind(&mut self, id: u32, unit: &str, at: Duration) {
if self.jobs.contains_key(&id) {
return;
}
@@ -307,7 +278,7 @@ impl BootState {
self.jobs.insert(id, unit.to_owned());
}
pub fn finish_job(&mut self, id: u32, result: JobResult, at: Micros) {
pub fn finish_job(&mut self, id: u32, result: JobResult, at: Duration) {
let Some(unit) = self.jobs.remove(&id) else {
return;
};
@@ -317,31 +288,43 @@ impl BootState {
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) {
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);
if outcome == Outcome::Failed && !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,
pub fn switch_root(&mut self, at: Duration) {
let finished_here = self
.units
.values()
.filter(|record| record.outcome.is_some())
.count();
self.finished_stages.push(FinishedStage {
label: Phase::Initrd.label(),
finished_units: finished_here + self.finished_before_reconnect,
started_at: self.origin,
reached_at: at,
});
self.phase = Phase::Host;
self.root = None;
self.root_job_seen = false;
self.finished_before_switch = 0;
self.finished_before_reconnect = 0;
self.units.clear();
self.jobs.clear();
}
pub fn forget_jobs(&mut self) {
self.finished_before_switch += self.finished_units();
self.finished_before_reconnect += self
.units
.values()
.filter(|record| record.outcome.is_some())
.count();
self.jobs.clear();
self.units.values_mut().for_each(|record| {
record.job = None;
@@ -349,13 +332,7 @@ impl BootState {
});
}
fn finished_units(&self) -> usize {
self.units
.values()
.filter(|record| record.outcome.is_some())
.count()
}
#[must_use]
pub fn is_complete(&self) -> bool {
if self.phase == Phase::Initrd {
return false;
@@ -375,39 +352,36 @@ impl BootState {
self.root_job_seen && root.job.is_none()
}
#[must_use]
pub fn tally(&self) -> Tally {
let carried = Tally {
done: self
.frozen
.finished_stages
.iter()
.map(|frozen| frozen.finished_units)
.map(|stage| stage.finished_units)
.sum::<usize>()
+ self.finished_before_switch,
+ self.finished_before_reconnect,
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;
match (record.job, record.running_since(), record.outcome) {
(Some(_), Some(_), _) => tally.running += 1,
(Some(_), None, _) => tally.waiting += 1,
(None, _, Some(Outcome::Succeeded { .. } | Outcome::Abandoned)) => tally.done += 1,
_ => {}
}
tally
})
}
fn milestone_reached_at(&self, target: &str) -> Option<Micros> {
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) if outcome.result == JobResult::Done => Some(outcome.at),
Some(Outcome::Succeeded { at }) => Some(at),
Some(_) => None,
None => record
.active_enter
@@ -415,31 +389,32 @@ impl BootState {
}
}
pub fn finished_stages(&self) -> Vec<MilestoneRow> {
self.frozen.iter().map(FrozenMilestone::row).collect()
}
pub fn current_stage_started_at(&self) -> Micros {
self.frozen
.last()
.map_or(self.origin, |frozen| frozen.reached_at)
}
#[must_use]
pub fn milestones(&self) -> Vec<MilestoneRow> {
let mut finished: Vec<Micros> = self
let mut succeeded: Vec<Duration> = self
.units
.values()
.filter_map(|record| record.outcome)
.filter(|outcome| !outcome.result.is_failure())
.map(|outcome| outcome.at)
.filter_map(|record| match record.outcome {
Some(Outcome::Succeeded { at }) => Some(at),
_ => None,
})
.collect();
finished.sort_unstable();
succeeded.sort_unstable();
let start = MilestoneWalk {
rows: self.frozen.iter().map(FrozenMilestone::row).collect(),
rows: self
.finished_stages
.iter()
.map(|stage| MilestoneRow {
label: stage.label.to_owned(),
finished_units: stage.finished_units,
started_at: stage.started_at,
reached_at: Some(stage.reached_at),
})
.collect(),
previous: self
.frozen
.finished_stages
.last()
.map_or(self.origin, |frozen| frozen.reached_at),
.map_or(self.origin, |stage| stage.reached_at),
consumed: 0,
};
let mut walk = self
@@ -449,8 +424,8 @@ impl BootState {
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;
.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(),
@@ -462,6 +437,7 @@ impl BootState {
walk.rows
}
#[must_use]
pub fn pending_rows(&self) -> Vec<PendingRow> {
let pending: HashSet<&str> = self
.units
@@ -527,6 +503,7 @@ impl BootState {
depth: ancestry.len(),
is_last_sibling,
label: display_label(&record.facts),
is_target: record.facts.name.ends_with(".target"),
status: if running_since.is_some() {
RowStatus::Running
} else {
@@ -589,42 +566,35 @@ impl BootState {
false
}
fn sibling_rank(&self, name: &str) -> SiblingRank {
match self.units[name].running_since() {
fn sort_siblings(&self, names: &mut [&str]) {
let rank = |name: &str| 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))
});
};
names.sort_by(|left, right| rank(left).cmp(&rank(right)).then_with(|| left.cmp(right)));
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum SiblingRank {
RunningSince(Micros),
RunningSince(Duration),
Waiting,
}
struct ReachedMilestone<'a> {
target: &'a str,
reached_at: Micros,
reached_at: Duration,
}
struct MilestoneWalk {
rows: Vec<MilestoneRow>,
previous: Micros,
previous: Duration,
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);
fn advance(mut self, reached: &ReachedMilestone, succeeded_sorted: &[Duration]) -> Self {
let upto = succeeded_sorted.partition_point(|at| *at <= reached.reached_at);
self.rows.push(MilestoneRow {
label: reached.target.to_owned(),
finished_units: upto.saturating_sub(self.consumed),
@@ -637,17 +607,6 @@ impl MilestoneWalk {
}
}
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();
@@ -662,6 +621,8 @@ fn display_label(facts: &UnitFacts) -> String {
mod tests {
use super::*;
const MS: Duration = Duration::from_millis(1);
fn facts(name: &str, after: &[&str]) -> UnitFacts {
UnitFacts {
name: name.to_owned(),
@@ -670,7 +631,7 @@ mod tests {
}
}
fn activating(since: Micros) -> Activity {
fn activating(since: Duration) -> Activity {
Activity {
state: Some(ActiveState::Activating),
inactive_exit: Some(since),
@@ -681,40 +642,37 @@ mod tests {
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",
(
facts("graphical.target", &["multi-user.target"]),
Activity::default(),
),
(
facts(
"multi-user.target",
&["docker.service", "nm-wait.service", "basic.target"],
),
Activity::default(),
),
(
facts("nm-wait.service", &["nm.service"]),
Activity::default(),
),
(facts("nm.service", &[]), activating(1000 * MS)),
(
facts("docker.service", &["containerd.service"]),
activating(3000 * MS),
),
(facts("containerd.service", &[]), Activity::default()),
(facts("basic.target", &[]), Activity::default()),
]
.into_iter()
.zip(1..)
.for_each(|(unit, id)| state.queue_job(id, unit, 500_000));
.for_each(|((unit, activity), id)| {
let name = unit.name.clone();
state.track_unit(unit, activity);
state.queue_job(id, &name, 500 * MS);
});
state
}
@@ -742,14 +700,14 @@ mod tests {
#[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.finish_job(6, JobResult::Done, 3500 * MS);
state.finish_job(7, JobResult::Done, 4000 * MS);
state.update_activity(
"basic.target",
Activity {
state: Some(ActiveState::Active),
inactive_exit: None,
active_enter: Some(4_000_000),
active_enter: Some(4000 * MS),
},
);
let rows = state.pending_rows();
@@ -766,8 +724,8 @@ mod tests {
#[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"]);
state.finish_job(4, JobResult::Failed, 2000 * MS);
assert_eq!(state.failed, ["nm.service"]);
let tally = state.tally();
assert_eq!(tally.failed, 1);
assert_eq!(tally.done, 0);
@@ -779,7 +737,7 @@ mod tests {
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));
(1..=7).for_each(|id| state.finish_job(id, JobResult::Done, 5000 * MS));
assert!(state.is_complete());
}
@@ -787,9 +745,9 @@ mod tests {
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);
state.queue_job(20, HANDOFF_UNIT, 500 * MS);
assert!(!state.is_complete());
state.update_activity(HANDOFF_UNIT, activating(6_000_000));
state.update_activity(HANDOFF_UNIT, activating(6000 * MS));
assert!(state.is_complete());
}
@@ -799,17 +757,23 @@ mod tests {
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);
state.queue_job(1, "initrd.target", Duration::ZERO);
state.queue_job(2, "sysroot.mount", Duration::ZERO);
state.finish_job(2, JobResult::Done, 1000 * MS);
state.finish_job(1, JobResult::Done, 1500 * MS);
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));
state.switch_root(2000 * MS);
assert_eq!(state.phase, Phase::Host);
assert_eq!(
state.finished_stages,
[FinishedStage {
label: "initrd",
finished_units: 2,
started_at: Duration::ZERO,
reached_at: 2000 * MS,
}]
);
assert_eq!(state.milestones()[0].reached_at, Some(2000 * MS));
assert_eq!(state.tally().done, 2);
assert!(state.pending_rows().is_empty());
}
@@ -825,7 +789,7 @@ mod tests {
},
Activity::default(),
);
state.queue_job(1, "dev-nvme1n1.device", 0);
state.queue_job(1, "dev-nvme1n1.device", Duration::ZERO);
assert_eq!(state.pending_rows()[0].label, "Lexar SSD NM790 2TB");
}
@@ -833,23 +797,22 @@ mod tests {
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));
facts("web.service", &["db.service"]),
facts("db.service", &[]),
]
.into_iter()
.zip(1..)
.for_each(|(unit, id)| {
let name = unit.name.clone();
state.track_unit(unit, Activity::default());
state.queue_job(id, &name, Duration::ZERO);
});
let outline: Vec<String> = state
.pending_rows()
.into_iter()
@@ -863,8 +826,8 @@ mod tests {
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);
state.queue_job(1, "a.service", Duration::ZERO);
state.queue_job(2, "b.service", Duration::ZERO);
assert_eq!(state.pending_rows().len(), 2);
}
}
+30 -90
View File
@@ -1,8 +1,8 @@
use std::{
path::Path,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
mpsc::{Receiver, channel},
},
thread::sleep,
time::Duration,
@@ -17,14 +17,11 @@ use ratatui::{
DefaultTerminal,
backend::{Backend, ClearType},
};
use rustix::system::uname;
use signal_hook::{consts::SIGTERM, flag};
use crate::{
clock::{host_name, monotonic_now},
console::ForegroundVt,
error::Error,
feed::{self, FeedOptions, JobKind, Update},
sysroot::running_in_initrd,
clock::monotonic_now, console::ForegroundVt, error::Error, feed::Feed, sysroot::INITRD_RELEASE,
systemd::Scope,
};
@@ -40,92 +37,26 @@ pub struct Options {
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 phase = match options.scope {
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);
let _foreground = ForegroundVt::take();
let mut terminal = ratatui::try_init()?;
let watched = watch(
&mut state,
&updates,
&mut feed,
&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, ..
@@ -139,25 +70,34 @@ fn asks_to_quit(event: &Event) -> bool {
fn watch(
state: &mut BootState,
updates: &Receiver<Update>,
feed: &mut Feed,
terminal: &mut DefaultTerminal,
terminate: &AtomicBool,
hold: Duration,
) -> Result<(), Error> {
let host = host_name();
let host = uname().nodename().to_string_lossy().into_owned();
let mut frame: u64 = 0;
loop {
if let Some(error) = updates.try_iter().find_map(|update| absorb(state, update)) {
return Err(error);
}
feed.pump(state, FRAME_INTERVAL)?;
if frame.is_multiple_of(FRAMES_PER_FULL_REPAINT) {
repaint_fully(terminal)?;
terminal.backend_mut().clear_region(ClearType::All)?;
terminal.swap_buffers();
}
draw(terminal, state, &host, frame)?;
terminal.draw(|canvas| {
canvas.render_widget(
BootView {
state,
now: monotonic_now(),
host: &host,
frame,
},
canvas.area(),
);
})?;
if state.is_complete() {
eprintln!(
"boot-tree: {} reached, handing the console over",
state.root().unwrap_or("boot")
state.root.as_deref().unwrap_or("boot")
);
sleep(hold);
return Ok(());
@@ -165,7 +105,7 @@ fn watch(
if terminate.load(Ordering::Relaxed) {
return Ok(());
}
if event::poll(FRAME_INTERVAL)? && asks_to_quit(&event::read()?) {
if event::poll(Duration::ZERO)? && asks_to_quit(&event::read()?) {
return Ok(());
}
frame += 1;
+2 -6
View File
@@ -1,4 +1,4 @@
use std::{os::fd::OwnedFd, path::Path};
use std::os::fd::OwnedFd;
use rustix::{
fs::{Mode, OFlags, open},
@@ -7,11 +7,7 @@ use rustix::{
};
const SYSROOT: &str = "/sysroot";
const INITRD_RELEASE: &str = "/etc/initrd-release";
pub fn running_in_initrd() -> bool {
Path::new(INITRD_RELEASE).exists()
}
pub const INITRD_RELEASE: &str = "/etc/initrd-release";
pub struct Sysroot {
directory: OwnedFd,
+91 -73
View File
@@ -1,6 +1,6 @@
use std::{iter, time::Duration};
use boot_tree::model::{ActiveState, Activity, JobResult, Micros, UnitFacts};
use boot_tree::model::{ActiveState, Activity, JobResult, UnitFacts};
use dbus::{
Message, MessageType, Path,
arg::{AppendAll, PropMap, RefArg, Variant},
@@ -20,6 +20,7 @@ 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 STOP_JOB: &str = "stop";
const CALL_TIMEOUT: Duration = Duration::from_secs(1);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -53,24 +54,24 @@ pub struct FetchedUnit {
pub struct JobListing {
pub id: u32,
pub unit: String,
pub kind: String,
}
pub fn brings_unit_up(job_kind: &str) -> bool {
job_kind != "stop"
pub brings_unit_up: bool,
}
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 }
Self {
id,
unit,
brings_unit_up: kind != STOP_JOB,
}
}
}
pub struct Session {
channel: Channel,
peer_to_peer: bool,
pub peer_to_peer: bool,
}
impl Session {
@@ -92,7 +93,7 @@ impl Session {
channel: Channel::get_private(bus)?,
peer_to_peer: false,
};
session.call_at(
session.call(
BUS_DESTINATION,
BUS_PATH,
BUS_DESTINATION,
@@ -102,11 +103,7 @@ impl Session {
Ok(session)
}
pub fn is_peer_to_peer(&self) -> bool {
self.peer_to_peer
}
fn call_at(
fn call(
&self,
destination: &str,
path: &str,
@@ -121,31 +118,31 @@ impl Session {
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")?;
self.call(
DESTINATION,
MANAGER_PATH,
MANAGER_INTERFACE,
"Subscribe",
(),
)?;
Ok(())
}
pub fn default_target(&self) -> Result<String, Error> {
Ok(self.call_manager("GetDefaultTarget")?.read1()?)
let reply = self.call(
DESTINATION,
MANAGER_PATH,
MANAGER_INTERFACE,
"GetDefaultTarget",
(),
)?;
Ok(reply.read1()?)
}
pub fn boot_in_progress(&self) -> Result<bool, Error> {
let reply = self.call(
DESTINATION,
MANAGER_PATH,
PROPERTIES_INTERFACE,
"Get",
@@ -156,49 +153,82 @@ impl Session {
}
pub fn list_jobs(&self) -> Result<Vec<JobListing>, Error> {
let listed: Vec<ListedJob> = self.call_manager("ListJobs")?.read1()?;
let reply = self.call(DESTINATION, MANAGER_PATH, MANAGER_INTERFACE, "ListJobs", ())?;
let listed: Vec<ListedJob> = reply.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"))?;
pub fn job_brings_unit_up(&self, job: &Path) -> Result<bool, Error> {
let reply = self.call(
DESTINATION,
job,
PROPERTIES_INTERFACE,
"Get",
(JOB_INTERFACE, "JobType"),
)?;
let kind: Variant<String> = reply.read1()?;
Ok(kind.0)
Ok(kind.0 != STOP_JOB)
}
pub fn fetch_unit(&self, name: &str) -> Result<FetchedUnit, Error> {
let path: Path<'static> = self
.call(MANAGER_PATH, MANAGER_INTERFACE, "GetUnit", (name,))?
.call(
DESTINATION,
MANAGER_PATH,
MANAGER_INTERFACE,
"GetUnit",
(name,),
)?
.read1()?;
let properties: PropMap = self
.call(&path, PROPERTIES_INTERFACE, "GetAll", (UNIT_INTERFACE,))?
.call(
DESTINATION,
&path,
PROPERTIES_INTERFACE,
"GetAll",
(UNIT_INTERFACE,),
)?
.read1()?;
let text = |property: &str| {
properties
.get(property)
.and_then(|value| value.0.as_str())
.map(ToOwned::to_owned)
};
let after = properties
.get("After")
.and_then(|value| value.0.as_iter())
.map(|items| {
items
.filter_map(|item| item.as_str().map(ToOwned::to_owned))
.collect()
})
.unwrap_or_default();
Ok(FetchedUnit {
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"),
name: text("Id").unwrap_or_else(|| name.to_owned()),
description: text("Description").unwrap_or_default(),
after,
},
activity: activity_from(&properties),
path,
})
}
pub fn receive(&self, timeout: Duration) -> Result<Vec<Signal>, Error> {
let queued = self.drain();
let drain = || -> Vec<Signal> {
iter::from_fn(|| self.channel.pop_message())
.filter_map(|message| parse_signal(&message))
.collect()
};
let queued = drain();
if !queued.is_empty() {
return Ok(queued);
}
if self.channel.read_write(Some(timeout)).is_err() || !self.channel.is_connected() {
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()
Ok(drain())
}
}
@@ -249,32 +279,20 @@ fn parse_signal(message: &Message) -> Option<Signal> {
}
}
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 {
let monotonic = |property: &str| {
properties
.get(property)
.and_then(|value| value.0.as_u64())
.filter(|micros| *micros != 0)
.map(Duration::from_micros)
};
Activity {
state: text_property(properties, "ActiveState").map(|raw| ActiveState::parse(&raw)),
inactive_exit: timestamp_property(properties, "InactiveExitTimestampMonotonic"),
active_enter: timestamp_property(properties, "ActiveEnterTimestampMonotonic"),
state: properties
.get("ActiveState")
.and_then(|value| value.0.as_str())
.map(ActiveState::parse),
inactive_exit: monotonic("InactiveExitTimestampMonotonic"),
active_enter: monotonic("ActiveEnterTimestampMonotonic"),
}
}
+139 -133
View File
@@ -1,5 +1,9 @@
use std::iter::{once, repeat_n};
use std::{
iter::{once, repeat_n},
time::Duration,
};
use jiff::fmt::friendly::{Designator, FractionalUnit, Spacing, SpanPrinter};
use ratatui::{
buffer::Buffer,
layout::{Constraint, Layout, Rect},
@@ -8,7 +12,7 @@ use ratatui::{
widgets::{Block, Borders, Paragraph, Row, Table, Widget},
};
use crate::model::{BootState, Micros, MilestoneRow, PendingRow, RowStatus, Tally};
use crate::model::{BootState, MilestoneRow, PendingRow, RowStatus, Tally};
const SPINNER: [char; 4] = ['|', '/', '-', '\\'];
const DONE: char = '√';
@@ -19,6 +23,7 @@ const STILL_GOING: char = '▶';
const RUNNING_MARK: char = '►';
const ROOT_SWITCH_MARK: char = '│';
const RULE: char = '─';
const RULE_STUB: &str = "──";
const DURATION_WIDTH: u16 = 8;
const TIMELINE_LABEL_WIDTH: u16 = 28;
@@ -28,12 +33,34 @@ const TIMELINE_CHROME_HEIGHT: u16 = 3;
const HEADER_HEIGHT: u16 = 2;
const FOOTER_HEIGHT: u16 = 2;
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;
const AXIS_LABEL_SPACING: u16 = 8;
const AXIS_STEPS: [Duration; 12] = [
Duration::from_secs(1),
Duration::from_secs(2),
Duration::from_secs(5),
Duration::from_secs(10),
Duration::from_secs(15),
Duration::from_secs(30),
Duration::from_mins(1),
Duration::from_mins(2),
Duration::from_mins(5),
Duration::from_mins(10),
Duration::from_mins(30),
Duration::from_hours(1),
];
const ELAPSED: SpanPrinter = SpanPrinter::new()
.designator(Designator::Compact)
.spacing(Spacing::None)
.fractional(Some(FractionalUnit::Second))
.precision(Some(1));
const AXIS_LABEL: SpanPrinter = SpanPrinter::new()
.designator(Designator::Compact)
.spacing(Spacing::None);
pub struct BootView<'a> {
pub state: &'a BootState,
pub now: Micros,
pub now: Duration,
pub host: &'a str,
pub frame: u64,
}
@@ -47,22 +74,25 @@ impl Widget for BootView<'_> {
.into_iter()
.filter(|row| row.reached_at.is_some())
.collect();
let units = timeline_units(&rows);
let failures = failure_lines(self.state.failed_units());
let mut units: Vec<&PendingRow> = rows.iter().filter(|row| !row.is_target).collect();
units.sort_by_key(|row| row.running_since.unwrap_or(Duration::MAX));
let failures = failure_lines(&self.state.failed);
let stages = self.stage_lines(area.width);
let fixed = HEADER_HEIGHT + stages.len() as u16 + failures.len() as u16 + FOOTER_HEIGHT;
let stages_height = u16::try_from(stages.len()).unwrap_or(u16::MAX);
let failures_height = u16::try_from(failures.len()).unwrap_or(u16::MAX);
let heights = Heights::share(
area.height.saturating_sub(fixed),
rows.len() as u16,
area.height
.saturating_sub(HEADER_HEIGHT + stages_height + failures_height + FOOTER_HEIGHT),
u16::try_from(rows.len()).unwrap_or(u16::MAX),
timeline_need(area, milestones.len() + units.len()),
);
let [header, _, stage_area, tree, failed, _, timeline, footer] = Layout::vertical([
Constraint::Length(1),
Constraint::Length(HEADER_HEIGHT - 1),
Constraint::Length(stages.len() as u16),
Constraint::Length(stages_height),
Constraint::Length(heights.tree),
Constraint::Length(failures.len() as u16),
Constraint::Length(failures_height),
Constraint::Fill(1),
Constraint::Length(heights.timeline),
Constraint::Length(FOOTER_HEIGHT),
@@ -77,8 +107,12 @@ impl Widget for BootView<'_> {
self.timeline(&milestones, &units, timeline.width)
.render(timeline, buf);
}
let root_switched = !self.state.finished_stages().is_empty();
footer_paragraph(self.state.tally(), footer.width, root_switched).render(footer, buf);
footer_paragraph(
self.state.tally(),
footer.width,
!self.state.finished_stages.is_empty(),
)
.render(footer, buf);
}
}
@@ -89,7 +123,7 @@ struct Heights {
impl Heights {
fn share(free: u16, tree_need: u16, timeline_need: u16) -> Self {
if tree_need + timeline_need <= free {
if tree_need.saturating_add(timeline_need) <= free {
return Self {
tree: tree_need,
timeline: timeline_need,
@@ -105,22 +139,19 @@ impl Heights {
fn rule_line(width: u16, left: Vec<Span<'static>>, right: Vec<Span<'static>>) -> Line<'static> {
let used = Line::from(left.clone()).width() + Line::from(right.clone()).width();
let fill = Span::from(rule(usize::from(width).saturating_sub(used))).dark_gray();
let fill: String = repeat_n(RULE, usize::from(width).saturating_sub(used)).collect();
Line::from(
left.into_iter()
.chain(once(fill))
.chain(once(Span::from(fill).dark_gray()))
.chain(right)
.collect::<Vec<_>>(),
)
}
fn rule(length: usize) -> String {
repeat_n(RULE, length).collect()
}
impl BootView<'_> {
fn header(&self) -> Table<'static> {
let elapsed = format_duration(self.now.saturating_sub(self.state.origin()));
let elapsed =
ELAPSED.unsigned_duration_to_string(&self.now.saturating_sub(self.state.origin));
Table::new(
[Row::new([
Line::from(format!("boot-tree {}", self.host)),
@@ -132,34 +163,43 @@ impl BootView<'_> {
}
fn stage_lines(&self, width: u16) -> Vec<Line<'static>> {
let finished = self.state.finished_stages().into_iter().map(|stage| {
let took = stage.reached_at.unwrap_or(stage.started_at) - stage.started_at;
let finished = self.state.finished_stages.iter().map(|stage| {
rule_line(
width,
vec![
Span::from(format!("{} ", rule(2))).dark_gray(),
Span::from(stage.label).dark_gray(),
Span::from(format!(" {} ", rule(2))).dark_gray(),
Span::from(format!("{BEAD} done in {}", format_duration(took))).green(),
Span::from(format!("{RULE_STUB} {} {RULE_STUB} ", stage.label)).dark_gray(),
Span::from(format!(
"{BEAD} done in {}",
ELAPSED.unsigned_duration_to_string(
&stage.reached_at.saturating_sub(stage.started_at)
)
))
.green(),
Span::from(format!(" · {} ", unit_count(stage.finished_units))).dark_gray(),
],
Vec::new(),
)
});
let running_for = self
.now
.saturating_sub(self.state.current_stage_started_at());
let current_started_at = self
.state
.finished_stages
.last()
.map_or(self.state.origin, |stage| stage.reached_at);
let current = rule_line(
width,
vec![
Span::from(format!("{} ", rule(2))).dark_gray(),
Span::from(self.state.phase().label()).bold(),
Span::from(format!("{RULE_STUB} ")).dark_gray(),
Span::from(self.state.phase.label()).bold(),
Span::raw(" "),
],
vec![
Span::raw(" "),
Span::from(format_duration(running_for)).bold(),
Span::from(format!(" {}", rule(2))).dark_gray(),
Span::from(
ELAPSED
.unsigned_duration_to_string(&self.now.saturating_sub(current_started_at)),
)
.bold(),
Span::from(format!(" {RULE_STUB}")).dark_gray(),
],
);
finished.chain(once(current)).collect()
@@ -192,7 +232,7 @@ impl BootView<'_> {
status_marker(row, self.frame),
Span::styled(row.label.as_str(), label_style(row)),
]),
Line::from(format_duration(self.now.saturating_sub(since)))
Line::from(ELAPSED.unsigned_duration_to_string(&self.now.saturating_sub(since)))
.style(label_style(row))
.right_aligned(),
])
@@ -205,15 +245,15 @@ impl BootView<'_> {
width: u16,
) -> Table<'a> {
let axis = TimeAxis::new(
self.state.origin(),
self.state.origin,
self.now,
width.saturating_sub(TIMELINE_LABEL_WIDTH + 1),
);
let root_switches: Vec<Micros> = self
let root_switches: Vec<Duration> = self
.state
.finished_stages()
.finished_stages
.iter()
.filter_map(|stage| stage.reached_at)
.map(|stage| stage.reached_at)
.collect();
let axis_rows = [
Row::new([Line::default(), axis.labels()]),
@@ -264,7 +304,7 @@ fn timeline_need(screen: Rect, entries: usize) -> u16 {
&& screen.height >= MIN_HEIGHT_FOR_TIMELINE
&& entries > 0;
if fits {
TIMELINE_CHROME_HEIGHT + entries as u16
TIMELINE_CHROME_HEIGHT.saturating_add(u16::try_from(entries).unwrap_or(u16::MAX))
} else {
0
}
@@ -315,8 +355,8 @@ fn footer_paragraph(tally: Tally, width: u16, root_switched: bool) -> Paragraph<
}
struct Segment {
from: Micros,
to: Micros,
from: Duration,
to: Duration,
symbol: char,
style: Style,
}
@@ -333,7 +373,7 @@ fn milestone_segments(row: &MilestoneRow) -> Vec<Segment> {
.collect()
}
fn unit_segments(row: &PendingRow, now: Micros) -> Vec<Segment> {
fn unit_segments(row: &PendingRow, now: Duration) -> Vec<Segment> {
let waiting_until = row.running_since.unwrap_or(now);
let waiting = (waiting_until > row.queued_at).then(|| Segment {
from: row.queued_at,
@@ -350,13 +390,6 @@ fn unit_segments(row: &PendingRow, now: Micros) -> Vec<Segment> {
waiting.into_iter().chain(running).collect()
}
struct TimeAxis {
origin: Micros,
end: Micros,
step: Micros,
width: u16,
}
struct Stroke {
column: u16,
glyphs: String,
@@ -413,36 +446,45 @@ fn canvas_line(width: u16, strokes: impl IntoIterator<Item = Stroke>) -> Line<'s
)
}
struct TimeAxis {
origin: Duration,
span: Duration,
step: Duration,
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
fn new(origin: Duration, now: Duration, width: u16) -> Self {
let elapsed = now.saturating_sub(origin).max(AXIS_STEPS[0]);
let max_labels = u128::from((width / AXIS_LABEL_SPACING).max(1));
let step = AXIS_STEPS
.into_iter()
.find(|step| span_seconds.div_ceil(*step) <= max_labels)
.unwrap_or(AXIS_STEPS_SECONDS[AXIS_STEPS_SECONDS.len() - 1]);
let end_seconds = span_seconds.div_ceil(step_seconds).max(1) * step_seconds;
.find(|step| elapsed.as_nanos().div_ceil(step.as_nanos()) <= max_labels)
.unwrap_or(AXIS_STEPS[AXIS_STEPS.len() - 1]);
let steps = u32::try_from(elapsed.as_nanos().div_ceil(step.as_nanos())).unwrap_or(u32::MAX);
Self {
origin,
end: origin + end_seconds * 1_000_000,
step: step_seconds * 1_000_000,
span: step * steps.max(1),
step,
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 column(&self, at: Duration) -> u16 {
let offset = at.saturating_sub(self.origin).min(self.span);
let column = offset.as_nanos() * u128::from(self.width) / self.span.as_nanos();
u16::try_from(column)
.unwrap_or(u16::MAX)
.min(self.width.saturating_sub(1))
}
fn tick_offsets(&self) -> impl Iterator<Item = Micros> + '_ {
fn tick_offsets(&self) -> impl Iterator<Item = Duration> + '_ {
(0..)
.map(|index| index * self.step)
.take_while(|offset| self.origin + offset <= self.end)
.map(|index: u32| self.step * index)
.take_while(|offset| *offset <= self.span)
}
fn root_switch_strokes(&self, root_switches: &[Micros]) -> Vec<Stroke> {
fn root_switch_strokes(&self, root_switches: &[Duration]) -> Vec<Stroke> {
root_switches
.iter()
.map(|at| {
@@ -460,11 +502,12 @@ impl TimeAxis {
canvas_line(
self.width,
self.tick_offsets().map(|offset| {
let glyphs = format_axis_label(offset);
let glyphs = AXIS_LABEL.unsigned_duration_to_string(&offset);
let label_width = u16::try_from(glyphs.len()).unwrap_or(self.width);
Stroke {
column: self
.column(self.origin + offset)
.min(self.width.saturating_sub(glyphs.len() as u16)),
.min(self.width.saturating_sub(label_width)),
glyphs,
style: Style::new().dark_gray(),
}
@@ -472,7 +515,7 @@ impl TimeAxis {
)
}
fn ticks_line(&self, root_switches: &[Micros]) -> Line<'static> {
fn ticks_line(&self, root_switches: &[Duration]) -> Line<'static> {
canvas_line(
self.width,
self.root_switch_strokes(root_switches)
@@ -491,8 +534,8 @@ impl TimeAxis {
fn bar(
&self,
segments: &[Segment],
still_going_at: Option<Micros>,
root_switches: &[Micros],
still_going_at: Option<Duration>,
root_switches: &[Duration],
) -> Line<'static> {
let bars = segments.iter().map(|segment| {
let start = self.column(segment.from);
@@ -511,21 +554,12 @@ impl TimeAxis {
}
}
fn timeline_units(rows: &[PendingRow]) -> Vec<&PendingRow> {
let mut units: Vec<&PendingRow> = rows.iter().filter(|row| !is_target(row)).collect();
units.sort_by_key(|row| row.running_since.unwrap_or(Micros::MAX));
units
}
fn is_target(row: &PendingRow) -> bool {
row.label.ends_with(".target")
}
fn status_marker(row: &PendingRow, frame: u64) -> Span<'static> {
match (is_target(row), row.status) {
match (row.is_target, row.status) {
(true, _) => Span::raw(""),
(false, RowStatus::Running) => {
Span::from(format!("[{}] ", SPINNER[(frame % 4) as usize])).yellow()
let spinner = SPINNER[usize::try_from(frame % 4).unwrap_or_default()];
Span::from(format!("[{spinner}] ")).yellow()
}
(false, RowStatus::Waiting) => Span::from("[ ] ").dark_gray(),
}
@@ -539,7 +573,7 @@ fn timeline_marker(row: &PendingRow) -> Span<'static> {
}
fn label_style(row: &PendingRow) -> Style {
match (is_target(row), row.status) {
match (row.is_target, row.status) {
(true, _) => Style::new().cyan(),
(false, RowStatus::Running) => Style::new(),
(false, RowStatus::Waiting) => Style::new().dark_gray(),
@@ -567,25 +601,6 @@ fn unit_count(count: usize) -> String {
}
}
fn format_duration(micros: Micros) -> String {
let tenths = micros / 100_000;
let seconds = micros / 1_000_000;
match seconds {
0..60 => format!("{}.{}s", tenths / 10, tenths % 10),
60..3600 => 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)
}
}
#[cfg(test)]
mod tests {
use ratatui::{Terminal, backend::TestBackend};
@@ -593,6 +608,8 @@ mod tests {
use super::*;
use crate::model::{ActiveState, Activity, JobResult, Phase, UnitFacts};
const MS: Duration = Duration::from_millis(1);
fn facts(name: &str, after: &[&str]) -> UnitFacts {
UnitFacts {
name: name.to_owned(),
@@ -601,7 +618,7 @@ mod tests {
}
}
fn render(state: &BootState, now: Micros, width: u16, height: u16) -> Vec<String> {
fn render(state: &BootState, now: Duration, width: u16, height: u16) -> Vec<String> {
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("test backend");
terminal
.draw(|frame| {
@@ -627,7 +644,7 @@ mod tests {
.collect()
}
fn running_since(since: Micros) -> Activity {
fn running_since(since: Duration) -> Activity {
Activity {
state: Some(ActiveState::Activating),
inactive_exit: Some(since),
@@ -650,10 +667,10 @@ mod tests {
),
Activity::default(),
),
(facts("docker.service", &[]), running_since(9_000_000)),
(facts("docker.service", &[]), running_since(9000 * MS)),
(
facts("systemd-rfkill.service", &[]),
running_since(6_000_000),
running_since(6000 * MS),
),
(facts("sysinit.target", &[]), Activity::default()),
(facts("nvidia-powerd.service", &[]), Activity::default()),
@@ -663,16 +680,16 @@ mod tests {
.for_each(|((unit, activity), id)| {
let name = unit.name.clone();
state.track_unit(unit, activity);
state.queue_job(id, &name, 1_000_000);
state.queue_job(id, &name, 1000 * MS);
});
state.finish_job(5, JobResult::Done, 4_000_000);
state.finish_job(6, JobResult::Failed, 5_000_000);
state.finish_job(5, JobResult::Done, 4000 * MS);
state.finish_job(6, JobResult::Failed, 5000 * MS);
state
}
#[test]
fn tree_on_top_timeline_below() {
let lines = render(&boot_in_progress(), 12_400_000, 110, 24);
let lines = render(&boot_in_progress(), 12_400 * MS, 110, 24);
let screen = lines.join("\n");
assert!(lines[0].starts_with("boot-tree ryzen"), "{screen}");
assert!(lines[0].ends_with("12.4s"), "{screen}");
@@ -707,10 +724,6 @@ mod tests {
);
assert!(lines[timeline + 5].starts_with("► docker"), "{screen}");
assert!(!screen.contains("root switch"), "{screen}");
assert!(
screen.contains("× nvidia-powerd.service failed"),
"{screen}"
);
assert!(
lines[23].starts_with("√ 1 done 2 running 2 waiting × 1 failed"),
"{screen}"
@@ -719,9 +732,9 @@ mod tests {
#[test]
fn narrow_screens_drop_the_timeline() {
let lines = render(&boot_in_progress(), 12_400_000, 36, 24);
let lines = render(&boot_in_progress(), 12_400 * MS, 36, 24);
assert!(
lines.iter().all(|line| !line.contains('█')),
lines.iter().all(|line| !line.contains('■')),
"{}",
lines.join("\n")
);
@@ -733,13 +746,13 @@ mod tests {
let mut state = BootState::new(Phase::Initrd);
state.set_root("initrd.target".to_owned());
state.track_unit(facts("initrd.target", &[]), Activity::default());
state.queue_job(1, "initrd.target", 0);
state.finish_job(1, JobResult::Done, 6_000_000);
state.switch_root(7_200_000);
state.queue_job(1, "initrd.target", Duration::ZERO);
state.finish_job(1, JobResult::Done, 6000 * MS);
state.switch_root(7200 * MS);
state.set_root("graphical.target".to_owned());
state.track_unit(facts("graphical.target", &[]), Activity::default());
state.queue_job(2, "graphical.target", 7_300_000);
let lines = render(&state, 17_300_000, 110, 24);
state.queue_job(2, "graphical.target", 7300 * MS);
let lines = render(&state, 17_300 * MS, 110, 24);
let screen = lines.join("\n");
assert!(
lines[2].starts_with("── initrd ── ■ done in 7.2s · 1 unit ──"),
@@ -773,20 +786,13 @@ mod tests {
(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);
state.queue_job(id, &name, Duration::ZERO);
});
let lines = render(&state, 1_000_000, 110, 20);
let lines = render(&state, 1000 * MS, 110, 20);
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");
}
}