feat: follow shutdowns on the boot console

This commit is contained in:
Willem Vanhulle committed 2026-10-11 20:16:16 +02:00
1 parent 74af283d57
commit 3fc9e2235c
16 files changed
+431 -103

No files matched your search

+6 -1
View File
@@ -13,6 +13,10 @@ follows the boot through the switch to the real root; without one it starts in
stage 2. While it runs it quiets the kernel console and systemd's status
output, and restores both when it hands the console back.
It also follows shutdowns and reboots: the units being stopped, nested under
the units that have to stop first, until systemd hands over to
`systemd-shutdown`.
## Try
```sh
@@ -29,7 +33,8 @@ On NixOS, import `nixosModules.default` from the flake and set
goes into the initrd as well.
Elsewhere, install the binary to `/usr/bin` and the package's `lib/` under
`/usr/lib`, then `systemctl enable bootvine.service`. To start it in the
`/usr/lib`, then `systemctl enable bootvine.service bootvine-shutdown.service`.
To start it in the
initrd, add `bootvine` to `add_dracutmodules` (dracut) or `sd-bootvine` after
`systemd` in `HOOKS` (mkinitcpio), and rebuild the initramfs.
+6 -1
View File
@@ -22,6 +22,11 @@ def "main start" [--units: path, --target: string] {
print $"started ($target); watch it with: bootvine --user --target ($target) --hold 3s"
}
def "main stop" [--units: path, --target: string] {
^systemctl --user stop --no-block ...(unit-names $units)
print $"stopping ($target); watch it with: bootvine --user --shutdown --target ($target)"
}
def "main remove" [--units: path, --target: string] {
^systemctl --user stop ...(unit-names $units)
unit-names $units | each {|name| rm -f (user-unit-dir | path join $name) } | ignore
@@ -29,5 +34,5 @@ def "main remove" [--units: path, --target: string] {
}
def main [--units: path, --target: string] {
print "usage: bootvine-demo-units (start | remove)"
print "usage: bootvine-demo-units (start | stop | remove)"
}
+5 -1
View File
@@ -14,6 +14,10 @@ let
"${pkgs.coreutils}/bin/sleep ${spec.seconds}"
]
++ lib.optional (spec.fails or false) "${pkgs.coreutils}/bin/false";
}
// lib.optionalAttrs (spec ? stopSeconds) {
RemainAfterExit = true;
ExecStop = "${pkgs.coreutils}/bin/sleep ${spec.stopSeconds}";
};
};
in
@@ -64,7 +68,7 @@ in
};
systemd.services = lib.mapAttrs (_: demoService) demoUnits.services // {
display-manager.after = [ "multi-user.target" ];
greetd.after = [ "multi-user.target" ];
};
services.greetd = {
+10 -1
View File
@@ -4,10 +4,14 @@
enableOCR = true;
nodes.machine =
{ lib, ... }:
{ lib, pkgs, ... }:
let
lingerFor = seconds: lib.mkForce "${pkgs.coreutils}/bin/sleep ${seconds}";
in
{
imports = [ demoHost ];
systemd.settings.Manager.ShowStatus = lib.mkForce true;
systemd.services.demo-db.serviceConfig.ExecStop = lingerFor "20";
virtualisation = {
memorySize = 2048;
qemu.options = [
@@ -51,5 +55,10 @@
assert "boot already finished" in machine.succeed("journalctl -u bootvine -o cat"), "a restart after boot did not stand down"
still_foreground = machine.succeed("cat /sys/class/tty/tty0/active").strip()
assert still_foreground == foreground, f"a restart after boot took the console: {foreground} -> {still_foreground}"
machine.succeed("systemctl poweroff --no-block")
machine.wait_for_text("demo-db")
machine.screenshot("shutdown")
machine.wait_for_shutdown()
'';
}
+10 -2
View File
@@ -2,14 +2,22 @@
target = "bootvine-demo";
initrdProbeSeconds = "6";
services = {
demo-disk.seconds = "2";
demo-disk = {
seconds = "2";
stopSeconds = "2";
};
demo-db = {
seconds = "3";
stopSeconds = "3";
after = [ "demo-disk" ];
};
demo-cache.seconds = "1.5";
demo-cache = {
seconds = "1.5";
stopSeconds = "1";
};
demo-web = {
seconds = "2";
stopSeconds = "2";
after = [
"demo-db"
"demo-cache"
+4
View File
@@ -23,6 +23,10 @@ let
"${coreutils}/bin/sleep ${spec.seconds}"
]
++ lib.optional (spec.fails or false) "${coreutils}/bin/false";
}
// lib.optionalAttrs (spec ? stopSeconds) {
RemainAfterExit = true;
ExecStop = "${coreutils}/bin/sleep ${spec.stopSeconds}";
};
});
+5 -2
View File
@@ -5,7 +5,7 @@ use std::{
};
use bootvine::{
model::{ActiveState, Activity, BootState, JobResult, Phase, UnitFacts},
model::{ActiveState, Activity, BootState, JobKind, JobResult, Phase, UnitFacts},
palette::Palette,
view::BootView,
};
@@ -177,6 +177,7 @@ impl ScriptedJob {
name: self.step.unit.to_owned(),
description: self.step.unit.to_owned(),
after: self.step.after.iter().map(ToString::to_string).collect(),
before: Vec::new(),
}
}
@@ -214,7 +215,7 @@ impl Script {
jobs.iter()
.for_each(|job| state.track_unit(job.facts(), Activity::default()));
jobs.iter()
.for_each(|job| state.queue_job(job.id, job.step.unit, now));
.for_each(|job| state.queue_job(job.id, job.step.unit, JobKind::BringsUp, now));
Self {
jobs,
started: HashMap::new(),
@@ -254,6 +255,7 @@ impl Script {
state: Some(ActiveState::Activating),
inactive_exit: Some(now),
active_enter: None,
active_exit: None,
},
);
});
@@ -273,6 +275,7 @@ impl Script {
state: Some(job.settled_state()),
inactive_exit: None,
active_enter: Some(now),
active_exit: None,
},
);
state.finish_job(job.id, job.outcome(), now);
+5 -3
View File
@@ -76,9 +76,11 @@
};
strictDeps = true;
postInstall = ''
install -Dm644 packaging/systemd/bootvine.service $out/lib/systemd/system/bootvine.service
substituteInPlace $out/lib/systemd/system/bootvine.service \
--replace-fail /usr/bin/bootvine $out/bin/bootvine
for unit in bootvine.service bootvine-shutdown.service; do
install -Dm644 packaging/systemd/$unit $out/lib/systemd/system/$unit
substituteInPlace $out/lib/systemd/system/$unit \
--replace-fail /usr/bin/bootvine $out/bin/bootvine
done
install -Dm755 packaging/dracut/90bootvine/module-setup.sh \
$out/lib/dracut/modules.d/90bootvine/module-setup.sh
install -Dm644 packaging/mkinitcpio/install/sd-bootvine \
+3 -1
View File
@@ -28,7 +28,8 @@ in
a live dependency tree of systemd jobs on the boot console. With a
systemd initrd it starts there and survives the switch to the real root;
otherwise it starts in stage 2. It hands the console back once the
display manager starts or the default target is reached
display manager starts or the default target is reached, and comes back
for shutdown until systemd hands over to systemd-shutdown
'';
package = lib.mkOption {
@@ -58,6 +59,7 @@ in
systemd = {
packages = [ cfg.package ];
services.bootvine.wantedBy = [ "sysinit.target" ];
services.bootvine-shutdown.wantedBy = [ "shutdown.target" ];
};
boot.initrd.systemd = lib.mkIf config.boot.initrd.systemd.enable {
@@ -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
+43 -15
View File
@@ -6,7 +6,9 @@ use std::{
time::{Duration, Instant},
};
use bootvine::model::{BootState, HANDOFF_UNIT, HOST_MILESTONES};
use bootvine::model::{
BootState, HANDOFF_UNIT, HOST_MILESTONES, JobKind, Phase, SHUTDOWN_MILESTONES,
};
use dbus::Path;
use crate::{
@@ -18,6 +20,14 @@ use crate::{
const RECONNECT_PATIENCE: Duration = Duration::from_secs(60);
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";
const SILENT_STATUS: &str = "no";
const CONFIGURED_STATUS: &str = "";
@@ -49,6 +59,10 @@ impl Feed {
}
pub fn pump(&mut self, state: &mut BootState, wait: Duration) -> Result<(), Error> {
if state.manager_exited_at.is_some() {
sleep(wait);
return Ok(());
}
let Some(session) = self.session.take() else {
return self.connect_or_wait(state, wait);
};
@@ -87,6 +101,9 @@ impl Feed {
self.unit_paths.clear();
state.switch_root(monotonic_now());
}
None if state.phase == Phase::Shutdown => {
state.manager_exited_at = Some(monotonic_now());
}
None => state.forget_jobs(),
}
self.reconnect_deadline = Instant::now() + RECONNECT_PATIENCE;
@@ -99,10 +116,29 @@ impl Feed {
if self.scope == Scope::System {
session.set_show_status(SILENT_STATUS).ok();
}
let shutting_down = state.phase == Phase::Shutdown;
let jobs: Vec<_> = session
.list_jobs()?
.into_iter()
.filter(|job| shutting_down || job.kind == JobKind::BringsUp)
.collect();
let requested_root = match &self.target {
Some(target) => target.clone(),
None if shutting_down => SHUTDOWN_ROOTS
.into_iter()
.find(|root| {
jobs.iter()
.any(|job| job.unit == *root && job.kind == JobKind::BringsUp)
})
.unwrap_or(SHUTDOWN_FALLBACK_ROOT)
.to_owned(),
None => session.default_target()?,
};
let milestones: &[&str] = if shutting_down {
&SHUTDOWN_MILESTONES
} else {
&HOST_MILESTONES
};
if !self.gave_origin {
state.origin = if session.boot_in_progress()? {
Duration::ZERO
@@ -117,24 +153,19 @@ impl Feed {
if let Some(handoff) = self.track(&session, state, HANDOFF_UNIT) {
state.set_handoff(handoff);
}
let jobs: Vec<_> = session
.list_jobs()?
.into_iter()
.filter(|job| job.brings_unit_up)
.collect();
jobs.iter()
.map(|job| job.unit.as_str())
.chain(HOST_MILESTONES)
.chain(milestones.iter().copied())
.for_each(|unit| {
self.track(&session, state, unit);
});
state.set_root(root.clone());
let now = monotonic_now();
jobs.iter()
.for_each(|job| state.queue_job(job.id, &job.unit, now));
.for_each(|job| state.queue_job(job.id, &job.unit, job.kind, now));
eprintln!(
"bootvine: watching {root} in {} as pid {} over {}",
if self.in_initrd { "initrd" } else { "stage 2" },
state.phase.label(),
process::id(),
if session.peer_to_peer {
"the private socket"
@@ -162,18 +193,15 @@ impl Feed {
fn apply(&mut self, session: &Session, state: &mut BootState, signal: Signal) {
match signal {
Signal::JobNew { id, job, unit } => {
let brings_unit_up = session.job_brings_unit_up(&job);
if brings_unit_up.as_ref().is_ok_and(|up| !up) {
let kind = session.job_kind(&job).unwrap_or(JobKind::Unknown);
if kind == JobKind::TakesDown && state.phase != Phase::Shutdown {
return;
}
let unit = self.track(session, state, &unit).unwrap_or(unit);
if self.in_initrd && unit == SWITCH_ROOT_UNIT {
self.sysroot = Sysroot::hold().ok();
}
match brings_unit_up {
Ok(_) => state.queue_job(id, &unit, monotonic_now()),
Err(_) => state.queue_job_of_unknown_kind(id, &unit, monotonic_now()),
}
state.queue_job(id, &unit, kind, monotonic_now());
}
Signal::JobRemoved { id, result } => state.finish_job(id, result, monotonic_now()),
Signal::UnitChanged { path, activity } => {
+6
View File
@@ -22,6 +22,11 @@ use crate::{
struct Cli {
#[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"
@@ -62,6 +67,7 @@ fn main() -> ExitCode {
};
let options = Options {
scope: if cli.user { Scope::User } else { Scope::System },
shutdown: cli.shutdown,
target: cli.target,
hold: cli.hold,
palette: config.palette,
+214 -43
View File
@@ -8,6 +8,7 @@ pub enum Phase {
Initrd,
Host,
User,
Shutdown,
}
impl Phase {
@@ -17,6 +18,7 @@ impl Phase {
Self::Initrd => "initrd",
Self::Host => "stage 2",
Self::User => "user",
Self::Shutdown => "shutdown",
}
}
}
@@ -74,6 +76,7 @@ pub struct UnitFacts {
pub name: String,
pub description: String,
pub after: Vec<String>,
pub before: Vec<String>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -81,13 +84,21 @@ pub struct Activity {
pub state: Option<ActiveState>,
pub inactive_exit: Option<Duration>,
pub active_enter: Option<Duration>,
pub active_exit: Option<Duration>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum JobKind {
BringsUp,
TakesDown,
Unknown,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct PendingJob {
id: u32,
queued_at: Duration,
brings_up: bool,
kind: JobKind,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -103,6 +114,7 @@ struct UnitRecord {
state: ActiveState,
inactive_exit: Option<Duration>,
active_enter: Option<Duration>,
active_exit: Option<Duration>,
job: Option<PendingJob>,
outcome: Option<Outcome>,
}
@@ -118,6 +130,16 @@ impl UnitRecord {
if activity.active_enter.is_some() {
self.active_enter = activity.active_enter;
}
if activity.active_exit.is_some() {
self.active_exit = activity.active_exit;
}
}
fn transition_started(&self, kind: JobKind) -> Option<Duration> {
match kind {
JobKind::TakesDown => self.active_exit,
JobKind::BringsUp | JobKind::Unknown => self.inactive_exit,
}
}
fn running_since(&self) -> Option<Duration> {
@@ -126,7 +148,11 @@ impl UnitRecord {
self.state,
ActiveState::Activating | ActiveState::Deactivating | ActiveState::Reloading
);
transitioning.then(|| self.inactive_exit.unwrap_or(job.queued_at))
transitioning.then(|| self.transition_started(job.kind).unwrap_or(job.queued_at))
}
fn takes_down(&self) -> bool {
self.job.is_some_and(|job| job.kind == JobKind::TakesDown)
}
}
@@ -188,6 +214,7 @@ pub struct BootState {
pub finished_stages: Vec<FinishedStage>,
pub finished_runs: Vec<FinishedRun>,
pub handoff_unit: Option<String>,
pub manager_exited_at: Option<Duration>,
root_job_seen: bool,
milestone_targets: Vec<String>,
finished_before_reconnect: usize,
@@ -202,6 +229,8 @@ pub const HOST_MILESTONES: [&str; 4] = [
"graphical.target",
];
pub const SHUTDOWN_MILESTONES: [&str; 3] = ["shutdown.target", "umount.target", "final.target"];
pub const HANDOFF_UNIT: &str = "display-manager.service";
impl BootState {
@@ -212,6 +241,13 @@ impl BootState {
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 {
@@ -223,6 +259,7 @@ impl BootState {
finished_runs: Vec::new(),
root_job_seen: false,
handoff_unit,
manager_exited_at: None,
milestone_targets,
finished_before_reconnect: 0,
units: HashMap::new(),
@@ -255,6 +292,7 @@ impl BootState {
state: ActiveState::Inactive,
inactive_exit: None,
active_enter: None,
active_exit: None,
job: None,
outcome: None,
});
@@ -268,20 +306,17 @@ impl BootState {
}
}
pub fn queue_job(&mut self, id: u32, unit: &str, at: Duration) {
self.enqueue(id, unit, at, true);
if self.jobs.get(&id).is_some_and(|tracked| tracked == unit)
pub fn queue_job(&mut self, id: u32, unit: &str, kind: JobKind, at: Duration) {
self.enqueue(id, unit, kind, at);
if kind == JobKind::BringsUp
&& self.jobs.get(&id).is_some_and(|tracked| tracked == unit)
&& self.root.as_deref() == Some(unit)
{
self.root_job_seen = true;
}
}
pub fn queue_job_of_unknown_kind(&mut self, id: u32, unit: &str, at: Duration) {
self.enqueue(id, unit, at, false);
}
fn enqueue(&mut self, id: u32, unit: &str, at: Duration, brings_up: bool) {
fn enqueue(&mut self, id: u32, unit: &str, kind: JobKind, at: Duration) {
if self.jobs.contains_key(&id) {
return;
}
@@ -291,7 +326,7 @@ impl BootState {
record.job = Some(PendingJob {
id,
queued_at: at,
brings_up,
kind,
});
record.outcome = None;
self.jobs.insert(id, unit.to_owned());
@@ -305,9 +340,10 @@ impl BootState {
return;
};
let started_at = record
.inactive_exit
.filter(|started| *started >= self.origin && *started <= at)
.filter(|_| record.job.is_some_and(|job| job.id == id && job.brings_up));
.job
.filter(|job| job.id == id && job.kind != JobKind::Unknown)
.and_then(|job| record.transition_started(job.kind))
.filter(|started| *started >= self.origin && *started <= at);
if record.job.is_some_and(|job| job.id == id) {
record.job = None;
}
@@ -370,7 +406,7 @@ impl BootState {
#[must_use]
pub fn is_complete(&self) -> bool {
if self.phase == Phase::Initrd {
if matches!(self.phase, Phase::Initrd | Phase::Shutdown) {
return false;
}
if let Some(handoff) = self
@@ -484,9 +520,7 @@ impl BootState {
let root = self.root.as_deref().filter(|root| pending.contains(root));
let blocked_by_pending: HashSet<&str> = pending
.iter()
.flat_map(|name| self.units[*name].facts.after.iter())
.map(String::as_str)
.filter(|dependency| pending.contains(dependency))
.flat_map(|name| self.waits_for(name, &pending))
.collect();
let mut unblocked: Vec<&str> = pending
.iter()
@@ -548,12 +582,10 @@ impl BootState {
queued_at: job.queued_at,
running_since,
});
let candidates: Vec<&str> = record
.facts
.after
.iter()
.map(String::as_str)
.filter(|dependency| pending.contains(dependency) && !visited.contains(dependency))
let candidates: Vec<&str> = self
.waits_for(unit, pending)
.into_iter()
.filter(|dependency| !visited.contains(dependency))
.collect();
let mut children: Vec<&str> = candidates
.iter()
@@ -585,23 +617,33 @@ impl BootState {
if !seen.insert(unit) {
continue;
}
let Some(record) = self.units.get(unit) else {
continue;
};
let mut next = record
.facts
.after
.iter()
.map(String::as_str)
.filter(|after| pending.contains(after));
if next.clone().any(|after| after == dependency) {
let next = self.waits_for(unit, pending);
if next.contains(&dependency) {
return true;
}
frontier.extend(next.by_ref());
frontier.extend(next);
}
false
}
fn waits_for<'a>(&'a self, waiter: &str, pending: &HashSet<&str>) -> Vec<&'a str> {
let Some(record) = self.units.get(waiter) else {
return Vec::new();
};
let pending_job = |dependency: &&'a str| pending.contains(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| match self.units[name].running_since() {
Some(since) => SiblingRank::RunningSince(since),
@@ -667,6 +709,7 @@ mod tests {
name: name.to_owned(),
description: format!("{name} description"),
after: after.iter().map(ToString::to_string).collect(),
before: Vec::new(),
}
}
@@ -675,6 +718,7 @@ mod tests {
state: Some(ActiveState::Activating),
inactive_exit: Some(since),
active_enter: None,
active_exit: None,
}
}
@@ -710,7 +754,7 @@ mod tests {
.for_each(|((unit, activity), id)| {
let name = unit.name.clone();
state.track_unit(unit, activity);
state.queue_job(id, &name, 500 * MS);
state.queue_job(id, &name, JobKind::BringsUp, 500 * MS);
});
state
}
@@ -747,6 +791,7 @@ mod tests {
state: Some(ActiveState::Active),
inactive_exit: None,
active_enter: Some(4000 * MS),
active_exit: None,
},
);
let rows = state.pending_rows();
@@ -784,7 +829,7 @@ mod tests {
fn display_manager_activation_hands_the_console_over() {
let mut state = sample();
state.track_unit(facts(HANDOFF_UNIT, &[]), Activity::default());
state.queue_job(20, HANDOFF_UNIT, 500 * MS);
state.queue_job(20, HANDOFF_UNIT, JobKind::BringsUp, 500 * MS);
assert!(!state.is_complete());
state.update_activity(HANDOFF_UNIT, activating(6000 * MS));
assert!(state.is_complete());
@@ -796,8 +841,8 @@ mod tests {
state.set_root("initrd.target".to_owned());
state.track_unit(facts("initrd.target", &[]), Activity::default());
state.track_unit(facts("sysroot.mount", &[]), Activity::default());
state.queue_job(1, "initrd.target", Duration::ZERO);
state.queue_job(2, "sysroot.mount", Duration::ZERO);
state.queue_job(1, "initrd.target", JobKind::BringsUp, Duration::ZERO);
state.queue_job(2, "sysroot.mount", JobKind::BringsUp, Duration::ZERO);
state.finish_job(2, JobResult::Done, 1000 * MS);
state.finish_job(1, JobResult::Done, 1500 * MS);
assert!(!state.is_complete());
@@ -825,10 +870,11 @@ mod tests {
name: "dev-nvme1n1.device".to_owned(),
description: "Lexar SSD NM790 2TB".to_owned(),
after: Vec::new(),
before: Vec::new(),
},
Activity::default(),
);
state.queue_job(1, "dev-nvme1n1.device", Duration::ZERO);
state.queue_job(1, "dev-nvme1n1.device", JobKind::BringsUp, Duration::ZERO);
assert_eq!(state.pending_rows()[0].label, "Lexar SSD NM790 2TB");
}
@@ -850,7 +896,7 @@ mod tests {
.for_each(|(unit, id)| {
let name = unit.name.clone();
state.track_unit(unit, Activity::default());
state.queue_job(id, &name, Duration::ZERO);
state.queue_job(id, &name, JobKind::BringsUp, Duration::ZERO);
});
let outline: Vec<String> = state
.pending_rows()
@@ -860,13 +906,138 @@ mod tests {
assert_eq!(outline, ["demo.target", " report", " web", " db"]);
}
fn ordered(name: &str, after: &[&str], before: &[&str]) -> UnitFacts {
UnitFacts {
before: before.iter().map(ToString::to_string).collect(),
..facts(name, after)
}
}
fn outline(state: &BootState) -> Vec<String> {
state
.pending_rows()
.into_iter()
.map(|row| format!("{}{}", " ".repeat(row.depth), row.label))
.collect()
}
#[test]
fn stopping_units_wait_on_what_was_ordered_after_them() {
let mut state = BootState::new(Phase::Shutdown);
state.set_root("poweroff.target".to_owned());
[
(
ordered("poweroff.target", &["shutdown.target"], &[]),
JobKind::BringsUp,
),
(
ordered("shutdown.target", &[], &["poweroff.target"]),
JobKind::BringsUp,
),
(
ordered("network.target", &[], &["web.service"]),
JobKind::TakesDown,
),
(
ordered("web.service", &["network.target"], &[]),
JobKind::TakesDown,
),
]
.into_iter()
.zip(1..)
.for_each(|((unit, kind), id)| {
let name = unit.name.clone();
state.track_unit(unit, Activity::default());
state.queue_job(id, &name, kind, Duration::ZERO);
});
assert_eq!(
outline(&state),
[
"poweroff.target",
" shutdown.target",
"network.target",
" web",
]
);
}
#[test]
fn starting_units_wait_on_stops_in_either_direction() {
let mut state = BootState::new(Phase::Shutdown);
state.set_root("shutdown.target".to_owned());
[
(
ordered("shutdown.target", &[], &["db.service"]),
JobKind::BringsUp,
),
(
ordered("db.service", &["shutdown.target"], &[]),
JobKind::TakesDown,
),
]
.into_iter()
.zip(1..)
.for_each(|((unit, kind), id)| {
let name = unit.name.clone();
state.track_unit(unit, Activity::default());
state.queue_job(id, &name, kind, Duration::ZERO);
});
assert_eq!(outline(&state), ["shutdown.target", " db"]);
}
#[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!(state.pending_rows()[0].running_since, Some(1200 * MS));
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,
}]
);
}
#[test]
fn shutdown_counts_toward_its_own_milestones_and_never_completes() {
let mut state = BootState::new(Phase::Shutdown);
state.set_root("poweroff.target".to_owned());
["poweroff.target", "shutdown.target", "db.service"]
.into_iter()
.for_each(|name| state.track_unit(facts(name, &[]), Activity::default()));
state.queue_job(1, "poweroff.target", JobKind::BringsUp, Duration::ZERO);
state.queue_job(2, "shutdown.target", JobKind::BringsUp, Duration::ZERO);
state.queue_job(3, "db.service", JobKind::TakesDown, Duration::ZERO);
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());
}
#[test]
fn ordering_cycles_do_not_repeat_units() {
let mut state = BootState::new(Phase::Host);
state.track_unit(facts("a.service", &["b.service"]), Activity::default());
state.track_unit(facts("b.service", &["a.service"]), Activity::default());
state.queue_job(1, "a.service", Duration::ZERO);
state.queue_job(2, "b.service", Duration::ZERO);
state.queue_job(1, "a.service", JobKind::BringsUp, Duration::ZERO);
state.queue_job(2, "b.service", JobKind::BringsUp, Duration::ZERO);
assert_eq!(state.pending_rows().len(), 2);
}
}
+3
View File
@@ -35,6 +35,7 @@ const FULL_REPAINT_INTERVAL: Duration = Duration::from_secs(1);
pub struct Options {
pub scope: Scope,
pub shutdown: bool,
pub target: Option<String>,
pub hold: Duration,
pub palette: Palette,
@@ -44,6 +45,7 @@ pub fn run(options: &Options) -> Result<(), Error> {
let terminate = Arc::new(AtomicBool::new(false));
flag::register(SIGTERM, Arc::clone(&terminate))?;
if options.scope == Scope::System
&& !options.shutdown
&& Session::open(Scope::System)
.and_then(|session| session.boot_in_progress())
.is_ok_and(|booting| !booting)
@@ -52,6 +54,7 @@ pub fn run(options: &Options) -> Result<(), Error> {
return Ok(());
}
let phase = match options.scope {
_ if options.shutdown => Phase::Shutdown,
Scope::User => Phase::User,
Scope::System if Path::new(INITRD_RELEASE).exists() => Phase::Initrd,
Scope::System => Phase::Host,
+27 -15
View File
@@ -1,6 +1,6 @@
use std::{iter, time::Duration};
use bootvine::model::{ActiveState, Activity, JobResult, UnitFacts};
use bootvine::model::{ActiveState, Activity, JobKind, JobResult, UnitFacts};
use dbus::{
Message, MessageType, Path,
arg::{AppendAll, PropMap, RefArg, Variant},
@@ -54,7 +54,7 @@ pub struct FetchedUnit {
pub struct JobListing {
pub id: u32,
pub unit: String,
pub brings_unit_up: bool,
pub kind: JobKind,
}
type ListedJob = (u32, String, String, String, Path<'static>, Path<'static>);
@@ -64,11 +64,19 @@ impl From<ListedJob> for JobListing {
Self {
id,
unit,
brings_unit_up: kind != STOP_JOB,
kind: job_kind(&kind),
}
}
}
fn job_kind(raw: &str) -> JobKind {
if raw == STOP_JOB {
JobKind::TakesDown
} else {
JobKind::BringsUp
}
}
pub struct Session {
channel: Channel,
pub peer_to_peer: bool,
@@ -169,7 +177,7 @@ impl Session {
Ok(listed.into_iter().map(JobListing::from).collect())
}
pub fn job_brings_unit_up(&self, job: &Path) -> Result<bool, Error> {
pub fn job_kind(&self, job: &Path) -> Result<JobKind, Error> {
let reply = self.call(
DESTINATION,
job,
@@ -178,7 +186,7 @@ impl Session {
(JOB_INTERFACE, "JobType"),
)?;
let kind: Variant<String> = reply.read1()?;
Ok(kind.0 != STOP_JOB)
Ok(job_kind(&kind.0))
}
pub fn fetch_unit(&self, name: &str) -> Result<FetchedUnit, Error> {
@@ -206,20 +214,23 @@ impl Session {
.and_then(|value| value.0.as_str())
.map(ToOwned::to_owned)
};
let after = properties
.get("After")
.and_then(|value| value.0.as_iter())
.map(|items| {
items
.filter_map(|item| item.as_str().map(ToOwned::to_owned))
.collect()
})
.unwrap_or_default();
let names = |property: &str| {
properties
.get(property)
.and_then(|value| value.0.as_iter())
.map(|items| {
items
.filter_map(|item| item.as_str().map(ToOwned::to_owned))
.collect()
})
.unwrap_or_default()
};
Ok(FetchedUnit {
facts: UnitFacts {
name: text("Id").unwrap_or_else(|| name.to_owned()),
description: text("Description").unwrap_or_default(),
after,
after: names("After"),
before: names("Before"),
},
activity: activity_from(&properties),
path,
@@ -305,5 +316,6 @@ fn activity_from(properties: &PropMap) -> Activity {
.map(ActiveState::parse),
inactive_exit: monotonic("InactiveExitTimestampMonotonic"),
active_enter: monotonic("ActiveEnterTimestampMonotonic"),
active_exit: monotonic("ActiveExitTimestampMonotonic"),
}
}
+67 -18
View File
@@ -29,6 +29,7 @@ const ROOT_SWITCH_MARK: char = '│';
const RULE: char = '─';
const RULE_STUB: &str = "──";
const KERNEL_ORIGIN_LABEL: &str = "kernel";
const SHUTDOWN_SUCCESSOR: &str = "systemd-shutdown";
const DURATION_WIDTH: u16 = 8;
const TIMELINE_LABEL_WIDTH: u16 = 28;
@@ -149,6 +150,12 @@ impl Widget for BootView<'_> {
}
}
struct Conclusion<'a> {
finished: &'static str,
took: Duration,
handed_to: &'a str,
}
struct Heights {
tree: u16,
timeline: u16,
@@ -236,28 +243,38 @@ impl BootView<'_> {
.finished_stages
.last()
.map_or(self.state.origin, |stage| stage.reached_at);
let current = if self.state.is_complete() {
let handed_to = self
.state
.handoff_unit
.as_deref()
.or(self.state.root.as_deref())
.unwrap_or("the console");
let conclusion = match self.state.manager_exited_at {
Some(exited_at) => Some(Conclusion {
finished: "shutdown",
took: exited_at.saturating_sub(self.state.origin),
handed_to: SHUTDOWN_SUCCESSOR,
}),
None => self.state.is_complete().then(|| Conclusion {
finished: "boot",
took: self.now.saturating_sub(self.state.origin),
handed_to: self
.state
.handoff_unit
.as_deref()
.or(self.state.root.as_deref())
.unwrap_or("the console"),
}),
};
let current = if let Some(conclusion) = conclusion {
self.rule_line(
width,
vec![
Span::styled(format!("{RULE_STUB} "), Style::new().fg(self.palette.muted)),
Span::styled(
format!(
"{BEAD} boot finished in {}",
ELAPSED.unsigned_duration_to_string(
&self.now.saturating_sub(self.state.origin)
)
"{BEAD} {} finished in {}",
conclusion.finished,
ELAPSED.unsigned_duration_to_string(&conclusion.took)
),
Style::new().fg(self.palette.done).bold(),
),
Span::styled(
format!(" · handing over to {handed_to} "),
format!(" · handing over to {} ", conclusion.handed_to),
Style::new().fg(self.palette.text),
),
],
@@ -715,7 +732,7 @@ mod tests {
use ratatui::{Terminal, backend::TestBackend};
use super::*;
use crate::model::{ActiveState, Activity, JobResult, Phase, UnitFacts};
use crate::model::{ActiveState, Activity, JobKind, JobResult, Phase, UnitFacts};
const MS: Duration = Duration::from_millis(1);
@@ -724,6 +741,7 @@ mod tests {
name: name.to_owned(),
description: String::new(),
after: after.iter().map(ToString::to_string).collect(),
before: Vec::new(),
}
}
@@ -759,6 +777,7 @@ mod tests {
state: Some(ActiveState::Activating),
inactive_exit: Some(since),
active_enter: None,
active_exit: None,
}
}
@@ -792,7 +811,7 @@ mod tests {
.for_each(|((unit, activity), id)| {
let name = unit.name.clone();
state.track_unit(unit, activity);
state.queue_job(id, &name, 1000 * MS);
state.queue_job(id, &name, JobKind::BringsUp, 1000 * MS);
});
state.finish_job(6, JobResult::Done, 4000 * MS);
state.finish_job(7, JobResult::Failed, 5000 * MS);
@@ -866,12 +885,12 @@ mod tests {
let mut state = BootState::new(Phase::Initrd);
state.set_root("initrd.target".to_owned());
state.track_unit(facts("initrd.target", &[]), Activity::default());
state.queue_job(1, "initrd.target", Duration::ZERO);
state.queue_job(1, "initrd.target", JobKind::BringsUp, Duration::ZERO);
state.finish_job(1, JobResult::Done, 6000 * MS);
state.switch_root(7200 * MS);
state.set_root("graphical.target".to_owned());
state.track_unit(facts("graphical.target", &[]), Activity::default());
state.queue_job(2, "graphical.target", 7300 * MS);
state.queue_job(2, "graphical.target", JobKind::BringsUp, 7300 * MS);
let lines = render(&state, 17_300 * MS, 110, 24);
let screen = lines.join("\n");
assert!(lines[0].ends_with("17.3s"), "{screen}");
@@ -905,7 +924,7 @@ mod tests {
let mut state = BootState::new(Phase::Host);
state.set_root("graphical.target".to_owned());
state.track_unit(facts("graphical.target", &[]), Activity::default());
state.queue_job(1, "graphical.target", Duration::ZERO);
state.queue_job(1, "graphical.target", JobKind::BringsUp, Duration::ZERO);
state.finish_job(1, JobResult::Done, 9000 * MS);
let lines = render(&state, 9500 * MS, 110, 24);
assert!(
@@ -917,13 +936,43 @@ mod tests {
);
}
#[test]
fn shutdown_in_progress_names_its_stage() {
let mut state = BootState::new(Phase::Shutdown);
state.origin = 20_000 * MS;
state.set_root("poweroff.target".to_owned());
state.track_unit(facts("poweroff.target", &[]), Activity::default());
state.queue_job(1, "poweroff.target", JobKind::BringsUp, 20_000 * MS);
let lines = render(&state, 21_500 * MS, 110, 24);
assert!(
lines[2].starts_with("── shutdown ─") && lines[2].ends_with(" 1.5s ──"),
"{}",
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[2].starts_with(
"── ■ shutdown finished in 4.2s · handing over to systemd-shutdown ──"
),
"{}",
lines.join("\n")
);
}
#[test]
fn overflowing_trees_are_cut_with_a_count() {
let mut state = BootState::new(Phase::Host);
(0..30).for_each(|id| {
let name = format!("unit{id:02}.service");
state.track_unit(facts(&name, &[]), Activity::default());
state.queue_job(id, &name, Duration::ZERO);
state.queue_job(id, &name, JobKind::BringsUp, Duration::ZERO);
});
let lines = render(&state, 1000 * MS, 110, 20);
assert!(