feat: show why units failed, with their last journal lines
Failed jobs keep their kind: units that broke or timed out get a failure panel entry with the reason systemd reports (exit status, signal, timeout, start limit, status text) and their last journal lines read through libsystemd. Units that failed only through a dependency are dimmed and left out of the panel, and units that crash after starting count as failed. Restructure the repository around this: - move the library and binary into bootvine/ and the scripted demos into their own unpublished scripted-demos crate, with their VHS tapes - move the crane builds and NixOS module into nix/ - group each sample VM with its check under vm-tests/, adding text-console, scripted-initrd, encrypted-volume and failures machines and a vm-failures check - add docs/guide.md walking through the screen with every recording, keep one recording in the README, and re-render all recordings
This commit is contained in:
1 parent
f2544a964a
commit
7e95cbd8e9
96 files changed
+2027
-462
No files matched your search
@@ -0,0 +1,69 @@
|
||||
[package]
|
||||
categories = ["command-line-utilities", "os::linux-apis"]
|
||||
description = "Boot and shutdown progress for systemd on the console, with each job nested under the units waiting on it"
|
||||
edition = "2024"
|
||||
include = ["/src", "/system-files", "/LICENSE"]
|
||||
keywords = ["systemd", "boot", "initrd", "tui", "console"]
|
||||
license = "GPL-3.0-or-later"
|
||||
name = "bootvine"
|
||||
readme = "../README.md"
|
||||
repository = "https://codeberg.org/wvhulle/bootvine"
|
||||
rust-version = "1.91"
|
||||
version = "0.1.0"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "4.6.7", default-features = false, features = [
|
||||
"std",
|
||||
"derive",
|
||||
"help",
|
||||
"usage",
|
||||
"error-context",
|
||||
] }
|
||||
crossterm = "0.29.0"
|
||||
dbus = "0.9.12"
|
||||
futures = { version = "0.3.34", default-features = false, features = [
|
||||
"std",
|
||||
"async-await",
|
||||
] }
|
||||
heck = "0.5.0"
|
||||
jiff = { version = "0.2.38", default-features = false, features = [
|
||||
"serde",
|
||||
"std",
|
||||
] }
|
||||
petgraph = { version = "0.8.3", default-features = false, features = [
|
||||
"std",
|
||||
"graphmap",
|
||||
] }
|
||||
ratatui = { version = "0.30.2", features = [
|
||||
"serde",
|
||||
"unstable-rendered-line-info",
|
||||
] }
|
||||
rustix = { version = "1.1.5", features = [
|
||||
"event",
|
||||
"fs",
|
||||
"process",
|
||||
"stdio",
|
||||
"system",
|
||||
"termios",
|
||||
"time",
|
||||
] }
|
||||
ser_nix = "0.2.4"
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_plain = "1.0.2"
|
||||
systemd = { version = "0.10.1", default-features = false, features = [
|
||||
"journal",
|
||||
] }
|
||||
thiserror = "2.0.12"
|
||||
tokio = { version = "1.54.0", default-features = false, features = [
|
||||
"rt",
|
||||
"time",
|
||||
"net",
|
||||
"signal",
|
||||
] }
|
||||
toml = { version = "1.1.8", features = ["preserve_order"] }
|
||||
unicode-truncate = "2.0.1"
|
||||
unicode-width = "0.2.2"
|
||||
zeroize = "1.9.1"
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../LICENSE
|
||||
@@ -0,0 +1,166 @@
|
||||
mod boot_change;
|
||||
pub mod boot_origin;
|
||||
mod job_ingestion;
|
||||
mod reached_milestones;
|
||||
mod unit_facts;
|
||||
mod waiting_tree;
|
||||
|
||||
use std::{collections::HashMap, time::Duration};
|
||||
|
||||
pub use self::{
|
||||
boot_change::BootChange,
|
||||
reached_milestones::MilestoneRow,
|
||||
unit_facts::{ActiveState, Activity, JobKind, JobResult, UnitFacts, UnitKind, UnitTimeouts},
|
||||
waiting_tree::{RowStatus, TreeNode, TreeRow, flatten_forest},
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Phase {
|
||||
Initrd,
|
||||
Host,
|
||||
User,
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
impl Phase {
|
||||
#[must_use]
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Initrd => "Initrd",
|
||||
Self::Host => "Stage 2",
|
||||
Self::User => "User",
|
||||
Self::Shutdown => "Shutdown",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct PendingJob {
|
||||
id: u32,
|
||||
queued_at: Duration,
|
||||
kind: JobKind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum FailureKind {
|
||||
Broke,
|
||||
TimedOut,
|
||||
DependencyFailed,
|
||||
}
|
||||
|
||||
impl FailureKind {
|
||||
#[must_use]
|
||||
pub fn has_own_cause(self) -> bool {
|
||||
self != Self::DependencyFailed
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FailureCause {
|
||||
pub reason: String,
|
||||
pub log_lines: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum FailureExplanation {
|
||||
Unexplained,
|
||||
Explained(FailureCause),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FailedUnit {
|
||||
pub unit: String,
|
||||
pub label: String,
|
||||
pub kind: FailureKind,
|
||||
pub explanation: FailureExplanation,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Outcome {
|
||||
Succeeded { at: Duration },
|
||||
Failed(FailureKind),
|
||||
Abandoned,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Progress {
|
||||
Untouched,
|
||||
Pending(PendingJob),
|
||||
Finished(Outcome),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct UnitRecord {
|
||||
facts: UnitFacts,
|
||||
activity: Activity,
|
||||
progress: Progress,
|
||||
}
|
||||
|
||||
#[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, PartialEq, Eq)]
|
||||
pub struct FinishedRun {
|
||||
pub label: String,
|
||||
pub started_at: Duration,
|
||||
pub finished_at: Duration,
|
||||
pub failed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FinishedStage {
|
||||
pub label: &'static str,
|
||||
pub finished_units: usize,
|
||||
pub failed_units: usize,
|
||||
pub started_at: Duration,
|
||||
pub reached_at: Duration,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Root {
|
||||
Unresolved,
|
||||
Awaiting(String),
|
||||
Queued(String),
|
||||
}
|
||||
|
||||
impl Root {
|
||||
#[must_use]
|
||||
pub fn unit(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::Unresolved => None,
|
||||
Self::Awaiting(unit) | Self::Queued(unit) => Some(unit),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BootState {
|
||||
pub phase: Phase,
|
||||
pub origin: Duration,
|
||||
pub root: Root,
|
||||
pub failed: Vec<FailedUnit>,
|
||||
pub finished_stages: Vec<FinishedStage>,
|
||||
pub finished_runs: Vec<FinishedRun>,
|
||||
pub handoff_unit: Option<String>,
|
||||
pub manager_exited_at: Option<Duration>,
|
||||
pub milestone_targets: Vec<String>,
|
||||
boot_finished: bool,
|
||||
units: HashMap<String, UnitRecord>,
|
||||
jobs: HashMap<u32, String>,
|
||||
}
|
||||
|
||||
const HOST_MILESTONES: [&str; 4] = [
|
||||
"sysinit.target",
|
||||
"basic.target",
|
||||
"multi-user.target",
|
||||
"graphical.target",
|
||||
];
|
||||
|
||||
const SHUTDOWN_MILESTONES: [&str; 3] = ["shutdown.target", "umount.target", "final.target"];
|
||||
|
||||
pub const HANDOFF_UNIT: &str = "display-manager.service";
|
||||
@@ -0,0 +1,115 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use super::{Activity, BootState, FailureCause, JobKind, JobResult, UnitFacts};
|
||||
|
||||
pub enum BootChange {
|
||||
TrackUnit {
|
||||
facts: UnitFacts,
|
||||
activity: Activity,
|
||||
},
|
||||
UpdateActivity {
|
||||
unit: String,
|
||||
activity: Activity,
|
||||
},
|
||||
QueueJob {
|
||||
id: u32,
|
||||
unit: String,
|
||||
kind: JobKind,
|
||||
at: Duration,
|
||||
},
|
||||
FinishJob {
|
||||
id: u32,
|
||||
result: JobResult,
|
||||
at: Duration,
|
||||
},
|
||||
ExplainFailure {
|
||||
unit: String,
|
||||
cause: FailureCause,
|
||||
},
|
||||
SetRoot(String),
|
||||
SetHandoff(String),
|
||||
SetOrigin(Duration),
|
||||
SwitchRoot {
|
||||
at: Duration,
|
||||
},
|
||||
ForgetJobs,
|
||||
ManagerExited {
|
||||
at: Duration,
|
||||
},
|
||||
BootFinished,
|
||||
}
|
||||
|
||||
impl BootState {
|
||||
pub fn apply(&mut self, change: BootChange) {
|
||||
match change {
|
||||
BootChange::TrackUnit { facts, activity } => self.track_unit(facts, activity),
|
||||
BootChange::UpdateActivity { unit, activity } => self.update_activity(&unit, activity),
|
||||
BootChange::QueueJob { id, unit, kind, at } => self.queue_job(id, &unit, kind, at),
|
||||
BootChange::FinishJob { id, result, at } => self.finish_job(id, result, at),
|
||||
BootChange::ExplainFailure { unit, cause } => self.explain_failure(&unit, cause),
|
||||
BootChange::SetRoot(root) => self.set_root(root),
|
||||
BootChange::SetHandoff(unit) => {
|
||||
if let Some(handoff) = &mut self.handoff_unit {
|
||||
*handoff = unit;
|
||||
}
|
||||
}
|
||||
BootChange::SetOrigin(origin) => self.origin = origin,
|
||||
BootChange::SwitchRoot { at } => self.switch_root(at),
|
||||
BootChange::ForgetJobs => self.forget_jobs(),
|
||||
BootChange::ManagerExited { at } => self.manager_exited_at = Some(at),
|
||||
BootChange::BootFinished => self.boot_finished = true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
boot_model::Phase,
|
||||
boot_test_fixtures::{MS, facts, waiting_rows},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn applied_changes_match_the_direct_calls() {
|
||||
let mut applied = BootState::new(Phase::Host);
|
||||
[
|
||||
BootChange::SetOrigin(100 * MS),
|
||||
BootChange::TrackUnit {
|
||||
facts: facts("web.service", &[]),
|
||||
activity: Activity::default(),
|
||||
},
|
||||
BootChange::SetRoot("web.service".to_owned()),
|
||||
BootChange::QueueJob {
|
||||
id: 1,
|
||||
unit: "web.service".to_owned(),
|
||||
kind: JobKind::BringsUp,
|
||||
at: 200 * MS,
|
||||
},
|
||||
BootChange::FinishJob {
|
||||
id: 1,
|
||||
result: JobResult::Done,
|
||||
at: 900 * MS,
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.for_each(|change| applied.apply(change));
|
||||
let mut called = BootState::new(Phase::Host);
|
||||
called.origin = 100 * MS;
|
||||
called.track_unit(facts("web.service", &[]), Activity::default());
|
||||
called.set_root("web.service".to_owned());
|
||||
called.queue_job(1, "web.service", JobKind::BringsUp, 200 * MS);
|
||||
called.finish_job(1, JobResult::Done, 900 * MS);
|
||||
assert_eq!(applied.tally(), called.tally());
|
||||
assert_eq!(applied.is_complete(), called.is_complete());
|
||||
assert_eq!(waiting_rows(&applied), waiting_rows(&called));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boot_finished_change_marks_the_boot_complete() {
|
||||
let mut state = BootState::new(Phase::Host);
|
||||
assert!(!state.is_complete());
|
||||
state.apply(BootChange::BootFinished);
|
||||
assert!(state.is_complete());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
use std::{
|
||||
fs::{read_dir, read_link, read_to_string},
|
||||
iter::once,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use rustix::system::uname;
|
||||
|
||||
const KERNEL_COMMAND_LINE: &str = "/proc/cmdline";
|
||||
const SYSTEM_PROFILES: &str = "/nix/var/nix/profiles";
|
||||
const OS_RELEASES: [&str; 2] = ["/etc/os-release", "/usr/lib/os-release"];
|
||||
const NIXOS_SYSTEM: &str = "nixos-system-";
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct BootOrigin {
|
||||
pub host: String,
|
||||
pub system: Option<String>,
|
||||
pub generation: Option<String>,
|
||||
pub kernel: String,
|
||||
}
|
||||
|
||||
impl BootOrigin {
|
||||
#[must_use]
|
||||
pub fn read() -> Self {
|
||||
let names = uname();
|
||||
let host = names.nodename().to_string_lossy().into_owned();
|
||||
let command_line = read_to_string(KERNEL_COMMAND_LINE).unwrap_or_default();
|
||||
let system_path = init_system(&command_line);
|
||||
let system = system_path
|
||||
.and_then(|path| nixos_version(path, &host))
|
||||
.map(|version| format!("NixOS {version}"))
|
||||
.or_else(|| {
|
||||
OS_RELEASES
|
||||
.iter()
|
||||
.find_map(|path| read_to_string(path).ok())
|
||||
.and_then(|release| pretty_name(&release))
|
||||
});
|
||||
let generation =
|
||||
system_path.and_then(|path| generation_of(Path::new(path), &system_links()));
|
||||
Self {
|
||||
kernel: format!("Linux {}", names.release().to_string_lossy()),
|
||||
host,
|
||||
system,
|
||||
generation,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn parts(&self) -> Vec<String> {
|
||||
once(self.host.clone())
|
||||
.chain(self.system.clone())
|
||||
.chain(
|
||||
self.generation
|
||||
.as_ref()
|
||||
.map(|generation| format!("generation {generation}")),
|
||||
)
|
||||
.chain(once(self.kernel.clone()))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn init_system(command_line: &str) -> Option<&str> {
|
||||
command_line
|
||||
.split_whitespace()
|
||||
.find_map(|argument| argument.strip_prefix("init="))
|
||||
.and_then(|init| init.strip_suffix("/init"))
|
||||
}
|
||||
|
||||
fn nixos_version<'a>(system_path: &'a str, host: &str) -> Option<&'a str> {
|
||||
let (_, name) = system_path.rsplit_once('/')?;
|
||||
let (_, rest) = name.split_once('-')?;
|
||||
rest.strip_prefix(NIXOS_SYSTEM)?
|
||||
.strip_prefix(host)?
|
||||
.strip_prefix('-')
|
||||
}
|
||||
|
||||
fn pretty_name(os_release: &str) -> Option<String> {
|
||||
os_release
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("PRETTY_NAME="))
|
||||
.map(|value| value.trim_matches('"').to_owned())
|
||||
}
|
||||
|
||||
struct SystemLink {
|
||||
generation: String,
|
||||
target: PathBuf,
|
||||
}
|
||||
|
||||
fn system_links() -> Vec<SystemLink> {
|
||||
read_dir(SYSTEM_PROFILES)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Result::ok)
|
||||
.filter_map(|entry| {
|
||||
let name = entry.file_name().into_string().ok()?;
|
||||
let generation = name.strip_prefix("system-")?.strip_suffix("-link")?;
|
||||
Some(SystemLink {
|
||||
generation: generation.to_owned(),
|
||||
target: read_link(entry.path()).ok()?,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn generation_of(system_path: &Path, links: &[SystemLink]) -> Option<String> {
|
||||
links
|
||||
.iter()
|
||||
.find(|link| link.target == system_path)
|
||||
.map(|link| link.generation.clone())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const COMMAND_LINE: &str = "initrd=\\EFI\\nixos\\x-initrd.efi \
|
||||
init=/nix/store/\
|
||||
av1146s7ayap8zgrpindi641v1fmdxsf-nixos-system-ryzen-26.11.\
|
||||
20261007.39ad350/init panic=10 root=fstab";
|
||||
|
||||
#[test]
|
||||
fn the_nixos_version_comes_from_the_init_on_the_command_line() {
|
||||
let system = init_system(COMMAND_LINE).expect("init system");
|
||||
assert_eq!(
|
||||
nixos_version(system, "ryzen"),
|
||||
Some("26.11.20261007.39ad350")
|
||||
);
|
||||
assert_eq!(nixos_version(system, "other-host"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_generation_is_the_profile_link_to_the_booted_system() {
|
||||
let system = init_system(COMMAND_LINE).expect("init system");
|
||||
let links = [
|
||||
SystemLink {
|
||||
generation: "2770".to_owned(),
|
||||
target: "/nix/store/x43q-nixos-system-ryzen-26.11".into(),
|
||||
},
|
||||
SystemLink {
|
||||
generation: "2771".to_owned(),
|
||||
target: system.into(),
|
||||
},
|
||||
];
|
||||
assert_eq!(
|
||||
generation_of(Path::new(system), &links),
|
||||
Some("2771".to_owned())
|
||||
);
|
||||
assert_eq!(generation_of(Path::new(system), &links[..1]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_distributions_use_their_pretty_name() {
|
||||
assert_eq!(
|
||||
pretty_name("NAME=Arch\nPRETTY_NAME=\"Arch Linux\"\n"),
|
||||
Some("Arch Linux".to_owned())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_parts_are_left_out() {
|
||||
let origin = BootOrigin {
|
||||
host: "ryzen".to_owned(),
|
||||
system: Some("NixOS 26.11".to_owned()),
|
||||
generation: None,
|
||||
kernel: "Linux 7.2.9".to_owned(),
|
||||
};
|
||||
assert_eq!(origin.parts(), ["ryzen", "NixOS 26.11", "Linux 7.2.9"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
use std::{collections::HashMap, time::Duration};
|
||||
|
||||
use super::{
|
||||
ActiveState, Activity, BootState, FailedUnit, FailureCause, FailureExplanation, FailureKind,
|
||||
FinishedRun, FinishedStage, HANDOFF_UNIT, HOST_MILESTONES, JobKind, JobResult, Outcome,
|
||||
PendingJob, Phase, Progress, Root, SHUTDOWN_MILESTONES, Tally, UnitFacts, UnitKind, UnitRecord,
|
||||
unit_facts::display_label,
|
||||
};
|
||||
|
||||
impl UnitRecord {
|
||||
fn transition_started(&self, kind: JobKind) -> Option<Duration> {
|
||||
match kind {
|
||||
JobKind::TakesDown => self.activity.active_exit,
|
||||
JobKind::BringsUp | JobKind::Unknown => self.activity.inactive_exit,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn running_since(&self) -> Option<Duration> {
|
||||
let Progress::Pending(job) = self.progress else {
|
||||
return None;
|
||||
};
|
||||
let transitioning = matches!(
|
||||
self.activity.state,
|
||||
Some(ActiveState::Activating | ActiveState::Deactivating | ActiveState::Reloading)
|
||||
);
|
||||
transitioning.then(|| self.transition_started(job.kind).unwrap_or(job.queued_at))
|
||||
}
|
||||
|
||||
pub(super) fn deadline(&self) -> Option<Duration> {
|
||||
let Progress::Pending(job) = self.progress else {
|
||||
return None;
|
||||
};
|
||||
let since = self.running_since()?;
|
||||
let timeouts = self.facts.timeouts;
|
||||
let transition = match job.kind {
|
||||
JobKind::TakesDown => timeouts.stop,
|
||||
JobKind::BringsUp | JobKind::Unknown => timeouts.start,
|
||||
};
|
||||
[
|
||||
transition.map(|limit| since + limit),
|
||||
timeouts.job_running.map(|limit| since + limit),
|
||||
timeouts.job.map(|limit| job.queued_at + limit),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.min()
|
||||
}
|
||||
|
||||
fn is_finished(&self) -> bool {
|
||||
matches!(self.progress, Progress::Finished(_))
|
||||
}
|
||||
|
||||
pub(super) fn takes_down(&self) -> bool {
|
||||
matches!(
|
||||
self.progress,
|
||||
Progress::Pending(PendingJob {
|
||||
kind: JobKind::TakesDown,
|
||||
..
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl BootState {
|
||||
#[must_use]
|
||||
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::Shutdown => (
|
||||
SHUTDOWN_MILESTONES
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect(),
|
||||
None,
|
||||
),
|
||||
Phase::User => (Vec::new(), None),
|
||||
};
|
||||
Self {
|
||||
phase,
|
||||
origin: Duration::ZERO,
|
||||
root: Root::Unresolved,
|
||||
failed: Vec::new(),
|
||||
finished_stages: Vec::new(),
|
||||
finished_runs: Vec::new(),
|
||||
handoff_unit,
|
||||
manager_exited_at: None,
|
||||
milestone_targets,
|
||||
boot_finished: false,
|
||||
units: HashMap::new(),
|
||||
jobs: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_root(&mut self, root: String) {
|
||||
if self.phase == Phase::User && !self.milestone_targets.contains(&root) {
|
||||
self.milestone_targets.push(root.clone());
|
||||
}
|
||||
if self.root.unit() != Some(&root) {
|
||||
self.root = Root::Awaiting(root);
|
||||
}
|
||||
}
|
||||
|
||||
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(),
|
||||
activity: Activity::default(),
|
||||
progress: Progress::Untouched,
|
||||
});
|
||||
record.facts = facts;
|
||||
record.activity = record.activity.merge(activity);
|
||||
}
|
||||
|
||||
pub fn update_activity(&mut self, unit: &str, activity: Activity) {
|
||||
let Some(record) = self.units.get_mut(unit) else {
|
||||
return;
|
||||
};
|
||||
record.activity = record.activity.merge(activity);
|
||||
if activity.state == Some(ActiveState::Failed) {
|
||||
let label = display_label(&record.facts);
|
||||
self.record_failure(unit, label, FailureKind::Broke);
|
||||
}
|
||||
}
|
||||
|
||||
fn record_failure(&mut self, unit: &str, label: String, kind: FailureKind) {
|
||||
match self.failed.iter_mut().find(|failed| failed.unit == unit) {
|
||||
Some(known) if kind != FailureKind::Broke => known.kind = kind,
|
||||
Some(_) => {}
|
||||
None => self.failed.push(FailedUnit {
|
||||
unit: unit.to_owned(),
|
||||
label,
|
||||
kind,
|
||||
explanation: FailureExplanation::Unexplained,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn explain_failure(&mut self, unit: &str, cause: FailureCause) {
|
||||
if let Some(failed) = self.failed.iter_mut().find(|failed| failed.unit == unit) {
|
||||
failed.explanation = FailureExplanation::Explained(cause);
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn has_failed(&self, unit: &str) -> bool {
|
||||
self.failed.iter().any(|failed| failed.unit == unit)
|
||||
}
|
||||
|
||||
pub fn queue_job(&mut self, id: u32, unit: &str, kind: JobKind, at: Duration) {
|
||||
if self.enqueue(id, unit, kind, at)
|
||||
&& kind == JobKind::BringsUp
|
||||
&& self.root == Root::Awaiting(unit.to_owned())
|
||||
{
|
||||
self.root = Root::Queued(unit.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
fn enqueue(&mut self, id: u32, unit: &str, kind: JobKind, at: Duration) -> bool {
|
||||
if let Some(tracked) = self.jobs.get(&id) {
|
||||
return tracked == unit;
|
||||
}
|
||||
let Some(record) = self.units.get_mut(unit) else {
|
||||
return false;
|
||||
};
|
||||
record.progress = Progress::Pending(PendingJob {
|
||||
id,
|
||||
queued_at: at,
|
||||
kind,
|
||||
});
|
||||
self.jobs.insert(id, unit.to_owned());
|
||||
true
|
||||
}
|
||||
|
||||
pub fn finish_job(&mut self, id: u32, result: JobResult, at: Duration) {
|
||||
let Some(unit) = self.jobs.remove(&id) else {
|
||||
return;
|
||||
};
|
||||
let Some(label) = self
|
||||
.units
|
||||
.get(&unit)
|
||||
.map(|record| display_label(&record.facts))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let outcome = match result {
|
||||
JobResult::Done => Outcome::Succeeded { at },
|
||||
JobResult::Skipped | JobResult::Canceled => Outcome::Abandoned,
|
||||
JobResult::Failed => Outcome::Failed(FailureKind::Broke),
|
||||
JobResult::Timeout => Outcome::Failed(FailureKind::TimedOut),
|
||||
JobResult::Dependency => Outcome::Failed(FailureKind::DependencyFailed),
|
||||
};
|
||||
if let Outcome::Failed(kind) = outcome {
|
||||
self.record_failure(&unit, label.clone(), kind);
|
||||
}
|
||||
let Some(record) = self.units.get_mut(&unit) else {
|
||||
return;
|
||||
};
|
||||
let job = match record.progress {
|
||||
Progress::Pending(job) if job.id == id => job,
|
||||
_ => return,
|
||||
};
|
||||
record.progress = Progress::Finished(outcome);
|
||||
if let Some(started_at) = record
|
||||
.transition_started(job.kind)
|
||||
.filter(|started| job.kind != JobKind::Unknown && (self.origin..=at).contains(started))
|
||||
&& UnitKind::of(&record.facts.name) != UnitKind::Target
|
||||
{
|
||||
self.finished_runs.push(FinishedRun {
|
||||
label,
|
||||
started_at,
|
||||
finished_at: at,
|
||||
failed: matches!(outcome, Outcome::Failed(_)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub fn switch_root(&mut self, at: Duration) {
|
||||
let finished_here = self
|
||||
.units
|
||||
.values()
|
||||
.filter(|record| record.is_finished())
|
||||
.count();
|
||||
self.finished_stages.push(FinishedStage {
|
||||
label: Phase::Initrd.label(),
|
||||
finished_units: finished_here,
|
||||
failed_units: self
|
||||
.units
|
||||
.values()
|
||||
.filter(|record| matches!(record.progress, Progress::Finished(Outcome::Failed(_))))
|
||||
.count(),
|
||||
started_at: self.origin,
|
||||
reached_at: at,
|
||||
});
|
||||
self.phase = Phase::Host;
|
||||
self.root = Root::Unresolved;
|
||||
self.units.clear();
|
||||
self.jobs.clear();
|
||||
}
|
||||
|
||||
pub fn forget_jobs(&mut self) {
|
||||
self.jobs.clear();
|
||||
self.units
|
||||
.values_mut()
|
||||
.filter(|record| matches!(record.progress, Progress::Pending(_)))
|
||||
.for_each(|record| record.progress = Progress::Untouched);
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn is_complete(&self) -> bool {
|
||||
if matches!(self.phase, Phase::Initrd | Phase::Shutdown) {
|
||||
return false;
|
||||
}
|
||||
if self.boot_finished {
|
||||
return true;
|
||||
}
|
||||
let Root::Queued(root) = &self.root else {
|
||||
return false;
|
||||
};
|
||||
self.units.get(root).is_some_and(UnitRecord::is_finished)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn started_display_manager(&self) -> Option<&str> {
|
||||
self.handoff_unit.as_deref().filter(|unit| {
|
||||
self.units
|
||||
.get(*unit)
|
||||
.and_then(|handoff| handoff.activity.state)
|
||||
.is_some_and(|state| state != ActiveState::Inactive)
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn tally(&self) -> Tally {
|
||||
let carried = Tally {
|
||||
done: self
|
||||
.finished_stages
|
||||
.iter()
|
||||
.map(|stage| stage.finished_units)
|
||||
.sum::<usize>(),
|
||||
failed: self.failed.len(),
|
||||
..Tally::default()
|
||||
};
|
||||
self.units.values().fold(carried, |mut tally, record| {
|
||||
match record.progress {
|
||||
Progress::Pending(_) if record.running_since().is_some() => tally.running += 1,
|
||||
Progress::Pending(_) => tally.waiting += 1,
|
||||
Progress::Finished(Outcome::Succeeded { .. } | Outcome::Abandoned) => {
|
||||
tally.done += 1;
|
||||
}
|
||||
Progress::Finished(Outcome::Failed(_)) | Progress::Untouched => {}
|
||||
}
|
||||
tally
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
boot_model::{BootChange, RowStatus, UnitTimeouts},
|
||||
boot_test_fixtures::{
|
||||
MS, activating, facts, nested_boot_sample as sample, queue_unit, queued_boot, running,
|
||||
waiting, waiting_rows,
|
||||
},
|
||||
};
|
||||
|
||||
fn failure_kinds(state: &BootState) -> Vec<(&str, FailureKind)> {
|
||||
state
|
||||
.failed
|
||||
.iter()
|
||||
.map(|failed| (failed.unit.as_str(), failed.kind))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn job_results_keep_their_failure_kind() {
|
||||
let mut state = sample();
|
||||
state.finish_job(4, JobResult::Timeout, 2000 * MS);
|
||||
state.finish_job(3, JobResult::Dependency, 2000 * MS);
|
||||
assert_eq!(
|
||||
failure_kinds(&state),
|
||||
[
|
||||
("nm.service", FailureKind::TimedOut),
|
||||
("nm-wait.service", FailureKind::DependencyFailed),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_unit_entering_the_failed_state_counts_without_a_failed_job() {
|
||||
let mut state = sample();
|
||||
state.update_activity(
|
||||
"nm.service",
|
||||
Activity {
|
||||
state: Some(ActiveState::Failed),
|
||||
..Activity::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(failure_kinds(&state), [("nm.service", FailureKind::Broke)]);
|
||||
state.finish_job(4, JobResult::Timeout, 2000 * MS);
|
||||
assert_eq!(
|
||||
failure_kinds(&state),
|
||||
[("nm.service", FailureKind::TimedOut)]
|
||||
);
|
||||
assert_eq!(state.tally().failed, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explanation_attaches_to_its_failed_unit() {
|
||||
let mut state = sample();
|
||||
let cause = FailureCause {
|
||||
reason: "exited with status 1".to_owned(),
|
||||
log_lines: vec!["no carrier".to_owned()],
|
||||
};
|
||||
state.explain_failure("nm.service", cause.clone());
|
||||
assert!(state.failed.is_empty());
|
||||
state.finish_job(4, JobResult::Failed, 2000 * MS);
|
||||
state.explain_failure("nm.service", cause.clone());
|
||||
assert_eq!(
|
||||
state.failed[0].explanation,
|
||||
FailureExplanation::Explained(cause)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failures_are_listed_and_not_counted_as_done() {
|
||||
let mut state = sample();
|
||||
state.finish_job(4, JobResult::Failed, 2000 * MS);
|
||||
assert_eq!(
|
||||
state
|
||||
.failed
|
||||
.iter()
|
||||
.map(|failed| failed.label.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["nm"]
|
||||
);
|
||||
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, 5000 * MS));
|
||||
assert!(state.is_complete());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconnecting_keeps_the_boot_running() {
|
||||
let mut state = sample();
|
||||
state.forget_jobs();
|
||||
assert!(!state.is_complete());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconnecting_keeps_the_finished_units() {
|
||||
let mut state = sample();
|
||||
state.finish_job(7, JobResult::Done, 2000 * MS);
|
||||
let tally = state.tally();
|
||||
let milestones = state.milestones();
|
||||
state.forget_jobs();
|
||||
assert_eq!(state.tally().done, tally.done);
|
||||
assert_eq!(state.milestones(), milestones);
|
||||
assert!(!milestones.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boot_completes_once_the_requeued_root_job_is_gone() {
|
||||
let mut state = sample();
|
||||
state.forget_jobs();
|
||||
state.queue_job(20, "graphical.target", JobKind::BringsUp, 6000 * MS);
|
||||
assert!(!state.is_complete());
|
||||
state.finish_job(20, JobResult::Done, 7000 * MS);
|
||||
assert!(state.is_complete());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_manager_activation_does_not_complete_the_boot() {
|
||||
let mut state = sample();
|
||||
queue_unit(&mut state, 20, waiting(HANDOFF_UNIT, &[]), 500 * MS);
|
||||
assert_eq!(state.started_display_manager(), None);
|
||||
state.update_activity(HANDOFF_UNIT, activating(6000 * MS));
|
||||
assert!(!state.is_complete());
|
||||
assert_eq!(state.started_display_manager(), Some(HANDOFF_UNIT));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boot_finished_hands_the_console_over() {
|
||||
let mut state = sample();
|
||||
queue_unit(&mut state, 20, waiting(HANDOFF_UNIT, &[]), 500 * MS);
|
||||
state.apply(BootChange::BootFinished);
|
||||
assert!(state.is_complete());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boot_finished_is_ignored_in_the_initrd() {
|
||||
let mut state = BootState::new(Phase::Initrd);
|
||||
state.apply(BootChange::BootFinished);
|
||||
assert!(!state.is_complete());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_root_freezes_the_initrd_summary() {
|
||||
let mut state = queued_boot(
|
||||
Phase::Initrd,
|
||||
Duration::ZERO,
|
||||
[waiting("initrd.target", &[]), waiting("sysroot.mount", &[])],
|
||||
);
|
||||
state.finish_job(2, JobResult::Done, 1000 * MS);
|
||||
state.finish_job(1, JobResult::Done, 1500 * MS);
|
||||
assert!(!state.is_complete());
|
||||
state.switch_root(2000 * MS);
|
||||
assert_eq!(state.phase, Phase::Host);
|
||||
assert_eq!(
|
||||
state.finished_stages,
|
||||
[FinishedStage {
|
||||
label: "Initrd",
|
||||
finished_units: 2,
|
||||
failed_units: 0,
|
||||
started_at: Duration::ZERO,
|
||||
reached_at: 2000 * MS,
|
||||
}]
|
||||
);
|
||||
assert_eq!(state.milestones()[0].reached_at, 2000 * MS);
|
||||
assert_eq!(state.tally().done, 2);
|
||||
assert!(waiting_rows(&state).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopped_units_join_the_timeline_from_when_they_began_stopping() {
|
||||
let mut state = BootState::new(Phase::Shutdown);
|
||||
state.origin = 1000 * MS;
|
||||
state.track_unit(facts("db.service", &[]), Activity::default());
|
||||
state.queue_job(1, "db.service", JobKind::TakesDown, 1000 * MS);
|
||||
state.update_activity(
|
||||
"db.service",
|
||||
Activity {
|
||||
state: Some(ActiveState::Deactivating),
|
||||
active_exit: Some(1200 * MS),
|
||||
..Activity::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(
|
||||
waiting_rows(&state)[0].status,
|
||||
RowStatus::Running {
|
||||
queued_at: 1000 * MS,
|
||||
since: 1200 * MS,
|
||||
deadline: None,
|
||||
}
|
||||
);
|
||||
state.finish_job(1, JobResult::Done, 1700 * MS);
|
||||
assert_eq!(
|
||||
state.finished_runs,
|
||||
[FinishedRun {
|
||||
label: "db".to_owned(),
|
||||
started_at: 1200 * MS,
|
||||
finished_at: 1700 * MS,
|
||||
failed: false,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
fn deadline_of(state: &BootState) -> Option<Duration> {
|
||||
match waiting_rows(state)[0].status {
|
||||
RowStatus::Running { deadline, .. } => deadline,
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_earliest_timer_sets_the_deadline() {
|
||||
let state = queued_boot(
|
||||
Phase::Host,
|
||||
1000 * MS,
|
||||
[
|
||||
running("web.service", &[], 3000 * MS).timing_out(UnitTimeouts {
|
||||
start: Some(90_000 * MS),
|
||||
job: Some(10_000 * MS),
|
||||
..UnitTimeouts::default()
|
||||
}),
|
||||
],
|
||||
);
|
||||
assert_eq!(deadline_of(&state), Some(11_000 * MS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopping_units_run_against_the_stop_timeout() {
|
||||
let mut state = queued_boot(
|
||||
Phase::Shutdown,
|
||||
Duration::ZERO,
|
||||
[waiting("db.service", &[])
|
||||
.stopping()
|
||||
.timing_out(UnitTimeouts {
|
||||
start: Some(5000 * MS),
|
||||
stop: Some(90_000 * MS),
|
||||
..UnitTimeouts::default()
|
||||
})],
|
||||
);
|
||||
assert_eq!(deadline_of(&state), None);
|
||||
state.update_activity(
|
||||
"db.service",
|
||||
Activity {
|
||||
state: Some(ActiveState::Deactivating),
|
||||
active_exit: Some(2000 * MS),
|
||||
..Activity::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(deadline_of(&state), Some(92_000 * MS));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use super::{ActiveState, BootState, Outcome, Progress};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct MilestoneRow {
|
||||
pub label: String,
|
||||
pub finished_units: usize,
|
||||
pub started_at: Duration,
|
||||
pub reached_at: Duration,
|
||||
}
|
||||
|
||||
struct MilestoneCursor {
|
||||
previous: Duration,
|
||||
consumed: usize,
|
||||
}
|
||||
|
||||
impl BootState {
|
||||
fn milestone_reached_at(&self, target: &str) -> Option<Duration> {
|
||||
let record = self.units.get(target)?;
|
||||
match record.progress {
|
||||
Progress::Finished(Outcome::Succeeded { at }) => Some(at),
|
||||
Progress::Untouched => record.activity.active_enter.filter(|entered| {
|
||||
record.activity.state == Some(ActiveState::Active) && *entered >= self.origin
|
||||
}),
|
||||
Progress::Pending(_) | Progress::Finished(Outcome::Failed(_) | Outcome::Abandoned) => {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn milestones(&self) -> Vec<MilestoneRow> {
|
||||
let mut succeeded: Vec<Duration> = self
|
||||
.units
|
||||
.values()
|
||||
.filter_map(|record| match record.progress {
|
||||
Progress::Finished(Outcome::Succeeded { at }) => Some(at),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
succeeded.sort_unstable();
|
||||
let start = MilestoneCursor {
|
||||
previous: self
|
||||
.finished_stages
|
||||
.last()
|
||||
.map_or(self.origin, |stage| stage.reached_at),
|
||||
consumed: 0,
|
||||
};
|
||||
let reached_rows = self
|
||||
.milestone_targets
|
||||
.iter()
|
||||
.scan(start, |cursor, target| {
|
||||
Some(self.milestone_reached_at(target).map(|reached_at| {
|
||||
let upto = succeeded.partition_point(|at| *at <= reached_at);
|
||||
let row = MilestoneRow {
|
||||
label: target.clone(),
|
||||
finished_units: upto.saturating_sub(cursor.consumed),
|
||||
started_at: cursor.previous.min(reached_at),
|
||||
reached_at,
|
||||
};
|
||||
cursor.consumed = cursor.consumed.max(upto);
|
||||
cursor.previous = reached_at;
|
||||
row
|
||||
}))
|
||||
})
|
||||
.flatten();
|
||||
self.finished_stages
|
||||
.iter()
|
||||
.map(|stage| MilestoneRow {
|
||||
label: stage.label.to_owned(),
|
||||
finished_units: stage.finished_units,
|
||||
started_at: stage.started_at,
|
||||
reached_at: stage.reached_at,
|
||||
})
|
||||
.chain(reached_rows)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
boot_model::{Activity, JobResult, Phase},
|
||||
boot_test_fixtures::{MS, nested_boot_sample, queued_boot, waiting, waiting_rows},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn finished_jobs_leave_the_tree_and_count_toward_their_milestone() {
|
||||
let mut state = nested_boot_sample();
|
||||
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(4000 * MS),
|
||||
active_exit: None,
|
||||
},
|
||||
);
|
||||
assert!(
|
||||
waiting_rows(&state)
|
||||
.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 shutdown_counts_toward_its_own_milestones_and_never_completes() {
|
||||
let mut state = queued_boot(
|
||||
Phase::Shutdown,
|
||||
Duration::ZERO,
|
||||
[
|
||||
waiting("poweroff.target", &[]),
|
||||
waiting("shutdown.target", &[]),
|
||||
waiting("db.service", &[]).stopping(),
|
||||
],
|
||||
);
|
||||
state.finish_job(3, JobResult::Done, 500 * MS);
|
||||
state.finish_job(2, JobResult::Done, 600 * MS);
|
||||
state.finish_job(1, JobResult::Done, 700 * MS);
|
||||
let milestones = state.milestones();
|
||||
assert_eq!(milestones[0].label, "shutdown.target");
|
||||
assert_eq!(milestones[0].finished_units, 2);
|
||||
assert!(!state.is_complete());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ActiveState {
|
||||
Activating,
|
||||
Active,
|
||||
Deactivating,
|
||||
Reloading,
|
||||
Failed,
|
||||
#[serde(other)]
|
||||
Inactive,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum JobResult {
|
||||
Done,
|
||||
Skipped,
|
||||
Canceled,
|
||||
Timeout,
|
||||
Dependency,
|
||||
#[serde(other)]
|
||||
Failed,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct UnitTimeouts {
|
||||
pub start: Option<Duration>,
|
||||
pub stop: Option<Duration>,
|
||||
pub job: Option<Duration>,
|
||||
pub job_running: Option<Duration>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct UnitFacts {
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub after: Vec<String>,
|
||||
pub before: Vec<String>,
|
||||
pub timeouts: UnitTimeouts,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Activity {
|
||||
pub state: Option<ActiveState>,
|
||||
pub inactive_exit: Option<Duration>,
|
||||
pub active_enter: Option<Duration>,
|
||||
pub active_exit: Option<Duration>,
|
||||
}
|
||||
|
||||
impl Activity {
|
||||
pub(super) fn merge(self, newer: Self) -> Self {
|
||||
Self {
|
||||
state: newer.state.or(self.state),
|
||||
inactive_exit: newer.inactive_exit.or(self.inactive_exit),
|
||||
active_enter: newer.active_enter.or(self.active_enter),
|
||||
active_exit: newer.active_exit.or(self.active_exit),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
|
||||
pub enum JobKind {
|
||||
#[serde(rename = "stop")]
|
||||
TakesDown,
|
||||
#[serde(skip)]
|
||||
Unknown,
|
||||
#[serde(other)]
|
||||
BringsUp,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum UnitKind {
|
||||
Service,
|
||||
Target,
|
||||
Socket,
|
||||
Mount,
|
||||
Automount,
|
||||
Device,
|
||||
Swap,
|
||||
Path,
|
||||
Timer,
|
||||
Slice,
|
||||
Scope,
|
||||
#[serde(other)]
|
||||
Other,
|
||||
}
|
||||
|
||||
impl UnitKind {
|
||||
#[must_use]
|
||||
pub fn of(name: &str) -> Self {
|
||||
name.rsplit_once('.')
|
||||
.and_then(|(_, suffix)| serde_plain::from_str(suffix).ok())
|
||||
.unwrap_or(Self::Other)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn tag(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::Service | Self::Target | Self::Other => None,
|
||||
Self::Socket => Some("Socket"),
|
||||
Self::Mount => Some("Mount"),
|
||||
Self::Automount => Some("Automount"),
|
||||
Self::Device => Some("Device"),
|
||||
Self::Swap => Some("Swap"),
|
||||
Self::Path => Some("Path"),
|
||||
Self::Timer => Some("Timer"),
|
||||
Self::Slice => Some("Slice"),
|
||||
Self::Scope => Some("Scope"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn description_label(facts: &UnitFacts) -> Option<&String> {
|
||||
facts.description.as_ref().filter(|_| {
|
||||
matches!(
|
||||
UnitKind::of(&facts.name),
|
||||
UnitKind::Device | UnitKind::Mount | UnitKind::Swap | UnitKind::Automount
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn display_label(facts: &UnitFacts) -> String {
|
||||
if let Some(description) = description_label(facts) {
|
||||
return description.clone();
|
||||
}
|
||||
match UnitKind::of(&facts.name) {
|
||||
UnitKind::Target | UnitKind::Other => facts.name.clone(),
|
||||
_ => facts
|
||||
.name
|
||||
.rsplit_once('.')
|
||||
.map_or_else(|| facts.name.clone(), |(stem, _)| stem.to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn summary(facts: &UnitFacts) -> Option<String> {
|
||||
let repeats_the_name = facts.description.as_deref().is_some_and(|description| {
|
||||
description == facts.name || description.eq_ignore_ascii_case(&display_label(facts))
|
||||
});
|
||||
if description_label(facts).is_some() || repeats_the_name {
|
||||
return None;
|
||||
}
|
||||
facts.description.clone()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_plain::from_str;
|
||||
|
||||
use super::*;
|
||||
use crate::boot_test_fixtures::{facts, waiting};
|
||||
|
||||
#[test]
|
||||
fn unknown_systemd_strings_fall_back_instead_of_failing() {
|
||||
assert_eq!(
|
||||
from_str("deactivating").ok(),
|
||||
Some(ActiveState::Deactivating)
|
||||
);
|
||||
assert_eq!(from_str("maintenance").ok(), Some(ActiveState::Inactive));
|
||||
assert_eq!(from_str("dependency").ok(), Some(JobResult::Dependency));
|
||||
assert_eq!(from_str("frozen").ok(), Some(JobResult::Failed));
|
||||
assert_eq!(from_str("stop").ok(), Some(JobKind::TakesDown));
|
||||
assert_eq!(from_str("restart").ok(), Some(JobKind::BringsUp));
|
||||
assert_eq!(UnitKind::of("dev-sda.swap"), UnitKind::Swap);
|
||||
assert_eq!(UnitKind::of("init.scope.d"), UnitKind::Other);
|
||||
assert_eq!(UnitKind::of("no-suffix"), UnitKind::Other);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kinds_with_a_tag_drop_their_suffix() {
|
||||
let socket = facts("docker.socket", &[]);
|
||||
assert_eq!(UnitKind::of(&socket.name), UnitKind::Socket);
|
||||
assert_eq!(UnitKind::Socket.tag(), Some("Socket"));
|
||||
assert_eq!(display_label(&socket), "docker");
|
||||
assert_eq!(display_label(&facts("sshd.service", &[])), "sshd");
|
||||
assert_eq!(display_label(&facts("basic.target", &[])), "basic.target");
|
||||
assert_eq!(UnitKind::Target.tag(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn descriptions_that_repeat_the_label_are_dropped() {
|
||||
let described = |name: &str, description: &str| {
|
||||
summary(&waiting(name, &[]).described(description).facts)
|
||||
};
|
||||
assert_eq!(
|
||||
described("multi-user.target", "Multi-User System"),
|
||||
Some("Multi-User System".to_owned())
|
||||
);
|
||||
assert_eq!(described("greetd.service", "greetd.service"), None);
|
||||
assert_eq!(described("greetd.service", "Greetd"), None);
|
||||
assert_eq!(described("dev-sda.device", "Samsung SSD"), None);
|
||||
assert_eq!(described("demo.service", ""), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
use std::{collections::HashSet, time::Duration};
|
||||
|
||||
use petgraph::{
|
||||
Direction::Incoming,
|
||||
graphmap::DiGraphMap,
|
||||
visit::{Dfs, Walker},
|
||||
};
|
||||
|
||||
use super::{
|
||||
BootState, FailureKind, Outcome, Phase, Progress, UnitKind, UnitRecord,
|
||||
unit_facts::{display_label, summary},
|
||||
};
|
||||
|
||||
type WaitingGraph<'a> = DiGraphMap<&'a str, ()>;
|
||||
|
||||
struct WaitingEdge<'a> {
|
||||
waiter: &'a str,
|
||||
dependency: &'a str,
|
||||
}
|
||||
|
||||
struct ReachableSibling<'a> {
|
||||
unit: &'a str,
|
||||
reaches: HashSet<&'a str>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RowStatus {
|
||||
Waiting,
|
||||
Running {
|
||||
queued_at: Duration,
|
||||
since: Duration,
|
||||
deadline: Option<Duration>,
|
||||
},
|
||||
Failed(FailureKind),
|
||||
Done,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct TreeRow {
|
||||
pub depth: usize,
|
||||
pub label: String,
|
||||
pub description: Option<String>,
|
||||
pub kind: UnitKind,
|
||||
pub status: RowStatus,
|
||||
pub chain: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TreeNode {
|
||||
pub row: TreeRow,
|
||||
pub children: Vec<TreeNode>,
|
||||
}
|
||||
|
||||
impl TreeNode {
|
||||
fn flatten_into(self, depth: usize, rows: &mut Vec<TreeRow>) {
|
||||
rows.push(TreeRow { depth, ..self.row });
|
||||
self.children
|
||||
.into_iter()
|
||||
.for_each(|child| child.flatten_into(depth + 1, rows));
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn flatten_forest(forest: Vec<TreeNode>) -> Vec<TreeRow> {
|
||||
let mut rows = Vec::new();
|
||||
forest
|
||||
.into_iter()
|
||||
.for_each(|root| root.flatten_into(0, &mut rows));
|
||||
rows
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum SiblingRank {
|
||||
RunningSince(Duration),
|
||||
Failed,
|
||||
Waiting,
|
||||
}
|
||||
|
||||
impl UnitRecord {
|
||||
fn row_status(&self) -> RowStatus {
|
||||
match self.progress {
|
||||
Progress::Pending(job) => {
|
||||
self.running_since()
|
||||
.map_or(RowStatus::Waiting, |since| RowStatus::Running {
|
||||
queued_at: job.queued_at,
|
||||
since,
|
||||
deadline: self.deadline(),
|
||||
})
|
||||
}
|
||||
Progress::Finished(Outcome::Failed(kind)) => RowStatus::Failed(kind),
|
||||
Progress::Finished(_) | Progress::Untouched => RowStatus::Done,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BootState {
|
||||
#[must_use]
|
||||
pub fn waiting_forest(&self, finished_since: Duration) -> Vec<TreeNode> {
|
||||
let mut graph = WaitingGraph::new();
|
||||
self.units
|
||||
.iter()
|
||||
.filter(|(name, record)| match record.progress {
|
||||
Progress::Pending(_) | Progress::Finished(Outcome::Failed(_)) => true,
|
||||
Progress::Finished(Outcome::Succeeded { at }) => {
|
||||
at >= finished_since || self.is_milestone(name)
|
||||
}
|
||||
Progress::Finished(Outcome::Abandoned) => self.is_milestone(name),
|
||||
Progress::Untouched => false,
|
||||
})
|
||||
.for_each(|(name, _)| {
|
||||
graph.add_node(name.as_str());
|
||||
});
|
||||
let edges: Vec<WaitingEdge> = graph
|
||||
.nodes()
|
||||
.flat_map(|waiter| {
|
||||
self.waits_for(waiter, &graph)
|
||||
.into_iter()
|
||||
.map(move |dependency| WaitingEdge { waiter, dependency })
|
||||
})
|
||||
.collect();
|
||||
graph.extend(edges.into_iter().map(|edge| (edge.waiter, edge.dependency)));
|
||||
let root = self.root.unit().filter(|root| graph.contains_node(root));
|
||||
let stages: Vec<&str> = self
|
||||
.milestone_targets
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.filter(|target| graph.contains_node(target))
|
||||
.chain(root.filter(|root| !self.is_milestone(root)))
|
||||
.collect();
|
||||
let mut unblocked: Vec<&str> = graph
|
||||
.nodes()
|
||||
.filter(|name| {
|
||||
graph.neighbors_directed(name, Incoming).next().is_none() && !stages.contains(name)
|
||||
})
|
||||
.collect();
|
||||
self.sort_siblings(&mut unblocked);
|
||||
let mut leftovers: Vec<&str> = graph.nodes().collect();
|
||||
self.sort_siblings(&mut leftovers);
|
||||
if self.phase == Phase::User {
|
||||
unblocked.clear();
|
||||
leftovers.clear();
|
||||
}
|
||||
let mut visited = HashSet::new();
|
||||
let mut forest = Vec::new();
|
||||
stages
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(unblocked)
|
||||
.chain(leftovers)
|
||||
.for_each(|top| {
|
||||
if visited.contains(top) {
|
||||
return;
|
||||
}
|
||||
let stage = self.grow(top, &graph, &mut visited);
|
||||
if stage.row.status != RowStatus::Done || !stage.children.is_empty() {
|
||||
forest.push(stage);
|
||||
}
|
||||
});
|
||||
forest
|
||||
}
|
||||
|
||||
fn grow<'a>(
|
||||
&'a self,
|
||||
unit: &'a str,
|
||||
graph: &WaitingGraph<'a>,
|
||||
visited: &mut HashSet<&'a str>,
|
||||
) -> TreeNode {
|
||||
visited.insert(unit);
|
||||
let record = &self.units[unit];
|
||||
let row = TreeRow {
|
||||
depth: 0,
|
||||
label: display_label(&record.facts),
|
||||
description: summary(&record.facts),
|
||||
kind: UnitKind::of(&record.facts.name),
|
||||
status: record.row_status(),
|
||||
chain: Vec::new(),
|
||||
};
|
||||
let siblings: Vec<ReachableSibling> = graph
|
||||
.neighbors(unit)
|
||||
.filter(|dependency| !visited.contains(dependency) && !self.is_milestone(dependency))
|
||||
.map(|sibling| ReachableSibling {
|
||||
unit: sibling,
|
||||
reaches: Dfs::new(graph, sibling).iter(graph).collect(),
|
||||
})
|
||||
.collect();
|
||||
let mut children: Vec<&str> = siblings
|
||||
.iter()
|
||||
.filter(|child| {
|
||||
!siblings.iter().any(|sibling| {
|
||||
sibling.unit != child.unit
|
||||
&& sibling.reaches.contains(child.unit)
|
||||
&& !child.reaches.contains(sibling.unit)
|
||||
})
|
||||
})
|
||||
.map(|child| child.unit)
|
||||
.collect();
|
||||
self.sort_siblings(&mut children);
|
||||
visited.extend(children.iter().copied());
|
||||
TreeNode {
|
||||
row,
|
||||
children: children
|
||||
.into_iter()
|
||||
.map(|child| {
|
||||
visited.remove(child);
|
||||
self.grow(child, graph, visited)
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_milestone(&self, unit: &str) -> bool {
|
||||
self.milestone_targets.iter().any(|target| target == unit)
|
||||
}
|
||||
|
||||
fn waits_for<'a>(&'a self, waiter: &str, graph: &WaitingGraph) -> Vec<&'a str> {
|
||||
let Some(record) = self.units.get(waiter) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let pending_job = |dependency: &&'a str| graph.contains_node(dependency);
|
||||
let taking_down = |dependency: &&'a str| self.units[*dependency].takes_down();
|
||||
let after = record.facts.after.iter().map(String::as_str);
|
||||
let before = record.facts.before.iter().map(String::as_str);
|
||||
if record.takes_down() {
|
||||
before.filter(pending_job).filter(taking_down).collect()
|
||||
} else {
|
||||
after
|
||||
.filter(pending_job)
|
||||
.chain(before.filter(pending_job).filter(taking_down))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn sort_siblings(&self, names: &mut [&str]) {
|
||||
let rank = |name: &str| {
|
||||
let record = &self.units[name];
|
||||
match record.progress {
|
||||
Progress::Pending(_) => record
|
||||
.running_since()
|
||||
.map_or(SiblingRank::Waiting, SiblingRank::RunningSince),
|
||||
Progress::Finished(Outcome::Succeeded { at }) => {
|
||||
SiblingRank::RunningSince(record.activity.inactive_exit.unwrap_or(at))
|
||||
}
|
||||
Progress::Finished(Outcome::Failed(_)) => SiblingRank::Failed,
|
||||
Progress::Finished(Outcome::Abandoned) | Progress::Untouched => {
|
||||
SiblingRank::Waiting
|
||||
}
|
||||
}
|
||||
};
|
||||
names.sort_by(|left, right| rank(left).cmp(&rank(right)).then_with(|| left.cmp(right)));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::boot_test_fixtures::{
|
||||
nested_boot_sample, queued_boot, tree_outline, waiting, waiting_rows,
|
||||
};
|
||||
|
||||
fn outline(state: &BootState) -> Vec<String> {
|
||||
tree_outline(&waiting_rows(state))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_units_nest_under_what_waits_on_them() {
|
||||
assert_eq!(
|
||||
outline(&nested_boot_sample()),
|
||||
[
|
||||
"basic.target",
|
||||
"multi-user.target",
|
||||
" docker",
|
||||
" containerd",
|
||||
" nm-wait",
|
||||
" nm",
|
||||
"graphical.target",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_unit_sits_in_the_earliest_stage_that_waits_on_it() {
|
||||
let state = queued_boot(
|
||||
Phase::Host,
|
||||
Duration::ZERO,
|
||||
[
|
||||
waiting(
|
||||
"multi-user.target",
|
||||
&["basic.target", "dbus.service", "web.service"],
|
||||
),
|
||||
waiting("basic.target", &["dbus.service"]),
|
||||
waiting("dbus.service", &[]),
|
||||
waiting("web.service", &[]),
|
||||
],
|
||||
);
|
||||
assert_eq!(
|
||||
outline(&state),
|
||||
["basic.target", " dbus", "multi-user.target", " web"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn devices_show_their_description() {
|
||||
let state = queued_boot(
|
||||
Phase::Host,
|
||||
Duration::ZERO,
|
||||
[waiting("dev-nvme1n1.device", &[]).described("Lexar SSD NM790 2TB")],
|
||||
);
|
||||
assert_eq!(waiting_rows(&state)[0].label, "Lexar SSD NM790 2TB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn units_nest_under_the_deepest_pending_waiter() {
|
||||
let state = queued_boot(
|
||||
Phase::Host,
|
||||
Duration::ZERO,
|
||||
[
|
||||
waiting(
|
||||
"demo.target",
|
||||
&["report.service", "web.service", "db.service"],
|
||||
),
|
||||
waiting("report.service", &["web.service"]),
|
||||
waiting("web.service", &["db.service"]),
|
||||
waiting("db.service", &[]),
|
||||
],
|
||||
);
|
||||
assert_eq!(
|
||||
outline(&state),
|
||||
["demo.target", " report", " web", " db"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopping_units_wait_on_what_was_ordered_after_them() {
|
||||
let state = queued_boot(
|
||||
Phase::Shutdown,
|
||||
Duration::ZERO,
|
||||
[
|
||||
waiting("poweroff.target", &["shutdown.target"]),
|
||||
waiting("shutdown.target", &[]).ordered_before(&["poweroff.target"]),
|
||||
waiting("network.target", &[])
|
||||
.ordered_before(&["web.service"])
|
||||
.stopping(),
|
||||
waiting("web.service", &["network.target"]).stopping(),
|
||||
],
|
||||
);
|
||||
assert_eq!(
|
||||
outline(&state),
|
||||
[
|
||||
"shutdown.target",
|
||||
"poweroff.target",
|
||||
"network.target",
|
||||
" web",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starting_units_wait_on_stops_in_either_direction() {
|
||||
let state = queued_boot(
|
||||
Phase::Shutdown,
|
||||
Duration::ZERO,
|
||||
[
|
||||
waiting("shutdown.target", &[]).ordered_before(&["db.service"]),
|
||||
waiting("db.service", &["shutdown.target"]).stopping(),
|
||||
],
|
||||
);
|
||||
assert_eq!(outline(&state), ["shutdown.target", " db"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordering_cycles_do_not_repeat_units() {
|
||||
let state = queued_boot(
|
||||
Phase::Host,
|
||||
Duration::ZERO,
|
||||
[
|
||||
waiting("a.service", &["b.service"]),
|
||||
waiting("b.service", &["a.service"]),
|
||||
],
|
||||
);
|
||||
assert_eq!(waiting_rows(&state).len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
use std::{iter::once, time::Duration};
|
||||
|
||||
use crate::boot_model::{
|
||||
ActiveState, Activity, BootState, JobKind, Phase, TreeRow, UnitFacts, UnitTimeouts,
|
||||
flatten_forest,
|
||||
};
|
||||
|
||||
pub const MS: Duration = Duration::from_millis(1);
|
||||
|
||||
pub struct QueuedUnit {
|
||||
pub facts: UnitFacts,
|
||||
pub activity: Activity,
|
||||
pub kind: JobKind,
|
||||
}
|
||||
|
||||
pub fn facts(name: &str, after: &[&str]) -> UnitFacts {
|
||||
UnitFacts {
|
||||
name: name.to_owned(),
|
||||
description: None,
|
||||
after: after.iter().map(ToString::to_string).collect(),
|
||||
before: Vec::new(),
|
||||
timeouts: UnitTimeouts::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn activating(since: Duration) -> Activity {
|
||||
Activity {
|
||||
state: Some(ActiveState::Activating),
|
||||
inactive_exit: Some(since),
|
||||
..Activity::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn waiting(name: &str, after: &[&str]) -> QueuedUnit {
|
||||
QueuedUnit {
|
||||
facts: facts(name, after),
|
||||
activity: Activity::default(),
|
||||
kind: JobKind::BringsUp,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn running(name: &str, after: &[&str], since: Duration) -> QueuedUnit {
|
||||
QueuedUnit {
|
||||
activity: activating(since),
|
||||
..waiting(name, after)
|
||||
}
|
||||
}
|
||||
|
||||
impl QueuedUnit {
|
||||
pub fn stopping(self) -> Self {
|
||||
Self {
|
||||
kind: JobKind::TakesDown,
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ordered_before(mut self, before: &[&str]) -> Self {
|
||||
self.facts.before = before.iter().map(ToString::to_string).collect();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn timing_out(mut self, timeouts: UnitTimeouts) -> Self {
|
||||
self.facts.timeouts = timeouts;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn described(mut self, description: &str) -> Self {
|
||||
self.facts.description = (!description.is_empty()).then(|| description.to_owned());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
pub fn queued_boot(
|
||||
phase: Phase,
|
||||
queued_at: Duration,
|
||||
units: impl IntoIterator<Item = QueuedUnit>,
|
||||
) -> BootState {
|
||||
let mut state = BootState::new(phase);
|
||||
units.into_iter().zip(1..).for_each(|(unit, id)| {
|
||||
if id == 1 {
|
||||
state.set_root(unit.facts.name.clone());
|
||||
}
|
||||
queue_unit(&mut state, id, unit, queued_at);
|
||||
});
|
||||
state
|
||||
}
|
||||
|
||||
pub fn nested_boot_sample() -> BootState {
|
||||
queued_boot(
|
||||
Phase::Host,
|
||||
500 * MS,
|
||||
[
|
||||
waiting("graphical.target", &["multi-user.target"]),
|
||||
waiting(
|
||||
"multi-user.target",
|
||||
&["docker.service", "nm-wait.service", "basic.target"],
|
||||
),
|
||||
waiting("nm-wait.service", &["nm.service"]),
|
||||
running("nm.service", &[], 1000 * MS),
|
||||
running("docker.service", &["containerd.service"], 3000 * MS),
|
||||
waiting("containerd.service", &[]),
|
||||
waiting("basic.target", &[]),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
pub fn queue_unit(state: &mut BootState, id: u32, unit: QueuedUnit, queued_at: Duration) {
|
||||
let name = unit.facts.name.clone();
|
||||
state.track_unit(unit.facts, unit.activity);
|
||||
state.queue_job(id, &name, unit.kind, queued_at);
|
||||
}
|
||||
|
||||
pub fn waiting_rows(state: &BootState) -> Vec<TreeRow> {
|
||||
flatten_forest(state.waiting_forest(Duration::MAX))
|
||||
}
|
||||
|
||||
pub fn tree_outline(rows: &[TreeRow]) -> Vec<String> {
|
||||
rows.iter()
|
||||
.map(|row| {
|
||||
let chain = once(row.label.as_str())
|
||||
.chain(row.chain.iter().map(String::as_str))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" > ");
|
||||
format!("{}{chain}", " ".repeat(row.depth))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
mod failure_panel;
|
||||
#[cfg(test)]
|
||||
mod frame_cost_bench;
|
||||
#[cfg(test)]
|
||||
mod panel_render_tests;
|
||||
mod run_timeline;
|
||||
mod screen_chrome;
|
||||
#[cfg(test)]
|
||||
mod screen_render_fixtures;
|
||||
mod stage_summary;
|
||||
mod tree_height_fitting;
|
||||
#[cfg(test)]
|
||||
mod tree_render_tests;
|
||||
mod unit_tree;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use jiff::fmt::friendly::{Designator, FractionalUnit, Spacing, SpanPrinter};
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
layout::{Constraint, Layout, Rect},
|
||||
style::Color,
|
||||
text::Line,
|
||||
widgets::{Block, Borders, Widget},
|
||||
};
|
||||
use unicode_truncate::UnicodeTruncateStr;
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
pub use self::screen_chrome::PasswordPrompt;
|
||||
use self::{
|
||||
failure_panel::FailurePanel,
|
||||
run_timeline::{RunningRun, Timeline},
|
||||
screen_chrome::{FOOTER_HEIGHT, Footer, Header, PasswordPopup},
|
||||
stage_summary::Stages,
|
||||
tree_height_fitting::rows_within_height,
|
||||
unit_tree::UnitTree,
|
||||
};
|
||||
use crate::{
|
||||
boot_model::{
|
||||
BootState, MilestoneRow, RowStatus, TreeNode, TreeRow, UnitKind, boot_origin::BootOrigin,
|
||||
flatten_forest,
|
||||
},
|
||||
screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs},
|
||||
};
|
||||
|
||||
const DURATION_WIDTH: u16 = 9;
|
||||
const MIN_BAR_WIDTH: u16 = 12;
|
||||
const MIN_HEIGHT_FOR_TIMELINE: u16 = 12;
|
||||
const MIN_TIMELINE_HEIGHT: u16 = run_timeline::CHROME_HEIGHT + 4;
|
||||
const HEADER_HEIGHT: u16 = 1;
|
||||
const MIN_FAILURE_PANEL_HEIGHT: u16 = failure_panel::RULE_HEIGHT + 1;
|
||||
const RESERVED_FAILURE_PANEL_HEIGHT: u16 = failure_panel::RULE_HEIGHT + 3;
|
||||
const MIN_TREE_HEIGHT_BESIDE_FAILURES: u16 = 4;
|
||||
const BRANCH: &str = "├─ ";
|
||||
const LAST_BRANCH: &str = "└─ ";
|
||||
const PASSING_TRUNK: &str = "│ ";
|
||||
const ENDED_TRUNK: &str = " ";
|
||||
|
||||
const ELAPSED: SpanPrinter = SpanPrinter::new()
|
||||
.designator(Designator::Compact)
|
||||
.spacing(Spacing::None)
|
||||
.fractional(Some(FractionalUnit::Second))
|
||||
.precision(Some(1));
|
||||
|
||||
const RUNNING_ELAPSED: SpanPrinter = ELAPSED.precision(Some(2));
|
||||
|
||||
const WHOLE_UNITS: SpanPrinter = SpanPrinter::new()
|
||||
.designator(Designator::Compact)
|
||||
.spacing(Spacing::None);
|
||||
|
||||
pub struct BootView<'a> {
|
||||
pub state: &'a BootState,
|
||||
pub projection: &'a BootProjection,
|
||||
pub colors: &'a Colors,
|
||||
pub timing: &'a Timing,
|
||||
pub glyphs: &'a Glyphs,
|
||||
pub now: Duration,
|
||||
pub origin: &'a BootOrigin,
|
||||
pub password_prompt: Option<PasswordPrompt<'a>>,
|
||||
}
|
||||
|
||||
impl BootView<'_> {
|
||||
fn failure_panel(&self) -> FailurePanel<'_> {
|
||||
FailurePanel {
|
||||
newest_first: self
|
||||
.state
|
||||
.failed
|
||||
.iter()
|
||||
.rev()
|
||||
.filter(|failed| failed.kind.has_own_cause())
|
||||
.collect(),
|
||||
colors: &self.colors.failures,
|
||||
glyphs: self.glyphs,
|
||||
}
|
||||
}
|
||||
|
||||
fn timeline<'a>(&'a self, rows: &'a [TreeRow]) -> Timeline<'a> {
|
||||
let mut running: Vec<RunningRun> = rows
|
||||
.iter()
|
||||
.filter(|row| row.kind != UnitKind::Target)
|
||||
.filter_map(|row| match row.status {
|
||||
RowStatus::Running {
|
||||
queued_at, since, ..
|
||||
} => Some(RunningRun {
|
||||
label: &row.label,
|
||||
queued_at,
|
||||
since,
|
||||
}),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
running.sort_by_key(|run| run.since);
|
||||
Timeline {
|
||||
origin: self.state.origin,
|
||||
now: self.now,
|
||||
root_switches: self
|
||||
.state
|
||||
.finished_stages
|
||||
.iter()
|
||||
.map(|stage| stage.reached_at)
|
||||
.collect(),
|
||||
milestones: &self.projection.milestones,
|
||||
finished: self
|
||||
.state
|
||||
.finished_runs
|
||||
.iter()
|
||||
.filter(|run| {
|
||||
run.finished_at.saturating_sub(run.started_at)
|
||||
>= self.timing.hide_runs_shorter_than
|
||||
})
|
||||
.collect(),
|
||||
running,
|
||||
colors: &self.colors.timeline,
|
||||
glyphs: self.glyphs,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for BootView<'_> {
|
||||
fn render(self, area: Rect, buf: &mut Buffer) {
|
||||
let forest = &self.projection.forest;
|
||||
let all_rows = flatten_forest(forest.clone());
|
||||
let pending_count = all_rows.len();
|
||||
let header = Header {
|
||||
origin: self.origin,
|
||||
total: (!self.state.finished_stages.is_empty())
|
||||
.then(|| self.now.saturating_sub(self.state.origin)),
|
||||
colors: &self.colors.header,
|
||||
};
|
||||
let stages = Stages {
|
||||
state: self.state,
|
||||
now: self.now,
|
||||
colors: &self.colors.stages,
|
||||
glyphs: self.glyphs,
|
||||
};
|
||||
let timeline = self.timeline(&all_rows);
|
||||
let failure_panel = self.failure_panel();
|
||||
let footer = Footer {
|
||||
tally: self.state.tally(),
|
||||
colors: &self.colors.footer,
|
||||
glyphs: self.glyphs,
|
||||
};
|
||||
let fits_timeline = area.width >= run_timeline::LABEL_WIDTH + 1 + MIN_BAR_WIDTH
|
||||
&& area.height >= MIN_HEIGHT_FOR_TIMELINE;
|
||||
let free = area
|
||||
.height
|
||||
.saturating_sub(HEADER_HEIGHT + stages.height() + FOOTER_HEIGHT);
|
||||
let heights = Heights::share(
|
||||
free,
|
||||
UnitTree::height_of(pending_count, 0),
|
||||
failure_panel.height(),
|
||||
if fits_timeline { timeline.height() } else { 0 },
|
||||
);
|
||||
let budget = usize::from(heights.tree.saturating_sub(1));
|
||||
let rows = rows_within_height(forest, budget);
|
||||
let tree = UnitTree {
|
||||
phase: stages.current_phase(),
|
||||
rows: &rows,
|
||||
hidden: pending_count - shown_units(&rows),
|
||||
now: self.now,
|
||||
hide_runs_shorter_than: self.timing.hide_runs_shorter_than,
|
||||
colors: &self.colors.tree,
|
||||
glyphs: self.glyphs,
|
||||
};
|
||||
let tree_height = tree.height().min(heights.tree);
|
||||
|
||||
let [
|
||||
header_area,
|
||||
stage_area,
|
||||
tree_area,
|
||||
_,
|
||||
failure_area,
|
||||
timeline_area,
|
||||
footer_area,
|
||||
] = Layout::vertical([
|
||||
Constraint::Length(HEADER_HEIGHT),
|
||||
Constraint::Length(stages.height()),
|
||||
Constraint::Length(tree_height),
|
||||
Constraint::Fill(1),
|
||||
Constraint::Length(heights.failures),
|
||||
Constraint::Length(heights.timeline),
|
||||
Constraint::Length(FOOTER_HEIGHT),
|
||||
])
|
||||
.areas(area);
|
||||
|
||||
header.render(header_area, buf);
|
||||
stages.render(stage_area, buf);
|
||||
tree.render(tree_area, buf);
|
||||
if heights.failures > 0 {
|
||||
failure_panel.render(failure_area, buf);
|
||||
}
|
||||
if heights.timeline > 0 {
|
||||
timeline.render(timeline_area, buf);
|
||||
}
|
||||
footer.render(footer_area, buf);
|
||||
if let Some(asking) = &self.password_prompt {
|
||||
PasswordPopup {
|
||||
asking,
|
||||
colors: &self.colors.password,
|
||||
glyphs: self.glyphs,
|
||||
}
|
||||
.render(area, buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Heights {
|
||||
tree: u16,
|
||||
failures: u16,
|
||||
timeline: u16,
|
||||
}
|
||||
|
||||
impl Heights {
|
||||
fn share(free: u16, tree_need: u16, failures_need: u16, timeline_need: u16) -> Self {
|
||||
let reserved = RESERVED_FAILURE_PANEL_HEIGHT
|
||||
.min(failures_need)
|
||||
.min(free.saturating_sub(MIN_TREE_HEIGHT_BESIDE_FAILURES));
|
||||
let failures = failures_need
|
||||
.min(free.saturating_sub(tree_need))
|
||||
.max(reserved);
|
||||
let failures = if failures >= MIN_FAILURE_PANEL_HEIGHT {
|
||||
failures
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let leftover = free.saturating_sub(tree_need).saturating_sub(failures);
|
||||
let timeline = if leftover >= MIN_TIMELINE_HEIGHT {
|
||||
timeline_need.min(leftover)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
Self {
|
||||
tree: free - failures - timeline,
|
||||
failures,
|
||||
timeline,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BootProjection {
|
||||
pub forest: Vec<TreeNode>,
|
||||
pub milestones: Vec<MilestoneRow>,
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn project_boot(state: &BootState, timing: &Timing, now: Duration) -> BootProjection {
|
||||
BootProjection {
|
||||
forest: state.waiting_forest(now.saturating_sub(timing.keep_finished_units_for)),
|
||||
milestones: state.milestones(),
|
||||
}
|
||||
}
|
||||
|
||||
fn rule(color: Color, left: Line<'static>) -> Block<'static> {
|
||||
Block::new()
|
||||
.borders(Borders::TOP)
|
||||
.border_style(color)
|
||||
.title(left)
|
||||
}
|
||||
|
||||
fn shown_units(rows: &[TreeRow]) -> usize {
|
||||
rows.iter().map(|row| 1 + row.chain.len()).sum()
|
||||
}
|
||||
|
||||
fn fit_width(text: &str, room: usize, ellipsis: &str) -> String {
|
||||
if text.width() <= room {
|
||||
return text.to_owned();
|
||||
}
|
||||
let (kept, _) = text.unicode_truncate(room.saturating_sub(ellipsis.width()));
|
||||
format!("{kept}{ellipsis}")
|
||||
}
|
||||
|
||||
fn unit_count(count: usize) -> String {
|
||||
match count {
|
||||
1 => "1 unit".to_owned(),
|
||||
count => format!("{count} units"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_tree_takes_the_room_and_the_timeline_only_what_is_left() {
|
||||
let heights = Heights::share(30, 40, 0, 50);
|
||||
assert_eq!((heights.tree, heights.timeline), (30, 0));
|
||||
let heights = Heights::share(30, 12, 0, 50);
|
||||
assert_eq!((heights.tree, heights.timeline), (12, 18));
|
||||
let heights = Heights::share(30, 25, 0, 50);
|
||||
assert_eq!((heights.tree, heights.timeline), (30, 0));
|
||||
let heights = Heights::share(30, 12, 0, 8);
|
||||
assert_eq!((heights.tree, heights.timeline), (22, 8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failures_come_before_the_timeline_and_keep_a_few_rows_beside_a_full_tree() {
|
||||
let heights = Heights::share(30, 12, 6, 50);
|
||||
assert_eq!(
|
||||
(heights.tree, heights.failures, heights.timeline),
|
||||
(12, 6, 12)
|
||||
);
|
||||
let heights = Heights::share(30, 40, 9, 50);
|
||||
assert_eq!(
|
||||
(heights.tree, heights.failures, heights.timeline),
|
||||
(26, 4, 0)
|
||||
);
|
||||
let heights = Heights::share(5, 40, 9, 50);
|
||||
assert_eq!(
|
||||
(heights.tree, heights.failures, heights.timeline),
|
||||
(5, 0, 0)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
use std::iter::once;
|
||||
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
layout::Rect,
|
||||
style::Stylize,
|
||||
text::{Line, Span},
|
||||
widgets::{Paragraph, Widget},
|
||||
};
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
use super::{fit_width, rule};
|
||||
use crate::{
|
||||
boot_model::{FailedUnit, FailureExplanation},
|
||||
screen_settings::{color_scheme::FailureColors, font_glyphs::Glyphs},
|
||||
};
|
||||
|
||||
pub const RULE_HEIGHT: u16 = 1;
|
||||
const LOG_INDENT: &str = " ";
|
||||
const REASON_GAP: &str = " ";
|
||||
|
||||
pub struct FailurePanel<'a> {
|
||||
pub newest_first: Vec<&'a FailedUnit>,
|
||||
pub colors: &'a FailureColors,
|
||||
pub glyphs: &'a Glyphs,
|
||||
}
|
||||
|
||||
fn log_lines(failed: &FailedUnit) -> &[String] {
|
||||
match &failed.explanation {
|
||||
FailureExplanation::Explained(cause) => &cause.log_lines,
|
||||
FailureExplanation::Unexplained => &[],
|
||||
}
|
||||
}
|
||||
|
||||
impl FailurePanel<'_> {
|
||||
pub fn height(&self) -> u16 {
|
||||
if self.newest_first.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let rows: usize = self
|
||||
.newest_first
|
||||
.iter()
|
||||
.map(|failed| 1 + log_lines(failed).len())
|
||||
.sum();
|
||||
RULE_HEIGHT.saturating_add(u16::try_from(rows).unwrap_or(u16::MAX))
|
||||
}
|
||||
|
||||
fn headline(&self, failed: &FailedUnit, width: usize) -> Line<'static> {
|
||||
let marker = format!("{} ", self.glyphs.failed);
|
||||
let label_room = width.saturating_sub(marker.width());
|
||||
let label = fit_width(&failed.label, label_room, self.glyphs.ellipsis);
|
||||
let reason_room = label_room.saturating_sub(label.width() + REASON_GAP.width());
|
||||
let reason = match &failed.explanation {
|
||||
FailureExplanation::Explained(cause) if reason_room > 0 => {
|
||||
fit_width(&cause.reason, reason_room, self.glyphs.ellipsis)
|
||||
}
|
||||
_ => String::new(),
|
||||
};
|
||||
let reason_span =
|
||||
(!reason.is_empty()).then(|| format!("{REASON_GAP}{reason}").fg(self.colors.reason));
|
||||
Line::from(
|
||||
[
|
||||
marker.fg(self.colors.unit),
|
||||
label.fg(self.colors.unit).bold(),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(reason_span)
|
||||
.collect::<Vec<Span>>(),
|
||||
)
|
||||
}
|
||||
|
||||
fn block(&self, failed: &FailedUnit, width: usize) -> Vec<Line<'static>> {
|
||||
let log_room = width.saturating_sub(LOG_INDENT.width());
|
||||
once(self.headline(failed, width))
|
||||
.chain(log_lines(failed).iter().map(|line| {
|
||||
format!(
|
||||
"{LOG_INDENT}{}",
|
||||
fit_width(line, log_room, self.glyphs.ellipsis)
|
||||
)
|
||||
.fg(self.colors.log)
|
||||
.into()
|
||||
}))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn lines_within(&self, rows: usize, width: usize) -> Vec<Line<'static>> {
|
||||
if self.newest_first.len() > rows {
|
||||
return self.headlines_with_overflow(rows, width);
|
||||
}
|
||||
let mut spare_rows = rows - self.newest_first.len();
|
||||
self.newest_first
|
||||
.iter()
|
||||
.flat_map(|failed| {
|
||||
let mut block = self.block(failed, width);
|
||||
let kept_log_lines = (block.len() - 1).min(spare_rows);
|
||||
spare_rows -= kept_log_lines;
|
||||
block.truncate(1 + kept_log_lines);
|
||||
block
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn headlines_with_overflow(&self, rows: usize, width: usize) -> Vec<Line<'static>> {
|
||||
let Some(headline_rows) = rows.checked_sub(1) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let hidden = self.newest_first.len() - headline_rows;
|
||||
self.newest_first
|
||||
.iter()
|
||||
.take(headline_rows)
|
||||
.map(|failed| self.headline(failed, width))
|
||||
.chain(once(
|
||||
Line::from(format!("{} {hidden} more failed", self.glyphs.ellipsis))
|
||||
.fg(self.colors.overflow),
|
||||
))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for FailurePanel<'_> {
|
||||
fn render(self, area: Rect, buf: &mut Buffer) {
|
||||
let block = rule(
|
||||
self.colors.rule,
|
||||
Line::from(" Failures ".fg(self.colors.title)),
|
||||
);
|
||||
let inner = block.inner(area);
|
||||
block.render(area, buf);
|
||||
Paragraph::new(self.lines_within(usize::from(inner.height), usize::from(inner.width)))
|
||||
.render(inner, buf);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::boot_model::{FailureCause, FailureKind};
|
||||
|
||||
fn explained(label: &str, log_lines: &[&str]) -> FailedUnit {
|
||||
FailedUnit {
|
||||
unit: format!("{label}.service"),
|
||||
label: label.to_owned(),
|
||||
kind: FailureKind::Broke,
|
||||
explanation: FailureExplanation::Explained(FailureCause {
|
||||
reason: "exited with status 1".to_owned(),
|
||||
log_lines: log_lines.iter().map(ToString::to_string).collect(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn panel_text(failures: &[FailedUnit], rows: usize) -> Vec<String> {
|
||||
FailurePanel {
|
||||
newest_first: failures.iter().collect(),
|
||||
colors: &FailureColors::default(),
|
||||
glyphs: &Glyphs::fitting(|_| true),
|
||||
}
|
||||
.lines_within(rows, 60)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_newest_failure_keeps_its_lines_and_older_ones_shrink_to_a_headline() {
|
||||
let failures = [
|
||||
explained("web", &["bind: address in use", "giving up"]),
|
||||
explained("db", &["disk full"]),
|
||||
explained("cache", &["no memory"]),
|
||||
];
|
||||
assert_eq!(
|
||||
panel_text(&failures, 5),
|
||||
[
|
||||
"× web exited with status 1",
|
||||
" bind: address in use",
|
||||
" giving up",
|
||||
"× db exited with status 1",
|
||||
"× cache exited with status 1",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn room_left_by_the_newest_failure_goes_to_older_ones() {
|
||||
let failures = [
|
||||
explained("web", &["giving up"]),
|
||||
explained("db", &["disk full", "read-only file system"]),
|
||||
explained("cache", &["no memory"]),
|
||||
];
|
||||
assert_eq!(
|
||||
panel_text(&failures, 6),
|
||||
[
|
||||
"× web exited with status 1",
|
||||
" giving up",
|
||||
"× db exited with status 1",
|
||||
" disk full",
|
||||
" read-only file system",
|
||||
"× cache exited with status 1",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failures_beyond_the_room_are_counted() {
|
||||
let failures = [
|
||||
explained("web", &["giving up"]),
|
||||
explained("db", &[]),
|
||||
explained("cache", &[]),
|
||||
explained("queue", &[]),
|
||||
];
|
||||
assert_eq!(
|
||||
panel_text(&failures, 3),
|
||||
[
|
||||
"× web exited with status 1",
|
||||
"× db exited with status 1",
|
||||
"… 2 more failed"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unexplained_failure_shows_only_its_name() {
|
||||
let failures = [FailedUnit {
|
||||
explanation: FailureExplanation::Unexplained,
|
||||
..explained("web", &[])
|
||||
}];
|
||||
assert_eq!(panel_text(&failures, 4), ["× web"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
use std::{
|
||||
hint::black_box,
|
||||
iter::once,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use ratatui::{Terminal, backend::TestBackend};
|
||||
|
||||
use super::{BootProjection, BootView, project_boot, screen_render_fixtures::ryzen_origin};
|
||||
use crate::{
|
||||
boot_model::{BootState, JobResult, Phase, flatten_forest},
|
||||
boot_test_fixtures::{MS, QueuedUnit, queued_boot, running, waiting},
|
||||
screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs},
|
||||
};
|
||||
|
||||
const SERVICE_COUNT: u32 = 200;
|
||||
const CHAIN_LENGTH: u32 = 5;
|
||||
const FINISHED_SERVICES: u32 = 40;
|
||||
const DRAW_COUNT: u32 = 200;
|
||||
const DRAW_SPACING: Duration = Duration::from_millis(16);
|
||||
|
||||
fn service_name(index: u32) -> String {
|
||||
format!("unit{index:03}.service")
|
||||
}
|
||||
|
||||
fn crowded_service(index: u32, names: &[String]) -> QueuedUnit {
|
||||
let earlier = (!index.is_multiple_of(CHAIN_LENGTH)).then(|| names[index as usize - 1].as_str());
|
||||
let after: Vec<&str> = earlier.into_iter().collect();
|
||||
let name = &names[index as usize];
|
||||
if index.is_multiple_of(3) {
|
||||
running(name, &after, MS * index)
|
||||
} else {
|
||||
waiting(name, &after)
|
||||
}
|
||||
}
|
||||
|
||||
fn crowded_boot() -> BootState {
|
||||
let names: Vec<String> = (0..SERVICE_COUNT).map(service_name).collect();
|
||||
let services: Vec<&str> = names.iter().map(String::as_str).collect();
|
||||
let mut state = queued_boot(
|
||||
Phase::Host,
|
||||
Duration::ZERO,
|
||||
once(waiting("crowded.target", &services))
|
||||
.chain((0..SERVICE_COUNT).map(|index| crowded_service(index, &names))),
|
||||
);
|
||||
(2..FINISHED_SERVICES + 2).for_each(|id| {
|
||||
state.finish_job(id, JobResult::Done, MS * 1500 * id);
|
||||
});
|
||||
state
|
||||
}
|
||||
|
||||
fn report_timed_draws(label: &str, mut work: impl FnMut(Duration)) {
|
||||
let mut timings: Vec<Duration> = (0..DRAW_COUNT)
|
||||
.map(|draw| {
|
||||
let started = Instant::now();
|
||||
work(Duration::from_secs(90) + DRAW_SPACING * draw);
|
||||
started.elapsed()
|
||||
})
|
||||
.collect();
|
||||
timings.sort_unstable();
|
||||
let median = timings[timings.len() / 2];
|
||||
let slowest_tenth = timings[timings.len() * 9 / 10];
|
||||
println!("{label} over {DRAW_COUNT} draws: median {median:?}, p90 {slowest_tenth:?}");
|
||||
}
|
||||
|
||||
fn draw_boot_frame(
|
||||
terminal: &mut Terminal<TestBackend>,
|
||||
state: &BootState,
|
||||
projection: &BootProjection,
|
||||
now: Duration,
|
||||
) {
|
||||
terminal
|
||||
.draw(|frame| {
|
||||
frame.render_widget(
|
||||
BootView {
|
||||
state,
|
||||
projection,
|
||||
colors: &Colors::default(),
|
||||
timing: &Timing::default(),
|
||||
glyphs: &Glyphs::default(),
|
||||
now,
|
||||
origin: &ryzen_origin(),
|
||||
password_prompt: None,
|
||||
},
|
||||
frame.area(),
|
||||
);
|
||||
})
|
||||
.expect("draw");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "benchmark: cargo test --release frame_cost -- --ignored --nocapture"]
|
||||
fn frame_cost_of_a_crowded_boot() {
|
||||
let state = crowded_boot();
|
||||
let mut terminal = Terminal::new(TestBackend::new(110, 40)).expect("test backend");
|
||||
report_timed_draws("whole frame", |now| {
|
||||
let projection = project_boot(&state, &Timing::default(), now);
|
||||
draw_boot_frame(&mut terminal, &state, &projection, now);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "benchmark: cargo test --release frame_cost -- --ignored --nocapture"]
|
||||
fn frame_cost_with_a_cached_projection() {
|
||||
let state = crowded_boot();
|
||||
let projection = project_boot(&state, &Timing::default(), Duration::from_secs(90));
|
||||
let mut terminal = Terminal::new(TestBackend::new(110, 40)).expect("test backend");
|
||||
report_timed_draws("cached frame", |now| {
|
||||
draw_boot_frame(&mut terminal, &state, &projection, now);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "benchmark: cargo test --release frame_cost -- --ignored --nocapture"]
|
||||
fn frame_cost_of_the_model_projection() {
|
||||
let state = crowded_boot();
|
||||
report_timed_draws("model projection", |now| {
|
||||
black_box(flatten_forest(state.waiting_forest(now)));
|
||||
black_box(state.milestones());
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,472 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use super::{
|
||||
PasswordPrompt,
|
||||
screen_render_fixtures::{boot_in_progress, render, render_prompted, screen_lines},
|
||||
};
|
||||
use crate::{
|
||||
boot_model::{ActiveState, Activity, BootState, FailureCause, HANDOFF_UNIT, JobResult, Phase},
|
||||
boot_test_fixtures::{MS, queue_unit, queued_boot, running, waiting},
|
||||
screen_settings::color_scheme::Colors,
|
||||
};
|
||||
|
||||
const CRYPTSETUP_MESSAGE: &str =
|
||||
"Please enter passphrase for disk Samsung SSD 980 PRO 1TB (cryptroot):";
|
||||
|
||||
#[test]
|
||||
fn tree_on_top_timeline_below() {
|
||||
let lines = render(&boot_in_progress(), 12_400 * MS, 110, 24);
|
||||
let screen = lines.join("\n");
|
||||
assert_eq!(
|
||||
lines[0], "ryzen · NixOS 26.11 · generation 2771 · Linux 7.2.9",
|
||||
"{screen}"
|
||||
);
|
||||
assert!(lines[1].starts_with("└─ Stage 2 12.4s"), "{screen}");
|
||||
assert!(lines[1].ends_with("Running"), "{screen}");
|
||||
assert!(
|
||||
lines[2].starts_with(" ├─ ◆ multi-user.target"),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(
|
||||
lines[3].starts_with(" │ ├─ [|] systemd-rfkill"),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(lines[4].starts_with(" │ ├─ [|] docker"), "{screen}");
|
||||
assert!(lines[5].starts_with(" │ └─ [ ] web"), "{screen}");
|
||||
assert!(lines[6].starts_with(" ├─ ◇ graphical.target"), "{screen}");
|
||||
assert!(lines[7].starts_with(" └─ [×] nvidia-powerd"), "{screen}");
|
||||
let timeline = lines
|
||||
.iter()
|
||||
.position(|line| line.contains(" Timeline "))
|
||||
.expect("timeline panel");
|
||||
assert!(
|
||||
lines[timeline + 1].starts_with(&format!("{:29}Kernel", "")),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(
|
||||
lines[timeline + 2].starts_with("√ sysinit.target (2 units)"),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(lines[timeline + 3].starts_with("√ udev-settle"), "{screen}");
|
||||
assert!(lines[timeline + 3].contains('■'), "{screen}");
|
||||
assert!(
|
||||
lines[timeline + 4].starts_with("► systemd-rfkill"),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(
|
||||
lines[timeline + 4].contains("·█")
|
||||
&& lines[timeline + 4].ends_with(['▏', '▎', '▍', '▌', '▋', '▊', '▉', '█']),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(lines[timeline + 5].starts_with("► docker"), "{screen}");
|
||||
assert!(
|
||||
lines[timeline..].iter().all(|line| !line.contains(" web")),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(!screen.contains("root switch"), "{screen}");
|
||||
assert!(
|
||||
lines[23].starts_with("√ 2 done 2 running 3 waiting × 1 failed"),
|
||||
"{screen}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn password_prompt_floats_over_a_dimmed_view() {
|
||||
let buffer = render_prompted(
|
||||
&boot_in_progress(),
|
||||
12_400 * MS,
|
||||
110,
|
||||
24,
|
||||
Some(PasswordPrompt {
|
||||
message: CRYPTSETUP_MESSAGE,
|
||||
hint: None,
|
||||
input: "***".to_owned(),
|
||||
sent: false,
|
||||
rejected: false,
|
||||
}),
|
||||
);
|
||||
let lines = screen_lines(&buffer);
|
||||
let screen = lines.join("\n");
|
||||
let title_row = lines
|
||||
.iter()
|
||||
.position(|line| line.contains("┌ Password "))
|
||||
.unwrap_or_else(|| panic!("{screen}"));
|
||||
assert!(lines[title_row].starts_with(' '), "{screen}");
|
||||
assert!(
|
||||
lines[title_row + 1].contains(&format!("│ {CRYPTSETUP_MESSAGE}")),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(lines[title_row + 3].contains("│ > ***_"), "{screen}");
|
||||
assert!(lines[title_row + 4].contains("Enter unlock"), "{screen}");
|
||||
assert!(
|
||||
lines[23].starts_with("√ 2 done 2 running 3 waiting × 1 failed"),
|
||||
"{screen}"
|
||||
);
|
||||
assert_eq!(
|
||||
buffer[(0, 0)].fg,
|
||||
Colors::default().password.backdrop,
|
||||
"{screen}"
|
||||
);
|
||||
let corner = buffer
|
||||
.content
|
||||
.iter()
|
||||
.find(|cell| cell.symbol() == "┌")
|
||||
.unwrap_or_else(|| panic!("{screen}"));
|
||||
assert_eq!(corner.fg, Colors::default().password.frame, "{screen}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn answered_password_prompt_shows_it_is_checking() {
|
||||
let lines = screen_lines(&render_prompted(
|
||||
&boot_in_progress(),
|
||||
12_400 * MS,
|
||||
110,
|
||||
24,
|
||||
Some(PasswordPrompt {
|
||||
message: CRYPTSETUP_MESSAGE,
|
||||
hint: None,
|
||||
input: String::new(),
|
||||
sent: true,
|
||||
rejected: false,
|
||||
}),
|
||||
));
|
||||
assert!(
|
||||
lines.iter().any(|line| line.contains("│ Checking…")),
|
||||
"{}",
|
||||
lines.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_password_messages_wrap_inside_narrow_screens() {
|
||||
let lines = screen_lines(&render_prompted(
|
||||
&boot_in_progress(),
|
||||
12_400 * MS,
|
||||
50,
|
||||
24,
|
||||
Some(PasswordPrompt {
|
||||
message: CRYPTSETUP_MESSAGE,
|
||||
hint: None,
|
||||
input: String::new(),
|
||||
sent: false,
|
||||
rejected: false,
|
||||
}),
|
||||
));
|
||||
let screen = lines.join("\n");
|
||||
assert!(
|
||||
lines.iter().any(|line| line.contains("(cryptroot):")),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(lines.iter().any(|line| line.contains("> _")), "{screen}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejected_passphrase_is_called_out_under_the_hint() {
|
||||
let buffer = render_prompted(
|
||||
&boot_in_progress(),
|
||||
12_400 * MS,
|
||||
110,
|
||||
24,
|
||||
Some(PasswordPrompt {
|
||||
message: CRYPTSETUP_MESSAGE,
|
||||
hint: Some("This demo unlocks with the passphrase \"demo\""),
|
||||
input: String::new(),
|
||||
sent: false,
|
||||
rejected: true,
|
||||
}),
|
||||
);
|
||||
let lines = screen_lines(&buffer);
|
||||
let screen = lines.join("\n");
|
||||
let message_row = lines
|
||||
.iter()
|
||||
.position(|line| line.contains(CRYPTSETUP_MESSAGE))
|
||||
.unwrap_or_else(|| panic!("{screen}"));
|
||||
assert!(
|
||||
lines[message_row + 1].contains("│ This demo unlocks with the passphrase \"demo\""),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(
|
||||
lines[message_row + 3].contains("│ Wrong passphrase, try again"),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(lines[message_row + 4].contains("│ > _"), "{screen}");
|
||||
let rejection_row = u16::try_from(message_row + 3).expect("row fits the screen");
|
||||
let warning = (0..buffer.area.width)
|
||||
.map(|column| &buffer[(column, rejection_row)])
|
||||
.find(|cell| cell.symbol() == "W")
|
||||
.unwrap_or_else(|| panic!("{screen}"));
|
||||
assert_eq!(warning.fg, Colors::default().password.rejected, "{screen}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sub_second_runs_stay_off_the_timeline() {
|
||||
let mut state = boot_in_progress();
|
||||
queue_unit(
|
||||
&mut state,
|
||||
20,
|
||||
running("blink.service", &[], 4000 * MS),
|
||||
4000 * MS,
|
||||
);
|
||||
state.finish_job(20, JobResult::Done, 4400 * MS);
|
||||
let lines = render(&state, 12_400 * MS, 110, 24);
|
||||
assert!(
|
||||
lines.iter().all(|line| !line.contains("blink")),
|
||||
"{}",
|
||||
lines.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_timeline_labels_end_in_an_ellipsis() {
|
||||
let mut state = boot_in_progress();
|
||||
queue_unit(
|
||||
&mut state,
|
||||
30,
|
||||
running("sys-kernel-config.mount", &[], 2000 * MS)
|
||||
.described("Kernel Configuration File System"),
|
||||
2000 * MS,
|
||||
);
|
||||
state.finish_job(30, JobResult::Done, 4000 * MS);
|
||||
let lines = render(&state, 12_400 * MS, 110, 24);
|
||||
assert!(
|
||||
lines
|
||||
.iter()
|
||||
.any(|line| line.starts_with("√ Kernel Configuration File…")),
|
||||
"{}",
|
||||
lines.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_screens_drop_the_timeline() {
|
||||
let lines = render(&boot_in_progress(), 12_400 * MS, 40, 24);
|
||||
assert!(
|
||||
lines.iter().all(|line| !line.contains('■')),
|
||||
"{}",
|
||||
lines.join("\n")
|
||||
);
|
||||
assert!(lines[3].contains("systemd-rfkill"), "{}", lines.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finished_stages_collapse_into_a_summary_rule() {
|
||||
let mut state = queued_boot(
|
||||
Phase::Initrd,
|
||||
Duration::ZERO,
|
||||
[waiting("initrd.target", &[])],
|
||||
);
|
||||
state.finish_job(1, JobResult::Done, 6000 * MS);
|
||||
state.switch_root(7200 * MS);
|
||||
state.set_root("graphical.target".to_owned());
|
||||
queue_unit(&mut state, 2, waiting("graphical.target", &[]), 7300 * MS);
|
||||
let lines = render(&state, 17_300 * MS, 110, 24);
|
||||
let screen = lines.join("\n");
|
||||
assert!(lines[0].ends_with("17.3s"), "{screen}");
|
||||
assert!(
|
||||
lines[1].starts_with("├─ Initrd ■ done in 7.2s · 1 unit"),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(lines[2].starts_with("└─ Stage 2 10.1s"), "{screen}");
|
||||
assert!(lines[3].starts_with(" └─ ◆ graphical.target"), "{screen}");
|
||||
let timeline = lines
|
||||
.iter()
|
||||
.position(|line| line.contains(" Timeline "))
|
||||
.expect("timeline panel");
|
||||
let initrd_bar = &lines[timeline + 2];
|
||||
assert!(initrd_bar.starts_with("√ Initrd (1 unit)"), "{screen}");
|
||||
assert!(initrd_bar.ends_with("■│"), "{screen}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_without_a_display_manager_hands_back_the_console() {
|
||||
let mut state = queued_boot(
|
||||
Phase::Host,
|
||||
Duration::ZERO,
|
||||
[waiting("graphical.target", &[])],
|
||||
);
|
||||
state.finish_job(1, JobResult::Done, 9000 * MS);
|
||||
let lines = render(&state, 9500 * MS, 110, 24);
|
||||
assert!(
|
||||
lines[1].starts_with("└─ ■ Boot finished in 9.5s · handing over to the console"),
|
||||
"{}",
|
||||
lines.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_names_the_display_manager_that_started() {
|
||||
let mut state = queued_boot(
|
||||
Phase::Host,
|
||||
Duration::ZERO,
|
||||
[waiting("graphical.target", &[])],
|
||||
);
|
||||
queue_unit(&mut state, 2, waiting(HANDOFF_UNIT, &[]), 500 * MS);
|
||||
state.update_activity(
|
||||
HANDOFF_UNIT,
|
||||
Activity {
|
||||
state: Some(ActiveState::Active),
|
||||
..Activity::default()
|
||||
},
|
||||
);
|
||||
state.finish_job(1, JobResult::Done, 9000 * MS);
|
||||
let lines = render(&state, 9500 * MS, 110, 24);
|
||||
assert!(
|
||||
lines[1]
|
||||
.starts_with("└─ ■ Boot finished in 9.5s · handing over to display-manager.service"),
|
||||
"{}",
|
||||
lines.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shutdown_in_progress_names_its_stage() {
|
||||
let mut state = queued_boot(
|
||||
Phase::Shutdown,
|
||||
20_000 * MS,
|
||||
[waiting("poweroff.target", &[])],
|
||||
);
|
||||
state.origin = 20_000 * MS;
|
||||
let lines = render(&state, 21_500 * MS, 110, 24);
|
||||
assert!(
|
||||
lines[1].starts_with("└─ Shutdown 1.5s") && lines[1].ends_with("Running"),
|
||||
"{}",
|
||||
lines.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shutdown_announces_the_handover_once_the_manager_exits() {
|
||||
let mut state = BootState::new(Phase::Shutdown);
|
||||
state.origin = 20_000 * MS;
|
||||
state.manager_exited_at = Some(24_200 * MS);
|
||||
let lines = render(&state, 30_000 * MS, 110, 24);
|
||||
assert!(
|
||||
lines[1].starts_with("└─ ■ Shutdown finished in 4.2s · handing over to systemd-shutdown"),
|
||||
"{}",
|
||||
lines.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_timeline_keeps_only_the_slowest_finished_runs() {
|
||||
let quick_units: Vec<String> = (0..10).map(|n| format!("run{n:02}.service")).collect();
|
||||
let after: Vec<&str> = quick_units
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.chain(["slow.service"])
|
||||
.collect();
|
||||
let mut state = queued_boot(
|
||||
Phase::Host,
|
||||
Duration::ZERO,
|
||||
[
|
||||
waiting("multi-user.target", &after),
|
||||
running("slow.service", &[], Duration::ZERO),
|
||||
],
|
||||
);
|
||||
quick_units.iter().zip(10..).for_each(|(name, id)| {
|
||||
queue_unit(
|
||||
&mut state,
|
||||
id,
|
||||
running(name, &[], Duration::ZERO),
|
||||
Duration::ZERO,
|
||||
);
|
||||
state.finish_job(id, JobResult::Done, (1000 * id - 9000) * MS);
|
||||
});
|
||||
let lines = render(&state, 20_000 * MS, 110, 40);
|
||||
let screen = lines.join("\n");
|
||||
let timeline = lines
|
||||
.iter()
|
||||
.position(|line| line.contains(" Timeline "))
|
||||
.expect("timeline panel");
|
||||
let (tree, panel) = lines.split_at(timeline);
|
||||
assert!(tree.iter().all(|line| !line.contains('…')), "{screen}");
|
||||
let shown: Vec<&str> = quick_units
|
||||
.iter()
|
||||
.map(|name| name.trim_end_matches(".service"))
|
||||
.filter(|label| panel.iter().any(|line| line.contains(label)))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
shown,
|
||||
["run05", "run06", "run07", "run08", "run09"],
|
||||
"{screen}"
|
||||
);
|
||||
}
|
||||
|
||||
fn explained_nvidia_failure() -> BootState {
|
||||
let mut state = boot_in_progress();
|
||||
state.explain_failure(
|
||||
"nvidia-powerd.service",
|
||||
FailureCause {
|
||||
reason: "exited with status 1".to_owned(),
|
||||
log_lines: vec![
|
||||
"ERROR! Failed to get system power limits".to_owned(),
|
||||
"giving up".to_owned(),
|
||||
],
|
||||
},
|
||||
);
|
||||
state
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failures_show_their_reason_and_journal_lines_above_the_timeline() {
|
||||
let lines = render(&explained_nvidia_failure(), 12_400 * MS, 110, 30);
|
||||
let screen = lines.join("\n");
|
||||
let failures = lines
|
||||
.iter()
|
||||
.position(|line| line.contains(" Failures "))
|
||||
.expect("failure panel");
|
||||
let timeline = lines
|
||||
.iter()
|
||||
.position(|line| line.contains(" Timeline "))
|
||||
.expect("timeline panel");
|
||||
assert!(failures < timeline, "{screen}");
|
||||
assert_eq!(
|
||||
lines[failures + 1],
|
||||
"× nvidia-powerd exited with status 1",
|
||||
"{screen}"
|
||||
);
|
||||
assert_eq!(
|
||||
lines[failures + 2],
|
||||
" ERROR! Failed to get system power limits",
|
||||
"{screen}"
|
||||
);
|
||||
assert_eq!(lines[failures + 3], " giving up", "{screen}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_lines_are_cut_to_a_narrow_screen() {
|
||||
let lines = render(&explained_nvidia_failure(), 12_400 * MS, 30, 30);
|
||||
let screen = lines.join("\n");
|
||||
let failures = lines
|
||||
.iter()
|
||||
.position(|line| line.contains(" Failures "))
|
||||
.expect("failure panel");
|
||||
assert_eq!(
|
||||
lines[failures + 1],
|
||||
"× nvidia-powerd exited with …",
|
||||
"{screen}"
|
||||
);
|
||||
assert_eq!(
|
||||
lines[failures + 2],
|
||||
" ERROR! Failed to get syst…",
|
||||
"{screen}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dependency_failures_stay_out_of_the_failure_panel() {
|
||||
let mut state = queued_boot(
|
||||
Phase::Host,
|
||||
1000 * MS,
|
||||
[
|
||||
waiting("multi-user.target", &["web.service"]),
|
||||
waiting("web.service", &[]),
|
||||
],
|
||||
);
|
||||
state.finish_job(2, JobResult::Dependency, 2000 * MS);
|
||||
let lines = render(&state, 3000 * MS, 110, 24);
|
||||
let screen = lines.join("\n");
|
||||
assert!(!screen.contains(" Failures "), "{screen}");
|
||||
assert!(screen.contains("[×] web"), "{screen}");
|
||||
assert!(screen.contains("× 1 failed"), "{screen}");
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
use std::{cmp::Reverse, iter::once, time::Duration};
|
||||
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
layout::{Constraint, Layout, Rect},
|
||||
style::{Color, Stylize},
|
||||
symbols::Marker,
|
||||
text::{Line, Span},
|
||||
widgets::{
|
||||
Paragraph, Widget,
|
||||
canvas::{Canvas, Line as Stroke, Points},
|
||||
},
|
||||
};
|
||||
|
||||
use super::{WHOLE_UNITS, fit_width, rule, unit_count};
|
||||
use crate::{
|
||||
boot_model::{FinishedRun, MilestoneRow},
|
||||
screen_settings::{color_scheme::TimelineColors, font_glyphs::Glyphs},
|
||||
};
|
||||
|
||||
pub const LABEL_WIDTH: u16 = 28;
|
||||
pub const CHROME_HEIGHT: u16 = 2;
|
||||
const MARK_WIDTH: u16 = 2;
|
||||
const SLOWEST_RUNS_SHOWN: usize = 5;
|
||||
const KERNEL_ORIGIN_LABEL: &str = "Kernel";
|
||||
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),
|
||||
];
|
||||
|
||||
pub struct Timeline<'a> {
|
||||
pub origin: Duration,
|
||||
pub now: Duration,
|
||||
pub root_switches: Vec<Duration>,
|
||||
pub milestones: &'a [MilestoneRow],
|
||||
pub finished: Vec<&'a FinishedRun>,
|
||||
pub running: Vec<RunningRun<'a>>,
|
||||
pub colors: &'a TimelineColors,
|
||||
pub glyphs: &'a Glyphs,
|
||||
}
|
||||
|
||||
pub struct RunningRun<'a> {
|
||||
pub label: &'a str,
|
||||
pub queued_at: Duration,
|
||||
pub since: Duration,
|
||||
}
|
||||
|
||||
impl Timeline<'_> {
|
||||
pub fn height(&self) -> u16 {
|
||||
let entries = self.milestones.len()
|
||||
+ self.finished.len().min(SLOWEST_RUNS_SHOWN)
|
||||
+ self.running.len();
|
||||
if entries == 0 {
|
||||
return 0;
|
||||
}
|
||||
CHROME_HEIGHT.saturating_add(u16::try_from(entries).unwrap_or(u16::MAX))
|
||||
}
|
||||
|
||||
fn finished_that_fit(&self, height: u16) -> Vec<&FinishedRun> {
|
||||
let bar_rows = usize::from(height.saturating_sub(CHROME_HEIGHT));
|
||||
let room = bar_rows.saturating_sub(self.milestones.len() + self.running.len());
|
||||
let mut longest_first = self.finished.clone();
|
||||
longest_first
|
||||
.sort_unstable_by_key(|run| Reverse(run.finished_at.saturating_sub(run.started_at)));
|
||||
longest_first.truncate(room.min(SLOWEST_RUNS_SHOWN));
|
||||
longest_first.sort_unstable_by_key(|run| run.started_at);
|
||||
longest_first
|
||||
}
|
||||
|
||||
fn milestone_entry(&self, row: &MilestoneRow) -> TimelineEntry<'static> {
|
||||
TimelineEntry {
|
||||
label: Line::styled(
|
||||
format!(
|
||||
"{} {} ({})",
|
||||
self.glyphs.done,
|
||||
row.label,
|
||||
unit_count(row.finished_units)
|
||||
),
|
||||
self.colors.milestone,
|
||||
),
|
||||
segments: vec![Segment {
|
||||
from: row.started_at,
|
||||
to: row.reached_at,
|
||||
symbol: self.glyphs.bead,
|
||||
color: self.colors.milestone,
|
||||
}],
|
||||
still_going: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn finished_entry<'a>(&self, run: &'a FinishedRun) -> TimelineEntry<'a> {
|
||||
let mark = if run.failed {
|
||||
self.glyphs.failed
|
||||
} else {
|
||||
self.glyphs.done
|
||||
};
|
||||
let outcome = if run.failed {
|
||||
self.colors.failed
|
||||
} else {
|
||||
self.colors.finished
|
||||
};
|
||||
TimelineEntry {
|
||||
label: Line::from(vec![
|
||||
Span::styled(format!("{mark} "), outcome),
|
||||
self.fitted(&run.label).fg(self.colors.finished_label),
|
||||
]),
|
||||
segments: vec![Segment {
|
||||
from: run.started_at,
|
||||
to: run.finished_at,
|
||||
symbol: self.glyphs.bead,
|
||||
color: outcome,
|
||||
}],
|
||||
still_going: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn fitted(&self, label: &str) -> String {
|
||||
fit_width(
|
||||
label,
|
||||
usize::from(LABEL_WIDTH - MARK_WIDTH),
|
||||
self.glyphs.ellipsis,
|
||||
)
|
||||
}
|
||||
|
||||
fn running_entry(&self, run: &RunningRun) -> TimelineEntry<'static> {
|
||||
let waited = (run.since > run.queued_at).then_some(Segment {
|
||||
from: run.queued_at,
|
||||
to: run.since,
|
||||
symbol: self.glyphs.waiting_bead,
|
||||
color: self.colors.queued_bar,
|
||||
});
|
||||
let running_bar = self
|
||||
.glyphs
|
||||
.growing_tip
|
||||
.map_or(self.glyphs.bead, |tips| tips[7]);
|
||||
let ran = Segment {
|
||||
from: run.since,
|
||||
to: self.now,
|
||||
symbol: running_bar,
|
||||
color: self.colors.running,
|
||||
};
|
||||
TimelineEntry {
|
||||
label: Line::from(vec![
|
||||
format!("{} ", self.glyphs.running_mark).fg(self.colors.running),
|
||||
self.fitted(run.label).fg(self.colors.running_label),
|
||||
]),
|
||||
segments: waited.into_iter().chain(once(ran)).collect(),
|
||||
still_going: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for Timeline<'_> {
|
||||
fn render(self, area: Rect, buf: &mut Buffer) {
|
||||
let block = rule(
|
||||
self.colors.rule,
|
||||
Line::from(" Timeline ".fg(self.colors.title)),
|
||||
);
|
||||
let inner = block.inner(area);
|
||||
block.render(area, buf);
|
||||
let [label_area, bar_area] =
|
||||
Layout::horizontal([Constraint::Length(LABEL_WIDTH), Constraint::Fill(1)])
|
||||
.spacing(1)
|
||||
.areas(inner);
|
||||
let entries: Vec<TimelineEntry> = self
|
||||
.milestones
|
||||
.iter()
|
||||
.map(|row| self.milestone_entry(row))
|
||||
.chain(
|
||||
self.finished_that_fit(area.height)
|
||||
.into_iter()
|
||||
.map(|run| self.finished_entry(run)),
|
||||
)
|
||||
.chain(self.running.iter().map(|row| self.running_entry(row)))
|
||||
.collect();
|
||||
Paragraph::new(
|
||||
once(Line::default())
|
||||
.chain(entries.iter().map(|entry| entry.label.clone()))
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.render(label_area, buf);
|
||||
let axis = TimeAxis::new(self.origin, self.now, bar_area.width);
|
||||
let label_row = f64::from(bar_area.height.saturating_sub(1).max(1));
|
||||
let axis_color = self.colors.axis;
|
||||
Canvas::default()
|
||||
.x_bounds(axis.bounds())
|
||||
.y_bounds([0.0, label_row])
|
||||
.paint(|ctx| {
|
||||
entries.iter().zip(1_u16..).for_each(|(entry, row)| {
|
||||
let y = label_row - f64::from(row);
|
||||
entry.segments.iter().for_each(|segment| {
|
||||
ctx.marker(Marker::Custom(segment.symbol));
|
||||
ctx.draw(&Stroke::new(
|
||||
segment.from.as_secs_f64(),
|
||||
y,
|
||||
segment.to.as_secs_f64(),
|
||||
y,
|
||||
segment.color,
|
||||
));
|
||||
});
|
||||
if entry.still_going {
|
||||
let tip = self
|
||||
.glyphs
|
||||
.growing_tip
|
||||
.map_or(self.glyphs.still_going, |tips| {
|
||||
tips[axis.eighths_into_column(self.now)]
|
||||
});
|
||||
let tip_color = if self.glyphs.growing_tip.is_some() {
|
||||
self.colors.running
|
||||
} else {
|
||||
axis_color
|
||||
};
|
||||
ctx.marker(Marker::Custom(tip));
|
||||
ctx.draw(&Points::new(&[(self.now.as_secs_f64(), y)], tip_color));
|
||||
}
|
||||
});
|
||||
ctx.marker(Marker::Custom(self.glyphs.root_switch_mark));
|
||||
self.root_switches.iter().for_each(|at| {
|
||||
let x = at.as_secs_f64();
|
||||
ctx.draw(&Stroke::new(x, 0.0, x, label_row - 1.0, axis_color));
|
||||
});
|
||||
axis.tick_offsets().for_each(|offset| {
|
||||
let label = axis.label(offset);
|
||||
let x = (axis.origin + offset)
|
||||
.as_secs_f64()
|
||||
.min(axis.bounds()[1] - axis.columns_to_seconds(label.len() - 1));
|
||||
ctx.print(x, label_row, label.fg(axis_color));
|
||||
});
|
||||
})
|
||||
.render(bar_area, buf);
|
||||
}
|
||||
}
|
||||
|
||||
struct TimelineEntry<'a> {
|
||||
label: Line<'a>,
|
||||
segments: Vec<Segment>,
|
||||
still_going: bool,
|
||||
}
|
||||
|
||||
struct Segment {
|
||||
from: Duration,
|
||||
to: Duration,
|
||||
symbol: char,
|
||||
color: Color,
|
||||
}
|
||||
|
||||
struct TimeAxis {
|
||||
origin: Duration,
|
||||
span: Duration,
|
||||
step: Duration,
|
||||
width: u16,
|
||||
}
|
||||
|
||||
impl TimeAxis {
|
||||
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| 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,
|
||||
span: step * steps.max(1),
|
||||
step,
|
||||
width,
|
||||
}
|
||||
}
|
||||
|
||||
fn bounds(&self) -> [f64; 2] {
|
||||
[
|
||||
self.origin.as_secs_f64(),
|
||||
(self.origin + self.span).as_secs_f64(),
|
||||
]
|
||||
}
|
||||
|
||||
fn eighths_into_column(&self, at: Duration) -> usize {
|
||||
let last_column = u128::from(self.width.saturating_sub(1).max(1));
|
||||
let span = self.span.as_nanos().max(1);
|
||||
let scaled = at.saturating_sub(self.origin).as_nanos() * last_column;
|
||||
usize::try_from(scaled % span * 8 / span).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn columns_to_seconds(&self, columns: usize) -> f64 {
|
||||
let last_column = self.width.saturating_sub(1).max(1);
|
||||
let columns = u16::try_from(columns).unwrap_or(last_column);
|
||||
self.span.as_secs_f64() * f64::from(columns) / f64::from(last_column)
|
||||
}
|
||||
|
||||
fn tick_offsets(&self) -> impl Iterator<Item = Duration> + '_ {
|
||||
(0..)
|
||||
.map(|index: u32| self.step * index)
|
||||
.take_while(|offset| *offset <= self.span)
|
||||
}
|
||||
|
||||
fn label(&self, offset: Duration) -> String {
|
||||
if offset.is_zero() && self.origin.is_zero() {
|
||||
KERNEL_ORIGIN_LABEL.to_owned()
|
||||
} else {
|
||||
WHOLE_UNITS.unsigned_duration_to_string(&offset)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_tip_fills_its_column_in_eighths() {
|
||||
let axis = TimeAxis {
|
||||
origin: Duration::ZERO,
|
||||
span: Duration::from_secs(10),
|
||||
step: Duration::from_secs(1),
|
||||
width: 11,
|
||||
};
|
||||
let eighths = |millis: u64| axis.eighths_into_column(Duration::from_millis(millis));
|
||||
assert_eq!(eighths(2000), 0);
|
||||
assert_eq!(eighths(2125), 1);
|
||||
assert_eq!(eighths(2500), 4);
|
||||
assert_eq!(eighths(2999), 7);
|
||||
assert_eq!(eighths(3000), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
use std::{iter::once, time::Duration};
|
||||
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
layout::{Constraint, Rect},
|
||||
style::{Style, Stylize},
|
||||
text::{Line, Span},
|
||||
widgets::{Block, Borders, Clear, Padding, Paragraph, Widget, Wrap},
|
||||
};
|
||||
|
||||
use super::{DURATION_WIDTH, ELAPSED};
|
||||
use crate::{
|
||||
boot_model::{Tally, boot_origin::BootOrigin},
|
||||
screen_settings::{
|
||||
color_scheme::{FooterColors, HeaderColors, PasswordColors},
|
||||
font_glyphs::Glyphs,
|
||||
},
|
||||
};
|
||||
|
||||
pub const FOOTER_HEIGHT: u16 = 2;
|
||||
const SEPARATOR: &str = " · ";
|
||||
const REJECTED_PASSPHRASE: &str = "Wrong passphrase, try again";
|
||||
|
||||
pub struct Header<'a> {
|
||||
pub origin: &'a BootOrigin,
|
||||
pub total: Option<Duration>,
|
||||
pub colors: &'a HeaderColors,
|
||||
}
|
||||
|
||||
impl Header<'_> {
|
||||
fn origin(&self) -> Line<'static> {
|
||||
Line::from(
|
||||
self.origin
|
||||
.parts()
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.flat_map(|(index, part)| {
|
||||
let separator = (index > 0).then(|| SEPARATOR.fg(self.colors.separators));
|
||||
let part = Span::from(part).fg(self.colors.origin);
|
||||
let part = if index == 0 { part.bold() } else { part };
|
||||
separator.into_iter().chain(once(part))
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for Header<'_> {
|
||||
fn render(self, area: Rect, buf: &mut Buffer) {
|
||||
self.origin().render(
|
||||
Rect {
|
||||
width: area.width.saturating_sub(DURATION_WIDTH),
|
||||
..area
|
||||
},
|
||||
buf,
|
||||
);
|
||||
if let Some(total) = self.total {
|
||||
Line::from(ELAPSED.unsigned_duration_to_string(&total))
|
||||
.fg(self.colors.total_time)
|
||||
.bold()
|
||||
.right_aligned()
|
||||
.render(area, buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Footer<'a> {
|
||||
pub tally: Tally,
|
||||
pub colors: &'a FooterColors,
|
||||
pub glyphs: &'a Glyphs,
|
||||
}
|
||||
|
||||
impl Widget for Footer<'_> {
|
||||
fn render(self, area: Rect, buf: &mut Buffer) {
|
||||
let failed = format!(" {} {} failed", self.glyphs.failed, self.tally.failed);
|
||||
let failed = if self.tally.failed > 0 {
|
||||
failed.fg(self.colors.failed).bold()
|
||||
} else {
|
||||
failed.fg(self.colors.no_failures)
|
||||
};
|
||||
let block = Block::new()
|
||||
.borders(Borders::TOP)
|
||||
.border_style(self.colors.rule);
|
||||
let inner = block.inner(area);
|
||||
block.render(area, buf);
|
||||
Line::from(vec![
|
||||
format!("{} {} done", self.glyphs.done, self.tally.done).fg(self.colors.done),
|
||||
format!(" {} running", self.tally.running).fg(self.colors.running),
|
||||
format!(" {} waiting", self.tally.waiting).fg(self.colors.waiting),
|
||||
failed,
|
||||
])
|
||||
.render(inner, buf);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PasswordPrompt<'a> {
|
||||
pub message: &'a str,
|
||||
pub hint: Option<&'a str>,
|
||||
pub input: String,
|
||||
pub sent: bool,
|
||||
pub rejected: bool,
|
||||
}
|
||||
|
||||
pub struct PasswordPopup<'a> {
|
||||
pub asking: &'a PasswordPrompt<'a>,
|
||||
pub colors: &'a PasswordColors,
|
||||
pub glyphs: &'a Glyphs,
|
||||
}
|
||||
|
||||
impl PasswordPopup<'_> {
|
||||
const MIN_WIDTH: u16 = 40;
|
||||
|
||||
fn input(&self) -> Line<'static> {
|
||||
if self.asking.sent {
|
||||
Line::from(format!("Checking{}", self.glyphs.ellipsis).fg(self.colors.checking))
|
||||
} else {
|
||||
Line::from(vec![
|
||||
"> ".fg(self.colors.frame),
|
||||
format!("{}_", self.asking.input).fg(self.colors.message),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
fn paragraph(&self) -> Paragraph<'_> {
|
||||
let message = Line::from(self.asking.message.fg(self.colors.message).bold());
|
||||
let hint = self
|
||||
.asking
|
||||
.hint
|
||||
.map(|hint| Line::from(hint.fg(self.colors.hint)));
|
||||
let rejection = (self.asking.rejected && !self.asking.sent)
|
||||
.then(|| Line::from(REJECTED_PASSPHRASE.fg(self.colors.rejected).bold()));
|
||||
let lines: Vec<Line> = once(message)
|
||||
.chain(hint)
|
||||
.chain(once(Line::default()))
|
||||
.chain(rejection)
|
||||
.chain(once(self.input()))
|
||||
.collect();
|
||||
Paragraph::new(lines).wrap(Wrap { trim: false }).block(
|
||||
Block::bordered()
|
||||
.border_style(self.colors.frame)
|
||||
.padding(Padding::horizontal(2))
|
||||
.title(" Password ".fg(self.colors.frame).bold())
|
||||
.title_bottom(
|
||||
Line::from(" Enter unlock · Ctrl+U clear ".fg(self.colors.hint))
|
||||
.right_aligned(),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for PasswordPopup<'_> {
|
||||
fn render(self, area: Rect, buf: &mut Buffer) {
|
||||
buf.set_style(area, Style::new().fg(self.colors.backdrop));
|
||||
let paragraph = self.paragraph();
|
||||
let width = u16::try_from(paragraph.line_width())
|
||||
.unwrap_or(u16::MAX)
|
||||
.max(Self::MIN_WIDTH)
|
||||
.min(area.width);
|
||||
let height = u16::try_from(paragraph.line_count(width)).unwrap_or(u16::MAX);
|
||||
let popup = area.centered(Constraint::Length(width), Constraint::Length(height));
|
||||
Clear.render(popup, buf);
|
||||
paragraph.render(popup, buf);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use ratatui::{Terminal, backend::TestBackend, buffer::Buffer};
|
||||
|
||||
use super::{BootView, PasswordPrompt, project_boot};
|
||||
use crate::{
|
||||
boot_model::{BootState, JobResult, Phase, boot_origin::BootOrigin},
|
||||
boot_test_fixtures::{MS, queued_boot, running, waiting},
|
||||
screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs},
|
||||
};
|
||||
|
||||
pub fn render(state: &BootState, now: Duration, width: u16, height: u16) -> Vec<String> {
|
||||
screen_lines(&render_prompted(state, now, width, height, None))
|
||||
}
|
||||
|
||||
pub fn render_prompted(
|
||||
state: &BootState,
|
||||
now: Duration,
|
||||
width: u16,
|
||||
height: u16,
|
||||
password_prompt: Option<PasswordPrompt>,
|
||||
) -> Buffer {
|
||||
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("test backend");
|
||||
let timing = Timing::default();
|
||||
let projection = project_boot(state, &timing, now);
|
||||
terminal
|
||||
.draw(|frame| {
|
||||
frame.render_widget(
|
||||
BootView {
|
||||
state,
|
||||
projection: &projection,
|
||||
colors: &Colors::default(),
|
||||
timing: &timing,
|
||||
glyphs: &Glyphs::default(),
|
||||
now,
|
||||
origin: &ryzen_origin(),
|
||||
password_prompt,
|
||||
},
|
||||
frame.area(),
|
||||
);
|
||||
})
|
||||
.expect("draw");
|
||||
terminal.backend().buffer().clone()
|
||||
}
|
||||
|
||||
pub fn ryzen_origin() -> BootOrigin {
|
||||
BootOrigin {
|
||||
host: "ryzen".to_owned(),
|
||||
system: Some("NixOS 26.11".to_owned()),
|
||||
generation: Some("2771".to_owned()),
|
||||
kernel: "Linux 7.2.9".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn screen_lines(buffer: &Buffer) -> Vec<String> {
|
||||
let area = buffer.area;
|
||||
(0..area.height)
|
||||
.map(|y| {
|
||||
let line: String = (0..area.width)
|
||||
.map(|x| buffer[(x, y)].symbol().to_owned())
|
||||
.collect();
|
||||
line.trim_end().to_owned()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn boot_in_progress() -> BootState {
|
||||
let mut state = queued_boot(
|
||||
Phase::Host,
|
||||
1000 * MS,
|
||||
[
|
||||
waiting("graphical.target", &["multi-user.target"]),
|
||||
waiting(
|
||||
"multi-user.target",
|
||||
&["docker.service", "systemd-rfkill.service", "web.service"],
|
||||
),
|
||||
running("docker.service", &[], 9000 * MS),
|
||||
running("systemd-rfkill.service", &[], 6000 * MS),
|
||||
waiting("web.service", &[]),
|
||||
waiting("sysinit.target", &[]),
|
||||
waiting("nvidia-powerd.service", &[]),
|
||||
running("udev-settle.service", &[], 2000 * MS),
|
||||
],
|
||||
);
|
||||
state.finish_job(6, JobResult::Done, 4000 * MS);
|
||||
state.finish_job(7, JobResult::Failed, 5000 * MS);
|
||||
state.finish_job(8, JobResult::Done, 3500 * MS);
|
||||
state
|
||||
}
|
||||
|
||||
pub fn chain_boot() -> BootState {
|
||||
queued_boot(
|
||||
Phase::Host,
|
||||
Duration::ZERO,
|
||||
[
|
||||
waiting("graphical.target", &["network-wait.service"]),
|
||||
waiting("network-wait.service", &["network.target"]),
|
||||
waiting("network.target", &["network-manager.service"]),
|
||||
waiting("network-manager.service", &["dbus.service"]),
|
||||
waiting("dbus.service", &["udev-settle.service"]),
|
||||
running("udev-settle.service", &[], 1000 * MS),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
pub fn described_boot() -> BootState {
|
||||
queued_boot(
|
||||
Phase::Host,
|
||||
Duration::ZERO,
|
||||
[
|
||||
running(
|
||||
"multi-user.target",
|
||||
&["docker.service", "systemd-rfkill.service"],
|
||||
1000 * MS,
|
||||
)
|
||||
.described("Multi-User System"),
|
||||
running("docker.service", &[], 1000 * MS)
|
||||
.described("Docker Application Container Engine"),
|
||||
running("systemd-rfkill.service", &[], 1000 * MS)
|
||||
.described("Load/Save RF Kill Switch Status"),
|
||||
],
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
layout::Rect,
|
||||
style::Stylize,
|
||||
text::{Line, Span},
|
||||
widgets::{Paragraph, Widget},
|
||||
};
|
||||
|
||||
use super::{BRANCH, ELAPSED, LAST_BRANCH, unit_count};
|
||||
use crate::{
|
||||
boot_model::BootState,
|
||||
screen_settings::{color_scheme::StageColors, font_glyphs::Glyphs},
|
||||
};
|
||||
|
||||
const SHUTDOWN_SUCCESSOR: &str = "systemd-shutdown";
|
||||
const PHASE_WIDTH: usize = 9;
|
||||
|
||||
pub struct Stages<'a> {
|
||||
pub state: &'a BootState,
|
||||
pub now: Duration,
|
||||
pub colors: &'a StageColors,
|
||||
pub glyphs: &'a Glyphs,
|
||||
}
|
||||
|
||||
struct Conclusion<'a> {
|
||||
finished: &'static str,
|
||||
took: Duration,
|
||||
handed_to: &'a str,
|
||||
}
|
||||
|
||||
impl Stages<'_> {
|
||||
pub fn height(&self) -> u16 {
|
||||
u16::try_from(self.state.finished_stages.len()).unwrap_or(u16::MAX)
|
||||
}
|
||||
|
||||
fn conclusion(&self) -> Option<Conclusion<'_>> {
|
||||
if let Some(exited_at) = self.state.manager_exited_at {
|
||||
return Some(Conclusion {
|
||||
finished: "Shutdown",
|
||||
took: exited_at.saturating_sub(self.state.origin),
|
||||
handed_to: SHUTDOWN_SUCCESSOR,
|
||||
});
|
||||
}
|
||||
self.state.is_complete().then(|| Conclusion {
|
||||
finished: "Boot",
|
||||
took: self.now.saturating_sub(self.state.origin),
|
||||
handed_to: self
|
||||
.state
|
||||
.started_display_manager()
|
||||
.unwrap_or("the console"),
|
||||
})
|
||||
}
|
||||
|
||||
fn finished_phases(&self) -> impl Iterator<Item = Line<'static>> + '_ {
|
||||
self.state.finished_stages.iter().map(|stage| {
|
||||
Line::from(vec![
|
||||
BRANCH.fg(self.colors.branches),
|
||||
format!("{:PHASE_WIDTH$}", stage.label).fg(self.colors.finished_label),
|
||||
format!(
|
||||
"{} done in {}",
|
||||
self.glyphs.bead,
|
||||
ELAPSED.unsigned_duration_to_string(
|
||||
&stage.reached_at.saturating_sub(stage.started_at)
|
||||
)
|
||||
)
|
||||
.fg(self.colors.finished_time),
|
||||
format!(" · {}", unit_count(stage.finished_units)).fg(self.colors.unit_count),
|
||||
if stage.failed_units > 0 {
|
||||
format!(" · {} {} failed", self.glyphs.failed, stage.failed_units)
|
||||
.fg(self.colors.failed_count)
|
||||
.bold()
|
||||
} else {
|
||||
Span::default()
|
||||
},
|
||||
])
|
||||
})
|
||||
}
|
||||
|
||||
fn concluded_phase(&self, conclusion: &Conclusion) -> Line<'static> {
|
||||
Line::from(vec![
|
||||
LAST_BRANCH.fg(self.colors.branches),
|
||||
format!(
|
||||
"{} {} finished in {}",
|
||||
self.glyphs.bead,
|
||||
conclusion.finished,
|
||||
ELAPSED.unsigned_duration_to_string(&conclusion.took)
|
||||
)
|
||||
.fg(self.colors.finished_time)
|
||||
.bold(),
|
||||
format!(" · handing over to {}", conclusion.handed_to).fg(self.colors.current),
|
||||
])
|
||||
}
|
||||
|
||||
pub fn current_phase(&self) -> Line<'static> {
|
||||
if let Some(conclusion) = self.conclusion() {
|
||||
return self.concluded_phase(&conclusion);
|
||||
}
|
||||
let started_at = self
|
||||
.state
|
||||
.finished_stages
|
||||
.last()
|
||||
.map_or(self.state.origin, |stage| stage.reached_at);
|
||||
let elapsed = ELAPSED.unsigned_duration_to_string(&self.now.saturating_sub(started_at));
|
||||
Line::from(vec![
|
||||
LAST_BRANCH.fg(self.colors.branches),
|
||||
format!("{:PHASE_WIDTH$}", self.state.phase.label())
|
||||
.fg(self.colors.current)
|
||||
.bold(),
|
||||
elapsed.fg(self.colors.current),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for Stages<'_> {
|
||||
fn render(self, area: Rect, buf: &mut Buffer) {
|
||||
Paragraph::new(self.finished_phases().collect::<Vec<_>>()).render(area, buf);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
use std::iter::successors;
|
||||
|
||||
use crate::boot_model::{RowStatus, TreeNode, TreeRow, UnitKind, flatten_forest};
|
||||
|
||||
const MIN_FOLDED_LINKS: usize = 2;
|
||||
|
||||
pub fn rows_within_height(forest: &[TreeNode], budget: usize) -> Vec<TreeRow> {
|
||||
[forest.to_vec(), fold_forest(forest.to_vec())]
|
||||
.into_iter()
|
||||
.map(flatten_forest)
|
||||
.find(|rows| rows.len() <= budget)
|
||||
.unwrap_or_else(|| {
|
||||
let essential = flatten_forest(prune_to_running(forest.to_vec(), 0)).len();
|
||||
let spare = budget.saturating_sub(essential + 1);
|
||||
flatten_forest(fold_forest(prune_to_running(forest.to_vec(), spare)))
|
||||
})
|
||||
}
|
||||
|
||||
fn fold_forest(forest: Vec<TreeNode>) -> Vec<TreeNode> {
|
||||
forest.into_iter().map(|root| root.fold(false)).collect()
|
||||
}
|
||||
|
||||
fn prune_to_running(forest: Vec<TreeNode>, mut spare: usize) -> Vec<TreeNode> {
|
||||
forest
|
||||
.into_iter()
|
||||
.filter_map(|root| {
|
||||
let anchors_the_tree = root.row.kind == UnitKind::Target;
|
||||
root.keep_on_paths_to_running(anchors_the_tree, &mut spare)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl TreeNode {
|
||||
fn leads_to_running(&self) -> bool {
|
||||
matches!(
|
||||
self.row.status,
|
||||
RowStatus::Running { .. } | RowStatus::Failed(_)
|
||||
) || self.children.iter().any(Self::leads_to_running)
|
||||
}
|
||||
|
||||
fn keep_on_paths_to_running(self, anchored: bool, spare: &mut usize) -> Option<Self> {
|
||||
if !anchored && !self.leads_to_running() {
|
||||
*spare = spare.checked_sub(1)?;
|
||||
}
|
||||
Some(Self {
|
||||
children: self
|
||||
.children
|
||||
.into_iter()
|
||||
.filter_map(|child| child.keep_on_paths_to_running(false, spare))
|
||||
.collect(),
|
||||
row: self.row,
|
||||
})
|
||||
}
|
||||
|
||||
fn is_chain_link(&self) -> bool {
|
||||
self.row.status == RowStatus::Waiting && self.children.len() == 1
|
||||
}
|
||||
|
||||
fn foldable_links(&self) -> usize {
|
||||
successors(Some(self), |cursor| {
|
||||
(cursor.is_chain_link() && cursor.children[0].is_chain_link())
|
||||
.then(|| &cursor.children[0])
|
||||
})
|
||||
.count()
|
||||
.saturating_sub(1)
|
||||
}
|
||||
|
||||
fn fold(mut self, may_absorb: bool) -> Self {
|
||||
let links = if may_absorb { self.foldable_links() } else { 0 };
|
||||
if links >= MIN_FOLDED_LINKS {
|
||||
let (chain, below) = (0..links).fold(
|
||||
(Vec::new(), self.children),
|
||||
|(mut chain, mut children), _| {
|
||||
let only = children.remove(0);
|
||||
chain.push(only.row.label);
|
||||
(chain, only.children)
|
||||
},
|
||||
);
|
||||
self.row.chain = chain;
|
||||
self.children = below;
|
||||
}
|
||||
self.children = self
|
||||
.children
|
||||
.into_iter()
|
||||
.map(|child| child.fold(true))
|
||||
.collect();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::Duration;
|
||||
|
||||
use super::*;
|
||||
use crate::{
|
||||
boot_model::{BootState, Phase},
|
||||
boot_test_fixtures::{
|
||||
activating, nested_boot_sample, queued_boot, running, tree_outline, waiting,
|
||||
},
|
||||
};
|
||||
|
||||
fn chain_state(waits: &[(&str, &[&str])], running_unit: &str) -> BootState {
|
||||
queued_boot(
|
||||
Phase::Host,
|
||||
Duration::ZERO,
|
||||
waits.iter().map(|(name, after)| {
|
||||
if *name == running_unit {
|
||||
running(name, after, Duration::ZERO)
|
||||
} else {
|
||||
waiting(name, after)
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn fitted_outline(state: &BootState, budget: usize) -> Vec<String> {
|
||||
tree_outline(&rows_within_height(
|
||||
&state.waiting_forest(Duration::MAX),
|
||||
budget,
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_chains_leading_to_running_units_stay_in_view() {
|
||||
assert_eq!(
|
||||
fitted_outline(&nested_boot_sample(), 0),
|
||||
[
|
||||
"basic.target",
|
||||
"multi-user.target",
|
||||
" docker",
|
||||
" nm-wait",
|
||||
" nm",
|
||||
"graphical.target",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spare_rows_bring_back_waiting_units_under_kept_parents() {
|
||||
let state = chain_state(
|
||||
&[
|
||||
("root.target", &["a.service", "b.service"]),
|
||||
("a.service", &["a1.service"]),
|
||||
("a1.service", &["a2.service"]),
|
||||
("a2.service", &[]),
|
||||
("b.service", &[]),
|
||||
],
|
||||
"b.service",
|
||||
);
|
||||
assert_eq!(fitted_outline(&state, 4), ["root.target", " b", " a"]);
|
||||
assert_eq!(
|
||||
fitted_outline(&state, 5),
|
||||
["root.target", " b", " a", " a1", " a2"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_child_waiting_chains_fold_into_one_row() {
|
||||
let state = chain_state(
|
||||
&[
|
||||
("root.target", &["a.service"]),
|
||||
("a.service", &["b.target"]),
|
||||
("b.target", &["c.service"]),
|
||||
("c.service", &["d.service"]),
|
||||
("d.service", &[]),
|
||||
],
|
||||
"d.service",
|
||||
);
|
||||
assert_eq!(
|
||||
fitted_outline(&state, 0),
|
||||
["root.target", " a > b.target > c", " d"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn branches_and_short_chains_stay_unfolded() {
|
||||
let state = chain_state(
|
||||
&[
|
||||
("root.target", &["a.service"]),
|
||||
("a.service", &["b.service", "c.service"]),
|
||||
("b.service", &["d.service"]),
|
||||
("c.service", &[]),
|
||||
("d.service", &[]),
|
||||
],
|
||||
"d.service",
|
||||
);
|
||||
let mut both = chain_state(
|
||||
&[
|
||||
("root.target", &["a.service"]),
|
||||
("a.service", &["b.service", "c.service"]),
|
||||
("b.service", &[]),
|
||||
("c.service", &[]),
|
||||
],
|
||||
"b.service",
|
||||
);
|
||||
both.update_activity("c.service", activating(Duration::ZERO));
|
||||
assert_eq!(
|
||||
fitted_outline(&state, 0),
|
||||
["root.target", " a", " b", " d"]
|
||||
);
|
||||
assert_eq!(
|
||||
fitted_outline(&both, 0),
|
||||
["root.target", " a", " b", " c"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_nothing_running_only_the_root_target_stays_in_view() {
|
||||
let state = queued_boot(
|
||||
Phase::Host,
|
||||
Duration::ZERO,
|
||||
[
|
||||
waiting("demo.target", &["idle.service"]),
|
||||
waiting("idle.service", &[]),
|
||||
],
|
||||
);
|
||||
assert_eq!(fitted_outline(&state, 0), ["demo.target"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
use super::screen_render_fixtures::{boot_in_progress, chain_boot, described_boot, render};
|
||||
use crate::{
|
||||
boot_model::{BootState, JobResult, Phase, UnitTimeouts},
|
||||
boot_test_fixtures::{MS, queue_unit, queued_boot, running, waiting},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn failures_stay_in_the_stage_that_wanted_them() {
|
||||
let mut state = queued_boot(
|
||||
Phase::Host,
|
||||
Duration::ZERO,
|
||||
[
|
||||
waiting("multi-user.target", &["basic.target", "web.service"]),
|
||||
waiting("basic.target", &["flaky.service", "quick.service"]),
|
||||
waiting("flaky.service", &[]),
|
||||
waiting("quick.service", &[]),
|
||||
waiting("web.service", &[]),
|
||||
],
|
||||
);
|
||||
state.finish_job(3, JobResult::Failed, 1000 * MS);
|
||||
state.finish_job(4, JobResult::Done, 1000 * MS);
|
||||
state.finish_job(2, JobResult::Done, 1500 * MS);
|
||||
let lines = render(&state, 5000 * MS, 110, 24);
|
||||
let screen = lines.join("\n");
|
||||
assert!(lines[2].starts_with(" ├─ √ basic.target"), "{screen}");
|
||||
assert!(lines[3].starts_with(" │ └─ [×] flaky"), "{screen}");
|
||||
assert!(
|
||||
lines[4].starts_with(" └─ ◆ multi-user.target"),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(lines[5].starts_with(" └─ [ ] web"), "{screen}");
|
||||
assert!(!screen.contains("quick"), "{screen}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finished_units_linger_in_place_before_leaving() {
|
||||
let mut state = queued_boot(
|
||||
Phase::Host,
|
||||
Duration::ZERO,
|
||||
[
|
||||
waiting("multi-user.target", &["early.service", "late.service"]),
|
||||
running("early.service", &[], Duration::ZERO),
|
||||
running("late.service", &[], Duration::ZERO),
|
||||
],
|
||||
);
|
||||
state.finish_job(2, JobResult::Done, 3000 * MS);
|
||||
let lingering = render(&state, 4000 * MS, 110, 24);
|
||||
let screen = lingering.join("\n");
|
||||
assert!(lingering[3].starts_with(" ├─ [√] early"), "{screen}");
|
||||
assert!(lingering[4].starts_with(" └─ [|] late"), "{screen}");
|
||||
let gone = render(&state, 5500 * MS, 110, 24);
|
||||
let tree: Vec<&String> = gone
|
||||
.iter()
|
||||
.take_while(|line| !line.contains(" Timeline "))
|
||||
.collect();
|
||||
assert!(
|
||||
tree.iter().all(|line| !line.contains("early")),
|
||||
"{}",
|
||||
gone.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_running_units_carry_a_timer() {
|
||||
let lines = render(&boot_in_progress(), 12_400 * MS, 110, 24);
|
||||
let screen = lines.join("\n");
|
||||
assert!(lines[2].ends_with("multi-user.target"), "{screen}");
|
||||
assert!(lines[3].ends_with("6.40s"), "{screen}");
|
||||
assert!(lines[5].ends_with("web"), "{screen}");
|
||||
}
|
||||
|
||||
fn timing_out_boot() -> BootState {
|
||||
let start_timeout = UnitTimeouts {
|
||||
start: Some(Duration::from_secs(90)),
|
||||
..UnitTimeouts::default()
|
||||
};
|
||||
queued_boot(
|
||||
Phase::Host,
|
||||
Duration::ZERO,
|
||||
[
|
||||
waiting(
|
||||
"multi-user.target",
|
||||
&["slow.service", "quick.service", "unlimited.service"],
|
||||
),
|
||||
running("slow.service", &[], 1000 * MS).timing_out(start_timeout),
|
||||
running("quick.service", &[], 5000 * MS).timing_out(start_timeout),
|
||||
running("unlimited.service", &[], 1000 * MS),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn line_with<'a>(lines: &'a [String], text: &str) -> &'a str {
|
||||
lines
|
||||
.iter()
|
||||
.find(|line| line.contains(text))
|
||||
.unwrap_or_else(|| panic!("{text} missing\n{}", lines.join("\n")))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slow_runs_show_their_timeout_in_a_column() {
|
||||
let lines = render(&timing_out_boot(), 7400 * MS, 110, 24);
|
||||
let screen = lines.join("\n");
|
||||
assert!(
|
||||
line_with(&lines, "Running").ends_with("Timeout"),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(
|
||||
line_with(&lines, "slow").ends_with("6.40s 1m30s"),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(line_with(&lines, "quick").ends_with("2.40s"), "{screen}");
|
||||
assert!(
|
||||
line_with(&lines, "unlimited").ends_with("6.40s"),
|
||||
"{screen}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_timeout_column_waits_for_a_slow_run() {
|
||||
let lines = render(&timing_out_boot(), 4000 * MS, 110, 24);
|
||||
assert!(
|
||||
lines.iter().all(|line| !line.contains("Timeout")),
|
||||
"{}",
|
||||
lines.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_screens_keep_the_timeout() {
|
||||
let lines = render(&timing_out_boot(), 7400 * MS, 50, 24);
|
||||
assert!(
|
||||
line_with(&lines, "slow").ends_with("1m30s"),
|
||||
"{}",
|
||||
lines.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chains_stay_unfolded_while_they_fit() {
|
||||
let lines = render(&chain_boot(), 5000 * MS, 110, 24);
|
||||
let screen = lines.join("\n");
|
||||
assert!(
|
||||
lines[3].starts_with(" └─ [ ] network-wait"),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(
|
||||
lines[4].starts_with(" └─ network.target"),
|
||||
"{screen}"
|
||||
);
|
||||
assert!(
|
||||
lines[7].starts_with(" └─ [-] udev-settle"),
|
||||
"{screen}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chains_fold_when_short_and_shorten_to_their_ends_when_narrow() {
|
||||
let short = render(&chain_boot(), 5000 * MS, 110, 9);
|
||||
assert!(
|
||||
short[3].starts_with(" └─ [ ] network-wait ─ network.target ─ network-manager ─ dbus"),
|
||||
"{}",
|
||||
short.join("\n")
|
||||
);
|
||||
assert!(
|
||||
short[4].starts_with(" └─ [-] udev-settle"),
|
||||
"{}",
|
||||
short.join("\n")
|
||||
);
|
||||
let narrow = render(&chain_boot(), 5000 * MS, 46, 8);
|
||||
assert!(
|
||||
narrow[3].starts_with(" └─ [ ] network-wait ─ … ─ dbus"),
|
||||
"{}",
|
||||
narrow.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn descriptions_line_up_in_a_column() {
|
||||
let lines = render(&described_boot(), 3000 * MS, 110, 24);
|
||||
let screen = lines.join("\n");
|
||||
let column_of = |text: &str| {
|
||||
lines
|
||||
.iter()
|
||||
.find_map(|line| line.find(text).map(|at| line[..at].width()))
|
||||
.unwrap_or_else(|| panic!("{text} missing\n{screen}"))
|
||||
};
|
||||
assert_eq!(column_of("Multi-User System"), column_of("Description"));
|
||||
assert_eq!(
|
||||
column_of("Multi-User System"),
|
||||
column_of("Docker Application")
|
||||
);
|
||||
assert_eq!(
|
||||
column_of("Multi-User System"),
|
||||
column_of("Load/Save RF Kill")
|
||||
);
|
||||
assert!(column_of("Multi-User System") > column_of("systemd-rfkill"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_service_units_carry_their_kind() {
|
||||
let mut state = described_boot();
|
||||
queue_unit(
|
||||
&mut state,
|
||||
9,
|
||||
running("docker.socket", &[], 1000 * MS).described("Docker Socket for the API"),
|
||||
Duration::ZERO,
|
||||
);
|
||||
let lines = render(&state, 3000 * MS, 110, 24);
|
||||
let screen = lines.join("\n");
|
||||
let socket_row = lines
|
||||
.iter()
|
||||
.find(|line| line.contains("Docker Socket"))
|
||||
.unwrap_or_else(|| panic!("{screen}"));
|
||||
assert!(socket_row.contains("[-] docker "), "{screen}");
|
||||
assert!(socket_row.contains(" Socket "), "{screen}");
|
||||
assert!(
|
||||
render(&described_boot(), 3000 * MS, 110, 24)
|
||||
.iter()
|
||||
.all(|line| !line.contains(" Socket ")),
|
||||
"{screen}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_screens_keep_names_and_drop_descriptions() {
|
||||
let lines = render(&described_boot(), 3000 * MS, 40, 24);
|
||||
let screen = lines.join("\n");
|
||||
assert!(screen.contains("systemd-rfkill"), "{screen}");
|
||||
assert!(!screen.contains("Docker"), "{screen}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overflowing_trees_are_cut_with_a_count() {
|
||||
let names: Vec<String> = (0..30).map(|id| format!("unit{id:02}.service")).collect();
|
||||
let state = queued_boot(
|
||||
Phase::Host,
|
||||
Duration::ZERO,
|
||||
names.iter().map(|name| waiting(name, &[])),
|
||||
);
|
||||
let lines = render(&state, 1000 * MS, 110, 20);
|
||||
assert!(
|
||||
lines.iter().any(|line| line.starts_with(" … ")),
|
||||
"{}",
|
||||
lines.join("\n")
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,427 @@
|
||||
use std::{iter::once, time::Duration};
|
||||
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
layout::{Constraint, Rect},
|
||||
style::{Style, Stylize},
|
||||
text::{Line, Span},
|
||||
widgets::{Row, Table, Widget},
|
||||
};
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
use super::{
|
||||
BRANCH, DURATION_WIDTH, ENDED_TRUNK, LAST_BRANCH, PASSING_TRUNK, RUNNING_ELAPSED, WHOLE_UNITS,
|
||||
fit_width,
|
||||
};
|
||||
use crate::{
|
||||
boot_model::{RowStatus, TreeRow, UnitKind},
|
||||
screen_settings::{color_scheme::TreeColors, font_glyphs::Glyphs},
|
||||
};
|
||||
|
||||
const SPINNER: [char; 4] = ['|', '/', '-', '\\'];
|
||||
const SPINNER_STEP: Duration = Duration::from_millis(100);
|
||||
const MIN_DESCRIPTION_WIDTH: u16 = 12;
|
||||
const MIN_TAG_WIDTH: u16 = 6;
|
||||
const MIN_LABEL_WIDTH: u16 = 24;
|
||||
const HEADER_ROWS: u16 = 1;
|
||||
const SHOW_TIMEOUT_AFTER: Duration = Duration::from_secs(5);
|
||||
const TIMEOUT_HEADER: &str = "Timeout";
|
||||
|
||||
struct RunTimeout {
|
||||
limit: Duration,
|
||||
exceeded: bool,
|
||||
}
|
||||
|
||||
pub struct UnitTree<'a> {
|
||||
pub phase: Line<'static>,
|
||||
pub rows: &'a [TreeRow],
|
||||
pub hidden: usize,
|
||||
pub now: Duration,
|
||||
pub hide_runs_shorter_than: Duration,
|
||||
pub colors: &'a TreeColors,
|
||||
pub glyphs: &'a Glyphs,
|
||||
}
|
||||
|
||||
struct Columns {
|
||||
label: u16,
|
||||
tag: u16,
|
||||
description: u16,
|
||||
timeout: u16,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Stage {
|
||||
Reached,
|
||||
Current,
|
||||
Upcoming,
|
||||
Inside,
|
||||
}
|
||||
|
||||
fn opens_a_stage(row: &TreeRow) -> bool {
|
||||
row.depth == 0 && row.kind == UnitKind::Target
|
||||
}
|
||||
|
||||
fn spinner_at(now: Duration) -> char {
|
||||
let steps = now.as_millis() / SPINNER_STEP.as_millis();
|
||||
SPINNER[usize::try_from(steps % 4).unwrap_or_default()]
|
||||
}
|
||||
|
||||
fn width_of(text: &str) -> u16 {
|
||||
u16::try_from(text.width()).unwrap_or(u16::MAX)
|
||||
}
|
||||
|
||||
impl UnitTree<'_> {
|
||||
pub fn height_of(rows: usize, hidden: usize) -> u16 {
|
||||
u16::try_from(rows + usize::from(hidden > 0))
|
||||
.unwrap_or(u16::MAX)
|
||||
.saturating_add(HEADER_ROWS)
|
||||
}
|
||||
|
||||
pub fn height(&self) -> u16 {
|
||||
Self::height_of(self.rows.len(), self.hidden)
|
||||
}
|
||||
|
||||
fn phase_fits_its_column(&self, columns: &Columns) -> bool {
|
||||
self.phase.width() <= usize::from(columns.label)
|
||||
}
|
||||
|
||||
fn header(&self, columns: &Columns) -> Row<'static> {
|
||||
if !self.phase_fits_its_column(columns) {
|
||||
return Row::default().height(HEADER_ROWS);
|
||||
}
|
||||
let name = |text: &'static str| Line::from(text).fg(self.colors.columns);
|
||||
Row::new(columns.shown([
|
||||
self.phase.clone(),
|
||||
name("Kind"),
|
||||
name("Description"),
|
||||
name("Running").right_aligned(),
|
||||
name(TIMEOUT_HEADER).right_aligned(),
|
||||
]))
|
||||
}
|
||||
|
||||
fn run_timeout(&self, row: &TreeRow) -> Option<RunTimeout> {
|
||||
let RowStatus::Running {
|
||||
since,
|
||||
deadline: Some(deadline),
|
||||
..
|
||||
} = row.status
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let elapsed = self.now.saturating_sub(since);
|
||||
let limit = deadline.saturating_sub(since);
|
||||
(elapsed >= SHOW_TIMEOUT_AFTER).then_some(RunTimeout {
|
||||
limit,
|
||||
exceeded: elapsed >= limit,
|
||||
})
|
||||
}
|
||||
|
||||
fn timeout_width(&self) -> u16 {
|
||||
self.rows
|
||||
.iter()
|
||||
.filter_map(|row| self.run_timeout(row))
|
||||
.map(|timeout| width_of(&WHOLE_UNITS.unsigned_duration_to_string(&timeout.limit)))
|
||||
.max()
|
||||
.map_or(0, |widest| widest.max(width_of(TIMEOUT_HEADER)))
|
||||
}
|
||||
|
||||
fn timeout_cell(&self, row: &TreeRow) -> Line<'static> {
|
||||
self.run_timeout(row)
|
||||
.map_or_else(Line::default, |timeout| {
|
||||
let color = if timeout.exceeded {
|
||||
self.colors.failed_unit
|
||||
} else {
|
||||
self.colors.columns
|
||||
};
|
||||
Line::from(WHOLE_UNITS.unsigned_duration_to_string(&timeout.limit)).fg(color)
|
||||
})
|
||||
.right_aligned()
|
||||
}
|
||||
|
||||
fn stages(&self) -> impl Iterator<Item = Stage> + '_ {
|
||||
let current = self
|
||||
.rows
|
||||
.iter()
|
||||
.position(|row| opens_a_stage(row) && row.status != RowStatus::Done);
|
||||
self.rows.iter().enumerate().map(move |(index, row)| {
|
||||
if Some(index) == current {
|
||||
Stage::Current
|
||||
} else if opens_a_stage(row) && row.status == RowStatus::Done {
|
||||
Stage::Reached
|
||||
} else if opens_a_stage(row) {
|
||||
Stage::Upcoming
|
||||
} else {
|
||||
Stage::Inside
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn label_style(&self, row: &TreeRow, stage: Stage) -> Style {
|
||||
match stage {
|
||||
Stage::Current => Style::from(self.colors.current_stage).bold(),
|
||||
Stage::Reached => self.colors.reached_stage.into(),
|
||||
Stage::Upcoming | Stage::Inside => self.unit_label_style(row),
|
||||
}
|
||||
}
|
||||
|
||||
fn unit_label_style(&self, row: &TreeRow) -> Style {
|
||||
match row.status {
|
||||
RowStatus::Failed(kind) if kind.has_own_cause() => {
|
||||
Style::from(self.colors.failed_unit).bold()
|
||||
}
|
||||
RowStatus::Failed(_) => Style::from(self.colors.failed_unit).dim(),
|
||||
_ if row.kind == UnitKind::Target => self.colors.target.into(),
|
||||
RowStatus::Running { .. } => self.colors.running_unit.into(),
|
||||
RowStatus::Waiting => self.colors.waiting_unit.into(),
|
||||
RowStatus::Done => self.colors.finished_unit.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn status_marker(&self, row: &TreeRow, stage: Stage) -> Span<'static> {
|
||||
match stage {
|
||||
Stage::Current => {
|
||||
format!("{} ", self.glyphs.stage_current).fg(self.colors.current_stage)
|
||||
}
|
||||
Stage::Upcoming => format!("{} ", self.glyphs.stage_upcoming).fg(self.colors.target),
|
||||
Stage::Reached => format!("{} ", self.glyphs.done).fg(self.colors.reached_stage),
|
||||
Stage::Inside => self.unit_marker(row),
|
||||
}
|
||||
}
|
||||
|
||||
fn unit_marker(&self, row: &TreeRow) -> Span<'static> {
|
||||
match row.status {
|
||||
RowStatus::Failed(_) => {
|
||||
format!("[{}] ", self.glyphs.failed).fg(self.colors.failed_unit)
|
||||
}
|
||||
_ if row.kind == UnitKind::Target => Span::default(),
|
||||
RowStatus::Running { .. } => {
|
||||
format!("[{}] ", spinner_at(self.now)).fg(self.colors.running_marker)
|
||||
}
|
||||
RowStatus::Waiting => "[ ] ".fg(self.colors.waiting_unit),
|
||||
RowStatus::Done => format!("[{}] ", self.glyphs.done).fg(self.colors.finished_marker),
|
||||
}
|
||||
}
|
||||
|
||||
fn chained_label(&self, row: &TreeRow, room: usize) -> String {
|
||||
let link = format!(" {} ", self.glyphs.chain_link);
|
||||
let full: String = once(row.label.as_str())
|
||||
.chain(row.chain.iter().map(String::as_str))
|
||||
.collect::<Vec<_>>()
|
||||
.join(&link);
|
||||
let label = match row.chain.as_slice() {
|
||||
[_, .., last] if full.width() > room => {
|
||||
format!("{}{link}{}{link}{last}", row.label, self.glyphs.ellipsis)
|
||||
}
|
||||
_ => full,
|
||||
};
|
||||
fit_width(&label, room, self.glyphs.ellipsis)
|
||||
}
|
||||
|
||||
fn columns(&self, width: u16) -> Columns {
|
||||
let timeout = self.timeout_width();
|
||||
let timeout_room = if timeout > 0 { timeout + 1 } else { 0 };
|
||||
let unannotated = width.saturating_sub(DURATION_WIDTH + 1 + timeout_room);
|
||||
let annotated: Vec<(&TreeRow, Stage)> = self
|
||||
.rows
|
||||
.iter()
|
||||
.zip(self.stages())
|
||||
.filter(|(row, _)| {
|
||||
row.chain.is_empty() && !(row.description.is_none() && row.kind.tag().is_none())
|
||||
})
|
||||
.collect();
|
||||
let tag = annotated
|
||||
.iter()
|
||||
.map(|(row, _)| width_of(row.kind.tag().unwrap_or_default()))
|
||||
.fold(MIN_TAG_WIDTH, u16::max);
|
||||
let content = unannotated.saturating_sub(2);
|
||||
let label = (content * 3 / 5).max(MIN_LABEL_WIDTH);
|
||||
let fits_annotations =
|
||||
!annotated.is_empty() && label + tag + MIN_DESCRIPTION_WIDTH <= content;
|
||||
fits_annotations.then_some(label).map_or(
|
||||
Columns {
|
||||
label: unannotated,
|
||||
tag: 0,
|
||||
description: 0,
|
||||
timeout,
|
||||
},
|
||||
|label| Columns {
|
||||
label,
|
||||
tag,
|
||||
description: content - label - tag,
|
||||
timeout,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn row(&self, row: &TreeRow, stage: Stage, prefix: String, columns: &Columns) -> Row<'static> {
|
||||
let marker = self.status_marker(row, stage);
|
||||
let room = usize::from(columns.label).saturating_sub(prefix.width() + marker.width());
|
||||
let annotation = |text: &str, width: u16| {
|
||||
if row.chain.is_empty() {
|
||||
fit_width(text, usize::from(width), self.glyphs.ellipsis)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
};
|
||||
let timer = match row.status {
|
||||
RowStatus::Running { since, .. }
|
||||
if self.now.saturating_sub(since) >= self.hide_runs_shorter_than =>
|
||||
{
|
||||
RUNNING_ELAPSED.unsigned_duration_to_string(&self.now.saturating_sub(since))
|
||||
}
|
||||
_ => String::new(),
|
||||
};
|
||||
let style = self.label_style(row, stage);
|
||||
Row::new(
|
||||
columns.shown([
|
||||
Line::from(vec![
|
||||
prefix.fg(self.colors.branches),
|
||||
marker,
|
||||
Span::styled(self.chained_label(row, room), style),
|
||||
]),
|
||||
Line::from(annotation(row.kind.tag().unwrap_or_default(), columns.tag))
|
||||
.fg(self.colors.columns),
|
||||
Line::from(annotation(
|
||||
row.description.as_deref().unwrap_or_default(),
|
||||
columns.description,
|
||||
))
|
||||
.fg(self.colors.columns),
|
||||
Line::from(timer).style(style).right_aligned(),
|
||||
self.timeout_cell(row),
|
||||
]),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Columns {
|
||||
fn shown<T>(&self, cells: [T; 5]) -> impl Iterator<Item = T> {
|
||||
let present = [
|
||||
true,
|
||||
self.tag > 0,
|
||||
self.description > 0,
|
||||
true,
|
||||
self.timeout > 0,
|
||||
];
|
||||
cells
|
||||
.into_iter()
|
||||
.zip(present)
|
||||
.filter_map(|(cell, present)| present.then_some(cell))
|
||||
}
|
||||
|
||||
fn widths(&self) -> impl Iterator<Item = Constraint> {
|
||||
self.shown([
|
||||
self.label,
|
||||
self.tag,
|
||||
self.description,
|
||||
DURATION_WIDTH,
|
||||
self.timeout,
|
||||
])
|
||||
.map(Constraint::Length)
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for UnitTree<'_> {
|
||||
fn render(self, area: Rect, buf: &mut Buffer) {
|
||||
let capacity = usize::from(area.height.saturating_sub(HEADER_ROWS));
|
||||
let shown = if usize::from(self.height() - HEADER_ROWS) > capacity {
|
||||
capacity.saturating_sub(1).min(self.rows.len())
|
||||
} else {
|
||||
self.rows.len()
|
||||
};
|
||||
let hidden = self.rows.len() - shown + self.hidden;
|
||||
let overflow = (hidden > 0).then(|| {
|
||||
Row::new([
|
||||
format!("{ENDED_TRUNK}{} {hidden} more", self.glyphs.ellipsis)
|
||||
.fg(self.colors.overflow),
|
||||
])
|
||||
});
|
||||
let columns = self.columns(area.width);
|
||||
Table::new(
|
||||
self.rows
|
||||
.iter()
|
||||
.zip(self.stages())
|
||||
.zip(tree_prefixes(self.rows))
|
||||
.take(shown)
|
||||
.map(|((row, stage), prefix)| self.row(row, stage, prefix, &columns))
|
||||
.chain(overflow),
|
||||
columns.widths(),
|
||||
)
|
||||
.header(self.header(&columns))
|
||||
.render(area, buf);
|
||||
if !self.phase_fits_its_column(&columns) {
|
||||
self.phase.render(Rect { height: 1, ..area }, buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn tree_prefixes(rows: &[TreeRow]) -> Vec<String> {
|
||||
let is_last = rows
|
||||
.iter()
|
||||
.rev()
|
||||
.scan(Vec::<bool>::new(), |later_sibling, row| {
|
||||
let last = !later_sibling.get(row.depth).copied().unwrap_or(false);
|
||||
later_sibling.resize(row.depth + 1, false);
|
||||
later_sibling[row.depth] = true;
|
||||
Some(last)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter()
|
||||
.rev();
|
||||
rows.iter()
|
||||
.zip(is_last)
|
||||
.scan(Vec::<&str>::new(), |trunks, (row, last)| {
|
||||
trunks.truncate(row.depth);
|
||||
let connector = if last { LAST_BRANCH } else { BRANCH };
|
||||
let prefix = once(ENDED_TRUNK)
|
||||
.chain(trunks.iter().copied())
|
||||
.chain(once(connector))
|
||||
.collect();
|
||||
trunks.push(if last { ENDED_TRUNK } else { PASSING_TRUNK });
|
||||
Some(prefix)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_spinner_turns_once_per_step_whatever_the_frame_rate() {
|
||||
let turned: String = (0..5)
|
||||
.map(|step| spinner_at(SPINNER_STEP * step + Duration::from_millis(16)))
|
||||
.collect();
|
||||
assert_eq!(turned, "|/-\\|");
|
||||
assert_eq!(
|
||||
spinner_at(Duration::from_millis(99)),
|
||||
spinner_at(Duration::ZERO)
|
||||
);
|
||||
}
|
||||
|
||||
fn at_depth(depth: usize) -> TreeRow {
|
||||
TreeRow {
|
||||
depth,
|
||||
label: String::new(),
|
||||
description: None,
|
||||
kind: UnitKind::Service,
|
||||
status: RowStatus::Waiting,
|
||||
chain: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefixes_close_each_branch_at_its_last_sibling() {
|
||||
let rows: Vec<TreeRow> = [0, 0, 1, 1, 2, 0].into_iter().map(at_depth).collect();
|
||||
assert_eq!(
|
||||
tree_prefixes(&rows),
|
||||
[
|
||||
" ├─ ",
|
||||
" ├─ ",
|
||||
" │ ├─ ",
|
||||
" │ └─ ",
|
||||
" │ └─ ",
|
||||
" └─ ",
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
pub mod ask_password;
|
||||
pub mod console_palette;
|
||||
pub mod console_takeover;
|
||||
pub mod live_desk;
|
||||
pub mod passphrase_input;
|
||||
pub mod stream_sources;
|
||||
pub mod watch_loop;
|
||||
pub mod watch_screen;
|
||||
@@ -0,0 +1,295 @@
|
||||
use std::{
|
||||
fs, io, iter,
|
||||
os::{
|
||||
fd::{AsRawFd, OwnedFd, RawFd},
|
||||
unix::net::UnixDatagram,
|
||||
},
|
||||
path::{Path, PathBuf},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use crossterm::event::Event;
|
||||
use rustix::{
|
||||
fs::inotify::{self, CreateFlags, WatchFlags},
|
||||
io::read,
|
||||
process::{Pid, test_kill_process},
|
||||
};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::{
|
||||
boot_view::PasswordPrompt, console_session::passphrase_input,
|
||||
systemd_link::monotonic_clock::monotonic_now,
|
||||
};
|
||||
|
||||
const REQUESTS: &str = "/run/systemd/ask-password";
|
||||
const REQUEST_PREFIX: &str = "ask.";
|
||||
const ASK_SECTION: &str = "[Ask]";
|
||||
const INOTIFY_BUFFER: usize = 4096;
|
||||
|
||||
pub struct RequestWatch {
|
||||
inotify: OwnedFd,
|
||||
}
|
||||
|
||||
impl RequestWatch {
|
||||
#[must_use]
|
||||
pub fn open() -> Option<Self> {
|
||||
fs::create_dir_all(REQUESTS).ok()?;
|
||||
let inotify = inotify::init(CreateFlags::CLOEXEC | CreateFlags::NONBLOCK).ok()?;
|
||||
inotify::add_watch(
|
||||
&inotify,
|
||||
REQUESTS,
|
||||
WatchFlags::CLOSE_WRITE
|
||||
| WatchFlags::MOVED_TO
|
||||
| WatchFlags::MOVED_FROM
|
||||
| WatchFlags::DELETE
|
||||
| WatchFlags::ONLYDIR,
|
||||
)
|
||||
.ok()?;
|
||||
Some(Self { inotify })
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn changed(&self) -> bool {
|
||||
let mut events = [0_u8; INOTIFY_BUFFER];
|
||||
iter::from_fn(|| {
|
||||
read(&self.inotify, &mut events)
|
||||
.ok()
|
||||
.filter(|read| *read > 0)
|
||||
})
|
||||
.count()
|
||||
> 0
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRawFd for RequestWatch {
|
||||
fn as_raw_fd(&self) -> RawFd {
|
||||
self.inotify.as_raw_fd()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct PasswordRequest {
|
||||
pub file: PathBuf,
|
||||
pub message: String,
|
||||
socket: PathBuf,
|
||||
echo: bool,
|
||||
silent: bool,
|
||||
not_after: Option<Duration>,
|
||||
asker: Option<Pid>,
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn requested() -> bool {
|
||||
!request_files().is_empty()
|
||||
}
|
||||
|
||||
fn request_files() -> Vec<PathBuf> {
|
||||
let mut files: Vec<PathBuf> = fs::read_dir(REQUESTS)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter(|entry| {
|
||||
entry
|
||||
.file_name()
|
||||
.to_string_lossy()
|
||||
.starts_with(REQUEST_PREFIX)
|
||||
})
|
||||
.map(|entry| entry.path())
|
||||
.collect();
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
|
||||
impl PasswordRequest {
|
||||
fn read(file: &Path) -> Option<Self> {
|
||||
Self::parse(file, &fs::read_to_string(file).ok()?)
|
||||
}
|
||||
|
||||
fn parse(file: &Path, text: &str) -> Option<Self> {
|
||||
let fields: Vec<(&str, &str)> = text
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.skip_while(|line| *line != ASK_SECTION)
|
||||
.skip(1)
|
||||
.take_while(|line| !line.starts_with('['))
|
||||
.filter_map(|line| line.split_once('='))
|
||||
.collect();
|
||||
let field = |key: &str| {
|
||||
fields
|
||||
.iter()
|
||||
.find(|(name, _)| *name == key)
|
||||
.map(|(_, value)| *value)
|
||||
};
|
||||
let flag = |key: &str| field(key).is_some_and(is_true);
|
||||
Some(Self {
|
||||
file: file.to_owned(),
|
||||
message: field("Message").unwrap_or_default().to_owned(),
|
||||
socket: PathBuf::from(field("Socket")?),
|
||||
echo: flag("Echo"),
|
||||
silent: flag("Silent"),
|
||||
not_after: field("NotAfter")
|
||||
.and_then(|value| value.parse().ok())
|
||||
.filter(|micros| *micros > 0)
|
||||
.map(Duration::from_micros),
|
||||
asker: field("PID")
|
||||
.and_then(|value| value.parse().ok())
|
||||
.and_then(Pid::from_raw),
|
||||
})
|
||||
}
|
||||
|
||||
fn is_awaited(&self) -> bool {
|
||||
self.not_after
|
||||
.is_none_or(|deadline| monotonic_now() <= deadline)
|
||||
&& self
|
||||
.asker
|
||||
.is_none_or(|asker| test_kill_process(asker).is_ok())
|
||||
}
|
||||
|
||||
fn answer(&self, password: &str) -> io::Result<()> {
|
||||
let mut packet = Zeroizing::new(Vec::with_capacity(password.len() + 1));
|
||||
packet.push(b'+');
|
||||
packet.extend_from_slice(password.as_bytes());
|
||||
UnixDatagram::unbound()?.send_to(&packet, &self.socket)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn is_true(value: &str) -> bool {
|
||||
matches!(
|
||||
value.to_ascii_lowercase().as_str(),
|
||||
"1" | "yes" | "y" | "true" | "t" | "on"
|
||||
)
|
||||
}
|
||||
|
||||
pub struct PasswordEntry {
|
||||
request: PasswordRequest,
|
||||
typed: Zeroizing<String>,
|
||||
sent: bool,
|
||||
}
|
||||
|
||||
impl PasswordEntry {
|
||||
pub fn follow(current: Option<Self>, requests_changed: bool) -> Option<Self> {
|
||||
match current {
|
||||
Some(entry) if entry.is_live(requests_changed) => return Some(entry),
|
||||
None if !requests_changed => return None,
|
||||
_ => {}
|
||||
}
|
||||
let entry = request_files()
|
||||
.iter()
|
||||
.filter_map(|file| PasswordRequest::read(file))
|
||||
.find_map(Self::open)?;
|
||||
eprintln!(
|
||||
"bootvine: asking for a password: {}",
|
||||
entry.request.file.display()
|
||||
);
|
||||
Some(entry)
|
||||
}
|
||||
|
||||
fn open(request: PasswordRequest) -> Option<Self> {
|
||||
if !request.is_awaited() {
|
||||
return None;
|
||||
}
|
||||
Some(Self {
|
||||
request,
|
||||
typed: passphrase_input::empty(),
|
||||
sent: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn is_live(&self, requests_changed: bool) -> bool {
|
||||
self.request.is_awaited() && (!requests_changed || self.request.file.exists())
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn prompt(&self) -> PasswordPrompt<'_> {
|
||||
let input = if self.request.silent {
|
||||
String::new()
|
||||
} else if self.request.echo {
|
||||
self.typed.to_string()
|
||||
} else {
|
||||
passphrase_input::masked(&self.typed)
|
||||
};
|
||||
PasswordPrompt {
|
||||
message: &self.request.message,
|
||||
hint: None,
|
||||
input,
|
||||
sent: self.sent,
|
||||
rejected: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn type_key(&mut self, event: &Event) -> io::Result<()> {
|
||||
if self.sent {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(submitted) = passphrase_input::type_key(&mut self.typed, event) else {
|
||||
return Ok(());
|
||||
};
|
||||
self.request.answer(&submitted)?;
|
||||
self.sent = true;
|
||||
eprintln!("bootvine: answered a password prompt");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crossterm::event::{KeyCode, KeyEvent};
|
||||
|
||||
use super::*;
|
||||
|
||||
const CRYPTSETUP_ASK: &str = concat!(
|
||||
"[Ask]\n",
|
||||
"PID=1\n",
|
||||
"Socket=/run/systemd/ask-password/sck.1\n",
|
||||
"AcceptCached=1\n",
|
||||
"Echo=0\n",
|
||||
"NotAfter=0\n",
|
||||
"Message=Please enter passphrase for disk secret:\n",
|
||||
"Icon=drive-harddisk\n",
|
||||
"Id=cryptsetup:/dev/vdb\n",
|
||||
);
|
||||
|
||||
#[test]
|
||||
fn reads_what_cryptsetup_asks() {
|
||||
let request = PasswordRequest::parse(Path::new("ask.x"), CRYPTSETUP_ASK).expect("parsed");
|
||||
assert_eq!(
|
||||
request,
|
||||
PasswordRequest {
|
||||
file: PathBuf::from("ask.x"),
|
||||
message: "Please enter passphrase for disk secret:".to_owned(),
|
||||
socket: PathBuf::from("/run/systemd/ask-password/sck.1"),
|
||||
echo: false,
|
||||
silent: false,
|
||||
not_after: None,
|
||||
asker: Pid::from_raw(1),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_requests_without_a_socket() {
|
||||
assert_eq!(
|
||||
PasswordRequest::parse(Path::new("ask.x"), "[Ask]\nMessage=hi\n"),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hides_what_is_typed() {
|
||||
let mut entry = PasswordEntry {
|
||||
request: PasswordRequest::parse(Path::new("ask.x"), CRYPTSETUP_ASK).expect("parsed"),
|
||||
typed: passphrase_input::empty(),
|
||||
sent: false,
|
||||
};
|
||||
"secret".chars().for_each(|character| {
|
||||
entry
|
||||
.type_key(&Event::Key(KeyEvent::from(KeyCode::Char(character))))
|
||||
.expect("typed");
|
||||
});
|
||||
entry
|
||||
.type_key(&Event::Key(KeyEvent::from(KeyCode::Backspace)))
|
||||
.expect("erased");
|
||||
assert_eq!(entry.prompt().input, "*****");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
style::{Color, Modifier},
|
||||
};
|
||||
|
||||
use crate::screen_settings::font_glyphs::Glyphs;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum ConsolePalette {
|
||||
#[default]
|
||||
Terminal,
|
||||
SixteenColorVt,
|
||||
EightColorVt,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ConsoleLook {
|
||||
pub glyphs: Glyphs,
|
||||
pub palette: ConsolePalette,
|
||||
}
|
||||
|
||||
impl ConsolePalette {
|
||||
pub fn fit_frame(self, frame: &mut Buffer) {
|
||||
if self == Self::Terminal {
|
||||
return;
|
||||
}
|
||||
frame.content.iter_mut().for_each(|cell| {
|
||||
cell.modifier.remove(Modifier::BOLD);
|
||||
if self == Self::EightColorVt {
|
||||
cell.fg = without_brightness(cell.fg);
|
||||
cell.bg = without_brightness(cell.bg);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn without_brightness(color: Color) -> Color {
|
||||
match color {
|
||||
Color::DarkGray | Color::White => Color::Gray,
|
||||
Color::LightRed => Color::Red,
|
||||
Color::LightGreen => Color::Green,
|
||||
Color::LightYellow => Color::Yellow,
|
||||
Color::LightBlue => Color::Blue,
|
||||
Color::LightMagenta => Color::Magenta,
|
||||
Color::LightCyan => Color::Cyan,
|
||||
Color::Indexed(bright @ 8..=15) => Color::Indexed(bright - 8),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use ratatui::{layout::Rect, style::Style};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn frame_painted(style: Style) -> Buffer {
|
||||
let mut frame = Buffer::empty(Rect::new(0, 0, 1, 1));
|
||||
frame.set_style(frame.area, style);
|
||||
frame
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eight_color_consoles_keep_dark_gray_visible() {
|
||||
let mut frame = frame_painted(Style::new().fg(Color::DarkGray).bold());
|
||||
ConsolePalette::EightColorVt.fit_frame(&mut frame);
|
||||
assert_eq!(frame.content[0].fg, Color::Gray);
|
||||
assert!(!frame.content[0].modifier.contains(Modifier::BOLD));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eight_color_consoles_fold_bright_colors_onto_normal_ones() {
|
||||
let mut frame = frame_painted(Style::new().fg(Color::LightYellow).bg(Color::Indexed(12)));
|
||||
ConsolePalette::EightColorVt.fit_frame(&mut frame);
|
||||
assert_eq!(frame.content[0].fg, Color::Yellow);
|
||||
assert_eq!(frame.content[0].bg, Color::Indexed(4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sixteen_color_consoles_only_lose_bold() {
|
||||
let mut frame = frame_painted(Style::new().fg(Color::DarkGray).bold());
|
||||
ConsolePalette::SixteenColorVt.fit_frame(&mut frame);
|
||||
assert_eq!(frame.content[0].fg, Color::DarkGray);
|
||||
assert!(!frame.content[0].modifier.contains(Modifier::BOLD));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminals_keep_the_frame_as_drawn() {
|
||||
let mut frame = frame_painted(Style::new().fg(Color::DarkGray).bold());
|
||||
ConsolePalette::Terminal.fit_frame(&mut frame);
|
||||
assert_eq!(frame.content[0].fg, Color::DarkGray);
|
||||
assert!(frame.content[0].modifier.contains(Modifier::BOLD));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
use std::{collections::HashSet, fs, mem, ptr};
|
||||
|
||||
use rustix::{
|
||||
io::Errno,
|
||||
ioctl::{Getter, IntegerSetter, Opcode, Updater, ioctl},
|
||||
stdio::stdin,
|
||||
termios::ttyname,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
console_session::{
|
||||
ask_password,
|
||||
console_palette::{ConsoleLook, ConsolePalette},
|
||||
},
|
||||
screen_settings::font_glyphs::Glyphs,
|
||||
};
|
||||
|
||||
const GIO_UNIMAP: Opcode = 0x4B66;
|
||||
const VT_GETSTATE: Opcode = 0x5603;
|
||||
const VT_ACTIVATE: Opcode = 0x5606;
|
||||
const VIRTUAL_TERMINAL_PREFIX: &str = "/dev/tty";
|
||||
const KERNEL_PRINTK: &str = "/proc/sys/kernel/printk";
|
||||
const ALERTS_ONLY: &str = "1";
|
||||
const HIGHEST_LOW_GLYPH: u16 = 255;
|
||||
|
||||
pub(super) struct QuietKernelConsole {
|
||||
previous_level: String,
|
||||
}
|
||||
|
||||
fn console_level() -> Option<String> {
|
||||
let levels = fs::read_to_string(KERNEL_PRINTK).ok()?;
|
||||
levels.split_whitespace().next().map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
impl QuietKernelConsole {
|
||||
pub(super) fn take() -> Option<Self> {
|
||||
let previous_level = console_level()?;
|
||||
fs::write(KERNEL_PRINTK, ALERTS_ONLY).ok()?;
|
||||
Some(Self { previous_level })
|
||||
}
|
||||
|
||||
pub(super) fn keep_quiet(&mut self) -> bool {
|
||||
let Some(level) = console_level() else {
|
||||
return false;
|
||||
};
|
||||
if level == ALERTS_ONLY || fs::write(KERNEL_PRINTK, ALERTS_ONLY).is_err() {
|
||||
return false;
|
||||
}
|
||||
self.previous_level = level;
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
struct LoadedFont {
|
||||
characters: HashSet<char>,
|
||||
uses_high_glyphs: bool,
|
||||
}
|
||||
|
||||
pub(super) fn console_look(own_vt: Option<u16>) -> ConsoleLook {
|
||||
let font = loaded_font();
|
||||
let glyphs = font.as_ref().map_or_else(Glyphs::default, |font| {
|
||||
Glyphs::fitting(|symbol| symbol.is_ascii() || font.characters.contains(&symbol))
|
||||
});
|
||||
let palette = match own_vt {
|
||||
None => ConsolePalette::Terminal,
|
||||
Some(_) if font.as_ref().is_some_and(|font| font.uses_high_glyphs) => {
|
||||
ConsolePalette::EightColorVt
|
||||
}
|
||||
Some(_) => ConsolePalette::SixteenColorVt,
|
||||
};
|
||||
ConsoleLook { glyphs, palette }
|
||||
}
|
||||
|
||||
impl Drop for QuietKernelConsole {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::write(KERNEL_PRINTK, &self.previous_level);
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct UnicodePair {
|
||||
unicode: u16,
|
||||
font_position: u16,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct UnicodeMap {
|
||||
count: u16,
|
||||
pairs: *mut UnicodePair,
|
||||
}
|
||||
|
||||
fn read_unicode_map(map: &mut UnicodeMap) -> Result<(), Errno> {
|
||||
unsafe { ioctl(stdin(), Updater::<GIO_UNIMAP, UnicodeMap>::new(map)) }
|
||||
}
|
||||
|
||||
fn loaded_font() -> Option<LoadedFont> {
|
||||
let mut probe = UnicodeMap {
|
||||
count: 0,
|
||||
pairs: ptr::null_mut(),
|
||||
};
|
||||
let _ = read_unicode_map(&mut probe);
|
||||
if probe.count == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut pairs = vec![UnicodePair::default(); usize::from(probe.count)];
|
||||
let mut map = UnicodeMap {
|
||||
count: probe.count,
|
||||
pairs: pairs.as_mut_ptr(),
|
||||
};
|
||||
read_unicode_map(&mut map).ok()?;
|
||||
let mapped = &pairs[..usize::from(map.count).min(pairs.len())];
|
||||
Some(LoadedFont {
|
||||
characters: mapped
|
||||
.iter()
|
||||
.filter_map(|pair| char::from_u32(u32::from(pair.unicode)))
|
||||
.collect(),
|
||||
uses_high_glyphs: mapped
|
||||
.iter()
|
||||
.any(|pair| pair.font_position > HIGHEST_LOW_GLYPH),
|
||||
})
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct VtState {
|
||||
active: u16,
|
||||
_signal: u16,
|
||||
_state: u16,
|
||||
}
|
||||
|
||||
pub(super) struct ForegroundVt {
|
||||
own: u16,
|
||||
previous: u16,
|
||||
}
|
||||
|
||||
fn active_vt() -> Option<u16> {
|
||||
let state: VtState = unsafe { ioctl(stdin(), Getter::<VT_GETSTATE, VtState>::new()) }.ok()?;
|
||||
Some(state.active)
|
||||
}
|
||||
|
||||
pub(super) fn vt_of_stdin() -> Option<u16> {
|
||||
let name = ttyname(stdin(), Vec::new()).ok()?;
|
||||
name.to_str()
|
||||
.ok()?
|
||||
.strip_prefix(VIRTUAL_TERMINAL_PREFIX)?
|
||||
.parse()
|
||||
.ok()
|
||||
.filter(|number| *number > 0)
|
||||
}
|
||||
|
||||
impl ForegroundVt {
|
||||
pub(super) fn take(own: u16) -> Option<Self> {
|
||||
let previous = active_vt()?;
|
||||
if previous != own {
|
||||
activate(own).ok()?;
|
||||
}
|
||||
Some(Self { own, previous })
|
||||
}
|
||||
|
||||
pub(super) fn insist(&self) -> bool {
|
||||
self.taken_away() && activate(self.own).is_ok()
|
||||
}
|
||||
|
||||
pub(super) fn taken_away(&self) -> bool {
|
||||
active_vt().is_some_and(|active| active != self.own)
|
||||
}
|
||||
|
||||
pub(super) fn stay_switched(self) {
|
||||
mem::forget(self);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ForegroundVt {
|
||||
fn drop(&mut self) {
|
||||
if ask_password::requested() {
|
||||
eprintln!("bootvine: leaving a password prompt to the console agent on this terminal");
|
||||
return;
|
||||
}
|
||||
let _ = activate(self.previous);
|
||||
}
|
||||
}
|
||||
|
||||
fn activate(number: u16) -> Result<(), Errno> {
|
||||
let number = usize::from(number);
|
||||
unsafe { ioctl(stdin(), IntegerSetter::<VT_ACTIVATE>::new_usize(number)) }
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
use std::{future::ready, io, ops::ControlFlow, time::Duration};
|
||||
|
||||
use crossterm::event::Event;
|
||||
use futures::{Stream, StreamExt};
|
||||
|
||||
use crate::{
|
||||
boot_model::BootChange,
|
||||
boot_view::PasswordPrompt,
|
||||
console_session::{
|
||||
ask_password::{self, PasswordEntry, RequestWatch},
|
||||
console_palette::ConsoleLook,
|
||||
console_takeover::{ForegroundVt, QuietKernelConsole, console_look, vt_of_stdin},
|
||||
passphrase_input::asks_to_quit,
|
||||
stream_sources::items_when_readable,
|
||||
watch_screen::{ConsoleDesk, Refresh, ScreenInput, WatchEnding},
|
||||
},
|
||||
};
|
||||
|
||||
pub struct LiveDesk {
|
||||
quiet_kernel: Option<QuietKernelConsole>,
|
||||
foreground: Option<ForegroundVt>,
|
||||
for_system: bool,
|
||||
own_vt: Option<u16>,
|
||||
look: ConsoleLook,
|
||||
entry: Option<PasswordEntry>,
|
||||
handover_deadline: Option<Duration>,
|
||||
}
|
||||
|
||||
impl LiveDesk {
|
||||
#[must_use]
|
||||
pub fn take_console(for_system: bool) -> Self {
|
||||
let prompt_elsewhere = for_system && ask_password::requested();
|
||||
if prompt_elsewhere {
|
||||
eprintln!("bootvine: a password prompt is already showing, staying behind it");
|
||||
}
|
||||
let own_vt = vt_of_stdin();
|
||||
Self {
|
||||
quiet_kernel: for_system.then(QuietKernelConsole::take).flatten(),
|
||||
foreground: own_vt
|
||||
.filter(|_| !prompt_elsewhere)
|
||||
.and_then(ForegroundVt::take),
|
||||
for_system,
|
||||
own_vt,
|
||||
look: console_look(own_vt),
|
||||
entry: None,
|
||||
handover_deadline: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn come_forward_once_prompts_are_gone(&mut self) -> bool {
|
||||
if !self.for_system || self.foreground.is_some() || ask_password::requested() {
|
||||
return false;
|
||||
}
|
||||
self.foreground = self.own_vt.and_then(ForegroundVt::take);
|
||||
if self.foreground.is_some() {
|
||||
eprintln!("bootvine: password prompt answered, taking the console back");
|
||||
}
|
||||
self.foreground.is_some()
|
||||
}
|
||||
|
||||
fn follow_requests(&mut self, requests_changed: bool) -> Refresh {
|
||||
let came_forward = requests_changed && self.come_forward_once_prompts_are_gone();
|
||||
self.entry = if self.for_system && self.foreground.is_some() {
|
||||
PasswordEntry::follow(self.entry.take(), requests_changed)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if came_forward {
|
||||
Refresh::Clear
|
||||
} else {
|
||||
Refresh::Steady
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ConsoleDesk for LiveDesk {
|
||||
fn look(&self) -> ConsoleLook {
|
||||
self.look
|
||||
}
|
||||
|
||||
fn prompt(&self, _now: Duration) -> Option<PasswordPrompt<'_>> {
|
||||
self.entry.as_ref().map(PasswordEntry::prompt)
|
||||
}
|
||||
|
||||
fn press_key(&mut self, event: &Event, _now: Duration) -> ControlFlow<WatchEnding> {
|
||||
let Some(entry) = &mut self.entry else {
|
||||
return if asks_to_quit(event, false) {
|
||||
ControlFlow::Break(WatchEnding::ViewerLeft)
|
||||
} else {
|
||||
ControlFlow::Continue(())
|
||||
};
|
||||
};
|
||||
if let Err(error) = entry.type_key(event) {
|
||||
eprintln!("bootvine: cannot answer the password prompt: {error}");
|
||||
}
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
|
||||
fn begin_handover(&mut self, reached: &str, deadline: Duration) {
|
||||
if self.handover_deadline.is_some() {
|
||||
return;
|
||||
}
|
||||
eprintln!("bootvine: {reached} reached, handing the console over");
|
||||
self.handover_deadline = Some(deadline);
|
||||
}
|
||||
|
||||
fn frame_passed(&mut self, now: Duration) -> ControlFlow<WatchEnding, Vec<BootChange>> {
|
||||
let Some(deadline) = self.handover_deadline else {
|
||||
return ControlFlow::Continue(Vec::new());
|
||||
};
|
||||
if self
|
||||
.foreground
|
||||
.as_ref()
|
||||
.is_some_and(ForegroundVt::taken_away)
|
||||
{
|
||||
eprintln!("bootvine: another program took the console, leaving it there");
|
||||
if let Some(foreground) = self.foreground.take() {
|
||||
foreground.stay_switched();
|
||||
}
|
||||
ControlFlow::Break(WatchEnding::BootCompleted)
|
||||
} else if now >= deadline {
|
||||
eprintln!("bootvine: nothing took the console, switching back");
|
||||
ControlFlow::Break(WatchEnding::BootCompleted)
|
||||
} else {
|
||||
ControlFlow::Continue(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
fn password_requests_changed(&mut self) -> Refresh {
|
||||
self.follow_requests(true)
|
||||
}
|
||||
|
||||
fn check_prompts(&mut self) {
|
||||
self.follow_requests(false);
|
||||
}
|
||||
|
||||
fn keep_console_up(&mut self) -> Refresh {
|
||||
let kernel_got_loud = self
|
||||
.quiet_kernel
|
||||
.as_mut()
|
||||
.is_some_and(QuietKernelConsole::keep_quiet);
|
||||
let terminal_was_taken = self.handover_deadline.is_none()
|
||||
&& self.foreground.as_ref().is_some_and(ForegroundVt::insist);
|
||||
let look = console_look(self.own_vt);
|
||||
let restyled = look != self.look;
|
||||
self.look = look;
|
||||
if kernel_got_loud || terminal_was_taken || restyled {
|
||||
Refresh::Repaint
|
||||
} else {
|
||||
Refresh::Steady
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn password_request_inputs(watch: RequestWatch) -> io::Result<impl Stream<Item = ScreenInput>> {
|
||||
Ok(items_when_readable(watch, RequestWatch::changed)?
|
||||
.filter(|changed| ready(*changed))
|
||||
.map(|_| ScreenInput::PasswordRequests))
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
use std::mem::take;
|
||||
|
||||
use ratatui::crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
const ROOM_FOR_TYPING: usize = 512;
|
||||
|
||||
#[must_use]
|
||||
pub fn empty() -> Zeroizing<String> {
|
||||
Zeroizing::new(String::with_capacity(ROOM_FOR_TYPING))
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn masked(typed: &str) -> String {
|
||||
"*".repeat(typed.chars().count())
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn asks_to_quit(event: &Event, typing: bool) -> bool {
|
||||
let Event::Key(KeyEvent {
|
||||
code, modifiers, ..
|
||||
}) = event
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let control_c = *code == KeyCode::Char('c') && modifiers.contains(KeyModifiers::CONTROL);
|
||||
*code == KeyCode::Esc || (!typing && (*code == KeyCode::Char('q') || control_c))
|
||||
}
|
||||
|
||||
pub fn type_key(typed: &mut Zeroizing<String>, event: &Event) -> Option<Zeroizing<String>> {
|
||||
let Event::Key(KeyEvent {
|
||||
code,
|
||||
modifiers,
|
||||
kind: KeyEventKind::Press,
|
||||
..
|
||||
}) = event
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
match code {
|
||||
KeyCode::Enter => return Some(Zeroizing::new(take(&mut **typed))),
|
||||
KeyCode::Backspace => {
|
||||
typed.pop();
|
||||
}
|
||||
KeyCode::Char('u') if modifiers.contains(KeyModifiers::CONTROL) => typed.clear(),
|
||||
KeyCode::Char(_) if modifiers.contains(KeyModifiers::CONTROL) => {}
|
||||
KeyCode::Char(character) if typed.len() + character.len_utf8() <= ROOM_FOR_TYPING => {
|
||||
typed.push(*character);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn press(code: KeyCode) -> Event {
|
||||
Event::Key(KeyEvent::from(code))
|
||||
}
|
||||
|
||||
fn typed(text: &str) -> Zeroizing<String> {
|
||||
let mut typed = empty();
|
||||
text.chars()
|
||||
.map(KeyCode::Char)
|
||||
.for_each(|code| assert_eq!(type_key(&mut typed, &press(code)), None));
|
||||
typed
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hides_what_is_typed() {
|
||||
let mut typed = typed("secret");
|
||||
type_key(&mut typed, &press(KeyCode::Backspace));
|
||||
assert_eq!(masked(&typed), "*****");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_u_clears() {
|
||||
let mut typed = typed("secret");
|
||||
let control_u = Event::Key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL));
|
||||
type_key(&mut typed, &control_u);
|
||||
assert_eq!(typed.as_str(), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_hands_over_what_was_typed() {
|
||||
let mut typed = typed("secret");
|
||||
let submitted = type_key(&mut typed, &press(KeyCode::Enter));
|
||||
assert_eq!(submitted.as_deref().map(String::as_str), Some("secret"));
|
||||
assert_eq!(typed.as_str(), "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
use std::{future::Future, io, iter, os::fd::AsRawFd, time::Duration};
|
||||
|
||||
use crossterm::event::{self, Event};
|
||||
use futures::{FutureExt, Stream, StreamExt, stream};
|
||||
use tokio::{
|
||||
io::{Interest, unix::AsyncFd},
|
||||
signal::unix::{SignalKind, signal},
|
||||
time::{Interval, MissedTickBehavior, interval, timeout},
|
||||
};
|
||||
|
||||
use crate::console_session::watch_screen::ScreenInput;
|
||||
|
||||
pub const FRAME_INTERVAL: Duration = Duration::from_millis(16);
|
||||
pub const BACKGROUND_CHECK_INTERVAL: Duration = Duration::from_millis(100);
|
||||
|
||||
pub struct CarriedItem<Item, State> {
|
||||
pub item: Item,
|
||||
pub state: State,
|
||||
}
|
||||
|
||||
pub fn unfold_carrying<State, Item, Next, Pending>(
|
||||
initial: State,
|
||||
mut next: Next,
|
||||
) -> impl Stream<Item = Item>
|
||||
where
|
||||
Next: FnMut(State) -> Pending,
|
||||
Pending: Future<Output = Option<CarriedItem<Item, State>>>,
|
||||
{
|
||||
stream::unfold(initial, move |state| {
|
||||
next(state).map(|carried| carried.map(|carried| (carried.item, carried.state)))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn readable_source<Source: AsRawFd>(source: Source) -> io::Result<AsyncFd<Source>> {
|
||||
Ok(unsafe { AsyncFd::register_with_interest(source, Interest::READABLE) }?)
|
||||
}
|
||||
|
||||
pub fn items_when_readable<Source: AsRawFd, Item>(
|
||||
source: Source,
|
||||
read: impl Fn(&Source) -> Item,
|
||||
) -> io::Result<impl Stream<Item = Item>> {
|
||||
let readiness = readable_source(source)?;
|
||||
Ok(stream::poll_fn(move |context| {
|
||||
readiness.poll_read_ready(context).map(|ready| {
|
||||
ready.ok().map(|mut guard| {
|
||||
guard.clear_ready();
|
||||
read(readiness.get_ref())
|
||||
})
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn readable_or_timeout<Source: AsRawFd>(readiness: &AsyncFd<Source>, patience: Duration) {
|
||||
if let Ok(Ok(mut guard)) = timeout(patience, readiness.readable()).await {
|
||||
guard.clear_ready();
|
||||
}
|
||||
}
|
||||
|
||||
fn steady_interval(period: Duration) -> Interval {
|
||||
let mut ticks = interval(period);
|
||||
ticks.set_missed_tick_behavior(MissedTickBehavior::Delay);
|
||||
ticks
|
||||
}
|
||||
|
||||
pub fn periodic_inputs(
|
||||
period: Duration,
|
||||
input: fn() -> ScreenInput,
|
||||
) -> impl Stream<Item = ScreenInput> {
|
||||
let mut ticks = steady_interval(period);
|
||||
stream::poll_fn(move |context| ticks.poll_tick(context).map(|_| Some(input())))
|
||||
}
|
||||
|
||||
pub fn frame_inputs() -> impl Stream<Item = ScreenInput> {
|
||||
periodic_inputs(FRAME_INTERVAL, || ScreenInput::Frame)
|
||||
}
|
||||
|
||||
fn drain_terminal_events() -> io::Result<Vec<Event>> {
|
||||
iter::from_fn(|| match event::poll(Duration::ZERO) {
|
||||
Ok(true) => Some(event::read()),
|
||||
Ok(false) => None,
|
||||
Err(error) => Some(Err(error)),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn terminal_inputs(drained: io::Result<Vec<Event>>) -> Vec<ScreenInput> {
|
||||
match drained {
|
||||
Ok(events) => events.into_iter().map(ScreenInput::Key).collect(),
|
||||
Err(error) => vec![ScreenInput::Failed(error.into())],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn key_inputs() -> io::Result<impl Stream<Item = ScreenInput>> {
|
||||
Ok(
|
||||
items_when_readable(io::stdin(), |_| drain_terminal_events())?
|
||||
.map(terminal_inputs)
|
||||
.flat_map(stream::iter),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn termination_inputs() -> io::Result<impl Stream<Item = ScreenInput>> {
|
||||
let mut terminate = signal(SignalKind::terminate())?;
|
||||
Ok(stream::once(async move {
|
||||
terminate.recv().await;
|
||||
ScreenInput::Terminate
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
use std::{path::Path, time::Duration};
|
||||
|
||||
use futures::{StreamExt, stream};
|
||||
use tokio::runtime::Builder;
|
||||
|
||||
use crate::{
|
||||
boot_model::{BootState, Phase, boot_origin::BootOrigin},
|
||||
console_session::{
|
||||
ask_password::RequestWatch,
|
||||
live_desk::{LiveDesk, password_request_inputs},
|
||||
stream_sources::{
|
||||
BACKGROUND_CHECK_INTERVAL, frame_inputs, key_inputs, periodic_inputs,
|
||||
termination_inputs,
|
||||
},
|
||||
watch_screen::{ScreenInput, WatchEnding, WatchScreen, watch_until_ending},
|
||||
},
|
||||
screen_settings::{color_scheme::Colors, config_file::Timing},
|
||||
systemd_link::{
|
||||
boot_feed::{RootRequest, bus_inputs},
|
||||
link_error::Error,
|
||||
switch_root::INITRD_RELEASE,
|
||||
systemd_bus::{Scope, Session, StatusOutput},
|
||||
},
|
||||
};
|
||||
|
||||
pub struct Settings {
|
||||
pub scope: Scope,
|
||||
pub shutdown: bool,
|
||||
pub target: RootRequest,
|
||||
pub timing: Timing,
|
||||
pub colors: Colors,
|
||||
}
|
||||
|
||||
const FULL_REPAINT_INTERVAL: Duration = Duration::from_secs(5);
|
||||
|
||||
struct ConfiguredStatusOnExit;
|
||||
|
||||
impl Drop for ConfiguredStatusOnExit {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(session) = Session::open(Scope::System) {
|
||||
session.set_show_status(StatusOutput::Configured).ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn boot_already_finished(settings: &Settings) -> bool {
|
||||
settings.scope == Scope::System
|
||||
&& !settings.shutdown
|
||||
&& Session::open(Scope::System)
|
||||
.and_then(|session| session.boot_in_progress())
|
||||
.is_ok_and(|booting| !booting)
|
||||
}
|
||||
|
||||
fn starting_phase(settings: &Settings) -> Phase {
|
||||
match settings.scope {
|
||||
_ if settings.shutdown => Phase::Shutdown,
|
||||
Scope::User => Phase::User,
|
||||
Scope::System if Path::new(INITRD_RELEASE).exists() => Phase::Initrd,
|
||||
Scope::System => Phase::Host,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(settings: &Settings) -> Result<(), Error> {
|
||||
if boot_already_finished(settings) {
|
||||
eprintln!("bootvine: boot already finished, leaving the console alone");
|
||||
return Ok(());
|
||||
}
|
||||
Builder::new_current_thread()
|
||||
.enable_io()
|
||||
.enable_time()
|
||||
.build()?
|
||||
.block_on(watch_live_boot(settings, starting_phase(settings)))
|
||||
}
|
||||
|
||||
async fn watch_live_boot(settings: &Settings, phase: Phase) -> Result<(), Error> {
|
||||
let for_system = settings.scope == Scope::System;
|
||||
let _restores_status = for_system.then_some(ConfiguredStatusOnExit);
|
||||
let requests = RequestWatch::open();
|
||||
let prompt_check: fn() -> ScreenInput = if requests.is_some() {
|
||||
|| ScreenInput::PromptCheck
|
||||
} else {
|
||||
|| ScreenInput::PasswordRequests
|
||||
};
|
||||
let desk = LiveDesk::take_console(for_system);
|
||||
let password_inputs = requests.map(password_request_inputs).transpose()?;
|
||||
let event_inputs = stream::select(
|
||||
stream::select(
|
||||
bus_inputs(phase, settings.scope, settings.target.clone()),
|
||||
key_inputs()?,
|
||||
),
|
||||
stream::select(
|
||||
termination_inputs()?,
|
||||
stream::iter(password_inputs).flatten(),
|
||||
),
|
||||
);
|
||||
let timer_inputs = stream::select(
|
||||
stream::select(
|
||||
frame_inputs(),
|
||||
periodic_inputs(BACKGROUND_CHECK_INTERVAL, prompt_check),
|
||||
),
|
||||
stream::select(
|
||||
periodic_inputs(BACKGROUND_CHECK_INTERVAL, || ScreenInput::ConsoleUpkeep),
|
||||
periodic_inputs(FULL_REPAINT_INTERVAL, || ScreenInput::FullRepaint),
|
||||
),
|
||||
);
|
||||
let inputs = stream::select(event_inputs, timer_inputs);
|
||||
let mut screen = WatchScreen::new(
|
||||
BootState::new(phase),
|
||||
desk,
|
||||
BootOrigin::read,
|
||||
settings.colors,
|
||||
settings.timing,
|
||||
Duration::ZERO,
|
||||
);
|
||||
let mut terminal = ratatui::try_init()?;
|
||||
let ending = watch_until_ending(&mut screen, &mut terminal, inputs).await;
|
||||
ratatui::restore();
|
||||
match ending {
|
||||
WatchEnding::Failed(error) => Err(error),
|
||||
WatchEnding::BootCompleted | WatchEnding::ViewerLeft => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
use std::{future::ready, ops::ControlFlow, time::Duration};
|
||||
|
||||
use crossterm::event::Event;
|
||||
use futures::{Stream, StreamExt};
|
||||
use ratatui::{
|
||||
Terminal,
|
||||
backend::Backend,
|
||||
buffer::{Buffer, CellDiffOption},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
boot_model::{BootChange, BootState, boot_origin::BootOrigin},
|
||||
boot_view::{BootProjection, BootView, PasswordPrompt, project_boot},
|
||||
console_session::console_palette::ConsoleLook,
|
||||
screen_settings::{color_scheme::Colors, config_file::Timing},
|
||||
systemd_link::{link_error::Error, monotonic_clock::monotonic_now},
|
||||
};
|
||||
|
||||
const INPUT_BATCH: usize = 64;
|
||||
const PROJECTION_REFRESH: Duration = Duration::from_millis(100);
|
||||
|
||||
pub enum ScreenInput {
|
||||
Boot(Vec<BootChange>),
|
||||
Key(Event),
|
||||
Frame,
|
||||
PromptCheck,
|
||||
ConsoleUpkeep,
|
||||
FullRepaint,
|
||||
PasswordRequests,
|
||||
Terminate,
|
||||
Failed(Error),
|
||||
}
|
||||
|
||||
pub enum WatchEnding {
|
||||
BootCompleted,
|
||||
ViewerLeft,
|
||||
Failed(Error),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Refresh {
|
||||
Steady,
|
||||
Repaint,
|
||||
Clear,
|
||||
}
|
||||
|
||||
pub trait ConsoleDesk {
|
||||
fn prompt(&self, now: Duration) -> Option<PasswordPrompt<'_>>;
|
||||
fn press_key(&mut self, event: &Event, now: Duration) -> ControlFlow<WatchEnding>;
|
||||
fn frame_passed(&mut self, now: Duration) -> ControlFlow<WatchEnding, Vec<BootChange>>;
|
||||
|
||||
fn look(&self) -> ConsoleLook {
|
||||
ConsoleLook::default()
|
||||
}
|
||||
|
||||
fn password_requests_changed(&mut self) -> Refresh {
|
||||
Refresh::Steady
|
||||
}
|
||||
|
||||
fn check_prompts(&mut self) {}
|
||||
|
||||
fn keep_console_up(&mut self) -> Refresh {
|
||||
Refresh::Steady
|
||||
}
|
||||
|
||||
fn begin_handover(&mut self, _reached: &str, _deadline: Duration) {}
|
||||
}
|
||||
|
||||
struct CachedProjection {
|
||||
projection: BootProjection,
|
||||
built_at: Duration,
|
||||
}
|
||||
|
||||
pub struct WatchScreen<Desk> {
|
||||
pub state: BootState,
|
||||
pub desk: Desk,
|
||||
read_origin: fn() -> BootOrigin,
|
||||
origin: BootOrigin,
|
||||
refresh_due: Refresh,
|
||||
colors: Colors,
|
||||
timing: Timing,
|
||||
epoch: Duration,
|
||||
projection: Option<CachedProjection>,
|
||||
}
|
||||
|
||||
impl<Desk: ConsoleDesk> WatchScreen<Desk> {
|
||||
pub fn new(
|
||||
state: BootState,
|
||||
desk: Desk,
|
||||
read_origin: fn() -> BootOrigin,
|
||||
colors: Colors,
|
||||
timing: Timing,
|
||||
epoch: Duration,
|
||||
) -> Self {
|
||||
Self {
|
||||
state,
|
||||
desk,
|
||||
read_origin,
|
||||
origin: read_origin(),
|
||||
refresh_due: Refresh::Steady,
|
||||
colors,
|
||||
timing,
|
||||
epoch,
|
||||
projection: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn request_refresh(&mut self, refresh: Refresh) {
|
||||
self.refresh_due = self.refresh_due.max(refresh);
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn now(&self) -> Duration {
|
||||
monotonic_now().saturating_sub(self.epoch)
|
||||
}
|
||||
|
||||
fn absorb(&mut self, input: ScreenInput) -> ControlFlow<WatchEnding> {
|
||||
let now = self.now();
|
||||
match input {
|
||||
ScreenInput::Boot(changes) => self.apply_boot_changes(changes, now),
|
||||
ScreenInput::Key(event) => self.desk.press_key(&event, now),
|
||||
ScreenInput::Frame => {
|
||||
let changes = self.desk.frame_passed(now)?;
|
||||
if changes.is_empty() {
|
||||
return ControlFlow::Continue(());
|
||||
}
|
||||
self.apply_boot_changes(changes, now)
|
||||
}
|
||||
ScreenInput::PromptCheck => {
|
||||
self.desk.check_prompts();
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
ScreenInput::ConsoleUpkeep => {
|
||||
let refresh = self.desk.keep_console_up();
|
||||
self.request_refresh(refresh);
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
ScreenInput::FullRepaint => {
|
||||
self.request_refresh(Refresh::Repaint);
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
ScreenInput::PasswordRequests => {
|
||||
let refresh = self.desk.password_requests_changed();
|
||||
self.request_refresh(refresh);
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
ScreenInput::Terminate => ControlFlow::Break(WatchEnding::ViewerLeft),
|
||||
ScreenInput::Failed(error) => ControlFlow::Break(WatchEnding::Failed(error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_boot_changes(
|
||||
&mut self,
|
||||
changes: Vec<BootChange>,
|
||||
now: Duration,
|
||||
) -> ControlFlow<WatchEnding> {
|
||||
let phase_before = self.state.phase;
|
||||
changes
|
||||
.into_iter()
|
||||
.for_each(|change| self.state.apply(change));
|
||||
self.projection = None;
|
||||
if self.state.phase != phase_before {
|
||||
self.origin = (self.read_origin)();
|
||||
}
|
||||
if let Some(display_manager) = self.state.started_display_manager() {
|
||||
self.desk
|
||||
.begin_handover(display_manager, now + self.timing.wait_for_display_manager);
|
||||
} else if self.state.is_complete() {
|
||||
self.desk.begin_handover(
|
||||
self.state.root.unit().unwrap_or("boot"),
|
||||
now + self.timing.keep_final_frame_for,
|
||||
);
|
||||
}
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
|
||||
fn absorb_batch<B: Backend>(
|
||||
&mut self,
|
||||
batch: Vec<ScreenInput>,
|
||||
terminal: &mut Terminal<B>,
|
||||
) -> ControlFlow<WatchEnding>
|
||||
where
|
||||
Error: From<B::Error>,
|
||||
{
|
||||
batch.into_iter().try_for_each(|input| self.absorb(input))?;
|
||||
match self.draw(terminal) {
|
||||
Ok(()) => ControlFlow::Continue(()),
|
||||
Err(error) => ControlFlow::Break(WatchEnding::Failed(error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn draw<B: Backend>(&mut self, terminal: &mut Terminal<B>) -> Result<(), Error>
|
||||
where
|
||||
Error: From<B::Error>,
|
||||
{
|
||||
if self.refresh_due == Refresh::Clear {
|
||||
terminal.clear()?;
|
||||
}
|
||||
let now = self.now();
|
||||
let look = self.desk.look();
|
||||
if self
|
||||
.projection
|
||||
.as_ref()
|
||||
.is_some_and(|cached| now.saturating_sub(cached.built_at) >= PROJECTION_REFRESH)
|
||||
{
|
||||
self.projection = None;
|
||||
}
|
||||
let projection = &self
|
||||
.projection
|
||||
.get_or_insert_with(|| CachedProjection {
|
||||
projection: project_boot(&self.state, &self.timing, now),
|
||||
built_at: now,
|
||||
})
|
||||
.projection;
|
||||
let completed = terminal.draw(|canvas| {
|
||||
canvas.render_widget(
|
||||
BootView {
|
||||
state: &self.state,
|
||||
projection,
|
||||
colors: &self.colors,
|
||||
timing: &self.timing,
|
||||
glyphs: &look.glyphs,
|
||||
now,
|
||||
origin: &self.origin,
|
||||
password_prompt: self.desk.prompt(now),
|
||||
},
|
||||
canvas.area(),
|
||||
);
|
||||
look.palette.fit_frame(canvas.buffer_mut());
|
||||
})?;
|
||||
if self.refresh_due == Refresh::Repaint {
|
||||
let painted = completed.buffer.clone();
|
||||
overwrite_every_cell(terminal.backend_mut(), &painted)?;
|
||||
}
|
||||
self.refresh_due = Refresh::Steady;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn watch_until_ending<Desk: ConsoleDesk, B: Backend>(
|
||||
screen: &mut WatchScreen<Desk>,
|
||||
terminal: &mut Terminal<B>,
|
||||
inputs: impl Stream<Item = ScreenInput>,
|
||||
) -> WatchEnding
|
||||
where
|
||||
Error: From<B::Error>,
|
||||
{
|
||||
inputs
|
||||
.ready_chunks(INPUT_BATCH)
|
||||
.filter_map(|batch| ready(screen.absorb_batch(batch, terminal).break_value()))
|
||||
.take(1)
|
||||
.fold(WatchEnding::ViewerLeft, |_, ending| ready(ending))
|
||||
.await
|
||||
}
|
||||
|
||||
fn overwrite_every_cell<B: Backend>(backend: &mut B, frame: &Buffer) -> Result<(), B::Error> {
|
||||
backend.draw(
|
||||
frame
|
||||
.content
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, cell)| cell.diff_option != CellDiffOption::Skip)
|
||||
.map(|(index, cell)| {
|
||||
let (x, y) = frame.pos_of(index);
|
||||
(x, y, cell)
|
||||
}),
|
||||
)?;
|
||||
backend.flush()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
boot_model::{ActiveState, Activity, HANDOFF_UNIT},
|
||||
boot_test_fixtures::{MS, nested_boot_sample, queue_unit, waiting},
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
struct HandoverRecorder {
|
||||
handovers: Vec<String>,
|
||||
}
|
||||
|
||||
impl ConsoleDesk for HandoverRecorder {
|
||||
fn prompt(&self, _now: Duration) -> Option<PasswordPrompt<'_>> {
|
||||
None
|
||||
}
|
||||
|
||||
fn press_key(&mut self, _event: &Event, _now: Duration) -> ControlFlow<WatchEnding> {
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
|
||||
fn frame_passed(&mut self, _now: Duration) -> ControlFlow<WatchEnding, Vec<BootChange>> {
|
||||
ControlFlow::Continue(Vec::new())
|
||||
}
|
||||
|
||||
fn begin_handover(&mut self, reached: &str, _deadline: Duration) {
|
||||
self.handovers.push(reached.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
fn test_origin() -> BootOrigin {
|
||||
BootOrigin {
|
||||
host: "test".to_owned(),
|
||||
system: None,
|
||||
generation: None,
|
||||
kernel: "Linux".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn screen_watching(state: BootState) -> WatchScreen<HandoverRecorder> {
|
||||
WatchScreen::new(
|
||||
state,
|
||||
HandoverRecorder::default(),
|
||||
test_origin,
|
||||
Colors::default(),
|
||||
Timing::default(),
|
||||
Duration::ZERO,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_manager_start_hands_over_before_the_boot_completes() {
|
||||
let mut state = nested_boot_sample();
|
||||
queue_unit(&mut state, 20, waiting(HANDOFF_UNIT, &[]), 500 * MS);
|
||||
let mut screen = screen_watching(state);
|
||||
let _ = screen.apply_boot_changes(Vec::new(), 1000 * MS);
|
||||
assert!(screen.desk.handovers.is_empty());
|
||||
let started = BootChange::UpdateActivity {
|
||||
unit: HANDOFF_UNIT.to_owned(),
|
||||
activity: Activity {
|
||||
state: Some(ActiveState::Active),
|
||||
..Activity::default()
|
||||
},
|
||||
};
|
||||
let _ = screen.apply_boot_changes(vec![started], 6000 * MS);
|
||||
assert!(!screen.state.is_complete());
|
||||
assert_eq!(screen.desk.handovers, [HANDOFF_UNIT]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
pub mod boot_model;
|
||||
#[cfg(test)]
|
||||
mod boot_test_fixtures;
|
||||
pub mod boot_view;
|
||||
pub mod console_session;
|
||||
pub mod screen_settings;
|
||||
pub mod system_install;
|
||||
pub mod systemd_link;
|
||||
@@ -0,0 +1,155 @@
|
||||
use std::{
|
||||
error::Error, fmt::Display, io::ErrorKind, path::PathBuf, process::ExitCode, time::Duration,
|
||||
};
|
||||
|
||||
use bootvine::{
|
||||
console_session::watch_loop::{Settings, run},
|
||||
screen_settings::config_file::{
|
||||
Config, ConfigError, Timing, default_config_table, read_config_file,
|
||||
},
|
||||
system_install::install_files::{
|
||||
InstallOptions, UninstallOptions, install_files, uninstall_files,
|
||||
},
|
||||
systemd_link::{boot_feed::RootRequest, systemd_bus::Scope},
|
||||
};
|
||||
use clap::{Args, Parser, Subcommand, ValueEnum};
|
||||
use jiff::fmt::friendly::SpanParser;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
version,
|
||||
about = "Live dependency tree of systemd jobs while the system boots",
|
||||
args_conflicts_with_subcommands = true
|
||||
)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Option<Command>,
|
||||
#[command(flatten)]
|
||||
watch: WatchOptions,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct WatchOptions {
|
||||
#[arg(long, help = "Watch the user service manager instead of PID 1")]
|
||||
user: bool,
|
||||
#[arg(
|
||||
long,
|
||||
help = "Follow a shutdown instead of a boot; started by bootvine-shutdown.service"
|
||||
)]
|
||||
shutdown: bool,
|
||||
#[arg(
|
||||
long,
|
||||
help = "Root unit of the tree; defaults to the manager's default target"
|
||||
)]
|
||||
target: Option<String>,
|
||||
#[arg(
|
||||
long,
|
||||
value_parser = |raw: &str| SpanParser::new().parse_unsigned_duration(raw),
|
||||
help = "How long the final frame stays on screen, e.g. 1s or 500ms; overrides \
|
||||
timing.keep-final-frame-for"
|
||||
)]
|
||||
hold: Option<Duration>,
|
||||
#[arg(
|
||||
long,
|
||||
default_value = "/etc/bootvine.toml",
|
||||
help = "TOML file with [colors] and [timing] tables; see `bootvine defaults`"
|
||||
)]
|
||||
config: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
#[command(about = "Print every setting with its default value")]
|
||||
Defaults(DefaultsOptions),
|
||||
#[command(about = "Exit with an error if a config file is unreadable or invalid")]
|
||||
Check(CheckOptions),
|
||||
#[command(
|
||||
about = "Install this binary and the systemd units, and enable them; asks sudo when needed"
|
||||
)]
|
||||
Install(InstallOptions),
|
||||
#[command(about = "Disable and remove what install put in place")]
|
||||
Uninstall(UninstallOptions),
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct DefaultsOptions {
|
||||
#[arg(long, value_enum, default_value_t = DefaultsFormat::Toml)]
|
||||
format: DefaultsFormat,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct CheckOptions {
|
||||
#[arg(help = "Config file to check, such as /etc/bootvine.toml")]
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, ValueEnum)]
|
||||
enum DefaultsFormat {
|
||||
Toml,
|
||||
Nix,
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let cli = Cli::parse();
|
||||
match cli.command {
|
||||
Some(Command::Defaults(options)) => report_outcome(
|
||||
render_defaults(options.format).map(|text| println!("{}", text.trim_end())),
|
||||
),
|
||||
Some(Command::Check(options)) => report_outcome(
|
||||
read_config_file(&options.path)
|
||||
.map(|_| ())
|
||||
.map_err(|error| format!("{}: {error}", options.path.display())),
|
||||
),
|
||||
Some(Command::Install(options)) => report_outcome(install_files(&options)),
|
||||
Some(Command::Uninstall(options)) => report_outcome(uninstall_files(&options)),
|
||||
None => watch_boot(cli.watch),
|
||||
}
|
||||
}
|
||||
|
||||
fn report_outcome(outcome: Result<(), impl Display>) -> ExitCode {
|
||||
match outcome {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(error) => {
|
||||
eprintln!("bootvine: {error}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn render_defaults(format: DefaultsFormat) -> Result<String, Box<dyn Error>> {
|
||||
let defaults = default_config_table()?;
|
||||
Ok(match format {
|
||||
DefaultsFormat::Toml => toml::to_string_pretty(&defaults)?,
|
||||
DefaultsFormat::Nix => ser_nix::to_string(&defaults)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn watch_boot(options: WatchOptions) -> ExitCode {
|
||||
let config = match read_config_file(&options.config) {
|
||||
Ok(config) => config,
|
||||
Err(ConfigError::Unreadable(error)) if error.kind() == ErrorKind::NotFound => {
|
||||
Config::default()
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!("bootvine: ignoring {}: {error}", options.config.display());
|
||||
Config::default()
|
||||
}
|
||||
};
|
||||
let settings = Settings {
|
||||
scope: if options.user {
|
||||
Scope::User
|
||||
} else {
|
||||
Scope::System
|
||||
},
|
||||
shutdown: options.shutdown,
|
||||
target: options
|
||||
.target
|
||||
.map_or(RootRequest::ManagerDefault, RootRequest::Named),
|
||||
timing: Timing {
|
||||
keep_final_frame_for: options.hold.unwrap_or(config.timing.keep_final_frame_for),
|
||||
..config.timing
|
||||
},
|
||||
colors: config.colors,
|
||||
};
|
||||
report_outcome(run(&settings))
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod color_scheme;
|
||||
pub mod config_file;
|
||||
pub mod font_glyphs;
|
||||
@@ -0,0 +1,196 @@
|
||||
use ratatui::style::Color;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub struct Colors {
|
||||
pub header: HeaderColors,
|
||||
pub stages: StageColors,
|
||||
pub tree: TreeColors,
|
||||
pub timeline: TimelineColors,
|
||||
pub failures: FailureColors,
|
||||
pub footer: FooterColors,
|
||||
pub password: PasswordColors,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub struct HeaderColors {
|
||||
pub origin: Color,
|
||||
pub separators: Color,
|
||||
pub total_time: Color,
|
||||
}
|
||||
|
||||
impl Default for HeaderColors {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
origin: Color::White,
|
||||
separators: Color::DarkGray,
|
||||
total_time: Color::White,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub struct StageColors {
|
||||
pub branches: Color,
|
||||
pub finished_label: Color,
|
||||
pub finished_time: Color,
|
||||
pub unit_count: Color,
|
||||
pub failed_count: Color,
|
||||
pub current: Color,
|
||||
}
|
||||
|
||||
impl Default for StageColors {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
branches: Color::DarkGray,
|
||||
finished_label: Color::Gray,
|
||||
finished_time: Color::Green,
|
||||
unit_count: Color::Gray,
|
||||
failed_count: Color::LightRed,
|
||||
current: Color::White,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub struct TreeColors {
|
||||
pub branches: Color,
|
||||
pub columns: Color,
|
||||
pub target: Color,
|
||||
pub current_stage: Color,
|
||||
pub reached_stage: Color,
|
||||
pub running_unit: Color,
|
||||
pub running_marker: Color,
|
||||
pub waiting_unit: Color,
|
||||
pub finished_unit: Color,
|
||||
pub finished_marker: Color,
|
||||
pub failed_unit: Color,
|
||||
pub overflow: Color,
|
||||
}
|
||||
|
||||
impl Default for TreeColors {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
branches: Color::DarkGray,
|
||||
columns: Color::DarkGray,
|
||||
target: Color::Cyan,
|
||||
current_stage: Color::Yellow,
|
||||
reached_stage: Color::Green,
|
||||
running_unit: Color::White,
|
||||
running_marker: Color::Yellow,
|
||||
waiting_unit: Color::Gray,
|
||||
finished_unit: Color::DarkGray,
|
||||
finished_marker: Color::Green,
|
||||
failed_unit: Color::LightRed,
|
||||
overflow: Color::Gray,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub struct TimelineColors {
|
||||
pub rule: Color,
|
||||
pub title: Color,
|
||||
pub axis: Color,
|
||||
pub milestone: Color,
|
||||
pub finished: Color,
|
||||
pub finished_label: Color,
|
||||
pub failed: Color,
|
||||
pub queued_bar: Color,
|
||||
pub running: Color,
|
||||
pub running_label: Color,
|
||||
}
|
||||
|
||||
impl Default for TimelineColors {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
rule: Color::DarkGray,
|
||||
title: Color::Gray,
|
||||
axis: Color::DarkGray,
|
||||
milestone: Color::Green,
|
||||
finished: Color::Green,
|
||||
finished_label: Color::Gray,
|
||||
failed: Color::LightRed,
|
||||
queued_bar: Color::Gray,
|
||||
running: Color::Yellow,
|
||||
running_label: Color::White,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub struct FailureColors {
|
||||
pub rule: Color,
|
||||
pub title: Color,
|
||||
pub unit: Color,
|
||||
pub reason: Color,
|
||||
pub log: Color,
|
||||
pub overflow: Color,
|
||||
}
|
||||
|
||||
impl Default for FailureColors {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
rule: Color::DarkGray,
|
||||
title: Color::LightRed,
|
||||
unit: Color::LightRed,
|
||||
reason: Color::White,
|
||||
log: Color::Gray,
|
||||
overflow: Color::DarkGray,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub struct FooterColors {
|
||||
pub rule: Color,
|
||||
pub done: Color,
|
||||
pub running: Color,
|
||||
pub waiting: Color,
|
||||
pub failed: Color,
|
||||
pub no_failures: Color,
|
||||
}
|
||||
|
||||
impl Default for FooterColors {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
rule: Color::DarkGray,
|
||||
done: Color::Green,
|
||||
running: Color::Yellow,
|
||||
waiting: Color::Gray,
|
||||
failed: Color::LightRed,
|
||||
no_failures: Color::Gray,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub struct PasswordColors {
|
||||
pub frame: Color,
|
||||
pub message: Color,
|
||||
pub hint: Color,
|
||||
pub checking: Color,
|
||||
pub rejected: Color,
|
||||
pub backdrop: Color,
|
||||
}
|
||||
|
||||
impl Default for PasswordColors {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
frame: Color::Yellow,
|
||||
message: Color::White,
|
||||
hint: Color::DarkGray,
|
||||
checking: Color::Gray,
|
||||
rejected: Color::LightRed,
|
||||
backdrop: Color::DarkGray,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
use std::{fs, io, path::Path, time::Duration};
|
||||
|
||||
use heck::ToKebabCase;
|
||||
use jiff::fmt::serde::unsigned_duration::friendly::compact::required as friendly_duration;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use toml::{Table, Value, de::Error as ParseError, ser::Error as SerializeError};
|
||||
|
||||
use crate::screen_settings::color_scheme::Colors;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub struct Config {
|
||||
pub colors: Colors,
|
||||
pub timing: Timing,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub struct Timing {
|
||||
#[serde(with = "friendly_duration")]
|
||||
pub keep_finished_units_for: Duration,
|
||||
#[serde(with = "friendly_duration")]
|
||||
pub hide_runs_shorter_than: Duration,
|
||||
#[serde(with = "friendly_duration")]
|
||||
pub keep_final_frame_for: Duration,
|
||||
#[serde(with = "friendly_duration")]
|
||||
pub wait_for_display_manager: Duration,
|
||||
}
|
||||
|
||||
impl Default for Timing {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
keep_finished_units_for: Duration::from_secs(2),
|
||||
hide_runs_shorter_than: Duration::from_secs(1),
|
||||
keep_final_frame_for: Duration::from_secs(1),
|
||||
wait_for_display_manager: Duration::from_secs(10),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConfigError {
|
||||
#[error("cannot read: {0}")]
|
||||
Unreadable(#[from] io::Error),
|
||||
#[error("invalid: {0}")]
|
||||
Invalid(#[from] ParseError),
|
||||
}
|
||||
|
||||
pub fn read_config_file(path: &Path) -> Result<Config, ConfigError> {
|
||||
Ok(toml::from_str(&fs::read_to_string(path)?)?)
|
||||
}
|
||||
|
||||
pub fn default_config_table() -> Result<Table, SerializeError> {
|
||||
Table::try_from(Config::default()).map(kebab_color_names)
|
||||
}
|
||||
|
||||
fn kebab_color_names(table: Table) -> Table {
|
||||
table
|
||||
.into_iter()
|
||||
.map(|(key, value)| {
|
||||
let value = match value {
|
||||
Value::Table(nested) => Value::Table(kebab_color_names(nested)),
|
||||
Value::String(name) if name.starts_with(char::is_alphabetic) => {
|
||||
Value::String(name.to_kebab_case())
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
(key, value)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn printed_defaults() -> String {
|
||||
toml::to_string_pretty(&default_config_table().expect("serializable defaults"))
|
||||
.expect("printable defaults")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timing_reads_friendly_durations_and_keeps_unset_defaults() {
|
||||
let config: Config = toml::from_str("[timing]\nkeep-finished-units-for = \"500ms\"\n")
|
||||
.expect("valid config");
|
||||
assert_eq!(
|
||||
config.timing.keep_finished_units_for,
|
||||
Duration::from_millis(500)
|
||||
);
|
||||
assert_eq!(
|
||||
config.timing.keep_final_frame_for,
|
||||
Timing::default().keep_final_frame_for
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonsense_durations_are_rejected() {
|
||||
assert!(toml::from_str::<Config>("[timing]\nkeep-final-frame-for = \"soon\"\n").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_color_keys_are_rejected() {
|
||||
assert!(toml::from_str::<Config>("[colors.tree]\nbogus = \"red\"\n").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn printed_defaults_read_back_unchanged() {
|
||||
let printed = printed_defaults();
|
||||
assert!(printed.contains("failed-unit = \"light-red\""), "{printed}");
|
||||
assert_eq!(
|
||||
toml::from_str::<Config>(&printed).expect("valid defaults"),
|
||||
Config::default()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Glyphs {
|
||||
pub done: char,
|
||||
pub failed: char,
|
||||
pub bead: char,
|
||||
pub waiting_bead: char,
|
||||
pub still_going: char,
|
||||
pub growing_tip: Option<[char; 8]>,
|
||||
pub running_mark: char,
|
||||
pub root_switch_mark: char,
|
||||
pub stage_current: char,
|
||||
pub stage_upcoming: char,
|
||||
pub ellipsis: &'static str,
|
||||
pub chain_link: &'static str,
|
||||
}
|
||||
|
||||
const DONE: [char; 2] = ['√', '+'];
|
||||
const FAILED: [char; 2] = ['×', 'x'];
|
||||
const BEAD: [char; 2] = ['■', '#'];
|
||||
const WAITING_BEAD: [char; 2] = ['·', '.'];
|
||||
const STILL_GOING: [char; 2] = ['▶', '>'];
|
||||
const GROWING_TIP: [char; 8] = ['▏', '▎', '▍', '▌', '▋', '▊', '▉', '█'];
|
||||
const RUNNING_MARK: [char; 3] = ['►', '▶', '>'];
|
||||
const ROOT_SWITCH_MARK: [char; 2] = ['│', '|'];
|
||||
const STAGE_MARKS: [&str; 3] = ["◆◇", "●○", "*o"];
|
||||
const ELLIPSIS: [&str; 2] = ["…", "..."];
|
||||
const CHAIN_LINK: [&str; 2] = ["─", "-"];
|
||||
|
||||
impl Default for Glyphs {
|
||||
fn default() -> Self {
|
||||
Self::fitting(|_| true)
|
||||
}
|
||||
}
|
||||
|
||||
impl Glyphs {
|
||||
pub fn fitting(covers: impl Fn(char) -> bool) -> Self {
|
||||
let symbol = |candidates: &[char]| {
|
||||
candidates
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|candidate| covers(*candidate))
|
||||
.unwrap_or(candidates[candidates.len() - 1])
|
||||
};
|
||||
let text = |candidates: &[&'static str]| {
|
||||
candidates
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|candidate| candidate.chars().all(&covers))
|
||||
.unwrap_or(candidates[candidates.len() - 1])
|
||||
};
|
||||
let stage_marks: Vec<char> = text(&STAGE_MARKS).chars().collect();
|
||||
Self {
|
||||
done: symbol(&DONE),
|
||||
failed: symbol(&FAILED),
|
||||
bead: symbol(&BEAD),
|
||||
waiting_bead: symbol(&WAITING_BEAD),
|
||||
still_going: symbol(&STILL_GOING),
|
||||
growing_tip: GROWING_TIP
|
||||
.iter()
|
||||
.all(|eighth| covers(*eighth))
|
||||
.then_some(GROWING_TIP),
|
||||
running_mark: symbol(&RUNNING_MARK),
|
||||
root_switch_mark: symbol(&ROOT_SWITCH_MARK),
|
||||
stage_current: stage_marks[0],
|
||||
stage_upcoming: stage_marks[1],
|
||||
ellipsis: text(&ELLIPSIS),
|
||||
chain_link: text(&CHAIN_LINK),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const LAT2_TERMINUS16: &str = "×■●▶·•…│├└─━█▒░↑↓←→≥";
|
||||
const DEFAULT8X16: &str = "√■○►▶·•│├└─▌▐█▓▒░▀▄↑↓←→≥";
|
||||
|
||||
fn covered_by(font: &'static str) -> impl Fn(char) -> bool {
|
||||
move |symbol| symbol.is_ascii() || font.contains(symbol)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_font_without_the_square_root_and_pointer_falls_back() {
|
||||
let glyphs = Glyphs::fitting(covered_by(LAT2_TERMINUS16));
|
||||
assert_eq!(glyphs.done, '+');
|
||||
assert_eq!(glyphs.running_mark, '▶');
|
||||
assert_eq!(glyphs.failed, '×');
|
||||
assert_eq!(glyphs.ellipsis, "…");
|
||||
assert_eq!((glyphs.stage_current, glyphs.stage_upcoming), ('*', 'o'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_built_in_kernel_font_loses_the_cross_and_ellipsis() {
|
||||
let glyphs = Glyphs::fitting(covered_by(DEFAULT8X16));
|
||||
assert_eq!(glyphs.done, '√');
|
||||
assert_eq!(glyphs.failed, 'x');
|
||||
assert_eq!(glyphs.ellipsis, "...");
|
||||
assert_eq!(glyphs.chain_link, "─");
|
||||
assert_eq!((glyphs.stage_current, glyphs.stage_upcoming), ('*', 'o'));
|
||||
assert_eq!(glyphs.growing_tip, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_unicode_keeps_every_preferred_glyph() {
|
||||
let glyphs = Glyphs::default();
|
||||
assert_eq!((glyphs.done, glyphs.running_mark), ('√', '►'));
|
||||
assert_eq!(glyphs.growing_tip, Some(GROWING_TIP));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod install_error;
|
||||
pub mod install_files;
|
||||
@@ -0,0 +1,11 @@
|
||||
use std::{io, path::PathBuf, process::ExitStatus};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum InstallError {
|
||||
#[error("{}: {source}", path.display())]
|
||||
File { path: PathBuf, source: io::Error },
|
||||
#[error("could not run {program}: {source}")]
|
||||
Spawn { program: String, source: io::Error },
|
||||
#[error("{program} failed: {status}")]
|
||||
Failed { program: String, status: ExitStatus },
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
use std::{
|
||||
env,
|
||||
ffi::OsString,
|
||||
fs::{self, Permissions},
|
||||
io::ErrorKind,
|
||||
iter::once,
|
||||
os::unix::fs::PermissionsExt,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
|
||||
use clap::{Args, ValueEnum};
|
||||
use rustix::process::geteuid;
|
||||
|
||||
use crate::system_install::install_error::InstallError;
|
||||
|
||||
const DRACUT_MODULE_DIR: &str = "/usr/lib/dracut/modules.d/90bootvine";
|
||||
const DRACUT_CONF: &str = "/etc/dracut.conf.d/bootvine.conf";
|
||||
const MKINITCPIO_HOOK: &str = "/usr/lib/initcpio/install/sd-bootvine";
|
||||
const PACKAGED_BINARY_PATH: &str = "/usr/bin/bootvine";
|
||||
|
||||
struct PackagedUnit {
|
||||
name: &'static str,
|
||||
contents: &'static str,
|
||||
}
|
||||
|
||||
const PACKAGED_UNITS: [PackagedUnit; 2] = [
|
||||
PackagedUnit {
|
||||
name: "bootvine.service",
|
||||
contents: include_str!("../../system-files/systemd/bootvine.service"),
|
||||
},
|
||||
PackagedUnit {
|
||||
name: "bootvine-shutdown.service",
|
||||
contents: include_str!("../../system-files/systemd/bootvine-shutdown.service"),
|
||||
},
|
||||
];
|
||||
const DRACUT_MODULE_SETUP: &str =
|
||||
include_str!("../../system-files/dracut/90bootvine/module-setup.sh");
|
||||
const MKINITCPIO_INSTALL_HOOK: &str =
|
||||
include_str!("../../system-files/mkinitcpio/install/sd-bootvine");
|
||||
const INITRD_GENERATORS: [InitrdGenerator; 2] =
|
||||
[InitrdGenerator::Dracut, InitrdGenerator::Mkinitcpio];
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct InstallTarget {
|
||||
#[arg(
|
||||
long,
|
||||
default_value = "/usr",
|
||||
help = "Prefix for bin/bootvine and lib/systemd/system"
|
||||
)]
|
||||
prefix: PathBuf,
|
||||
#[arg(
|
||||
long,
|
||||
help = "Stage the files under this directory instead of /; skips sudo and systemctl"
|
||||
)]
|
||||
destdir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct InstallOptions {
|
||||
#[command(flatten)]
|
||||
target: InstallTarget,
|
||||
#[arg(
|
||||
long,
|
||||
value_enum,
|
||||
default_value_t = InitrdGenerator::None,
|
||||
help = "Also install the hook that adds bootvine to this initramfs generator"
|
||||
)]
|
||||
initrd: InitrdGenerator,
|
||||
#[arg(long, help = "Leave the units disabled")]
|
||||
no_enable: bool,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct UninstallOptions {
|
||||
#[command(flatten)]
|
||||
target: InstallTarget,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
|
||||
pub enum InitrdGenerator {
|
||||
None,
|
||||
Dracut,
|
||||
Mkinitcpio,
|
||||
}
|
||||
|
||||
struct InstalledFile {
|
||||
destination: PathBuf,
|
||||
contents: Vec<u8>,
|
||||
mode: u32,
|
||||
}
|
||||
|
||||
impl InstallTarget {
|
||||
fn staged(&self, path: &Path) -> PathBuf {
|
||||
match &self.destdir {
|
||||
Some(root) => root.join(path.strip_prefix("/").unwrap_or(path)),
|
||||
None => path.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn changes_live_system(&self) -> bool {
|
||||
self.destdir.is_none()
|
||||
}
|
||||
|
||||
fn needs_sudo(&self) -> bool {
|
||||
self.changes_live_system() && !geteuid().is_root()
|
||||
}
|
||||
|
||||
fn binary_path(&self) -> PathBuf {
|
||||
self.prefix.join("bin/bootvine")
|
||||
}
|
||||
|
||||
fn unit_path(&self, unit: &str) -> PathBuf {
|
||||
self.prefix.join("lib/systemd/system").join(unit)
|
||||
}
|
||||
|
||||
fn every_installed_path(&self) -> Vec<PathBuf> {
|
||||
once(self.binary_path())
|
||||
.chain(unit_files(self).map(|file| file.destination))
|
||||
.chain(
|
||||
INITRD_GENERATORS
|
||||
.into_iter()
|
||||
.flat_map(initrd_hook_files)
|
||||
.map(|file| file.destination),
|
||||
)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl InitrdGenerator {
|
||||
fn install_hint(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::None => None,
|
||||
Self::Dracut => Some("rebuild the initramfs: sudo dracut --force"),
|
||||
Self::Mkinitcpio => Some(
|
||||
"add sd-bootvine after systemd in HOOKS in /etc/mkinitcpio.conf, then run: sudo \
|
||||
mkinitcpio -P",
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn removal_hint(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::None => None,
|
||||
Self::Dracut => Some("rebuild the initramfs without bootvine: sudo dracut --force"),
|
||||
Self::Mkinitcpio => Some(
|
||||
"remove sd-bootvine from HOOKS in /etc/mkinitcpio.conf, then run: sudo mkinitcpio \
|
||||
-P",
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn running_binary() -> Result<PathBuf, InstallError> {
|
||||
env::current_exe().map_err(|source| InstallError::File {
|
||||
path: PathBuf::from("/proc/self/exe"),
|
||||
source,
|
||||
})
|
||||
}
|
||||
|
||||
fn binary_file(target: &InstallTarget) -> Result<Option<InstalledFile>, InstallError> {
|
||||
let running = running_binary()?;
|
||||
let destination = target.binary_path();
|
||||
if fs::canonicalize(target.staged(&destination)).is_ok_and(|resolved| resolved == running) {
|
||||
return Ok(None);
|
||||
}
|
||||
let contents = fs::read(&running).map_err(|source| InstallError::File {
|
||||
path: running,
|
||||
source,
|
||||
})?;
|
||||
Ok(Some(InstalledFile {
|
||||
destination,
|
||||
contents,
|
||||
mode: 0o755,
|
||||
}))
|
||||
}
|
||||
|
||||
fn unit_files(target: &InstallTarget) -> impl Iterator<Item = InstalledFile> {
|
||||
let binary_path = target.binary_path();
|
||||
PACKAGED_UNITS.iter().map(move |unit| InstalledFile {
|
||||
destination: target.unit_path(unit.name),
|
||||
contents: unit
|
||||
.contents
|
||||
.replace(PACKAGED_BINARY_PATH, &binary_path.to_string_lossy())
|
||||
.into_bytes(),
|
||||
mode: 0o644,
|
||||
})
|
||||
}
|
||||
|
||||
fn initrd_hook_files(initrd: InitrdGenerator) -> Vec<InstalledFile> {
|
||||
match initrd {
|
||||
InitrdGenerator::None => Vec::new(),
|
||||
InitrdGenerator::Dracut => vec![
|
||||
InstalledFile {
|
||||
destination: Path::new(DRACUT_MODULE_DIR).join("module-setup.sh"),
|
||||
contents: DRACUT_MODULE_SETUP.as_bytes().to_vec(),
|
||||
mode: 0o755,
|
||||
},
|
||||
InstalledFile {
|
||||
destination: PathBuf::from(DRACUT_CONF),
|
||||
contents: b"add_dracutmodules+=\" bootvine \"\n".to_vec(),
|
||||
mode: 0o644,
|
||||
},
|
||||
],
|
||||
InitrdGenerator::Mkinitcpio => vec![InstalledFile {
|
||||
destination: PathBuf::from(MKINITCPIO_HOOK),
|
||||
contents: MKINITCPIO_INSTALL_HOOK.as_bytes().to_vec(),
|
||||
mode: 0o644,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn sibling_for_replacement(path: &Path) -> PathBuf {
|
||||
let mut file_name = OsString::from(".");
|
||||
file_name.push(path.file_name().unwrap_or_default());
|
||||
file_name.push(".bootvine-new");
|
||||
path.with_file_name(file_name)
|
||||
}
|
||||
|
||||
fn write_installed_file(target: &InstallTarget, file: &InstalledFile) -> Result<(), InstallError> {
|
||||
let path = target.staged(&file.destination);
|
||||
let replacement = sibling_for_replacement(&path);
|
||||
path.parent()
|
||||
.map_or(Ok(()), fs::create_dir_all)
|
||||
.and_then(|()| fs::write(&replacement, &file.contents))
|
||||
.and_then(|()| fs::set_permissions(&replacement, Permissions::from_mode(file.mode)))
|
||||
.and_then(|()| fs::rename(&replacement, &path))
|
||||
.map_err(|source| InstallError::File { path, source })
|
||||
}
|
||||
|
||||
fn remove_if_present(path: PathBuf) -> Result<(), InstallError> {
|
||||
match fs::remove_file(&path) {
|
||||
Err(error) if error.kind() != ErrorKind::NotFound => Err(InstallError::File {
|
||||
path,
|
||||
source: error,
|
||||
}),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn run_command(command: &mut Command) -> Result<(), InstallError> {
|
||||
let program = command.get_program().to_string_lossy().into_owned();
|
||||
let status = command.status().map_err(|source| InstallError::Spawn {
|
||||
program: program.clone(),
|
||||
source,
|
||||
})?;
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(InstallError::Failed { program, status })
|
||||
}
|
||||
}
|
||||
|
||||
fn systemctl<'a>(arguments: impl IntoIterator<Item = &'a str>) -> Result<(), InstallError> {
|
||||
run_command(Command::new("systemctl").args(arguments))
|
||||
}
|
||||
|
||||
fn unit_names() -> impl Iterator<Item = &'static str> {
|
||||
PACKAGED_UNITS.iter().map(|unit| unit.name)
|
||||
}
|
||||
|
||||
fn rerun_with_sudo() -> Result<(), InstallError> {
|
||||
run_command(
|
||||
Command::new("sudo")
|
||||
.arg(running_binary()?)
|
||||
.args(env::args_os().skip(1)),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn install_files(options: &InstallOptions) -> Result<(), InstallError> {
|
||||
let target = &options.target;
|
||||
if target.needs_sudo() {
|
||||
return rerun_with_sudo();
|
||||
}
|
||||
binary_file(target)?
|
||||
.into_iter()
|
||||
.chain(unit_files(target))
|
||||
.chain(initrd_hook_files(options.initrd))
|
||||
.try_for_each(|file| write_installed_file(target, &file))?;
|
||||
if target.changes_live_system() {
|
||||
systemctl(["daemon-reload"])?;
|
||||
if !options.no_enable {
|
||||
systemctl(once("enable").chain(unit_names()))?;
|
||||
}
|
||||
if let Some(hint) = options.initrd.install_hint() {
|
||||
println!("{hint}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn installed_initrd_hooks(target: &InstallTarget) -> Vec<InitrdGenerator> {
|
||||
INITRD_GENERATORS
|
||||
.into_iter()
|
||||
.filter(|generator| {
|
||||
initrd_hook_files(*generator)
|
||||
.iter()
|
||||
.any(|file| target.staged(&file.destination).exists())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn uninstall_files(options: &UninstallOptions) -> Result<(), InstallError> {
|
||||
let target = &options.target;
|
||||
if target.needs_sudo() {
|
||||
return rerun_with_sudo();
|
||||
}
|
||||
let removed_initrd_hooks = installed_initrd_hooks(target);
|
||||
if target.changes_live_system() {
|
||||
let installed_units: Vec<&str> = unit_names()
|
||||
.filter(|unit| target.unit_path(unit).exists())
|
||||
.collect();
|
||||
if !installed_units.is_empty() {
|
||||
systemctl(once("disable").chain(installed_units))?;
|
||||
}
|
||||
}
|
||||
target
|
||||
.every_installed_path()
|
||||
.into_iter()
|
||||
.try_for_each(|path| remove_if_present(target.staged(&path)))?;
|
||||
let dracut_module_dir = target.staged(Path::new(DRACUT_MODULE_DIR));
|
||||
match fs::remove_dir(&dracut_module_dir) {
|
||||
Err(error) if error.kind() == ErrorKind::DirectoryNotEmpty => {
|
||||
return Err(InstallError::File {
|
||||
path: dracut_module_dir,
|
||||
source: error,
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if target.changes_live_system() {
|
||||
systemctl(["daemon-reload"])?;
|
||||
removed_initrd_hooks
|
||||
.into_iter()
|
||||
.filter_map(InitrdGenerator::removal_hint)
|
||||
.for_each(|hint| println!("{hint}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
pub mod boot_feed;
|
||||
mod journal_tail;
|
||||
pub mod link_error;
|
||||
pub mod monotonic_clock;
|
||||
pub mod switch_root;
|
||||
pub mod systemd_bus;
|
||||
@@ -0,0 +1,566 @@
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
iter::once,
|
||||
process,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use dbus::Path;
|
||||
use futures::{Stream, StreamExt, stream};
|
||||
use tokio::time::sleep;
|
||||
|
||||
use crate::{
|
||||
boot_model::{
|
||||
ActiveState, Activity, BootChange, BootState, FailureCause, HANDOFF_UNIT, JobKind,
|
||||
JobResult, Phase, UnitFacts,
|
||||
},
|
||||
console_session::{
|
||||
stream_sources::{BACKGROUND_CHECK_INTERVAL, CarriedItem, unfold_carrying},
|
||||
watch_screen::ScreenInput,
|
||||
},
|
||||
systemd_link::{
|
||||
journal_tail::recent_unit_messages,
|
||||
link_error::Error,
|
||||
monotonic_clock::monotonic_now,
|
||||
switch_root::Sysroot,
|
||||
systemd_bus::{
|
||||
BusConnection, FetchedUnit, JobListing, Scope, Session, Signal, SignalBatch,
|
||||
StatusOutput,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const RECONNECT_PATIENCE: Duration = Duration::from_secs(60);
|
||||
const JOURNAL_SETTLING_WAITS: [Duration; 3] = [
|
||||
Duration::from_millis(200),
|
||||
Duration::from_millis(300),
|
||||
Duration::from_millis(500),
|
||||
];
|
||||
const LOG_LINES_KEPT: usize = 6;
|
||||
const SWITCH_ROOT_UNIT: &str = "initrd-switch-root.service";
|
||||
const SHUTDOWN_ROOTS: [&str; 5] = [
|
||||
"poweroff.target",
|
||||
"reboot.target",
|
||||
"halt.target",
|
||||
"kexec.target",
|
||||
"soft-reboot.target",
|
||||
];
|
||||
const SHUTDOWN_FALLBACK_ROOT: &str = "shutdown.target";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum RootRequest {
|
||||
Named(String),
|
||||
ManagerDefault,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum ConnectAttempt {
|
||||
First,
|
||||
Again,
|
||||
}
|
||||
|
||||
enum Link {
|
||||
Connected(BusConnection),
|
||||
Connecting {
|
||||
deadline: Instant,
|
||||
attempt: ConnectAttempt,
|
||||
},
|
||||
Finished,
|
||||
}
|
||||
|
||||
impl Link {
|
||||
fn connecting(attempt: ConnectAttempt) -> Self {
|
||||
Self::Connecting {
|
||||
deadline: Instant::now() + RECONNECT_PATIENCE,
|
||||
attempt,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum RootSwitch {
|
||||
NotQueued,
|
||||
Queued(Sysroot),
|
||||
}
|
||||
|
||||
enum TrackedUnit {
|
||||
Known(String),
|
||||
New {
|
||||
facts: UnitFacts,
|
||||
activity: Activity,
|
||||
},
|
||||
}
|
||||
|
||||
impl TrackedUnit {
|
||||
fn name(&self) -> &str {
|
||||
match self {
|
||||
Self::Known(name) => name,
|
||||
Self::New { facts, .. } => &facts.name,
|
||||
}
|
||||
}
|
||||
|
||||
fn into_change(self) -> Option<BootChange> {
|
||||
match self {
|
||||
Self::Known(_) => None,
|
||||
Self::New { facts, activity } => Some(BootChange::TrackUnit { facts, activity }),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn queued_units(signals: &[Signal]) -> impl Iterator<Item = &str> {
|
||||
signals.iter().filter_map(|signal| match signal {
|
||||
Signal::JobNew { unit, .. } => Some(unit.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
struct BootTracker {
|
||||
scope: Scope,
|
||||
target: RootRequest,
|
||||
phase: Phase,
|
||||
unit_paths: HashMap<Path<'static>, String>,
|
||||
explained_failures: HashSet<String>,
|
||||
units_in_failed_state: HashSet<String>,
|
||||
root_switch: RootSwitch,
|
||||
}
|
||||
|
||||
struct BusFeed {
|
||||
link: Link,
|
||||
tracker: BootTracker,
|
||||
}
|
||||
|
||||
struct FeedProgress<'feed> {
|
||||
tracker: &'feed mut BootTracker,
|
||||
connection: &'feed mut BusConnection,
|
||||
changes: Vec<BootChange>,
|
||||
}
|
||||
|
||||
impl BusFeed {
|
||||
fn new(phase: Phase, scope: Scope, target: RootRequest) -> Self {
|
||||
Self {
|
||||
link: Link::connecting(ConnectAttempt::First),
|
||||
tracker: BootTracker {
|
||||
scope,
|
||||
target,
|
||||
phase,
|
||||
unit_paths: HashMap::new(),
|
||||
explained_failures: HashSet::new(),
|
||||
units_in_failed_state: HashSet::new(),
|
||||
root_switch: RootSwitch::NotQueued,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async fn next_inputs(&mut self) -> Option<Vec<ScreenInput>> {
|
||||
match &mut self.link {
|
||||
Link::Finished => None,
|
||||
Link::Connecting { deadline, attempt } => {
|
||||
let deadline = *deadline;
|
||||
let attempt = *attempt;
|
||||
Some(self.connect(deadline, attempt).await)
|
||||
}
|
||||
Link::Connected(connection) => {
|
||||
let received = self.tracker.receive(connection).await;
|
||||
Some(match received {
|
||||
Ok(changes) if changes.is_empty() => Vec::new(),
|
||||
Ok(changes) => vec![ScreenInput::Boot(changes)],
|
||||
Err(_) => self.lose_connection(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn open_watched(&mut self, attempt: ConnectAttempt) -> Result<Vec<BootChange>, Error> {
|
||||
let mut connection = BusConnection::register(Session::open(self.tracker.scope)?)?;
|
||||
let changes = self
|
||||
.tracker
|
||||
.start_watching(&mut connection, attempt)
|
||||
.await?;
|
||||
self.link = Link::Connected(connection);
|
||||
Ok(changes)
|
||||
}
|
||||
|
||||
async fn connect(&mut self, deadline: Instant, attempt: ConnectAttempt) -> Vec<ScreenInput> {
|
||||
match self.open_watched(attempt).await {
|
||||
Ok(changes) => vec![ScreenInput::Boot(changes), ScreenInput::FullRepaint],
|
||||
Err(_) if Instant::now() < deadline => {
|
||||
sleep(BACKGROUND_CHECK_INTERVAL).await;
|
||||
Vec::new()
|
||||
}
|
||||
Err(_) => {
|
||||
self.link = Link::Finished;
|
||||
vec![ScreenInput::Failed(Error::ManagerUnreachable)]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn lose_connection(&mut self) -> Vec<ScreenInput> {
|
||||
let at = monotonic_now();
|
||||
let tracker = &mut self.tracker;
|
||||
let RootSwitch::Queued(sysroot) = &tracker.root_switch else {
|
||||
if tracker.phase == Phase::Shutdown {
|
||||
self.link = Link::Finished;
|
||||
return vec![ScreenInput::Boot(vec![BootChange::ManagerExited { at }])];
|
||||
}
|
||||
self.link = Link::connecting(ConnectAttempt::Again);
|
||||
return vec![ScreenInput::Boot(vec![BootChange::ForgetJobs])];
|
||||
};
|
||||
if let Err(error) = sysroot.enter() {
|
||||
self.link = Link::Finished;
|
||||
return vec![ScreenInput::Failed(error.into())];
|
||||
}
|
||||
tracker.root_switch = RootSwitch::NotQueued;
|
||||
tracker.unit_paths.clear();
|
||||
tracker.explained_failures.clear();
|
||||
tracker.units_in_failed_state.clear();
|
||||
tracker.phase = Phase::Host;
|
||||
self.link = Link::connecting(ConnectAttempt::Again);
|
||||
vec![ScreenInput::Boot(vec![BootChange::SwitchRoot { at }])]
|
||||
}
|
||||
}
|
||||
|
||||
impl BootTracker {
|
||||
async fn receive(&mut self, connection: &mut BusConnection) -> Result<Vec<BootChange>, Error> {
|
||||
match connection.receive_signals(BACKGROUND_CHECK_INTERVAL).await {
|
||||
SignalBatch::Open(signals) => {
|
||||
self.arm_root_switch(queued_units(&signals));
|
||||
Ok(self
|
||||
.collect_changes(connection, signals, async |tracker, connection, signal| {
|
||||
tracker.changes_for(connection, signal).await
|
||||
})
|
||||
.await)
|
||||
}
|
||||
SignalBatch::Closed(signals) => {
|
||||
self.arm_root_switch(queued_units(&signals));
|
||||
Err(Error::Disconnected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn arm_root_switch<'unit>(&mut self, mut queued_units: impl Iterator<Item = &'unit str>) {
|
||||
if self.phase == Phase::Initrd
|
||||
&& matches!(self.root_switch, RootSwitch::NotQueued)
|
||||
&& queued_units.any(|unit| unit == SWITCH_ROOT_UNIT)
|
||||
&& let Ok(sysroot) = Sysroot::hold()
|
||||
{
|
||||
self.root_switch = RootSwitch::Queued(sysroot);
|
||||
}
|
||||
}
|
||||
|
||||
async fn collect_changes<Item>(
|
||||
&mut self,
|
||||
connection: &mut BusConnection,
|
||||
items: Vec<Item>,
|
||||
step: impl AsyncFn(&mut Self, &mut BusConnection, Item) -> Vec<BootChange>,
|
||||
) -> Vec<BootChange> {
|
||||
let step = &step;
|
||||
stream::iter(items)
|
||||
.fold(
|
||||
FeedProgress {
|
||||
tracker: self,
|
||||
connection,
|
||||
changes: Vec::new(),
|
||||
},
|
||||
|mut progress, item| async move {
|
||||
let changes = step(progress.tracker, progress.connection, item).await;
|
||||
progress.changes.extend(changes);
|
||||
progress
|
||||
},
|
||||
)
|
||||
.await
|
||||
.changes
|
||||
}
|
||||
|
||||
async fn requested_root(
|
||||
&self,
|
||||
connection: &mut BusConnection,
|
||||
jobs: &[JobListing],
|
||||
) -> Result<String, Error> {
|
||||
let RootRequest::Named(target) = &self.target else {
|
||||
if self.phase != Phase::Shutdown {
|
||||
return connection.default_target().await;
|
||||
}
|
||||
return Ok(SHUTDOWN_ROOTS
|
||||
.into_iter()
|
||||
.find(|root| {
|
||||
jobs.iter()
|
||||
.any(|job| job.unit == *root && job.kind == JobKind::BringsUp)
|
||||
})
|
||||
.unwrap_or(SHUTDOWN_FALLBACK_ROOT)
|
||||
.to_owned());
|
||||
};
|
||||
Ok(target.clone())
|
||||
}
|
||||
|
||||
async fn boot_progress_changes(
|
||||
&self,
|
||||
connection: &mut BusConnection,
|
||||
attempt: ConnectAttempt,
|
||||
) -> Result<Vec<BootChange>, Error> {
|
||||
let boot_in_progress = connection.boot_in_progress().await?;
|
||||
let origin = (attempt == ConnectAttempt::First).then(|| {
|
||||
BootChange::SetOrigin(if boot_in_progress {
|
||||
Duration::ZERO
|
||||
} else {
|
||||
monotonic_now()
|
||||
})
|
||||
});
|
||||
let finished = if boot_in_progress {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.boot_finished()
|
||||
};
|
||||
Ok(origin.into_iter().chain(finished).collect())
|
||||
}
|
||||
|
||||
async fn start_watching(
|
||||
&mut self,
|
||||
connection: &mut BusConnection,
|
||||
attempt: ConnectAttempt,
|
||||
) -> Result<Vec<BootChange>, Error> {
|
||||
connection.subscribe().await?;
|
||||
if self.scope == Scope::System {
|
||||
connection.set_show_status(StatusOutput::Silent).await.ok();
|
||||
}
|
||||
let shutting_down = self.phase == Phase::Shutdown;
|
||||
let jobs: Vec<JobListing> = connection
|
||||
.list_jobs()
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter(|job| shutting_down || job.kind == JobKind::BringsUp)
|
||||
.collect();
|
||||
self.arm_root_switch(jobs.iter().map(|job| job.unit.as_str()));
|
||||
let requested_root = self.requested_root(connection, &jobs).await?;
|
||||
let boot_progress = self.boot_progress_changes(connection, attempt).await?;
|
||||
let tracked_root = self.track(connection, &requested_root).await;
|
||||
let root = tracked_root
|
||||
.as_ref()
|
||||
.map_or(requested_root, |tracked| tracked.name().to_owned());
|
||||
let tracked_handoff = self.track(connection, HANDOFF_UNIT).await;
|
||||
let handoff = tracked_handoff
|
||||
.as_ref()
|
||||
.map(|tracked| BootChange::SetHandoff(tracked.name().to_owned()));
|
||||
let watched_units = jobs
|
||||
.iter()
|
||||
.map(|job| job.unit.clone())
|
||||
.chain(BootState::new(self.phase).milestone_targets)
|
||||
.collect();
|
||||
let tracked_changes = self
|
||||
.collect_changes(
|
||||
connection,
|
||||
watched_units,
|
||||
async |tracker, connection, unit| {
|
||||
tracker
|
||||
.track(connection, &unit)
|
||||
.await
|
||||
.and_then(TrackedUnit::into_change)
|
||||
.into_iter()
|
||||
.collect()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
eprintln!(
|
||||
"bootvine: watching {root} in {} as pid {} over {}",
|
||||
self.phase.label(),
|
||||
process::id(),
|
||||
if connection.peer_to_peer() {
|
||||
"the private socket"
|
||||
} else {
|
||||
"the bus"
|
||||
},
|
||||
);
|
||||
let queued_at = monotonic_now();
|
||||
Ok(boot_progress
|
||||
.into_iter()
|
||||
.chain(tracked_root.and_then(TrackedUnit::into_change))
|
||||
.chain(tracked_handoff.and_then(TrackedUnit::into_change))
|
||||
.chain(handoff)
|
||||
.chain(tracked_changes)
|
||||
.chain(once(BootChange::SetRoot(root)))
|
||||
.chain(jobs.into_iter().map(|job| BootChange::QueueJob {
|
||||
id: job.id,
|
||||
unit: job.unit,
|
||||
kind: job.kind,
|
||||
at: queued_at,
|
||||
}))
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn track(&mut self, connection: &mut BusConnection, unit: &str) -> Option<TrackedUnit> {
|
||||
if self.unit_paths.values().any(|known| known == unit) {
|
||||
return Some(TrackedUnit::Known(unit.to_owned()));
|
||||
}
|
||||
let FetchedUnit {
|
||||
path,
|
||||
facts,
|
||||
activity,
|
||||
} = connection.fetch_unit(unit).await.ok()?;
|
||||
if self.unit_paths.values().any(|known| *known == facts.name) {
|
||||
return Some(TrackedUnit::Known(facts.name));
|
||||
}
|
||||
self.unit_paths.insert(path, facts.name.clone());
|
||||
Some(TrackedUnit::New { facts, activity })
|
||||
}
|
||||
|
||||
async fn changes_for(
|
||||
&mut self,
|
||||
connection: &mut BusConnection,
|
||||
signal: Signal,
|
||||
) -> Vec<BootChange> {
|
||||
let at = monotonic_now();
|
||||
match signal {
|
||||
Signal::JobNew { id, job, unit } => {
|
||||
self.queue_new_job(connection, id, &job, unit, at).await
|
||||
}
|
||||
Signal::JobRemoved { id, unit, result } => {
|
||||
let explanation = match result {
|
||||
JobResult::Failed => self.explain_failure(connection, unit, "failed").await,
|
||||
JobResult::Timeout => self.explain_failure(connection, unit, "timed out").await,
|
||||
_ => None,
|
||||
};
|
||||
once(BootChange::FinishJob { id, result, at })
|
||||
.chain(explanation)
|
||||
.collect()
|
||||
}
|
||||
Signal::UnitChanged { path, activity } => {
|
||||
let Some(unit) = self.unit_paths.get(&path).cloned() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let explanation = if self.enters_failed_state(&unit, activity) {
|
||||
self.explain_failure(connection, unit.clone(), "failed")
|
||||
.await
|
||||
} else {
|
||||
None
|
||||
};
|
||||
once(BootChange::UpdateActivity { unit, activity })
|
||||
.chain(explanation)
|
||||
.collect()
|
||||
}
|
||||
Signal::BootFinished => self.boot_finished(),
|
||||
}
|
||||
}
|
||||
|
||||
fn enters_failed_state(&mut self, unit: &str, activity: Activity) -> bool {
|
||||
match activity.state {
|
||||
Some(ActiveState::Failed) => self.units_in_failed_state.insert(unit.to_owned()),
|
||||
Some(_) => {
|
||||
self.units_in_failed_state.remove(unit);
|
||||
false
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
async fn explain_failure(
|
||||
&mut self,
|
||||
connection: &mut BusConnection,
|
||||
unit: String,
|
||||
fallback_reason: &str,
|
||||
) -> Option<BootChange> {
|
||||
if !self.unit_paths.values().any(|known| *known == unit) {
|
||||
return None;
|
||||
}
|
||||
self.explained_failures.insert(unit.clone());
|
||||
let reason = connection
|
||||
.failure_reason(&unit)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or_else(|| fallback_reason.to_owned());
|
||||
let log_lines = settled_unit_messages(&unit).await;
|
||||
Some(BootChange::ExplainFailure {
|
||||
unit,
|
||||
cause: FailureCause { reason, log_lines },
|
||||
})
|
||||
}
|
||||
|
||||
fn boot_finished(&self) -> Vec<BootChange> {
|
||||
(self.phase == Phase::Host)
|
||||
.then_some(BootChange::BootFinished)
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn queue_new_job(
|
||||
&mut self,
|
||||
connection: &mut BusConnection,
|
||||
id: u32,
|
||||
job: &Path<'static>,
|
||||
unit: String,
|
||||
at: Duration,
|
||||
) -> Vec<BootChange> {
|
||||
let kind = connection.job_kind(job).await.unwrap_or(JobKind::Unknown);
|
||||
if kind == JobKind::TakesDown && self.phase != Phase::Shutdown {
|
||||
return Vec::new();
|
||||
}
|
||||
let tracked = self.track(connection, &unit).await;
|
||||
let unit = tracked
|
||||
.as_ref()
|
||||
.map_or(unit, |tracked| tracked.name().to_owned());
|
||||
tracked
|
||||
.and_then(TrackedUnit::into_change)
|
||||
.into_iter()
|
||||
.chain(once(BootChange::QueueJob { id, unit, kind, at }))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
async fn settled_unit_messages(unit: &str) -> Vec<String> {
|
||||
for settling in JOURNAL_SETTLING_WAITS {
|
||||
sleep(settling).await;
|
||||
let log_lines = recent_unit_messages(unit.to_owned(), LOG_LINES_KEPT).await;
|
||||
if !log_lines.is_empty() {
|
||||
return log_lines;
|
||||
}
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
pub fn bus_inputs(
|
||||
phase: Phase,
|
||||
scope: Scope,
|
||||
target: RootRequest,
|
||||
) -> impl Stream<Item = ScreenInput> {
|
||||
unfold_carrying(BusFeed::new(phase, scope, target), |mut feed| async move {
|
||||
let inputs = feed.next_inputs().await?;
|
||||
Some(CarriedItem {
|
||||
item: inputs,
|
||||
state: feed,
|
||||
})
|
||||
})
|
||||
.flat_map(stream::iter)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn host_tracker() -> BootTracker {
|
||||
BootTracker {
|
||||
scope: Scope::System,
|
||||
target: RootRequest::ManagerDefault,
|
||||
phase: Phase::Host,
|
||||
unit_paths: HashMap::new(),
|
||||
explained_failures: HashSet::new(),
|
||||
units_in_failed_state: HashSet::new(),
|
||||
root_switch: RootSwitch::NotQueued,
|
||||
}
|
||||
}
|
||||
|
||||
fn in_state(state: ActiveState) -> Activity {
|
||||
Activity {
|
||||
state: Some(state),
|
||||
..Activity::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_entering_the_failed_state_asks_for_a_fresh_explanation() {
|
||||
let mut tracker = host_tracker();
|
||||
let unit = "http-listener.service";
|
||||
assert!(tracker.enters_failed_state(unit, in_state(ActiveState::Failed)));
|
||||
assert!(!tracker.enters_failed_state(unit, in_state(ActiveState::Failed)));
|
||||
assert!(!tracker.enters_failed_state(unit, Activity::default()));
|
||||
assert!(!tracker.enters_failed_state(unit, in_state(ActiveState::Activating)));
|
||||
assert!(tracker.enters_failed_state(unit, in_state(ActiveState::Failed)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
use std::{io, str::Chars};
|
||||
|
||||
use systemd::{
|
||||
id128::Id128,
|
||||
journal::{Journal, OpenOptions},
|
||||
};
|
||||
use tokio::task::spawn_blocking;
|
||||
|
||||
const UNIT_FIELDS: [&str; 4] = ["_SYSTEMD_UNIT", "UNIT", "_SYSTEMD_USER_UNIT", "USER_UNIT"];
|
||||
const MANAGER_SUMMARY_MESSAGE_IDS: [&str; 10] = [
|
||||
"7d4958e842da4a758f6c1cdc7b36dcc5",
|
||||
"39f53479d3a045ac8e11786248231fbf",
|
||||
"7ad2d189f7e94e70a38c781354912448",
|
||||
"5eb03494b6584870a536b337290809b3",
|
||||
"be02cf6855d2428ba40df7e9d022f03d",
|
||||
"de5b426a63be47a7b6ac3eaac82e2f6f",
|
||||
"9d1aaa27d60140bd96365438aad20286",
|
||||
"ae8f7b866b0347b9af31fe1c80b127c0",
|
||||
"d9b373ed55a64feb8242e02dbe79a49c",
|
||||
"98e322203f7a4ed290d09fe03c09fe15",
|
||||
];
|
||||
const ENTRIES_SCANNED: usize = 200;
|
||||
const ESCAPE: char = '\u{1b}';
|
||||
|
||||
pub async fn recent_unit_messages(unit: String, wanted: usize) -> Vec<String> {
|
||||
spawn_blocking(move || {
|
||||
read_recent_messages(&unit, wanted).unwrap_or_else(|error| {
|
||||
eprintln!("bootvine: reading the journal of {unit}: {error}");
|
||||
Vec::new()
|
||||
})
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn read_recent_messages(unit: &str, wanted: usize) -> io::Result<Vec<String>> {
|
||||
let mut journal = OpenOptions::default().open()?;
|
||||
match_unit_in_this_boot(&mut journal, unit)?;
|
||||
journal.seek_tail()?;
|
||||
let mut newest_first = Vec::new();
|
||||
let mut scanned = 0;
|
||||
while newest_first.len() < wanted
|
||||
&& scanned < ENTRIES_SCANNED
|
||||
&& journal.previous().is_ok_and(|moved| moved > 0)
|
||||
{
|
||||
scanned += 1;
|
||||
if is_manager_summary(&mut journal).unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
if let Ok(Some(message)) = entry_message(&mut journal) {
|
||||
newest_first.push(message);
|
||||
}
|
||||
}
|
||||
newest_first.reverse();
|
||||
Ok(newest_first)
|
||||
}
|
||||
|
||||
fn match_unit_in_this_boot(journal: &mut Journal, unit: &str) -> io::Result<()> {
|
||||
UNIT_FIELDS.iter().try_for_each(|field| {
|
||||
journal.match_add(field, unit)?.match_or()?;
|
||||
Ok::<_, io::Error>(())
|
||||
})?;
|
||||
journal
|
||||
.match_and()?
|
||||
.match_add("_BOOT_ID", Id128::from_boot()?.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn field_text(journal: &mut Journal, field: &str) -> io::Result<Option<String>> {
|
||||
Ok(journal.get_data(field)?.and_then(|entry_field| {
|
||||
entry_field
|
||||
.value()
|
||||
.map(|value| String::from_utf8_lossy(value).into_owned())
|
||||
}))
|
||||
}
|
||||
|
||||
fn is_manager_summary(journal: &mut Journal) -> io::Result<bool> {
|
||||
Ok(field_text(journal, "MESSAGE_ID")?
|
||||
.is_some_and(|message_id| MANAGER_SUMMARY_MESSAGE_IDS.contains(&message_id.as_str())))
|
||||
}
|
||||
|
||||
fn entry_message(journal: &mut Journal) -> io::Result<Option<String>> {
|
||||
Ok(field_text(journal, "MESSAGE")?
|
||||
.map(|message| printable_line(&message))
|
||||
.filter(|line| !line.is_empty()))
|
||||
}
|
||||
|
||||
fn printable_line(message: &str) -> String {
|
||||
let mut characters = message.lines().next().unwrap_or_default().chars();
|
||||
let mut printable = String::new();
|
||||
while let Some(character) = characters.next() {
|
||||
if character == ESCAPE {
|
||||
skip_escape_sequence(&mut characters);
|
||||
} else if !character.is_control() {
|
||||
printable.push(character);
|
||||
}
|
||||
}
|
||||
printable.trim_end().to_owned()
|
||||
}
|
||||
|
||||
fn skip_escape_sequence(characters: &mut Chars<'_>) {
|
||||
if characters.clone().next() == Some('[') {
|
||||
characters.next();
|
||||
characters.find(|character| ('@'..='~').contains(character));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::env;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[ignore = "reads this machine's journal: cargo test journal_of_this_boot -- --ignored \
|
||||
--nocapture"]
|
||||
fn journal_of_this_boot_has_lines_for_journald() {
|
||||
let unit = env::var("BOOTVINE_JOURNAL_UNIT")
|
||||
.unwrap_or_else(|_| "systemd-journald.service".to_owned());
|
||||
let lines = read_recent_messages(&unit, 6).expect("readable journal");
|
||||
lines.iter().for_each(|line| println!("{line}"));
|
||||
assert!(!lines.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn printable_line_keeps_the_first_line_without_colours() {
|
||||
assert_eq!(
|
||||
printable_line("\u{1b}[31mno such file\u{1b}[0m\nsecond line"),
|
||||
"no such file"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
use std::{convert::Infallible, io};
|
||||
|
||||
use dbus::{Error as BusError, arg::TypeMismatchError};
|
||||
use rustix::io::Errno;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error("systemd bus: {0}")]
|
||||
Bus(#[from] BusError),
|
||||
#[error("unexpected reply from systemd: {0}")]
|
||||
Reply(#[from] TypeMismatchError),
|
||||
#[error("could not build a method call")]
|
||||
MalformedCall,
|
||||
#[error("the service manager closed the connection")]
|
||||
Disconnected,
|
||||
#[error("the service manager did not answer in time")]
|
||||
CallTimedOut,
|
||||
#[error("console: {0}")]
|
||||
Console(#[from] io::Error),
|
||||
#[error("entering the new root: {0}")]
|
||||
RootSwitch(#[from] Errno),
|
||||
#[error("the service manager did not come back")]
|
||||
ManagerUnreachable,
|
||||
}
|
||||
|
||||
impl From<Infallible> for Error {
|
||||
fn from(never: Infallible) -> Self {
|
||||
match never {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use rustix::time::{ClockId, clock_gettime};
|
||||
|
||||
#[must_use]
|
||||
pub fn monotonic_now() -> Duration {
|
||||
let now = clock_gettime(ClockId::Monotonic);
|
||||
Duration::new(
|
||||
now.tv_sec.cast_unsigned(),
|
||||
u32::try_from(now.tv_nsec).unwrap_or_default(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
use std::os::fd::OwnedFd;
|
||||
|
||||
use rustix::{
|
||||
fs::{Mode, OFlags, open},
|
||||
io::Errno,
|
||||
process::{chdir, chroot, fchdir},
|
||||
};
|
||||
|
||||
const SYSROOT: &str = "/sysroot";
|
||||
pub const INITRD_RELEASE: &str = "/etc/initrd-release";
|
||||
|
||||
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("/")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,677 @@
|
||||
use std::{
|
||||
future::ready,
|
||||
io, iter, mem,
|
||||
os::fd::{AsFd, AsRawFd, BorrowedFd, RawFd},
|
||||
pin::pin,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use dbus::{
|
||||
Message, MessageType, Path,
|
||||
arg::{AppendAll, PropMap, RefArg, Variant},
|
||||
channel::{BusType, Channel},
|
||||
};
|
||||
use futures::{TryStreamExt, stream};
|
||||
use rustix::event::{PollFd, PollFlags, Timespec, poll};
|
||||
use tokio::{io::unix::AsyncFd, time::timeout};
|
||||
|
||||
use crate::{
|
||||
boot_model::{Activity, JobKind, JobResult, UnitFacts, UnitKind, UnitTimeouts},
|
||||
console_session::stream_sources::{
|
||||
CarriedItem, readable_or_timeout, readable_source, unfold_carrying,
|
||||
},
|
||||
systemd_link::link_error::Error,
|
||||
};
|
||||
|
||||
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 SERVICE_INTERFACE: &str = "org.freedesktop.systemd1.Service";
|
||||
const MOUNT_INTERFACE: &str = "org.freedesktop.systemd1.Mount";
|
||||
const SWAP_INTERFACE: &str = "org.freedesktop.systemd1.Swap";
|
||||
const SOCKET_INTERFACE: &str = "org.freedesktop.systemd1.Socket";
|
||||
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);
|
||||
const UNLIMITED: Duration = Duration::from_micros(u64::MAX);
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Scope {
|
||||
System,
|
||||
User,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum StatusOutput {
|
||||
Silent,
|
||||
Configured,
|
||||
}
|
||||
|
||||
impl StatusOutput {
|
||||
fn bus_mode(self) -> &'static str {
|
||||
match self {
|
||||
Self::Silent => "no",
|
||||
Self::Configured => "",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum SignalBatch {
|
||||
Open(Vec<Signal>),
|
||||
Closed(Vec<Signal>),
|
||||
}
|
||||
|
||||
pub enum Signal {
|
||||
JobNew {
|
||||
id: u32,
|
||||
job: Path<'static>,
|
||||
unit: String,
|
||||
},
|
||||
JobRemoved {
|
||||
id: u32,
|
||||
unit: String,
|
||||
result: JobResult,
|
||||
},
|
||||
UnitChanged {
|
||||
path: Path<'static>,
|
||||
activity: Activity,
|
||||
},
|
||||
BootFinished,
|
||||
}
|
||||
|
||||
pub struct FetchedUnit {
|
||||
pub path: Path<'static>,
|
||||
pub facts: UnitFacts,
|
||||
pub activity: Activity,
|
||||
}
|
||||
|
||||
pub struct JobListing {
|
||||
pub id: u32,
|
||||
pub unit: String,
|
||||
pub kind: JobKind,
|
||||
}
|
||||
|
||||
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: serde_plain::from_str(&kind).unwrap_or(JobKind::Unknown),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Session {
|
||||
channel: Channel,
|
||||
peer_to_peer: bool,
|
||||
}
|
||||
|
||||
fn method_call(
|
||||
destination: &str,
|
||||
path: &str,
|
||||
interface: &str,
|
||||
member: &str,
|
||||
arguments: impl AppendAll,
|
||||
) -> Result<Message, Error> {
|
||||
let Ok(mut call) = Message::new_method_call(destination, path, interface, member) else {
|
||||
return Err(Error::MalformedCall);
|
||||
};
|
||||
call.append_all(arguments);
|
||||
Ok(call)
|
||||
}
|
||||
|
||||
fn manager_call(member: &str, arguments: impl AppendAll) -> Result<Message, Error> {
|
||||
method_call(
|
||||
DESTINATION,
|
||||
MANAGER_PATH,
|
||||
MANAGER_INTERFACE,
|
||||
member,
|
||||
arguments,
|
||||
)
|
||||
}
|
||||
|
||||
fn property_call(path: &str, interface: &str, property: &str) -> Result<Message, Error> {
|
||||
method_call(
|
||||
DESTINATION,
|
||||
path,
|
||||
PROPERTIES_INTERFACE,
|
||||
"Get",
|
||||
(interface, property),
|
||||
)
|
||||
}
|
||||
|
||||
fn boot_in_progress_call() -> Result<Message, Error> {
|
||||
property_call(MANAGER_PATH, MANAGER_INTERFACE, "FinishTimestampMonotonic")
|
||||
}
|
||||
|
||||
fn read_boot_in_progress(reply: &Message) -> Result<bool, Error> {
|
||||
let finished: Variant<u64> = reply.read1()?;
|
||||
Ok(finished.0 == 0)
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn open(scope: Scope) -> Result<Self, Error> {
|
||||
if scope == Scope::System
|
||||
&& let Ok(channel) = Channel::open_private(PRIVATE_SOCKET)
|
||||
{
|
||||
let session = Self::watching(channel, true);
|
||||
session.send(authentication_carrier()?)?;
|
||||
return Ok(session);
|
||||
}
|
||||
let bus = match scope {
|
||||
Scope::System => BusType::System,
|
||||
Scope::User => BusType::Session,
|
||||
};
|
||||
let session = Self::watching(Channel::get_private(bus)?, false);
|
||||
session.blocking_call(method_call(
|
||||
BUS_DESTINATION,
|
||||
BUS_PATH,
|
||||
BUS_DESTINATION,
|
||||
"AddMatch",
|
||||
(SIGNAL_RULE,),
|
||||
)?)?;
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
fn watching(mut channel: Channel, peer_to_peer: bool) -> Self {
|
||||
channel.set_watch_enabled(true);
|
||||
Self {
|
||||
channel,
|
||||
peer_to_peer,
|
||||
}
|
||||
}
|
||||
|
||||
fn blocking_call(&self, call: Message) -> Result<Message, Error> {
|
||||
Ok(self.channel.send_with_reply_and_block(call, CALL_TIMEOUT)?)
|
||||
}
|
||||
|
||||
pub fn set_show_status(&self, output: StatusOutput) -> Result<(), Error> {
|
||||
self.blocking_call(manager_call("SetShowStatus", (output.bus_mode(),))?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn boot_in_progress(&self) -> Result<bool, Error> {
|
||||
read_boot_in_progress(&self.blocking_call(boot_in_progress_call()?)?)
|
||||
}
|
||||
|
||||
fn send(&self, call: Message) -> Result<u32, Error> {
|
||||
let serial = self.channel.send(call).map_err(|()| Error::Disconnected)?;
|
||||
self.channel.flush();
|
||||
Ok(serial)
|
||||
}
|
||||
|
||||
fn socket_has_unread_bytes(&self) -> bool {
|
||||
let mut watched = [PollFd::new(self, PollFlags::IN)];
|
||||
poll(&mut watched, Some(&Timespec::default())).is_ok_and(|ready| ready > 0)
|
||||
}
|
||||
|
||||
fn read_one_chunk(&self) -> bool {
|
||||
self.channel.read_write(Some(Duration::ZERO)).is_ok() && self.channel.is_connected()
|
||||
}
|
||||
|
||||
fn arrived_messages(&self) -> Vec<Message> {
|
||||
iter::repeat_with(|| self.read_one_chunk())
|
||||
.find(|still_connected| !still_connected || !self.socket_has_unread_bytes());
|
||||
iter::from_fn(|| self.channel.pop_message()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BusConnection {
|
||||
session: AsyncFd<Session>,
|
||||
early_signals: Vec<Signal>,
|
||||
}
|
||||
|
||||
impl BusConnection {
|
||||
pub fn register(session: Session) -> io::Result<Self> {
|
||||
Ok(Self {
|
||||
session: readable_source(session)?,
|
||||
early_signals: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn peer_to_peer(&self) -> bool {
|
||||
self.session.get_ref().peer_to_peer
|
||||
}
|
||||
|
||||
fn drain_replies(&mut self) -> Result<Vec<Message>, Error> {
|
||||
let session = self.session.get_ref();
|
||||
let (signals, replies): (Vec<Message>, Vec<Message>) = session
|
||||
.arrived_messages()
|
||||
.into_iter()
|
||||
.partition(|message| message.msg_type() == MessageType::Signal);
|
||||
self.early_signals
|
||||
.extend(signals.iter().filter_map(parse_signal));
|
||||
if session.channel.is_connected() {
|
||||
Ok(replies)
|
||||
} else {
|
||||
Err(Error::Disconnected)
|
||||
}
|
||||
}
|
||||
|
||||
async fn next_replies(&mut self) -> Result<Vec<Message>, Error> {
|
||||
let drained = self.drain_replies()?;
|
||||
if !drained.is_empty() {
|
||||
return Ok(drained);
|
||||
}
|
||||
self.session.readable().await?.clear_ready();
|
||||
self.drain_replies()
|
||||
}
|
||||
|
||||
async fn reply_to(&mut self, serial: u32) -> Result<Message, Error> {
|
||||
let mut replies = pin!(
|
||||
unfold_carrying(self, |connection| async move {
|
||||
let replies = connection.next_replies().await;
|
||||
Some(CarriedItem {
|
||||
item: replies,
|
||||
state: connection,
|
||||
})
|
||||
})
|
||||
.map_ok(|replies| stream::iter(replies.into_iter().map(Ok::<_, Error>)))
|
||||
.try_flatten()
|
||||
.try_filter(|reply| ready(reply.get_reply_serial() == Some(serial)))
|
||||
);
|
||||
replies.try_next().await?.ok_or(Error::Disconnected)
|
||||
}
|
||||
|
||||
async fn call(&mut self, call: Message) -> Result<Message, Error> {
|
||||
let serial = self.session.get_ref().send(call)?;
|
||||
let Ok(reply) = timeout(CALL_TIMEOUT, self.reply_to(serial)).await else {
|
||||
return Err(Error::CallTimedOut);
|
||||
};
|
||||
let mut reply = reply?;
|
||||
reply.as_result()?;
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
pub async fn subscribe(&mut self) -> Result<(), Error> {
|
||||
self.call(manager_call("Subscribe", ())?).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn set_show_status(&mut self, output: StatusOutput) -> Result<(), Error> {
|
||||
self.call(manager_call("SetShowStatus", (output.bus_mode(),))?)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn default_target(&mut self) -> Result<String, Error> {
|
||||
let reply = self.call(manager_call("GetDefaultTarget", ())?).await?;
|
||||
Ok(reply.read1()?)
|
||||
}
|
||||
|
||||
pub async fn boot_in_progress(&mut self) -> Result<bool, Error> {
|
||||
read_boot_in_progress(&self.call(boot_in_progress_call()?).await?)
|
||||
}
|
||||
|
||||
pub async fn list_jobs(&mut self) -> Result<Vec<JobListing>, Error> {
|
||||
let reply = self.call(manager_call("ListJobs", ())?).await?;
|
||||
let listed: Vec<ListedJob> = reply.read1()?;
|
||||
Ok(listed.into_iter().map(JobListing::from).collect())
|
||||
}
|
||||
|
||||
pub async fn job_kind(&mut self, job: &Path<'_>) -> Result<JobKind, Error> {
|
||||
let reply = self
|
||||
.call(property_call(job, JOB_INTERFACE, "JobType")?)
|
||||
.await?;
|
||||
let kind: Variant<String> = reply.read1()?;
|
||||
Ok(serde_plain::from_str(&kind.0).unwrap_or(JobKind::Unknown))
|
||||
}
|
||||
|
||||
pub async fn fetch_unit(&mut self, name: &str) -> Result<FetchedUnit, Error> {
|
||||
let path: Path<'static> = self
|
||||
.call(manager_call("GetUnit", (name,))?)
|
||||
.await?
|
||||
.read1()?;
|
||||
let properties = self.all_properties(&path, UNIT_INTERFACE).await?;
|
||||
let kind_properties = match kind_interface(UnitKind::of(&unit_id(name, &properties))) {
|
||||
Some(interface) => self.all_properties(&path, interface).await?,
|
||||
None => PropMap::new(),
|
||||
};
|
||||
Ok(FetchedUnit {
|
||||
facts: unit_facts_from(name, &properties, &kind_properties),
|
||||
activity: activity_from(&properties),
|
||||
path,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn failure_reason(&mut self, name: &str) -> Result<Option<String>, Error> {
|
||||
let Some(interface) = kind_interface(UnitKind::of(name)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let path: Path<'static> = self
|
||||
.call(manager_call("GetUnit", (name,))?)
|
||||
.await?
|
||||
.read1()?;
|
||||
let properties = self.all_properties(&path, interface).await?;
|
||||
Ok(failure_reason_from(&properties))
|
||||
}
|
||||
|
||||
async fn all_properties(&mut self, path: &Path<'_>, interface: &str) -> Result<PropMap, Error> {
|
||||
Ok(self
|
||||
.call(method_call(
|
||||
DESTINATION,
|
||||
path,
|
||||
PROPERTIES_INTERFACE,
|
||||
"GetAll",
|
||||
(interface,),
|
||||
)?)
|
||||
.await?
|
||||
.read1()?)
|
||||
}
|
||||
|
||||
pub async fn receive_signals(&mut self, patience: Duration) -> SignalBatch {
|
||||
if self.early_signals.is_empty() {
|
||||
readable_or_timeout(&self.session, patience).await;
|
||||
}
|
||||
let still_connected = self.drain_replies().is_ok();
|
||||
let signals = mem::take(&mut self.early_signals);
|
||||
if still_connected {
|
||||
SignalBatch::Open(signals)
|
||||
} else {
|
||||
SignalBatch::Closed(signals)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn text_property(properties: &PropMap, property: &str) -> Option<String> {
|
||||
properties
|
||||
.get(property)
|
||||
.and_then(|value| value.0.as_str())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
fn signal_name(number: i64) -> String {
|
||||
let name = match number {
|
||||
1 => "SIGHUP",
|
||||
2 => "SIGINT",
|
||||
3 => "SIGQUIT",
|
||||
4 => "SIGILL",
|
||||
5 => "SIGTRAP",
|
||||
6 => "SIGABRT",
|
||||
7 => "SIGBUS",
|
||||
8 => "SIGFPE",
|
||||
9 => "SIGKILL",
|
||||
11 => "SIGSEGV",
|
||||
13 => "SIGPIPE",
|
||||
14 => "SIGALRM",
|
||||
15 => "SIGTERM",
|
||||
other => return format!("signal {other}"),
|
||||
};
|
||||
name.to_owned()
|
||||
}
|
||||
|
||||
fn failure_reason_from(properties: &PropMap) -> Option<String> {
|
||||
let result = text_property(properties, "Result").filter(|result| result != "success")?;
|
||||
let status = properties
|
||||
.get("ExecMainStatus")
|
||||
.and_then(|value| value.0.as_i64());
|
||||
let reason = match (result.as_str(), status) {
|
||||
("exit-code", Some(status)) if status != 0 => format!("exited with status {status}"),
|
||||
("exit-code", _) => "exited with an error".to_owned(),
|
||||
("signal", Some(signal)) => format!("killed by {}", signal_name(signal)),
|
||||
("core-dump", Some(signal)) => format!("dumped core on {}", signal_name(signal)),
|
||||
("timeout", _) => "timed out".to_owned(),
|
||||
("watchdog", _) => "stopped answering the watchdog".to_owned(),
|
||||
("start-limit-hit", _) => "restarted too often".to_owned(),
|
||||
("oom-kill", _) => "killed for running out of memory".to_owned(),
|
||||
("resources", _) => "could not set up its resources".to_owned(),
|
||||
("protocol", _) => "broke the start-up protocol".to_owned(),
|
||||
(other, _) => other.to_owned(),
|
||||
};
|
||||
Some(
|
||||
match text_property(properties, "StatusText").filter(|text| !text.is_empty()) {
|
||||
Some(status_text) => format!("{reason}: {status_text}"),
|
||||
None => reason,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn unit_id(name: &str, properties: &PropMap) -> String {
|
||||
text_property(properties, "Id").unwrap_or_else(|| name.to_owned())
|
||||
}
|
||||
|
||||
fn kind_interface(kind: UnitKind) -> Option<&'static str> {
|
||||
match kind {
|
||||
UnitKind::Service => Some(SERVICE_INTERFACE),
|
||||
UnitKind::Mount => Some(MOUNT_INTERFACE),
|
||||
UnitKind::Swap => Some(SWAP_INTERFACE),
|
||||
UnitKind::Socket => Some(SOCKET_INTERFACE),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn time_limit(properties: &PropMap, property: &str) -> Option<Duration> {
|
||||
properties
|
||||
.get(property)
|
||||
.and_then(|value| value.0.as_u64())
|
||||
.map(Duration::from_micros)
|
||||
.filter(|limit| !limit.is_zero() && *limit != UNLIMITED)
|
||||
}
|
||||
|
||||
fn timeouts_from(kind: UnitKind, unit: &PropMap, kind_specific: &PropMap) -> UnitTimeouts {
|
||||
let (start, stop) = if kind == UnitKind::Service {
|
||||
("TimeoutStartUSec", "TimeoutStopUSec")
|
||||
} else {
|
||||
("TimeoutUSec", "TimeoutUSec")
|
||||
};
|
||||
UnitTimeouts {
|
||||
start: time_limit(kind_specific, start),
|
||||
stop: time_limit(kind_specific, stop),
|
||||
job: time_limit(unit, "JobTimeoutUSec"),
|
||||
job_running: time_limit(unit, "JobRunningTimeoutUSec"),
|
||||
}
|
||||
}
|
||||
|
||||
fn unit_facts_from(name: &str, properties: &PropMap, kind_properties: &PropMap) -> UnitFacts {
|
||||
let text = |property: &str| text_property(properties, property);
|
||||
let names = |property: &str| {
|
||||
properties
|
||||
.get(property)
|
||||
.and_then(|value| value.0.as_iter())
|
||||
.map(|items| {
|
||||
items
|
||||
.filter_map(|item| item.as_str().map(ToOwned::to_owned))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let id = unit_id(name, properties);
|
||||
UnitFacts {
|
||||
timeouts: timeouts_from(UnitKind::of(&id), properties, kind_properties),
|
||||
name: id,
|
||||
description: text("Description").filter(|description| !description.is_empty()),
|
||||
after: names("After"),
|
||||
before: names("Before"),
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRawFd for Session {
|
||||
fn as_raw_fd(&self) -> RawFd {
|
||||
self.channel.watch().fd
|
||||
}
|
||||
}
|
||||
|
||||
impl AsFd for Session {
|
||||
fn as_fd(&self) -> BorrowedFd<'_> {
|
||||
unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
|
||||
}
|
||||
}
|
||||
|
||||
fn authentication_carrier() -> Result<Message, Error> {
|
||||
let mut ping = method_call(DESTINATION, MANAGER_PATH, PEER_INTERFACE, "Ping", ())?;
|
||||
ping.set_no_reply(true);
|
||||
Ok(ping)
|
||||
}
|
||||
|
||||
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" | "JobRemoved") => parse_job_signal(message, &member),
|
||||
(MANAGER_INTERFACE, "StartupFinished") => Some(Signal::BootFinished),
|
||||
(PROPERTIES_INTERFACE, "PropertiesChanged") => parse_unit_change(message),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_job_signal(message: &Message, member: &str) -> Option<Signal> {
|
||||
match member {
|
||||
"JobNew" => {
|
||||
let (id, job, unit): (u32, Path<'static>, String) = message.read3().ok()?;
|
||||
Some(Signal::JobNew { id, job, unit })
|
||||
}
|
||||
"JobRemoved" => {
|
||||
let (id, _job, unit, result): (u32, Path<'static>, String, String) =
|
||||
message.read4().ok()?;
|
||||
Some(Signal::JobRemoved {
|
||||
id,
|
||||
unit,
|
||||
result: serde_plain::from_str(&result).unwrap_or(JobResult::Failed),
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_unit_change(message: &Message) -> Option<Signal> {
|
||||
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),
|
||||
})
|
||||
}
|
||||
|
||||
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: properties
|
||||
.get("ActiveState")
|
||||
.and_then(|value| value.0.as_str())
|
||||
.and_then(|raw| serde_plain::from_str(raw).ok()),
|
||||
inactive_exit: monotonic("InactiveExitTimestampMonotonic"),
|
||||
active_enter: monotonic("ActiveEnterTimestampMonotonic"),
|
||||
active_exit: monotonic("ActiveExitTimestampMonotonic"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn startup_finished_signal_marks_the_boot_finished() {
|
||||
let startup_finished = Message::signal(
|
||||
&Path::from(MANAGER_PATH),
|
||||
&MANAGER_INTERFACE.into(),
|
||||
&"StartupFinished".into(),
|
||||
)
|
||||
.append3(0_u64, 0_u64, 0_u64)
|
||||
.append3(0_u64, 0_u64, 0_u64);
|
||||
assert!(matches!(
|
||||
parse_signal(&startup_finished),
|
||||
Some(Signal::BootFinished)
|
||||
));
|
||||
}
|
||||
|
||||
fn limit_properties(entries: &[(&str, Duration)]) -> PropMap {
|
||||
entries
|
||||
.iter()
|
||||
.map(|(name, limit)| {
|
||||
let micros = u64::try_from(limit.as_micros()).unwrap_or(u64::MAX);
|
||||
(
|
||||
(*name).to_owned(),
|
||||
Variant(Box::new(micros) as Box<dyn RefArg>),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlimited_timeouts_are_absent() {
|
||||
let unit = limit_properties(&[
|
||||
("JobTimeoutUSec", UNLIMITED),
|
||||
("JobRunningTimeoutUSec", Duration::ZERO),
|
||||
]);
|
||||
let service = limit_properties(&[
|
||||
("TimeoutStartUSec", UNLIMITED),
|
||||
("TimeoutStopUSec", Duration::from_secs(90)),
|
||||
]);
|
||||
assert_eq!(
|
||||
timeouts_from(UnitKind::Service, &unit, &service),
|
||||
UnitTimeouts {
|
||||
stop: Some(Duration::from_secs(90)),
|
||||
..UnitTimeouts::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
fn reason_properties(result: &str, status: i32, status_text: &str) -> PropMap {
|
||||
[
|
||||
("Result", Box::new(result.to_owned()) as Box<dyn RefArg>),
|
||||
("ExecMainStatus", Box::new(status)),
|
||||
("StatusText", Box::new(status_text.to_owned())),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(name, value)| (name.to_owned(), Variant(value)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_codes_and_signals_become_a_reason() {
|
||||
assert_eq!(
|
||||
failure_reason_from(&reason_properties("exit-code", 1, "")).as_deref(),
|
||||
Some("exited with status 1")
|
||||
);
|
||||
assert_eq!(
|
||||
failure_reason_from(&reason_properties("signal", 11, "")).as_deref(),
|
||||
Some("killed by SIGSEGV")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_text_follows_the_reason() {
|
||||
assert_eq!(
|
||||
failure_reason_from(&reason_properties("timeout", 0, "waiting for the disk"))
|
||||
.as_deref(),
|
||||
Some("timed out: waiting for the disk")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn success_has_no_reason() {
|
||||
assert_eq!(
|
||||
failure_reason_from(&reason_properties("success", 0, "")),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mounts_use_one_timeout_for_both_directions() {
|
||||
let mount = limit_properties(&[("TimeoutUSec", Duration::from_secs(20))]);
|
||||
let timeouts = timeouts_from(UnitKind::Mount, &PropMap::new(), &mount);
|
||||
assert_eq!(timeouts.start, Some(Duration::from_secs(20)));
|
||||
assert_eq!(timeouts.stop, Some(Duration::from_secs(20)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
disable=SC2154
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/bash
|
||||
|
||||
check() {
|
||||
require_binaries bootvine || return 1
|
||||
return 255
|
||||
}
|
||||
|
||||
depends() {
|
||||
echo systemd
|
||||
}
|
||||
|
||||
install() {
|
||||
inst_binary bootvine
|
||||
inst_simple "$systemdsystemunitdir/bootvine.service"
|
||||
if [[ -f /etc/bootvine.toml ]]; then
|
||||
inst_simple /etc/bootvine.toml
|
||||
fi
|
||||
$SYSTEMCTL -q --root "$initdir" enable bootvine.service
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/bash
|
||||
|
||||
build() {
|
||||
add_binary bootvine
|
||||
add_systemd_unit bootvine.service
|
||||
if [[ -f /etc/bootvine.toml ]]; then
|
||||
add_file /etc/bootvine.toml
|
||||
fi
|
||||
add_symlink /usr/lib/systemd/system/sysinit.target.wants/bootvine.service \
|
||||
/usr/lib/systemd/system/bootvine.service
|
||||
}
|
||||
|
||||
help() {
|
||||
cat <<HELP
|
||||
Shows a live dependency tree of systemd jobs while the initramfs boots.
|
||||
Requires the systemd hook; add sd-bootvine after it in HOOKS.
|
||||
HELP
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
[Unit]
|
||||
Description=Live dependency tree of shutdown jobs
|
||||
DefaultDependencies=no
|
||||
After=bootvine.service display-manager.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/bin/bootvine --shutdown
|
||||
StandardInput=tty
|
||||
StandardOutput=tty
|
||||
StandardError=journal
|
||||
TTYPath=/dev/tty12
|
||||
TTYReset=yes
|
||||
TTYVTDisallocate=no
|
||||
|
||||
[Install]
|
||||
WantedBy=shutdown.target
|
||||
@@ -0,0 +1,19 @@
|
||||
[Unit]
|
||||
Description=Live dependency tree of boot jobs
|
||||
DefaultDependencies=no
|
||||
IgnoreOnIsolate=yes
|
||||
Before=display-manager.service shutdown.target
|
||||
Conflicts=shutdown.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=@/usr/bin/bootvine @bootvine
|
||||
StandardInput=tty
|
||||
StandardOutput=tty
|
||||
StandardError=journal
|
||||
TTYPath=/dev/tty12
|
||||
TTYReset=yes
|
||||
TTYVTDisallocate=no
|
||||
|
||||
[Install]
|
||||
WantedBy=sysinit.target
|
||||
Reference in new issue
Block a user