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