From 097caf81a2402db902e59d140c206daf0b8969a5 Mon Sep 17 00:00:00 2001 From: Willem Vanhulle Date: Sun, 11 Oct 2026 12:38:29 +0200 Subject: [PATCH] boot-tree: live systemd boot dependency tree on a dedicated VT --- .gitignore | 3 + Cargo.lock | 1878 ++++++++++++++++++++++++++++++++++++++++++ Cargo.toml | 24 + demo/demo-units.nu | 33 + demo/host.nix | 56 ++ demo/interactive.nix | 18 + demo/test.nix | 41 + demo/units.nix | 32 + demo/user-units.nix | 55 ++ flake.lock | 64 ++ flake.nix | 114 +++ nixos-module.nix | 126 +++ rust-toolchain.toml | 3 + rustfmt.toml | 10 + src/clock.rs | 15 + src/console.rs | 59 ++ src/error.rs | 55 ++ src/feed.rs | 254 ++++++ src/main.rs | 52 ++ src/model.rs | 860 +++++++++++++++++++ src/run.rs | 171 ++++ src/sysroot.rs | 35 + src/systemd.rs | 282 +++++++ src/view.rs | 577 +++++++++++++ 24 files changed, 4817 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100755 demo/demo-units.nu create mode 100644 demo/host.nix create mode 100644 demo/interactive.nix create mode 100644 demo/test.nix create mode 100644 demo/units.nix create mode 100644 demo/user-units.nix create mode 100644 flake.lock create mode 100644 flake.nix create mode 100644 nixos-module.nix create mode 100644 rust-toolchain.toml create mode 100644 rustfmt.toml create mode 100644 src/clock.rs create mode 100644 src/console.rs create mode 100644 src/error.rs create mode 100644 src/feed.rs create mode 100644 src/main.rs create mode 100644 src/model.rs create mode 100644 src/run.rs create mode 100644 src/sysroot.rs create mode 100644 src/systemd.rs create mode 100644 src/view.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3dec543 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +target +result* +*.qcow2 diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..3d72cf8 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1878 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "approx" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +dependencies = [ + "num-traits", +] + +[[package]] +name = "atomic" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bit-set" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "boot-tree" +version = "0.1.0" +dependencies = [ + "clap", + "crossterm", + "dbus", + "ratatui", + "rustix", + "signal-hook 0.4.5", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "by_address" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cc" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50a649af8a827553c29fb0cb4bd4a6f1a0dd695bd3232b9bc98bd9c8a3ffbb8b" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.7", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "compact_str" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + +[[package]] +name = "crossterm" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" +dependencies = [ + "bitflags 2.13.2", + "crossterm_winapi", + "derive_more", + "document-features", + "mio", + "parking_lot", + "rustix", + "signal-hook 0.3.18", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "csscolorparser" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb2a7d3066da2de787b7f032c736763eb7ae5d355f81a68bab2675a96008b0bf" +dependencies = [ + "lab", + "phf", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.7", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.7", +] + +[[package]] +name = "dbus" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e" +dependencies = [ + "libc", + "libdbus-sys", + "windows-sys", +] + +[[package]] +name = "deltae" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5729f5117e208430e437df2f4843f5e5952997175992d1414f94c57d61e270b4" + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "fancy-regex" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b95f7c0680e4142284cf8b22c14a476e87d61b004a3a0861872b32ef7ead40a2" +dependencies = [ + "bit-set", + "regex", +] + +[[package]] +name = "filedescriptor" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" +dependencies = [ + "libc", + "thiserror 1.0.69", + "winapi", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "finl_unicode" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bb028c8b4148c9ee0cca68fcd9add6044e81d3619f48577ddf13a263d047a2" + +[[package]] +name = "fixedbitset" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "indoc" +version = "2.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1" +dependencies = [ + "rustversion", +] + +[[package]] +name = "instability" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20" +dependencies = [ + "darling", + "indoc", + "proc-macro2", + "quote", + "syn 3.0.7", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "kasuari" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde5057d6143cc94e861d90f591b9303d6716c6b9602309150bd068853c10899" +dependencies = [ + "hashbrown 0.16.1", + "portable-atomic", + "thiserror 2.0.21", +] + +[[package]] +name = "lab" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf36173d4167ed999940f804952e6b08197cae5ad5d572eb4db150ce8ad5d58f" + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "libdbus-sys" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043" +dependencies = [ + "pkg-config", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "line-clipping" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e752191d037c44ad111a8caa762921926658402f01cc1253f7bef2020ece4f5e" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litrs" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" +dependencies = [ + "hashbrown 0.17.1", +] + +[[package]] +name = "mac_address" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3d0581a75c45969c63afd2bb87b1d8b25cfcc556c7a918cf9bb13b0fe8d2381" +dependencies = [ + "nix 0.31.3", + "windows-sys", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmem" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a64a92489e2744ce060c349162be1c5f33c6969234104dbd99ddb5feb08b8c15" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys", +] + +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", + "memoffset", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_threads" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9" +dependencies = [ + "libc", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "ordered-float" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bb71e1b3fa6ca1c61f383464aaf2bb0e2f8e772a1f01d486832464de363b951" +dependencies = [ + "num-traits", +] + +[[package]] +name = "palette" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddeed8580d347d2abf3dcf06a5f0b3dc020258338526b277847cd4248a70fc64" +dependencies = [ + "approx", + "libm", + "palette_derive", + "palette_math", +] + +[[package]] +name = "palette_derive" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88537020289b719d81be994ccf1bbf4990f477e2f69ee52fe3e45f43a02e56be" +dependencies = [ + "by_address", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "palette_math" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e6eb142958d64335fb0e345c5b9ead2ecd6fc438c307e9d7d3c4fd428dbaf12" +dependencies = [ + "libm", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pest" +version = "2.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b568374ba38b33a6c627141f891faf16902b08d2db26b8ede1bcb0a15b1919fa" +dependencies = [ + "memchr", + "psm", + "stacker", + "ucd-trie", +] + +[[package]] +name = "pest_derive" +version = "2.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66e184b924cebaaff20ab2256ca52f12332d528a39aa76553b5d96f92aacf7f" +dependencies = [ + "pest", + "pest_generator", +] + +[[package]] +name = "pest_generator" +version = "2.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a87478d267e4de54a626af9754f2f0f58e927aac6ed0575fe89bc05ad6851694" +dependencies = [ + "pest", + "pest_meta", + "proc-macro2", + "quote", + "syn 3.0.7", +] + +[[package]] +name = "pest_meta" +version = "2.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f986f248b4241ac359b831f6139aaa34e03b08a37b6caf7e201a33f95c869e1" +dependencies = [ + "pest", +] + +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros", + "phf_shared", +] + +[[package]] +name = "phf_codegen" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared", + "rand", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "psm" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "200b9ff220857e53e184257720a14553b2f4aa02577d2ed9842d45d4b9654810" +dependencies = [ + "cc", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "ratatui" +version = "0.30.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3274ba0a2c5e1bcad2a2005d20f4dc59dad26b2eb0940fb094500dba4099d57d" +dependencies = [ + "instability", + "ratatui-core", + "ratatui-crossterm", + "ratatui-macros", + "ratatui-termina", + "ratatui-termwiz", + "ratatui-widgets", + "serde", +] + +[[package]] +name = "ratatui-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c" +dependencies = [ + "bitflags 2.13.2", + "compact_str", + "critical-section", + "hashbrown 0.17.1", + "itertools", + "kasuari", + "lru", + "palette", + "serde", + "strum", + "thiserror 2.0.21", + "unicode-segmentation", + "unicode-truncate", + "unicode-width", +] + +[[package]] +name = "ratatui-crossterm" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "567584a3b0e6a8203c23de40b4861497266725eb5363dbfd18a1edd603cca9f0" +dependencies = [ + "cfg-if", + "crossterm", + "instability", + "ratatui-core", +] + +[[package]] +name = "ratatui-macros" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed7dc68daa7498a43e4d68e0eb078427e10c38fbcfbb1e42d955f1fa2140d814" +dependencies = [ + "ratatui-core", + "ratatui-widgets", +] + +[[package]] +name = "ratatui-termina" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0bf912d9e66f057a759d92e386a280ea886b352ab757d6ac4d653c7ed2c43c2" +dependencies = [ + "instability", + "ratatui-core", + "termina", +] + +[[package]] +name = "ratatui-termwiz" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf03e0380b7744054d6cb74224fe3adf062a029754933f575ca1e3b4c2ce977" +dependencies = [ + "ratatui-core", + "termwiz", +] + +[[package]] +name = "ratatui-widgets" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66e3d19bcc9130ca376277d93b60767ff121ace3be06f5f95f81dd68956407d1" +dependencies = [ + "bitflags 2.13.2", + "hashbrown 0.17.1", + "indoc", + "instability", + "itertools", + "line-clipping", + "ratatui-core", + "serde", + "strum", + "time", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.7", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b29ffa27d3d59a049bb328258de100f8012848d1b08d444e08bbc02ac468435e" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook 0.3.18", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d62a2e0561533f2ca2561d0cf27fd9fedb640a1bf2616ff5d5c80d99017faadc" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "termina" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9048a889effe34a5cddee0af7f53285198b16dca3be510858d38dfdb3e62a04e" +dependencies = [ + "bitflags 2.13.2", + "parking_lot", + "rustix", + "signal-hook 0.3.18", + "windows-sys", +] + +[[package]] +name = "terminfo" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ea810f0692f9f51b382fff5893887bb4580f5fa246fde546e0b13e7fcee662" +dependencies = [ + "fnv", + "nom", + "phf", + "phf_codegen", +] + +[[package]] +name = "termios" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411c5bf740737c7918b8b1fe232dca4dc9f8e754b8ad5e20966814001ed0ac6b" +dependencies = [ + "libc", +] + +[[package]] +name = "termwiz" +version = "0.23.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4676b37242ccbd1aabf56edb093a4827dc49086c0ffd764a5705899e0f35f8f7" +dependencies = [ + "anyhow", + "base64", + "bitflags 2.13.2", + "fancy-regex", + "filedescriptor", + "finl_unicode", + "fixedbitset", + "hex", + "lazy_static", + "libc", + "log", + "memmem", + "nix 0.29.0", + "num-derive", + "num-traits", + "ordered-float", + "pest", + "pest_derive", + "phf", + "sha2", + "signal-hook 0.3.18", + "siphasher", + "terminfo", + "termios", + "thiserror 1.0.69", + "ucd-trie", + "unicode-segmentation", + "vtparse", + "wezterm-bidi", + "wezterm-blob-leases", + "wezterm-color-types", + "wezterm-dynamic", + "wezterm-input-types", + "winapi", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.7", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "libc", + "num-conv", + "num_threads", + "powerfmt", + "serde_core", + "time-core", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "ucd-trie" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-truncate" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5" +dependencies = [ + "itertools", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uuid" +version = "1.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" +dependencies = [ + "atomic", + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vtparse" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9b2acfb050df409c972a37d3b8e08cdea3bddb0c09db9d53137e504cfabed0" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.7", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wezterm-bidi" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0a6e355560527dd2d1cf7890652f4f09bb3433b6aadade4c9b5ed76de5f3ec" +dependencies = [ + "log", + "wezterm-dynamic", +] + +[[package]] +name = "wezterm-blob-leases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "692daff6d93d94e29e4114544ef6d5c942a7ed998b37abdc19b17136ea428eb7" +dependencies = [ + "getrandom 0.3.4", + "mac_address", + "sha2", + "thiserror 1.0.69", + "uuid", +] + +[[package]] +name = "wezterm-color-types" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7de81ef35c9010270d63772bebef2f2d6d1f2d20a983d27505ac850b8c4b4296" +dependencies = [ + "csscolorparser", + "deltae", + "lazy_static", + "wezterm-dynamic", +] + +[[package]] +name = "wezterm-dynamic" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f2ab60e120fd6eaa68d9567f3226e876684639d22a4219b313ff69ec0ccd5ac" +dependencies = [ + "log", + "ordered-float", + "strsim", + "thiserror 1.0.69", + "wezterm-dynamic-derive", +] + +[[package]] +name = "wezterm-dynamic-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c0cf2d539c645b448eaffec9ec494b8b19bd5077d9e58cb1ae7efece8d575b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "wezterm-input-types" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7012add459f951456ec9d6c7e6fc340b1ce15d6fc9629f8c42853412c029e57e" +dependencies = [ + "bitflags 1.3.2", + "euclid", + "lazy_static", + "serde", + "wezterm-dynamic", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..4cacfdc --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,24 @@ +[package] +edition = "2024" +name = "boot-tree" +version = "0.1.0" + +[lints.clippy] +absolute_paths = "warn" +pedantic = { priority = -1, level = "warn" } +cast_possible_truncation = "allow" +cast_precision_loss = "allow" +cast_sign_loss = "allow" +needless_for_each = "allow" + +[dependencies] +clap = { version = "4.5", features = ["derive"] } +crossterm = "0.29" +dbus = "0.9" +ratatui = "0.30" +rustix = { version = "1", features = ["fs", "process", "stdio", "system", "termios", "time"] } +signal-hook = "0.4" + +[profile.release] +lto = "thin" +strip = true diff --git a/demo/demo-units.nu b/demo/demo-units.nu new file mode 100755 index 0000000..c5541d2 --- /dev/null +++ b/demo/demo-units.nu @@ -0,0 +1,33 @@ +#!/usr/bin/env nu + +def user-unit-dir []: nothing -> path { + $env.XDG_RUNTIME_DIR | path join systemd user +} + +def unit-names [units: path]: nothing -> list { + ls $units | get name | path basename +} + +def install-units [units: path] { + let target_dir = user-unit-dir + mkdir $target_dir + unit-names $units | each {|name| ^ln -sfn ($units | path join $name) ($target_dir | path join $name) } | ignore + ^systemctl --user daemon-reload +} + +def "main start" [--units: path, --target: string] { + install-units $units + ^systemctl --user stop ...(unit-names $units) + ^systemctl --user start --no-block $target + print $"started ($target); watch it with: boot-tree --user --target ($target) --hold-ms 3000" +} + +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 + ^systemctl --user daemon-reload +} + +def main [--units: path, --target: string] { + print "usage: boot-tree-demo-units (start | remove)" +} diff --git a/demo/host.nix b/demo/host.nix new file mode 100644 index 0000000..c3f3ca0 --- /dev/null +++ b/demo/host.nix @@ -0,0 +1,56 @@ +{ + demoUnits, + lib, + pkgs, + ... +}: +let + demoService = spec: { + after = map (dependency: "${dependency}.service") (spec.after or [ ]); + wantedBy = [ "multi-user.target" ]; + serviceConfig = { + Type = "oneshot"; + ExecStart = [ + "${pkgs.coreutils}/bin/sleep ${spec.seconds}" + ] + ++ lib.optional (spec.fails or false) "${pkgs.coreutils}/bin/false"; + }; + }; +in +{ + networking.hostName = "boot-tree-demo"; + system.stateVersion = "26.05"; + + boot.initrd.systemd = { + enable = true; + services.demo-initrd-probe = { + description = "boot-tree demo: slow initrd step"; + wantedBy = [ "initrd.target" ]; + before = [ "initrd.target" ]; + unitConfig.DefaultDependencies = false; + serviceConfig = { + Type = "oneshot"; + ExecStart = "/bin/sleep ${demoUnits.initrdProbeSeconds}"; + }; + }; + }; + + services.boot-tree = { + enable = true; + consoleFont = "ter-v20n"; + }; + + systemd.services = lib.mapAttrs (_: demoService) demoUnits.services // { + display-manager.after = [ "multi-user.target" ]; + }; + + services.greetd = { + enable = true; + settings.default_session.command = "${pkgs.greetd}/bin/agreety --cmd ${pkgs.bashInteractive}/bin/bash"; + }; + + users.users.demo = { + isNormalUser = true; + password = "demo"; + }; +} diff --git a/demo/interactive.nix b/demo/interactive.nix new file mode 100644 index 0000000..f0591f1 --- /dev/null +++ b/demo/interactive.nix @@ -0,0 +1,18 @@ +{ + boot.loader.grub.enable = false; + + services.getty.autologinUser = "root"; fileSystems."/" = { + device = "/dev/disk/by-label/nixos"; + fsType = "ext4"; + }; + + virtualisation.vmVariant.virtualisation = { + memorySize = 2048; + cores = 2; + graphics = true; + qemu.options = [ + "-vga none" + "-device virtio-vga,xres=1920,yres=1080" + ]; + }; +} diff --git a/demo/test.nix b/demo/test.nix new file mode 100644 index 0000000..cd19c1d --- /dev/null +++ b/demo/test.nix @@ -0,0 +1,41 @@ +{ demoHost }: +{ + name = "boot-tree"; + enableOCR = true; + + nodes.machine = { + imports = [ demoHost ]; + virtualisation = { + memorySize = 2048; + qemu.options = [ + "-vga none" + "-device virtio-vga,xres=1280,yres=800" + ]; + }; + }; + + testScript = '' + machine.start() + + machine.wait_for_text("initrd") + machine.screenshot("initrd") + + machine.wait_for_text("demo-slow") + machine.screenshot("stage-2") + + machine.wait_for_unit("greetd.service") + machine.wait_until_succeeds("systemctl show -p ActiveState --value boot-tree | grep -qx inactive") + + journal = machine.succeed("journalctl -b -u boot-tree -o cat") + print(journal) + watched = [line for line in journal.splitlines() if line.startswith("boot-tree: watching")] + assert any(" in initrd " in line for line in watched), "never ran in the initrd" + assert any(" in stage 2 " in line for line in watched), "never reconnected after the root switch" + pids = {line.split(" as pid ")[1].split()[0] for line in watched} + assert len(pids) == 1, f"the initrd process did not survive the root switch: {pids}" + assert "handing the console over" in journal, "never handed the console over" + + machine.succeed("test \"$(systemctl show -p Result --value boot-tree)\" = success") + machine.screenshot("handed-over") + ''; +} diff --git a/demo/units.nix b/demo/units.nix new file mode 100644 index 0000000..bfd7f74 --- /dev/null +++ b/demo/units.nix @@ -0,0 +1,32 @@ +{ + target = "boot-tree-demo"; + initrdProbeSeconds = "6"; + services = { + demo-disk.seconds = "2"; + demo-db = { + seconds = "3"; + after = [ "demo-disk" ]; + }; + demo-cache.seconds = "1.5"; + demo-web = { + seconds = "2"; + after = [ + "demo-db" + "demo-cache" + ]; + }; + demo-fetch.seconds = "4"; + demo-flaky = { + seconds = "1"; + fails = true; + }; + demo-slow.seconds = "8"; + demo-report = { + seconds = "1"; + after = [ + "demo-web" + "demo-fetch" + ]; + }; + }; +} diff --git a/demo/user-units.nix b/demo/user-units.nix new file mode 100644 index 0000000..90aa10d --- /dev/null +++ b/demo/user-units.nix @@ -0,0 +1,55 @@ +{ + demoUnits, + lib, + coreutils, + linkFarm, + nushell, + writeShellApplication, + writeText, +}: +let + toUnitFile = lib.generators.toINI { listsAsDuplicateKeys = true; }; + + serviceFile = + name: spec: + writeText "${name}.service" (toUnitFile { + Unit = { + Description = "boot-tree demo: ${name}"; + After = map (dependency: "${dependency}.service") (spec.after or [ ]); + }; + Service = { + Type = "oneshot"; + ExecStart = [ + "${coreutils}/bin/sleep ${spec.seconds}" + ] + ++ lib.optional (spec.fails or false) "${coreutils}/bin/false"; + }; + }); + + serviceNames = map (name: "${name}.service") (lib.attrNames demoUnits.services); + + targetFile = writeText "${demoUnits.target}.target" (toUnitFile { + Unit = { + Description = "boot-tree demo target"; + Wants = serviceNames; + After = serviceNames; + }; + }); + + units = linkFarm "boot-tree-demo-units" ( + lib.mapAttrsToList (name: spec: { + name = "${name}.service"; + path = serviceFile name spec; + }) demoUnits.services + ++ [ + { + name = "${demoUnits.target}.target"; + path = targetFile; + } + ] + ); +in +writeShellApplication { + name = "boot-tree-demo-units"; + text = ''exec ${lib.getExe nushell} ${./demo-units.nu} "$@" --units ${units} --target ${demoUnits.target}.target''; +} diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..5701449 --- /dev/null +++ b/flake.lock @@ -0,0 +1,64 @@ +{ + "nodes": { + "crane": { + "locked": { + "lastModified": 1790899423, + "narHash": "sha256-THGtz65UGJU+sonZidRboyCMk+9DclpMF7pwL4uDV4M=", + "owner": "ipetkov", + "repo": "crane", + "rev": "47b6b27ed9a3a9181415e4367d0c30ab2a0e0250", + "type": "github" + }, + "original": { + "owner": "ipetkov", + "repo": "crane", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1790340521, + "narHash": "sha256-cRrWlIjVRJ6BHDr9caUdXsZ3owzWIKYHpNmGPHBInIU=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "f5c082a40f7571c266e74e80ae2e68aadd8a9fc7", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "crane": "crane", + "nixpkgs": "nixpkgs", + "rust-overlay": "rust-overlay" + } + }, + "rust-overlay": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1791707771, + "narHash": "sha256-w3m8HtAVCfGTHw+gcCTAy7jFHSdGbokm8NngbeFrkek=", + "owner": "oxalica", + "repo": "rust-overlay", + "rev": "c1cfa7a2c809d364ac1a7e9b3ec418afa3f19793", + "type": "github" + }, + "original": { + "owner": "oxalica", + "repo": "rust-overlay", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..a67f948 --- /dev/null +++ b/flake.nix @@ -0,0 +1,114 @@ +{ + description = "boot-tree — live dependency tree of systemd jobs on the boot console"; + + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; + crane.url = "github:ipetkov/crane"; + rust-overlay = { + url = "github:oxalica/rust-overlay"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + }; + + outputs = + { + self, + nixpkgs, + crane, + rust-overlay, + }: + let + inherit (nixpkgs) lib; + + forEachSystem = + f: + lib.genAttrs [ "x86_64-linux" "aarch64-linux" ] ( + system: + f rec { + inherit system; + pkgs = import nixpkgs { + inherit system; + overlays = [ (import rust-overlay) ]; + }; + craneLib = (crane.mkLib pkgs).overrideToolchain ( + p: p.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml + ); + } + ); + + buildInputsFor = pkgs: { + nativeBuildInputs = [ pkgs.pkg-config ]; + buildInputs = [ pkgs.dbus ]; + }; + + demoUnits = import ./demo/units.nix; + + demoHost = { + imports = [ + self.nixosModules.default + ./demo/host.nix + ]; + _module.args = { inherit demoUnits; }; + }; + + demoSystem = + system: + lib.nixosSystem { + inherit system; + modules = [ + demoHost + ./demo/interactive.nix + ]; + }; + in + { + packages = forEachSystem ( + { pkgs, craneLib, ... }: + { + default = craneLib.buildPackage { + inherit (buildInputsFor pkgs) nativeBuildInputs buildInputs; + src = craneLib.cleanCargoSource ./.; + strictDeps = true; + meta.mainProgram = "boot-tree"; + meta.platforms = lib.platforms.linux; + }; + demo-units = pkgs.callPackage ./demo/user-units.nix { inherit demoUnits; }; + } + ); + + nixosModules.default = import ./nixos-module.nix { inherit self; }; + + nixosConfigurations.demo = demoSystem "x86_64-linux"; + + apps = forEachSystem ( + { system, ... }: + { + vm = { + type = "app"; + program = lib.getExe (demoSystem system).config.system.build.vm; + }; + demo-units = { + type = "app"; + program = lib.getExe self.packages.${system}.demo-units; + }; + } + ); + + checks = forEachSystem ( + { pkgs, system, ... }: + { + package = self.packages.${system}.default; + boot = pkgs.testers.runNixOSTest (import ./demo/test.nix { inherit demoHost; }); + } + ); + + devShells = forEachSystem ( + { pkgs, craneLib, ... }: + { + default = craneLib.devShell { + packages = with buildInputsFor pkgs; nativeBuildInputs ++ buildInputs; + }; + } + ); + }; +} diff --git a/nixos-module.nix b/nixos-module.nix new file mode 100644 index 0000000..2763556 --- /dev/null +++ b/nixos-module.nix @@ -0,0 +1,126 @@ +{ self }: +{ + config, + lib, + pkgs, + ... +}: +let + cfg = config.services.boot-tree; + + unit = { + description = "Live dependency tree of boot jobs on ${cfg.tty}"; + wantedBy = [ "sysinit.target" ]; + after = [ "systemd-vconsole-setup.service" ]; + before = [ + "display-manager.service" + "shutdown.target" + ]; + conflicts = [ "shutdown.target" ]; + unitConfig = { + DefaultDependencies = false; + IgnoreOnIsolate = true; + }; + serviceConfig = { + Type = "simple"; + ExecStart = "@${lib.getExe cfg.package} @boot-tree --hold-ms ${toString cfg.holdMs}"; + StandardInput = "tty"; + StandardOutput = "tty"; + StandardError = "journal"; + TTYPath = cfg.tty; + TTYReset = true; + TTYVTDisallocate = false; + }; + }; +in +{ + options.services.boot-tree = { + enable = lib.mkEnableOption '' + a live dependency tree of systemd jobs on the boot console. It starts in + the systemd initrd, survives the switch to the real root, and hands the + console over once the display manager starts or the default target is + reached + ''; + + package = lib.mkOption { + type = lib.types.package; + default = self.packages.${pkgs.stdenv.hostPlatform.system}.default; + defaultText = lib.literalExpression "boot-tree.packages.\${system}.default"; + description = "The boot-tree package."; + }; + + tty = lib.mkOption { + type = lib.types.str; + default = "/dev/tty12"; + description = '' + Virtual terminal the tree is drawn on. boot-tree switches to it while + it runs, so gettys, greeters and kernel output on other terminals + cannot draw over the tree, and switches back to the previously active + terminal when it hands the console over. + ''; + }; + + holdMs = lib.mkOption { + type = lib.types.ints.unsigned; + default = 0; + description = "Milliseconds the final frame stays on screen before the console is handed over."; + }; + + quietConsole = lib.mkOption { + type = lib.types.bool; + default = true; + description = '' + Silence kernel, udev and systemd status output on the console so it + does not draw over the tree, and load a large Terminus console font in + the initrd. + ''; + }; + + consoleFont = lib.mkOption { + type = lib.types.str; + default = "ter-v32n"; + example = "ter-v20n"; + description = "Terminus console font loaded when {option}`services.boot-tree.quietConsole` is set."; + }; + }; + + config = lib.mkIf cfg.enable ( + lib.mkMerge [ + { + assertions = [ + { + assertion = config.boot.initrd.systemd.enable; + message = "services.boot-tree needs boot.initrd.systemd.enable to start before the root switch."; + } + ]; + + environment.systemPackages = [ cfg.package ]; + + systemd.services.boot-tree = unit; + + boot.initrd.systemd = { + services.boot-tree = unit; + storePaths = [ (lib.getExe cfg.package) ]; + }; + } + + (lib.mkIf cfg.quietConsole { + boot = { + consoleLogLevel = lib.mkDefault 3; + kernelParams = [ + "quiet" + "systemd.show_status=error" + "rd.systemd.show_status=error" + "udev.log_level=3" + "rd.udev.log_level=3" + ]; + }; + + console = { + earlySetup = true; + font = lib.mkDefault "${pkgs.terminus_font}/share/consolefonts/${cfg.consoleFont}.psf.gz"; + }; + }) + ] + ); +} diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..fbf1afb --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "nightly-2026-07-19" +components = ["rust-src", "rustfmt", "clippy", "rust-analyzer"] diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..2ca85e7 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,10 @@ +edition = "2024" +format_code_in_doc_comments = true +format_strings = true +group_imports = "StdExternalCrate" +imports_granularity = "Crate" +normalize_comments = true +normalize_doc_attributes = true +unstable_features = true +use_field_init_shorthand = true +wrap_comments = true diff --git a/src/clock.rs b/src/clock.rs new file mode 100644 index 0000000..fa8ef44 --- /dev/null +++ b/src/clock.rs @@ -0,0 +1,15 @@ +use rustix::{ + system::uname, + time::{ClockId, clock_gettime}, +}; + +use crate::model::Micros; + +pub fn monotonic_now() -> Micros { + let now = clock_gettime(ClockId::Monotonic); + now.tv_sec as Micros * 1_000_000 + now.tv_nsec as Micros / 1_000 +} + +pub fn host_name() -> String { + uname().nodename().to_string_lossy().into_owned() +} diff --git a/src/console.rs b/src/console.rs new file mode 100644 index 0000000..76b913d --- /dev/null +++ b/src/console.rs @@ -0,0 +1,59 @@ +use rustix::{ + io::Errno, + ioctl::{Getter, IntegerSetter, Opcode, ioctl}, + stdio::stdin, + termios::ttyname, +}; + +const VT_GETSTATE: Opcode = 0x5603; +const VT_ACTIVATE: Opcode = 0x5606; +const VT_WAITACTIVE: Opcode = 0x5607; +const VIRTUAL_TERMINAL_PREFIX: &str = "/dev/tty"; + +#[repr(C)] +struct VtState { + active: u16, + _signal: u16, + _state: u16, +} + +pub struct ForegroundVt { + previous: u16, +} + +impl ForegroundVt { + pub fn take() -> Option { + let own = own_vt_number()?; + let previous = active_vt().ok()?; + if previous != own { + activate(own).ok()?; + } + Some(Self { previous }) + } + + pub fn give_back(self) { + let _ = activate(self.previous); + } +} + +fn own_vt_number() -> Option { + let name = ttyname(stdin(), Vec::new()).ok()?; + name.to_str() + .ok()? + .strip_prefix(VIRTUAL_TERMINAL_PREFIX)? + .parse() + .ok() + .filter(|number| *number > 0) +} + +fn active_vt() -> Result { + let state: VtState = unsafe { ioctl(stdin(), Getter::::new()) }?; + Ok(state.active) +} + +fn activate(number: u16) -> Result<(), Errno> { + let number = usize::from(number); + unsafe { ioctl(stdin(), IntegerSetter::::new_usize(number)) }?; + unsafe { ioctl(stdin(), IntegerSetter::::new_usize(number)) }?; + Ok(()) +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..23ad905 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,55 @@ +use std::{error, fmt, io}; + +use dbus::{Error as BusError, arg::TypeMismatchError}; +use rustix::io::Errno; + +#[derive(Debug)] +pub enum Error { + Bus(BusError), + Reply(TypeMismatchError), + MalformedCall, + Disconnected, + Console(io::Error), + RootSwitch(Errno), + ManagerUnreachable, +} + +impl fmt::Display for Error { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Bus(error) => write!(formatter, "systemd bus: {error}"), + Self::Reply(error) => write!(formatter, "unexpected reply from systemd: {error}"), + Self::MalformedCall => write!(formatter, "could not build a method call"), + Self::Disconnected => write!(formatter, "the service manager closed the connection"), + Self::Console(error) => write!(formatter, "console: {error}"), + Self::RootSwitch(error) => write!(formatter, "entering the new root: {error}"), + Self::ManagerUnreachable => write!(formatter, "the service manager did not come back"), + } + } +} + +impl error::Error for Error {} + +impl From for Error { + fn from(error: BusError) -> Self { + Self::Bus(error) + } +} + +impl From for Error { + fn from(error: TypeMismatchError) -> Self { + Self::Reply(error) + } +} + +impl From for Error { + fn from(error: io::Error) -> Self { + Self::Console(error) + } +} + +impl From for Error { + fn from(error: Errno) -> Self { + Self::RootSwitch(error) + } +} diff --git a/src/feed.rs b/src/feed.rs new file mode 100644 index 0000000..ae8050e --- /dev/null +++ b/src/feed.rs @@ -0,0 +1,254 @@ +use std::{ + collections::HashMap, + process, + sync::mpsc::Sender, + thread::{self, JoinHandle}, + time::{Duration, Instant}, +}; + +use dbus::Path; + +use crate::{ + clock::monotonic_now, + error::Error, + model::{Activity, HANDOFF_UNIT, HOST_MILESTONES, JobResult, Micros, UnitFacts}, + sysroot::{Sysroot, running_in_initrd}, + systemd::{Scope, Session, Signal, brings_unit_up}, +}; + +const RECEIVE_TIMEOUT: Duration = Duration::from_millis(100); +const RECONNECT_INTERVAL: Duration = Duration::from_millis(50); +const RECONNECT_PATIENCE: Duration = Duration::from_secs(60); +const SWITCH_ROOT_UNIT: &str = "initrd-switch-root.service"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum JobKind { + BringsUp, + Unknown, +} + +pub enum Update { + Root(String), + Handoff(String), + Origin(Micros), + Unit { + facts: UnitFacts, + activity: Activity, + }, + JobQueued { + id: u32, + unit: String, + at: Micros, + kind: JobKind, + }, + JobFinished { + id: u32, + result: JobResult, + at: Micros, + }, + Activity { + unit: String, + activity: Activity, + }, + RootSwitched { + at: Micros, + }, + Resubscribed, + Ended(Error), +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum OriginChoice { + FromManager, + Keep, +} + +pub struct FeedOptions { + pub scope: Scope, + pub target: Option, +} + +pub fn spawn(options: FeedOptions, sender: Sender) -> JoinHandle<()> { + thread::spawn(move || { + let ended = Feed::new(options, sender.clone()).run(); + let _ = sender.send(Update::Ended(ended)); + }) +} + +struct Feed { + options: FeedOptions, + sender: Sender, + unit_paths: HashMap, String>, + in_initrd: bool, + sysroot: Option, +} + +impl Feed { + fn new(options: FeedOptions, sender: Sender) -> Self { + Self { + in_initrd: options.scope == Scope::System && running_in_initrd(), + options, + sender, + unit_paths: HashMap::new(), + sysroot: None, + } + } + + fn send(&self, update: Update) { + let _ = self.sender.send(update); + } + + fn run(mut self) -> Error { + let mut session = match self.connect_patiently(OriginChoice::FromManager) { + Ok(session) => session, + Err(error) => return error, + }; + loop { + match session.receive(RECEIVE_TIMEOUT) { + Ok(signals) => signals + .into_iter() + .for_each(|signal| self.apply(&session, signal)), + Err(_) => match self.reconnect() { + Ok(reconnected) => session = reconnected, + Err(error) => return error, + }, + } + } + } + + fn connect(&mut self, origin: OriginChoice) -> Result { + let session = Session::open(self.options.scope)?; + session.subscribe()?; + let requested_root = match &self.options.target { + Some(target) => target.clone(), + None => session.default_target()?, + }; + if origin == OriginChoice::FromManager { + let boot_in_progress = session.boot_in_progress()?; + self.send(Update::Origin(if boot_in_progress { + 0 + } else { + monotonic_now() + })); + } + let root = self + .track(&session, &requested_root) + .unwrap_or(requested_root); + self.send(Update::Root(root.clone())); + if let Some(handoff) = self.track(&session, HANDOFF_UNIT) { + self.send(Update::Handoff(handoff)); + } + let jobs: Vec<_> = session + .list_jobs()? + .into_iter() + .filter(|job| brings_unit_up(&job.kind)) + .collect(); + jobs.iter() + .map(|job| job.unit.as_str()) + .chain(HOST_MILESTONES) + .for_each(|unit| { + self.track(&session, unit); + }); + let now = monotonic_now(); + jobs.into_iter().for_each(|job| { + self.send(Update::JobQueued { + id: job.id, + unit: job.unit, + at: now, + kind: JobKind::BringsUp, + }); + }); + eprintln!( + "boot-tree: watching {root} in {} as pid {} over {}", + if self.in_initrd { "initrd" } else { "stage 2" }, + process::id(), + if session.is_peer_to_peer() { + "the private socket" + } else { + "the bus" + }, + ); + Ok(session) + } + + fn reconnect(&mut self) -> Result { + match self.sysroot.take() { + Some(sysroot) => { + sysroot.enter()?; + self.in_initrd = false; + self.unit_paths.clear(); + self.send(Update::RootSwitched { + at: monotonic_now(), + }); + } + None => self.send(Update::Resubscribed), + } + self.connect_patiently(OriginChoice::Keep) + } + + fn connect_patiently(&mut self, origin: OriginChoice) -> Result { + let deadline = Instant::now() + RECONNECT_PATIENCE; + loop { + match self.connect(origin) { + Ok(session) => return Ok(session), + Err(_) if Instant::now() < deadline => thread::sleep(RECONNECT_INTERVAL), + Err(_) => return Err(Error::ManagerUnreachable), + } + } + } + + fn track(&mut self, session: &Session, unit: &str) -> Option { + if let Some(known) = self.unit_paths.values().find(|known| *known == unit) { + return Some(known.clone()); + } + let fetched = session.fetch_unit(unit).ok()?; + let canonical = fetched.facts.name.clone(); + if self.unit_paths.values().any(|known| *known == canonical) { + return Some(canonical); + } + self.unit_paths.insert(fetched.path, canonical.clone()); + self.send(Update::Unit { + facts: fetched.facts, + activity: fetched.activity, + }); + Some(canonical) + } + + fn apply(&mut self, session: &Session, signal: Signal) { + match signal { + Signal::JobNew { id, job, unit } => { + let kind = session.job_kind(&job); + if kind.as_deref().is_ok_and(|kind| !brings_unit_up(kind)) { + return; + } + let unit = self.track(session, &unit).unwrap_or(unit); + if self.in_initrd && unit == SWITCH_ROOT_UNIT { + self.sysroot = Sysroot::hold().ok(); + } + self.send(Update::JobQueued { + id, + unit, + at: monotonic_now(), + kind: if kind.is_ok() { + JobKind::BringsUp + } else { + JobKind::Unknown + }, + }); + } + Signal::JobRemoved { id, result } => self.send(Update::JobFinished { + id, + result, + at: monotonic_now(), + }), + Signal::UnitChanged { path, activity } => { + if let Some(unit) = self.unit_paths.get(&path) { + self.send(Update::Activity { + unit: unit.clone(), + activity, + }); + } + } + } + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..7742e51 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,52 @@ +mod clock; +mod console; +mod error; +mod feed; +mod model; +mod run; +mod sysroot; +mod systemd; +mod view; + +use std::{process::ExitCode, time::Duration}; + +use clap::Parser; + +use crate::{ + run::{Options, run}, + systemd::Scope, +}; + +#[derive(Parser)] +#[command(about = "Live dependency tree of systemd jobs while the system boots")] +struct Cli { + #[arg(long, help = "Watch the user service manager instead of PID 1")] + user: bool, + #[arg( + long, + help = "Root unit of the tree; defaults to the manager's default target" + )] + target: Option, + #[arg( + long, + default_value_t = 0, + help = "Milliseconds to keep the final frame on screen" + )] + hold_ms: u64, +} + +fn main() -> ExitCode { + let cli = Cli::parse(); + let options = Options { + scope: if cli.user { Scope::User } else { Scope::System }, + target: cli.target, + hold: Duration::from_millis(cli.hold_ms), + }; + match run(options) { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("boot-tree: {error}"); + ExitCode::FAILURE + } + } +} diff --git a/src/model.rs b/src/model.rs new file mode 100644 index 0000000..93f6dc2 --- /dev/null +++ b/src/model.rs @@ -0,0 +1,860 @@ +use std::collections::{HashMap, HashSet}; + +pub type Micros = u64; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Phase { + Initrd, + Host, + User, +} + +impl Phase { + pub fn label(self) -> &'static str { + match self { + Self::Initrd => "initrd", + Self::Host => "stage 2", + Self::User => "user", + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ActiveState { + Inactive, + Activating, + Active, + Deactivating, + Reloading, + Failed, +} + +impl ActiveState { + pub fn parse(raw: &str) -> Self { + match raw { + "activating" => Self::Activating, + "active" => Self::Active, + "deactivating" => Self::Deactivating, + "reloading" => Self::Reloading, + "failed" => Self::Failed, + _ => Self::Inactive, + } + } + + fn is_transitioning(self) -> bool { + matches!( + self, + Self::Activating | Self::Deactivating | Self::Reloading + ) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum JobResult { + Done, + Skipped, + Canceled, + Failed, + Timeout, + Dependency, +} + +impl JobResult { + pub fn parse(raw: &str) -> Self { + match raw { + "done" => Self::Done, + "skipped" => Self::Skipped, + "canceled" => Self::Canceled, + "timeout" => Self::Timeout, + "dependency" => Self::Dependency, + _ => Self::Failed, + } + } + + pub fn is_failure(self) -> bool { + matches!(self, Self::Failed | Self::Timeout | Self::Dependency) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UnitFacts { + pub name: String, + pub description: String, + pub after: Vec, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Activity { + pub state: Option, + pub inactive_exit: Option, + pub active_enter: Option, +} + +impl Activity { + pub fn timestamp(raw: u64) -> Option { + (raw != 0).then_some(raw) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct PendingJob { + id: u32, + queued_at: Micros, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Outcome { + result: JobResult, + at: Micros, +} + +#[derive(Clone, Debug)] +struct UnitRecord { + facts: UnitFacts, + state: ActiveState, + inactive_exit: Option, + active_enter: Option, + job: Option, + outcome: Option, +} + +impl UnitRecord { + fn apply(&mut self, activity: Activity) { + if let Some(state) = activity.state { + self.state = state; + } + if activity.inactive_exit.is_some() { + self.inactive_exit = activity.inactive_exit; + } + if activity.active_enter.is_some() { + self.active_enter = activity.active_enter; + } + } + + fn running_since(&self) -> Option { + let job = self.job?; + if !self.state.is_transitioning() { + return None; + } + Some(self.inactive_exit.unwrap_or(job.queued_at)) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RowStatus { + Waiting, + Running, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PendingRow { + pub depth: usize, + pub is_last_sibling: Vec, + pub label: String, + pub status: RowStatus, + pub queued_at: Micros, + pub running_since: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MilestoneRow { + pub label: String, + pub finished_units: usize, + pub started_at: Micros, + pub reached_at: Option, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Tally { + pub done: usize, + pub running: usize, + pub waiting: usize, + pub failed: usize, +} + +#[derive(Clone, Debug)] +struct FrozenMilestone { + label: String, + finished_units: usize, + started_at: Micros, + reached_at: Micros, +} + +#[derive(Clone, Debug)] +pub struct BootState { + phase: Phase, + origin: Micros, + root: Option, + root_job_seen: bool, + handoff_unit: Option, + milestone_targets: Vec, + frozen: Vec, + failed: Vec, + finished_before_switch: usize, + units: HashMap, + jobs: HashMap, +} + +pub const HOST_MILESTONES: [&str; 4] = [ + "sysinit.target", + "basic.target", + "multi-user.target", + "graphical.target", +]; + +pub const HANDOFF_UNIT: &str = "display-manager.service"; + +impl BootState { + pub fn new(phase: Phase) -> Self { + let (milestone_targets, handoff_unit) = match phase { + Phase::Initrd | Phase::Host => ( + HOST_MILESTONES.iter().map(ToString::to_string).collect(), + Some(HANDOFF_UNIT.to_owned()), + ), + Phase::User => (Vec::new(), None), + }; + Self { + phase, + origin: 0, + root: None, + root_job_seen: false, + handoff_unit, + milestone_targets, + frozen: Vec::new(), + failed: Vec::new(), + finished_before_switch: 0, + units: HashMap::new(), + jobs: HashMap::new(), + } + } + + pub fn phase(&self) -> Phase { + self.phase + } + + pub fn origin(&self) -> Micros { + self.origin + } + + pub fn set_origin(&mut self, origin: Micros) { + self.origin = origin; + } + + pub fn root(&self) -> Option<&str> { + self.root.as_deref() + } + + pub fn set_root(&mut self, root: String) { + if self.root.as_ref() != Some(&root) { + self.root_job_seen = false; + } + if self.phase == Phase::User && !self.milestone_targets.contains(&root) { + self.milestone_targets.push(root.clone()); + } + self.root = Some(root); + } + + pub fn set_handoff(&mut self, unit: String) { + if self.handoff_unit.is_some() { + self.handoff_unit = Some(unit); + } + } + + pub fn failed_units(&self) -> &[String] { + &self.failed + } + + pub fn track_unit(&mut self, facts: UnitFacts, activity: Activity) { + let record = self + .units + .entry(facts.name.clone()) + .or_insert_with(|| UnitRecord { + facts: facts.clone(), + state: ActiveState::Inactive, + inactive_exit: None, + active_enter: None, + job: None, + outcome: None, + }); + record.facts = facts; + record.apply(activity); + } + + pub fn update_activity(&mut self, unit: &str, activity: Activity) { + if let Some(record) = self.units.get_mut(unit) { + record.apply(activity); + } + } + + pub fn queue_job(&mut self, id: u32, unit: &str, at: Micros) { + self.queue_job_of_unknown_kind(id, unit, at); + if self.jobs.get(&id).is_some_and(|tracked| tracked == unit) + && self.root.as_deref() == Some(unit) + { + self.root_job_seen = true; + } + } + + pub fn queue_job_of_unknown_kind(&mut self, id: u32, unit: &str, at: Micros) { + if self.jobs.contains_key(&id) { + return; + } + let Some(record) = self.units.get_mut(unit) else { + return; + }; + record.job = Some(PendingJob { id, queued_at: at }); + record.outcome = None; + self.jobs.insert(id, unit.to_owned()); + } + + pub fn finish_job(&mut self, id: u32, result: JobResult, at: Micros) { + let Some(unit) = self.jobs.remove(&id) else { + return; + }; + let Some(record) = self.units.get_mut(&unit) else { + return; + }; + if record.job.is_some_and(|job| job.id == id) { + record.job = None; + } + record.outcome = Some(Outcome { result, at }); + if result.is_failure() && !self.failed.contains(&unit) { + self.failed.push(unit); + } + } + + pub fn switch_root(&mut self, at: Micros) { + let started_at = self.origin; + let finished_units = self.finished_units() + self.finished_before_switch; + self.frozen.push(FrozenMilestone { + label: Phase::Initrd.label().to_owned(), + finished_units, + started_at, + reached_at: at, + }); + self.phase = Phase::Host; + self.root = None; + self.root_job_seen = false; + self.finished_before_switch = 0; + self.units.clear(); + self.jobs.clear(); + } + + pub fn forget_jobs(&mut self) { + self.finished_before_switch += self.finished_units(); + self.jobs.clear(); + self.units.values_mut().for_each(|record| { + record.job = None; + record.outcome = None; + }); + } + + fn finished_units(&self) -> usize { + self.units + .values() + .filter(|record| record.outcome.is_some()) + .count() + } + + pub fn is_complete(&self) -> bool { + if self.phase == Phase::Initrd { + return false; + } + if let Some(handoff) = self + .handoff_unit + .as_deref() + .and_then(|unit| self.units.get(unit)) + && handoff.job.is_some() + && handoff.state != ActiveState::Inactive + { + return true; + } + let Some(root) = self.root.as_deref().and_then(|root| self.units.get(root)) else { + return false; + }; + self.root_job_seen && root.job.is_none() + } + + pub fn tally(&self) -> Tally { + let carried = Tally { + done: self + .frozen + .iter() + .map(|frozen| frozen.finished_units) + .sum::() + + self.finished_before_switch, + failed: self.failed.len(), + ..Tally::default() + }; + self.units.values().fold(carried, |mut tally, record| { + if record.job.is_some() && record.running_since().is_some() { + tally.running += 1; + } else if record.job.is_some() { + tally.waiting += 1; + } else if record + .outcome + .is_some_and(|outcome| !outcome.result.is_failure()) + { + tally.done += 1; + } + tally + }) + } + + fn milestone_reached_at(&self, target: &str) -> Option { + let record = self.units.get(target)?; + if record.job.is_some() { + return None; + } + match record.outcome { + Some(outcome) if outcome.result == JobResult::Done => Some(outcome.at), + Some(_) => None, + None => record + .active_enter + .filter(|entered| record.state == ActiveState::Active && *entered >= self.origin), + } + } + + pub fn milestones(&self) -> Vec { + let mut finished: Vec = self + .units + .values() + .filter_map(|record| record.outcome) + .filter(|outcome| !outcome.result.is_failure()) + .map(|outcome| outcome.at) + .collect(); + finished.sort_unstable(); + let start = MilestoneWalk { + rows: self.frozen.iter().map(FrozenMilestone::row).collect(), + previous: self + .frozen + .last() + .map_or(self.origin, |frozen| frozen.reached_at), + consumed: 0, + }; + let mut walk = self + .milestone_targets + .iter() + .filter_map(|target| { + self.milestone_reached_at(target) + .map(|reached_at| ReachedMilestone { target, reached_at }) + }) + .fold(start, |walk, reached| walk.advance(&reached, &finished)); + let remaining = finished.len() - walk.consumed + self.finished_before_switch; + if remaining > 0 { + walk.rows.push(MilestoneRow { + label: "finished".to_owned(), + finished_units: remaining, + started_at: walk.previous, + reached_at: None, + }); + } + walk.rows + } + + pub fn pending_rows(&self) -> Vec { + let pending: HashSet<&str> = self + .units + .iter() + .filter(|(_, record)| record.job.is_some()) + .map(|(name, _)| name.as_str()) + .collect(); + let root = self.root.as_deref().filter(|root| pending.contains(root)); + let blocked_by_pending: HashSet<&str> = pending + .iter() + .flat_map(|name| self.units[*name].facts.after.iter()) + .map(String::as_str) + .filter(|dependency| pending.contains(dependency)) + .collect(); + let mut unblocked: Vec<&str> = pending + .iter() + .copied() + .filter(|name| !blocked_by_pending.contains(name) && Some(*name) != root) + .collect(); + self.sort_siblings(&mut unblocked); + let mut leftovers: Vec<&str> = pending.iter().copied().collect(); + self.sort_siblings(&mut leftovers); + if self.phase == Phase::User { + unblocked.clear(); + leftovers.clear(); + } + let mut rows = Vec::new(); + let mut visited = HashSet::new(); + root.into_iter() + .chain(unblocked) + .chain(leftovers) + .for_each(|top| { + if !visited.contains(top) { + self.emit( + top, + &pending, + &mut visited, + &mut Vec::new(), + true, + &mut rows, + ); + } + }); + rows + } + + fn emit<'a>( + &'a self, + unit: &'a str, + pending: &HashSet<&'a str>, + visited: &mut HashSet<&'a str>, + ancestry: &mut Vec, + is_last: bool, + rows: &mut Vec, + ) { + visited.insert(unit); + let record = &self.units[unit]; + let job = record.job.expect("pending rows only hold units with a job"); + let running_since = record.running_since(); + let mut is_last_sibling = ancestry.clone(); + is_last_sibling.push(is_last); + rows.push(PendingRow { + depth: ancestry.len(), + is_last_sibling, + label: display_label(&record.facts), + status: if running_since.is_some() { + RowStatus::Running + } else { + RowStatus::Waiting + }, + queued_at: job.queued_at, + running_since, + }); + let candidates: Vec<&str> = record + .facts + .after + .iter() + .map(String::as_str) + .filter(|dependency| pending.contains(dependency) && !visited.contains(dependency)) + .collect(); + let mut children: Vec<&str> = candidates + .iter() + .copied() + .filter(|child| { + !candidates.iter().any(|sibling| { + sibling != child + && self.waits_on(sibling, child, pending) + && !self.waits_on(child, sibling, pending) + }) + }) + .collect(); + self.sort_siblings(&mut children); + children.dedup(); + visited.extend(children.iter().copied()); + ancestry.push(is_last); + let count = children.len(); + children.into_iter().enumerate().for_each(|(index, child)| { + visited.remove(child); + self.emit(child, pending, visited, ancestry, index + 1 == count, rows); + }); + ancestry.pop(); + } + + fn waits_on(&self, waiter: &str, dependency: &str, pending: &HashSet<&str>) -> bool { + let mut seen = HashSet::new(); + let mut frontier = vec![waiter]; + while let Some(unit) = frontier.pop() { + if !seen.insert(unit) { + continue; + } + let Some(record) = self.units.get(unit) else { + continue; + }; + let mut next = record + .facts + .after + .iter() + .map(String::as_str) + .filter(|after| pending.contains(after)); + if next.clone().any(|after| after == dependency) { + return true; + } + frontier.extend(next.by_ref()); + } + false + } + + fn sibling_rank(&self, name: &str) -> SiblingRank { + match self.units[name].running_since() { + Some(since) => SiblingRank::RunningSince(since), + None => SiblingRank::Waiting, + } + } + + fn sort_siblings(&self, names: &mut [&str]) { + names.sort_by(|left, right| { + self.sibling_rank(left) + .cmp(&self.sibling_rank(right)) + .then_with(|| left.cmp(right)) + }); + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum SiblingRank { + RunningSince(Micros), + Waiting, +} + +struct ReachedMilestone<'a> { + target: &'a str, + reached_at: Micros, +} + +struct MilestoneWalk { + rows: Vec, + previous: Micros, + consumed: usize, +} + +impl MilestoneWalk { + fn advance(mut self, reached: &ReachedMilestone, finished_sorted: &[Micros]) -> Self { + let upto = finished_sorted.partition_point(|at| *at <= reached.reached_at); + self.rows.push(MilestoneRow { + label: reached.target.to_owned(), + finished_units: upto.saturating_sub(self.consumed), + started_at: self.previous.min(reached.reached_at), + reached_at: Some(reached.reached_at), + }); + self.consumed = self.consumed.max(upto); + self.previous = reached.reached_at; + self + } +} + +impl FrozenMilestone { + fn row(&self) -> MilestoneRow { + MilestoneRow { + label: self.label.clone(), + finished_units: self.finished_units, + started_at: self.started_at, + reached_at: Some(self.reached_at), + } + } +} + +fn display_label(facts: &UnitFacts) -> String { + if let Some(stem) = facts.name.strip_suffix(".service") { + return stem.to_owned(); + } + if facts.name.ends_with(".device") && !facts.description.is_empty() { + return facts.description.clone(); + } + facts.name.clone() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn facts(name: &str, after: &[&str]) -> UnitFacts { + UnitFacts { + name: name.to_owned(), + description: format!("{name} description"), + after: after.iter().map(ToString::to_string).collect(), + } + } + + fn activating(since: Micros) -> Activity { + Activity { + state: Some(ActiveState::Activating), + inactive_exit: Some(since), + active_enter: None, + } + } + + fn sample() -> BootState { + let mut state = BootState::new(Phase::Host); + state.set_root("graphical.target".to_owned()); + state.track_unit( + facts("graphical.target", &["multi-user.target"]), + Activity::default(), + ); + state.track_unit( + facts( + "multi-user.target", + &["docker.service", "nm-wait.service", "basic.target"], + ), + Activity::default(), + ); + state.track_unit( + facts("nm-wait.service", &["nm.service"]), + Activity::default(), + ); + state.track_unit(facts("nm.service", &[]), activating(1_000_000)); + state.track_unit( + facts("docker.service", &["containerd.service"]), + activating(3_000_000), + ); + state.track_unit(facts("containerd.service", &[]), Activity::default()); + state.track_unit(facts("basic.target", &[]), Activity::default()); + [ + "graphical.target", + "multi-user.target", + "nm-wait.service", + "nm.service", + "docker.service", + "containerd.service", + "basic.target", + ] + .into_iter() + .zip(1..) + .for_each(|(unit, id)| state.queue_job(id, unit, 500_000)); + state + } + + #[test] + fn pending_units_nest_under_what_waits_on_them() { + let outline: Vec = sample() + .pending_rows() + .into_iter() + .map(|row| format!("{}{}", " ".repeat(row.depth), row.label)) + .collect(); + assert_eq!( + outline, + [ + "graphical.target", + " multi-user.target", + " docker", + " containerd", + " basic.target", + " nm-wait", + " nm", + ] + ); + } + + #[test] + fn finished_jobs_leave_the_tree_and_count_toward_their_milestone() { + let mut state = sample(); + state.finish_job(6, JobResult::Done, 3_500_000); + state.finish_job(7, JobResult::Done, 4_000_000); + state.update_activity( + "basic.target", + Activity { + state: Some(ActiveState::Active), + inactive_exit: None, + active_enter: Some(4_000_000), + }, + ); + let rows = state.pending_rows(); + assert!( + rows.iter() + .all(|row| row.label != "containerd" && row.label != "basic.target") + ); + let milestones = state.milestones(); + assert_eq!(milestones.len(), 1); + assert_eq!(milestones[0].label, "basic.target"); + assert_eq!(milestones[0].finished_units, 2); + } + + #[test] + fn failures_are_listed_and_not_counted_as_done() { + let mut state = sample(); + state.finish_job(4, JobResult::Failed, 2_000_000); + assert_eq!(state.failed_units(), ["nm.service"]); + let tally = state.tally(); + assert_eq!(tally.failed, 1); + assert_eq!(tally.done, 0); + assert_eq!(tally.running, 1); + assert_eq!(tally.waiting, 5); + } + + #[test] + fn boot_completes_when_the_root_job_is_gone() { + let mut state = sample(); + assert!(!state.is_complete()); + (1..=7).for_each(|id| state.finish_job(id, JobResult::Done, 5_000_000)); + assert!(state.is_complete()); + } + + #[test] + fn display_manager_activation_hands_the_console_over() { + let mut state = sample(); + state.track_unit(facts(HANDOFF_UNIT, &[]), Activity::default()); + state.queue_job(20, HANDOFF_UNIT, 500_000); + assert!(!state.is_complete()); + state.update_activity(HANDOFF_UNIT, activating(6_000_000)); + assert!(state.is_complete()); + } + + #[test] + fn switching_root_freezes_the_initrd_summary() { + let mut state = BootState::new(Phase::Initrd); + state.set_root("initrd.target".to_owned()); + state.track_unit(facts("initrd.target", &[]), Activity::default()); + state.track_unit(facts("sysroot.mount", &[]), Activity::default()); + state.queue_job(1, "initrd.target", 0); + state.queue_job(2, "sysroot.mount", 0); + state.finish_job(2, JobResult::Done, 1_000_000); + state.finish_job(1, JobResult::Done, 1_500_000); + assert!(!state.is_complete()); + state.switch_root(2_000_000); + assert_eq!(state.phase(), Phase::Host); + let milestones = state.milestones(); + assert_eq!(milestones[0].label, "initrd"); + assert_eq!(milestones[0].finished_units, 2); + assert_eq!(milestones[0].reached_at, Some(2_000_000)); + assert_eq!(state.tally().done, 2); + assert!(state.pending_rows().is_empty()); + } + + #[test] + fn devices_show_their_description() { + let mut state = BootState::new(Phase::Host); + state.track_unit( + UnitFacts { + name: "dev-nvme1n1.device".to_owned(), + description: "Lexar SSD NM790 2TB".to_owned(), + after: Vec::new(), + }, + Activity::default(), + ); + state.queue_job(1, "dev-nvme1n1.device", 0); + assert_eq!(state.pending_rows()[0].label, "Lexar SSD NM790 2TB"); + } + + #[test] + fn units_nest_under_the_deepest_pending_waiter() { + let mut state = BootState::new(Phase::Host); + state.set_root("demo.target".to_owned()); + state.track_unit( + facts( + "demo.target", + &["report.service", "web.service", "db.service"], + ), + Activity::default(), + ); + state.track_unit( + facts("report.service", &["web.service"]), + Activity::default(), + ); + state.track_unit(facts("web.service", &["db.service"]), Activity::default()); + state.track_unit(facts("db.service", &[]), Activity::default()); + ["demo.target", "report.service", "web.service", "db.service"] + .into_iter() + .zip(1..) + .for_each(|(unit, id)| state.queue_job(id, unit, 0)); + let outline: Vec = state + .pending_rows() + .into_iter() + .map(|row| format!("{}{}", " ".repeat(row.depth), row.label)) + .collect(); + assert_eq!(outline, ["demo.target", " report", " web", " db"]); + } + + #[test] + fn ordering_cycles_do_not_repeat_units() { + let mut state = BootState::new(Phase::Host); + state.track_unit(facts("a.service", &["b.service"]), Activity::default()); + state.track_unit(facts("b.service", &["a.service"]), Activity::default()); + state.queue_job(1, "a.service", 0); + state.queue_job(2, "b.service", 0); + assert_eq!(state.pending_rows().len(), 2); + } +} diff --git a/src/run.rs b/src/run.rs new file mode 100644 index 0000000..32c8c9b --- /dev/null +++ b/src/run.rs @@ -0,0 +1,171 @@ +use std::{ + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + mpsc::{Receiver, channel}, + }, + thread::sleep, + time::Duration, +}; + +use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers}; +use ratatui::{ + DefaultTerminal, + backend::{Backend, ClearType}, +}; +use signal_hook::{consts::SIGTERM, flag}; + +use crate::{ + clock::{host_name, monotonic_now}, + console::ForegroundVt, + error::Error, + feed::{self, FeedOptions, JobKind, Update}, + model::{BootState, Phase}, + sysroot::running_in_initrd, + systemd::Scope, + view::BootView, +}; + +const FRAME_INTERVAL: Duration = Duration::from_millis(100); +const FRAMES_PER_FULL_REPAINT: u64 = 20; + +pub struct Options { + pub scope: Scope, + pub target: Option, + pub hold: Duration, +} + +pub fn run(options: Options) -> Result<(), Error> { + let terminate = Arc::new(AtomicBool::new(false)); + flag::register(SIGTERM, Arc::clone(&terminate))?; + let (sender, updates) = channel(); + let mut state = BootState::new(initial_phase(options.scope)); + feed::spawn( + FeedOptions { + scope: options.scope, + target: options.target, + }, + sender, + ); + let foreground = ForegroundVt::take(); + let mut terminal = ratatui::try_init()?; + let watched = watch( + &mut state, + &updates, + &mut terminal, + &terminate, + options.hold, + ); + ratatui::restore(); + if let Some(foreground) = foreground { + foreground.give_back(); + } + watched +} + +fn initial_phase(scope: Scope) -> Phase { + match scope { + Scope::User => Phase::User, + Scope::System if running_in_initrd() => Phase::Initrd, + Scope::System => Phase::Host, + } +} + +fn absorb(state: &mut BootState, update: Update) -> Option { + match update { + Update::Root(root) => state.set_root(root), + Update::Handoff(unit) => state.set_handoff(unit), + Update::Origin(origin) => state.set_origin(origin), + Update::Unit { facts, activity } => state.track_unit(facts, activity), + Update::JobQueued { + id, + unit, + at, + kind: JobKind::BringsUp, + } => state.queue_job(id, &unit, at), + Update::JobQueued { + id, + unit, + at, + kind: JobKind::Unknown, + } => state.queue_job_of_unknown_kind(id, &unit, at), + Update::JobFinished { id, result, at } => state.finish_job(id, result, at), + Update::Activity { unit, activity } => state.update_activity(&unit, activity), + Update::RootSwitched { at } => state.switch_root(at), + Update::Resubscribed => state.forget_jobs(), + Update::Ended(error) => return Some(error), + } + None +} + +fn draw( + terminal: &mut DefaultTerminal, + state: &BootState, + host: &str, + frame: u64, +) -> Result<(), Error> { + terminal.draw(|canvas| { + canvas.render_widget( + BootView { + state, + now: monotonic_now(), + host, + frame, + }, + canvas.area(), + ); + })?; + Ok(()) +} + +fn repaint_fully(terminal: &mut DefaultTerminal) -> Result<(), Error> { + terminal.backend_mut().clear_region(ClearType::All)?; + terminal.swap_buffers(); + Ok(()) +} + +fn asks_to_quit(event: &Event) -> bool { + let Event::Key(KeyEvent { + code, modifiers, .. + }) = event + else { + return false; + }; + *code == KeyCode::Char('q') + || (*code == KeyCode::Char('c') && modifiers.contains(KeyModifiers::CONTROL)) +} + +fn watch( + state: &mut BootState, + updates: &Receiver, + terminal: &mut DefaultTerminal, + terminate: &AtomicBool, + hold: Duration, +) -> Result<(), Error> { + let host = host_name(); + let mut frame: u64 = 0; + loop { + if let Some(error) = updates.try_iter().find_map(|update| absorb(state, update)) { + return Err(error); + } + if frame.is_multiple_of(FRAMES_PER_FULL_REPAINT) { + repaint_fully(terminal)?; + } + draw(terminal, state, &host, frame)?; + if state.is_complete() { + eprintln!( + "boot-tree: {} reached, handing the console over", + state.root().unwrap_or("boot") + ); + sleep(hold); + return Ok(()); + } + if terminate.load(Ordering::Relaxed) { + return Ok(()); + } + if event::poll(FRAME_INTERVAL)? && asks_to_quit(&event::read()?) { + return Ok(()); + } + frame += 1; + } +} diff --git a/src/sysroot.rs b/src/sysroot.rs new file mode 100644 index 0000000..e832024 --- /dev/null +++ b/src/sysroot.rs @@ -0,0 +1,35 @@ +use std::{os::fd::OwnedFd, path::Path}; + +use rustix::{ + fs::{Mode, OFlags, open}, + io::Errno, + process::{chdir, chroot, fchdir}, +}; + +const SYSROOT: &str = "/sysroot"; +const INITRD_RELEASE: &str = "/etc/initrd-release"; + +pub fn running_in_initrd() -> bool { + Path::new(INITRD_RELEASE).exists() +} + +pub struct Sysroot { + directory: OwnedFd, +} + +impl Sysroot { + pub fn hold() -> Result { + 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("/") + } +} diff --git a/src/systemd.rs b/src/systemd.rs new file mode 100644 index 0000000..df83008 --- /dev/null +++ b/src/systemd.rs @@ -0,0 +1,282 @@ +use std::{iter, time::Duration}; + +use dbus::{ + Message, MessageType, Path, + arg::{AppendAll, PropMap, RefArg, Variant}, + channel::{BusType, Channel}, +}; + +use crate::{ + error::Error, + model::{ActiveState, Activity, JobResult, Micros, UnitFacts}, +}; + +const DESTINATION: &str = "org.freedesktop.systemd1"; +const MANAGER_PATH: &str = "/org/freedesktop/systemd1"; +const MANAGER_INTERFACE: &str = "org.freedesktop.systemd1.Manager"; +const UNIT_INTERFACE: &str = "org.freedesktop.systemd1.Unit"; +const JOB_INTERFACE: &str = "org.freedesktop.systemd1.Job"; +const PROPERTIES_INTERFACE: &str = "org.freedesktop.DBus.Properties"; +const PEER_INTERFACE: &str = "org.freedesktop.DBus.Peer"; +const BUS_DESTINATION: &str = "org.freedesktop.DBus"; +const BUS_PATH: &str = "/org/freedesktop/DBus"; +const PRIVATE_SOCKET: &str = "unix:path=/run/systemd/private"; +const SIGNAL_RULE: &str = "type='signal',path_namespace='/org/freedesktop/systemd1'"; +const CALL_TIMEOUT: Duration = Duration::from_secs(1); + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Scope { + System, + User, +} + +pub enum Signal { + JobNew { + id: u32, + job: Path<'static>, + unit: String, + }, + JobRemoved { + id: u32, + result: JobResult, + }, + UnitChanged { + path: Path<'static>, + activity: Activity, + }, +} + +pub struct FetchedUnit { + pub path: Path<'static>, + pub facts: UnitFacts, + pub activity: Activity, +} + +pub struct JobListing { + pub id: u32, + pub unit: String, + pub kind: String, +} + +pub fn brings_unit_up(job_kind: &str) -> bool { + job_kind != "stop" +} + +type ListedJob = (u32, String, String, String, Path<'static>, Path<'static>); + +impl From for JobListing { + fn from((id, unit, kind, ..): ListedJob) -> Self { + Self { id, unit, kind } + } +} + +pub struct Session { + channel: Channel, + peer_to_peer: bool, +} + +impl Session { + pub fn open(scope: Scope) -> Result { + if scope == Scope::System + && let Ok(channel) = Channel::open_private(PRIVATE_SOCKET) + { + send_authentication_carrier(&channel)?; + return Ok(Self { + channel, + peer_to_peer: true, + }); + } + let bus = match scope { + Scope::System => BusType::System, + Scope::User => BusType::Session, + }; + let session = Self { + channel: Channel::get_private(bus)?, + peer_to_peer: false, + }; + session.call_at( + BUS_DESTINATION, + BUS_PATH, + BUS_DESTINATION, + "AddMatch", + (SIGNAL_RULE,), + )?; + Ok(session) + } + + pub fn is_peer_to_peer(&self) -> bool { + self.peer_to_peer + } + + fn call_at( + &self, + destination: &str, + path: &str, + interface: &str, + member: &str, + arguments: impl AppendAll, + ) -> Result { + let Ok(mut call) = Message::new_method_call(destination, path, interface, member) else { + return Err(Error::MalformedCall); + }; + call.append_all(arguments); + Ok(self.channel.send_with_reply_and_block(call, CALL_TIMEOUT)?) + } + + fn call( + &self, + path: &str, + interface: &str, + member: &str, + arguments: impl AppendAll, + ) -> Result { + self.call_at(DESTINATION, path, interface, member, arguments) + } + + fn call_manager(&self, member: &str) -> Result { + self.call(MANAGER_PATH, MANAGER_INTERFACE, member, ()) + } + + pub fn subscribe(&self) -> Result<(), Error> { + self.call_manager("Subscribe")?; + Ok(()) + } + + pub fn default_target(&self) -> Result { + Ok(self.call_manager("GetDefaultTarget")?.read1()?) + } + + pub fn boot_in_progress(&self) -> Result { + let reply = self.call( + MANAGER_PATH, + PROPERTIES_INTERFACE, + "Get", + (MANAGER_INTERFACE, "FinishTimestampMonotonic"), + )?; + let finished: Variant = reply.read1()?; + Ok(finished.0 == 0) + } + + pub fn list_jobs(&self) -> Result, Error> { + let listed: Vec = self.call_manager("ListJobs")?.read1()?; + Ok(listed.into_iter().map(JobListing::from).collect()) + } + + pub fn job_kind(&self, job: &Path) -> Result { + let reply = self.call(job, PROPERTIES_INTERFACE, "Get", (JOB_INTERFACE, "JobType"))?; + let kind: Variant = reply.read1()?; + Ok(kind.0) + } + + pub fn fetch_unit(&self, name: &str) -> Result { + let path: Path<'static> = self + .call(MANAGER_PATH, MANAGER_INTERFACE, "GetUnit", (name,))? + .read1()?; + let properties: PropMap = self + .call(&path, PROPERTIES_INTERFACE, "GetAll", (UNIT_INTERFACE,))? + .read1()?; + Ok(FetchedUnit { + path, + facts: UnitFacts { + name: text_property(&properties, "Id").unwrap_or_else(|| name.to_owned()), + description: text_property(&properties, "Description").unwrap_or_default(), + after: list_property(&properties, "After"), + }, + activity: activity_from(&properties), + }) + } + + pub fn receive(&self, timeout: Duration) -> Result, Error> { + let queued = self.drain(); + if !queued.is_empty() { + return Ok(queued); + } + if self.channel.read_write(Some(timeout)).is_err() || !self.channel.is_connected() { + return Err(Error::Disconnected); + } + Ok(self.drain()) + } + + fn drain(&self) -> Vec { + iter::from_fn(|| self.channel.pop_message()) + .filter_map(|message| parse_signal(&message)) + .collect() + } +} + +fn send_authentication_carrier(channel: &Channel) -> Result<(), Error> { + let Ok(mut ping) = Message::new_method_call(DESTINATION, MANAGER_PATH, PEER_INTERFACE, "Ping") + else { + return Err(Error::MalformedCall); + }; + ping.set_no_reply(true); + if channel.send(ping).is_err() { + return Err(Error::Disconnected); + } + channel.flush(); + Ok(()) +} + +fn parse_signal(message: &Message) -> Option { + if message.msg_type() != MessageType::Signal { + return None; + } + let interface = message.interface()?; + let member = message.member()?; + match (&*interface, &*member) { + (MANAGER_INTERFACE, "JobNew") => { + let (id, job, unit): (u32, Path<'static>, String) = message.read3().ok()?; + Some(Signal::JobNew { id, job, unit }) + } + (MANAGER_INTERFACE, "JobRemoved") => { + let (id, _job, _unit, result): (u32, Path<'static>, String, String) = + message.read4().ok()?; + Some(Signal::JobRemoved { + id, + result: JobResult::parse(&result), + }) + } + (PROPERTIES_INTERFACE, "PropertiesChanged") => { + let (changed_interface, changed, _invalidated): (String, PropMap, Vec) = + message.read3().ok()?; + if changed_interface != UNIT_INTERFACE { + return None; + } + Some(Signal::UnitChanged { + path: message.path()?.into_static(), + activity: activity_from(&changed), + }) + } + _ => None, + } +} + +fn text_property(properties: &PropMap, name: &str) -> Option { + properties.get(name)?.0.as_str().map(ToOwned::to_owned) +} + +fn list_property(properties: &PropMap, name: &str) -> Vec { + let Some(items) = properties.get(name).and_then(|value| value.0.as_iter()) else { + return Vec::new(); + }; + items + .filter_map(|item| item.as_str()) + .map(ToOwned::to_owned) + .collect() +} + +fn timestamp_property(properties: &PropMap, name: &str) -> Option { + properties + .get(name)? + .0 + .as_u64() + .and_then(Activity::timestamp) +} + +fn activity_from(properties: &PropMap) -> Activity { + Activity { + state: text_property(properties, "ActiveState").map(|raw| ActiveState::parse(&raw)), + inactive_exit: timestamp_property(properties, "InactiveExitTimestampMonotonic"), + active_enter: timestamp_property(properties, "ActiveEnterTimestampMonotonic"), + } +} diff --git a/src/view.rs b/src/view.rs new file mode 100644 index 0000000..bacd11c --- /dev/null +++ b/src/view.rs @@ -0,0 +1,577 @@ +use std::iter::repeat_n; + +use ratatui::{ + buffer::Buffer, + layout::Rect, + style::{Color, Modifier, Style}, + widgets::Widget, +}; + +use crate::model::{BootState, Micros, MilestoneRow, PendingRow, RowStatus, Tally}; + +const SPINNER: [char; 4] = ['|', '/', '-', '\\']; +const DONE: char = '√'; +const FAILED: char = '×'; +const RUNNING_BAR: char = '█'; +const WAITING_BAR: char = '░'; +const STILL_GOING: char = '▶'; +const ELLIPSIS: char = '…'; +const PHASE_ARROW: char = '→'; + +const MIN_BAR_WIDTH: u16 = 12; +const DURATION_WIDTH: usize = 7; +const MAX_FAILED_ROWS: usize = 3; +const AXIS_STEPS_SECONDS: [u64; 12] = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 1800, 3600]; +const AXIS_LABEL_SPACING: u64 = 8; + +pub struct BootView<'a> { + pub state: &'a BootState, + pub now: Micros, + pub host: &'a str, + pub frame: u64, +} + +struct Columns { + left: u16, + bar_x: u16, + bar_width: u16, +} + +impl Columns { + fn for_width(width: u16) -> Self { + let left = (width * 11 / 20).clamp(40.min(width), 72); + let bar_x = left + 1; + let bar_width = width.saturating_sub(bar_x); + if bar_width < MIN_BAR_WIDTH { + return Self { + left: width, + bar_x: width, + bar_width: 0, + }; + } + Self { + left, + bar_x, + bar_width, + } + } +} + +struct TimeAxis { + origin: Micros, + end: Micros, + step: Micros, + width: u16, +} + +impl TimeAxis { + fn new(origin: Micros, now: Micros, width: u16) -> Self { + let span_seconds = now.saturating_sub(origin).div_ceil(1_000_000).max(1); + let max_labels = (u64::from(width) / AXIS_LABEL_SPACING).max(1); + let step_seconds = AXIS_STEPS_SECONDS + .into_iter() + .find(|step| span_seconds.div_ceil(*step) <= max_labels) + .unwrap_or(*AXIS_STEPS_SECONDS.last().expect("axis steps are not empty")); + let end_seconds = span_seconds.div_ceil(step_seconds).max(1) * step_seconds; + Self { + origin, + end: origin + end_seconds * 1_000_000, + step: step_seconds * 1_000_000, + width, + } + } + + fn column(&self, at: Micros) -> u16 { + let clamped = at.clamp(self.origin, self.end); + let fraction = (clamped - self.origin) as f64 / (self.end - self.origin) as f64; + ((fraction * f64::from(self.width)) as u16).min(self.width.saturating_sub(1)) + } + + fn ticks(&self) -> impl Iterator + '_ { + (0..) + .map(|index| index * self.step) + .take_while(|offset| self.origin + offset <= self.end) + .map(|offset| AxisTick { + column: self.column(self.origin + offset), + offset, + }) + } +} + +struct AxisTick { + column: u16, + offset: Micros, +} + +fn format_duration(micros: Micros) -> String { + let tenths = micros / 100_000; + if tenths < 600 { + return format!("{}.{}s", tenths / 10, tenths % 10); + } + let seconds = micros / 1_000_000; + if seconds < 3600 { + return format!("{}m{:02}s", seconds / 60, seconds % 60); + } + format!("{}h{:02}m", seconds / 3600, seconds % 3600 / 60) +} + +fn format_axis_label(offset: Micros) -> String { + let seconds = offset / 1_000_000; + if seconds < 60 || !seconds.is_multiple_of(60) { + format!("{seconds}s") + } else { + format!("{}m", seconds / 60) + } +} + +fn truncate(text: &str, width: usize) -> String { + if text.chars().count() <= width { + return text.to_owned(); + } + if width == 0 { + return String::new(); + } + let mut kept: String = text.chars().take(width - 1).collect(); + kept.push(ELLIPSIS); + kept +} + +fn tree_prefix(row: &PendingRow) -> String { + let mut prefix: String = row + .is_last_sibling + .iter() + .skip(1) + .take(row.depth.saturating_sub(1)) + .map(|ancestor_is_last| if *ancestor_is_last { " " } else { "│ " }) + .collect(); + if row.depth > 0 { + let is_last = row.is_last_sibling.last().copied().unwrap_or(true); + prefix.push_str(if is_last { "└─ " } else { "├─ " }); + } + prefix +} + +struct Palette; + +impl Palette { + fn header() -> Style { + Style::new().add_modifier(Modifier::BOLD) + } + + fn dim() -> Style { + Style::new().fg(Color::DarkGray) + } + + fn running() -> Style { + Style::new().fg(Color::Yellow) + } + + fn waiting() -> Style { + Style::new().fg(Color::DarkGray) + } + + fn done() -> Style { + Style::new().fg(Color::Green) + } + + fn failed() -> Style { + Style::new().fg(Color::Red).add_modifier(Modifier::BOLD) + } + + fn target() -> Style { + Style::new().fg(Color::Cyan) + } +} + +struct Painter<'b> { + buf: &'b mut Buffer, + area: Rect, +} + +impl Painter<'_> { + fn text(&mut self, x: u16, y: u16, text: &str, style: Style) { + if y >= self.area.height || x >= self.area.width { + return; + } + let room = usize::from(self.area.width - x); + self.buf + .set_stringn(self.area.x + x, self.area.y + y, text, room, style); + } + + fn right_aligned(&mut self, right_edge: u16, y: u16, text: &str, style: Style) { + let width = text.chars().count() as u16; + self.text(right_edge.saturating_sub(width), y, text, style); + } + + fn fill(&mut self, x: u16, y: u16, length: u16, symbol: char, style: Style) { + let run: String = repeat_n(symbol, usize::from(length)).collect(); + self.text(x, y, &run, style); + } +} + +impl BootView<'_> { + fn draw_header(&self, painter: &mut Painter, columns: &Columns, axis: Option<&TimeAxis>) { + let title = format!( + "boot-tree {} {PHASE_ARROW} {}", + self.host, + self.state.phase().label() + ); + painter.text(0, 0, &title, Palette::header()); + let elapsed = format_duration(self.now.saturating_sub(self.state.origin())); + painter.right_aligned(columns.left, 0, &elapsed, Palette::header()); + let Some(axis) = axis else { + return; + }; + axis.ticks().for_each(|tick| { + let label = format_axis_label(tick.offset); + let label_width = label.chars().count() as u16; + let x = columns.bar_x + tick.column.min(axis.width.saturating_sub(label_width)); + painter.text(x, 0, &label, Palette::dim()); + painter.text(columns.bar_x + tick.column, 1, "|", Palette::dim()); + }); + } + + fn draw_pending( + &self, + painter: &mut Painter, + columns: &Columns, + axis: Option<&TimeAxis>, + y: u16, + row: &PendingRow, + ) { + let is_target = row.label.ends_with(".target"); + let prefix = tree_prefix(row); + let marker = match (is_target, row.status) { + (true, _) => String::new(), + (false, RowStatus::Running) => format!("[{}] ", SPINNER[(self.frame % 4) as usize]), + (false, RowStatus::Waiting) => "[ ] ".to_owned(), + }; + let label_style = match (is_target, row.status) { + (true, _) => Palette::target(), + (false, RowStatus::Running) => Style::new(), + (false, RowStatus::Waiting) => Palette::dim(), + }; + let since = row.running_since.unwrap_or(row.queued_at); + let duration = format_duration(self.now.saturating_sub(since)); + let fixed = prefix.chars().count() + marker.chars().count() + DURATION_WIDTH + 1; + let label_room = usize::from(columns.left).saturating_sub(fixed); + let mut x = 0; + painter.text(x, y, &prefix, Palette::dim()); + x += prefix.chars().count() as u16; + let marker_style = if row.status == RowStatus::Running { + Palette::running() + } else { + Palette::dim() + }; + painter.text(x, y, &marker, marker_style); + x += marker.chars().count() as u16; + painter.text(x, y, &truncate(&row.label, label_room), label_style); + painter.right_aligned(columns.left, y, &duration, label_style); + let Some(axis) = axis else { + return; + }; + let queued = axis.column(row.queued_at); + let now = axis.column(self.now); + match row.running_since { + Some(running_since) => { + let started = axis.column(running_since); + if started > queued { + painter.fill( + columns.bar_x + queued, + y, + started - queued, + WAITING_BAR, + Palette::waiting(), + ); + } + painter.fill( + columns.bar_x + started, + y, + now.saturating_sub(started).max(1), + RUNNING_BAR, + Palette::running(), + ); + } + None => { + painter.fill( + columns.bar_x + queued, + y, + now.saturating_sub(queued).max(1), + WAITING_BAR, + Palette::waiting(), + ); + } + } + let arrow_x = (now + 1).min(axis.width.saturating_sub(1)); + painter.text( + columns.bar_x + arrow_x, + y, + &STILL_GOING.to_string(), + Palette::dim(), + ); + } +} + +impl Painter<'_> { + fn milestone( + &mut self, + columns: &Columns, + axis: Option<&TimeAxis>, + y: u16, + row: &MilestoneRow, + ) { + let units = match row.finished_units { + 1 => "1 unit".to_owned(), + count => format!("{count} units"), + }; + let label = truncate(&row.label, 18); + let Some(reached_at) = row.reached_at else { + self.text(0, y, &format!(" {label:<18} {units:>10}"), Palette::dim()); + return; + }; + self.text( + 0, + y, + &format!("{DONE} {label:<18} {units:>10}"), + Palette::done(), + ); + let duration = format_duration(reached_at.saturating_sub(row.started_at)); + self.right_aligned(columns.left, y, &duration, Palette::done()); + if let Some(axis) = axis { + let start = axis.column(row.started_at); + let end = axis.column(reached_at); + self.fill( + columns.bar_x + start, + y, + end.saturating_sub(start).max(1), + RUNNING_BAR, + Palette::done(), + ); + } + } + + fn footer(&mut self, tally: Tally, y: u16) { + self.fill(0, y, self.area.width, '─', Palette::dim()); + let counts = format!( + "{DONE} {} done {} running {} waiting {FAILED} {} failed", + tally.done, tally.running, tally.waiting, tally.failed + ); + let style = if tally.failed > 0 { + Palette::failed() + } else { + Style::new() + }; + self.text(0, y + 1, &counts, style); + let legend = format!("{RUNNING_BAR} running {WAITING_BAR} waiting"); + let room_left = usize::from(self.area.width).saturating_sub(counts.chars().count()); + if room_left > legend.chars().count() + 2 { + self.right_aligned(self.area.width, y + 1, &legend, Palette::dim()); + } + } +} + +impl Widget for BootView<'_> { + fn render(self, area: Rect, buf: &mut Buffer) { + let mut painter = Painter { buf, area }; + let columns = Columns::for_width(area.width); + let axis = (columns.bar_width > 0) + .then(|| TimeAxis::new(self.state.origin(), self.now, columns.bar_width)); + self.draw_header(&mut painter, &columns, axis.as_ref()); + + let milestones = self.state.milestones(); + let failed = self.state.failed_units(); + let shown_failed = failed.len().min(MAX_FAILED_ROWS); + let failed_lines = shown_failed + usize::from(failed.len() > MAX_FAILED_ROWS); + let footer_height = 2; + let bottom_height = (milestones.len() + failed_lines + footer_height) as u16; + let tree_top = 2; + let tree_bottom = area.height.saturating_sub(bottom_height + 1).max(tree_top); + + let rows = self.state.pending_rows(); + let capacity = usize::from(tree_bottom - tree_top); + let overflow = rows.len() > capacity; + let visible = if overflow { + capacity.saturating_sub(1) + } else { + rows.len() + }; + rows.iter() + .take(visible) + .zip(tree_top..) + .for_each(|(row, y)| self.draw_pending(&mut painter, &columns, axis.as_ref(), y, row)); + if overflow { + let hidden = rows.len() - visible; + painter.text( + 0, + tree_top + visible as u16, + &format!("{ELLIPSIS} {hidden} more"), + Palette::dim(), + ); + } + + let milestones_top = area.height.saturating_sub(bottom_height); + milestones + .iter() + .zip(milestones_top..) + .for_each(|(milestone, y)| painter.milestone(&columns, axis.as_ref(), y, milestone)); + let failed_top = milestones_top + milestones.len() as u16; + let hidden_failures = failed.len().saturating_sub(MAX_FAILED_ROWS); + failed + .iter() + .take(shown_failed) + .map(|unit| format!("{FAILED} {unit} failed")) + .chain((hidden_failures > 0).then(|| format!("{FAILED} {hidden_failures} more failed"))) + .zip(failed_top..) + .for_each(|(line, y)| painter.text(0, y, &line, Palette::failed())); + painter.footer(self.state.tally(), failed_top + failed_lines as u16); + } +} + +#[cfg(test)] +mod tests { + use ratatui::{Terminal, backend::TestBackend}; + + use super::*; + use crate::model::{ActiveState, Activity, JobResult, Phase, UnitFacts}; + + fn facts(name: &str, after: &[&str]) -> UnitFacts { + UnitFacts { + name: name.to_owned(), + description: String::new(), + after: after.iter().map(ToString::to_string).collect(), + } + } + + fn render(state: &BootState, now: Micros, width: u16, height: u16) -> Vec { + let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("test backend"); + terminal + .draw(|frame| { + frame.render_widget( + BootView { + state, + now, + host: "ryzen", + frame: 1, + }, + frame.area(), + ); + }) + .expect("draw"); + let buffer = terminal.backend().buffer().clone(); + (0..height) + .map(|y| { + let line: String = (0..width) + .map(|x| buffer[(x, y)].symbol().to_owned()) + .collect(); + line.trim_end().to_owned() + }) + .collect() + } + + fn boot_in_progress() -> BootState { + let mut state = BootState::new(Phase::Host); + state.set_root("graphical.target".to_owned()); + state.track_unit( + facts("graphical.target", &["multi-user.target"]), + Activity::default(), + ); + state.track_unit( + facts( + "multi-user.target", + &["docker.service", "systemd-rfkill.service"], + ), + Activity::default(), + ); + state.track_unit( + facts("docker.service", &[]), + Activity { + state: Some(ActiveState::Activating), + inactive_exit: Some(9_000_000), + active_enter: None, + }, + ); + state.track_unit( + facts("systemd-rfkill.service", &[]), + Activity { + state: Some(ActiveState::Activating), + inactive_exit: Some(6_000_000), + active_enter: None, + }, + ); + state.track_unit(facts("sysinit.target", &[]), Activity::default()); + state.track_unit(facts("nvidia-powerd.service", &[]), Activity::default()); + [ + "graphical.target", + "multi-user.target", + "docker.service", + "systemd-rfkill.service", + "sysinit.target", + "nvidia-powerd.service", + ] + .into_iter() + .zip(1..) + .for_each(|(unit, id)| state.queue_job(id, unit, 1_000_000)); + state.finish_job(5, JobResult::Done, 4_000_000); + state.finish_job(6, JobResult::Failed, 5_000_000); + state + } + + #[test] + fn renders_tree_bars_milestones_and_footer() { + let lines = render(&boot_in_progress(), 12_400_000, 110, 14); + let screen = lines.join("\n"); + assert!( + lines[0].starts_with("boot-tree ryzen → stage 2"), + "{screen}" + ); + assert!(lines[0].contains("12.4s"), "{screen}"); + assert!(lines[2].starts_with("graphical.target"), "{screen}"); + assert!(lines[3].starts_with("└─ multi-user.target"), "{screen}"); + assert!(lines[4].starts_with(" ├─ [/] systemd-rfkill"), "{screen}"); + assert!(lines[5].starts_with(" └─ [/] docker"), "{screen}"); + assert!(lines[4].contains('█') && lines[4].contains('▶'), "{screen}"); + assert!(screen.contains("√ sysinit.target"), "{screen}"); + assert!( + screen.contains("× nvidia-powerd.service failed"), + "{screen}" + ); + assert!( + screen.contains("√ 1 done 2 running 2 waiting × 1 failed"), + "{screen}" + ); + } + + #[test] + fn narrow_screens_drop_the_timeline() { + let lines = render(&boot_in_progress(), 12_400_000, 50, 14); + assert!( + lines.iter().all(|line| !line.contains('█')), + "{}", + lines.join("\n") + ); + assert!(lines[4].contains("systemd-rfkill")); + } + + #[test] + fn overflowing_trees_are_cut_with_a_count() { + let mut state = BootState::new(Phase::Host); + (0..30).for_each(|id| { + let name = format!("unit{id:02}.service"); + state.track_unit(facts(&name, &[]), Activity::default()); + state.queue_job(id, &name, 0); + }); + let lines = render(&state, 1_000_000, 110, 12); + assert!( + lines.iter().any(|line| line.starts_with("… ")), + "{}", + lines.join("\n") + ); + } + + #[test] + fn durations_switch_units_past_a_minute() { + assert_eq!(format_duration(12_400_000), "12.4s"); + assert_eq!(format_duration(65_000_000), "1m05s"); + assert_eq!(format_duration(3_720_000_000), "1h02m"); + } +}