diff --git a/Cargo.lock b/Cargo.lock index cdac464052..772b1f151f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -318,6 +318,21 @@ version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +[[package]] +name = "cassowary" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" + +[[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.4.0" @@ -436,6 +451,20 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "compact_str" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd622ebbb56a5b2ccb651b32b911cdeb2a9b4b11776b2473bf26a26a286244e" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + [[package]] name = "configparser" version = "3.1.0" @@ -564,6 +593,31 @@ version = "0.8.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" +[[package]] +name = "crossterm" +version = "0.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" +dependencies = [ + "bitflags", + "crossterm_winapi", + "mio", + "parking_lot", + "rustix 0.38.41", + "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.6" @@ -1651,6 +1705,47 @@ version = "2.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b248f5224d1d606005e02c97f5aa4e88eeb230488bcc03bc9ca4d7991399f2b5" +[[package]] +name = "instability" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6778b0196eefee7df739db78758e5cf9b37412268bfa5650bfeed028aed20d9c" +dependencies = [ + "darling", + "indoc", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "installer" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "crossterm", + "env_logger 0.11.5", + "indoc", + "log", + "nix", + "osutils", + "ratatui", + "regex", + "reqwest", + "serde", + "serde_json", + "serde_yaml", + "sha2", + "tar", + "tempfile", + "tokio", + "toml", + "trident-client", + "trident_api", + "url", +] + [[package]] name = "instant" version = "0.1.13" @@ -1945,6 +2040,15 @@ version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" +[[package]] +name = "lru" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" +dependencies = [ + "hashbrown", +] + [[package]] name = "maplit" version = "1.0.2" @@ -1994,6 +2098,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd" dependencies = [ "libc", + "log", "wasi 0.11.0+wasi-snapshot-preview1", "windows-sys 0.52.0", ] @@ -2336,6 +2441,12 @@ dependencies = [ "regex", ] +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + [[package]] name = "pem" version = "3.0.6" @@ -2758,6 +2869,27 @@ dependencies = [ "zerocopy 0.8.27", ] +[[package]] +name = "ratatui" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b" +dependencies = [ + "bitflags", + "cassowary", + "compact_str", + "crossterm", + "indoc", + "instability", + "itertools", + "lru", + "paste", + "strum 0.26.3", + "unicode-segmentation", + "unicode-truncate", + "unicode-width 0.2.0", +] + [[package]] name = "rayon" version = "1.10.0" @@ -3160,6 +3292,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -3241,6 +3382,16 @@ 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.3" @@ -3251,6 +3402,17 @@ dependencies = [ "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.7" @@ -3364,6 +3526,12 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" +[[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.10.0" @@ -3381,6 +3549,9 @@ name = "strum" version = "0.26.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros 0.26.4", +] [[package]] name = "strum" @@ -3582,7 +3753,7 @@ checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057" dependencies = [ "smawk", "unicode-linebreak", - "unicode-width", + "unicode-width 0.2.0", ] [[package]] @@ -3733,6 +3904,47 @@ dependencies = [ "tokio", ] +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + [[package]] name = "tonic" version = "0.14.2" @@ -3987,7 +4199,7 @@ dependencies = [ "serde_json", "serde_yaml", "sha2", - "signal-hook", + "signal-hook 0.4.3", "sqlite", "strum 0.26.3", "strum_macros 0.26.4", @@ -4229,6 +4441,23 @@ version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" +[[package]] +name = "unicode-truncate" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf" +dependencies = [ + "itertools", + "unicode-segmentation", + "unicode-width 0.1.14", +] + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + [[package]] name = "unicode-width" version = "0.2.0" @@ -4765,6 +4994,15 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + [[package]] name = "winsafe" version = "0.0.19" diff --git a/Cargo.toml b/Cargo.toml index 1483194d00..5d53d8ea74 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,7 @@ default-members = ["crates/trident"] members = [ "crates/docbuilder", + "crates/installer", "crates/trident-acl-agent", "crates/trident-client", "crates/osmodifier", @@ -34,6 +35,7 @@ chrono = { version = "0.4.38", features = ["serde"] } clap = { version = "4.4.18", features = ["derive", "wrap_help"] } configparser = { version = "3.1.0", features = ["indexmap"] } const_format = "0.2.33" +crossterm = "0.28.1" derive_more = "0.99.19" docker_credential = "1.0.1" documented = "0.6.0" @@ -78,6 +80,7 @@ prost = "0.14.1" prost-types = "0.14.1" quote = "1.0.37" rand = "0.9.3" +ratatui = "0.29.0" rayon = "1.10" regex = "1.11.1" reqwest = { version = "0.12.9", features = [ @@ -114,6 +117,7 @@ tonic = "0.14.2" tonic-middleware = "0.4.0" tonic-prost = "0.14.2" tonic-prost-build = "0.14.2" +toml = "0.8.23" tower = "0.5.2" tracing = "0.1.41" tracing-journald = "0.3.0" diff --git a/Makefile b/Makefile index e26b33e6c8..6f4e551ed9 100644 --- a/Makefile +++ b/Makefile @@ -141,8 +141,8 @@ format: .PHONY: test test: .cargo/config - cargo test --all --no-fail-fast - cargo test -p trident-client --all-features --no-fail-fast + cargo test --locked --all --no-fail-fast + cargo test --locked -p trident-client --all-features --no-fail-fast COVERAGE_EXCLUDED_FILES_REGEX='crates/docbuilder|crates/pytest|crates/setsail|target|/mnt/vss' @@ -184,12 +184,12 @@ clean-coverage: rm -rf target/coverage/profraw rm -rf target/lcov.info -target/release/trident target/release/trident-acl-agent: .cargo/config | version-vars +target/release/trident target/release/trident-acl-agent target/release/trident-installer: .cargo/config | version-vars @OPENSSL_STATIC=1 \ OPENSSL_LIB_DIR=$(shell dirname `whereis libssl.a | cut -d" " -f2`) \ OPENSSL_INCLUDE_DIR=/usr/include/openssl \ TRIDENT_VERSION="$(LOCAL_BUILD_TRIDENT_VERSION)" \ - cargo build --release --features dangerous-options,grpc-preview -p trident -p trident-acl-agent + cargo build --release --features dangerous-options,grpc-preview -p trident -p trident-acl-agent -p installer ARTIFACTS_DIR="artifacts" @@ -212,7 +212,7 @@ clean-builder-image: azl-version-vars @echo "Removing local image $(BUILDER_IMAGE)..." @docker rmi $(BUILDER_IMAGE) || echo "Image $(BUILDER_IMAGE) not found locally." -target/$(DISTRO)/release/trident target/$(DISTRO)/release/trident-acl-agent: azl-version-vars version-vars builder-image +target/$(DISTRO)/release/trident target/$(DISTRO)/release/trident-acl-agent target/$(DISTRO)/release/trident-installer: azl-version-vars version-vars builder-image @mkdir -p bin/ @mkdir -p target/$(DISTRO)/ @echo "Building Trident for Azure Linux ($(DISTRO)) using Docker image $(BUILDER_IMAGE)..." @@ -225,10 +225,11 @@ target/$(DISTRO)/release/trident target/$(DISTRO)/release/trident-acl-agent: azl --release \ --features dangerous-options,grpc-preview \ -p trident \ - -p trident-acl-agent + -p trident-acl-agent \ + -p installer # This will do a proper build on azl3, exactly as the pipelines would, with the custom registry and all. -bin/trident-rpms-%.tar.gz: packaging/docker/Dockerfile.full packaging/systemd/*.service packaging/rpm/trident.spec packaging/selinux-policy-trident/* LICENSE NOTICE version-vars azl-version-vars +bin/trident-rpms-%.tar.gz: packaging/docker/Dockerfile.full packaging/etc/installer.toml packaging/systemd/*.service packaging/systemd/*/*.conf packaging/rpm/trident.spec packaging/selinux-policy-trident/* LICENSE NOTICE version-vars azl-version-vars @case "$@" in \ *$(DISTRO).tar.gz) ;; \ *) echo "Invalid target '$@' for DISTRO '$(DISTRO)'. Expected target ending in '$(DISTRO).tar.gz'."; exit 1 ;; \ @@ -262,7 +263,7 @@ bin/trident-rpms-%.tar.gz: packaging/docker/Dockerfile.full packaging/systemd/*. # backward compatibility; other distros use the in-container distro build. TRIDENT_RPM_BIN_DIR := $(if $(filter azl3,$(DISTRO)),target/release,target/$(DISTRO)/release) -bin/trident-rpms.tar.gz: azl-version-vars packaging/docker/Dockerfile.azl packaging/systemd/*.service packaging/rpm/trident.spec $(TRIDENT_RPM_BIN_DIR)/trident $(TRIDENT_RPM_BIN_DIR)/trident-acl-agent packaging/selinux-policy-trident/* LICENSE NOTICE +bin/trident-rpms.tar.gz: azl-version-vars packaging/docker/Dockerfile.azl packaging/etc/installer.toml packaging/systemd/*.service packaging/systemd/*/*.conf packaging/rpm/trident.spec $(TRIDENT_RPM_BIN_DIR)/trident $(TRIDENT_RPM_BIN_DIR)/trident-acl-agent $(TRIDENT_RPM_BIN_DIR)/trident-installer packaging/selinux-policy-trident/* LICENSE NOTICE @mkdir -p bin/ @if [ ! -f bin/trident ] || ! cmp -s $(TRIDENT_RPM_BIN_DIR)/trident bin/trident; then \ cp $(TRIDENT_RPM_BIN_DIR)/trident bin/trident; \ @@ -270,6 +271,9 @@ bin/trident-rpms.tar.gz: azl-version-vars packaging/docker/Dockerfile.azl packag @if [ ! -f bin/trident-acl-agent ] || ! cmp -s $(TRIDENT_RPM_BIN_DIR)/trident-acl-agent bin/trident-acl-agent; then \ cp $(TRIDENT_RPM_BIN_DIR)/trident-acl-agent bin/trident-acl-agent; \ fi + @if [ ! -f bin/trident-installer ] || ! cmp -s $(TRIDENT_RPM_BIN_DIR)/trident-installer bin/trident-installer; then \ + cp $(TRIDENT_RPM_BIN_DIR)/trident-installer bin/trident-installer; \ + fi @docker build -t trident/trident-build:latest \ --build-arg TRIDENT_VERSION="$(LOCAL_BUILD_TRIDENT_VERSION)" \ --build-arg RPM_VER="$(TRIDENT_CARGO_VERSION)" \ diff --git a/NOTICE b/NOTICE index bddc349267..edea8b7fdd 100644 --- a/NOTICE +++ b/NOTICE @@ -2651,6 +2651,35 @@ The `cfg_aliases!` macro uses a lot of the code from [`tectonic_cfg_support::tar -------------------------------------------------------------------------------- MIT License (MIT) +Used by: + - instability 0.3.10 + +# MIT License + +Copyright (c) 2020 Stephen M. Coakley +Copyright (c) The Ratatui Developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +-------------------------------------------------------------------------------- +MIT License (MIT) + Used by: - schemars_derive 0.8.21 @@ -3383,6 +3412,7 @@ Used by: - heck 0.5.0 - unicode-normalization 0.1.24 - unicode-segmentation 1.12.0 + - unicode-width 0.1.14 - unicode-width 0.2.0 - unicode-xid 0.2.6 @@ -4488,7 +4518,9 @@ DEALINGS IN THE SOFTWARE. MIT License (MIT) Used by: + - signal-hook 0.3.18 - signal-hook 0.4.3 + - signal-hook-mio 0.2.5 - signal-hook-registry 1.4.7 Copyright (c) 2017 tokio-jsonrpc developers @@ -4863,6 +4895,38 @@ DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- MIT License (MIT) +Used by: + - unicode-truncate 1.1.0 + +Copyright (c) 2019 Aetf + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + +-------------------------------------------------------------------------------- +MIT License (MIT) + Used by: - slab 0.4.9 @@ -5422,6 +5486,11 @@ Used by: - env_logger 0.10.2 - env_logger 0.11.5 - is_terminal_polyfill 1.70.1 + - serde_spanned 0.6.9 + - toml 0.8.23 + - toml_datetime 0.6.11 + - toml_edit 0.22.27 + - toml_write 0.1.2 Copyright (c) Individual contributors @@ -5705,6 +5774,34 @@ DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- MIT License (MIT) +Used by: + - lru 0.12.5 + +MIT License + +Copyright (c) 2016 Jerome Froelich + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +-------------------------------------------------------------------------------- +MIT License (MIT) + Used by: - textwrap 0.16.2 @@ -5874,6 +5971,34 @@ SOFTWARE. -------------------------------------------------------------------------------- MIT License (MIT) +Used by: + - static_assertions 1.1.0 + +MIT License + +Copyright (c) 2017 Nikolai Vazquez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +-------------------------------------------------------------------------------- +MIT License (MIT) + Used by: - gpt 4.1.0 @@ -6290,6 +6415,62 @@ SOFTWARE. -------------------------------------------------------------------------------- MIT License (MIT) +Used by: + - compact_str 0.8.2 + +MIT License + +Copyright (c) 2021 Parker Timmerman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +-------------------------------------------------------------------------------- +MIT License (MIT) + +Used by: + - castaway 0.2.4 + +MIT License + +Copyright (c) 2021 Stephen M. Coakley + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +-------------------------------------------------------------------------------- +MIT License (MIT) + Used by: - jsonptr 0.6.3 @@ -6613,6 +6794,34 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI -------------------------------------------------------------------------------- MIT License (MIT) +Used by: + - crossterm 0.28.1 + +MIT License + +Copyright (c) 2019 Timon + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +-------------------------------------------------------------------------------- +MIT License (MIT) + Used by: - jsonpath-rust 0.7.5 @@ -6660,6 +6869,7 @@ Used by: - linux-raw-sys 0.4.14 - once_cell 1.20.2 - parking 2.2.1 + - paste 1.0.15 - pest 2.7.14 - pest_derive 2.7.14 - pest_generator 2.7.14 @@ -6748,6 +6958,7 @@ MIT License (MIT) Used by: - systemd-journal-logger 2.2.2 + - winnow 0.7.15 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the @@ -7278,6 +7489,35 @@ SOFTWARE. -------------------------------------------------------------------------------- MIT License (MIT) +Used by: + - ratatui 0.29.0 + +The MIT License (MIT) + +Copyright (c) 2016-2022 Florian Dehau +Copyright (c) 2023-2024 The Ratatui Developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +-------------------------------------------------------------------------------- +MIT License (MIT) + Used by: - same-file 1.0.6 @@ -7553,6 +7793,34 @@ SOFTWARE. -------------------------------------------------------------------------------- MIT License (MIT) +Used by: + - cassowary 0.3.0 + +The MIT License (MIT) + +Copyright (c) 2016 Dylan Ede + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +-------------------------------------------------------------------------------- +MIT License (MIT) + Used by: - quick-xml 0.41.0 diff --git a/crates/installer/Cargo.toml b/crates/installer/Cargo.toml new file mode 100644 index 0000000000..e1be8c6fd3 --- /dev/null +++ b/crates/installer/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "installer" +version = "0.1.0" +edition = "2024" +rust-version = "1.85.0" +publish = false +license = "MIT" + +[[bin]] +name = "trident-installer" +path = "src/main.rs" + +[dependencies] +anyhow = { workspace = true } +clap = { workspace = true } +crossterm = { workspace = true } +env_logger = { workspace = true } +log = { workspace = true } +nix = { workspace = true, features = ["fs", "process", "term"] } +ratatui = { workspace = true, features = ["unstable-rendered-line-info"] } +regex = { workspace = true } +reqwest = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +serde_yaml = { workspace = true } +sha2 = { workspace = true } +tar = { workspace = true } +tokio = { workspace = true } +toml = { workspace = true } +url = { workspace = true } + +# Local Crate Dependencies +osutils = { path = "../osutils", features = ["run-interactive"] } +trident-client = { path = "../trident-client", features = ["preview"] } +trident_api = { path = "../trident_api" } + +[dev-dependencies] +indoc = { workspace = true } +tempfile = { workspace = true } diff --git a/crates/installer/README.md b/crates/installer/README.md new file mode 100644 index 0000000000..258ad31dd7 --- /dev/null +++ b/crates/installer/README.md @@ -0,0 +1,214 @@ +# Trident Linux Installer + +`installer` builds the `trident-installer` binary and optional RPM. It is an +autorun wrapper around Trident's gRPC API through the shared `trident-client` +crate, not a partitioning engine. + +See the [Installer reference](../../docs/Reference/Installer.md) for the +source-selection and screen flows. + +## Configuration + +Read `/etc/trident/installer.toml` or the path supplied with `--config`. +See the [Installer Configuration reference](../../docs/Reference/Installer-Configuration.md) +for all fields, defaults, and media-overlay rules. +`mode = "autorun"` is required and controls startup, not the servicing +operation: a Host Configuration selects Install; without one, the first media +COSI selects StreamDisk. All other fields are optional: + +```toml +mode = "autorun" +serialMode = "logs" +serialVerbosity = "debug" + +[media] +cosiDirectory = "cosi/" +# Optional: filesystemLabel = "CUSTOM_LABEL" +# Or use mountPath for already-mounted media. + +[autorun] +# If omitted, use /etc/trident/config.yaml when that file exists. +# hostConfiguration = "installer/host-configuration.yaml" +reboot = true +``` + +Unknown fields and conflicting media selectors are errors. `interactive` is +reserved for later work, not an alias for autorun. COSI directory paths must +stay beneath the media root. +`serialMode` defaults to `logs`. `ui` is reserved and currently rejected with +an error rather than showing an unfinished serial TUI. +`serialVerbosity` defaults to `debug` and accepts `off`, `error`, `warn`, +`info`, `debug`, and `trace`. + +`media.filesystemLabel` is a filesystem label, not a CD-ROM device name. When +omitted, the installer looks for either `TRD_INSTALL` (FAT-compatible, 11 +characters) or `CDROM` (Image Customizer's ISO label), and rejects ambiguity +if both are present. Set it explicitly for other labels or when booting from +an optical ISO alongside a separate installer USB. +The older `cdromLabel` key is accepted as an alias; setting both is an error. +Media is mounted read-only with filesystem auto-detection at +`/run/trident/installer-media`. Media discovery waits up to 60 seconds for +USB/BMC block-device enumeration when the Host Configuration or COSI depends +on media. A live-OS or HTTP(S) Host Configuration without media-backed inputs +skips discovery and media-local overrides; a symlink to media, +`installer://image`, or a file-backed HC input on media still waits. Explicit +remote Stream COSI recovery bypasses local media discovery, configuration +overlays, and COSI scanning, including when media is broken. +Other filesystem types require corresponding kernel mount support on the live +OS. Duplicate labels are rejected. Optional `installer/installer.toml` on the +mounted media can override mode, image directory, and autorun options, but not +bootstrap media discovery or `serialMode`. Relative HC paths are media-relative; +absolute paths and `file://` refer to the live filesystem. HTTP(S) HC sources +are supported. Remote connection and timeout failures are retried for at most +60 seconds while networking comes up; HTTP errors fail immediately. + +With an HC, use Install. Otherwise stream the first regular `.cosi` file in +the configured folder, sorted by filename, without recursing or following +image symlinks. Invalid HC or selected-image input is an error, not permission +to choose another operation or image. + +An HC can use the installer-only image reference: + +```yaml +image: + url: installer://image + sha384: ignored +``` + +The marker becomes the selected image's encoded `file://` URL before validation +and submission. Authored checksum settings are preserved. An explicit HC image +URL stays unchanged and needs no ISO image. Configure a checksum for production +images rather than copying the deliberately unverified example above. +HC disk paths are used as authored. The installer does not resolve legacy disk +placeholders or automatically choose a disk for an HC. + +## Console and recovery + +The UI uses the cyan Trident ASCII wordmark and the name Trident Linux +Installer. At 80x24 and larger the complete wordmark is shown; smaller terminals +use a compact text header to preserve usable controls and error details. + +On the ISO, `--system-console` uses the graphical virtual console for local +keyboard/monitor and BMC KVM, independent of `console=` order. With +`serialMode = "logs"`, active serial consoles receive only formatted installer +and gRPC logs, never a TUI, even when no graphical console exists. Autorun +continues without an interactive console; missing inputs and failures +emit an error and stop. +Failures to open or write a serial console are logged and mirroring to that +console stops; they do not stop installation. On boots with +`trident.installer=1`, the RPM's getty drop-ins prevent serial login prompts +from mixing with the log stream and prevent tty1 getty from taking input. +Serial mirrors are nonblocking; a console that cannot accept a record is +disabled rather than delaying installation or reboot. +Firmware, kernel and systemd output during boot is separate from the +installer's stream and may precede it; scrapers should match tagged log lines. + +No ordinary source picker or confirmation precedes autorun. Missing sources +and failures keep recent logs visible in a red result frame; `D` opens the +scrollable full error details and Esc returns to the logs. Successful installs +keep their logs in a green result frame. Each result is also the last highlighted +log entry. Continue opens recovery: Shell, +Stream COSI URL, remote HC URL, or Shutdown. Shell `exit` returns to the +originating screen; a nonzero shell exit is logged without changing the +installation result or reboot decision. The recovery shell is a root login +Bash, so it reads `/etc/profile` and the root profile (if present); on the installer ISO, +`/etc/profile` gives root a red prompt. The ISO service sets `TERM=linux` +for tty1 so terminal tools such as `clear` work in the shell. Installation +continues while a shell is open; automatic reboot waits. The success screen +offers Reboot and Shell. While servicing is active, Ctrl-C remains in the +installation menu and power actions are blocked. + +Only the installer enables `osutils`'s `run-interactive` feature. The recovery +shell gets the controlling TTY as stdin, stdout, and stderr and runs in its own +foreground process group so keyboard signals reach the shell rather than the +installer. After the shell exits, the installer reclaims the foreground group +and resumes the UI; a shell that reads before the handoff is continued once +it owns the TTY. + +Before each recovery attempt the baked configuration is reloaded, so shell +edits take effect. Invalid or missing configuration never supplies implicit +defaults for an installation. + +Display filtering never removes daemon log records. All received responses are +also appended to the private `/var/log/trident-installer.log`. HTTP(S) URLs in +received diagnostics have credentials, queries and fragments removed before +display, serial mirroring or installer-log persistence; Trident's own journal +is separate. Installer events and daemon records use +`MM:SS [INST:LEVEL] message` and +`MM:SS [TRIDENT:LEVEL] message`, respectively. `serialVerbosity` controls the +serial stream independently of TUI verbosity; each line of a multiline message +gets its own `MM:SS [SOURCE:LEVEL]` prefix. The TUI defaults to Debug: errors red, warnings +amber, INFO pale neutral, DEBUG steel gray and TRACE slate gray; INST labels +are muted slate and TRIDENT labels seafoam. The wordmark remains cyan and +success is green. On the graphical Linux virtual terminal, the installer +programs its 16 ANSI palette slots to A1 RGB values, then restores the +original palette when opening a shell or leaving the UI. Non-VT terminals use +the RGB values directly. +`V` opens a live verbosity picker (Off, +Error, Warn, Info, Debug, Trace) beside the operation; this only filters the +display, not serial or stored diagnostics. The private diagnostic file retains +all levels even when serialVerbosity filters them. PgUp/PgDn scroll by wrapped +terminal rows, keeping the latest result visible. +TRACE output can expose low-level inputs; restrict access to BMC serial captures. +A missing final Completed response means unknown +outcome, not success. Another write requires a successful Trident status query +establishing that the daemon is idle; power actions remain unavailable until +that check or a confirmed completion resolves the uncertain outcome. + +Autorun does not compare filesystem UUIDs or confirm repeat installations. +**An ISO left in the boot path can reimage the machine on every boot.** Remove +or deprioritize the media after installation. The former `autorun.force` key +is accepted for compatibility but ignored; interactive mode, where an operator +could confirm a repeat install, is not implemented yet. +Mounted or read-only potential stream targets are still refused. +For StreamDisk, the daemon checks the SHA-384 of the metadata inspected by +the installer before selecting the target disk; changed metadata stops the +operation instead of bypassing this safety check. +If the installer USB itself is the smallest disk fitting the COSI, streaming +stops rather than overwriting it; use a USB smaller than the COSI's original +disk size or an HC selecting an explicit target. The current StreamDisk RPC +cannot exclude a specific disk. +**HC installation also has no repeat-install guard:** the HC is +the operator's authority to overwrite its selected disks. Remove ISO media or +correct boot order to avoid repeated HC-driven installations. + +`autorun.reboot` defaults to true. Successful installations requiring reboot +show a short countdown, then reboot; false leaves the success screen. Errors, +unknown outcomes, and no-servicing results never +automatically reboot. + +## ISO integration + +On a full-OS installer ISO, install `trident-installer`, add +`trident.installer=1` to its **ISO kernel command line**, and provide a COSI +under `cosi/` or a Host Configuration. The RPM pulls in Trident and Bash for +the recovery shell, enables its service, starts the gRPC socket and waits for +udev from the running installer only on marked boots, and suppresses tty1 and +serial gettys on those boots. +Without that flag the service skips startup and normal gettys are unchanged, +including on an installed OS that happens to have the RPM. +Include optional tools in the ISO when the image or Host Configuration needs +them (for example, `veritysetup` for verity-enabled storage). + +Do not also enable `trident-install.service` or older autologin entrypoints. +The daemon must be built with `grpc-preview` for regular Install; repository +RPM builds enable it. For Image Customizer ISOs, `CDROM` is automatically +recognized; for GPT USB media, `TRD_INSTALL` is automatically recognized. +Specify `media.filesystemLabel` in the bootstrap TOML only to override those +labels or disambiguate multiple matching devices. With full-OS initramfs, +keep SELinux disabled and include USB storage/UAS, CD-ROM/SCSI, and USB +host-controller drivers. QEMU's IDE CD-ROM does not validate BMC virtual +media support. + +## Validation + +```console +cargo test -p installer +cargo test -p osutils terminal::tests +cargo clippy -p installer --all-targets --no-deps -- -D warnings +cargo fmt --all -- --check +``` + +Interactive disk-selection strategies and broader HC generation are follow-ups. +ISO boot, serial-terminal behaviour, RPM builds, and physical BMC virtual media +need separate integration validation. diff --git a/crates/installer/src/client.rs b/crates/installer/src/client.rs new file mode 100644 index 0000000000..b2e8d4376d --- /dev/null +++ b/crates/installer/src/client.rs @@ -0,0 +1,473 @@ +use std::borrow::Cow; + +use anyhow::{anyhow, bail, Error}; +use log::Level; +use tokio::{sync::mpsc::Sender, task}; + +use trident_client::{ + Client, ClientError, Completion as ClientCompletion, ExecutionState, RebootDisposition, + RebootPolicy, RemoteError, RemoteErrorCategory, ServicingEvent, ServicingKind, + ServicingOperation, ServicingState, Sha384Hash, +}; + +use crate::{ + config::{Config, SerialVerbosity, DEFAULT_HOST_CONFIGURATION}, + source::{self, Plan, Request}, +}; + +/// Messages passed from source preparation and the gRPC worker to the UI. +#[derive(Debug)] +pub(super) enum Event { + /// Installer or dependency log, before display and serial filtering. + InstallerLog { level: Level, message: String }, + /// A named preparation step while no daemon operation is active. + Preparing(String), + /// Current source and policy; sent again if media settings change them. + Prepared { + /// Display-safe source description; never include signed URL parameters. + description: String, + /// Caller-managed automatic reboot policy, not a daemon action. + reboot: bool, + /// Media settings may change which records reach serial. + serial_verbosity: SerialVerbosity, + }, + /// A domain event received from Trident, including its terminal result. + Response(ServicingEvent), + /// A status call established that an earlier uncertain write is no longer active. + IdleConfirmed, + /// `uncertain` keeps power actions blocked when Trident may still be writing. + Error { + details: String, + /// An ambiguous RPC or disconnected stream cannot prove Trident is idle. + uncertain: bool, + }, +} + +/// Interpreted daemon completion, separate from a broken or invalid response. +#[derive(Debug, PartialEq, Eq)] +pub(super) enum Completion { + /// `performed` prevents a no-op from triggering the installer's reboot countdown. + Success { + /// Reported by Trident; used only when the caller allows automatic reboot. + reboot_required: bool, + /// No-op completions must not claim an installation or trigger reboot. + performed: bool, + }, + /// Trident completed with a known failure, so the active-write guard can clear. + Failure(String), +} + +/// Interprets a domain completion, enforcing the installer's caller-managed reboot contract. +pub(super) fn completion( + outcome: Result, +) -> Result { + match outcome { + Ok(ClientCompletion { + reboot, + servicing_kind, + .. + }) => { + let reboot_required = match reboot { + RebootDisposition::NotRequired => false, + RebootDisposition::Required => true, + RebootDisposition::Started => { + bail!("Daemon did not honour caller-managed reboot: {reboot:?}") + } + _ => bail!("Unsupported daemon reboot disposition: {reboot:?}"), + }; + let performed = match servicing_kind { + None => true, + Some(ServicingKind::NoneRequired) => false, + Some( + ServicingKind::RuntimeUpdate + | ServicingKind::AbUpdate + | ServicingKind::CleanInstall + | ServicingKind::ManualRollbackAb + | ServicingKind::ManualRollbackRuntime, + ) => true, + Some(other) => bail!("Unsupported daemon servicing kind: {other:?}"), + }; + Ok(Completion::Success { + reboot_required, + performed, + }) + } + Err(error) => Ok(Completion::Failure(format_error(&error))), + } +} + +/// Renders a structured Trident error as readable multi-line diagnostics. +fn format_error(error: &RemoteError) -> String { + let category = match error.category { + RemoteErrorCategory::ExecutionEnvironmentMisconfiguration => { + Cow::Borrowed("Execution environment") + } + RemoteErrorCategory::HealthChecks => Cow::Borrowed("Health checks"), + RemoteErrorCategory::Initialization => Cow::Borrowed("Initialization"), + RemoteErrorCategory::Internal => Cow::Borrowed("Internal error"), + RemoteErrorCategory::InvalidInput => Cow::Borrowed("Invalid input"), + RemoteErrorCategory::Servicing => Cow::Borrowed("Servicing"), + RemoteErrorCategory::UnsupportedConfiguration => Cow::Borrowed("Unsupported configuration"), + RemoteErrorCategory::Unspecified => Cow::Borrowed("Unspecified"), + RemoteErrorCategory::Unknown(value) => Cow::Owned(format!("Unknown ({value})")), + other => Cow::Owned(format!("{other:?}")), + }; + let mut details = format!( + "{}\n\nCategory: {category}\nCode: {}", + error.message.trim(), + error.subkind + ); + if !error.error_message.is_empty() && !error.message.contains(&error.error_message) { + details.push_str(&format!("\nCause: {}", error.error_message)); + } + if let Some(location) = &error.location { + details.push_str(&format!("\nLocation: {}:{}", location.path, location.line)); + } + details +} + +/// Keeps invalid completions and unacknowledged writes uncertain, but not known remote failures. +fn operation_uncertain(error: &ClientError) -> bool { + error.remote_error().is_none() && error.execution_state() != ExecutionState::NotStarted +} + +/// Rejects unrecognized states before retrying an operation with an unknown prior outcome. +fn recognized_servicing_state(state: ServicingState) -> bool { + matches!( + state, + ServicingState::NotProvisioned + | ServicingState::CleanInstallStaged + | ServicingState::AbUpdateStaged + | ServicingState::ManualRollbackAbStaged + | ServicingState::ManualRollbackRuntimeStaged + | ServicingState::RuntimeUpdateStaged + | ServicingState::CleanInstallFinalized + | ServicingState::AbUpdateFinalized + | ServicingState::ManualRollbackAbFinalized + | ServicingState::Provisioned + | ServicingState::AbUpdateHealthCheckFailed + ) +} + +/// Describes the requested operation without exposing credentials in source URLs. +fn request_description(settings: &Config, request: &Request) -> String { + match request { + Request::Autorun => format!( + "Autorun: HC '{}' or first media COSI in '{}'", + source::display_source( + settings + .autorun + .host_configuration + .as_deref() + .unwrap_or(DEFAULT_HOST_CONFIGURATION) + ), + settings.media.cosi_directory.display() + ), + Request::HostConfiguration(url) => format!("Install from {}", source::display_source(url)), + Request::Stream(url) => format!("StreamDisk from {}", source::display_url(url)), + } +} + +/// Prepares a source, checks stream safety, and forwards Trident's domain events to the UI. +/// +/// After an uncertain previous operation, `require_idle` prevents a new write until the daemon +/// answers a status request. Ambiguous RPC failures are reported as uncertain instead of retrying. +pub(super) async fn execute( + settings: Config, + request: Request, + require_idle: bool, + tx: Sender, +) -> Result<(), Error> { + let description = request_description(&settings, &request); + send( + &tx, + Event::Prepared { + description, + reboot: settings.autorun.reboot, + serial_verbosity: settings.serial_verbosity, + }, + ) + .await?; + let progress = tx.clone(); + let prepared = task::spawn_blocking(move || { + source::prepare_with_progress(&settings, &request, |stage| { + progress + .blocking_send(Event::Preparing(stage.to_owned())) + .map_err(|_| anyhow!("Installer event receiver closed")) + }) + }) + .await?; + let (settings, plan) = match prepared { + Ok(prepared) => prepared, + Err(error) => { + return send( + &tx, + Event::Error { + details: format!("{error:#}"), + uncertain: require_idle, + }, + ) + .await + } + }; + send( + &tx, + Event::Prepared { + description: plan.description(), + reboot: settings.autorun.reboot, + serial_verbosity: settings.serial_verbosity, + }, + ) + .await?; + let stream_hash: Option = if let Plan::Stream { image } = &plan { + send( + &tx, + Event::Preparing("Checking image metadata and available disks".into()), + ) + .await?; + let image = image.clone(); + match task::spawn_blocking(move || source::stream_preflight(&image)).await? { + Ok(hash) => Some(hash), + Err(error) => { + return send( + &tx, + Event::Error { + details: format!("{error:#}"), + uncertain: false, + }, + ) + .await + } + } + } else { + None + }; + send(&tx, Event::Preparing("Connecting to Trident daemon".into())).await?; + let client = match Client::connect_default().await { + Ok(client) => client, + Err(error) => { + return send( + &tx, + Event::Error { + details: format!("{error:#}"), + uncertain: require_idle, + }, + ) + .await + } + }; + if require_idle { + match client.servicing_state().await { + Ok(state) if recognized_servicing_state(state) => { + send(&tx, Event::IdleConfirmed).await?; + } + Ok(state) => { + return send(&tx, Event::Error { + details: format!("The previous operation's outcome is unknown. Trident returned an unsupported servicing state {state:?}; refusing another write."), + uncertain: true, + }).await; + } + Err(error) => { + return send(&tx, Event::Error { + details: format!("The previous operation's outcome is unknown. Cannot establish that Trident is idle; refusing another write.\n{error}"), + uncertain: true, + }).await; + } + } + } + let response = match (plan, stream_hash) { + (Plan::Stream { image }, Some(hash)) => { + client + .stream_disk(&image, Some(&hash), RebootPolicy::Caller) + .await + } + (Plan::Install { config, .. }, None) => client.install(&config, RebootPolicy::Caller).await, + _ => { + return Err(anyhow!( + "Installer plan and preflight hash are inconsistent" + )) + } + }; + let response = match response { + Ok(response) => response, + Err(error) => { + return send( + &tx, + Event::Error { + details: format!("gRPC request failed: {error}"), + uncertain: operation_uncertain(&error), + }, + ) + .await; + } + }; + receive(response, &tx).await +} + +/// Forwards domain events until a completed result; a broken stream leaves the outcome unknown. +async fn receive(mut operation: ServicingOperation, tx: &Sender) -> Result<(), Error> { + loop { + let event = match operation.next_event().await { + Ok(Some(event)) => event, + Ok(None) => { + return send( + tx, + Event::Error { + details: "The gRPC stream ended without a final Completed response. Installation outcome is unknown; it may still be running.".into(), + uncertain: true, + }, + ) + .await; + } + Err(error) => { + return send( + tx, + Event::Error { + details: format!( + "The gRPC stream failed; installation outcome is unknown.\n{error}" + ), + uncertain: operation_uncertain(&error), + }, + ) + .await; + } + }; + let completed = matches!(event, ServicingEvent::Completed(_)); + send(tx, Event::Response(event)).await?; + if completed { + return Ok(()); + } + } +} + +/// Sends an installer event, returning an error if the UI receiver has closed. +pub(super) async fn send(tx: &Sender, event: Event) -> Result<(), Error> { + tx.send(event) + .await + .map_err(|_| anyhow!("Installer event receiver closed")) +} + +#[cfg(test)] +mod tests { + use super::*; + + use url::Url; + + use trident_client::SourceLocation; + + #[test] + /// Autorun and recovery descriptions must not disclose signed source URLs. + fn request_descriptions_redact_secrets() { + let url = "https://user:password@example.com/image.cosi?token=secret#fragment"; + let mut settings = Config::default(); + settings.autorun.host_configuration = Some(url.into()); + for request in [ + Request::Autorun, + Request::HostConfiguration(url.into()), + Request::Stream(Url::parse(url).unwrap()), + ] { + let description = request_description(&settings, &request); + assert!(description.contains("https://example.com/image.cosi")); + for secret in ["user", "password", "token=secret", "fragment"] { + assert!(!description.contains(secret), "{description}"); + } + } + } + + /// Builds a valid domain completion for installer-specific result checks. + fn successful() -> ClientCompletion { + ClientCompletion { + reboot: RebootDisposition::Required, + servicing_kind: Some(ServicingKind::CleanInstall), + image_hash: None, + } + } + + #[test] + /// Ensures caller-managed reboot and no-op completions retain their installer semantics. + fn final_response_is_strict() { + assert_eq!( + completion(Ok(successful())).unwrap(), + Completion::Success { + reboot_required: true, + performed: true, + } + ); + completion(Ok(ClientCompletion { + reboot: RebootDisposition::Started, + ..successful() + })) + .unwrap_err(); + assert_eq!( + completion(Ok(ClientCompletion { + servicing_kind: Some(ServicingKind::NoneRequired), + ..successful() + })) + .unwrap(), + Completion::Success { + reboot_required: true, + performed: false, + } + ); + completion(Ok(ClientCompletion { + servicing_kind: Some(ServicingKind::Unknown(42)), + ..successful() + })) + .unwrap_err(); + } + + /// Builds a structured remote failure for formatting and execution-state tests. + fn remote_failure() -> RemoteError { + RemoteError { + category: RemoteErrorCategory::Servicing, + subkind: "download-image".into(), + message: "Installation failed\n Failed to download the image".into(), + error_message: "Connection timed out".into(), + location: Some(SourceLocation { + path: "source.rs".into(), + line: 42, + }), + } + } + + #[test] + /// Ensures domain errors remain readable without protobuf debug output. + fn errors_are_readable_without_debug_dumps() { + let formatted = format_error(&remote_failure()); + assert!(formatted.contains("Installation failed\n Failed to download the image")); + assert!(formatted.contains("Category: Servicing")); + assert!(formatted.contains("Code: download-image")); + assert!(formatted.contains("Cause: Connection timed out")); + assert!(formatted.contains("Location: source.rs:42")); + assert!(!formatted.contains("TridentError {")); + assert!(!formatted.contains("\\n")); + assert_eq!( + completion(Err(remote_failure())).unwrap(), + Completion::Failure(formatted) + ); + let category = RemoteError { + category: RemoteErrorCategory::Unknown(42), + ..remote_failure() + }; + assert!(format_error(&category).contains("Category: Unknown (42)")); + } + + /// Connection errors cannot be mistaken for an accepted servicing request. + #[tokio::test] + async fn connection_errors_do_not_mark_a_write_uncertain() { + let error = Client::connect("not an endpoint").await.unwrap_err(); + assert_eq!(error.execution_state(), ExecutionState::NotStarted); + assert!(!operation_uncertain(&error)); + } + + #[test] + /// Unknown servicing states cannot clear the uncertainty of a previous write. + fn unknown_servicing_state_is_not_accepted_for_retry() { + assert!(recognized_servicing_state(ServicingState::NotProvisioned)); + assert!(recognized_servicing_state( + ServicingState::CleanInstallFinalized + )); + assert!(!recognized_servicing_state(ServicingState::Unspecified)); + assert!(!recognized_servicing_state(ServicingState::Unknown(42))); + } +} diff --git a/crates/installer/src/config.rs b/crates/installer/src/config.rs new file mode 100644 index 0000000000..03ba4d970f --- /dev/null +++ b/crates/installer/src/config.rs @@ -0,0 +1,450 @@ +use std::{ + fs, + io::ErrorKind, + path::{Component, Path, PathBuf}, +}; + +use anyhow::{bail, ensure, Context, Error}; +use log::LevelFilter; +use serde::{Deserialize, Serialize}; +use toml::Value as TomlValue; + +/// Bootstrap TOML packaged with the installer RPM. +pub(super) const DEFAULT_CONFIG: &str = "/etc/trident/installer.toml"; +/// Fallback Host Configuration when no explicit source is configured. +pub(super) const DEFAULT_HOST_CONFIGURATION: &str = "/etc/trident/config.yaml"; +/// Optional settings layered from the selected installation media. +pub(super) const MEDIA_CONFIG: &str = "installer/installer.toml"; +/// Read-only mount for media selected by filesystem label. +pub(super) const MEDIA_MOUNT: &str = "/run/trident/installer-media"; +/// FAT-compatible label for installer USB partitions. +pub(super) const DEFAULT_MEDIA_LABEL: &str = "TRD_INSTALL"; +/// Also recognize the ISO label emitted by Image Customizer. +pub(super) const DEFAULT_MEDIA_LABELS: &[&str] = &[DEFAULT_MEDIA_LABEL, "CDROM"]; + +/// Bootstrap settings merged with media-local overrides when the install needs media. +#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, Eq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct Config { + /// Startup mode; only autorun is implemented. + pub mode: Mode, + /// Serial consoles mirror logs, not the interactive UI. + #[serde(default)] + pub serial_mode: SerialMode, + /// Filters serial output independently of the on-screen log filter. + #[serde(default)] + pub serial_verbosity: SerialVerbosity, + /// How to find and scan installation media. + #[serde(default)] + pub media: Media, + /// Source and reboot policy for unattended startup. + #[serde(default)] + pub autorun: Autorun, +} + +/// Interactive source selection is reserved; recovery remains available after autorun. +#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, Eq)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +pub(super) enum Mode { + #[default] + Autorun, + /// Reserved; `require_autorun` rejects it until source selection is implemented. + Interactive, +} + +/// The serial UI variant is reserved so it cannot silently enable an unfinished feature. +#[derive(Serialize, Deserialize, Debug, Default, Clone, Copy, PartialEq, Eq)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +pub(super) enum SerialMode { + #[default] + Logs, + /// Reserved; a serial TUI is not implemented. + Ui, +} + +/// Limits serial records without dropping them from the private diagnostic log. +#[derive(Serialize, Deserialize, Debug, Default, Clone, Copy, PartialEq, Eq)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +pub(super) enum SerialVerbosity { + Off, + Error, + Warn, + Info, + #[default] + Debug, + Trace, +} + +impl SerialVerbosity { + /// Maps the serialized level to a serial filter without changing retained records. + pub(super) fn filter(self) -> LevelFilter { + match self { + Self::Off => LevelFilter::Off, + Self::Error => LevelFilter::Error, + Self::Warn => LevelFilter::Warn, + Self::Info => LevelFilter::Info, + Self::Debug => LevelFilter::Debug, + Self::Trace => LevelFilter::Trace, + } + } +} + +/// Locate media by label or use an existing mount; only one selector may be set. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct Media { + /// Overrides automatic discovery of the USB and ISO labels. + #[serde(default, alias = "cdromLabel", skip_serializing_if = "Option::is_none")] + pub filesystem_label: Option, + /// Already-mounted media, never mounted again by label discovery. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mount_path: Option, + /// Relative directory containing directly selectable COSI files. + #[serde(default = "default_cosi_directory")] + pub cosi_directory: PathBuf, +} + +impl Default for Media { + /// Leaves media discovery on the default label and searches the `cosi/` directory. + fn default() -> Self { + Self { + filesystem_label: None, + mount_path: None, + cosi_directory: default_cosi_directory(), + } + } +} + +fn default_cosi_directory() -> PathBuf { + "cosi".into() +} + +/// Picks a Host Configuration before falling back to a COSI, then handles reboot. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct Autorun { + /// Local, remote, or media-relative YAML source; absent uses the live-OS fallback. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub host_configuration: Option, + /// Reboot only if Trident reports completed work that requires it. + #[serde(default = "default_reboot")] + pub reboot: bool, + /// Accepted for compatibility with older installer media; autorun does not check UUIDs. + #[serde(default)] + pub force: bool, +} + +impl Default for Autorun { + /// Enables reboot after a successful install. + fn default() -> Self { + Self { + host_configuration: None, + reboot: default_reboot(), + force: false, + } + } +} + +fn default_reboot() -> bool { + true +} + +impl Config { + /// Reads and validates the bootstrap installer configuration from disk. + pub(super) fn read(path: impl AsRef) -> Result { + let path = path.as_ref(); + let text = fs::read_to_string(path).with_context(|| { + format!( + "Failed to read installer configuration '{}'", + path.display() + ) + })?; + Self::parse(&text) + } + + /// Parses installer TOML, rejecting unknown fields and unsupported settings. + pub(super) fn parse(text: &str) -> Result { + let config: Self = toml::from_str(text).context("Invalid installer TOML configuration")?; + config.validate()?; + Ok(config) + } + + /// Checks media paths, source fields, and the reserved serial UI mode. + fn validate(&self) -> Result<(), Error> { + ensure!( + self.serial_mode == SerialMode::Logs, + "serialMode = \"ui\" is not implemented yet; use \"logs\"" + ); + ensure!( + self.media.filesystem_label.is_none() || self.media.mount_path.is_none(), + "media.filesystemLabel and media.mountPath are mutually exclusive" + ); + if let Some(label) = &self.media.filesystem_label { + ensure!( + !label.trim().is_empty(), + "media.filesystemLabel must not be empty" + ); + } + if let Some(path) = &self.media.mount_path { + ensure!(path.is_absolute(), "media.mountPath must be absolute"); + } + ensure!( + !self.media.cosi_directory.as_os_str().is_empty() + && self.media.cosi_directory.components().all(|component| { + matches!(component, Component::Normal(_) | Component::CurDir) + }), + "media.cosiDirectory must be a nonempty relative path beneath the media root" + ); + if let Some(source) = &self.autorun.host_configuration { + ensure!( + !source.trim().is_empty(), + "autorun.hostConfiguration must not be empty" + ); + } + Ok(()) + } + + /// Rejects interactive mode until interactive source selection is implemented. + pub(super) fn require_autorun(&self) -> Result<(), Error> { + ensure!( + self.mode == Mode::Autorun, + "Interactive installation is not implemented yet; choose mode = \"autorun\"" + ); + Ok(()) + } + + /// Applies an optional media-local config without allowing bootstrap media or serial changes. + pub(super) fn overlay(&self, root: impl AsRef) -> Result { + let path = root.as_ref().join(MEDIA_CONFIG); + let text = match fs::read_to_string(&path) { + Ok(text) => text, + Err(error) if error.kind() == ErrorKind::NotFound => return Ok(self.clone()), + Err(error) => { + return Err(error).with_context(|| format!("Failed to read '{}'", path.display())) + } + }; + let overlay: TomlValue = toml::from_str(&text) + .with_context(|| format!("Invalid media configuration '{}'", path.display()))?; + ensure!( + overlay.get("serialMode").is_none(), + "Media configuration cannot change bootstrap serialMode" + ); + if let Some(media) = overlay.get("media") { + ensure!( + media.get("filesystemLabel").is_none() + && media.get("cdromLabel").is_none() + && media.get("mountPath").is_none(), + "Media configuration cannot change bootstrap filesystemLabel or mountPath" + ); + } + let mut base = TomlValue::try_from(self)?; + merge(&mut base, overlay); + let config: Self = base.try_into()?; + config.validate()?; + Ok(config) + } +} + +/// Recursively overlays TOML tables; non-table values replace their base values. +fn merge(base: &mut TomlValue, overlay: TomlValue) { + match (base, overlay) { + (TomlValue::Table(base), TomlValue::Table(overlay)) => { + for (key, value) in overlay { + match base.get_mut(&key) { + Some(base_value) => merge(base_value, value), + None => { + base.insert(key, value); + } + } + } + } + (base, overlay) => *base = overlay, + } +} + +/// Lists regular `.cosi` files directly beneath the media directory in name order. +/// +/// Rejects directories that resolve outside the media root; an absent directory yields no images. +pub(super) fn discover_images( + root: impl AsRef, + directory: impl AsRef, +) -> Result, Error> { + let root = root + .as_ref() + .canonicalize() + .context("Failed to resolve media root")?; + let directory = root.join(directory); + let entries = match fs::read_dir(&directory) { + Ok(entries) => entries, + Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Vec::new()), + Err(error) => { + return Err(error).with_context(|| format!("Failed to scan '{}'", directory.display())) + } + }; + ensure!( + directory.canonicalize()?.starts_with(&root), + "COSI directory escapes the media root" + ); + let mut images = Vec::new(); + for entry in entries { + let entry = entry?; + let path = entry.path(); + if entry.file_type()?.is_file() + && path + .extension() + .is_some_and(|extension| extension == "cosi") + { + images.push(path); + } + } + images.sort(); + Ok(images) +} + +/// Selects the sole media device, or fails rather than guessing between duplicate labels. +pub(super) fn choose_media(devices: &[PathBuf]) -> Result, Error> { + match devices { + [] => Ok(None), + [device] => Ok(Some(device.as_path())), + _ => bail!("Multiple devices match the installer media label: {devices:?}"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use std::os::unix::fs as unix_fs; + + use indoc::indoc; + use tempfile::TempDir; + + #[test] + /// Ensures mode is required and omitted settings keep their safe defaults. + fn explicit_mode_and_strict_fields() { + Config::parse("").unwrap_err(); + Config::parse("mode = 'autorun'\nunknown = true").unwrap_err(); + let config = Config::parse("mode = 'autorun'").unwrap(); + assert_eq!(config.serial_mode, SerialMode::Logs); + assert_eq!(config.serial_verbosity, SerialVerbosity::Debug); + assert!(config.autorun.reboot); + assert!(!config.autorun.force); + assert_eq!(config.media.cosi_directory, Path::new("cosi")); + assert_eq!(DEFAULT_MEDIA_LABEL.len(), 11); + Config::parse("mode = 'interactive'") + .unwrap() + .require_autorun() + .unwrap_err(); + } + + #[test] + /// Older media can still specify the now-ignored force flag. + fn legacy_force_setting_remains_compatible() { + let config = Config::parse("mode = 'autorun'\n[autorun]\nforce = true").unwrap(); + assert!(config.autorun.force); + let config = Config::parse("mode = 'autorun'\n[autorun]\nforce = false").unwrap(); + assert!(!config.autorun.force); + Config::parse("mode = 'autorun'\n[autorun]\nforce = 'yes'").unwrap_err(); + } + + #[test] + /// Ensures the reserved serial UI mode fails validation instead of being enabled. + fn serial_ui_mode_is_reserved_not_silently_enabled() { + Config::parse("mode = 'autorun'\nserialMode = 'logs'").unwrap(); + let error = Config::parse("mode = 'autorun'\nserialMode = 'ui'").unwrap_err(); + assert!(error.to_string().contains("not implemented"), "{error:#}"); + } + + #[test] + /// Ensures serial verbosity defaults to debug and invalid levels are rejected. + fn serial_verbosity_defaults_to_debug_and_rejects_invalid_levels() { + let config = Config::parse("mode = 'autorun'\nserialVerbosity = 'trace'").unwrap(); + assert_eq!(config.serial_verbosity.filter(), LevelFilter::Trace); + let config = Config::parse("mode = 'autorun'\nserialVerbosity = 'off'").unwrap(); + assert_eq!(config.serial_verbosity.filter(), LevelFilter::Off); + Config::parse("mode = 'autorun'\nserialVerbosity = 'verbose'").unwrap_err(); + } + + #[test] + /// Ensures the shipped TOML stays compatible with the runtime schema. + fn packaged_configuration_matches_the_runtime_schema() { + let config = Config::parse(include_str!("../../../packaging/etc/installer.toml")).unwrap(); + config.require_autorun().unwrap(); + assert!(config.media.filesystem_label.is_none()); + assert_eq!(DEFAULT_MEDIA_LABELS, ["TRD_INSTALL", "CDROM"]); + assert!(config.autorun.reboot); + } + + #[test] + /// Ensures media selectors are exclusive and the image directory stays relative. + fn media_selector_and_path_validation() { + Config::parse(indoc! {" + mode = 'autorun' + [media] + filesystemLabel = 'TEST' + mountPath = '/media' + "}) + .unwrap_err(); + for directory in ["/cosi", "../cosi", "cosi/../../outside", ""] { + Config::parse(&format!( + "mode = 'autorun'\n[media]\ncosiDirectory = '{directory}'" + )) + .unwrap_err(); + } + Config::parse("mode = 'autorun'\n[media]\nmountPath = '/media'").unwrap(); + choose_media(&[PathBuf::from("/dev/sr0"), PathBuf::from("/dev/sr1")]).unwrap_err(); + } + + #[test] + /// Ensures image discovery is sorted, nonrecursive, and excludes symlinks. + fn catalog_is_sorted_nonrecursive_and_ignores_symlinks() { + let root = TempDir::new().unwrap(); + let directory = root.path().join("cosi"); + fs::create_dir(&directory).unwrap(); + for filename in ["z.cosi", "a.cosi", "readme.txt"] { + fs::write(directory.join(filename), "").unwrap(); + } + fs::create_dir(directory.join("nested")).unwrap(); + fs::write(directory.join("nested/hidden.cosi"), "").unwrap(); + unix_fs::symlink(directory.join("z.cosi"), directory.join("0.cosi")).unwrap(); + assert_eq!( + discover_images(root.path(), "cosi").unwrap(), + [directory.join("a.cosi"), directory.join("z.cosi")] + ); + } + + #[test] + /// Ensures media overlays cannot change bootstrap settings or discard defaults. + fn media_overlay_preserves_defaults_and_bootstrap() { + let root = TempDir::new().unwrap(); + fs::create_dir(root.path().join("installer")).unwrap(); + let path = root.path().join(MEDIA_CONFIG); + fs::write(&path, "[autorun]\nreboot = false\nforce = true").unwrap(); + let config = Config::parse("mode = 'autorun'") + .unwrap() + .overlay(root.path()) + .unwrap(); + assert!(!config.autorun.reboot); + assert!(config.autorun.force); + assert_eq!(config.media.cosi_directory, Path::new("cosi")); + fs::write(&path, "[media]\nfilesystemLabel = 'OTHER'").unwrap(); + config.overlay(root.path()).unwrap_err(); + fs::write(&path, "[media]\ncdromLabel = 'OTHER'").unwrap(); + config.overlay(root.path()).unwrap_err(); + fs::write(&path, "serialMode = 'ui'").unwrap(); + config.overlay(root.path()).unwrap_err(); + } + + #[test] + /// Ensures the former CD-ROM key maps to the filesystem-label setting. + fn legacy_cdrom_label_alias_still_mounts_the_same_filesystem() { + let legacy = Config::parse("mode = 'autorun'\n[media]\ncdromLabel = 'CDROM'").unwrap(); + let generic = + Config::parse("mode = 'autorun'\n[media]\nfilesystemLabel = 'CDROM'").unwrap(); + assert_eq!(legacy, generic); + Config::parse( + "mode = 'autorun'\n[media]\ncdromLabel = 'CDROM'\nfilesystemLabel = 'TRD_INSTALL'", + ) + .unwrap_err(); + } +} diff --git a/crates/installer/src/main.rs b/crates/installer/src/main.rs new file mode 100644 index 0000000000..72c3fc6bdf --- /dev/null +++ b/crates/installer/src/main.rs @@ -0,0 +1,193 @@ +use std::{ + fs::{self, OpenOptions, Permissions}, + io::{self, IsTerminal, Write}, + os::unix::fs::{OpenOptionsExt, PermissionsExt}, + path::PathBuf, + process::ExitCode, + sync::OnceLock, +}; + +use anyhow::{Context, Error}; +use clap::Parser; +use log::{warn, LevelFilter, Record}; +use tokio::runtime::Builder; +use tokio::sync::mpsc::UnboundedSender; + +use osutils::systemd; + +use crate::{client::Event, config::DEFAULT_CONFIG, ui::Output}; + +mod client; +mod config; +mod source; +mod terminal; +mod ui; + +/// Append-only diagnostic log; unlike the display, it keeps full event details. +const LOG_PATH: &str = "/var/log/trident-installer.log"; +/// Restricts diagnostic records that may contain configuration details. +const PRIVATE_FILE_MODE: u32 = 0o600; +/// Leaves a runtime worker available while another drives a servicing request. +const WORKER_THREADS: usize = 2; +/// One name for the command help and console header. +const APPLICATION_NAME: &str = "Trident Linux Installer"; +/// The logger forwards records here after the UI starts; earlier records use stderr. +static INSTALLER_LOG_TX: OnceLock> = OnceLock::new(); + +/// Bootstrap options; installation details come from installer TOML and the Host Configuration. +#[derive(Debug, Parser)] +#[command( + name = "trident-installer", + version, + about = APPLICATION_NAME +)] +struct Args { + /// Path to installer TOML, not the Host Configuration YAML. + #[arg(long, default_value = DEFAULT_CONFIG)] + config: PathBuf, + /// Show line-oriented output instead of the full-screen UI. + #[arg(long)] + plain: bool, + /// Claim the ISO console and mirror log records to active serial consoles. + #[arg(long)] + system_console: bool, +} + +/// Starts logging and the installer runtime, returning a failing exit code on startup errors. +fn main() -> ExitCode { + let stderr_is_terminal = io::stderr().is_terminal(); + env_logger::Builder::from_default_env() + .filter_level(LevelFilter::Info) + .filter_module("installer", LevelFilter::Trace) + .filter_module("osutils", LevelFilter::Trace) + .format(move |buf, record| { + format_log_record(buf, record, INSTALLER_LOG_TX.get(), stderr_is_terminal) + }) + .init(); + let args = Args::parse(); + let result = Builder::new_multi_thread() + .worker_threads(WORKER_THREADS) + .enable_all() + .build() + .context("Failed to create installer async runtime") + .and_then(|runtime| runtime.block_on(run(args))); + match result { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("Installer failed: {error:#}"); + ExitCode::FAILURE + } + } +} + +/// Keeps terminal-bound logs in Ratatui while retaining startup and journal diagnostics. +fn format_log_record( + output: &mut impl Write, + record: &Record<'_>, + log_tx: Option<&UnboundedSender>, + stderr_is_terminal: bool, +) -> io::Result<()> { + let message = record.args().to_string(); + if let Some(tx) = log_tx { + if tx + .send(Event::InstallerLog { + level: record.level(), + message: message.clone(), + }) + .is_ok() + { + if stderr_is_terminal { + return Ok(()); + } + } else { + writeln!( + output, + "Installer log receiver unavailable; entry retained in journal" + )?; + } + } + writeln!( + output, + "[{} {}] {}", + record.level(), + record.target(), + message + ) +} + +/// Sets up private diagnostics and optional console ownership before starting the UI. +async fn run(args: Args) -> Result<(), Error> { + let mut linux_vt = false; + let mut output = Output { + log: None, + mirrors: Vec::new(), + }; + output.log = Some( + OpenOptions::new() + .create(true) + .append(true) + .mode(PRIVATE_FILE_MODE) + .open(LOG_PATH) + .context("Failed to open private installer diagnostic log; run as root")?, + ); + fs::set_permissions(LOG_PATH, Permissions::from_mode(PRIVATE_FILE_MODE))?; + if args.system_console { + systemd::start_unit("tridentd.socket")?; + systemd::start_unit("systemd-udev-settle.service")?; + let consoles = terminal::active_consoles()?; + if let Some(graphical) = consoles.iter().find(|path| path.ends_with("tty1")) { + systemd::stop_unit("getty@tty1.service")?; + let _terminal = terminal::attach(graphical)?; + linux_vt = true; + } + for path in consoles.iter().filter(|path| !path.ends_with("tty1")) { + match terminal::open_nonblocking_console(path) { + Ok(terminal) => output.mirrors.push((path.clone(), terminal)), + Err(error) => warn!("Could not mirror status to '{}': {error}", path.display()), + } + } + } + ui::run(args.config, args.plain, linux_vt, output).await +} + +#[cfg(test)] +mod tests { + use super::*; + + use log::Level; + use tokio::sync::mpsc; + + #[test] + fn terminal_logs_use_ui_events_while_journal_and_startup_logs_remain_visible() { + let record = Record::builder() + .args(format_args!("Installer progress")) + .level(Level::Info) + .target("installer") + .build(); + let (tx, mut rx) = mpsc::unbounded_channel(); + let mut output = Vec::new(); + format_log_record(&mut output, &record, Some(&tx), true).unwrap(); + assert!(output.is_empty()); + assert!(matches!( + rx.try_recv().unwrap(), + Event::InstallerLog { + level: Level::Info, + message + } if message == "Installer progress" + )); + + format_log_record(&mut output, &record, Some(&tx), false).unwrap(); + assert_eq!(output, b"[INFO installer] Installer progress\n"); + output.clear(); + + format_log_record(&mut output, &record, None, true).unwrap(); + assert_eq!(output, b"[INFO installer] Installer progress\n"); + output.clear(); + + drop(rx); + format_log_record(&mut output, &record, Some(&tx), true).unwrap(); + assert!(String::from_utf8(output) + .unwrap() + .contains("Installer log receiver unavailable")); + } +} diff --git a/crates/installer/src/source.rs b/crates/installer/src/source.rs new file mode 100644 index 0000000000..97748b24b0 --- /dev/null +++ b/crates/installer/src/source.rs @@ -0,0 +1,1178 @@ +use std::{ + fs::{self, File}, + io::{ErrorKind, Read}, + path::{Path, PathBuf}, + sync::OnceLock, + thread, + time::{Duration, Instant}, +}; + +use anyhow::{anyhow, bail, ensure, Context, Error}; +use log::warn; +use regex::{Captures, Regex}; +use reqwest::blocking::Client; +use serde::{de::IgnoredAny, Deserialize}; +use sha2::{Digest, Sha384}; +use tar::Archive; +use url::Url; + +use osutils::{ + filesystems::MountFileSystemType, + findmnt::FindMnt, + lsblk::{self, BlockDevice, BlockDeviceType}, + mount, mountpoint, +}; +use trident_api::{ + config::{Check, HostConfiguration, Script, ScriptSource}, + constants::MOUNT_OPTION_READ_ONLY, + primitives::hash::Sha384Hash, +}; + +use crate::config::{self, Config}; + +/// Host Configuration image reference replaced with the first selected media COSI. +pub(super) const IMAGE_MARKER: &str = "installer://image"; +/// Maximum time for one HTTP source request. +const SOURCE_TIMEOUT: Duration = Duration::from_secs(30); +/// Overall window for transient connection and request-timeout retries. +const REMOTE_RETRY_TIMEOUT: Duration = Duration::from_secs(60); +/// Pause between remote source retries while networking starts. +const REMOTE_RETRY_INTERVAL: Duration = Duration::from_secs(2); +/// Allow time for late USB or BMC virtual-media enumeration. +const MEDIA_DISCOVERY_TIMEOUT: Duration = Duration::from_secs(60); +/// Recheck labelled block devices while awaiting media. +const MEDIA_POLL_INTERVAL: Duration = Duration::from_secs(2); +/// Reject oversized YAML before deserializing a Host Configuration. +const MAX_HOST_CONFIGURATION_BYTES: u64 = 2 * 1024 * 1024; +/// Bound the archive scan and the metadata entry read during preflight. +const MAX_METADATA_BYTES: u64 = 16 * 1024 * 1024; +/// Trident's COSI metadata member name. +const METADATA_PATH: &str = "metadata.json"; +/// Match the disk-name families StreamDisk may choose as a target. +const STREAM_DISK_PREFIXES: &[&str] = &["sd", "nvme", "vd", "hd", "mmcblk"]; + +/// Initial autorun or a manually chosen recovery source. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum Request { + /// Select a Host Configuration or COSI from the configured sources. + Autorun, + /// Remote Host Configuration URL entered on the recovery screen. + HostConfiguration(String), + /// Remote COSI URL entered on the recovery screen. + Stream(Url), +} + +/// Fully selected servicing operation passed to the gRPC worker. +#[derive(Debug, Clone)] +pub(super) enum Plan { + /// Validated Host Configuration and its original diagnostic source. + Install { + /// `installer://image`, if present, has already been resolved. + config: Box, + /// Original source reference; redact URL credentials before display. + source: String, + }, + /// Image URL retained for preflight and the daemon's subsequent fetch. + Stream { + /// May contain signed query parameters, so never log it raw. + image: Url, + }, +} + +impl Plan { + /// Describes the selected source for the progress window. + pub(super) fn description(&self) -> String { + match self { + Self::Install { source, .. } => format!("Install from {}", display_source(source)), + Self::Stream { image } => format!("StreamDisk from {}", display_url(image)), + } + } +} + +/// Removes URL credentials and signed query data from diagnostic source names. +pub(super) fn display_url(source: &Url) -> String { + let mut url = source.clone(); + if (url.password().is_some() && url.set_password(None).is_err()) + || (!url.username().is_empty() && url.set_username("").is_err()) + { + return "".into(); + } + url.set_query(None); + url.set_fragment(None); + url.to_string() +} + +/// Preserves local path descriptions without exposing URL secrets. +pub(super) fn display_source(source: &str) -> String { + match Url::parse(source) { + Ok(url) => display_url(&url), + Err(_) if source.contains("://") => "".into(), + Err(_) => source.to_owned(), + } +} + +/// Removes credentials and signed query data from URLs embedded in diagnostics. +pub(super) fn redact_message_urls(message: &str) -> String { + /// Share the URL pattern across diagnostic records instead of recompiling it. + static URLS: OnceLock = OnceLock::new(); + let urls = URLS.get_or_init(|| { + Regex::new(r#"(?i)https?://[^\s"<>]+"#).expect("invariant: diagnostic URL pattern is valid") + }); + urls.replace_all(message, |capture: &Captures<'_>| { + let matched = capture + .get(0) + .expect("invariant: entire URL match") + .as_str(); + let url = matched.trim_end_matches(['.', ',', ')', ']', ';', '\'']); + let suffix = &matched[url.len()..]; + let description = Url::parse(url) + .map(|url| display_url(&url)) + .unwrap_or_else(|_| "".into()); + format!("{description}{suffix}") + }) + .into_owned() +} + +/// Resolves installation media and returns an install or stream plan with progress callbacks. +/// +/// Only autorun waits for media enumeration; explicit recovery sources proceed immediately. +pub(super) fn prepare_with_progress( + settings: &Config, + request: &Request, + mut progress: impl FnMut(&str) -> Result<(), Error>, +) -> Result<(Config, Plan), Error> { + if matches!(request, Request::Stream(_)) { + return prepare_from_media_with_progress(settings, request, None, &mut progress); + } + if request == &Request::Autorun { + settings.require_autorun()?; + if let Some(plan) = self_contained_install(settings, &mut progress)? { + return Ok((settings.clone(), plan)); + } + } + let root = media_root(settings, request == &Request::Autorun, &mut progress)?; + prepare_from_media_with_progress(settings, request, root.as_deref(), &mut progress) +} + +/// Treats a complete live-OS or remote Host Configuration as authoritative. +/// +/// `None` means it or another file-backed input may need media and its overlay. +fn self_contained_install( + settings: &Config, + progress: &mut impl FnMut(&str) -> Result<(), Error>, +) -> Result, Error> { + let Some(source) = configured_host_configuration_source(settings)? else { + return Ok(None); + }; + if !source.starts_with('/') && !source.contains("://") { + return Ok(None); + } + let url = source_url(&source, None)?; + if file_source_may_need_media(&url, settings)? { + return Ok(None); + } + progress("Checking Host Configuration")?; + let text = read_text(&url)?; + let config: HostConfiguration = + serde_yaml::from_str(&text).context("Invalid Host Configuration YAML")?; + if host_configuration_needs_media(&config, settings)? { + return Ok(None); + } + let config = resolve_parsed_host_configuration(config, None)?; + Ok(Some(Plan::Install { + config: Box::new(config), + source, + })) +} + +/// Checks file-backed HC inputs that Trident may need from the installer mount. +fn host_configuration_needs_media( + config: &HostConfiguration, + settings: &Config, +) -> Result { + if let Some(image) = &config.image { + if image.url.as_str() == IMAGE_MARKER || file_source_may_need_media(&image.url, settings)? { + return Ok(true); + } + } + if let Some(key) = config + .storage + .encryption + .as_ref() + .and_then(|encryption| encryption.recovery_key_url.as_ref()) + { + if file_source_may_need_media(key, settings)? { + return Ok(true); + } + } + for extension in config.os.sysexts.iter().chain(&config.os.confexts) { + if file_source_may_need_media(&extension.url, settings)? { + return Ok(true); + } + } + for file in &config.os.additional_files { + if let Some(path) = &file.source { + if path_may_need_media(path, settings)? { + return Ok(true); + } + } + } + let scripts = config + .scripts + .pre_servicing + .iter() + .chain(&config.scripts.post_provision) + .chain(&config.scripts.post_configure) + .chain(config.health.checks.iter().filter_map(|check| match check { + Check::Script(script) => Some(script), + Check::SystemdCheck(_) => None, + })); + for script in scripts { + if script_needs_media(script, settings)? { + return Ok(true); + } + } + Ok(false) +} + +/// Checks typed script paths; shell contents and arbitrary arguments cannot be inspected. +fn script_needs_media(script: &Script, settings: &Config) -> Result { + if let ScriptSource::Path(path) = &script.source { + if path_may_need_media(path, settings)? { + return Ok(true); + } + } + if let Some(interpreter) = &script.interpreter { + if path_may_need_media(interpreter, settings)? { + return Ok(true); + } + } + Ok(false) +} + +/// A missing path behind a symlink may become readable only after installer media is mounted. +fn file_source_may_need_media(url: &Url, settings: &Config) -> Result { + if url.scheme() != "file" { + return Ok(false); + } + let path = url + .to_file_path() + .map_err(|()| anyhow!("Invalid local file URL"))?; + path_may_need_media(&path, settings) +} + +/// A missing path behind any symlink may become readable after mounting late media. +fn path_may_need_media(path: &Path, settings: &Config) -> Result { + let media = settings + .media + .mount_path + .as_deref() + .unwrap_or(Path::new(config::MEDIA_MOUNT)); + if path.starts_with(media) { + return Ok(true); + } + match path.canonicalize() { + Ok(resolved) => Ok(resolved.starts_with(media)), + Err(error) if error.kind() == ErrorKind::NotFound => { + let mut ancestor = PathBuf::new(); + for component in path.components() { + ancestor.push(component); + match fs::symlink_metadata(&ancestor) { + Ok(metadata) if metadata.file_type().is_symlink() => return Ok(true), + Ok(_) => {} + Err(error) if error.kind() == ErrorKind::NotFound => break, + Err(error) => { + return Err(error) + .with_context(|| format!("Failed to inspect '{}'", ancestor.display())) + } + } + } + Ok(false) + } + Err(error) => Err(error).with_context(|| format!("Failed to resolve '{}'", path.display())), + } +} + +/// Keeps dangling default Host Configuration symlinks eligible for media-dependent installs. +fn configured_host_configuration_source(settings: &Config) -> Result, Error> { + if let Some(source) = &settings.autorun.host_configuration { + return Ok(Some(source.clone())); + } + match fs::symlink_metadata(config::DEFAULT_HOST_CONFIGURATION) { + Ok(_) => Ok(Some(config::DEFAULT_HOST_CONFIGURATION.into())), + Err(error) if error.kind() == ErrorKind::NotFound => Ok(None), + Err(error) => Err(error).context("Failed to inspect default Host Configuration"), + } +} + +#[cfg(test)] +/// Prepares a plan from an already-mounted media root for tests. +fn prepare_from_media( + settings: &Config, + request: &Request, + root: Option<&Path>, +) -> Result<(Config, Plan), Error> { + prepare_from_media_with_progress(settings, request, root, &mut |_| Ok(())) +} + +/// Merges media settings and selects a Host Configuration before falling back to the first COSI. +fn prepare_from_media_with_progress( + settings: &Config, + request: &Request, + root: Option<&Path>, + progress: &mut impl FnMut(&str) -> Result<(), Error>, +) -> Result<(Config, Plan), Error> { + if let Request::Stream(image) = request { + settings.require_autorun()?; + return Ok(( + settings.clone(), + Plan::Stream { + image: image.clone(), + }, + )); + } + progress("Reading installer configuration")?; + let settings = match root { + Some(root) => settings.overlay(root)?, + None => settings.clone(), + }; + settings.require_autorun()?; + progress("Scanning media for COSI images")?; + let images = match root { + Some(root) => config::discover_images(root, &settings.media.cosi_directory)?, + None => Vec::new(), + }; + progress("Checking Host Configuration")?; + let source = if let Request::HostConfiguration(source) = request { + remote_url(source)?; + Some(source.clone()) + } else { + configured_host_configuration_source(&settings)? + }; + let plan = match source { + Some(source) => { + let url = source_url(&source, root)?; + let text = read_text(&url)?; + let config = resolve_host_configuration(&text, images.first().map(PathBuf::as_path))?; + Plan::Install { + config: Box::new(config), + source, + } + } + None => { + let path = images.first().with_context(|| { + format!( + "No Host Configuration at '{}' and no COSI images in '{}'. Configure networking in Shell, then choose a remote source.", + config::DEFAULT_HOST_CONFIGURATION, + settings.media.cosi_directory.display() + ) + })?; + Plan::Stream { + image: file_url(path)?, + } + } + }; + Ok((settings, plan)) +} + +/// Finds labelled media and mounts it read-only, or validates a configured mount path. +/// +/// When `wait_for_media` is set, waits up to the discovery timeout for late USB partitions. +/// A pre-existing mount must belong to the selected device and be read-only. +fn media_root( + settings: &Config, + wait_for_media: bool, + progress: &mut impl FnMut(&str) -> Result<(), Error>, +) -> Result, Error> { + if let Some(path) = &settings.media.mount_path { + progress("Checking the configured media mount")?; + ensure!( + mountpoint::check_is_mountpoint(path)?, + "media.mountPath is not a mount point: {}", + path.display() + ); + return Ok(Some(path.canonicalize()?)); + } + let labels = settings + .media + .filesystem_label + .as_deref() + .map(|label| vec![label]) + .unwrap_or_else(|| config::DEFAULT_MEDIA_LABELS.to_vec()); + progress("Looking for installer media by filesystem label")?; + let deadline = Instant::now() + MEDIA_DISCOVERY_TIMEOUT; + let mut attempts = 0; + let devices = loop { + let devices = lsblk::devices_by_labels(&labels)?; + if !devices.is_empty() || !wait_for_media || Instant::now() >= deadline { + break devices; + } + if attempts % 5 == 0 { + progress(&format!( + "Waiting for installation media labelled {}", + labels.join(" or ") + ))?; + } + attempts += 1; + thread::sleep(MEDIA_POLL_INTERVAL); + }; + let Some(device) = config::choose_media(&devices)? else { + return Ok(None); + }; + let target = Path::new(config::MEDIA_MOUNT); + fs::create_dir_all(target)?; + if mountpoint::check_is_mountpoint(target)? { + let mounts = FindMnt::run()? + .root() + .context("findmnt did not report a root mount")?; + let existing = mounts + .find_mount_point_for_path(target) + .context("Mounted installer media is not visible in findmnt")?; + ensure!( + existing.target == target + && existing.options.contains(MOUNT_OPTION_READ_ONLY) + && existing.source.as_ref().map(fs::canonicalize).transpose()? + == Some(device.canonicalize()?), + "Existing installer mount does not match the requested read-only media" + ); + } else { + progress("Mounting installer media read-only")?; + mount::mount( + device, + target, + MountFileSystemType::Auto, + &[ + MOUNT_OPTION_READ_ONLY.into(), + "nosuid".into(), + "nodev".into(), + "noexec".into(), + ], + )?; + } + Ok(Some(target.into())) +} + +/// Accepts only credential-free HTTP(S) URLs for manually entered recovery sources. +pub(super) fn remote_url(source: &str) -> Result { + let url = Url::parse(source).context("Enter an absolute http:// or https:// URL")?; + ensure!( + matches!(url.scheme(), "http" | "https"), + "Remote source must use HTTP or HTTPS" + ); + ensure!( + url.username().is_empty() && url.password().is_none(), + "Credentials in source URLs are not supported" + ); + Ok(url) +} + +/// Resolves local, remote, or media-relative Host Configuration sources. +/// +/// Media-relative paths must resolve beneath the media root. +fn source_url(source: &str, root: Option<&Path>) -> Result { + if source.starts_with('/') { + return file_url(Path::new(source)); + } + if source.contains("://") { + let url = Url::parse(source)?; + ensure!( + matches!(url.scheme(), "file" | "http" | "https"), + "Unsupported source URL scheme" + ); + return Ok(url); + } + let root = root.context("A media-relative Host Configuration requires installer media")?; + let path = root + .join(source) + .canonicalize() + .context("Failed to resolve media-relative Host Configuration")?; + ensure!( + path.starts_with(root.canonicalize()?), + "Host Configuration escapes the media root" + ); + file_url(&path) +} + +/// Converts a local path to a `file://` URL, preserving URL escaping. +fn file_url(path: &Path) -> Result { + Url::from_file_path(path) + .map_err(|()| anyhow!("Cannot convert '{}' to a file URL", path.display())) +} + +/// Opens a local file or a time-limited HTTP(S) response for source inspection. +fn reader(url: &Url) -> Result, Error> { + match url.scheme() { + "file" => { + let path = url + .to_file_path() + .map_err(|()| anyhow!("Invalid local file URL"))?; + Ok(Box::new(File::open(&path).with_context(|| { + format!("Failed to open '{}'", path.display()) + })?)) + } + "http" | "https" => { + let client = Client::builder().build()?; + let deadline = Instant::now() + REMOTE_RETRY_TIMEOUT; + let response = loop { + let remaining = deadline.saturating_duration_since(Instant::now()); + let response = client + .get(url.clone()) + .timeout(SOURCE_TIMEOUT.min(remaining)) + .send(); + match response { + Ok(response) => { + break response.error_for_status().map_err(|error| { + anyhow!( + "Failed to fetch '{}': {}", + display_url(url), + error.without_url() + ) + })? + } + Err(error) + if (error.is_connect() || error.is_timeout()) + && Instant::now() < deadline => + { + warn!( + "Remote source '{}' unavailable ({}); retrying while network starts", + display_url(url), + error.without_url() + ); + thread::sleep( + REMOTE_RETRY_INTERVAL + .min(deadline.saturating_duration_since(Instant::now())), + ); + } + Err(error) => { + return Err(anyhow!( + "Failed to fetch '{}': {}", + display_url(url), + error.without_url() + )); + } + } + }; + Ok(Box::new(response)) + } + _ => bail!("Unsupported source scheme '{}'", url.scheme()), + } +} + +/// Reads a Host Configuration as UTF-8 while enforcing the configured byte limit. +fn read_text(url: &Url) -> Result { + let mut text = String::new(); + reader(url)? + .take(MAX_HOST_CONFIGURATION_BYTES + 1) + .read_to_string(&mut text)?; + ensure!( + text.len() as u64 <= MAX_HOST_CONFIGURATION_BYTES, + "Host Configuration exceeds the size limit" + ); + Ok(text) +} + +/// Parses and validates a Host Configuration, resolving `installer://image` to the chosen COSI. +pub(super) fn resolve_host_configuration( + text: &str, + selected: Option<&Path>, +) -> Result { + let config: HostConfiguration = + serde_yaml::from_str(text).context("Invalid Host Configuration YAML")?; + resolve_parsed_host_configuration(config, selected) +} + +/// Validate only after replacing the installer marker with the chosen local image. +fn resolve_parsed_host_configuration( + mut config: HostConfiguration, + selected: Option<&Path>, +) -> Result { + if let Some(image) = &mut config.image { + if image.url.as_str() == IMAGE_MARKER { + image.url = file_url(selected.context( + "Host Configuration uses installer://image but no COSI was discovered", + )?)?; + } + } + config + .validate() + .context("Host Configuration validation failed")?; + Ok(config) +} + +/// Only the fields needed for disk safety and hash binding; Trident parses the full COSI. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct Metadata { + /// StreamDisk needs COSI version 1.2 or newer. + version: String, + /// Disk size decides which attached device Trident could select. + disk: Option, + /// An image-less COSI is invalid even when it declares disk metadata. + images: Vec, +} + +/// The disk size is in bytes, matching `lsblk` capacity. +#[derive(Debug, Deserialize)] +struct DiskMetadata { + /// Trident chooses the smallest disk fitting this byte size. + size: u64, +} + +/// Extracts and hashes the raw COSI metadata within a bounded archive read. +fn metadata(reader: impl Read) -> Result<(Metadata, Sha384Hash), Error> { + let mut archive = Archive::new(reader.take(MAX_METADATA_BYTES)); + for entry in archive.entries().context("Invalid COSI archive")? { + let mut entry = entry?; + let path = entry.path()?; + if path.strip_prefix("./").unwrap_or(&path) == Path::new(METADATA_PATH) { + ensure!( + entry.header().entry_type().is_file(), + "COSI metadata must be a regular file" + ); + ensure!( + entry.size() <= MAX_METADATA_BYTES, + "COSI metadata is too large" + ); + let mut raw = Vec::new(); + entry.read_to_end(&mut raw)?; + let metadata: Metadata = + serde_json::from_slice(&raw).context("Invalid COSI metadata")?; + ensure!( + metadata.disk.as_ref().is_some_and(|disk| disk.size > 0), + "StreamDisk requires COSI disk metadata" + ); + ensure!( + !metadata.images.is_empty(), + "COSI metadata contains no images" + ); + let (major, minor) = metadata + .version + .split_once('.') + .context("Invalid COSI metadata version")?; + ensure!( + major == "1" && minor.parse::()? >= 2, + "StreamDisk requires COSI v1.2 or newer" + ); + return Ok(( + metadata, + Sha384Hash::from(format!("{:x}", Sha384::digest(&raw))), + )); + } + } + bail!("COSI metadata.json was not found within the metadata read limit") +} + +/// Checks disk eligibility and returns the metadata hash to bind the daemon's fetch. +pub(super) fn stream_preflight(image: &Url) -> Result { + let (metadata, hash) = metadata(reader(image)?)?; + let devices = lsblk::list().context("Failed to inspect attached disks")?; + checked_stream_hash(&metadata, hash, &devices) +} + +/// Keeps target-media safety independent of previously installed filesystem UUIDs. +fn checked_stream_hash( + metadata: &Metadata, + hash: Sha384Hash, + devices: &[BlockDevice], +) -> Result { + let required = metadata + .disk + .as_ref() + .context("COSI disk metadata is missing")? + .size; + ensure_stream_target_safe(devices, required)?; + Ok(hash) +} + +/// Refuses streaming if Trident could choose a mounted or read-only smallest fitting disk. +fn ensure_stream_target_safe(devices: &[BlockDevice], required: u64) -> Result<(), Error> { + let candidates = devices + .iter() + .filter(|device| device.blkdev_type == BlockDeviceType::Disk) + .filter(|device| { + STREAM_DISK_PREFIXES + .iter() + .any(|prefix| device.name.starts_with(prefix)) + }) + .filter(|device| device.size >= required) + .collect::>(); + let minimum = candidates + .iter() + .map(|device| device.size) + .min() + .context("No disk fits the COSI image")?; + // Until StreamDisk accepts an explicit target, any minimum-sized candidate may win. + for device in candidates.iter().filter(|device| device.size == minimum) { + ensure!( + !device.readonly && device.get_all_mountpoints_recursive().is_empty(), + "StreamDisk could select mounted or read-only disk '{}', possibly the installer USB; refusing to overwrite installation media. Use media smaller than the COSI disk size or a Host Configuration with an explicit target disk", + device.device_path().display() + ); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + use std::{ + io::{Cursor, Write}, + net::TcpListener, + os::unix::fs as unix_fs, + }; + + use indoc::indoc; + use tar::Builder as TarBuilder; + use tempfile::TempDir; + + use trident_api::config::{AdditionalFile, Encryption}; + + #[test] + /// Ensures recovery sources cannot silently fall back to local files or other schemes. + fn remote_sources_are_explicit_and_limited() { + remote_url("https://example.com/image.cosi").unwrap(); + for invalid in [ + "file:///image.cosi", + "ftp://example.com/image.cosi", + "image.cosi", + "https://user:secret@example.com/image.cosi", + ] { + remote_url(invalid).unwrap_err(); + } + } + + #[test] + /// Remote sources recover when the network becomes reachable after startup. + fn remote_source_retries_until_listener_is_ready() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + drop(listener); + let url = Url::parse(&format!("http://{address}/host.yaml")).unwrap(); + let initial = Client::builder() + .timeout(Duration::from_secs(2)) + .build() + .unwrap() + .get(url.clone()) + .send() + .unwrap_err(); + assert!(initial.is_connect(), "{initial}"); + let server = thread::spawn(move || { + thread::sleep(Duration::from_millis(200)); + let listener = TcpListener::bind(address).unwrap(); + let (mut socket, _) = listener.accept().unwrap(); + let mut request = [0; 512]; + assert_ne!(socket.read(&mut request).unwrap(), 0); + socket + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 16\r\nConnection: close\r\n\r\nmode = 'autorun'", + ) + .unwrap(); + }); + assert_eq!(read_text(&url).unwrap(), "mode = 'autorun'"); + server.join().unwrap(); + } + + #[test] + /// Keeps signed source credentials out of operator-visible descriptions. + fn source_descriptions_redact_url_secrets() { + let url = + Url::parse("https://user:password@example.com/image.cosi?token=secret#key").unwrap(); + assert_eq!(display_url(&url), "https://example.com/image.cosi"); + assert_eq!( + display_source(url.as_str()), + "https://example.com/image.cosi" + ); + assert_eq!( + Plan::Stream { image: url.clone() }.description(), + "StreamDisk from https://example.com/image.cosi" + ); + assert_eq!( + Plan::Install { + config: Box::default(), + source: url.to_string() + } + .description(), + "Install from https://example.com/image.cosi" + ); + assert_eq!( + display_source("/etc/trident/config.yaml"), + "/etc/trident/config.yaml" + ); + assert_eq!( + display_url(&Url::parse("file:///media/image.cosi").unwrap()), + "file:///media/image.cosi" + ); + assert_eq!( + display_source("https://bad URL?token=secret"), + "" + ); + assert_eq!( + redact_message_urls( + "Loaded 'https://u:p@example.test/image.cosi?sig=sec'ret#fragment', done" + ), + "Loaded 'https://example.test/image.cosi', done" + ); + } + + #[test] + /// Explicit stream recovery ignores broken media mounts, overlays and COSI directories. + fn explicit_stream_ignores_local_media() { + let root = TempDir::new().unwrap(); + fs::create_dir(root.path().join("installer")).unwrap(); + fs::write(root.path().join(config::MEDIA_CONFIG), "invalid TOML").unwrap(); + let mut settings = Config::default(); + settings.media.mount_path = Some("/nonexistent-installer-media".into()); + let url = Url::parse("https://example.com/image.cosi?token=secret").unwrap(); + let (_, plan) = + prepare_from_media(&settings, &Request::Stream(url.clone()), Some(root.path())) + .unwrap(); + assert!(matches!(plan, Plan::Stream { image } if image == url)); + let (_, plan) = + prepare_with_progress(&settings, &Request::Stream(url.clone()), |_| Ok(())).unwrap(); + assert!(matches!(plan, Plan::Stream { image } if image == url)); + } + + #[test] + /// A complete live-OS Host Configuration never waits for media or applies its overlay. + fn self_contained_autorun_skips_media() { + let root = TempDir::new().unwrap(); + let path = root.path().join("host.yaml"); + fs::write( + &path, + valid_host_configuration().replace(IMAGE_MARKER, "https://example.com/image.cosi"), + ) + .unwrap(); + let mut settings = Config::default(); + settings.autorun.host_configuration = Some(path.display().to_string()); + settings.media.mount_path = Some(root.path().join("not-mounted")); + let (_, plan) = prepare_with_progress(&settings, &Request::Autorun, |_| Ok(())).unwrap(); + assert!(matches!(plan, Plan::Install { source, .. } if source == path.to_string_lossy())); + + settings.mode = config::Mode::Interactive; + let error = prepare_with_progress(&settings, &Request::Autorun, |_| Ok(())).unwrap_err(); + assert!( + error.to_string().contains("Interactive installation"), + "{error:#}" + ); + } + + #[test] + /// An HTTP Host Configuration with its own image does not need a local media mount. + fn self_contained_remote_autorun_skips_media() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}/host.yaml", listener.local_addr().unwrap()); + let server = thread::spawn(move || { + let (mut socket, _) = listener.accept().unwrap(); + let mut request = [0; 512]; + assert_ne!(socket.read(&mut request).unwrap(), 0); + let body = + valid_host_configuration().replace(IMAGE_MARKER, "https://example.com/image.cosi"); + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + socket.write_all(response.as_bytes()).unwrap(); + }); + let mut settings = Config::default(); + settings.autorun.host_configuration = Some(url.clone()); + settings.media.mount_path = Some("/nonexistent-installer-media".into()); + let (_, plan) = prepare_with_progress(&settings, &Request::Autorun, |_| Ok(())).unwrap(); + assert!(matches!(plan, Plan::Install { source, .. } if source == url)); + server.join().unwrap(); + } + + #[test] + /// Media-relative Host Configurations and media-backed images still need discovery. + fn media_dependent_host_configuration_is_not_self_contained() { + let root = TempDir::new().unwrap(); + let path = root.path().join("host.yaml"); + fs::write(&path, valid_host_configuration()).unwrap(); + let mut settings = Config::default(); + settings.autorun.host_configuration = Some(path.display().to_string()); + assert!(self_contained_install(&settings, &mut |_| Ok(())) + .unwrap() + .is_none()); + settings.autorun.host_configuration = Some("installer/host.yaml".into()); + assert!(self_contained_install(&settings, &mut |_| Ok(())) + .unwrap() + .is_none()); + fs::write( + &path, + valid_host_configuration().replace( + IMAGE_MARKER, + &format!("file://{}/cosi/image.cosi", config::MEDIA_MOUNT), + ), + ) + .unwrap(); + settings.autorun.host_configuration = Some(path.display().to_string()); + assert!(self_contained_install(&settings, &mut |_| Ok(())) + .unwrap() + .is_none()); + } + + #[test] + /// An HTTPS image does not make an HC self-contained if other inputs live on installer media. + fn additional_file_and_scripts_keep_media_discovery() { + let root = TempDir::new().unwrap(); + let path = root.path().join("host.yaml"); + let mut settings = Config::default(); + let mount = root.path().join("not-mounted"); + settings.media.mount_path = Some(mount.clone()); + settings.autorun.host_configuration = Some(path.display().to_string()); + let mut config: HostConfiguration = serde_yaml::from_str( + &valid_host_configuration().replace(IMAGE_MARKER, "https://example.com/image.cosi"), + ) + .unwrap(); + assert!(!host_configuration_needs_media(&config, &settings).unwrap()); + + config.os.additional_files.push(AdditionalFile { + destination: "/etc/example".into(), + source: Some(mount.join("installer/example")), + ..Default::default() + }); + fs::write(&path, serde_yaml::to_string(&config).unwrap()).unwrap(); + assert!(host_configuration_needs_media(&config, &settings).unwrap()); + let error = prepare_with_progress(&settings, &Request::Autorun, |_| Ok(())).unwrap_err(); + assert!(error.to_string().contains("not a mount point"), "{error:#}"); + + config.os.additional_files.clear(); + config.scripts.post_provision.push(Script { + source: ScriptSource::Path(mount.join("installer/script.sh")), + ..Default::default() + }); + assert!(host_configuration_needs_media(&config, &settings).unwrap()); + config.scripts.post_provision.clear(); + + config.storage.encryption = Some(Encryption { + recovery_key_url: Some(file_url(&mount.join("installer/recovery.key")).unwrap()), + ..Default::default() + }); + assert!(host_configuration_needs_media(&config, &settings).unwrap()); + } + + #[test] + /// Dangling links into installer media must not be mistaken for an absent Host Configuration. + fn symlinked_host_configuration_waits_for_media() { + let root = TempDir::new().unwrap(); + let link = root.path().join("host.yaml"); + unix_fs::symlink( + Path::new(config::MEDIA_MOUNT).join("installer/host.yaml"), + &link, + ) + .unwrap(); + assert!(fs::metadata(&link).is_err()); + assert!(fs::symlink_metadata(&link).is_ok()); + let mut settings = Config::default(); + settings.autorun.host_configuration = Some(link.display().to_string()); + assert!(self_contained_install(&settings, &mut |_| Ok(())) + .unwrap() + .is_none()); + + let directory_link = root.path().join("media"); + unix_fs::symlink(config::MEDIA_MOUNT, &directory_link).unwrap(); + settings.autorun.host_configuration = Some( + directory_link + .join("installer/host.yaml") + .display() + .to_string(), + ); + assert!(self_contained_install(&settings, &mut |_| Ok(())) + .unwrap() + .is_none()); + + let local = root.path().join("local.yaml"); + fs::write( + &local, + valid_host_configuration().replace(IMAGE_MARKER, "https://example.com/image.cosi"), + ) + .unwrap(); + let local_link = root.path().join("local-link.yaml"); + unix_fs::symlink(local, &local_link).unwrap(); + settings.autorun.host_configuration = Some(local_link.display().to_string()); + assert!(self_contained_install(&settings, &mut |_| Ok(())) + .unwrap() + .is_some()); + } + + #[test] + /// Ensures the image marker needs a COSI and leaves other image URLs untouched. + fn marker_requires_an_image_and_does_not_touch_other_urls() { + let yaml = valid_host_configuration(); + resolve_host_configuration(yaml, None).unwrap_err(); + let resolved = + resolve_host_configuration(yaml, Some(Path::new("/media/cosi/an image.cosi"))).unwrap(); + assert_eq!( + resolved.image.unwrap().url.as_str(), + "file:///media/cosi/an%20image.cosi" + ); + let remote = yaml.replace(IMAGE_MARKER, "https://example.com/image.cosi"); + assert_eq!( + resolve_host_configuration(&remote, None) + .unwrap() + .image + .unwrap() + .url + .as_str(), + "https://example.com/image.cosi" + ); + } + + /// Provides a valid Host Configuration containing the installer image marker. + fn valid_host_configuration() -> &'static str { + indoc! {" + storage: + disks: + - id: os + device: /dev/test + partitionTableType: gpt + partitions: + - id: esp + type: esp + size: 192M + - id: root + type: root + size: 1G + filesystems: + - deviceId: esp + mountPoint: + path: /boot/efi + - deviceId: root + mountPoint: + path: / + image: + url: installer://image + sha384: ignored + "} + } + + #[test] + /// Ensures Host Configuration takes priority and invalid input never falls back to COSI. + fn host_configuration_wins_and_invalid_hc_never_falls_back() { + let root = TempDir::new().unwrap(); + fs::create_dir(root.path().join("cosi")).unwrap(); + fs::write(root.path().join("cosi/z.cosi"), "").unwrap(); + fs::write(root.path().join("cosi/a.cosi"), "").unwrap(); + let path = root.path().join("host.yaml"); + fs::write(&path, valid_host_configuration()).unwrap(); + let mut settings = Config::default(); + settings.autorun.host_configuration = Some(path.display().to_string()); + let (_, plan) = + prepare_from_media(&settings, &Request::Autorun, Some(root.path())).unwrap(); + let Plan::Install { config, .. } = plan else { + panic!("HC must select Install") + }; + assert_eq!( + config.image.unwrap().url, + file_url(&root.path().join("cosi/a.cosi")).unwrap() + ); + fs::write(&path, "unknown: field").unwrap(); + prepare_from_media(&settings, &Request::Autorun, Some(root.path())).unwrap_err(); + } + + #[test] + /// Ensures an oversized Host Configuration is rejected before parsing. + fn configuration_read_limit_is_enforced() { + let root = TempDir::new().unwrap(); + let path = root.path().join("oversized.yaml"); + fs::write( + &path, + vec![b'x'; usize::try_from(MAX_HOST_CONFIGURATION_BYTES + 1).unwrap()], + ) + .unwrap(); + let error = read_text(&file_url(&path).unwrap()).unwrap_err(); + assert!(error.to_string().contains("size limit"), "{error:#}"); + } + + #[test] + /// Ensures unreadable and missing COSI metadata cannot pass preflight. + fn truncated_and_missing_metadata_are_errors() { + metadata(Cursor::new(b"not a tar file")).unwrap_err(); + let mut builder = TarBuilder::new(Vec::new()); + builder.finish().unwrap(); + metadata(Cursor::new(builder.into_inner().unwrap())).unwrap_err(); + } + + #[test] + /// Hashes the original metadata bytes rather than re-serialized JSON. + fn preflight_metadata_hash_matches_daemon_contract() { + let raw = br#"{"version":"1.2","disk":{"size":4294967296},"images":[{}]}"#; + let inspect = |raw: &[u8], path: &str| { + let mut builder = TarBuilder::new(Vec::new()); + let mut header = tar::Header::new_gnu(); + header.set_size(raw.len() as u64); + header.set_cksum(); + builder.append_data(&mut header, path, raw).unwrap(); + builder.finish().unwrap(); + metadata(Cursor::new(builder.into_inner().unwrap())).unwrap() + }; + let (parsed, hash) = inspect(raw, METADATA_PATH); + assert_eq!(parsed.disk.unwrap().size, 4294967296); + assert_eq!(hash, Sha384Hash::from(format!("{:x}", Sha384::digest(raw)))); + let (_, prefixed_hash) = inspect(raw, "./metadata.json"); + assert_eq!(hash, prefixed_hash); + + let padded = br#"{ "version":"1.2","disk":{"size":4294967296},"images":[{}]}"#; + let (_, padded_hash) = inspect(padded, METADATA_PATH); + assert_ne!(hash, padded_hash); + } + + #[test] + /// Autorun still streams to a safe disk with matching UUIDs already present. + fn existing_filesystem_uuids_do_not_block_stream_preflight() { + let raw = br#"{"version":"1.2","disk":{"size":4294967296},"images":[{"fsUuid":"existing-root"}]}"#; + let mut builder = TarBuilder::new(Vec::new()); + let mut header = tar::Header::new_gnu(); + header.set_size(raw.len() as u64); + header.set_cksum(); + builder + .append_data(&mut header, METADATA_PATH, &raw[..]) + .unwrap(); + builder.finish().unwrap(); + let (metadata, hash) = metadata(Cursor::new(builder.into_inner().unwrap())).unwrap(); + let disk = BlockDevice { + name: "vda".into(), + size: 8 * 1024 * 1024 * 1024, + blkdev_type: BlockDeviceType::Disk, + children: vec![BlockDevice { + fsuuid: Some("existing-root".into()), + ..Default::default() + }], + ..Default::default() + }; + assert_eq!( + checked_stream_hash(&metadata, hash.clone(), &[disk]).unwrap(), + hash + ); + } + + #[test] + /// Ensures a small installer USB is skipped and an eligible mounted USB is refused. + fn smaller_gpt_usb_media_is_not_a_stream_target() { + let media = BlockDevice { + name: "sdb".into(), + size: 2 * 1024 * 1024 * 1024, + blkdev_type: BlockDeviceType::Disk, + children: vec![BlockDevice { + name: "sdb1".into(), + mountpoints: vec![config::MEDIA_MOUNT.into()], + ..Default::default() + }], + ..Default::default() + }; + let target = BlockDevice { + name: "vda".into(), + size: 8 * 1024 * 1024 * 1024, + blkdev_type: BlockDeviceType::Disk, + ..Default::default() + }; + let required = 4 * 1024 * 1024 * 1024; + ensure_stream_target_safe(&[media.clone(), target.clone()], required).unwrap(); + let larger_media = BlockDevice { + size: 6 * 1024 * 1024 * 1024, + ..media + }; + let error = ensure_stream_target_safe(&[larger_media, target], required).unwrap_err(); + assert!(error.to_string().contains("installer USB"), "{error:#}"); + } +} diff --git a/crates/installer/src/terminal.rs b/crates/installer/src/terminal.rs new file mode 100644 index 0000000000..d1a2e2416f --- /dev/null +++ b/crates/installer/src/terminal.rs @@ -0,0 +1,167 @@ +//! Console ownership, serial mirrors and recovery-shell setup for installer boots. + +use std::{ + fs::{self, File, OpenOptions}, + io::{self, IsTerminal, Write}, + os::{ + fd::AsRawFd, + unix::fs::{FileTypeExt, OpenOptionsExt}, + }, + path::{Path, PathBuf}, +}; + +use anyhow::{ensure, Context, Error}; +use nix::{libc, unistd}; + +use osutils::dependencies::{self, Dependency}; + +/// Kernel list of consoles active for this boot. +const ACTIVE_CONSOLES_PATH: &str = "/sys/class/tty/console/active"; +/// The installer service owns tty1 and stops its getty before attaching. +const GRAPHICAL_CONSOLE: &str = "tty1"; +/// Linux virtual terminals expose 16 programmable ANSI color slots. +const VT_PALETTE_SIZE: u8 = 16; + +/// Sets RGB values for the Linux virtual console's 16 ANSI colour slots. +pub(super) fn set_vt_palette( + output: &mut impl Write, + colours: &[(u8, u8, u8, u8)], +) -> io::Result<()> { + for &(slot, red, green, blue) in colours { + if slot >= VT_PALETTE_SIZE { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("Invalid Linux VT palette slot {slot}"), + )); + } + write!(output, "\x1b]P{slot:x}{red:02x}{green:02x}{blue:02x}")?; + } + output.flush() +} + +/// Restores the Linux virtual console's built-in ANSI colour palette. +pub(super) fn reset_vt_palette(output: &mut impl Write) -> io::Result<()> { + output.write_all(b"\x1b]R")?; + output.flush() +} + +/// Reads the active kernel consoles, resolving `tty0` to the graphical `tty1`. +pub(super) fn active_consoles() -> Result, Error> { + let active = fs::read_to_string(ACTIVE_CONSOLES_PATH) + .context("Failed to read active kernel consoles")?; + console_paths(&active) +} + +/// Validates console names before producing unique `/dev` paths. +fn console_paths(active: &str) -> Result, Error> { + let mut consoles = Vec::new(); + for name in active.split_whitespace() { + ensure!( + name.chars().all(|c| c.is_ascii_alphanumeric()), + "Invalid console name '{name}'" + ); + let name = if name == "tty0" { + GRAPHICAL_CONSOLE + } else { + name + }; + let path = Path::new("/dev").join(name); + if !consoles.contains(&path) { + consoles.push(path); + } + } + ensure!(!consoles.is_empty(), "No active kernel consoles found"); + Ok(consoles) +} + +/// Opens a serial console without allowing flow control to block a caller's event loop. +pub(super) fn open_nonblocking_console(path: impl AsRef) -> Result { + let path = path.as_ref(); + OpenOptions::new() + .write(true) + .custom_flags(libc::O_NONBLOCK | libc::O_NOCTTY) + .open(path) + .with_context(|| format!("Failed to open console '{}'", path.display())) +} + +/// Claims a character terminal as the controlling TTY and redirects stdin/stdout to it. +/// +/// The caller must stop competing getty units before attaching. +pub(super) fn attach(path: impl AsRef) -> Result { + let path = path.as_ref(); + let terminal = OpenOptions::new() + .read(true) + .write(true) + .open(path) + .with_context(|| format!("Failed to open terminal '{}'", path.display()))?; + ensure!( + terminal.metadata()?.file_type().is_char_device() && terminal.is_terminal(), + "Not a terminal: {}", + path.display() + ); + if unistd::getsid(None)? != unistd::getpid() { + // A session leader can claim tty1 as its controlling terminal. + unistd::setsid()?; + } + // The caller has stopped competing getty units before claiming the terminal. + if unsafe { libc::ioctl(terminal.as_raw_fd(), libc::TIOCSCTTY, 1) } < 0 { + return Err(io::Error::last_os_error()).context("Failed to claim controlling terminal"); + } + // The recovery shell later takes this foreground group and returns it on exit. + dependencies::set_foreground_group(&terminal, unistd::getpgrp()) + .context("Failed to make installer the terminal's foreground process group")?; + for target in [libc::STDIN_FILENO, libc::STDOUT_FILENO] { + // Leave stderr on its inherited sink rather than drawing it over tty1. + if unsafe { libc::dup2(terminal.as_raw_fd(), target) } < 0 { + return Err(io::Error::last_os_error()).context("Failed to attach terminal"); + } + } + Ok(terminal) +} + +/// Runs an interactive login Bash on the supplied terminal, loading the root profile. +pub(super) fn shell(terminal: &File) -> Result<(), Error> { + Dependency::Bash + .cmd() + .args(["--login", "-i"]) + .run_interactive(terminal)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + /// Ensures graphical console aliases are deduplicated and invalid names fail. + fn graphical_console_wins_and_aliases_are_deduplicated() { + let consoles = console_paths("ttyS0 tty0 tty1").unwrap(); + assert_eq!( + consoles, + [PathBuf::from("/dev/ttyS0"), PathBuf::from("/dev/tty1")] + ); + console_paths("../tty1").unwrap_err(); + console_paths("").unwrap_err(); + } + + #[test] + /// Serial mirrors must not block the installer when a console stops draining. + fn serial_console_is_nonblocking() { + let terminal = nix::pty::openpty(None, None).unwrap(); + let path = unistd::ttyname(&terminal.slave).unwrap(); + let mirror = open_nonblocking_console(path).unwrap(); + let flags = unsafe { libc::fcntl(mirror.as_raw_fd(), libc::F_GETFL) }; + assert!(flags >= 0); + assert_ne!(flags & libc::O_NONBLOCK, 0); + } + + #[test] + /// Ensures VT palette slots are encoded correctly and out-of-range slots fail. + fn linux_vt_palette_sequences_set_rgb_slots_and_reset() { + let mut output = Vec::new(); + set_vt_palette(&mut output, &[(0, 11, 17, 24), (15, 229, 234, 236)]).unwrap(); + reset_vt_palette(&mut output).unwrap(); + assert_eq!(output, b"\x1b]P00b1118\x1b]Pfe5eaec\x1b]R"); + set_vt_palette(&mut output, &[(16, 0, 0, 0)]).unwrap_err(); + } +} diff --git a/crates/installer/src/ui/mod.rs b/crates/installer/src/ui/mod.rs new file mode 100644 index 0000000000..86e79e2a05 --- /dev/null +++ b/crates/installer/src/ui/mod.rs @@ -0,0 +1,690 @@ +//! Runs the live installer console, coordinating operations, TTY ownership and power actions. + +use std::{ + fs::OpenOptions, + io::{self, IsTerminal}, + path::PathBuf, + time::{Duration, Instant}, +}; + +use anyhow::{anyhow, Error}; +use crossterm::{ + cursor::MoveTo, + event::{self, Event as TerminalEvent}, + execute, + terminal::{ + self, Clear as ClearTerminal, ClearType, EnterAlternateScreen, LeaveAlternateScreen, + }, +}; +use log::{error, Level}; +use ratatui::{backend::CrosstermBackend, Terminal}; +use tokio::{ + signal::unix::{self, SignalKind}, + sync::mpsc, + task::{self, JoinError, JoinHandle}, + time, +}; + +use osutils::systemd; +use trident_client::{LogLevel, ServicingEvent}; + +use crate::{ + client::{self, Event}, + config::Config, + source::{self, Request}, + terminal as installer_terminal, INSTALLER_LOG_TX, +}; + +mod model; +mod output; +mod render; +mod theme; + +use model::{display_text, log_visible, Action, LogSource, Model, Screen}; +pub(super) use output::Output; +use render::{render, title}; +use theme::{vt_rgb_palette, VERBOSITY_LEVELS}; + +/// Refresh often enough to show progress without busy-polling the terminal. +const FRAME_INTERVAL: Duration = Duration::from_millis(100); +/// Drain pasted input promptly without starving worker events. +const INPUT_EVENTS_PER_FRAME: usize = 256; +/// Bound the worker event queue and the amount processed in one loop iteration. +const EVENT_CAPACITY: usize = 64; + +/// Owns the alternate screen and restores terminal state even on early exit. +struct Display { + /// Ratatui draws to stdout, which may be an attached graphical console. + terminal: Terminal>, + /// Only restore raw mode and the alternate screen when the UI owns them. + active: bool, + /// Linux VTs need a programmed ANSI palette; other terminals use RGB directly. + linux_vt: bool, +} + +impl Display { + /// Creates a terminal display and enters its alternate screen. + fn new(linux_vt: bool) -> Result { + let mut display = Self { + terminal: Terminal::new(CrosstermBackend::new(io::stdout()))?, + active: false, + linux_vt, + }; + display.resume()?; + Ok(display) + } + + /// Restores raw-mode drawing and the VT palette after a shell exits. + fn resume(&mut self) -> Result<(), Error> { + terminal::enable_raw_mode()?; + self.active = true; + if self.linux_vt { + installer_terminal::set_vt_palette(&mut io::stdout(), &vt_rgb_palette()?)?; + } + execute!(self.terminal.backend_mut(), EnterAlternateScreen)?; + self.terminal.clear()?; + Ok(()) + } + + /// Leaves raw mode and the alternate screen so an interactive shell can use the terminal. + /// On Linux VTs, also clears the old UI and restores the original palette. + fn suspend(&mut self) -> Result<(), Error> { + let restore = self.leave_screen(); + let palette = if self.linux_vt { + installer_terminal::reset_vt_palette(&mut io::stdout()) + } else { + Ok(()) + }; + self.active = false; + restore?; + palette?; + Ok(()) + } + + /// Releases the screen before palette cleanup, which must run even if this fails. + fn leave_screen(&mut self) -> Result<(), Error> { + terminal::disable_raw_mode()?; + execute!(self.terminal.backend_mut(), LeaveAlternateScreen)?; + if self.linux_vt { + // Linux VT leaves the old TUI visible when exiting its alternate screen. + execute!( + self.terminal.backend_mut(), + ClearTerminal(ClearType::All), + MoveTo(0, 0) + )?; + } + self.terminal.show_cursor()?; + Ok(()) + } +} + +impl Drop for Display { + /// Attempts terminal restoration if the display was not explicitly suspended. + fn drop(&mut self) { + if self.active { + if let Err(error) = self.suspend() { + error!("Failed to restore terminal: {error:#}"); + } + } + } +} + +/// Reloads live configuration for each installation attempt. +/// Configuration read errors are reported as events rather than worker failures. +fn spawn_operation( + config_path: PathBuf, + request: Request, + uncertain: bool, + tx: mpsc::Sender, +) -> JoinHandle> { + task::spawn(async move { + match Config::read(config_path) { + Ok(settings) => client::execute(settings, request, uncertain, tx).await, + Err(error) => { + client::send( + &tx, + Event::Error { + details: format!("{error:#}"), + uncertain, + }, + ) + .await + } + } + }) +} + +/// Reports shell failures without changing the result of an independent installation. +fn shell_result_event(result: Result, JoinError>) -> Option { + match result { + Ok(Ok(())) => None, + Ok(Err(error)) => Some(Event::InstallerLog { + level: Level::Warn, + message: format!("Recovery shell failed: {error:#}"), + }), + Err(error) => Some(Event::InstallerLog { + level: Level::Warn, + message: format!("Recovery shell task terminated: {error}"), + }), + } +} + +/// Sanitizes received diagnostics before persistence, display, or serial mirroring. +fn redact_event(mut event: Event) -> Event { + match &mut event { + Event::InstallerLog { message, .. } | Event::Preparing(message) => { + *message = source::redact_message_urls(message); + } + Event::Prepared { description, .. } => { + *description = source::redact_message_urls(description); + } + Event::Error { details, .. } => { + *details = source::redact_message_urls(details); + } + Event::Response(ServicingEvent::Log(record)) => { + record.message = source::redact_message_urls(&record.message); + } + Event::Response(ServicingEvent::Completed(Err(error))) => { + error.message = source::redact_message_urls(&error.message); + error.error_message = source::redact_message_urls(&error.error_message); + } + _ => {} + } + event +} + +/// Runs the installer event loop, starting autorun and offering recovery on a terminal. +/// Noninteractive runs return after work completes and fail if recovery needs user input; +/// `plain` selects text output instead of the full-screen display. +pub(super) async fn run( + config_path: PathBuf, + plain: bool, + linux_vt: bool, + mut output: Output, +) -> Result<(), Error> { + let (tx, mut rx) = mpsc::channel(EVENT_CAPACITY); + let (log_tx, mut log_rx) = mpsc::unbounded_channel(); + INSTALLER_LOG_TX + .set(log_tx) + .map_err(|_| anyhow!("Installer log receiver already initialized"))?; + let mut interrupts = unix::signal(SignalKind::interrupt())?; + let mut termination = unix::signal(SignalKind::terminate())?; + let mut model = Model::new(); + model.linux_vt = linux_vt; + let mut worker = Some(spawn_operation( + config_path.clone(), + Request::Autorun, + false, + tx.clone(), + )); + let interactive = io::stdin().is_terminal() && io::stdout().is_terminal(); + let mut display = if interactive && !plain { + Some(Display::new(linux_vt)?) + } else { + None + }; + let mut shell: Option>> = None; + let mut printed_screen = None; + loop { + for _ in 0..EVENT_CAPACITY { + let event = match rx.try_recv() { + Ok(event) => event, + Err(_) => match log_rx.try_recv() { + Ok(event) => event, + Err(_) => break, + }, + }; + let event = redact_event(event); + output.record(&event)?; + let entry = model.event(event); + output.announce(&entry, model.serial_verbosity); + if display.is_none() && shell.is_none() && log_visible(entry.level, model.verbosity) { + println!("{}", entry.plain()); + } + } + // A finished worker cannot enqueue a terminal event after the queue check. + if worker.as_ref().is_some_and(JoinHandle::is_finished) && rx.is_empty() { + if let Some(finished) = worker.take() { + let failure = match finished.await { + Ok(Ok(())) => None, + Ok(Err(error)) => { + Some(model.fail(format!("Installer worker failed: {error:#}"), true)) + } + Err(error) => { + Some(model.fail(format!("Installer worker terminated: {error}"), true)) + } + }; + if let Some(failure) = failure { + output.announce(&failure, model.serial_verbosity); + } + } + } + if shell.as_ref().is_some_and(JoinHandle::is_finished) { + if let Some(finished) = shell.take() { + if let Some(event) = shell_result_event(finished.await) { + let event = redact_event(event); + output.record(&event)?; + let warning = model.event(event); + output.announce(&warning, model.serial_verbosity); + } + } + if let Some(display) = &mut display { + display.resume()?; + } + printed_screen = None; + } + if shell.is_some() { + // Keep draining servicing events while the shell owns the TTY, but hold reboot. + tokio::select! { + _ = time::sleep(FRAME_INTERVAL) => {} + _ = termination.recv() => return Err(anyhow!("Installer stopped; servicing may continue in Trident")), + } + continue; + } + if model + .reboot_at + .is_some_and(|deadline| Instant::now() >= deadline) + { + model.reboot_at = None; + let reboot = model.log( + LogSource::Inst, + LogLevel::Info, + "Rebooting after successful installation".into(), + ); + output.announce(&reboot, model.serial_verbosity); + match systemd::reboot() { + Ok(()) => return Ok(()), + Err(error) => { + let failure = model.fail(format!("Failed to reboot: {error:#}"), false); + output.announce(&failure, model.serial_verbosity); + } + } + } + if !interactive { + if worker.is_none() && rx.is_empty() && log_rx.is_empty() && model.reboot_at.is_none() { + if model.failed { + return Err(anyhow!( + "{}\nRecovery requires an interactive terminal.", + model.details + )); + } + return Ok(()); + } + } else { + if let Some(display) = &mut display { + display.terminal.draw(|frame| render(frame, &model))?; + } else if printed_screen != Some((model.screen, model.verbosity_open)) { + if model.verbosity_open { + println!("\nLOG VERBOSITY (display only)"); + for (index, level) in VERBOSITY_LEVELS.iter().enumerate() { + println!("{}: {level}", index + 1); + } + println!("Number + Enter: apply; Esc: cancel"); + } else { + println!( + "\n{}\n{}", + title(model.screen), + display_text(&model.details) + ); + for (index, choice) in model.choices().iter().enumerate() { + println!("{}: {choice}", index + 1); + } + if matches!(model.screen, Screen::StreamUrl | Screen::HostConfigUrl) { + println!("Enter an http:// or https:// URL, then press Enter"); + } + println!("Number + Enter: select; S + Enter: shell; Esc: menu; V: verbosity"); + } + printed_screen = Some((model.screen, model.verbosity_open)); + } + for _ in 0..INPUT_EVENTS_PER_FRAME { + if !event::poll(Duration::ZERO)? { + break; + } + let event = event::read()?; + if let TerminalEvent::Key(key) = event { + if let Some(action) = model.key(key, worker.is_some()) { + match action { + Action::Shell => { + if let Some(display) = &mut display { + display.suspend()?; + } + println!("\nShell: type exit to return. Installation continues; automatic reboot waits."); + let tty = + OpenOptions::new().read(true).write(true).open("/dev/tty")?; + shell = Some(task::spawn_blocking(move || { + installer_terminal::shell(&tty) + })); + break; + } + Action::Start(request) => { + if worker.is_some() { + let failure = model.fail("An installer operation is still active. Wait for it to finish.".into(), true); + output.announce(&failure, model.serial_verbosity); + } else { + model.screen = Screen::Progress; + model.activity = "Preparing installation".into(); + model.started = Instant::now(); + model.reboot_at = None; + model.scroll = 0; + model.selected = 0; + worker = Some(spawn_operation( + config_path.clone(), + request, + model.uncertain, + tx.clone(), + )); + } + } + Action::BlockedPower => { + model.screen = if worker.is_some() { + Screen::Menu + } else { + Screen::Recovery + }; + model.selected = 0; + model.activity = "Servicing may still be active; power actions are unavailable until Trident confirms it is idle".into(); + let warning = model.log( + LogSource::Inst, + LogLevel::Warn, + model.activity.clone(), + ); + output.announce(&warning, model.serial_verbosity); + } + Action::Reboot => { + let action = model.log( + LogSource::Inst, + LogLevel::Info, + "Reboot requested".into(), + ); + output.announce(&action, model.serial_verbosity); + if let Err(error) = systemd::reboot() { + let failure = + model.fail(format!("Failed to reboot: {error:#}"), false); + output.announce(&failure, model.serial_verbosity); + } else { + return Ok(()); + } + } + Action::Poweroff => { + let action = model.log( + LogSource::Inst, + LogLevel::Info, + "Shutdown requested".into(), + ); + output.announce(&action, model.serial_verbosity); + if let Err(error) = systemd::poweroff() { + let failure = model + .fail(format!("Failed to shut down: {error:#}"), false); + output.announce(&failure, model.serial_verbosity); + } else { + return Ok(()); + } + } + } + } + } + } + } + tokio::select! { + _ = time::sleep(FRAME_INTERVAL) => {} + signal = interrupts.recv() => { + if signal.is_none() { + return Err(anyhow!("Installer interrupt handler closed")); + } + model.screen = if worker.is_some() { Screen::Menu } else { Screen::Recovery }; + model.selected = 0; + } + _ = termination.recv() => return Err(anyhow!("Installer stopped; servicing may continue in Trident")), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use std::fs::{self, File}; + + use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; + use tempfile::TempDir; + use tokio::sync::oneshot; + + use trident_client::{ + Completion as ClientCompletion, LogRecord, RebootDisposition, RemoteError, + RemoteErrorCategory, ServicingKind, + }; + + /// Creates an unmodified Enter press for navigation tests. + fn enter() -> KeyEvent { + KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE) + } + + /// Trident's COSI-loading messages must not expose signed URLs on any installer output. + #[test] + fn daemon_image_urls_are_redacted_before_recording_or_mirroring() { + let root = TempDir::new().unwrap(); + let diagnostic = root.path().join("installer.log"); + let serial = root.path().join("serial.log"); + let mut output = Output { + log: Some(File::create(&diagnostic).unwrap()), + mirrors: vec![(serial.clone(), File::create(&serial).unwrap())], + }; + let mut model = Model::new(); + for message in [ + "Attempting to load COSI file from 'https://user:password@example.test/image.cosi?sig=secret#fragment'", + "Loaded COSI file from 'https://user:password@example.test/image.cosi?sig=secret#fragment' with hash 'abc'", + ] { + let event = redact_event(Event::Response(ServicingEvent::Log(LogRecord { + timestamp: None, + level: LogLevel::Info, + message: message.into(), + module: String::new(), + target: String::new(), + location: None, + }))); + output.record(&event).unwrap(); + let entry = model.event(event); + output.announce(&entry, model.serial_verbosity); + assert!(entry.message.contains("https://example.test/image.cosi")); + for secret in ["user", "password", "sig=secret", "fragment"] { + assert!(!entry.message.contains(secret), "{entry:?}"); + } + } + for text in [ + fs::read_to_string(diagnostic).unwrap(), + fs::read_to_string(serial).unwrap(), + ] { + assert!(text.contains("https://example.test/image.cosi"), "{text}"); + for secret in ["user", "password", "sig=secret", "fragment"] { + assert!(!text.contains(secret), "{text}"); + } + } + } + + /// Daemon failures cannot reintroduce a signed URL through structured error details. + #[test] + fn daemon_image_errors_redact_signed_urls() { + let event = redact_event(Event::Response(ServicingEvent::Completed(Err( + RemoteError { + category: RemoteErrorCategory::Servicing, + message: "Failed to load 'https://user:password@example.test/image.cosi?sig=secret#fragment'".into(), + error_message: "HTTP failure at https://user:password@example.test/image.cosi?sig=secret#fragment".into(), + subkind: "image-load-failed".into(), + location: None, + }, + )))); + let mut model = Model::new(); + let entry = model.event(event); + assert!(model.details.contains("https://example.test/image.cosi")); + for secret in ["user", "password", "sig=secret", "fragment"] { + assert!(!model.details.contains(secret), "{}", model.details); + assert!(!entry.plain().contains(secret)); + } + } + + /// A failed recovery shell cannot erase a successful servicing result or its reboot. + #[test] + fn shell_exit_failure_is_only_a_warning() { + let mut model = Model::new(); + model.event(Event::Response(ServicingEvent::Completed(Ok( + ClientCompletion { + reboot: RebootDisposition::Required, + servicing_kind: Some(ServicingKind::CleanInstall), + image_hash: None, + }, + )))); + let reboot_at = model.reboot_at; + assert!(reboot_at.is_some()); + assert!(shell_result_event(Ok(Ok(()))).is_none()); + let warning = model.event(shell_result_event(Ok(Err(anyhow!("exit 1")))).unwrap()); + assert_eq!(warning.level, LogLevel::Warn); + assert!(warning.plain().contains("Recovery shell failed: exit 1")); + assert_eq!(model.screen, Screen::Success); + assert!(!model.failed); + assert_eq!(model.reboot_at, reboot_at); + } + + /// Recovery reports invalid reloaded configuration instead of using defaults. + #[tokio::test] + async fn recovery_reloads_configuration_without_using_defaults_on_error() { + let root = TempDir::new().unwrap(); + let path = root.path().join("installer.toml"); + for (text, diagnostic) in [("", "mode"), ("mode = 'not-a-mode'", "not-a-mode")] { + fs::write(&path, text).unwrap(); + let (tx, mut rx) = mpsc::channel(EVENT_CAPACITY); + let worker = spawn_operation(path.clone(), Request::Autorun, false, tx); + let Event::Error { details, uncertain } = rx.recv().await.unwrap() else { + panic!("Invalid settings must fail before preparing a source"); + }; + assert!(!uncertain); + assert!(details.contains(diagnostic), "{details}"); + worker.await.unwrap().unwrap(); + rx.try_recv().unwrap_err(); + } + } + + /// An enqueued completion must be handled before the worker stops blocking power actions. + #[tokio::test] + async fn pending_completion_keeps_worker_active() { + let (tx, mut rx) = mpsc::channel(EVENT_CAPACITY); + let worker = task::spawn(async move { + tx.send(Event::Response(ServicingEvent::Completed(Ok( + ClientCompletion { + reboot: RebootDisposition::NotRequired, + servicing_kind: Some(ServicingKind::CleanInstall), + image_hash: None, + }, + )))) + .await + .unwrap(); + Ok::<(), Error>(()) + }); + time::timeout(Duration::from_secs(1), async { + while !worker.is_finished() { + task::yield_now().await; + } + }) + .await + .unwrap(); + + let mut model = Model::new(); + model.screen = Screen::Recovery; + model.selected = 3; + assert!(!rx.is_empty()); + assert_eq!( + model.key(enter(), !(rx.is_empty() && worker.is_finished())), + Some(Action::BlockedPower) + ); + model.event(rx.recv().await.unwrap()); + assert!(rx.is_empty()); + assert_eq!(model.screen, Screen::Success); + worker.await.unwrap().unwrap(); + } + + /// An uncertain terminal event queued behind a full batch must block shutdown. + #[tokio::test] + async fn pending_disconnect_cannot_release_power_guard() { + let (tx, mut rx) = mpsc::channel(EVENT_CAPACITY); + let worker = task::spawn(async move { + for _ in 0..EVENT_CAPACITY { + tx.send(Event::Preparing("Still writing".into())) + .await + .unwrap(); + } + tx.send(Event::Error { + details: "gRPC stream disconnected".into(), + uncertain: true, + }) + .await + .unwrap(); + Ok::<(), Error>(()) + }); + for _ in 0..EVENT_CAPACITY { + rx.recv().await.unwrap(); + } + time::timeout(Duration::from_secs(1), async { + while !worker.is_finished() { + task::yield_now().await; + } + }) + .await + .unwrap(); + + let mut model = Model::new(); + model.screen = Screen::Recovery; + model.selected = 3; + assert!(!rx.is_empty()); + assert_eq!( + model.key(enter(), !(rx.is_empty() && worker.is_finished())), + Some(Action::BlockedPower) + ); + model.event(rx.recv().await.unwrap()); + assert!(model.uncertain); + model.screen = Screen::Recovery; + model.selected = 3; + assert_eq!(model.key(enter(), false), Some(Action::BlockedPower)); + worker.await.unwrap().unwrap(); + } + + /// Rechecking an empty queue before worker completion misses a late disconnect. + #[tokio::test] + async fn disconnect_between_worker_and_queue_checks_stays_guarded() { + let (tx, mut rx) = mpsc::channel(EVENT_CAPACITY); + let (release, ready) = oneshot::channel::<()>(); + let worker = task::spawn(async move { + ready.await.unwrap(); + tx.send(Event::Error { + details: "gRPC stream disconnected".into(), + uncertain: true, + }) + .await + .unwrap(); + Ok::<(), Error>(()) + }); + let previously_empty = rx.is_empty(); + release.send(()).unwrap(); + time::timeout(Duration::from_secs(1), async { + while !worker.is_finished() { + task::yield_now().await; + } + }) + .await + .unwrap(); + assert!(previously_empty && worker.is_finished()); + assert!(!rx.is_empty()); + + let mut model = Model::new(); + model.screen = Screen::Recovery; + model.selected = 3; + assert_eq!( + model.key(enter(), !(worker.is_finished() && rx.is_empty())), + Some(Action::BlockedPower) + ); + model.event(rx.recv().await.unwrap()); + assert!(model.uncertain); + model.screen = Screen::Recovery; + model.selected = 3; + assert_eq!(model.key(enter(), false), Some(Action::BlockedPower)); + worker.await.unwrap().unwrap(); + } +} diff --git a/crates/installer/src/ui/model.rs b/crates/installer/src/ui/model.rs new file mode 100644 index 0000000000..2a82193fe7 --- /dev/null +++ b/crates/installer/src/ui/model.rs @@ -0,0 +1,841 @@ +//! Installer screen state, actions and bounded log history. + +use std::{ + borrow::Cow, + collections::VecDeque, + time::{Duration, Instant}, +}; + +use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; +use log::{Level, LevelFilter}; +use ratatui::{ + style::{Color, Modifier, Style}, + text::{Line, Span}, +}; +use trident_client::{LogLevel, ServicingEvent}; + +use crate::{ + client::{self, Completion, Event}, + config::SerialVerbosity, + source::{self, Request}, +}; + +use super::theme::{ + theme_color, COLOR_DEBUG, COLOR_ERROR, COLOR_INFO, COLOR_INST, COLOR_SUCCESS, COLOR_TRACE, + COLOR_TRIDENT, COLOR_WARN, VERBOSITY_LEVELS, +}; + +/// Give operators time to remove installer media before the automatic reboot. +const REBOOT_DELAY: Duration = Duration::from_secs(5); +/// Limit in-memory display history; the private diagnostic file keeps complete records. +const LOG_CAPACITY: usize = 500; +/// Bound work spent rendering one record without shortening saved diagnostics. +const DISPLAY_LOG_CHARACTERS: usize = 4096; + +/// Screen state used by both Ratatui and the plain-text fallback. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Screen { + Progress, + Error, + /// Actions after a failed attempt when no worker is active. + Recovery, + Success, + StreamUrl, + HostConfigUrl, + /// Limited actions while an operation may still be writing. + Menu, +} + +/// Distinguishes local installer messages from records sent by Trident. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum LogSource { + Inst, + Trident, +} + +impl LogSource { + /// Returns the source tag used in both displayed and mirrored diagnostics. + fn label(self) -> &'static str { + match self { + Self::Inst => "INST", + Self::Trident => "TRIDENT", + } + } + + /// Uses the source's theme color or its Linux VT equivalent. + fn color(self, linux_vt: bool) -> Color { + theme_color( + match self { + Self::Inst => COLOR_INST, + Self::Trident => COLOR_TRIDENT, + }, + linux_vt, + ) + } +} + +/// One diagnostic, with a shortened copy retained in UI history. +#[derive(Debug, Clone)] +pub(super) struct LogEntry { + /// Time since this installation attempt began. + pub(super) elapsed: Duration, + /// Controls the source tag and its color in both output modes. + pub(super) source: LogSource, + /// Used by display and serial filters independently. + pub(super) level: LogLevel, + /// Full message for output; the copy in `Model::logs` may be shortened. + pub(super) message: String, + /// Keeps a success or failure record visible even under a restrictive filter. + pub(super) result_color: Option, +} + +impl LogEntry { + /// Formats elapsed time as a minutes-and-seconds prefix without wrapping at an hour. + fn prefix(&self) -> String { + let seconds = self.elapsed.as_secs(); + format!("{:02}:{:02} [", seconds / 60, seconds % 60) + } + + /// Prefixes each line of a diagnostic for plain output and serial mirrors. + pub(super) fn plain(&self) -> String { + let prefix = format!( + "{}{}:{}] ", + self.prefix(), + self.source.label(), + level_label(self.level) + ); + display_text(&self.message) + .split('\n') + .map(|line| format!("{prefix}{line}")) + .collect::>() + .join("\n") + } + + /// Styles the source and severity separately, highlighting result records as a whole. + pub(super) fn styled(&self, linux_vt: bool) -> Line<'_> { + let level = Style::default().fg(theme_color( + self.result_color.unwrap_or(log_color(self.level)), + linux_vt, + )); + let surrounding = self + .result_color + .map(|color| Style::default().fg(theme_color(color, linux_vt))) + .unwrap_or_default(); + Line::from(vec![ + Span::styled(self.prefix(), surrounding), + Span::styled( + self.source.label(), + Style::default().fg(self.source.color(linux_vt)), + ), + Span::styled(":", surrounding), + Span::styled(level_label(self.level), level.add_modifier(Modifier::BOLD)), + Span::styled("] ", surrounding), + Span::styled(self.message.as_str(), level), + ]) + } +} + +/// Mutable UI state; events and keys change it without directly performing I/O. +#[derive(Debug)] +pub(super) struct Model { + /// Current page, including recovery menus shown while work may still run. + pub(super) screen: Screen, + /// Sanitized description of the current Host Configuration or COSI source. + pub(super) source: String, + /// Short, most recent progress message above the log panel. + pub(super) activity: String, + /// Current result or failure, retained for the detailed error view. + pub(super) details: String, + /// Bounded, single-line copies of diagnostics; complete entries go to the log file. + pub(super) logs: VecDeque, + /// On-screen filter; changing it does not discard stored records. + pub(super) verbosity: LevelFilter, + /// Separate serial filter loaded from installer settings. + pub(super) serial_verbosity: LevelFilter, + /// Whether the display-only log filter is being edited. + pub(super) verbosity_open: bool, + /// Highlighted option in the log filter picker. + pub(super) verbosity_selected: usize, + /// Highlighted action on the current screen. + pub(super) selected: usize, + /// Wrapped log rows to scroll back, or detail rows when details are open. + pub(super) scroll: u16, + /// Recovery URL under edit; it is validated before starting a request. + pub(super) url: String, + /// The daemon may still be writing; block power actions until idleness is confirmed. + pub(super) uncertain: bool, + /// Media settings can disable the otherwise automatic reboot. + reboot: bool, + /// Countdown starts only after Trident reports completed work needing reboot. + pub(super) reboot_at: Option, + /// Reset at each attempt so elapsed times refer to the current operation. + pub(super) started: Instant, + /// Headless runs return an error if recovery requires a terminal. + pub(super) failed: bool, + /// Toggle between retained logs and the full failure details. + error_details_open: bool, + /// Selects ANSI palette roles instead of raw RGB for graphical Linux VTs. + pub(super) linux_vt: bool, +} + +impl Model { + /// Starts on the progress screen with default display and serial log levels. + pub(super) fn new() -> Self { + Self { + screen: Screen::Progress, + source: String::new(), + activity: "Preparing installer".into(), + details: String::new(), + logs: VecDeque::new(), + verbosity: LevelFilter::Debug, + serial_verbosity: SerialVerbosity::Debug.filter(), + verbosity_open: false, + verbosity_selected: 4, + selected: 0, + scroll: 0, + url: String::new(), + uncertain: false, + reboot: true, + reboot_at: None, + started: Instant::now(), + failed: false, + error_details_open: false, + linux_vt: false, + } + } + + /// Records a failure, preserving any earlier uncertainty and cancelling automatic reboot. + pub(super) fn fail(&mut self, details: String, uncertain: bool) -> LogEntry { + self.details = details.clone(); + self.uncertain |= uncertain; + self.reboot_at = None; + self.failed = true; + self.scroll = 0; + self.selected = 0; + self.screen = Screen::Error; + self.error_details_open = false; + self.result_log(LogLevel::Error, format!("FAILURE: {details}"), COLOR_ERROR) + } + + /// Retains a bounded, single-line display copy while returning the full diagnostic. + pub(super) fn log(&mut self, source: LogSource, level: LogLevel, message: String) -> LogEntry { + let entry = LogEntry { + elapsed: self.started.elapsed(), + source, + level, + message: display_text(&message), + result_color: None, + }; + let mut characters = entry.message.chars(); + let mut displayed = characters + .by_ref() + .take(DISPLAY_LOG_CHARACTERS) + .collect::() + .replace('\n', " "); + if characters.next().is_some() { + displayed.push_str(" [Display shortened; full record preserved in diagnostic log]"); + } + if self.logs.len() == LOG_CAPACITY { + self.logs.pop_front(); + } + self.logs.push_back(LogEntry { + message: displayed, + ..entry.clone() + }); + entry + } + + /// Marks an installer result record with a color even when logs are filtered. + fn result_log(&mut self, level: LogLevel, message: String, color: Color) -> LogEntry { + let mut entry = self.log(LogSource::Inst, level, message); + entry.result_color = Some(color); + if let Some(last) = self.logs.back_mut() { + last.result_color = Some(color); + } + entry + } + + /// Applies a worker event to the current screen and returns its diagnostic record. + pub(super) fn event(&mut self, event: Event) -> LogEntry { + match event { + Event::InstallerLog { level, message } => self.log( + LogSource::Inst, + match level { + Level::Error => LogLevel::Error, + Level::Warn => LogLevel::Warn, + Level::Info => LogLevel::Info, + Level::Debug => LogLevel::Debug, + Level::Trace => LogLevel::Trace, + }, + message, + ), + Event::Preparing(activity) => { + self.activity = activity.clone(); + self.log(LogSource::Inst, LogLevel::Info, activity) + } + Event::Prepared { + description, + reboot, + serial_verbosity, + } => { + self.source = description.clone(); + self.reboot = reboot; + self.serial_verbosity = serial_verbosity.filter(); + self.log(LogSource::Inst, LogLevel::Info, description) + } + Event::IdleConfirmed => { + self.uncertain = false; + self.log( + LogSource::Inst, + LogLevel::Info, + "Trident confirmed that no servicing is active".into(), + ) + } + Event::Error { details, uncertain } => self.fail(details, uncertain), + Event::Response(response) => match response { + ServicingEvent::Started { .. } => { + self.activity = "Servicing started".into(); + self.log(LogSource::Inst, LogLevel::Info, self.activity.clone()) + } + ServicingEvent::Log(log) => { + let level = log.level; + if level == LogLevel::Info { + self.activity = display_text(&log.message); + } + self.log(LogSource::Trident, level, log.message) + } + ServicingEvent::Completed(completed) => match client::completion(completed) { + Ok(Completion::Success { + reboot_required, + performed, + }) => { + self.uncertain = false; + self.failed = false; + self.screen = Screen::Success; + self.selected = 0; + self.details = if performed { + "Installation completed successfully.\nRemove the installation media before booting the installed OS.".into() + } else { + "Trident reported that no servicing was performed.".into() + }; + self.reboot_at = (self.reboot && reboot_required && performed) + .then(|| Instant::now() + REBOOT_DELAY); + self.result_log( + LogLevel::Info, + format!("SUCCESS: {}", self.details), + COLOR_SUCCESS, + ) + } + Ok(Completion::Failure(details)) => { + self.uncertain = false; + self.fail(details, false) + } + Err(error) => { + let details = format!("{error:#}"); + self.fail(details, true) + } + }, + _ => self.fail( + "Unsupported Trident servicing event; installation outcome is unknown".into(), + true, + ), + }, + } + } + + /// Lists actions in keyboard-selection order for the current screen. + pub(super) fn choices(&self) -> Vec<&'static str> { + match self.screen { + Screen::Recovery => { + let mut actions = vec![ + "Shell", + "Stream COSI from URL", + "Install from Host Configuration URL", + ]; + if !self.uncertain { + actions.push("Shutdown"); + } + actions + } + Screen::Success => vec!["Reboot", "Shell"], + Screen::Menu => vec!["Return to installation", "Shell"], + Screen::Error => vec!["Continue to recovery", "Shell"], + _ => Vec::new(), + } + } + + /// Shows the log panel on result screens unless full error details are open. + pub(super) fn showing_logs(&self) -> bool { + matches!( + self.screen, + Screen::Progress | Screen::Menu | Screen::Success + ) || self.screen == Screen::Error && !self.error_details_open + } + + /// Updates navigation for a key press and returns an action only when one is requested. + /// URL entry and the verbosity picker consume keys before screen-level shortcuts; + /// a running worker or uncertain outcome blocks power even on a stale screen. + pub(super) fn key(&mut self, key: KeyEvent, worker_active: bool) -> Option { + if !matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) { + return None; + } + if self.verbosity_open { + match key.code { + KeyCode::Esc => self.verbosity_open = false, + KeyCode::Up | KeyCode::BackTab => { + self.verbosity_selected = (self.verbosity_selected + VERBOSITY_LEVELS.len() + - 1) + % VERBOSITY_LEVELS.len(); + } + KeyCode::Down | KeyCode::Tab => { + self.verbosity_selected = + (self.verbosity_selected + 1) % VERBOSITY_LEVELS.len(); + } + KeyCode::Char(digit) if digit.is_ascii_digit() => { + if let Some(index) = digit.to_digit(10).and_then(|value| value.checked_sub(1)) { + if (index as usize) < VERBOSITY_LEVELS.len() { + self.verbosity_selected = index as usize; + } + } + } + KeyCode::Enter => { + self.verbosity = VERBOSITY_LEVELS[self.verbosity_selected]; + self.verbosity_open = false; + self.scroll = 0; + } + _ => {} + } + return None; + } + if matches!(self.screen, Screen::StreamUrl | Screen::HostConfigUrl) { + return match key.code { + KeyCode::Esc => { + self.screen = Screen::Recovery; + None + } + KeyCode::Backspace => { + self.url.pop(); + None + } + KeyCode::Char(c) if !c.is_control() => { + self.url.push(c); + None + } + KeyCode::Enter => match source::remote_url(self.url.trim()) { + Ok(url) => Some(Action::Start(if self.screen == Screen::StreamUrl { + Request::Stream(url) + } else { + Request::HostConfiguration(url.to_string()) + })), + Err(error) => { + self.fail(format!("{error:#}"), false); + None + } + }, + _ => None, + }; + } + if self.screen == Screen::Error && matches!(key.code, KeyCode::Char('d' | 'D')) { + self.error_details_open = !self.error_details_open; + self.scroll = 0; + return None; + } + if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') { + self.screen = if worker_active || self.screen == Screen::Progress { + Screen::Menu + } else { + Screen::Recovery + }; + self.selected = 0; + return None; + } + let count = self.choices().len(); + match key.code { + KeyCode::Char(digit) if digit.is_ascii_digit() => { + if let Some(index) = digit.to_digit(10).and_then(|value| value.checked_sub(1)) { + if (index as usize) < count { + self.selected = index as usize; + } + } + } + KeyCode::Char('s') => return Some(Action::Shell), + KeyCode::Char('v' | 'V') => { + self.verbosity_selected = VERBOSITY_LEVELS + .iter() + .position(|level| *level == self.verbosity) + .expect("invariant: all log levels are present in the verbosity picker"); + self.verbosity_open = true; + return None; + } + KeyCode::PageUp => { + self.scroll = if self.showing_logs() { + self.scroll.saturating_add(5) + } else { + self.scroll.saturating_sub(5) + }; + return None; + } + KeyCode::PageDown => { + self.scroll = if self.showing_logs() { + self.scroll.saturating_sub(5) + } else { + self.scroll.saturating_add(5) + }; + return None; + } + KeyCode::Esc => { + if self.screen == Screen::Error && self.error_details_open { + self.error_details_open = false; + self.scroll = 0; + return None; + } + self.screen = match self.screen { + Screen::Progress => Screen::Menu, + Screen::Menu => Screen::Progress, + Screen::Error => Screen::Recovery, + other => other, + }; + self.selected = 0; + return None; + } + _ => {} + } + if count == 0 { + return None; + } + match key.code { + KeyCode::Up | KeyCode::BackTab => self.selected = (self.selected + count - 1) % count, + KeyCode::Down | KeyCode::Tab => self.selected = (self.selected + 1) % count, + KeyCode::Enter => { + let action = match (self.screen, self.selected) { + (Screen::Recovery, 0) + | (Screen::Success, 1) + | (Screen::Menu, 1) + | (Screen::Error, 1) => Some(Action::Shell), + (Screen::Recovery, 1) => { + self.url.clear(); + self.screen = Screen::StreamUrl; + None + } + (Screen::Recovery, 2) => { + self.url.clear(); + self.screen = Screen::HostConfigUrl; + None + } + (Screen::Recovery, 3) => Some(Action::Poweroff), + (Screen::Success, 0) => Some(Action::Reboot), + (Screen::Menu, 0) => { + self.screen = Screen::Progress; + None + } + (Screen::Error, 0) => { + self.screen = Screen::Recovery; + self.selected = 0; + None + } + _ => None, + }; + return if (worker_active || self.uncertain) + && matches!(action, Some(Action::Reboot | Action::Poweroff)) + { + Some(Action::BlockedPower) + } else { + action + }; + } + _ => {} + } + None + } +} + +/// A request for the runtime to act; key handling itself never starts servicing. +#[derive(Debug, PartialEq, Eq)] +pub(super) enum Action { + /// Launch the selected recovery operation after releasing any previous worker. + Start(Request), + Shell, + /// Reject power actions while a worker runs or the prior outcome is uncertain. + BlockedPower, + Reboot, + Poweroff, +} + +/// Removes terminal control characters while retaining newlines and expanding tabs. +pub(super) fn display_text(text: &str) -> String { + text.chars() + .filter(|c| !c.is_control() || *c == '\n' || *c == '\t') + .collect::() + .replace('\t', " ") +} + +/// Compares a Trident severity against the chosen display filter. +pub(super) fn log_visible(level: LogLevel, verbosity: LevelFilter) -> bool { + let level = match level { + LogLevel::Error => Level::Error, + LogLevel::Warn | LogLevel::Unspecified | LogLevel::Unknown(_) => Level::Warn, + LogLevel::Info => Level::Info, + LogLevel::Debug => Level::Debug, + LogLevel::Trace => Level::Trace, + _ => Level::Warn, + }; + level.to_level_filter() <= verbosity +} + +/// Preserves the uppercase severity names used by TUI and serial records. +fn level_label(level: LogLevel) -> Cow<'static, str> { + match level { + LogLevel::Error => Cow::Borrowed("ERROR"), + LogLevel::Warn => Cow::Borrowed("WARN"), + LogLevel::Info => Cow::Borrowed("INFO"), + LogLevel::Debug => Cow::Borrowed("DEBUG"), + LogLevel::Trace => Cow::Borrowed("TRACE"), + LogLevel::Unspecified => Cow::Borrowed("UNSPECIFIED"), + LogLevel::Unknown(value) => Cow::Owned(format!("UNKNOWN({value})")), + _ => Cow::Borrowed("UNSUPPORTED"), + } +} + +/// Selects the severity color for Trident and installer records. +fn log_color(level: LogLevel) -> Color { + match level { + LogLevel::Error => COLOR_ERROR, + LogLevel::Warn | LogLevel::Unspecified | LogLevel::Unknown(_) => COLOR_WARN, + LogLevel::Info => COLOR_INFO, + LogLevel::Debug => COLOR_DEBUG, + LogLevel::Trace => COLOR_TRACE, + _ => COLOR_WARN, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use trident_client::{ + Completion as ClientCompletion, LogRecord, RebootDisposition, ServicingKind, + }; + + use crate::config::Config; + + /// Creates an unmodified Enter press for navigation tests. + fn enter() -> KeyEvent { + KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE) + } + + /// Changing display verbosity hides entries without deleting retained logs. + #[test] + fn live_verbosity_picker_filters_without_discarding_logs() { + let mut model = Model::new(); + model.log(LogSource::Inst, LogLevel::Info, "ordinary event".into()); + model.log( + LogSource::Trident, + LogLevel::Trace, + "diagnostic detail".into(), + ); + assert_eq!(model.verbosity, LevelFilter::Debug); + assert!(!log_visible(LogLevel::Trace, model.verbosity)); + model.key(KeyEvent::new(KeyCode::Char('v'), KeyModifiers::NONE), false); + assert!(model.verbosity_open); + model.key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE), false); + model.key(enter(), false); + assert_eq!(model.verbosity, LevelFilter::Trace); + assert!(!model.verbosity_open); + assert!(log_visible(LogLevel::Trace, model.verbosity)); + assert_eq!(model.logs.len(), 2); + model.key(KeyEvent::new(KeyCode::Char('v'), KeyModifiers::NONE), false); + model.key(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE), false); + model.key(enter(), false); + assert_eq!(model.verbosity, LevelFilter::Off); + assert!(!log_visible(LogLevel::Error, model.verbosity)); + assert_eq!(model.logs.len(), 2); + } + + /// Preparation events replace the initial idle activity with the current step. + #[test] + fn preparation_steps_replace_the_idle_status() { + let mut model = Model::new(); + let step = "Looking for installer media by filesystem label"; + let entry = model.event(Event::Preparing(step.into())); + assert_eq!(entry.source, LogSource::Inst); + assert_eq!(entry.message, step); + assert_eq!(model.activity, step); + } + + /// Installer logger events retain their own source tag and severity styling. + #[test] + fn installer_logger_records_use_inst_source_and_colour() { + let mut model = Model::new(); + let entry = model.event(Event::InstallerLog { + level: Level::Debug, + message: "Loaded installer settings".into(), + }); + assert_eq!(entry.source, LogSource::Inst); + assert_eq!( + entry.plain(), + "00:00 [INST:DEBUG] Loaded installer settings" + ); + assert_eq!( + entry.styled(false).spans[1].style.fg, + Some(Color::Rgb(171, 186, 196)) + ); + assert_eq!( + entry.styled(false).spans[3].style.fg, + Some(Color::Rgb(167, 180, 189)) + ); + assert_eq!(model.logs.len(), 1); + } + + /// Domain logs retain Trident's source tag and update the displayed activity. + #[test] + fn trident_domain_log_event_updates_activity_and_serial_record() { + let mut model = Model::new(); + let entry = model.event(Event::Response(ServicingEvent::Log(LogRecord { + timestamp: None, + level: LogLevel::Info, + message: "Preparing storage".into(), + module: String::new(), + target: String::new(), + location: None, + }))); + assert_eq!(entry.source, LogSource::Trident); + assert_eq!(model.activity, "Preparing storage"); + assert_eq!(entry.plain(), "00:00 [TRIDENT:INFO] Preparing storage"); + } + + /// Unknown daemon severities remain identifiable in serial output and visible as warnings. + #[test] + fn unknown_log_level_is_not_silently_discarded() { + let mut model = Model::new(); + let entry = model.event(Event::Response(ServicingEvent::Log(LogRecord { + timestamp: None, + level: LogLevel::Unknown(42), + message: "New severity".into(), + module: String::new(), + target: String::new(), + location: None, + }))); + assert_eq!(entry.plain(), "00:00 [TRIDENT:UNKNOWN(42)] New severity"); + assert!(log_visible(entry.level, LevelFilter::Warn)); + assert_eq!(log_color(entry.level), COLOR_WARN); + } + + /// The autorun default schedules a reboot when servicing requires one. + #[test] + fn headless_autorun_keeps_automatic_reboot_enabled_by_default() { + let config = Config::parse("mode = 'autorun'\nserialMode = 'logs'").unwrap(); + let mut model = Model::new(); + model.reboot = config.autorun.reboot; + model.event(Event::Response(ServicingEvent::Completed(Ok( + ClientCompletion { + reboot: RebootDisposition::Required, + servicing_kind: None, + image_hash: None, + }, + )))); + assert!(model.reboot_at.is_some()); + } + + /// Unknown servicing kinds fail rather than triggering an automatic reboot. + #[test] + fn unknown_completion_kind_does_not_claim_success() { + let mut model = Model::new(); + model.reboot = true; + let entry = model.event(Event::Response(ServicingEvent::Completed(Ok( + ClientCompletion { + reboot: RebootDisposition::Required, + servicing_kind: Some(ServicingKind::Unknown(42)), + image_hash: None, + }, + )))); + assert!(model.failed); + assert!(model.uncertain); + assert!(model.reboot_at.is_none()); + assert!(entry.plain().contains("Unsupported daemon servicing kind")); + } + + /// Missing inputs produce a tagged failure record suitable for serial output. + #[test] + fn errors_for_missing_inputs_are_tagged_for_serial_without_a_tui() { + let mut model = Model::new(); + let entry = model.event(Event::Error { + details: "No image or Host Configuration".into(), + uncertain: false, + }); + assert!(model.failed); + assert_eq!( + entry.plain(), + "00:00 [INST:ERROR] FAILURE: No image or Host Configuration" + ); + } + + /// Continuing from an error opens recovery; shell actions leave their screen unchanged. + #[test] + fn error_continue_and_shell_keep_the_originating_screen() { + let mut model = Model::new(); + model.fail("Complete diagnostic information".into(), false); + assert!(model.key(enter(), false).is_none()); + assert_eq!(model.screen, Screen::Recovery); + assert_eq!(model.key(enter(), false), Some(Action::Shell)); + assert_eq!(model.screen, Screen::Recovery); + assert_eq!(model.details, "Complete diagnostic information"); + model.screen = Screen::Success; + model.selected = 1; + assert_eq!(model.key(enter(), false), Some(Action::Shell)); + assert_eq!(model.screen, Screen::Success); + model.selected = 0; + assert_eq!(model.key(enter(), false), Some(Action::Reboot)); + } + + /// Repeated interrupts and power choices cannot shut down an active installation. + #[test] + fn active_worker_cannot_reach_a_power_action() { + let mut model = Model::new(); + let interrupt = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL); + model.key(interrupt, true); + assert_eq!(model.screen, Screen::Menu); + model.key(interrupt, true); + assert_eq!(model.screen, Screen::Menu); + + model.screen = Screen::Recovery; + model.selected = 3; + assert_eq!(model.key(enter(), true), Some(Action::BlockedPower)); + assert_eq!(model.key(enter(), false), Some(Action::Poweroff)); + model.screen = Screen::Success; + model.selected = 0; + assert_eq!(model.key(enter(), true), Some(Action::BlockedPower)); + } + + /// Losing the client stream must not make shutdown safe until Trident confirms idleness. + #[test] + fn uncertain_outcome_blocks_power_after_worker_exits() { + let mut model = Model::new(); + model.event(Event::Error { + details: "gRPC stream disconnected; servicing may continue".into(), + uncertain: true, + }); + model.screen = Screen::Recovery; + model.selected = 3; + assert!(!model.choices().contains(&"Shutdown")); + assert_eq!(model.key(enter(), false), Some(Action::BlockedPower)); + + model.event(Event::IdleConfirmed); + assert!(!model.uncertain); + assert!(model.choices().contains(&"Shutdown")); + assert_eq!(model.key(enter(), false), Some(Action::Poweroff)); + + model.event(Event::Error { + details: "Another stream disconnected".into(), + uncertain: true, + }); + model.event(Event::Response(ServicingEvent::Completed(Ok( + ClientCompletion { + reboot: RebootDisposition::NotRequired, + servicing_kind: Some(ServicingKind::CleanInstall), + image_hash: None, + }, + )))); + assert!(!model.uncertain); + assert_eq!(model.key(enter(), false), Some(Action::Reboot)); + } +} diff --git a/crates/installer/src/ui/output.rs b/crates/installer/src/ui/output.rs new file mode 100644 index 0000000000..343088b8af --- /dev/null +++ b/crates/installer/src/ui/output.rs @@ -0,0 +1,147 @@ +//! Persists installer diagnostics and mirrors eligible records to serial consoles. + +use std::{fs::File, io::Write, path::PathBuf}; + +use anyhow::{Context, Error}; +use log::{warn, LevelFilter}; + +use crate::client::Event; + +use super::model::{log_visible, LogEntry}; + +/// Writes complete diagnostics privately and mirrors filtered status to serial ports. +pub(crate) struct Output { + /// Opened by startup with restrictive permissions; optional in tests. + pub(crate) log: Option, + /// Device paths identify failing mirrors so only those ports are disabled. + pub(crate) mirrors: Vec<(PathBuf, File)>, +} + +impl Output { + /// Preserve the event before the UI shortens its display copy. + pub(super) fn record(&mut self, event: &Event) -> Result<(), Error> { + if let Some(log) = &mut self.log { + writeln!(log, "{event:#?}").context("Failed to preserve installer diagnostics")?; + log.flush()?; + } + Ok(()) + } + + /// Sends visible records to serial mirrors, dropping mirrors that fail to write. + pub(super) fn announce(&mut self, entry: &LogEntry, verbosity: LevelFilter) { + if !log_visible(entry.level, verbosity) { + return; + } + self.mirrors.retain_mut(|(path, mirror)| { + if let Err(error) = writeln!(mirror, "{}", entry.plain()) { + warn!( + "Stopped mirroring installer status to '{}': {error}", + path.display() + ); + return false; + } + true + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use std::{ + fs::{self, OpenOptions}, + time::Duration, + }; + + use tempfile::TempDir; + use trident_client::LogLevel; + + use crate::config::SerialVerbosity; + + use super::super::model::{LogSource, Model}; + + /// A failed serial destination is removed without blocking healthy mirrors. + #[test] + fn unavailable_serial_mirror_does_not_stop_the_installer() { + let root = TempDir::new().unwrap(); + let transcript = root.path().join("serial.log"); + let mut output = Output { + log: None, + mirrors: vec![ + ( + PathBuf::from("/dev/full"), + OpenOptions::new().write(true).open("/dev/full").unwrap(), + ), + ( + transcript.clone(), + OpenOptions::new() + .create(true) + .truncate(true) + .write(true) + .open(&transcript) + .unwrap(), + ), + ], + }; + let entry = LogEntry { + elapsed: Duration::from_secs(125), + source: LogSource::Inst, + level: LogLevel::Info, + message: "Preparing installer".into(), + result_color: None, + }; + output.announce(&entry, LevelFilter::Debug); + assert_eq!(output.mirrors.len(), 1); + output.announce( + &LogEntry { + message: "Still running".into(), + ..entry + }, + LevelFilter::Debug, + ); + assert_eq!( + fs::read_to_string(transcript).unwrap(), + "02:05 [INST:INFO] Preparing installer\n02:05 [INST:INFO] Still running\n" + ); + } + + /// Serial filtering preserves line prefixes and does not change display filtering. + #[test] + fn serial_verbosity_filters_independently_of_display() { + let mut model = Model::new(); + let root = TempDir::new().unwrap(); + let serial = root.path().join("serial.log"); + let mut output = Output { + log: None, + mirrors: vec![(serial.clone(), File::create(&serial).unwrap())], + }; + for level in [ + LogLevel::Error, + LogLevel::Warn, + LogLevel::Info, + LogLevel::Debug, + LogLevel::Trace, + ] { + let entry = model.log(LogSource::Trident, level, "first\nsecond".into()); + output.announce(&entry, SerialVerbosity::Debug.filter()); + } + let text = fs::read_to_string(&serial).unwrap(); + let lines = text.lines().collect::>(); + assert_eq!(lines.len(), 8); + assert!(lines.iter().all(|line| line.starts_with("00:00 [TRIDENT:"))); + assert_eq!(lines[0], "00:00 [TRIDENT:ERROR] first"); + assert_eq!(lines[1], "00:00 [TRIDENT:ERROR] second"); + assert!(!text.contains("\\n")); + let trace = model.log(LogSource::Trident, LogLevel::Trace, "trace detail".into()); + output.announce(&trace, SerialVerbosity::Trace.filter()); + let text = fs::read_to_string(serial).unwrap(); + assert!(text + .lines() + .last() + .unwrap() + .ends_with("[TRIDENT:TRACE] trace detail")); + assert!(!log_visible(LogLevel::Trace, model.verbosity)); + assert_eq!(model.logs.len(), 6); + } +} diff --git a/crates/installer/src/ui/render.rs b/crates/installer/src/ui/render.rs new file mode 100644 index 0000000000..1aaed363a8 --- /dev/null +++ b/crates/installer/src/ui/render.rs @@ -0,0 +1,721 @@ +//! Draws the Ratatui screens, their action lists and the scrollable log panel. + +use std::time::Instant; + +use ratatui::{ + layout::{Alignment, Constraint, Layout, Rect}, + style::{Color, Modifier, Style}, + symbols::border::Set as BorderSet, + text::{Line, Span}, + widgets::{Block, Borders, Clear, List, ListItem, Paragraph, Wrap}, + Frame, +}; + +use crate::APPLICATION_NAME; + +use super::{ + model::{display_text, log_visible, Model, Screen}, + theme::{ + theme_color, COLOR_BACKGROUND, COLOR_BRAND, COLOR_ERROR, COLOR_FRAME, COLOR_SUCCESS, + VERBOSITY_LEVELS, + }, +}; + +/// Reserve space for the wordmark, name and state on a standard terminal. +const WORDMARK_HEADER_HEIGHT: u16 = 12; +/// Keep a readable two-line heading when the wordmark does not fit. +const COMPACT_HEADER_HEIGHT: u16 = 2; +/// Leave enough height for logs and actions beneath the full wordmark. +const MIN_WORDMARK_TERMINAL_HEIGHT: u16 = 24; +/// Trident name drawn without relying on terminal-specific fonts or graphics. +const TRIDENT_WORDMARK: [&str; 8] = [ + r#"88888888888 d8b 888 888"#, + r#" 888 Y8P 888 888"#, + r#" 888 888 888"#, + r#" 888 888d888 888 .d88888 .d88b. 88888b. 888888"#, + r#" 888 888P" 888 d88" 888 d8P Y8b 888 "88b 888"#, + r#" 888 888 888 888 888 88888888 888 888 888"#, + r#" 888 888 888 Y88b 888 Y8b. 888 888 Y88b."#, + r#" 888 888 888 "Y88888 "Y8888 888 888 "Y888"#, +]; +/// ASCII borders remain legible on Linux VTs and serial-like terminals. +const ASCII_BORDER: BorderSet = BorderSet { + top_left: "+", + top_right: "+", + bottom_left: "+", + bottom_right: "+", + vertical_left: "|", + vertical_right: "|", + horizontal_top: "-", + horizontal_bottom: "-", +}; + +/// Use the same screen headings in Ratatui and plain terminal output. +pub(super) fn title(screen: Screen) -> &'static str { + match screen { + Screen::Progress => "INSTALLING", + Screen::Error => "INSTALLATION ERROR", + Screen::Recovery => "RECOVERY", + Screen::Success => "INSTALLATION COMPLETE", + Screen::StreamUrl => "STREAM COSI FROM URL", + Screen::HostConfigUrl => "INSTALL FROM HOST CONFIGURATION URL", + Screen::Menu => "INSTALLER MENU", + } +} + +/// Gives panels a consistent ASCII border and VT-aware background. +fn block(title: &str, linux_vt: bool) -> Block<'_> { + Block::default() + .borders(Borders::ALL) + .border_set(ASCII_BORDER) + .style(Style::default().bg(theme_color(COLOR_BACKGROUND, linux_vt))) + .border_style(Style::default().fg(theme_color(COLOR_FRAME, linux_vt))) + .title(title) +} + +/// Center against the widest row; the ASCII rows do not all have equal width. +fn wordmark_width() -> usize { + TRIDENT_WORDMARK + .iter() + .fold(0, |width, row| width.max(row.len())) +} + +/// Reserves wordmark space only when both the terminal width and height fit it. +fn header_height(viewport: Rect) -> u16 { + if usize::from(viewport.width) >= wordmark_width() + && viewport.height >= MIN_WORDMARK_TERMINAL_HEIGHT + { + WORDMARK_HEADER_HEIGHT + } else { + COMPACT_HEADER_HEIGHT + } +} + +/// Draws the wordmark when space permits, plus the installer status. +fn render_header(frame: &mut Frame, area: Rect, state: &str, state_color: Color, linux_vt: bool) { + let brand = Style::default() + .fg(theme_color(COLOR_BRAND, linux_vt)) + .add_modifier(Modifier::BOLD); + let mut lines = Vec::new(); + if area.height >= WORDMARK_HEADER_HEIGHT { + lines.push(Line::default()); + let width = wordmark_width(); + lines.extend( + TRIDENT_WORDMARK + .iter() + .map(|row| Line::from(Span::styled(format!("{row: Paragraph<'_> { + let (title, color) = match model.screen { + Screen::Success => ("SUCCESS - Installation complete", COLOR_SUCCESS), + Screen::Error => ("FAILURE - Installation stopped", COLOR_ERROR), + _ => ("Activity / logs", COLOR_FRAME), + }; + let mut lines = Vec::new(); + let header_lines = if matches!(model.screen, Screen::Progress | Screen::Menu) { + 2 + } else { + 0 + }; + if header_lines > 0 { + lines.push(Line::from(Span::styled( + model.activity.clone(), + Style::default().fg(theme_color(COLOR_BRAND, model.linux_vt)), + ))); + lines.push(Line::default()); + } + let mut logs = model + .logs + .iter() + .filter(|entry| entry.result_color.is_some() || log_visible(entry.level, model.verbosity)) + .collect::>(); + if matches!(model.screen, Screen::Success | Screen::Error) { + if let Some(index) = logs.iter().rposition(|entry| entry.result_color.is_some()) { + let result = logs.remove(index); + logs.push(result); + } + } + lines.extend(logs.into_iter().map(|entry| entry.styled(model.linux_vt))); + let block = Block::default() + .borders(Borders::ALL) + .border_set(ASCII_BORDER) + .style(Style::default().bg(theme_color(COLOR_BACKGROUND, model.linux_vt))) + .border_style(Style::default().fg(theme_color(color, model.linux_vt))) + .title(Span::styled( + title, + Style::default().fg(theme_color(color, model.linux_vt)), + )); + let paragraph = Paragraph::new(lines).wrap(Wrap { trim: false }); + let visible_rows = usize::from(area.height.saturating_sub(2)); + // Wrapped rows, not entry counts, determine whether the final result remains visible. + let total_rows = paragraph.line_count(area.width.saturating_sub(2).max(1)); + let offset = total_rows + .saturating_sub(visible_rows) + .saturating_sub(usize::from(model.scroll)); + paragraph + .block(block) + .scroll((u16::try_from(offset).unwrap_or(u16::MAX), 0)) +} + +/// Draws the current screen, actions, log controls, and any pending reboot countdown. +pub(super) fn render(frame: &mut Frame, model: &Model) { + frame.render_widget( + Block::default().style(Style::default().bg(theme_color(COLOR_BACKGROUND, model.linux_vt))), + frame.area(), + ); + let choices = model.choices(); + let action_height = if choices.is_empty() { + 0 + } else { + u16::try_from(choices.len()) + .expect("invariant: static action lists have at most four items") + + 2 + }; + let areas = Layout::vertical([ + Constraint::Length(header_height(frame.area())), + Constraint::Length(match model.screen { + Screen::Recovery => 0, + _ => 2, + }), + Constraint::Min(3), + Constraint::Length(action_height), + Constraint::Length(2), + ]) + .split(frame.area()); + render_header( + frame, + areas[0], + title(model.screen), + match model.screen { + Screen::Error => COLOR_ERROR, + Screen::Success => COLOR_SUCCESS, + _ => COLOR_BRAND, + }, + model.linux_vt, + ); + if areas[1].width > 22 { + let operation = + Layout::horizontal([Constraint::Min(0), Constraint::Length(21)]).split(areas[1]); + frame.render_widget( + Paragraph::new(display_text(&model.source)).wrap(Wrap { trim: false }), + operation[0], + ); + frame.render_widget( + Paragraph::new(format!("Logs: {} [V]", model.verbosity)) + .alignment(Alignment::Right) + .style(Style::default().fg(theme_color(COLOR_BRAND, model.linux_vt))), + operation[1], + ); + } else { + frame.render_widget( + Paragraph::new(display_text(&model.source)).wrap(Wrap { trim: false }), + areas[1], + ); + } + let content = match model.screen { + _ if model.showing_logs() => log_panel(model, areas[2]), + Screen::StreamUrl | Screen::HostConfigUrl => Paragraph::new(format!( + "Enter an http:// or https:// URL:\n\n{}\n\nEnter: start Esc: back", + display_text(&model.url) + )) + .block(block("Remote source", model.linux_vt)) + .wrap(Wrap { trim: false }), + Screen::Error => Paragraph::new(display_text(&model.details)) + .block( + block("Full error details / Esc to return", model.linux_vt) + .border_style(Style::default().fg(theme_color(COLOR_ERROR, model.linux_vt))), + ) + .wrap(Wrap { trim: false }) + .scroll((model.scroll, 0)), + _ => Paragraph::new(display_text(&model.details)) + .block(block("Result", model.linux_vt)) + .wrap(Wrap { trim: false }), + }; + frame.render_widget(content, areas[2]); + let choices = choices + .iter() + .enumerate() + .map(|(index, choice)| { + ListItem::new(format!( + "{} {choice}", + if index == model.selected { ">" } else { " " } + )) + .style(if index == model.selected { + Style::default() + .fg(theme_color(COLOR_BRAND, model.linux_vt)) + .add_modifier(Modifier::BOLD) + } else { + Style::default() + }) + }) + .collect::>(); + frame.render_widget( + List::new(choices).block(block("Actions", model.linux_vt)), + areas[3], + ); + let countdown = model + .reboot_at + .map(|deadline| { + format!( + "Automatic reboot in {}s; Shell holds reboot", + deadline.saturating_duration_since(Instant::now()).as_secs() + ) + }) + .unwrap_or_else(|| format!("Elapsed {}s", model.started.elapsed().as_secs())); + let controls = if matches!(model.screen, Screen::StreamUrl | Screen::HostConfigUrl) { + "Enter: start Esc: return to recovery".to_owned() + } else { + format!( + "Arrows: choose Enter: select S: shell V: logs{} Esc: back", + if model.screen == Screen::Error { + " D: details" + } else { + "" + }, + ) + }; + frame.render_widget( + Paragraph::new(format!("{controls}\n{countdown}")) + .style(Style::default().fg(theme_color(COLOR_BRAND, model.linux_vt))), + areas[4], + ); + if model.verbosity_open { + render_verbosity_picker(frame, model); + } +} + +/// Overlays the display-only log filter without modifying the stored diagnostics. +fn render_verbosity_picker(frame: &mut Frame, model: &Model) { + let viewport = frame.area(); + let width = viewport.width.min(44); + let height = viewport.height.min(10); + let area = Rect::new( + viewport.x + (viewport.width - width) / 2, + viewport.y + (viewport.height - height) / 2, + width, + height, + ); + frame.render_widget(Clear, area); + let rows = VERBOSITY_LEVELS + .iter() + .enumerate() + .map(|(index, level)| { + Line::from(Span::styled( + format!( + "{} {level}", + if index == model.verbosity_selected { + ">" + } else { + " " + } + ), + if index == model.verbosity_selected { + Style::default() + .fg(theme_color(COLOR_BRAND, model.linux_vt)) + .add_modifier(Modifier::BOLD) + } else { + Style::default() + }, + )) + }) + .chain([Line::default(), Line::from("Enter: apply Esc: cancel")]) + .collect::>(); + frame.render_widget( + Paragraph::new(rows).block(block("Log verbosity / display only", model.linux_vt)), + area, + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; + use log::LevelFilter; + use ratatui::{backend::TestBackend, style::Color, Terminal}; + + use trident_client::{ + Completion as ClientCompletion, LogLevel, RebootDisposition, ServicingEvent, ServicingKind, + }; + + use crate::{client::Event, APPLICATION_NAME}; + + use super::super::{ + model::LogSource, + theme::{vt_rgb_palette, COLOR_DEBUG, COLOR_INFO, COLOR_TRACE}, + }; + + /// The full-size header and background keep their intended colors and spacing. + #[test] + fn wordmark_and_background_use_clear_neutrals_palette_at_80_by_24() { + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + terminal.draw(|frame| render(frame, &Model::new())).unwrap(); + let buffer = terminal.backend().buffer(); + assert_eq!(buffer.content[0].bg, Color::Rgb(11, 17, 24)); + assert_eq!(buffer.content[14 * 80].fg, Color::Rgb(53, 69, 83)); + let padding = (80 - wordmark_width()) / 2; + assert!(buffer.content[..80].iter().all(|cell| cell.symbol() == " ")); + for (row_index, expected) in TRIDENT_WORDMARK.iter().enumerate() { + let row_index = row_index + 1; + let row = buffer.content[row_index * 80..(row_index + 1) * 80] + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert_eq!(&row[padding..padding + expected.len()], *expected); + for column in padding..padding + expected.len() { + assert_eq!( + buffer.content[row_index * 80 + column].fg, + Color::Rgb(75, 216, 220) + ); + } + assert!(buffer.content[9 * 80..10 * 80] + .iter() + .all(|cell| cell.symbol() == " ")); + } + let text = buffer + .content + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert!(text.contains(APPLICATION_NAME), "{text}"); + assert!(text.contains("INSTALLING"), "{text}"); + } + + /// RPC log severities and the Trident source receive independent colors. + #[test] + fn rpc_logs_are_coloured_by_severity() { + let mut model = Model::new(); + model.verbosity = LevelFilter::Trace; + let records = [ + (LogLevel::Error, "error-line", Color::Rgb(255, 107, 115)), + (LogLevel::Warn, "warn-line", Color::Rgb(245, 182, 93)), + (LogLevel::Info, "info-line", Color::Rgb(229, 234, 236)), + (LogLevel::Debug, "debug-line", Color::Rgb(167, 180, 189)), + (LogLevel::Trace, "trace-line", Color::Rgb(99, 115, 129)), + ]; + for (level, text, _) in records { + model.log(LogSource::Trident, level, text.into()); + } + let mut terminal = Terminal::new(TestBackend::new(80, 32)).unwrap(); + terminal.draw(|frame| render(frame, &model)).unwrap(); + let buffer = terminal.backend().buffer(); + for (_, message, expected) in records { + let row = buffer + .content + .chunks(80) + .find(|row| { + row.iter() + .map(|cell| cell.symbol()) + .collect::() + .contains(message) + }) + .unwrap(); + let text = row.iter().map(|cell| cell.symbol()).collect::(); + assert_eq!(row[text.find(message).unwrap()].fg, expected); + let source = text.find("TRIDENT").unwrap(); + assert_eq!(row[source].fg, Color::Rgb(114, 185, 165)); + } + } + + /// VT palette slots distinguish log severities without changing RGB-mode colors. + #[test] + fn linux_vt_palette_uses_distinct_slots_for_a1_log_levels() { + let entries = vt_rgb_palette().unwrap(); + assert!(entries.contains(&(15, 229, 234, 236))); + assert!(entries.contains(&(7, 167, 180, 189))); + assert!(entries.contains(&(8, 99, 115, 129))); + assert_eq!(theme_color(COLOR_INFO, true), Color::White); + assert_eq!(theme_color(COLOR_DEBUG, true), Color::Gray); + assert_eq!(theme_color(COLOR_TRACE, true), Color::DarkGray); + assert_eq!(theme_color(COLOR_SUCCESS, true), Color::LightGreen); + assert_eq!(theme_color(COLOR_DEBUG, false), Color::Rgb(167, 180, 189)); + + let mut model = Model::new(); + model.linux_vt = true; + model.verbosity = LevelFilter::Trace; + for (level, message) in [ + (LogLevel::Info, "info-vt"), + (LogLevel::Debug, "debug-vt"), + (LogLevel::Trace, "trace-vt"), + ] { + model.log(LogSource::Trident, level, message.into()); + } + let mut terminal = Terminal::new(TestBackend::new(80, 32)).unwrap(); + terminal.draw(|frame| render(frame, &model)).unwrap(); + let buffer = terminal.backend().buffer(); + for (message, expected) in [ + ("info-vt", Color::White), + ("debug-vt", Color::Gray), + ("trace-vt", Color::DarkGray), + ] { + let row = buffer + .content + .chunks(80) + .find(|row| { + row.iter() + .map(|cell| cell.symbol()) + .collect::() + .contains(message) + }) + .unwrap(); + let text = row.iter().map(|cell| cell.symbol()).collect::(); + assert_eq!(row[text.find(message).unwrap()].fg, expected); + } + } + + /// The source and verbosity indicator both fit on the standard-width status line. + #[test] + fn operation_and_verbosity_share_one_line() { + let mut model = Model::new(); + model.source = "StreamDisk from file:///media/cosi/payload.cosi".into(); + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + terminal.draw(|frame| render(frame, &model)).unwrap(); + let row = terminal.backend().buffer().content[12 * 80..13 * 80] + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert!(row.contains("StreamDisk from file://"), "{row}"); + assert!(row.contains("Logs: DEBUG [V]"), "{row}"); + } + + /// A success result remains highlighted even when earlier logs are filtered out. + #[test] + fn success_keeps_prior_logs_and_highlights_the_final_record() { + let mut model = Model::new(); + model.log( + LogSource::Trident, + LogLevel::Debug, + "Earlier disk action".into(), + ); + let result = model.event(Event::Response(ServicingEvent::Completed(Ok( + ClientCompletion { + reboot: RebootDisposition::NotRequired, + servicing_kind: None, + image_hash: None, + }, + )))); + assert_eq!(result.result_color, Some(Color::Rgb(93, 200, 148))); + assert_eq!( + result.plain(), + "00:00 [INST:INFO] SUCCESS: Installation completed successfully.\n\ + 00:00 [INST:INFO] Remove the installation media before booting the installed OS." + ); + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + terminal.draw(|frame| render(frame, &model)).unwrap(); + let rows = terminal + .backend() + .buffer() + .content + .chunks(80) + .collect::>(); + let rendered = rows + .iter() + .map(|row| row.iter().map(|cell| cell.symbol()).collect::()) + .collect::>(); + let title = rendered + .iter() + .position(|row| row.contains("SUCCESS - Installation complete")) + .unwrap(); + assert_eq!( + rows[title][rendered[title].find("SUCCESS").unwrap()].fg, + Color::Rgb(93, 200, 148) + ); + let result_row = rendered + .iter() + .position(|row| row.contains("SUCCESS: Installation")) + .unwrap(); + assert_eq!( + rows[result_row][rendered[result_row].find("SUCCESS:").unwrap()].fg, + Color::Rgb(93, 200, 148) + ); + model.key(KeyEvent::new(KeyCode::PageUp, KeyModifiers::NONE), false); + terminal.draw(|frame| render(frame, &model)).unwrap(); + let earlier = terminal + .backend() + .buffer() + .content + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert!(earlier.contains("Earlier disk action")); + model.scroll = 0; + model.verbosity = LevelFilter::Off; + terminal.draw(|frame| render(frame, &model)).unwrap(); + let text = terminal + .backend() + .buffer() + .content + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert!(text.contains("SUCCESS: Installation")); + assert!(!text.contains("Earlier disk action")); + } + + /// Wrapped diagnostics and activity cannot hide the latest result at 80x24. + #[test] + fn wrapped_log_rows_keep_the_result_visible_and_scrollable() { + let mut model = Model::new(); + model.log( + LogSource::Trident, + LogLevel::Info, + "Long preceding diagnostic ".repeat(40), + ); + model.event(Event::Response(ServicingEvent::Completed(Ok( + ClientCompletion { + reboot: RebootDisposition::NotRequired, + servicing_kind: Some(ServicingKind::CleanInstall), + image_hash: None, + }, + )))); + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + let visible_text = |terminal: &Terminal| { + terminal + .backend() + .buffer() + .content + .iter() + .map(|cell| cell.symbol()) + .collect::() + }; + terminal.draw(|frame| render(frame, &model)).unwrap(); + assert!( + visible_text(&terminal).contains("SUCCESS: Installation"), + "{}", + visible_text(&terminal) + ); + model.key(KeyEvent::new(KeyCode::PageUp, KeyModifiers::NONE), false); + terminal.draw(|frame| render(frame, &model)).unwrap(); + assert!(!visible_text(&terminal).contains("SUCCESS: Installation")); + model.key(KeyEvent::new(KeyCode::PageDown, KeyModifiers::NONE), false); + terminal.draw(|frame| render(frame, &model)).unwrap(); + assert!(visible_text(&terminal).contains("SUCCESS: Installation")); + + model.screen = Screen::Progress; + model.activity = "Scanning media ".repeat(60); + model.log(LogSource::Inst, LogLevel::Info, "Latest activity".into()); + terminal.draw(|frame| render(frame, &model)).unwrap(); + assert!(visible_text(&terminal).contains("Latest activity")); + } + + /// Failures show prior logs first while still allowing full diagnostic details. + #[test] + fn failure_shows_logs_by_default_and_keeps_full_details_accessible() { + let mut model = Model::new(); + model.log(LogSource::Trident, LogLevel::Warn, "Earlier warning".into()); + let result = model.event(Event::Error { + details: "Network timeout\nUnderlying transport failure".into(), + uncertain: false, + }); + assert_eq!(result.result_color, Some(Color::Rgb(255, 107, 115))); + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + terminal.draw(|frame| render(frame, &model)).unwrap(); + let text = terminal + .backend() + .buffer() + .content + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert!(text.contains("FAILURE - Installation stopped")); + assert!(text.contains("Earlier warning")); + assert!(text.contains("FAILURE: Network timeout")); + for marker in ["FAILURE - Installation stopped", "FAILURE: Network timeout"] { + let row = terminal + .backend() + .buffer() + .content + .chunks(80) + .find(|row| { + row.iter() + .map(|cell| cell.symbol()) + .collect::() + .contains(marker) + }) + .unwrap(); + let content = row.iter().map(|cell| cell.symbol()).collect::(); + assert_eq!( + row[content.find(marker).unwrap()].fg, + Color::Rgb(255, 107, 115) + ); + } + model.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE), false); + assert!(!model.showing_logs()); + terminal.draw(|frame| render(frame, &model)).unwrap(); + let text = terminal + .backend() + .buffer() + .content + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert!(text.contains("Underlying transport failure")); + model.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE), false); + assert_eq!(model.screen, Screen::Error); + assert!(model.showing_logs()); + } + + /// Compact layouts retain the application heading and available actions. + #[test] + fn small_terminals_use_a_readable_compact_header() { + assert_eq!( + header_height(Rect::new(0, 0, 40, 24)), + COMPACT_HEADER_HEIGHT + ); + assert_eq!( + header_height(Rect::new(0, 0, 80, 16)), + COMPACT_HEADER_HEIGHT + ); + let mut model = Model::new(); + model.screen = Screen::Success; + let mut terminal = Terminal::new(TestBackend::new(40, 16)).unwrap(); + terminal.draw(|frame| render(frame, &model)).unwrap(); + let text = terminal + .backend() + .buffer() + .content + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert!(text.contains(APPLICATION_NAME), "{text}"); + assert!(text.contains("Reboot"), "{text}"); + assert!(text.contains("Shell"), "{text}"); + } + + /// Standard-size result and recovery screens expose their expected actions. + #[test] + fn screens_render_at_80_by_24_with_visible_actions() { + for screen in [Screen::Recovery, Screen::Success, Screen::Error] { + let mut model = Model::new(); + model.screen = screen; + model.details = "Diagnostic or result details".into(); + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + terminal.draw(|frame| render(frame, &model)).unwrap(); + let text = terminal + .backend() + .buffer() + .content + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert!(text.contains("Shell"), "{text}"); + if screen == Screen::Success { + assert!(text.contains("Reboot"), "{text}"); + } + if screen == Screen::Recovery { + assert!(text.contains("Shutdown"), "{text}"); + } + } + } +} diff --git a/crates/installer/src/ui/theme.rs b/crates/installer/src/ui/theme.rs new file mode 100644 index 0000000000..fcf274d1bf --- /dev/null +++ b/crates/installer/src/ui/theme.rs @@ -0,0 +1,80 @@ +//! Shares the terminal colour palette between logs, rendering and Linux VT setup. + +use std::io; + +use log::LevelFilter; +use ratatui::style::Color; + +/// Keep the same dark surface across Ratatui panels and the Linux VT palette. +pub(super) const COLOR_BACKGROUND: Color = Color::Rgb(11, 17, 24); +/// Neutral borders distinguish ordinary panels from success and failure. +pub(super) const COLOR_FRAME: Color = Color::Rgb(53, 69, 83); +/// Highlight the wordmark, selected controls and current activity. +pub(super) const COLOR_BRAND: Color = Color::Rgb(75, 216, 220); +/// Source tag for messages produced by the installer itself. +pub(super) const COLOR_INST: Color = Color::Rgb(171, 186, 196); +/// Source tag for logs received from the Trident daemon. +pub(super) const COLOR_TRIDENT: Color = Color::Rgb(114, 185, 165); +/// Failure frame and error severity share one palette role. +pub(super) const COLOR_ERROR: Color = Color::Rgb(255, 107, 115); +/// Unknown daemon levels receive the same attention as warnings. +pub(super) const COLOR_WARN: Color = Color::Rgb(245, 182, 93); +/// Informational records stay readable against the dark background. +pub(super) const COLOR_INFO: Color = Color::Rgb(229, 234, 236); +/// Debug records remain legible without competing with results. +pub(super) const COLOR_DEBUG: Color = Color::Rgb(167, 180, 189); +/// Trace records are the least prominent diagnostic level. +pub(super) const COLOR_TRACE: Color = Color::Rgb(99, 115, 129); +/// Successful completion uses a distinct result color. +pub(super) const COLOR_SUCCESS: Color = Color::Rgb(93, 200, 148); +/// Linux VT maps RGB requests into 16 ANSI colors, so each role needs its own slot. +const VT_PALETTE: &[(u8, Color, Color)] = &[ + (0, COLOR_BACKGROUND, Color::Black), + (1, COLOR_ERROR, Color::Red), + (2, COLOR_TRIDENT, Color::Green), + (3, COLOR_WARN, Color::Yellow), + (4, COLOR_FRAME, Color::Blue), + (5, COLOR_INST, Color::Magenta), + (6, COLOR_BRAND, Color::Cyan), + (7, COLOR_DEBUG, Color::Gray), + (8, COLOR_TRACE, Color::DarkGray), + (10, COLOR_SUCCESS, Color::LightGreen), + (15, COLOR_INFO, Color::White), +]; + +/// One stable order for the picker and its number-key shortcuts. +pub(super) const VERBOSITY_LEVELS: [LevelFilter; 6] = [ + LevelFilter::Off, + LevelFilter::Error, + LevelFilter::Warn, + LevelFilter::Info, + LevelFilter::Debug, + LevelFilter::Trace, +]; + +/// Maps known theme RGB colors to distinct ANSI roles on Linux VTs. +/// Other colors and non-VT terminals retain the original value. +pub(super) fn theme_color(color: Color, linux_vt: bool) -> Color { + if !linux_vt { + return color; + } + VT_PALETTE + .iter() + .find(|(_, rgb, _)| *rgb == color) + .map(|(_, _, ansi)| *ansi) + .unwrap_or(color) +} + +/// Builds the Linux VT palette entries, rejecting any theme slot without an RGB value. +pub(super) fn vt_rgb_palette() -> Result, io::Error> { + VT_PALETTE + .iter() + .map(|(slot, color, _)| match color { + Color::Rgb(red, green, blue) => Ok((*slot, *red, *green, *blue)), + other => Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("Linux VT palette requires RGB values, got {other:?}"), + )), + }) + .collect() +} diff --git a/crates/osutils/Cargo.toml b/crates/osutils/Cargo.toml index 9480233ee2..9efb364438 100644 --- a/crates/osutils/Cargo.toml +++ b/crates/osutils/Cargo.toml @@ -19,7 +19,7 @@ indoc = {workspace = true} inventory = {workspace = true} log = {workspace = true, features = ["std"]} netplan-types = {workspace = true} -nix = {workspace = true, features = ["fs"]} +nix = {workspace = true, features = ["fs", "process", "term"]} once_cell = {workspace = true} openssl = {workspace = true} serde = {workspace = true} @@ -51,4 +51,5 @@ rand = {workspace = true} [features] functional-test = ["pytest", "test-utilities"] pytest-generator = ["pytest"] +run-interactive = [] test-utilities = ["rand"] diff --git a/crates/osutils/src/dependencies.rs b/crates/osutils/src/dependencies.rs index 61b4b6d445..932a588c5a 100644 --- a/crates/osutils/src/dependencies.rs +++ b/crates/osutils/src/dependencies.rs @@ -14,6 +14,12 @@ use trident_api::error::{ ExecutionEnvironmentMisconfigurationError, ServicingError, TridentError, TridentResultExt, }; +#[cfg(feature = "run-interactive")] +mod interactive; + +#[cfg(feature = "run-interactive")] +pub use interactive::set_foreground_group; + #[derive(Debug, thiserror::Error)] pub enum DependencyError { #[error("Failed to find dependency '{dependency}': {source}")] @@ -88,6 +94,7 @@ impl DependencyResultExt for Result> { #[derive(Debug, Clone, Copy, IntoStaticStr)] #[strum(serialize_all = "lowercase")] pub enum Dependency { + Bash, Blkid, Chown, Chpasswd, diff --git a/crates/osutils/src/dependencies/interactive.rs b/crates/osutils/src/dependencies/interactive.rs new file mode 100644 index 0000000000..de82c05066 --- /dev/null +++ b/crates/osutils/src/dependencies/interactive.rs @@ -0,0 +1,105 @@ +use std::{ + fs::File, + io, + os::unix::process::CommandExt, + process::{Command as StdCommand, Output}, +}; + +use nix::{ + sys::signal::{self, SigSet, SigmaskHow, Signal}, + unistd::{self, Pid}, +}; + +use super::{Command, CommandOutput, DependencyError}; + +impl Command { + /// Runs a command on its controlling TTY in a separate foreground process group. + /// + /// Unlike `output()`, a shell needs the real TTY for job control, and keyboard + /// signals must reach the shell rather than its caller. The former foreground + /// group is restored after exit; nonzero exits become [`DependencyError`]. + pub fn run_interactive(&self, terminal: &File) -> Result<(), Box> { + let binary = self.dependency.path()?; + let execute = || -> Result { + if self.stdin_data.is_some() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Interactive commands cannot pipe stdin", + )); + } + let parent_group = unistd::tcgetpgrp(terminal)?; + let mut command = StdCommand::new(&binary); + // A separate group makes keyboard signals target the shell, not the installer. + command + .args(&self.args) + .envs(self.envs.clone()) + .stdin(terminal.try_clone()?) + .stdout(terminal.try_clone()?) + .stderr(terminal.try_clone()?) + .process_group(0); + let mut child = command.spawn()?; + let child_group = Pid::from_raw(i32::try_from(child.id()).map_err(io::Error::other)?); + let foreground = set_foreground_group(terminal, child_group); + if let Err(error) = foreground { + child.kill()?; + child.wait()?; + return Err(error); + } + // The child can stop on SIGTTIN if it reads before the parent hands over the TTY. + let continued = signal::killpg(child_group, Signal::SIGCONT); + let status = child.wait(); + let restored = set_foreground_group(terminal, parent_group); + restored?; + continued?; + // Output went directly to the TTY, not to pipes we could collect here. + Ok(Output { + status: status?, + stdout: Vec::new(), + stderr: Vec::new(), + }) + }; + CommandOutput { + rendered_command: self.render_command(), + dependency: self.dependency, + inner: execute().map_err(|inner| DependencyError::CouldNotExecute { + dependency: self.dependency, + inner, + })?, + } + .check() + } +} + +/// A background process must block SIGTTOU to reclaim the TTY from its child. +pub fn set_foreground_group(terminal: &File, group: Pid) -> io::Result<()> { + let mut blocked = SigSet::empty(); + blocked.add(Signal::SIGTTOU); + let mut previous = SigSet::empty(); + signal::pthread_sigmask(SigmaskHow::SIG_BLOCK, Some(&blocked), Some(&mut previous))?; + let result = unistd::tcsetpgrp(terminal, group); + signal::pthread_sigmask(SigmaskHow::SIG_SETMASK, Some(&previous), None)?; + result?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::dependencies::Dependency; + + #[test] + fn interactive_command_rejects_piped_stdin() { + let terminal = File::open("/dev/null").unwrap(); + let error = Dependency::Echo + .cmd() + .with_stdin(b"not a terminal".to_vec()) + .run_interactive(&terminal) + .unwrap_err(); + assert!(matches!( + *error, + DependencyError::CouldNotExecute { inner, .. } + if inner.kind() == io::ErrorKind::InvalidInput + )); + } +} diff --git a/crates/osutils/src/lsblk.rs b/crates/osutils/src/lsblk.rs index 8b0beb23ef..47b88f8a04 100644 --- a/crates/osutils/src/lsblk.rs +++ b/crates/osutils/src/lsblk.rs @@ -3,7 +3,7 @@ use std::{ path::{Path, PathBuf}, }; -use anyhow::{bail, Context, Error}; +use anyhow::{bail, ensure, Context, Error}; use serde::{Deserialize, Serialize}; use sysdefs::osuuid::OsUuid; @@ -160,17 +160,81 @@ pub enum PartitionTableType { /// structs. /// pub fn list() -> Result, Error> { - let result = Dependency::Lsblk + parse_lsblk_output(&lsblk_output()?) +} + +/// Reads the full device tree once for either block-device or label inspection. +fn lsblk_output() -> Result { + Dependency::Lsblk .cmd() .arg("--json") .arg("--output-all") .arg("--bytes") .output_and_check() - .context("Failed to execute lsblk")?; + .context("Failed to execute lsblk") +} - let parsed: Vec = parse_lsblk_output(result.as_str())?; +/// BlockDevice has no label and requires fields that label discovery does not need. +#[derive(Deserialize, Default)] +struct LabelledDevice { + name: String, + label: Option, + #[serde(default)] + children: Vec, +} + +#[derive(Deserialize)] +struct LabelledDevices { + blockdevices: Vec, +} + +/// Finds all devices with a filesystem label, including devices nested below disks. +pub fn devices_by_label(label: impl AsRef) -> Result, Error> { + let label = label.as_ref(); + ensure!(!label.is_empty(), "Filesystem label must not be empty"); + devices_by_labels(&[label]) +} - Ok(parsed) +/// Finds devices matching any of the given filesystem labels in one `lsblk` scan. +pub fn devices_by_labels(labels: &[&str]) -> Result, Error> { + ensure!( + !labels.is_empty() && labels.iter().all(|label| !label.is_empty()), + "Filesystem labels must not be empty" + ); + let mut devices = Vec::new(); + collect_devices_by_labels( + &parse_labelled_devices(&lsblk_output()?)?, + labels, + &mut devices, + ); + devices.sort(); + devices.dedup(); + Ok(devices) +} + +/// Parses only the fields needed for label discovery without changing `BlockDevice`. +fn parse_labelled_devices(output: &str) -> Result, Error> { + let parsed: LabelledDevices = + serde_json::from_str(output).context("Failed to parse lsblk label output")?; + Ok(parsed.blockdevices) +} + +/// Adds paths of matching devices and their descendants. +fn collect_devices_by_labels( + devices: &[LabelledDevice], + labels: &[&str], + matches: &mut Vec, +) { + for device in devices { + if device + .label + .as_deref() + .is_some_and(|label| labels.contains(&label)) + { + matches.push(Path::new("/dev").join(&device.name)); + } + collect_devices_by_labels(&device.children, labels, matches); + } } /// Finds and returns all block devices (and their children) that match a @@ -307,6 +371,62 @@ where mod tests { use super::*; + #[test] + /// Ensures optical and partition labels both match, and rejects empty label filters. + fn label_scan_includes_cdrom_and_detects_duplicate_filesystem_labels() { + let devices = vec![ + LabelledDevice { + name: "sr0".into(), + label: Some("CDROM".into()), + ..Default::default() + }, + LabelledDevice { + name: "sda".into(), + children: vec![LabelledDevice { + name: "sda1".into(), + label: Some("CDROM".into()), + ..Default::default() + }], + ..Default::default() + }, + ]; + let mut matches = Vec::new(); + collect_devices_by_labels(&devices, &["CDROM"], &mut matches); + matches.sort(); + assert_eq!( + matches, + [PathBuf::from("/dev/sda1"), PathBuf::from("/dev/sr0")] + ); + assert!(devices_by_label("").is_err()); + assert!(devices_by_labels(&[]).is_err()); + assert!(devices_by_labels(&["CDROM", ""]).is_err()); + } + + #[test] + /// Ensures optical-drive labels survive parsing the `lsblk` JSON tree. + fn parses_optical_drive_label_from_lsblk_json() { + let devices = parse_labelled_devices( + r#"{"blockdevices":[{"name":"sr0","size":355497984,"type":"rom","label":"CDROM"}]}"#, + ) + .unwrap(); + let mut matches = Vec::new(); + collect_devices_by_labels(&devices, &["CDROM"], &mut matches); + assert_eq!(matches, [PathBuf::from("/dev/sr0")]); + } + + #[test] + /// Ensures optical and GPT USB labels are both found without choosing between them. + fn parses_gpt_usb_partition_label_from_lsblk_json() { + let output = r#"{"blockdevices":[{"name":"sdb","size":1073741824,"type":"disk","pttype":"gpt","children":[{"name":"sdb1","size":1069547520,"type":"part","fstype":"vfat","label":"TRD_INSTALL"}]},{"name":"sr0","size":355497984,"type":"rom","label":"CDROM"}]}"#; + let devices = parse_labelled_devices(output).unwrap(); + let mut matches = Vec::new(); + collect_devices_by_labels(&devices, &["TRD_INSTALL", "CDROM"], &mut matches); + assert_eq!( + matches, + [PathBuf::from("/dev/sdb1"), PathBuf::from("/dev/sr0")] + ); + } + /// Output obtained from running `lsblk --json --bytes --output-all --paths /dev/sda` /// on the functional test VM AzL 3.0, lsblk from util-linux 2.40.2 const SAMPLE_LSBLK_OUTPUT: &str = indoc::indoc! { diff --git a/crates/osutils/src/systemd.rs b/crates/osutils/src/systemd.rs index 28e6bf5731..2d68b996cd 100644 --- a/crates/osutils/src/systemd.rs +++ b/crates/osutils/src/systemd.rs @@ -42,6 +42,41 @@ where .with_context(|| format!("Failed to restart unit: {}", unit.as_ref())) } +/// Stops the named systemd unit, reporting failures with the unit name. +pub fn stop_unit(unit: impl AsRef) -> Result<(), Error> { + let unit = unit.as_ref(); + Dependency::Systemctl + .cmd() + .args(["stop", unit]) + .run_and_check() + .with_context(|| format!("Failed to stop unit '{unit}'")) +} + +/// Starts the named systemd unit and waits for its start job to finish. +pub fn start_unit(unit: impl AsRef) -> Result<(), Error> { + let unit = unit.as_ref(); + Dependency::Systemctl + .cmd() + .args(["start", unit]) + .run_and_check() + .with_context(|| format!("Failed to start unit '{unit}'")) +} + +/// Requests a reboot through systemd and reports command failures. +pub fn reboot() -> Result<(), Error> { + Dependency::Systemctl.cmd().arg("reboot").run_and_check()?; + Ok(()) +} + +/// Requests a power-off through systemd and reports command failures. +pub fn poweroff() -> Result<(), Error> { + Dependency::Systemctl + .cmd() + .arg("poweroff") + .run_and_check()?; + Ok(()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/docs/Reference/Installer-Configuration.md b/docs/Reference/Installer-Configuration.md new file mode 100644 index 0000000000..a3281e54df --- /dev/null +++ b/docs/Reference/Installer-Configuration.md @@ -0,0 +1,198 @@ +--- +sidebar_position: 8 +title: Installer Configuration +--- + +# Installer Configuration (TOML) + +`trident-installer` reads `/etc/trident/installer.toml` by default. Pass +`--config PATH` to use another file. This TOML file controls the **installer**; +the [Host Configuration](./Host-Configuration/Host-Configuration.md) is a +separate YAML document describing what Trident installs. Installation requires +a readable TOML file. See [Trident Installer](./Installer.md) for the +source-selection and recovery-screen flows. + +The packaged `/etc/trident/installer.toml` explicitly sets: + +```toml +mode = "autorun" +serialMode = "logs" +serialVerbosity = "debug" + +[media] +cosiDirectory = "cosi/" + +[autorun] +reboot = true +``` + +There is **no implicit default for `mode`** in a TOML file: omitting it is an +error, even though the packaged file sets it to `"autorun"`. All other fields +may be omitted; unknown fields and invalid values are errors. + +The packaged file (or the file passed with `--config`) is the **bootstrap +configuration**: it supplies media-discovery settings before an optional +[media-local override](#optional-configuration-on-the-media) can be read. + +## Selecting Install or StreamDisk + +`mode = "autorun"` means **start without an interactive source picker**. The +selected source, not `mode`, determines whether Trident performs Install or +StreamDisk. If the bootstrap configuration names a live-OS or HTTP(S) Host +Configuration whose file-backed inputs do not need installer media, autorun +uses it without looking for media or applying +[media-local overrides](#optional-configuration-on-the-media). Otherwise it +discovers media, applies any overrides, and makes this choice: + +| Priority | Condition | Operation | +| --- | --- | --- | +| 1 | `autorun.hostConfiguration` is set | **Install** using that Host Configuration, even if a COSI is present. | +| 2 | Otherwise, `/etc/trident/config.yaml` exists or is a symlink in the live OS | **Install** using that file, even if a COSI is present. | +| 3 | Otherwise, media contains a `.cosi` file | **StreamDisk** using the first regular COSI in `media.cosiDirectory`, sorted by filename. | +| 4 | Neither source is available | Show recovery actions on the graphical console, or report an error without one. | + +For example, to **Install** from a Host Configuration placed on an +Image Customizer ISO: + +```toml +# /etc/trident/installer.toml in the live installer OS +mode = "autorun" + +[media] +filesystemLabel = "CDROM" + +[autorun] +hostConfiguration = "installer/host.yaml" +reboot = false +``` + +Put `installer/host.yaml` on the ISO filesystem (not only in the live OS). +If its `image.url` is `installer://image`, also put a COSI in `cosi/`. +`installer://image` is a reserved installer-only URL meaning "use the first +regular COSI in `media.cosiDirectory`, sorted by filename"; it does not name +an image file. The operation remains **Install**, with disk layout taken from +the Host Configuration. An explicit image URL in the Host Configuration does +not require a media COSI. See the +[Host Configuration reference](./Host-Configuration/Host-Configuration.md) +for its YAML schema. To **StreamDisk** instead, leave +`autorun.hostConfiguration` unset *and* ensure +`/etc/trident/config.yaml` is absent from the live OS. A specified but +invalid Host Configuration fails rather than falling back to streaming. + +## Fields + +The Default column gives the effective value when a key is omitted, not +necessarily the value written in the packaged file. + +| Key | Default | Description | +| --- | --- | --- | +| `mode` | **None; required** | Set `"autorun"` (as the packaged file does). This is a startup mode, not the Install/StreamDisk selector. `"interactive"` is reserved and rejected. | +| `serialMode` | `"logs"` | Sends plain installer and Trident log records to active serial consoles, without a serial TUI. `"ui"` is reserved and rejected. | +| `serialVerbosity` | `"debug"` | Serial log filter: `"off"`, `"error"`, `"warn"`, `"info"`, `"debug"`, or `"trace"`. Independent of the on-screen log filter, which starts at Debug. | +| `media.filesystemLabel` | Unset (auto) | Exact filesystem label when set. Otherwise find either `TRD_INSTALL` (FAT-compatible USB) or `CDROM` (Image Customizer ISO). If both labels are present, choose neither; specify a label to disambiguate. | +| `media.cdromLabel` | — | Legacy alias for `filesystemLabel`. Do not specify both names. | +| `media.mountPath` | Unset | Absolute path to an **already mounted** filesystem instead of label discovery. Cannot be combined with `filesystemLabel`; this path is not mounted or made read-only by the installer. | +| `media.cosiDirectory` | `"cosi"` | Nonempty directory relative to the media root. Absolute paths and `..` are rejected. Only regular `.cosi` files directly inside it are considered, in filename order. | +| `autorun.hostConfiguration` | Unset | Host Configuration source. When omitted, `/etc/trident/config.yaml` is used **if it exists**; otherwise autorun looks for a COSI. | +| `autorun.reboot` | `true` | Reboot after successful servicing **only if** Trident reports that work was performed and a reboot is required. | +| `autorun.force` | `false` | Legacy key accepted for compatibility but ignored. Autorun never compares installed filesystem UUIDs or asks for repeat-install confirmation. | + +Media-dependent autorun waits up to 60 seconds for late USB/BMC device +enumeration; a self-contained Host Configuration skips discovery entirely. +Discovery fails if more than one device matches the selected/default +labels. The selected filesystem is mounted read-only at +`/run/trident/installer-media`; +the live OS must support its filesystem. A manually selected remote recovery +source does not wait for media. + +### Host Configuration sources + +`autorun.hostConfiguration` accepts: + +| Form | Example | Resolution | +| --- | --- | --- | +| Media-relative path | `"installer/host.yaml"` | Beneath the mounted media root; cannot escape it. | +| Absolute path | `"/etc/trident/config.yaml"` | A file in the live installer OS. | +| File URL | `"file:///etc/trident/config.yaml"` | A file in the live installer OS. | +| HTTP(S) URL | `"https://example.com/host.yaml"` | Fetched over the network. | + +Remote connection and timeout errors are retried for up to 60 seconds while +networking starts; HTTP response errors fail immediately. +Host Configuration input must be valid YAML and is limited to 2 MiB. A Host +Configuration image URL of `installer://image` fails if no COSI is available. +Authored disk paths and image checksums remain unchanged. Media-relative Host +Configuration paths and file-backed inputs on installer media (including +`installer://image`, additional files, script paths, extension images and +recovery keys) require discovery; a default `/etc/trident/config.yaml` symlink +pointing into the media also waits for its target to become available. A Host +Configuration with no media-backed inputs takes precedence over media overlays +even when media is already present. Script content and arguments are not +inspected for embedded paths; use a media-relative Host Configuration when +those depend on the installer media. + +Explicit remote Stream COSI recovery bypasses local media discovery and +overlays, so it remains available when the local media cannot be read. + +Without a Host Configuration, the first regular COSI in `cosiDirectory` is +streamed. If neither source is available, the graphical console offers +recovery; a headless run reports an error instead. **Autorun streams on every +boot from the installer media, even after a successful install:** remove or +deprioritize the media before rebooting into the installed OS. The separate +media safety check still refuses a mounted or read-only disk that Trident +could select as its smallest fitting target, such as a large installer USB. + +## Optional configuration on the media + +For media-dependent installs, after finding or mounting media the installer +merges `installer/installer.toml` from its root over the bootstrap configuration. +For example, this media-local file selects **Install** without changing the +bootstrap file baked into the live OS: + +```toml +# /installer/installer.toml on the media +[autorun] +hostConfiguration = "installer/host.yaml" +reboot = false +``` + +The bootstrap media selection must already match the media for this overlay +to be found. Place the referenced `installer/host.yaml` on the same media. + +The media file can change `serialVerbosity`, `media.cosiDirectory`, `mode`, +and `autorun` options. It cannot change `serialMode`, +`media.filesystemLabel` (including `cdromLabel`), or `media.mountPath`: +those settings are needed to find the media in the first place. Other +fields still undergo the same validation; setting `mode = "interactive"` +remains unsupported. + +## Building an installer ISO + +On a full-OS Azure Linux ISO, install the `trident-installer` RPM and add +`trident.installer=1` to the **ISO boot kernel command line**. Include a +COSI in `cosi/`, or provide a Host Configuration as described above. For +example, the essential Image Customizer settings are: + +```yaml +os: + packages: + install: + - trident-installer +iso: + initramfsType: full-os + additionalFiles: + - source: cosi/payload.cosi + destination: /cosi/payload.cosi + kernelCommandLine: + extraCommandLine: + - trident.installer=1 +``` + +The RPM includes the installer TOML and requires Trident and Bash. It starts +its service on a marked installer boot; the installer starts the gRPC socket +and waits for udev before servicing. It prevents gettys from reclaiming tty1 +or mixing login prompts with serial logs. +No separate service enablement, getty override, or label override is +necessary for a single `CDROM` ISO or `TRD_INSTALL` USB. On an unmarked +normal OS, the service does not run and gettys are unaffected. A Host +Configuration may require additional tools for optional features such as +RAID, encryption, or verity. diff --git a/docs/Reference/Installer.md b/docs/Reference/Installer.md new file mode 100644 index 0000000000..944def4bb4 --- /dev/null +++ b/docs/Reference/Installer.md @@ -0,0 +1,155 @@ +--- +sidebar_position: 7 +title: Trident Installer +--- + +# Trident Installer + +Install the optional `trident-installer` RPM on a full-OS installer ISO and add +`trident.installer=1` to the **ISO boot kernel command line**. The packaged +systemd service starts only when that argument is present; installing the RPM +alone does not start an installation. See +[Installer Configuration](./Installer-Configuration.md#building-an-installer-iso) +for an ISO recipe. + +A [Host Configuration](./Host-Configuration/Host-Configuration.md) (HC) is YAML +describing the OS image, disk layout, and settings for Trident's **Install** +operation. A [Composable OS Image](./Composable-OS-Image.md) (COSI) contains +the image data that **StreamDisk** writes to a disk. **Autorun** selects one +of these operations from the available sources and starts without an initial +confirmation or source picker. The terminal UI shows progress and offers +recovery after a failure or interruption. `mode = "interactive"` is reserved +and currently rejected. + +## Choosing the installation source + +```mermaid +flowchart TD + START(("START: installer boots")) --> CONFIG["Read installer TOML; require autorun"] + CONFIG -->|Invalid| ERROR["ERROR"] + CONFIG --> SELF{"Complete live-OS or HTTP(S) HC without media-backed inputs?"} + SELF -->|Yes| INSTALL["Install with that HC; skip media overrides"] + SELF -->|No| MEDIA["Find installer media; wait up to 60 seconds during autorun"] + MEDIA --> OVERLAY["Apply media-local installer.toml, if present"] + OVERLAY --> HC{"Configured HC or default config.yaml file or symlink?"} + HC -->|Yes| READ["Read HC; resolve installer://image to first media COSI if used"] + READ --> INSTALL + HC -->|No| COSI{"Media contains a COSI?"} + COSI -->|Yes| STREAM["StreamDisk: first regular COSI by filename"] + COSI -->|No| ERROR + STREAM --> PREFLIGHT["Check metadata hash and eligible disk safety"] + PREFLIGHT -->|Failed| ERROR + INSTALL --> TRIDENT["Send operation to Trident over gRPC"] + PREFLIGHT --> TRIDENT + TRIDENT -->|Completed successfully| SUCCESS["SUCCESS"] + TRIDENT -->|Failure or unknown outcome| ERROR + classDef startPoint fill:#07545b,stroke:#77e6db,color:#f0fffc,stroke-width:3px + classDef success fill:#123c2a,stroke:#3fb950,color:#e7ffed,stroke-width:2px + classDef error fill:#52212a,stroke:#f85149,color:#ffe8e5,stroke-width:2px + class START startPoint + class SUCCESS success + class ERROR error +``` + +`installer://image` is a reserved HC image URL meaning "use the first COSI +found on installer media," not a filename. Media is also needed for a +media-relative HC, a dangling HC symlink into the media, or another file-backed +HC input on the media (such as an additional file, script, extension, or +recovery key). A self-contained HC takes +precedence over media settings even if the media is already present. An invalid +HC fails; it does not fall back to StreamDisk. + +StreamDisk preflight reads the COSI's required disk size and metadata hash. It +refuses a mounted or read-only disk that Trident could select as the smallest +one that fits, then passes the hash to Trident so its fetch uses the checked +metadata. See [Installer Configuration](./Installer-Configuration.md) for +accepted paths, filesystem labels, and overrides. + +:::warning Reinstall on every installer boot + +Autorun does not ask for confirmation or check whether the target OS is already +installed. Remove or deprioritize the installer media after installation; +leaving it first in boot order can reimage the machine on every boot. + +::: + +## Screens + +The same screen has the same color in both diagrams: blue **PROGRESS**, amber +**MENU**, red **ERROR**, purple **RECOVERY**, and green **SUCCESS**. Teal circles +mark entry points; teal rectangles are URL-entry screens. + +```mermaid +flowchart TD + START(("START: autorun")) --> P["PROGRESS: activity and logs"] + P -->|Ctrl-C or Esc| M["MENU: Return to installation; Shell"] + M -->|Return or Esc| P + P -->|Completed successfully| S["SUCCESS: Reboot; Shell"] + M -->|Completed successfully| S + P -->|Failure or unknown outcome| E["ERROR: logs; Continue; Shell"] + M -->|Failure or unknown outcome| E + E -->|D| ED["Full error details"] + ED -->|D or Esc| E + E -->|Continue, Esc, or Ctrl-C| R["RECOVERY"] + S -->|Ctrl-C| R + classDef startPoint fill:#07545b,stroke:#77e6db,color:#f0fffc,stroke-width:3px + classDef progress fill:#153858,stroke:#58a6ff,color:#f0f6fc,stroke-width:2px + classDef menu fill:#493416,stroke:#d29922,color:#fff3dc,stroke-width:2px + classDef success fill:#123c2a,stroke:#3fb950,color:#e7ffed,stroke-width:2px + classDef error fill:#52212a,stroke:#f85149,color:#ffe8e5,stroke-width:2px + classDef recovery fill:#342450,stroke:#b392f0,color:#f4ebff,stroke-width:2px + class START startPoint + class P progress + class M menu + class S success + class E,ED error + class R recovery +``` + +```mermaid +flowchart TD + START(("START: enter recovery")) --> R["RECOVERY: Shell; Stream COSI URL; Install HC URL; optional Shutdown"] + R -->|Stream COSI URL| U1["STREAM URL entry"] + R -->|Install HC URL| U2["HOST CONFIG URL entry"] + U1 -->|Esc| R + U2 -->|Esc| R + U1 -->|Invalid URL| E["ERROR"] + U2 -->|Invalid URL| E + U1 -->|Enter valid URL| P["PROGRESS: new attempt"] + U2 -->|Enter valid URL| P + P -->|Success| S["SUCCESS"] + P -->|Failure or unknown outcome| E + R -->|Shutdown when safe| OFF["Power off"] + S -->|Reboot when safe| REBOOT["Reboot"] + S -->|Automatic reboot eligible| TIMER["5-second countdown"] + TIMER --> REBOOT + classDef startPoint fill:#07545b,stroke:#77e6db,color:#f0fffc,stroke-width:3px + classDef progress fill:#153858,stroke:#58a6ff,color:#f0f6fc,stroke-width:2px + classDef success fill:#123c2a,stroke:#3fb950,color:#e7ffed,stroke-width:2px + classDef error fill:#52212a,stroke:#f85149,color:#ffe8e5,stroke-width:2px + classDef recovery fill:#342450,stroke:#b392f0,color:#f4ebff,stroke-width:2px + classDef urlEntry fill:#123c42,stroke:#56d4ca,color:#e5fffc,stroke-width:2px + class START startPoint + class R recovery + class U1,U2 urlEntry + class P progress + class E error + class S success +``` + +| Action | Behavior | +| --- | --- | +| Arrows, Tab, number keys, Enter | Select and activate an action. `V` changes only the display log filter; Page Up/Down scrolls logs or error details. | +| Ctrl-C / Esc | On PROGRESS, open MENU without stopping work; MENU's Esc or Return returns to PROGRESS. On ERROR, Esc or Continue opens RECOVERY; Esc first closes full details if open. On a URL-entry screen, Esc returns to RECOVERY. On SUCCESS, Ctrl-C opens RECOVERY. | +| `D` on ERROR | Toggle between the log panel and full error details. | +| Shell or `S` | Opens a root recovery shell from PROGRESS, MENU, ERROR, RECOVERY, or SUCCESS. Servicing continues and automatic reboot waits while the shell owns the terminal; `exit` returns to the latest screen. A nonzero shell exit is only a warning. | +| Stream COSI URL / Install HC URL | Recovery accepts HTTP(S) URLs without embedded username or password. A new attempt reloads installer TOML. Explicit StreamDisk recovery skips local media; recovery HC checks it once without waiting. | +| Reboot / Shutdown | A running worker or uncertain outcome blocks power actions. Shutdown is not offered while the outcome is uncertain; a later attempt first checks Trident's servicing state before another write. | +| Automatic reboot | Starts five seconds after success **only** when enabled, work was performed, and Trident says a reboot is required. | + +With `--system-console`, the installer uses tty1 for the UI and mirrors logs +to active serial consoles; serial consoles do not receive a TUI. `--plain` +uses line-oriented output instead of the full-screen display. Without an +interactive terminal, autorun still runs, but a failure exits with an error +instead of opening recovery. All received events are retained in the private +`/var/log/trident-installer.log`, regardless of display or serial filtering. diff --git a/packaging/docker/Dockerfile.azl b/packaging/docker/Dockerfile.azl index b1806bc901..db3380d9b1 100644 --- a/packaging/docker/Dockerfile.azl +++ b/packaging/docker/Dockerfile.azl @@ -23,6 +23,7 @@ COPY packaging ./packaging COPY LICENSE NOTICE ./ COPY bin/trident ./target/release/trident COPY bin/trident-acl-agent ./target/release/trident-acl-agent +COPY bin/trident-installer ./target/release/trident-installer ARG TRIDENT_VERSION=dev-build ARG RPM_VER=0.1.0 diff --git a/packaging/etc/installer.toml b/packaging/etc/installer.toml new file mode 100644 index 0000000000..b947c02ba2 --- /dev/null +++ b/packaging/etc/installer.toml @@ -0,0 +1,9 @@ +mode = "autorun" +serialMode = "logs" +serialVerbosity = "debug" + +[media] +cosiDirectory = "cosi/" + +[autorun] +reboot = true diff --git a/packaging/rpm/trident.spec b/packaging/rpm/trident.spec index ee37f3a83c..cec8aeb9e8 100644 --- a/packaging/rpm/trident.spec +++ b/packaging/rpm/trident.spec @@ -251,6 +251,33 @@ The Trident ACL components required to orchestrate servicing of ACL images. # ------------------------------------------------------------------------------ +%package installer +Summary: Trident Linux Installer console for installer media +Requires: %{name} = %{version}-%{release} +Requires: bash +Conflicts: %{name}-install-service + +%description installer +Autorun installer, recovery console, and local demonstration UI. +The service starts only when the ISO boot command line has trident.installer=1. + +%files installer +%license LICENSE NOTICE +%{_bindir}/%{name}-installer +%{_unitdir}/%{name}-installer.service +%{_unitdir}/multi-user.target.wants/%{name}-installer.service +%{_unitdir}/getty@tty1.service.d/%{name}-installer.conf +%{_unitdir}/serial-getty@.service.d/%{name}-installer.conf +%config(noreplace) /etc/%{name}/installer.toml + +%preun installer +%systemd_preun %{name}-installer.service + +%postun installer +%systemd_postun %{name}-installer.service + +# ------------------------------------------------------------------------------ + %if %{undefined rpm_ver} # Use cargo with source and vendor tarballs for distro build %prep @@ -279,7 +306,7 @@ export TRIDENT_VERSION="%{version}-%{release}" # Use %{trident_version} for Trident repo build export TRIDENT_VERSION="%{trident_version}" %endif -cargo build --release -p trident -p trident-acl-agent +cargo build --release --features trident/grpc-preview -p trident -p trident-acl-agent -p installer mkdir selinux cp -p packaging/selinux-policy-trident/trident.fc selinux/ @@ -310,7 +337,14 @@ cargo test --all --no-fail-fast -- --skip test_run_systemd_check --skip test_pre %install install -D -m 755 target/release/%{name} %{buildroot}/%{_bindir}/%{name} install -D -m 755 target/release/%{name}-acl-agent %{buildroot}/%{_bindir}/%{name}-acl-agent +install -D -m 755 target/release/%{name}-installer %{buildroot}/%{_bindir}/%{name}-installer install -D -m 644 packaging/systemd/%{name}-acl-agent.service %{buildroot}%{_unitdir}/%{name}-acl-agent.service +install -D -m 644 packaging/systemd/%{name}-installer.service %{buildroot}%{_unitdir}/%{name}-installer.service +install -d %{buildroot}%{_unitdir}/multi-user.target.wants +ln -s ../%{name}-installer.service %{buildroot}%{_unitdir}/multi-user.target.wants/%{name}-installer.service +install -D -m 644 packaging/systemd/getty@tty1.service.d/%{name}-installer.conf %{buildroot}%{_unitdir}/getty@tty1.service.d/%{name}-installer.conf +install -D -m 644 packaging/systemd/serial-getty@.service.d/%{name}-installer.conf %{buildroot}%{_unitdir}/serial-getty@.service.d/%{name}-installer.conf +install -D -m 644 packaging/etc/installer.toml %{buildroot}/etc/%{name}/installer.toml # Copy Trident SELinux policy module to /usr/share/selinux/packages install -D -m 0644 %{name}.pp.bz2 %{buildroot}%{_datadir}/selinux/packages/%{selinuxtype}/%{name}.pp.bz2 diff --git a/packaging/systemd/getty@tty1.service.d/trident-installer.conf b/packaging/systemd/getty@tty1.service.d/trident-installer.conf new file mode 100644 index 0000000000..de9d71aec8 --- /dev/null +++ b/packaging/systemd/getty@tty1.service.d/trident-installer.conf @@ -0,0 +1,2 @@ +[Unit] +ConditionKernelCommandLine=!trident.installer=1 diff --git a/packaging/systemd/serial-getty@.service.d/trident-installer.conf b/packaging/systemd/serial-getty@.service.d/trident-installer.conf new file mode 100644 index 0000000000..de9d71aec8 --- /dev/null +++ b/packaging/systemd/serial-getty@.service.d/trident-installer.conf @@ -0,0 +1,2 @@ +[Unit] +ConditionKernelCommandLine=!trident.installer=1 diff --git a/packaging/systemd/trident-installer.service b/packaging/systemd/trident-installer.service new file mode 100644 index 0000000000..747e678ee1 --- /dev/null +++ b/packaging/systemd/trident-installer.service @@ -0,0 +1,19 @@ +[Unit] +Description=Trident Linux Installer +ConditionKernelCommandLine=trident.installer=1 +After=network.target +Conflicts=trident-install.service + +[Service] +Type=simple +Environment=TERM=linux +ExecStart=/usr/bin/trident-installer --system-console +StandardInput=null +StandardOutput=journal +StandardError=journal +TimeoutStartSec=infinity +Restart=no +SendSIGHUP=yes + +[Install] +WantedBy=multi-user.target