From cce363d12d80bfd8de2624c3fa3a36a3894549d4 Mon Sep 17 00:00:00 2001 From: Helight Date: Sat, 14 Nov 2026 23:38:09 +0100 Subject: [PATCH 01/94] feat(serve)!: remove the browser page berth serve no longer takes --web, and berth has no web feature. berth-remote is the client for a server elsewhere. --- Cargo.lock | 383 +------------------- Cargo.toml | 21 +- container/berth.Dockerfile | 7 +- crates/berth-api/Cargo.toml | 2 +- crates/berth-page/Cargo.toml | 3 +- crates/berth-page/src/app.rs | 77 +--- crates/berth-page/src/device.rs | 25 +- crates/berth-page/src/home.rs | 35 +- crates/berth-page/src/installed.rs | 8 +- crates/berth-page/src/lib.rs | 6 +- crates/berth-page/src/portal.rs | 13 +- crates/berth-page/src/setup.rs | 4 +- crates/berth-remote/Cargo.toml | 2 +- crates/berth-remote/src/device.rs | 32 +- crates/berth-remote/src/lib.rs | 8 +- crates/berth-remote/src/socket.rs | 5 +- crates/berth-tui/Cargo.toml | 3 +- crates/berth-tui/src/berth_key.rs | 2 +- crates/berth-tui/src/event.rs | 4 +- crates/berth-tui/src/host.rs | 2 +- crates/berth-tui/src/lib.rs | 4 +- crates/berth-tui/src/machine.rs | 3 +- crates/berth-tui/src/page.rs | 2 +- crates/berth-tui/src/plugins.rs | 6 +- crates/berth-tui/src/provisioners.rs | 2 +- crates/berth-tui/src/qr.rs | 136 +------ crates/berth-tui/src/setup.rs | 2 +- crates/berth-web/Cargo.toml | 29 -- crates/berth-web/index.html | 35 -- crates/berth-web/src/browser.rs | 511 --------------------------- crates/berth-web/src/main.rs | 19 - crates/berth-web/src/socket.rs | 72 ---- crates/berth/Cargo.toml | 9 - crates/berth/build.rs | 127 ------- crates/berth/src/serve/mod.rs | 27 +- crates/berth/src/serve/page.rs | 51 --- crates/berth/src/serve/setup_key.rs | 4 +- crates/berth/src/serve/tests.rs | 26 -- crates/berth/src/ui.rs | 156 +------- crates/berth/src/update.rs | 4 - install.sh | 8 +- tests/e2e/e2e_access.py | 2 +- tests/e2e/e2e_own_key.py | 2 +- tests/e2e/e2e_provisioners.py | 4 +- tests/e2e/e2e_restore.py | 4 +- tests/e2e/e2e_serve.py | 29 +- tests/e2e/harness.py | 8 +- tests/e2e/run.py | 1 - 48 files changed, 114 insertions(+), 1811 deletions(-) delete mode 100644 crates/berth-web/Cargo.toml delete mode 100644 crates/berth-web/index.html delete mode 100644 crates/berth-web/src/browser.rs delete mode 100644 crates/berth-web/src/main.rs delete mode 100644 crates/berth-web/src/socket.rs delete mode 100644 crates/berth/build.rs delete mode 100644 crates/berth/src/serve/page.rs diff --git a/Cargo.lock b/Cargo.lock index c8145e5..c6f9b34 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,12 +2,6 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - [[package]] name = "aead" version = "0.5.2" @@ -166,63 +160,6 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" -[[package]] -name = "beamterm-core" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0375f7f3df163a52a06807f2150bac9a5da1933864ed40d52dda7dcd7cfa193b" -dependencies = [ - "beamterm-data", - "beamterm-unicode", - "bitflags 2.13.2", - "compact_str", - "glow", - "lru 0.16.4", - "rustc-hash", - "thiserror 2.0.21", - "unicode-width", -] - -[[package]] -name = "beamterm-data" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f21ff1fc630079352bae9b024f85519bf1f641cf7f326623f4c0b59f7ea834fd" -dependencies = [ - "compact_str", - "miniz_oxide", - "thiserror 2.0.21", -] - -[[package]] -name = "beamterm-renderer" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8db76d04d575a0534ad5dba63acc05ccbe69597f977f11c59a612cbea199112" -dependencies = [ - "beamterm-core", - "beamterm-data", - "bitflags 2.13.2", - "compact_str", - "console_error_panic_hook", - "glow", - "js-sys", - "thiserror 2.0.21", - "unicode-width", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - -[[package]] -name = "beamterm-unicode" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f44155933cdd0625a699c554c504aab30a571e4df68f3532fb95bf9cf53b935" -dependencies = [ - "unicode-width", -] - [[package]] name = "berth" version = "0.5.2" @@ -250,7 +187,6 @@ dependencies = [ "utoipa", "utoipa-axum", "vt100", - "wasm-bindgen-cli-support", ] [[package]] @@ -301,7 +237,6 @@ dependencies = [ "ratatui", "serde_json", "tui-input", - "web-time", ] [[package]] @@ -342,21 +277,6 @@ dependencies = [ "serde_json", "tui-input", "vt100", - "web-time", -] - -[[package]] -name = "berth-web" -version = "0.5.2" -dependencies = [ - "berth-page", - "berth-tui", - "console_error_panic_hook", - "critical-section", - "js-sys", - "ratzilla", - "wasm-bindgen", - "web-sys", ] [[package]] @@ -408,18 +328,6 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" -[[package]] -name = "bitvec" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" -dependencies = [ - "funty", - "radium", - "tap", - "wyz", -] - [[package]] name = "block-buffer" version = "0.10.4" @@ -578,16 +486,6 @@ dependencies = [ "static_assertions", ] -[[package]] -name = "console_error_panic_hook" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" -dependencies = [ - "cfg-if", - "wasm-bindgen", -] - [[package]] name = "const-oid" version = "0.9.6" @@ -649,31 +547,6 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" -[[package]] -name = "crossbeam-deque" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" -dependencies = [ - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" - [[package]] name = "crossterm" version = "0.29.0" @@ -1105,12 +978,6 @@ dependencies = [ "percent-encoding", ] -[[package]] -name = "funty" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" - [[package]] name = "futures-channel" version = "0.3.34" @@ -1198,29 +1065,6 @@ dependencies = [ "rand_core 0.10.1", ] -[[package]] -name = "gimli" -version = "0.32.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" -dependencies = [ - "fallible-iterator 0.3.0", - "indexmap", - "stable_deref_trait", -] - -[[package]] -name = "glow" -version = "0.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5" -dependencies = [ - "js-sys", - "slotmap", - "wasm-bindgen", - "web-sys", -] - [[package]] name = "group" version = "0.13.0" @@ -1241,8 +1085,6 @@ dependencies = [ "allocator-api2", "equivalent", "foldhash", - "serde", - "serde_core", ] [[package]] @@ -1393,15 +1235,6 @@ dependencies = [ "tower-service", ] -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" -dependencies = [ - "rayon", -] - [[package]] name = "ident_case" version = "1.0.1" @@ -1525,18 +1358,6 @@ dependencies = [ "spin", ] -[[package]] -name = "leb128" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" - -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - [[package]] name = "libc" version = "0.2.191" @@ -1605,15 +1426,6 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" -[[package]] -name = "lru" -version = "0.16.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39" -dependencies = [ - "hashbrown 0.16.1", -] - [[package]] name = "lru" version = "0.18.5" @@ -1682,15 +1494,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" -[[package]] -name = "miniz_oxide" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" -dependencies = [ - "adler2", -] - [[package]] name = "mio" version = "1.2.4" @@ -2268,12 +2071,6 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" -[[package]] -name = "radium" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" - [[package]] name = "rand" version = "0.8.8" @@ -2379,7 +2176,7 @@ dependencies = [ "hashbrown 0.17.1", "itertools", "kasuari", - "lru 0.18.5", + "lru", "palette", "serde", "strum", @@ -2463,42 +2260,6 @@ dependencies = [ "unicode-width", ] -[[package]] -name = "ratzilla" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d53309a50b2cfb9828d1ea653b77fc6d2fe08137b05e65aa070ab87630e35b49" -dependencies = [ - "beamterm-renderer", - "bitvec", - "compact_str", - "console_error_panic_hook", - "ratatui", - "thiserror 2.0.21", - "unicode-width", - "web-sys", -] - -[[package]] -name = "rayon" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" -dependencies = [ - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", -] - [[package]] name = "redox_syscall" version = "0.5.18" @@ -2606,24 +2367,6 @@ dependencies = [ "sqlite-wasm-rs", ] -[[package]] -name = "rustc-demangle" -version = "0.1.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" - -[[package]] -name = "rustc-hash" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" - -[[package]] -name = "rustc-std-workspace-core" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa9c45b374136f52f2d6311062c7146bff20fec063c3f5d46a410bd937746955" - [[package]] name = "rustc_version" version = "0.4.1" @@ -2931,15 +2674,6 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" -[[package]] -name = "slotmap" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" -dependencies = [ - "version_check", -] - [[package]] name = "smallvec" version = "1.16.4" @@ -2984,12 +2718,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - [[package]] name = "stacker" version = "0.1.25" @@ -3092,12 +2820,6 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" -[[package]] -name = "tap" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" - [[package]] name = "tempfile" version = "3.27.0" @@ -3545,9 +3267,6 @@ name = "unicode-width" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" -dependencies = [ - "rustc-std-workspace-core", -] [[package]] name = "universal-hash" @@ -3662,35 +3381,6 @@ dependencies = [ "utf8parse", ] -[[package]] -name = "walrus" -version = "0.27.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5691aeb3546554822fe2c13d63149c26a027cd07d900a72c7c7f37f4321bfaea" -dependencies = [ - "anyhow", - "gimli", - "id-arena", - "leb128", - "log", - "rayon", - "walrus-macro", - "wasm-encoder", - "wasmparser", -] - -[[package]] -name = "walrus-macro" -version = "0.26.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a9b0525d7ea6e5f906aca581a172e5c91b4c595290dfa8ad4a2bc9ffef33b44" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "want" version = "0.3.2" @@ -3746,35 +3436,6 @@ dependencies = [ "wasm-bindgen-shared", ] -[[package]] -name = "wasm-bindgen-cli-support" -version = "0.2.129" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0724352b96c7779dcfd3f580b9e7e29beac8f4229c9a27cd2ea53e04f1cc65a" -dependencies = [ - "anyhow", - "base64", - "leb128", - "log", - "rustc-demangle", - "serde", - "serde_json", - "walrus", - "wasm-bindgen-shared", - "wasmparser", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.79" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" -dependencies = [ - "js-sys", - "tokio", - "wasm-bindgen", -] - [[package]] name = "wasm-bindgen-macro" version = "0.2.129" @@ -3807,29 +3468,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "wasm-encoder" -version = "0.245.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9dca005e69bf015e45577e415b9af8c67e8ee3c0e38b5b0add5aa92581ed5c" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasmparser" -version = "0.245.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f08c9adee0428b7bddf3890fc27e015ac4b761cc608c822667102b8bfd6995e" -dependencies = [ - "bitflags 2.13.2", - "hashbrown 0.16.1", - "indexmap", - "semver", - "serde", -] - [[package]] name = "web-sys" version = "0.3.106" @@ -3840,16 +3478,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "web-time" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - [[package]] name = "webpki-roots" version = "1.0.12" @@ -4060,15 +3688,6 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" -[[package]] -name = "wyz" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" -dependencies = [ - "tap", -] - [[package]] name = "x509-cert" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index a2fd53a..daaeaca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "3" -members = ["crates/berth-api", "crates/berth-pty", "crates/berth-core", "crates/berth-tui", "crates/berth", "crates/berthd", "crates/box", "crates/berth-page", "crates/berth-web", "crates/berth-remote"] +members = ["crates/berth-api", "crates/berth-pty", "crates/berth-core", "crates/berth-tui", "crates/berth", "crates/berthd", "crates/box", "crates/berth-page", "crates/berth-remote"] # The vendored crate is a member because it lives inside; it is left out of what # is built, tested and linted by default. default-members = ["crates/berth-api", "crates/berth-pty", "crates/berth-core", "crates/berth-tui", "crates/berth", "crates/berthd", "crates/box", "crates/berth-page", "crates/berth-remote"] @@ -12,7 +12,7 @@ rust-version = "1.88" license = "MIT OR Apache-2.0" [workspace.dependencies] -# Members that talk to a server ask for the client; the browser build does not. +# Members that talk to a server ask for the client; the screens alone do not. berth-api = { path = "crates/berth-api", default-features = false } berth-pty = { path = "crates/berth-pty" } berth-core = { path = "crates/berth-core" } @@ -51,25 +51,10 @@ debug = false [profile.release] strip = true -# The page of berth serve: small rather than fast, since it is carried in berth. -[profile.web] -inherits = "release" -opt-level = "s" -lto = "fat" -codegen-units = 1 - # What a development or test build of berth carries. berthd and box are built -# incrementally, and small, as berth packs them. The page keeps its -# optimisation without the whole-program link that takes most of its build -# time after a change. +# incrementally, and small, as berth packs them. [profile.host-dev] inherits = "dev" opt-level = "s" debug = false strip = true - -[profile.web-dev] -inherits = "web" -lto = false -codegen-units = 16 -incremental = true diff --git a/container/berth.Dockerfile b/container/berth.Dockerfile index e2bac4c..e7cef49 100644 --- a/container/berth.Dockerfile +++ b/container/berth.Dockerfile @@ -12,12 +12,11 @@ FROM rust:1-bookworm AS build RUN apt-get update && apt-get install -y --no-install-recommends musl-tools python3 \ && rm -rf /var/lib/apt/lists/* \ - && rustup target add x86_64-unknown-linux-musl wasm32-unknown-unknown + && rustup target add x86_64-unknown-linux-musl WORKDIR /src COPY . . ARG BERTH_BUILD_VERSION= -# With the page for a browser, which the default command serves. -RUN cargo build --release --locked --target x86_64-unknown-linux-musl -p berth --features web \ +RUN cargo build --release --locked --target x86_64-unknown-linux-musl -p berth \ && said=$(target/x86_64-unknown-linux-musl/release/berth --version) && echo "$said" \ && { [ -z "$BERTH_BUILD_VERSION" ] || [ "$said" = "berth $BERTH_BUILD_VERSION" ]; } @@ -37,4 +36,4 @@ ENV XDG_CONFIG_HOME=/config XDG_DATA_HOME=/data TERM=xterm-256color VOLUME ["/config", "/data"] EXPOSE 7777 ENTRYPOINT ["tini", "--", "berth"] -CMD ["serve", "--listen", "0.0.0.0:7777", "--expose", "--web"] +CMD ["serve", "--listen", "0.0.0.0:7777", "--expose"] diff --git a/crates/berth-api/Cargo.toml b/crates/berth-api/Cargo.toml index 62521b1..7a4cb24 100644 --- a/crates/berth-api/Cargo.toml +++ b/crates/berth-api/Cargo.toml @@ -20,5 +20,5 @@ futures-util = { workspace = true, optional = true } [features] default = ["client"] # The client over a byte stream; without it only the types and tables remain, -# which is what a browser build takes. +# which is all the shared screens take. client = ["dep:tokio", "dep:hyper", "dep:hyper-util", "dep:http-body-util", "dep:tokio-tungstenite", "dep:futures-util"] diff --git a/crates/berth-page/Cargo.toml b/crates/berth-page/Cargo.toml index f329c54..c071329 100644 --- a/crates/berth-page/Cargo.toml +++ b/crates/berth-page/Cargo.toml @@ -4,12 +4,11 @@ version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true -description = "The page of berth serve, its screens and its portal, for a browser (berth-web) and a terminal (berth-remote)" +description = "The screens of a berth serve elsewhere and its portal, for berth-remote" [dependencies] berth-api.workspace = true berth-tui.workspace = true serde_json.workspace = true tui-input.workspace = true -web-time = "1" ratatui = { version = "=0.30.2", default-features = false } diff --git a/crates/berth-page/src/app.rs b/crates/berth-page/src/app.rs index fa4080b..e37b057 100644 --- a/crates/berth-page/src/app.rs +++ b/crates/berth-page/src/app.rs @@ -24,8 +24,8 @@ use serde_json::{Value, json}; use std::cell::RefCell; use std::collections::BTreeMap; use std::rc::Rc; +use std::time::{Duration, Instant}; use tui_input::Input; -use web_time::{Duration, Instant}; /// How often the list of hosts is asked for again. const HOSTS_EVERY: Duration = Duration::from_secs(10); @@ -35,13 +35,13 @@ const RETRY: Duration = Duration::from_secs(3); const SAID_FOR: Duration = Duration::from_secs(5); /// What the status line says while the server is away. const AWAY: &str = "The berth server does not answer; trying again…"; -/// The key that leaves a running session: a browser keeps Ctrl+Q to itself. +/// The key that leaves a running session, as Ctrl+Q quits the program. const LEAVE: &str = "Alt+Q"; #[derive(PartialEq)] enum Screen { Token, - /// What a setup key in the link opens. + /// What a setup key opens. Installed, Hosts, Host, @@ -91,10 +91,8 @@ pub struct App { /// The portal has been open with this token, so it is the right one. proven: bool, retry: Option, - /// The server: where the page came from, or the one that was named. + /// The server that was named, or the one that was kept. server: String, - /// `berth serve` gave this page, so the server is not asked for. - embedded: bool, token: String, typing: Input, typing_server: Input, @@ -152,27 +150,21 @@ impl App { /// Not a `Default`: making the screens signs in and opens the portal. #[allow(clippy::new_without_default)] pub fn new() -> App { - let embedded = device::embedded(); let linked = device::linked(); let (linked_server, linked_token) = (linked.server, linked.token); let kept = device::stored(Kept::Server).unwrap_or_default(); - let server = match embedded { - true => device::origin(), - false => linked_server - .map(|server| device::address(&server)) - .unwrap_or_else(|| kept.clone()), - }; + let server = linked_server + .map(|server| device::address(&server)) + .unwrap_or_else(|| kept.clone()); // The token that was kept is the one of the server that was kept. let token = linked_token .or_else(|| { - (embedded || server == kept) + (server == kept) .then(|| device::stored(Kept::Token)) .flatten() }) .unwrap_or_default(); - if !embedded { - device::store(Kept::Server, &server); - } + device::store(Kept::Server, &server); device::store(Kept::Token, &token); let mut app = App { screen: Screen::Token, @@ -182,7 +174,6 @@ impl App { on_server: server.is_empty(), typing_server: Input::new(server.clone()), server, - embedded, token, typing: Input::default(), refused: String::new(), @@ -396,15 +387,6 @@ impl App { ) } - /// The server, and the link that opens this page signed in with its - /// token: at this page's own address, which is the server's when the - /// server gave it, and told which server otherwise. - fn connect_link(&self) -> Option<(String, String)> { - let server = (!self.embedded).then_some(self.server.as_str()); - let link = qr::connect_link(&device::page(), server, &self.token)?; - Some((self.server.clone(), link)) - } - fn is_admin(&self) -> bool { self.data.borrow().admin() } @@ -1240,9 +1222,6 @@ impl App { if let Some(said) = self.home.key(tab - 1, key, &admin) { self.status = said; } - if let Some(shown) = self.home.qr.take() { - self.qr = Some(shown); - } if std::mem::take(&mut self.home.to_hosts) { self.open_tab(0); } @@ -1264,7 +1243,6 @@ impl App { if !admin { self.tab = 0; } - self.home.connect = self.connect_link(); self.home.server = device::shown(&self.server).to_owned(); let tabs: &[&str] = if admin { &TABS } else { &[] }; self.tab_hits = draw_header(frame, header, tabs, self.tab, device::shown(&self.server)); @@ -1596,27 +1574,21 @@ impl App { fn token_event(&mut self, event: Event) { match event { Event::Key(key) - if !self.embedded - && matches!(key.code, Code::Tab | Code::BackTab | Code::Up | Code::Down) => + if matches!(key.code, Code::Tab | Code::BackTab | Code::Up | Code::Down) => { self.on_server = !self.on_server; } Event::Key(key) if key.code == Code::Enter && self.on_server => self.on_server = false, Event::Key(key) if key.code == Code::Enter => { let token = self.typing.value().trim().to_owned(); - let server = match self.embedded { - true => self.server.clone(), - false => device::address(self.typing_server.value()), - }; + let server = device::address(self.typing_server.value()); if server.is_empty() { self.on_server = true; } else if !token.is_empty() { self.token = token; self.server = server; - if !self.embedded { - device::store(Kept::Server, &self.server); - self.typing_server = Input::new(self.server.clone()); - } + device::store(Kept::Server, &self.server); + self.typing_server = Input::new(self.server.clone()); device::store(Kept::Token, &self.token); self.typing = Input::default(); self.refused.clear(); @@ -1683,16 +1655,10 @@ impl App { self.draw_backdrop(frame, area); let masked = ellipsize(&"•".repeat(self.typing.value().chars().count()), 44); let named = ellipsize(self.typing_server.value(), 44); - let mut lines = match self.embedded { - true => vec![ - Line::raw("The token of this berth server. It is in serve.token,"), - Line::raw("in the data directory of the berth that serves."), - ], - false => vec![ - Line::raw("The address of a berth serve, and its token. The token"), - Line::raw("is in serve.token, in that berth's data directory."), - ], - }; + let mut lines = vec![ + Line::raw("The address of a berth serve, and its token. The token"), + Line::raw("is in serve.token, in that berth's data directory."), + ]; if !self.refused.is_empty() { for line in screen::wrap(&self.refused, 56) { lines.push(Line::styled(line, Style::new().fg(theme::WARN))); @@ -1709,16 +1675,11 @@ impl App { Span::raw(value.to_owned()), ]) }; - if !self.embedded { - lines.push(field("Server ", &named, self.on_server)); - } + lines.push(field("Server ", &named, self.on_server)); let server_row = lines.len() as u16; lines.push(field("Token ", &masked, !self.on_server)); let rows = lines.len() as u16; - let keys = match self.embedded { - true => " Enter connect · Ctrl+O copy ", - false => " Tab switch · Enter connect · Ctrl+O copy ", - }; + let keys = " Tab switch · Enter connect · Ctrl+O copy "; let area = dialog(frame, " Connect ", keys, lines); if area.width > 14 && area.height > rows { let (typed, row) = match self.on_server { diff --git a/crates/berth-page/src/device.rs b/crates/berth-page/src/device.rs index e34848e..082c0c4 100644 --- a/crates/berth-page/src/device.rs +++ b/crates/berth-page/src/device.rs @@ -1,6 +1,5 @@ -//! What the screens need from the device they run on, which a browser and a -//! terminal give in their own ways: the clipboard, links, files, what is kept -//! between runs, plain HTTP and the portal's socket. The program installs its +//! What the screens need from the device they run on: the clipboard, links, +//! files, what is kept between runs, plain HTTP and the portal's socket. The program installs its //! [`Device`] before it makes the [`App`](crate::App). use berth_tui::screen::Platform; @@ -16,7 +15,7 @@ pub enum Kept { Token, } -/// What the program was started with, such as from a link to the page. +/// What the program was started with. #[derive(Clone, Default)] pub struct Linked { pub server: Option, @@ -58,13 +57,7 @@ pub trait Device { fn stored(&self, key: Kept) -> Option; /// Keep `value`, or forget what was kept when it is empty. fn store(&self, key: Kept, value: &str); - /// Whether the server that gave these screens is the one to use. - fn embedded(&self) -> bool; fn linked(&self) -> Linked; - /// The address of the server that gave these screens, when it did. - fn origin(&self) -> String; - /// The page a link for a phone opens. - fn page(&self) -> String; /// One plain HTTP request with a bearer; `then` gets its status and body. fn request(&self, method: &str, url: &str, bearer: &str, then: Answer); /// Open a WebSocket to `url` with `token` as its protocol. `said` gets @@ -109,22 +102,10 @@ impl Platform for Here { } } -pub(crate) fn embedded() -> bool { - device().embedded() -} - pub(crate) fn linked() -> Linked { device().linked() } -pub(crate) fn origin() -> String { - device().origin() -} - -pub(crate) fn page() -> String { - device().page() -} - pub(crate) fn stored(key: Kept) -> Option { device().stored(key).filter(|value| !value.is_empty()) } diff --git a/crates/berth-page/src/home.rs b/crates/berth-page/src/home.rs index 34d301f..1be9c51 100644 --- a/crates/berth-page/src/home.rs +++ b/crates/berth-page/src/home.rs @@ -230,13 +230,8 @@ pub struct Home { pub provisioners: provisioners::Tab, /// Set when the hosts' list is to be shown again, for the page to take. pub to_hosts: bool, - /// The server, and the link that opens this page signed in, when there - /// is one to give: a row of the Settings tab. - pub connect: Option<(String, String)>, /// The address of the server, as the header shows it. pub server: String, - /// A QR code to show, for the page to take. - pub qr: Option, } /// The rows of the Settings tab after the server's own settings. @@ -244,7 +239,6 @@ pub struct Home { enum SettingsRow { /// A key of the server's ring, by its place in the list. Key(usize), - Connect, } /// The tabs after Hosts, in their order. @@ -382,9 +376,6 @@ impl Home { return extras; } extras.extend((0..data.keys.len()).map(SettingsRow::Key)); - if self.connect.is_some() { - extras.push(SettingsRow::Connect); - } extras } @@ -418,20 +409,12 @@ impl Home { SettingsRow::Key(index) => { berth_key::row(&data.keys[*index].0, &data.keys[*index].1) } - SettingsRow::Connect => Line::from(vec![ - Span::styled("Open on another device ", Style::new().fg(theme::TEXT)), - Span::styled("QR code and link, with the token", muted), - ]), }); } let extra = self.selected[SETTINGS] .checked_sub(data.settings.len()) .and_then(|index| extras.get(index).copied()); - let help = match ( - data.settings.get(self.selected[SETTINGS]), - extra, - &self.connect, - ) { + let help = match (data.settings.get(self.selected[SETTINGS]), extra) { (Some(setting), ..) => { let meaning = berth_tui::screen::describe_setting(setting["meaning"].as_str().unwrap_or("")); @@ -443,13 +426,10 @@ impl Home { ), } } - (None, Some(SettingsRow::Key(index)), _) => { + (None, Some(SettingsRow::Key(index))) => { let (name, public) = &data.keys[index]; berth_key::help(name, public, Some(&self.server)) } - (None, Some(SettingsRow::Connect), Some((server, _))) => { - berth_tui::qr::connect_help(server, false) - } _ => "Asking the server for its settings…".into(), }; Shown { @@ -460,9 +440,6 @@ impl Home { keys: match (&self.editor, extra) { (Some(_), _) => "Enter accept · Esc cancel · Ctrl+O copy", (None, Some(SettingsRow::Key(_))) => "↑↓ select · Enter copy the key · Esc hosts", - (None, Some(SettingsRow::Connect)) => { - "↑↓ select · Enter show the QR code · Esc hosts" - } (None, None) => "↑↓ select · Enter change · Esc hosts", }, } @@ -502,14 +479,6 @@ impl Home { let public = keys.get(index).map(|(_, public)| public.as_str()); return Some(berth_key::copy(&mut Here, public.unwrap_or(""))); } - // The last row shows the link that opens this page. - if extra == Some(SettingsRow::Connect) - && (key.code == Code::Enter || berth_tui::qr::is_key(&key)) - && let Some((_, link)) = &self.connect - { - self.qr = Some(berth_tui::qr::Overlay::connect(link.clone())); - return None; - } match key.code { Code::Up => self.selected[SETTINGS] = selected.saturating_sub(1), Code::Down => self.selected[SETTINGS] = (selected + 1).min(count.saturating_sub(1)), diff --git a/crates/berth-page/src/installed.rs b/crates/berth-page/src/installed.rs index 820d480..efb21b5 100644 --- a/crates/berth-page/src/installed.rs +++ b/crates/berth-page/src/installed.rs @@ -1,6 +1,6 @@ -//! The screen a setup key opens, after an install: berth is installed, this -//! browser is signed in, and the token for a terminal. The key works until -//! Done, so opening the link again before then shows the screen again. +//! The screen a setup key opens, after an install: berth is installed, these +//! screens are signed in, and the token for berth. The key works until Done, +//! so starting again with it before then shows the screen again. use crate::device::{self, Here}; use berth_tui::screen::{Platform, note_hints, wrap}; @@ -67,7 +67,7 @@ impl Installed { } } Ok((401, _)) => Claim::Failed( - "The setup key in the link was not taken: it is wrong, used up or expired. Make a new one where the server runs (berth setup-key), or give the token." + "The setup key was not taken: it is wrong, used up or expired. Make a new one where the server runs (berth setup-key), or give the token." .into(), ), Ok((status, body)) => { diff --git a/crates/berth-page/src/lib.rs b/crates/berth-page/src/lib.rs index 00b4ca3..b0cb168 100644 --- a/crates/berth-page/src/lib.rs +++ b/crates/berth-page/src/lib.rs @@ -1,6 +1,6 @@ -//! The page of `berth serve`: the hosts of a server, its plugins, settings -//! and setup, through its portal. A browser draws it (berth-web) and so does -//! a terminal (berth-remote); each gives it a [`device::Device`]. +//! The screens of a `berth serve` elsewhere: the hosts of a server, its +//! plugins, settings and setup, through its portal. berth-remote draws them +//! in a terminal and gives them a [`device::Device`]. mod admin; mod app; diff --git a/crates/berth-page/src/portal.rs b/crates/berth-page/src/portal.rs index 7fb8848..1170d00 100644 --- a/crates/berth-page/src/portal.rs +++ b/crates/berth-page/src/portal.rs @@ -172,8 +172,8 @@ fn request(id: u32, op: &str, host: Option<&str>, args: Value, data: Value) -> V } impl Portal { - /// Open the portal at `url`, showing the token the way a browser can: as - /// the WebSocket's protocol. + /// Open the portal at `url`, showing the token as the WebSocket's + /// protocol. pub fn open(url: &str, token: &str) -> Result { let inner = Rc::new(Inner { socket: RefCell::default(), @@ -323,18 +323,9 @@ mod tests { None } fn store(&self, _: Kept, _: &str) {} - fn embedded(&self) -> bool { - false - } fn linked(&self) -> Linked { Linked::default() } - fn origin(&self) -> String { - String::new() - } - fn page(&self) -> String { - String::new() - } fn request(&self, _: &str, _: &str, _: &str, then: Answer) { then(Err("no".into())) } diff --git a/crates/berth-page/src/setup.rs b/crates/berth-page/src/setup.rs index 1d20ff0..a27a6fb 100644 --- a/crates/berth-page/src/setup.rs +++ b/crates/berth-page/src/setup.rs @@ -253,7 +253,7 @@ impl Setup { fn help(&self) -> String { match self.selected() { - // F5 is the browser's own, so the letters do what berth's F4 and F5 do. + // g and p do what berth's F4 and F5 do. Some(Entry::Field(field)) => field.spec().help.replace("F4", "g").replace("F5", "p"), Some(Entry::Key(Account::Operator, Some(_))) => Field::OperatorKey.spec().help.into(), Some(Entry::Key(Account::Agent, Some(_))) => Field::AgentKey.spec().help.into(), @@ -557,7 +557,7 @@ impl Setup { match key.code { Code::Up => self.move_selection(true), Code::Down => self.move_selection(false), - // F5 is the browser's own, so the letters do what berth's F4 and F5 do. + // g and p do what berth's F4 and F5 do. Code::Char('g') | Code::F(4) if self.selected_field().is_some_and(Field::can_generate) => { diff --git a/crates/berth-remote/Cargo.toml b/crates/berth-remote/Cargo.toml index 2f46df5..64ea57a 100644 --- a/crates/berth-remote/Cargo.toml +++ b/crates/berth-remote/Cargo.toml @@ -4,7 +4,7 @@ version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true -description = "The page of berth serve in a terminal: the hosts of a berth serve elsewhere, on Linux, macOS or Windows" +description = "The screens of a berth serve in a terminal: the hosts of a berth serve elsewhere, on Linux, macOS or Windows" [[bin]] name = "berth-remote" diff --git a/crates/berth-remote/src/device.rs b/crates/berth-remote/src/device.rs index 215a90f..226d875 100644 --- a/crates/berth-remote/src/device.rs +++ b/crates/berth-remote/src/device.rs @@ -1,6 +1,6 @@ -//! What a browser does for the page, done by this program instead: the -//! clipboard, opening links, choosing a file, plain HTTP, the portal's socket, -//! and the server and token it keeps between runs. +//! The device the screens run on, in a terminal: the clipboard, opening +//! links, choosing a file, plain HTTP, the portal's socket, and the server +//! and token it keeps between runs. use crate::settings::Settings; use crate::{net, socket}; @@ -157,26 +157,10 @@ impl Device for Terminal { } } - /// This program is never given by a server: it always asks which one. - fn embedded(&self) -> bool { - false - } - fn linked(&self) -> Linked { self.linked.clone() } - fn origin(&self) -> String { - String::new() - } - - /// The page `berth serve --web` gives at the server in use, for a phone. - fn page(&self) -> String { - self.stored(Kept::Server) - .map(|server| format!("{}/", server.trim_end_matches('/'))) - .unwrap_or_default() - } - fn request(&self, method: &str, url: &str, bearer: &str, then: Answer) { let (method, url, bearer) = (method.to_owned(), url.to_owned(), bearer.to_owned()); net::later(async move { net::http(&method, &url, &bearer).await }, then); @@ -474,7 +458,10 @@ mod tests { let again = Terminal::new(Linked::default(), Settings::new(Some(dir.clone())), false).unwrap(); assert_eq!(again.stored(Kept::Token).as_deref(), Some("secret")); - assert_eq!(again.page(), "https://studio.example/"); + assert_eq!( + again.stored(Kept::Server).as_deref(), + Some("https://studio.example") + ); let forgetting = Terminal::new(Linked::default(), Settings::new(Some(dir.clone())), true).unwrap(); @@ -484,7 +471,10 @@ mod tests { forgetting.store(Kept::Server, "https://dock.example"); forgetting.store(Kept::Token, "other"); assert_eq!(forgetting.stored(Kept::Token).as_deref(), Some("other")); - assert_eq!(forgetting.page(), "https://dock.example/"); + assert_eq!( + forgetting.stored(Kept::Server).as_deref(), + Some("https://dock.example") + ); assert!(!dir.exists()); } diff --git a/crates/berth-remote/src/lib.rs b/crates/berth-remote/src/lib.rs index 259c488..336f7d4 100644 --- a/crates/berth-remote/src/lib.rs +++ b/crates/berth-remote/src/lib.rs @@ -1,7 +1,7 @@ -//! berth-remote: the page of `berth serve --web` in a terminal, for a -//! machine that only looks after the hosts of a berth serve elsewhere. It -//! runs on Linux, macOS and Windows: the screens are berth-page's, and this -//! crate gives them a terminal and a network in place of a browser. It is a +//! berth-remote: the screens of a berth serve in a terminal, for a machine +//! that only looks after the hosts of a berth serve elsewhere. It runs on +//! Linux, macOS and Windows: the screens are berth-page's, and this crate +//! gives them a terminal and a network. It is a //! library as well as the program so that berth's tests can sign it in to a //! server of their own. diff --git a/crates/berth-remote/src/socket.rs b/crates/berth-remote/src/socket.rs index 6a6bc7d..30fedc8 100644 --- a/crates/berth-remote/src/socket.rs +++ b/crates/berth-remote/src/socket.rs @@ -1,4 +1,4 @@ -//! The WebSocket under the page's portal: it runs on the runtime, and what it +//! The WebSocket under the screens' portal: it runs on the runtime, and what it //! says is handed to the main thread at [`pump`]. use crate::net; @@ -42,8 +42,7 @@ impl Socket for NativeSocket { } } -/// Open a WebSocket to `url`, with `token` as its protocol, the way the page -/// sends it. +/// Open a WebSocket to `url`, with `token` as its protocol. pub fn open(url: &str, token: &str, to: Box) -> Result { let target = net::target(url)?; let (out, outgoing) = unbounded_channel(); diff --git a/crates/berth-tui/Cargo.toml b/crates/berth-tui/Cargo.toml index 5cb0ecb..7aed47f 100644 --- a/crates/berth-tui/Cargo.toml +++ b/crates/berth-tui/Cargo.toml @@ -4,7 +4,7 @@ version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true -description = "The screens of a host with no terminal in them, for berth and for its page in a browser" +description = "The screens of a host with no terminal in them, for berth and berth-remote" [dependencies] berth-api.workspace = true @@ -16,4 +16,3 @@ ratatui = { version = "=0.30.2", default-features = false } qrcode = { version = "0.14", default-features = false } pulldown-cmark = { version = "0.13", default-features = false } tui-input.workspace = true -web-time = "1" diff --git a/crates/berth-tui/src/berth_key.rs b/crates/berth-tui/src/berth_key.rs index c6b3ffa..caf2a5e 100644 --- a/crates/berth-tui/src/berth_key.rs +++ b/crates/berth-tui/src/berth_key.rs @@ -92,7 +92,7 @@ mod tests { } fn open(&mut self, _: &str) -> Result<(), String> { - Err("no browser".into()) + Err("nothing to open it with".into()) } } diff --git a/crates/berth-tui/src/event.rs b/crates/berth-tui/src/event.rs index 91bb5c1..0a9acff 100644 --- a/crates/berth-tui/src/event.rs +++ b/crates/berth-tui/src/event.rs @@ -1,5 +1,5 @@ -//! Keys and the mouse as the screens take them. A terminal's and a browser's -//! events are both turned into these. +//! Keys and the mouse as the screens take them. The events of a terminal are +//! turned into these. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Code { diff --git a/crates/berth-tui/src/host.rs b/crates/berth-tui/src/host.rs index 23ac5a3..2ac3a92 100644 --- a/crates/berth-tui/src/host.rs +++ b/crates/berth-tui/src/host.rs @@ -8,7 +8,7 @@ pub use crate::page::{Arguments, Launch, argument_label}; use berth_api as api; use serde_json::{Value, json}; use std::collections::BTreeMap; -use web_time::{Duration, Instant}; +use std::time::{Duration, Instant}; /// The lowest `api` of a host this berth can work with. pub const NEEDS_API: u32 = 1; diff --git a/crates/berth-tui/src/lib.rs b/crates/berth-tui/src/lib.rs index 0a78bc9..10a9007 100644 --- a/crates/berth-tui/src/lib.rs +++ b/crates/berth-tui/src/lib.rs @@ -1,6 +1,6 @@ //! The screens of a host with no terminal in them: they draw into ratatui -//! frames and take keys of their own type, which berth turns a terminal's -//! events into and its page in a browser the browser's. +//! frames and take keys of their own type, which berth and berth-remote turn +//! a terminal's events into. pub mod berth_key; pub mod event; diff --git a/crates/berth-tui/src/machine.rs b/crates/berth-tui/src/machine.rs index c07e193..05985bc 100644 --- a/crates/berth-tui/src/machine.rs +++ b/crates/berth-tui/src/machine.rs @@ -4,8 +4,7 @@ //! rest of its arguments on the Settings tab, and creating it, or the machine //! once there is one, on the Run tab. The machine is the host's resource of //! the machine kind, and starting, stopping and deleting it are its actions. -//! berth and its page in a browser ask for these and run the jobs each their -//! own way. +//! berth and berth-remote ask for these and run the jobs each their own way. use crate::fields::{Kind, Step}; use crate::setup::{Entry, Problem, Row, value_line}; diff --git a/crates/berth-tui/src/page.rs b/crates/berth-tui/src/page.rs index e1929a4..f3f58ca 100644 --- a/crates/berth-tui/src/page.rs +++ b/crates/berth-tui/src/page.rs @@ -2,7 +2,7 @@ //! in groups, and the dialogs before an action runs, its question and then //! its arguments one after another. A host's page is one. A page of another //! subject is its state and its actions given to the same functions; the -//! terminal and the browser draw the rows each their own way. +//! berth and berth-remote draw the rows each their own way. use berth_api::{Action, Argument}; use std::collections::BTreeMap; diff --git a/crates/berth-tui/src/plugins.rs b/crates/berth-tui/src/plugins.rs index 72221ce..3c57196 100644 --- a/crates/berth-tui/src/plugins.rs +++ b/crates/berth-tui/src/plugins.rs @@ -1,8 +1,8 @@ //! The Plugins tab of the home screen: the plugins there are with their //! features, installing, updating and removing one, and bringing the hosts //! that are behind up to date afterwards. berth shows those of this -//! machine or of its berth server, the page in a browser those of the server -//! it came from. What the tab asks for, each of them does its own way. +//! machine or of its berth server, berth-remote those of the server it is +//! signed in to. What the tab asks for, each of them does its own way. use crate::event::{self, Code, Key}; use crate::theme; @@ -19,7 +19,7 @@ pub enum Place<'a> { Here, /// The server's at this address, for berth in a terminal. Server(&'a str), - /// The server's, for the page in a browser. + /// The server's, for berth-remote. Page, } diff --git a/crates/berth-tui/src/provisioners.rs b/crates/berth-tui/src/provisioners.rs index 4001a86..f5a9d0c 100644 --- a/crates/berth-tui/src/provisioners.rs +++ b/crates/berth-tui/src/provisioners.rs @@ -3,7 +3,7 @@ //! [`crate::page`]: how it is now, what it says of itself, what it holds by //! kind, and its actions. A resource berth made with it has a page of its own //! with its state, its actions and its log. berth shows those of this machine or of its -//! berth server, the page in a browser those of the server it came from. What +//! berth server, berth-remote those of the server it is signed in to. What //! the tab asks for, each of them does its own way, and tells the tab what //! came back. diff --git a/crates/berth-tui/src/qr.rs b/crates/berth-tui/src/qr.rs index 82ca3c3..0190f85 100644 --- a/crates/berth-tui/src/qr.rs +++ b/crates/berth-tui/src/qr.rs @@ -19,7 +19,7 @@ use ratatui::{ }; /// The key that shows a link as a QR code. Alt keeps it from the program in a -/// terminal panel, and a browser leaves it to the page. +/// terminal panel. pub const KEY: &str = "Alt+R"; /// Its hint in a footer. pub const HINT: &str = "Alt+R QR code"; @@ -176,8 +176,6 @@ pub struct Overlay { pub title: String, pub links: Vec, pub index: usize, - /// A few words in the bottom border: what the code gives whoever scans it. - pub note: Option, } impl Overlay { @@ -193,20 +191,9 @@ impl Overlay { title: "QR code".into(), links, index: 0, - note: None, }) } - /// The link that opens a berth server's page, signed in. - pub fn connect(link: String) -> Overlay { - Overlay { - title: "Open berth on another device".into(), - links: vec![link], - index: 0, - note: Some("holds the server's token".into()), - } - } - pub fn link(&self) -> &str { &self.links[self.index.min(self.links.len() - 1)] } @@ -293,12 +280,7 @@ impl Overlay { _ => "←→ other links · Esc close", }; note_hints(keys, area.x + 1, area.bottom().saturating_sub(1), true); - let mut block = theme::popup(&title, theme::ACCENT).title_bottom(theme::hints(keys)); - if let Some(note) = &self.note { - block = block.title_bottom( - Line::styled(format!(" {note} "), Style::new().fg(theme::WARN)).right_aligned(), - ); - } + let block = theme::popup(&title, theme::ACCENT).title_bottom(theme::hints(keys)); let inner = block.inner(area); frame.render_widget(Clear, area); frame.render_widget(block, area); @@ -361,80 +343,6 @@ pub fn any_link<'a>(lines: impl IntoIterator) -> bool { }) } -/// A value as it may stand in an address: letters, digits and `-._~` as they -/// are, and with `keep` also those characters; everything else -/// percent-encoded. -fn encoded(value: &str, keep: &str) -> String { - let mut out = String::new(); - for byte in value.bytes() { - let ch = byte as char; - if ch.is_ascii_alphanumeric() || "-._~".contains(ch) || keep.contains(ch) { - out.push(ch); - } else { - out.push_str(&format!("%{byte:02X}")); - } - } - out -} - -/// An access token of an OAuth issuer is a JWT, of three parts in base64. -/// It runs out, and belongs to whoever it was issued to, so it is never handed on. -fn issued(token: &str) -> bool { - token.starts_with("eyJ") && token.matches('.').count() == 2 -} - -/// The link that opens the browser page of a berth server, signed in with -/// `token`: `page` is where the page is. A page that is not the server's own, -/// as on the documentation site, is told the `server` as well. `None` when -/// there is no such link: no token, an access token of an issuer, or no address over the -/// network. -pub fn connect_link(page: &str, server: Option<&str>, token: &str) -> Option { - let token = token.trim(); - let web = |address: &str| address.starts_with("https://") || address.starts_with("http://"); - if token.is_empty() || issued(token) || !web(page) || server.is_some_and(|server| !web(server)) - { - return None; - } - let query = match server { - Some(server) => format!("?server={}", encoded(server.trim_end_matches('/'), ":/")), - None => String::new(), - }; - Some(format!("{page}{query}#token={}", encoded(token, ""))) -} - -/// The link to the page that `berth serve --web` gives at `server`. -pub fn served_link(server: &str, token: &str) -> Option { - connect_link(&format!("{}/", server.trim_end_matches('/')), None, token) -} - -/// What the information box says of the row that shows the link to the -/// server's page. `served` when the link is to the page `berth serve --web` -/// gives, which a server without `--web` does not have. -pub fn connect_help(server: &str, served: bool) -> String { - let mut help = format!( - "A QR code and a link that open this berth server, {server}, in a browser on a phone or another computer, signed in.\n\n**Both hold the server's token**, which gives full control of its hosts. Show them to nobody who should not have it." - ); - if served { - help += &format!( - "\n\nThe link is to the page of `berth serve --web`. Without `--web`, the page of the documentation site takes `/web/?server={server}#token=TOKEN`." - ); - } - if loopback(server) { - help += "\n\nThat address is this machine's own, which a phone cannot reach. Use one of the server's addresses on your network or tailnet."; - } - help -} - -/// Whether an address is this machine's own, which a phone cannot reach. -pub fn loopback(address: &str) -> bool { - let rest = address - .trim_start_matches("https://") - .trim_start_matches("http://"); - ["localhost", "127.", "[::1]", "0.0.0.0"] - .iter() - .any(|name| rest.starts_with(name)) -} - #[cfg(test)] mod tests { use super::*; @@ -587,44 +495,18 @@ mod tests { #[test] fn the_overlay_falls_back_to_text_in_a_small_window() { - let overlay = Overlay::connect("https://berth.example.ts.net/#token=secret".into()); + let overlay = Overlay { + title: "QR code".into(), + links: vec!["https://berth.example.ts.net/?query=a-long-enough-link".into()], + index: 0, + }; let drawn = text(&screen(60, 12, |frame| overlay.draw(frame))); assert!( drawn.contains("too small") && !drawn.contains('▀'), "{drawn}" ); - assert!(drawn.contains("#token=secret") && drawn.contains("token")); + assert!(drawn.contains("a-long-enough-link")); let drawn = text(&screen(100, 40, |frame| overlay.draw(frame))); - assert!( - drawn.contains('▀') && drawn.contains("holds the server's token"), - "{drawn}" - ); - } - - #[test] - fn connect_links_are_what_the_page_takes() { - assert_eq!( - served_link("https://berth.example.ts.net/", "a1b2").as_deref(), - Some("https://berth.example.ts.net/#token=a1b2") - ); - assert_eq!( - connect_link( - "https://docs.example.org/web/", - Some("https://berth.example.ts.net"), - "a+b/c" - ) - .as_deref(), - Some( - "https://docs.example.org/web/?server=https://berth.example.ts.net#token=a%2Bb%2Fc" - ) - ); - // No token, a login's token, or a socket: nothing to hand on. - assert_eq!(served_link("https://berth.example.ts.net", ""), None); - assert_eq!( - served_link("https://berth.example.ts.net", "eyJhbGciOi.eyJzdWIi.c2ln"), - None - ); - assert_eq!(served_link("unix:/run/berth/serve.sock", "a1b2"), None); - assert!(loopback("http://127.0.0.1:7777") && !loopback("https://berth.example.ts.net")); + assert!(drawn.contains('▀'), "{drawn}"); } } diff --git a/crates/berth-tui/src/setup.rs b/crates/berth-tui/src/setup.rs index f04c100..df8b5bd 100644 --- a/crates/berth-tui/src/setup.rs +++ b/crates/berth-tui/src/setup.rs @@ -1,6 +1,6 @@ //! The set-up pages of a host: what its profile holds, the rows each page //! shows of it, and what changing a row does to it. Nothing here reads a file -//! or runs a command, so berth and its page in a browser share it. +//! or runs a command, so berth and berth-remote share it. use crate::fields::{Action, Field, Group, Kind, Step}; use crate::theme; diff --git a/crates/berth-web/Cargo.toml b/crates/berth-web/Cargo.toml deleted file mode 100644 index 7ffe444..0000000 --- a/crates/berth-web/Cargo.toml +++ /dev/null @@ -1,29 +0,0 @@ -[package] -name = "berth-web" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -description = "berth in a browser: the hosts of a berth serve, drawn by ratzilla" - -# Only a browser runs it; berth's own build makes the wasm and carries it. -[[bin]] -name = "berth-web" -path = "src/main.rs" - -[target.'cfg(target_arch = "wasm32")'.dependencies] -berth-page.workspace = true -berth-tui.workspace = true -ratzilla = "0.3.1" -wasm-bindgen = "=0.2.129" -js-sys = "0.3" -console_error_panic_hook = "0.1" -# ratatui locks through critical-section; a page has one thread, and std's lock does. -critical-section = { version = "1", features = ["std"] } -web-sys = { version = "0.3", features = [ - "BinaryType", "Blob", "Clipboard", "ClipboardEvent", "CloseEvent", "DataTransfer", "Document", "DomRect", - "Element", "Event", "EventTarget", "File", "FileList", "Headers", "History", "HtmlElement", "HtmlInputElement", - "KeyboardEvent", "Location", - "MessageEvent", "MouseEvent", "Navigator", "RequestInit", "ResizeObserver", "Response", "Storage", "WebSocket", "WheelEvent", - "Window", -] } diff --git a/crates/berth-web/index.html b/crates/berth-web/index.html deleted file mode 100644 index ed88a6b..0000000 --- a/crates/berth-web/index.html +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - -berth - - - - -
- - - - diff --git a/crates/berth-web/src/browser.rs b/crates/berth-web/src/browser.rs deleted file mode 100644 index 63fa8b0..0000000 --- a/crates/berth-web/src/browser.rs +++ /dev/null @@ -1,511 +0,0 @@ -//! What the browser does for the page: its keys and mouse as the screens -//! take them, the clipboard, the token it keeps, and the canvas. - -use berth_page::App; -use berth_page::device::{Answer, Device, Kept, Linked, Said, Socket}; -use berth_tui::{Click, Code, Event, Key, Mouse}; -use ratzilla::backend::webgl2::WebGl2BackendOptions; -use ratzilla::ratatui::{Terminal, style::Color}; -use ratzilla::{CellSized, FontAtlasConfig, WebGl2Backend, WebRenderer}; -use std::cell::RefCell; -use std::rc::Rc; -use wasm_bindgen::{JsCast, prelude::*}; -use web_sys::{KeyboardEvent, window}; - -/// Where the browser keeps what the page keeps between visits. -fn item(key: Kept) -> &'static str { - match key { - Kept::Token => "berth.token", - Kept::Server => "berth.server", - } -} - -/// The fonts the page draws with, the first the browser has. -const FONTS: &[&str] = &[ - "JetBrains Mono", - "JetBrainsMono Nerd Font Mono", - "Cascadia Mono", - "DejaVu Sans Mono", - "Menlo", - "Consolas", - "monospace", -]; - -pub struct Browser; - -/// Let the user choose a file of this device, and hand over its name and -/// bytes once the browser has read it. Nothing happens when none is chosen. -fn choose_file(accept: &str, then: Box)>) { - let Some(element) = window() - .and_then(|window| window.document()) - .and_then(|document| document.create_element("input").ok()) - else { - return; - }; - let input: web_sys::HtmlInputElement = element.unchecked_into(); - input.set_type("file"); - input.set_accept(accept); - let chosen = input.clone(); - let changed = Closure::once_into_js(move || { - let Some(file) = chosen.files().and_then(|files| files.get(0)) else { - return; - }; - let name = file.name(); - let read = Closure::once_into_js(move |buffer: JsValue| { - then(name, js_sys::Uint8Array::new(&buffer).to_vec()); - }); - let reading: JsValue = file.array_buffer().into(); - if let Ok(then) = js_sys::Reflect::get(&reading, &"then".into()) { - let _ = then - .unchecked_into::() - .call1(&reading, &read); - } - }); - input.set_onchange(Some(changed.unchecked_ref())); - input.click(); -} - -fn storage() -> Option { - window()?.local_storage().ok()? -} - -/// Whether `berth serve` gave this page itself, so that it is the server. -/// A copy hosted elsewhere, as on the documentation site, asks which server. -fn embedded() -> bool { - window() - .and_then(|window| window.document()) - .and_then(|document| { - document - .query_selector("meta[name=berth-server]") - .ok() - .flatten() - }) - .and_then(|meta| meta.get_attribute("content")) - .is_some_and(|content| content == "self") -} - -/// Undo the percent-encoding of a value in an address. -fn decoded(value: &str) -> String { - js_sys::decode_uri_component(value) - .ok() - .and_then(|text| text.as_string()) - .unwrap_or_else(|| value.to_owned()) -} - -/// What the link to this page carried. A token or a setup key is taken out -/// of the address so that it is not left in the bar or the history. -fn linked() -> Linked { - let Some(window) = window() else { - return Linked::default(); - }; - let location = window.location(); - let (search, hash) = ( - location.search().unwrap_or_default(), - location.hash().unwrap_or_default(), - ); - let parts = |text: &str| -> Vec { - text.trim_start_matches(['?', '#']) - .split('&') - .filter(|part| !part.is_empty()) - .map(str::to_owned) - .collect() - }; - let (query, fragment) = (parts(&search), parts(&hash)); - let value = |name: &str| { - query.iter().chain(&fragment).find_map(|part| { - let (key, value) = part.split_once('=')?; - (key == name && !value.is_empty()).then(|| decoded(value)) - }) - }; - let linked = Linked { - server: value("server"), - token: value("token"), - setup_key: value("setup-key"), - }; - if linked.token.is_some() || linked.setup_key.is_some() { - let secret = |part: &str| part.starts_with("token=") || part.starts_with("setup-key="); - let keep = |parts: &[String], mark: &str| { - let kept: Vec<&str> = parts - .iter() - .filter(|part| !secret(part)) - .map(String::as_str) - .collect(); - match kept.is_empty() { - true => String::new(), - false => format!("{mark}{}", kept.join("&")), - } - }; - let bare = format!( - "{}{}{}", - location.pathname().unwrap_or_default(), - keep(&query, "?"), - keep(&fragment, "#") - ); - if let Ok(history) = window.history() { - let _ = history.replace_state_with_url(&JsValue::NULL, "", Some(&bare)); - } - } - linked -} - -/// Call `then` on the outcome of a promise: what it gave, or why it failed. -fn settle(promise: &JsValue, then: impl FnOnce(Result) + 'static) { - let then = Rc::new(RefCell::new(Some(then))); - let failed = then.clone(); - let given = Closure::once_into_js(move |value: JsValue| { - if let Some(then) = then.borrow_mut().take() { - then(Ok(value)); - } - }); - let refused = Closure::once_into_js(move |error: JsValue| { - if let Some(then) = failed.borrow_mut().take() { - let said = js_sys::Reflect::get(&error, &"message".into()) - .ok() - .and_then(|message| message.as_string()) - .unwrap_or_else(|| "the browser did not send the request".into()); - then(Err(said)); - } - }); - if let Ok(method) = js_sys::Reflect::get(promise, &"then".into()) { - let _ = method - .unchecked_into::() - .call2(promise, &given, &refused); - } -} - -/// One plain HTTP request with a bearer, and then its status and body. For -/// what the portal cannot carry because the caller has no token yet. -fn request(method: &str, url: &str, bearer: &str, then: Answer) { - let Some(window) = window() else { - return then(Err("there is no window".into())); - }; - let init = web_sys::RequestInit::new(); - init.set_method(method); - if let Ok(headers) = web_sys::Headers::new() { - let _ = headers.set("Authorization", &format!("Bearer {bearer}")); - init.set_headers(&headers); - } - let sent: JsValue = window.fetch_with_str_and_init(url, &init).into(); - settle(&sent, move |answer| { - let response: web_sys::Response = match answer { - Ok(response) => response.unchecked_into(), - Err(error) => return then(Err(error)), - }; - let status = response.status(); - match response.text() { - Ok(text) => settle(&text.into(), move |body| { - then(body.map(|body| (status, body.as_string().unwrap_or_default()))) - }), - Err(_) => then(Ok((status, String::new()))), - } - }); -} - -/// The address this page came from: `http://host:port`. -fn origin() -> String { - window() - .and_then(|window| window.location().origin().ok()) - .unwrap_or_default() -} - -/// Where this page is: its origin and path, without what follows them. -fn page() -> String { - window() - .map(|window| { - let location = window.location(); - format!( - "{}{}", - location.origin().unwrap_or_default(), - location.pathname().unwrap_or_default() - ) - }) - .unwrap_or_default() -} - -impl Device for Browser { - fn copy(&self, text: &str) -> bool { - match window() { - Some(window) => { - let _ = window.navigator().clipboard().write_text(text); - true - } - None => false, - } - } - - /// Pasting is the browser's: its `paste` event carries the text. - fn paste(&self) -> Option { - None - } - - fn open(&self, link: &str) -> Result<(), String> { - let window = window().ok_or("there is no window")?; - match window.open_with_url_and_target(link, "_blank") { - Ok(Some(_)) => Ok(()), - _ => Err("the browser kept the tab from opening".into()), - } - } - - fn choose_file( - &self, - accept: &str, - then: Box)>, - ) -> Result<(), String> { - choose_file(accept, then); - Ok(()) - } - - fn stored(&self, key: Kept) -> Option { - storage()?.get_item(item(key)).ok()? - } - - fn store(&self, key: Kept, value: &str) { - if let Some(storage) = storage() { - let _ = match value.is_empty() { - true => storage.remove_item(item(key)), - false => storage.set_item(item(key), value), - }; - } - } - - fn embedded(&self) -> bool { - embedded() - } - - fn linked(&self) -> Linked { - linked() - } - - fn origin(&self) -> String { - origin() - } - - fn page(&self) -> String { - page() - } - - fn request(&self, method: &str, url: &str, bearer: &str, then: Answer) { - request(method, url, bearer, then) - } - - fn connect( - &self, - url: &str, - token: &str, - said: Box, - ) -> Result, String> { - let socket = crate::socket::open(url, token, said)?; - Ok(Box::new(socket)) - } -} - -/// The key a `keydown` was; `None` for keys the screens have no use for. -fn key_of(event: &KeyboardEvent) -> Option { - let mut name = event.key(); - // Option on a Mac types a character of its own, such as ® for R, where the - // screens want the letter of the key. AltGr, which adds Ctrl, types text. - if event.alt_key() - && !event.ctrl_key() - && let Some(letter) = event.code().strip_prefix("Key") - && letter.len() == 1 - && !(name.len() == 1 && name.chars().all(|ch| ch.is_ascii_alphabetic())) - { - name = letter.to_lowercase(); - } - let mut chars = name.chars(); - let code = match (chars.next(), chars.next()) { - (Some(ch), None) => Code::Char(ch), - _ => match name.as_str() { - "Enter" => Code::Enter, - "Escape" => Code::Esc, - "Backspace" => Code::Backspace, - "Delete" => Code::Delete, - "Insert" => Code::Insert, - "Tab" if event.shift_key() => Code::BackTab, - "Tab" => Code::Tab, - "ArrowUp" => Code::Up, - "ArrowDown" => Code::Down, - "ArrowLeft" => Code::Left, - "ArrowRight" => Code::Right, - "Home" => Code::Home, - "End" => Code::End, - "PageUp" => Code::PageUp, - "PageDown" => Code::PageDown, - other => Code::F(other.strip_prefix('F')?.parse().ok()?), - }, - }; - Some(Key { - code, - ctrl: event.ctrl_key(), - alt: event.alt_key(), - shift: event.shift_key(), - }) -} - -/// Keys whose answer is the browser's own: its developer tools, a reload, -/// full screen, and anything with the Meta key. -fn leaves_to_browser(event: &KeyboardEvent) -> bool { - let key = event.key().to_lowercase(); - event.meta_key() - || matches!(key.as_str(), "f5" | "f11" | "f12") - || (event.ctrl_key() && event.shift_key() && matches!(key.as_str(), "i" | "j" | "c" | "r")) - || (event.ctrl_key() && matches!(key.as_str(), "r" | "+" | "-" | "0")) -} - -fn canvas() -> Option { - window()? - .document()? - .query_selector("#terminal canvas") - .ok()? -} - -/// Size and place the canvas inside `#terminal` for cells of `cell` CSS -/// pixels: a whole number of cells, centred. ratzilla follows on its next frame. -fn fit(cell: (f32, f32)) { - let Some(container) = window() - .and_then(|window| window.document()) - .and_then(|document| document.get_element_by_id("terminal")) - else { - return; - }; - let Some(canvas) = canvas() else { - return; - }; - let (width, height) = ( - container.client_width() as f32, - container.client_height() as f32, - ); - let whole = |space: f32, cell: f32| match cell > 0.0 { - true => (space / cell).floor().max(1.0) * cell, - false => space, - }; - let (w, h) = (whole(width, cell.0), whole(height, cell.1)); - let _ = canvas.set_attribute( - "style", - &format!( - "position:absolute;display:block;left:{}px;top:{}px;width:{w}px;height:{h}px", - ((width - w) / 2.0).max(0.0).floor(), - ((height - h) / 2.0).max(0.0).floor() - ), - ); -} - -fn listen(target: &web_sys::EventTarget, name: &str, handler: impl FnMut(E) + 'static) -where - E: wasm_bindgen::convert::FromWasmAbi + 'static, -{ - let closure = Closure::::new(handler); - let _ = target.add_event_listener_with_callback(name, closure.as_ref().unchecked_ref()); - // The page keeps its listeners for as long as it is open. - closure.forget(); -} - -/// The cell of the canvas a mouse event is over. -fn cell_of(event: &web_sys::MouseEvent, cell: (f32, f32)) -> Option<(u16, u16)> { - let area = canvas()?.get_bounding_client_rect(); - let (x, y) = ( - event.client_x() as f64 - area.left(), - event.client_y() as f64 - area.top(), - ); - let inside = x >= 0.0 && y >= 0.0 && x < area.width() && y < area.height(); - (inside && cell.0 > 0.0 && cell.1 > 0.0) - .then(|| ((x / cell.0 as f64) as u16, (y / cell.1 as f64) as u16)) -} - -pub fn start() { - console_error_panic_hook::set_once(); - berth_page::device::install(Browser); - let Some(window) = window() else { - return; - }; - let app = Rc::new(RefCell::new(App::new())); - - let keys = app.clone(); - listen(&window, "keydown", move |event: KeyboardEvent| { - // Pasting is the browser's: a prevented key would not give its text. - if leaves_to_browser(&event) || (event.ctrl_key() && event.key().eq_ignore_ascii_case("v")) - { - return; - } - let Some(key) = key_of(&event) else { - return; - }; - event.prevent_default(); - keys.borrow_mut().event(Event::Key(key)); - }); - let pasted = app.clone(); - listen(&window, "paste", move |event: web_sys::ClipboardEvent| { - if let Some(text) = event - .clipboard_data() - .and_then(|data| data.get_data("text").ok()) - { - event.prevent_default(); - pasted.borrow_mut().event(Event::Paste(text)); - } - }); - - let container = window - .document() - .and_then(|document| document.get_element_by_id("terminal")); - let (width, height) = container.as_ref().map_or((960, 600), |container| { - ( - container.client_width().max(320) as u32, - container.client_height().max(200) as u32, - ) - }); - // The browser draws the glyphs, so box drawing and arrows come out of - // whatever monospace font it has. - let backend = WebGl2Backend::new_with_options( - WebGl2BackendOptions::new() - .grid_id("terminal") - .size((width, height)) - .disable_auto_css_resize() - .canvas_padding_color(Color::Rgb(13, 17, 28)) - .font_atlas_config(FontAtlasConfig::dynamic(FONTS, 15.0)), - ) - .expect("the page has a #terminal element and WebGL2"); - let cell = backend.cell_size_css_px(); - fit(cell); - - if let Some(container) = &container { - for name in ["mousedown", "wheel"] { - let app = app.clone(); - listen(container, name, move |event: web_sys::MouseEvent| { - let Some((column, row)) = cell_of(&event, cell) else { - return; - }; - let click = match event.dyn_ref::() { - Some(wheel) if wheel.delta_y() < 0.0 => Click::ScrollUp, - Some(wheel) if wheel.delta_y() > 0.0 => Click::ScrollDown, - Some(_) => return, - None => match event.button() { - 0 => Click::Left, - 2 => Click::Right, - _ => return, - }, - }; - // The page's own wheel and selection are not wanted over the screen. - event.prevent_default(); - app.borrow_mut() - .event(Event::Mouse(Mouse { click, column, row })); - }); - } - // A right click copies a value here; it is not the browser's menu. - listen(container, "contextmenu", |event: web_sys::Event| { - event.prevent_default() - }); - // The container's size is watched itself: a zoom or a font that loads - // late changes it without a `resize`. - let resized = Closure::::new(move || fit(cell)).into_js_value(); - if let Ok(observer) = web_sys::ResizeObserver::new(resized.unchecked_ref()) { - observer.observe(container); - } - } - - let terminal = Terminal::new(backend).expect("the terminal starts"); - terminal.draw_web(move |frame| { - let mut app = app.borrow_mut(); - app.tick(); - app.draw(frame); - }); -} diff --git a/crates/berth-web/src/main.rs b/crates/berth-web/src/main.rs deleted file mode 100644 index 4be3e9b..0000000 --- a/crates/berth-web/src/main.rs +++ /dev/null @@ -1,19 +0,0 @@ -//! berth in a browser: the hosts of the `berth serve` that served this page, -//! through its portal. The screens are berth-page's; this program gives them -//! the browser's canvas, keys, clipboard, storage and WebSocket. The page -//! keeps nothing but the token; every host is the server's. - -#[cfg(target_arch = "wasm32")] -mod browser; -#[cfg(target_arch = "wasm32")] -mod socket; - -#[cfg(target_arch = "wasm32")] -fn main() { - browser::start(); -} - -#[cfg(not(target_arch = "wasm32"))] -fn main() { - eprintln!("berth-web is the page berth serve shows: building berth builds it for wasm32"); -} diff --git a/crates/berth-web/src/socket.rs b/crates/berth-web/src/socket.rs deleted file mode 100644 index 7ec680d..0000000 --- a/crates/berth-web/src/socket.rs +++ /dev/null @@ -1,72 +0,0 @@ -//! The browser's WebSocket under the page's portal. - -use berth_page::device::{Said, Socket}; -use std::rc::Rc; -use wasm_bindgen::{JsCast, prelude::*}; -use web_sys::{BinaryType, MessageEvent, WebSocket}; - -pub struct BrowserSocket(WebSocket); - -impl Drop for BrowserSocket { - fn drop(&mut self) { - for name in ["onopen", "onmessage", "onclose"] { - let _ = js_sys::Reflect::set(&self.0, &name.into(), &JsValue::NULL); - } - let _ = self.0.close(); - } -} - -impl Socket for BrowserSocket { - fn send_text(&self, text: &str) -> bool { - self.0.send_with_str(text).is_ok() - } - - fn send_bytes(&self, bytes: &[u8]) -> bool { - self.0.send_with_u8_array(bytes).is_ok() - } -} - -/// Open a WebSocket to `url`, showing the token the way a browser can: as -/// its protocol. -pub fn open(url: &str, token: &str, said: Box) -> Result { - let socket = match token.is_empty() { - true => WebSocket::new(url), - false => WebSocket::new_with_str(url, token), - } - .map_err(|_| match url.starts_with("ws://") { - // A browser does not let a page over https open plain ws. - true => { - "The browser did not open it: from a page over https, use an https address.".to_owned() - } - false => "The browser did not open that address.".to_owned(), - })?; - socket.set_binary_type(BinaryType::Arraybuffer); - let said: Rc = Rc::from(said); - let listen = |name: &str, handler: Box Option>| { - let said = said.clone(); - let closure = Closure::::new(move |event: JsValue| { - if let Some(what) = handler(event) { - said(what); - } - }); - let _ = js_sys::Reflect::set(&socket, &name.into(), closure.as_ref()); - // The socket keeps it for as long as the page has it. - closure.forget(); - }; - listen("onopen", Box::new(|_| Some(Said::Open))); - listen("onclose", Box::new(|_| Some(Said::Closed))); - listen( - "onmessage", - Box::new(|event| { - let data = event.dyn_into::().ok()?.data(); - if let Some(text) = data.as_string() { - Some(Said::Text(text)) - } else if data.is_instance_of::() { - Some(Said::Bytes(js_sys::Uint8Array::new(&data).to_vec())) - } else { - None - } - }), - ); - Ok(BrowserSocket(socket)) -} diff --git a/crates/berth/Cargo.toml b/crates/berth/Cargo.toml index bbbf1a1..e9050e4 100644 --- a/crates/berth/Cargo.toml +++ b/crates/berth/Cargo.toml @@ -29,15 +29,6 @@ jsonwebtoken = { version = "11", default-features = false, features = ["rust_cry tui-input = { workspace = true, features = ["crossterm"] } -[features] -# The page for a browser, carried in the program for `berth serve --web`. -# Building it needs the wasm32-unknown-unknown target. -web = ["dep:wasm-bindgen-cli-support"] - -[build-dependencies] -# The same version as the wasm-bindgen the page is built with. -wasm-bindgen-cli-support = { version = "=0.2.129", optional = true } - [dev-dependencies] # Signs the access tokens of the tests. ring = "0.17" diff --git a/crates/berth/build.rs b/crates/berth/build.rs deleted file mode 100644 index cc58ce1..0000000 --- a/crates/berth/build.rs +++ /dev/null @@ -1,127 +0,0 @@ -//! With the `web` feature, builds the page `berth serve --web` shows in a -//! browser: berth-web for wasm32, and the JavaScript that loads it, into -//! OUT_DIR for the program to carry. It needs the target once: -//! `rustup target add wasm32-unknown-unknown`. -//! -//! A release build of berth carries the page of the `web` profile. Any other -//! build carries that of `web-dev`, which is built in seconds rather than -//! linked whole again after each change. BERTH_WEB_PROFILE names another. - -#[cfg(not(feature = "web"))] -fn main() {} - -#[cfg(feature = "web")] -fn main() { - page::build(); -} - -#[cfg(feature = "web")] -mod page { - - use std::{ - env, fs, - hash::{DefaultHasher, Hash, Hasher}, - path::Path, - process::Command, - }; - - const TARGET: &str = "wasm32-unknown-unknown"; - - /// A cargo that knows rustup's targets: a system cargo found first on the path does not. - fn cargo() -> Command { - let rustup = |tool: &str| { - let output = Command::new("rustup").args(["which", tool]).output().ok()?; - let path = String::from_utf8(output.stdout).ok()?.trim().to_owned(); - (output.status.success() && !path.is_empty()).then_some(path) - }; - match (rustup("cargo"), rustup("rustc")) { - (Some(cargo), Some(rustc)) => { - let mut command = Command::new(cargo); - command.env("RUSTC", rustc); - command - } - _ => Command::new(env::var("CARGO").unwrap_or_else(|_| "cargo".into())), - } - } - - pub fn build() { - let out = env::var("OUT_DIR").expect("OUT_DIR"); - let manifest = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"); - let root = Path::new(&manifest) - .ancestors() - .nth(2) - .expect("the checkout"); - for entry in [ - "crates/berth-web", - "crates/berth-page", - "crates/berth-tui", - "crates/berth-api", - "crates/vendor/tui-input", - "Cargo.lock", - ] { - println!("cargo:rerun-if-changed=../../{entry}"); - } - println!("cargo:rerun-if-env-changed=BERTH_WEB_PROFILE"); - println!("cargo:rerun-if-env-changed=BERTH_BUILD_VERSION"); - let profile = env::var("BERTH_WEB_PROFILE").unwrap_or_else(|_| { - match env::var("PROFILE").as_deref() { - Ok("release") => "web", - _ => "web-dev", - } - .into() - }); - // Its own target directory: the outer build holds the lock on the usual one. - let target = root.join("target/web"); - let mut build = cargo(); - build - .current_dir(root) - .args(["build", "--locked", "--target", TARGET]) - .args(["--profile", &profile]) - .args(["-p", "berth-web", "--target-dir"]) - .arg(&target); - // Flags and wrappers of the outer build (clippy's among them) are for another target. - for variable in [ - "CARGO_ENCODED_RUSTFLAGS", - "RUSTFLAGS", - "CARGO_BUILD_TARGET", - "TARGET", - "RUSTC_WRAPPER", - "RUSTC_WORKSPACE_WRAPPER", - ] { - build.env_remove(variable); - } - let status = build.status().expect("cargo is needed to build the page"); - assert!( - status.success(), - "building the page failed; the target is added with: rustup target add {TARGET}" - ); - // Cargo puts what the dev and test profiles build in debug/. - let folder = match profile.as_str() { - "dev" | "test" => "debug", - other => other, - }; - let wasm = target.join(TARGET).join(folder).join("berth-web.wasm"); - let page = Path::new(&out).join("web"); - let _ = fs::remove_dir_all(&page); - wasm_bindgen_cli_support::Bindgen::new() - .input_path(&wasm) - .web(true) - .expect("a page for the web") - .typescript(false) - .generate(&page) - .expect("the JavaScript that loads the page"); - // A copy at a place that does not move, for the documentation site. - let dist = root.join("target/web-dist"); - fs::create_dir_all(&dist).expect("target/web-dist"); - for name in ["berth-web.js", "berth-web_bg.wasm"] { - fs::copy(page.join(name), dist.join(name)).expect("copying the page"); - } - // Named in the page's addresses, so a browser never runs the script of one - // build with the wasm of another. - let mut hasher = DefaultHasher::new(); - fs::read(page.join("berth-web_bg.wasm")) - .expect("the page's wasm") - .hash(&mut hasher); - println!("cargo:rustc-env=BERTH_WEB_BUILD={:016x}", hasher.finish()); - } -} diff --git a/crates/berth/src/serve/mod.rs b/crates/berth/src/serve/mod.rs index a020f21..4af0773 100644 --- a/crates/berth/src/serve/mod.rs +++ b/crates/berth/src/serve/mod.rs @@ -7,8 +7,6 @@ mod api; mod auth; mod docs; pub(crate) mod keys; -#[cfg(feature = "web")] -mod page; mod provisioners; mod resources; mod setup; @@ -403,7 +401,7 @@ fn lock(paths: &Paths) -> Result { Ok(file) } -const USAGE: &str = "Usage: berth serve [--listen ADDRESS:PORT [--expose] [--web]]"; +const USAGE: &str = "Usage: berth serve [--listen ADDRESS:PORT [--expose]]"; /// A berth set to use a berth server keeps that server's hosts, so its /// commands, and the ones a serve starts, would take a host's name for one of @@ -420,31 +418,24 @@ fn refuse_a_server(paths: &Paths) -> Result<()> { } } -/// `berth serve [--listen ADDRESS:PORT [--expose] [--web]]` +/// `berth serve [--listen ADDRESS:PORT [--expose]]` /// /// Over TCP every request shows the token, but the connection is plain HTTP, /// so an address other than this machine's own takes `--expose` as well: for a -/// container whose port is published, or behind a proxy that adds TLS. With -/// `--web` the address also gives the hosts as a page for a browser. +/// container whose port is published, or behind a proxy that adds TLS. pub fn command(paths: &Paths, args: &[&str]) -> Result<()> { - let (mut listen, mut expose, mut web) = (None, false, false); + let (mut listen, mut expose) = (None, false); let mut words = args.iter(); while let Some(word) = words.next() { match *word { "--listen" => listen = Some(*words.next().ok_or(USAGE)?), "--expose" => expose = true, - "--web" => web = true, _ => return Err(USAGE.into()), } } - if listen.is_none() && (expose || web) { + if listen.is_none() && expose { return Err(USAGE.into()); } - if web && !cfg!(feature = "web") { - return Err( - "This berth is built without the page for a browser: the berth-web build has it".into(), - ); - } let listen = match listen { None => None, Some(address) => { @@ -512,14 +503,6 @@ pub fn command(paths: &Paths, args: &[&str]) -> Result<()> { state.paths.data_dir.join("serve.token").display() ); let guarded = api::router(state.clone(), true); - #[cfg(feature = "web")] - let guarded = match web { - true => { - println!("The hosts in a browser: http://{}/", tcp.local_addr()?); - guarded.merge(page::router()) - } - false => guarded, - }; Some(tokio::spawn(async move { axum::serve(tcp, guarded).await })) } None => None, diff --git a/crates/berth/src/serve/page.rs b/crates/berth/src/serve/page.rs deleted file mode 100644 index 7d2b029..0000000 --- a/crates/berth/src/serve/page.rs +++ /dev/null @@ -1,51 +0,0 @@ -//! berth in a browser: the page built from `crates/berth-web/`, carried in the program. -//! It is served to anyone who asks, since it holds nothing: what it shows it -//! gets through the portal, with the token its user gives it. - -use axum::{ - Router, - http::{HeaderValue, header}, - response::{Html, IntoResponse, Response}, - routing::get, -}; - -const BUILD: &str = env!("BERTH_WEB_BUILD"); -const PAGE: &str = include_str!("../../../berth-web/index.html"); -const SCRIPT: &str = include_str!(concat!(env!("OUT_DIR"), "/web/berth-web.js")); -const WASM: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/web/berth-web_bg.wasm")); - -/// Script and wasm are asked for by the build they are of, so they can be kept. -const KEPT: &str = "public, max-age=31536000, immutable"; - -fn file(kind: &'static str, body: &'static [u8]) -> Response { - ( - [ - (header::CONTENT_TYPE, HeaderValue::from_static(kind)), - (header::CACHE_CONTROL, HeaderValue::from_static(KEPT)), - ], - body, - ) - .into_response() -} - -async fn page() -> Response { - ( - [(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"))], - // `self`: this server is the one the page is of. - Html(PAGE.replace("@BUILD@", BUILD).replace("@SERVER@", "self")), - ) - .into_response() -} - -pub fn router() -> Router { - Router::new() - .route("/", get(page)) - .route( - "/berth-web.js", - get(|| async { file("text/javascript; charset=utf-8", SCRIPT.as_bytes()) }), - ) - .route( - "/berth-web_bg.wasm", - get(|| async { file("application/wasm", WASM) }), - ) -} diff --git a/crates/berth/src/serve/setup_key.rs b/crates/berth/src/serve/setup_key.rs index 05928c7..c194653 100644 --- a/crates/berth/src/serve/setup_key.rs +++ b/crates/berth/src/serve/setup_key.rs @@ -82,8 +82,8 @@ pub fn command(paths: &Paths, args: &[&str]) -> Result<()> { println!("{key}"); eprintln!( "This setup key lets the first user collect the token of this berth server, until {} or until they are done.\n\ - In a terminal: berth connect URL and paste the key when asked.\n\ - In a browser: URL/#setup-key=KEY\n\ + With berth: berth connect URL and paste the key when asked.\n\ + With berth-remote: berth-remote --server URL with the key in BERTH_SETUP_KEY.\n\ URL is the server's address, such as https://studio.example.ts.net.", rfc3339(expires) ); diff --git a/crates/berth/src/serve/tests.rs b/crates/berth/src/serve/tests.rs index e5b8c17..29d76c1 100644 --- a/crates/berth/src/serve/tests.rs +++ b/crates/berth/src/serve/tests.rs @@ -1043,32 +1043,6 @@ fn the_committed_documents_are_current() { } } -#[cfg(feature = "web")] -#[tokio::test(flavor = "multi_thread")] -async fn the_page_is_given_without_the_token() { - let dir = tempfile::tempdir().unwrap(); - let state = state_in(dir.path(), Some("s3cret-token")); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let router = api::router(state, true).merge(super::page::router()); - tokio::spawn(async move { axum::serve(listener, router).await }); - let stream = tokio::net::TcpStream::connect(address).await.unwrap(); - let mut client = Client::over(stream).await.unwrap(); - // The page for a browser holds nothing, so it is given without the token; - // what it shows it asks the portal for. - let page = client - .send("GET", "/", &[], Default::default()) - .await - .unwrap(); - let text = String::from_utf8_lossy(&page.body).into_owned(); - assert!(page.status == 200 && text.contains("berth-web.js?v=") && !text.contains("@BUILD@")); - let wasm = client - .send("GET", "/berth-web_bg.wasm", &[], Default::default()) - .await - .unwrap(); - assert!(wasm.status == 200 && wasm.body.starts_with(b"\0asm")); -} - async fn send(client: &mut Client, method: &str, path: &str, body: Value) -> (u16, Value) { let body = match body { Value::Null => String::new(), diff --git a/crates/berth/src/ui.rs b/crates/berth/src/ui.rs index f0540fa..2adc6ef 100644 --- a/crates/berth/src/ui.rs +++ b/crates/berth/src/ui.rs @@ -2104,8 +2104,6 @@ struct Home { status: String, /// The water moves with the time since then. started: std::time::Instant, - /// The link that opens the server's page, as a QR code, while it is shown. - qr: Option, /// The SSH keys of this berth's key ring, or of the berth server it /// uses, by name and public half, and that server. Asked for when /// Settings is first shown; empty when unknown. @@ -2222,17 +2220,13 @@ type RingKeys = (Vec<(String, String)>, Option); enum SettingsRow { /// A key of the ring, by its place in the list. Key(usize), - Connect, } -fn settings_extras(home: &Home, paths: &Paths) -> Vec { +fn settings_extras(home: &Home) -> Vec { let mut extras = vec![]; if let Some((keys, _)) = &home.berth_key { extras.extend((0..keys.len()).map(SettingsRow::Key)); } - if connect_link(paths).is_some() { - extras.push(SettingsRow::Connect); - } extras } @@ -2327,14 +2321,6 @@ fn setting( (stored.unwrap_or_default(), fallback) } -/// The berth server this berth uses, and the link that opens its page signed -/// in with its token. None without a token: a login is not handed on. -fn connect_link(paths: &Paths) -> Option<(String, String)> { - let server = berth_core::server::Server::configured(paths)?; - let link = berth_tui::qr::served_link(&server.url, server.token.as_deref()?)?; - Some((server.url, link)) -} - /// Clears a status line once it has been showing for a while. #[derive(Default)] struct Fade { @@ -2419,7 +2405,6 @@ fn home_loop( mode: HomeMode::Hosts, status: String::new(), started: std::time::Instant::now(), - qr: None, berth_key: None, served: None, known: None, @@ -2461,12 +2446,6 @@ fn home_loop( continue; } let event = hint_click(crate::keys::read()?); - if home.qr.is_some() { - if let Some(event) = crate::keys::event(&event) { - berth_tui::qr::take(&mut home.qr, &vec![], &event, &mut None); - } - continue; - } let left = match event { Event::Key(key) if key.kind != KeyEventKind::Release => { if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) { @@ -2595,7 +2574,7 @@ fn home_key( platform: &mut dyn Platform, ) -> Option> { let extras = match home.mode { - HomeMode::Settings(..) => settings_extras(home, paths), + HomeMode::Settings(..) => settings_extras(home), _ => vec![], }; let extra = |selected: usize| { @@ -2671,8 +2650,7 @@ fn home_key( HomeMode::Settings(selected, editor) => match key.code { KeyCode::Up => *selected = selected.saturating_sub(1), KeyCode::Down => { - // The key of berth and the row that opens the server's page - // come after the settings. + // The keys of berth come after the settings. let last = crate::paths::SETTINGS.len() + extras.len() - 1; *selected = (*selected + 1).min(last); } @@ -2690,15 +2668,6 @@ fn home_key( home.status = berth_tui::berth_key::copy(platform, public); } } - KeyCode::Enter | KeyCode::Char('r') - if key.code == KeyCode::Enter || key.modifiers.contains(KeyModifiers::ALT) => - { - if extra(*selected) == Some(SettingsRow::Connect) - && let Some((_, link)) = connect_link(paths) - { - home.qr = Some(berth_tui::qr::Overlay::connect(link)); - } - } _ => match leave_tab(key, tabs::SETTINGS) { Outcome::Tab(tab) => open_tab(home, tab), Outcome::Quit => return Some(None), @@ -2810,8 +2779,7 @@ fn draw_home(frame: &mut Frame, paths: &Paths, home: &Home, hits: &mut Vec<(Rect let muted = Style::new().fg(theme::MUTED); let (rows, selected, editor, help, keys): (Vec, usize, _, String, _) = match &home.mode { HomeMode::Settings(selected, editor) => { - let connect = connect_link(paths); - let extras = settings_extras(home, paths); + let extras = settings_extras(home); let (keys, server) = home.berth_key.clone().unwrap_or_default(); let mut rows: Vec = crate::paths::SETTINGS .iter() @@ -2843,17 +2811,13 @@ fn draw_home(frame: &mut Frame, paths: &Paths, home: &Home, hits: &mut Vec<(Rect let (name, public) = &keys[*index]; berth_tui::berth_key::row(name, public) } - SettingsRow::Connect => Line::from(vec![ - Span::styled("Open on another device ", Style::new().fg(theme::TEXT)), - Span::styled("QR code and link, with the token", muted), - ]), }); } let selected = (*selected).min(rows.len() - 1); let extra = selected .checked_sub(crate::paths::SETTINGS.len()) .and_then(|index| extras.get(index)); - let (help, keys) = match (crate::paths::SETTINGS.get(selected), extra, &connect) { + let (help, keys) = match (crate::paths::SETTINGS.get(selected), extra) { (Some((name, help)), ..) => ( format!( "{}.\n\nLeave it empty to use the default. Also: berth config {name} VALUE\n\nKept {}", @@ -2874,14 +2838,10 @@ fn draw_home(frame: &mut Frame, paths: &Paths, home: &Home, hits: &mut Vec<(Rect ), "↑↓ select · Enter change · q quit", ), - (None, Some(SettingsRow::Key(index)), _) => ( + (None, Some(SettingsRow::Key(index))) => ( berth_tui::berth_key::help(&keys[*index].0, &keys[*index].1, server.as_deref()), "↑↓ select · Enter copy the key · q quit", ), - (None, Some(SettingsRow::Connect), Some((url, _))) => ( - berth_tui::qr::connect_help(url, true), - "↑↓ select · Enter show the QR code · q quit", - ), _ => (String::new(), ""), }; ( @@ -3132,9 +3092,6 @@ fn draw_home(frame: &mut Frame, paths: &Paths, home: &Home, hits: &mut Vec<(Rect if let HomeMode::Provisioners(view) = &home.mode { view.draw_over(frame, status); } - if let Some(qr) = &home.qr { - qr.draw(frame); - } } /// Run a host's screen. Returns true when the chosen action has to run in the @@ -3438,7 +3395,6 @@ mod tests { mode: HomeMode::Hosts, status: String::new(), started: std::time::Instant::now(), - qr: None, berth_key: None, served: None, known: None, @@ -3544,7 +3500,6 @@ mod tests { mode: HomeMode::Hosts, status: String::new(), started: std::time::Instant::now(), - qr: None, berth_key: None, served: None, known: None, @@ -3637,7 +3592,6 @@ mod tests { mode: HomeMode::Hosts, status: String::new(), started: std::time::Instant::now(), - qr: None, berth_key: None, served: None, known: None, @@ -3867,7 +3821,6 @@ mod tests { mode: HomeMode::Hosts, status: String::new(), started: std::time::Instant::now(), - qr: None, berth_key: None, served: None, known: None, @@ -3973,77 +3926,6 @@ mod tests { false } - #[test] - fn settings_offer_the_link_to_the_servers_page_as_a_qr_code() { - let directory = tempfile::tempdir().unwrap(); - let paths = Paths { - config_dir: directory.path().join("config"), - data_dir: directory.path().join("data"), - }; - let mut home = Home { - hosts: vec![], - selected: 0, - mode: HomeMode::Settings(0, None), - status: String::new(), - started: std::time::Instant::now(), - qr: None, - berth_key: None, - served: None, - known: None, - asking: false, - refresh: false, - rotating: vec![], - }; - let last = berth_core::paths::SETTINGS.len(); - let down = |home: &mut Home| { - for _ in 0..last + 2 { - home_key( - home, - &paths, - KeyEvent::new(KeyCode::Down, KeyModifiers::NONE), - &mut Clipboard::default(), - ); - } - }; - // Without a server, or with one reached through a socket, there is no such row. - down(&mut home); - assert!(matches!(home.mode, HomeMode::Settings(index, _) if index == last - 1)); - paths.set("server", "https://berth.example.ts.net").unwrap(); - paths.set("server_token", "a1b2").unwrap(); - down(&mut home); - assert!(matches!(home.mode, HomeMode::Settings(index, _) if index == last)); - let mut terminal = Terminal::new(TestBackend::new(110, 50)).unwrap(); - let mut shown = |home: &Home| { - terminal - .draw(|frame| draw_home(frame, &paths, home, &mut vec![])) - .unwrap(); - let buffer = terminal.backend().buffer(); - (0..50) - .map(|y| { - (0..110) - .map(|x| buffer[(x, y)].symbol()) - .collect::() - }) - .collect::>() - .join("\n") - }; - let screen = shown(&home); - assert!(screen.contains("Open on another device") && screen.contains("server's token")); - home_key( - &mut home, - &paths, - KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE), - &mut Clipboard::default(), - ); - let overlay = home.qr.clone().unwrap(); - assert_eq!(overlay.link(), "https://berth.example.ts.net/#token=a1b2"); - let screen = shown(&home); - assert!( - screen.contains('▀') && screen.contains("#token=a1b2"), - "{screen}" - ); - } - #[test] fn alt_r_shows_the_links_of_a_panel_as_qr_codes() { let mut app = unsaved_app(b"{}"); @@ -4080,7 +3962,6 @@ mod tests { mode: HomeMode::Hosts, status: String::new(), started: std::time::Instant::now(), - qr: None, berth_key: None, served: None, known: None, @@ -4149,7 +4030,6 @@ mod tests { mode: HomeMode::Settings(0, None), status: String::new(), started: std::time::Instant::now(), - qr: None, berth_key: None, served: None, known: None, @@ -5124,7 +5004,6 @@ mod tests { mode: HomeMode::Settings(0, None), status: String::new(), started: std::time::Instant::now(), - qr: None, berth_key: Some(( vec![("berth".into(), BERTH_KEY.into())], Some("https://192.0.2.7:8443".into()), @@ -5145,7 +5024,7 @@ mod tests { &mut clipboard, ); } - // The key comes after the settings, before the row with the QR code. + // The key comes after the settings. assert!(matches!(home.mode, HomeMode::Settings(index, _) if index == settings)); let mut terminal = Terminal::new(TestBackend::new(130, 50)).unwrap(); terminal @@ -5165,7 +5044,6 @@ mod tests { "{screen}" ); assert!(screen.contains("Enter copy the key") && screen.contains("berth server at")); - assert!(screen.contains("Open on another device")); home_key( &mut home, &paths, @@ -5174,32 +5052,16 @@ mod tests { ); assert_eq!(clipboard.0.as_deref(), Some(BERTH_KEY)); assert_eq!(home.status, "Copied this berth's SSH public key"); - assert!(home.qr.is_none()); - // The row after it still shows the QR code. - home_key( - &mut home, - &paths, - KeyEvent::new(KeyCode::Down, KeyModifiers::NONE), - &mut clipboard, - ); - home_key( - &mut home, - &paths, - KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE), - &mut clipboard, - ); - assert!(home.qr.is_some()); // Without a key to give there is no row for it. home.berth_key = Some((vec![], None)); home.mode = HomeMode::Settings(settings, None); - home.qr = None; home_key( &mut home, &paths, - KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE), + KeyEvent::new(KeyCode::Down, KeyModifiers::NONE), &mut clipboard, ); - assert!(home.qr.is_some()); + assert!(matches!(home.mode, HomeMode::Settings(index, _) if index == settings - 1)); } fn lab(id: &str, label: &str, resources: &[&str]) -> berth_api::ProvisionerInfo { diff --git a/crates/berth/src/update.rs b/crates/berth/src/update.rs index 783ac03..934eaae 100644 --- a/crates/berth/src/update.rs +++ b/crates/berth/src/update.rs @@ -9,11 +9,7 @@ use crate::Result; use std::{fs, path::Path, process::Command}; const REPOSITORY: &str = "https://github.com/helightdev/berth"; -/// The archive of this build's kind: with the page for a browser, or without. -#[cfg(not(feature = "web"))] const ASSET: &str = "berth-x86_64-linux.tar.gz"; -#[cfg(feature = "web")] -const ASSET: &str = "berth-web-x86_64-linux.tar.gz"; /// Where the releases are: GitHub's, or `BERTH_RELEASES` for a mirror. fn releases() -> String { diff --git a/install.sh b/install.sh index 73c7849..2a80113 100755 --- a/install.sh +++ b/install.sh @@ -10,8 +10,6 @@ set -eu repo=helightdev/berth dir=${BERTH_INSTALL_DIR:-$HOME/.local/bin} version=${BERTH_VERSION:-latest} -# BERTH_VARIANT=web takes the build that carries the page for a browser. -variant=${BERTH_VARIANT:-} fail() { printf 'install: %s\n' "$1" >&2; exit 1; } @@ -20,11 +18,7 @@ case "$(uname -m)" in x86_64|amd64) arch=x86_64 ;; *) fail "no released program for $(uname -m): build it with cargo install --locked --git https://github.com/$repo berth" ;; esac -case "$variant" in - "") asset=berth-$arch-linux.tar.gz ;; - web) asset=berth-web-$arch-linux.tar.gz ;; - *) fail "no variant $variant: leave BERTH_VARIANT unset, or set it to web" ;; -esac +asset=berth-$arch-linux.tar.gz for tool in curl tar sha256sum; do command -v "$tool" >/dev/null || fail "$tool is needed" done diff --git a/tests/e2e/e2e_access.py b/tests/e2e/e2e_access.py index fd8e89b..42e6ec8 100644 --- a/tests/e2e/e2e_access.py +++ b/tests/e2e/e2e_access.py @@ -200,7 +200,7 @@ def test_6_automatic_logins_stop_at_a_refusal_so_sshd_does_not_shut_berth_out(se try: server = Workstation('access-penalty', ssh_key=False, trust=False) server.write_profile(profile(access={'address': HOST, 'user': OPERATOR, 'auth': 'berth'})) - serve = Serve(server, web=False) + serve = Serve(server) try: client = Workstation('access-penalty-client', ssh_key=False, trust=False) client.berth('config', 'server', serve.url) diff --git a/tests/e2e/e2e_own_key.py b/tests/e2e/e2e_own_key.py index 06242d8..dac08e6 100644 --- a/tests/e2e/e2e_own_key.py +++ b/tests/e2e/e2e_own_key.py @@ -200,7 +200,7 @@ class Served(OwnKeyOnly, unittest.TestCase): @classmethod def setUpClass(cls): cls.keyed = keyed() - cls.serve = Serve(cls.keyed, web=False) + cls.serve = Serve(cls.keyed) catalogue = cls.serve.call('GET', '/v1/setup') cls.serve.call('PUT', f'/v1/hosts/{HOST}/profile', bare_profile(catalogue['template'])) cls.station = Workstation('own-key-client', ssh_key=False) diff --git a/tests/e2e/e2e_provisioners.py b/tests/e2e/e2e_provisioners.py index e6fb438..6575fc1 100644 --- a/tests/e2e/e2e_provisioners.py +++ b/tests/e2e/e2e_provisioners.py @@ -142,7 +142,7 @@ def test_its_settings_page_and_actions_from_the_command_line(self): def test_through_berth_serve_an_action_that_changes_something_is_a_job(self): self.berth('provisioner', 'box', 'run', 'settings', 'place=attic', '--yes') - serve = Serve(self.station, web=False) + serve = Serve(self.station) try: page = serve.call('GET', '/v1/provisioners/box') self.assertEqual((page['state'], page['message']), ('ready', 'The lab at attic answers')) @@ -223,7 +223,7 @@ def test_2_its_page_actions_log_and_change(self): self.assertEqual(requests(self.folder)[-1]['verb'], 'change') def test_3_through_berth_serve_with_a_token_asked_twice(self): - serve = Serve(self.station, web=False) + serve = Serve(self.station) try: body = {'provisioner': 'box', 'kind': 'deployment', 'name': 'yard', 'spec': 'yard: 1\n', 'secrets': [{'name': 'bench_token', 'env': 'TOKEN'}], 'token': 'yard-1'} diff --git a/tests/e2e/e2e_restore.py b/tests/e2e/e2e_restore.py index a07d157..2b1fd08 100644 --- a/tests/e2e/e2e_restore.py +++ b/tests/e2e/e2e_restore.py @@ -62,7 +62,7 @@ def setUpClass(cls): key = station.own_key_file() wait_for('the operator taking the key of the server', lambda: station.ssh( OPERATOR, 'true', key=key, check=False).returncode == 0) - serve = Serve(station, web=False) + serve = Serve(station) try: cls.fill(serve) finally: @@ -76,7 +76,7 @@ def setUpClass(cls): wipe(station) shutil.rmtree(keep) station.env.update(BERTH_STORE=str(cls.moved / 'berth.db'), BERTH_STORE_KEY=str(cls.moved / 'store.key')) - cls.serve = Serve(station, web=False) + cls.serve = Serve(station) @classmethod def give_the_host_the_keys(cls): diff --git a/tests/e2e/e2e_serve.py b/tests/e2e/e2e_serve.py index 84e07fd..98e484a 100644 --- a/tests/e2e/e2e_serve.py +++ b/tests/e2e/e2e_serve.py @@ -1,6 +1,5 @@ """berth serve over TCP: its routes and the portal, the roles of access -tokens, setting the server up through the API, applying as a job, and the -page for a browser. +tokens, setting the server up through the API, and applying as a job. All but ApplyJob use berth serve as harness.served() starts it. ApplyJob looks at the job of the server's own shared state (harness.served_extended()).""" @@ -285,35 +284,11 @@ def test_applying_is_a_job_of_the_server(self): class ClosedSetUp(unittest.TestCase): def test_set_up_can_be_closed_to_the_network(self): station = Workstation('closed', ssh_key=False) - closed = Serve(station, web=False, env={'BERTH_SERVE_SETUP': 'off'}) + closed = Serve(station, env={'BERTH_SERVE_SETUP': 'off'}) try: self.assertEqual(closed.call('GET', '/v1/access'), {'role': 'operate', 'setup': False}) status, answer = closed.request('PUT', '/v1/secrets/x', {'value': 'y'}) self.assertEqual(status, 403) self.assertIn('set-up', answer['error']['message']) - # The page is only there with --web. - status, _ = closed.request('GET', '/', token='') - self.assertNotEqual(status, 200) finally: closed.stop() - - -@needs_e2e -class Page(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.serve = served() - - def test_the_page_is_given_to_anyone(self): - status, page, headers = self.serve.request('GET', '/', token='', raw=True) - self.assertEqual(status, 200) - self.assertTrue(headers['content-type'].startswith('text/html'), headers) - self.assertIn(b'berth-web', page) - status, script, headers = self.serve.request('GET', '/berth-web.js', token='', raw=True) - self.assertEqual(status, 200) - self.assertIn('javascript', headers['content-type']) - status, wasm, headers = self.serve.request('GET', '/berth-web_bg.wasm', token='', raw=True) - self.assertEqual((status, wasm[:4], headers['content-type']), (200, b'\0asm', 'application/wasm')) - # What the page shows it fetches with a token. - self.assertEqual(self.serve.request('GET', '/v1/hosts', token='')[0], 401) - diff --git a/tests/e2e/harness.py b/tests/e2e/harness.py index c3dec1d..b090cbe 100644 --- a/tests/e2e/harness.py +++ b/tests/e2e/harness.py @@ -355,8 +355,8 @@ def served(): wait_for('the operator taking the server\'s key', lambda: server.ssh( OPERATOR, 'true', key=key, check=False).returncode == 0) issuer = Issuer() - serve = Serve(server, web=True, env={'BERTH_OAUTH_ISSUER': issuer.url, 'BERTH_OAUTH_AUDIENCE': 'berth', - **package_registry().env()}) + serve = Serve(server, env={'BERTH_OAUTH_ISSUER': issuer.url, 'BERTH_OAUTH_AUDIENCE': 'berth', + **package_registry().env()}) serve.issuer = issuer # The host's profile as the workstation has it, so applying it from the # server keeps the workstation's keys; the server adds its own. What the @@ -688,11 +688,11 @@ def unb64(text): class Serve: """`berth serve --listen` of a workstation, on a port of its own.""" - def __init__(self, station, web=True, env=None): + def __init__(self, station, env=None): MADE['serve'] += 1 self.station = station self.port = free_port() - args = ['serve', '--listen', f'127.0.0.1:{self.port}'] + (['--web'] if web else []) + args = ['serve', '--listen', f'127.0.0.1:{self.port}'] self.process = station.spawn(*args, env=env) self.lines = [] self._reader = threading.Thread(target=self._read, daemon=True) diff --git a/tests/e2e/run.py b/tests/e2e/run.py index baaf3d1..a4ceede 100644 --- a/tests/e2e/run.py +++ b/tests/e2e/run.py @@ -65,7 +65,6 @@ 'e2e_serve.Roles', 'e2e_serve.SetUp', 'e2e_serve.ClosedSetUp', - 'e2e_serve.Page', 'e2e_client.Client', 'e2e_client.AccessToken', # served_extended(): applied by the server, with a plugin and the tailnet. From 2ff37e156866a75c772fd88dfbc04e48950441d5 Mon Sep 17 00:00:00 2001 From: Helight Date: Sat, 14 Nov 2026 23:38:09 +0100 Subject: [PATCH 02/94] ci: drop the wasm build and the berth-web release archive --- .github/workflows/ci.yml | 2 +- .github/workflows/docs.yml | 6 ------ .github/workflows/release.yml | 24 +++++++----------------- ci/boot.sh | 2 +- ci/checks.sh | 13 +++---------- ci/dev.Dockerfile | 2 +- ci/run.sh | 2 +- 7 files changed, 14 insertions(+), 37 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 51196b3..f13437d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -81,7 +81,7 @@ jobs: key: e2e-${{ hashFiles('Cargo.lock', 'ci/dev.Dockerfile') }}-${{ github.sha }} restore-keys: e2e-${{ hashFiles('Cargo.lock', 'ci/dev.Dockerfile') }}- - name: Build berth - run: ci/run.sh run cargo build --locked -p berth --features web + run: ci/run.sh run cargo build --locked -p berth # berth, and the berthd and box it puts into the role's files. A tar # keeps their modes, which an artifact does not. - name: Pack what the shards test diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index dfddb30..5dfbd9b 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -24,16 +24,10 @@ jobs: - uses: actions/setup-node@v4 with: node-version: 24 - # The site has the page of berth serve under /web, which building berth makes. - - uses: dtolnay/rust-toolchain@stable - with: - targets: x86_64-unknown-linux-musl, wasm32-unknown-unknown - - uses: Swatinem/rust-cache@v2 - run: npm install --no-audit --no-fund && npm run build working-directory: docs env: DOCS_BASE_PATH: ${{ steps.pages.outputs.base_path }} - - run: test -f docs/out/web/berth-web_bg.wasm - uses: actions/upload-pages-artifact@v5 with: path: docs/out diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 23e0059..39b399a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -26,7 +26,7 @@ jobs: fi - uses: dtolnay/rust-toolchain@stable with: - targets: x86_64-unknown-linux-musl, wasm32-unknown-unknown + targets: x86_64-unknown-linux-musl - name: musl compiler for the bundled SQLite run: sudo apt-get update && sudo apt-get install -y --no-install-recommends musl-tools - uses: Swatinem/rust-cache@v2 @@ -39,21 +39,13 @@ jobs: tar -czf berth-x86_64-linux.tar.gz -C dist berth LICENSE-MIT LICENSE-APACHE sha256sum berth-x86_64-linux.tar.gz > berth-x86_64-linux.tar.gz.sha256 cp target/host/x86_64-unknown-linux-musl/release/berthd target/host/x86_64-unknown-linux-musl/release/box dist/ - - name: Build berth with the page for a browser - run: cargo build --release --locked --target x86_64-unknown-linux-musl -p berth --features web - - name: Pack it - run: | - cp target/x86_64-unknown-linux-musl/release/berth dist/berth - tar -czf berth-web-x86_64-linux.tar.gz -C dist berth LICENSE-MIT LICENSE-APACHE - sha256sum berth-web-x86_64-linux.tar.gz > berth-web-x86_64-linux.tar.gz.sha256 - name: Check the versions - # berth in both archives, and the berthd and box it carries, all say the same. + # berth in the archive, and the berthd and box it carries, all say the same. run: | want=${BERTH_BUILD_VERSION:-$(sed -n '/^\[workspace.package\]/,/^\[/s/^version = "\(.*\)"/\1/p' Cargo.toml)} - mkdir check check-web + mkdir check tar -xzf berth-x86_64-linux.tar.gz -C check berth - tar -xzf berth-web-x86_64-linux.tar.gz -C check-web berth - for program in check/berth check-web/berth dist/berthd dist/box; do + for program in check/berth dist/berthd dist/box; do said=$("$program" --version) echo "$program: $said" case "$said" in @@ -61,22 +53,20 @@ jobs: *) echo "::error::$program says $said, not $want"; exit 1 ;; esac done - rm -r check check-web + rm -r check - uses: actions/upload-artifact@v4 with: name: berth-x86_64-linux path: | berth-x86_64-linux.tar.gz berth-x86_64-linux.tar.gz.sha256 - berth-web-x86_64-linux.tar.gz - berth-web-x86_64-linux.tar.gz.sha256 - uses: actions/upload-artifact@v4 with: name: host-programs-x86_64-linux path: | dist/berthd dist/box - # berth-remote, the page of berth serve in a terminal, to use a server's + # berth-remote, the screens of berth serve in a terminal, to use a server's # hosts from another machine. Each is built on the system it is for, so # that its version can be run there. remote: @@ -186,7 +176,7 @@ jobs: # A release made on GitHub's page exists already, and only lacks the files. gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1 \ || gh release create "$GITHUB_REF_NAME" --verify-tag --generate-notes $prerelease - gh release upload "$GITHUB_REF_NAME" --clobber berth-x86_64-linux.tar.gz berth-x86_64-linux.tar.gz.sha256 berth-web-x86_64-linux.tar.gz berth-web-x86_64-linux.tar.gz.sha256 \ + gh release upload "$GITHUB_REF_NAME" --clobber berth-x86_64-linux.tar.gz berth-x86_64-linux.tar.gz.sha256 \ berth-remote-*.zip berth-remote-*.zip.sha256 berth-remote-*.tar.gz berth-remote-*.tar.gz.sha256 \ install.sh install-remote.sh install.ps1 VERSION image: diff --git a/ci/boot.sh b/ci/boot.sh index 8ebf7c8..e283643 100644 --- a/ci/boot.sh +++ b/ci/boot.sh @@ -63,7 +63,7 @@ boot() { boot_compose build --quiet fi # The guest gets berth's host programs from the role's files, which this build puts there. - dev cargo build --locked -p berth --features web + dev cargo build --locked -p berth local kind status=0 run for kind in "${kinds[@]}"; do diff --git a/ci/checks.sh b/ci/checks.sh index 6c2bd00..61fff7f 100755 --- a/ci/checks.sh +++ b/ci/checks.sh @@ -4,14 +4,11 @@ set -euo pipefail cd /src -crates=(-p berth-api -p berth-pty -p berth-core -p berth-tui -p berth -p berthd -p box -p berth-page -p berth-web -p berth-remote) +crates=(-p berth-api -p berth-pty -p berth-core -p berth-tui -p berth -p berthd -p box -p berth-page -p berth-remote) # Each runs as the condition of an if, where set -e does not stop it: the # steps are joined with && instead. -rust-tests() { - cargo test --locked && - cargo test --locked -p berth --features web -} +rust-tests() { cargo test --locked; } python-tests() { python3 -m unittest discover -s tests -v; } shell-syntax() { local script bad=0 @@ -29,11 +26,7 @@ ansible-syntax() { (cd recipes/berth-server && ansible-playbook -i localhost, site.yml --syntax-check) } fmt() { cargo fmt --check "${crates[@]}"; } -clippy() { - cargo clippy --locked --all-targets -- -D warnings && - cargo clippy --locked --all-targets -p berth --features web -- -D warnings && - cargo clippy --locked -p berth-web --target wasm32-unknown-unknown -- -D warnings -} +clippy() { cargo clippy --locked --all-targets -- -D warnings; } vale() { command vale --minAlertLevel=warning README.md AGENTS.md docs/content/docs plugins/*/guide.md; } all=(fmt shell-syntax ansible-syntax vale python-tests rust-tests clippy) diff --git a/ci/dev.Dockerfile b/ci/dev.Dockerfile index a48d1d2..13da9fc 100644 --- a/ci/dev.Dockerfile +++ b/ci/dev.Dockerfile @@ -11,7 +11,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ procps python3 python3-venv tini xz-utils \ && rm -rf /var/lib/apt/lists/* \ && rustup component add clippy rustfmt \ - && rustup target add x86_64-unknown-linux-musl wasm32-unknown-unknown + && rustup target add x86_64-unknown-linux-musl RUN curl -fsSL "https://github.com/errata-ai/vale/releases/download/v${VALE_VERSION}/vale_${VALE_VERSION}_Linux_64-bit.tar.gz" \ | tar -xz -C /usr/local/bin vale COPY provision/requirements.txt /tmp/requirements.txt diff --git a/ci/run.sh b/ci/run.sh index c9fb3bd..c59d924 100755 --- a/ci/run.sh +++ b/ci/run.sh @@ -144,7 +144,7 @@ docker_up() { e2e() { # The test host and the runner have no way out, so berth is built first. if [[ ${BERTH_CI_PREBUILT:-} != 1 ]]; then - dev cargo build --locked -p berth --features web + dev cargo build --locked -p berth fi e2e_down trap e2e_down EXIT From afe1eca7d97530bb3e8e7316393ec301752873b2 Mon Sep 17 00:00:00 2001 From: Helight Date: Sat, 14 Nov 2026 23:38:09 +0100 Subject: [PATCH 03/94] docs: point to berth-remote where the browser page was --- .agents/skills/install-berth/SKILL.md | 2 +- .github/CONTRIBUTING.md | 2 +- .github/PULL_REQUEST_TEMPLATE.md | 2 +- AGENTS.md | 14 ++- crates/berth-remote/README.md | 6 +- docs/.gitignore | 3 - .../docs/(guide)/deploy/deployments.mdx | 2 +- .../docs/(guide)/deploy/provisioners.mdx | 4 +- .../content/docs/(guide)/deploy/resources.mdx | 2 +- docs/content/docs/(guide)/extend/plugins.mdx | 2 +- docs/content/docs/(guide)/extend/serve.mdx | 4 +- .../docs/(guide)/reference/building.mdx | 31 ++----- docs/content/docs/(guide)/start/install.mdx | 2 +- docs/content/docs/(guide)/use/accounts.mdx | 2 +- docs/content/docs/(guide)/use/cli.mdx | 2 +- docs/content/docs/(guide)/use/levels.mdx | 6 +- docs/content/docs/(guide)/use/moving.mdx | 2 +- docs/content/docs/(guide)/use/server.mdx | 86 ++++++------------- docs/content/docs/(guide)/use/terminal-ui.mdx | 2 +- docs/next.config.mjs | 6 -- docs/scripts/gather.mjs | 3 +- docs/scripts/web.mjs | 44 ---------- docs/src/lib/layout.shared.tsx | 2 - recipes/README.md | 4 +- recipes/berth-server/README.md | 10 ++- recipes/incus-host/README.md | 11 ++- recipes/shared/berth-server.yml | 6 +- 27 files changed, 80 insertions(+), 182 deletions(-) delete mode 100644 docs/scripts/web.mjs diff --git a/.agents/skills/install-berth/SKILL.md b/.agents/skills/install-berth/SKILL.md index bfeda7a..69bc080 100644 --- a/.agents/skills/install-berth/SKILL.md +++ b/.agents/skills/install-berth/SKILL.md @@ -161,7 +161,7 @@ The recipes make a key on the first run and print it at the end. Give the user the key and the address, which `tailscale serve status` shows: 1. On their own machine they run `berth connect https://THIS-MACHINE.YOUR-TAILNET.ts.net` and enter the key. -2. Or they open `https://THIS-MACHINE.YOUR-TAILNET.ts.net/#setup-key=KEY` in a browser. +2. Or they run `berth-remote --server https://THIS-MACHINE.YOUR-TAILNET.ts.net` with the key in `BERTH_SETUP_KEY`. It works on Windows and macOS too. The key ends when they choose Done, or when `berth connect` has saved the token. diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index db0cf93..8ef6200 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -109,7 +109,7 @@ A pull request is ready when: vale --minAlertLevel=warning "docs/content/docs/(guide)" README.md AGENTS.md ``` -- The terminal client and the page in a browser do the same things. A feature +- berth and berth-remote do the same things with a server's hosts. A feature added to one is added to the other, with the shared part in `crates/berth-tui`. - Commits follow [Conventional Commits](https://www.conventionalcommits.org/), diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index adaea1f..b28a811 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -11,5 +11,5 @@ Issue: # - [ ] `ci/run.sh all` passes - [ ] Tried on a real host as well as in the containers (say which kind above) - [ ] Documentation is updated and Vale doesn't report warnings -- [ ] The terminal client and the page in a browser both have it, where it applies +- [ ] berth and berth-remote both have it, where it applies - [ ] I read every line of this change myself diff --git a/AGENTS.md b/AGENTS.md index 202ce0e..2f41159 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,12 +9,11 @@ berth sets up and looks after agent workstations. These are Ubuntu machines with | `crates/berth/` | The `berth` program: terminal UI, commands and `berth serve` (`crates/berth/src/serve/`). In `serve/`, `actions.rs` has the actions of hosts and of the installation, `keys.rs` the key ring's routes, `provisioners.rs` and `resources.rs` those of provisioners and resources | | `crates/berth-api/` | Types and the operations table shared by every program (`ops.rs` names each operation, its HTTP route and its role) | | `crates/berth-core/` | Hosts, profiles, links to hosts, registries and secrets, and plugins. The store is in `store/`. `kept.rs` and `plugin_state.rs` write files from it, and `import.rs` takes in the files of older versions. `kept_profile.rs` is the profile a host keeps of itself and `berth adopt`. `runner.rs` runs every action as a job. `keys/` is the key ring and how berth logs in to hosts. `level.rs` says what a host can do at each level. `provisioner.rs` and `resource.rs` are the provisioners of plugins and what they made | -| `crates/berth-tui/` | The parts of the UI that run in a terminal and in a browser | +| `crates/berth-tui/` | The parts of the UI that `berth` and `berth-remote` share | | `crates/berth-pty/` | Terminals for sessions | | `crates/berthd/`, `crates/box/` | The controller on each host and the agent's own tool there | -| `crates/berth-page/` | The screens of the page of `berth serve`, shared by `berth-web` and `berth-remote`. `device.rs` is what a browser and a terminal each give them, and `portal.rs` the server's portal over it | -| `crates/berth-web/` | The page of `berth serve --web`, built for WebAssembly: the browser's side of `berth-page`'s device | -| `crates/berth-remote/` | `berth-remote`, the same screens in a terminal on Linux, macOS and Windows, for a `berth serve` on another machine | +| `crates/berth-page/` | The screens of `berth-remote` for a `berth serve` elsewhere. `device.rs` is what the program gives them, and `portal.rs` the server's portal over it | +| `crates/berth-remote/` | `berth-remote`, those screens in a terminal on Linux, macOS and Windows, for a `berth serve` on another machine | | `crates/vendor/` | The vendored `tui-input` crate | | `provision/` | The installer side of the provisioning source: the role in `ansible/`, first-boot provisioning in `bootstrap/`, the builder of seeds and releases in `bin/devbox.py` and the example profile in `config/`. berth names these paths in `layout` in `crates/berth-core/src/paths.rs` | | `plugins/` | The plugins that come with berth, each an npm-format package with a `guide.md`. With `provision/` they make the provisioning source, which berth carries and unpacks with the same layout | @@ -48,16 +47,13 @@ Use cargo for everything Rust. These are what CI runs: ```bash cargo test --locked -cargo test --locked -p berth --features web -cargo fmt --check -p berth-api -p berth-pty -p berth-core -p berth-tui -p berth -p berthd -p box -p berth-page -p berth-web -p berth-remote +cargo fmt --check -p berth-api -p berth-pty -p berth-core -p berth-tui -p berth -p berthd -p box -p berth-page -p berth-remote cargo clippy --locked --all-targets -- -D warnings -cargo clippy --locked --all-targets -p berth --features web -- -D warnings -cargo clippy --locked -p berth-web --target wasm32-unknown-unknown -- -D warnings python3 -m unittest discover -s tests -v vale --minAlertLevel=warning README.md docs/content/docs plugins/*/guide.md ``` -Development and test builds embed quick builds of berthd, box and the page (the `host-dev` and `web-dev` profiles). Only `--release` embeds the release builds. The `web` feature needs the `wasm32-unknown-unknown` target. The Python tests skip their YAML checks without PyYAML, so install `provision/requirements.txt` in a virtual environment to run them all. +Development and test builds embed quick builds of berthd and box (the `host-dev` profile). Only `--release` embeds the release builds. The Python tests skip their YAML checks without PyYAML, so install `provision/requirements.txt` in a virtual environment to run them all. ### In containers diff --git a/crates/berth-remote/README.md b/crates/berth-remote/README.md index 773ea52..cda5862 100644 --- a/crates/berth-remote/README.md +++ b/crates/berth-remote/README.md @@ -1,6 +1,6 @@ # berth-remote -berth-remote shows the hosts of a `berth serve` on another machine, in a terminal. It has the screens of the page that `berth serve --web` gives, and it runs on Windows, macOS and Linux. +berth-remote shows the hosts of a `berth serve` on another machine, in a terminal. It runs on Windows, macOS and Linux. It is only a client. Setting up hosts, Ansible and SSH stay on the server. @@ -25,7 +25,7 @@ Each script checks the download against its SHA-256. It installs to `%LOCALAPPDA Start the server on an address of your network: ```bash -berth serve --listen 0.0.0.0:7878 +berth serve --listen 0.0.0.0:7878 --expose ``` Then on your own machine: @@ -55,7 +55,7 @@ Ctrl+Q quits. ## How it is built -The screens are in `crates/berth-page`, which the page for a browser (`crates/berth-web`) uses too. This crate gives them a terminal in place of a browser: `device.rs` has the clipboard, links, the file dialog and the kept settings, `net.rs` and `socket.rs` the HTTP requests and the portal's WebSocket over TCP or TLS. +The screens are in `crates/berth-page`. This crate gives them a terminal: `device.rs` has the clipboard, links, the file dialog and the kept settings, `net.rs` and `socket.rs` the HTTP requests and the portal's WebSocket over TCP or TLS. On the system it is for: diff --git a/docs/.gitignore b/docs/.gitignore index 1bae26f..3644477 100644 --- a/docs/.gitignore +++ b/docs/.gitignore @@ -11,6 +11,3 @@ npm-debug.log* /content/docs/api/host/ /content/docs/api/serve/ /public/openapi/ - -# the page of berth serve, copied from target/web-dist (npm run gather) -/public/web/ diff --git a/docs/content/docs/(guide)/deploy/deployments.mdx b/docs/content/docs/(guide)/deploy/deployments.mdx index 78ce8ab..ed174fe 100644 --- a/docs/content/docs/(guide)/deploy/deployments.mdx +++ b/docs/content/docs/(guide)/deploy/deployments.mdx @@ -61,7 +61,7 @@ berth refuses before anything is made when a secret has no value, or when the na ### From the provisioner's page -The Hosts tab has the row **+ New compose project**, and the provisioner's page the action of that name, `new-deployment`, in the terminal UI and in the page of [`berth serve --web`](/docs/use/server#in-a-browser). Both open a form laid out like a host's set-up, with the provisioner, the name, the Compose file, the secrets and the deployment's own arguments each on a row. Enter on a row edits it, and Enter on **Run** makes the deployment. The Compose file opens in a text editor that takes the whole screen. Ctrl+S keeps the file, and Esc leaves it as it was. The file is kept in berth's store, so no file on your machine is needed. Give the secrets as `NAME` or `NAME:VARIABLE`, separated by commas. The deployment is made as a job of the provisioner, and is listed on its page when the job ends. +The Hosts tab has the row **+ New compose project**, and the provisioner's page the action of that name, `new-deployment`, in the terminal UI and in [berth-remote](/docs/use/server#with-berth-remote). Both open a form laid out like a host's set-up, with the provisioner, the name, the Compose file, the secrets and the deployment's own arguments each on a row. Enter on a row edits it, and Enter on **Run** makes the deployment. The Compose file opens in a text editor that takes the whole screen. Ctrl+S keeps the file, and Esc leaves it as it was. The file is kept in berth's store, so no file on your machine is needed. Give the secrets as `NAME` or `NAME:VARIABLE`, separated by commas. The deployment is made as a job of the provisioner, and is listed on its page when the job ends. From the command line the action takes the same values: diff --git a/docs/content/docs/(guide)/deploy/provisioners.mdx b/docs/content/docs/(guide)/deploy/provisioners.mdx index 53b21c8..9314775 100644 --- a/docs/content/docs/(guide)/deploy/provisioners.mdx +++ b/docs/content/docs/(guide)/deploy/provisioners.mdx @@ -151,7 +151,7 @@ berth provisioner docker run prune volumes=yes In a terminal, `run` prompts for a required argument you leave out. It puts the action's question first, unless `--yes` is given. An action that only reads, such as `images`, answers at once. One that changes something runs as a job and shows its output as it comes. Only one such job runs at a time for a provisioner. -In the terminal UI, the **Provisioners** tab of the home screen (`2`) lists the provisioners, and `a` registers one. Enter opens a page, which lists the actions in their groups and what berth made there, by kind. Enter on an action shows its question and then a dialog for its arguments. A job's output fills a panel. An argument of several lines, such as a Compose file, keeps the line breaks of what you paste. Each shows as `⏎`. Enter on something berth made opens its [resource's page](/docs/deploy/resources#in-the-terminal-ui), and Esc comes back. The page of [`berth serve --web`](/docs/use/server#in-a-browser) has the same tab. +In the terminal UI, the **Provisioners** tab of the home screen (`2`) lists the provisioners, and `a` registers one. Enter opens a page, which lists the actions in their groups and what berth made there, by kind. Enter on an action shows its question and then a dialog for its arguments. A job's output fills a panel. An argument of several lines, such as a Compose file, keeps the line breaks of what you paste. Each shows as `⏎`. Enter on something berth made opens its [resource's page](/docs/deploy/resources#in-the-terminal-ui), and Esc comes back. [berth-remote](/docs/use/server#with-berth-remote) has the same tab. ## Seed and apply @@ -247,7 +247,7 @@ In the terminal UI, choose **Create a machine** under **How To Install** on the | Settings | Under **Machine**, the resources it has, such as CPUs, memory and disk. Under **Provisioner Options**, its other arguments | | Run | **Create machine**, and every problem | -The first provisioner is chosen when the list arrives. There is no **Host profile** row. A created machine is always a `cloud` host. berth writes that into the profile before it creates the machine, on the command line as well. Enter on an argument changes it. A missing secret is a problem of the Install tab, and a bad resource value one of the Settings tab. **Create machine** on the Run tab asks once before it saves the profile and starts, and does not start while a problem is listed. The output is shown as it runs. The page of [`berth serve --web`](/docs/use/server#in-a-browser) has the same tabs. +The first provisioner is chosen when the list arrives. There is no **Host profile** row. A created machine is always a `cloud` host. berth writes that into the profile before it creates the machine, on the command line as well. Enter on an argument changes it. A missing secret is a problem of the Install tab, and a bad resource value one of the Settings tab. **Create machine** on the Run tab asks once before it saves the profile and starts, and does not start while a problem is listed. The output is shown as it runs. [berth-remote](/docs/use/server#with-berth-remote) has the same tabs. Only one thing runs at a time for a host. A second command for the same host is refused until the first ends. diff --git a/docs/content/docs/(guide)/deploy/resources.mdx b/docs/content/docs/(guide)/deploy/resources.mdx index e89e039..1eae969 100644 --- a/docs/content/docs/(guide)/deploy/resources.mdx +++ b/docs/content/docs/(guide)/deploy/resources.mdx @@ -145,7 +145,7 @@ Compose project berth made with it An entry the provisioner lists with berth's labels, but that berth has no record of, is marked *no record of it*. berth does not remove it. -Enter on an entry opens the resource's page. It shows the resource's state and fields, and its actions in their groups. **Show its log** is there when its kind gives logs, and follows the log in a panel until you close it. Esc goes back to the provisioner's page. The page of [`berth serve --web`](/docs/use/server#in-a-browser) has the same tab. +Enter on an entry opens the resource's page. It shows the resource's state and fields, and its actions in their groups. **Show its log** is there when its kind gives logs, and follows the log in a panel until you close it. Esc goes back to the provisioner's page. [berth-remote](/docs/use/server#with-berth-remote) has the same tab. A host's machine is also on the host's Run tab, with its state and rows to start, stop and delete it. diff --git a/docs/content/docs/(guide)/extend/plugins.mdx b/docs/content/docs/(guide)/extend/plugins.mdx index 437593c..794f12c 100644 --- a/docs/content/docs/(guide)/extend/plugins.mdx +++ b/docs/content/docs/(guide)/extend/plugins.mdx @@ -76,7 +76,7 @@ A host keeps what it was applied with until it is applied again. After an update ### On a berth server -With a [berth server](/docs/use/server) set, the Plugins tab and `berth plugins` show the server's plugins and change those, which needs the role `admin` there. The server installs a package name or an `https://` address with its own npm and npm configuration. A `.tgz` or a folder on your machine is packed and sent to the server. The page in a browser has the same tab, and `u` there sends a `.tgz` from the device. +With a [berth server](/docs/use/server) set, the Plugins tab and `berth plugins` show the server's plugins and change those, which needs the role `admin` there. The server installs a package name or an `https://` address with its own npm and npm configuration. A `.tgz` or a folder on your machine is packed and sent to the server. berth-remote has the same tab, and `u` there sends a `.tgz` from its machine. The server's hosts can have a new plugin's features as soon as it is installed. Its tasks run on the server when a host is applied, so installing is part of set-up. A server with `serve_setup off` takes it only on its own socket ([Closing set-up](/docs/extend/serve#closing-set-up)). diff --git a/docs/content/docs/(guide)/extend/serve.mdx b/docs/content/docs/(guide)/extend/serve.mdx index 459feb2..6a238ba 100644 --- a/docs/content/docs/(guide)/extend/serve.mdx +++ b/docs/content/docs/(guide)/extend/serve.mdx @@ -158,7 +158,7 @@ curl -H "Authorization: Bearer $ACCESS_TOKEN" https://berth.example.ts.net/v1/ac # {"role":"operate","setup":true,"subject":"ada"} ``` -An access token is used like the server's token. It works as a bearer and as the WebSocket protocol. berth takes it as `--token` or `server_token`, and the page for a browser takes it too. +An access token is used like the server's token. It works as a bearer and as the WebSocket protocol. berth takes it as `--token` or `server_token`, and berth-remote as `BERTH_TOKEN` or when it asks. The server says which issuer it trusts at `/.well-known/oauth-protected-resource`, without a token. @@ -196,7 +196,7 @@ A caller over TCP is then `operate` at most, and the socket stays `admin`. Some ## In a container -The `ghcr.io/helightdev/berth` image runs `berth serve --listen 0.0.0.0:7777 --expose --web` by default, as user `berth` (uid 1000): +The `ghcr.io/helightdev/berth` image runs `berth serve --listen 0.0.0.0:7777 --expose` by default, as user `berth` (uid 1000): ```bash docker run -d --name berth -p 127.0.0.1:7777:7777 \ diff --git a/docs/content/docs/(guide)/reference/building.mdx b/docs/content/docs/(guide)/reference/building.mdx index 3931f55..b26c196 100644 --- a/docs/content/docs/(guide)/reference/building.mdx +++ b/docs/content/docs/(guide)/reference/building.mdx @@ -9,9 +9,9 @@ icon: Hammer | Folder | Holds | | --- | --- | | `crates/berth/` | `berth`: the terminal UI, the commands and `berth serve` | -| `crates/berth-core/`, `berth-api/`, `berth-pty/`, `berth-tui/` | Shared libraries. `berth-tui` has the screens the terminal UI and the page share | +| `crates/berth-core/`, `berth-api/`, `berth-pty/`, `berth-tui/` | Shared libraries. `berth-tui` has the screens berth and `berth-remote` share | | `crates/vendor/` | The vendored `tui-input` crate | -| `crates/berth-web/` | The page `berth serve --web` shows in a browser, built for WebAssembly. The docs build copies it to `/web` | +| `crates/berth-page/`, `crates/berth-remote/` | `berth-remote` and its screens, for a berth server elsewhere | | `crates/berthd/`, `crates/box/` | `berthd` and `box`, built static for hosts | | `provision/ansible/` | The devbox role | | `provision/bootstrap/` | First-boot provisioning | @@ -33,12 +33,11 @@ cargo install --locked --path crates/berth # into ~/.cargo/bin The build first makes `berthd` and `box` as static musl binaries and places them in the role's files. It then packs the provisioning source and embeds it in `berth`. It needs Python 3 for the packing. -A release build embeds release builds of `berthd`, `box` and the page. A development or test build (`cargo build`, `cargo test`) embeds quicker ones: +A release build embeds release builds of `berthd` and `box`. A development or test build (`cargo build`, `cargo test`) embeds quicker ones: | Part | Profile | Built | | --- | --- | --- | | `berthd`, `box` | `host-dev` | Optimised for size, incrementally, with debug assertions | -| The page | `web-dev` | Optimised, without the link-time optimisation of `web` | | berth itself | `dev` | Line numbers, no other debug information | For a debugger, `CARGO_PROFILE_DEV_DEBUG=true` gives berth's own crates full debug information. @@ -130,34 +129,18 @@ GitHub Actions build on every push: To release, push a tag such as `v0.3.0`, or create the release on GitHub's release page with a new tag. Build then: -1. Builds `berth`, `berthd`, `box` and the page with the version of the tag, and checks that each says it. Runs `boot cloud`. When it fails, nothing is published. -2. Publishes the release with both archives, the archives of `berth-remote`, their checksum files, `install.sh`, `install-remote.sh`, `install.ps1` and `VERSION`. A release made on the page gets the files added. +1. Builds `berth`, `berthd` and `box` with the version of the tag, and checks that each says it. Runs `boot cloud`. When it fails, nothing is published. +2. Publishes the release with the archive of `berth`, the archives of `berth-remote`, their checksum files, `install.sh`, `install-remote.sh`, `install.ps1` and `VERSION`. A release made on the page gets the files added. 3. Pushes the image tagged `0.3.0`, `0.3` and `latest`. 4. Opens a pull request that sets the version on `main` in `Cargo.toml`, `Cargo.lock` and `docs/openapi/`. Merge it once its checks have passed. -You don't edit a version anywhere. A build from a checkout says the version in `Cargo.toml`, which is that of the latest release. That way `berth update` never offers an older version. `berth`, `berthd`, `box` and the page take the version from `berth_api::VERSION`. A release build sets it with `BERTH_BUILD_VERSION`, and `docker build` takes the same name as a build argument. +You don't edit a version anywhere. A build from a checkout says the version in `Cargo.toml`, which is that of the latest release. That way `berth update` never offers an older version. `berth`, `berthd`, `box` and `berth-remote` take the version from `berth_api::VERSION`. A release build sets it with `BERTH_BUILD_VERSION`, and `docker build` takes the same name as a build argument. A tag with a suffix, such as `v0.4.0-rc.1`, makes a pre-release. Its programs say `0.4.0-rc.1` and its image is tagged only with that. `main` stays as it is. The install scripts and `berth update` pass over pre-releases, and `BERTH_VERSION=v0.4.0-rc.1` installs one. -## With the page for a browser - -berth comes in two builds. The usual one has no page. The `web` feature adds the page `berth serve --web` shows, built from `crates/berth-web/` as WebAssembly and carried in the program (about 2 MB more): - -```bash -rustup target add wasm32-unknown-unknown # once -cargo build --release -p berth --features web -``` - -| Build | Release archive | Install script | -| --- | --- | --- | -| Usual | `berth-x86_64-linux.tar.gz` | the default | -| With the page | `berth-web-x86_64-linux.tar.gz` | `BERTH_VARIANT=web` | - -`berth update` stays with the build it is. The container image is the one with the page. The docs build takes the page from `target/web-dist` for `/web`. It builds the page with the `web` profile, as a release does, by setting `BERTH_WEB_PROFILE=web`. - ## berth-remote -`berth-remote` is the client for a [berth server](/docs/use/server#with-berth-remote) in a terminal. The screens of the page are in `crates/berth-page/`, which `crates/berth-web/` builds for a browser and `crates/berth-remote/` for a terminal. Each program gives the screens its own `Device`, from `crates/berth-page/src/device.rs`. It covers the clipboard, links, files, what is kept and the portal's socket. +`berth-remote` is the client for a [berth server](/docs/use/server#with-berth-remote) in a terminal. Its screens are in `crates/berth-page/`, and `crates/berth-remote/` gives them a terminal through a `Device`, from `crates/berth-page/src/device.rs`. It covers the clipboard, links, files, what is kept and the portal's socket. It builds on the system it is for: diff --git a/docs/content/docs/(guide)/start/install.mdx b/docs/content/docs/(guide)/start/install.mdx index da556d3..4f6e890 100644 --- a/docs/content/docs/(guide)/start/install.mdx +++ b/docs/content/docs/(guide)/start/install.mdx @@ -65,7 +65,7 @@ See [A berth server](/docs/use/server). -berth itself needs Linux. `berth-remote` is the client for a [berth server](/docs/use/server) on another machine, with the screens of its page in a terminal. It runs on Windows, macOS and Linux: +berth itself needs Linux. `berth-remote` is the client for a [berth server](/docs/use/server) on another machine, in a terminal. It runs on Windows, macOS and Linux: ```powershell title="Windows, in PowerShell" irm https://raw.githubusercontent.com/helightdev/berth/main/install.ps1 | iex diff --git a/docs/content/docs/(guide)/use/accounts.mdx b/docs/content/docs/(guide)/use/accounts.mdx index 9f3e49b..3697e99 100644 --- a/docs/content/docs/(guide)/use/accounts.mdx +++ b/docs/content/docs/(guide)/use/accounts.mdx @@ -143,7 +143,7 @@ The SSH host key of studio is not the one berth recorded: the machine was set up 1. berth makes a new key and stores it beside the current one as pending. 2. On each host that takes the key, it logs in and adds the new key. Once a login with the new key works, it removes the old one. -3. A host that does not answer stays pending. berth offers it both keys until then, and an apply gives the operator both. The Hosts tab marks it, in the terminal UI and on the browser page. +3. A host that does not answer stays pending. berth offers it both keys until then, and an apply gives the operator both. The Hosts tab marks it, in the terminal UI and in berth-remote. 4. When no host is pending, the new key replaces the old one, which is deleted. Running it again goes on where it stopped. With a berth server set, the rotation runs as a job on the server, and its output is shown as it comes. diff --git a/docs/content/docs/(guide)/use/cli.mdx b/docs/content/docs/(guide)/use/cli.mdx index ad61670..69aa57e 100644 --- a/docs/content/docs/(guide)/use/cli.mdx +++ b/docs/content/docs/(guide)/use/cli.mdx @@ -156,7 +156,7 @@ With a [berth server](/docs/use/server) set, these show and change the server's | --- | --- | | `berth call HOST SERVICE METHOD [JSON]` | Call a service a plugin runs on the host | | `berth channel HOST [TOPIC-PREFIX] [--since ID]` | Messages on the host's channel as they come | -| `berth serve [--listen ADDRESS:PORT [--expose] [--web]]` | The API over all hosts ([berth serve](/docs/extend/serve)). `--expose` allows an address other than loopback. `--web` also shows [the hosts in a browser](/docs/use/server#in-a-browser) | +| `berth serve [--listen ADDRESS:PORT [--expose]]` | The API over all hosts ([berth serve](/docs/extend/serve)). `--expose` allows an address other than loopback | | `berth update [--check]` | Replace this program with the latest release ([Updates](/docs/use/updates#berth-itself)) | | `berth setup-key [--remove]` | Make a [setup key](/docs/use/server#with-a-setup-key) for the `berth serve` whose data is on this machine, valid for 24 hours, in place of any earlier one. `--remove` ends it | | `berth inbox [HOST] [--topic PREFIX] [--all]` | Messages `berth serve` took in from the hosts' channels | diff --git a/docs/content/docs/(guide)/use/levels.mdx b/docs/content/docs/(guide)/use/levels.mdx index 0effb20..089afda 100644 --- a/docs/content/docs/(guide)/use/levels.mdx +++ b/docs/content/docs/(guide)/use/levels.mdx @@ -27,7 +27,7 @@ The level is part of the host's [profile](/docs/reference/profile#level), as `le | Apply, roll-out, cloud seed, USB installer | no | no | yes | | Desktop and access links | no | no | yes | -The terminal UI, the browser page, the commands and the API all use the same check in berth. An action the level rules out is still listed, as unavailable, with the reason and what raises the level. Asked for anyway, the server refuses it with `501 not_available`. A roll-out leaves hosts that aren't workstations and says how many it left. +The terminal UI, berth-remote, the commands and the API all use the same check in berth. An action the level rules out is still listed, as unavailable, with the reason and what raises the level. Asked for anyway, the server refuses it with `501 not_available`. A roll-out leaves hosts that aren't workstations and says how many it left. ## Adding a machine that exists @@ -63,7 +63,7 @@ berth host level dock controller `berth host level HOST LEVEL` only changes the profile here. A host's page says the same when its controller reports more than its profile says. berth refuses to install the controller alone on a host that is a workstation, whatever its profile here says. It asks the host's controller first, and the playbook checks the host's own record and the profile it keeps. -In the terminal UI, create a host on the home screen and choose **Existing host, SSH only** on the **Install** tab. The address and the login are all the set-up asks for, and **Run** saves the host. For a controller, choose **Existing host over SSH** and set **Level** to `controller`. **Run** then installs the controller. The browser page does the same through the server. +In the terminal UI, create a host on the home screen and choose **Existing host, SSH only** on the **Install** tab. The address and the login are all the set-up asks for, and **Run** saves the host. For a controller, choose **Existing host over SSH** and set **Level** to `controller`. **Run** then installs the controller. berth-remote does the same through the server. Over the API, `hosts.save` takes a profile with only the level and `access`: @@ -98,7 +98,7 @@ berth host install dock The controller is berthd and box with the files they read, from the same part of the role that a full apply runs. Nothing else of a workstation is installed: no accounts, desktop, agents or plugins. The SSH user is the account sessions run as, and its home is where the file calls may go. The host's level becomes `controller`, and its tasks are status, update, reboot and secrets. -The same is the host's action **Install the controller** on its overview, in the browser page and over the API as `install-controller`. On a controller host it's called **Update the controller**: run it after updating berth, as berth's own version is all such a host is compared with. A workstation's controller comes with applying its configuration, so the action is not offered there. +The same is the host's action **Install the controller** on its overview, in berth-remote and over the API as `install-controller`. On a controller host it's called **Update the controller**: run it after updating berth, as berth's own version is all such a host is compared with. A workstation's controller comes with applying its configuration, so the action is not offered there. berth also refuses it on a host that is a workstation whatever its profile here says. It asks the host's controller first. The role checks again on the host before it changes anything. It stops when the host's record says workstation. It also stops when berthd there serves an account other than the SSH user. Installing the controller alone on such a host would take the workstation's controller apart. The overview and `berth tasks` say when a host is more than its profile, and how to adopt it. diff --git a/docs/content/docs/(guide)/use/moving.mdx b/docs/content/docs/(guide)/use/moving.mdx index bfa3bbf..29d21df 100644 --- a/docs/content/docs/(guide)/use/moving.mdx +++ b/docs/content/docs/(guide)/use/moving.mdx @@ -122,4 +122,4 @@ berth moves everything it keeps under the old name to the new one, in one change With `--hostname`, the new name becomes the profile's hostname as well. The machine takes it at its next apply, which also writes the profile the host keeps with the new name. The name has to suit a hostname then: lower-case letters, digits and `-`. -berth refuses when a host has the new name already. A job that is creating the host's machine blocks the rename until that job ends. When a [berth server](/docs/use/server) keeps the host, the server renames it as a job. On the server's page and over its API it's the host's action **Rename**, `rename`. +berth refuses when a host has the new name already. A job that is creating the host's machine blocks the rename until that job ends. When a [berth server](/docs/use/server) keeps the host, the server renames it as a job. In berth-remote and over the server's API it's the host's action **Rename**, `rename`. diff --git a/docs/content/docs/(guide)/use/server.mdx b/docs/content/docs/(guide)/use/server.mdx index c9111bf..f622ee8 100644 --- a/docs/content/docs/(guide)/use/server.mdx +++ b/docs/content/docs/(guide)/use/server.mdx @@ -83,13 +83,14 @@ It prints the key. On your own machine, give it to berth when it asks: berth connect https://berth.example.ts.net ``` -berth checks the key, collects the token and saves `server` and `server_token`. Or open the server's page with the key in the link: +berth checks the key, collects the token and saves `server` and `server_token`. [berth-remote](#with-berth-remote) takes the key in `BERTH_SETUP_KEY` instead: -```text -https://berth.example.ts.net/#setup-key=KEY +```bash +read -rs BERTH_SETUP_KEY && export BERTH_SETUP_KEY +berth-remote --server https://berth.example.ts.net ``` -The page signs the browser in and shows the token, with the two `berth config` commands for a terminal. The key lasts 24 hours. It ends sooner when you choose **Done** on the page, or when `berth connect` has saved the token. Until then it's as good as the token, so keep it to yourself. A new key replaces the old one, and `berth setup-key --remove` ends it. A server with `serve_token` off has no token to hand out, so it doesn't make a key. +berth-remote signs in and shows the token, with the two `berth config` commands for berth. The key lasts 24 hours. It ends sooner when you choose **Done** there, or when `berth connect` has saved the token. Until then it's as good as the token, so keep it to yourself. A new key replaces the old one, and `berth setup-key --remove` ends it. A server with `serve_token` off has no token to hand out, so it doesn't make a key. | Address | Reaches | | --- | --- | @@ -97,61 +98,9 @@ The page signs the browser in and shows the token, with the two `berth config` c | `http://HOST:PORT` | A server's port directly | | `unix:/path/to/serve.sock` | A `berth serve` on this machine, without a token | -## In a browser - -With `--web`, `berth serve` also shows its hosts as a page. It needs the build of berth with the page in it. The container image is one, and the install script takes it with `BERTH_VARIANT=web` ([Building](/docs/reference/building#with-the-page-for-a-browser)). - -```bash title="On the server" -berth serve --listen 0.0.0.0:7777 --expose --web -``` - -Open the server's address in a browser and enter the token: - -``` -https://berth.example.ts.net/ -https://berth.example.ts.net/#token=TOKEN # a link that signs in -``` - -To open the page on a phone, choose **Open on another device** on the Settings tab of the home screen. It shows a QR code and the link with the token in it, so anyone who scans it gets in. The row is there when berth reaches the server with its token, such as `server_token`, and in the page for the role `admin`. From the terminal UI the link opens the server's own page, which needs `--web`. From the page it opens the same page you are on, such as the one at /web. - -The page is the terminal UI drawn in the browser. It has the host list and the overview of each host, where tasks run and sessions open in the terminal panel. The browser keeps the token until **o** on the host list signs out. A token in a link is taken out of the address bar when the page opens. - -With the role `admin` the page also sets the server up, with the same screens as the terminal UI: - -- **Provisioners**, **Settings**, **Registries**, **Secrets** and **Plugins** are tabs of the home screen. On **Plugins**, `u` sends a `.tgz` from the device. A provisioner's page opens the pages of what berth made with it ([Resources](/docs/deploy/resources#in-the-terminal-ui)). -- **New host** starts a profile, and a host's overview opens its Install, Features, Settings and Run tabs. A new host opens on Install with **Create a machine** chosen, and offers only Create a machine, Cloud-init seed and Existing host over SSH. -- **Run** does what the chosen method does on the server. That is creating the machine, a cloud-init seed to copy, or an apply over SSH. The output is shown as it runs. -- **Install secrets and registry logins** sends a host what its profile names. - -Some keys differ: - -| In the page | Instead of | -| --- | --- | -| **Alt+Q** leaves a running session | `Ctrl+Q`, which closes some browsers | -| **Ctrl+V** and the browser's paste | The desktop clipboard tools | -| A click on a link opens a tab | `xdg-open` | -| **g** generates and **p** takes a password to hash | `F4` and `F5`, which reloads a page | - -A password the server makes up is shown once in the page. The server keeps a copy in its store, and `berth credentials HOST` shows it again to an admin of the server. - -What needs your own machine stays in the terminal UI. That is the USB installer and the container image, values read from your local keys, and sending a plugin's folder. - -Keys the browser keeps for itself, such as `Ctrl+W` and `Ctrl+T`, never reach a shell in the page. A phone can tap rows and key hints, but has no keyboard for a terminal. - -### Without `--web` - -The same page is part of this site, at [/web](/web/). It asks which server to use, or takes it from its address: - -``` -/web/?server=https://berth.example.ts.net -/web/?server=https://berth.example.ts.net#token=TOKEN -``` - -Your browser talks to the server you name, and to nothing else. It keeps the server and the token. A page loaded over `https` can only reach a server over `https`. - ## With berth-remote -berth runs on Linux. `berth-remote` uses the hosts of a server from a terminal on Windows, macOS or Linux. It shows the screens of the page, and works with a server that runs without `--web`. Install it on Windows in PowerShell: +berth runs on Linux. `berth-remote` uses the hosts of a server from a terminal on Windows, macOS or Linux. Install it on Windows in PowerShell: ```powershell irm https://raw.githubusercontent.com/helightdev/berth/main/install.ps1 | iex @@ -192,13 +141,32 @@ The server and the token are in `settings.json` in a folder of your own: It talks to a server over `https` only with a certificate that the system or the Mozilla roots trust. It opens only `http` and `https` links, in the system's browser. -The screens and keys are those of the page. **Ctrl+Q** quits, and `u` on **Plugins** opens the system's file dialog: on Linux that of zenity or kdialog. +berth-remote has the host list and the overview of each host, where tasks run and sessions open in the terminal panel. **o** on the host list signs out. + +With the role `admin` it also sets the server up, with the same screens as the terminal UI: + +- **Provisioners**, **Settings**, **Registries**, **Secrets** and **Plugins** are tabs of the home screen. On **Plugins**, `u` opens the system's file dialog to send a `.tgz`: on Linux that of zenity or kdialog. A provisioner's page opens the pages of what berth made with it ([Resources](/docs/deploy/resources#in-the-terminal-ui)). +- **New host** starts a profile, and a host's overview opens its Install, Features, Settings and Run tabs. A new host opens on Install with **Create a machine** chosen, and offers only Create a machine, Cloud-init seed and Existing host over SSH. +- **Run** does what the chosen method does on the server. That is creating the machine, a cloud-init seed to copy, or an apply over SSH. The output is shown as it runs. +- **Install secrets and registry logins** sends a host what its profile names. + +Some keys differ from the terminal UI: + +| In berth-remote | Instead of | +| --- | --- | +| **Ctrl+Q** quits | `q` on the home screen | +| **Alt+Q** leaves a running session | `Ctrl+Q` | +| **g** generates and **p** takes a password to hash | `F4` and `F5` | + +A password the server makes up is shown once. The server keeps a copy in its store, and `berth credentials HOST` shows it again to an admin of the server. + +What needs berth on your own machine stays in the terminal UI. That is the USB installer and the container image, values read from your local keys, and sending a plugin's folder. ## What works from another machine | Works through the server | Stays on a machine with the host's profile | | --- | --- | -| `berth list`, and the host list of the home screen and of the page | USB installers: `berth iso` and writing a drive | +| `berth list`, and the host list of the home screen and of berth-remote | USB installers: `berth iso` and writing a drive | | The host's overview with its tasks, sessions and terminal panel | Applying to this machine or an inventory, and container images | | The host commands such as `berth run`, `exec`, `attach` and `channel` | Publishing a release or an image by hand | | The set-up tabs of a host, new hosts, and `berth remove` | | diff --git a/docs/content/docs/(guide)/use/terminal-ui.mdx b/docs/content/docs/(guide)/use/terminal-ui.mdx index d152323..77d9a28 100644 --- a/docs/content/docs/(guide)/use/terminal-ui.mdx +++ b/docs/content/docs/(guide)/use/terminal-ui.mdx @@ -19,7 +19,7 @@ The home screen has six tabs, switched with the number keys, or with Tab and Shi | --- | --- | | `1` Hosts | The saved hosts and their addresses. With a berth server, a dot shows whether each host answered the server, and the Information panel says why not. A host that still takes the old key of a [key rotation](/docs/use/accounts#rekeying) is marked `key rotation pending`. `n` creates one, `d` makes the selected one the default, `r` asks the server again, or reads the saved hosts again when there is no server | | `2` Provisioners | The provisioners of the plugins, and whether each can be used here. Enter opens the page of one, with how it is and what berth made with it, grouped by kind. Enter on one of its actions runs it. Enter on something it made opens that [resource's page](/docs/deploy/resources#in-the-terminal-ui), with its state, its actions and its log. Esc goes back a page ([Provisioners](/docs/deploy/provisioners#a-provisioners-page)). With a server set, the server's | -| `3` Settings | The settings of `berth config`, the SSH keys of berth's key ring to copy, and with a berth server a QR code that opens its page on a phone. With a server, the `tailnet_` settings are the server's | +| `3` Settings | The settings of `berth config` and the SSH keys of berth's key ring to copy. With a server, the `tailnet_` settings are the server's | | `4` Registries | npm, Docker, file and Nexus registries ([Registries](/docs/use/registries)) | | `5` Secrets | Secret values, kept in berth's store ([Secrets](/docs/use/secrets)) | | `6` Plugins | Built-in and installed plugins, and adding, updating and removing your own ([Plugins](/docs/extend/plugins#updating-a-plugin)). With a server set, the server's | diff --git a/docs/next.config.mjs b/docs/next.config.mjs index 0d031e6..b0d450b 100644 --- a/docs/next.config.mjs +++ b/docs/next.config.mjs @@ -17,10 +17,4 @@ const config = { env: { NEXT_PUBLIC_BASE_PATH: basePath ?? '' }, }; -// A file host gives public/web/index.html for /web/ by itself; the -// development server has to be told. -if (process.env.NODE_ENV === 'development') { - config.rewrites = async () => [{ source: '/web/', destination: '/web/index.html' }]; -} - export default withMDX(config); diff --git a/docs/scripts/gather.mjs b/docs/scripts/gather.mjs index 2150a27..1c902dc 100644 --- a/docs/scripts/gather.mjs +++ b/docs/scripts/gather.mjs @@ -1,5 +1,4 @@ // Generates the API reference before every build, from the committed operation // documents in docs/openapi. The guide, and the overview and portal pages of -// the API, are written by hand. Then puts the page of berth serve under /web. +// the API, are written by hand. await import('./reference.mjs'); -await import('./web.mjs'); diff --git a/docs/scripts/web.mjs b/docs/scripts/web.mjs deleted file mode 100644 index 39e755c..0000000 --- a/docs/scripts/web.mjs +++ /dev/null @@ -1,44 +0,0 @@ -// Puts the page of `berth serve` into public/web, so the site carries it at -// /web as plain files. The page is built with berth (cargo build -p berth -// --features web leaves it in target/web-dist); without it the site still builds, and /web -// says how to get it. -import { execFileSync } from 'node:child_process'; -import { createHash } from 'node:crypto'; -import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import { dirname, join } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..'); -const dist = join(root, 'target', 'web-dist'); -const out = join(root, 'docs', 'public', 'web'); -const files = ['berth-web.js', 'berth-web_bg.wasm']; -const built = () => files.every((file) => existsSync(join(dist, file))); - -if (!built() && process.env.BERTH_WEB_BUILD !== '0') { - try { - // The page of a release, though berth itself is a development build. - execFileSync('cargo', ['build', '--locked', '-p', 'berth', '--features', 'web'], { - cwd: root, - stdio: 'inherit', - env: { ...process.env, BERTH_WEB_PROFILE: 'web' }, - }); - } catch { - // No Rust here, or no wasm target: the site is built without the page. - } -} - -rmSync(out, { recursive: true, force: true }); -mkdirSync(out, { recursive: true }); -if (built()) { - for (const file of files) cpSync(join(dist, file), join(out, file)); - const build = createHash('sha256').update(readFileSync(join(dist, files[1]))).digest('hex').slice(0, 16); - const page = readFileSync(join(root, 'crates', 'berth-web', 'index.html'), 'utf8'); - // No server of its own: the page asks for one, or takes ?server= from its address. - writeFileSync(join(out, 'index.html'), page.replaceAll('@BUILD@', build).replaceAll('@SERVER@', '')); -} else { - console.warn('docs: the page for /web is not built (cargo build -p berth --features web); a note is put in its place'); - writeFileSync( - join(out, 'index.html'), - 'berthThis copy of the site was built without the page. berth serve --listen ADDRESS --web shows it.\n', - ); -} diff --git a/docs/src/lib/layout.shared.tsx b/docs/src/lib/layout.shared.tsx index 4114494..a2d6edb 100644 --- a/docs/src/lib/layout.shared.tsx +++ b/docs/src/lib/layout.shared.tsx @@ -15,8 +15,6 @@ export function baseOptions(): BaseLayoutProps { ), }, - // The page of berth serve, as plain files under public/web: not a route of the site. - links: [{ text: 'Web', url: asset('/web/'), external: true }], githubUrl: github, // Dark only. themeSwitch: { enabled: false }, diff --git a/recipes/README.md b/recipes/README.md index 6813f8b..f74d5ef 100644 --- a/recipes/README.md +++ b/recipes/README.md @@ -13,8 +13,8 @@ A recipe runs without berth. The playbooks use only the modules that come with `ansible-core`, and share the tasks in `shared/`. The recipes that set up a berth server end with a setup key. With it the -first user collects the server's token, with `berth connect URL` or in a -browser, so the token never has to be read out or passed on. +first user collects the server's token, with `berth connect URL` or with +`berth-remote`, so the token never has to be read out or passed on. ## Get the recipes diff --git a/recipes/berth-server/README.md b/recipes/berth-server/README.md index f866544..136dbd6 100644 --- a/recipes/berth-server/README.md +++ b/recipes/berth-server/README.md @@ -55,13 +55,15 @@ On your own machine, give berth the key when it asks: berth connect https://THIS-MACHINE.YOUR-TAILNET.ts.net ``` -Or open the server's page with the key in the link: +Or start [berth-remote](https://github.com/helightdev/berth/tree/main/crates/berth-remote) +with the key in `BERTH_SETUP_KEY`: -```text -https://THIS-MACHINE.YOUR-TAILNET.ts.net/#setup-key=KEY +```bash +read -rs BERTH_SETUP_KEY && export BERTH_SETUP_KEY +berth-remote --server https://THIS-MACHINE.YOUR-TAILNET.ts.net ``` -The page signs the browser in and shows the token. `tailscale serve status` on +berth-remote signs in and shows the token. `tailscale serve status` on the machine says the address. Make a new key on the machine at any time: ```bash diff --git a/recipes/incus-host/README.md b/recipes/incus-host/README.md index f93f579..944d8f9 100644 --- a/recipes/incus-host/README.md +++ b/recipes/incus-host/README.md @@ -120,9 +120,14 @@ or until they choose Done. On your own machine: berth connect https://THIS-MACHINE.YOUR-TAILNET.ts.net ``` -berth asks for the key. In a browser, open -`https://THIS-MACHINE.YOUR-TAILNET.ts.net/#setup-key=KEY` instead. Make a new -key with `sudo docker exec berth berth setup-key`. +berth asks for the key. berth-remote takes it in `BERTH_SETUP_KEY` instead: + +```bash +read -rs BERTH_SETUP_KEY && export BERTH_SETUP_KEY +berth-remote --server https://THIS-MACHINE.YOUR-TAILNET.ts.net +``` + +Make a new key with `sudo docker exec berth berth setup-key`. The token itself gives full control of every host. Without a key, read it with `sudo cat /srv/berth/data/berth/serve.token`, then set it with diff --git a/recipes/shared/berth-server.yml b/recipes/shared/berth-server.yml index 6c29de6..f9cdcdf 100644 --- a/recipes/shared/berth-server.yml +++ b/recipes/shared/berth-server.yml @@ -99,11 +99,11 @@ with_key: - "berth server: {{ berth_url }}{{ berth_here }}" - "Setup key for the first user, valid for 24 hours: {{ berth_key }}" - - "In a terminal: berth connect {{ berth_url }} and paste the setup key when asked" - - "In a browser: {{ berth_url }}/#setup-key={{ berth_key }}" + - "With berth: berth connect {{ berth_url }} and paste the setup key when asked" + - "With berth-remote: berth-remote --server {{ berth_url }}, with the setup key in BERTH_SETUP_KEY" - "The key ends when the user chooses Done. A new one: sudo docker exec berth berth setup-key" without_key: - "berth server: {{ berth_url }}{{ berth_here }}" - "A setup key for a user to collect the token: sudo docker exec berth berth setup-key" - - "With it: berth connect {{ berth_url }}, or open {{ berth_url }}/#setup-key=KEY in a browser" + - "With it: berth connect {{ berth_url }}, or berth-remote --server {{ berth_url }} with it in BERTH_SETUP_KEY" - "Or the token itself: sudo cat {{ berth_server_dir }}/data/berth/serve.token" From a07539639c429deb164287de5fc05b4e9c62559d Mon Sep 17 00:00:00 2001 From: Helight Date: Sat, 14 Nov 2026 23:40:26 +0100 Subject: [PATCH 04/94] feat(serve): read roles from the keys of an object claim --- crates/berth/src/serve/auth.rs | 20 ++++++++++++++++++-- docs/content/docs/(guide)/extend/serve.mdx | 8 ++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/crates/berth/src/serve/auth.rs b/crates/berth/src/serve/auth.rs index 0bc9800..4a47b1f 100644 --- a/crates/berth/src/serve/auth.rs +++ b/crates/berth/src/serve/auth.rs @@ -378,8 +378,9 @@ fn metadata_addresses(issuer: &str) -> Vec { } /// The highest role a claim names. The claim is a name, or a way into objects -/// with dots; its value a text of words or a list. In `scope` only `berth:ROLE` -/// counts, in a claim of its own the bare role does too. +/// with dots; its value a text of words, a list, or an object whose keys are +/// the words. In `scope` only `berth:ROLE` counts, in a claim of its own the +/// bare role does too. pub fn role(claims: &Value, claim: &str) -> Option { let value = match claims.get(claim) { Some(value) => value, @@ -392,6 +393,8 @@ pub fn role(claims: &Value, claim: &str) -> Option { .split(|ch: char| ch.is_whitespace() || ch == ',') .collect(), Value::Array(list) => list.iter().filter_map(Value::as_str).collect(), + // Zitadel writes a project's roles so: each role a key, its value where it holds. + Value::Object(roles) => roles.keys().map(String::as_str).collect(), _ => vec![], }; let bare = !matches!(claim, "scope" | "scp"); @@ -427,6 +430,19 @@ mod tests { ); assert_eq!(role(&claims, "groups"), None); assert_eq!(role(&json!({"scope": "openid"}), "scope"), None); + // An object's keys are the words, as Zitadel writes a project's roles. + let zitadel = json!({ + "urn:zitadel:iam:org:project:roles": { + "view": {"317401": "studio.example"}, + "berth:operate": {"317401": "studio.example"}, + "billing": {}, + }, + }); + assert_eq!( + role(&zitadel, "urn:zitadel:iam:org:project:roles"), + Some(Role::Operate) + ); + assert_eq!(role(&json!({"roles": {}}), "roles"), None); } #[test] diff --git a/docs/content/docs/(guide)/extend/serve.mdx b/docs/content/docs/(guide)/extend/serve.mdx index 6a238ba..aa4d292 100644 --- a/docs/content/docs/(guide)/extend/serve.mdx +++ b/docs/content/docs/(guide)/extend/serve.mdx @@ -153,6 +153,14 @@ berth config oauth_audience berth A token is a JWT signed with one of the issuer's keys (RSA, ECDSA or Ed25519). It needs `iss` and `exp`, and the role in the claim: `berth:view`, `berth:operate` or `berth:admin`. In a claim other than `scope` the bare `view`, `operate` and `admin` count too. The highest role named is the caller's. +The roles can be written in the claim three ways: + +| Claim's value | Example | Roles read | +| --- | --- | --- | +| Text | `"openid berth:operate"` | The words, split at spaces and commas | +| List | `["berth:view", "admin"]` | Each entry | +| Object | `{"admin": {…}, "billing": {…}}` | Each key. Zitadel writes project roles this way, in `urn:zitadel:iam:org:project:roles` | + ```bash curl -H "Authorization: Bearer $ACCESS_TOKEN" https://berth.example.ts.net/v1/access # {"role":"operate","setup":true,"subject":"ada"} From a721b9b10c234f225736965bf941b77914d143fa Mon Sep 17 00:00:00 2001 From: Helight Date: Sat, 14 Nov 2026 23:42:05 +0100 Subject: [PATCH 05/94] feat(serve): tell a follower how many events it missed --- crates/berth-api/src/streams.rs | 27 ++++++-- crates/berth/src/serve/api.rs | 21 +++--- crates/berth/src/serve/tests.rs | 62 ++++++++++++++++++ docs/content/docs/(guide)/extend/streams.mdx | 5 ++ docs/openapi/berth.asyncapi.json | 69 ++++++++++++++++++++ docs/openapi/berth.operations.json | 30 +++++++++ 6 files changed, 200 insertions(+), 14 deletions(-) diff --git a/crates/berth-api/src/streams.rs b/crates/berth-api/src/streams.rs index 91a3131..8045408 100644 --- a/crates/berth-api/src/streams.rs +++ b/crates/berth-api/src/streams.rs @@ -212,11 +212,18 @@ pub const SERVE: &[Stream] = &[ ("topic", "Only topics starting with this."), ], resumable: false, - server: &[text( - "message", - "A stored message with its host.", - r#"{"host":"server","id":4812,"topic":"myplugin/progress","body":{},"keep":"log","from":{"level":"agent","uid":1001},"time":"2026-11-12T10:00:00Z","done":false}"#, - )], + server: &[ + text( + "message", + "A stored message with its host.", + r#"{"host":"server","id":4812,"topic":"myplugin/progress","body":{},"keep":"log","from":{"level":"agent","uid":1001},"time":"2026-11-12T10:00:00Z","done":false}"#, + ), + text( + "dropped", + "This follower was too slow and missed so many events; read the inbox again.", + r#"{"dropped":{"events":12}}"#, + ), + ], client: &[], }, Stream { @@ -237,6 +244,11 @@ pub const SERVE: &[Stream] = &[ "A key was removed.", r#"{"key":"layout","removed":true}"#, ), + text( + "dropped", + "This follower was too slow and missed so many changes; list the namespace again.", + r#"{"dropped":{"events":12}}"#, + ), ], client: &[], }, @@ -263,6 +275,11 @@ pub const SERVE: &[Stream] = &[ "A key changed.", r#"{"source":"kv","namespace":"ui","key":"layout","value":{},"revision":4}"#, ), + text( + "dropped", + "This follower was too slow and missed so many events, of any kind it follows; read what it shows again.", + r#"{"dropped":{"events":12}}"#, + ), ], client: &[text( "follow", diff --git a/crates/berth/src/serve/api.rs b/crates/berth/src/serve/api.rs index 1695864..9e317eb 100644 --- a/crates/berth/src/serve/api.rs +++ b/crates/berth/src/serve/api.rs @@ -800,16 +800,19 @@ async fn forward( ) { loop { tokio::select! { - event = events.recv() => match event { - Ok(event) => { - if let Some(frame) = pick(event) - && socket.send(WsMessage::Text(frame.to_string().into())).await.is_err() - { - return; - } + event = events.recv() => { + let frame = match event { + Ok(event) => pick(event), + // A reader that fell behind is told how much it missed, + // so it can read the current state again. + Err(RecvError::Lagged(missed)) => Some(json!({"dropped": {"events": missed}})), + Err(RecvError::Closed) => return, + }; + if let Some(frame) = frame + && socket.send(WsMessage::Text(frame.to_string().into())).await.is_err() + { + return; } - Err(RecvError::Lagged(_)) => {} - Err(RecvError::Closed) => return, }, frame = socket.recv() => if !matches!(frame, Some(Ok(_))) { return }, } diff --git a/crates/berth/src/serve/tests.rs b/crates/berth/src/serve/tests.rs index 29d76c1..d684052 100644 --- a/crates/berth/src/serve/tests.rs +++ b/crates/berth/src/serve/tests.rs @@ -227,6 +227,68 @@ async fn the_key_value_store_over_the_api() { assert_eq!(refused.status, 413); } +fn kv_event(key: &str, value: Value) -> super::Event { + super::Event::Kv { + namespace: "ui".into(), + key: key.into(), + value: Some(value), + revision: 1, + } +} + +/// Wait for a frame that says events were dropped, past the ones before it. +async fn dropped(stream: &mut S) -> u64 +where + S: StreamExt> + Unpin, + E: std::fmt::Debug, +{ + loop { + let frame = text(stream).await; + if let Some(missed) = frame["dropped"]["events"].as_u64() { + return missed; + } + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_follower_that_falls_behind_is_told_what_it_missed() { + let served = served().await; + // The events stream listens from the handshake on, before it is told + // what to follow, so all of these are waiting when it starts. + let mut events = client::websocket_unix(&served.socket, "/v1/events") + .await + .unwrap(); + for n in 0..1100 { + let _ = served.state.events.send(kv_event("layout", json!(n))); + } + let follow = json!({"kv": ["ui"]}).to_string(); + events.send(Frame::Text(follow.into())).await.unwrap(); + assert_eq!( + text(&mut events).await, + json!({"dropped": {"events": 76}}) + ); + assert_eq!(text(&mut events).await["value"], 76); + + // A follower of a namespace that reads nothing while the server's buffers + // fill misses the rest, and goes on after the notice. + let mut changes = client::websocket_unix(&served.socket, "/v1/kv/ui") + .await + .unwrap(); + tokio::time::sleep(Duration::from_millis(100)).await; + let large = "x".repeat(4096); + for _ in 0..5000 { + let _ = served.state.events.send(kv_event("layout", json!(large))); + } + let _ = served.state.events.send(kv_event("last", json!(true))); + assert!(dropped(&mut changes).await > 0); + loop { + let frame = text(&mut changes).await; + if frame["key"] == "last" { + break; + } + } +} + fn message(id: u64, topic: &str, keep: &str) -> berth_api::Message { serde_json::from_value(json!({ "id": id, "topic": topic, "body": {"n": id}, "keep": keep, diff --git a/docs/content/docs/(guide)/extend/streams.mdx b/docs/content/docs/(guide)/extend/streams.mdx index 13f0178..2138e79 100644 --- a/docs/content/docs/(guide)/extend/streams.mdx +++ b/docs/content/docs/(guide)/extend/streams.mdx @@ -104,6 +104,11 @@ A client that cannot keep up does not slow the others down: `GET /v1/sessions/{id}/output?since=OFFSET`, or reconnect with `since=`. - On the channel, a listener that falls 1,000 messages behind is closed. Open it again with `since` set to the last id it saw. +- On `events.follow`, `inbox.follow` and `kv.follow` of `berth serve`, a + follower that is too slow gets `{"dropped":{"events":12}}` and the stream + goes on. The number counts all the server's events it missed, also those it + does not follow. Read the current state again with `inbox.list`, `kv.list` or + `jobs.list`. ## Events on your machine diff --git a/docs/openapi/berth.asyncapi.json b/docs/openapi/berth.asyncapi.json index 43af0d7..93f5e72 100644 --- a/docs/openapi/berth.asyncapi.json +++ b/docs/openapi/berth.asyncapi.json @@ -16,6 +16,9 @@ "events.channel": { "$ref": "#/components/messages/events.channel" }, + "events.dropped": { + "$ref": "#/components/messages/events.dropped" + }, "events.follow": { "$ref": "#/components/messages/events.follow" }, @@ -203,6 +206,9 @@ }, "description": "Messages as they are taken in from the hosts.", "messages": { + "inbox.dropped": { + "$ref": "#/components/messages/inbox.dropped" + }, "inbox.message": { "$ref": "#/components/messages/inbox.message" } @@ -255,6 +261,9 @@ }, "description": "Changes to a namespace of the key-value store.", "messages": { + "kv.dropped": { + "$ref": "#/components/messages/kv.dropped" + }, "kv.removed": { "$ref": "#/components/messages/kv.removed" }, @@ -332,6 +341,23 @@ }, "summary": "A message from a host's channel." }, + "events.dropped": { + "contentType": "application/json", + "examples": [ + { + "payload": { + "dropped": { + "events": 12 + } + } + } + ], + "name": "dropped", + "payload": { + "type": "object" + }, + "summary": "This follower was too slow and missed so many events, of any kind it follows; read what it shows again." + }, "events.follow": { "contentType": "application/json", "examples": [ @@ -618,6 +644,23 @@ }, "summary": "INT, TERM, HUP or KILL to the session's process group." }, + "inbox.dropped": { + "contentType": "application/json", + "examples": [ + { + "payload": { + "dropped": { + "events": 12 + } + } + } + ], + "name": "dropped", + "payload": { + "type": "object" + }, + "summary": "This follower was too slow and missed so many events; read the inbox again." + }, "inbox.message": { "contentType": "application/json", "examples": [ @@ -669,6 +712,23 @@ }, "summary": "The job's output." }, + "kv.dropped": { + "contentType": "application/json", + "examples": [ + { + "payload": { + "dropped": { + "events": 12 + } + } + } + ], + "name": "dropped", + "payload": { + "type": "object" + }, + "summary": "This follower was too slow and missed so many changes; list the namespace again." + }, "kv.removed": { "contentType": "application/json", "examples": [ @@ -764,6 +824,9 @@ }, { "$ref": "#/channels/events/messages/events.kv" + }, + { + "$ref": "#/channels/events/messages/events.dropped" } ] }, @@ -870,6 +933,9 @@ "messages": [ { "$ref": "#/channels/inbox/messages/inbox.message" + }, + { + "$ref": "#/channels/inbox/messages/inbox.dropped" } ] }, @@ -898,6 +964,9 @@ }, { "$ref": "#/channels/kv/messages/kv.removed" + }, + { + "$ref": "#/channels/kv/messages/kv.dropped" } ] }, diff --git a/docs/openapi/berth.operations.json b/docs/openapi/berth.operations.json index d7ed772..417ff4d 100644 --- a/docs/openapi/berth.operations.json +++ b/docs/openapi/berth.operations.json @@ -4043,6 +4043,16 @@ "topic": "myplugin/progress" }, "name": "message" + }, + { + "binary": false, + "description": "This follower was too slow and missed so many events; read the inbox again.", + "example": { + "dropped": { + "events": 12 + } + }, + "name": "dropped" } ], "resumable": false, @@ -4187,6 +4197,16 @@ "removed": true }, "name": "removed" + }, + { + "binary": false, + "description": "This follower was too slow and missed so many changes; list the namespace again.", + "example": { + "dropped": { + "events": 12 + } + }, + "name": "dropped" } ], "resumable": false, @@ -4395,6 +4415,16 @@ "value": {} }, "name": "kv" + }, + { + "binary": false, + "description": "This follower was too slow and missed so many events, of any kind it follows; read what it shows again.", + "example": { + "dropped": { + "events": 12 + } + }, + "name": "dropped" } ], "resumable": false, From c67c0a758e74d68d3325cb91b6b472762b01709b Mon Sep 17 00:00:00 2001 From: Helight Date: Sat, 14 Nov 2026 23:46:07 +0100 Subject: [PATCH 06/94] feat(serve): tell changes to hosts and resources on events.follow --- crates/berth-api/src/streams.rs | 20 ++- crates/berth/src/serve/api.rs | 19 +++ crates/berth/src/serve/mod.rs | 154 ++++++++++++++++++- crates/berth/src/serve/setup.rs | 1 + crates/berth/src/serve/tests.rs | 136 +++++++++++++++- docs/content/docs/(guide)/extend/serve.mdx | 2 +- docs/content/docs/(guide)/extend/streams.mdx | 36 ++++- docs/openapi/berth.asyncapi.json | 61 +++++++- docs/openapi/berth.openapi.json | 2 +- docs/openapi/berth.operations.json | 35 ++++- docs/scripts/reference.mjs | 2 +- 11 files changed, 439 insertions(+), 29 deletions(-) diff --git a/crates/berth-api/src/streams.rs b/crates/berth-api/src/streams.rs index 8045408..bb087fe 100644 --- a/crates/berth-api/src/streams.rs +++ b/crates/berth-api/src/streams.rs @@ -220,7 +220,7 @@ pub const SERVE: &[Stream] = &[ ), text( "dropped", - "This follower was too slow and missed so many events; read the inbox again.", + "This follower was too slow. `events` counts the server's events it missed, of every kind. Read the inbox again.", r#"{"dropped":{"events":12}}"#, ), ], @@ -246,7 +246,7 @@ pub const SERVE: &[Stream] = &[ ), text( "dropped", - "This follower was too slow and missed so many changes; list the namespace again.", + "This follower was too slow. `events` counts the server's events it missed, of every kind. List the namespace again.", r#"{"dropped":{"events":12}}"#, ), ], @@ -255,7 +255,7 @@ pub const SERVE: &[Stream] = &[ Stream { id: "events", path: "/v1/events", - summary: "Channel messages of chosen hosts, jobs and key-value changes together. The first frame sent names what to follow; each frame received says where it came from.", + summary: "Channel messages of chosen hosts, jobs, key-value changes and changes to hosts and resources together. The first frame sent names what to follow; each frame received says where it came from.", level: "host", parameters: &[], resumable: false, @@ -275,16 +275,26 @@ pub const SERVE: &[Stream] = &[ "A key changed.", r#"{"source":"kv","namespace":"ui","key":"layout","value":{},"revision":4}"#, ), + text( + "host", + "A saved host was `added`, `removed`, `renamed` (with the name it had `from`) or its profile `changed`. Read the host itself with hosts.get.", + r#"{"source":"host","host":"studio","change":"renamed","from":"desk"}"#, + ), + text( + "resource", + "A resource was `created`, `removed` or its record `changed`. Read it with resources.get.", + r#"{"source":"resource","resource":"r-k3v9qz2m","provisioner":"docker","kind":"deployment","change":"created"}"#, + ), text( "dropped", - "This follower was too slow and missed so many events, of any kind it follows; read what it shows again.", + "This follower was too slow. `events` counts the server's events it missed, of every kind. Read what it follows again.", r#"{"dropped":{"events":12}}"#, ), ], client: &[text( "follow", "What to follow. Sent once, first.", - r#"{"hosts":["server"],"topics":["myplugin/"],"jobs":true,"kv":["ui"]}"#, + r#"{"hosts":["server"],"topics":["myplugin/"],"jobs":true,"kv":["ui"],"changes":["hosts","resources"]}"#, )], }, ]; diff --git a/crates/berth/src/serve/api.rs b/crates/berth/src/serve/api.rs index 9e317eb..d1b11e0 100644 --- a/crates/berth/src/serve/api.rs +++ b/crates/berth/src/serve/api.rs @@ -988,6 +988,15 @@ struct Follow { jobs: bool, /// Changes in these namespaces of the key-value store. kv: Vec, + /// The kinds of thing whose changes to tell. + changes: Vec, +} + +#[derive(Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +enum Changes { + Hosts, + Resources, } async fn events(State(state): App, ws: WebSocketUpgrade) -> Response { @@ -1019,6 +1028,16 @@ async fn events(State(state): App, ws: WebSocketUpgrade) -> Response { Some(value) => json!({"source": "kv", "namespace": namespace, "key": key, "value": value, "revision": revision}), None => json!({"source": "kv", "namespace": namespace, "key": key, "removed": true}), }), + Event::Host { name, change, from } if follow.changes.contains(&Changes::Hosts) => { + let mut frame = json!({"source": "host", "host": name, "change": change}); + if let Some(from) = from { + frame["from"] = json!(from); + } + Some(frame) + } + Event::Resource { id, provisioner, kind, change } if follow.changes.contains(&Changes::Resources) => { + Some(json!({"source": "resource", "resource": id, "provisioner": provisioner, "kind": kind, "change": change})) + } _ => None, }) .await; diff --git a/crates/berth/src/serve/mod.rs b/crates/berth/src/serve/mod.rs index 4af0773..426a505 100644 --- a/crates/berth/src/serve/mod.rs +++ b/crates/berth/src/serve/mod.rs @@ -55,6 +55,130 @@ pub enum Event { value: Option, revision: i64, }, + /// A saved host was added, removed or renamed, or its profile changed. + Host { + name: String, + change: &'static str, + /// Its name before, when it was renamed. + from: Option, + }, + /// A resource was created, removed, or its record changed. + Resource { + id: String, + provisioner: String, + kind: String, + change: &'static str, + }, +} + +/// What the store held of the hosts and resources when last looked at, so a +/// change to it can be told as an event whoever made it. +struct Watch { + paths: Paths, + events: broadcast::Sender, + seen: Mutex, +} + +/// Unknown until the store could first be read, which tells nothing. +#[derive(Default)] +struct Seen { + hosts: Option>, + resources: Option>, +} + +/// How each key of `now` differs from `before`: added, removed or changed. +fn differences<'a, T: PartialEq>( + before: &'a BTreeMap, + now: &'a BTreeMap, +) -> Vec<(&'a str, &'static str)> { + let gone = before + .keys() + .filter(|name| !now.contains_key(*name)) + .map(|name| (name.as_str(), "removed")); + let came = now + .iter() + .filter_map(|(name, value)| match before.get(name) { + None => Some((name.as_str(), "added")), + Some(was) if was != value => Some((name.as_str(), "changed")), + Some(_) => None, + }); + gone.chain(came).collect() +} + +impl Watch { + fn hosts(&self) -> Option> { + berth_core::profiles::list(&self.paths, store::OWN) + .ok() + .map(|saved| saved.into_iter().collect()) + } + + fn resources(&self) -> Option> { + let kept = berth_core::resource::list(&self.paths).ok()?; + Some( + kept.into_iter() + .map(|kept| { + // When it was last looked at is no change of it. + let record = berth_core::resource::Record { + checked: String::new(), + ..kept.record + }; + (record.id.clone(), record) + }) + .collect(), + ) + } + + /// Tell what changed in the store since it was last looked at. + fn notice(&self) { + let (hosts, resources) = (self.hosts(), self.resources()); + // Held while telling, so two callers cannot tell a change twice or out of order. + let mut seen = self.seen.lock().unwrap(); + if let Some(now) = hosts { + if let Some(before) = &seen.hosts { + for (name, change) in differences(before, &now) { + let _ = self.events.send(Event::Host { + name: name.to_owned(), + change, + from: None, + }); + } + } + seen.hosts = Some(now); + } + if let Some(now) = resources { + if let Some(before) = &seen.resources { + for (id, change) in differences(before, &now) { + let record = now.get(id).or_else(|| before.get(id)); + let change = match change { + "added" => "created", + other => other, + }; + let _ = self.events.send(Event::Resource { + id: id.to_owned(), + provisioner: record.map(|r| r.provisioner.clone()).unwrap_or_default(), + kind: record.map(|r| r.kind.clone()).unwrap_or_default(), + change, + }); + } + } + seen.resources = Some(now); + } + } + + /// Tell a rename as one, and not as a host removed and another added. + fn renamed(&self, old: &str, new: &str) { + let mut seen = self.seen.lock().unwrap(); + if let Some(hosts) = seen.hosts.as_mut() + && let Some(profile) = hosts.remove(old) + { + hosts.insert(new.to_owned(), profile); + } + let _ = self.events.send(Event::Host { + name: new.to_owned(), + change: "renamed", + from: Some(old.to_owned()), + }); + } } /// A host as `berth serve` knows it. @@ -131,6 +255,7 @@ pub struct Serve { /// How long provisioners may take and how a new machine is waited for, /// which tests make quick. pub provision: fn() -> berth_core::provision::Options, + watch: Arc, } impl Serve { @@ -143,9 +268,17 @@ impl Serve { pub fn with(paths: Paths, store: Arc, auth: auth::Auth) -> Arc { let jobs_dir = berth_core::runner::jobs_dir(&paths); let events = broadcast::channel(1024).0; - let told = events.clone(); + let watch = Arc::new(Watch { + paths: paths.clone(), + events: events.clone(), + seen: Mutex::new(Seen::default()), + }); + watch.notice(); + let (told, watching) = (events.clone(), watch.clone()); let notify = Arc::new(move |job: &store::Job| { let _ = told.send(Event::Job(job.json())); + // A job is what changes hosts and resources, besides the routes. + watching.notice(); }); let runner = berth_core::runner::Runner::new(paths.clone(), store.clone(), jobs_dir.clone(), notify); @@ -160,9 +293,16 @@ impl Serve { followers: Mutex::new(BTreeMap::new()), passwords: Mutex::new(BTreeMap::new()), provision: Default::default, + watch, }) } + /// Tell whoever follows changes what changed among the saved hosts and + /// the resources since this was last asked. + pub fn notice(&self) { + self.watch.notice(); + } + pub fn host(&self, name: &str) -> Option> { self.hosts.read().unwrap().get(name).cloned() } @@ -202,6 +342,7 @@ impl Serve { /// [`Serve::refresh`] takes it up under that name. pub fn renamed(&self, old: &str, new: &str) { self.forget(old); + self.watch.renamed(old, new); let mut passwords = self.passwords.lock().unwrap(); if let Some(password) = passwords.remove(old) { passwords.insert(new.to_owned(), password); @@ -217,6 +358,7 @@ impl Serve { let Ok(saved) = berth_core::profiles::list(&self.paths, store::OWN) else { return; }; + self.notice(); let stale: Vec = { let hosts = self.hosts.read().unwrap(); hosts @@ -483,6 +625,16 @@ pub fn command(paths: &Paths, args: &[&str]) -> Result<()> { daily.prune(); } }); + // Another berth beside the server changes the store too. + let watching = state.clone(); + tokio::spawn(async move { + loop { + tokio::time::sleep(Duration::from_secs(5)).await; + if watching.events.receiver_count() > 0 { + watching.notice(); + } + } + }); let socket = runtime_dir().join("serve.sock"); let _ = std::fs::remove_file(&socket); diff --git a/crates/berth/src/serve/setup.rs b/crates/berth/src/serve/setup.rs index 24e3305..070405e 100644 --- a/crates/berth/src/serve/setup.rs +++ b/crates/berth/src/serve/setup.rs @@ -159,6 +159,7 @@ pub async fn remove_host(State(state): App, Path(name): Path) -> Answer< } profiles::remove(&state.paths, &place).map_err(internal)?; state.forget(&name); + state.notice(); Ok(Json(Done { ok: true })) } diff --git a/crates/berth/src/serve/tests.rs b/crates/berth/src/serve/tests.rs index d684052..5d550b9 100644 --- a/crates/berth/src/serve/tests.rs +++ b/crates/berth/src/serve/tests.rs @@ -263,10 +263,7 @@ async fn a_follower_that_falls_behind_is_told_what_it_missed() { } let follow = json!({"kv": ["ui"]}).to_string(); events.send(Frame::Text(follow.into())).await.unwrap(); - assert_eq!( - text(&mut events).await, - json!({"dropped": {"events": 76}}) - ); + assert_eq!(text(&mut events).await, json!({"dropped": {"events": 76}})); assert_eq!(text(&mut events).await["value"], 76); // A follower of a namespace that reads nothing while the server's buffers @@ -3125,6 +3122,137 @@ async fn a_host_is_renamed_as_a_job_with_what_the_server_keeps_of_it() { assert_eq!(inbox["messages"][0]["topic"], "agent/done", "{inbox}"); } +/// The frames of an events stream up to the first of `source` with `change`, which is returned. +async fn change_of(stream: &mut S, source: &str, change: &str) -> Value +where + S: StreamExt> + Unpin, + E: std::fmt::Debug, +{ + let mut seen = vec![]; + loop { + let frame = tokio::time::timeout(Duration::from_secs(20), text(stream)) + .await + .unwrap_or_else(|_| panic!("no {source} {change} after {seen:?}")); + if frame["source"] == source && frame["change"] == change { + return frame; + } + seen.push(frame); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn hosts_and_resources_that_change_are_told_on_the_events_stream() { + let served = served_with(quick).await; + let fake = fake_provisioner(&served); + let mut client = served.client().await; + let client = &mut client; + register_fake(client).await; + let paths = &served.state.paths; + paths.prepare().unwrap(); + let mut events = client::websocket_unix(&served.socket, "/v1/events") + .await + .unwrap(); + let follow = json!({"changes": ["hosts", "resources"]}).to_string(); + events.send(Frame::Text(follow.into())).await.unwrap(); + + // Saved by another berth beside the server: told when the server looks. + let profile = json!({"hostname": "studio", "builder": {}, "access": {"address": "192.0.2.7", "link": ["sh", "-c", "exit 1"]}}); + berth_core::profiles::Place::own("studio") + .unwrap() + .save(paths, &profile) + .unwrap(); + served.state.notice(); + assert_eq!( + change_of(&mut events, "host", "added").await, + json!({"source": "host", "host": "studio", "change": "added"}) + ); + let mut moved = profile.clone(); + moved["access"]["address"] = json!("192.0.2.8"); + let (status, said) = send(client, "PUT", "/v1/hosts/studio/profile", moved).await; + assert_eq!(status, 200, "{said}"); + assert_eq!( + change_of(&mut events, "host", "changed").await["host"], + "studio" + ); + let rename = json!({"arguments": {"name": "dock", "hostname": "no"}}); + let (status, acted) = send(client, "POST", "/v1/hosts/studio/actions/rename", rename).await; + assert_eq!(status, 202, "{acted}"); + assert_eq!( + change_of(&mut events, "host", "renamed").await, + json!({"source": "host", "host": "dock", "change": "renamed", "from": "studio"}) + ); + job_done(client, acted["job"]["id"].as_str().unwrap()).await; + let (status, said) = send(client, "DELETE", "/v1/hosts/dock", Value::Null).await; + assert_eq!(status, 200, "{said}"); + assert_eq!( + change_of(&mut events, "host", "removed").await["host"], + "dock" + ); + + send( + client, + "PUT", + "/v1/secrets/api_token", + json!({"value": "tok-made-up"}), + ) + .await; + std::fs::write( + fake.join("answer.create"), + r#"{"id": "wiki", "state": "running"}"#, + ) + .unwrap(); + let asked = json!({"provisioner": "vm", "kind": "deployment", "name": "wiki", + "arguments": {"server": "x"}, "spec": "services:\n wiki:\n image: wiki\n", + "token": "t-1"}); + let (status, created) = send(client, "POST", "/v1/resources", asked).await; + assert_eq!(status, 202, "{created}"); + let id = created["resource"]["id"].as_str().unwrap().to_owned(); + assert_eq!( + change_of(&mut events, "resource", "created").await, + json!({"source": "resource", "resource": id, "provisioner": "vm", "kind": "deployment", "change": "created"}) + ); + let (_, code) = job_ended(&served.socket, created["job"]["id"].as_str().unwrap()).await; + assert_eq!(code, 0); + // Made, it has the provisioner's id now. + assert_eq!( + change_of(&mut events, "resource", "changed").await["resource"], + json!(id) + ); + let (status, removed) = send( + client, + "DELETE", + &format!("/v1/resources/{id}"), + Value::Null, + ) + .await; + assert_eq!(status, 202, "{removed}"); + assert_eq!( + change_of(&mut events, "resource", "removed").await["resource"], + json!(id) + ); + + // Not asked for, nothing of the kind is told. + let mut quiet = client::websocket_unix(&served.socket, "/v1/events") + .await + .unwrap(); + let follow = json!({"kv": ["ui"]}).to_string(); + quiet.send(Frame::Text(follow.into())).await.unwrap(); + berth_core::profiles::Place::own("pier") + .unwrap() + .save(paths, &profile) + .unwrap(); + served.state.notice(); + put(&served.socket, &[], "1").await; + assert_eq!(text(&mut quiet).await["source"], "kv"); + // A kind it does not know is refused. + let mut wrong = client::websocket_unix(&served.socket, "/v1/events") + .await + .unwrap(); + let follow = json!({"changes": ["plugins"]}).to_string(); + wrong.send(Frame::Text(follow.into())).await.unwrap(); + assert_eq!(text(&mut wrong).await["error"]["code"], "bad_request"); +} + // Not on a runtime of the test's: the screen waits for the server on one of its own. #[test] fn generated_passwords_are_kept_where_the_host_is_and_shown_to_an_admin() { diff --git a/docs/content/docs/(guide)/extend/serve.mdx b/docs/content/docs/(guide)/extend/serve.mdx index aa4d292..1d0ed12 100644 --- a/docs/content/docs/(guide)/extend/serve.mdx +++ b/docs/content/docs/(guide)/extend/serve.mdx @@ -26,7 +26,7 @@ It prints where it listens and how many hosts it knows. Only one runs per user. | [`jobs.*`](/docs/api/serve/jobs) | Jobs, one for each run of an action that runs here or follows a task, with their output. Each says its subject and its action. A roll-out's job has a report, host by host | | [`inbox.*`](/docs/api/serve/inbox) | Messages the hosts published on their channels and kept, taken in while `berth serve` runs; each can be marked done | | [`kv.*`](/docs/api/serve/kv) | A key-value store with revisions, for user interfaces to keep state in | -| [`events.follow`](/docs/api/serve/events) | One stream of channel messages, jobs and key-value changes, at `/v1/events` | +| [`events.follow`](/docs/api/serve/events) | One stream of channel messages, jobs, key-value changes and changes to hosts and resources, at `/v1/events` | All of it is also on the [portal](/docs/api/portal), the one WebSocket at `/v1/portal` for calls and streams together. diff --git a/docs/content/docs/(guide)/extend/streams.mdx b/docs/content/docs/(guide)/extend/streams.mdx index 2138e79..d835e88 100644 --- a/docs/content/docs/(guide)/extend/streams.mdx +++ b/docs/content/docs/(guide)/extend/streams.mdx @@ -121,19 +121,39 @@ GET /v1/events The first frame the client sends says what to follow. It is sent once, first: ```json -{ "hosts": ["studio"], "jobs": true, "kv": ["ui"], "topics": ["myplugin/"] } +{ "hosts": ["studio"], "jobs": true, "kv": ["ui"], "topics": ["myplugin/"], "changes": ["hosts", "resources"] } ``` -`hosts` and `topics` select channel messages by host and by topic prefix. `jobs` -turns on job starts and ends. `kv` lists the key-value namespaces to watch. +| Field | Follows | +| --- | --- | +| `hosts`, `topics` | Channel messages, by host and by topic prefix. All hosts when `hosts` is empty | +| `jobs` | Job starts and ends | +| `kv` | Changes in these key-value namespaces | +| `changes` | Changes to the saved `hosts` and to `resources` | -Each frame the server sends names where it came from in `source`, which is -`channel`, `job` or `kv`: +Each frame the server sends names where it came from in `source`: ```json { "source": "kv", "namespace": "ui", "key": "layout", "revision": 4, "value": {} } ``` -A channel frame also has the `host` and the `message`, and a job frame has the -`job`. Events are not resumable. After a reconnect, read what was missed with -`inbox.list` and `kv.list`, then follow again. `inbox.follow` and `kv.follow` follow one of them alone. +| `source` | The frame also has | +| --- | --- | +| `channel` | The `host` and the `message` | +| `job` | The `job` | +| `kv` | The `namespace`, the `key`, and the `value` and `revision`, or `removed` | +| `host` | The `host` and the `change`: `added`, `removed`, `renamed` or `changed`. A rename has the old name in `from` | +| `resource` | The `resource` id, its `provisioner` and `kind`, and the `change`: `created`, `removed` or `changed` | + +A host or resource frame only names what changed. Read the rest with `hosts.get` +or `resources.get`. A host changes when its profile is saved, as by +`hosts.save` or an action, and a resource when its record does, as when a job +creates it or its state is checked. A change that another berth makes in the +store is told within a few seconds. + +```json +{ "source": "host", "host": "dock", "change": "renamed", "from": "studio" } +``` + +Events are not resumable. After a reconnect, read what was missed with +`inbox.list`, `kv.list`, `hosts.list` and `resources.list`, then follow again. `inbox.follow` and `kv.follow` follow one of them alone. diff --git a/docs/openapi/berth.asyncapi.json b/docs/openapi/berth.asyncapi.json index 93f5e72..c30793d 100644 --- a/docs/openapi/berth.asyncapi.json +++ b/docs/openapi/berth.asyncapi.json @@ -11,7 +11,7 @@ } } }, - "description": "Channel messages of chosen hosts, jobs and key-value changes together. The first frame sent names what to follow; each frame received says where it came from.", + "description": "Channel messages of chosen hosts, jobs, key-value changes and changes to hosts and resources together. The first frame sent names what to follow; each frame received says where it came from.", "messages": { "events.channel": { "$ref": "#/components/messages/events.channel" @@ -22,11 +22,17 @@ "events.follow": { "$ref": "#/components/messages/events.follow" }, + "events.host": { + "$ref": "#/components/messages/events.host" + }, "events.job": { "$ref": "#/components/messages/events.job" }, "events.kv": { "$ref": "#/components/messages/events.kv" + }, + "events.resource": { + "$ref": "#/components/messages/events.resource" } }, "parameters": {}, @@ -356,13 +362,17 @@ "payload": { "type": "object" }, - "summary": "This follower was too slow and missed so many events, of any kind it follows; read what it shows again." + "summary": "This follower was too slow. `events` counts the server's events it missed, of every kind. Read what it follows again." }, "events.follow": { "contentType": "application/json", "examples": [ { "payload": { + "changes": [ + "hosts", + "resources" + ], "hosts": [ "server" ], @@ -382,6 +392,24 @@ }, "summary": "What to follow. Sent once, first." }, + "events.host": { + "contentType": "application/json", + "examples": [ + { + "payload": { + "change": "renamed", + "from": "desk", + "host": "studio", + "source": "host" + } + } + ], + "name": "host", + "payload": { + "type": "object" + }, + "summary": "A saved host was `added`, `removed`, `renamed` (with the name it had `from`) or its profile `changed`. Read the host itself with hosts.get." + }, "events.job": { "contentType": "application/json", "examples": [ @@ -423,6 +451,25 @@ }, "summary": "A key changed." }, + "events.resource": { + "contentType": "application/json", + "examples": [ + { + "payload": { + "change": "created", + "kind": "deployment", + "provisioner": "docker", + "resource": "r-k3v9qz2m", + "source": "resource" + } + } + ], + "name": "resource", + "payload": { + "type": "object" + }, + "summary": "A resource was `created`, `removed` or its record `changed`. Read it with resources.get." + }, "host.channel.message": { "contentType": "application/json", "examples": [ @@ -659,7 +706,7 @@ "payload": { "type": "object" }, - "summary": "This follower was too slow and missed so many events; read the inbox again." + "summary": "This follower was too slow. `events` counts the server's events it missed, of every kind. Read the inbox again." }, "inbox.message": { "contentType": "application/json", @@ -727,7 +774,7 @@ "payload": { "type": "object" }, - "summary": "This follower was too slow and missed so many changes; list the namespace again." + "summary": "This follower was too slow. `events` counts the server's events it missed, of every kind. List the namespace again." }, "kv.removed": { "contentType": "application/json", @@ -825,6 +872,12 @@ { "$ref": "#/channels/events/messages/events.kv" }, + { + "$ref": "#/channels/events/messages/events.host" + }, + { + "$ref": "#/channels/events/messages/events.resource" + }, { "$ref": "#/channels/events/messages/events.dropped" } diff --git a/docs/openapi/berth.openapi.json b/docs/openapi/berth.openapi.json index d3c2cde..f198071 100644 --- a/docs/openapi/berth.openapi.json +++ b/docs/openapi/berth.openapi.json @@ -3212,7 +3212,7 @@ "description": "A WebSocket; its frames are in the AsyncAPI document" } }, - "summary": "Channel messages of chosen hosts, jobs and key-value changes together. The first frame sent names what to follow; each frame received says where it came from.", + "summary": "Channel messages of chosen hosts, jobs, key-value changes and changes to hosts and resources together. The first frame sent names what to follow; each frame received says where it came from.", "tags": [ "streams" ] diff --git a/docs/openapi/berth.operations.json b/docs/openapi/berth.operations.json index 417ff4d..f01c8a0 100644 --- a/docs/openapi/berth.operations.json +++ b/docs/openapi/berth.operations.json @@ -4046,7 +4046,7 @@ }, { "binary": false, - "description": "This follower was too slow and missed so many events; read the inbox again.", + "description": "This follower was too slow. `events` counts the server's events it missed, of every kind. Read the inbox again.", "example": { "dropped": { "events": 12 @@ -4200,7 +4200,7 @@ }, { "binary": false, - "description": "This follower was too slow and missed so many changes; list the namespace again.", + "description": "This follower was too slow. `events` counts the server's events it missed, of every kind. List the namespace again.", "example": { "dropped": { "events": 12 @@ -4418,7 +4418,30 @@ }, { "binary": false, - "description": "This follower was too slow and missed so many events, of any kind it follows; read what it shows again.", + "description": "A saved host was `added`, `removed`, `renamed` (with the name it had `from`) or its profile `changed`. Read the host itself with hosts.get.", + "example": { + "change": "renamed", + "from": "desk", + "host": "studio", + "source": "host" + }, + "name": "host" + }, + { + "binary": false, + "description": "A resource was `created`, `removed` or its record `changed`. Read it with resources.get.", + "example": { + "change": "created", + "kind": "deployment", + "provisioner": "docker", + "resource": "r-k3v9qz2m", + "source": "resource" + }, + "name": "resource" + }, + { + "binary": false, + "description": "This follower was too slow. `events` counts the server's events it missed, of every kind. Read what it follows again.", "example": { "dropped": { "events": 12 @@ -4434,6 +4457,10 @@ "binary": false, "description": "What to follow. Sent once, first.", "example": { + "changes": [ + "hosts", + "resources" + ], "hosts": [ "server" ], @@ -4448,7 +4475,7 @@ "name": "follow" } ], - "summary": "Channel messages of chosen hosts, jobs and key-value changes together. The first frame sent names what to follow; each frame received says where it came from." + "summary": "Channel messages of chosen hosts, jobs, key-value changes and changes to hosts and resources together. The first frame sent names what to follow; each frame received says where it came from." } ], "portal": { diff --git a/docs/scripts/reference.mjs b/docs/scripts/reference.mjs index f1ab55e..17160a0 100644 --- a/docs/scripts/reference.mjs +++ b/docs/scripts/reference.mjs @@ -46,7 +46,7 @@ const groups = { jobs: ['Jobs', 'Long-running work of berth serve, such as an apply: one run of an action.'], inbox: ['Inbox', "Messages taken in from the hosts' channels."], kv: ['Key-value store', 'Small JSON values with revisions, for user interfaces.'], - events: ['Events', 'One stream for channel messages, jobs and key-value changes.'], + events: ['Events', 'One stream for channel messages, jobs, key-value changes and changes to hosts and resources.'], }; const groupOrder = Object.keys(groups); From 45903b9596d7dc5387127bcb2b9eb999ad8de4e4 Mon Sep 17 00:00:00 2001 From: Helight Date: Sat, 14 Nov 2026 23:56:16 +0100 Subject: [PATCH 07/94] feat(api): ports.connect, a stream to a port on a host's loopback Streams on the portal can now ask for a window on their bytes, which both sides keep to with credit frames, and the server's frames wait for room in a bounded queue. A stream nobody reads no longer grows the other side's memory or holds up the rest of the portal. --- crates/berth-api/src/lib.rs | 2 + crates/berth-api/src/ops.rs | 12 + crates/berth-api/src/portal.rs | 195 ++++++++++++++-- crates/berth-api/src/streams.rs | 27 +++ crates/berth-api/src/tunnel.rs | 142 ++++++++++++ crates/berth/src/serve/api.rs | 47 ++-- crates/berth/src/serve/auth.rs | 10 + crates/berth/src/serve/tests.rs | 88 ++++++++ crates/berthd/src/http.rs | 9 +- crates/berthd/src/lib.rs | 1 + crates/berthd/src/portal.rs | 220 ++++++++++++++----- crates/berthd/src/ports.rs | 121 ++++++++++ crates/berthd/tests/api.rs | 119 ++++++++++ docs/content/docs/(guide)/extend/streams.mdx | 22 ++ docs/content/docs/api/portal.mdx | 19 ++ docs/openapi/berth.asyncapi.json | 82 +++++++ docs/openapi/berth.openapi.json | 44 ++++ docs/openapi/berthd.asyncapi.json | 79 +++++++ docs/openapi/berthd.openapi.json | 35 +++ docs/openapi/berthd.operations.json | 54 +++++ docs/scripts/reference.mjs | 1 + 21 files changed, 1230 insertions(+), 99 deletions(-) create mode 100644 crates/berth-api/src/tunnel.rs create mode 100644 crates/berthd/src/ports.rs diff --git a/crates/berth-api/src/lib.rs b/crates/berth-api/src/lib.rs index c9182a6..4f1a3a6 100644 --- a/crates/berth-api/src/lib.rs +++ b/crates/berth-api/src/lib.rs @@ -9,6 +9,8 @@ pub mod ops; pub mod portal; pub mod profile; pub mod streams; +#[cfg(feature = "client")] +pub mod tunnel; mod types; pub use types::*; diff --git a/crates/berth-api/src/ops.rs b/crates/berth-api/src/ops.rs index c7fe239..d9d94f9 100644 --- a/crates/berth-api/src/ops.rs +++ b/crates/berth-api/src/ops.rs @@ -29,6 +29,16 @@ //! ↔ {"sub": 7, "end": true} the last frame; from the server it may carry "error" //! ``` //! +//! A request to open a stream may add `"window": BYTES`. A server that keeps +//! to it says so in its answer, `{"open": true, "window": BYTES}`, with the +//! window it took. Each side then sends at most that many bytes of binary +//! frames of the stream that the other side has not yet said it took, and +//! says what it took as it goes: +//! +//! ```text +//! ↔ {"sub": 7, "credit": 131072} so many more bytes may come +//! ``` +//! //! Bytes in a result or as input are `{"base64": "…"}` (a result adds //! `content_type`), up to [`PORTAL_BYTES`]; larger transfers are HTTP's. @@ -218,6 +228,7 @@ pub static HOST: &[Op] = &[ "/v1/services/{plugin}/{name}/{method}", ), stream("services.serve", "/v1/services/{plugin}/{name}/serve"), + stream("ports.connect", "/v1/ports/{port}"), ]; const IF_MATCH: (&str, &str) = ("if_match", "if-match"); @@ -445,6 +456,7 @@ mod tests { assert_eq!(role(HOST, "files.read"), Role::Operate); assert_eq!(role(HOST, "applied.profile"), Role::Admin); assert_eq!(role(HOST, "sessions.attach"), Role::Operate); + assert_eq!(role(HOST, "ports.connect"), Role::Operate); assert_eq!(role(SERVE, "hosts.save"), Role::Admin); assert_eq!(role(SERVE, "hosts.act"), Role::View); assert_eq!(role(SERVE, "provisioners.get"), Role::View); diff --git a/crates/berth-api/src/portal.rs b/crates/berth-api/src/portal.rs index 5f97bf8..849a441 100644 --- a/crates/berth-api/src/portal.rs +++ b/crates/berth-api/src/portal.rs @@ -2,14 +2,14 @@ //! WebSocket. The frames are described in [`crate::ops`]. use crate::client::{Error, Result}; -use futures_util::{Sink, SinkExt, Stream, StreamExt}; +use futures_util::{Sink, SinkExt, Stream, StreamExt, task::AtomicWaker}; use serde_json::{Value, json}; use std::{ collections::HashMap, pin::Pin, sync::{ Arc, Mutex, - atomic::{AtomicU32, Ordering}, + atomic::{AtomicBool, AtomicI64, AtomicU32, Ordering}, }, task::{Context, Poll}, }; @@ -31,11 +31,108 @@ enum Event { End(Option), } +/// The window a client asks for on each stream it opens: bytes of binary +/// frames on their way each way. Its frames wait in the other side's queue +/// for its reader, so this is what one stream can hold there. +pub const WINDOW: u32 = 256 * 1024; + +/// The least and the most window a server takes. +pub const WINDOWS: (u32, u32) = (16 * 1024, 4 << 20); + +/// What one side of a stream may still send, by what the other side said it +/// took. Without a window it may always send. +#[derive(Default)] +pub struct Credit { + on: AtomicBool, + room: AtomicI64, + waiting: AtomicWaker, +} + +impl Credit { + pub fn with(window: Option) -> Credit { + let credit = Credit::default(); + if let Some(window) = window { + credit.start(window); + } + credit + } + + pub fn start(&self, window: u32) { + self.room.store(window as i64, Ordering::SeqCst); + self.on.store(true, Ordering::SeqCst); + } + + /// The other side took so many more bytes. + pub fn grant(&self, bytes: u64) { + self.room + .fetch_add(bytes.min(i64::MAX as u64) as i64, Ordering::SeqCst); + self.waiting.wake(); + } + + /// So many bytes were sent. One frame may go beyond the window, so a + /// frame larger than it is not held forever. + pub fn spend(&self, bytes: usize) { + if self.on.load(Ordering::SeqCst) { + self.room.fetch_sub(bytes as i64, Ordering::SeqCst); + } + } + + /// Ready once a frame may be sent. One task waits on it at a time. + pub fn poll_room(&self, cx: &mut Context<'_>) -> Poll<()> { + let open = || !self.on.load(Ordering::SeqCst) || self.room.load(Ordering::SeqCst) > 0; + if open() { + return Poll::Ready(()); + } + self.waiting.register(cx.waker()); + // A grant between the look and the registration would be missed otherwise. + if open() { + Poll::Ready(()) + } else { + Poll::Pending + } + } + + pub async fn room(&self) { + std::future::poll_fn(|cx| self.poll_room(cx)).await + } +} + +/// What the receiving side of a stream took and has not yet said: the credit +/// to send, once it is half the window, so not every frame costs one. +pub struct Taken { + window: Option, + bytes: u64, +} + +impl Taken { + pub fn new(window: Option) -> Taken { + Taken { window, bytes: 0 } + } + + /// The frame that says what was taken, when it is time for one. + pub fn took(&mut self, sub: u32, bytes: usize) -> Option { + let window = self.window?; + self.bytes += bytes as u64; + if self.bytes < u64::from(window / 2) { + return None; + } + let credit = std::mem::take(&mut self.bytes); + Some(json!({"sub": sub, "credit": credit})) + } +} + +struct Open { + frames: mpsc::UnboundedSender, + credit: Arc, +} + #[derive(Default)] struct Shared { next: AtomicU32, calls: Mutex>>>, - streams: Mutex>>, + // Unbounded so the reader never waits on one stream: what the server may + // send a stream with a window is bounded by it. + streams: Mutex>, /// Why the connection ended, once it has. closed: Mutex>, } @@ -48,7 +145,9 @@ impl Shared { let _ = call.send(Err(Error::Transport(reason.to_owned()))); } for (_, stream) in self.streams.lock().unwrap().drain() { - let _ = stream.send(Event::End(Some(Error::Transport(reason.to_owned())))); + let _ = stream + .frames + .send(Event::End(Some(Error::Transport(reason.to_owned())))); } } } @@ -111,7 +210,9 @@ impl Portal { if let Some((id, bytes)) = untagged(&bytes) && let Some(stream) = reader.streams.lock().unwrap().get(&id) { - let _ = stream.send(Event::Piece(Piece::Binary(bytes.to_vec()))); + let _ = stream + .frames + .send(Event::Piece(Piece::Binary(bytes.to_vec()))); } } Some(Ok(Message::Close(_))) | None => break "The connection closed".to_owned(), @@ -135,6 +236,7 @@ impl Portal { host: Option<&str>, args: Value, data: Option, + window: Option, ) -> Result<(u32, oneshot::Receiver>)> { if let Some(reason) = self.shared.closed.lock().unwrap().clone() { return Err(Error::Transport(reason)); @@ -156,6 +258,9 @@ impl Portal { if let Some(data) = data { frame["data"] = data; } + if let Some(window) = window { + frame["window"] = json!(window); + } if self .out .send(Message::Text(frame.to_string().into())) @@ -175,28 +280,44 @@ impl Portal { args: Value, data: Option, ) -> Result { - let (_, waiting) = self.request(op, host, args, data)?; + let (_, waiting) = self.request(op, host, args, data, None)?; waiting .await .unwrap_or_else(|_| Err(Error::Transport("The connection closed".into()))) } - /// Open a streaming operation. + /// Open a streaming operation, with a window on its bytes when the + /// server takes one. pub async fn open(&self, op: &str, host: Option<&str>, args: Value) -> Result { let (frames, incoming) = mpsc::unbounded_channel(); + let credit = Arc::new(Credit::default()); let (id, waiting) = { // Registered before the request leaves, so no frame can come too early. let mut streams = self.shared.streams.lock().unwrap(); - let (id, waiting) = self.request(op, host, args, None)?; - streams.insert(id, frames); + let (id, waiting) = self.request(op, host, args, None, Some(WINDOW))?; + let open = Open { + frames, + credit: credit.clone(), + }; + streams.insert(id, open); (id, waiting) }; let opened = waiting .await .unwrap_or_else(|_| Err(Error::Transport("The connection closed".into()))); - if let Err(error) = opened { - self.shared.streams.lock().unwrap().remove(&id); - return Err(error); + let opened = match opened { + Ok(opened) => opened, + Err(error) => { + self.shared.streams.lock().unwrap().remove(&id); + return Err(error); + } + }; + // A server that does not say a window keeps to none. + let window = opened["window"] + .as_u64() + .and_then(|window| u32::try_from(window).ok()); + if let Some(window) = window { + credit.start(window); } Ok(PortalStream { id, @@ -204,8 +325,22 @@ impl Portal { incoming, shared: self.shared.clone(), ended: false, + credit, + taken: Taken::new(window), }) } + + /// A TCP connection to a port on a host's loopback, through `ports.connect`. + pub async fn connect_port( + &self, + host: Option<&str>, + port: u16, + ) -> Result> { + let stream = self + .open("ports.connect", host, json!({"port": port})) + .await?; + Ok(crate::tunnel::Tunnel::new(stream)) + } } impl Shared { @@ -222,10 +357,18 @@ impl Shared { let mut streams = self.streams.lock().unwrap(); if frame["end"].as_bool() == Some(true) { if let Some(stream) = streams.remove(&id) { - let _ = stream.send(Event::End(frame.get("error").map(error_of))); + let _ = stream + .frames + .send(Event::End(frame.get("error").map(error_of))); } } else if let Some(stream) = streams.get(&id) { - let _ = stream.send(Event::Piece(Piece::Text(frame["data"].clone()))); + match frame["credit"].as_u64() { + Some(bytes) => stream.credit.grant(bytes), + None => { + let piece = Piece::Text(frame["data"].clone()); + let _ = stream.frames.send(Event::Piece(piece)); + } + } } } } @@ -238,6 +381,10 @@ pub struct PortalStream { incoming: mpsc::UnboundedReceiver, shared: Arc, ended: bool, + /// What this side may still send. + credit: Arc, + /// What this side took and has not said yet. + taken: Taken, } impl PortalStream { @@ -251,7 +398,14 @@ impl PortalStream { return Poll::Ready(None); } match self.incoming.poll_recv(cx) { - Poll::Ready(Some(Event::Piece(piece))) => Poll::Ready(Some(Ok(piece))), + Poll::Ready(Some(Event::Piece(piece))) => { + if let Piece::Binary(bytes) = &piece + && let Some(credit) = self.taken.took(self.id, bytes.len()) + { + let _ = self.out.send(Message::Text(credit.to_string().into())); + } + Poll::Ready(Some(Ok(piece))) + } Poll::Ready(Some(Event::End(error))) => { self.ended = true; Poll::Ready(error.map(Err)) @@ -264,12 +418,16 @@ impl PortalStream { } } + /// Send a frame now. It does not wait for the window: the [`Sink`] does. pub fn push(&self, piece: Piece) -> Result<()> { let message = match piece { Piece::Text(data) => { Message::Text(json!({"sub": self.id, "data": data}).to_string().into()) } - Piece::Binary(bytes) => Message::Binary(tagged(self.id, &bytes).into()), + Piece::Binary(bytes) => { + self.credit.spend(bytes.len()); + Message::Binary(tagged(self.id, &bytes).into()) + } }; self.out .send(message) @@ -318,11 +476,12 @@ impl Stream for PortalStream { impl Sink for PortalStream { type Error = WsError; + /// Ready once the window has room. fn poll_ready( self: Pin<&mut Self>, - _: &mut Context<'_>, + cx: &mut Context<'_>, ) -> Poll> { - Poll::Ready(Ok(())) + self.credit.poll_room(cx).map(Ok) } fn start_send(self: Pin<&mut Self>, message: Message) -> std::result::Result<(), WsError> { diff --git a/crates/berth-api/src/streams.rs b/crates/berth-api/src/streams.rs index bb087fe..adb2fe2 100644 --- a/crates/berth-api/src/streams.rs +++ b/crates/berth-api/src/streams.rs @@ -161,8 +161,35 @@ pub const HOST: &[Stream] = &[ ), ], }, + Stream { + id: "port", + path: "/v1/ports/{port}", + summary: "A TCP connection to a port on the host's loopback, 127.0.0.1. The port is dialled first, so one that nothing listens on is an error and not a stream.", + level: "host", + parameters: &[], + resumable: false, + server: &[ + binary("bytes", "What the program on the port sent."), + text( + "eof", + "The program on the port closed its side. Bytes sent towards it still arrive. The stream ends once both sides have sent this.", + EOF, + ), + ], + client: &[ + binary("bytes", "Bytes for the program on the port."), + text( + "eof", + "The client sends no more, and the program on the port reads the end. What it sends still comes back.", + EOF, + ), + ], + }, ]; +/// The frame by which one side of a stream of a port says it sends no more. +pub const EOF: &str = r#"{"eof":true}"#; + /// The streams `berth serve` adds to each host's own. pub const SERVE: &[Stream] = &[ Stream { diff --git a/crates/berth-api/src/tunnel.rs b/crates/berth-api/src/tunnel.rs new file mode 100644 index 0000000..4aae11e --- /dev/null +++ b/crates/berth-api/src/tunnel.rs @@ -0,0 +1,142 @@ +//! A TCP connection to a port of a host, as `ports.connect` gives it: read +//! and written like a socket, over the stream's own WebSocket or the portal. + +use crate::client::{Frame, Result, WebSocketStream, WsError, websocket}; +use crate::streams::EOF; +use futures_util::{Sink, Stream}; +use std::{ + io, + pin::Pin, + task::{Context, Poll, ready}, +}; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; + +/// The most bytes one frame carries, so a large write does not become one +/// frame that the other side has to hold whole. +const FRAME: usize = 64 * 1024; + +/// The bytes of a stream of a port. Shutting down the writing side sends +/// the end, and reading goes on until the other side has sent its own. +/// Dropping it ends the connection. +pub struct Tunnel { + inner: S, + /// What was received and not read yet. + buffer: Vec, + at: usize, + /// The other side said it sends no more. + read_end: bool, + /// This side said it sends no more. + write_end: bool, +} + +/// Open a port of the host at the other end of `io`, a connection to its berthd. +pub async fn tunnel(io: S, port: u16) -> Result>> +where + S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, +{ + let stream = websocket(io, &format!("/v1/ports/{port}"), "").await?; + Ok(Tunnel::new(stream)) +} + +impl Tunnel { + /// The stream of a port that is already open. + pub fn new(inner: S) -> Tunnel { + Tunnel { + inner, + buffer: vec![], + at: 0, + read_end: false, + write_end: false, + } + } + + pub fn into_inner(self) -> S { + self.inner + } +} + +fn broken(error: impl std::fmt::Display) -> io::Error { + io::Error::other(error.to_string()) +} + +fn said_end(text: &str) -> bool { + serde_json::from_str::(text).is_ok_and(|frame| frame["eof"] == true) +} + +impl AsyncRead for Tunnel +where + S: Stream> + Unpin, +{ + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + let this = &mut *self; + loop { + if this.at < this.buffer.len() { + let count = out.remaining().min(this.buffer.len() - this.at); + out.put_slice(&this.buffer[this.at..this.at + count]); + this.at += count; + return Poll::Ready(Ok(())); + } + if this.read_end { + return Poll::Ready(Ok(())); + } + match ready!(Pin::new(&mut this.inner).poll_next(cx)) { + Some(Ok(Frame::Binary(bytes))) => { + this.buffer = bytes.to_vec(); + this.at = 0; + } + Some(Ok(Frame::Text(text))) if said_end(text.as_str()) => this.read_end = true, + Some(Ok(_)) => {} + Some(Err(error)) => return Poll::Ready(Err(broken(error))), + // Ended without saying so first: the connection was lost, not closed. + None => { + return Poll::Ready(Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "The connection to the port ended before its end", + ))); + } + } + } + } +} + +impl AsyncWrite for Tunnel +where + S: Sink + Unpin, +{ + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + data: &[u8], + ) -> Poll> { + if self.write_end { + return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())); + } + ready!(Pin::new(&mut self.inner).poll_ready(cx)).map_err(broken)?; + let count = data.len().min(FRAME); + let frame = Frame::Binary(data[..count].to_vec().into()); + Pin::new(&mut self.inner) + .start_send(frame) + .map_err(broken)?; + Poll::Ready(Ok(count)) + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_flush(cx).map_err(broken) + } + + /// Say the end and leave the other direction open. + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + if !self.write_end { + ready!(Pin::new(&mut self.inner).poll_ready(cx)).map_err(broken)?; + Pin::new(&mut self.inner) + .start_send(Frame::Text(EOF.into())) + .map_err(broken)?; + self.write_end = true; + } + Pin::new(&mut self.inner).poll_flush(cx).map_err(broken) + } +} diff --git a/crates/berth/src/serve/api.rs b/crates/berth/src/serve/api.rs index d1b11e0..0780ee1 100644 --- a/crates/berth/src/serve/api.rs +++ b/crates/berth/src/serve/api.rs @@ -1108,32 +1108,41 @@ async fn proxy( Ok(response) } -/// Frames both ways until either side closes. +/// Frames both ways until either side closes, each way on its own, so a +/// side that is slow to take frames does not hold up the other direction. async fn pump(socket: WebSocket, upstream: berth_core::link::LinkStream) { use client::Frame; let (mut to_client, mut from_client) = socket.split(); let (mut to_host, mut from_host) = upstream.split(); - loop { - tokio::select! { - frame = from_client.next() => { - let sent = match frame { - Some(Ok(WsMessage::Text(text))) => to_host.send(Frame::Text(text.as_str().into())).await, - Some(Ok(WsMessage::Binary(data))) => to_host.send(Frame::Binary(data)).await, - Some(Ok(WsMessage::Ping(_) | WsMessage::Pong(_))) => Ok(()), - _ => break, - }; - if sent.is_err() { break } + let towards_host = async { + while let Some(Ok(frame)) = from_client.next().await { + let sent = match frame { + WsMessage::Text(text) => to_host.send(Frame::Text(text.as_str().into())).await, + WsMessage::Binary(data) => to_host.send(Frame::Binary(data)).await, + WsMessage::Ping(_) | WsMessage::Pong(_) => Ok(()), + WsMessage::Close(_) => break, + }; + if sent.is_err() { + break; } - frame = from_host.next() => { - let sent = match frame { - Some(Ok(Frame::Text(text))) => to_client.send(WsMessage::Text(text.as_str().into())).await, - Some(Ok(Frame::Binary(data))) => to_client.send(WsMessage::Binary(data)).await, - Some(Ok(Frame::Ping(_) | Frame::Pong(_) | Frame::Frame(_))) => Ok(()), - _ => break, - }; - if sent.is_err() { break } + } + }; + let towards_client = async { + while let Some(Ok(frame)) = from_host.next().await { + let sent = match frame { + Frame::Text(text) => to_client.send(WsMessage::Text(text.as_str().into())).await, + Frame::Binary(data) => to_client.send(WsMessage::Binary(data)).await, + Frame::Ping(_) | Frame::Pong(_) | Frame::Frame(_) => Ok(()), + Frame::Close(_) => break, + }; + if sent.is_err() { + break; } } + }; + tokio::select! { + () = towards_host => {} + () = towards_client => {} } let _ = to_host.send(Frame::Close(None)).await; let _ = to_client.send(WsMessage::Close(None)).await; diff --git a/crates/berth/src/serve/auth.rs b/crates/berth/src/serve/auth.rs index 4a47b1f..632e14a 100644 --- a/crates/berth/src/serve/auth.rs +++ b/crates/berth/src/serve/auth.rs @@ -460,6 +460,7 @@ mod tests { name("GET", "/v1/hosts/a/sessions/x", true), "sessions.attach" ); + assert_eq!(name("GET", "/v1/hosts/a/ports/8080", true), "ports.connect"); assert_eq!( name("PUT", "/v1/secrets/registry%2Fmain", false), "secrets.set" @@ -490,6 +491,15 @@ mod tests { subject: None, }; assert!(auth.allows(&viewer, run).unwrap_err().1.contains("operate")); + // A port of a host is used, not looked at. + let port = ops::find(ops::HOST, "ports.connect").unwrap(); + assert!( + auth.allows(&viewer, port) + .unwrap_err() + .1 + .contains("operate") + ); + assert!(auth.allows(&admin, port).is_ok()); // An action's own role is asked the same way. assert!(auth.permits(&viewer, "apply", Role::Admin).is_err()); assert!( diff --git a/crates/berth/src/serve/tests.rs b/crates/berth/src/serve/tests.rs index 5d550b9..78850e6 100644 --- a/crates/berth/src/serve/tests.rs +++ b/crates/berth/src/serve/tests.rs @@ -952,6 +952,94 @@ async fn a_hosts_actions_are_its_tasks_and_berths_own() { ); } +/// A listener on the loopback that sends back what it gets, and ends its +/// side once the caller has ended theirs. +async fn echo() -> u16 { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { + while let Ok((connection, _)) = listener.accept().await { + tokio::spawn(async move { + use tokio::io::AsyncWriteExt; + let (mut reading, mut writing) = connection.into_split(); + let _ = tokio::io::copy(&mut reading, &mut writing).await; + let _ = writing.shutdown().await; + }); + } + }); + port +} + +/// Write `data` and end, while what comes back is read: what came back. +async fn through(open: T, data: &[u8]) -> Vec +where + T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + 'static, +{ + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let (mut reading, mut writing) = tokio::io::split(open); + let sent = data.to_vec(); + let writer = tokio::spawn(async move { + writing.write_all(&sent).await.unwrap(); + writing.shutdown().await.unwrap(); + writing + }); + let mut back = vec![]; + tokio::time::timeout(Duration::from_secs(60), reading.read_to_end(&mut back)) + .await + .expect("all of it back in time") + .unwrap(); + drop(writer.await.unwrap()); + back +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_port_of_a_host_is_reached_through_the_server() { + use berth_api::{portal::Portal, tunnel::Tunnel}; + let Some(host) = Berthd::start().await else { + return; + }; + let served = served().await; + served + .state + .add(Remote::new("studio", "192.0.2.10", host.link())); + let port = echo().await; + let data: Vec = (0..3_000_000u32).map(|n| (n % 251) as u8).collect(); + + // As the host's own stream, passed through. + let path = format!("/v1/hosts/studio/ports/{port}"); + let open = client::websocket_unix(&served.socket, &path).await.unwrap(); + assert_eq!(through(Tunnel::new(open), b"hello").await, b"hello"); + let open = client::websocket_unix(&served.socket, &path).await.unwrap(); + assert!(through(Tunnel::new(open), &data).await == data); + + // On the portal, with the host named. + let portal = Portal::over( + client::websocket_unix(&served.socket, "/v1/portal") + .await + .unwrap(), + ); + let open = portal.connect_port(Some("studio"), port).await.unwrap(); + assert!(through(open, &data).await == data); + + // A port nothing listens on is the host's error, either way. + let closed = { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.local_addr().unwrap().port() + }; + let path = format!("/v1/hosts/studio/ports/{closed}"); + let refused = client::websocket_unix(&served.socket, &path) + .await + .err() + .unwrap(); + assert_eq!((refused.status(), refused.code()), (503, "not_served")); + let refused = portal + .connect_port(Some("studio"), closed) + .await + .err() + .unwrap(); + assert_eq!((refused.status(), refused.code()), (503, "not_served")); +} + #[tokio::test(flavor = "multi_thread")] async fn the_portal_reaches_serve_and_its_hosts() { use berth_api::portal::{Piece, Portal}; diff --git a/crates/berthd/src/http.rs b/crates/berthd/src/http.rs index fdc86c7..ecad0e0 100644 --- a/crates/berthd/src/http.rs +++ b/crates/berthd/src/http.rs @@ -3,7 +3,7 @@ use crate::error::E; use crate::state::{Caller, Mode, State}; -use crate::{channel, files, services, sessions, system, tasks}; +use crate::{channel, files, ports, services, sessions, system, tasks}; use axum::{ Json, Router, extract::{Extension, Request, State as AppState}, @@ -77,6 +77,8 @@ pub const ROUTES: &[Route] = &[ Route { method: "GET", path: "/v1/services", summary: "The services that can be called, and whether each is up.", level: "both", query: &[], body: "", reply: "Service[]", stream: "", handler: || get(services::list) }, Route { method: "POST", path: "/v1/services/{plugin}/{name}/{method}", summary: "Call a method of the service PLUGIN/NAME: JSON in, JSON out.", level: "both", query: &[], body: "json", reply: "json", stream: "", handler: || post(services::call) }, Route { method: "GET", path: "/v1/services/{plugin}/{name}/serve", summary: "Only as a WebSocket: for the program that answers the service's calls.", level: "both", query: &[], body: "", reply: "", stream: "serve", handler: || get(services::serve) }, + + Route { method: "GET", path: "/v1/ports/{port}", summary: "Only as a WebSocket: a TCP connection to a port on the host's loopback. A port that nothing listens on is an error before the handshake.", level: "host", query: &[], body: "", reply: "", stream: "port", handler: || get(ports::connect) }, ]; async fn version(AppState(state): AppState>) -> Json { @@ -403,6 +405,11 @@ const PATH_ARGUMENTS: &[(&str, &str, &str)] = &[ ("services.", "plugin", "The plugin the service belongs to."), ("services.", "name", "The service's name within its plugin."), ("services.call", "method", "One of the service's methods."), + ( + "ports.", + "port", + "A TCP port on the host's loopback, 127.0.0.1: a number from 1 to 65535.", + ), ("jobs.", "id", "A job's id."), ("kv.", "namespace", "A namespace."), ("kv.", "key", "A key."), diff --git a/crates/berthd/src/lib.rs b/crates/berthd/src/lib.rs index 4f7079a..52c2b49 100644 --- a/crates/berthd/src/lib.rs +++ b/crates/berthd/src/lib.rs @@ -6,6 +6,7 @@ mod error; mod files; pub mod http; pub mod portal; +mod ports; mod services; mod sessions; pub mod state; diff --git a/crates/berthd/src/portal.rs b/crates/berthd/src/portal.rs index 69f3329..331b8e6 100644 --- a/crates/berthd/src/portal.rs +++ b/crates/berthd/src/portal.rs @@ -12,14 +12,14 @@ use axum::{ use berth_api::{ ErrorBody, b64, client, code, ops::{self, Kind, Op}, - portal::{tagged, untagged}, + portal::{Credit, Taken, WINDOWS, tagged, untagged}, unb64, }; use futures_util::{SinkExt, StreamExt}; use hyper_util::{rt::TokioIo, service::TowerToHyperService}; use serde_json::{Map, Value, json}; use std::{collections::HashMap, sync::Arc}; -use tokio::sync::mpsc; +use tokio::sync::{Semaphore, mpsc}; use tower::ServiceExt; /// The messages of the WebSocket an operation is on its own. @@ -231,6 +231,8 @@ async fn open( code::NOT_FOUND, code::BAD_REQUEST, code::UNREACHABLE, + code::NOT_SERVED, + code::TIMEOUT, ]; let kind = known .into_iter() @@ -240,23 +242,75 @@ async fn open( }) } +/// The most bytes of frames waiting to be written to the socket. Only the +/// writer gives room back, and it waits on nothing but the socket, so a task +/// that waits for room waits for the network and never for another task; the +/// reader and the credits it answers take no room, so they cannot be stalled +/// behind a stream's bytes. +const ROOM: usize = 1 << 20; + +/// The frames on their way to the socket, in the order they were sent. +#[derive(Clone)] +struct Out { + queue: mpsc::UnboundedSender<(Message, u32)>, + room: Arc, +} + +impl Out { + /// A frame of a stream or the answer to a call: it waits for room. + async fn data(&self, message: Message) -> bool { + let size = match &message { + Message::Text(text) => text.len(), + Message::Binary(bytes) => bytes.len(), + _ => 0, + }; + let size = size.clamp(1, ROOM) as u32; + let Ok(permit) = self.room.acquire_many(size).await else { + return false; + }; + permit.forget(); + self.queue.send((message, size)).is_ok() + } + + /// A small frame that waits for nothing. + fn control(&self, frame: Value) { + let _ = self + .queue + .send((Message::Text(frame.to_string().into()), 0)); + } +} + +/// What the caller sends towards an open stream, and what that stream may +/// still send the caller. +struct Inbound { + // Unbounded, so the reader never waits on one stream: a caller that + // asked for a window sends no more than it. + input: mpsc::UnboundedSender, + credit: Arc, +} + /// Serve a portal until its socket closes. `router` answers as the caller /// the portal was opened by. pub async fn run(socket: WebSocket, router: Router, resolve: Resolve) { let (mut sink, mut source) = socket.split(); - let (out, mut outgoing) = mpsc::unbounded_channel::(); - tokio::spawn(async move { - while let Some(message) = outgoing.recv().await { - if sink.send(message).await.is_err() { + let (queue, mut outgoing) = mpsc::unbounded_channel::<(Message, u32)>(); + let room = Arc::new(Semaphore::new(ROOM)); + let out = Out { + queue, + room: room.clone(), + }; + let writer = tokio::spawn(async move { + while let Some((message, size)) = outgoing.recv().await { + let sent = sink.send(message).await; + room.add_permits(size as usize); + if sent.is_err() { break; } } + // Whoever waits for room would wait for a socket that is gone. + room.close(); }); - let say = |out: &mpsc::UnboundedSender, frame: Value| { - let _ = out.send(Message::Text(frame.to_string().into())); - }; - // What the caller sends towards each open stream. - let mut streams: HashMap> = HashMap::new(); + let mut streams: HashMap = HashMap::new(); while let Some(Ok(message)) = source.next().await { let frame: Value = match message { Message::Text(text) => match serde_json::from_str(text.as_str()) { @@ -267,7 +321,9 @@ pub async fn run(socket: WebSocket, router: Router, resolve: Resolve) { if let Some((id, bytes)) = untagged(&bytes) && let Some(stream) = streams.get(&id) { - let _ = stream.send(upstream::Frame::Binary(bytes.to_vec().into())); + let _ = stream + .input + .send(upstream::Frame::Binary(bytes.to_vec().into())); } continue; } @@ -279,7 +335,13 @@ pub async fn run(socket: WebSocket, router: Router, resolve: Resolve) { if frame["end"].as_bool() == Some(true) { streams.remove(&id); } else if let Some(stream) = streams.get(&id) { - let _ = stream.send(upstream::Frame::Text(frame["data"].to_string().into())); + match frame["credit"].as_u64() { + Some(bytes) => stream.credit.grant(bytes), + None => { + let text = frame["data"].to_string(); + let _ = stream.input.send(upstream::Frame::Text(text.into())); + } + } } continue; } @@ -290,11 +352,11 @@ pub async fn run(socket: WebSocket, router: Router, resolve: Resolve) { let target = match resolve(name, frame["host"].as_str()) { Ok(target) => target, Err(problem) => { - say(&out, failure(id, problem)); + out.control(failure(id, problem)); continue; } }; - streams.retain(|_, stream| !stream.is_closed()); + streams.retain(|_, stream| !stream.input.is_closed()); match target.op.kind { Kind::Call => { let (router, out) = (router.clone(), out.clone()); @@ -303,63 +365,99 @@ pub async fn run(socket: WebSocket, router: Router, resolve: Resolve) { Ok(result) => json!({"id": id, "result": result}), Err(problem) => failure(id, problem), }; - let _ = out.send(Message::Text(frame.to_string().into())); + out.data(Message::Text(frame.to_string().into())).await; }); } Kind::Stream => { - let (towards, mut input) = mpsc::unbounded_channel(); - streams.insert(id as u32, towards); + let window = frame["window"] + .as_u64() + .map(|window| window.clamp(WINDOWS.0.into(), WINDOWS.1.into()) as u32); + let (towards, input) = mpsc::unbounded_channel(); + let credit = Arc::new(Credit::with(window)); + let inbound = Inbound { + input: towards, + credit: credit.clone(), + }; + streams.insert(id as u32, inbound); let (router, out) = (router.clone(), out.clone()); tokio::spawn(async move { let stream = match open(router, &target, &frame["args"]).await { Ok(stream) => stream, - Err(problem) => { - let _ = - out.send(Message::Text(failure(id, problem).to_string().into())); - return; - } + Err(problem) => return out.control(failure(id, problem)), }; - let opened = json!({"id": id, "result": {"open": true}}); - let _ = out.send(Message::Text(opened.to_string().into())); - let (mut up, mut down) = stream.split(); - let sub = id as u32; - loop { - tokio::select! { - frame = down.next() => match frame { - Some(Ok(upstream::Frame::Text(text))) => { - let data = serde_json::from_str::(text.as_str()) - .unwrap_or_else(|_| json!(text.as_str())); - let frame = json!({"sub": sub, "data": data}); - if out.send(Message::Text(frame.to_string().into())).is_err() { - return; - } - } - Some(Ok(upstream::Frame::Binary(bytes))) => { - if out.send(Message::Binary(tagged(sub, &bytes).into())).is_err() { - return; - } - } - Some(Ok(upstream::Frame::Close(_))) | Some(Err(_)) | None => break, - Some(Ok(_)) => {} - }, - frame = input.recv() => match frame { - Some(frame) => { - if up.send(frame).await.is_err() { - break; - } - } - // The caller ended it, or left. - None => { - let _ = up.close().await; - return; - } - }, - } + let mut opened = json!({"id": id, "result": {"open": true}}); + if let Some(window) = window { + opened["result"]["window"] = json!(window); + } + if !out.data(Message::Text(opened.to_string().into())).await { + return; } - let end = json!({"sub": sub, "end": true}); - let _ = out.send(Message::Text(end.to_string().into())); + pipe(id as u32, stream, input, &out, &credit, window).await; }); } } } + drop(streams); + drop(out); + let _ = writer.await; +} + +/// One open stream: its frames to the caller and the caller's to it, each way +/// on its own, so a direction that waits does not hold up the other. +async fn pipe( + sub: u32, + stream: client::WebSocketStream, + mut input: mpsc::UnboundedReceiver, + out: &Out, + credit: &Credit, + window: Option, +) { + let (mut up, mut down) = stream.split(); + let downstream = async { + while let Some(Ok(frame)) = down.next().await { + let message = match frame { + upstream::Frame::Text(text) => { + let data = serde_json::from_str::(text.as_str()) + .unwrap_or_else(|_| json!(text.as_str())); + Message::Text(json!({"sub": sub, "data": data}).to_string().into()) + } + upstream::Frame::Binary(bytes) => { + credit.room().await; + credit.spend(bytes.len()); + Message::Binary(tagged(sub, &bytes).into()) + } + upstream::Frame::Close(_) => break, + _ => continue, + }; + if !out.data(message).await { + return false; + } + } + true + }; + let upstream = async { + let mut taken = Taken::new(window); + while let Some(frame) = input.recv().await { + let size = match &frame { + upstream::Frame::Binary(bytes) => bytes.len(), + _ => 0, + }; + // A stream that takes nothing more ends from its side, downstream. + if up.send(frame).await.is_err() { + return std::future::pending().await; + } + if let Some(credit) = taken.took(sub, size) { + out.control(credit); + } + } + // The caller ended it, or left. + let _ = up.close().await; + }; + tokio::select! { + ended = downstream => if ended { + let end = json!({"sub": sub, "end": true}); + out.data(Message::Text(end.to_string().into())).await; + }, + () = upstream => {} + } } diff --git a/crates/berthd/src/ports.rs b/crates/berthd/src/ports.rs new file mode 100644 index 0000000..3b15970 --- /dev/null +++ b/crates/berthd/src/ports.rs @@ -0,0 +1,121 @@ +//! A TCP connection to a port on the host's loopback, as a stream. + +use crate::error::{E, R}; +use axum::{ + extract::{ + Path, + ws::{Message, WebSocket, WebSocketUpgrade, rejection::WebSocketUpgradeRejection}, + }, + response::Response, +}; +use berth_api::{code, streams::EOF}; +use futures_util::{SinkExt, StreamExt}; +use std::{net::Ipv4Addr, time::Duration}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpStream, +}; + +/// How much is read from the port at a time, which is the most one frame carries. +const FRAME: usize = 64 * 1024; + +/// The port is dialled before the stream opens, so one that nothing listens +/// on is an answer of its own and not a stream that ends at once. +pub async fn connect( + Path(port): Path, + upgrade: Result, +) -> R { + let upgrade = upgrade.map_err(|_| E::bad("A port is opened only as a WebSocket"))?; + let port = port + .parse::() + .ok() + .filter(|port| *port > 0) + .ok_or_else(|| E::bad(format!("{port} is no port: a number from 1 to 65535")))?; + let dialled = tokio::time::timeout( + Duration::from_secs(10), + TcpStream::connect((Ipv4Addr::LOCALHOST, port)), + ) + .await; + let tcp = match dialled { + Ok(Ok(tcp)) => tcp, + Ok(Err(error)) => { + return Err(E( + code::NOT_SERVED, + format!("Nothing answers on port {port} of the host: {error}"), + )); + } + Err(_) => { + return Err(E( + code::TIMEOUT, + format!("Port {port} of the host does not answer"), + )); + } + }; + let _ = tcp.set_nodelay(true); + Ok(upgrade.on_upgrade(move |socket| tunnel(socket, tcp))) +} + +fn said_end(text: &str) -> bool { + serde_json::from_str::(text).is_ok_and(|frame| frame["eof"] == true) +} + +/// Bytes both ways, each direction on its own. Each side's end is a frame, +/// so the other direction goes on until it ends too; the caller leaving, or +/// the port failing, ends both at once. +async fn tunnel(socket: WebSocket, tcp: TcpStream) { + let (mut sink, mut source) = socket.split(); + let (reader, writer) = tcp.into_split(); + let (said, heard) = tokio::sync::oneshot::channel::<()>(); + let upstream = async move { + let (mut writer, mut said) = (Some(writer), Some(said)); + while let Some(Ok(message)) = source.next().await { + match message { + Message::Binary(bytes) => { + if let Some(open) = writer.as_mut() + && open.write_all(&bytes).await.is_err() + { + writer = None; + } + } + Message::Text(text) if said_end(text.as_str()) => { + if let Some(mut open) = writer.take() { + let _ = open.shutdown().await; + } + if let Some(said) = said.take() { + let _ = said.send(()); + } + } + Message::Close(_) => break, + _ => {} + } + } + }; + let downstream = async move { + let mut reader = reader; + let mut buffer = vec![0; FRAME]; + let ended = loop { + match reader.read(&mut buffer).await { + Ok(0) => break true, + Ok(count) => { + let bytes = buffer[..count].to_vec(); + if sink.send(Message::Binary(bytes.into())).await.is_err() { + return; + } + } + Err(_) => break false, + } + }; + if ended { + if sink.send(Message::Text(EOF.into())).await.is_err() { + return; + } + // Until the caller has said its end too. + let _ = heard.await; + } + let _ = sink.send(Message::Close(None)).await; + }; + tokio::select! { + () = upstream => {} + () = downstream => {} + } +} diff --git a/crates/berthd/tests/api.rs b/crates/berthd/tests/api.rs index 958a200..d12039e 100644 --- a/crates/berthd/tests/api.rs +++ b/crates/berthd/tests/api.rs @@ -1236,6 +1236,125 @@ async fn the_portal_carries_calls_and_streams_together() { assert_eq!(refused.unwrap_err().status(), 403); } +/// A listener on the loopback that sends back what it gets, and ends its +/// side once the caller has ended theirs. +async fn echo() -> u16 { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { + while let Ok((connection, _)) = listener.accept().await { + tokio::spawn(async move { + use tokio::io::AsyncWriteExt; + let (mut reading, mut writing) = connection.into_split(); + let _ = tokio::io::copy(&mut reading, &mut writing).await; + let _ = writing.shutdown().await; + }); + } + }); + port +} + +/// Write `data` and end, while what comes back is read: what came back. +async fn through(open: T, data: &[u8]) -> Vec +where + T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + 'static, +{ + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let (mut reading, mut writing) = tokio::io::split(open); + let sent = data.to_vec(); + let writer = tokio::spawn(async move { + writing.write_all(&sent).await.unwrap(); + writing.shutdown().await.unwrap(); + writing + }); + let mut back = vec![]; + tokio::time::timeout(Duration::from_secs(60), reading.read_to_end(&mut back)) + .await + .expect("all of it back in time") + .unwrap(); + drop(writer.await.unwrap()); + back +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_port_on_the_loopback_is_a_stream() { + use berth_api::{portal::Portal, tunnel}; + use tokio::io::AsyncWriteExt; + let daemon = Daemon::start(&[]); + let port = echo().await; + let control = || tokio::net::UnixStream::connect(daemon.socket("control")); + + // What is sent comes back, and after this side's end the rest still arrives. + let open = tunnel::tunnel(control().await.unwrap(), port) + .await + .unwrap(); + assert_eq!(through(open, b"hello").await, b"hello"); + // A few MB at once, over the stream's own WebSocket and over the portal's windows. + let data: Vec = (0..4_000_000u32).map(|n| (n % 251) as u8).collect(); + let open = tunnel::tunnel(control().await.unwrap(), port) + .await + .unwrap(); + assert!(through(open, &data).await == data); + let portal = Portal::over(daemon.stream("control", "/v1/portal").await); + let open = portal.connect_port(None, port).await.unwrap(); + assert!(through(open, &data).await == data); + + // A stream that is not read holds up neither calls nor other streams. + // It takes more than the system's buffers hold, which the window then keeps. + let mut stuck = portal.connect_port(None, port).await.unwrap(); + let writing = vec![7u8; 64 << 20]; + let writer = tokio::spawn(async move { + stuck.write_all(&writing).await.unwrap(); + stuck + }); + tokio::time::sleep(Duration::from_millis(300)).await; + assert!(!writer.is_finished(), "the window let it all through"); + let version = tokio::time::timeout( + Duration::from_secs(10), + portal.call("version", None, Value::Null, None), + ) + .await + .expect("an answer beside the stuck stream"); + assert_eq!(version.unwrap()["api"], api::API); + let other = portal.connect_port(None, port).await.unwrap(); + assert_eq!(through(other, b"beside").await, b"beside"); + drop(writer); + + // A port nothing listens on is an error before the stream opens. + let closed = { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.local_addr().unwrap().port() + }; + let refused = tunnel::tunnel(control().await.unwrap(), closed) + .await + .err() + .unwrap(); + assert_eq!((refused.status(), refused.code()), (503, "not_served")); + let refused = portal.connect_port(None, closed).await.err().unwrap(); + assert_eq!((refused.status(), refused.code()), (503, "not_served")); + // Only a port of the loopback, by its number. + for wrong in ["0", "65536", "http", "192.0.2.1:22", "-1"] { + let path = format!("/v1/ports/{wrong}"); + let refused = client::websocket_unix(&daemon.socket("control"), &path) + .await + .err() + .unwrap(); + assert_eq!(refused.status(), 400, "{wrong}"); + } + // A plain request is no stream, and the agent may not open one. + let plain = daemon + .host() + .await + .get::(&format!("/v1/ports/{port}")) + .await; + assert_eq!(code(plain).0, 400); + let agent = client::websocket_unix(&daemon.socket("agent"), &format!("/v1/ports/{port}")) + .await + .err() + .unwrap(); + assert_eq!(agent.status(), 403); +} + /// The committed API documents are what the program generates. Run with /// BERTH_UPDATE_DOCS=1 to write them after a change to the API. #[test] diff --git a/docs/content/docs/(guide)/extend/streams.mdx b/docs/content/docs/(guide)/extend/streams.mdx index d835e88..8c3890c 100644 --- a/docs/content/docs/(guide)/extend/streams.mdx +++ b/docs/content/docs/(guide)/extend/streams.mdx @@ -61,6 +61,28 @@ Text frames are the same for both kinds: Any number of viewers can be connected to one session. A terminal has the size that the last viewer to resize it asked for. +## The stream of a port + +[`ports.connect`](/docs/api/host/ports) is a TCP connection to a port on the +host's loopback, `127.0.0.1`. It is at `/v1/ports/{port}`, and through +`berth serve` at `/v1/hosts/{name}/ports/{port}`. berthd connects to the port +before the handshake, so a port that nothing listens on gives the error `503 +not_served`. It needs the role `operate` and the host +level. + +Binary frames are the connection's bytes in both directions. Either side ends +its direction with a text frame: + +| Frame | From | Meaning | +|---|---|---| +| `{"eof":true}` | client | The client sends no more. The program on the port reads the end, and what it sends still comes back | +| `{"eof":true}` | server | The program closed its side. Bytes sent towards it still arrive | + +The stream ends once both sides have sent `{"eof":true}`. It ends at once when +the client closes the WebSocket or the connection to the port breaks. A stream +that closes before its `{"eof":true}` has lost its connection. +`berth_api::tunnel` reads and writes such a stream like a socket. + ## Resuming A stream that can be resumed takes `since=` and starts there. The page of each diff --git a/docs/content/docs/api/portal.mdx b/docs/content/docs/api/portal.mdx index bd82d26..0f06da0 100644 --- a/docs/content/docs/api/portal.mdx +++ b/docs/content/docs/api/portal.mdx @@ -71,6 +71,25 @@ The reply to a streaming operation is `{"open": true}`. The server then sends fr The frames inside `data` and the bytes after the four-byte prefix are those of the stream's own WebSocket, listed on each stream's page. Calls go on beside open streams. +## A window on a stream's bytes + +When nobody reads a stream, its bytes would fill the other side's memory or hold up the frames of the other streams. A client asks for a window when it opens the stream to prevent this: + +```js +→ {"id": 12, "op": "ports.connect", "args": {"port": 8080}, "window": 262144} +← {"id": 12, "result": {"open": true, "window": 262144}} +→ binary: 00 00 00 0c, then up to 262144 bytes +← {"sub": 12, "credit": 131072} +``` + +| Rule | Means | +| --- | --- | +| `window` in the request | How many bytes of binary frames each side may send before the other side credits them. The server takes 16 KB to 4 MB | +| `window` in the answer | The server keeps to that window. Without it, no window applies to the stream | +| `{"sub": N, "credit": BYTES}` | Either side has taken so many bytes, and the other may send that many more | + +A side may send one frame beyond the window, so a large frame isn't held forever. JSON frames don't count against it. Each side says what it took once it has taken half the window. berth's client asks for a window on every stream it opens, and a client that asks for none gets the streams as before. + ## Bytes Bytes in input or a result are `{"base64": "…"}`, and a result adds `content_type`. The portal takes up to 8 MB of bytes per operation, and a larger result is a `413` error. Use HTTP for larger transfers, such as big files. diff --git a/docs/openapi/berth.asyncapi.json b/docs/openapi/berth.asyncapi.json index c30793d..69f9478 100644 --- a/docs/openapi/berth.asyncapi.json +++ b/docs/openapi/berth.asyncapi.json @@ -108,6 +108,36 @@ "x-berth-level": "host", "x-berth-resumable": true }, + "host.port": { + "address": "/v1/hosts/{name}/ports/{port}", + "bindings": { + "ws": { + "query": { + "properties": {}, + "type": "object" + } + } + }, + "description": "A TCP connection to a port on the host's loopback, 127.0.0.1. The port is dialled first, so one that nothing listens on is an error and not a stream.", + "messages": { + "host.port.bytes": { + "$ref": "#/components/messages/host.port.bytes" + }, + "host.port.eof": { + "$ref": "#/components/messages/host.port.eof" + } + }, + "parameters": { + "name": { + "description": "name" + }, + "port": { + "description": "port" + } + }, + "x-berth-level": "host", + "x-berth-resumable": false + }, "host.serve": { "address": "/v1/hosts/{name}/services/{service}/serve", "bindings": { @@ -533,6 +563,30 @@ }, "summary": "One journal entry." }, + "host.port.bytes": { + "contentType": "application/octet-stream", + "name": "bytes", + "payload": { + "format": "binary", + "type": "string" + }, + "summary": "Bytes for the program on the port." + }, + "host.port.eof": { + "contentType": "application/json", + "examples": [ + { + "payload": { + "eof": true + } + } + ], + "name": "eof", + "payload": { + "type": "object" + }, + "summary": "The client sends no more, and the program on the port reads the end. What it sends still comes back." + }, "host.serve.call": { "contentType": "application/json", "examples": [ @@ -916,6 +970,34 @@ } ] }, + "host.port.receive": { + "action": "receive", + "channel": { + "$ref": "#/channels/host.port" + }, + "messages": [ + { + "$ref": "#/channels/host.port/messages/host.port.bytes" + }, + { + "$ref": "#/channels/host.port/messages/host.port.eof" + } + ] + }, + "host.port.send": { + "action": "send", + "channel": { + "$ref": "#/channels/host.port" + }, + "messages": [ + { + "$ref": "#/channels/host.port/messages/host.port.bytes" + }, + { + "$ref": "#/channels/host.port/messages/host.port.eof" + } + ] + }, "host.serve.receive": { "action": "receive", "channel": { diff --git a/docs/openapi/berth.openapi.json b/docs/openapi/berth.openapi.json index f198071..3725279 100644 --- a/docs/openapi/berth.openapi.json +++ b/docs/openapi/berth.openapi.json @@ -3971,6 +3971,50 @@ ] } }, + "/v1/hosts/{name}/ports/{port}": { + "get": { + "description": "Host level only.", + "operationId": "host_get_v1_ports__port_", + "parameters": [ + { + "description": "A saved host", + "in": "path", + "name": "name", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "path", + "name": "port", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "101": { + "description": "With a WebSocket handshake: the stream `port` of the AsyncAPI document." + }, + "default": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "An error." + } + }, + "summary": "Only as a WebSocket: a TCP connection to a port on the host's loopback. A port that nothing listens on is an error before the handshake.", + "tags": [ + "host: ports" + ] + } + }, "/v1/hosts/{name}/power/{verb}": { "post": { "description": "Host level only.", diff --git a/docs/openapi/berthd.asyncapi.json b/docs/openapi/berthd.asyncapi.json index ebe4ad0..531cc34 100644 --- a/docs/openapi/berthd.asyncapi.json +++ b/docs/openapi/berthd.asyncapi.json @@ -62,6 +62,33 @@ "x-berth-level": "host", "x-berth-resumable": true }, + "port": { + "address": "/v1/ports/{port}", + "bindings": { + "ws": { + "query": { + "properties": {}, + "type": "object" + } + } + }, + "description": "A TCP connection to a port on the host's loopback, 127.0.0.1. The port is dialled first, so one that nothing listens on is an error and not a stream.", + "messages": { + "port.bytes": { + "$ref": "#/components/messages/port.bytes" + }, + "port.eof": { + "$ref": "#/components/messages/port.eof" + } + }, + "parameters": { + "port": { + "description": "port" + } + }, + "x-berth-level": "host", + "x-berth-resumable": false + }, "serve": { "address": "/v1/services/{service}/serve", "bindings": { @@ -205,6 +232,30 @@ }, "summary": "One journal entry." }, + "port.bytes": { + "contentType": "application/octet-stream", + "name": "bytes", + "payload": { + "format": "binary", + "type": "string" + }, + "summary": "Bytes for the program on the port." + }, + "port.eof": { + "contentType": "application/json", + "examples": [ + { + "payload": { + "eof": true + } + } + ], + "name": "eof", + "payload": { + "type": "object" + }, + "summary": "The client sends no more, and the program on the port reads the end. What it sends still comes back." + }, "serve.call": { "contentType": "application/json", "examples": [ @@ -405,6 +456,34 @@ } ] }, + "port.receive": { + "action": "receive", + "channel": { + "$ref": "#/channels/port" + }, + "messages": [ + { + "$ref": "#/channels/port/messages/port.bytes" + }, + { + "$ref": "#/channels/port/messages/port.eof" + } + ] + }, + "port.send": { + "action": "send", + "channel": { + "$ref": "#/channels/port" + }, + "messages": [ + { + "$ref": "#/channels/port/messages/port.bytes" + }, + { + "$ref": "#/channels/port/messages/port.eof" + } + ] + }, "serve.receive": { "action": "receive", "channel": { diff --git a/docs/openapi/berthd.openapi.json b/docs/openapi/berthd.openapi.json index 5da3811..f95f483 100644 --- a/docs/openapi/berthd.openapi.json +++ b/docs/openapi/berthd.openapi.json @@ -1808,6 +1808,41 @@ ] } }, + "/v1/ports/{port}": { + "get": { + "description": "Host level only.", + "operationId": "get_v1_ports__port_", + "parameters": [ + { + "in": "path", + "name": "port", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "101": { + "description": "With a WebSocket handshake: the stream `port` of the AsyncAPI document." + }, + "default": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "An error." + } + }, + "summary": "Only as a WebSocket: a TCP connection to a port on the host's loopback. A port that nothing listens on is an error before the handshake.", + "tags": [ + "ports" + ] + } + }, "/v1/power/{verb}": { "post": { "description": "Host level only.", diff --git a/docs/openapi/berthd.operations.json b/docs/openapi/berthd.operations.json index 9720f93..697af14 100644 --- a/docs/openapi/berthd.operations.json +++ b/docs/openapi/berthd.operations.json @@ -2650,6 +2650,60 @@ } ], "summary": "For the program that answers a service's calls. While it is open the service is up." + }, + { + "args": [ + { + "description": "A TCP port on the host's loopback, 127.0.0.1: a number from 1 to 65535.", + "in": "path", + "name": "port", + "required": true + } + ], + "group": "ports", + "http": { + "method": "GET", + "path": "/v1/ports/{port}" + }, + "kind": "stream", + "level": "Host level only.", + "name": "ports.connect", + "portal": true, + "receives": [ + { + "binary": true, + "description": "What the program on the port sent.", + "example": null, + "name": "bytes" + }, + { + "binary": false, + "description": "The program on the port closed its side. Bytes sent towards it still arrive. The stream ends once both sides have sent this.", + "example": { + "eof": true + }, + "name": "eof" + } + ], + "resumable": false, + "role": "operate", + "sends": [ + { + "binary": true, + "description": "Bytes for the program on the port.", + "example": null, + "name": "bytes" + }, + { + "binary": false, + "description": "The client sends no more, and the program on the port reads the end. What it sends still comes back.", + "example": { + "eof": true + }, + "name": "eof" + } + ], + "summary": "A TCP connection to a port on the host's loopback, 127.0.0.1. The port is dialled first, so one that nothing listens on is an error and not a stream." } ], "portal": { diff --git a/docs/scripts/reference.mjs b/docs/scripts/reference.mjs index 17160a0..3f7efda 100644 --- a/docs/scripts/reference.mjs +++ b/docs/scripts/reference.mjs @@ -38,6 +38,7 @@ const groups = { processes: ['Processes', 'The processes of the host.'], channel: ['Channel', 'Messages between programs on the host and berth.'], services: ['Services', 'Programs of plugins that answer calls.'], + ports: ['Ports', "TCP connections to ports on the host's loopback."], setup_key: ['Setup key', 'Collecting the token with a short-lived key, after an install.'], hosts: ['Hosts', 'The hosts berth serve knows, their profiles, and what can be done to each.'], actions: ['Actions', 'What can be done to the installation as a whole, such as a roll-out.'], From f3140bc660d9c7a8942ca5bc6882fb10bb1366ac Mon Sep 17 00:00:00 2001 From: Helight Date: Sat, 14 Nov 2026 23:57:17 +0100 Subject: [PATCH 08/94] feat(api): raise the API number to 2 --- crates/berth-api/src/lib.rs | 2 +- docs/content/docs/api/index.mdx | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/berth-api/src/lib.rs b/crates/berth-api/src/lib.rs index 4f1a3a6..b84b4db 100644 --- a/crates/berth-api/src/lib.rs +++ b/crates/berth-api/src/lib.rs @@ -28,7 +28,7 @@ const _: () = assert!( "BERTH_BUILD_VERSION is a version such as 0.3.0, without the v of its tag" ); /// Rises when something is added to the API. -pub const API: u32 = 1; +pub const API: u32 = 2; /// Where berthd listens in system mode. pub const RUN_DIR: &str = "/run/berth"; diff --git a/docs/content/docs/api/index.mdx b/docs/content/docs/api/index.mdx index 253abf5..e29da33 100644 --- a/docs/content/docs/api/index.mdx +++ b/docs/content/docs/api/index.mdx @@ -27,6 +27,15 @@ Every operation page shows the portal frame and the HTTP request side by side. A *call* takes arguments and input and gives back a result. After it opens, a *stream* keeps sending frames, such as a session's output or new channel messages, and some streams take frames back, such as typed input. On the portal a stream is a subscription. See [Streams](/docs/extend/streams) for what all streams have in common. +## The API number + +`version` answers with `api`, a number that rises when something is added to the API. A client compares it to see what a host or a server can do. In `berth serve`, `hosts.list` gives each host's number too. + +| `api` | Added | +| --- | --- | +| 1 | The API as first released | +| 2 | `ports.connect` with windows on the portal's streams, roles from the keys of an object claim, the `dropped` frame of `events.follow`, `inbox.follow` and `kv.follow`, and host and resource changes on `events.follow` | + ## Who may call berthd answers on two sockets, and each operation says which may use it: From d286b9bfe72f8b098db4f6674445a91d4178323f Mon Sep 17 00:00:00 2001 From: Helight Date: Sun, 15 Nov 2026 00:12:24 +0100 Subject: [PATCH 09/94] refactor!: a host has a type, not a level The levels reachable, controller and workstation become the types ssh, managed and workstation, in profiles, the API, the screens and the commands (berth host type, --type). The role still records a managed host as level controller; berthd and berth read that, and berth reads the version of a berthd of API 1. --- .agents/skills/install-berth/SKILL.md | 6 +- crates/berth-api/src/profile.rs | 101 ++++----- crates/berth-api/src/types.rs | 138 +++++++++--- crates/berth-core/src/apply.rs | 31 ++- .../berth-core/src/{level.rs => host_type.rs} | 205 ++++++++++-------- crates/berth-core/src/lib.rs | 2 +- crates/berth-core/src/link.rs | 8 + crates/berth-core/src/profiles.rs | 12 +- crates/berth-core/src/provision.rs | 9 +- crates/berth-core/src/rollout.rs | 28 +-- crates/berth-core/src/seed.rs | 2 +- crates/berth-page/src/app.rs | 24 +- crates/berth-page/src/setup.rs | 16 +- crates/berth-tui/src/fields.rs | 30 +-- crates/berth-tui/src/host.rs | 62 +++--- crates/berth-tui/src/setup.rs | 36 +-- crates/berth/src/app.rs | 86 ++++---- crates/berth/src/commands.rs | 116 +++++----- crates/berth/src/main.rs | 17 +- crates/berth/src/remote.rs | 2 +- crates/berth/src/serve/actions.rs | 42 ++-- crates/berth/src/serve/api.rs | 33 +-- crates/berth/src/serve/mod.rs | 3 +- crates/berth/src/serve/setup.rs | 4 +- crates/berth/src/serve/tests.rs | 33 ++- crates/berth/src/ui.rs | 48 ++-- crates/berthd/src/http.rs | 15 +- docs/content/docs/(guide)/deploy/ssh.mdx | 2 +- docs/content/docs/(guide)/extend/serve.mdx | 6 +- .../docs/(guide)/reference/profile.mdx | 8 +- docs/content/docs/(guide)/start/concepts.mdx | 3 +- docs/content/docs/(guide)/use/cli.mdx | 8 +- docs/content/docs/(guide)/use/meta.json | 2 +- docs/content/docs/(guide)/use/moving.mdx | 2 +- docs/content/docs/(guide)/use/overview.mdx | 4 +- .../(guide)/use/{levels.mdx => types.mdx} | 54 ++--- docs/openapi/berth.openapi.json | 40 ++-- docs/openapi/berth.operations.json | 40 ++-- docs/openapi/berthd.openapi.json | 22 +- docs/openapi/berthd.operations.json | 22 +- .../roles/devbox/files/tasks/status.sh | 2 +- recipes/incus-host/README.md | 4 +- tests/e2e/e2e_adopt.py | 2 +- tests/e2e/e2e_controller.py | 29 +-- 44 files changed, 724 insertions(+), 635 deletions(-) rename crates/berth-core/src/{level.rs => host_type.rs} (61%) rename docs/content/docs/(guide)/use/{levels.mdx => types.mdx} (56%) diff --git a/.agents/skills/install-berth/SKILL.md b/.agents/skills/install-berth/SKILL.md index 69bc080..68c594e 100644 --- a/.agents/skills/install-berth/SKILL.md +++ b/.agents/skills/install-berth/SKILL.md @@ -14,7 +14,7 @@ terminal. A set-up has these pieces: | --- | --- | | `berth` client | The program on the user's machine. It has a terminal UI and commands. | | berth server | Optional. `berth serve`, usually in a Docker container, reached over a tailnet with TLS. It keeps the hosts, profiles and secrets. | -| Host | A machine berth works with, at one of three levels. `reachable` means berth only logs in, `controller` adds berthd and box, and `workstation` is set up from a profile. A machine that exists is added with `berth host add NAME ADDRESS --user USER`. | +| Host | A machine berth reaches and logs in to. Its type is one of three: `ssh` means berth only logs in, `managed` adds berthd and box, and `workstation` is set up from a profile. A machine that exists is added with `berth host add NAME ADDRESS --user USER`. | | Provisioner | Creates the machine for a host, such as on Docker or Incus. Plugins bring the types `docker/container`, `incus/vm` and `incus/container`, and berth runs each provisioner under a name of its own, registered with `berth provisioner add NAME TYPE`. The `incus-host` recipe registers `incus-vm`, `incus-container` and `docker`. `berth provisioner` lists them, and the Provisioners tab of the terminal UI (key `2`) shows each one's page. | ## Where to look things up @@ -24,7 +24,7 @@ terminal. A set-up has these pieces: | `README.md` | Installing the client | | `docs/content/docs/(guide)/start/quick-start.mdx` | A first host from the terminal UI | | `docs/content/docs/(guide)/use/server.mdx` | Running a server and connecting to it | -| `docs/content/docs/(guide)/use/levels.mdx` | Host levels, and adding a machine by its address | +| `docs/content/docs/(guide)/use/types.mdx` | Host types, and adding a machine by its address | | `docs/content/docs/(guide)/use/store.mdx` | Where a server keeps its state, and restoring it | | `docs/content/docs/(guide)/deploy/index.mdx` | The install methods | | `docs/content/docs/(guide)/deploy/provisioners.mdx` | Creating a host's machine with a provisioner | @@ -107,7 +107,7 @@ berth host add big 192.0.2.20 --user root --auth ssh berth host install big ``` -`host add` saves a reachable host. The default `--auth berth` uses berth's own +`host add` saves a host of the type `ssh`. The default `--auth berth` uses berth's own key, which berth installs on first contact with a password or a private key that logs in once. `--auth ssh` uses the user's own SSH configuration and agent, and works with a local berth only. `host install` puts the controller alone on the diff --git a/crates/berth-api/src/profile.rs b/crates/berth-api/src/profile.rs index e365eef..005ffe4 100644 --- a/crates/berth-api/src/profile.rs +++ b/crates/berth-api/src/profile.rs @@ -61,7 +61,7 @@ pub fn operator(config: &Value) -> &str { pub fn settle_after_apply(config: &mut Value) -> bool { let mut access = Access::of(config); if config["profile"] == "container" - || level(config) != crate::HostLevel::Workstation + || host_type(config) != crate::HostType::Workstation || access.link.is_some() || access.user.is_empty() || access.user != operator(config) @@ -295,67 +295,68 @@ impl Access { } } -/// The level a profile means its host to have: `level`, a workstation when -/// it does not say, so profiles from before levels keep their meaning. -pub fn level(config: &Value) -> crate::HostLevel { - config["level"] +/// The type a profile means its host to be: `type`, a workstation when it +/// does not say, so profiles from before types keep their meaning. +pub fn host_type(config: &Value) -> crate::HostType { + config["type"] .as_str() - .and_then(crate::HostLevel::parse) + .and_then(crate::HostType::parse) .unwrap_or_default() } -/// Set the level a profile means its host to have. A workstation is left -/// unsaid, as profiles from before levels are. -pub fn set_level(config: &mut Value, level: crate::HostLevel) { +/// Set the type a profile means its host to be. A workstation is left +/// unsaid, as profiles from before types are. +pub fn set_host_type(config: &mut Value, host_type: crate::HostType) { if !config.is_object() { *config = json!({}); } - match level { - crate::HostLevel::Workstation => { + match host_type { + crate::HostType::Workstation => { if let Some(profile) = config.as_object_mut() { - profile.remove("level"); + profile.remove("type"); } } - other => config["level"] = json!(other.name()), + other => config["type"] = json!(other.name()), } } -/// The profile of a host berth only reaches or only controls: its level and -/// how it is reached, nothing of a workstation. -pub fn minimal(level: crate::HostLevel, access: &Access) -> Value { +/// The profile of a host berth only logs in to or only manages: its type +/// and how it is reached, nothing of a workstation. +pub fn minimal(host_type: crate::HostType, access: &Access) -> Value { let mut config = json!({}); - set_level(&mut config, level); + set_host_type(&mut config, host_type); access.write(&mut config); config } -/// What is wrong with a profile as a whole, in sentences: its level, its +/// What is wrong with a profile as a whole, in sentences: its type, its /// `access`, and for a workstation the `builder` its set-up keeps. A host -/// of a lower level needs only to be reachable. +/// of another type needs only to be reachable. pub fn problems(config: &Value) -> Vec { if !config.is_object() { return vec!["A profile is an object".into()]; } let mut problems = vec![]; - let level = match &config["level"] { - Value::Null => Some(crate::HostLevel::Workstation), - Value::String(text) => crate::HostLevel::parse(text), + let host_type = match &config["type"] { + Value::Null => Some(crate::HostType::Workstation), + Value::String(text) => crate::HostType::parse(text), _ => None, }; - let Some(level) = level else { + let Some(host_type) = host_type else { return vec![format!( - "level is reachable, controller or workstation, not {}", - config["level"] + "type is {}, not {}", + crate::HostType::choices(), + config["type"] )]; }; problems.extend(Access::problems(config)); - match level { - crate::HostLevel::Workstation if !config["builder"].is_object() => { + match host_type { + crate::HostType::Workstation if !config["builder"].is_object() => { problems.push("A workstation's profile has a builder object".into()) } - crate::HostLevel::Workstation => {} + crate::HostType::Workstation => {} _ if !Access::of(config).reachable() => problems.push(format!( - "A {level} host needs access.address, where berth reaches it" + "A host of the type {host_type} needs access.address, where berth reaches it" )), _ => {} } @@ -505,7 +506,7 @@ mod tests { for bad in ["-oProxyCommand=touch /tmp/x;#", "a b", "a@b", "a\tb"] { assert!(!valid_user(bad), "{bad}"); } - let problems = |access: Value| problems(&json!({"level": "reachable", "access": access})); + let problems = |access: Value| problems(&json!({"type": "ssh", "access": access})); assert!(problems(json!({"address": "192.0.2.10", "user": "ops"})).is_empty()); assert_eq!(problems(json!({"address": "-oProxyCommand=x"})).len(), 1); assert_eq!( @@ -580,12 +581,12 @@ mod tests { let mut named = json!({"operator_username": "admin", "builder": {}, "access": {"user": "admin", "sudo": "password"}}); assert!(settle_after_apply(&mut named)); assert!(!asks_become_pass(&named)); - // A container has no operator, and a host below a workstation was not set up by berth. + // A container has no operator, and a host of another type was not set up by berth. let mut container = json!({"profile": "container", "access": {"user": "ops", "sudo": "password"}}); assert!(!settle_after_apply(&mut container)); - let mut controller = json!({"level": "controller", "access": {"address": "192.0.2.4", "user": "ops", "sudo": "password"}}); - assert!(!settle_after_apply(&mut controller)); + let mut managed = json!({"type": "managed", "access": {"address": "192.0.2.4", "user": "ops", "sudo": "password"}}); + assert!(!settle_after_apply(&mut managed)); } #[test] @@ -652,36 +653,36 @@ mod tests { } #[test] - fn a_profile_without_a_level_is_a_workstation() { - use crate::HostLevel; - assert_eq!(level(&json!({"builder": {}})), HostLevel::Workstation); + fn a_profile_without_a_type_is_a_workstation() { + use crate::HostType; + assert_eq!(host_type(&json!({"builder": {}})), HostType::Workstation); + assert_eq!(host_type(&json!({"type": "managed"})), HostType::Managed); + // One berth does not know reads as the default, and is named a problem. + assert_eq!(host_type(&json!({"type": "server"})), HostType::Workstation); assert_eq!( - level(&json!({"level": "controller"})), - HostLevel::Controller + problems(&json!({"type": "server"})), + ["type is ssh, managed or workstation, not \"server\""] ); - // One berth does not know reads as the default, and is named a problem. - assert_eq!(level(&json!({"level": "server"})), HostLevel::Workstation); - assert!(problems(&json!({"level": "server"}))[0].contains("not \"server\"")); let access = Access { address: "192.0.2.10".into(), user: "ops".into(), ..Access::default() }; - let reachable = minimal(HostLevel::Reachable, &access); + let ssh = minimal(HostType::Ssh, &access); assert_eq!( - reachable, - json!({"level": "reachable", "access": {"address": "192.0.2.10", "user": "ops", "auth": "berth"}}) + ssh, + json!({"type": "ssh", "access": {"address": "192.0.2.10", "user": "ops", "auth": "berth"}}) ); - assert!(problems(&reachable).is_empty()); - // Only a workstation needs the set-up's part; a lower level needs an address. + assert!(problems(&ssh).is_empty()); + // Only a workstation needs the set-up's part; another type needs an address. assert_eq!( problems(&json!({"access": {"address": "studio"}})), ["A workstation's profile has a builder object"] ); - assert!(problems(&json!({"level": "controller"}))[0].contains("access.address")); - let mut changed = reachable.clone(); - set_level(&mut changed, HostLevel::Workstation); - assert!(changed.get("level").is_none()); + assert!(problems(&json!({"type": "managed"}))[0].contains("access.address")); + let mut changed = ssh.clone(); + set_host_type(&mut changed, HostType::Workstation); + assert!(changed.get("type").is_none()); } #[test] diff --git a/crates/berth-api/src/types.rs b/crates/berth-api/src/types.rs index 27b615c..45c15d1 100644 --- a/crates/berth-api/src/types.rs +++ b/crates/berth-api/src/types.rs @@ -44,15 +44,33 @@ pub struct Version { /// recorded it. An older berthd does not say. #[serde(default, skip_serializing_if = "Option::is_none")] pub applied: Option, - /// What was installed on the host, by that record: `controller` when + /// What was installed on the host, by that record: `managed` when /// only the controller was, `workstation` for a whole profile. Absent /// when the host keeps no record. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub level: Option, + #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] + pub host_type: Option, +} + +impl Version { + /// A berthd's answer to `version`. A berthd of API 1 named the type + /// `level`, with the values `reachable`, `controller` and + /// `workstation`; its answer is read as this API's. + pub fn from_reply(mut reply: serde_json::Value) -> serde_json::Result { + if let Some(object) = reply.as_object_mut() + && !object.contains_key("type") + && let Some(level) = object.remove("level") + { + let converted = level.as_str().and_then(HostType::from_level); + if let Some(host_type) = converted { + object.insert("type".into(), serde_json::json!(host_type.name())); + } + } + serde_json::from_value(reply) + } } -/// How much of berth a host has: what its profile means it to have, or -/// what it was seen to have. Each level can do what the ones before it can. +/// What berth does with a host: what its profile means it to be, or what it +/// was seen to be. They are in the order of how much of berth each has. #[derive( Debug, Clone, @@ -68,49 +86,66 @@ pub struct Version { ToSchema, )] #[serde(rename_all = "lowercase")] -pub enum HostLevel { +pub enum HostType { /// berth logs in over SSH. Nothing of berth is installed. - Reachable, - /// berthd and box are installed and answer: sessions, tasks and files. - Controller, + Ssh, + /// berthd and box are installed and answer: sessions, actions and files. + Managed, /// The whole profile is applied: desktop, agents and plugins. #[default] Workstation, } -impl HostLevel { - pub const ALL: [HostLevel; 3] = [ - HostLevel::Reachable, - HostLevel::Controller, - HostLevel::Workstation, - ]; +impl HostType { + pub const ALL: [HostType; 3] = [HostType::Ssh, HostType::Managed, HostType::Workstation]; pub fn name(self) -> &'static str { match self { - HostLevel::Reachable => "reachable", - HostLevel::Controller => "controller", - HostLevel::Workstation => "workstation", + HostType::Ssh => "ssh", + HostType::Managed => "managed", + HostType::Workstation => "workstation", } } - pub fn parse(text: &str) -> Option { - HostLevel::ALL + pub fn parse(text: &str) -> Option { + HostType::ALL .into_iter() - .find(|level| level.name() == text.trim()) + .find(|host_type| host_type.name() == text.trim()) } - /// What a host of this level has, in a few words that fit a line - /// beside the level on a narrow page. + /// The names of the types, as a sentence says them: `a, b or c`. + pub fn choices() -> String { + let names: Vec<&str> = HostType::ALL.iter().map(|t| t.name()).collect(); + match names.split_last() { + Some((last, [])) => (*last).to_owned(), + Some((last, rest)) => format!("{} or {last}", rest.join(", ")), + None => String::new(), + } + } + + /// The type a value of the `level` that profiles and berthd had before + /// types stands for. + pub fn from_level(level: &str) -> Option { + match level.trim() { + "reachable" => Some(HostType::Ssh), + "controller" => Some(HostType::Managed), + "workstation" => Some(HostType::Workstation), + _ => None, + } + } + + /// What a host of this type has, in a few words that fit a line + /// beside the type on a narrow page. pub fn describe(self) -> &'static str { match self { - HostLevel::Reachable => "SSH only, nothing of berth installed", - HostLevel::Controller => "berthd alone: sessions, tasks, files", - HostLevel::Workstation => "the whole profile", + HostType::Ssh => "SSH only, nothing of berth installed", + HostType::Managed => "berthd alone: sessions, actions, files", + HostType::Workstation => "the whole profile", } } } -impl std::fmt::Display for HostLevel { +impl std::fmt::Display for HostType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.name()) } @@ -118,18 +153,14 @@ impl std::fmt::Display for HostLevel { /// What to say when a host is seen to be more than its profile here says, /// with how to adopt it: as when a workstation is added by its address. -pub fn level_mismatch( - name: &str, - intended: HostLevel, - observed: Option, -) -> Option { +pub fn type_mismatch(name: &str, intended: HostType, observed: Option) -> Option { let observed = observed.filter(|observed| *observed > intended)?; Some(match observed { - HostLevel::Workstation => format!( + HostType::Workstation => format!( "{name} is a workstation; its profile here says {intended}. To adopt it from the profile it keeps: berth adopt {name}" ), _ => format!( - "{name} has berth's controller; its profile here says {intended}. To adopt it: berth host level {name} controller" + "{name} has berth's controller; its profile here says {intended}. To adopt it: berth host type {name} managed" ), }) } @@ -1498,3 +1529,42 @@ pub struct RolloutReport { /// Every host is done or current. pub ok: bool, } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn a_host_type_is_named_and_parsed() { + for host_type in HostType::ALL { + assert_eq!(HostType::parse(host_type.name()), Some(host_type)); + assert_eq!(json!(host_type), json!(host_type.name())); + } + assert_eq!(HostType::choices(), "ssh, managed or workstation"); + assert_eq!(HostType::parse("controller"), None); + assert_eq!(HostType::from_level("reachable"), Some(HostType::Ssh)); + assert_eq!(HostType::from_level("controller"), Some(HostType::Managed)); + assert_eq!(HostType::from_level("ssh"), None); + } + + #[test] + fn the_version_of_an_older_berthd_is_read_with_its_type() { + let old = json!({"version": "0.5.1", "api": 1, "mode": "system", "level": "controller"}); + let version = Version::from_reply(old).unwrap(); + assert_eq!(version.host_type, Some(HostType::Managed)); + let new = json!({"version": "0.6.0", "api": 2, "type": "ssh"}); + assert_eq!( + Version::from_reply(new).unwrap().host_type, + Some(HostType::Ssh) + ); + let without = json!({"version": "0.5.1", "api": 1}); + assert_eq!(Version::from_reply(without).unwrap().host_type, None); + // What a berthd says now is written with the name of this API. + let written = json!( + Version::from_reply(json!({"version": "1", "api": 2, "level": "workstation"})).unwrap() + ); + assert_eq!(written["type"], "workstation"); + assert!(written.get("level").is_none()); + } +} diff --git a/crates/berth-core/src/apply.rs b/crates/berth-core/src/apply.rs index 1ba056b..3bf022a 100644 --- a/crates/berth-core/src/apply.rs +++ b/crates/berth-core/src/apply.rs @@ -113,7 +113,7 @@ pub fn playbook(source: &std::path::Path) -> Command { /// host that asks for a password is asked for on the terminal. Only a /// workstation is applied: every way to apply comes through here. pub fn prepare(paths: &Paths, host: &Host, become_password: Option<&str>) -> Result { - crate::level::guard(host, crate::level::Capability::Apply)?; + crate::host_type::guard(host, crate::host_type::Capability::Apply)?; let source = paths.source()?; let plugins = plugins::load(&[source.join("plugins"), paths.config_dir.join("plugins")]); let dirs = plugin_dirs(&plugins); @@ -136,15 +136,16 @@ pub fn prepare(paths: &Paths, host: &Host, become_password: Option<&str>) -> Res Ok(prepared) } -/// The Ansible run that puts berth's controller alone on a host below a -/// workstation: berthd and box, what they read, and the record of what was -/// installed. The SSH user is the account sessions run as. +/// The Ansible run that puts berth's controller alone on a host that is not +/// a workstation: berthd and box, what they read, and the record of what +/// was installed. The SSH user is the account sessions run as. pub fn prepare_controller( paths: &Paths, host: &Host, become_password: Option<&str>, ) -> Result { - crate::level::guard(host, crate::level::Capability::InstallController)?; + crate::host_type::guard(host, crate::host_type::Capability::InstallController)?; + // The role calls the type managed by its older name. let mut vars = json!({ "devbox_level": "controller", "devbox_berth_applied": {"berth": berth_api::VERSION, "plugins": []}, @@ -254,7 +255,7 @@ const CONTROLLER_PATIENCE: std::time::Duration = std::time::Duration::from_secs( /// Install berth's controller alone on a host from where berth runs, its /// output to `out`, and wait for it to answer: whether all went well. A -/// reachable host becomes a controller in its profile once the controller +/// host of the type ssh becomes managed in its profile once the controller /// is there. pub fn install_controller( paths: &Paths, @@ -268,9 +269,9 @@ pub fn install_controller( }; // The profile here may say less than the host is, as for a workstation // added by its address; the role refuses it too. - let intended = crate::level::of(&host.config); + let intended = crate::host_type::of(&host.config); let asked = crate::keys::refusal::now(); - let observed = crate::level::observe(paths, host, become_password); + let observed = crate::host_type::observe(paths, host, become_password); // A host that refused the login just now would refuse Ansible's too. if observed.is_none() && let Ok(login) = crate::keys::login_of(paths, host) @@ -279,7 +280,7 @@ pub fn install_controller( { return fail(out, &refused.sentence(&host.name, refused.at)); } - if let Some(why) = crate::level::refuse_install(&host.name, intended, observed) { + if let Some(why) = crate::host_type::refuse_install(&host.name, intended, observed) { return fail(out, &why); } let prepared = match prepare_controller(paths, host, become_password) { @@ -301,16 +302,16 @@ pub fn install_controller( } None => return fail(out, &"Installing the controller was ended by a signal"), } - if crate::level::of(&host.config) != crate::level::Level::Controller { + if crate::host_type::of(&host.config) != crate::host_type::HostType::Managed { let mut config = host.config.clone(); - berth_api::profile::set_level(&mut config, crate::level::Level::Controller); + berth_api::profile::set_host_type(&mut config, crate::host_type::HostType::Managed); if let Err(error) = host.place.save(paths, &config) { return fail( out, &format!("The controller is installed, but the profile was not saved: {error}"), ); } - let _ = writeln!(out, "✓ {} is a controller host now", host.name); + let _ = writeln!(out, "✓ {} is a managed host now", host.name); } match answers(paths, host, become_password) { Ok(version) => { @@ -339,11 +340,7 @@ fn answers(paths: &Paths, host: &Host, password: Option<&str>) -> Result let started = std::time::Instant::now(); loop { let asked = runtime.block_on(async { - tokio::time::timeout( - std::time::Duration::from_secs(15), - link.get::("/v1/version"), - ) - .await + tokio::time::timeout(std::time::Duration::from_secs(15), link.version()).await }); match asked { Ok(Ok(version)) => return Ok(version.version), diff --git a/crates/berth-core/src/level.rs b/crates/berth-core/src/host_type.rs similarity index 61% rename from crates/berth-core/src/level.rs rename to crates/berth-core/src/host_type.rs index 829b457..f6f1c12 100644 --- a/crates/berth-core/src/level.rs +++ b/crates/berth-core/src/host_type.rs @@ -1,12 +1,12 @@ -//! What a host can do at each of its levels, and the one check that every -//! client asks before it offers or runs something: the UIs, the commands -//! and the server's API. A host's level is what its profile says it is -//! meant to be; what it is seen to be comes from asking it. +//! What a host of each type can do, and the one check that every client +//! asks before it offers or runs something: the UIs, the commands and the +//! server's API. A host's type is what its profile says it is meant to be; +//! what it is seen to be comes from asking it. use crate::{Result, host::Host}; use berth_api::{Action, Version, ops::Role}; -pub use berth_api::HostLevel as Level; +pub use berth_api::HostType; /// Something berth can do with a host. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -17,11 +17,11 @@ pub enum Capability { InstallController, /// Sessions, the channel, files, units, logs and processes. Sessions, - /// The controller's tasks: status, update and reboot. - Tasks, + /// The controller's actions: status, update and reboot. + Actions, /// Secrets and registry logins sent to the host. Secrets, - /// Plugin features, their tasks and services. + /// Plugin features, their actions and services. Plugins, /// Applying the profile, a roll-out over it, a seed or an installer image. Apply, @@ -34,7 +34,7 @@ impl Capability { Capability::Ssh, Capability::InstallController, Capability::Sessions, - Capability::Tasks, + Capability::Actions, Capability::Secrets, Capability::Plugins, Capability::Apply, @@ -46,7 +46,7 @@ impl Capability { Capability::Ssh => "ssh", Capability::InstallController => "install-controller", Capability::Sessions => "sessions", - Capability::Tasks => "tasks", + Capability::Actions => "actions", Capability::Secrets => "secrets", Capability::Plugins => "plugins", Capability::Apply => "apply", @@ -60,7 +60,7 @@ impl Capability { Capability::Ssh => "a terminal over SSH", Capability::InstallController => "installing the controller alone", Capability::Sessions => "working with sessions, the channel and files", - Capability::Tasks => "running the controller's tasks", + Capability::Actions => "running the controller's actions", Capability::Secrets => "sending secrets and registry logins", Capability::Plugins => "using plugin features", Capability::Apply => "applying a profile, a roll-out, a seed or an installer", @@ -68,38 +68,40 @@ impl Capability { } } - /// Whether a host of `level` has it. The controller alone is installed - /// on a host below a workstation; a workstation's comes with applying. - pub fn allowed(self, level: Level) -> bool { + /// Whether a host of `host_type` has it. The controller alone is + /// installed on a host that is not a workstation; a workstation's comes + /// with applying. + pub fn allowed(self, host_type: HostType) -> bool { + use HostType::*; match self { Capability::Ssh => true, - Capability::InstallController => level != Level::Workstation, - Capability::Sessions | Capability::Tasks | Capability::Secrets => { - level >= Level::Controller + Capability::InstallController => matches!(host_type, Ssh | Managed), + Capability::Sessions | Capability::Actions | Capability::Secrets => { + matches!(host_type, Managed | Workstation) } Capability::Plugins | Capability::Apply | Capability::Desktop => { - level == Level::Workstation + host_type == Workstation } } } } -/// The capabilities and the levels that have each, in the order of -/// [`Level::ALL`]: for a page that shows the table. +/// The capabilities and the types that have each, in the order of +/// [`HostType::ALL`]: for a page that shows the table. pub fn table() -> Vec<(Capability, [bool; 3])> { Capability::ALL .into_iter() .map(|capability| { ( capability, - Level::ALL.map(|level| capability.allowed(level)), + HostType::ALL.map(|host_type| capability.allowed(host_type)), ) }) .collect() } /// Why something cannot be done with a host now, and the action that -/// raises its level so it can. +/// changes its type so it can. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Refusal { pub why: String, @@ -116,28 +118,32 @@ impl std::fmt::Display for Refusal { impl std::error::Error for Refusal {} -/// Whether the host `name` of `level` may do this, or why not. -pub fn check(name: &str, level: Level, capability: Capability) -> std::result::Result<(), Refusal> { - if capability.allowed(level) { +/// Whether the host `name` of `host_type` may do this, or why not. +pub fn check( + name: &str, + host_type: HostType, + capability: Capability, +) -> std::result::Result<(), Refusal> { + if capability.allowed(host_type) { return Ok(()); } let what = capability.label(); - Err(match (capability, level) { + Err(match (capability, host_type) { (Capability::InstallController, _) => Refusal { why: format!( "{name} is a workstation: applying its configuration installs and updates its controller. Apply it with: berth apply {name}" ), raise: "apply", }, - (_, Level::Reachable) if capability.allowed(Level::Controller) => Refusal { + (_, HostType::Ssh) if capability.allowed(HostType::Managed) => Refusal { why: format!( - "{name} is reachable only: berth's controller is not installed there, and {what} needs it. Install it with: berth host install {name}" + "{name} is a host of the type ssh: berth's controller is not installed there, and {what} needs it. Install it with: berth host install {name}" ), raise: "install-controller", }, _ => Refusal { why: format!( - "{name} is a {level} host, not a workstation: {what} needs its whole profile. Set its level to workstation in its set-up, then apply it" + "{name} is a host of the type {host_type}, not a workstation: {what} needs its whole profile. Set its type to workstation in its set-up, then apply it" ), raise: "setup", }, @@ -150,15 +156,15 @@ pub fn guard(host: &Host, capability: Capability) -> Result<()> { Ok(()) } -/// The level a profile means its host to have. -pub fn of(config: &serde_json::Value) -> Level { - berth_api::profile::level(config) +/// The type a profile means its host to be. +pub fn of(config: &serde_json::Value) -> HostType { + berth_api::profile::host_type(config) } -/// An action as a host of `level` may run it: unavailable, with the reason, -/// when the level rules it out. -pub fn fit(mut action: Action, name: &str, level: Level, capability: Capability) -> Action { - if let Err(refusal) = check(name, level, capability) { +/// An action as a host of `host_type` may run it: unavailable, with the +/// reason, when the type rules it out. +pub fn fit(mut action: Action, name: &str, host_type: HostType, capability: Capability) -> Action { + if let Err(refusal) = check(name, host_type, capability) { action.available = false; action.why = refusal.why; } @@ -166,26 +172,30 @@ pub fn fit(mut action: Action, name: &str, level: Level, capability: Capability) } /// What a host was seen to be by asking its controller: what its record -/// says when it answers, reachable when berth logged in and found no +/// says when it answers, ssh when berth logged in and found no /// controller, nothing when it could not be asked. -pub fn seen(answer: std::result::Result<&Version, bool>) -> Option { +pub fn seen(answer: std::result::Result<&Version, bool>) -> Option { match answer { // A controller without a record was installed outside berth. - Ok(version) => Some(version.level.unwrap_or(Level::Controller)), - Err(true) => Some(Level::Reachable), + Ok(version) => Some(version.host_type.unwrap_or(HostType::Managed)), + Err(true) => Some(HostType::Ssh), Err(false) => None, } } -pub use berth_api::level_mismatch as mismatch; +pub use berth_api::type_mismatch as mismatch; /// Why installing the controller alone must not run on a host seen to be a /// workstation, whatever its profile says: it would take the workstation's /// controller apart. -pub fn refuse_install(name: &str, intended: Level, observed: Option) -> Option { +pub fn refuse_install( + name: &str, + intended: HostType, + observed: Option, +) -> Option { match (intended, observed) { - (Level::Workstation, _) | (_, None) => None, - (_, Some(Level::Workstation)) => Some(format!( + (HostType::Workstation, _) | (_, None) => None, + (_, Some(HostType::Workstation)) => Some(format!( "{} Installing the controller alone would take its controller apart, so it is not offered", mismatch(name, intended, observed).unwrap_or_default() )), @@ -195,15 +205,15 @@ pub fn refuse_install(name: &str, intended: Level, observed: Option) -> O /// What the host's controller says the host is, asked through the link /// once and briefly: `None` when no controller answers. -pub fn observe(paths: &crate::paths::Paths, host: &Host, password: Option<&str>) -> Option { +pub fn observe( + paths: &crate::paths::Paths, + host: &Host, + password: Option<&str>, +) -> Option { let link = crate::link::Link::new(host.link(paths, password).ok()?); let runtime = crate::link::runtime().ok()?; let asked = runtime.block_on(async { - tokio::time::timeout( - std::time::Duration::from_secs(15), - link.get::("/v1/version"), - ) - .await + tokio::time::timeout(std::time::Duration::from_secs(15), link.version()).await }); runtime.shutdown_background(); match asked { @@ -213,17 +223,21 @@ pub fn observe(paths: &crate::paths::Paths, host: &Host, password: Option<&str>) } /// berth's own action that puts the controller on a host, as a host of -/// `level` sees it. `observed` is what its controller says it is, when it -/// answered. -pub fn install_controller_action(name: &str, level: Level, observed: Option) -> Action { - let (label, help) = match level { - Level::Controller => ( +/// `host_type` sees it. `observed` is what its controller says it is, when +/// it answered. +pub fn install_controller_action( + name: &str, + host_type: HostType, + observed: Option, +) -> Action { + let (label, help) = match host_type { + HostType::Managed => ( "Update the controller", "Install berthd and box of this berth on the host again, and restart the controller: for example after berth was updated. Nothing else of the profile is applied.", ), _ => ( "Install the controller", - "Put berthd and box on the host and start the controller, so that sessions, tasks and files work there. Nothing else of a workstation is installed: no desktop, agents or plugins. The SSH user is the account sessions run as. The host's level becomes controller.", + "Put berthd and box on the host and start the controller, so that sessions, actions and files work there. Nothing else of a workstation is installed: no desktop, agents or plugins. The SSH user is the account sessions run as. The host's type becomes managed.", ), }; let action = Action { @@ -235,15 +249,15 @@ pub fn install_controller_action(name: &str, level: Level, observed: Option Action { Action { @@ -275,10 +289,10 @@ pub fn rename_action() -> Action { } /// berth's own actions on a host of this machine, which need no server: -/// those that change the host's level, and renaming it. -pub fn local_actions(name: &str, level: Level, observed: Option) -> Vec { +/// those that change the host's type, and renaming it. +pub fn local_actions(name: &str, host_type: HostType, observed: Option) -> Vec { vec![ - install_controller_action(name, level, observed), + install_controller_action(name, host_type, observed), rename_action(), ] } @@ -288,11 +302,11 @@ mod tests { use super::*; #[test] - fn each_level_can_do_what_the_ones_below_it_can() { + fn each_type_can_do_what_the_ones_before_it_can() { use Capability::*; let rows: Vec<(&str, [bool; 3])> = table() .into_iter() - .map(|(capability, levels)| (capability.name(), levels)) + .map(|(capability, types)| (capability.name(), types)) .collect(); assert_eq!( rows, @@ -300,7 +314,7 @@ mod tests { (Ssh.name(), [true, true, true]), (InstallController.name(), [true, true, false]), (Sessions.name(), [false, true, true]), - (Tasks.name(), [false, true, true]), + (Actions.name(), [false, true, true]), (Secrets.name(), [false, true, true]), (Plugins.name(), [false, false, true]), (Apply.name(), [false, false, true]), @@ -310,19 +324,23 @@ mod tests { } #[test] - fn a_refusal_names_the_action_that_raises_the_level() { - let refused = check("studio", Level::Reachable, Capability::Sessions).unwrap_err(); + fn a_refusal_names_the_action_that_changes_the_type() { + let refused = check("studio", HostType::Ssh, Capability::Sessions).unwrap_err(); assert_eq!(refused.raise, "install-controller"); assert!(refused.why.contains("berth host install studio")); - let refused = check("studio", Level::Reachable, Capability::Apply).unwrap_err(); + let refused = check("studio", HostType::Ssh, Capability::Apply).unwrap_err(); assert_eq!(refused.raise, "setup"); - assert!(refused.why.contains("a reachable host, not a workstation")); - let refused = check("studio", Level::Controller, Capability::Desktop).unwrap_err(); + assert!(refused.why.contains("of the type ssh, not a workstation")); + let refused = check("studio", HostType::Managed, Capability::Desktop).unwrap_err(); assert_eq!(refused.raise, "setup"); - let refused = - check("studio", Level::Workstation, Capability::InstallController).unwrap_err(); + let refused = check( + "studio", + HostType::Workstation, + Capability::InstallController, + ) + .unwrap_err(); assert_eq!(refused.raise, "apply"); - assert!(check("studio", Level::Workstation, Capability::Apply).is_ok()); + assert!(check("studio", HostType::Workstation, Capability::Apply).is_ok()); } #[test] @@ -332,50 +350,49 @@ mod tests { place: crate::profiles::Place::File("/dock.json".into()), config, }; - let reachable = - host(serde_json::json!({"level": "reachable", "access": {"address": "192.0.2.4"}})); - let refused = guard(&reachable, Capability::Apply).unwrap_err(); + let ssh = host(serde_json::json!({"type": "ssh", "access": {"address": "192.0.2.4"}})); + let refused = guard(&ssh, Capability::Apply).unwrap_err(); assert!(refused.to_string().contains("not a workstation")); assert!(guard(&host(serde_json::json!({"builder": {}})), Capability::Apply).is_ok()); } #[test] fn what_a_host_is_seen_to_be_comes_from_its_controller() { - let version = |level| Version { + let version = |host_type| Version { version: "1".into(), - api: 1, + api: 2, mode: "system".into(), applied: None, - level, + host_type, }; - assert_eq!(seen(Ok(&version(None))), Some(Level::Controller)); + assert_eq!(seen(Ok(&version(None))), Some(HostType::Managed)); assert_eq!( - seen(Ok(&version(Some(Level::Workstation)))), - Some(Level::Workstation) + seen(Ok(&version(Some(HostType::Workstation)))), + Some(HostType::Workstation) ); - assert_eq!(seen(Err(true)), Some(Level::Reachable)); + assert_eq!(seen(Err(true)), Some(HostType::Ssh)); assert_eq!(seen(Err(false)), None); } #[test] - fn installing_the_controller_is_offered_below_a_workstation() { - let action = install_controller_action("dock", Level::Reachable, None); + fn installing_the_controller_is_offered_to_a_host_that_is_not_a_workstation() { + let action = install_controller_action("dock", HostType::Ssh, None); assert!(action.available && action.label == "Install the controller"); assert_eq!( - install_controller_action("dock", Level::Controller, None).label, + install_controller_action("dock", HostType::Managed, None).label, "Update the controller" ); - let action = install_controller_action("dock", Level::Workstation, None); + let action = install_controller_action("dock", HostType::Workstation, None); assert!(!action.available && action.why.contains("berth apply dock")); // A controller seen to be one is updated as its profile says. - let action = install_controller_action("dock", Level::Reachable, Some(Level::Controller)); + let action = install_controller_action("dock", HostType::Ssh, Some(HostType::Managed)); assert!(action.available); } #[test] fn a_host_seen_to_be_a_workstation_never_gets_the_controller_alone() { - for intended in [Level::Reachable, Level::Controller] { - let action = install_controller_action("dock", intended, Some(Level::Workstation)); + for intended in [HostType::Ssh, HostType::Managed] { + let action = install_controller_action("dock", intended, Some(HostType::Workstation)); assert!(!action.available); assert!( action.why.starts_with(&format!( @@ -387,10 +404,10 @@ mod tests { assert!(action.why.contains("berth adopt dock")); } assert_eq!( - mismatch("dock", Level::Reachable, Some(Level::Controller)).unwrap(), - "dock has berth's controller; its profile here says reachable. To adopt it: berth host level dock controller" + mismatch("dock", HostType::Ssh, Some(HostType::Managed)).unwrap(), + "dock has berth's controller; its profile here says ssh. To adopt it: berth host type dock managed" ); - assert!(mismatch("dock", Level::Workstation, Some(Level::Controller)).is_none()); - assert!(mismatch("dock", Level::Controller, None).is_none()); + assert!(mismatch("dock", HostType::Workstation, Some(HostType::Managed)).is_none()); + assert!(mismatch("dock", HostType::Managed, None).is_none()); } } diff --git a/crates/berth-core/src/lib.rs b/crates/berth-core/src/lib.rs index 1f84c7d..4f95715 100644 --- a/crates/berth-core/src/lib.rs +++ b/crates/berth-core/src/lib.rs @@ -5,12 +5,12 @@ pub mod apply; pub mod credentials; pub mod discovery; pub mod host; +pub mod host_type; pub mod import; pub mod job; pub mod kept; pub mod kept_profile; pub mod keys; -pub mod level; pub mod link; pub mod paths; pub mod plugin_state; diff --git a/crates/berth-core/src/link.rs b/crates/berth-core/src/link.rs index e1b104a..98a91f0 100644 --- a/crates/berth-core/src/link.rs +++ b/crates/berth-core/src/link.rs @@ -284,6 +284,14 @@ impl Link { self.call("GET", path, None).await } + /// What the host's controller says of itself, read as this API says it + /// also from a berthd of an older API. + pub async fn version(&self) -> client::Result { + let reply: Value = self.get("/v1/version").await?; + berth_api::Version::from_reply(reply) + .map_err(|error| Error::Transport(format!("version: {error}"))) + } + pub async fn post(&self, path: &str, body: &Value) -> client::Result { self.call("POST", path, Some(body)).await } diff --git a/crates/berth-core/src/profiles.rs b/crates/berth-core/src/profiles.rs index ab6a504..8c609b6 100644 --- a/crates/berth-core/src/profiles.rs +++ b/crates/berth-core/src/profiles.rs @@ -232,10 +232,10 @@ pub fn remove(paths: &Paths, place: &Place) -> Result<()> { /// Whether a rename may give the host's profile the new name as its /// hostname: only a workstation is applied, which is what sets it. pub fn hostname_allowed(name: &str, profile: &Value) -> Result<()> { - match crate::level::of(profile) { - crate::level::Level::Workstation => Ok(()), - level => Err(format!( - "{name} is a {level} host, and only a workstation is given its hostname by berth" + match crate::host_type::of(profile) { + crate::host_type::HostType::Workstation => Ok(()), + host_type => Err(format!( + "{name} is a host of the type {host_type}, and only a workstation is given its hostname by berth" ) .into()), } @@ -543,12 +543,12 @@ mod tests { let dock = Place::own("dock").unwrap(); dock.save( &paths, - &json!({"level": "reachable", "access": {"address": "192.0.2.30"}}), + &json!({"type": "ssh", "access": {"address": "192.0.2.30"}}), ) .unwrap(); assert_eq!( error(rename(&paths, &dock, "pier", true)), - "dock is a reachable host, and only a workstation is given its hostname by berth" + "dock is a host of the type ssh, and only a workstation is given its hostname by berth" ); assert!(dock.load(&paths).unwrap().is_some()); let file = Place::File(home.path().join("attic.json")); diff --git a/crates/berth-core/src/provision.rs b/crates/berth-core/src/provision.rs index b6d9536..d0fb669 100644 --- a/crates/berth-core/src/provision.rs +++ b/crates/berth-core/src/provision.rs @@ -1083,13 +1083,8 @@ fn answers(paths: &Paths, host: &Host) -> bool { }; let link = Link::new(spec); // The timer is made inside the runtime, which is what it runs on. - let asked = runtime.block_on(async { - tokio::time::timeout( - Duration::from_secs(20), - link.get::("/v1/version"), - ) - .await - }); + let asked = runtime + .block_on(async { tokio::time::timeout(Duration::from_secs(20), link.version()).await }); runtime.shutdown_background(); matches!(asked, Ok(Ok(_))) } diff --git a/crates/berth-core/src/rollout.rs b/crates/berth-core/src/rollout.rs index 5ffa715..aaf62a0 100644 --- a/crates/berth-core/src/rollout.rs +++ b/crates/berth-core/src/rollout.rs @@ -246,9 +246,9 @@ pub fn chosen(all: Vec, asked: &[String]) -> Result> { /// The hosts a roll-out applies, and the names of those it leaves because /// they are not workstations: only a workstation is applied. pub fn workstations(hosts: Vec) -> (Vec, Vec) { - let (taken, left): (Vec, Vec) = hosts - .into_iter() - .partition(|host| crate::level::of(&host.config) == crate::level::Level::Workstation); + let (taken, left): (Vec, Vec) = hosts.into_iter().partition(|host| { + crate::host_type::of(&host.config) == crate::host_type::HostType::Workstation + }); (taken, left.into_iter().map(|host| host.name).collect()) } @@ -325,10 +325,7 @@ impl Target for Live<'_> { } fn version(&mut self) -> std::result::Result, String> { - match self - .runtime - .block_on(self.link.get::("/v1/version")) - { + match self.runtime.block_on(self.link.version()) { Ok(version) => Ok(Some(version)), Err(error) if Link::missing(&error) => Ok(None), Err(error) => Err(error.to_string()), @@ -471,13 +468,10 @@ pub fn survey(paths: &Paths) -> Vec { if link.refused().is_some() { return None; } - let version = tokio::time::timeout( - std::time::Duration::from_secs(20), - link.get::("/v1/version"), - ) - .await - .ok()? - .ok()?; + let version = tokio::time::timeout(std::time::Duration::from_secs(20), link.version()) + .await + .ok()? + .ok()?; Some((host.name.clone(), version)) }, ))); @@ -529,7 +523,7 @@ mod tests { api: api::API, mode: "system".into(), applied: self.applied.clone(), - level: None, + host_type: None, })) } fn apply(&mut self, _out: &mut dyn Write) -> std::result::Result<(), String> { @@ -835,8 +829,8 @@ mod tests { }; let (taken, skipped) = workstations(vec![ host("studio", json!({"builder": {}})), - host("dock", json!({"level": "controller"})), - host("pier", json!({"level": "reachable"})), + host("dock", json!({"type": "managed"})), + host("pier", json!({"type": "ssh"})), ]); assert_eq!(taken.len(), 1); assert_eq!(taken[0].name, "studio"); diff --git a/crates/berth-core/src/seed.rs b/crates/berth-core/src/seed.rs index 01d7dc8..b81c57b 100644 --- a/crates/berth-core/src/seed.rs +++ b/crates/berth-core/src/seed.rs @@ -34,7 +34,7 @@ pub struct Archive { pub fn cloud(paths: &Paths, store: &Store, name: &str, delivered: bool) -> Result { let host = Host::load(paths, name)?; // A seed installs a whole workstation. - crate::level::guard(&host, crate::level::Capability::Apply)?; + crate::host_type::guard(&host, crate::host_type::Capability::Apply)?; let source = paths.source()?; let dirs = apply::plugin_dirs(&plugins::found( &source, diff --git a/crates/berth-page/src/app.rs b/crates/berth-page/src/app.rs index e37b057..fe180c2 100644 --- a/crates/berth-page/src/app.rs +++ b/crates/berth-page/src/app.rs @@ -545,13 +545,13 @@ impl App { self.address, device::shown(&self.server) ))); - for line in host::level_lines(&self.name, &self.host) { + for line in host::type_lines(&self.name, &self.host) { rows.push(Row::info(Line::styled( format!(" {line}"), Style::new().fg(theme::MUTED), ))); } - let workstation = self.host.level == berth_api::HostLevel::Workstation; + let workstation = self.host.host_type == berth_api::HostType::Workstation; let said = match &self.host.state { State::Ready(_) => { if let Some(text) = host::behind_note(&self.host) { @@ -587,10 +587,10 @@ impl App { State::Idle | State::Connecting | State::Password => { vec![note("Asking the host what it can do…".into(), theme::MUTED)] } - // Below a workstation the controller is installed alone, by berth's own action. + // On a host that is not a workstation the controller is installed alone, by berth's own action. State::Missing if !workstation => vec![ note( - "berth's controller is not on this host. Install it for sessions, tasks and files here.".into(), + "berth's controller is not on this host. Install it for sessions, actions and files here.".into(), theme::MUTED, ), again(), @@ -722,12 +722,10 @@ impl App { self.host.disconnect(); let listed = self.hosts.borrow(); let found = listed.list.iter().find(|host| host["name"] == name); - let level = |key: &str| { - found - .and_then(|host| host[key].as_str()) - .and_then(berth_api::HostLevel::parse) - }; - self.host.level = level("level").unwrap_or_default(); + self.host.host_type = found + .and_then(|host| host["type"].as_str()) + .and_then(berth_api::HostType::parse) + .unwrap_or_default(); drop(listed); self.host.own.clear(); if let Some(admin) = &self.admin { @@ -1356,11 +1354,11 @@ impl App { if host["behind"].is_object() { line.push(Span::styled(" behind", Style::new().fg(theme::WARN))); } - if let Some(level) = host["level"] + if let Some(host_type) = host["type"] .as_str() - .filter(|level| *level != "workstation") + .filter(|host_type| *host_type != "workstation") { - line.push(Span::styled(format!(" {level}"), muted)); + line.push(Span::styled(format!(" {host_type}"), muted)); } if host["rotating"] == true { line.push(Span::styled( diff --git a/crates/berth-page/src/setup.rs b/crates/berth-page/src/setup.rs index a27a6fb..b420ee0 100644 --- a/crates/berth-page/src/setup.rs +++ b/crates/berth-page/src/setup.rs @@ -265,10 +265,10 @@ impl Setup { Some(Entry::Feature(index)) => self.features[index].help.clone(), Some(Entry::Registry(_)) => setup::REGISTRY_HELP.into(), Some(Entry::Secret(_)) => setup::SECRET_HELP.into(), - Some(Entry::Run) => match (self.action, berth_api::profile::level(&self.config)) { + Some(Entry::Run) => match (self.action, berth_api::profile::host_type(&self.config)) { (Action::CloudSeed, _) => "Saves the profile on the server and renders the seed. Paste it into the provider's user data field when creating the machine.".into(), - (Action::Ssh, berth_api::HostLevel::Reachable) => "Saves the host on the server. Nothing is installed: the server logs in to it over SSH, with a key of its own that the host takes.".into(), - (Action::Ssh, berth_api::HostLevel::Controller) => "Saves the profile on the server and installs berth's controller alone on the host from there.".into(), + (Action::Ssh, berth_api::HostType::Ssh) => "Saves the host on the server. Nothing is installed: the server logs in to it over SSH, with a key of its own that the host takes.".into(), + (Action::Ssh, berth_api::HostType::Managed) => "Saves the profile on the server and installs berth's controller alone on the host from there.".into(), _ => "Saves the profile on the server and applies it to the host from there.".into(), }, Some(Entry::Machine(pick)) => self.machine.help(pick), @@ -429,20 +429,20 @@ impl Setup { return Some("Fix the listed problems first".into()); } let (name, action, size) = (self.name.clone(), self.action, self.panel); - // Over SSH a host below a workstation gets the controller alone, or nothing. - let level = berth_api::profile::level(&self.config); + // Over SSH a host that is not a workstation gets the controller alone, or nothing. + let host_type = berth_api::profile::host_type(&self.config); let install = berth_api::Action { name: "install-controller".into(), label: "Install the controller".into(), ..berth_api::Action::default() }; admin.save(&self.name, &self.config, move |admin| { - match (action, level) { + match (action, host_type) { (Action::CloudSeed, _) => admin.seed(&name), - (Action::Ssh, berth_api::HostLevel::Controller) => { + (Action::Ssh, berth_api::HostType::Managed) => { admin.act(&name, &install, &Default::default(), size) } - (Action::Ssh, berth_api::HostLevel::Reachable) => {} + (Action::Ssh, berth_api::HostType::Ssh) => {} _ => admin.apply(&name, None, size), } }); diff --git a/crates/berth-tui/src/fields.rs b/crates/berth-tui/src/fields.rs index 7a7e82e..bd85f8c 100644 --- a/crates/berth-tui/src/fields.rs +++ b/crates/berth-tui/src/fields.rs @@ -8,8 +8,8 @@ pub const DISK_TYPES: &[&str] = &["any", "ssd", "hdd"]; /// The ways to log in that are not a key of the ring; `key:NAME` is offered /// for each of those. pub const LOGINS: &[&str] = &["berth", "password", "ssh"]; -/// The levels a host can be meant to have, the whole profile first. -pub const LEVELS: &[&str] = &["workstation", "controller", "reachable"]; +/// The types a host can be meant to be, the whole profile first. +pub const TYPES: &[&str] = &["workstation", "managed", "ssh"]; /// The pages of a host: its overview (`Manage`) and the tabs of the set-up /// flow. Each tab depends only on the ones before it. @@ -75,7 +75,7 @@ pub const TASKS: &[(&str, &str, &str)] = &[ ( "install-controller", "Install the controller", - "Put berthd and box on the host and start berth's controller, so that sessions, tasks and files work there, without the rest of a workstation. The host's level becomes controller. Continues in the terminal. From the command line: `berth host install HOST`.", + "Put berthd and box on the host and start berth's controller, so that sessions, actions and files work there, without the rest of a workstation. The host's type becomes managed. Continues in the terminal. From the command line: `berth host install HOST`.", ), ( "ssh", @@ -98,7 +98,7 @@ pub enum Action { Docker, Ssh, /// An existing host berth only logs in to: a way offered on the Install - /// tab that chooses [`Action::Ssh`] at the level reachable. + /// tab that chooses [`Action::Ssh`] for a host of the type ssh. Reach, Manage, } @@ -115,18 +115,18 @@ impl Action { Action::Docker, ]; - /// The action a way of the Install tab sets, with the level it gives the + /// The action a way of the Install tab sets, with the type it gives the /// profile when it gives one. pub fn choose(self, config: &mut serde_json::Value) -> Action { - let level = berth_api::profile::level(config); + let host_type = berth_api::profile::host_type(config); match self { Action::Reach => { - berth_api::profile::set_level(config, berth_api::HostLevel::Reachable); + berth_api::profile::set_host_type(config, berth_api::HostType::Ssh); Action::Ssh } // Installing over SSH installs something: the whole profile, unless the controller is chosen. - Action::Ssh if level == berth_api::HostLevel::Reachable => { - berth_api::profile::set_level(config, berth_api::HostLevel::Workstation); + Action::Ssh if host_type == berth_api::HostType::Ssh => { + berth_api::profile::set_host_type(config, berth_api::HostType::Workstation); Action::Ssh } action => action, @@ -269,7 +269,7 @@ pub enum Field { SshUser, SshPort, Login, - Level, + Type, } impl Field { @@ -571,11 +571,11 @@ impl Field { Choice(LOGINS), "How berth logs in. berth: the installation's own key, which hosts it sets up take. key:NAME: another key of berth's key ring (the Settings tab of the home screen lists them). password: a password, kept as the secret ssh/HOST or asked for. ssh: your own SSH configuration and agent, with berth's key offered after them. A host that does not take its key yet gets it with: berth key trust HOST.", ), - Level => ( - "Level", - "/level", - Choice(LEVELS), - "How much of berth the host gets. workstation: the whole profile, with the desktop, the agents and plugins. controller: berthd and box alone, for sessions, tasks and files on a machine that stays as it is. reachable: nothing is installed; berth logs in over SSH. A lower level can be raised later: install the controller, or set workstation and apply.", + Type => ( + "Type", + "/type", + Choice(TYPES), + "What berth does with the host. workstation: the whole profile, with the desktop, the agents and plugins. managed: berthd and box alone, for sessions, actions and files on a machine that stays as it is. ssh: nothing is installed; berth logs in over SSH. The type can change later: install the controller, or set workstation and apply.", ), UsbDevice => ( "Then write to USB drive", diff --git a/crates/berth-tui/src/host.rs b/crates/berth-tui/src/host.rs index 2ac3a92..2d73fde 100644 --- a/crates/berth-tui/src/host.rs +++ b/crates/berth-tui/src/host.rs @@ -235,10 +235,10 @@ pub struct HostView { pub stats: Option, /// What changed since the host was applied, when berth knows. pub behind: Option, - /// The level the host's profile means it to have. - pub level: api::HostLevel, - /// The level the host was seen to have, once it was asked. - pub seen: Option, + /// The type the host's profile means it to be. + pub host_type: api::HostType, + /// The type the host was seen to be, once it was asked. + pub seen: Option, /// berth's own actions on the host, beside its tasks: what a berth /// server lists for its host, or what this berth does itself. pub own: Vec, @@ -263,7 +263,7 @@ impl Default for HostView { sessions: vec![], stats: None, behind: None, - level: api::HostLevel::Workstation, + host_type: api::HostType::Workstation, seen: None, own: vec![], view: None, @@ -468,7 +468,7 @@ impl HostView { } Event::Version(version) => { // A controller without a record was installed outside berth. - self.seen = Some(version.level.unwrap_or(api::HostLevel::Controller)); + self.seen = Some(version.host_type.unwrap_or(api::HostType::Managed)); self.state = State::Ready(version.version); } Event::Failed { message, missing } => { @@ -480,7 +480,7 @@ impl HostView { self.state = State::Password; note = Some("sudo on the host did not take that password".to_owned()); } else if missing { - self.seen = Some(api::HostLevel::Reachable); + self.seen = Some(api::HostType::Ssh); self.state = State::Missing; } else if message.contains("a password is required") { self.state = State::Password; @@ -646,13 +646,13 @@ pub fn groups(host: &HostView, terminal_user: &str) -> Vec<(String, Vec<(String, groups } -/// The line the overview shows of the host's level, with what the host +/// The line the overview shows of the host's type, with what the host /// itself was seen to be when that is different. -pub fn level_line(name: &str, host: &HostView) -> String { - let mut line = format!("Level · {} ({})", host.level, host.level.describe()); - if let Some(said) = api::level_mismatch(name, host.level, host.seen) { +pub fn type_line(name: &str, host: &HostView) -> String { + let mut line = format!("Type · {} ({})", host.host_type, host.host_type.describe()); + if let Some(said) = api::type_mismatch(name, host.host_type, host.seen) { line += &format!(". {said}"); - } else if let Some(seen) = host.seen.filter(|seen| *seen != host.level) { + } else if let Some(seen) = host.seen.filter(|seen| *seen != host.host_type) { line += &format!(". The host itself is {seen} now"); } line @@ -662,9 +662,9 @@ pub fn level_line(name: &str, host: &HostView) -> String { /// the page beside the information box. pub const NOTE_WIDTH: usize = 64; -/// [`level_line`], wrapped to the overview's width. -pub fn level_lines(name: &str, host: &HostView) -> Vec { - crate::screen::wrap(&level_line(name, host), NOTE_WIDTH) +/// [`type_line`], wrapped to the overview's width. +pub fn type_lines(name: &str, host: &HostView) -> Vec { + crate::screen::wrap(&type_line(name, host), NOTE_WIDTH) } /// What the overview says of a host whose configuration is behind. @@ -781,32 +781,32 @@ mod tests { } #[test] - fn the_level_line_says_what_the_host_was_seen_to_be() { + fn the_type_line_says_what_the_host_was_seen_to_be() { let mut host = HostView { - level: api::HostLevel::Reachable, + host_type: api::HostType::Ssh, ..HostView::default() }; assert_eq!( - level_line("studio", &host), - "Level · reachable (SSH only, nothing of berth installed)" + type_line("studio", &host), + "Type · ssh (SSH only, nothing of berth installed)" ); - host.seen = Some(api::HostLevel::Reachable); - assert!(!level_line("studio", &host).contains("now")); + host.seen = Some(api::HostType::Ssh); + assert!(!type_line("studio", &host).contains("now")); // One seen to be more than its profile says names how to adopt it. - host.seen = Some(api::HostLevel::Workstation); + host.seen = Some(api::HostType::Workstation); assert!( - level_line("studio", &host) - .contains("studio is a workstation; its profile here says reachable. To adopt it"), + type_line("studio", &host) + .contains("studio is a workstation; its profile here says ssh. To adopt it"), "{}", - level_line("studio", &host) + type_line("studio", &host) ); - host.level = api::HostLevel::Workstation; - host.seen = Some(api::HostLevel::Controller); - assert!(level_line("studio", &host).ends_with("The host itself is controller now")); + host.host_type = api::HostType::Workstation; + host.seen = Some(api::HostType::Managed); + assert!(type_line("studio", &host).ends_with("The host itself is managed now")); // Wrapped, every line fits the overview beside the information box. - host.level = api::HostLevel::Reachable; - host.seen = Some(api::HostLevel::Workstation); - let lines = level_lines("studio", &host); + host.host_type = api::HostType::Ssh; + host.seen = Some(api::HostType::Workstation); + let lines = type_lines("studio", &host); assert!(lines.len() > 1); assert!( lines.iter().all(|line| line.chars().count() <= NOTE_WIDTH), diff --git a/crates/berth-tui/src/setup.rs b/crates/berth-tui/src/setup.rs index df8b5bd..c99bac7 100644 --- a/crates/berth-tui/src/setup.rs +++ b/crates/berth-tui/src/setup.rs @@ -536,7 +536,7 @@ impl<'a> Profile<'a> { .unwrap_or(""); match (field, text) { (Field::Login, "") => "berth", - (Field::Level, "") => "workstation", + (Field::Type, "") => "workstation", _ => text, } } @@ -820,7 +820,7 @@ impl<'a> Profile<'a> { if self.locked() { return vec![]; } - vec![Level, SshHost, SshUser, SshPort, Login, AskBecomePass] + vec![Type, SshHost, SshUser, SshPort, Login, AskBecomePass] } /// The fields of the Install tab: those before the provisioner's rows, @@ -832,11 +832,11 @@ impl<'a> Profile<'a> { return (vec![], vec![]); } // A host below a workstation needs only to be reached. - let level = berth_api::profile::level(self.config); - if action == Action::Ssh && level != berth_api::HostLevel::Workstation { - let mut after = vec![Level, SshHost, SshUser, SshPort, Login]; - // Nothing is installed on a reachable host, so nothing asks for sudo. - if level == berth_api::HostLevel::Controller { + let host_type = berth_api::profile::host_type(self.config); + if action == Action::Ssh && host_type != berth_api::HostType::Workstation { + let mut after = vec![Type, SshHost, SshUser, SshPort, Login]; + // Nothing is installed on a host of the type ssh, so nothing asks for sudo. + if host_type == berth_api::HostType::Managed { after.push(AskBecomePass); } return (vec![], after); @@ -848,7 +848,7 @@ impl<'a> Profile<'a> { }; let mut after = vec![]; if action == Action::Ssh { - after.extend([Level, SshHost, SshUser, SshPort, Login, AskBecomePass]); + after.extend([Type, SshHost, SshUser, SshPort, Login, AskBecomePass]); } if action.installer() || action.seeds() { after.push(Hostname); @@ -1046,11 +1046,11 @@ impl<'a> Profile<'a> { rows } - /// The way of the Install tab the action and the profile's level are: - /// over SSH at the level reachable, the host is only logged in to. + /// The way of the Install tab the action and the profile's type are: + /// over SSH to a host of the type ssh, the host is only logged in to. pub fn way(&self) -> Action { - match (self.action, berth_api::profile::level(self.config)) { - (Action::Ssh, berth_api::HostLevel::Reachable) => Action::Reach, + match (self.action, berth_api::profile::host_type(self.config)) { + (Action::Ssh, berth_api::HostType::Ssh) => Action::Reach, (action, _) => action, } } @@ -1208,7 +1208,7 @@ impl<'a> Profile<'a> { pub fn problems_with(&self, machine: &crate::machine::Machine) -> Vec { // A host below a workstation is only reached: the workstation's settings do not apply. if self.action == Action::Ssh - && berth_api::profile::level(self.config) != berth_api::HostLevel::Workstation + && berth_api::profile::host_type(self.config) != berth_api::HostType::Workstation { return vec![]; } @@ -1842,7 +1842,7 @@ mod tests { fn an_existing_host_can_be_added_to_be_reached_over_ssh_alone() { let mut config = json!({"profile": "laptop"}); assert_eq!(Action::Reach.choose(&mut config), Action::Ssh); - assert_eq!(config["level"], "reachable"); + assert_eq!(config["type"], "ssh"); let machine = incus(); let profile = Profile { config: &config, @@ -1885,10 +1885,10 @@ mod tests { ); // Installing over SSH again means installing something. assert_eq!(Action::Ssh.choose(&mut config), Action::Ssh); - assert!(config.get("level").is_none()); - let mut controller = json!({"level": "controller"}); - Action::Ssh.choose(&mut controller); - assert_eq!(controller["level"], "controller"); + assert!(config.get("type").is_none()); + let mut managed = json!({"type": "managed"}); + Action::Ssh.choose(&mut managed); + assert_eq!(managed["type"], "managed"); } #[test] diff --git a/crates/berth/src/app.rs b/crates/berth/src/app.rs index 7d7849c..b8334fa 100644 --- a/crates/berth/src/app.rs +++ b/crates/berth/src/app.rs @@ -13,7 +13,7 @@ use crate::{ use berth_core::{ apply, host::Host, - level, + host_type, paths::{Paths, layout}, profiles::Place, }; @@ -190,9 +190,9 @@ pub struct App { pub renamed: Option, /// What the host's controller says the host is, asked in the background /// once its address is given on the set-up's Install tab. - found_level: Option>>, - /// The level was chosen on the Level row, so what the host says is only told. - level_chosen: bool, + found_type: Option>>, + /// The type was chosen on the Type row, so what the host says is only told. + type_chosen: bool, } /// What the provisioners there are, and the host's machine, came back as. @@ -309,8 +309,8 @@ impl App { own_answers: None, own_command: None, renamed: None, - found_level: None, - level_chosen: false, + found_type: None, + type_chosen: false, }; app.saved = app.config.clone(); app @@ -621,7 +621,7 @@ impl App { rows.push(Row::info("")); } rows.push(heading("Connection")); - for line in berth_tui::host::level_lines(&self.name(), &self.host) { + for line in berth_tui::host::type_lines(&self.name(), &self.host) { rows.push(Row::info(Line::styled( format!(" {line}"), Style::new().fg(theme::MUTED), @@ -653,7 +653,7 @@ impl App { // A host without its controller offers Apply above already; // only a workstation is applied. if !matches!(self.host.state, State::Missing | State::Old(_)) - && self.host.level == level::Level::Workstation + && self.host.host_type == host_type::HostType::Workstation { setup.push(Row::entry( " ▸ Apply this configuration", @@ -721,7 +721,7 @@ impl App { ]); } // Below a workstation the controller is installed alone. - State::Missing if self.host.level != level::Level::Workstation => { + State::Missing if self.host.host_type != host_type::HostType::Workstation => { let rows = vec![ note("berth's controller is not on this host. Install it for sessions, tasks and files here; berth reaches the host over SSH meanwhile.".into(), theme::MUTED), fixed("ssh"), @@ -735,8 +735,8 @@ impl App { ]); } State::Old(version) => { - let raise = match self.host.level { - level::Level::Workstation => "apply", + let raise = match self.host.host_type { + host_type::HostType::Workstation => "apply", _ => "install-controller", }; let mut rows = vec![note( @@ -783,8 +783,8 @@ impl App { true => self.agent_label().to_owned(), false => self.operator_label(), }; - let raise = match self.host.level { - level::Level::Workstation => "apply", + let raise = match self.host.host_type { + host_type::HostType::Workstation => "apply", _ => "install-controller", }; let behind = berth_tui::host::behind_note(&self.host).map(|text| { @@ -1360,8 +1360,8 @@ impl App { if field == Field::SshHost && !value.is_empty() { self.fill_from_ssh_config(value); } - if field == Field::Level { - self.level_chosen = true; + if field == Field::Type { + self.type_chosen = true; } // An existing host over SSH is asked what it is, as berth host add does. if matches!( @@ -1371,7 +1371,7 @@ impl App { && self.step != Step::Manage && !self.text(Field::SshHost).is_empty() { - self.ask_found_level(); + self.ask_found_type(); } if field == Field::WifiSsid && let Some(password) = self.saved_wifi_password().map(str::to_owned) @@ -1399,41 +1399,43 @@ impl App { } /// Ask the host's controller, in the background, what the host is. - fn ask_found_level(&mut self) { + fn ask_found_type(&mut self) { let (paths, host) = (self.paths.clone(), self.host_profile()); let (sender, receiver) = mpsc::channel(); std::thread::spawn(move || { - let _ = sender.send(level::observe(&paths, &host, None)); + let _ = sender.send(host_type::observe(&paths, &host, None)); }); - self.found_level = Some(receiver); + self.found_type = Some(receiver); } /// Take in what the host said it is, when it has. Called between events. - pub fn watch_found_level(&mut self) { - let Some(answer) = &self.found_level else { + pub fn watch_found_type(&mut self) { + let Some(answer) = &self.found_type else { return; }; if let Ok(found) = answer.try_recv() { - self.found_level = None; - self.offer_level(found); + self.found_type = None; + self.offer_type(found); } } - /// Offer the level the host was found to have: it is taken unless a - /// level was chosen on the Level row, which is only told of it. - pub fn offer_level(&mut self, found: Option) { - let current = level::of(&self.config); + /// Offer the type the host was found to be: it is taken unless a + /// type was chosen on the Type row, which is only told of it. + pub fn offer_type(&mut self, found: Option) { + let current = host_type::of(&self.config); let Some(found) = found.filter(|found| *found != current) else { return; }; let name = self.name(); - if self.level_chosen { - self.status = - format!("{name} answers as a {found} host; its Level here says {current}"); + if self.type_chosen { + self.status = format!( + "{name} answers as a host of the type {found}; its Type here says {current}" + ); return; } - berth_api::profile::set_level(&mut self.config, found); - self.status = format!("{name} answers as a {found} host, so its Level is {found} now"); + berth_api::profile::set_host_type(&mut self.config, found); + self.status = + format!("{name} answers as a host of the type {found}, so its Type is {found} now"); } /// Record the checksum of the chosen ISO so the build can detect a changed file. @@ -1607,7 +1609,8 @@ impl App { .collect(); } // A host below a workstation needs only to be reached. - if action == Action::Ssh && level::of(&self.config) != level::Level::Workstation { + if action == Action::Ssh && host_type::of(&self.config) != host_type::HostType::Workstation + { let access = self.host_profile().access(); return berth_core::keys::check(&access.address, &access.port) .err() @@ -1698,7 +1701,7 @@ impl App { /// password gets the dialog first, once. pub fn connect_host(&mut self) { let host = self.host_profile(); - self.host.level = level::of(&self.config); + self.host.host_type = host_type::of(&self.config); self.ask_own_actions(); let own_link = host.access().link.is_some() || host.served(&self.paths).is_some(); if host.asks_password() && !own_link && self.host.password.is_none() { @@ -1731,7 +1734,8 @@ impl App { fn ask_own_actions(&mut self) { let host = self.host_profile(); let Some(server) = host.served(&self.paths) else { - self.host.own = level::local_actions(&host.name, self.host.level, self.host.seen); + self.host.own = + host_type::local_actions(&host.name, self.host.host_type, self.host.seen); return; }; let (sender, receiver) = mpsc::channel(); @@ -1969,7 +1973,7 @@ impl App { let profile = seeded.as_ref().map(|file| file.path().to_owned()); let mut command; match action { - // Reach is only a way to choose, which sets Ssh at the level reachable. + // Reach is only a way to choose, which sets Ssh for a host of the type ssh. Action::Save | Action::Manage | Action::Machine | Action::Reach => { return Err("Nothing to run".into()); } @@ -2177,15 +2181,15 @@ impl App { } // Over SSH, a host below a workstation gets the controller alone, or nothing. if self.action == Action::Ssh { - match level::of(&self.config) { - level::Level::Workstation => {} - level::Level::Controller => { + match host_type::of(&self.config) { + host_type::HostType::Workstation => {} + host_type::HostType::Managed => { let words = ["host", "install", &self.place.argument()].map(str::to_owned); return self.run_own(&words); } - level::Level::Reachable => { + host_type::HostType::Ssh => { println!( - "Nothing is installed on a reachable host. If it does not take berth's key yet: berth key trust {}", + "Nothing is installed on a host of the type ssh. If it does not take berth's key yet: berth key trust {}", self.place.argument() ); return Ok(()); diff --git a/crates/berth/src/commands.rs b/crates/berth/src/commands.rs index d53060c..a7fc4cd 100644 --- a/crates/berth/src/commands.rs +++ b/crates/berth/src/commands.rs @@ -11,7 +11,7 @@ use berth_api::{ }; use berth_core::{ host::Host, - level, + host_type, link::{self, Link}, paths::Paths, profiles::Place, @@ -62,11 +62,11 @@ fn reach(paths: &Paths, name: &str) -> Result { }) } -/// The way to a host's controller, for what needs one: a host meant to be -/// only reachable is refused with the action that installs it. +/// The way to a host's controller, for what needs one: a host of the type +/// ssh is refused with the action that installs it. fn controlled(paths: &Paths, name: &str) -> Result { let reach = reach(paths, name)?; - level::guard(&reach.host, level::Capability::Sessions)?; + host_type::guard(&reach.host, host_type::Capability::Sessions)?; Ok(reach) } @@ -529,14 +529,14 @@ fn host_actions(paths: &Paths, reach: &Reach) -> Result<(Vec, Vec { - // A host that is only reachable has no controller to ask. - let host_level = level::of(&reach.host.config); - let tasks = match host_level { - level::Level::Reachable => vec![], + // A host of the type ssh has no controller to ask. + let host_type = host_type::of(&reach.host.config); + let tasks = match host_type { + host_type::HostType::Ssh => vec![], _ => host_tasks(reach)?, }; let mut actions = api::Action::of_tasks(&tasks); - let own = level::local_actions(&reach.host.name, host_level, observed(reach)); + let own = host_type::local_actions(&reach.host.name, host_type, observed(reach)); actions.retain(|action| !own.iter().any(|known| known.name == action.name)); actions.extend(own); Ok((actions, tasks)) @@ -545,18 +545,13 @@ fn host_actions(paths: &Paths, reach: &Reach) -> Result<(Vec, Vec Option { - if level::of(&reach.host.config) == level::Level::Workstation { +/// Only a host whose profile says it is not a workstation is asked. +fn observed(reach: &Reach) -> Option { + if host_type::of(&reach.host.config) == host_type::HostType::Workstation { return None; } let asked = reach.wait(async { - match tokio::time::timeout( - std::time::Duration::from_secs(15), - reach.link.get::("/v1/version"), - ) - .await - { + match tokio::time::timeout(std::time::Duration::from_secs(15), reach.link.version()).await { Ok(Ok(version)) => Ok(version), _ => Err(()), } @@ -564,14 +559,16 @@ fn observed(reach: &Reach) -> Option { asked .ok() .as_ref() - .and_then(|version| level::seen(Ok(version))) + .and_then(|version| host_type::seen(Ok(version))) } /// `berth tasks HOST`: what the host can do, by group. pub fn tasks(paths: &Paths, name: &str) -> Result<()> { let reach = reach(paths, name)?; let (actions, _) = host_actions(paths, &reach)?; - if let Some(said) = level::mismatch(name, level::of(&reach.host.config), observed(&reach)) { + if let Some(said) = + host_type::mismatch(name, host_type::of(&reach.host.config), observed(&reach)) + { println!("! {said}\n"); } let mut groups: Vec<(&str, Vec<&api::Action>)> = vec![]; @@ -726,7 +723,7 @@ pub fn install_controller(paths: &Paths, name: &str) -> Result<()> { /// Install the controller from here, holding the host's lock as an apply /// does: the exit code. fn install_controller_here(paths: &Paths, host: &Host) -> Result { - level::guard(host, level::Capability::InstallController)?; + host_type::guard(host, host_type::Capability::InstallController)?; let password = host.sudo_password(paths)?; let request = runner::Request { secrets: password.iter().cloned().collect(), @@ -748,16 +745,16 @@ fn install_controller_here(paths: &Paths, host: &Host) -> Result { Ok(code.unwrap_or(1)) } -/// `berth host level HOST LEVEL`: save the level the host's profile says, +/// `berth host type HOST TYPE`: save the type the host's profile says, /// such as for a workstation added by its address. Nothing on the host /// changes; a workstation's set-up then fills in the rest before an apply. -pub fn set_level(paths: &Paths, name: &str, given: &str) -> Result<()> { - let wanted = level::Level::parse(given) - .ok_or_else(|| format!("A level is reachable, controller or workstation, not {given}"))?; +pub fn set_type(paths: &Paths, name: &str, given: &str) -> Result<()> { + let wanted = host_type::HostType::parse(given) + .ok_or_else(|| format!("A type is {}, not {given}", host_type::HostType::choices()))?; let host = Host::load(paths, name)?; let mut profile = host.config.clone(); - api::profile::set_level(&mut profile, wanted); - if wanted == level::Level::Workstation && !profile["builder"].is_object() { + api::profile::set_host_type(&mut profile, wanted); + if wanted == host_type::HostType::Workstation && !profile["builder"].is_object() { profile["builder"] = json!({}); } match host.served(paths) { @@ -767,40 +764,39 @@ pub fn set_level(paths: &Paths, name: &str, given: &str) -> Result<()> { } None => host.place.save(paths, &profile)?, } - println!("{} is a {wanted} host now in its profile", host.name); - if wanted == level::Level::Workstation { + println!( + "{} is a host of the type {wanted} now in its profile", + host.name + ); + if wanted == host_type::HostType::Workstation { println!("Check its set-up, then apply it: berth apply {}", host.name); } Ok(()) } -/// Offer to save the level a host just added was found to have, when it is +/// Offer to save the type a host just added was found to be, when it is /// more than its profile says: a workstation added by its address is not /// to be treated as a bare machine. -fn offer_found_level(paths: &Paths, name: &str, intended: level::Level) -> Result<()> { +fn offer_found_type(paths: &Paths, name: &str, intended: host_type::HostType) -> Result<()> { let Ok(reach) = reach(paths, name) else { return Ok(()); }; let found = { let asked = reach.wait(async { - tokio::time::timeout( - std::time::Duration::from_secs(15), - reach.link.get::("/v1/version"), - ) - .await + tokio::time::timeout(std::time::Duration::from_secs(15), reach.link.version()).await }); match asked { - Ok(Ok(version)) => level::seen(Ok(&version)), + Ok(Ok(version)) => host_type::seen(Ok(&version)), _ => None, } }; drop(reach); - let (Some(found), Some(said)) = (found, level::mismatch(name, intended, found)) else { + let (Some(found), Some(said)) = (found, host_type::mismatch(name, intended, found)) else { return Ok(()); }; println!("! {said}"); - // A workstation keeps its profile, which says more than a level would. - if found == level::Level::Workstation { + // A workstation keeps its profile, which says more than a type would. + if found == host_type::HostType::Workstation { if std::io::stdin().is_terminal() && !ask(&format!("Adopt {name} from the profile it keeps? [Y/n]"))? .eq_ignore_ascii_case("n") @@ -811,26 +807,27 @@ fn offer_found_level(paths: &Paths, name: &str, intended: level::Level) -> Resul return Ok(()); } if std::io::stdin().is_terminal() - && !ask(&format!("Save {name} as a {found} host? [Y/n]"))?.eq_ignore_ascii_case("n") + && !ask(&format!("Save {name} as a host of the type {found}? [Y/n]"))? + .eq_ignore_ascii_case("n") { - return set_level(paths, name, found.name()); + return set_type(paths, name, found.name()); } - println!("Save it with: berth host level {name} {found}"); + println!("Save it with: berth host type {name} {found}"); Ok(()) } /// `berth host add NAME ADDRESS [--user USER] [--port PORT] [--auth AUTH] -/// [--level LEVEL] [--no-contact]`: save a host that exists already, by +/// [--type TYPE] [--no-contact]`: save a host that exists already, by /// where it is and how berth logs in, with nothing of a workstation. Then /// first contact, unless told not to: berth's key is tried, and a host that /// refuses it is logged in to once with a password or key to install it. pub fn add_host(paths: &Paths, name: &str, address: &str, args: &[&str]) -> Result<()> { - const USAGE: &str = "Usage: berth host add NAME ADDRESS [--user USER] [--port PORT] [--auth berth|key:NAME|password|ssh] [--level reachable|controller|workstation] [--no-contact]"; + const USAGE: &str = "Usage: berth host add NAME ADDRESS [--user USER] [--port PORT] [--auth berth|key:NAME|password|ssh] [--type ssh|managed|workstation] [--no-contact]"; let mut access = api::profile::Access { address: address.to_owned(), ..api::profile::Access::default() }; - let (mut host_level, mut contact) = (level::Level::Reachable, true); + let (mut host_type, mut contact) = (host_type::HostType::Ssh, true); let mut rest = args.iter(); while let Some(arg) = rest.next() { let mut value = || rest.next().copied().ok_or(USAGE); @@ -843,10 +840,10 @@ pub fn add_host(paths: &Paths, name: &str, address: &str, args: &[&str]) -> Resu format!("--auth is berth, key:NAME, password or ssh, not {given}") })?; } - "--level" => { + "--type" => { let given = value()?; - host_level = level::Level::parse(given).ok_or_else(|| { - format!("--level is reachable, controller or workstation, not {given}") + host_type = host_type::HostType::parse(given).ok_or_else(|| { + format!("--type is {}, not {given}", host_type::HostType::choices()) })?; } "--no-contact" => contact = false, @@ -858,9 +855,9 @@ pub fn add_host(paths: &Paths, name: &str, address: &str, args: &[&str]) -> Resu format!("{name} cannot be a host's name: letters, digits, -, _ and . only").into(), ); } - let mut profile = api::profile::minimal(host_level, &access); + let mut profile = api::profile::minimal(host_type, &access); // A workstation keeps what its set-up fills in; it starts empty. - if host_level == level::Level::Workstation { + if host_type == host_type::HostType::Workstation { profile["builder"] = json!({}); } let problems = api::profile::problems(&profile); @@ -895,7 +892,10 @@ pub fn add_host(paths: &Paths, name: &str, address: &str, args: &[&str]) -> Resu } } place.save(paths, &profile)?; - println!("Added {name} as a {host_level} host: {}", place.describe()); + println!( + "Added {name} as a host of the type {host_type}: {}", + place.describe() + ); seed_host_key(paths, &place, &access)?; } } @@ -905,7 +905,7 @@ pub fn add_host(paths: &Paths, name: &str, address: &str, args: &[&str]) -> Resu crate::key_command::trust(paths, name, &[]).map_err(|error| -> Box { format!("{name} is saved, but logging in to it did not work yet: {error}. Try again with: berth key trust {name}").into() })?; - offer_found_level(paths, name, host_level) + offer_found_type(paths, name, host_type) } /// Take the host key of a host just added from the user's own @@ -1529,7 +1529,7 @@ pub fn adopt(paths: &Paths, name: &str, args: &[&str]) -> Result<()> { // A host saved below a workstation says less than the host keeps; // adopting it by its own address is what replacing it means. (Some(profile), "") => { - if level::of(profile) == level::Level::Workstation && !asked.force { + if host_type::of(profile) == host_type::HostType::Workstation && !asked.force { return Err(format!( "{name} is saved as a workstation already. Replace its profile with the one it keeps with --force" ) @@ -1840,18 +1840,18 @@ mod tests { .unwrap(); assert_eq!( saved, - json!({"level": "reachable", "access": {"address": "192.0.2.4", "user": "ops", "port": "2222", "auth": "berth"}}) + json!({"type": "ssh", "access": {"address": "192.0.2.4", "user": "ops", "port": "2222", "auth": "berth"}}) ); let said = |result: Result<()>| result.unwrap_err().to_string(); assert!(said(add("dock", &["--no-contact"])).contains("already")); - assert!(said(add("pier", &["--level", "server", "--no-contact"])).contains("--level")); + assert!(said(add("pier", &["--type", "server", "--no-contact"])).contains("--type")); assert!(said(add("pier", &["--auth", "key:none", "--no-contact"])).contains("no key none")); assert!(said(add("../pier", &["--no-contact"])).contains("name")); // A workstation starts with the part its set-up fills in. - add("studio", &["--level", "workstation", "--no-contact"]).unwrap(); + add("studio", &["--type", "workstation", "--no-contact"]).unwrap(); let studio = Host::load(&paths, "studio").unwrap(); assert!(studio.config["builder"].is_object()); - // Applying is refused below a workstation, before anything runs. + // Applying is refused to a host that is not a workstation, before anything runs. let dock = Host::load(&paths, "dock").unwrap(); let refused = berth_core::apply::prepare(&paths, &dock, None); assert!(said(refused.map(|_| ())).contains("not a workstation")); diff --git a/crates/berth/src/main.rs b/crates/berth/src/main.rs index f59283e..ffee213 100644 --- a/crates/berth/src/main.rs +++ b/crates/berth/src/main.rs @@ -33,12 +33,12 @@ Usage: berth HOST open a host (a saved name, or a path to a profile) berth list saved hosts berth host add NAME ADDRESS [--user USER] [--port PORT] [--auth AUTH] - [--level reachable|controller|workstation] [--no-contact] + [--type ssh|managed|workstation] [--no-contact] save a machine that exists already, by its address, and - install berth's key there; it is reachable unless told - berth host install HOST install berth's controller alone on a host below a - workstation: sessions, tasks and files, no desktop - berth host level HOST reachable|controller|workstation + install berth's key there; its type is ssh unless told + berth host install HOST install berth's controller alone on a host that is not + a workstation: sessions, actions and files, no desktop + berth host type HOST ssh|managed|workstation say what the host is, as for one added by its address that berth set up before; nothing on the host changes berth host rename HOST NAME [--hostname] @@ -399,7 +399,10 @@ fn open(paths: &Paths, host: &str) -> Result { /// Stop with the list of problems when the profile cannot run the action. fn require_ready(app: &App) -> Result<()> { // A seed and an installer make a whole workstation. - berth_core::level::guard(&app.host_profile(), berth_core::level::Capability::Apply)?; + berth_core::host_type::guard( + &app.host_profile(), + berth_core::host_type::Capability::Apply, + )?; let problems = app.problems(); if problems.is_empty() { return Ok(()); @@ -688,7 +691,7 @@ fn run() -> Result<()> { return commands::add_host(&paths, name, address, rest); } ["host", "install", host] => return commands::install_controller(&paths, host), - ["host", "level", host, level] => return commands::set_level(&paths, host, level), + ["host", "type", host, given] => return commands::set_type(&paths, host, given), ["host", "rename", host, name] => return commands::rename(&paths, host, name, false), ["host", "rename", host, name, "--hostname"] | ["host", "rename", host, "--hostname", name] => { diff --git a/crates/berth/src/remote.rs b/crates/berth/src/remote.rs index 100801b..f6db674 100644 --- a/crates/berth/src/remote.rs +++ b/crates/berth/src/remote.rs @@ -31,7 +31,7 @@ async fn refresh( compare: Option, ) { if all { - match link.get::("/v1/version").await { + match link.version().await { Ok(version) => { let old = version.api < NEEDS_API; if let Some(compare) = compare { diff --git a/crates/berth/src/serve/actions.rs b/crates/berth/src/serve/actions.rs index db4cb00..557e8b8 100644 --- a/crates/berth/src/serve/actions.rs +++ b/crates/berth/src/serve/actions.rs @@ -24,8 +24,8 @@ use berth_api::{ use berth_core::{ apply, host::Host, + host_type::{self, Capability, HostType}, keys::{self, Once, contact, ring}, - level::{self, Capability, Level}, profiles::Place, registry::Store, rollout, @@ -47,10 +47,10 @@ pub(super) struct Seen<'a> { pub tasks: Option<&'a [Task]>, /// The names of the secrets the server keeps. pub secrets: &'a [String], - /// The level the host's profile means it to have. - pub level: Level, + /// The type the host's profile means it to be. + pub host_type: HostType, /// What its controller says it is, when it answered. - pub observed: Option, + pub observed: Option, /// Why its controller did not answer, when it was asked and did not. pub unanswered: Option<&'a str>, } @@ -162,13 +162,13 @@ async fn host_tasks(remote: &Remote) -> Result, String> { } /// What a host's controller says the host is, when it answers. -async fn observed(remote: &Remote) -> Option { +async fn observed(remote: &Remote) -> Option { remote .version() .await .ok() .as_ref() - .and_then(|version| level::seen(Ok(version))) + .and_then(|version| host_type::seen(Ok(version))) } /// A host's actions: its tasks, then berth's own. A task that takes the @@ -250,9 +250,9 @@ pub async fn host_actions( state.refresh(false); let remote = remote(&state, &name)?; let profile = profile_of(&state, &name); - // A host that is only reachable has no controller to ask. - let asked = match level::of(&profile) { - Level::Reachable => None, + // A host of the type ssh has no controller to ask. + let asked = match host_type::of(&profile) { + HostType::Ssh => None, _ => Some(host_tasks(&remote).await), }; let (tasks, unanswered) = match &asked { @@ -267,7 +267,7 @@ pub async fn host_actions( profile: &profile, tasks, secrets: &secrets, - level: level::of(&profile), + host_type: host_type::of(&profile), observed, unanswered, }))) @@ -297,10 +297,10 @@ pub async fn host_act( let profile = profile_of(&state, &name); // berth's own are described without asking the host, which they do themselves. let builtin = HOST.iter().find(|builtin| builtin.name == action); - let reachable_only = level::of(&profile) == Level::Reachable; + let ssh_only = host_type::of(&profile) == HostType::Ssh; let mut unanswered = None; let tasks = match builtin { - Some(_) if reachable_only || !THROUGH_CONTROLLER.contains(&action.as_str()) => None, + Some(_) if ssh_only || !THROUGH_CONTROLLER.contains(&action.as_str()) => None, // One that runs through the controller is described as the host answers. Some(_) => match host_tasks(&remote).await { Ok(tasks) => Some(tasks), @@ -309,7 +309,7 @@ pub async fn host_act( None } }, - None if reachable_only => Some(vec![]), + None if ssh_only => Some(vec![]), None => Some( host_tasks(&remote) .await @@ -323,7 +323,7 @@ pub async fn host_act( profile: &profile, tasks: tasks.as_deref(), secrets: &secrets, - level: level::of(&profile), + host_type: host_type::of(&profile), observed, unanswered: unanswered.as_deref(), }); @@ -351,7 +351,7 @@ fn installation_list() -> Vec { profile: &Value::Null, tasks: None, secrets: &[], - level: Level::Workstation, + host_type: HostType::Workstation, observed: None, unanswered: None, }; @@ -509,7 +509,7 @@ fn apply_action(seen: &Seen) -> Action { "Run the installer role against the host again, from the server, with the settings of its profile: for example after changing what is installed. It also installs or updates berth's own tools on the host. It runs as a job of the server.", ) }; - let action = level::fit(action, seen.name, seen.level, Capability::Apply); + let action = host_type::fit(action, seen.name, seen.host_type, Capability::Apply); logs_in_alone(seen, action) } @@ -534,7 +534,7 @@ fn logs_in_alone(seen: &Seen, action: Action) -> Action { } fn install_controller_action(seen: &Seen) -> Action { - let action = level::install_controller_action(seen.name, seen.level, seen.observed); + let action = host_type::install_controller_action(seen.name, seen.host_type, seen.observed); let action = match seen.profile.is_null() { true => unavailable( action, @@ -633,7 +633,7 @@ fn seed_action(seen: &Seen) -> Action { "Render the cloud-init user data that installs the host on a new machine, for a provider's field of that name. It answers with the seed.", ) }; - level::fit(action, seen.name, seen.level, Capability::Apply) + host_type::fit(action, seen.name, seen.host_type, Capability::Apply) } fn seed(state: Arc, name: String, _: Act) -> Run { @@ -669,7 +669,7 @@ fn secrets_action(seen: &Seen) -> Action { action.help = task.help.clone(); action.group = task.group.clone(); } - if let Err(refusal) = level::check(seen.name, seen.level, Capability::Secrets) { + if let Err(refusal) = host_type::check(seen.name, seen.host_type, Capability::Secrets) { return unavailable(action, Some(refusal.why)); } let why = match (seen.tasks, task, seen.unanswered) { @@ -765,7 +765,7 @@ fn rollout(state: Arc, _: String, act: Act) -> Run { .and_then(|place| Host::load_at(&paths, place)); // Only a workstation is applied; the others are said and left. let host = match host { - Ok(host) if level::of(&host.config) != Level::Workstation => { + Ok(host) if host_type::of(&host.config) != HostType::Workstation => { skipped.push(host.name); continue; } @@ -971,7 +971,7 @@ fn host_key(state: Arc, name: String, act: Act) -> Run { // ── Its name ──────────────────────────────────────────────────────────────── fn rename_action(seen: &Seen) -> Action { - let action = level::rename_action(); + let action = host_type::rename_action(); let why = seen .profile .is_null() diff --git a/crates/berth/src/serve/api.rs b/crates/berth/src/serve/api.rs index 0780ee1..4dbd5e1 100644 --- a/crates/berth/src/serve/api.rs +++ b/crates/berth/src/serve/api.rs @@ -20,7 +20,7 @@ use axum::{ routing::{any, get}, }; use berth_api::{ - Applied, Behind, Done, ErrorBody, ErrorDetail, HostBehind, HostLevel, JobInfo, Message, Output, + Applied, Behind, Done, ErrorBody, ErrorDetail, HostBehind, HostType, JobInfo, Message, Output, Version, b64, client, code, ops::{self, Role}, streams, @@ -115,13 +115,14 @@ pub struct HostInfo { /// What changed since then, when the server would apply something else now. #[serde(skip_serializing_if = "Option::is_none")] pub behind: Option, - /// The level its profile means it to have. - pub level: HostLevel, - /// The level it was seen to have: what its controller's record says, - /// `reachable` when berth logged in and found no controller. Absent - /// when it could not be asked. + /// The type its profile means it to be. + #[serde(rename = "type")] + pub host_type: HostType, + /// The type it was seen to be: what its controller's record says, `ssh` + /// when berth logged in and found no controller. Absent when it could + /// not be asked. #[serde(skip_serializing_if = "Option::is_none")] - pub seen: Option, + pub seen: Option, /// A rotation of a key it logs in with is not done on it yet. #[serde(skip_serializing_if = "std::ops::Not::not")] pub rotating: bool, @@ -426,13 +427,13 @@ pub(super) fn compare(state: &Serve) -> Compare { Arc::new(rollout::comparer(&state.paths)) } -/// What the server knows of a host apart from asking it: the level of its +/// What the server knows of a host apart from asking it: the type of its /// profile, and whether a key it logs in with is being rotated. -pub(super) fn known(state: &Serve, name: &str) -> (HostLevel, bool) { +pub(super) fn known(state: &Serve, name: &str) -> (HostType, bool) { let profile = super::setup::saved_profile(state, name).map(|(_, profile)| profile); - let level = profile + let host_type = profile .as_ref() - .map_or(HostLevel::Workstation, berth_api::profile::level); + .map_or(HostType::Workstation, berth_api::profile::host_type); let rotating = profile.is_ok_and(|profile| { let place = berth_core::profiles::Place::own(name); let store = berth_core::store::shared(&state.paths); @@ -442,16 +443,16 @@ pub(super) fn known(state: &Serve, name: &str) -> (HostLevel, bool) { _ => false, } }); - (level, rotating) + (host_type, rotating) } -async fn info(remote: Arc, compare: Compare, known: (HostLevel, bool)) -> HostInfo { +async fn info(remote: Arc, compare: Compare, known: (HostType, bool)) -> HostInfo { let seen = remote.version().await; let applied = seen .as_ref() .ok() .and_then(|version| version.applied.clone()); - let observed = berth_core::level::seen( + let observed = berth_core::host_type::seen( seen.as_ref() .map_err(|error| error.starts_with(super::NO_BERTHD)), ); @@ -464,7 +465,7 @@ async fn info(remote: Arc, compare: Compare, known: (HostLevel, bool)) - error: seen.err(), behind: applied.as_ref().and_then(|applied| compare(applied)), applied: applied.map(|applied| applied.berth), - level: known.0, + host_type: known.0, seen: observed, rotating: known.1, } @@ -505,7 +506,7 @@ async fn version() -> Json { api: berth_api::API, mode: "serve".into(), applied: None, - level: None, + host_type: None, }) } diff --git a/crates/berth/src/serve/mod.rs b/crates/berth/src/serve/mod.rs index 426a505..21bbe5a 100644 --- a/crates/berth/src/serve/mod.rs +++ b/crates/berth/src/serve/mod.rs @@ -225,8 +225,7 @@ impl Remote { if let Some(refused) = link.refused() { return Err(refused); } - let asked = - tokio::time::timeout(Duration::from_secs(15), link.get::("/v1/version")).await; + let asked = tokio::time::timeout(Duration::from_secs(15), link.version()).await; let answer = match asked { Ok(Ok(version)) => Ok(version), Ok(Err(error)) if Link::missing(&error) => Err(format!("{NO_BERTHD}: {error}")), diff --git a/crates/berth/src/serve/setup.rs b/crates/berth/src/serve/setup.rs index 070405e..a09bca0 100644 --- a/crates/berth/src/serve/setup.rs +++ b/crates/berth/src/serve/setup.rs @@ -68,9 +68,9 @@ pub async fn profile(State(state): App, Path(name): Path) -> Answer&2; exit 255")]}}); berth_core::profiles::Place::own("dock") .unwrap() diff --git a/crates/berth/src/ui.rs b/crates/berth/src/ui.rs index 2adc6ef..a67957f 100644 --- a/crates/berth/src/ui.rs +++ b/crates/berth/src/ui.rs @@ -3115,7 +3115,7 @@ pub fn run( app.update_suggestions(); app.watch_host(); app.watch_machine(); - app.watch_found_level(); + app.watch_found_type(); // One of berth's own actions on the host runs in the normal terminal. if app.own_command.is_some() { return Ok(true); @@ -4706,17 +4706,17 @@ mod tests { } #[test] - fn a_host_below_a_workstation_is_offered_the_controller_and_no_apply() { + fn a_host_that_is_not_a_workstation_is_offered_the_controller_and_no_apply() { use crate::remote::State; - let mut app = unsaved_app(br#"{"level": "reachable", "access": {"address": "192.0.2.4"}}"#); + let mut app = unsaved_app(br#"{"type": "ssh", "access": {"address": "192.0.2.4"}}"#); app.set_step(Step::Manage); - app.host.level = berth_api::HostLevel::Reachable; + app.host.host_type = berth_api::HostType::Ssh; app.host.state = State::Missing; - app.host.seen = Some(berth_api::HostLevel::Reachable); + app.host.seen = Some(berth_api::HostType::Ssh); app.host.own = - berth_core::level::local_actions("devbox", berth_api::HostLevel::Reachable, None); + berth_core::host_type::local_actions("devbox", berth_api::HostType::Ssh, None); let text = screen_text(&mut app); - assert!(text.contains("Level · reachable"), "{text}"); + assert!(text.contains("Type · ssh"), "{text}"); assert!(text.contains("▸ Install the controller") && text.contains("▸ Terminal over SSH")); assert!(!app.entries().contains(&Entry::Task("apply"))); // Choosing it, and saying yes, runs berth host install in the normal terminal. @@ -4747,17 +4747,17 @@ mod tests { ); assert!(app.entries().contains(&Entry::HostTask(0))); - // A controller host lists berth's own beside its tasks; one it cannot + // A managed host lists berth's own beside its actions; one it cannot // run is marked, and its reason is in the information box. app.own_command = None; - app.config["level"] = json!("controller"); - app.host.level = berth_api::HostLevel::Controller; + app.config["type"] = json!("managed"); + app.host.host_type = berth_api::HostType::Managed; app.host.state = State::Ready(berth_api::VERSION.into()); app.host.tasks = host_tasks(); app.host.own = vec![ - berth_core::level::install_controller_action( + berth_core::host_type::install_controller_action( "devbox", - berth_api::HostLevel::Controller, + berth_api::HostType::Managed, None, ), berth_api::Action { @@ -4793,21 +4793,21 @@ mod tests { } #[test] - fn an_existing_host_is_offered_the_level_it_says_it_has() { + fn an_existing_host_is_offered_the_type_it_says_it_has() { let mut app = unsaved_app(br#"{"access": {"address": "192.0.2.4"}}"#); - app.offer_level(Some(berth_api::HostLevel::Controller)); - assert_eq!(app.config["level"], "controller"); - assert!(app.status.contains("answers as a controller host")); + app.offer_type(Some(berth_api::HostType::Managed)); + assert_eq!(app.config["type"], "managed"); + assert!(app.status.contains("answers as a host of the type managed")); // Nothing found, or what it is already, changes nothing. - app.offer_level(None); - app.offer_level(Some(berth_api::HostLevel::Controller)); - assert_eq!(app.config["level"], "controller"); - // A level chosen on its row stays; the host's answer is only told. - app.commit(Field::Level, "reachable"); - app.offer_level(Some(berth_api::HostLevel::Workstation)); - assert_eq!(app.config["level"], "reachable"); + app.offer_type(None); + app.offer_type(Some(berth_api::HostType::Managed)); + assert_eq!(app.config["type"], "managed"); + // A type chosen on its row stays; the host's answer is only told. + app.commit(Field::Type, "ssh"); + app.offer_type(Some(berth_api::HostType::Workstation)); + assert_eq!(app.config["type"], "ssh"); assert!( - app.status.contains("its Level here says reachable"), + app.status.contains("its Type here says ssh"), "{}", app.status ); diff --git a/crates/berthd/src/http.rs b/crates/berthd/src/http.rs index ecad0e0..2c3e3de 100644 --- a/crates/berthd/src/http.rs +++ b/crates/berthd/src/http.rs @@ -95,14 +95,15 @@ async fn version(AppState(state): AppState>) -> Json { let applied = record .clone() .and_then(|record| serde_json::from_value(record).ok()); - // A record without a level is of a whole profile, as before levels, and - // only a workstation's apply or first boot leaves the profile it keeps. + // A record without a level is of a whole profile, as before there were + // types, and only a workstation's apply or first boot leaves the profile + // it keeps. The role records the type as `level` with its older values. let kept = state.config_dir.join("profile.json").exists(); - let level = match kept { - true => Some(api::HostLevel::Workstation), + let host_type = match kept { + true => Some(api::HostType::Workstation), false => record.map(|record| match record["level"].as_str() { - Some(level) => api::HostLevel::parse(level).unwrap_or_default(), - None => api::HostLevel::Workstation, + Some(level) => api::HostType::from_level(level).unwrap_or_default(), + None => api::HostType::Workstation, }), }; Json(api::Version { @@ -110,7 +111,7 @@ async fn version(AppState(state): AppState>) -> Json { api: api::API, mode: mode.into(), applied, - level, + host_type, }) } diff --git a/docs/content/docs/(guide)/deploy/ssh.mdx b/docs/content/docs/(guide)/deploy/ssh.mdx index cf4e806..f4959bf 100644 --- a/docs/content/docs/(guide)/deploy/ssh.mdx +++ b/docs/content/docs/(guide)/deploy/ssh.mdx @@ -6,7 +6,7 @@ icon: Server This method runs the role over SSH against a machine that already has Ubuntu. The role adds accounts, packages and services to the existing system without partitioning or reinstalling. -A machine that should stay as it is can be added with only an address instead, and get berth's controller alone or nothing at all ([Host levels](/docs/use/levels)). The **Level** row on the Install tab chooses. +A machine that should stay as it is can be added with only an address instead, and get berth's controller alone or nothing at all ([Host types](/docs/use/types)). The **Type** row on the Install tab chooses. The role installs services, changes the firewall policy and grants the agent sudo for the entire machine. Do not point it at a computer you use for anything else. diff --git a/docs/content/docs/(guide)/extend/serve.mdx b/docs/content/docs/(guide)/extend/serve.mdx index 1d0ed12..399daea 100644 --- a/docs/content/docs/(guide)/extend/serve.mdx +++ b/docs/content/docs/(guide)/extend/serve.mdx @@ -16,7 +16,7 @@ It prints where it listens and how many hosts it knows. Only one runs per user. | Operations | For | | --- | --- | -| [`hosts.*`](/docs/api/serve/hosts) | The saved hosts and their profiles, and whether each is behind. Each says its [level](/docs/use/levels), the level it was seen to have, and whether a key rotation has yet to reach it. `hosts.save` takes a host below a workstation with only `level` and `access`. `hosts.actions` lists what can be done to a host and `hosts.act` runs one of those [actions](#actions) | +| [`hosts.*`](/docs/api/serve/hosts) | The saved hosts and their profiles, and whether each is behind. Each says its [type](/docs/use/types), the type it was seen to be, and whether a key rotation has yet to reach it. `hosts.save` takes a host that is not a workstation with only `type` and `access`. `hosts.actions` lists what can be done to a host and `hosts.act` runs one of those [actions](#actions) | | [`actions.*`](/docs/api/serve/actions) | The actions of the installation itself, such as `rollout`, which applies the hosts that are behind one after another | | [`secrets.*`](/docs/api/serve/secrets), [`registries.*`](/docs/api/serve/registries), [`settings.*`](/docs/api/serve/settings) | What the server keeps beside the hosts. A secret's value goes in and never comes back out | | [`plugins.*`](/docs/api/serve/plugins) | The server's plugins. One is installed from its npm registry, from an `https://` address, or from a `.tgz` that is sent, and one of its own is removed. `plugins.check` asks the registries for newer versions and `plugins.update` installs them. `setup.catalogue` lists the new features straight away | @@ -38,13 +38,13 @@ What berth does to a host or to the installation is an *action*. `GET /v1/hosts/ | --- | --- | --- | --- | | A task of the host, such as `status` | The host | On the host, as a session | `202` with the session and a job that copies its output. A task that needs a terminal answers `200` with the session alone, to attach to | | `apply` | The host | Here, as a job | `202` with the job | -| `install-controller` | The host | Here, as a job | `202` with the job. It installs berthd and box alone on a host below a workstation | +| `install-controller` | The host | Here, as a job | `202` with the job. It installs berthd and box alone on a host that is not a workstation | | `seed` | The host | Here, at once | `200` with the seed's `user_data` as the result | | `secrets` | The host | On the host, with the server's secrets | `202` with the session and its job | | `rename` | The host | Here, as a job | `202` with the job. It gives the host the name in its `name` argument, with what the server keeps of it ([Renaming a host](/docs/use/moving#renaming-a-host)) | | `rollout` | The installation | Here, as a job | `202` with the job; its report says how each host went | -An action that the host's level rules out is listed with `available` false, and its `why` says which action raises the level. Run anyway, it is refused with `501 not_available`. +An action that the host's type rules out is listed with `available` false, and its `why` says which action changes the type. Run anyway, it is refused with `501 not_available`. To run one, POST to its name with its arguments: diff --git a/docs/content/docs/(guide)/reference/profile.mdx b/docs/content/docs/(guide)/reference/profile.mdx index b36819f..bbd2ce9 100644 --- a/docs/content/docs/(guide)/reference/profile.mdx +++ b/docs/content/docs/(guide)/reference/profile.mdx @@ -112,19 +112,19 @@ Any `devbox_` setting of the role. The ones the terminal UI edits: Others, such as `devbox_tailscale_serve`, the agent versions and the backup settings, are described where they are used. All defaults are in [`defaults/main.yml`](https://github.com/helightdev/berth/blob/main/ansible/roles/devbox/defaults/main.yml). -## Level +## Type -A host below a workstation needs only its level and `access`. The other fields are for a workstation. See [Host levels](/docs/use/levels). +A host that is not a workstation needs only its type and `access`. The other fields are for a workstation. See [Host types](/docs/use/types). ```json title="dock's profile" { - "level": "reachable", + "type": "ssh", "access": { "address": "192.0.2.4", "user": "ops", "auth": "berth" } } ``` diff --git a/docs/content/docs/(guide)/start/concepts.mdx b/docs/content/docs/(guide)/start/concepts.mdx index 8b5ae25..2e07c7b 100644 --- a/docs/content/docs/(guide)/start/concepts.mdx +++ b/docs/content/docs/(guide)/start/concepts.mdx @@ -32,7 +32,8 @@ The software berth puts on a host is called *devbox*. The name appears in paths | Term | Meaning | | --- | --- | -| Host | A laptop, server, VM or container that berth sets up and manages | +| Host | Anything berth reaches and logs in to: a laptop, server, VM or container | +| Type | What berth does with a host: `ssh` only logs in, `managed` adds berth's controller, `workstation` applies the whole profile. See [Host types](/docs/use/types) | | Profile | The JSON document that describes one host, from what to install to how it is reached. berth keeps it in its store. See [Profile](/docs/reference/profile) | | Operator | Your account on the host, `ops` by default, for SSH and Cockpit | | Agent | The account the coding agents work in, `agent` by default. The virtual desktop runs as this account. Its sudo rights are its [privileges](/docs/use/accounts) | diff --git a/docs/content/docs/(guide)/use/cli.mdx b/docs/content/docs/(guide)/use/cli.mdx index 69aa57e..bba5b5d 100644 --- a/docs/content/docs/(guide)/use/cli.mdx +++ b/docs/content/docs/(guide)/use/cli.mdx @@ -17,7 +17,7 @@ With a [berth server](/docs/use/server) set, by `--server` or the `server` setti | `berth` | The home screen | | `berth HOST` | Open a host in the terminal UI; a new name starts a new profile | | `berth list` | Saved hosts and their addresses | -| `berth host add NAME ADDRESS [--user USER] [--port PORT] [--auth AUTH] [--level LEVEL] [--no-contact]` | Save a machine that exists by its address, reachable unless `--level` says otherwise, and install berth's key there ([Host levels](/docs/use/levels#adding-a-machine-that-exists)) | +| `berth host add NAME ADDRESS [--user USER] [--port PORT] [--auth AUTH] [--type TYPE] [--no-contact]` | Save a machine that exists by its address, of the type `ssh` unless `--type` says otherwise, and install berth's key there ([Host types](/docs/use/types#adding-a-machine-that-exists)) | | `berth profile HOST` | The host's profile, as JSON on standard output | | `berth profile HOST --set FILE` | Save the profile in FILE as the host's, checked as the terminal UI reads one. `-` reads standard input. With a [berth server](/docs/use/server) set, it is saved on the server | | `berth credentials HOST [--show]` | The passwords berth generated for the host's accounts, an account and its password to a line. Only to a terminal unless `--show` is given. For a server's host they come from the server | @@ -36,8 +36,8 @@ With a [berth server](/docs/use/server) set, by `--server` or the `server` setti | `berth iso HOST [--write /dev/sdX]` | Build the USB installer, downloading the ISO if none is set; write it to a drive after asking | | `berth seed HOST` | Render the cloud-init seed | | `berth apply HOST` | Apply the host's profile to it over SSH. With a [berth server](/docs/use/server) set, as a job there. Only a workstation is applied | -| `berth host install HOST` | Install berth's controller alone on a host below a workstation ([Installing the controller](/docs/use/levels#installing-the-controller)) | -| `berth host level HOST LEVEL` | Save the level the host's profile says, such as for a host with berth's controller added by its address. A workstation is adopted instead ([Adding a machine that exists](/docs/use/levels#adding-a-machine-that-exists)) | +| `berth host install HOST` | Install berth's controller alone on a host that is not a workstation ([Installing the controller](/docs/use/types#installing-the-controller)) | +| `berth host type HOST TYPE` | Save the type the host's profile says, such as for a host with berth's controller added by its address. A workstation is adopted instead ([Adding a machine that exists](/docs/use/types#adding-a-machine-that-exists)) | | `berth apply --behind [--update] [--reboot [--force]]` | Apply every host that is behind, one at a time ([Updates](/docs/use/updates#bringing-hosts-up-to-date)). `--all` takes the current ones too | | `berth host rename HOST NAME [--hostname]` | Give a host another name in berth, with everything berth keeps of it. The machine is left as it is. With `--hostname`, the profile's hostname changes to NAME as well, for the next apply ([Renaming a host](/docs/use/moving#renaming-a-host)) | | `berth remove HOST` | Forget a host. The machine itself is left as it is, and a machine berth created for the host must be deleted first | @@ -92,7 +92,7 @@ berth run studio claude:login # a sign-in runs in your terminal `berth run HOST TASK` runs a task and its plugin steps and leaves with the task's exit code. A task's arguments are given as `NAME=VALUE`, and `--yes` answers its confirmation. `berth manage HOST TASK` is the same command. Tasks that need a terminal, such as sign-ins, run in your terminal over `ssh -t`. -`berth tasks` lists berth's own actions beside the host's tasks, such as `install-controller`, and says why one cannot run now. A host that is only reachable has no tasks yet. +`berth tasks` lists berth's own actions beside the host's tasks, such as `install-controller`, and says why one cannot run now. A host of the type `ssh` has no tasks yet. When a [berth server](/docs/use/server) keeps the host, `berth tasks` lists the server's actions for the host: its tasks, and berth's own such as `apply` and `seed`. `berth run` runs any of them through the server, which keeps a job of each run ([Actions](/docs/extend/serve#actions)). diff --git a/docs/content/docs/(guide)/use/meta.json b/docs/content/docs/(guide)/use/meta.json index a689f03..c4de13d 100644 --- a/docs/content/docs/(guide)/use/meta.json +++ b/docs/content/docs/(guide)/use/meta.json @@ -1,5 +1,5 @@ { "title": "Using berth", "icon": "SquareTerminal", - "pages": ["terminal-ui", "overview", "cli", "levels", "server", "store", "access", "accounts", "sign-ins", "secrets", "registries", "backups", "moving", "updates"] + "pages": ["terminal-ui", "overview", "cli", "types", "server", "store", "access", "accounts", "sign-ins", "secrets", "registries", "backups", "moving", "updates"] } diff --git a/docs/content/docs/(guide)/use/moving.mdx b/docs/content/docs/(guide)/use/moving.mdx index 29d21df..8e854d0 100644 --- a/docs/content/docs/(guide)/use/moving.mdx +++ b/docs/content/docs/(guide)/use/moving.mdx @@ -37,7 +37,7 @@ berth apply studio `berth adopt NAME [USER@]ADDRESS` logs in over SSH as a user who can become root, reads the file with sudo and saves it as host `NAME`. It does not need berthd. `--port PORT` gives another SSH port. `--key FILE` offers one more private key for this read only. `--force` replaces a saved host of the same name. Without it, berth refuses. -Without an address, `berth adopt NAME` adopts the saved host `NAME` at the address its profile has. This is the way for a workstation that was saved by its address with [`berth host add`](/docs/use/levels#adding-a-machine-that-exists), whose profile here says less than the host keeps. `berth host add` suggests the command when it finds such a host. A host saved as a workstation already needs `--force`. +Without an address, `berth adopt NAME` adopts the saved host `NAME` at the address its profile has. This is the way for a workstation that was saved by its address with [`berth host add`](/docs/use/types#adding-a-machine-that-exists), whose profile here says less than the host keeps. `berth host add` suggests the command when it finds such a host. A host saved as a workstation already needs `--force`. The profile's `access` comes from how berth got in. It logs in with `berth` when this berth's own key worked, and with `ssh` when your SSH configuration, your agent or the key of `--key` did. `sudo` is `password` when sudo asked for one. After the first apply, the operator takes this berth's key, and an apply as the operator sets `sudo` to `none` ([Logging in to hosts](/docs/use/accounts#logging-in-to-hosts)). diff --git a/docs/content/docs/(guide)/use/overview.mdx b/docs/content/docs/(guide)/use/overview.mdx index 7bc13cc..4dd1a3d 100644 --- a/docs/content/docs/(guide)/use/overview.mdx +++ b/docs/content/docs/(guide)/use/overview.mdx @@ -8,7 +8,7 @@ Opening an installed host shows its overview, with the connection at the top and -The line under the title is the host's load, CPU, memory, disk and uptime. Under **Connection**, a line says the host's [level](/docs/use/levels), and what the host itself was seen to be when that differs. +The line under the title is the host's load, CPU, memory, disk and uptime. Under **Connection**, a line says the host's [type](/docs/use/types), and what the host itself was seen to be when that differs. ## Tasks @@ -30,7 +30,7 @@ The line under the title is the host's load, CPU, memory, disk and uptime. Under When the host was applied before a plugin or berth itself changed, a **Configuration** group at the top says which, such as `claude 1.0.0 → 1.1.0`, with **Apply this configuration** below it ([Updates](/docs/use/updates#hosts-that-are-behind)). -berth's own actions on the host are listed beside its tasks, such as **Install the controller** for a host below a workstation. One the host's level or state rules out is marked `not now`, and the Information panel says why and what to do first. A host with the controller alone has only Status, Update, Reboot and the secrets. +berth's own actions on the host are listed beside its tasks, such as **Install the controller** for a host that is not a workstation. One the host's type or state rules out is marked `not now`, and the Information panel says why and what to do first. A host with the controller alone has only Status, Update, Reboot and the secrets. Plugins add tasks to these groups or bring groups of their own, such as **Backup**. They also add steps to built-in tasks such as Status and Update. A task's output stays on the page. diff --git a/docs/content/docs/(guide)/use/levels.mdx b/docs/content/docs/(guide)/use/types.mdx similarity index 56% rename from docs/content/docs/(guide)/use/levels.mdx rename to docs/content/docs/(guide)/use/types.mdx index 089afda..4720b03 100644 --- a/docs/content/docs/(guide)/use/levels.mdx +++ b/docs/content/docs/(guide)/use/types.mdx @@ -1,33 +1,33 @@ --- -title: Host levels -description: A host has a level, from a machine berth only logs in to up to a whole workstation. What each level allows, and how to add a host by its address. +title: Host types +description: A host has a type, from a machine berth only logs in to up to a whole workstation. What each type allows, and how to add a host by its address. icon: Layers --- -berth does not have to set a machine up to work with it. Each host has one of three levels: +berth does not have to set a machine up to work with it. A host is anything berth reaches and logs in to, and its type says what berth does with it: -| Level | What is on the host | What berth does with it | +| Type | What is on the host | What berth does with it | | --- | --- | --- | -| `reachable` | Nothing of berth | Logs in over SSH for a terminal, commands and the inventory | -| `controller` | berthd and box | Also sessions, the channel, files, tasks and secrets | +| `ssh` | Nothing of berth | Logs in over SSH for a terminal, commands and the inventory | +| `managed` | berthd and box | Also sessions, the channel, files, actions and secrets | | `workstation` | The whole profile | Also the desktop, the agents, plugins, applying and roll-outs | -The level is part of the host's [profile](/docs/reference/profile#level), as `level`. A profile that doesn't say is a workstation, so profiles from before levels mean what they always did. What the host has right now is asked of it. The overview and the Hosts tab show both when they differ, such as for a controller installed by hand. +The type is part of the host's [profile](/docs/reference/profile#type), as `type`. A profile that doesn't say is a workstation, so older profiles mean what they always did. What the host has right now is asked of it. The overview and the Hosts tab show both when they differ, such as for a controller installed by hand. ## Capabilities -| Capability | `reachable` | `controller` | `workstation` | +| Capability | `ssh` | `managed` | `workstation` | | --- | --- | --- | --- | | Terminal and commands over SSH, inventory | yes | yes | yes | | Install the controller alone | yes | update it | by applying | | Sessions, channel, files, units, logs, processes | no | yes | yes | -| The tasks status, update and reboot | no | yes | yes | +| The actions status, update and reboot | no | yes | yes | | Secrets and registry logins sent to the host | no | yes | yes | -| Plugin features, their tasks and services | no | no | yes | +| Plugin features, their actions and services | no | no | yes | | Apply, roll-out, cloud seed, USB installer | no | no | yes | | Desktop and access links | no | no | yes | -The terminal UI, berth-remote, the commands and the API all use the same check in berth. An action the level rules out is still listed, as unavailable, with the reason and what raises the level. Asked for anyway, the server refuses it with `501 not_available`. A roll-out leaves hosts that aren't workstations and says how many it left. +The terminal UI, berth-remote, the commands and the API all use the same check in berth. An action the type rules out is still listed, as unavailable, with the reason and what changes the type. Asked for anyway, the server refuses it with `501 not_available`. A roll-out leaves hosts that aren't workstations and says how many it left. ## Adding a machine that exists @@ -42,12 +42,12 @@ berth host add dock 192.0.2.4 --user ops | `--user USER` | Your SSH configuration | The SSH user | | `--port PORT` | Your SSH configuration | The SSH port | | `--auth AUTH` | `berth` | How berth [logs in](/docs/use/accounts#logging-in-to-hosts): `berth`, `key:NAME`, `password` or `ssh` | -| `--level LEVEL` | `reachable` | The level it is meant to have | +| `--type TYPE` | `ssh` | The type it is meant to be | | `--no-contact` | | Save it without logging in | After saving the host, berth logs in the way [first contact](/docs/use/accounts#first-contact) does. It tries its own key, and if the machine refuses it, it asks for a password or a private key that logs in once to install the key. It records the host's SSH host key and prints its fingerprint. When your `~/.ssh/known_hosts` knows the address, berth takes the host key from there. With a [berth server](/docs/use/server) set, the host is saved on the server, which logs in with its own keys. -Then berth asks the host what it is. A machine that berth set up before has a controller that says its level, and berth offers to change the profile here to a higher one than `--level` gave. Without a terminal it prints the command. +Then berth asks the host what it is. A machine that berth set up before has a controller that says its type, and berth offers to change the profile here when the host has more than `--type` gave. Without a terminal it prints the command. A workstation has its whole profile on the host as well. berth offers to [adopt](/docs/use/moving) it from there: @@ -55,21 +55,21 @@ A workstation has its whole profile on the host as well. berth offers to [adopt] berth adopt dock ``` -A host with berth's controller alone has nothing more to keep, and berth offers to save its level: +A host with berth's controller alone has nothing more to keep, and berth offers to save its type: ```bash -berth host level dock controller +berth host type dock managed ``` -`berth host level HOST LEVEL` only changes the profile here. A host's page says the same when its controller reports more than its profile says. berth refuses to install the controller alone on a host that is a workstation, whatever its profile here says. It asks the host's controller first, and the playbook checks the host's own record and the profile it keeps. +`berth host type HOST TYPE` only changes the profile here. A host's page says the same when its controller reports more than its profile says. berth refuses to install the controller alone on a host that is a workstation, whatever its profile here says. It asks the host's controller first, and the playbook checks the host's own record and the profile it keeps. -In the terminal UI, create a host on the home screen and choose **Existing host, SSH only** on the **Install** tab. The address and the login are all the set-up asks for, and **Run** saves the host. For a controller, choose **Existing host over SSH** and set **Level** to `controller`. **Run** then installs the controller. berth-remote does the same through the server. +In the terminal UI, create a host on the home screen and choose **Existing host, SSH only** on the **Install** tab. The address and the login are all the set-up asks for, and **Run** saves the host. For a managed host, choose **Existing host over SSH** and set **Type** to `managed`. **Run** then installs the controller. berth-remote does the same through the server. -Over the API, `hosts.save` takes a profile with only the level and `access`: +Over the API, `hosts.save` takes a profile with only the type and `access`: ```bash curl --unix-socket "$XDG_RUNTIME_DIR/berth/serve.sock" -X PUT \ - -d '{"level": "reachable", "access": {"address": "192.0.2.4", "user": "ops"}}' \ + -d '{"type": "ssh", "access": {"address": "192.0.2.4", "user": "ops"}}' \ http://berth/v1/hosts/dock/profile ``` @@ -84,9 +84,9 @@ berth host add big 192.0.2.20 --user root --auth ssh berth host install big ``` -`berth host add` saves `big` as a reachable host. `--auth ssh` makes berth log in with your own SSH configuration and agent, so the key that works for `ssh root@192.0.2.20` works for berth. The default, `--auth berth`, uses berth's own key, which berth installs on the first contact with a password or a private key that logs in once. `--auth ssh` works with a local berth only. With a [berth server](/docs/use/server) set, the server logs in with its own keys. +`berth host add` saves `big` as a host of the type `ssh`. `--auth ssh` makes berth log in with your own SSH configuration and agent, so the key that works for `ssh root@192.0.2.20` works for berth. The default, `--auth berth`, uses berth's own key, which berth installs on the first contact with a password or a private key that logs in once. `--auth ssh` works with a local berth only. With a [berth server](/docs/use/server) set, the server logs in with its own keys. -`berth host install big` puts the controller alone on the server. berth can then report its status and run commands there, and it can update and reboot the server. Sessions run as the SSH user, here `root`. berth does not apply such a server as a workstation. It stays a reachable or controller host, and the machines on it are created with the Incus or Docker provisioner. +`berth host install big` puts the controller alone on the server. berth can then report its status and run commands there, and it can update and reboot the server. Sessions run as the SSH user, here `root`. berth does not apply such a server as a workstation. It stays a host of the type `ssh` or `managed`, and the machines on it are created with the Incus or Docker provisioner. The recipes are in [`recipes/`](https://github.com/helightdev/berth/tree/main/recipes): `rescue-install` installs Ubuntu, and `incus-host` makes the server a host for machines. @@ -96,9 +96,9 @@ The recipes are in [`recipes/`](https://github.com/helightdev/berth/tree/main/re berth host install dock ``` -The controller is berthd and box with the files they read, from the same part of the role that a full apply runs. Nothing else of a workstation is installed: no accounts, desktop, agents or plugins. The SSH user is the account sessions run as, and its home is where the file calls may go. The host's level becomes `controller`, and its tasks are status, update, reboot and secrets. +The controller is berthd and box with the files they read, from the same part of the role that a full apply runs. Nothing else of a workstation is installed: no accounts, desktop, agents or plugins. The SSH user is the account sessions run as, and its home is where the file calls may go. The host's type becomes `managed`, and its actions are status, update, reboot and secrets. -The same is the host's action **Install the controller** on its overview, in berth-remote and over the API as `install-controller`. On a controller host it's called **Update the controller**: run it after updating berth, as berth's own version is all such a host is compared with. A workstation's controller comes with applying its configuration, so the action is not offered there. +The same is the host's action **Install the controller** on its overview, in berth-remote and over the API as `install-controller`. On a managed host it's called **Update the controller**: run it after updating berth, as berth's own version is all such a host is compared with. A workstation's controller comes with applying its configuration, so the action is not offered there. berth also refuses it on a host that is a workstation whatever its profile here says. It asks the host's controller first. The role checks again on the host before it changes anything. It stops when the host's record says workstation. It also stops when berthd there serves an account other than the SSH user. Installing the controller alone on such a host would take the workstation's controller apart. The overview and `berth tasks` say when a host is more than its profile, and how to adopt it. @@ -106,11 +106,11 @@ berth also refuses it on a host that is a workstation whatever its profile here On a host with systemd the controller is a service that starts at boot. Without systemd, as in most containers, the controller is installed but nothing on the host starts it. berth says so and waits a minute for it to answer. The install fails when it doesn't. Something on the host then has to run `/usr/local/bin/berthd`, as the init of a container can. -## Raising a level +## Changing the type | From | To | How | | --- | --- | --- | -| `reachable` | `controller` | Install the controller | -| `reachable` or `controller` | `workstation` | Set **Level** to `workstation` in the set-up, fill in the rest of the tabs, and apply | +| `ssh` | `managed` | Install the controller | +| `ssh` or `managed` | `workstation` | Set **Type** to `workstation` in the set-up, fill in the rest of the tabs, and apply | -berth never lowers a level, and never removes what it installed. +berth never takes a host back to a type with less, and never removes what it installed. diff --git a/docs/openapi/berth.openapi.json b/docs/openapi/berth.openapi.json index 3725279..c5cc28e 100644 --- a/docs/openapi/berth.openapi.json +++ b/docs/openapi/berth.openapi.json @@ -778,10 +778,6 @@ "null" ] }, - "level": { - "$ref": "#/components/schemas/HostLevel", - "description": "The level its profile means it to have." - }, "name": { "type": "string" }, @@ -795,14 +791,18 @@ "seen": { "oneOf": [ { - "$ref": "#/components/schemas/HostLevel", - "description": "The level it was seen to have: what its controller's record says,\n`reachable` when berth logged in and found no controller. Absent\nwhen it could not be asked." + "$ref": "#/components/schemas/HostType", + "description": "The type it was seen to be: what its controller's record says, `ssh`\nwhen berth logged in and found no controller. Absent when it could\nnot be asked." }, { "type": "null" } ] }, + "type": { + "$ref": "#/components/schemas/HostType", + "description": "The type its profile means it to be." + }, "version": { "description": "The version of its berthd.", "type": [ @@ -815,15 +815,15 @@ "name", "address", "reachable", - "level" + "type" ], "type": "object" }, - "HostLevel": { - "description": "How much of berth a host has: what its profile means it to have, or\nwhat it was seen to have. Each level can do what the ones before it can.", + "HostType": { + "description": "What berth does with a host: what its profile means it to be, or what it\nwas seen to be. They are in the order of how much of berth each has.", "enum": [ - "reachable", - "controller", + "ssh", + "managed", "workstation" ], "type": "string" @@ -3035,21 +3035,21 @@ } ] }, - "level": { + "mode": { + "description": "`system` or `single`.", + "type": "string" + }, + "type": { "oneOf": [ { - "$ref": "#/components/schemas/HostLevel", - "description": "What was installed on the host, by that record: `controller` when\nonly the controller was, `workstation` for a whole profile. Absent\nwhen the host keeps no record." + "$ref": "#/components/schemas/HostType", + "description": "What was installed on the host, by that record: `managed` when\nonly the controller was, `workstation` for a whole profile. Absent\nwhen the host keeps no record." }, { "type": "null" } ] }, - "mode": { - "description": "`system` or `single`.", - "type": "string" - }, "version": { "type": "string" } @@ -4238,7 +4238,7 @@ "schema": {} } }, - "description": "The whole profile. A workstation's has a builder object; a reachable or controller host's needs only level and access", + "description": "The whole profile. A workstation's has a builder object; a host of the type ssh or managed needs only type and access", "required": true }, "responses": { @@ -4263,7 +4263,7 @@ "description": "Not a profile, or not a name" } }, - "summary": "Save a host's profile: a new host, or a changed one. A host below a workstation needs only its level and access.", + "summary": "Save a host's profile: a new host, or a changed one. A host that is not a workstation needs only its type and access.", "tags": [ "set-up" ] diff --git a/docs/openapi/berth.operations.json b/docs/openapi/berth.operations.json index f01c8a0..e256c74 100644 --- a/docs/openapi/berth.operations.json +++ b/docs/openapi/berth.operations.json @@ -589,10 +589,6 @@ "null" ] }, - "level": { - "$ref": "#/components/schemas/HostLevel", - "description": "The level its profile means it to have." - }, "name": { "type": "string" }, @@ -606,14 +602,18 @@ "seen": { "oneOf": [ { - "$ref": "#/components/schemas/HostLevel", - "description": "The level it was seen to have: what its controller's record says,\n`reachable` when berth logged in and found no controller. Absent\nwhen it could not be asked." + "$ref": "#/components/schemas/HostType", + "description": "The type it was seen to be: what its controller's record says, `ssh`\nwhen berth logged in and found no controller. Absent when it could\nnot be asked." }, { "type": "null" } ] }, + "type": { + "$ref": "#/components/schemas/HostType", + "description": "The type its profile means it to be." + }, "version": { "description": "The version of its berthd.", "type": [ @@ -626,15 +626,15 @@ "name", "address", "reachable", - "level" + "type" ], "type": "object" }, - "HostLevel": { - "description": "How much of berth a host has: what its profile means it to have, or\nwhat it was seen to have. Each level can do what the ones before it can.", + "HostType": { + "description": "What berth does with a host: what its profile means it to be, or what it\nwas seen to be. They are in the order of how much of berth each has.", "enum": [ - "reachable", - "controller", + "ssh", + "managed", "workstation" ], "type": "string" @@ -2026,21 +2026,21 @@ } ] }, - "level": { + "mode": { + "description": "`system` or `single`.", + "type": "string" + }, + "type": { "oneOf": [ { - "$ref": "#/components/schemas/HostLevel", - "description": "What was installed on the host, by that record: `controller` when\nonly the controller was, `workstation` for a whole profile. Absent\nwhen the host keeps no record." + "$ref": "#/components/schemas/HostType", + "description": "What was installed on the host, by that record: `managed` when\nonly the controller was, `workstation` for a whole profile. Absent\nwhen the host keeps no record." }, { "type": "null" } ] }, - "mode": { - "description": "`system` or `single`.", - "type": "string" - }, "version": { "type": "string" } @@ -2297,7 +2297,7 @@ } ], "data": { - "description": "The whole profile. A workstation's has a builder object; a reachable or controller host's needs only level and access", + "description": "The whole profile. A workstation's has a builder object; a host of the type ssh or managed needs only type and access", "schema": {} }, "errors": [ @@ -2320,7 +2320,7 @@ } }, "role": "admin", - "summary": "Save a host's profile: a new host, or a changed one. A host below a workstation needs only its level and access." + "summary": "Save a host's profile: a new host, or a changed one. A host that is not a workstation needs only its type and access." }, { "args": [ diff --git a/docs/openapi/berthd.openapi.json b/docs/openapi/berthd.openapi.json index f95f483..1b4e5c4 100644 --- a/docs/openapi/berthd.openapi.json +++ b/docs/openapi/berthd.openapi.json @@ -337,11 +337,11 @@ ], "type": "object" }, - "HostLevel": { - "description": "How much of berth a host has: what its profile means it to have, or\nwhat it was seen to have. Each level can do what the ones before it can.", + "HostType": { + "description": "What berth does with a host: what its profile means it to be, or what it\nwas seen to be. They are in the order of how much of berth each has.", "enum": [ - "reachable", - "controller", + "ssh", + "managed", "workstation" ], "type": "string" @@ -1413,21 +1413,21 @@ } ] }, - "level": { + "mode": { + "description": "`system` or `single`.", + "type": "string" + }, + "type": { "oneOf": [ { - "$ref": "#/components/schemas/HostLevel", - "description": "What was installed on the host, by that record: `controller` when\nonly the controller was, `workstation` for a whole profile. Absent\nwhen the host keeps no record." + "$ref": "#/components/schemas/HostType", + "description": "What was installed on the host, by that record: `managed` when\nonly the controller was, `workstation` for a whole profile. Absent\nwhen the host keeps no record." }, { "type": "null" } ] }, - "mode": { - "description": "`system` or `single`.", - "type": "string" - }, "version": { "type": "string" } diff --git a/docs/openapi/berthd.operations.json b/docs/openapi/berthd.operations.json index 697af14..1e26067 100644 --- a/docs/openapi/berthd.operations.json +++ b/docs/openapi/berthd.operations.json @@ -337,11 +337,11 @@ ], "type": "object" }, - "HostLevel": { - "description": "How much of berth a host has: what its profile means it to have, or\nwhat it was seen to have. Each level can do what the ones before it can.", + "HostType": { + "description": "What berth does with a host: what its profile means it to be, or what it\nwas seen to be. They are in the order of how much of berth each has.", "enum": [ - "reachable", - "controller", + "ssh", + "managed", "workstation" ], "type": "string" @@ -1413,21 +1413,21 @@ } ] }, - "level": { + "mode": { + "description": "`system` or `single`.", + "type": "string" + }, + "type": { "oneOf": [ { - "$ref": "#/components/schemas/HostLevel", - "description": "What was installed on the host, by that record: `controller` when\nonly the controller was, `workstation` for a whole profile. Absent\nwhen the host keeps no record." + "$ref": "#/components/schemas/HostType", + "description": "What was installed on the host, by that record: `managed` when\nonly the controller was, `workstation` for a whole profile. Absent\nwhen the host keeps no record." }, { "type": "null" } ] }, - "mode": { - "description": "`system` or `single`.", - "type": "string" - }, "version": { "type": "string" } diff --git a/provision/ansible/roles/devbox/files/tasks/status.sh b/provision/ansible/roles/devbox/files/tasks/status.sh index 4f76085..783c0f5 100644 --- a/provision/ansible/roles/devbox/files/tasks/status.sh +++ b/provision/ansible/roles/devbox/files/tasks/status.sh @@ -3,7 +3,7 @@ # A host with berth's controller alone has no desktop, agents or tailnet of berth's. if [[ ${1:-} == controller ]]; then echo "Host $(hostname), up since $(uptime -s)" - echo "Level controller: berthd and box, nothing of a workstation" + echo "Type managed: berthd and box, nothing of a workstation" for unit in ssh berthd; do systemctl cat "$unit" >/dev/null 2>&1 && printf '%-11s %s\n' "$unit" "$(systemctl is-active "$unit" || true)" done diff --git a/recipes/incus-host/README.md b/recipes/incus-host/README.md index 944d8f9..4f2f519 100644 --- a/recipes/incus-host/README.md +++ b/recipes/incus-host/README.md @@ -65,9 +65,9 @@ berth host add big 192.0.2.20 --user root --auth ssh berth host install big ``` -`berth host add` saves `big` as a reachable host. `--auth ssh` makes berth log in with your own SSH configuration and agent, so the key that works for `ssh root@192.0.2.20` works for berth. The default, `--auth berth`, uses berth's own key, which berth installs on the first contact with a password or a private key that logs in once. `--auth ssh` works with a local berth only. With a berth server set, the server logs in with its own keys. +`berth host add` saves `big` as a host of the type `ssh`. `--auth ssh` makes berth log in with your own SSH configuration and agent, so the key that works for `ssh root@192.0.2.20` works for berth. The default, `--auth berth`, uses berth's own key, which berth installs on the first contact with a password or a private key that logs in once. `--auth ssh` works with a local berth only. With a berth server set, the server logs in with its own keys. -`berth host install big` puts the controller alone on the server. berth can then report its status and run commands there, and it can update and reboot the server. Sessions run as the SSH user, here `root`. berth never applies such a server as a workstation: it stays a reachable or controller host, and the machines on it are created with the Incus or Docker provisioner. +`berth host install big` puts the controller alone on the server. berth can then report its status and run commands there, and it can update and reboot the server. Sessions run as the SSH user, here `root`. berth never applies such a server as a workstation: it stays a host of the type `ssh` or `managed`, and the machines on it are created with the Incus or Docker provisioner. ## Settings diff --git a/tests/e2e/e2e_adopt.py b/tests/e2e/e2e_adopt.py index f7d8212..2d43b27 100644 --- a/tests/e2e/e2e_adopt.py +++ b/tests/e2e/e2e_adopt.py @@ -60,7 +60,7 @@ def test_berthd_serves_it(self): link = BerthdLink(self.station, key=self.station.key) self.assertEqual(link.get('/v1/applied/profile'), self.kept) # The controller says the host is a workstation, as the file shows. - self.assertEqual(link.get('/v1/version')['level'], 'workstation') + self.assertEqual(link.get('/v1/version')['type'], 'workstation') def test_another_berth_adopts_the_host_while_berthd_is_broken(self): adopter = Workstation('adopter') diff --git a/tests/e2e/e2e_controller.py b/tests/e2e/e2e_controller.py index 003f0d6..33d683e 100644 --- a/tests/e2e/e2e_controller.py +++ b/tests/e2e/e2e_controller.py @@ -47,15 +47,15 @@ def berth(self, *args, **kwargs): kwargs.setdefault('timeout', 120) return self.station.berth(*args, **kwargs) - def test_1_a_machine_added_by_its_address_is_only_reachable(self): - self.assertIn(f'Added {HOST} as a reachable host', self.added.stdout) + def test_1_a_machine_added_by_its_address_is_only_logged_in_to(self): + self.assertIn(f'Added {HOST} as a host of the type ssh', self.added.stdout) self.assertIn(f'{HOST} takes the key berth already', self.added.stdout) self.assertEqual(self.station.read_profile(), { - 'level': 'reachable', 'access': {'address': HOST, 'user': OPERATOR, 'auth': 'berth'}}) + 'type': 'ssh', 'access': {'address': HOST, 'user': OPERATOR, 'auth': 'berth'}}) self.assertEqual(self.berth('ssh', HOST, 'id -un').stdout.strip(), OPERATOR) listed = self.berth('tasks', HOST).stdout self.assertRegex(listed, r'(?m)^ install-controller\s+Install the controller') - # What needs more than a login is refused, and says what raises the level. + # What needs more than a login is refused, and says what changes the type. refused = self.berth('apply', HOST, check=False) self.assertNotEqual(refused.returncode, 0) self.assertIn('not a workstation', refused.stderr) @@ -66,13 +66,14 @@ def test_1_a_machine_added_by_its_address_is_only_reachable(self): def test_2_installing_the_controller_puts_berthd_and_box_there_alone(self): done = self.berth('host', 'install', HOST, timeout=600) - self.assertIn(f'{HOST} is a controller host now', done.stdout) + self.assertIn(f'{HOST} is a managed host now', done.stdout) self.assertIn(f"berth's controller answers on {HOST}", done.stdout) - self.assertEqual(self.station.read_profile()['level'], 'controller') + self.assertEqual(self.station.read_profile()['type'], 'managed') + # The role's record keeps the older name of the type. applied = json.loads(self.root('cat /etc/berth/applied.json').stdout) self.assertEqual((applied['level'], applied['plugins']), ('controller', [])) version = self.station.link().get('/v1/version') - self.assertEqual(version['level'], 'controller') + self.assertEqual(version['type'], 'managed') # Nothing of a workstation: no agent account, desktop or role record. for absent in ('id agent', 'test -e /etc/devbox', 'test -e /var/lib/devbox/status.json', 'test -e /etc/sudoers.d/90-devbox-agent', 'command -v Xvnc'): @@ -87,7 +88,7 @@ def test_3_sessions_and_tasks_run_as_the_ssh_user(self): self.assertNotRegex(listed, r'(?m)^ smoke\s+') self.assertRegex(listed, r'(?m)^ install-controller\s+Update the controller') status = self.berth('run', HOST, 'status') - self.assertIn('Level controller', status.stdout) + self.assertIn('Type managed', status.stdout) marker = random_text('controller') self.berth('exec', HOST, '--keep', '--', 'echo', marker) line = next(line for line in self.berth('sessions', HOST).stdout.splitlines() if marker in line) @@ -109,28 +110,28 @@ class OnAWorkstation(unittest.TestCase): a profile saved here under another name says the host is less: on `studio`, as provisioned() applied it.""" - def test_a_workstation_added_again_as_reachable_keeps_its_controller(self): + def test_a_workstation_added_again_as_ssh_keeps_its_controller(self): station = provisioned() files = 'cat /etc/berth/applied.json /etc/berth/berthd.json /etc/berth/tasks.json' before = station.root_on_host(files).stdout - added = station.berth('host', 'add', 'adopted', HOST, '--user', OPERATOR, '--level', 'reachable', input='') + added = station.berth('host', 'add', 'adopted', HOST, '--user', OPERATOR, '--type', 'ssh', input='') try: # berth sees what the host is, and says how to adopt it. - self.assertIn('adopted is a workstation; its profile here says reachable', added.stdout) + self.assertIn('adopted is a workstation; its profile here says ssh', added.stdout) self.assertIn('berth adopt adopted', added.stdout) listed = station.berth('tasks', 'adopted').stdout - self.assertIn('adopted is a workstation; its profile here says reachable', listed) + self.assertIn('adopted is a workstation; its profile here says ssh', listed) self.assertRegex(listed, r'(?m)^ install-controller\s+.*take its controller apart') refused = station.berth('host', 'install', 'adopted', check=False, timeout=600) self.assertNotEqual(refused.returncode, 0) self.assertIn('would take its controller apart', refused.stdout + refused.stderr) self.assertEqual(station.root_on_host(files).stdout, before) - self.assertEqual(station.read_profile('adopted')['level'], 'reachable') + self.assertEqual(station.read_profile('adopted')['type'], 'ssh') # Adopted from the profile the host keeps, by the address it was added at. adopted = station.berth('adopt', 'adopted') self.assertIn('Adopted adopted', adopted.stdout) profile = station.read_profile('adopted') - self.assertNotIn('level', profile) + self.assertNotIn('type', profile) saved = station.read_profile() for key in ('hostname', 'operator_ssh_public_keys', 'agent_ssh_public_keys', 'ansible_vars'): self.assertEqual(profile[key], saved[key], key) From 7f0015bb11f5fe9cd90db20996e5218cd35a72c4 Mon Sep 17 00:00:00 2001 From: Helight Date: Sun, 15 Nov 2026 00:17:52 +0100 Subject: [PATCH 10/94] refactor!: a profile says its target, not its profile The field that says what a host is installed on (laptop, cloud) is target now. The role keeps its variable devbox_profile, and bootstrap.sh reads a seed of either name. --- README.md | 2 +- crates/berth-api/src/profile.rs | 22 +++++------ crates/berth-core/src/apply.rs | 13 ++++--- crates/berth-core/src/import.rs | 2 +- crates/berth-core/src/kept_profile.rs | 4 +- crates/berth-core/src/provision.rs | 20 +++++----- crates/berth-page/src/setup.rs | 8 ++-- crates/berth-tui/src/fields.rs | 15 ++++---- crates/berth-tui/src/setup.rs | 37 +++++++++---------- crates/berth/src/app.rs | 10 ++--- crates/berth/src/main.rs | 16 ++++---- crates/berth/src/serve/tests.rs | 2 +- crates/berth/src/ui.rs | 18 ++++----- docs/content/docs/(guide)/deploy/ansible.mdx | 8 ++-- docs/content/docs/(guide)/deploy/cloud.mdx | 2 +- docs/content/docs/(guide)/deploy/index.mdx | 2 +- .../docs/(guide)/deploy/provisioners.mdx | 2 +- docs/content/docs/(guide)/deploy/qemu.mdx | 4 +- docs/content/docs/(guide)/deploy/usb.mdx | 2 +- .../docs/(guide)/reference/profile.mdx | 4 +- docs/content/docs/(guide)/start/concepts.mdx | 3 +- .../docs/(guide)/start/quick-start.mdx | 2 +- docs/content/docs/(guide)/use/cli.mdx | 2 +- docs/content/docs/(guide)/use/terminal-ui.mdx | 2 +- provision/bin/devbox.py | 16 ++++---- provision/bootstrap/bootstrap.sh | 3 +- provision/config/example.json | 2 +- tests/e2e/boot.py | 2 +- tests/e2e/e2e_own_key.py | 2 +- tests/e2e/harness.py | 2 +- tests/test_devbox.py | 34 +++++++++-------- tests/test_kept_profile.py | 4 +- 32 files changed, 135 insertions(+), 132 deletions(-) diff --git a/README.md b/README.md index 847c71c..062b5f2 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ curl -fsSL https://raw.githubusercontent.com/helightdev/berth/main/install-remot ## Quick start ```bash -berth studio # a new profile: choose how to install, features and settings +berth studio # a new host: choose how to install, features and settings berth # the home screen with all hosts berth run studio status ``` diff --git a/crates/berth-api/src/profile.rs b/crates/berth-api/src/profile.rs index 005ffe4..ff9f6b6 100644 --- a/crates/berth-api/src/profile.rs +++ b/crates/berth-api/src/profile.rs @@ -60,7 +60,7 @@ pub fn operator(config: &Value) -> &str { /// keep what they say. Says whether it changed the profile. pub fn settle_after_apply(config: &mut Value) -> bool { let mut access = Access::of(config); - if config["profile"] == "container" + if config["target"] == "container" || host_type(config) != crate::HostType::Workstation || access.link.is_some() || access.user.is_empty() @@ -473,14 +473,14 @@ pub fn joins_automatically(config: &Value) -> bool { /// Where a QEMU guest on the user-mode network sees the machine it runs on. pub const QEMU_HOST: &str = "10.0.2.2/32"; -/// Make a profile of the `qemu` kind there once was a `cloud` one. That kind -/// let SSH in only from the QEMU host when no recovery network was named, so +/// Make a profile of the `qemu` target there once was a `cloud` one. That +/// target let SSH in only from the QEMU host when no recovery network was named, so /// it gets that network rather than SSH open to every address. pub fn retire_qemu(config: &mut Value) { - if config["profile"] != "qemu" { + if config["target"] != "qemu" { return; } - config["profile"] = json!("cloud"); + config["target"] = json!("cloud"); if !config["ansible_vars"].is_object() { config["ansible_vars"] = json!({}); } @@ -583,7 +583,7 @@ mod tests { assert!(!asks_become_pass(&named)); // A container has no operator, and a host of another type was not set up by berth. let mut container = - json!({"profile": "container", "access": {"user": "ops", "sudo": "password"}}); + json!({"target": "container", "access": {"user": "ops", "sudo": "password"}}); assert!(!settle_after_apply(&mut container)); let mut managed = json!({"type": "managed", "access": {"address": "192.0.2.4", "user": "ops", "sudo": "password"}}); assert!(!settle_after_apply(&mut managed)); @@ -687,21 +687,21 @@ mod tests { #[test] fn a_qemu_profile_is_a_cloud_one_reached_from_the_qemu_host() { - let mut old = json!({"profile": "qemu"}); + let mut old = json!({"target": "qemu"}); retire_qemu(&mut old); assert_eq!( old, - json!({"profile": "cloud", "ansible_vars": {"devbox_bootstrap_ssh_cidr": "10.0.2.2/32"}}) + json!({"target": "cloud", "ansible_vars": {"devbox_bootstrap_ssh_cidr": "10.0.2.2/32"}}) ); // A network it names stays, and other kinds are left as they are. - let mut named = json!({"profile": "qemu", "ansible_vars": {"devbox_bootstrap_ssh_cidr": "192.0.2.0/24"}}); + let mut named = json!({"target": "qemu", "ansible_vars": {"devbox_bootstrap_ssh_cidr": "192.0.2.0/24"}}); retire_qemu(&mut named); - assert_eq!(named["profile"], "cloud"); + assert_eq!(named["target"], "cloud"); assert_eq!( named["ansible_vars"]["devbox_bootstrap_ssh_cidr"], "192.0.2.0/24" ); - for kept in [json!({"profile": "laptop"}), json!({"profile": "cloud"})] { + for kept in [json!({"target": "laptop"}), json!({"target": "cloud"})] { let mut profile = kept.clone(); retire_qemu(&mut profile); assert_eq!(profile, kept); diff --git a/crates/berth-core/src/apply.rs b/crates/berth-core/src/apply.rs index 3bf022a..6c1b947 100644 --- a/crates/berth-core/src/apply.rs +++ b/crates/berth-core/src/apply.rs @@ -62,7 +62,8 @@ pub fn ansible_vars(config: &Value, plugin_dirs: &Value, own: &[String]) -> Valu .filter(|key| !key.is_empty()) .collect(); vars["devbox_berth_ssh_public_key"] = json!(own.join("\n")); - vars["devbox_profile"] = config["profile"].clone(); + // The role names the target by its older name. + vars["devbox_profile"] = config["target"].clone(); vars["devbox_plugin_dirs"] = plugin_dirs.clone(); if let Some(key) = config["tailscale_auth_key"] .as_str() @@ -362,7 +363,7 @@ mod tests { #[test] fn variables_come_from_the_profile() { let config = json!({ - "profile": "cloud", "agent_username": "bot", "agent_privileges": "limited", + "target": "cloud", "agent_username": "bot", "agent_privileges": "limited", "tailscale_auth_key": "tskey", "ansible_vars": {"devbox_geometry": "1x1"}, "operator_ssh_public_key": "ssh-ed25519 ME", }); @@ -390,8 +391,8 @@ mod tests { assert_eq!(vars["devbox_tailscale_auth_key"], "tskey"); // A pasted key without a login server goes to Tailscale, as always. assert!(vars.get("devbox_tailscale_login_server").is_none()); - // A profile of the qemu kind there once was is applied as cloud, reached from the QEMU host. - let qemu = ansible_vars(&json!({"profile": "qemu"}), &json!({}), &[]); + // A profile of the qemu target there once was is applied as cloud, reached from the QEMU host. + let qemu = ansible_vars(&json!({"target": "qemu"}), &json!({}), &[]); assert_eq!(qemu["devbox_profile"], "cloud"); assert_eq!(qemu["devbox_bootstrap_ssh_cidr"], "10.0.2.2/32"); let headscale = json!({"tailscale_login_server": "https://hs.example.org"}); @@ -422,7 +423,7 @@ mod tests { let host = Host { name: "box".into(), place: Place::own("box").unwrap(), - config: json!({"profile": "cloud", "access": {"address": "box", "user": "ops", "sudo": "password"}}), + config: json!({"target": "cloud", "access": {"address": "box", "user": "ops", "sudo": "password"}}), }; let prepared = prepare(&paths, &host, Some("hunter2")).unwrap(); let args: Vec = prepared @@ -467,7 +468,7 @@ mod tests { paths.own_public_key().unwrap() ); assert_eq!(extra["devbox_berth_profile"]["host"], "box"); - assert_eq!(extra["devbox_berth_profile"]["profile"]["profile"], "cloud"); + assert_eq!(extra["devbox_berth_profile"]["profile"]["target"], "cloud"); assert!( extra["devbox_berth_profile"]["profile"] .get("access") diff --git a/crates/berth-core/src/import.rs b/crates/berth-core/src/import.rs index b5241bc..cc21ea0 100644 --- a/crates/berth-core/src/import.rs +++ b/crates/berth-core/src/import.rs @@ -1166,7 +1166,7 @@ mod tests { fs::create_dir_all(&hosts).unwrap(); fs::write( hosts.join("studio.json"), - r#"{"hostname": "studio", "profile": "cloud", "operator_username": "ops", + r#"{"hostname": "studio", "target": "cloud", "operator_username": "ops", "builder": {"ssh_host": "192.0.2.10", "ssh_user": "admin", "ssh_key": "", "ask_become_pass": true, "ask_pass": false}}"#, ) diff --git a/crates/berth-core/src/kept_profile.rs b/crates/berth-core/src/kept_profile.rs index 8b685d9..36a1411 100644 --- a/crates/berth-core/src/kept_profile.rs +++ b/crates/berth-core/src/kept_profile.rs @@ -436,7 +436,7 @@ mod tests { fn profile() -> Value { json!({ - "hostname": "studio", "profile": "cloud", + "hostname": "studio", "target": "cloud", "operator_username": "ops", "operator_password_hash": "$6$salt$hash", "operator_ssh_public_keys": ["ssh-ed25519 AAAA user"], "agent_username": "agent", "agent_password_hash": "$6$salt$agent", @@ -571,7 +571,7 @@ mod tests { let kept = json!({ "format": 1, "berth": "0.4.1", "host": "studio", "written": "2026-11-13T10:00:00Z", "profile": { - "hostname": "studio", "profile": "cloud", "operator_username": "ops", + "hostname": "studio", "target": "cloud", "operator_username": "ops", "operator_ssh_public_keys": ["ssh-ed25519 AAAA user"], "builder": {"ask_become_pass": true, "ask_pass": false, "shipped_plugins": true}, }, diff --git a/crates/berth-core/src/provision.rs b/crates/berth-core/src/provision.rs index d0fb669..bf641ae 100644 --- a/crates/berth-core/src/provision.rs +++ b/crates/berth-core/src/provision.rs @@ -565,16 +565,16 @@ pub fn prepare(paths: &Paths, store: &Store, host: &str, asked: &NewResource) -> }) } -/// Make the host's profile a `cloud` one before the machine is made from it: +/// Make the host's target `cloud` before the machine is made from it: /// a created machine has no laptop's physical login or power settings, and /// the seed is rendered from, or the role applied with, what is saved. -fn cloud_profile(paths: &Paths, host: &str) -> Result<()> { +fn cloud_target(paths: &Paths, host: &str) -> Result<()> { let place = Place::resolve(paths, host)?; let mut profile = place .load(paths)? .ok_or_else(|| format!("No host {host}"))?; - if profile["profile"] != "cloud" && profile.is_object() { - profile["profile"] = json!("cloud"); + if profile["target"] != "cloud" && profile.is_object() { + profile["target"] = json!("cloud"); place.save(paths, &profile)?; } Ok(()) @@ -630,7 +630,7 @@ impl Prepared { ) -> Result<()> { let (host, name) = (self.host.clone(), self.name.clone()); say(out, &format!("▸ {host}: creating its machine with {name}")); - cloud_profile(paths, &host)?; + cloud_target(paths, &host)?; let profile = Host::load(paths, &host)?; let mut request = resource::request( "create", @@ -1257,7 +1257,7 @@ out = build / config['hostname'] / 'cloud' out.mkdir(parents=True, exist_ok=True) (build / 'devbox-release.tar.gz').write_bytes(b'release') (out / 'user-data').write_text('#cloud-config\n# delivered=' + os.environ.get('BERTH_RELEASE_DELIVERED', '') + '\n' - + '# profile=' + config.get('profile', '') + '\n') + + '# target=' + config.get('target', '') + '\n') print(build / 'devbox-release.tar.gz') print(out) "#; @@ -1415,7 +1415,7 @@ print(out) &format!( "finished {} as {}", host.address(), - host.config["profile"].as_str().unwrap_or("") + host.config["target"].as_str().unwrap_or("") ), ); Ok(()) @@ -1823,10 +1823,10 @@ print(out) // A created machine is a cloud host, whatever the profile said before. assert_eq!( create["seed"]["user_data"], - "#cloud-config\n# delivered=1\n# profile=cloud\n" + "#cloud-config\n# delivered=1\n# target=cloud\n" ); let host = Host::load(&world.paths, "studio").unwrap(); - assert_eq!(host.config["profile"], "cloud"); + assert_eq!(host.config["target"], "cloud"); assert_eq!( create["seed"]["meta_data"], format!("instance-id: {token}\nlocal-hostname: studio\n") @@ -2027,7 +2027,7 @@ print(out) #[test] fn the_secrets_a_seed_carries_are_found_in_it() { - let deployment = json!({"profile": "cloud", "ansible_vars": { + let deployment = json!({"target": "cloud", "ansible_vars": { "devbox_tailscale_auth_key": "tskey-auth-kAbc123-xyz", "devbox_operator_password_hash": "$6$salt$hashhashhash", "devbox_operator_ssh_public_key": "ssh-ed25519 AAAAexample", diff --git a/crates/berth-page/src/setup.rs b/crates/berth-page/src/setup.rs index b420ee0..ffd5bf1 100644 --- a/crates/berth-page/src/setup.rs +++ b/crates/berth-page/src/setup.rs @@ -83,7 +83,7 @@ impl Setup { /// The set-up of a new host, from the server's starting profile. pub fn new(name: &str, template: Value, admin: &Admin) -> Setup { let mut setup = Setup::with(name, template, Value::Null); - setup::fit_profile(&mut setup.config, setup.action); + setup::fit_target(&mut setup.config, setup.action); setup.ask_machine(admin); setup } @@ -144,7 +144,7 @@ impl Setup { self.action = Action::Ssh; } // A profile saved with another kind opens as the machine's. - setup::fit_profile(&mut self.config, self.action); + setup::fit_target(&mut self.config, self.action); } Err(error) => self.failed = Some(error), } @@ -453,7 +453,7 @@ impl Setup { match entry { Entry::Action(action) => { self.action = action.choose(&mut self.config); - setup::fit_profile(&mut self.config, self.action); + setup::fit_target(&mut self.config, self.action); } Entry::Field(field) => return self.activate(field), Entry::Registry(index) => { @@ -472,7 +472,7 @@ impl Setup { // The machine is made from the profile, which has to be whole // first, and of the kind a created machine is. if pick == machine::Pick::Create { - setup::fit_profile(&mut self.config, Action::Machine); + setup::fit_target(&mut self.config, Action::Machine); } if pick == machine::Pick::Create && !self.problems().is_empty() { return Some("Fix the listed problems first".into()); diff --git a/crates/berth-tui/src/fields.rs b/crates/berth-tui/src/fields.rs index bd85f8c..34e0450 100644 --- a/crates/berth-tui/src/fields.rs +++ b/crates/berth-tui/src/fields.rs @@ -1,6 +1,7 @@ //! The settings the UI can edit, and the wizard steps and actions around them. -pub const PROFILES: &[&str] = &["laptop", "cloud"]; +/// What a host can be installed on, as its profile's `target` says. +pub const TARGETS: &[&str] = &["laptop", "cloud"]; pub const DISK_MODES: &[&str] = &[ "auto", "serial", "model", "path", "largest", "smallest", "ssd", "hdd", ]; @@ -219,7 +220,7 @@ pub struct Spec { #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Field { - Profile, + Target, Hostname, Keyboard, Geometry, @@ -277,11 +278,11 @@ impl Field { use Field::*; use Kind::*; let (label, pointer, kind, help) = match self { - Profile => ( - "Host profile", - "/profile", - Choice(PROFILES), - "Choose laptop or cloud provisioning defaults. Only laptop adds a physical login and power settings. Cloud leaves SSH open to any address when no recovery SSH CIDR is set; for a QEMU guest, set that to 10.0.2.2/32.", + Target => ( + "Target", + "/target", + Choice(TARGETS), + "What the host is installed on: laptop or cloud, with their provisioning defaults. Only laptop adds a physical login and power settings. Cloud leaves SSH open to any address when no recovery SSH CIDR is set; for a QEMU guest, set that to 10.0.2.2/32.", ), Hostname => ( "Hostname", diff --git a/crates/berth-tui/src/setup.rs b/crates/berth-tui/src/setup.rs index c99bac7..5635437 100644 --- a/crates/berth-tui/src/setup.rs +++ b/crates/berth-tui/src/setup.rs @@ -161,12 +161,12 @@ pub fn host_secrets(mut names: Vec) -> Vec { names } -/// Give the profile the host profile the way of installing it takes. A -/// seed would give a laptop's physical login and power settings to a server, -/// and a created machine has none, so both make the profile `cloud`. -pub fn fit_profile(config: &mut Value, action: Action) { - if action.seeds() && config["profile"] != "cloud" && config.is_object() { - config["profile"] = json!("cloud"); +/// Give the profile the target the way of installing it takes. A seed would +/// give a laptop's physical login and power settings to a server, and a +/// created machine has none, so both make the target `cloud`. +pub fn fit_target(config: &mut Value, action: Action) { + if action.seeds() && config["target"] != "cloud" && config.is_object() { + config["target"] = json!("cloud"); } } @@ -841,10 +841,10 @@ impl<'a> Profile<'a> { } return (vec![], after); } - // A created machine is always a cloud host, so there is no profile to choose. + // A created machine is always a cloud host, so there is no target to choose. let before = match action { Action::Machine => vec![], - _ => vec![Profile], + _ => vec![Target], }; let mut after = vec![]; if action == Action::Ssh { @@ -1185,7 +1185,7 @@ impl<'a> Profile<'a> { if matches!(self.action, Action::Machine | Action::Docker) { return None; } - let cloud = self.action == Action::CloudSeed || self.text(Field::Profile) == "cloud"; + let cloud = self.action == Action::CloudSeed || self.text(Field::Target) == "cloud"; (cloud && self.text(Field::RecoveryCidr).is_empty()).then(|| { if self.enabled(Field::HardenSsh) { "! No recovery SSH CIDR: SSH is reachable from any address (keys only)" @@ -1625,9 +1625,9 @@ mod tests { "{pair:?}" ); } - // A created machine is always a cloud host: there is no profile to choose. + // A created machine is always a cloud host: there is no target to choose. for elsewhere in [ - "Host profile", + "Target", "cpus", "Operator username", "Desktop size", @@ -1692,7 +1692,7 @@ mod tests { "agent_passwordless_sudo": true}); let machine = crate::machine::Machine::default(); let install = tab(&config, Action::CloudSeed, Step::Install, &machine); - assert!(place(&install, "Host profile") < place(&install, "Hostname studio")); + assert!(place(&install, "Target") < place(&install, "Hostname studio")); assert!( !install .iter() @@ -1840,7 +1840,7 @@ mod tests { #[test] fn an_existing_host_can_be_added_to_be_reached_over_ssh_alone() { - let mut config = json!({"profile": "laptop"}); + let mut config = json!({"target": "laptop"}); assert_eq!(Action::Reach.choose(&mut config), Action::Ssh); assert_eq!(config["type"], "ssh"); let machine = incus(); @@ -1879,10 +1879,7 @@ mod tests { "{rows:?}" ); assert!(!rows.iter().any(|row| row.contains("sudo")), "{rows:?}"); - assert!( - !rows.iter().any(|row| row.contains("Host profile")), - "{rows:?}" - ); + assert!(!rows.iter().any(|row| row.contains("Target")), "{rows:?}"); // Installing over SSH again means installing something. assert_eq!(Action::Ssh.choose(&mut config), Action::Ssh); assert!(config.get("type").is_none()); @@ -1899,9 +1896,9 @@ mod tests { (Action::Iso, "laptop", "laptop"), (Action::Ssh, "laptop", "laptop"), ] { - let mut config = json!({"profile": before}); - fit_profile(&mut config, action); - assert_eq!(config["profile"], after, "{action:?}"); + let mut config = json!({"target": before}); + fit_target(&mut config, action); + assert_eq!(config["target"], after, "{action:?}"); } } } diff --git a/crates/berth/src/app.rs b/crates/berth/src/app.rs index b8334fa..4303662 100644 --- a/crates/berth/src/app.rs +++ b/crates/berth/src/app.rs @@ -512,7 +512,7 @@ impl App { "/access/port", "/access/user", "/access/auth", - "/profile", + "/target", ] { let kept = profile.pointer(pointer).cloned().unwrap_or(Value::Null); if self.config.pointer(pointer) != Some(&kept) && !kept.is_null() { @@ -970,7 +970,7 @@ impl App { && !self.methods().contains(&self.action) { self.action = self.methods()[0]; - setup::fit_profile(&mut self.config, self.action); + setup::fit_target(&mut self.config, self.action); } // The Manage tab acts on the running host; the others on the install method. if step == Step::Manage { @@ -983,7 +983,7 @@ impl App { } // A profile saved with another kind opens as the machine's. if step != Step::Manage && self.action == Action::Machine { - setup::fit_profile(&mut self.config, self.action); + setup::fit_target(&mut self.config, self.action); } // A host with an address opens on its tasks rather than the address. let task = |entry: &Entry| matches!(entry, Entry::Task(_) | Entry::HostTask(_)); @@ -2475,7 +2475,7 @@ impl App { // The machine is made from the profile, which has to be whole first, // and of the kind a created machine is. if pick == machine::Pick::Create { - setup::fit_profile(&mut self.config, Action::Machine); + setup::fit_target(&mut self.config, Action::Machine); } if pick == machine::Pick::Create && !self.problems().is_empty() { self.status = "Fix the listed problems first".into(); @@ -2620,7 +2620,7 @@ pub fn parse_config(data: &[u8]) -> Result { } } for (key, value) in [ - ("profile", json!("laptop")), + ("target", json!("laptop")), ("keyboard", json!("de")), ("operator_username", json!("ops")), ("agent_username", json!("agent")), diff --git a/crates/berth/src/main.rs b/crates/berth/src/main.rs index ffee213..2b8f268 100644 --- a/crates/berth/src/main.rs +++ b/crates/berth/src/main.rs @@ -1113,14 +1113,14 @@ mod tests { assert_eq!(legacy["target_disk_mode"], "serial"); assert_eq!(legacy["wifi_enabled"], true); assert_eq!(legacy["release_url"], ""); - // A profile of the qemu kind there once was shows as cloud, reached from the QEMU host. - let qemu = parse_config(br#"{"profile": "qemu"}"#).unwrap(); - assert_eq!(qemu["profile"], "cloud"); + // A profile of the qemu target there once was shows as cloud, reached from the QEMU host. + let qemu = parse_config(br#"{"target": "qemu"}"#).unwrap(); + assert_eq!(qemu["target"], "cloud"); assert_eq!( qemu["ansible_vars"]["devbox_bootstrap_ssh_cidr"], "10.0.2.2/32" ); - let app = app(r#"{"profile": "qemu"}"#); + let app = app(r#"{"target": "qemu"}"#); assert_eq!(app.text(Field::RecoveryCidr), "10.0.2.2/32"); } @@ -1179,10 +1179,10 @@ mod tests { app.activate(Field::ToolsJvm); assert_eq!(app.config["ansible_vars"]["devbox_tools_jvm"], true); - app.activate(Field::Profile); - assert_eq!(app.text(Field::Profile), "cloud"); - app.commit(Field::Profile, "desktop"); - assert_eq!(app.text(Field::Profile), "cloud"); + app.activate(Field::Target); + assert_eq!(app.text(Field::Target), "cloud"); + app.commit(Field::Target, "desktop"); + assert_eq!(app.text(Field::Target), "cloud"); assert!(app.unsaved()); } diff --git a/crates/berth/src/serve/tests.rs b/crates/berth/src/serve/tests.rs index 30196bc..2d1125a 100644 --- a/crates/berth/src/serve/tests.rs +++ b/crates/berth/src/serve/tests.rs @@ -3926,7 +3926,7 @@ fn the_screen_keeps_the_address_a_server_gave_a_new_machine_and_opens_its_overvi // The server made the machine in a job of its own and gave its profile the address. let mut made = own.load(&served.state.paths).unwrap().unwrap(); made["access"] = json!({"address": "192.0.2.40", "user": "ops", "auth": "berth"}); - made["profile"] = json!("cloud"); + made["target"] = json!("cloud"); own.save(&served.state.paths, &made).unwrap(); let stage = crate::job::Stage { title: "Create machine".into(), diff --git a/crates/berth/src/ui.rs b/crates/berth/src/ui.rs index a67957f..a87f112 100644 --- a/crates/berth/src/ui.rs +++ b/crates/berth/src/ui.rs @@ -1017,7 +1017,7 @@ fn choose(app: &mut App, entry: Entry) -> Flow { match entry { Entry::Action(action) => { app.action = action.choose(&mut app.config); - berth_tui::setup::fit_profile(&mut app.config, app.action); + berth_tui::setup::fit_target(&mut app.config, app.action); } Entry::Field(field) => app.activate(field), Entry::Setup => app.set_step(Step::Install), @@ -4456,12 +4456,12 @@ mod tests { ) }; // What `berth provision` does from the screen: the machine's address - // and the cloud profile go into the stored profile. + // and the cloud target go into the stored profile. let provisioned = |port: &str| { let mut kept = place.load(&paths).unwrap().unwrap(); kept["access"]["address"] = json!("192.0.2.40"); kept["access"]["port"] = json!(port); - kept["profile"] = json!("cloud"); + kept["target"] = json!("cloud"); place.save(&paths, &kept).unwrap(); }; let mut app = open(); @@ -4484,7 +4484,7 @@ mod tests { app.save().unwrap(); let kept = place.load(&paths).unwrap().unwrap(); assert_eq!( - (&kept["access"]["port"], &kept["keyboard"], &kept["profile"]), + (&kept["access"]["port"], &kept["keyboard"], &kept["target"]), (&json!("2200"), &json!("us"), &json!("cloud")) ); } @@ -4556,7 +4556,7 @@ mod tests { assert_eq!(app.action, Action::Iso); let install = screen(&mut app); assert!(install.contains("● USB installer")); - assert!(install.contains("▌ Host profile laptop"), "{install}"); + assert!(install.contains("▌ Target laptop"), "{install}"); assert!(install.contains("Suggestions")); assert!(!install.contains("Disk selection") && !install.contains("Source ISO")); @@ -5232,18 +5232,18 @@ mod tests { fn the_provisioner_is_a_choice_like_the_others() { use KeyCode::*; use berth_tui::machine::Pick; - let mut app = unsaved_app(br#"{"profile": "laptop"}"#); + let mut app = unsaved_app(br#"{"target": "laptop"}"#); app.machine.asking(); app.machine.listed(Ok(vec![ lab("lab/vm", "Lab machine", &["cpus"]), lab("lab/box", "Lab box", &[]), ])); app.machine.found(Ok(None)); - // Choosing the way makes the profile a cloud one, and offers none to choose. + // Choosing the way makes the target cloud, and offers none to choose. select(&mut app, Entry::Action(Action::Machine)); press(&mut app, &[Enter]); - assert_eq!(app.config["profile"], "cloud"); - assert!(!lines(&app).iter().any(|row| row.contains("Host profile"))); + assert_eq!(app.config["target"], "cloud"); + assert!(!lines(&app).iter().any(|row| row.contains("Target"))); // The row offers the provisioners in the panel, at the chosen one. select(&mut app, Entry::Machine(Pick::Provisioner)); let shown = screen(&mut app); diff --git a/docs/content/docs/(guide)/deploy/ansible.mdx b/docs/content/docs/(guide)/deploy/ansible.mdx index 51e6376..0e8454c 100644 --- a/docs/content/docs/(guide)/deploy/ansible.mdx +++ b/docs/content/docs/(guide)/deploy/ansible.mdx @@ -57,17 +57,17 @@ Remote runs also leave the current SSH source address open in the firewall when -## Profiles +## Targets -`devbox_profile` selects defaults for the kind of machine: +`devbox_profile` selects defaults for the target, the kind of machine the host is installed on. A berth profile says it as `target`: -| Profile | For | +| Target | For | | --- | --- | | `laptop` | Physical machines, with the LightDM login and power defaults | | `cloud` | Cloud instances, virtual machines and tests. Set a bootstrap SSH CIDR to limit SSH, such as `10.0.2.2/32` for a QEMU guest | | `container` | The container image | -Cloud networking and disks are left as they are in every profile. The agent's username and home are configurable, and its UID is discovered rather than assumed. +Cloud networking and disks are left as they are on every target. The agent's username and home are configurable, and its UID is discovered rather than assumed. ## Settings diff --git a/docs/content/docs/(guide)/deploy/cloud.mdx b/docs/content/docs/(guide)/deploy/cloud.mdx index 3570536..7c617d5 100644 --- a/docs/content/docs/(guide)/deploy/cloud.mdx +++ b/docs/content/docs/(guide)/deploy/cloud.mdx @@ -17,7 +17,7 @@ The seed gives the operator [the key of berth itself](/docs/reference/profile#th ### Set the profile -Create the host. On **Install**, choose **Cloud-init seed**, which switches a `laptop` **Host profile** to `cloud`. For the host to join the tailnet on first boot, give it an enrollment key there or switch on **Automatic enrollment key** ([joining the tailnet](/docs/use/access#joining-the-tailnet)). +Create the host. On **Install**, choose **Cloud-init seed**, which switches a `laptop` **Target** to `cloud`. For the host to join the tailnet on first boot, give it an enrollment key there or switch on **Automatic enrollment key** ([joining the tailnet](/docs/use/access#joining-the-tailnet)). diff --git a/docs/content/docs/(guide)/deploy/index.mdx b/docs/content/docs/(guide)/deploy/index.mdx index f5b372c..e29a396 100644 --- a/docs/content/docs/(guide)/deploy/index.mdx +++ b/docs/content/docs/(guide)/deploy/index.mdx @@ -55,7 +55,7 @@ The set-up of a host has four tabs. Each tab depends only on the tabs before it. | Tab | What it holds | | --- | --- | -| Install | How to install, with the host profile (not for a created machine, which is always `cloud`), the provisioner and its required arguments, the SSH address, the hostname and Tailscale | +| Install | How to install, with the target (not for a created machine, which is always `cloud`), the provisioner and its required arguments, the SSH address, the hostname and Tailscale | | Features | What gets installed, including Cockpit and Docker on the host | | Settings | Everything with a default, such as the machine's resources, the accounts, registries and secrets, and the installer's disk and Wi-Fi | | Run | The last files for the method, every problem, and the buttons | diff --git a/docs/content/docs/(guide)/deploy/provisioners.mdx b/docs/content/docs/(guide)/deploy/provisioners.mdx index 9314775..425b391 100644 --- a/docs/content/docs/(guide)/deploy/provisioners.mdx +++ b/docs/content/docs/(guide)/deploy/provisioners.mdx @@ -247,7 +247,7 @@ In the terminal UI, choose **Create a machine** under **How To Install** on the | Settings | Under **Machine**, the resources it has, such as CPUs, memory and disk. Under **Provisioner Options**, its other arguments | | Run | **Create machine**, and every problem | -The first provisioner is chosen when the list arrives. There is no **Host profile** row. A created machine is always a `cloud` host. berth writes that into the profile before it creates the machine, on the command line as well. Enter on an argument changes it. A missing secret is a problem of the Install tab, and a bad resource value one of the Settings tab. **Create machine** on the Run tab asks once before it saves the profile and starts, and does not start while a problem is listed. The output is shown as it runs. [berth-remote](/docs/use/server#with-berth-remote) has the same tabs. +The first provisioner is chosen when the list arrives. There is no **Target** row. A created machine always has the target `cloud`. berth writes that into the profile before it creates the machine, on the command line as well. Enter on an argument changes it. A missing secret is a problem of the Install tab, and a bad resource value one of the Settings tab. **Create machine** on the Run tab asks once before it saves the profile and starts, and does not start while a problem is listed. The output is shown as it runs. [berth-remote](/docs/use/server#with-berth-remote) has the same tabs. Only one thing runs at a time for a host. A second command for the same host is refused until the first ends. diff --git a/docs/content/docs/(guide)/deploy/qemu.mdx b/docs/content/docs/(guide)/deploy/qemu.mdx index 1496a6a..fe6a56a 100644 --- a/docs/content/docs/(guide)/deploy/qemu.mdx +++ b/docs/content/docs/(guide)/deploy/qemu.mdx @@ -12,7 +12,7 @@ QEMU, OVMF firmware and `cloud-image-utils` on your machine. Optionally Canonica ## Make a test host -Create a separate host with `profile: cloud` and the recovery SSH CIDR `10.0.2.2/32`, QEMU's address for your machine. For the USB installer, use disk mode `auto`, or `serial` with the virtual serial `DEVBOX_TEST_DISK`. Check the virtio disk's udev identifier in the VM installer if it differs. +Create a separate host with `target: cloud` and the recovery SSH CIDR `10.0.2.2/32`, QEMU's address for your machine. For the USB installer, use disk mode `auto`, or `serial` with the virtual serial `DEVBOX_TEST_DISK`. Check the virtio disk's udev identifier in the VM installer if it differs. Never put a physical machine's disk serial into a VM seed, or a VM's into a physical one. @@ -53,7 +53,7 @@ python3 provision/bin/qemu.py cloud --directory build/vm-cloud \ -To test the role without publishing a release, boot the cloud image with a minimal user data that only creates your login. Then use **Existing host over SSH** against `127.0.0.1` port 2222 with the `qemu` profile. +To test the role without publishing a release, boot the cloud image with a minimal user data that only creates your login. Then use **Existing host over SSH** against `127.0.0.1` port 2222 with the target `cloud` and the recovery SSH CIDR `10.0.2.2/32`. diff --git a/docs/content/docs/(guide)/deploy/usb.mdx b/docs/content/docs/(guide)/deploy/usb.mdx index b63cd60..5e641ce 100644 --- a/docs/content/docs/(guide)/deploy/usb.mdx +++ b/docs/content/docs/(guide)/deploy/usb.mdx @@ -27,7 +27,7 @@ The USB installer is the Ubuntu Server 26.04 ISO with the host's profile built i berth garage-laptop ``` -It opens on **Install**. Choose **USB installer** under **How To Install**, and keep **Host profile** at `laptop`. **Hostname** is the name the machine gets. F4 generates one. +It opens on **Install**. Choose **USB installer** under **How To Install**, and keep **Target** at `laptop`. **Hostname** is the name the machine gets. F4 generates one. diff --git a/docs/content/docs/(guide)/reference/profile.mdx b/docs/content/docs/(guide)/reference/profile.mdx index bbd2ce9..0ad7de4 100644 --- a/docs/content/docs/(guide)/reference/profile.mdx +++ b/docs/content/docs/(guide)/reference/profile.mdx @@ -20,7 +20,7 @@ Settings of the Ansible role go under `ansible_vars`, and how berth reaches and ```json title="studio's profile (excerpt)" { "hostname": "studio", - "profile": "laptop", + "target": "laptop", "operator_username": "ops", "operator_ssh_public_keys": ["ssh-ed25519 AAAA... you@workstation"], "agent_username": "agent", @@ -39,7 +39,7 @@ Settings of the Ansible role go under `ansible_vars`, and how berth reaches and diff --git a/docs/content/docs/(guide)/use/cli.mdx b/docs/content/docs/(guide)/use/cli.mdx index bba5b5d..d245766 100644 --- a/docs/content/docs/(guide)/use/cli.mdx +++ b/docs/content/docs/(guide)/use/cli.mdx @@ -15,7 +15,7 @@ With a [berth server](/docs/use/server) set, by `--server` or the `server` setti | Command | Does | | --- | --- | | `berth` | The home screen | -| `berth HOST` | Open a host in the terminal UI; a new name starts a new profile | +| `berth HOST` | Open a host in the terminal UI; a new name starts a new host | | `berth list` | Saved hosts and their addresses | | `berth host add NAME ADDRESS [--user USER] [--port PORT] [--auth AUTH] [--type TYPE] [--no-contact]` | Save a machine that exists by its address, of the type `ssh` unless `--type` says otherwise, and install berth's key there ([Host types](/docs/use/types#adding-a-machine-that-exists)) | | `berth profile HOST` | The host's profile, as JSON on standard output | diff --git a/docs/content/docs/(guide)/use/terminal-ui.mdx b/docs/content/docs/(guide)/use/terminal-ui.mdx index 77d9a28..46ea315 100644 --- a/docs/content/docs/(guide)/use/terminal-ui.mdx +++ b/docs/content/docs/(guide)/use/terminal-ui.mdx @@ -34,7 +34,7 @@ Each tab depends only on the tabs before it. Install holds what you have to choo | Set-up tab | For | | --- | --- | -| `1` Install | How to install, with the host profile (not for a created machine, which is always `cloud`), the provisioner and its required arguments, the SSH address, the hostname and Tailscale | +| `1` Install | How to install, with the target (not for a created machine, which is always `cloud`), the provisioner and its required arguments, the SSH address, the hostname and Tailscale | | `2` Features | The coding agents and T3 Code, with tool categories, browsers, graphics, Cockpit, Docker on the host and plugin features | | `3` Settings | Everything with a default. See the list below | | `4` Run | The last files for the method, every problem grouped by tab, warnings, and the Run, Create machine and Save buttons | diff --git a/provision/bin/devbox.py b/provision/bin/devbox.py index 9cd928c..42c77c8 100755 --- a/provision/bin/devbox.py +++ b/provision/bin/devbox.py @@ -32,7 +32,7 @@ 'crates/berth/Cargo.toml', 'crates/berth/build.rs', 'crates/berth/src', 'crates/vendor/tui-input', 'crates/vendor/README.md', ] -PROFILES = {'laptop', 'cloud'} +TARGETS = {'laptop', 'cloud'} # Where a QEMU guest on the user-mode network sees the machine it runs on. QEMU_HOST = '10.0.2.2/32' DEFAULT_OPERATOR = 'ops' @@ -145,12 +145,12 @@ def release_delivered(): def retire_qemu(c): - """A profile of the qemu kind there once was, as the cloud one it is now. - That kind let SSH in only from the QEMU host when no recovery network was + """A profile of the qemu target there once was, as the cloud one it is now. + That target let SSH in only from the QEMU host when no recovery network was named, so it gets that network rather than SSH open to every address.""" - if c.get('profile') != 'qemu': + if c.get('target') != 'qemu': return c - c = dict(c, profile='cloud') + c = dict(c, target='cloud') variables = dict(c.get('ansible_vars') or {}) if not variables.get('devbox_bootstrap_ssh_cidr'): variables['devbox_bootstrap_ssh_cidr'] = QEMU_HOST @@ -166,8 +166,8 @@ def checked_config(path, kind): c = retire_qemu(c) if not HOSTNAME.fullmatch(text(c, 'hostname')): raise ValueError('Invalid hostname: use lowercase letters, digits and hyphens, starting with a letter') - if text(c, 'profile') not in PROFILES: - raise ValueError('profile must be laptop or cloud') + if text(c, 'target') not in TARGETS: + raise ValueError('target must be laptop or cloud') operator = text(c, 'operator_username', DEFAULT_OPERATOR) agent = text(c, 'agent_username', 'agent') @@ -305,7 +305,7 @@ def deployment(c, sha): # berth hands over the profile as the host keeps it, and the role writes it. if isinstance(c.get('berth_profile'), dict): variables['devbox_berth_profile'] = c['berth_profile'] - return {'profile': c['profile'], 'release_sha256': sha, + return {'target': c['target'], 'release_sha256': sha, 'release_url': '' if release_delivered() else c.get('release_url', ''), 'ansible_vars': variables} diff --git a/provision/bootstrap/bootstrap.sh b/provision/bootstrap/bootstrap.sh index 5a6571a..3d1a351 100755 --- a/provision/bootstrap/bootstrap.sh +++ b/provision/bootstrap/bootstrap.sh @@ -90,7 +90,8 @@ import json, os from pathlib import Path d=json.loads(Path('/opt/devbox-bootstrap/deployment.json').read_text()) p=Path('/etc/devbox'); p.mkdir(parents=True,exist_ok=True) -v=d['ansible_vars']; v['devbox_profile']=d['profile'] +# The role names the target by its older name, as did the seeds of berth 0.5. +v=d['ansible_vars']; v['devbox_profile']=d.get('target', d.get('profile')) # A seed of the qemu kind there once was is a cloud host that SSH reaches only from the QEMU host. if v['devbox_profile']=='qemu': v['devbox_profile']='cloud' diff --git a/provision/config/example.json b/provision/config/example.json index e075f9e..5f4ca16 100644 --- a/provision/config/example.json +++ b/provision/config/example.json @@ -1,6 +1,6 @@ { "hostname": "", - "profile": "laptop", + "target": "laptop", "operator_username": "ops", "operator_ssh_public_keys": [], "operator_password_hash": "", diff --git a/tests/e2e/boot.py b/tests/e2e/boot.py index 53556d9..0071386 100644 --- a/tests/e2e/boot.py +++ b/tests/e2e/boot.py @@ -83,7 +83,7 @@ def password_hash(): def boot_profile(station, kind, **values): profile = json.loads((SRC / 'provision/config/example.json').read_text()) profile.update({ - 'hostname': HOST, 'profile': 'cloud', 'keyboard': 'us', + 'hostname': HOST, 'target': 'cloud', 'keyboard': 'us', # As berth writes a new host: the shipped plugins' features are chosen # in the list, not switched on for a profile from before them. 'builder': {'shipped_plugins': True}, diff --git a/tests/e2e/e2e_own_key.py b/tests/e2e/e2e_own_key.py index dac08e6..0f0b718 100644 --- a/tests/e2e/e2e_own_key.py +++ b/tests/e2e/e2e_own_key.py @@ -23,7 +23,7 @@ def bare_profile(template): """A profile for the test host as a new host starts, with no SSH key in it.""" profile = json.loads(json.dumps(template)) - profile.update({'hostname': HOST, 'profile': 'cloud', 'keyboard': 'us', 'ansible_vars': light_vars()}) + profile.update({'hostname': HOST, 'target': 'cloud', 'keyboard': 'us', 'ansible_vars': light_vars()}) profile['builder'] = {'shipped_plugins': True} profile['access'] = {'address': HOST, 'user': OPERATOR, 'auth': 'berth'} return profile diff --git a/tests/e2e/harness.py b/tests/e2e/harness.py index b090cbe..b0e843d 100644 --- a/tests/e2e/harness.py +++ b/tests/e2e/harness.py @@ -269,7 +269,7 @@ def profile(**values): """A profile like berth writes for a new host, with the test host's address.""" base = json.loads((SRC / 'provision/config/example.json').read_text()) base.update({ - 'hostname': HOST, 'profile': 'cloud', 'keyboard': 'us', + 'hostname': HOST, 'target': 'cloud', 'keyboard': 'us', # The operator's sudo needs no password, as by default, so berth asks # for none. shipped_plugins says the features are chosen already, as # in every profile berth saves. berth logs in with the user's SSH diff --git a/tests/test_devbox.py b/tests/test_devbox.py index d56306a..ee37127 100755 --- a/tests/test_devbox.py +++ b/tests/test_devbox.py @@ -20,7 +20,7 @@ def load(name,path): guard=load('guard','provision/bin/check-target-disk.py') def config(): - return {'hostname':'test-devbox','profile':'cloud', + return {'hostname':'test-devbox','target':'cloud', 'operator_ssh_public_key':'ssh-ed25519 '+base64.b64encode(b'\0'*64).decode(), 'operator_password_hash':'$6$salt$'+'a'*86,'target_disk_serial':'DEVBOX_TEST_DISK', 'release_url':'https://example.com/devbox.tar.gz', @@ -98,7 +98,7 @@ def test_cloud_seed_carries_a_release_login_only_when_given(self): self.assertRaises(ValueError,builder.cloud_config,config(),'a'*64) def test_only_the_usb_installer_needs_an_operator_password(self): with tempfile.TemporaryDirectory() as d: - path=Path(d)/'c.json'; c=config(); c['profile']='cloud'; del c['operator_password_hash'] + path=Path(d)/'c.json'; c=config(); c['target']='cloud'; del c['operator_password_hash'] path.write_text(json.dumps(c)) operator=builder.cloud_config(builder.checked_config(path,'cloud'),'a'*64)['users'][1] # Locked with `*`, not `!`: sshd without PAM refuses keys for an account locked with `!`. @@ -107,7 +107,7 @@ def test_only_the_usb_installer_needs_an_operator_password(self): with self.assertRaises(ValueError): builder.checked_config(path,'usb') # A profile from when the operator's sudo could ask still renders, and gets no password. for laptop in ('cloud','laptop'): - c['operator_passwordless_sudo']=False; c['profile']=laptop; path.write_text(json.dumps(c)) + c['operator_passwordless_sudo']=False; c['target']=laptop; path.write_text(json.dumps(c)) builder.checked_config(path,'cloud') operator=builder.cloud_config(config(),'a'*64)['users'][1] self.assertEqual((operator['lock_passwd'],operator['passwd']),(False,config()['operator_password_hash'])) @@ -202,20 +202,20 @@ def test_cloud_recovery_network_is_optional_but_checked(self): builder.checked_config(path,'cloud') c['ansible_vars']={'devbox_bootstrap_ssh_cidr':'not a network'}; path.write_text(json.dumps(c)) with self.assertRaises(ValueError): builder.checked_config(path,'cloud') - def test_a_qemu_profile_is_a_cloud_one_reached_from_the_qemu_host(self): + def test_a_qemu_target_is_a_cloud_one_reached_from_the_qemu_host(self): with tempfile.TemporaryDirectory() as temp: path=Path(temp)/'host.json' - c=config(); c['profile']='qemu'; c['ansible_vars']={}; path.write_text(json.dumps(c)) + c=config(); c['target']='qemu'; c['ansible_vars']={}; path.write_text(json.dumps(c)) checked=builder.checked_config(path,'cloud') - self.assertEqual(checked['profile'],'cloud') + self.assertEqual(checked['target'],'cloud') self.assertEqual(checked['ansible_vars']['devbox_bootstrap_ssh_cidr'],'10.0.2.2/32') - self.assertEqual(builder.deployment(checked,'a'*64)['profile'],'cloud') + self.assertEqual(builder.deployment(checked,'a'*64)['target'],'cloud') # A network it names stays; laptop and cloud are left alone. c['ansible_vars']={'devbox_bootstrap_ssh_cidr':'192.0.2.0/24'}; path.write_text(json.dumps(c)) self.assertEqual(builder.checked_config(path,'cloud')['ansible_vars']['devbox_bootstrap_ssh_cidr'],'192.0.2.0/24') for kept in ['laptop','cloud']: - self.assertEqual(builder.retire_qemu({'profile':kept}),{'profile':kept}) - c['profile']='desktop'; path.write_text(json.dumps(c)) + self.assertEqual(builder.retire_qemu({'target':kept}),{'target':kept}) + c['target']='desktop'; path.write_text(json.dumps(c)) with self.assertRaisesRegex(ValueError,'laptop or cloud'): builder.checked_config(path,'cloud') def test_bootstrap_hands_a_qemu_seed_to_the_role_as_cloud(self): script=(ROOT/'provision/bootstrap/bootstrap.sh').read_text() @@ -223,14 +223,16 @@ def test_bootstrap_hands_a_qemu_seed_to_the_role_as_cloud(self): handover=script[start:script.index('\nPY\n',start)] with tempfile.TemporaryDirectory() as temp: root=Path(temp) - deployment={'profile':'qemu','ansible_vars':{'devbox_user':'agent'}} code=(handover.replace("/opt/devbox-bootstrap/deployment.json",str(root/'deployment.json')) .replace("Path('/etc/devbox')","Path(%r)"%str(root/'etc'))) - (root/'deployment.json').write_text(json.dumps(deployment)) - subprocess.run([sys.executable,'-c',code],check=True) - handed=json.loads((root/'etc/host.json').read_text()) - self.assertEqual(handed['devbox_profile'],'cloud') - self.assertEqual(handed['devbox_bootstrap_ssh_cidr'],'10.0.2.2/32') + # A seed of berth 0.5 named the target profile. + for key in ('target','profile'): + deployment={key:'qemu','ansible_vars':{'devbox_user':'agent'}} + (root/'deployment.json').write_text(json.dumps(deployment)) + subprocess.run([sys.executable,'-c',code],check=True) + handed=json.loads((root/'etc/host.json').read_text()) + self.assertEqual(handed['devbox_profile'],'cloud',key) + self.assertEqual(handed['devbox_bootstrap_ssh_cidr'],'10.0.2.2/32',key) def test_accounts_take_several_keys_and_the_operator_this_berths(self): key=lambda byte:'ssh-ed25519 '+base64.b64encode(bytes([byte])*64).decode() c={**config(),'operator_ssh_public_keys':[key(1),key(1)],'agent_ssh_public_keys':[key(2),key(3)]} @@ -266,7 +268,7 @@ def test_accounts_take_several_keys_and_the_operator_this_berths(self): path=Path(temp)/'host.json'; path.write_text(json.dumps(only)) with self.assertRaises(ValueError): builder.checked_config(path,'cloud') def test_malformed_profiles_are_rejected_cleanly(self): - for change in [{'hostname':None},{'hostname':'trailing-'},{'profile':'container'}, + for change in [{'hostname':None},{'hostname':'trailing-'},{'target':'container'}, {'agent_ssh_public_key':'not a key'},{'operator_username':'root'}, {'agent_username':'ops'},{'operator_username':'operator'},{'agent_username':'admin'},{'agent_passwordless_sudo':'no'}, {'ansible_vars':{'other':1}},{'target_disk_mode':'serial','target_disk_serial':''}]: diff --git a/tests/test_kept_profile.py b/tests/test_kept_profile.py index 48cb12f..c7b6efd 100644 --- a/tests/test_kept_profile.py +++ b/tests/test_kept_profile.py @@ -43,11 +43,11 @@ def playbook(): class SeedTests(unittest.TestCase): def test_the_seed_builder_hands_the_kept_profile_to_the_first_boot(self): builder = load('builder', 'provision/bin/devbox.py') - c = {'profile': 'cloud', 'tailscale_auth_key': 'tskey-once', 'berth_profile': DOCUMENT} + c = {'target': 'cloud', 'tailscale_auth_key': 'tskey-once', 'berth_profile': DOCUMENT} variables = builder.deployment(c, 'a' * 64)['ansible_vars'] self.assertEqual(variables['devbox_berth_profile'], DOCUMENT) # A profile written without berth keeps nothing. - self.assertNotIn('devbox_berth_profile', builder.deployment({'profile': 'cloud'}, 'a' * 64)['ansible_vars']) + self.assertNotIn('devbox_berth_profile', builder.deployment({'target': 'cloud'}, 'a' * 64)['ansible_vars']) # The first boot reads these variables from host.json and strips only the key. self.assertNotIn('tskey', json.dumps(variables['devbox_berth_profile'])) From 8ebd61c903a9401294d577646198943d69ef8966 Mon Sep 17 00:00:00 2001 From: Helight Date: Sun, 15 Nov 2026 00:23:35 +0100 Subject: [PATCH 11/94] feat(core): read profiles of berth 0.5 with the names of now A seventh import gives every stored profile type and target in place of level and profile, in one change with its marker; the rows may be sealed, so a migration of the database cannot. Profiles read from the store, from files, from --set and from what a host keeps take the new names too, and the kept profile is format 3 so that an older berth asks to be updated instead of misreading it. The API of berth serve takes the new names only. --- crates/berth-api/src/profile.rs | 66 ++++++++ crates/berth-core/src/import.rs | 147 ++++++++++++++++-- crates/berth-core/src/kept_profile.rs | 42 ++++- crates/berth-core/src/profiles.rs | 19 ++- crates/berth-core/src/store/suite.rs | 55 +++++++ crates/berth/src/app.rs | 1 + crates/berth/src/commands.rs | 15 ++ crates/berth/src/serve/setup.rs | 4 +- crates/berth/src/serve/tests.rs | 5 + .../docs/(guide)/reference/profile.mdx | 13 ++ docs/content/docs/(guide)/use/moving.mdx | 2 +- docs/content/docs/(guide)/use/types.mdx | 2 + docs/content/docs/(guide)/use/updates.mdx | 4 +- provision/bin/devbox.py | 18 ++- tests/e2e/e2e_adopt.py | 2 +- tests/test_devbox.py | 12 ++ 16 files changed, 381 insertions(+), 26 deletions(-) diff --git a/crates/berth-api/src/profile.rs b/crates/berth-api/src/profile.rs index ff9f6b6..2de3a8d 100644 --- a/crates/berth-api/src/profile.rs +++ b/crates/berth-api/src/profile.rs @@ -329,6 +329,42 @@ pub fn minimal(host_type: crate::HostType, access: &Access) -> Value { config } +/// Give a profile of berth 0.5 or earlier the names fields have now: +/// `level` (`reachable`, `controller`, `workstation`) becomes `type` +/// (`ssh`, `managed`, a workstation left unsaid), and `profile`, what the +/// host is installed on, becomes `target`. What a later berth wrote stays. +/// Says whether it changed the profile. +pub fn take_old_names(config: &mut Value) -> bool { + let Some(profile) = config.as_object_mut() else { + return false; + }; + let mut changed = false; + if let Some(level) = profile.remove("level") { + changed = true; + if !profile.contains_key("type") { + match level + .as_str() + .map(|text| (text, crate::HostType::from_level(text))) + { + Some((_, Some(crate::HostType::Workstation))) => {} + Some((_, Some(host_type))) => { + profile.insert("type".into(), json!(host_type.name())); + } + // One berth never wrote is kept, so that problems() names it. + _ => { + profile.insert("type".into(), level); + } + } + } + } + if profile.get("profile").is_some_and(Value::is_string) { + let target = profile.remove("profile").unwrap_or_default(); + changed = true; + profile.entry("target").or_insert(target); + } + changed +} + /// What is wrong with a profile as a whole, in sentences: its type, its /// `access`, and for a workstation the `builder` its set-up keeps. A host /// of another type needs only to be reachable. @@ -685,6 +721,36 @@ mod tests { assert!(changed.get("type").is_none()); } + #[test] + fn a_profile_of_berth_05_takes_the_names_of_now() { + for (level, written) in [ + ("reachable", json!("ssh")), + ("controller", json!("managed")), + ("workstation", Value::Null), + ("server", json!("server")), + ] { + let mut old = + json!({"level": level, "profile": "cloud", "access": {"address": "192.0.2.4"}}); + assert!(take_old_names(&mut old), "{level}"); + assert_eq!(old["type"], written, "{level}"); + assert_eq!(old["target"], "cloud"); + assert!(old.get("level").is_none() && old.get("profile").is_none()); + assert!(!take_old_names(&mut old), "{level}"); + } + // What a later berth wrote wins, and the old field goes. + let mut both = json!({"type": "managed", "level": "reachable", "target": "laptop", "profile": "cloud"}); + assert!(take_old_names(&mut both)); + assert_eq!(both, json!({"type": "managed", "target": "laptop"})); + // A profile of now is left as it is. + let mut now = json!({"type": "ssh", "target": "cloud", "builder": {}}); + assert!(!take_old_names(&mut now)); + assert_eq!( + now, + json!({"type": "ssh", "target": "cloud", "builder": {}}) + ); + assert!(!take_old_names(&mut json!([]))); + } + #[test] fn a_qemu_profile_is_a_cloud_one_reached_from_the_qemu_host() { let mut old = json!({"target": "qemu"}); diff --git a/crates/berth-core/src/import.rs b/crates/berth-core/src/import.rs index cc21ea0..64ef298 100644 --- a/crates/berth-core/src/import.rs +++ b/crates/berth-core/src/import.rs @@ -10,8 +10,10 @@ //! the token and the plugin directory stay where they are, as they are //! used as files; only `serve.setup-key` goes. //! -//! Two more change rows the store has already: how hosts are reached moves -//! into `access`, and the records of hosts' machines become resources. +//! More change rows the store has already: how hosts are reached moves into +//! `access`, the records of hosts' machines become resources, provisioners +//! get names of their own, and profiles take the names their fields have +//! now ([`take_in_names`]). //! //! The rows of an import go into the store in one change with its marker, so //! they are all there or none of them are. Only then are the old files put @@ -44,6 +46,9 @@ pub const RESOURCES_MARKER: &str = "import:resources"; /// The marker of the sixth, which registers each provisioner that has /// settings or made something under a name of its own. pub const PROVISIONERS_MARKER: &str = "import:provisioners"; +/// The marker of the seventh, which gives every stored profile the names its +/// fields have now: `type` for `level` and `target` for `profile`. +pub const NAMES_MARKER: &str = "import:names"; /// What a row of the import is. #[derive(Debug, Default, PartialEq, Eq)] @@ -74,6 +79,7 @@ pub fn run(paths: &Paths, installation: &Installation, store: &Store) -> Result< && marked(store, ACCESS_MARKER)? && marked(store, RESOURCES_MARKER)? && marked(store, PROVISIONERS_MARKER)? + && marked(store, NAMES_MARKER)? { return Ok(()); } @@ -151,9 +157,54 @@ pub fn run(paths: &Paths, installation: &Installation, store: &Store) -> Result< ); } } + if !marked(store, NAMES_MARKER)? { + let renamed = take_in_names(store)?; + if renamed > 0 { + let (noun, verb) = match renamed { + 1 => ("profile", "says"), + _ => ("profiles", "say"), + }; + eprintln!("berth: {renamed} {noun} {verb} type for level and target for profile now"); + } + } Ok(()) } +/// The seventh import, in one change with its marker: every stored profile, +/// of every scope, takes the names of now ([`berth_api::profile::take_old_names`]). +/// The values may be sealed, so this is done here rather than by a migration +/// of the database. Returns how many profiles changed. +pub(crate) fn take_in_names(store: &Store) -> Result { + let mut scopes = std::collections::BTreeSet::new(); + if let crate::store::Rows::State(rows) = store.export(crate::store::Table::State)? { + for row in rows.into_iter().filter(|row| row.kind == kind::PROFILE) { + scopes.insert(row.scope); + } + } + let mut writes: Vec<(String, String, Vec)> = vec![]; + for scope in scopes { + for (name, value) in store.entries(kind::PROFILE, &scope)? { + let Ok(mut config) = serde_json::from_slice::(&value) else { + continue; + }; + if berth_api::profile::take_old_names(&mut config) { + writes.push((scope.clone(), name, config.to_string().into_bytes())); + } + } + } + let renamed = writes.len(); + let marker = + json!({"version": berth_api::VERSION, "at": berth_api::rfc3339(berth_api::unix_now())}); + let marker = marker.to_string().into_bytes(); + let mut rows: Vec<(&str, &str, &str, Vec)> = writes + .iter() + .map(|(scope, name, value)| (kind::PROFILE, scope.as_str(), name.as_str(), value.clone())) + .collect(); + rows.push((kind::META, OWN, NAMES_MARKER, marker)); + store.change(&rows, &[])?; + Ok(renamed) +} + /// The sixth import, in one change with its marker: each type of provisioner /// that has settings, or that made a resource of any scope, is registered /// under a name of its own, such as `incus-vm` for `incus/vm`, with those @@ -545,10 +596,17 @@ pub(crate) fn take_in_access( Ok(converted.notices) } -/// A profile of an older layout as it is read or given: of the access -/// layout, its key file taken into the ring. A file is written only when the -/// user saves it. +/// A profile of an older layout as it is read or given: with the names its +/// fields have now, and of the access layout, its key file taken into the +/// ring. A file is written only when the user saves it. pub fn convert_profile(paths: &Paths, title: &str, config: &mut Value) { + berth_api::profile::take_old_names(config); + convert_layout(paths, title, config); +} + +/// A profile of the layout before `access`, in the access layout, its key +/// file taken into the ring. +pub fn convert_layout(paths: &Paths, title: &str, config: &mut Value) { use crate::keys::ring::{Halves, blob}; if config["builder"].as_object().is_none_or(|builder| { ![ @@ -1166,7 +1224,7 @@ mod tests { fs::create_dir_all(&hosts).unwrap(); fs::write( hosts.join("studio.json"), - r#"{"hostname": "studio", "target": "cloud", "operator_username": "ops", + r#"{"hostname": "studio", "profile": "cloud", "operator_username": "ops", "builder": {"ssh_host": "192.0.2.10", "ssh_user": "admin", "ssh_key": "", "ask_become_pass": true, "ask_pass": false}}"#, ) @@ -1208,6 +1266,8 @@ mod tests { json!({"address": "192.0.2.10", "user": "admin", "auth": "ssh", "sudo": "password"}) ); assert!(berth_api::profile::asks_become_pass(&studio)); + assert_eq!(studio["target"], "cloud"); + assert!(studio.get("profile").is_none()); assert_eq!(machine_of(&store, "studio").unwrap().external_id, "vm-1"); let mut applied = studio.clone(); applied["access"]["user"] = json!("ops"); @@ -1288,18 +1348,87 @@ mod tests { assert_eq!(read(&store, kind::SECRET, "registry/nexus").unwrap(), "pw"); } + #[test] + fn an_installation_of_berth_05_gives_its_profiles_the_names_of_now() { + let (_dir, paths) = scratch(); + // berth 0.5 had run every import but the last, and saved hosts of each level. + let store = open(&paths); + store + .change(&[], &[(kind::META, OWN, NAMES_MARKER)]) + .unwrap(); + for (name, level) in [("dock", "reachable"), ("pier", "controller")] { + let old = + json!({"level": level, "profile": "cloud", "access": {"address": "192.0.2.4"}}); + store + .write(kind::PROFILE, OWN, name, old.to_string().as_bytes()) + .unwrap(); + } + let studio = json!({"hostname": "studio", "profile": "laptop", "builder": {}}); + store + .write(kind::PROFILE, OWN, "studio", studio.to_string().as_bytes()) + .unwrap(); + let found = installation(&paths); + run(&paths, &found, &store).unwrap(); + assert!(read(&store, kind::META, NAMES_MARKER).is_some()); + let dock = json_row(&store, kind::PROFILE, "dock").unwrap(); + assert_eq!( + (&dock["type"], &dock["target"]), + (&json!("ssh"), &json!("cloud")) + ); + assert_eq!( + json_row(&store, kind::PROFILE, "pier").unwrap()["type"], + "managed" + ); + assert_eq!( + json_row(&store, kind::PROFILE, "studio").unwrap(), + json!({"hostname": "studio", "target": "laptop", "builder": {}}) + ); + // A row an older berth writes later is read with the names of now. + let late = json!({"level": "controller", "access": {"address": "192.0.2.5"}}); + store + .write(kind::PROFILE, OWN, "late", late.to_string().as_bytes()) + .unwrap(); + let place = crate::profiles::Place::own("late").unwrap(); + assert_eq!(place.load(&paths).unwrap().unwrap()["type"], "managed"); + let listed = crate::profiles::list(&paths, OWN).unwrap(); + let (_, listed) = listed.iter().find(|(name, _)| name == "late").unwrap(); + assert!(listed.get("level").is_none()); + } + + #[test] + fn a_profile_given_in_a_file_is_read_with_the_names_of_now() { + let (dir, paths) = scratch(); + let file = dir.path().join("dock.json"); + fs::write( + &file, + r#"{"level": "reachable", "profile": "cloud", "access": {"address": "192.0.2.4"}}"#, + ) + .unwrap(); + let place = crate::profiles::Place::File(file.clone()); + let read = place.load(&paths).unwrap().unwrap(); + assert_eq!( + read, + json!({"type": "ssh", "target": "cloud", "access": {"address": "192.0.2.4"}}) + ); + // The file keeps what it said until it is saved. + assert!(fs::read_to_string(&file).unwrap().contains("reachable")); + place.save(&paths, &read).unwrap(); + assert!(!fs::read_to_string(&file).unwrap().contains("level")); + } + #[test] fn a_new_installation_gets_only_the_marker() { let (_dir, paths) = scratch(); let store = open(&paths); let report = store.seal_report().unwrap(); - assert_eq!((report.sealed, report.plain), (0, 6)); + assert_eq!((report.sealed, report.plain), (0, 7)); assert!(read(&store, kind::META, MARKER).is_some()); assert!(read(&store, kind::META, PROVISIONERS_MARKER).is_some()); assert!(read(&store, kind::META, PROFILES_MARKER).is_some()); assert!(read(&store, kind::META, KEYS_MARKER).is_some()); assert!(read(&store, kind::META, ACCESS_MARKER).is_some()); assert!(read(&store, kind::META, RESOURCES_MARKER).is_some()); + assert!(read(&store, kind::META, NAMES_MARKER).is_some()); assert!(!paths.config_dir.join("migrated").exists()); assert!(!paths.settings_file().exists()); } @@ -1313,8 +1442,8 @@ mod tests { let store = open(&paths); assert!(store.encrypted()); let report = store.seal_report().unwrap(); - // Two secrets, a registry, two settings and the six markers. - assert_eq!((report.sealed, report.plain), (11, 0)); + // Two secrets, a registry, two settings and the seven markers. + assert_eq!((report.sealed, report.plain), (12, 0)); assert_eq!(read(&store, kind::SECRET, "github").unwrap(), "ghp-made-up"); } diff --git a/crates/berth-core/src/kept_profile.rs b/crates/berth-core/src/kept_profile.rs index 36a1411..7107f1d 100644 --- a/crates/berth-core/src/kept_profile.rs +++ b/crates/berth-core/src/kept_profile.rs @@ -16,10 +16,12 @@ use std::{io::Write, path::PathBuf, process::Stdio}; /// Where the role writes it, readable by root only. pub const PATH: &str = "/etc/berth/profile.json"; -/// The format of the document: 2 has the profile in the layout with -/// `access`. Format 1, of berth 0.4.1, had the layout before it; it is -/// converted when it is read. A berth refuses one newer than it knows. -pub const FORMAT: u64 = 2; +/// The format of the document: 3 has the profile with the fields `type` +/// and `target`. Format 2 named them `level` and `profile`, and format 1, of +/// berth 0.4.1, had the layout before `access`; both are converted when they +/// are read. A berth refuses one newer than it knows, so a berth of format 2 +/// asks to be updated rather than read `type` as a workstation. +pub const FORMAT: u64 = 3; /// What a profile's `builder` held of how one berth reached the host, or of /// that berth's own machine, in the layout before `access`, and what still @@ -243,8 +245,8 @@ pub fn adopted(paths: &Paths, title: &str, kept: &Value, access: &Access) -> Res if !profile["builder"].is_object() { profile["builder"] = json!({}); } - // berth 0.4.1 kept a profile of the layout before `access`; what is left - // of that becomes the new layout, and then the adopting berth's way in. + // An older berth kept a profile of older names or of the layout before + // `access`; it takes those of now, and then the adopting berth's way in. crate::import::convert_profile(paths, title, &mut profile); profile = stored(&profile); if !profile["builder"].is_object() { @@ -571,7 +573,7 @@ mod tests { let kept = json!({ "format": 1, "berth": "0.4.1", "host": "studio", "written": "2026-11-13T10:00:00Z", "profile": { - "hostname": "studio", "target": "cloud", "operator_username": "ops", + "hostname": "studio", "profile": "cloud", "operator_username": "ops", "operator_ssh_public_keys": ["ssh-ed25519 AAAA user"], "builder": {"ask_become_pass": true, "ask_pass": false, "shipped_plugins": true}, }, @@ -580,6 +582,8 @@ mod tests { }); let back = adopted(&paths, "studio", &kept, &reached()).unwrap(); assert_eq!(back.profile["builder"], json!({"shipped_plugins": true})); + assert_eq!(back.profile["target"], "cloud"); + assert!(back.profile.get("profile").is_none()); assert_eq!(back.profile["access"]["address"], "192.0.2.10"); assert_eq!(back.profile["access"]["auth"], "berth"); // sudo is how the adopting berth found it, not what the old switch said. @@ -597,6 +601,30 @@ mod tests { assert_eq!(machine.arguments["server"], "https://192.0.2.20:8443"); } + #[test] + fn a_profile_kept_by_berth_05_takes_the_names_of_now() { + let (_home, paths) = scratch(); + let old = |level: &str| { + json!({ + "format": 2, "berth": "0.5.2", "host": "studio", "written": "2026-11-13T10:00:00Z", + "profile": {"hostname": "studio", "profile": "laptop", "level": level, "builder": {}}, + }) + }; + let back = adopted(&paths, "studio", &old("workstation"), &reached()).unwrap(); + assert_eq!(back.profile["target"], "laptop"); + assert!(back.profile.get("profile").is_none() && back.profile.get("type").is_none()); + assert!(back.profile.get("level").is_none()); + let back = adopted(&paths, "studio", &old("controller"), &reached()).unwrap(); + assert_eq!(back.profile["type"], "managed"); + // Kept again, it is written in the format of now. + let again = document("studio", &back.profile, None); + assert_eq!(again["format"], 3); + assert_eq!( + (&again["profile"]["type"], &again["profile"]["target"]), + (&json!("managed"), &json!("laptop")) + ); + } + #[test] fn a_newer_format_or_no_profile_is_refused() { let (_home, paths) = scratch(); diff --git a/crates/berth-core/src/profiles.rs b/crates/berth-core/src/profiles.rs index 8c609b6..e7772d9 100644 --- a/crates/berth-core/src/profiles.rs +++ b/crates/berth-core/src/profiles.rs @@ -135,14 +135,21 @@ impl Place { pub fn load(&self, paths: &Paths) -> Result> { match self { Place::Stored { scope, name } => { - Ok(store::shared(paths)?.read_json(kind::PROFILE, scope, name)?) + let mut profile: Option = + store::shared(paths)?.read_json(kind::PROFILE, scope, name)?; + // A row an older berth or berth server wrote after the store's + // names were converted is read with the names of now. + if let Some(profile) = &mut profile { + berth_api::profile::take_old_names(profile); + } + Ok(profile) } Place::File(path) => match fs::read(path) { Ok(data) => { let mut profile: Value = serde_json::from_slice(&data) .map_err(|error| format!("{}: {error}", path.display()))?; - // A profile of berth 0.4 is read in the access layout; the - // file keeps the old one until the user saves. + // A profile of an older berth is read in the layout of now; + // the file keeps the old one until the user saves. crate::import::convert_profile(paths, &self.title(), &mut profile); Ok(Some(profile)) } @@ -184,7 +191,11 @@ pub fn list(paths: &Paths, scope: &str) -> Result> { let entries = store::shared(paths)?.entries(kind::PROFILE, scope)?; Ok(entries .into_iter() - .filter_map(|(name, value)| Some((name, serde_json::from_slice(&value).ok()?))) + .filter_map(|(name, value)| { + let mut profile = serde_json::from_slice(&value).ok()?; + berth_api::profile::take_old_names(&mut profile); + Some((name, profile)) + }) .collect()) } diff --git a/crates/berth-core/src/store/suite.rs b/crates/berth-core/src/store/suite.rs index 1d4d310..d313958 100644 --- a/crates/berth-core/src/store/suite.rs +++ b/crates/berth-core/src/store/suite.rs @@ -97,6 +97,7 @@ on_each_backend!( resealing_keeps_the_times, resealing_refuses_a_table_that_changed, the_old_files_go_into_an_empty_store, + sealed_profiles_of_an_older_berth_take_the_names_of_now, a_copy_takes_every_table_as_it_is_and_back, a_copy_into_a_store_that_has_rows_keeps_them, ); @@ -1222,6 +1223,60 @@ fn the_old_files_go_into_an_empty_store(place: &Place) { ); } +/// Profiles of berth 0.5, sealed and in any scope, are given the names of now +/// once, with nothing else changed. +fn sealed_profiles_of_an_older_berth_take_the_names_of_now(place: &Place) { + let store = place.open().with_keys(Some(keys()), None); + let old = |level: &str| { + json!({"level": level, "profile": "cloud", "access": {"address": "192.0.2.4"}}).to_string() + }; + store + .write(kind::PROFILE, OWN, "dock", old("reachable").as_bytes()) + .unwrap(); + store + .write(kind::PROFILE, OWN, "studio", old("workstation").as_bytes()) + .unwrap(); + store + .write( + kind::PROFILE, + "served:http://192.0.2.7:7777", + "yard", + old("controller").as_bytes(), + ) + .unwrap(); + let now = br#"{"type":"ssh","target":"laptop"}"#; + store.write(kind::PROFILE, OWN, "pier", now).unwrap(); + let before = stored_row(&store, kind::PROFILE, OWN, "pier"); + assert_eq!(crate::import::take_in_names(&store).unwrap(), 3); + let read = |scope: &str, name: &str| { + store + .read_json(kind::PROFILE, scope, name) + .unwrap() + .unwrap() + }; + assert_eq!( + read(OWN, "dock"), + json!({"type": "ssh", "target": "cloud", "access": {"address": "192.0.2.4"}}) + ); + assert_eq!( + read(OWN, "studio"), + json!({"target": "cloud", "access": {"address": "192.0.2.4"}}) + ); + assert_eq!( + read("served:http://192.0.2.7:7777", "yard")["type"], + "managed" + ); + assert!(stored_row(&store, kind::PROFILE, OWN, "dock").sealed); + assert_eq!(stored_row(&store, kind::PROFILE, OWN, "pier"), before); + assert!( + store + .names(kind::META, OWN) + .unwrap() + .contains(&crate::import::NAMES_MARKER.to_owned()) + ); + assert_eq!(crate::import::take_in_names(&store).unwrap(), 0); +} + /// A store with something in every table: messages, a cursor, values at a /// later revision, jobs, sealed and plain state, and a berth server's scope. fn filled(store: &Store) { diff --git a/crates/berth/src/app.rs b/crates/berth/src/app.rs index 4303662..5a465fb 100644 --- a/crates/berth/src/app.rs +++ b/crates/berth/src/app.rs @@ -2608,6 +2608,7 @@ pub fn parse_config(data: &[u8]) -> Result { if !config.is_object() { return Err("Configuration must be a JSON object".into()); } + berth_api::profile::take_old_names(&mut config); berth_api::profile::retire_qemu(&mut config); for field in ["wifi", "ansible_vars", "builder"] { if !config[field].is_null() && !config[field].is_object() { diff --git a/crates/berth/src/commands.rs b/crates/berth/src/commands.rs index a7fc4cd..655b282 100644 --- a/crates/berth/src/commands.rs +++ b/crates/berth/src/commands.rs @@ -1958,6 +1958,21 @@ mod tests { let place = Place::own("studio").unwrap(); let kept = place.load(&paths).unwrap().unwrap(); assert_eq!(kept["access"]["address"], "192.0.2.20"); + // One exported by berth 0.5 is saved with the names of now. + let store = berth_core::store::shared(&paths).unwrap(); + let raw = |store: &berth_core::store::Store| -> Value { + serde_json::from_slice(&store.read("profile", "", "dock").unwrap().unwrap()).unwrap() + }; + std::fs::write( + &file, + r#"{"level": "controller", "profile": "cloud", "access": {"address": "192.0.2.21"}}"#, + ) + .unwrap(); + set_profile(&paths, "dock", file.to_str().unwrap()).unwrap(); + assert_eq!( + raw(&store), + json!({"type": "managed", "target": "cloud", "access": {"address": "192.0.2.21"}}) + ); // What is not a profile is refused, and the one kept stays. std::fs::write(&file, r#"{"builder": []}"#).unwrap(); assert!(set_profile(&paths, "studio", file.to_str().unwrap()).is_err()); diff --git a/crates/berth/src/serve/setup.rs b/crates/berth/src/serve/setup.rs index a09bca0..1e62370 100644 --- a/crates/berth/src/serve/setup.rs +++ b/crates/berth/src/serve/setup.rs @@ -87,8 +87,8 @@ pub async fn save_profile( if let Some(builder) = profile["builder"].as_object_mut() { builder.remove("ssh_key"); } - berth_core::import::convert_profile(&state.paths, &name, &mut profile); - // A workstation's has its set-up's part; a host below that, only how it is reached. + berth_core::import::convert_layout(&state.paths, &name, &mut profile); + // A workstation's has its set-up's part; a host of another type, only how it is reached. let problems = berth_api::profile::problems(&profile); if !problems.is_empty() { return Err(bad(problems.join("; "))); diff --git a/crates/berth/src/serve/tests.rs b/crates/berth/src/serve/tests.rs index 2d1125a..ef1a2f4 100644 --- a/crates/berth/src/serve/tests.rs +++ b/crates/berth/src/serve/tests.rs @@ -3620,6 +3620,11 @@ async fn a_host_added_by_its_address_has_a_type_and_actions_to_match() { "type", ), (json!({"type": "managed"}), "access.address"), + // The API takes the names of now only. + ( + json!({"level": "reachable", "access": {"address": "192.0.2.9"}}), + "builder", + ), (json!({"access": {"address": "192.0.2.9"}}), "builder"), ] { let (status, said) = send(client, "PUT", "/v1/hosts/pier/profile", refused).await; diff --git a/docs/content/docs/(guide)/reference/profile.mdx b/docs/content/docs/(guide)/reference/profile.mdx index 0ad7de4..7c47260 100644 --- a/docs/content/docs/(guide)/reference/profile.mdx +++ b/docs/content/docs/(guide)/reference/profile.mdx @@ -158,6 +158,19 @@ A profile of berth 0.4 kept these under `builder`: berth converts stored profiles once, and reads a profile in a file in the new layout. The file keeps the old layout until you save it. A key file that `ssh_key` named becomes a key of the key ring, and the host logs in with it. If berth cannot read the file, the host logs in with `ssh`, and berth says so. A host without a key file logs in with `ssh`, which is what it did before. +## Older profiles + +A profile of berth 0.5 or earlier names two fields differently: + +| berth 0.5 | Now | +| --- | --- | +| `level`: `reachable` | `type`: `ssh` | +| `level`: `controller` | `type`: `managed` | +| `level`: `workstation` | No `type`, which means a workstation | +| `profile` | `target` | + +berth converts its stored profiles once, the profiles of a berth server's hosts with them. It reads the old names wherever a profile comes from: a file such as `berth ./studio.json`, `berth profile HOST --set FILE`, and the profile a host keeps, which [`berth adopt`](/docs/use/moving) reads. A file keeps the old names until you save it. berth writes the new names only. The API of `berth serve` takes the new names only. + ## Install (`builder`) How berth installs the host. These settings stay on your machine. diff --git a/docs/content/docs/(guide)/use/moving.mdx b/docs/content/docs/(guide)/use/moving.mdx index 8e854d0..3c34e82 100644 --- a/docs/content/docs/(guide)/use/moving.mdx +++ b/docs/content/docs/(guide)/use/moving.mdx @@ -24,7 +24,7 @@ The file contains the profile as berth stores it, with a few fields left out: | `wifi` | Yes | The USB installer wrote the same network into the host's network settings | | The machine a provisioner made | Yes | Its record, so it is still a [resource](/docs/deploy/resources) of the host. Its token is a label on the machine and does not grant access | -The file also says its format, the version of the berth that wrote it, the time, and the host's name there. A file of berth 0.4.1 has format 1 and the profile layout of then. berth converts it when it adopts the host. +The file also says its format, the version of the berth that wrote it, the time, and the host's name there. A file of berth 0.4.1 has format 1 and the profile layout of then. Format 2, of berth 0.5, has the [older names](/docs/reference/profile#older-profiles) `level` and `profile`. berth converts both when it adopts the host, and writes format 3. A berth that knows only format 2 refuses a file of format 3 and asks to be updated. berthd serves the same file to an administrator as `GET /v1/applied/profile`. Through a berth server that is `GET /v1/hosts/NAME/applied/profile`. diff --git a/docs/content/docs/(guide)/use/types.mdx b/docs/content/docs/(guide)/use/types.mdx index 4720b03..1cc51d1 100644 --- a/docs/content/docs/(guide)/use/types.mdx +++ b/docs/content/docs/(guide)/use/types.mdx @@ -14,6 +14,8 @@ berth does not have to set a machine up to work with it. A host is anything bert The type is part of the host's [profile](/docs/reference/profile#type), as `type`. A profile that doesn't say is a workstation, so older profiles mean what they always did. What the host has right now is asked of it. The overview and the Hosts tab show both when they differ, such as for a controller installed by hand. +A profile of berth 0.5 or earlier calls the type `level`, with the values `reachable`, `controller` and `workstation`. berth reads it with the names of now ([Older profiles](/docs/reference/profile#older-profiles)). + ## Capabilities | Capability | `ssh` | `managed` | `workstation` | diff --git a/docs/content/docs/(guide)/use/updates.mdx b/docs/content/docs/(guide)/use/updates.mdx index 82581c7..57710c1 100644 --- a/docs/content/docs/(guide)/use/updates.mdx +++ b/docs/content/docs/(guide)/use/updates.mdx @@ -26,7 +26,9 @@ berth update --check # is there a newer release? berth update # download it, check its SHA-256 and replace this program ``` -`berth update` takes the same archive as the install script. It offers only full releases, not pre-releases such as `0.4.0-rc.1`, and moves from a pre-release to its release. A container is updated by pulling a newer image. `berthd` and `box` travel inside `berth`. A host gets the new ones when you apply its configuration. Its overview says when its tools are of another version than your berth. `BERTH_RELEASES` names a mirror of the releases page. +`berth update` takes the same archive as the install script. It offers only full releases, not pre-releases such as `0.4.0-rc.1`, and moves from a pre-release to its release. A container is updated by pulling a newer image. `berthd` and `box` travel inside `berth`. A host gets the new ones when you apply its configuration. Its overview says when its tools are of another version than your berth. + +A berthd of berth 0.5 says the host's type by its older name, and berth reads it. An older berth that meets a newer berthd is out of date: update it. It refuses the profile a newer berth left on the host rather than misread it. `BERTH_RELEASES` names a mirror of the releases page. ## Hosts that are behind diff --git a/provision/bin/devbox.py b/provision/bin/devbox.py index 42c77c8..8b3caa8 100755 --- a/provision/bin/devbox.py +++ b/provision/bin/devbox.py @@ -144,6 +144,22 @@ def release_delivered(): return os.environ.get('BERTH_RELEASE_DELIVERED') == '1' +def take_old_names(c): + """A profile of berth 0.5 or earlier with the names its fields have now: + `type` for `level`, whose values were reachable, controller and + workstation, and `target` for `profile`. What a later berth wrote stays.""" + c = dict(c) + level = c.pop('level', None) + if level is not None and 'type' not in c: + host_type = {'reachable': 'ssh', 'controller': 'managed', 'workstation': None}.get(level, level) + if host_type is not None: + c['type'] = host_type + if isinstance(c.get('profile'), str): + c.setdefault('target', c.pop('profile')) + c.pop('profile', None) + return c + + def retire_qemu(c): """A profile of the qemu target there once was, as the cloud one it is now. That target let SSH in only from the QEMU host when no recovery network was @@ -163,7 +179,7 @@ def checked_config(path, kind): c = json.loads(Path(path).read_text()) if not isinstance(c, dict): raise ValueError('Configuration must be a JSON object') - c = retire_qemu(c) + c = retire_qemu(take_old_names(c)) if not HOSTNAME.fullmatch(text(c, 'hostname')): raise ValueError('Invalid hostname: use lowercase letters, digits and hyphens, starting with a letter') if text(c, 'target') not in TARGETS: diff --git a/tests/e2e/e2e_adopt.py b/tests/e2e/e2e_adopt.py index 2d43b27..aeeca5c 100644 --- a/tests/e2e/e2e_adopt.py +++ b/tests/e2e/e2e_adopt.py @@ -42,7 +42,7 @@ def setUpClass(cls): def test_the_host_keeps_its_profile_for_root_only(self): self.assertEqual(self.station.root_on_host(f'stat -c %a:%U:%G {KEPT}').stdout.strip(), '600:root:root') self.assertNotEqual(self.station.ssh(OPERATOR, f'cat {KEPT}', check=False).returncode, 0) - self.assertEqual((self.kept['format'], self.kept['host']), (2, HOST)) + self.assertEqual((self.kept['format'], self.kept['host']), (3, HOST)) self.assertRegex(self.kept['written'], r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$') saved = self.station.read_profile() kept = self.kept['profile'] diff --git a/tests/test_devbox.py b/tests/test_devbox.py index ee37127..e86442c 100755 --- a/tests/test_devbox.py +++ b/tests/test_devbox.py @@ -217,6 +217,18 @@ def test_a_qemu_target_is_a_cloud_one_reached_from_the_qemu_host(self): self.assertEqual(builder.retire_qemu({'target':kept}),{'target':kept}) c['target']='desktop'; path.write_text(json.dumps(c)) with self.assertRaisesRegex(ValueError,'laptop or cloud'): builder.checked_config(path,'cloud') + def test_a_profile_of_berth_05_is_read_with_the_names_of_now(self): + with tempfile.TemporaryDirectory() as temp: + path=Path(temp)/'host.json' + c=config(); del c['target']; c['profile']='laptop'; c['level']='workstation' + path.write_text(json.dumps(c)) + checked=builder.checked_config(path,'cloud') + self.assertEqual(checked['target'],'laptop') + self.assertNotIn('profile',checked); self.assertNotIn('level',checked); self.assertNotIn('type',checked) + self.assertEqual(builder.deployment(checked,'a'*64)['target'],'laptop') + self.assertEqual(builder.take_old_names({'level':'controller','profile':'cloud'}),{'type':'managed','target':'cloud'}) + self.assertEqual(builder.take_old_names({'type':'ssh','level':'controller','target':'laptop','profile':'cloud'}), + {'type':'ssh','target':'laptop'}) def test_bootstrap_hands_a_qemu_seed_to_the_role_as_cloud(self): script=(ROOT/'provision/bootstrap/bootstrap.sh').read_text() start=script.index("python3 - <<'PY'\n")+len("python3 - <<'PY'\n") From b9e670afd03d36ea4bc26288d8eb73c1925cd874 Mon Sep 17 00:00:00 2001 From: Helight Date: Sun, 15 Nov 2026 00:42:07 +0100 Subject: [PATCH 12/94] refactor!: a host's tasks are actions on the wire berthd's tasks.list, tasks.run and tasks.choices become actions.list, actions.run and actions.choices under /v1/actions, and the installation's actions of berth serve move to installation.actions and installation.act under /v1/installation/actions. berth serve passes a host's operations through under /v1/hosts/NAME/controller, as /v1/hosts/NAME/actions is its own list of the host's actions. The role writes /etc/berth/actions.json, which berthd reads before tasks.json. berth needs a berthd of API 2. The commands are berth actions HOST and box actions. --- .agents/skills/install-berth/SKILL.md | 4 +- AGENTS.md | 6 +- README.md | 2 +- crates/berth-api/src/ops.rs | 18 +- crates/berth-api/src/types.rs | 77 +- crates/berth-core/src/kept_profile.rs | 2 +- crates/berth-core/src/link.rs | 8 +- crates/berth-core/src/plugins.rs | 46 +- crates/berth-core/src/rollout.rs | 24 +- crates/berth-core/src/runner.rs | 8 +- crates/berth-page/src/admin.rs | 4 +- crates/berth-page/src/app.rs | 16 +- crates/berth-page/src/remote.rs | 35 +- crates/berth-tui/src/fields.rs | 8 +- crates/berth-tui/src/host.rs | 81 +- crates/berth-tui/src/plugins.rs | 2 +- crates/berth-tui/src/screen.rs | 10 +- crates/berth/src/app.rs | 74 +- crates/berth/src/commands.rs | 58 +- crates/berth/src/main.rs | 19 +- crates/berth/src/remote.rs | 42 +- crates/berth/src/serve/actions.rs | 92 +- crates/berth/src/serve/api.rs | 19 +- crates/berth/src/serve/auth.rs | 34 +- crates/berth/src/serve/docs.rs | 41 +- crates/berth/src/serve/tests.rs | 180 ++- crates/berth/src/ui.rs | 68 +- crates/berthd/src/{tasks.rs => actions.rs} | 90 +- crates/berthd/src/http.rs | 24 +- crates/berthd/src/lib.rs | 4 +- crates/berthd/src/sessions.rs | 10 +- crates/berthd/src/state.rs | 10 +- crates/berthd/tests/api.rs | 58 +- crates/box/src/main.rs | 4 +- crates/box/src/net.rs | 30 +- crates/box/tests/berthd.rs | 10 +- .../content/docs/(guide)/deploy/container.mdx | 2 +- docs/content/docs/(guide)/extend/index.mdx | 2 +- docs/content/docs/(guide)/extend/plugins.mdx | 6 +- docs/content/docs/(guide)/extend/serve.mdx | 14 +- docs/content/docs/(guide)/extend/streams.mdx | 6 +- .../docs/(guide)/extend/writing-plugins.mdx | 12 +- docs/content/docs/(guide)/index.mdx | 2 +- docs/content/docs/(guide)/reference/box.mdx | 12 +- docs/content/docs/(guide)/reference/index.mdx | 2 +- .../docs/(guide)/reference/on-the-host.mdx | 8 +- .../docs/(guide)/reference/profile.mdx | 2 +- .../docs/(guide)/reference/validation.mdx | 4 +- docs/content/docs/(guide)/start/concepts.mdx | 12 +- .../docs/(guide)/start/quick-start.mdx | 4 +- docs/content/docs/(guide)/use/access.mdx | 6 +- docs/content/docs/(guide)/use/backups.mdx | 4 +- docs/content/docs/(guide)/use/cli.mdx | 14 +- docs/content/docs/(guide)/use/index.mdx | 2 +- docs/content/docs/(guide)/use/moving.mdx | 4 +- docs/content/docs/(guide)/use/overview.mdx | 16 +- docs/content/docs/(guide)/use/server.mdx | 6 +- docs/content/docs/(guide)/use/sign-ins.mdx | 4 +- docs/content/docs/(guide)/use/types.mdx | 6 +- docs/content/docs/(guide)/use/updates.mdx | 10 +- docs/content/docs/api/index.mdx | 18 +- docs/content/docs/api/portal.mdx | 4 +- docs/openapi/berth.asyncapi.json | 12 +- docs/openapi/berth.openapi.json | 1092 ++++++++--------- docs/openapi/berth.operations.json | 126 +- docs/openapi/berthd.openapi.json | 428 +++---- docs/openapi/berthd.operations.json | 174 +-- .../roles/devbox/files/tasks/common.sh | 7 +- .../ansible/roles/devbox/files/tasks/pair.sh | 4 +- .../roles/devbox/files/tasks/update.sh | 2 +- .../ansible/roles/devbox/tasks/berth.yml | 7 +- .../roles/devbox/templates/AGENT.md.j2 | 6 +- provision/ansible/roles/devbox/vars/main.yml | 6 +- recipes/incus-host/README.md | 4 +- tests/container_link.py | 12 +- tests/e2e/e2e_access.py | 2 +- tests/e2e/e2e_apply.py | 2 +- tests/e2e/e2e_client.py | 2 +- tests/e2e/e2e_controller.py | 8 +- tests/e2e/e2e_host.py | 14 +- tests/e2e/e2e_own_key.py | 4 +- tests/e2e/e2e_plugins.py | 8 +- tests/e2e/e2e_restore.py | 4 +- tests/e2e/e2e_serve.py | 20 +- tests/e2e/e2e_update.py | 2 +- 85 files changed, 1768 insertions(+), 1578 deletions(-) rename crates/berthd/src/{tasks.rs => actions.rs} (65%) diff --git a/.agents/skills/install-berth/SKILL.md b/.agents/skills/install-berth/SKILL.md index 68c594e..3c5a273 100644 --- a/.agents/skills/install-berth/SKILL.md +++ b/.agents/skills/install-berth/SKILL.md @@ -14,7 +14,7 @@ terminal. A set-up has these pieces: | --- | --- | | `berth` client | The program on the user's machine. It has a terminal UI and commands. | | berth server | Optional. `berth serve`, usually in a Docker container, reached over a tailnet with TLS. It keeps the hosts, profiles and secrets. | -| Host | A machine berth reaches and logs in to. Its type is one of three: `ssh` means berth only logs in, `managed` adds berthd and box, and `workstation` is set up from a profile. A machine that exists is added with `berth host add NAME ADDRESS --user USER`. | +| Host | A machine berth logs in to over SSH. Its type is one of three: `ssh` means berth only logs in, `managed` adds berthd and box, and `workstation` is set up from a profile. A machine that exists is added with `berth host add NAME ADDRESS --user USER`. | | Provisioner | Creates the machine for a host, such as on Docker or Incus. Plugins bring the types `docker/container`, `incus/vm` and `incus/container`, and berth runs each provisioner under a name of its own, registered with `berth provisioner add NAME TYPE`. The `incus-host` recipe registers `incus-vm`, `incus-container` and `docker`. `berth provisioner` lists them, and the Provisioners tab of the terminal UI (key `2`) shows each one's page. | ## Where to look things up @@ -107,7 +107,7 @@ berth host add big 192.0.2.20 --user root --auth ssh berth host install big ``` -`host add` saves a host of the type `ssh`. The default `--auth berth` uses berth's own +`host add` saves the host with the type `ssh`. The default `--auth berth` uses berth's own key, which berth installs on first contact with a password or a private key that logs in once. `--auth ssh` uses the user's own SSH configuration and agent, and works with a local berth only. `host install` puts the controller alone on the diff --git a/AGENTS.md b/AGENTS.md index 2f41159..84b651e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ berth sets up and looks after agent workstations. These are Ubuntu machines with | --- | --- | | `crates/berth/` | The `berth` program: terminal UI, commands and `berth serve` (`crates/berth/src/serve/`). In `serve/`, `actions.rs` has the actions of hosts and of the installation, `keys.rs` the key ring's routes, `provisioners.rs` and `resources.rs` those of provisioners and resources | | `crates/berth-api/` | Types and the operations table shared by every program (`ops.rs` names each operation, its HTTP route and its role) | -| `crates/berth-core/` | Hosts, profiles, links to hosts, registries and secrets, and plugins. The store is in `store/`. `kept.rs` and `plugin_state.rs` write files from it, and `import.rs` takes in the files of older versions. `kept_profile.rs` is the profile a host keeps of itself and `berth adopt`. `runner.rs` runs every action as a job. `keys/` is the key ring and how berth logs in to hosts. `level.rs` says what a host can do at each level. `provisioner.rs` and `resource.rs` are the provisioners of plugins and what they made | +| `crates/berth-core/` | Hosts, profiles, links to hosts, registries and secrets, and plugins. The store is in `store/`. `kept.rs` and `plugin_state.rs` write files from it, and `import.rs` takes in the files of older versions. `kept_profile.rs` is the profile a host keeps of itself and `berth adopt`. `runner.rs` runs every action as a job. `keys/` is the key ring and how berth logs in to hosts. `host_type.rs` says what a host of each type can do. `provisioner.rs` and `resource.rs` are the provisioners of plugins and what they made | | `crates/berth-tui/` | The parts of the UI that `berth` and `berth-remote` share | | `crates/berth-pty/` | Terminals for sessions | | `crates/berthd/`, `crates/box/` | The controller on each host and the agent's own tool there | @@ -93,11 +93,11 @@ CI builds berth once and runs the tests of each test host as a shard, in a job o ### Actions -Give a new thing a host, the installation, a provisioner or a resource can do an action in the matching registry. It does not get a route of its own. The routes `hosts.act`, `actions.act`, `provisioners.act` and `resources.act` run it, and each action says whether it can run now and what role it needs. +Give a new thing a host, the installation, a provisioner or a resource can do an action in the matching registry. It does not get a route of its own. The routes `hosts.act`, `installation.act`, `provisioners.act` and `resources.act` run it, and each action says whether it can run now and what role it needs. | Subject | Where its actions are | | --- | --- | -| A host | `HOST` in `crates/berth/src/serve/actions.rs`, besides the tasks its controller lists | +| A host | `HOST` in `crates/berth/src/serve/actions.rs`, besides the actions its controller lists | | The installation | `INSTALLATION` in the same file | | A provisioner | `provisioner::actions` in `crates/berth-core/src/provisioner.rs`: its plugin's actions and berth's own | | A resource | `resource::actions` in `crates/berth-core/src/resource.rs`: those of its kind and its plugin's | diff --git a/README.md b/README.md index 062b5f2..70257c8 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ installs and can apply again. Once the host runs, its page in berth has the status, sign-ins, updates and secrets. A machine you only log in to can be a host too: `berth host add dock 192.0.2.4 --user ops`. -berth's terminal UI showing the overview of a host with its tasks +berth's terminal UI showing the overview of a host with its actions **Status:** early. Try a profile in the container or a VM before booting the installer on real hardware: **the installer erases the disk it selects.** diff --git a/crates/berth-api/src/ops.rs b/crates/berth-api/src/ops.rs index d9d94f9..840683e 100644 --- a/crates/berth-api/src/ops.rs +++ b/crates/berth-api/src/ops.rs @@ -82,7 +82,7 @@ pub enum Body { pub enum Role { /// Look: hosts, sessions and their output, logs, the inbox, the store. View, - /// Use the hosts: run tasks and commands, write files, control units. + /// Use the hosts: run actions and commands, write files, control units. Operate, /// Set up: profiles, secrets, registries, plugins, and applying them to hosts. Admin, @@ -198,12 +198,12 @@ pub static HOST: &[Op] = &[ call("sessions.input", "POST", "/v1/sessions/{id}/input"), call("sessions.resize", "POST", "/v1/sessions/{id}/resize"), call("sessions.signal", "POST", "/v1/sessions/{id}/signal"), - call("tasks.list", "GET", "/v1/tasks"), - call("tasks.run", "POST", "/v1/tasks/{name}"), + call("actions.list", "GET", "/v1/actions"), + call("actions.run", "POST", "/v1/actions/{action}"), call( - "tasks.choices", + "actions.choices", "GET", - "/v1/tasks/{name}/choices/{argument}", + "/v1/actions/{action}/choices/{argument}", ), call("system.stats", "GET", "/v1/stats"), call("system.power", "POST", "/v1/power/{verb}"), @@ -259,9 +259,13 @@ pub static SERVE: &[Op] = &[ call("hosts.act", "POST", "/v1/hosts/{name}/actions/{action}"), Role::View, ), - call("actions.list", "GET", "/v1/actions"), + call("installation.actions", "GET", "/v1/installation/actions"), role( - call("actions.act", "POST", "/v1/actions/{action}"), + call( + "installation.act", + "POST", + "/v1/installation/actions/{action}", + ), Role::View, ), admin(call("secrets.list", "GET", "/v1/secrets")), diff --git a/crates/berth-api/src/types.rs b/crates/berth-api/src/types.rs index 45c15d1..058dfc0 100644 --- a/crates/berth-api/src/types.rs +++ b/crates/berth-api/src/types.rs @@ -265,9 +265,10 @@ pub struct Session { pub command: Vec, pub user: String, pub started_by: From, - /// The task it was started for, if any. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub task: Option, + /// The action it was started for, if any. The sessions an older + /// berthd kept on the host say `task`. + #[serde(default, alias = "task", skip_serializing_if = "Option::is_none")] + pub action: Option, pub started: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub ended: Option, @@ -362,7 +363,7 @@ pub struct Signal { pub signal: String, } -// ── Tasks ─────────────────────────────────────────────────────────────────── +// ── A host's actions ─────────────────────────────────────────────────────────────── #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)] pub struct Argument { @@ -407,9 +408,10 @@ impl Argument { } } -/// An entry of `/etc/berth/tasks.json`. Listed without `run`. +/// An action of the host's controller: an entry of `/etc/berth/actions.json`. +/// Listed without `run`. #[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema)] -pub struct Task { +pub struct HostAction { pub name: String, #[serde(default)] pub label: String, @@ -424,7 +426,7 @@ pub struct Task { /// The agent may run it. #[serde(default)] pub agent: bool, - /// Tasks it is a step of; it then has no row of its own. + /// Actions it is a step of; it then has no row of its own. #[serde(default)] pub extends: Vec, #[serde(default)] @@ -439,7 +441,7 @@ pub struct Task { } #[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema)] -pub struct RunTask { +pub struct RunAction { #[serde(default)] pub arguments: BTreeMap, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -544,26 +546,26 @@ impl Default for Action { } impl Action { - /// The actions of a host's tasks, in the order the host lists them: each - /// task that is no step of another, with the steps plugins add to it. The - /// host keeps the rest of a task (its user, its command, its input), and - /// runs it by name. - pub fn of_tasks(tasks: &[Task]) -> Vec { - tasks + /// The actions of a host's controller as actions to describe, in the + /// order the host lists them: each that is no step of another, with the + /// steps plugins add to it. The host keeps the rest of one (its user, its + /// command, its input), and runs it by name. + pub fn of_host(listed: &[HostAction]) -> Vec { + listed .iter() - .filter(|task| task.extends.is_empty()) - .map(|task| Action { - name: task.name.clone(), - label: task.label.clone(), - help: task.help.clone(), - group: task.group.clone(), - arguments: task.arguments.clone(), - confirm: task.confirm.clone(), + .filter(|action| action.extends.is_empty()) + .map(|action| Action { + name: action.name.clone(), + label: action.label.clone(), + help: action.help.clone(), + group: action.group.clone(), + arguments: action.arguments.clone(), + confirm: action.confirm.clone(), runs: Runs::Host, - terminal: task.terminal, - steps: tasks + terminal: action.terminal, + steps: listed .iter() - .filter(|step| step.extends.contains(&task.name)) + .filter(|step| step.extends.contains(&action.name)) .map(|step| ActionStep { label: step.label.clone(), help: step.help.clone(), @@ -920,10 +922,10 @@ pub enum PluginOrigin { Folder, } -/// A task a feature adds to a host's overview. +/// An action a feature adds to a host. #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)] -pub struct PluginTask { - /// The task is `PLUGIN:NAME` on the host. +pub struct PluginAction { + /// The action is `PLUGIN:NAME` on the host. pub name: String, pub label: String, /// `agent`, `operator` or `root`. @@ -931,7 +933,7 @@ pub struct PluginTask { /// The agent may run it with `box run`. #[serde(default)] pub agent: bool, - /// Tasks of berth it runs after, with no row of its own. + /// Actions of berth it runs after, with no row of its own. #[serde(default)] pub extends: Vec, /// The names of the arguments it asks for. @@ -960,7 +962,7 @@ pub struct PluginFeature { #[serde(default)] pub help: String, #[serde(default)] - pub tasks: Vec, + pub actions: Vec, #[serde(default)] pub services: Vec, /// Channel topics, without the plugin's id. @@ -1423,7 +1425,7 @@ pub struct Rollout { /// Also the hosts that are current. #[serde(default)] pub all: bool, - /// Run each host's `update` task after applying. + /// Run each host's `update` action after applying. #[serde(default)] pub update: bool, /// Reboot a host that says it needs it, and wait for it to come back. @@ -1515,7 +1517,7 @@ pub struct RolloutHost { } /// Whether a line of a roll-out's output is one of its own, rather than -/// what Ansible or a task wrote: those start with ▸, ✓, ! or ✗. +/// what Ansible or an action wrote: those start with ▸, ✓, ! or ✗. pub fn rollout_line(line: &str) -> bool { ["▸ ", "✓ ", "! ", "✗ "] .iter() @@ -1548,6 +1550,17 @@ mod tests { assert_eq!(HostType::from_level("ssh"), None); } + #[test] + fn a_session_an_older_berthd_kept_names_its_action() { + let kept = json!({"id": "s1", "kind": "process", "title": "", "command": [], "user": "agent", + "started_by": {"level": "host", "uid": 0}, "task": "status", "started": "2026-11-12T10:00:00Z"}); + let session: Session = serde_json::from_value(kept).unwrap(); + assert_eq!(session.action.as_deref(), Some("status")); + let written = json!(session); + assert_eq!(written["action"], "status"); + assert!(written.get("task").is_none()); + } + #[test] fn the_version_of_an_older_berthd_is_read_with_its_type() { let old = json!({"version": "0.5.1", "api": 1, "mode": "system", "level": "controller"}); diff --git a/crates/berth-core/src/kept_profile.rs b/crates/berth-core/src/kept_profile.rs index 7107f1d..62f4e61 100644 --- a/crates/berth-core/src/kept_profile.rs +++ b/crates/berth-core/src/kept_profile.rs @@ -26,7 +26,7 @@ pub const FORMAT: u64 = 3; /// What a profile's `builder` held of how one berth reached the host, or of /// that berth's own machine, in the layout before `access`, and what still /// belongs to this machine alone: a served host names this berth's server, -/// and a USB drive and the last task were never meant to be kept. +/// and a USB drive and the last action were never meant to be kept. const LOCAL_BUILDER: &[&str] = &[ "ssh_host", "ssh_user", diff --git a/crates/berth-core/src/link.rs b/crates/berth-core/src/link.rs index 98a91f0..3d42ce4 100644 --- a/crates/berth-core/src/link.rs +++ b/crates/berth-core/src/link.rs @@ -296,12 +296,12 @@ impl Link { self.call("POST", path, Some(body)).await } - /// Run a task of the host, as `tasks.run` takes it, and the session it + /// Run an action of the host, as `actions.run` takes it, and the session it /// runs as. Through a berth server it is the host's action there, which /// the server keeps a job of and gives the server's secrets to. - pub async fn run_task(&self, name: &str, body: &Value) -> client::Result { + pub async fn run_action(&self, name: &str, body: &Value) -> client::Result { let Some((server, host)) = &self.spec.via else { - let path = format!("/v1/tasks/{}", client::encode(name)); + let path = format!("/v1/actions/{}", client::encode(name)); return self.post(&path, body).await; }; let portal = self.portal(server).await?; @@ -311,7 +311,7 @@ impl Link { .await?; serde_json::from_value(acted["session"].clone()).map_err(|_| { Error::Transport(format!( - "{name} on {host} is not a task of the host: run it with berth run {host} {name}" + "{name} on {host} is not an action of its controller: run it with berth run {host} {name}" )) }) } diff --git a/crates/berth-core/src/plugins.rs b/crates/berth-core/src/plugins.rs index 1014257..8a6615c 100644 --- a/crates/berth-core/src/plugins.rs +++ b/crates/berth-core/src/plugins.rs @@ -1,13 +1,13 @@ //! Plugins: npm-format packages whose `package.json` has a `berth` section. -//! Each contributes features to the groups of the Features page, and tasks to -//! the overview of a host. The role does the installing from the same manifest. +//! Each contributes features to the groups of the Features page, and actions +//! to the overview of a host. The role does the installing from the same manifest. //! A plugin can also bring provisioners, programs that create the machine a //! profile describes; berth runs those itself (see [`crate::provision`]). use crate::{Result, paths::Paths, server::Server}; use berth_api::{ - AppliedPlugin, PluginFeature, PluginInfo, PluginList as Listing, PluginOrigin, - PluginReport as Report, PluginService, PluginTask, PluginUpdate, PluginUpdates, + AppliedPlugin, PluginAction as ListedAction, PluginFeature, PluginInfo, PluginList as Listing, + PluginOrigin, PluginReport as Report, PluginService, PluginUpdate, PluginUpdates, ProvisionerInfo, }; use serde_json::{Value, json}; @@ -19,7 +19,7 @@ pub struct PluginAction { pub label: String, pub help: &'static str, /// Shell command the host runs. berth does not run it from here: the - /// role writes it into the host's task list. + /// role writes it into the host's list of actions. pub run: String, /// `agent`, `operator` or `root`. pub user: String, @@ -27,7 +27,7 @@ pub struct PluginAction { pub terminal: bool, /// The group of the overview it is listed in; the plugin's own when empty. pub group: String, - /// Tasks of berth it is part of, such as `status`. It runs after them and + /// Actions of berth it is part of, such as `status`. It runs after them and /// has no row of its own. pub extends: Vec, /// The agent may run it with `box run`. @@ -272,10 +272,10 @@ fn read(dir: &Path) -> Option { terminal: action["terminal"].as_bool().unwrap_or(false), group: text(action, "group"), extends: match &action["extends"] { - Value::String(task) => vec![task.clone()], - tasks => list(tasks) + Value::String(name) => vec![name.clone()], + names => list(names) .iter() - .filter_map(|task| task.as_str().map(str::to_owned)) + .filter_map(|name| name.as_str().map(str::to_owned)) .collect(), }, agent: action["agent"].as_bool().unwrap_or(false), @@ -286,7 +286,7 @@ fn read(dir: &Path) -> Option { }) .filter(|argument| valid_name(&argument.name)) // Only a provisioner's arguments size a machine or are a - // list of values; a task's offers them with `choices`. + // list of values; another action offers them with `choices`. .map(|argument| berth_api::Argument { kind: String::new(), values: vec![], @@ -570,10 +570,10 @@ impl Plugin { label: feature.label.clone(), group: feature.group.clone(), help: feature.help.to_owned(), - tasks: feature + actions: feature .actions .iter() - .map(|action| PluginTask { + .map(|action| ListedAction { name: action.name.clone(), label: action.label.clone(), user: action.user.clone(), @@ -628,22 +628,22 @@ pub fn describe(plugins: &[PluginInfo]) -> String { " {}/{} {} ({})\n", plugin.id, feature.id, feature.label, feature.group ); - for task in &feature.tasks { - let mut notes = vec![format!("as {}", task.user)]; - if task.agent { + for action in &feature.actions { + let mut notes = vec![format!("as {}", action.user)]; + if action.agent { notes.push("the agent may run it".into()); } - if !task.extends.is_empty() { - notes.push(format!("part of {}", task.extends.join(", "))); + if !action.extends.is_empty() { + notes.push(format!("part of {}", action.extends.join(", "))); } - for argument in &task.arguments { + for argument in &action.arguments { notes.push(format!("asks {argument}")); } text += &format!( - " task {}:{} {} ({})\n", + " action {}:{} {} ({})\n", plugin.id, - task.name, - task.label, + action.name, + action.label, notes.join("; ") ); } @@ -1585,8 +1585,8 @@ mod tests { assert_eq!(linked.len(), 1); assert_eq!(linked[0].origin(&own), PluginOrigin::Npm); let info = linked[0].info(&own); - assert_eq!(info.features[0].tasks[0].name, "go"); - assert!(describe(&[info]).contains(" task x:go")); + assert_eq!(info.features[0].actions[0].name, "go"); + assert!(describe(&[info]).contains(" action x:go")); assert!(remove(&paths, &shipped[0]).is_err()); fs::remove_file(own.join("node_modules/berth-plugin-x")).unwrap(); write(&own.join("x")); diff --git a/crates/berth-core/src/rollout.rs b/crates/berth-core/src/rollout.rs index aaf62a0..021b8bc 100644 --- a/crates/berth-core/src/rollout.rs +++ b/crates/berth-core/src/rollout.rs @@ -22,8 +22,8 @@ pub trait Target { fn version(&mut self) -> std::result::Result, String>; /// Apply its configuration, its output going to `out`. fn apply(&mut self, out: &mut dyn Write) -> std::result::Result<(), String>; - /// Run one of its tasks to the end, with its output to `out`: the exit code. - fn task(&mut self, name: &str, out: &mut dyn Write) -> std::result::Result; + /// Run one of its actions to the end, with its output to `out`: the exit code. + fn run_action(&mut self, name: &str, out: &mut dyn Write) -> std::result::Result; /// Seconds it has been up, and whether it says it needs a reboot. fn uptime(&mut self) -> std::result::Result<(u64, bool), String>; /// How many sessions run there. @@ -159,7 +159,7 @@ fn one( target.apply(out)?; if options.update { say(out, &format!("▸ {name}: update")); - match target.task("update", out) { + match target.run_action("update", out) { Ok(0) => {} Ok(code) => host.warnings.push(format!("update ended with {code}")), Err(error) => host.warnings.push(format!("update did not run: {error}")), @@ -200,9 +200,9 @@ fn one( return Err(format!("still behind after applying: {}", behind.text())); } } - match target.task("status", out)? { + match target.run_action("status", out)? { 0 => {} - code => return Err(format!("its status task ended with {code}")), + code => return Err(format!("its status action ended with {code}")), } host.state = RolloutState::Done; say(out, &format!("✓ {name} is up to date")); @@ -367,12 +367,12 @@ impl Target for Live<'_> { } } - fn task(&mut self, name: &str, out: &mut dyn Write) -> std::result::Result { - let path = format!("/v1/tasks/{}?wait=10m", api::client::encode(name)); + fn run_action(&mut self, name: &str, out: &mut dyn Write) -> std::result::Result { + let path = format!("/v1/actions/{}?wait=10m", api::client::encode(name)); let started: api::Started = self.post(&path, &json!({}))?; let id = started.session.id.clone(); let mut session = started.session; - // A task that takes longer than the wait is asked after again. + // An action that takes longer than the wait is asked after again. while session.running() { self.pause(REBOOT_EVERY); session = self.get(&format!("/v1/sessions/{id}"))?; @@ -536,7 +536,11 @@ mod tests { } } } - fn task(&mut self, name: &str, _out: &mut dyn Write) -> std::result::Result { + fn run_action( + &mut self, + name: &str, + _out: &mut dyn Write, + ) -> std::result::Result { self.log.borrow_mut().push(format!("{} {name}", self.name)); Ok(match name { "update" => self.update_code, @@ -809,7 +813,7 @@ mod tests { let log = Default::default(); let mut targets: Vec> = vec![Box::new(make(&log, 0, true, 3))]; let report = run(&mut targets, &reboot, &now, &mut vec![]); - assert_eq!(report.hosts[0].error, "its status task ended with 3"); + assert_eq!(report.hosts[0].error, "its status action ended with 3"); } #[test] diff --git a/crates/berth-core/src/runner.rs b/crates/berth-core/src/runner.rs index 18f424d..828546d 100644 --- a/crates/berth-core/src/runner.rs +++ b/crates/berth-core/src/runner.rs @@ -6,7 +6,7 @@ //! //! What a job runs is one of three executors: a function of berth (applying //! a host's profile, a roll-out, a provisioning), a program (ansible, or a -//! plugin's provisioner), or a task of a host's controller. A task runs as +//! plugin's provisioner), or an action of a host's controller. An action runs as //! a session on the host, and its job copies the session's output while it //! runs, so the job stays readable when the host is not and after the host //! has forgotten the session. @@ -292,7 +292,7 @@ pub enum Work { /// whether it went well. Function(Box bool + Send>), Program(Box), - /// A session a task of a host's controller runs, by its id there, + /// A session an action of a host's controller runs, by its id there, /// followed until it ends. Session { controller: Box, @@ -904,7 +904,7 @@ mod tests { } #[test] - fn a_task_of_a_host_is_a_job_that_copies_its_session() { + fn an_action_of_a_host_is_a_job_that_copies_its_session() { let world = world(); let asked = Arc::new(Mutex::new(vec![])); let controller = Box::new(Fake { @@ -913,7 +913,7 @@ mod tests { failures: 1, }); let mut request = Request::new(Subject::Host("studio".into()), "status"); - // A task runs beside the host's other sessions, without the lock. + // An action runs beside the host's other sessions, without the lock. request.changes = false; let work = Work::Session { controller, diff --git a/crates/berth-page/src/admin.rs b/crates/berth-page/src/admin.rs index 292d590..8526980 100644 --- a/crates/berth-page/src/admin.rs +++ b/crates/berth-page/src/admin.rs @@ -348,7 +348,7 @@ impl Admin { let body = json!({"arguments": options.arguments()}); let asked = json!({"action": "rollout"}); self.portal - .call("actions.act", None, asked, body, move |result| { + .call("installation.act", None, asked, body, move |result| { let job = match result { Ok(acted) => acted["job"].clone(), Err(error) => { @@ -577,7 +577,7 @@ impl Admin { self.job("apply", name, body, title, size, |_| {}); } - /// What the server lists as the host's actions: its tasks and berth's own. + /// What the server lists as the host's actions: its controller's and berth's own. pub fn actions(&self, name: &str) { let admin = self.clone(); let host = name.to_owned(); diff --git a/crates/berth-page/src/app.rs b/crates/berth-page/src/app.rs index fe180c2..0147461 100644 --- a/crates/berth-page/src/app.rs +++ b/crates/berth-page/src/app.rs @@ -449,7 +449,7 @@ impl App { setup.machine.found(found); } } - // berth's own actions are beside the host's tasks; applying + // berth's own actions are beside the controller's; applying // and the seed have rows of their own. Arrived::Actions(name, listed) if name == self.name => { self.host.own = listed @@ -625,14 +625,14 @@ impl App { // A host that cannot be worked with yet still has berth's own // actions, such as first contact and installing the controller. let actions = self.host.actions(); - let mut groups: Vec<(String, Vec)> = berth_tui::page::groups(&actions, Pick::Task) + let mut groups: Vec<(String, Vec)> = berth_tui::page::groups(&actions, Pick::Action) .into_iter() .map(|group| { let picks = group .rows .into_iter() .filter( - |(_, pick)| matches!(pick, Pick::Task(index) if self.host.is_own(*index)), + |(_, pick)| matches!(pick, Pick::Action(index) if self.host.is_own(*index)), ) .map(|(line, pick)| Row { line: line.into(), @@ -704,7 +704,7 @@ impl App { fn help(&self) -> String { match self.selected() { - Some(Entry::Pick(Pick::Task(index))) => host::task_help(&self.host, index), + Some(Entry::Pick(Pick::Action(index))) => host::action_help(&self.host, index), Some(Entry::Pick(Pick::Session(index))) => host::session_help(&self.host, index), Some(Entry::Pick(Pick::Terminal)) => format!( "A shell on the host, as one of its sessions. Space switches between the agent and the SSH user.\n\nLeaving the shell closes it; {LEAVE} leaves it running, to be opened again from Sessions." @@ -749,21 +749,21 @@ impl App { } return; } - let body = self.host.task_body(&action, &values); + let body = self.host.action_body(&action, &values); self.status = format!("Starting {}…", action.title()); self.host.run(&action.name, body); } fn choose(&mut self, entry: Entry) { match entry { - Entry::Pick(Pick::Task(index)) => { + Entry::Pick(Pick::Action(index)) => { if let Some(action) = self.host.actions().get(index) && !action.available { self.status = format!("{} cannot run now: {}", action.title(), action.why); return; } - if let Some((index, values)) = self.host.begin_task(index, false) { + if let Some((index, values)) = self.host.begin_action(index, false) { self.launch(index, values); } } @@ -873,7 +873,7 @@ impl App { match key.code { Code::Char('y' | 'Y') => match self.host.question.take() { Some((_, Pending::Action(index))) => { - if let Some((index, values)) = self.host.begin_task(index, true) { + if let Some((index, values)) = self.host.begin_action(index, true) { self.launch(index, values); } } diff --git a/crates/berth-page/src/remote.rs b/crates/berth-page/src/remote.rs index 0229636..6da0e0a 100644 --- a/crates/berth-page/src/remote.rs +++ b/crates/berth-page/src/remote.rs @@ -175,11 +175,11 @@ impl Transport for Remote { events: events.clone(), stream: Cell::new(None), }; - again.call("tasks.list", json!({}), Value::Null, |result, events| { - if let Ok(tasks) = result { + again.call("actions.list", json!({}), Value::Null, |result, events| { + if let Ok(listed) = result { events .borrow_mut() - .push_back(Event::Tasks(list(tasks, "tasks"))); + .push_back(Event::Actions(list(listed, "actions"))); } }); again.poll(); @@ -192,7 +192,7 @@ impl Transport for Remote { }); } Request::Poll => self.poll(), - // A task is the host's action on the server, which keeps a job of it. + // An action is the host's action on the server, which keeps a job of it. Request::Run { name, body } => { let events = self.events.clone(); let args = json!({"name": self.host, "action": name}); @@ -245,17 +245,22 @@ impl Transport for Remote { }, ); } - Request::Choices { task, argument } => { - let args = json!({"name": task, "argument": argument}); - self.call("tasks.choices", args, Value::Null, move |result, events| { - events.borrow_mut().push_back(Event::Choices { - task, - argument, - choices: result - .map(|value| list(value, "choices")) - .unwrap_or_default(), - }); - }); + Request::Choices { action, argument } => { + let args = json!({"action": action, "argument": argument}); + self.call( + "actions.choices", + args, + Value::Null, + move |result, events| { + events.borrow_mut().push_back(Event::Choices { + action, + argument, + choices: result + .map(|value| list(value, "choices")) + .unwrap_or_default(), + }); + }, + ); } } } diff --git a/crates/berth-tui/src/fields.rs b/crates/berth-tui/src/fields.rs index 34e0450..eef5419 100644 --- a/crates/berth-tui/src/fields.rs +++ b/crates/berth-tui/src/fields.rs @@ -51,8 +51,8 @@ impl Step { } /// The rows of a host's overview that are berth's own: name, label and help. -/// Everything else there is a task the host lists itself. -pub const TASKS: &[(&str, &str, &str)] = &[ +/// Everything else there is an action the host lists itself. +pub const OFFERS: &[(&str, &str, &str)] = &[ ( "terminal", "Terminal", @@ -173,13 +173,13 @@ impl Action { "Build the desktop image using Docker Compose. Start it afterwards with docker compose." } Action::Manage => { - "Look after a host that is already set up, over SSH: show its status and access links, publish the desktop on the tailnet, run the smoke test, install updates or reboot. Pick the task on the overview." + "Look after a host that is already set up, over SSH: show its status and access links, publish the desktop on the tailnet, run the smoke test, install updates or reboot. Pick the action on the overview." } Action::Ssh => { "Install on an existing Ubuntu host over SSH. Enter a hostname, IP address or SSH config alias, and how berth logs in: its own key by default. A host that does not take that key yet gets it with berth key trust HOST and a password used once. Sudo prompts use the normal terminal." } Action::Reach => { - "Add a host berth only logs in to over SSH, such as a server that stays as it is: nothing is installed on it. Enter a hostname, IP address or SSH config alias, and how berth logs in. Run saves it; a host that does not take berth's key yet gets it with berth key trust HOST. Its page can install the controller later, for sessions, tasks and files." + "Add a host berth only logs in to over SSH, such as a server that stays as it is: nothing is installed on it. Enter a hostname, IP address or SSH config alias, and how berth logs in. Run saves it; a host that does not take berth's key yet gets it with berth key trust HOST. Its page can install the controller later, for sessions, actions and files." } } } diff --git a/crates/berth-tui/src/host.rs b/crates/berth-tui/src/host.rs index 2d73fde..0ecc5b9 100644 --- a/crates/berth-tui/src/host.rs +++ b/crates/berth-tui/src/host.rs @@ -11,7 +11,7 @@ use std::collections::BTreeMap; use std::time::{Duration, Instant}; /// The lowest `api` of a host this berth can work with. -pub const NEEDS_API: u32 = 1; +pub const NEEDS_API: u32 = 2; /// How often the overview asks for stats and sessions again. const POLL: Duration = Duration::from_secs(10); /// Lines of a process session's transcript kept for scrolling back. @@ -25,11 +25,11 @@ pub trait Transport { } pub enum Request { - /// Version, tasks, sessions and stats. + /// Version, actions, sessions and stats. Refresh, /// Sessions and stats. Poll, - /// Run a task; the answer is `Opened`. + /// Run an action; the answer is `Opened`. Run { name: String, body: Value, @@ -45,7 +45,7 @@ pub enum Request { Close, Delete(String), Choices { - task: String, + action: String, argument: String, }, } @@ -60,7 +60,7 @@ pub enum Event { message: String, missing: bool, }, - Tasks(Vec), + Actions(Vec), Sessions(Vec), Stats(Box), Opened(Box), @@ -70,7 +70,7 @@ pub enum Event { /// The stream of a session ended without it having exited. Closed(String), Choices { - task: String, + action: String, argument: String, choices: Vec, }, @@ -230,7 +230,7 @@ pub enum Pending { pub struct HostView { remote: Option>, pub state: State, - pub tasks: Vec, + pub host_actions: Vec, pub sessions: Vec, pub stats: Option, /// What changed since the host was applied, when berth knows. @@ -239,7 +239,7 @@ pub struct HostView { pub host_type: api::HostType, /// The type the host was seen to be, once it was asked. pub seen: Option, - /// berth's own actions on the host, beside its tasks: what a berth + /// berth's own actions on the host, beside its controller's: what a berth /// server lists for its host, or what this berth does itself. pub own: Vec, pub view: Option, @@ -259,7 +259,7 @@ impl Default for HostView { HostView { remote: None, state: State::Idle, - tasks: vec![], + host_actions: vec![], sessions: vec![], stats: None, behind: None, @@ -300,7 +300,7 @@ impl HostView { pub fn disconnect(&mut self) { self.remote = None; self.view = None; - self.tasks.clear(); + self.host_actions.clear(); self.sessions.clear(); self.stats = None; self.behind = None; @@ -314,7 +314,7 @@ impl HostView { } } - /// Run a task; its session opens in the panel when the host has started it. + /// Run an action; its session opens in the panel when the host has started it. pub fn run(&mut self, name: &str, body: Value) { self.starting = Some(false); self.send(Request::Run { @@ -323,15 +323,15 @@ impl HostView { }); } - /// What can be done on the host: its tasks as actions, each task that + /// What can be done on the host: its controller's actions, each that /// is no step of another, with the steps plugins add to it, and then - /// berth's own that are no task of the host. + /// berth's own that are no action of the host. pub fn actions(&self) -> Vec { - let mut actions = api::Action::of_tasks(&self.tasks); + let mut actions = api::Action::of_host(&self.host_actions); let own = self .own .iter() - .filter(|action| !actions.iter().any(|task| task.name == action.name)) + .filter(|action| !actions.iter().any(|listed| listed.name == action.name)) .cloned() .collect::>(); actions.extend(own); @@ -343,12 +343,12 @@ impl HostView { pub fn is_own(&self, index: usize) -> bool { self.actions() .get(index) - .is_some_and(|action| self.task(action).is_none()) + .is_some_and(|action| self.host_action(action).is_none()) } /// Begin an action: its question first, then its arguments. Returns the /// action to run now when it needs neither. - pub fn begin_task(&mut self, index: usize, confirmed: bool) -> Option { + pub fn begin_action(&mut self, index: usize, confirmed: bool) -> Option { match page::begin(&self.actions(), index, confirmed) { Begin::Ask(question) => self.question = Some((question, Pending::Action(index))), Begin::Arguments(dialog) => { @@ -362,12 +362,12 @@ impl HostView { } fn ask_choices(&self) { - if let Some((task, argument)) = self + if let Some((action, argument)) = self .arguments .as_ref() .and_then(|dialog| dialog.wants_choices(&self.actions())) { - self.send(Request::Choices { task, argument }); + self.send(Request::Choices { action, argument }); } } @@ -391,8 +391,8 @@ impl HostView { } } - /// What starting a task sends: its arguments, and the panel's size for a terminal. - pub fn task_body(&self, action: &api::Action, values: &BTreeMap) -> Value { + /// What starting an action sends: its arguments, and the panel's size for a terminal. + pub fn action_body(&self, action: &api::Action, values: &BTreeMap) -> Value { let mut body = json!({"arguments": values}); if action.terminal { (body["rows"], body["cols"]) = (json!(self.size.0), json!(self.size.1)); @@ -400,9 +400,11 @@ impl HostView { body } - /// The task an action of the host runs, with what the host keeps of it. - pub fn task(&self, action: &api::Action) -> Option<&api::Task> { - self.tasks.iter().find(|task| task.name == action.name) + /// What the host keeps of one of its controller's actions. + pub fn host_action(&self, action: &api::Action) -> Option<&api::HostAction> { + self.host_actions + .iter() + .find(|kept| kept.name == action.name) } /// Start a shell as `user`. @@ -489,7 +491,7 @@ impl HostView { } } Event::Behind(behind) => self.behind = behind, - Event::Tasks(tasks) => self.tasks = tasks, + Event::Actions(listed) => self.host_actions = listed, Event::Sessions(sessions) => self.sessions = sessions, Event::Stats(stats) => self.stats = Some(*stats), Event::Opened(session) => { @@ -526,13 +528,13 @@ impl HostView { } } Event::Choices { - task, + action, argument, choices, } => { let actions = self.actions(); if let Some(dialog) = &mut self.arguments { - dialog.offered(&actions, &task, &argument, choices); + dialog.offered(&actions, &action, &argument, choices); } } Event::Error(message) => { @@ -610,20 +612,21 @@ pub fn session_state(session: &api::Session) -> String { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Pick { /// An action, by index into [`HostView::actions`]. - Task(usize), + Action(usize), Terminal, /// A session, by index. Session(usize), } -/// The groups of the overview of a host that answers, as it lists its tasks: +/// The groups of the overview of a host that answers, as it lists its actions: /// each in the group it names, with the terminal among the first and the /// host's sessions after them. pub fn groups(host: &HostView, terminal_user: &str) -> Vec<(String, Vec<(String, Pick)>)> { - let mut groups: Vec<(String, Vec<(String, Pick)>)> = page::groups(&host.actions(), Pick::Task) - .into_iter() - .map(|group| (group.title, group.rows)) - .collect(); + let mut groups: Vec<(String, Vec<(String, Pick)>)> = + page::groups(&host.actions(), Pick::Action) + .into_iter() + .map(|group| (group.title, group.rows)) + .collect(); let terminal = (format!(" ▸ Terminal · as {terminal_user}"), Pick::Terminal); match groups.iter_mut().find(|(title, _)| title == "System") { Some((_, rows)) => rows.insert(1.min(rows.len()), terminal), @@ -700,7 +703,7 @@ pub fn exited(frame: &Value) -> Option> { } /// What the information box says of an action of the host. -pub fn task_help(host: &HostView, index: usize) -> String { +pub fn action_help(host: &HostView, index: usize) -> String { match host.actions().get(index) { Some(action) => page::help(action, &command_of(&action.name)), None => String::new(), @@ -745,13 +748,13 @@ mod tests { use super::*; #[test] - fn berths_own_actions_follow_the_tasks_and_say_when_they_cannot_run() { + fn berths_own_actions_follow_the_controllers_and_say_when_they_cannot_run() { let mut host = HostView { - tasks: vec![api::Task { + host_actions: vec![api::HostAction { name: "status".into(), label: "Status".into(), group: "System".into(), - ..api::Task::default() + ..api::HostAction::default() }], ..HostView::default() }; @@ -771,13 +774,13 @@ mod tests { ]; let actions = host.actions(); let names: Vec<&str> = actions.iter().map(|action| action.name.as_str()).collect(); - // A task of the host wins over one of berth's of the same name. + // An action of the host wins over one of berth's of the same name. assert_eq!(names, ["status", "install-controller"]); assert!(!host.is_own(0) && host.is_own(1)); let groups = groups(&host, "agent"); let setup = groups.iter().find(|(title, _)| title == "Set-Up").unwrap(); assert_eq!(setup.1[0].0, " ▸ Update the controller · not now"); - assert!(task_help(&host, 1).contains("It cannot run now: studio is a workstation")); + assert!(action_help(&host, 1).contains("It cannot run now: studio is a workstation")); } #[test] diff --git a/crates/berth-tui/src/plugins.rs b/crates/berth-tui/src/plugins.rs index 3c57196..aab81e0 100644 --- a/crates/berth-tui/src/plugins.rs +++ b/crates/berth-tui/src/plugins.rs @@ -60,7 +60,7 @@ impl Place<'_> { fn server_note(dir: &str) -> String { format!( - "Registries and logins come from the server's npm configuration. npm runs none of the plugin's scripts; its tasks run when a host is applied.\n\nA folder copied to {dir} on the server works as well." + "Registries and logins come from the server's npm configuration. npm runs none of the plugin's scripts; its Ansible tasks run when a host is applied.\n\nA folder copied to {dir} on the server works as well." ) } diff --git a/crates/berth-tui/src/screen.rs b/crates/berth-tui/src/screen.rs index 12255b9..80cbec9 100644 --- a/crates/berth-tui/src/screen.rs +++ b/crates/berth-tui/src/screen.rs @@ -491,10 +491,10 @@ pub fn draw_arguments(frame: &mut Frame, host: &HostView) { /// The dialog that asks for the arguments of one of a subject's actions. pub fn draw_action_arguments(frame: &mut Frame, actions: &[berth_api::Action], asked: &Arguments) { - let Some(task) = actions.get(asked.action) else { + let Some(action) = actions.get(asked.action) else { return; }; - let Some(argument) = task.arguments.get(asked.index) else { + let Some(argument) = action.arguments.get(asked.index) else { return; }; let mut lines = vec![Line::raw(ellipsize(argument_label(argument), 56))]; @@ -522,9 +522,9 @@ pub fn draw_action_arguments(frame: &mut Frame, actions: &[berth_api::Action], a let title = ellipsize( &format!( " {} · {} of {} ", - task.title(), + action.title(), asked.index + 1, - task.arguments.len() + action.arguments.len() ), 58, ); @@ -699,7 +699,7 @@ pub fn view_event( None } -/// Keys of the dialog that asks for a task's arguments. Returns whether the +/// Keys of the dialog that asks for an action's arguments. Returns whether the /// value was accepted, for the caller to go on with. pub fn arguments_event( host: &mut HostView, diff --git a/crates/berth/src/app.rs b/crates/berth/src/app.rs index 5a465fb..1bc651c 100644 --- a/crates/berth/src/app.rs +++ b/crates/berth/src/app.rs @@ -3,7 +3,7 @@ use crate::{ Result, credentials, discovery::{self, Choices, expand_path}, - fields::{Action, Field, Kind, Step, TASKS}, + fields::{Action, Field, Kind, OFFERS, Step}, job::{Job, Stage}, picker::Picker, plugins::{self, Plugin}, @@ -32,13 +32,13 @@ pub enum Entry { Action(Action), Field(Field), /// Something the overview of a host offers, by name. - Task(&'static str), + Offer(&'static str), /// The heading of a group on the Features page. Group(usize), /// A plugin's feature, switched on or off for this host: its index among them. Feature(usize), - /// A task of the host, by index into what it listed. - HostTask(usize), + /// An action of the host, by index into what it listed. + HostAction(usize), /// A session on the host, by index into what it listed. HostSession(usize), /// A registry this host can be given, by index into `App::registry_names`. @@ -657,7 +657,7 @@ impl App { { setup.push(Row::entry( " ▸ Apply this configuration", - Entry::Task("apply"), + Entry::Offer("apply"), )); } match groups.iter_mut().find(|(title, _)| title == "Set-Up") { @@ -682,18 +682,18 @@ impl App { } /// The groups of the overview under the connection, as the host lists its - /// tasks: each in the group it names, with the terminal among the first and + /// actions: each in the group it names, with the terminal among the first and /// the host's sessions after them. A host that cannot be asked says why. fn overview_groups(&self) -> Vec<(String, Vec)> { let note = |text: String, colour| { Row::info(Line::styled(format!(" {text}"), Style::new().fg(colour))) }; let fixed = |name: &'static str| { - let label = TASKS + let label = OFFERS .iter() - .find(|(task, ..)| *task == name) + .find(|(offer, ..)| *offer == name) .map_or(name, |(_, label, _)| label); - Row::entry(format!(" ▸ {label}"), Entry::Task(name)) + Row::entry(format!(" ▸ {label}"), Entry::Offer(name)) }; // A host that cannot be worked with yet still has berth's own // actions, such as first contact and installing the controller. @@ -723,7 +723,7 @@ impl App { // Below a workstation the controller is installed alone. State::Missing if self.host.host_type != host_type::HostType::Workstation => { let rows = vec![ - note("berth's controller is not on this host. Install it for sessions, tasks and files here; berth reaches the host over SSH meanwhile.".into(), theme::MUTED), + note("berth's controller is not on this host. Install it for sessions, actions and files here; berth reaches the host over SSH meanwhile.".into(), theme::MUTED), fixed("ssh"), ]; return host(rows); @@ -742,7 +742,7 @@ impl App { let mut rows = vec![note( format!( "The host's tools ({version}) are older than this berth needs. {} brings them up to date.", - TASKS + OFFERS .iter() .find(|(name, ..)| *name == raise) .map_or(raise, |(_, label, _)| label) @@ -803,8 +803,8 @@ impl App { .into_iter() .map(|(line, pick)| { let entry = match pick { - Pick::Task(index) => Entry::HostTask(index), - Pick::Terminal => Entry::Task("terminal"), + Pick::Action(index) => Entry::HostAction(index), + Pick::Terminal => Entry::Offer("terminal"), Pick::Session(index) => Entry::HostSession(index), }; Row::entry(line, entry) @@ -816,7 +816,7 @@ impl App { .collect() } - /// berth's own actions on the host in their groups, without its tasks. + /// berth's own actions on the host in their groups, without its controller's. fn own_groups(&self) -> Vec<(String, Vec)> { berth_tui::page::groups(&self.host.actions(), |index| index) .into_iter() @@ -825,7 +825,7 @@ impl App { .rows .into_iter() .filter(|(_, index)| self.host.is_own(*index)) - .map(|(line, index)| Row::entry(line, Entry::HostTask(index))) + .map(|(line, index)| Row::entry(line, Entry::HostAction(index))) .collect(); (group.title, rows) }) @@ -867,12 +867,12 @@ impl App { } } - /// The information box for the selected row, as Markdown. A task that has + /// The information box for the selected row, as Markdown. An action that has /// steps from plugins lists what each of them adds. pub fn help(&self) -> String { match self.selected_entry() { Some(Entry::Feature(index)) => self.catalogue[index].help.clone(), - Some(Entry::HostTask(index)) => berth_tui::host::task_help(&self.host, index), + Some(Entry::HostAction(index)) => berth_tui::host::action_help(&self.host, index), Some(Entry::HostSession(index)) => berth_tui::host::session_help(&self.host, index), Some(Entry::Machine(pick)) => self.machine.help(pick), _ => self.entry_help().to_owned(), @@ -883,13 +883,13 @@ impl App { match self.selected_entry() { Some(Entry::Action(action)) => action.help(), Some(Entry::Field(field)) => field.spec().help, - Some(Entry::Task(name)) => TASKS + Some(Entry::Offer(name)) => OFFERS .iter() - .find(|(task, ..)| *task == name) + .find(|(offer, ..)| *offer == name) .map_or("", |(.., help)| help), Some(Entry::Group(_)) => setup::GROUP_HELP, Some(Entry::Feature(_)) => "", - Some(Entry::HostTask(_) | Entry::HostSession(_) | Entry::Machine(_)) => "", + Some(Entry::HostAction(_) | Entry::HostSession(_) | Entry::Machine(_)) => "", Some(Entry::HostRegistry(_)) => { "Give this host the login of this registry. Its npm repositories become the agent's npm registry with the login in ~/.npmrc, and its Docker addresses get the login in ~/.docker/config.json. Registries are set up on the Registries tab of the home screen." } @@ -985,10 +985,10 @@ impl App { if step != Step::Manage && self.action == Action::Machine { setup::fit_target(&mut self.config, self.action); } - // A host with an address opens on its tasks rather than the address. - let task = |entry: &Entry| matches!(entry, Entry::Task(_) | Entry::HostTask(_)); + // A host with an address opens on its actions rather than the address. + let offered = |entry: &Entry| matches!(entry, Entry::Offer(_) | Entry::HostAction(_)); let first = match self.text(Field::SshHost).is_empty() { - false if step == Step::Manage => self.entries().iter().position(task), + false if step == Step::Manage => self.entries().iter().position(offered), _ => None, }; if step == Step::Settings { @@ -1751,7 +1751,7 @@ impl App { } /// Of what a server lists, berth's own that the overview has no row of: - /// applying and the seed are on the set-up, sending secrets is a task. + /// applying and the seed are on the set-up, sending secrets is an action. fn take_own_actions(&mut self) { let Some(answers) = &self.own_answers else { return; @@ -1832,30 +1832,30 @@ impl App { } } - /// Run a task of the host: after its question and its arguments, if it has any. - pub fn begin_task(&mut self, index: usize, confirmed: bool) { + /// Run an action of the host: after its question and its arguments, if it has any. + pub fn begin_action(&mut self, index: usize, confirmed: bool) { if let Some(action) = self.host.actions().get(index) && !action.available { self.status = format!("{} cannot run now: {}", action.title(), action.why); return; } - if let Some((index, values)) = self.host.begin_task(index, confirmed) { - self.launch_task(index, values); + if let Some((index, values)) = self.host.begin_action(index, confirmed) { + self.launch_action(index, values); } } /// Take the value typed for the argument being asked and go on to the - /// next, or run the task after the last. + /// next, or run the action after the last. pub fn accept_argument(&mut self) { match self.host.accept_argument() { - Ok(Some((index, values))) => self.launch_task(index, values), + Ok(Some((index, values))) => self.launch_action(index, values), Ok(None) => {} Err(missing) => self.status = missing, } } - fn launch_task(&mut self, index: usize, values: std::collections::BTreeMap) { + fn launch_action(&mut self, index: usize, values: std::collections::BTreeMap) { let Some(action) = self.host.actions().get(index).cloned() else { return; }; @@ -1864,13 +1864,13 @@ impl App { self.own_command = Some(own_command(&self.place.argument(), &action, &values)); return; } - let mut body = self.host.task_body(&action, &values); - // Secrets are built here and travel on the task's standard input. A + let mut body = self.host.action_body(&action, &values); + // Secrets are built here and travel on the action's standard input. A // server's host is given the server's own, which its action sends. let secrets = self .host - .task(&action) - .and_then(|task| task.input.as_deref()); + .host_action(&action) + .and_then(|kept| kept.input.as_deref()); if secrets == Some("secrets") && self.served().is_none() { let payload = self .access() @@ -2249,7 +2249,7 @@ impl App { /// Run the chosen action inside the UI. Writing a USB drive first asks for /// confirmation and for administrator rights. pub fn run(&mut self, confirmed: bool) { - // The overview has no action of its own: its rows are the host's tasks. + // The overview has no action of its own: its rows are the host's actions. if self.action == Action::Manage { return; } @@ -2709,7 +2709,7 @@ pub fn parse_config(data: &[u8]) -> Result { if config["agent_privileges"].is_null() && config["agent_passwordless_sudo"] == true { config["agent_privileges"] = json!("full"); } - // The task last run from the overview was kept once; the host lists its own now. + // The action last run from the overview was kept once; the host lists its own now. if let Some(builder) = config["builder"].as_object_mut() { builder.remove("manage_task"); } diff --git a/crates/berth/src/commands.rs b/crates/berth/src/commands.rs index 655b282..07c03f1 100644 --- a/crates/berth/src/commands.rs +++ b/crates/berth/src/commands.rs @@ -1,4 +1,4 @@ -//! The commands that talk to a host's controller: sessions, tasks, the +//! The commands that talk to a host's controller: sessions, actions, the //! channel and services. Each is a plain program that waits on a runtime. use crate::{ @@ -512,17 +512,17 @@ pub fn output(paths: &Paths, name: &str, id: &str, args: &[&str]) -> Result<()> std::process::exit(code); } -fn host_tasks(reach: &Reach) -> Result> { +fn controller_actions(reach: &Reach) -> Result> { reach - .wait(reach.link.get::("/v1/tasks")) - .map(|value| list(value, "tasks")) + .wait(reach.link.get::("/v1/actions")) + .map(|value| list(value, "actions")) .map_err(|error| explain(error, &reach.host.name)) } -/// What a host can do, with the tasks its controller lists for a host of +/// What a host can do, with the actions its controller lists for a host of /// this machine. A berth server's host has the server's list of its -/// actions, which has berth's own beside its tasks. -fn host_actions(paths: &Paths, reach: &Reach) -> Result<(Vec, Vec)> { +/// actions, which has berth's own beside its controller's. +fn host_actions(paths: &Paths, reach: &Reach) -> Result<(Vec, Vec)> { match reach.host.served(paths) { Some(server) => { let listed = server.call("hosts.actions", json!({"name": reach.host.name}), None)?; @@ -531,15 +531,15 @@ fn host_actions(paths: &Paths, reach: &Reach) -> Result<(Vec, Vec { // A host of the type ssh has no controller to ask. let host_type = host_type::of(&reach.host.config); - let tasks = match host_type { + let listed = match host_type { host_type::HostType::Ssh => vec![], - _ => host_tasks(reach)?, + _ => controller_actions(reach)?, }; - let mut actions = api::Action::of_tasks(&tasks); + let mut actions = api::Action::of_host(&listed); let own = host_type::local_actions(&reach.host.name, host_type, observed(reach)); actions.retain(|action| !own.iter().any(|known| known.name == action.name)); actions.extend(own); - Ok((actions, tasks)) + Ok((actions, listed)) } } } @@ -562,8 +562,8 @@ fn observed(reach: &Reach) -> Option { .and_then(|version| host_type::seen(Ok(version))) } -/// `berth tasks HOST`: what the host can do, by group. -pub fn tasks(paths: &Paths, name: &str) -> Result<()> { +/// `berth actions HOST`: what the host can do, by group. +pub fn actions(paths: &Paths, name: &str) -> Result<()> { let reach = reach(paths, name)?; let (actions, _) = host_actions(paths, &reach)?; if let Some(said) = @@ -635,7 +635,11 @@ pub(crate) fn ready( ) -> Result<(api::Action, BTreeMap)> { let Some(found) = actions.iter().find(|known| known.name == name) else { let names: Vec<&str> = actions.iter().map(|known| known.name.as_str()).collect(); - return Err(format!("{subject} has no task {name}. Tasks: {}", names.join(", ")).into()); + return Err(format!( + "{subject} has no action {name}. Actions: {}", + names.join(", ") + ) + .into()); }; if !found.available { return Err(format!("{name} cannot run now: {}", found.why).into()); @@ -667,13 +671,13 @@ pub(crate) fn ready( Ok((found.clone(), values)) } -/// `berth run HOST TASK [NAME=VALUE…] [--yes]`: run one of the host's +/// `berth run HOST ACTION [NAME=VALUE…] [--yes]`: run one of the host's /// actions and leave with its exit code. -pub fn run(paths: &Paths, name: &str, task: &str, args: &[&str]) -> Result<()> { +pub fn run(paths: &Paths, name: &str, wanted: &str, args: &[&str]) -> Result<()> { let (values, yes) = parse_arguments(args)?; let reach = reach(paths, name)?; - let (actions, tasks) = host_actions(paths, &reach)?; - let (action, values) = ready(name, &actions, task, values, yes)?; + let (actions, listed) = host_actions(paths, &reach)?; + let (action, values) = ready(name, &actions, wanted, values, yes)?; let mut act = api::Act { arguments: values, ..api::Act::default() @@ -690,7 +694,7 @@ pub fn run(paths: &Paths, name: &str, task: &str, args: &[&str]) -> Result<()> { follow_acted(&server, Some(&reach), acted, &mut std::io::stdout())? } None if action.runs == api::Runs::Berth => run_own(paths, &reach.host, &action.name)?, - None => run_here(paths, &reach, &tasks, &action, act)?, + None => run_here(paths, &reach, &listed, &action, act)?, }; std::process::exit(code); } @@ -933,11 +937,11 @@ fn seed_host_key(paths: &Paths, place: &Place, access: &api::profile::Access) -> Ok(()) } -/// Run a task of a host of this machine as a session there and follow it. +/// Run an action of a host of this machine as a session there and follow it. fn run_here( paths: &Paths, reach: &Reach, - tasks: &[api::Task], + listed: &[api::HostAction], action: &api::Action, act: api::Act, ) -> Result { @@ -945,14 +949,14 @@ fn run_here( if let (Some(rows), Some(cols)) = (act.rows, act.cols) { (body["rows"], body["cols"]) = (json!(rows), json!(cols)); } - // Secrets are built here and travel on the task's standard input. - let task = tasks.iter().find(|task| task.name == action.name); - if task.and_then(|task| task.input.as_deref()) == Some("secrets") { + // Secrets are built here and travel on the action's standard input. + let kept = listed.iter().find(|kept| kept.name == action.name); + if kept.and_then(|kept| kept.input.as_deref()) == Some("secrets") { let payload = registry::Store::new(paths)?.host_payload(&reach.host.config)?; body["input_b64"] = json!(api::b64(format!("{payload}\n").as_bytes())); } reach.wait(async { - let path = format!("/v1/tasks/{}", encode(&action.name)); + let path = format!("/v1/actions/{}", encode(&action.name)); let session: api::Session = reach.link.post(&path, &body).await?; let ended = follow_session(&reach.link, &session).await?; Ok::>(finish(reach, &session.id, ended, true).await) @@ -1068,7 +1072,7 @@ pub(crate) fn act_on( ) -> Result { let (op, args) = match host { Some(name) => ("hosts.act", json!({"name": name, "action": action})), - None => ("actions.act", json!({"action": action})), + None => ("installation.act", json!({"action": action})), }; let acted = server.call(op, args, Some(serde_json::to_value(act)?))?; Ok(serde_json::from_value(acted)?) @@ -1814,7 +1818,7 @@ mod tests { } #[test] - fn task_arguments_are_names_with_values() { + fn action_arguments_are_names_with_values() { let (values, yes) = parse_arguments(&["folder=~/my project", "--yes", "empty="]).unwrap(); assert!(yes); assert_eq!(values["folder"], "~/my project"); diff --git a/crates/berth/src/main.rs b/crates/berth/src/main.rs index 2b8f268..782f666 100644 --- a/crates/berth/src/main.rs +++ b/crates/berth/src/main.rs @@ -52,7 +52,7 @@ Usage: berth apply --behind [--update] [--reboot [--force]] apply every host that is behind, one at a time, stopping at the first that fails; --all takes current ones too, - --update runs their update task, --reboot reboots those + --update runs their update action, --reboot reboots those that need it unless sessions run (--force: even then) berth connect URL use the berth server at URL: give it the setup key made there with berth setup-key, on standard input @@ -100,10 +100,11 @@ Usage: delete the machine; the profile stays berth key this berth's own SSH public key, which the operator of a host it sets up takes - berth tasks HOST what the host can do: its tasks and those of its plugins - berth run HOST TASK [NAME=VALUE…] [--yes] + berth actions HOST what the host can do: its controller's actions, those of + its plugins and berth's own + berth run HOST ACTION [NAME=VALUE…] [--yes] run one of them and leave with its exit code - (berth manage HOST TASK is the same) + (berth manage HOST ACTION is the same) berth exec HOST [--user agent|operator|root] [--keep] -- COMMAND… run a command on the host; its exit code is berth's berth attach HOST [ID] this terminal onto a terminal session of the host, or onto @@ -802,9 +803,9 @@ fn run() -> Result<()> { require_ready(&app)?; return app.execute(); } - ["tasks", host] => return commands::tasks(&paths, host), - ["run" | "manage", host, task, ref rest @ ..] => { - return commands::run(&paths, host, task, rest); + ["actions", host] => return commands::actions(&paths, host), + ["run" | "manage", host, action, ref rest @ ..] => { + return commands::run(&paths, host, action, rest); } ["exec", host, ref rest @ ..] => return commands::exec(&paths, host, rest), ["attach", host] => return commands::attach(&paths, host, None), @@ -890,7 +891,7 @@ mod tests { fn only_the_screen_opens_before_the_mirror_is_made() { assert!(opens_screen(&[]) && opens_screen(&["studio"])); assert!(!opens_screen(&["list"]) && !opens_screen(&["--version"])); - assert!(!opens_screen(&["run", "studio", "task"])); + assert!(!opens_screen(&["run", "studio", "status"])); } use super::*; @@ -989,7 +990,7 @@ mod tests { assert!( !app.entries() .iter() - .any(|entry| matches!(entry, Entry::HostTask(_))) + .any(|entry| matches!(entry, Entry::HostAction(_))) ); app.set_item(Item::Feature(0), false); assert_eq!( diff --git a/crates/berth/src/remote.rs b/crates/berth/src/remote.rs index f6db674..d790bd7 100644 --- a/crates/berth/src/remote.rs +++ b/crates/berth/src/remote.rs @@ -54,8 +54,8 @@ async fn refresh( return; } } - if let Ok(tasks) = link.get::("/v1/tasks").await { - let _ = events.send(Event::Tasks(list(tasks, "tasks"))); + if let Ok(listed) = link.get::("/v1/actions").await { + let _ = events.send(Event::Actions(list(listed, "actions"))); } } if let Ok(sessions) = link.get::("/v1/sessions").await { @@ -157,7 +157,7 @@ async fn worker( Request::Refresh => drop(tokio::spawn(refresh(link, events, true, compare.clone()))), Request::Poll => drop(tokio::spawn(refresh(link, events, false, None))), Request::Run { name, body } => drop(tokio::spawn(async move { - let _ = events.send(match link.run_task(&name, &body).await { + let _ = events.send(match link.run_action(&name, &body).await { Ok(session) => Event::Opened(Box::new(session)), Err(error) => Event::Error(error.to_string()), }); @@ -193,10 +193,10 @@ async fn worker( } refresh(link, events, false, None).await; })), - Request::Choices { task, argument } => drop(tokio::spawn(async move { + Request::Choices { action, argument } => drop(tokio::spawn(async move { let path = format!( - "/v1/tasks/{}/choices/{}", - api::client::encode(&task), + "/v1/actions/{}/choices/{}", + api::client::encode(&action), api::client::encode(&argument) ); let choices = match link.get::(&path).await { @@ -204,7 +204,7 @@ async fn worker( Err(_) => vec![], }; let _ = events.send(Event::Choices { - task, + action, argument, choices, }); @@ -273,10 +273,10 @@ mod tests { #[test] fn lists_come_bare_or_under_a_key() { - let bare: Vec = list(json!([{"name": "status"}]), "tasks"); - let keyed: Vec = list( - json!({"tasks": [{"name": "status"}, {"no": "name"}]}), - "tasks", + let bare: Vec = list(json!([{"name": "status"}]), "actions"); + let keyed: Vec = list( + json!({"actions": [{"name": "status"}, {"no": "name"}]}), + "actions", ); assert_eq!((bare.len(), keyed.len()), (1, 1)); assert_eq!(exited(r#"{"exited":{"exit_code":3}}"#), Some(Some(3))); @@ -306,7 +306,7 @@ mod tests { } /// The overview against a real controller, when one has been built - /// (`cargo build -p berthd`): connect, list, run tasks, type into one. + /// (`cargo build -p berthd`): connect, list, run actions, type into one. #[test] fn the_overview_talks_to_a_controller() { let built = std::env::current_exe() @@ -322,14 +322,14 @@ mod tests { } let dir = tempfile::tempdir().unwrap(); std::fs::create_dir_all(dir.path().join("etc")).unwrap(); - let tasks = json!([ + let actions = json!([ {"name": "status", "label": "Status", "group": "System", "user": "agent", "run": "echo up; echo warn >&2"}, {"name": "demo:status", "label": "Demo", "extends": ["status"], "user": "agent", "run": "echo demo; exit 4"}, {"name": "greet", "label": "Greet", "user": "agent", "run": "echo \"hello $BERTH_ARG_WHO\"", "arguments": [{"name": "who", "required": true, "choices": "printf 'ann\\nbob\\n'"}]}, {"name": "ask", "label": "Ask", "user": "agent", "terminal": true, "run": "printf 'code? '; read c; echo got $c"}, ]); - std::fs::write(dir.path().join("etc/tasks.json"), tasks.to_string()).unwrap(); + std::fs::write(dir.path().join("etc/actions.json"), actions.to_string()).unwrap(); let mut daemon = std::process::Command::new(&built) .arg("--single") .arg(dir.path()) @@ -374,14 +374,14 @@ mod tests { } panic!("never: {what}; state {:?}", host.state); } - until(&mut host, "ready with tasks", |host| { - matches!(host.state, State::Ready(_)) && host.tasks.len() == 4 + until(&mut host, "ready with actions", |host| { + matches!(host.state, State::Ready(_)) && host.host_actions.len() == 4 }); until(&mut host, "stats", |host| host.stats.is_some()); assert!(host.stats_line().unwrap().contains("load ")); - assert!(host.tasks[0].run.is_empty() && host.tasks[1].extends == ["status"]); + assert!(host.host_actions[0].run.is_empty() && host.host_actions[1].extends == ["status"]); - // A task and the step a plugin adds, as one transcript; the first + // An action and the step a plugin adds, as one transcript; the first // failing step is the outcome. host.run("status", json!({})); until(&mut host, "status ended", |host| { @@ -404,7 +404,7 @@ mod tests { // Arguments reach the command; the host offers choices for one. host.send(Request::Choices { - task: "greet".into(), + action: "greet".into(), argument: "who".into(), }); host.arguments = Some(Arguments { @@ -438,7 +438,7 @@ mod tests { host.sessions.iter().any(|session| session.title == "Greet") }); - // A terminal task takes typing; left with Ctrl+Q it runs on and can be + // A terminal action takes typing; left with Ctrl+Q it runs on and can be // opened again. host.run("ask", json!({"rows": 10, "cols": 40})); until(&mut host, "the question", |host| { @@ -473,7 +473,7 @@ mod tests { assert!(view.screen().contents().contains("got 42") && view.outcome() == Some(true)); assert!(!view.ours); - // A task the host does not have says so. + // An action the host does not have says so. host.close(true); host.run("nothing", json!({})); let mut said = None; diff --git a/crates/berth/src/serve/actions.rs b/crates/berth/src/serve/actions.rs index 557e8b8..94ae09b 100644 --- a/crates/berth/src/serve/actions.rs +++ b/crates/berth/src/serve/actions.rs @@ -1,5 +1,5 @@ //! The actions of a host and of the installation: what can be done to each, -//! and running one. A host's actions are the tasks its controller lists and +//! and running one. A host's actions are the actions its controller lists and //! berth's own from [`HOST`]; the installation's are [`INSTALLATION`]. An //! action that changes something runs as a job; one the host runs is a //! session there, which a job follows unless it needs a terminal. @@ -18,8 +18,8 @@ use axum::{ }; use berth_api::profile::{self, Auth}; use berth_api::{ - Act, Acted, Action, Argument, ErrorBody, Rollout, RolloutReport, Runs, Session, Task, b64, - client, code, ops::Role, + Act, Acted, Action, Argument, ErrorBody, HostAction, Rollout, RolloutReport, Runs, Session, + b64, client, code, ops::Role, }; use berth_core::{ apply, @@ -44,7 +44,7 @@ pub(super) struct Seen<'a> { /// The host's profile; null for the installation. pub profile: &'a Value, /// What the host's controller lists; `None` when it did not answer. - pub tasks: Option<&'a [Task]>, + pub host_actions: Option<&'a [HostAction]>, /// The names of the secrets the server keeps. pub secrets: &'a [String], /// The type the host's profile means it to be. @@ -148,14 +148,14 @@ pub(super) fn answer(acted: Acted) -> (StatusCode, Json) { (status, Json(acted)) } -/// The tasks a host's controller lists, asked for with a time limit. -async fn host_tasks(remote: &Remote) -> Result, String> { +/// The actions a host's controller lists, asked for with a time limit. +async fn controller_actions(remote: &Remote) -> Result, String> { let link = remote .link .as_ref() .ok_or_else(|| remote.problem.clone().unwrap_or_else(|| "no link".into()))?; - match tokio::time::timeout(Duration::from_secs(15), link.get::("/v1/tasks")).await { - Ok(Ok(tasks)) => Ok(berth_tui::host::list(tasks, "tasks")), + match tokio::time::timeout(Duration::from_secs(15), link.get::("/v1/actions")).await { + Ok(Ok(listed)) => Ok(berth_tui::host::list(listed, "actions")), Ok(Err(error)) => Err(error.to_string()), Err(_) => Err("no answer in time".into()), } @@ -171,20 +171,20 @@ async fn observed(remote: &Remote) -> Option { .and_then(|version| host_type::seen(Ok(version))) } -/// A host's actions: its tasks, then berth's own. A task that takes the +/// A host's actions: its controller's, then berth's own. One that takes the /// workstation's secrets on its input is berth's to run, with the server's. fn host_list(seen: &Seen) -> Vec { let own: Vec = HOST .iter() .map(|builtin| (builtin.describe)(seen)) .collect(); - let tasks = seen.tasks.unwrap_or(&[]); - let mut actions: Vec = Action::of_tasks(tasks) + let listed = seen.host_actions.unwrap_or(&[]); + let mut actions: Vec = Action::of_host(listed) .into_iter() .filter(|action| !own.iter().any(|known| known.name == action.name)) .filter(|action| { - let task = tasks.iter().find(|task| task.name == action.name); - task.is_none_or(|task| task.input.is_none()) + let kept = listed.iter().find(|kept| kept.name == action.name); + kept.is_none_or(|kept| kept.input.is_none()) }) .collect(); actions.extend(own); @@ -239,7 +239,7 @@ fn no_action(subject: &str, action: &str, actions: &[Action]) -> Fail { ) } -#[utoipa::path(get, path = "/v1/hosts/{name}/actions", summary = "What can be done to a host: the tasks its controller lists, and berth's own actions.", tag = "hosts", +#[utoipa::path(get, path = "/v1/hosts/{name}/actions", summary = "What can be done to a host: the actions its controller lists, and berth's own.", tag = "hosts", params(("name" = String, Path, description = "A saved host")), responses((status = 200, description = "The actions, each saying whether it can run now", body = Vec), (status = 404, description = "No such host", body = ErrorBody)))] @@ -253,10 +253,10 @@ pub async fn host_actions( // A host of the type ssh has no controller to ask. let asked = match host_type::of(&profile) { HostType::Ssh => None, - _ => Some(host_tasks(&remote).await), + _ => Some(controller_actions(&remote).await), }; - let (tasks, unanswered) = match &asked { - Some(Ok(tasks)) => (Some(tasks.as_slice()), None), + let (listed, unanswered) = match &asked { + Some(Ok(listed)) => (Some(listed.as_slice()), None), Some(Err(error)) => (None, Some(error.as_str())), None => (None, None), }; @@ -265,7 +265,7 @@ pub async fn host_actions( Ok(Json(host_list(&Seen { name: &name, profile: &profile, - tasks, + host_actions: listed, secrets: &secrets, host_type: host_type::of(&profile), observed, @@ -273,11 +273,11 @@ pub async fn host_actions( }))) } -#[utoipa::path(post, path = "/v1/hosts/{name}/actions/{action}", summary = "Run one of a host's actions. One of berth's that changes something is a job; a task of the host is a session there, which a job follows unless it needs a terminal.", tag = "hosts", +#[utoipa::path(post, path = "/v1/hosts/{name}/actions/{action}", summary = "Run one of a host's actions. One of berth's that changes something is a job; an action of the host's controller is a session there, which a job follows unless it needs a terminal.", tag = "hosts", params(("name" = String, Path, description = "A saved host"), ("action" = String, Path, description = "The action, as hosts.actions names it")), request_body(content = Option, description = "Its arguments, and a token that makes asking again safe"), - responses((status = 202, description = "Started as a job; a task of the host also says its session", body = Acted), + responses((status = 202, description = "Started as a job; an action of its controller also says its session", body = Acted), (status = 200, description = "Answered at once: the result, or the terminal session to attach to", body = Acted), (status = 400, description = "An argument is missing, or the body is not one", body = ErrorBody), (status = 403, description = "The caller's role is below the action's", body = ErrorBody), @@ -299,11 +299,11 @@ pub async fn host_act( let builtin = HOST.iter().find(|builtin| builtin.name == action); let ssh_only = host_type::of(&profile) == HostType::Ssh; let mut unanswered = None; - let tasks = match builtin { + let listed = match builtin { Some(_) if ssh_only || !THROUGH_CONTROLLER.contains(&action.as_str()) => None, // One that runs through the controller is described as the host answers. - Some(_) => match host_tasks(&remote).await { - Ok(tasks) => Some(tasks), + Some(_) => match controller_actions(&remote).await { + Ok(listed) => Some(listed), Err(error) => { unanswered = Some(error); None @@ -311,7 +311,7 @@ pub async fn host_act( }, None if ssh_only => Some(vec![]), None => Some( - host_tasks(&remote) + controller_actions(&remote) .await .map_err(|error| Fail::new(code::UNREACHABLE, error))?, ), @@ -321,7 +321,7 @@ pub async fn host_act( let actions = host_list(&Seen { name: &name, profile: &profile, - tasks: tasks.as_deref(), + host_actions: listed.as_deref(), secrets: &secrets, host_type: host_type::of(&profile), observed, @@ -334,12 +334,12 @@ pub async fn host_act( admit(&state, &caller(access), found, &act)?; let acted = match builtin { Some(builtin) => (builtin.run)(state, name, act).await?, - None => run_task(&state, &remote, found, act, None).await?, + None => run_action(&state, &remote, found, act, None).await?, }; Ok(answer(acted)) } -#[utoipa::path(get, path = "/v1/actions", summary = "What can be done to the installation as a whole, such as a roll-out over its hosts.", tag = "hosts", +#[utoipa::path(get, path = "/v1/installation/actions", summary = "What can be done to the installation as a whole, such as a roll-out over its hosts.", tag = "hosts", responses((status = 200, description = "The actions", body = Vec)))] pub async fn list() -> Json> { Json(installation_list()) @@ -349,7 +349,7 @@ fn installation_list() -> Vec { let seen = Seen { name: "", profile: &Value::Null, - tasks: None, + host_actions: None, secrets: &[], host_type: HostType::Workstation, observed: None, @@ -361,8 +361,8 @@ fn installation_list() -> Vec { .collect() } -#[utoipa::path(post, path = "/v1/actions/{action}", summary = "Run one of the installation's actions, as a job.", tag = "hosts", - params(("action" = String, Path, description = "The action, as actions.list names it")), +#[utoipa::path(post, path = "/v1/installation/actions/{action}", summary = "Run one of the installation's actions, as a job.", tag = "hosts", + params(("action" = String, Path, description = "The action, as installation.actions names it")), request_body(content = Option, description = "Its arguments, and a token that makes asking again safe"), responses((status = 202, description = "Started as a job", body = Acted), (status = 400, description = "An argument is wrong, or the body is not one", body = ErrorBody), @@ -398,7 +398,7 @@ pub(super) fn refused(error: Box) -> Fail { } } -// ── Tasks of a host ───────────────────────────────────────────────────────── +// ── Actions of a host ───────────────────────────────────────────────────────── /// The host's controller through the server's link to it, for a job that /// waits on it from a thread of its own. @@ -416,9 +416,9 @@ impl Controller for Through { } } -/// Run a task of the host as a session there, with `input` on its standard +/// Run an action of the host as a session there, with `input` on its standard /// input. A job follows one that needs no terminal, copying its output. -async fn run_task( +async fn run_action( state: &Arc, remote: &Arc, action: &Action, @@ -437,7 +437,7 @@ async fn run_task( if let Some(input) = input { body["input_b64"] = json!(b64(format!("{input}\n").as_bytes())); } - let path = format!("/v1/tasks/{}", client::encode(&action.name)); + let path = format!("/v1/actions/{}", client::encode(&action.name)); // One to attach to is the session alone, with no job to find again. if action.terminal { let session: Session = link.post(&path, &body).await?; @@ -448,7 +448,7 @@ async fn run_task( } let mut request = Request::new(Subject::Host(remote.name.clone()), &action.name); request.token = act.token; - // A task is the host's own session, and runs beside the others there. + // An action is the host's own session, and runs beside the others there. request.changes = false; // The job is written first, so that of the callers with one token only // the one that wrote it starts a session; the others find its job. @@ -655,30 +655,30 @@ fn seed(state: Arc, name: String, _: Act) -> Run { } fn secrets_action(seen: &Seen) -> Action { - let task = seen - .tasks - .and_then(|tasks| tasks.iter().find(|task| task.name == "secrets")); + let kept = seen + .host_actions + .and_then(|listed| listed.iter().find(|kept| kept.name == "secrets")); let mut action = set_up( "secrets", "Send secrets", "Send the host the secrets and registry logins its profile names, from the server's own.", ); action.runs = Runs::Host; - if let Some(task) = task { - action.label = task.label.clone(); - action.help = task.help.clone(); - action.group = task.group.clone(); + if let Some(kept) = kept { + action.label = kept.label.clone(); + action.help = kept.help.clone(); + action.group = kept.group.clone(); } if let Err(refusal) = host_type::check(seen.name, seen.host_type, Capability::Secrets) { return unavailable(action, Some(refusal.why)); } - let why = match (seen.tasks, task, seen.unanswered) { + let why = match (seen.host_actions, kept, seen.unanswered) { (_, _, Some(error)) => Some(format!( "The controller on {} does not answer, and the secrets go through it: {error}", seen.name )), (Some(_), None, _) => Some(format!( - "The controller on {} has no secrets task yet: apply its configuration", + "The controller on {} has no secrets action yet: apply its configuration", seen.name )), _ => None, @@ -699,7 +699,7 @@ fn secrets(state: Arc, name: String, act: Act) -> Run { name: "secrets".into(), ..Action::default() }; - run_task(&state, &remote, &action, act, Some(payload.to_string())).await + run_action(&state, &remote, &action, act, Some(payload.to_string())).await }) } @@ -731,7 +731,7 @@ fn rollout_action(_: &Seen) -> Action { ..Argument::default() }, flag("all", "Also current hosts", "Apply the hosts that are current too."), - flag("update", "Update", "Run each host's update task after applying."), + flag("update", "Update", "Run each host's update action after applying."), flag("reboot", "Reboot", "Reboot a host that says it needs it, and wait for it to come back."), flag("force", "Force", "Reboot although sessions run, which ends them."), ], diff --git a/crates/berth/src/serve/api.rs b/crates/berth/src/serve/api.rs index 4dbd5e1..88a1865 100644 --- a/crates/berth/src/serve/api.rs +++ b/crates/berth/src/serve/api.rs @@ -269,6 +269,10 @@ fn guarded_routes() -> OpenApiRouter> { .routes(routes!(kv_get, kv_put, kv_delete)) } +/// Where a host's controller's operations are passed through: berthd's +/// `/v1/PATH` is `/v1/hosts/NAME/controller/PATH` here. +pub const HOST_PREFIX: &str = "/v1/hosts/{name}/controller/{*rest}"; + pub fn router(state: Arc, guarded: bool) -> Router { let (mut router, _) = guarded_routes().split_for_parts(); // Every stream of the table gets its route here, so none can exist undescribed. @@ -280,7 +284,8 @@ pub fn router(state: Arc, guarded: bool) -> Router { other => panic!("no handler for the stream {other}"), }; } - router = router.route("/v1/hosts/{name}/{*rest}", any(proxy)); + // Under a prefix of its own, so that no route of ours can hide one of the host's. + router = router.route(HOST_PREFIX, any(proxy)); router = router.route(ops::PORTAL, get(portal)); if guarded { router = router.layer(middleware::from_fn_with_state(state.clone(), guard)); @@ -367,7 +372,8 @@ pub fn caller(access: Option>) -> Access { } /// The portal: every operation over one WebSocket. With `host` an operation -/// is that host's, and goes the way a request under `/v1/hosts/NAME` does. +/// is that host's, and goes the way a request under +/// `/v1/hosts/NAME/controller` does. async fn portal( State(state): App, access: Option>, @@ -384,7 +390,10 @@ async fn portal( let asked = state.clone(); let resolve: berthd::portal::Resolve = Arc::new(move |name, host| { let (table, prefix) = match host { - Some(host) => (ops::HOST, format!("/hosts/{}", client::encode(host))), + Some(host) => ( + ops::HOST, + format!("/hosts/{}/controller", client::encode(host)), + ), None => (ops::SERVE, String::new()), }; let op = ops::find(table, name) @@ -1075,10 +1084,10 @@ async fn proxy( ) -> Answer { let remote = remote(&state, &name)?; // The secrets a host gets are the server's own: a caller cannot hand it others. - if method == Method::POST && rest.trim_end_matches('/') == "tasks/secrets" { + if method == Method::POST && rest.trim_end_matches('/') == "actions/secrets" { return Err(Fail::new( code::FORBIDDEN, - "The secrets task takes the server's secrets: run the host's secrets action (POST /v1/hosts/NAME/actions/secrets)", + "The controller's secrets action takes the server's secrets: run the server's secrets action of the host (POST /v1/hosts/NAME/actions/secrets)", )); } let Some(link) = &remote.link else { diff --git a/crates/berth/src/serve/auth.rs b/crates/berth/src/serve/auth.rs index 632e14a..e0ba061 100644 --- a/crates/berth/src/serve/auth.rs +++ b/crates/berth/src/serve/auth.rs @@ -210,12 +210,15 @@ pub fn operation(method: &str, path: &str, stream: bool) -> Result Ok(Some(op)), None => Err(()), @@ -454,13 +457,32 @@ mod tests { "hosts.act" ); assert_eq!(name("GET", "/v1/hosts/a/actions", false), "hosts.actions"); - assert_eq!(name("POST", "/v1/actions/rollout", false), "actions.act"); - assert_eq!(name("GET", "/v1/hosts/a/sessions", false), "sessions.list"); assert_eq!( - name("GET", "/v1/hosts/a/sessions/x", true), + name("POST", "/v1/installation/actions/rollout", false), + "installation.act" + ); + assert_eq!( + name("GET", "/v1/hosts/a/controller/sessions", false), + "sessions.list" + ); + assert_eq!( + name("GET", "/v1/hosts/a/controller/sessions/x", true), "sessions.attach" ); - assert_eq!(name("GET", "/v1/hosts/a/ports/8080", true), "ports.connect"); + assert_eq!( + name("GET", "/v1/hosts/a/controller/ports/8080", true), + "ports.connect" + ); + // The host's actions and the server's view of them do not meet. + assert_eq!( + name("GET", "/v1/hosts/a/controller/actions", false), + "actions.list" + ); + assert_eq!( + name("POST", "/v1/hosts/a/controller/actions/x", false), + "actions.run" + ); + assert!(operation("GET", "/v1/hosts/a/sessions", false).is_err()); assert_eq!( name("PUT", "/v1/secrets/registry%2Fmain", false), "secrets.set" @@ -482,7 +504,7 @@ mod tests { }; let admin = Access::local(); let apply = ops::find(ops::SERVE, "hosts.save").unwrap(); - let run = ops::find(ops::HOST, "tasks.run").unwrap(); + let run = ops::find(ops::HOST, "actions.run").unwrap(); assert_eq!(auth.role(&admin), Role::Operate); assert!(auth.allows(&admin, run).is_ok()); assert!(auth.allows(&admin, apply).unwrap_err().1.contains("set-up")); diff --git a/crates/berth/src/serve/docs.rs b/crates/berth/src/serve/docs.rs index fd5f87e..2e592ed 100644 --- a/crates/berth/src/serve/docs.rs +++ b/crates/berth/src/serve/docs.rs @@ -18,10 +18,10 @@ pub fn openapi() -> Value { api.info.version = berth_api::VERSION.into(); api.info.description = Some( "One API over all hosts, with the inbox and a key-value store. Everything under \ - /v1/hosts/{name}/ that is not named here is that host's own API, passed through unchanged; \ - only the `secrets` task is refused, which the host's `secrets` action stands in for. \ + /v1/hosts/{name}/controller/ is that host's own API, passed through unchanged; \ + only the controller's own `secrets` action is refused, which the server's `secrets` action of the host stands in for. \ What can be done to a host or to the installation is listed at /v1/hosts/{name}/actions and \ - /v1/actions, and run by POST to an action's name there. Over TCP every request \ + /v1/installation/actions, and run by POST to an action's name there. Over TCP every request \ carries the server's token or an OAuth 2.0 access token as a bearer, and needs the role its operation names. \ The routes of the setup key take that key as the bearer instead." .into(), @@ -68,7 +68,8 @@ fn upgrade(stream: &Stream, id: &str) -> Value { }) } -/// Put a host's paths under `/v1/hosts/{name}` and its schemas beside ours. +/// Put a host's paths under `/v1/hosts/{name}/controller` and its schemas +/// beside ours. fn merge_host(document: &mut Value, host: &Value) { let name = json!({"name": "name", "in": "path", "required": true, "description": NAME, "schema": {"type": "string"}}); for (path, item) in host["paths"].as_object().into_iter().flatten() { @@ -99,11 +100,12 @@ fn merge_host(document: &mut Value, host: &Value) { .collect(); operation["tags"] = json!(tags); } - let target = format!("/v1/hosts/{{name}}{rest}"); - // What berth serve answers itself is not the host's. - if document["paths"].get(&target).is_none() { - document["paths"][target] = item; - } + let target = format!("/v1/hosts/{{name}}/controller{rest}"); + assert!( + document["paths"].get(&target).is_none(), + "{target} is a route of berth serve and of the host" + ); + document["paths"][target] = item; } for (name, schema) in host["components"]["schemas"] .as_object() @@ -123,7 +125,7 @@ pub fn operations() -> Value { let own = serde_json::to_value(own).expect("the document is JSON"); let mut document = berthd::http::operations_of( "berth serve", - "The operations of berth serve. Every operation of a host is one here too: on the portal with `\"host\": \"NAME\"` in the frame, over HTTP under /v1/hosts/NAME. Only the `secrets` task is refused; the host's `secrets` action sends the server's own. An action's own role is asked when it runs. Each operation names the least role a caller over TCP needs: view, operate or admin.", + "The operations of berth serve. Every operation of a host is one here too: on the portal with `\"host\": \"NAME\"` in the frame, over HTTP under /v1/hosts/NAME/controller. Only the controller's own `secrets` action is refused; the server's `secrets` action of the host sends the server's secrets. An action's own role is asked when it runs. Each operation names the least role a caller over TCP needs: view, operate or admin.", berth_api::ops::SERVE, &own, &|op| streams::SERVE.iter().find(|stream| stream.path == op.path), @@ -139,7 +141,7 @@ pub fn asyncapi() -> Value { .map(|stream| Stream { id: keep(format!("host.{}", stream.id)), path: keep(format!( - "/v1/hosts/{{name}}{}", + "/v1/hosts/{{name}}/controller{}", stream.path.trim_start_matches("/v1") )), summary: stream.summary, @@ -153,7 +155,7 @@ pub fn asyncapi() -> Value { let all: Vec<&Stream> = streams::SERVE.iter().chain(&hosted).collect(); streams::asyncapi( "berth serve", - "The WebSockets of berth serve: its own, and each host's under /v1/hosts/{name}. \ + "The WebSockets of berth serve: its own, and each host's under /v1/hosts/{name}/controller. \ Text frames are JSON, one message each; binary frames carry only session and job bytes.", &all, ) @@ -169,13 +171,13 @@ mod tests { let paths = [ "/v1/hosts", "/v1/hosts/{name}/actions/{action}", - "/v1/actions", + "/v1/installation/actions", "/v1/jobs/{id}/output", "/v1/inbox/{host}/{id}/done", "/v1/kv/{namespace}/{key}", // The host's own, under its name. - "/v1/hosts/{name}/sessions/{id}/output", - "/v1/hosts/{name}/tasks", + "/v1/hosts/{name}/controller/sessions/{id}/output", + "/v1/hosts/{name}/controller/actions", ]; for path in paths { assert!(document["paths"].get(path).is_some(), "{path}"); @@ -222,7 +224,7 @@ mod tests { let streams = asyncapi(); assert_eq!( streams["channels"]["host.session"]["address"], - "/v1/hosts/{name}/sessions/{id}" + "/v1/hosts/{name}/controller/sessions/{id}" ); assert_eq!(streams["channels"]["events"]["address"], "/v1/events"); } @@ -238,16 +240,21 @@ mod tests { "components": {"schemas": {"Done": {"ours": false}, "Session": {}}}, }); merge_host(&mut document, &host); - let get = &document["paths"]["/v1/hosts/{name}/sessions/{id}"]["get"]; + let get = &document["paths"]["/v1/hosts/{name}/controller/sessions/{id}"]["get"]; assert_eq!(get["operationId"], "host_session"); assert_eq!(get["parameters"][0]["name"], "name"); assert_eq!(get["parameters"][1]["name"], "id"); assert_eq!(get["tags"][0], "host: sessions"); + // The host's actions and the server's own of the host are apart. assert!( document["paths"]["/v1/hosts/{name}/actions"]["post"] .get("operationId") .is_none() ); + assert_eq!( + document["paths"]["/v1/hosts/{name}/controller/actions"]["post"]["operationId"], + "host_theirs" + ); assert_eq!(document["components"]["schemas"]["Done"]["ours"], true); assert!(document["components"]["schemas"].get("Session").is_some()); } diff --git a/crates/berth/src/serve/tests.rs b/crates/berth/src/serve/tests.rs index ef1a2f4..a3a5142 100644 --- a/crates/berth/src/serve/tests.rs +++ b/crates/berth/src/serve/tests.rs @@ -311,7 +311,7 @@ async fn hosts_jobs_and_the_inbox_over_the_api() { ); assert_eq!( client - .get::("/v1/hosts/nope/version") + .get::("/v1/hosts/nope/controller/version") .await .unwrap_err() .status(), @@ -348,13 +348,13 @@ async fn hosts_jobs_and_the_inbox_over_the_api() { "{hosts}" ); let through = client - .get::("/v1/hosts/broken/tasks") + .get::("/v1/hosts/broken/controller/actions") .await .unwrap_err(); assert_eq!((through.status(), through.code()), (502, "unreachable")); // Secrets are refused before the host is even tried. let secrets = client - .post::("/v1/hosts/broken/tasks/secrets", &json!({})) + .post::("/v1/hosts/broken/controller/actions/secrets", &json!({})) .await .unwrap_err(); assert_eq!((secrets.status(), secrets.code()), (403, "forbidden")); @@ -619,11 +619,11 @@ impl Berthd { /// A berthd in single-user mode, or nothing when it is not built or does /// not answer yet. async fn start() -> Option { - Berthd::with_tasks(json!([])).await + Berthd::with_actions(json!([])).await } - /// The same, with these tasks in its `etc/tasks.json`. - async fn with_tasks(tasks: Value) -> Option { + /// The same, with these actions in its `etc/actions.json`. + async fn with_actions(actions: Value) -> Option { let program = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/debug/berthd"); if !program.is_file() { eprintln!("skipped: {} is not built", program.display()); @@ -631,7 +631,7 @@ impl Berthd { } let dir = tempfile::tempdir().unwrap(); std::fs::create_dir_all(dir.path().join("etc")).unwrap(); - std::fs::write(dir.path().join("etc/tasks.json"), tasks.to_string()).unwrap(); + std::fs::write(dir.path().join("etc/actions.json"), actions.to_string()).unwrap(); let child = std::process::Command::new(&program) .arg("--single") .arg(dir.path()) @@ -707,12 +707,15 @@ async fn a_hosts_api_is_passed_through() { let hosts: Value = client.get("/v1/hosts").await.unwrap(); assert_eq!(hosts[0]["reachable"], true, "{hosts}"); assert_eq!(hosts[0]["version"], berth_api::VERSION); - let version: Value = client.get("/v1/hosts/box/version").await.unwrap(); + let version: Value = client + .get("/v1/hosts/box/controller/version") + .await + .unwrap(); assert_eq!(version["api"], berth_api::API); // A request with a body and a query, and the host's own error passed back. let start = json!({"kind": "process", "command": "echo through; exit 3"}); let ran: Value = client - .post("/v1/hosts/box/sessions?wait=20", &start) + .post("/v1/hosts/box/controller/sessions?wait=20", &start) .await .unwrap(); assert_eq!(ran["exit_code"], 3, "{ran}"); @@ -721,20 +724,21 @@ async fn a_hosts_api_is_passed_through() { b"through\n" ); let missing = client - .get::("/v1/hosts/box/sessions/snope") + .get::("/v1/hosts/box/controller/sessions/snope") .await .unwrap_err(); assert_eq!((missing.status(), missing.code()), (404, "not_found")); let secrets = client - .post::("/v1/hosts/box/tasks/secrets", &json!({})) + .post::("/v1/hosts/box/controller/actions/secrets", &json!({})) .await .unwrap_err(); assert_eq!(secrets.status(), 403); // A stream, both ways: what is published through it comes back on it. - let mut channel = client::websocket_unix(&served.socket, "/v1/hosts/box/channel?topic=t/") - .await - .unwrap(); + let mut channel = + client::websocket_unix(&served.socket, "/v1/hosts/box/controller/channel?topic=t/") + .await + .unwrap(); let publish = r#"{"topic":"t/x","body":{"hello":1},"keep":"none"}"#; channel.send(Frame::Text(publish.into())).await.unwrap(); let message = text(&mut channel).await; @@ -744,9 +748,12 @@ async fn a_hosts_api_is_passed_through() { ); // A terminal session's bytes come through as binary frames. let start = json!({"kind": "terminal", "command": "printf ready; read line; echo got-$line"}); - let session: Value = client.post("/v1/hosts/box/sessions", &start).await.unwrap(); + let session: Value = client + .post("/v1/hosts/box/controller/sessions", &start) + .await + .unwrap(); let path = format!( - "/v1/hosts/box/sessions/{}?since=0", + "/v1/hosts/box/controller/sessions/{}?since=0", session["id"].as_str().unwrap() ); let mut terminal = client::websocket_unix(&served.socket, &path).await.unwrap(); @@ -778,8 +785,8 @@ async fn job_done(client: &mut Client, id: &str) -> Value { } #[tokio::test(flavor = "multi_thread")] -async fn a_hosts_actions_are_its_tasks_and_berths_own() { - let tasks = json!([ +async fn a_hosts_actions_are_its_controllers_and_berths_own() { + let actions = json!([ {"name": "status", "label": "Status", "group": "System", "user": "agent", "run": "echo up"}, {"name": "demo:status", "label": "Demo", "extends": ["status"], "user": "agent", "run": "echo demo; exit 4"}, {"name": "greet", "label": "Greet", "user": "agent", "run": "echo \"hello $BERTH_ARG_WHO\"", @@ -788,7 +795,7 @@ async fn a_hosts_actions_are_its_tasks_and_berths_own() { {"name": "secrets", "label": "Send the secrets", "user": "agent", "input": "secrets", "run": "cat >/dev/null"}, {"name": "elevated", "label": "As root", "user": "root", "run": "true"}, ]); - let Some(host) = Berthd::with_tasks(tasks).await else { + let Some(host) = Berthd::with_actions(actions).await else { return; }; let served = served().await; @@ -799,8 +806,8 @@ async fn a_hosts_actions_are_its_tasks_and_berths_own() { let actions: Vec = client.get("/v1/hosts/box/actions").await.unwrap(); let names: Vec<&str> = actions.iter().map(|action| action.name.as_str()).collect(); - // The host's tasks, a step under the task it extends, then berth's own; the - // secrets task is berth's, which sends the server's secrets. + // The host's actions, a step under the action it extends, then berth's own; the + // secrets action is berth's, which sends the server's secrets. assert_eq!( names, [ @@ -830,7 +837,7 @@ async fn a_hosts_actions_are_its_tasks_and_berths_own() { ); assert!(secrets.available && actions[4].role == Role::Admin); - // A task that needs no terminal is a session there and a job here, which + // An action that needs no terminal is a session there and a job here, which // copies its output and ends with its exit code. let run = |body: Value| { let socket = served.socket.clone(); @@ -861,11 +868,21 @@ async fn a_hosts_actions_are_its_tasks_and_berths_own() { ); // Asked again with its token, it is the same job, and nothing runs again. let sessions = |value: Value| berth_tui::host::list::(value, "sessions").len(); - let before = sessions(client.get("/v1/hosts/box/sessions").await.unwrap()); + let before = sessions( + client + .get("/v1/hosts/box/controller/sessions") + .await + .unwrap(), + ); let again = run(json!({"token": "t-1"})).await.unwrap(); assert_eq!(again["job"]["id"], json!(id)); assert_eq!( - sessions(client.get("/v1/hosts/box/sessions").await.unwrap()), + sessions( + client + .get("/v1/hosts/box/controller/sessions") + .await + .unwrap() + ), before ); @@ -880,11 +897,16 @@ async fn a_hosts_actions_are_its_tasks_and_berths_own() { assert_eq!(ids.len(), 1, "{ids:?}"); job_done(&mut client, ids.first().unwrap()).await; assert_eq!( - sessions(client.get("/v1/hosts/box/sessions").await.unwrap()), + sessions( + client + .get("/v1/hosts/box/controller/sessions") + .await + .unwrap() + ), before + 1 ); - // A task the host will not start ends its job as failed, with the reason, + // An action the host will not start ends its job as failed, with the reason, // and asked again with the token that is the answer. let path = "/v1/hosts/box/actions/elevated"; let refused = client @@ -1006,7 +1028,7 @@ async fn a_port_of_a_host_is_reached_through_the_server() { let data: Vec = (0..3_000_000u32).map(|n| (n % 251) as u8).collect(); // As the host's own stream, passed through. - let path = format!("/v1/hosts/studio/ports/{port}"); + let path = format!("/v1/hosts/studio/controller/ports/{port}"); let open = client::websocket_unix(&served.socket, &path).await.unwrap(); assert_eq!(through(Tunnel::new(open), b"hello").await, b"hello"); let open = client::websocket_unix(&served.socket, &path).await.unwrap(); @@ -1026,7 +1048,7 @@ async fn a_port_of_a_host_is_reached_through_the_server() { let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); listener.local_addr().unwrap().port() }; - let path = format!("/v1/hosts/studio/ports/{closed}"); + let path = format!("/v1/hosts/studio/controller/ports/{closed}"); let refused = client::websocket_unix(&served.socket, &path) .await .err() @@ -1104,11 +1126,24 @@ async fn the_portal_reaches_serve_and_its_hosts() { other => panic!("the stream ended after {seen:?}: {other:?}"), } } + // The controller's actions are its own, apart from the server's of the host. + let listed = portal + .call("actions.list", Some("box"), Value::Null, None) + .await + .unwrap(); + assert!( + listed + .as_array() + .unwrap() + .iter() + .all(|action| action.get("available").is_none()), + "{listed}" + ); let secrets = portal .call( - "tasks.run", + "actions.run", Some("box"), - json!({"name": "secrets"}), + json!({"action": "secrets"}), Some(json!({})), ) .await; @@ -1550,7 +1585,7 @@ async fn plugins_are_managed_through_the_api() { &json!("1.0.0") ) ); - assert_eq!(hello["features"][0]["tasks"][0]["name"], "moo"); + assert_eq!(hello["features"][0]["actions"][0]["name"], "moo"); assert!(listed["dir"].as_str().unwrap().ends_with("config/plugins")); let (_, found) = send(client, "GET", "/v1/setup", Value::Null).await; assert!(keys(&found).contains(&"hello/cow".to_owned())); @@ -1577,10 +1612,10 @@ async fn plugins_are_managed_through_the_api() { ); } let asked = json!({"arguments": {"hosts": "nothing"}}); - let (status, said) = send(client, "POST", "/v1/actions/rollout", asked).await; + let (status, said) = send(client, "POST", "/v1/installation/actions/rollout", asked).await; assert_eq!(status, 404, "{said}"); let asked = json!({"arguments": {"force": "yes"}}); - let (status, said) = send(client, "POST", "/v1/actions/rollout", asked).await; + let (status, said) = send(client, "POST", "/v1/installation/actions/rollout", asked).await; assert_eq!(status, 400, "{said}"); let (status, said) = send(client, "DELETE", "/v1/plugins/hello", Value::Null).await; assert_eq!(status, 200, "{said}"); @@ -1757,9 +1792,15 @@ async fn an_access_token_gets_in_with_the_role_it_names() { .contains("operate") ); assert_eq!( - as_bearer(address, &viewer, "POST", "/v1/hosts/a/tasks/x", json!({})) - .await - .0, + as_bearer( + address, + &viewer, + "POST", + "/v1/hosts/a/controller/actions/x", + json!({}) + ) + .await + .0, 403 ); assert_eq!( @@ -1767,7 +1808,7 @@ async fn an_access_token_gets_in_with_the_role_it_names() { address, &viewer, "GET", - "/v1/hosts/a/files?path=x", + "/v1/hosts/a/controller/files?path=x", Value::Null ) .await @@ -1814,7 +1855,7 @@ async fn an_access_token_gets_in_with_the_role_it_names() { for path in [ "/v1/hosts/a/actions/apply", "/v1/hosts/a/actions/seed", - "/v1/actions/rollout", + "/v1/installation/actions/rollout", ] { let (status, said) = as_bearer(address, &operator, "POST", path, Value::Null).await; assert_eq!(status, 403, "{path}: {said}"); @@ -1823,7 +1864,14 @@ async fn an_access_token_gets_in_with_the_role_it_names() { "{said}" ); } - let (status, said) = as_bearer(address, &viewer, "GET", "/v1/actions", Value::Null).await; + let (status, said) = as_bearer( + address, + &viewer, + "GET", + "/v1/installation/actions", + Value::Null, + ) + .await; assert_eq!((status, &said[0]["name"]), (200, &json!("rollout"))); assert_eq!(said[0]["role"], "admin"); // A provisioner is looked at by anyone, and each of its actions has its own role. @@ -1925,17 +1973,21 @@ async fn an_access_token_gets_in_with_the_role_it_names() { assert_eq!(saved.unwrap_err().status(), 403); let run = portal .call( - "tasks.run", + "actions.run", Some("a"), - json!({"name": "x"}), + json!({"action": "x"}), Some(json!({})), ) .await; assert_eq!(run.unwrap_err().status(), 403); assert!( - client::websocket(connect().await, "/v1/hosts/a/sessions/x", &viewer) - .await - .is_err() + client::websocket( + connect().await, + "/v1/hosts/a/controller/sessions/x", + &viewer + ) + .await + .is_err() ); } @@ -1961,7 +2013,7 @@ async fn set_up_can_be_closed_to_the_network() { .unwrap() .contains("set-up") ); - // Installing a plugin is set-up too: its tasks run when a host is applied. + // Installing a plugin is set-up too: its Ansible tasks run when a host is applied. let spec = json!({"spec": "berth-plugin-foo"}); assert_eq!( as_bearer(address, token, "POST", "/v1/plugins", spec) @@ -1972,7 +2024,7 @@ async fn set_up_can_be_closed_to_the_network() { for (method, path) in [ ("POST", "/v1/resources"), ("DELETE", "/v1/resources/r-a"), - ("POST", "/v1/actions/rollout"), + ("POST", "/v1/installation/actions/rollout"), ] { let (status, said) = as_bearer(address, token, method, path, json!({})).await; assert_eq!(status, 403, "{method} {path}: {said}"); @@ -3585,23 +3637,35 @@ async fn first_contact_and_keys_are_actions_of_the_server() { assert_eq!(acted["result"], json!({"host_keys": [], "accepted": false})); // The installation rotates a key as keys.rotate does. - let (status, listed) = send(client, "GET", "/v1/actions", Value::Null).await; + let (status, listed) = send(client, "GET", "/v1/installation/actions", Value::Null).await; assert_eq!(status, 200); assert_eq!( action(&listed, "rotate-key")["arguments"][0]["default"], "berth" ); let nothing = json!({"arguments": {"name": "nothing"}}); - let (status, _) = send(client, "POST", "/v1/actions/rotate-key", nothing).await; + let (status, _) = send( + client, + "POST", + "/v1/installation/actions/rotate-key", + nothing, + ) + .await; assert_eq!(status, 404); let asked = json!({"arguments": {"name": "berth"}, "token": "rotate-1"}); - let (status, acted) = send(client, "POST", "/v1/actions/rotate-key", asked.clone()).await; + let (status, acted) = send( + client, + "POST", + "/v1/installation/actions/rotate-key", + asked.clone(), + ) + .await; assert_eq!(status, 202, "{acted}"); assert_eq!(acted["job"]["action"], "rotate-key:berth"); let id = acted["job"]["id"].as_str().unwrap().to_owned(); let (output, _) = job_ended(&served.socket, &id).await; assert!(output.contains("Replacing the key berth"), "{output}"); - let (_, again) = send(client, "POST", "/v1/actions/rotate-key", asked).await; + let (_, again) = send(client, "POST", "/v1/installation/actions/rotate-key", asked).await; assert_eq!(again["job"]["id"], json!(id)); } @@ -3678,7 +3742,13 @@ async fn a_host_added_by_its_address_has_a_type_and_actions_to_match() { assert_eq!(status, 501); // A roll-out leaves it, and says so. - let (status, acted) = send(client, "POST", "/v1/actions/rollout", Value::Null).await; + let (status, acted) = send( + client, + "POST", + "/v1/installation/actions/rollout", + Value::Null, + ) + .await; assert_eq!(status, 202, "{acted}"); let id = acted["job"]["id"].as_str().unwrap().to_owned(); let (output, code) = job_ended(&served.socket, &id).await; @@ -3812,7 +3882,13 @@ async fn a_host_whose_controller_does_not_answer_says_why_and_keeps_berths_own_a let socket = served.socket.clone(); async move { let mut client = Client::unix(&socket).await.unwrap(); - send(&mut client, "GET", "/v1/hosts/dock/version", Value::Null).await + send( + &mut client, + "GET", + "/v1/hosts/dock/controller/version", + Value::Null, + ) + .await } }); for (status, answer) in futures_util::future::join_all(asks).await { diff --git a/crates/berth/src/ui.rs b/crates/berth/src/ui.rs index a87f112..87e2fc2 100644 --- a/crates/berth/src/ui.rs +++ b/crates/berth/src/ui.rs @@ -59,7 +59,7 @@ fn buttons(app: &App) -> Vec<(&'static str, KeyCode)> { ("[All on Space]", KeyCode::Char(' ')) }); } - if app.selected_entry() == Some(Entry::Task("terminal")) { + if app.selected_entry() == Some(Entry::Offer("terminal")) { buttons.push(if app.as_agent { ("[As the SSH user Space]", KeyCode::Char(' ')) } else { @@ -723,14 +723,14 @@ fn view_event(app: &mut App, event: &Event) { } } -/// The yes-or-no question before a task or before applying. +/// The yes-or-no question before an action or before applying. fn question_event(app: &mut App, event: &Event) -> Flow { let Event::Key(key) = event else { return Flow::Continue; }; match key.code { KeyCode::Char('y' | 'Y') => match app.host.question.take() { - Some((_, crate::remote::Pending::Action(index))) => app.begin_task(index, true), + Some((_, crate::remote::Pending::Action(index))) => app.begin_action(index, true), Some((_, crate::remote::Pending::Apply)) => return apply(app, true), None => {} }, @@ -740,7 +740,7 @@ fn question_event(app: &mut App, event: &Event) -> Flow { Flow::Continue } -/// The dialog that asks for a task's arguments. +/// The dialog that asks for an action's arguments. fn arguments_event(app: &mut App, event: &Event, platform: &mut dyn Platform) { let Some(event) = crate::keys::event(event) else { return; @@ -1030,21 +1030,21 @@ fn choose(app: &mut App, entry: Entry) -> Flow { let item = Item::Feature(index); app.set_item(item, !app.item_enabled(item)); } - Entry::HostTask(index) => app.begin_task(index, false), + Entry::HostAction(index) => app.begin_action(index, false), Entry::HostSession(index) => { if let Some(session) = app.host.sessions.get(index).cloned() { app.host.open(&session); } } - Entry::Task("terminal") => app.start_host_shell(), - Entry::Task("ssh") => { + Entry::Offer("terminal") => app.start_host_shell(), + Entry::Offer("ssh") => { let (rows, cols) = session_size(); app.start_shell(rows, cols); } - Entry::Task("connect") => app.reconnect_host(), - Entry::Task("address") => app.edit_address(), - Entry::Task("apply") => return apply(app, false), - Entry::Task("install-controller") => { + Entry::Offer("connect") => app.reconnect_host(), + Entry::Offer("address") => app.edit_address(), + Entry::Offer("apply") => return apply(app, false), + Entry::Offer("install-controller") => { let _ = app.save(); app.own_command = Some( ["host", "install", &app.place.argument()] @@ -1056,7 +1056,7 @@ fn choose(app: &mut App, entry: Entry) -> Flow { Entry::Save => { save(app); } - Entry::Task(_) => {} + Entry::Offer(_) => {} Entry::Run => { if !app.problems().is_empty() { app.status = "Fix the listed problems first".into(); @@ -1196,7 +1196,7 @@ fn key_event( } KeyCode::Char(' ') => match app.selected_entry() { Some(Entry::Group(group)) => app.toggle_group(group), - Some(Entry::Task("terminal")) => app.as_agent = !app.as_agent, + Some(Entry::Offer("terminal")) => app.as_agent = !app.as_agent, Some( entry @ (Entry::Field(_) | Entry::Feature(..) @@ -4286,7 +4286,7 @@ mod tests { .unwrap() .remove("served"); // The action opens the address for editing. - choose(&mut app, Entry::Task("address")); + choose(&mut app, Entry::Offer("address")); assert!(app.retry_address && app.editing.is_some(), "{}", app.status); assert_eq!(app.selected_field(), Some(Field::SshHost)); let mut armed = false; @@ -4690,8 +4690,8 @@ mod tests { assert!(app.confirm.is_none() && app.job.is_none()); } - /// A host that has answered, with a few tasks as it would list them. - fn host_tasks() -> Vec { + /// A host that has answered, with a few actions as it would list them. + fn controller_actions() -> Vec { serde_json::from_value(json!([ {"name": "status", "label": "Status", "group": "System", "user": "root", "help": "How the host is."}, {"name": "claude:status", "label": "Claude Code sign-in", "extends": ["sign-in:status"], "help": "Whether Claude is signed in."}, @@ -4718,12 +4718,12 @@ mod tests { let text = screen_text(&mut app); assert!(text.contains("Type · ssh"), "{text}"); assert!(text.contains("▸ Install the controller") && text.contains("▸ Terminal over SSH")); - assert!(!app.entries().contains(&Entry::Task("apply"))); + assert!(!app.entries().contains(&Entry::Offer("apply"))); // Choosing it, and saying yes, runs berth host install in the normal terminal. let at = app .entries() .iter() - .position(|entry| *entry == Entry::HostTask(0)) + .position(|entry| *entry == Entry::HostAction(0)) .unwrap(); app.list.select(Some(at)); press(&mut app, &[KeyCode::Enter]); @@ -4745,7 +4745,7 @@ mod tests { text.contains("Network is unreachable") && text.contains("▸ Install the controller"), "{text}" ); - assert!(app.entries().contains(&Entry::HostTask(0))); + assert!(app.entries().contains(&Entry::HostAction(0))); // A managed host lists berth's own beside its actions; one it cannot // run is marked, and its reason is in the information box. @@ -4753,7 +4753,7 @@ mod tests { app.config["type"] = json!("managed"); app.host.host_type = berth_api::HostType::Managed; app.host.state = State::Ready(berth_api::VERSION.into()); - app.host.tasks = host_tasks(); + app.host.host_actions = controller_actions(); app.host.own = vec![ berth_core::host_type::install_controller_action( "devbox", @@ -4780,14 +4780,14 @@ mod tests { 1, "{rows:?}" ); - assert!(!app.entries().contains(&Entry::Task("apply"))); + assert!(!app.entries().contains(&Entry::Offer("apply"))); let index = app .host .actions() .iter() .position(|action| action.name == "host-key") .unwrap(); - app.begin_task(index, false); + app.begin_action(index, false); assert!(app.status.contains("cannot run now: devbox has no profile")); assert!(app.own_command.is_none()); } @@ -4822,7 +4822,7 @@ mod tests { // Without an address there is nothing to ask. let manage = screen(&mut app); assert!(manage.contains("✗ Enter an SSH hostname") && !manage.contains("▸ Status")); - assert!(app.entries().contains(&Entry::Task("apply"))); + assert!(app.entries().contains(&Entry::Offer("apply"))); app.commit(Field::SshHost, "devbox.example"); app.config["agent_username"] = json!("robot"); @@ -4832,7 +4832,7 @@ mod tests { let applies = |app: &App| { app.entries() .iter() - .filter(|entry| **entry == Entry::Task("apply")) + .filter(|entry| **entry == Entry::Offer("apply")) .count() }; assert!(screen_text(&mut app).contains("not on this host yet") && applies(&app) == 1); @@ -4840,11 +4840,11 @@ mod tests { State::Unreachable("ssh: connect to host devbox.example: timed out\nmore".into()); let text = screen_text(&mut app); assert!(text.contains("✗ ssh: connect to host") && text.contains("▸ Terminal over SSH")); - assert!(app.entries().contains(&Entry::Task("connect"))); + assert!(app.entries().contains(&Entry::Offer("connect"))); - // One that answered lists its tasks in their groups. + // One that answered lists its actions in their groups. app.host.state = State::Ready("0.2.0".into()); - app.host.tasks = host_tasks(); + app.host.host_actions = controller_actions(); let rows: Vec = app.rows().iter().map(|row| row.line.to_string()).collect(); let place = |text: &str| rows.iter().position(|row| row.contains(text)).unwrap(); assert!( @@ -4863,15 +4863,15 @@ mod tests { app.list.select(Some(at.unwrap())); }; // The information box says what the plugins' steps add. - select(&mut app, Entry::HostTask(1)); + select(&mut app, Entry::HostAction(1)); let help = app.help(); assert!( help.contains("### From plugins") && help.contains("**Claude Code sign-in**: Whether") ); assert!(help.contains("berth run HOST sign-in:status")); - // A task with a question waits for the yes. - select(&mut app, Entry::HostTask(3)); + // An action with a question waits for the yes. + select(&mut app, Entry::HostAction(3)); assert!(!press(&mut app, &[KeyCode::Enter])); assert_eq!( app.host.question, @@ -4884,8 +4884,8 @@ mod tests { ); assert!(app.host.question.is_none()); - // A task with arguments asks for each; a needed one cannot be left empty. - select(&mut app, Entry::HostTask(4)); + // An action with arguments asks for each; a needed one cannot be left empty. + select(&mut app, Entry::HostAction(4)); press(&mut app, &[KeyCode::Enter]); let key = |app: &mut App, code| { arguments_event( @@ -4946,7 +4946,7 @@ mod tests { // Applying with a session running asks first; then it is the SSH install. app.config["hostname"] = json!("devbox-1"); app.config["operator_ssh_public_key"] = json!("ssh-ed25519 AAAA me"); - select(&mut app, Entry::Task("apply")); + select(&mut app, Entry::Offer("apply")); assert!(!press(&mut app, &[KeyCode::Enter])); assert!(matches!(app.host.question, Some((_, Pending::Apply)))); let yes = Event::Key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); @@ -4957,7 +4957,7 @@ mod tests { // Space switches the Terminal row between the two accounts. app.host.state = State::Ready("0.2.0".into()); - select(&mut app, Entry::Task("terminal")); + select(&mut app, Entry::Offer("terminal")); press(&mut app, &[KeyCode::Char(' ')]); assert!(!app.as_agent && screen_text(&mut app).contains("the SSH user")); press(&mut app, &[KeyCode::Char(' ')]); diff --git a/crates/berthd/src/tasks.rs b/crates/berthd/src/actions.rs similarity index 65% rename from crates/berthd/src/tasks.rs rename to crates/berthd/src/actions.rs index ae401f7..b22fc9f 100644 --- a/crates/berthd/src/tasks.rs +++ b/crates/berthd/src/actions.rs @@ -1,5 +1,5 @@ -//! Tasks: the host's named operations. Running one starts a session whose -//! steps are the task and the tasks that extend it, each as its own user. +//! Actions: the host's named operations. Running one starts a session whose +//! steps are the action and the actions that extend it, each as its own user. use crate::error::{E, R}; use crate::sessions::{Plan, Wait, new_id, started}; @@ -8,24 +8,24 @@ use axum::{ Json, extract::{Extension, Path, Query, State as AppState}, }; -use berth_api::{self as api, CommandLine, SessionKind, Task}; +use berth_api::{self as api, CommandLine, HostAction, SessionKind}; use std::{collections::BTreeMap, sync::Arc}; -fn allowed(caller: &Caller, task: &Task) -> bool { - caller.host() || task.agent +fn allowed(caller: &Caller, action: &HostAction) -> bool { + caller.host() || action.agent } -fn find(state: &State, caller: &Caller, name: &str) -> R { +fn find(state: &State, caller: &Caller, name: &str) -> R { let config = state.config(); - let task = config - .tasks + let action = config + .actions .iter() - .find(|task| task.name == name) - .ok_or_else(|| E::missing(format!("task {name}")))?; - if !allowed(caller, task) { + .find(|action| action.name == name) + .ok_or_else(|| E::missing(format!("action {name}")))?; + if !allowed(caller, action) { return Err(E::forbidden(format!("The agent may not run {name}"))); } - Ok(task.clone()) + Ok(action.clone()) } /// The name an argument has in the command's environment. @@ -46,14 +46,17 @@ pub fn variable(name: &str) -> String { pub async fn list( AppState(state): AppState>, Extension(caller): Extension, -) -> Json> { +) -> Json> { let config = state.config(); - let tasks = config.tasks.iter().filter(|task| allowed(&caller, task)); + let actions = config + .actions + .iter() + .filter(|action| allowed(&caller, action)); Json( - tasks - .map(|task| Task { + actions + .map(|action| HostAction { run: String::new(), - ..task.clone() + ..action.clone() }) .collect(), ) @@ -64,12 +67,16 @@ pub async fn run( Extension(caller): Extension, Path(name): Path, Query(wait): Query, - body: Option>, + body: Option>, ) -> R> { let request = body.map(|Json(request)| request).unwrap_or_default(); - let task = find(&state, &caller, &name)?; - let mut env = BTreeMap::from([("BERTH_TASK".to_owned(), task.name.clone())]); - for argument in &task.arguments { + let action = find(&state, &caller, &name)?; + // BERTH_TASK is what plugins written for berth 0.5 read. + let mut env = BTreeMap::from([ + ("BERTH_ACTION".to_owned(), action.name.clone()), + ("BERTH_TASK".to_owned(), action.name.clone()), + ]); + for argument in &action.arguments { let value = request .arguments .get(&argument.name) @@ -83,26 +90,27 @@ pub async fn run( } env.insert(variable(&argument.name), value); } - if let Some(unknown) = request - .arguments - .keys() - .find(|key| task.arguments.iter().all(|argument| &argument.name != *key)) - { + if let Some(unknown) = request.arguments.keys().find(|key| { + action + .arguments + .iter() + .all(|argument| &argument.name != *key) + }) { return Err(E::bad(format!("{name} has no argument {unknown}"))); } - let input = match (&task.input, &request.input_b64) { + let input = match (&action.input, &request.input_b64) { (Some(what), None) => return Err(E::bad(format!("{name} needs {what} sent as input_b64"))), (_, Some(data)) => Some(api::unb64(data).ok_or_else(|| E::bad("input_b64 is not base64"))?), (None, None) => None, }; - // The task itself, then what extends it, in the order of the file. + // The action itself, then what extends it, in the order of the file. let config = state.config(); let extenders = config - .tasks + .actions .iter() - .filter(|other| other.extends.contains(&task.name) && other.name != task.name); + .filter(|other| other.extends.contains(&action.name) && other.name != action.name); let mut steps = vec![]; - for step in std::iter::once(&task).chain(extenders) { + for step in std::iter::once(&action).chain(extenders) { let command = crate::users::command( &state, &step.user, @@ -121,19 +129,19 @@ pub async fn run( } let plan = Plan { id: new_id(), - kind: if task.terminal { + kind: if action.terminal { SessionKind::Terminal } else { SessionKind::Process }, - title: if task.label.is_empty() { - task.name.clone() + title: if action.label.is_empty() { + action.name.clone() } else { - task.label.clone() + action.label.clone() }, - command: vec![task.name.clone()], - user: task.user.clone(), - task: Some(task.name.clone()), + command: vec![action.name.clone()], + user: action.user.clone(), + action: Some(action.name.clone()), steps, input, close_input: true, @@ -150,8 +158,8 @@ pub async fn choices( Extension(caller): Extension, Path((name, argument)): Path<(String, String)>, ) -> R> { - let task = find(&state, &caller, &name)?; - let argument = task + let action = find(&state, &caller, &name)?; + let argument = action .arguments .iter() .find(|known| known.name == argument) @@ -161,7 +169,7 @@ pub async fn choices( } let line = CommandLine::Shell(argument.choices.clone()); let (code, output, errors) = - crate::users::capture(&state, &task.user, &line, 15, 256 << 10).await?; + crate::users::capture(&state, &action.user, &line, 15, 256 << 10).await?; if code != 0 { return Err(E::internal(format!( "The choices command failed ({code}): {errors}" diff --git a/crates/berthd/src/http.rs b/crates/berthd/src/http.rs index 2c3e3de..577889d 100644 --- a/crates/berthd/src/http.rs +++ b/crates/berthd/src/http.rs @@ -3,7 +3,7 @@ use crate::error::E; use crate::state::{Caller, Mode, State}; -use crate::{channel, files, ports, services, sessions, system, tasks}; +use crate::{actions, channel, files, ports, services, sessions, system}; use axum::{ Json, Router, extract::{Extension, Request, State as AppState}, @@ -46,7 +46,7 @@ pub const ROUTES: &[Route] = &[ Route { method: "POST", path: "/v1/sessions", summary: "Start a session.", level: "host", query: &[WAIT], body: "StartSession", reply: "Started", stream: "", handler: || post(sessions::start) }, Route { method: "GET", path: "/v1/sessions", summary: "All sessions, running and ended.", level: "host", query: &[], body: "", reply: "Session[]", stream: "", handler: || get(sessions::list) }, - Route { method: "GET", path: "/v1/sessions/{id}", summary: "One session's state. The agent sees those it started through a task.", level: "both", query: &[], body: "", reply: "Session", stream: "session", handler: || get(sessions::one) }, + Route { method: "GET", path: "/v1/sessions/{id}", summary: "One session's state. The agent sees those it started through an action.", level: "both", query: &[], body: "", reply: "Session", stream: "session", handler: || get(sessions::one) }, Route { method: "DELETE", path: "/v1/sessions/{id}", summary: "End it if it runs (HUP, after five seconds KILL) and forget it with its transcript.", level: "host", query: &[], body: "", reply: "Done", stream: "", handler: || delete(sessions::delete) }, Route { method: "GET", path: "/v1/sessions/{id}/output", summary: "The transcript, by bytes or by lines.", level: "both", query: &[("stream", "stdout, stderr or merged (default), for a process."), ("since", "Byte offset to read from."), ("limit", "Most bytes to return; default 1 MB."), ("line", "Read lines from this line number (a process only)."), ("count", "How many lines; default 100."), ("tail", "The last so many lines.")], body: "", reply: "Output", stream: "", handler: || get(sessions::output) }, Route { method: "GET", path: "/v1/sessions/{id}/screen", summary: "A terminal as it looks now, as text.", level: "both", query: &[("format", "text (default) or ansi, which keeps colours."), ("tail", "That many lines of screen and scrollback instead.")], body: "", reply: "Screen", stream: "", handler: || get(sessions::screen) }, @@ -54,9 +54,9 @@ pub const ROUTES: &[Route] = &[ Route { method: "POST", path: "/v1/sessions/{id}/resize", summary: "Give a terminal a new size.", level: "host", query: &[], body: "Resize", reply: "Done", stream: "", handler: || post(sessions::resize) }, Route { method: "POST", path: "/v1/sessions/{id}/signal", summary: "Send INT, TERM, HUP or KILL to the session's process group.", level: "host", query: &[], body: "Signal", reply: "Done", stream: "", handler: || post(sessions::signal) }, - Route { method: "GET", path: "/v1/tasks", summary: "The tasks the caller may run, in the order of the file.", level: "both", query: &[], body: "", reply: "Task[]", stream: "", handler: || get(tasks::list) }, - Route { method: "POST", path: "/v1/tasks/{name}", summary: "Run a task. It and what extends it are the steps of one session.", level: "both", query: &[WAIT], body: "RunTask", reply: "Started", stream: "", handler: || post(tasks::run) }, - Route { method: "GET", path: "/v1/tasks/{name}/choices/{argument}", summary: "The values to offer for an argument.", level: "both", query: &[], body: "", reply: "Choices", stream: "", handler: || get(tasks::choices) }, + Route { method: "GET", path: "/v1/actions", summary: "The actions the caller may run, in the order of the file.", level: "both", query: &[], body: "", reply: "HostAction[]", stream: "", handler: || get(actions::list) }, + Route { method: "POST", path: "/v1/actions/{action}", summary: "Run an action. It and what extends it are the steps of one session.", level: "both", query: &[WAIT], body: "RunAction", reply: "Started", stream: "", handler: || post(actions::run) }, + Route { method: "GET", path: "/v1/actions/{action}/choices/{argument}", summary: "The values to offer for an argument.", level: "both", query: &[], body: "", reply: "Choices", stream: "", handler: || get(actions::choices) }, Route { method: "GET", path: "/v1/stats", summary: "Load, CPU, memory, filesystems, network, GPU and unit states, read now.", level: "host", query: &[], body: "", reply: "Stats", stream: "", handler: || get(system::stats) }, Route { method: "GET", path: "/v1/screenshot", summary: "The shared desktop as PNG.", level: "host", query: &[], body: "", reply: "png", stream: "", handler: || get(system::screenshot) }, @@ -323,8 +323,8 @@ pub fn paths(prefix: &str) -> serde_json::Map { api::Resize, api::Signal, api::Argument, - api::Task, - api::RunTask, + api::HostAction, + api::RunAction, api::Choices, api::Memory, api::Filesystem, @@ -380,11 +380,15 @@ const PATH_ARGUMENTS: &[(&str, &str, &str)] = &[ "id", "A session's id, as starting it or the list gives it.", ), - ("tasks.", "name", "A task's name, as the list gives it."), ( - "tasks.", + "actions.", + "action", + "An action's name, as the list gives it.", + ), + ( + "actions.", "argument", - "The name of one of the task's arguments.", + "The name of one of the action's arguments.", ), ("system.power", "verb", "`reboot` or `poweroff`."), ( diff --git a/crates/berthd/src/lib.rs b/crates/berthd/src/lib.rs index 52c2b49..15fa31f 100644 --- a/crates/berthd/src/lib.rs +++ b/crates/berthd/src/lib.rs @@ -1,6 +1,7 @@ -//! berthd: the host's API. Sessions, tasks, system calls, a channel and +//! berthd: the host's API. Sessions, actions, system calls, a channel and //! services, over unix sockets. +mod actions; mod channel; mod error; mod files; @@ -11,7 +12,6 @@ mod services; mod sessions; pub mod state; mod system; -mod tasks; mod transcript; mod users; diff --git a/crates/berthd/src/sessions.rs b/crates/berthd/src/sessions.rs index 5de8359..d08dd0e 100644 --- a/crates/berthd/src/sessions.rs +++ b/crates/berthd/src/sessions.rs @@ -82,7 +82,7 @@ pub struct Plan { pub title: String, pub command: Vec, pub user: String, - pub task: Option, + pub action: Option, /// The commands to run one after another, with the step each is. A plain /// session has one command and no step. pub steps: Vec<(Option, Command)>, @@ -280,7 +280,7 @@ impl Sessions { uid: caller.uid, session: None, }, - task: plan.task, + action: plan.action, started: api::now(), ended: None, exit_code: None, @@ -450,7 +450,7 @@ impl Session { self.meta.lock().unwrap().kind } - /// The agent may look at the sessions it started through a task. + /// The agent may look at the sessions it started through an action. pub fn visible_to(&self, caller: &Caller) -> bool { let meta = self.meta.lock().unwrap(); caller.host() @@ -785,7 +785,7 @@ pub async fn start( title: request.title.clone().unwrap_or_else(|| words.join(" ")), command: words, user: request.user.clone(), - task: None, + action: None, steps: vec![(None, command)], // Nobody can type into a command that is waited for in one request. close_input: input.is_some() || wait.wait.is_some(), @@ -806,7 +806,7 @@ fn visible(state: &State, caller: &Caller, id: &str) -> R> { let session = state.sessions.get(id)?; if !session.visible_to(caller) { return Err(E::forbidden( - "The agent sees only the sessions it started through a task", + "The agent sees only the sessions it started through an action", )); } Ok(session) diff --git a/crates/berthd/src/state.rs b/crates/berthd/src/state.rs index 54ccc15..85c2fc3 100644 --- a/crates/berthd/src/state.rs +++ b/crates/berthd/src/state.rs @@ -1,4 +1,4 @@ -use berth_api::{Config, Level, ServiceSpec, Task, Topic}; +use berth_api::{Config, HostAction, Level, ServiceSpec, Topic}; use std::{ path::{Path, PathBuf}, sync::{Arc, RwLock}, @@ -30,7 +30,7 @@ impl Caller { #[derive(Debug, Default)] pub struct Loaded { pub berthd: Config, - pub tasks: Vec, + pub actions: Vec, pub services: Vec, pub topics: Vec, } @@ -60,7 +60,11 @@ impl Loaded { let mut problems = vec![]; let loaded = Loaded { berthd: read(dir, "berthd.json", &mut problems), - tasks: read(dir, "tasks.json", &mut problems), + actions: match dir.join("actions.json").exists() { + true => read(dir, "actions.json", &mut problems), + // What a role of berth 0.5 wrote, until the host is applied again. + false => read(dir, "tasks.json", &mut problems), + }, services: read(dir, "services.json", &mut problems), topics: read(dir, "channels.json", &mut problems), }; diff --git a/crates/berthd/tests/api.rs b/crates/berthd/tests/api.rs index d12039e..3ed4302 100644 --- a/crates/berthd/tests/api.rs +++ b/crates/berthd/tests/api.rs @@ -431,31 +431,31 @@ async fn a_terminal_keeps_its_screen_for_viewers_that_come_and_go() { } #[tokio::test] -async fn tasks_run_as_steps_with_arguments() { - let tasks = json!([ +async fn actions_run_as_steps_with_arguments() { + let actions = json!([ {"name": "greet", "label": "Greet", "group": "Demo", "agent": true, "confirm": "Really?", "arguments": [{"name": "who", "required": true}, {"name": "how-loud", "default": "quiet"}, {"name": "pick", "choices": "echo one; echo; echo 'two words'"}], "run": "printf '%s|%s\\n' \"$BERTH_ARG_WHO\" \"$BERTH_ARG_HOW_LOUD\"; exit 2"}, - {"name": "plug:extra", "extends": ["greet"], "run": "echo extra for $BERTH_TASK"}, + {"name": "plug:extra", "extends": ["greet"], "run": "echo extra for $BERTH_ACTION and $BERTH_TASK"}, {"name": "plug:last", "extends": ["greet", "other"], "run": "exit 5"}, {"name": "private", "run": "echo host only"}, {"name": "feed", "input": "secrets", "run": "cat"}, {"name": "ask", "terminal": true, "agent": true, "run": "printf 'go? '; read answer; echo went $answer"}, ]); - let daemon = Daemon::start(&[("tasks.json", tasks)]); + let daemon = Daemon::start(&[("actions.json", actions)]); let mut host = daemon.host().await; let mut agent = daemon.agent().await; - let listed: Vec = host.get("/v1/tasks").await.unwrap(); + let listed: Vec = host.get("/v1/actions").await.unwrap(); assert_eq!(listed.len(), 6); - assert!(listed.iter().all(|task| task.run.is_empty())); + assert!(listed.iter().all(|action| action.run.is_empty())); assert_eq!(listed[0].confirm.as_deref(), Some("Really?")); - let listed: Vec = agent.get("/v1/tasks").await.unwrap(); + let listed: Vec = agent.get("/v1/actions").await.unwrap(); assert_eq!( listed .iter() - .map(|task| task.name.as_str()) + .map(|action| action.name.as_str()) .collect::>(), ["greet", "ask"] ); @@ -463,10 +463,10 @@ async fn tasks_run_as_steps_with_arguments() { // Arguments arrive in the environment, quotes and spaces untouched. All // steps run; the exit code is the first that was not 0. let run = json!({"arguments": {"who": "it's \"me\" $HOME; ls"}}); - let done: Value = host.post("/v1/tasks/greet?wait=10s", &run).await.unwrap(); + let done: Value = host.post("/v1/actions/greet?wait=10s", &run).await.unwrap(); assert_eq!( text(&done["stdout_b64"]), - "it's \"me\" $HOME; ls|quiet\nextra for greet\n" + "it's \"me\" $HOME; ls|quiet\nextra for greet and greet\n" ); assert_eq!(done["exit_code"], 2); let steps: Vec<(String, i64)> = done["steps"] @@ -488,13 +488,16 @@ async fn tasks_run_as_steps_with_arguments() { ("plug:last".to_owned(), 5) ] ); - assert_eq!(done["task"], "greet"); + assert_eq!(done["action"], "greet"); - assert_eq!(code(host.post("/v1/tasks/greet", &json!({})).await).0, 400); + assert_eq!( + code(host.post("/v1/actions/greet", &json!({})).await).0, + 400 + ); assert_eq!( code( host.post( - "/v1/tasks/greet", + "/v1/actions/greet", &json!({"arguments": {"who": "x", "nope": "y"}}) ) .await @@ -503,17 +506,17 @@ async fn tasks_run_as_steps_with_arguments() { 400 ); assert_eq!( - code(host.post("/v1/tasks/missing", &json!({})).await).0, + code(host.post("/v1/actions/missing", &json!({})).await).0, 404 ); - let choices: api::Choices = host.get("/v1/tasks/greet/choices/pick").await.unwrap(); + let choices: api::Choices = host.get("/v1/actions/greet/choices/pick").await.unwrap(); assert_eq!(choices.choices, ["one", "two words"]); // What the workstation sends as input reaches the command and nothing else does. - assert_eq!(code(host.post("/v1/tasks/feed", &json!({})).await).0, 400); + assert_eq!(code(host.post("/v1/actions/feed", &json!({})).await).0, 400); let done: Value = host .post( - "/v1/tasks/feed?wait=10s", + "/v1/actions/feed?wait=10s", &json!({"input_b64": api::b64(b"{\"k\":1}\n")}), ) .await @@ -522,11 +525,11 @@ async fn tasks_run_as_steps_with_arguments() { // The agent runs what is marked for it, reads and follows that session, and nothing else. assert_eq!( - code(agent.post("/v1/tasks/private", &json!({})).await).0, + code(agent.post("/v1/actions/private", &json!({})).await).0, 403 ); let hosts: Value = host - .post("/v1/tasks/private?wait=10s", &json!({})) + .post("/v1/actions/private?wait=10s", &json!({})) .await .unwrap(); assert_eq!( @@ -539,7 +542,7 @@ async fn tasks_run_as_steps_with_arguments() { 403 ); let started: Value = agent - .post("/v1/tasks/ask", &json!({"rows": 5, "cols": 40})) + .post("/v1/actions/ask", &json!({"rows": 5, "cols": 40})) .await .unwrap(); assert_eq!( @@ -1061,6 +1064,7 @@ async fn services_answer_calls_through_their_socket() { #[tokio::test] async fn a_restart_ends_sessions_and_keeps_their_transcripts() { + // What the role of berth 0.5 wrote is read until there is the file of now. let mut daemon = Daemon::start(&[("tasks.json", json!([{"name": "one", "run": "echo first"}]))]); let mut host = daemon.host().await; @@ -1074,18 +1078,20 @@ async fn a_restart_ends_sessions_and_keeps_their_transcripts() { let id = started["id"].as_str().unwrap().to_owned(); tokio::time::sleep(Duration::from_millis(200)).await; - // A reload takes up new tasks and leaves the session running. + let actions: Vec = host.get("/v1/actions").await.unwrap(); + assert_eq!(actions[0].name, "one"); + // A reload takes up new actions and leaves the session running. std::fs::write( - daemon.dir.path().join("etc/tasks.json"), + daemon.dir.path().join("etc/actions.json"), json!([{"name": "two", "run": "true"}]).to_string(), ) .unwrap(); let _: Value = host.post("/v1/reload", &json!({})).await.unwrap(); - let tasks: Vec = host.get("/v1/tasks").await.unwrap(); - assert_eq!(tasks[0].name, "two"); + let actions: Vec = host.get("/v1/actions").await.unwrap(); + assert_eq!(actions[0].name, "two"); let state: api::Session = host.get(&format!("/v1/sessions/{id}")).await.unwrap(); assert!(state.running()); - std::fs::write(daemon.dir.path().join("etc/tasks.json"), "not json").unwrap(); + std::fs::write(daemon.dir.path().join("etc/actions.json"), "not json").unwrap(); assert_eq!(code(host.post("/v1/reload", &json!({})).await).0, 400); drop(host); @@ -1228,7 +1234,7 @@ async fn the_portal_carries_calls_and_streams_together() { let agent = Portal::over(daemon.stream("agent", "/v1/portal").await); assert!( agent - .call("tasks.list", None, Value::Null, None) + .call("actions.list", None, Value::Null, None) .await .is_ok() ); diff --git a/crates/box/src/main.rs b/crates/box/src/main.rs index 119ae01..3700a78 100644 --- a/crates/box/src/main.rs +++ b/crates/box/src/main.rs @@ -11,8 +11,8 @@ const USAGE: &str = "usage: box desktop screenshot [--output PATH|-] | click X Y [BUTTON] | type TEXT | key CHORD | scroll up|down [STEPS] | clipboard | pause | resume box mcp the desktop tools as an MCP server on stdio box exec [COMMAND...] run a command, or a shell, with the desktop's environment - box tasks the tasks this user may run - box run TASK [NAME=VALUE...] run one; output here, its exit code as box's + box actions the actions this user may run + box run ACTION [NAME=VALUE...] run one; output here, its exit code as box's box publish TOPIC [JSON] [--keep none|last|log] box listen TOPIC-PREFIX [--since ID] one JSON message per line box services what can be called, and whether it is up diff --git a/crates/box/src/net.rs b/crates/box/src/net.rs index 8a7c819..940588d 100644 --- a/crates/box/src/net.rs +++ b/crates/box/src/net.rs @@ -2,7 +2,7 @@ use crate::{assignments, json_or_string, serve, take_flag}; use berth_api::client::{self, Client, Frame, encode, encode_path}; -use berth_api::{Service, Session, SessionKind, Task}; +use berth_api::{HostAction, Service, Session, SessionKind}; use futures_util::{SinkExt, StreamExt}; use serde_json::{Value, json}; use std::io::{IsTerminal, Read, Write}; @@ -41,10 +41,10 @@ fn e(error: impl std::fmt::Display) -> String { async fn verb_async(verb: &str, mut args: Vec) -> Result { let usage = |text: &str| Err(format!("usage: box {text}")); match (verb, args.len()) { - ("tasks", 0) | ("services", 0) => {} + ("actions", 0) | ("services", 0) => {} ("run", 1..) | ("publish", 1..) | ("listen", 1..) | ("call", 2..) | ("serve", 3..) => {} - ("tasks" | "services", _) => return usage(verb), - ("run", _) => return usage("run TASK [NAME=VALUE…]"), + ("actions" | "services", _) => return usage(verb), + ("run", _) => return usage("run ACTION [NAME=VALUE…]"), ("publish", _) => return usage("publish TOPIC [JSON] [--keep none|last|log]"), ("listen", _) => return usage("listen TOPIC-PREFIX [--since ID]"), ("call", _) => return usage("call SERVICE METHOD [JSON]"), @@ -57,12 +57,12 @@ async fn verb_async(verb: &str, mut args: Vec) -> Result { let sock = socket()?; let mut api = Client::unix(&sock).await.map_err(e)?; match verb { - "tasks" => { - let tasks: Vec = api.get("/v1/tasks").await.map_err(e)?; - for task in tasks.iter().filter(|t| t.extends.is_empty()) { - let mut line = format!("{}\t{}", task.name, task.label); - if !task.arguments.is_empty() { - let names: Vec = task + "actions" => { + let actions: Vec = api.get("/v1/actions").await.map_err(e)?; + for action in actions.iter().filter(|a| a.extends.is_empty()) { + let mut line = format!("{}\t{}", action.name, action.label); + if !action.arguments.is_empty() { + let names: Vec = action .arguments .iter() .map(|a| format!("{}{}", a.name, if a.required { "*" } else { "" })) @@ -84,8 +84,8 @@ async fn verb_async(verb: &str, mut args: Vec) -> Result { } } "run" => { - let task = args.remove(0); - return run_task(&sock, &mut api, &task, &args).await; + let action = args.remove(0); + return run_action(&sock, &mut api, &action, &args).await; } "publish" => { let keep = take_flag(&mut args, "--keep")?; @@ -205,10 +205,10 @@ fn exit_status(code: Option) -> i32 { code.map_or(1, |n| (n & 0xff) as i32) } -async fn run_task( +async fn run_action( sock: &std::path::Path, api: &mut Client, - task: &str, + action: &str, words: &[String], ) -> Result { let mut body = json!({"arguments": assignments(words)?}); @@ -218,7 +218,7 @@ async fn run_task( body["cols"] = cols.into(); } let session: Session = api - .post(&format!("/v1/tasks/{}", encode(task)), &body) + .post(&format!("/v1/actions/{}", encode(action)), &body) .await .map_err(e)?; let mut ws = client::websocket_unix( diff --git a/crates/box/tests/berthd.rs b/crates/box/tests/berthd.rs index 3a1b6e1..44729bd 100644 --- a/crates/box/tests/berthd.rs +++ b/crates/box/tests/berthd.rs @@ -26,7 +26,7 @@ fn verbs_against_berthd() { let dir = tempfile::tempdir().unwrap(); std::fs::create_dir(dir.path().join("etc")).unwrap(); std::fs::write( - dir.path().join("etc/tasks.json"), + dir.path().join("etc/actions.json"), r#"[{"name":"hello","label":"Hello","user":"agent","agent":true,"arguments":[{"name":"who","required":true}],"run":"echo hi $BERTH_ARG_WHO; echo err >&2; exit 3"}]"#, ) .unwrap(); @@ -51,11 +51,11 @@ fn verbs_against_berthd() { cmd.env("BERTH_DIR", dir.path()).args(args); cmd }; - let out = bx(&["tasks"]).output().unwrap(); - let tasks = String::from_utf8_lossy(&out.stdout).into_owned(); - if !tasks.contains("hello\tHello\twho*") { + let out = bx(&["actions"]).output().unwrap(); + let actions = String::from_utf8_lossy(&out.stdout).into_owned(); + if !actions.contains("hello\tHello\twho*") { return eprintln!( - "skipped: berthd does not serve tasks yet: {tasks} {}", + "skipped: berthd does not serve actions yet: {actions} {}", String::from_utf8_lossy(&out.stderr) ); } diff --git a/docs/content/docs/(guide)/deploy/container.mdx b/docs/content/docs/(guide)/deploy/container.mdx index 7b74c00..164d5be 100644 --- a/docs/content/docs/(guide)/deploy/container.mdx +++ b/docs/content/docs/(guide)/deploy/container.mdx @@ -42,7 +42,7 @@ Ports are published on host loopback only. If Docker runs on another machine, tu ## Reaching it from berth -The container runs `berthd` for the agent account, without systemd and without root. Sessions, tasks that run as the agent, the channel and files work. Calls that need systemd or another user are refused. A profile connects to it with a `link` command in its `builder` section: +The container runs `berthd` for the agent account, without systemd and without root. Sessions, actions that run as the agent, the channel and files work. Calls that need systemd or another user are refused. A profile connects to it with a `link` command in its `builder` section: ```json title="In the host's profile" { "builder": { "link": ["docker", "exec", "-i", "CONTAINER", "berthd", "connect"] } } diff --git a/docs/content/docs/(guide)/extend/index.mdx b/docs/content/docs/(guide)/extend/index.mdx index fb07e69..199f25c 100644 --- a/docs/content/docs/(guide)/extend/index.mdx +++ b/docs/content/docs/(guide)/extend/index.mdx @@ -6,7 +6,7 @@ icon: Puzzle The plugins that come with berth, installing your own, and switching features on. - The package format with its features, actions, tasks and guides. + The package format with its features, actions, Ansible tasks and guides. A program on the host that answers calls from the agent and from you. One local API over all hosts, with an inbox and a key-value store. The WebSockets of berthd and berth serve: frames, resuming, reconnecting. diff --git a/docs/content/docs/(guide)/extend/plugins.mdx b/docs/content/docs/(guide)/extend/plugins.mdx index 794f12c..bc52f48 100644 --- a/docs/content/docs/(guide)/extend/plugins.mdx +++ b/docs/content/docs/(guide)/extend/plugins.mdx @@ -1,10 +1,10 @@ --- title: Plugins -description: Optional software, tasks and guides for hosts, switched on per host. +description: Optional software, actions and guides for hosts, switched on per host. icon: Blocks --- -A plugin adds optional things to a host. Each thing is a **feature**: packages, set-up steps, a guide for the agents working there, and tasks on the host's overview. A plugin can have several features, each switched on by itself. Even the coding agents are plugins. +A plugin adds optional things to a host. Each thing is a **feature**: packages, set-up steps, a guide for the agents working there, and actions on the host's overview. A plugin can have several features, each switched on by itself. Even the coding agents are plugins. ## Plugins that come with berth @@ -78,7 +78,7 @@ A host keeps what it was applied with until it is applied again. After an update With a [berth server](/docs/use/server) set, the Plugins tab and `berth plugins` show the server's plugins and change those, which needs the role `admin` there. The server installs a package name or an `https://` address with its own npm and npm configuration. A `.tgz` or a folder on your machine is packed and sent to the server. berth-remote has the same tab, and `u` there sends a `.tgz` from its machine. -The server's hosts can have a new plugin's features as soon as it is installed. Its tasks run on the server when a host is applied, so installing is part of set-up. A server with `serve_setup off` takes it only on its own socket ([Closing set-up](/docs/extend/serve#closing-set-up)). +The server's hosts can have a new plugin's features as soon as it is installed. Its Ansible tasks run on the server when a host is applied, so installing is part of set-up. A server with `serve_setup off` takes it only on its own socket ([Closing set-up](/docs/extend/serve#closing-set-up)). A plugin of yours with the same id as a built-in one replaces it. berth reads a plugin's `package.json` and hands its tasks to Ansible. It never runs the package's npm scripts. diff --git a/docs/content/docs/(guide)/extend/serve.mdx b/docs/content/docs/(guide)/extend/serve.mdx index 399daea..66327a4 100644 --- a/docs/content/docs/(guide)/extend/serve.mdx +++ b/docs/content/docs/(guide)/extend/serve.mdx @@ -22,8 +22,8 @@ It prints where it listens and how many hosts it knows. Only one runs per user. | [`plugins.*`](/docs/api/serve/plugins) | The server's plugins. One is installed from its npm registry, from an `https://` address, or from a `.tgz` that is sent, and one of its own is removed. `plugins.check` asks the registries for newer versions and `plugins.update` installs them. `setup.catalogue` lists the new features straight away | | [`provisioners.*`](/docs/api/serve/provisioners) | The provisioners of the plugins with their pages and actions. A page lists what berth made with the provisioner, by kind. An action of a provisioner has its own role ([Provisioners](/docs/deploy/provisioners#with-a-berth-server)) | | [`resources.*`](/docs/api/serve/resources) | What provisioners made for berth, such as a host's machine or a deployment. Creating, changing and removing one are jobs of the subject `resource:ID` and need the role `admin`. Its log needs `operate`, and its actions have their own roles ([Resources](/docs/deploy/resources#with-a-berth-server)) | -| Every [berthd operation](/docs/api/host) | With a host: `"host": "NAME"` on the portal, `/v1/hosts/NAME/…` over HTTP. Only the `secrets` task is refused; the host's `secrets` action sends the server's own | -| [`jobs.*`](/docs/api/serve/jobs) | Jobs, one for each run of an action that runs here or follows a task, with their output. Each says its subject and its action. A roll-out's job has a report, host by host | +| Every [berthd operation](/docs/api/host) | With a host: `"host": "NAME"` on the portal, `/v1/hosts/NAME/controller/…` over HTTP. Only the controller's own `secrets` action is refused; the server's `secrets` action of the host sends the server's own | +| [`jobs.*`](/docs/api/serve/jobs) | Jobs, one for each run of an action that runs here or follows one of a host's controller, with their output. Each says its subject and its action. A roll-out's job has a report, host by host | | [`inbox.*`](/docs/api/serve/inbox) | Messages the hosts published on their channels and kept, taken in while `berth serve` runs; each can be marked done | | [`kv.*`](/docs/api/serve/kv) | A key-value store with revisions, for user interfaces to keep state in | | [`events.follow`](/docs/api/serve/events) | One stream of channel messages, jobs, key-value changes and changes to hosts and resources, at `/v1/events` | @@ -32,11 +32,11 @@ All of it is also on the [portal](/docs/api/portal), the one WebSocket at `/v1/p ## Actions -What berth does to a host or to the installation is an *action*. `GET /v1/hosts/NAME/actions` lists a host's, and `GET /v1/actions` lists those of the installation. A form can be built from an action's description. It has the arguments with their defaults and choices, a question to confirm, the least role, and whether it can run now. +What berth does to a host or to the installation is an *action*. `GET /v1/hosts/NAME/actions` lists a host's, and `GET /v1/installation/actions` lists those of the installation. A host's controller has actions of its own, which are among the host's here. Its own list, `actions.list`, is at `/v1/hosts/NAME/controller/actions`. A form can be built from an action's description. It has the arguments with their defaults and choices, a question to confirm, the least role, and whether it can run now. | Action | Of | Runs | Answers | | --- | --- | --- | --- | -| A task of the host, such as `status` | The host | On the host, as a session | `202` with the session and a job that copies its output. A task that needs a terminal answers `200` with the session alone, to attach to | +| An action of the host's controller, such as `status` | The host | On the host, as a session | `202` with the session and a job that copies its output. One that needs a terminal answers `200` with the session alone, to attach to | | `apply` | The host | Here, as a job | `202` with the job | | `install-controller` | The host | Here, as a job | `202` with the job. It installs berthd and box alone on a host that is not a workstation | | `seed` | The host | Here, at once | `200` with the seed's `user_data` as the result | @@ -51,7 +51,7 @@ To run one, POST to its name with its arguments: ```bash curl --unix-socket "$XDG_RUNTIME_DIR/berth/serve.sock" -X POST \ -d '{"arguments": {"update": "yes"}, "token": "nightly-2026-11-13"}' \ - http://berth/v1/actions/rollout + http://berth/v1/installation/actions/rollout ``` The token is optional. The same token again for the same subject and action answers with the job the first request started, and nothing runs a second time. That lets a caller that lost the answer ask again. While an action changes a host, a second one that changes it is refused with `409` until the first has ended, and so is a second roll-out. A job is followed with `jobs.get`, `jobs.output` and the `jobs.follow` stream, and the events stream says when it starts and ends. @@ -127,10 +127,10 @@ A caller over TCP shows the server's token or an OAuth 2.0 access token, and act | Role | May | | --- | --- | | `view` | Read what the hosts and the server report, such as sessions with their output, logs, jobs and the inbox | -| `operate` | Work on the hosts with tasks, commands, terminals and files. Units, power and the key-value store are included | +| `operate` | Work on the hosts with actions, commands, terminals and files. Units, power and the key-value store are included | | `admin` | Change profiles, secrets, registries, settings and plugins, apply a profile to a host, and create or delete the machine of a host | -Each action has a role of its own, which is checked when it runs. A host's tasks need `operate`, berth's own actions `admin`. +Each action has a role of its own, which is checked when it runs. The actions of a host's controller need `operate`, berth's own actions `admin`. The server's token is `admin`. The socket doesn't ask for a token and is `admin` too. The [API reference](/docs/api/serve) lists the role of each operation, and [`access`](/docs/api/serve/general) tells a caller its own. diff --git a/docs/content/docs/(guide)/extend/streams.mdx b/docs/content/docs/(guide)/extend/streams.mdx index 8c3890c..05ccd90 100644 --- a/docs/content/docs/(guide)/extend/streams.mdx +++ b/docs/content/docs/(guide)/extend/streams.mdx @@ -13,8 +13,8 @@ output is at `/v1/sessions/{id}`, the channel at `/v1/channel`, and a service's serving connection at `/v1/services/{service}/serve`. Open it with a `GET` and the usual upgrade headers, on the same unix socket as the plain requests. -`berth serve` passes a host's streams through under `/v1/hosts/{name}`, so the -session above is at `/v1/hosts/{name}/sessions/{id}` there, with the same +`berth serve` passes a host's streams through under `/v1/hosts/{name}/controller`, +so the session above is at `/v1/hosts/{name}/controller/sessions/{id}` there, with the same frames. Over TCP the token from `serve.token` goes in an `Authorization: Bearer` header. A browser cannot set a header on a WebSocket, so the token is also accepted as the `Sec-WebSocket-Protocol` value. @@ -65,7 +65,7 @@ that the last viewer to resize it asked for. [`ports.connect`](/docs/api/host/ports) is a TCP connection to a port on the host's loopback, `127.0.0.1`. It is at `/v1/ports/{port}`, and through -`berth serve` at `/v1/hosts/{name}/ports/{port}`. berthd connects to the port +`berth serve` at `/v1/hosts/{name}/controller/ports/{port}`. berthd connects to the port before the handshake, so a port that nothing listens on gives the error `503 not_served`. It needs the role `operate` and the host level. diff --git a/docs/content/docs/(guide)/extend/writing-plugins.mdx b/docs/content/docs/(guide)/extend/writing-plugins.mdx index a3d7283..b6027d1 100644 --- a/docs/content/docs/(guide)/extend/writing-plugins.mdx +++ b/docs/content/docs/(guide)/extend/writing-plugins.mdx @@ -91,7 +91,7 @@ The plugin's id is the package name without its scope and without a leading `ber commands: { type: 'string[]', description: 'Commands the host must have afterwards; added to /etc/devbox/expected-commands, which the self-test checks.' }, tasks: { type: 'string', description: 'Path of an Ansible task list in the package.' }, guide: { type: 'string', description: 'Path of a guide for agents in the package.' }, - actions: { type: 'Action[]', description: "Tasks for the host's overview." }, + actions: { type: 'Action[]', description: "Actions for the host's overview." }, services: { type: 'Service[]', description: 'Programs that keep running on the host and answer calls. See Writing a service.' }, channels: { type: 'Channel[]', description: "Topics of the host's channel the feature uses, with how long messages are kept." }, }} @@ -99,7 +99,7 @@ The plugin's id is the package name without its scope and without a leading `ber ## Actions -An action becomes a task of the host named `PLUGIN:ACTION`. Applying the configuration writes the actions of the chosen features to the host, and they appear on the overview in their group. From the command line: `berth run HOST PLUGIN:ACTION`. +An action becomes an action of the host's controller named `PLUGIN:ACTION`. Applying the configuration writes the actions of the chosen features to the host, and they appear on the overview in their group. From the command line: `berth run HOST PLUGIN:ACTION`. + ## On each host diff --git a/docs/content/docs/(guide)/reference/box.mdx b/docs/content/docs/(guide)/reference/box.mdx index 99565be..74a98ed 100644 --- a/docs/content/docs/(guide)/reference/box.mdx +++ b/docs/content/docs/(guide)/reference/box.mdx @@ -1,6 +1,6 @@ --- title: box -description: The command on every host for the agent's side of berth, from desktop control to tasks, the channel and services. +description: The command on every host for the agent's side of berth, from desktop control to actions, the channel and services. icon: Box --- @@ -10,8 +10,8 @@ icon: Box box desktop screenshot [--output PATH|-] | click X Y [BUTTON] | type TEXT | key CHORD | scroll up|down [STEPS] | clipboard | pause | resume box mcp the desktop tools as an MCP server on stdio box exec [COMMAND...] run a command, or a shell, with the desktop's environment -box tasks the tasks this user may run -box run TASK [NAME=VALUE...] run one; output here, its exit code as box's +box actions the actions this user may run +box run ACTION [NAME=VALUE...] run one; output here, its exit code as box's box publish TOPIC [JSON] [--keep none|last|log] box listen TOPIC-PREFIX [--since ID] one JSON message per line box services what can be called, and whether it is up @@ -58,12 +58,12 @@ box exec xvfb-run -a COMMAND box exec devbox-smoke ``` -## Tasks +## Actions -`box tasks` lists the host's tasks the agent may run, those marked `agent: true`, and `box run` runs one with its plugin steps: +`box actions` lists the host's actions the agent may run, those marked `agent: true`, and `box run` runs one with its plugin steps: ```bash title="As the agent" -box tasks +box actions box run smoke box run sign-in:status ``` diff --git a/docs/content/docs/(guide)/reference/index.mdx b/docs/content/docs/(guide)/reference/index.mdx index 1ba4875..d32fa53 100644 --- a/docs/content/docs/(guide)/reference/index.mdx +++ b/docs/content/docs/(guide)/reference/index.mdx @@ -7,7 +7,7 @@ icon: Library The tool inventory, categories, mise and versions. CPU or GPU rendering, and Xvfb. - The agent's command for the desktop, MCP, tasks, the channel and services. + The agent's command for the desktop, MCP, actions, the channel and services. Files, units, and what agents read. Every field of a host profile. The checks and the upstream references. diff --git a/docs/content/docs/(guide)/reference/on-the-host.mdx b/docs/content/docs/(guide)/reference/on-the-host.mdx index a952c59..291226a 100644 --- a/docs/content/docs/(guide)/reference/on-the-host.mdx +++ b/docs/content/docs/(guide)/reference/on-the-host.mdx @@ -20,7 +20,7 @@ icon: FolderTree - + @@ -58,10 +58,10 @@ icon: FolderTree | `/etc/devbox/guides/` | Longer guides for the desktop, graphics, and each plugin feature with a guide | | `/etc/devbox/expected-commands` | Commands the self-test requires, including those plugins list | | `/etc/devbox/mcp.json` | The desktop MCP server, to merge into an MCP client's configuration | -| `/etc/berth/*.json` | berthd's settings, tasks, services and channel topics | +| `/etc/berth/*.json` | berthd's settings, actions, services and channel topics | | `/etc/berth/applied.json` | The versions of berth and its plugins at the last apply | | `/etc/berth/profile.json` | The host's profile, for root only, which [another berth can adopt](/docs/use/moving) | -| `/usr/local/lib/berth/tasks/` | The scripts of berth's own tasks | +| `/usr/local/lib/berth/tasks/` | The scripts of berth's own actions | | `/var/lib/devbox/provision-state` | The state of the first-boot provisioning | | `/var/lib/devbox/ready` | Written when Ansible converged, with the release's digest | | `/var/lib/devbox/toolchains.json` | The runtime versions that were installed | @@ -96,7 +96,7 @@ GUI programs, T3 Code and the commands it starts share the desktop's `DISPLAY`, ## The self-test -`devbox-smoke` is the **Self-Test** task. It checks: +`devbox-smoke` is the **Self-Test** action. It checks: - that the expected commands exist - llvmpipe on the shared desktop and in Xvfb, and lavapipe enumeration diff --git a/docs/content/docs/(guide)/reference/profile.mdx b/docs/content/docs/(guide)/reference/profile.mdx index 7c47260..830a657 100644 --- a/docs/content/docs/(guide)/reference/profile.mdx +++ b/docs/content/docs/(guide)/reference/profile.mdx @@ -169,7 +169,7 @@ A profile of berth 0.5 or earlier names two fields differently: | `level`: `workstation` | No `type`, which means a workstation | | `profile` | `target` | -berth converts its stored profiles once, the profiles of a berth server's hosts with them. It reads the old names wherever a profile comes from: a file such as `berth ./studio.json`, `berth profile HOST --set FILE`, and the profile a host keeps, which [`berth adopt`](/docs/use/moving) reads. A file keeps the old names until you save it. berth writes the new names only. The API of `berth serve` takes the new names only. +berth converts its stored profiles once, the profiles of a berth server's hosts with them. It reads the old names wherever a profile comes from: a file such as `berth ./studio.json`, `berth profile HOST --set FILE`, and the profile a host keeps, which [`berth adopt`](/docs/use/moving) reads. A file keeps the old names until you save it. berth writes `type` and `target` and nothing else, and the API of `berth serve` takes no other spelling. ## Install (`builder`) diff --git a/docs/content/docs/(guide)/reference/validation.mdx b/docs/content/docs/(guide)/reference/validation.mdx index bec893f..97337c5 100644 --- a/docs/content/docs/(guide)/reference/validation.mdx +++ b/docs/content/docs/(guide)/reference/validation.mdx @@ -16,7 +16,7 @@ CI runs these on every push, without network access to hosts: | `ansible-playbook --syntax-check` | The role | | `cargo fmt`, `cargo clippy` | Formatting and lints | | `vale` | The prose of the README, these docs and the plugin guides | -| `tests/e2e` | berth against a test host in a container. A profile is applied over SSH, and a second time without changes. Then the tests use the host with SSH keys, tasks, terminals, files, secrets and a plugin from a folder. `berth serve` is tested with its roles, its set-up and its page, and with a restore of the installation from its database and key file. They use a development build of berth | +| `tests/e2e` | berth against a test host in a container. A profile is applied over SSH, and a second time without changes. Then the tests use the host with SSH keys, actions, terminals, files, secrets and a plugin from a folder. `berth serve` is tested with its roles, its set-up and its page, and with a restore of the installation from its database and key file. They use a development build of berth | See [Building and releasing](/docs/reference/building#in-containers) for running them locally. @@ -33,7 +33,7 @@ After the first boot, berth reaches the host over SSH and checks: - berthd and a plugin's service run as systemd units, and berthd starts, stops and restarts units and reads the journal - the firewall lets in SSH and nothing else, and SSH takes keys only and refuses root -- the status task ends without failed units, and a second apply in a row doesn't change anything +- the status action ends without failed units, and a second apply in a row doesn't change anything - `berth apply --all --reboot` refuses while a session runs, then reboots the host, waits for it and checks it - the end-to-end tests of commands, berthd's API and secrets diff --git a/docs/content/docs/(guide)/start/concepts.mdx b/docs/content/docs/(guide)/start/concepts.mdx index 23658b8..d503f46 100644 --- a/docs/content/docs/(guide)/start/concepts.mdx +++ b/docs/content/docs/(guide)/start/concepts.mdx @@ -21,10 +21,10 @@ berth has a side on your machine, the *workstation*, and a side on each host. | --- | --- | --- | | `berth` | your machine | Keeps a profile per host and installs it. Manages hosts afterwards from its terminal UI or commands | | The role | the host, once per install or apply | The Ansible role that sets up the host. Every install method runs it | -| `berthd` | the host, as root | Runs tasks, sessions and services and answers the [API](/docs/api/host) | -| `box` | the host, for the agent | Desktop control, tasks the agent may run, the channel and services, from the agent's side ([box](/docs/reference/box)) | +| `berthd` | the host, as root | Runs actions, sessions and services and answers the [API](/docs/api/host) | +| `box` | the host, for the agent | Desktop control, actions the agent may run, the channel and services, from the agent's side ([box](/docs/reference/box)) | | `berth serve` | your machine or a server | One API over all hosts, with an inbox and a key-value store. Other machines' berth can use its hosts ([A berth server](/docs/use/server)) | -| Plugins | both | Optional software, tasks and services, switched on per host ([Plugins](/docs/extend/plugins)) | +| Plugins | both | Optional software, actions and services, switched on per host ([Plugins](/docs/extend/plugins)) | The software berth puts on a host is called *devbox*. The name appears in paths and settings there, such as `/etc/devbox` and `devbox_` variables. @@ -32,13 +32,13 @@ The software berth puts on a host is called *devbox*. The name appears in paths | Term | Meaning | | --- | --- | -| Host | Anything berth reaches and logs in to: a laptop, server, VM or container | +| Host | Anything berth reaches and logs in to, such as a laptop, server, VM or container | | Type | What berth does with a host: `ssh` only logs in, `managed` adds berth's controller, `workstation` applies the whole profile. See [Host types](/docs/use/types) | | Profile | The JSON document that describes one host, from what to install to how it is reached, or a template to start one from. berth keeps it in its store. See [Profile](/docs/reference/profile) | -| Target | What a host is installed on, such as a laptop, a cloud machine or a container. A profile says it as `target` | +| Target | The kind of machine a host is installed on, such as a laptop, a cloud machine or a container. A profile says it as `target` | | Operator | Your account on the host, `ops` by default, for SSH and Cockpit | | Agent | The account the coding agents work in, `agent` by default. The virtual desktop runs as this account. Its sudo rights are its [privileges](/docs/use/accounts) | -| Task | Something a host can do, such as Status or a sign-in, run from its overview or with `berth run HOST TASK`. Plugins add tasks | +| Action | Something a host, a provisioner, a resource or the installation can do. A host's controller has actions such as Status or a sign-in, run from its overview or with `berth run HOST ACTION`. Plugins add actions | | Host level, agent level | berthd answers on two sockets. berth connects at host level, as root. `box` connects at agent level, as the agent. Each call says which levels may use it | ## Connecting to a host diff --git a/docs/content/docs/(guide)/start/quick-start.mdx b/docs/content/docs/(guide)/start/quick-start.mdx index 5b57639..406bc9a 100644 --- a/docs/content/docs/(guide)/start/quick-start.mdx +++ b/docs/content/docs/(guide)/start/quick-start.mdx @@ -77,7 +77,7 @@ The other methods are on [Deploying](/docs/deploy). Once the host has an SSH address, `berth studio` opens its **overview**. Run **Status** to check it, then **Access links and desktop password** for the address of the desktop. - + @@ -94,5 +94,5 @@ Installing a coding agent does not sign it in. Under **Sign-In**, **Sign in to C Tailnet addresses, Cockpit and SSH. Give the agent a GitHub token. - The same tasks without the UI. + The same work without the UI. diff --git a/docs/content/docs/(guide)/use/access.mdx b/docs/content/docs/(guide)/use/access.mdx index 66df2ff..a2e0cfa 100644 --- a/docs/content/docs/(guide)/use/access.mdx +++ b/docs/content/docs/(guide)/use/access.mdx @@ -19,7 +19,7 @@ berth run studio access In the panel, **Alt+R** shows the links as QR codes. Scan one with a phone to open it there. The pairing link of **Use T3 from another device** works the same way. -The desktop link printed by the task includes the password after `#` and signs in by itself, so treat it like the password. The names are the ones `tailscale status` reports for the host, such as `HOST.TAILNET.ts.net` on Tailscale. They need the tailnet's DNS on the machine you browse from, while the tailnet address works without it. berth configures no Funnel or public proxy for them. +The desktop link printed by the action includes the password after `#` and signs in by itself, so treat it like the password. The names are the ones `tailscale status` reports for the host, such as `HOST.TAILNET.ts.net` on Tailscale. They need the tailnet's DNS on the machine you browse from, while the tailnet address works without it. berth configures no Funnel or public proxy for them. ## Joining the tailnet @@ -41,7 +41,7 @@ sudo tailscale serve --bg --https=443 http://127.0.0.1:6080 sudo tailscale serve --bg --https=8443 http://127.0.0.1:3773 ``` -Enable tailnet HTTPS if Tailscale asks for it. The publish task also gives Cockpit the tailnet's trusted certificate in place of its self-signed one. +Enable tailnet HTTPS if Tailscale asks for it. The publish action also gives Cockpit the tailnet's trusted certificate in place of its self-signed one. ### Automatic enrollment keys @@ -78,7 +78,7 @@ Hosts then join with `tailscale up --login-server https://hs.example.org`. Heads | | On Headscale | | --- | --- | | Names | Those of Headscale's MagicDNS, `HOST.BASE_DOMAIN`. berth shows what `tailscale status` reports | -| `tailscale serve`, Funnel | Headscale doesn't offer them, so the desktop and T3 aren't published. The access task shows SSH tunnels for them instead | +| `tailscale serve`, Funnel | Headscale doesn't offer them, so the desktop and T3 aren't published. The access action shows SSH tunnels for them instead | | HTTPS certificates | Headscale doesn't issue them. Cockpit stays on its self-signed certificate, at `https://TAILNET-ADDRESS:9090` | ## The desktop diff --git a/docs/content/docs/(guide)/use/backups.mdx b/docs/content/docs/(guide)/use/backups.mdx index 8965973..247d206 100644 --- a/docs/content/docs/(guide)/use/backups.mdx +++ b/docs/content/docs/(guide)/use/backups.mdx @@ -55,9 +55,9 @@ Run **Apply this configuration**. The schedule is switched on only when a reposi Keep a copy of the repository password somewhere else. Without it the snapshots cannot be read. -## Tasks +## Actions -| Task | Does | +| Action | Does | | --- | --- | | Back up now (`backup:snapshot`) | Takes a snapshot and applies the retention policy; the first run creates the repository | | List snapshots (`backup:list`) | The snapshots in the repository, of this host and of others that share it | diff --git a/docs/content/docs/(guide)/use/cli.mdx b/docs/content/docs/(guide)/use/cli.mdx index d245766..563a7b0 100644 --- a/docs/content/docs/(guide)/use/cli.mdx +++ b/docs/content/docs/(guide)/use/cli.mdx @@ -8,7 +8,7 @@ icon: Terminal With a [berth server](/docs/use/server) set, by `--server` or the `server` setting, the host commands use the server's hosts. Installing, secrets and registries then stay on the server. - + ## Hosts and profiles @@ -81,20 +81,20 @@ Both build commands refuse to start while the profile has problems, and list the With a [berth server](/docs/use/server) set, the server's provisioners, plugins and resources are used. Changing a resource needs the role `admin`, reading its log `operate`, and an action of a provisioner or a resource its own role. See [Provisioners](/docs/deploy/provisioners) and [Resources](/docs/deploy/resources#with-a-berth-server). -## Tasks +## Actions ```bash -berth tasks studio # what the host can do -berth run studio status # run a task; its exit code is berth's +berth actions studio # what the host can do +berth run studio status # run an action; its exit code is berth's berth run studio backup:restore snapshot=latest --yes berth run studio claude:login # a sign-in runs in your terminal ``` -`berth run HOST TASK` runs a task and its plugin steps and leaves with the task's exit code. A task's arguments are given as `NAME=VALUE`, and `--yes` answers its confirmation. `berth manage HOST TASK` is the same command. Tasks that need a terminal, such as sign-ins, run in your terminal over `ssh -t`. +`berth run HOST ACTION` runs an action and its plugin steps and leaves with the action's exit code. An action's arguments are given as `NAME=VALUE`, and `--yes` answers its confirmation. `berth manage HOST ACTION` is the same command. Actions that need a terminal, such as sign-ins, run in your terminal over `ssh -t`. -`berth tasks` lists berth's own actions beside the host's tasks, such as `install-controller`, and says why one cannot run now. A host of the type `ssh` has no tasks yet. +`berth actions` lists berth's own actions beside those of the host's controller, such as `install-controller`, and says why one cannot run now. A host whose type is `ssh` has none of its controller's yet. -When a [berth server](/docs/use/server) keeps the host, `berth tasks` lists the server's actions for the host: its tasks, and berth's own such as `apply` and `seed`. `berth run` runs any of them through the server, which keeps a job of each run ([Actions](/docs/extend/serve#actions)). +When a [berth server](/docs/use/server) keeps the host, `berth actions` lists the server's actions for the host: its controller's, and berth's own such as `apply` and `seed`. `berth run` runs any of them through the server, which keeps a job of each run ([Actions](/docs/extend/serve#actions)). ## Sessions and commands diff --git a/docs/content/docs/(guide)/use/index.mdx b/docs/content/docs/(guide)/use/index.mdx index 96613e6..13382af 100644 --- a/docs/content/docs/(guide)/use/index.mdx +++ b/docs/content/docs/(guide)/use/index.mdx @@ -10,7 +10,7 @@ Once a host is installed, you look after it from berth, from sign-ins and tokens The home screen, the set-up tabs, keys and the mouse. - Tasks, the terminal panel and sessions. + Actions, the terminal panel and sessions. Everything without the UI, for scripts. Use the hosts of a berth serve from another machine. Links, the tailnet, Cockpit and SSH. diff --git a/docs/content/docs/(guide)/use/moving.mdx b/docs/content/docs/(guide)/use/moving.mdx index 3c34e82..3dead46 100644 --- a/docs/content/docs/(guide)/use/moving.mdx +++ b/docs/content/docs/(guide)/use/moving.mdx @@ -24,9 +24,9 @@ The file contains the profile as berth stores it, with a few fields left out: | `wifi` | Yes | The USB installer wrote the same network into the host's network settings | | The machine a provisioner made | Yes | Its record, so it is still a [resource](/docs/deploy/resources) of the host. Its token is a label on the machine and does not grant access | -The file also says its format, the version of the berth that wrote it, the time, and the host's name there. A file of berth 0.4.1 has format 1 and the profile layout of then. Format 2, of berth 0.5, has the [older names](/docs/reference/profile#older-profiles) `level` and `profile`. berth converts both when it adopts the host, and writes format 3. A berth that knows only format 2 refuses a file of format 3 and asks to be updated. +The file also says its format, the version of the berth that wrote it, the time, and the host's name there. A file of berth 0.4.1 has format 1 and the profile layout of then. Format 2, of berth 0.5, has the [older names](/docs/reference/profile#older-profiles) `level` and `profile`. `berth adopt` converts both, and writes format 3. A berth that knows only format 2 refuses a file of format 3 and asks to be updated. -berthd serves the same file to an administrator as `GET /v1/applied/profile`. Through a berth server that is `GET /v1/hosts/NAME/applied/profile`. +berthd serves the same file to an administrator as `GET /v1/applied/profile`. Through a berth server that is `GET /v1/hosts/NAME/controller/applied/profile`. ## Adopt a host diff --git a/docs/content/docs/(guide)/use/overview.mdx b/docs/content/docs/(guide)/use/overview.mdx index 4dd1a3d..19a2402 100644 --- a/docs/content/docs/(guide)/use/overview.mdx +++ b/docs/content/docs/(guide)/use/overview.mdx @@ -1,18 +1,18 @@ --- title: A host's overview -description: The page of a running host, with its tasks, the terminal panel and its sessions. +description: The page of a running host, with its actions, the terminal panel and its sessions. icon: LayoutDashboard --- -Opening an installed host shows its overview, with the connection at the top and the host's tasks in groups below. The host reports its own tasks, and the list changes with what is installed there. +Opening an installed host shows its overview, with the connection at the top and the host's actions in groups below. The host's controller reports its own actions, and the list changes with what is installed there. The line under the title is the host's load, CPU, memory, disk and uptime. Under **Connection**, a line says the host's [type](/docs/use/types), and what the host itself was seen to be when that differs. -## Tasks +## Actions -| Group | Task | Does | +| Group | Action | Does | | --- | --- | --- | | System | Status | Provisioning state and services, graphics and disk space, failed units and the access links, then what plugins report | | | Terminal | A shell on the host in a panel; Space switches between the agent and the SSH user | @@ -30,11 +30,11 @@ The line under the title is the host's load, CPU, memory, disk and uptime. Under When the host was applied before a plugin or berth itself changed, a **Configuration** group at the top says which, such as `claude 1.0.0 → 1.1.0`, with **Apply this configuration** below it ([Updates](/docs/use/updates#hosts-that-are-behind)). -berth's own actions on the host are listed beside its tasks, such as **Install the controller** for a host that is not a workstation. One the host's type or state rules out is marked `not now`, and the Information panel says why and what to do first. A host with the controller alone has only Status, Update, Reboot and the secrets. +berth's own actions on the host are listed beside its controller's, such as **Install the controller** for a host that is not a workstation. One the host's type or state rules out is marked `not now`, and the Information panel says why and what to do first. A host with the controller alone has only Status, Update, Reboot and the secrets. -Plugins add tasks to these groups or bring groups of their own, such as **Backup**. They also add steps to built-in tasks such as Status and Update. A task's output stays on the page. +Plugins add actions to these groups or bring groups of their own, such as **Backup**. They also add steps to built-in actions such as Status and Update. An action's output stays on the page. -Some tasks take arguments, such as which snapshot to restore. Tasks that cannot be undone ask for confirmation first. When the profile says to ask for the SSH user's sudo password, berth asks once and keeps it until it closes. +Some actions take arguments, such as which snapshot to restore. Actions that cannot be undone ask for confirmation first. When the profile says to ask for the SSH user's sudo password, berth asks once and keeps it until it closes. ## Panels @@ -60,7 +60,7 @@ A terminal is a session of the host and keeps running when you leave it. Running ## Unreachable hosts -Instead of the tasks, the overview then says why, and offers: +Instead of the actions, the overview then says why, and offers: | Row | Does | | --- | --- | diff --git a/docs/content/docs/(guide)/use/server.mdx b/docs/content/docs/(guide)/use/server.mdx index f622ee8..99d7c0e 100644 --- a/docs/content/docs/(guide)/use/server.mdx +++ b/docs/content/docs/(guide)/use/server.mdx @@ -141,7 +141,7 @@ The server and the token are in `settings.json` in a folder of your own: It talks to a server over `https` only with a certificate that the system or the Mozilla roots trust. It opens only `http` and `https` links, in the system's browser. -berth-remote has the host list and the overview of each host, where tasks run and sessions open in the terminal panel. **o** on the host list signs out. +berth-remote has the host list and the overview of each host, where actions run and sessions open in the terminal panel. **o** on the host list signs out. With the role `admin` it also sets the server up, with the same screens as the terminal UI: @@ -167,11 +167,11 @@ What needs berth on your own machine stays in the terminal UI. That is the USB i | Works through the server | Stays on a machine with the host's profile | | --- | --- | | `berth list`, and the host list of the home screen and of berth-remote | USB installers: `berth iso` and writing a drive | -| The host's overview with its tasks, sessions and terminal panel | Applying to this machine or an inventory, and container images | +| The host's overview with its actions, sessions and terminal panel | Applying to this machine or an inventory, and container images | | The host commands such as `berth run`, `exec`, `attach` and `channel` | Publishing a release or an image by hand | | The set-up tabs of a host, new hosts, and `berth remove` | | | `berth profile` and `berth credentials` | | -| `berth apply`, `berth seed`, and the **Secrets and registry logins** task | | +| `berth apply`, `berth seed`, and the **Secrets and registry logins** action | | | `berth provisioner`, `berth provision`, `berth instance`, `berth resource` and `berth deploy` | | | `berth secret`, `berth registry` and `berth host` | | | The Plugins tab and `berth plugins` | | diff --git a/docs/content/docs/(guide)/use/sign-ins.mdx b/docs/content/docs/(guide)/use/sign-ins.mdx index 27b7838..dcf9f01 100644 --- a/docs/content/docs/(guide)/use/sign-ins.mdx +++ b/docs/content/docs/(guide)/use/sign-ins.mdx @@ -10,7 +10,7 @@ A new host has the agents installed but nobody signed in. Each sign-in runs on t Under **Sign-In**: -| Task | Signs in | +| Action | Signs in | | --- | --- | | Sign in to Claude Code | Claude Code, from the `claude` plugin | | Sign in to Codex | Codex, from the `codex` plugin | @@ -25,7 +25,7 @@ berth run studio claude:login berth run studio sign-in:status ``` -Pi has no sign-in task. Start `pi` in the terminal and complete its own sign-in. +Pi has no sign-in action. Start `pi` in the terminal and complete its own sign-in. ## GitHub without signing in diff --git a/docs/content/docs/(guide)/use/types.mdx b/docs/content/docs/(guide)/use/types.mdx index 1cc51d1..ef76c54 100644 --- a/docs/content/docs/(guide)/use/types.mdx +++ b/docs/content/docs/(guide)/use/types.mdx @@ -86,9 +86,9 @@ berth host add big 192.0.2.20 --user root --auth ssh berth host install big ``` -`berth host add` saves `big` as a host of the type `ssh`. `--auth ssh` makes berth log in with your own SSH configuration and agent, so the key that works for `ssh root@192.0.2.20` works for berth. The default, `--auth berth`, uses berth's own key, which berth installs on the first contact with a password or a private key that logs in once. `--auth ssh` works with a local berth only. With a [berth server](/docs/use/server) set, the server logs in with its own keys. +`berth host add` saves `big` with the type `ssh`. `--auth ssh` makes berth log in with your own SSH configuration and agent, so the key that works for `ssh root@192.0.2.20` works for berth. The default, `--auth berth`, uses berth's own key, which berth installs on the first contact with a password or a private key that logs in once. `--auth ssh` works with a local berth only. With a [berth server](/docs/use/server) set, the server logs in with its own keys. -`berth host install big` puts the controller alone on the server. berth can then report its status and run commands there, and it can update and reboot the server. Sessions run as the SSH user, here `root`. berth does not apply such a server as a workstation. It stays a host of the type `ssh` or `managed`, and the machines on it are created with the Incus or Docker provisioner. +`berth host install big` puts the controller alone on the server. berth can then report its status and run commands there, and it can update and reboot the server. Sessions run as the SSH user, here `root`. berth does not apply such a server as a workstation. Its type stays `ssh` or `managed`, and the machines on it are created with the Incus or Docker provisioner. The recipes are in [`recipes/`](https://github.com/helightdev/berth/tree/main/recipes): `rescue-install` installs Ubuntu, and `incus-host` makes the server a host for machines. @@ -102,7 +102,7 @@ The controller is berthd and box with the files they read, from the same part of The same is the host's action **Install the controller** on its overview, in berth-remote and over the API as `install-controller`. On a managed host it's called **Update the controller**: run it after updating berth, as berth's own version is all such a host is compared with. A workstation's controller comes with applying its configuration, so the action is not offered there. -berth also refuses it on a host that is a workstation whatever its profile here says. It asks the host's controller first. The role checks again on the host before it changes anything. It stops when the host's record says workstation. It also stops when berthd there serves an account other than the SSH user. Installing the controller alone on such a host would take the workstation's controller apart. The overview and `berth tasks` say when a host is more than its profile, and how to adopt it. +berth also refuses it on a host that is a workstation whatever its profile here says. It asks the host's controller first. The role checks again on the host before it changes anything. It stops when the host's record says workstation. It also stops when berthd there serves an account other than the SSH user. Installing the controller alone on such a host would take the workstation's controller apart. The overview and `berth actions` say when a host is more than its profile, and how to adopt it. On a host with systemd the controller is a service that starts at boot. Without systemd, as in most containers, the controller is installed but nothing on the host starts it. berth says so and waits a minute for it to answer. The install fails when it doesn't. Something on the host then has to run `/usr/local/bin/berthd`, as the init of a container can. diff --git a/docs/content/docs/(guide)/use/updates.mdx b/docs/content/docs/(guide)/use/updates.mdx index 57710c1..3ef5022 100644 --- a/docs/content/docs/(guide)/use/updates.mdx +++ b/docs/content/docs/(guide)/use/updates.mdx @@ -14,7 +14,7 @@ Ubuntu security updates and Firefox's vendor updates install automatically. The | --- | --- | | **Update** on the overview, or `berth run HOST update` | `apt` update and `dist-upgrade`, then Claude Code, Codex, Pi, T3 Code and the Unity CLI to their latest versions, through their plugins | | **Reboot**, or `berth run HOST reboot` | Restarts the host to finish updates | -| **Apply this configuration** | Runs the role again, which brings new or changed features and settings, berthd and box, and plugin tasks and services | +| **Apply this configuration** | Runs the role again, which brings new or changed features and settings, berthd and box, and plugin actions and services | | `berth plugins update` | Your plugins, to the latest version of their registry ([Updating a plugin](/docs/extend/plugins#updating-a-plugin)) | The versions in the defaults (`devbox_claude_version`, `devbox_codex_version`, `devbox_pi_version`, `devbox_t3_version`) are the least ones, so applying the configuration again does not go back to them after an update. Claude Code's own self-update is off. @@ -28,7 +28,7 @@ berth update # download it, check its SHA-256 and replace this progr `berth update` takes the same archive as the install script. It offers only full releases, not pre-releases such as `0.4.0-rc.1`, and moves from a pre-release to its release. A container is updated by pulling a newer image. `berthd` and `box` travel inside `berth`. A host gets the new ones when you apply its configuration. Its overview says when its tools are of another version than your berth. -A berthd of berth 0.5 says the host's type by its older name, and berth reads it. An older berth that meets a newer berthd is out of date: update it. It refuses the profile a newer berth left on the host rather than misread it. `BERTH_RELEASES` names a mirror of the releases page. +A berthd of berth 0.5 says the host's type by its older name, and berth reads it. For sessions, actions and files berth needs the berthd of API 2, and until then the overview offers to install the controller or apply the configuration, which brings berthd up to date. An older berth that meets a newer berthd is out of date: update it. It refuses the profile a newer berth left on the host rather than misread it. `BERTH_RELEASES` names a mirror of the releases page. ## Hosts that are behind @@ -44,11 +44,11 @@ berth apply --behind --update --reboot # and run Update, and reboot where need berth plugins update --apply # update the plugins, then the same ``` -The hosts are taken one at a time, by name. Each is applied and then checked. Its berthd has to answer with this berth's version and the host must no longer be behind. Its Status task has to end well too. Hosts that are current are skipped. The first host that fails stops the roll-out, and the hosts after it are not touched. +The hosts are taken one at a time, by name. Each is applied and then checked. Its berthd has to answer with this berth's version and the host must no longer be behind. Its Status action has to end well too. Hosts that are current are skipped. The first host that fails stops the roll-out, and the hosts after it are not touched. | Option | Does | | --- | --- | -| `--update` | Runs the host's Update task after applying. If it ends badly, that host is finished and the roll-out stops after it | +| `--update` | Runs the host's Update action after applying. If it ends badly, that host is finished and the roll-out stops after it | | `--reboot` | Reboots a host that says it needs it, waits up to ten minutes for it to answer again, then checks it. A host with running sessions is not rebooted, and the roll-out stops there | | `--force` | Reboots also while sessions run, which ends them | | `--all` | Applies the hosts that are current too | @@ -65,7 +65,7 @@ A task, service or channel topic a plugin no longer has is gone after applying. Applying does not restart desktops that are already running or turns an agent is in the middle of. After changing versions, a service's environment or unit files, restart the agent's user services in a quiet moment, or reboot. -Applying restarts berthd only when its program or unit changed, because a restart ends the sessions it holds. New tasks, services and channel topics only need a reload, which applying does. +Applying restarts berthd only when its program or unit changed, because a restart ends the sessions it holds. New actions, services and channel topics only need a reload, which applying does. ## What berth does not do diff --git a/docs/content/docs/api/index.mdx b/docs/content/docs/api/index.mdx index e29da33..a5512cd 100644 --- a/docs/content/docs/api/index.mdx +++ b/docs/content/docs/api/index.mdx @@ -11,7 +11,7 @@ berthd and `berth serve` answer the same kind of API. Each of their *operations* | berthd | every host, as root | unix sockets in `/run/berth` | [berthd](/docs/api/host) | | `berth serve` | your machine, or a server | a unix socket of your user, and optionally TCP | [berth serve](/docs/api/serve) | -`berth serve` passes berthd's operations through to the host it names, so a program that talks to `berth serve` reaches all hosts. It also lists what can be done to each host and to the installation as [actions](/docs/extend/serve#actions), and runs one as a job it keeps. +`berth serve` passes berthd's operations through to the host it names, under `/v1/hosts/NAME/controller`, so a program that talks to `berth serve` reaches all hosts. It also lists what can be done to each host and to the installation as [actions](/docs/extend/serve#actions), and runs one as a job it keeps. ## Ways to call an operation @@ -34,7 +34,21 @@ A *call* takes arguments and input and gives back a result. After it opens, a *s | `api` | Added | | --- | --- | | 1 | The API as first released | -| 2 | `ports.connect` with windows on the portal's streams, roles from the keys of an object claim, the `dropped` frame of `events.follow`, `inbox.follow` and `kv.follow`, and host and resource changes on `events.follow` | +| 2 | `ports.connect` with windows on the portal's streams, roles from the keys of an object claim, the `dropped` frame of `events.follow`, `inbox.follow` and `kv.follow`, and host and resource changes on `events.follow`. It also renames, and breaks what a client of number 1 calls: see below | + +What number 2 renames, with no old name kept: + +| Number 1 | Number 2 | +| --- | --- | +| `tasks.list`, `tasks.run`, `tasks.choices` at `/v1/tasks…` | `actions.list`, `actions.run`, `actions.choices` at `/v1/actions…`, with the action's name as `action` | +| The schemas `Task`, `RunTask`, `PluginTask` and a feature's `tasks` | `HostAction`, `RunAction`, `PluginAction` and `actions` | +| A session's `task` | `action` | +| `actions.list`, `actions.act` of `berth serve` at `/v1/actions…` | `installation.actions`, `installation.act` at `/v1/installation/actions…` | +| A host's operations through `berth serve` at `/v1/hosts/NAME/…` | `/v1/hosts/NAME/controller/…`, so that none meets the server's own routes of a host | +| `level` of `version` and `hosts.get`, with `reachable`, `controller`, `workstation` | `type`, with `ssh`, `managed`, `workstation` | +| `level` and `profile` in a profile that `hosts.save` takes | `type` and `target` | + +berth reads what a berthd of number 1 says of the host's type. It needs number 2 for everything else, and says to update the controller or apply the host until it has it. ## Who may call diff --git a/docs/content/docs/api/portal.mdx b/docs/content/docs/api/portal.mdx index 0f06da0..6e0806e 100644 --- a/docs/content/docs/api/portal.mdx +++ b/docs/content/docs/api/portal.mdx @@ -43,11 +43,11 @@ An unknown operation is `404`, and a missing argument is `400`. On the portal of `berth serve`, `host` names the host and the rest of the frame is the host's operation, exactly as berthd takes it: ```js -→ {"id": 9, "host": "studio", "op": "tasks.run", "args": {"name": "status"}} +→ {"id": 9, "host": "studio", "op": "actions.run", "args": {"action": "status"}} ← {"id": 9, "result": {"id": "a81kq0wd3m5c"}} ``` -`berth serve` refuses the `secrets` task, because the secrets stay on the machine that runs it. +`berth serve` refuses the controller's own `secrets` action, because the secrets stay on the machine that runs it. ## A stream diff --git a/docs/openapi/berth.asyncapi.json b/docs/openapi/berth.asyncapi.json index 69f9478..f4033f6 100644 --- a/docs/openapi/berth.asyncapi.json +++ b/docs/openapi/berth.asyncapi.json @@ -40,7 +40,7 @@ "x-berth-resumable": false }, "host.channel": { - "address": "/v1/hosts/{name}/channel", + "address": "/v1/hosts/{name}/controller/channel", "bindings": { "ws": { "query": { @@ -76,7 +76,7 @@ "x-berth-resumable": true }, "host.logs": { - "address": "/v1/hosts/{name}/logs", + "address": "/v1/hosts/{name}/controller/logs", "bindings": { "ws": { "query": { @@ -109,7 +109,7 @@ "x-berth-resumable": true }, "host.port": { - "address": "/v1/hosts/{name}/ports/{port}", + "address": "/v1/hosts/{name}/controller/ports/{port}", "bindings": { "ws": { "query": { @@ -139,7 +139,7 @@ "x-berth-resumable": false }, "host.serve": { - "address": "/v1/hosts/{name}/services/{service}/serve", + "address": "/v1/hosts/{name}/controller/services/{service}/serve", "bindings": { "ws": { "query": { @@ -172,7 +172,7 @@ "x-berth-resumable": false }, "host.session": { - "address": "/v1/hosts/{name}/sessions/{id}", + "address": "/v1/hosts/{name}/controller/sessions/{id}", "bindings": { "ws": { "query": { @@ -895,7 +895,7 @@ }, "defaultContentType": "application/json", "info": { - "description": "The WebSockets of berth serve: its own, and each host's under /v1/hosts/{name}. Text frames are JSON, one message each; binary frames carry only session and job bytes.", + "description": "The WebSockets of berth serve: its own, and each host's under /v1/hosts/{name}/controller. Text frames are JSON, one message each; binary frames carry only session and job bytes.", "title": "berth serve", "version": "0.5.2" }, diff --git a/docs/openapi/berth.openapi.json b/docs/openapi/berth.openapi.json index c5cc28e..8e9b7bf 100644 --- a/docs/openapi/berth.openapi.json +++ b/docs/openapi/berth.openapi.json @@ -720,6 +720,66 @@ ], "type": "object" }, + "HostAction": { + "description": "An action of the host's controller: an entry of `/etc/berth/actions.json`.\nListed without `run`.", + "properties": { + "agent": { + "description": "The agent may run it.", + "type": "boolean" + }, + "arguments": { + "items": { + "$ref": "#/components/schemas/Argument" + }, + "type": "array" + }, + "confirm": { + "type": [ + "string", + "null" + ] + }, + "extends": { + "description": "Actions it is a step of; it then has no row of its own.", + "items": { + "type": "string" + }, + "type": "array" + }, + "group": { + "type": "string" + }, + "help": { + "type": "string" + }, + "input": { + "description": "What the workstation sends on standard input: `secrets`.", + "type": [ + "string", + "null" + ] + }, + "label": { + "type": "string" + }, + "name": { + "type": "string" + }, + "run": { + "type": "string" + }, + "terminal": { + "type": "boolean" + }, + "user": { + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, "HostBehind": { "allOf": [ { @@ -1421,9 +1481,55 @@ ], "type": "object" }, + "PluginAction": { + "description": "An action a feature adds to a host.", + "properties": { + "agent": { + "description": "The agent may run it with `box run`.", + "type": "boolean" + }, + "arguments": { + "description": "The names of the arguments it asks for.", + "items": { + "type": "string" + }, + "type": "array" + }, + "extends": { + "description": "Actions of berth it runs after, with no row of its own.", + "items": { + "type": "string" + }, + "type": "array" + }, + "label": { + "type": "string" + }, + "name": { + "description": "The action is `PLUGIN:NAME` on the host.", + "type": "string" + }, + "user": { + "description": "`agent`, `operator` or `root`.", + "type": "string" + } + }, + "required": [ + "name", + "label", + "user" + ], + "type": "object" + }, "PluginFeature": { "description": "Something a plugin installs, switched on per host.", "properties": { + "actions": { + "items": { + "$ref": "#/components/schemas/PluginAction" + }, + "type": "array" + }, "channels": { "description": "Channel topics, without the plugin's id.", "items": { @@ -1450,12 +1556,6 @@ "$ref": "#/components/schemas/PluginService" }, "type": "array" - }, - "tasks": { - "items": { - "$ref": "#/components/schemas/PluginTask" - }, - "type": "array" } }, "required": [ @@ -1602,46 +1702,6 @@ ], "type": "object" }, - "PluginTask": { - "description": "A task a feature adds to a host's overview.", - "properties": { - "agent": { - "description": "The agent may run it with `box run`.", - "type": "boolean" - }, - "arguments": { - "description": "The names of the arguments it asks for.", - "items": { - "type": "string" - }, - "type": "array" - }, - "extends": { - "description": "Tasks of berth it runs after, with no row of its own.", - "items": { - "type": "string" - }, - "type": "array" - }, - "label": { - "type": "string" - }, - "name": { - "description": "The task is `PLUGIN:NAME` on the host.", - "type": "string" - }, - "user": { - "description": "`agent`, `operator` or `root`.", - "type": "string" - } - }, - "required": [ - "name", - "label", - "user" - ], - "type": "object" - }, "PluginUpdate": { "description": "Whether a newer version of a plugin is there, as its registry says.", "properties": { @@ -2238,7 +2298,7 @@ ], "type": "string" }, - "RunTask": { + "RunAction": { "properties": { "arguments": { "additionalProperties": { @@ -2452,6 +2512,13 @@ }, "Session": { "properties": { + "action": { + "description": "The action it was started for, if any. The sessions an older\nberthd kept on the host say `task`.", + "type": [ + "string", + "null" + ] + }, "cols": { "format": "int32", "minimum": 0, @@ -2520,13 +2587,6 @@ }, "type": "array" }, - "task": { - "description": "The task it was started for, if any.", - "type": [ - "string", - "null" - ] - }, "title": { "type": "string" }, @@ -2877,66 +2937,6 @@ ], "type": "object" }, - "Task": { - "description": "An entry of `/etc/berth/tasks.json`. Listed without `run`.", - "properties": { - "agent": { - "description": "The agent may run it.", - "type": "boolean" - }, - "arguments": { - "items": { - "$ref": "#/components/schemas/Argument" - }, - "type": "array" - }, - "confirm": { - "type": [ - "string", - "null" - ] - }, - "extends": { - "description": "Tasks it is a step of; it then has no row of its own.", - "items": { - "type": "string" - }, - "type": "array" - }, - "group": { - "type": "string" - }, - "help": { - "type": "string" - }, - "input": { - "description": "What the workstation sends on standard input: `secrets`.", - "type": [ - "string", - "null" - ] - }, - "label": { - "type": "string" - }, - "name": { - "type": "string" - }, - "run": { - "type": "string" - }, - "terminal": { - "type": "boolean" - }, - "user": { - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - }, "Topic": { "description": "An entry of `/etc/berth/channels.json`.", "properties": { @@ -3063,7 +3063,7 @@ } }, "info": { - "description": "One API over all hosts, with the inbox and a key-value store. Everything under /v1/hosts/{name}/ that is not named here is that host's own API, passed through unchanged; only the `secrets` task is refused, which the host's `secrets` action stands in for. What can be done to a host or to the installation is listed at /v1/hosts/{name}/actions and /v1/actions, and run by POST to an action's name there. Over TCP every request carries the server's token or an OAuth 2.0 access token as a bearer, and needs the role its operation names. The routes of the setup key take that key as the bearer instead.", + "description": "One API over all hosts, with the inbox and a key-value store. Everything under /v1/hosts/{name}/controller/ is that host's own API, passed through unchanged; only the controller's own `secrets` action is refused, which the server's `secrets` action of the host stands in for. What can be done to a host or to the installation is listed at /v1/hosts/{name}/actions and /v1/installation/actions, and run by POST to an action's name there. Over TCP every request carries the server's token or an OAuth 2.0 access token as a bearer, and needs the role its operation names. The routes of the setup key take that key as the bearer instead.", "title": "berth serve", "version": "0.5.2" }, @@ -3090,166 +3090,53 @@ ] } }, - "/v1/actions": { + "/v1/events": { "get": { - "operationId": "list", + "operationId": "stream_events", + "parameters": [], + "responses": { + "101": { + "description": "A WebSocket; its frames are in the AsyncAPI document" + } + }, + "summary": "Channel messages of chosen hosts, jobs, key-value changes and changes to hosts and resources together. The first frame sent names what to follow; each frame received says where it came from.", + "tags": [ + "streams" + ] + } + }, + "/v1/hosts": { + "get": { + "operationId": "hosts", "responses": { "200": { "content": { "application/json": { "schema": { "items": { - "$ref": "#/components/schemas/Action" + "$ref": "#/components/schemas/HostInfo" }, "type": "array" } } }, - "description": "The actions" + "description": "The saved hosts and whether each answers" } }, - "summary": "What can be done to the installation as a whole, such as a roll-out over its hosts.", + "summary": "The saved hosts and whether each answers.", "tags": [ "hosts" ] } }, - "/v1/actions/{action}": { - "post": { - "operationId": "act", + "/v1/hosts/{name}": { + "delete": { + "operationId": "remove_host", "parameters": [ { - "description": "The action, as actions.list names it", + "description": "A saved host", "in": "path", - "name": "action", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "oneOf": [ - { - "$ref": "#/components/schemas/Act" - }, - { - "type": "null" - } - ] - } - } - }, - "description": "Its arguments, and a token that makes asking again safe" - }, - "responses": { - "202": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Acted" - } - } - }, - "description": "Started as a job" - }, - "400": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorBody" - } - } - }, - "description": "An argument is wrong, or the body is not one" - }, - "403": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorBody" - } - } - }, - "description": "The caller's role is below the action's" - }, - "404": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorBody" - } - } - }, - "description": "No such action, or a host it names" - }, - "409": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorBody" - } - } - }, - "description": "Another one is running" - } - }, - "summary": "Run one of the installation's actions, as a job.", - "tags": [ - "hosts" - ] - } - }, - "/v1/events": { - "get": { - "operationId": "stream_events", - "parameters": [], - "responses": { - "101": { - "description": "A WebSocket; its frames are in the AsyncAPI document" - } - }, - "summary": "Channel messages of chosen hosts, jobs, key-value changes and changes to hosts and resources together. The first frame sent names what to follow; each frame received says where it came from.", - "tags": [ - "streams" - ] - } - }, - "/v1/hosts": { - "get": { - "operationId": "hosts", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "items": { - "$ref": "#/components/schemas/HostInfo" - }, - "type": "array" - } - } - }, - "description": "The saved hosts and whether each answers" - } - }, - "summary": "The saved hosts and whether each answers.", - "tags": [ - "hosts" - ] - } - }, - "/v1/hosts/{name}": { - "delete": { - "operationId": "remove_host", - "parameters": [ - { - "description": "A saved host", - "in": "path", - "name": "name", + "name": "name", "required": true, "schema": { "type": "string" @@ -3373,7 +3260,7 @@ "description": "No such host" } }, - "summary": "What can be done to a host: the tasks its controller lists, and berth's own actions.", + "summary": "What can be done to a host: the actions its controller lists, and berth's own.", "tags": [ "hosts" ] @@ -3438,7 +3325,7 @@ } } }, - "description": "Started as a job; a task of the host also says its session" + "description": "Started as a job; an action of its controller also says its session" }, "400": { "content": { @@ -3501,16 +3388,16 @@ "description": "The host could not be reached" } }, - "summary": "Run one of a host's actions. One of berth's that changes something is a job; a task of the host is a session there, which a job follows unless it needs a terminal.", + "summary": "Run one of a host's actions. One of berth's that changes something is a job; an action of the host's controller is a session there, which a job follows unless it needs a terminal.", "tags": [ "hosts" ] } }, - "/v1/hosts/{name}/applied/profile": { + "/v1/hosts/{name}/controller/actions": { "get": { - "description": "Host level only.", - "operationId": "host_get_v1_applied_profile", + "description": "Host and agent level.", + "operationId": "host_get_v1_actions", "parameters": [ { "description": "A saved host", @@ -3527,7 +3414,10 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/KeptProfile" + "items": { + "$ref": "#/components/schemas/HostAction" + }, + "type": "array" } } }, @@ -3544,16 +3434,16 @@ "description": "An error." } }, - "summary": "The profile the host keeps of itself, as the last apply or the first boot wrote it.", + "summary": "The actions the caller may run, in the order of the file.", "tags": [ - "host: applied" + "host: actions" ] } }, - "/v1/hosts/{name}/channel": { - "get": { + "/v1/hosts/{name}/controller/actions/{action}": { + "post": { "description": "Host and agent level.", - "operationId": "host_get_v1_channel", + "operationId": "host_post_v1_actions__action_", "parameters": [ { "description": "A saved host", @@ -3565,39 +3455,37 @@ } }, { - "description": "Only topics starting with this.", - "in": "query", - "name": "topic", - "schema": { - "type": "string" - } - }, - { - "description": "Messages after this id; default 0.", - "in": "query", - "name": "since", + "in": "path", + "name": "action", + "required": true, "schema": { "type": "string" } }, { - "description": "Most messages; default 100, at most 1000.", + "description": "A duration such as 30s, at most 10m: answer when the command has ended, with what it wrote.", "in": "query", - "name": "limit", + "name": "wait", "schema": { "type": "string" } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RunAction" + } + } + } + }, "responses": { - "101": { - "description": "With a WebSocket handshake: the stream `channel` of the AsyncAPI document." - }, "200": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Messages" + "$ref": "#/components/schemas/Started" } } }, @@ -3614,16 +3502,16 @@ "description": "An error." } }, - "summary": "Kept messages after `since`.", + "summary": "Run an action. It and what extends it are the steps of one session.", "tags": [ - "host: channel" + "host: actions" ] } }, - "/v1/hosts/{name}/channel/{topic}": { - "post": { + "/v1/hosts/{name}/controller/actions/{action}/choices/{argument}": { + "get": { "description": "Host and agent level.", - "operationId": "host_post_v1_channel___topic_", + "operationId": "host_get_v1_actions__action__choices__argument_", "parameters": [ { "description": "A saved host", @@ -3636,28 +3524,27 @@ }, { "in": "path", - "name": "topic", + "name": "action", "required": true, "schema": { "type": "string" } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Publish" - } + }, + { + "in": "path", + "name": "argument", + "required": true, + "schema": { + "type": "string" } } - }, + ], "responses": { "200": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Message" + "$ref": "#/components/schemas/Choices" } } }, @@ -3674,15 +3561,16 @@ "description": "An error." } }, - "summary": "Publish a message on a topic.", + "summary": "The values to offer for an argument.", "tags": [ - "host: channel" + "host: actions" ] } }, - "/v1/hosts/{name}/credentials": { + "/v1/hosts/{name}/controller/applied/profile": { "get": { - "operationId": "credentials", + "description": "Host level only.", + "operationId": "host_get_v1_applied_profile", "parameters": [ { "description": "A saved host", @@ -3699,13 +3587,13 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Credentials" + "$ref": "#/components/schemas/KeptProfile" } } }, - "description": "The passwords by account; none when none were generated" + "description": "Done." }, - "404": { + "default": { "content": { "application/json": { "schema": { @@ -3713,19 +3601,19 @@ } } }, - "description": "No such host" + "description": "An error." } }, - "summary": "The passwords the server generated for a host's accounts.", + "summary": "The profile the host keeps of itself, as the last apply or the first boot wrote it.", "tags": [ - "set-up" + "host: applied" ] } }, - "/v1/hosts/{name}/files": { - "delete": { - "description": "Host level only.", - "operationId": "host_delete_v1_files", + "/v1/hosts/{name}/controller/channel": { + "get": { + "description": "Host and agent level.", + "operationId": "host_get_v1_channel", "parameters": [ { "description": "A saved host", @@ -3737,28 +3625,39 @@ } }, { - "description": "An absolute path under a root.", + "description": "Only topics starting with this.", "in": "query", - "name": "path", + "name": "topic", "schema": { "type": "string" } }, { - "description": "true for a folder with its contents.", + "description": "Messages after this id; default 0.", "in": "query", - "name": "recursive", + "name": "since", + "schema": { + "type": "string" + } + }, + { + "description": "Most messages; default 100, at most 1000.", + "in": "query", + "name": "limit", "schema": { "type": "string" } } ], "responses": { + "101": { + "description": "With a WebSocket handshake: the stream `channel` of the AsyncAPI document." + }, "200": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Done" + "$ref": "#/components/schemas/Messages" } } }, @@ -3775,14 +3674,16 @@ "description": "An error." } }, - "summary": "Remove a file or an empty folder; never a root itself.", + "summary": "Kept messages after `since`.", "tags": [ - "host: files" + "host: channel" ] - }, - "get": { - "description": "Host level only.", - "operationId": "host_get_v1_files", + } + }, + "/v1/hosts/{name}/controller/channel/{topic}": { + "post": { + "description": "Host and agent level.", + "operationId": "host_post_v1_channel___topic_", "parameters": [ { "description": "A saved host", @@ -3794,20 +3695,137 @@ } }, { - "description": "An absolute path under a root.", - "in": "query", - "name": "path", + "in": "path", + "name": "topic", + "required": true, "schema": { "type": "string" } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Publish" + } + } + } + }, "responses": { "200": { "content": { - "application/octet-stream": { + "application/json": { "schema": { - "format": "binary", + "$ref": "#/components/schemas/Message" + } + } + }, + "description": "Done." + }, + "default": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "An error." + } + }, + "summary": "Publish a message on a topic.", + "tags": [ + "host: channel" + ] + } + }, + "/v1/hosts/{name}/controller/files": { + "delete": { + "description": "Host level only.", + "operationId": "host_delete_v1_files", + "parameters": [ + { + "description": "A saved host", + "in": "path", + "name": "name", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "An absolute path under a root.", + "in": "query", + "name": "path", + "schema": { + "type": "string" + } + }, + { + "description": "true for a folder with its contents.", + "in": "query", + "name": "recursive", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Done" + } + } + }, + "description": "Done." + }, + "default": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "An error." + } + }, + "summary": "Remove a file or an empty folder; never a root itself.", + "tags": [ + "host: files" + ] + }, + "get": { + "description": "Host level only.", + "operationId": "host_get_v1_files", + "parameters": [ + { + "description": "A saved host", + "in": "path", + "name": "name", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "An absolute path under a root.", + "in": "query", + "name": "path", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/octet-stream": { + "schema": { + "format": "binary", "type": "string" } } @@ -3898,7 +3916,7 @@ ] } }, - "/v1/hosts/{name}/logs": { + "/v1/hosts/{name}/controller/logs": { "get": { "description": "Host level only.", "operationId": "host_get_v1_logs", @@ -3971,7 +3989,7 @@ ] } }, - "/v1/hosts/{name}/ports/{port}": { + "/v1/hosts/{name}/controller/ports/{port}": { "get": { "description": "Host level only.", "operationId": "host_get_v1_ports__port_", @@ -4015,7 +4033,7 @@ ] } }, - "/v1/hosts/{name}/power/{verb}": { + "/v1/hosts/{name}/controller/power/{verb}": { "post": { "description": "Host level only.", "operationId": "host_post_v1_power__verb_", @@ -4074,7 +4092,7 @@ ] } }, - "/v1/hosts/{name}/processes": { + "/v1/hosts/{name}/controller/processes": { "get": { "description": "Host level only.", "operationId": "host_get_v1_processes", @@ -4120,7 +4138,7 @@ ] } }, - "/v1/hosts/{name}/processes/{pid}/signal": { + "/v1/hosts/{name}/controller/processes/{pid}/signal": { "post": { "description": "Host level only.", "operationId": "host_post_v1_processes__pid__signal", @@ -4180,96 +4198,7 @@ ] } }, - "/v1/hosts/{name}/profile": { - "get": { - "operationId": "profile", - "parameters": [ - { - "description": "A saved host", - "in": "path", - "name": "name", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": {} - } - }, - "description": "The profile, with the passwords and keys in it" - }, - "404": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorBody" - } - } - }, - "description": "No such host" - } - }, - "summary": "A host's profile, as it is saved.", - "tags": [ - "set-up" - ] - }, - "put": { - "operationId": "save_profile", - "parameters": [ - { - "description": "The name to save it under: letters, digits, `-`, `_` and `.`", - "in": "path", - "name": "name", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {} - } - }, - "description": "The whole profile. A workstation's has a builder object; a host of the type ssh or managed needs only type and access", - "required": true - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Done" - } - } - }, - "description": "Saved" - }, - "400": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorBody" - } - } - }, - "description": "Not a profile, or not a name" - } - }, - "summary": "Save a host's profile: a new host, or a changed one. A host that is not a workstation needs only its type and access.", - "tags": [ - "set-up" - ] - } - }, - "/v1/hosts/{name}/reload": { + "/v1/hosts/{name}/controller/reload": { "post": { "description": "Host level only.", "operationId": "host_post_v1_reload", @@ -4312,7 +4241,7 @@ ] } }, - "/v1/hosts/{name}/screenshot": { + "/v1/hosts/{name}/controller/screenshot": { "get": { "description": "Host level only.", "operationId": "host_get_v1_screenshot", @@ -4356,7 +4285,7 @@ ] } }, - "/v1/hosts/{name}/services": { + "/v1/hosts/{name}/controller/services": { "get": { "description": "Host and agent level.", "operationId": "host_get_v1_services", @@ -4402,7 +4331,7 @@ ] } }, - "/v1/hosts/{name}/services/{plugin}/{name}/serve": { + "/v1/hosts/{name}/controller/services/{plugin}/{name}/serve": { "get": { "description": "Host and agent level.", "operationId": "host_get_v1_services__plugin___name__serve", @@ -4454,7 +4383,7 @@ ] } }, - "/v1/hosts/{name}/services/{plugin}/{name}/{method}": { + "/v1/hosts/{name}/controller/services/{plugin}/{name}/{method}": { "post": { "description": "Host and agent level.", "operationId": "host_post_v1_services__plugin___name___method_", @@ -4526,7 +4455,7 @@ ] } }, - "/v1/hosts/{name}/sessions": { + "/v1/hosts/{name}/controller/sessions": { "get": { "description": "Host level only.", "operationId": "host_get_v1_sessions", @@ -4630,7 +4559,7 @@ ] } }, - "/v1/hosts/{name}/sessions/{id}": { + "/v1/hosts/{name}/controller/sessions/{id}": { "delete": { "description": "Host level only.", "operationId": "host_delete_v1_sessions__id_", @@ -4727,13 +4656,13 @@ "description": "An error." } }, - "summary": "One session's state. The agent sees those it started through a task.", + "summary": "One session's state. The agent sees those it started through an action.", "tags": [ "host: sessions" ] } }, - "/v1/hosts/{name}/sessions/{id}/input": { + "/v1/hosts/{name}/controller/sessions/{id}/input": { "post": { "description": "Host level only.", "operationId": "host_post_v1_sessions__id__input", @@ -4793,7 +4722,7 @@ ] } }, - "/v1/hosts/{name}/sessions/{id}/output": { + "/v1/hosts/{name}/controller/sessions/{id}/output": { "get": { "description": "Host and agent level.", "operationId": "host_get_v1_sessions__id__output", @@ -4892,7 +4821,7 @@ ] } }, - "/v1/hosts/{name}/sessions/{id}/resize": { + "/v1/hosts/{name}/controller/sessions/{id}/resize": { "post": { "description": "Host level only.", "operationId": "host_post_v1_sessions__id__resize", @@ -4952,7 +4881,7 @@ ] } }, - "/v1/hosts/{name}/sessions/{id}/screen": { + "/v1/hosts/{name}/controller/sessions/{id}/screen": { "get": { "description": "Host and agent level.", "operationId": "host_get_v1_sessions__id__screen", @@ -5019,7 +4948,7 @@ ] } }, - "/v1/hosts/{name}/sessions/{id}/signal": { + "/v1/hosts/{name}/controller/sessions/{id}/signal": { "post": { "description": "Host level only.", "operationId": "host_post_v1_sessions__id__signal", @@ -5079,7 +5008,7 @@ ] } }, - "/v1/hosts/{name}/stats": { + "/v1/hosts/{name}/controller/stats": { "get": { "description": "Host level only.", "operationId": "host_get_v1_stats", @@ -5122,10 +5051,10 @@ ] } }, - "/v1/hosts/{name}/tasks": { + "/v1/hosts/{name}/controller/units": { "get": { - "description": "Host and agent level.", - "operationId": "host_get_v1_tasks", + "description": "Host level only.", + "operationId": "host_get_v1_units", "parameters": [ { "description": "A saved host", @@ -5143,7 +5072,7 @@ "application/json": { "schema": { "items": { - "$ref": "#/components/schemas/Task" + "$ref": "#/components/schemas/Unit" }, "type": "array" } @@ -5162,16 +5091,16 @@ "description": "An error." } }, - "summary": "The tasks the caller may run, in the order of the file.", + "summary": "The units and their state.", "tags": [ - "host: tasks" + "host: units" ] } }, - "/v1/hosts/{name}/tasks/{name}": { - "post": { - "description": "Host and agent level.", - "operationId": "host_post_v1_tasks__name_", + "/v1/hosts/{name}/controller/units/{unit}": { + "get": { + "description": "Host level only.", + "operationId": "host_get_v1_units__unit_", "parameters": [ { "description": "A saved host", @@ -5184,36 +5113,22 @@ }, { "in": "path", - "name": "name", + "name": "unit", "required": true, "schema": { "type": "string" } - }, - { - "description": "A duration such as 30s, at most 10m: answer when the command has ended, with what it wrote.", - "in": "query", - "name": "wait", - "schema": { - "type": "string" - } } ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/RunTask" - } - } - } - }, "responses": { "200": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Started" + "additionalProperties": { + "type": "string" + }, + "type": "object" } } }, @@ -5230,16 +5145,16 @@ "description": "An error." } }, - "summary": "Run a task. It and what extends it are the steps of one session.", + "summary": "One unit's properties, as systemctl show gives them.", "tags": [ - "host: tasks" + "host: units" ] } }, - "/v1/hosts/{name}/tasks/{name}/choices/{argument}": { - "get": { - "description": "Host and agent level.", - "operationId": "host_get_v1_tasks__name__choices__argument_", + "/v1/hosts/{name}/controller/units/{unit}/{verb}": { + "post": { + "description": "Host level only.", + "operationId": "host_post_v1_units__unit___verb_", "parameters": [ { "description": "A saved host", @@ -5252,7 +5167,7 @@ }, { "in": "path", - "name": "name", + "name": "unit", "required": true, "schema": { "type": "string" @@ -5260,7 +5175,7 @@ }, { "in": "path", - "name": "argument", + "name": "verb", "required": true, "schema": { "type": "string" @@ -5272,7 +5187,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Choices" + "$ref": "#/components/schemas/Done" } } }, @@ -5289,16 +5204,16 @@ "description": "An error." } }, - "summary": "The values to offer for an argument.", + "summary": "Start, stop, restart, reload, enable or disable a unit.", "tags": [ - "host: tasks" + "host: units" ] } }, - "/v1/hosts/{name}/units": { + "/v1/hosts/{name}/controller/version": { "get": { - "description": "Host level only.", - "operationId": "host_get_v1_units", + "description": "Host and agent level.", + "operationId": "host_get_v1_version", "parameters": [ { "description": "A saved host", @@ -5315,10 +5230,7 @@ "content": { "application/json": { "schema": { - "items": { - "$ref": "#/components/schemas/Unit" - }, - "type": "array" + "$ref": "#/components/schemas/Version" } } }, @@ -5335,16 +5247,15 @@ "description": "An error." } }, - "summary": "The units and their state.", + "summary": "The version of berthd and of its API.", "tags": [ - "host: units" + "host: version" ] } }, - "/v1/hosts/{name}/units/{unit}": { + "/v1/hosts/{name}/credentials": { "get": { - "description": "Host level only.", - "operationId": "host_get_v1_units__unit_", + "operationId": "credentials", "parameters": [ { "description": "A saved host", @@ -5354,14 +5265,6 @@ "schema": { "type": "string" } - }, - { - "in": "path", - "name": "unit", - "required": true, - "schema": { - "type": "string" - } } ], "responses": { @@ -5369,16 +5272,13 @@ "content": { "application/json": { "schema": { - "additionalProperties": { - "type": "string" - }, - "type": "object" + "$ref": "#/components/schemas/Credentials" } } }, - "description": "Done." + "description": "The passwords by account; none when none were generated" }, - "default": { + "404": { "content": { "application/json": { "schema": { @@ -5386,19 +5286,18 @@ } } }, - "description": "An error." + "description": "No such host" } }, - "summary": "One unit's properties, as systemctl show gives them.", + "summary": "The passwords the server generated for a host's accounts.", "tags": [ - "host: units" + "set-up" ] } }, - "/v1/hosts/{name}/units/{unit}/{verb}": { - "post": { - "description": "Host level only.", - "operationId": "host_post_v1_units__unit___verb_", + "/v1/hosts/{name}/profile": { + "get": { + "operationId": "profile", "parameters": [ { "description": "A saved host", @@ -5408,36 +5307,18 @@ "schema": { "type": "string" } - }, - { - "in": "path", - "name": "unit", - "required": true, - "schema": { - "type": "string" - } - }, - { - "in": "path", - "name": "verb", - "required": true, - "schema": { - "type": "string" - } } ], "responses": { "200": { "content": { "application/json": { - "schema": { - "$ref": "#/components/schemas/Done" - } + "schema": {} } }, - "description": "Done." + "description": "The profile, with the passwords and keys in it" }, - "default": { + "404": { "content": { "application/json": { "schema": { @@ -5445,22 +5326,19 @@ } } }, - "description": "An error." + "description": "No such host" } }, - "summary": "Start, stop, restart, reload, enable or disable a unit.", + "summary": "A host's profile, as it is saved.", "tags": [ - "host: units" + "set-up" ] - } - }, - "/v1/hosts/{name}/version": { - "get": { - "description": "Host and agent level.", - "operationId": "host_get_v1_version", + }, + "put": { + "operationId": "save_profile", "parameters": [ { - "description": "A saved host", + "description": "The name to save it under: letters, digits, `-`, `_` and `.`", "in": "path", "name": "name", "required": true, @@ -5469,18 +5347,27 @@ } } ], + "requestBody": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "The whole profile. A workstation's has a builder object; a host of the type ssh or managed needs only type and access", + "required": true + }, "responses": { "200": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Version" + "$ref": "#/components/schemas/Done" } } }, - "description": "Done." + "description": "Saved" }, - "default": { + "400": { "content": { "application/json": { "schema": { @@ -5488,12 +5375,12 @@ } } }, - "description": "An error." + "description": "Not a profile, or not a name" } }, - "summary": "The version of berthd and of its API.", + "summary": "Save a host's profile: a new host, or a changed one. A host that is not a workstation needs only its type and access.", "tags": [ - "host: version" + "set-up" ] } }, @@ -5674,6 +5561,119 @@ ] } }, + "/v1/installation/actions": { + "get": { + "operationId": "list", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/Action" + }, + "type": "array" + } + } + }, + "description": "The actions" + } + }, + "summary": "What can be done to the installation as a whole, such as a roll-out over its hosts.", + "tags": [ + "hosts" + ] + } + }, + "/v1/installation/actions/{action}": { + "post": { + "operationId": "act", + "parameters": [ + { + "description": "The action, as installation.actions names it", + "in": "path", + "name": "action", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/Act" + }, + { + "type": "null" + } + ] + } + } + }, + "description": "Its arguments, and a token that makes asking again safe" + }, + "responses": { + "202": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Acted" + } + } + }, + "description": "Started as a job" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "An argument is wrong, or the body is not one" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The caller's role is below the action's" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "No such action, or a host it names" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Another one is running" + } + }, + "summary": "Run one of the installation's actions, as a job.", + "tags": [ + "hosts" + ] + } + }, "/v1/jobs": { "get": { "operationId": "jobs", diff --git a/docs/openapi/berth.operations.json b/docs/openapi/berth.operations.json index e256c74..8233b36 100644 --- a/docs/openapi/berth.operations.json +++ b/docs/openapi/berth.operations.json @@ -1039,9 +1039,55 @@ ], "type": "object" }, + "PluginAction": { + "description": "An action a feature adds to a host.", + "properties": { + "agent": { + "description": "The agent may run it with `box run`.", + "type": "boolean" + }, + "arguments": { + "description": "The names of the arguments it asks for.", + "items": { + "type": "string" + }, + "type": "array" + }, + "extends": { + "description": "Actions of berth it runs after, with no row of its own.", + "items": { + "type": "string" + }, + "type": "array" + }, + "label": { + "type": "string" + }, + "name": { + "description": "The action is `PLUGIN:NAME` on the host.", + "type": "string" + }, + "user": { + "description": "`agent`, `operator` or `root`.", + "type": "string" + } + }, + "required": [ + "name", + "label", + "user" + ], + "type": "object" + }, "PluginFeature": { "description": "Something a plugin installs, switched on per host.", "properties": { + "actions": { + "items": { + "$ref": "#/components/schemas/PluginAction" + }, + "type": "array" + }, "channels": { "description": "Channel topics, without the plugin's id.", "items": { @@ -1068,12 +1114,6 @@ "$ref": "#/components/schemas/PluginService" }, "type": "array" - }, - "tasks": { - "items": { - "$ref": "#/components/schemas/PluginTask" - }, - "type": "array" } }, "required": [ @@ -1220,46 +1260,6 @@ ], "type": "object" }, - "PluginTask": { - "description": "A task a feature adds to a host's overview.", - "properties": { - "agent": { - "description": "The agent may run it with `box run`.", - "type": "boolean" - }, - "arguments": { - "description": "The names of the arguments it asks for.", - "items": { - "type": "string" - }, - "type": "array" - }, - "extends": { - "description": "Tasks of berth it runs after, with no row of its own.", - "items": { - "type": "string" - }, - "type": "array" - }, - "label": { - "type": "string" - }, - "name": { - "description": "The task is `PLUGIN:NAME` on the host.", - "type": "string" - }, - "user": { - "description": "`agent`, `operator` or `root`.", - "type": "string" - } - }, - "required": [ - "name", - "label", - "user" - ], - "type": "object" - }, "PluginUpdate": { "description": "Whether a newer version of a plugin is there, as its registry says.", "properties": { @@ -1793,6 +1793,13 @@ }, "Session": { "properties": { + "action": { + "description": "The action it was started for, if any. The sessions an older\nberthd kept on the host say `task`.", + "type": [ + "string", + "null" + ] + }, "cols": { "format": "int32", "minimum": 0, @@ -1861,13 +1868,6 @@ }, "type": "array" }, - "task": { - "description": "The task it was started for, if any.", - "type": [ - "string", - "null" - ] - }, "title": { "type": "string" }, @@ -2053,7 +2053,7 @@ } } }, - "description": "The operations of berth serve. Every operation of a host is one here too: on the portal with `\"host\": \"NAME\"` in the frame, over HTTP under /v1/hosts/NAME. Only the `secrets` task is refused; the host's `secrets` action sends the server's own. An action's own role is asked when it runs. Each operation names the least role a caller over TCP needs: view, operate or admin.", + "description": "The operations of berth serve. Every operation of a host is one here too: on the portal with `\"host\": \"NAME\"` in the frame, over HTTP under /v1/hosts/NAME/controller. Only the controller's own `secrets` action is refused; the server's `secrets` action of the host sends the server's secrets. An action's own role is asked when it runs. Each operation names the least role a caller over TCP needs: view, operate or admin.", "hosts": true, "operations": [ { @@ -2385,7 +2385,7 @@ } }, "role": "view", - "summary": "What can be done to a host: the tasks its controller lists, and berth's own actions." + "summary": "What can be done to a host: the actions its controller lists, and berth's own." }, { "args": [ @@ -2455,17 +2455,17 @@ } }, "role": "view", - "summary": "Run one of a host's actions. One of berth's that changes something is a job; a task of the host is a session there, which a job follows unless it needs a terminal." + "summary": "Run one of a host's actions. One of berth's that changes something is a job; an action of the host's controller is a session there, which a job follows unless it needs a terminal." }, { "args": [], - "group": "actions", + "group": "installation", "http": { "method": "GET", - "path": "/v1/actions" + "path": "/v1/installation/actions" }, "kind": "call", - "name": "actions.list", + "name": "installation.actions", "portal": true, "result": { "schema": { @@ -2481,7 +2481,7 @@ { "args": [ { - "description": "The action, as actions.list names it", + "description": "The action, as installation.actions names it", "in": "path", "name": "action", "required": true @@ -2518,13 +2518,13 @@ "status": "409" } ], - "group": "actions", + "group": "installation", "http": { "method": "POST", - "path": "/v1/actions/{action}" + "path": "/v1/installation/actions/{action}" }, "kind": "call", - "name": "actions.act", + "name": "installation.act", "portal": true, "result": null, "role": "view", diff --git a/docs/openapi/berthd.openapi.json b/docs/openapi/berthd.openapi.json index 1b4e5c4..b5c8a5e 100644 --- a/docs/openapi/berthd.openapi.json +++ b/docs/openapi/berthd.openapi.json @@ -337,6 +337,66 @@ ], "type": "object" }, + "HostAction": { + "description": "An action of the host's controller: an entry of `/etc/berth/actions.json`.\nListed without `run`.", + "properties": { + "agent": { + "description": "The agent may run it.", + "type": "boolean" + }, + "arguments": { + "items": { + "$ref": "#/components/schemas/Argument" + }, + "type": "array" + }, + "confirm": { + "type": [ + "string", + "null" + ] + }, + "extends": { + "description": "Actions it is a step of; it then has no row of its own.", + "items": { + "type": "string" + }, + "type": "array" + }, + "group": { + "type": "string" + }, + "help": { + "type": "string" + }, + "input": { + "description": "What the workstation sends on standard input: `secrets`.", + "type": [ + "string", + "null" + ] + }, + "label": { + "type": "string" + }, + "name": { + "type": "string" + }, + "run": { + "type": "string" + }, + "terminal": { + "type": "boolean" + }, + "user": { + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, "HostType": { "description": "What berth does with a host: what its profile means it to be, or what it\nwas seen to be. They are in the order of how much of berth each has.", "enum": [ @@ -762,7 +822,7 @@ ], "type": "object" }, - "RunTask": { + "RunAction": { "properties": { "arguments": { "additionalProperties": { @@ -918,6 +978,13 @@ }, "Session": { "properties": { + "action": { + "description": "The action it was started for, if any. The sessions an older\nberthd kept on the host say `task`.", + "type": [ + "string", + "null" + ] + }, "cols": { "format": "int32", "minimum": 0, @@ -986,13 +1053,6 @@ }, "type": "array" }, - "task": { - "description": "The task it was started for, if any.", - "type": [ - "string", - "null" - ] - }, "title": { "type": "string" }, @@ -1255,66 +1315,6 @@ ], "type": "object" }, - "Task": { - "description": "An entry of `/etc/berth/tasks.json`. Listed without `run`.", - "properties": { - "agent": { - "description": "The agent may run it.", - "type": "boolean" - }, - "arguments": { - "items": { - "$ref": "#/components/schemas/Argument" - }, - "type": "array" - }, - "confirm": { - "type": [ - "string", - "null" - ] - }, - "extends": { - "description": "Tasks it is a step of; it then has no row of its own.", - "items": { - "type": "string" - }, - "type": "array" - }, - "group": { - "type": "string" - }, - "help": { - "type": "string" - }, - "input": { - "description": "What the workstation sends on standard input: `secrets`.", - "type": [ - "string", - "null" - ] - }, - "label": { - "type": "string" - }, - "name": { - "type": "string" - }, - "run": { - "type": "string" - }, - "terminal": { - "type": "boolean" - }, - "user": { - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - }, "Topic": { "description": "An entry of `/etc/berth/channels.json`.", "properties": { @@ -1450,6 +1450,151 @@ }, "openapi": "3.1.0", "paths": { + "/v1/actions": { + "get": { + "description": "Host and agent level.", + "operationId": "get_v1_actions", + "parameters": [], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/HostAction" + }, + "type": "array" + } + } + }, + "description": "Done." + }, + "default": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "An error." + } + }, + "summary": "The actions the caller may run, in the order of the file.", + "tags": [ + "actions" + ] + } + }, + "/v1/actions/{action}": { + "post": { + "description": "Host and agent level.", + "operationId": "post_v1_actions__action_", + "parameters": [ + { + "in": "path", + "name": "action", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "A duration such as 30s, at most 10m: answer when the command has ended, with what it wrote.", + "in": "query", + "name": "wait", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RunAction" + } + } + } + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Started" + } + } + }, + "description": "Done." + }, + "default": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "An error." + } + }, + "summary": "Run an action. It and what extends it are the steps of one session.", + "tags": [ + "actions" + ] + } + }, + "/v1/actions/{action}/choices/{argument}": { + "get": { + "description": "Host and agent level.", + "operationId": "get_v1_actions__action__choices__argument_", + "parameters": [ + { + "in": "path", + "name": "action", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "path", + "name": "argument", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Choices" + } + } + }, + "description": "Done." + }, + "default": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "An error." + } + }, + "summary": "The values to offer for an argument.", + "tags": [ + "actions" + ] + } + }, "/v1/applied/profile": { "get": { "description": "Host level only.", @@ -2353,7 +2498,7 @@ "description": "An error." } }, - "summary": "One session's state. The agent sees those it started through a task.", + "summary": "One session's state. The agent sees those it started through an action.", "tags": [ "sessions" ] @@ -2693,151 +2838,6 @@ ] } }, - "/v1/tasks": { - "get": { - "description": "Host and agent level.", - "operationId": "get_v1_tasks", - "parameters": [], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "items": { - "$ref": "#/components/schemas/Task" - }, - "type": "array" - } - } - }, - "description": "Done." - }, - "default": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorBody" - } - } - }, - "description": "An error." - } - }, - "summary": "The tasks the caller may run, in the order of the file.", - "tags": [ - "tasks" - ] - } - }, - "/v1/tasks/{name}": { - "post": { - "description": "Host and agent level.", - "operationId": "post_v1_tasks__name_", - "parameters": [ - { - "in": "path", - "name": "name", - "required": true, - "schema": { - "type": "string" - } - }, - { - "description": "A duration such as 30s, at most 10m: answer when the command has ended, with what it wrote.", - "in": "query", - "name": "wait", - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/RunTask" - } - } - } - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Started" - } - } - }, - "description": "Done." - }, - "default": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorBody" - } - } - }, - "description": "An error." - } - }, - "summary": "Run a task. It and what extends it are the steps of one session.", - "tags": [ - "tasks" - ] - } - }, - "/v1/tasks/{name}/choices/{argument}": { - "get": { - "description": "Host and agent level.", - "operationId": "get_v1_tasks__name__choices__argument_", - "parameters": [ - { - "in": "path", - "name": "name", - "required": true, - "schema": { - "type": "string" - } - }, - { - "in": "path", - "name": "argument", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Choices" - } - } - }, - "description": "Done." - }, - "default": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorBody" - } - } - }, - "description": "An error." - } - }, - "summary": "The values to offer for an argument.", - "tags": [ - "tasks" - ] - } - }, "/v1/units": { "get": { "description": "Host level only.", diff --git a/docs/openapi/berthd.operations.json b/docs/openapi/berthd.operations.json index 1e26067..4366e75 100644 --- a/docs/openapi/berthd.operations.json +++ b/docs/openapi/berthd.operations.json @@ -337,6 +337,66 @@ ], "type": "object" }, + "HostAction": { + "description": "An action of the host's controller: an entry of `/etc/berth/actions.json`.\nListed without `run`.", + "properties": { + "agent": { + "description": "The agent may run it.", + "type": "boolean" + }, + "arguments": { + "items": { + "$ref": "#/components/schemas/Argument" + }, + "type": "array" + }, + "confirm": { + "type": [ + "string", + "null" + ] + }, + "extends": { + "description": "Actions it is a step of; it then has no row of its own.", + "items": { + "type": "string" + }, + "type": "array" + }, + "group": { + "type": "string" + }, + "help": { + "type": "string" + }, + "input": { + "description": "What the workstation sends on standard input: `secrets`.", + "type": [ + "string", + "null" + ] + }, + "label": { + "type": "string" + }, + "name": { + "type": "string" + }, + "run": { + "type": "string" + }, + "terminal": { + "type": "boolean" + }, + "user": { + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, "HostType": { "description": "What berth does with a host: what its profile means it to be, or what it\nwas seen to be. They are in the order of how much of berth each has.", "enum": [ @@ -762,7 +822,7 @@ ], "type": "object" }, - "RunTask": { + "RunAction": { "properties": { "arguments": { "additionalProperties": { @@ -918,6 +978,13 @@ }, "Session": { "properties": { + "action": { + "description": "The action it was started for, if any. The sessions an older\nberthd kept on the host say `task`.", + "type": [ + "string", + "null" + ] + }, "cols": { "format": "int32", "minimum": 0, @@ -986,13 +1053,6 @@ }, "type": "array" }, - "task": { - "description": "The task it was started for, if any.", - "type": [ - "string", - "null" - ] - }, "title": { "type": "string" }, @@ -1255,66 +1315,6 @@ ], "type": "object" }, - "Task": { - "description": "An entry of `/etc/berth/tasks.json`. Listed without `run`.", - "properties": { - "agent": { - "description": "The agent may run it.", - "type": "boolean" - }, - "arguments": { - "items": { - "$ref": "#/components/schemas/Argument" - }, - "type": "array" - }, - "confirm": { - "type": [ - "string", - "null" - ] - }, - "extends": { - "description": "Tasks it is a step of; it then has no row of its own.", - "items": { - "type": "string" - }, - "type": "array" - }, - "group": { - "type": "string" - }, - "help": { - "type": "string" - }, - "input": { - "description": "What the workstation sends on standard input: `secrets`.", - "type": [ - "string", - "null" - ] - }, - "label": { - "type": "string" - }, - "name": { - "type": "string" - }, - "run": { - "type": "string" - }, - "terminal": { - "type": "boolean" - }, - "user": { - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - }, "Topic": { "description": "An entry of `/etc/berth/channels.json`.", "properties": { @@ -1578,7 +1578,7 @@ } }, "role": "view", - "summary": "One session's state. The agent sees those it started through a task." + "summary": "One session's state. The agent sees those it started through an action." }, { "args": [ @@ -1903,32 +1903,32 @@ }, { "args": [], - "group": "tasks", + "group": "actions", "http": { "method": "GET", - "path": "/v1/tasks" + "path": "/v1/actions" }, "kind": "call", "level": "Host and agent level.", - "name": "tasks.list", + "name": "actions.list", "portal": true, "result": { "schema": { "items": { - "$ref": "#/components/schemas/Task" + "$ref": "#/components/schemas/HostAction" }, "type": "array" } }, "role": "view", - "summary": "The tasks the caller may run, in the order of the file." + "summary": "The actions the caller may run, in the order of the file." }, { "args": [ { - "description": "A task's name, as the list gives it.", + "description": "An action's name, as the list gives it.", "in": "path", - "name": "name", + "name": "action", "required": true }, { @@ -1942,17 +1942,17 @@ "data": { "description": null, "schema": { - "$ref": "#/components/schemas/RunTask" + "$ref": "#/components/schemas/RunAction" } }, - "group": "tasks", + "group": "actions", "http": { "method": "POST", - "path": "/v1/tasks/{name}" + "path": "/v1/actions/{action}" }, "kind": "call", "level": "Host and agent level.", - "name": "tasks.run", + "name": "actions.run", "portal": true, "result": { "schema": { @@ -1960,31 +1960,31 @@ } }, "role": "operate", - "summary": "Run a task. It and what extends it are the steps of one session." + "summary": "Run an action. It and what extends it are the steps of one session." }, { "args": [ { - "description": "A task's name, as the list gives it.", + "description": "An action's name, as the list gives it.", "in": "path", - "name": "name", + "name": "action", "required": true }, { - "description": "The name of one of the task's arguments.", + "description": "The name of one of the action's arguments.", "in": "path", "name": "argument", "required": true } ], - "group": "tasks", + "group": "actions", "http": { "method": "GET", - "path": "/v1/tasks/{name}/choices/{argument}" + "path": "/v1/actions/{action}/choices/{argument}" }, "kind": "call", "level": "Host and agent level.", - "name": "tasks.choices", + "name": "actions.choices", "portal": true, "result": { "schema": { diff --git a/provision/ansible/roles/devbox/files/tasks/common.sh b/provision/ansible/roles/devbox/files/tasks/common.sh index 7727780..9cb79e7 100644 --- a/provision/ansible/roles/devbox/files/tasks/common.sh +++ b/provision/ansible/roles/devbox/files/tasks/common.sh @@ -1,5 +1,6 @@ -# Shared by berth's task scripts. Sourced, not run. The tasks run on the host -# as root, started by berthd; `berth run HOST TASK` or the overview runs them. +# Shared by the scripts of berth's own actions. Sourced, not run. They run on +# the host as root, started by berthd; `berth run HOST ACTION` or the overview +# runs them. set -euo pipefail agent=$(. /etc/devbox/environment 2>/dev/null; echo "${DEVBOX_USER:-agent}") operator=$(jq -r '.operator // empty' /etc/berth/berthd.json 2>/dev/null || true) @@ -25,7 +26,7 @@ access() { echo "Desktop https://$name/vnc.html${password:+#autoconnect=1&password=$encoded}" echo "T3 https://$name:8443/" else - echo 'Desktop and T3 are not published on the tailnet yet (task: publish).' + echo 'Desktop and T3 are not published on the tailnet yet (action: publish).' fi if systemctl is-active -q cockpit.socket && own_control; then echo "Cockpit https://$address:9090 (its own certificate; log in as the operator)" diff --git a/provision/ansible/roles/devbox/files/tasks/pair.sh b/provision/ansible/roles/devbox/files/tasks/pair.sh index 27af8fc..02d5da4 100644 --- a/provision/ansible/roles/devbox/files/tasks/pair.sh +++ b/provision/ansible/roles/devbox/files/tasks/pair.sh @@ -3,9 +3,9 @@ # machine only, so the token goes into the published tailnet address. . "$(dirname "$0")/common.sh" [[ -n $name ]] || { echo 'Not on a tailnet. Run: sudo tailscale up' >&2; exit 1; } -tailscale serve status 2>/dev/null | grep -q 127.0.0.1:3773 || { echo 'T3 is not published on the tailnet yet (task: publish).' >&2; exit 1; } +tailscale serve status 2>/dev/null | grep -q 127.0.0.1:3773 || { echo 'T3 is not published on the tailnet yet (action: publish).' >&2; exit 1; } token=$(as_agent t3 pair --ttl 10m --label "berth $(date +%F)" | sed -n 's/^Token: *//p') -[[ -n $token ]] || { echo 'T3 gave no pairing token. Is it running? (task: status)' >&2; exit 1; } +[[ -n $token ]] || { echo 'T3 gave no pairing token. Is it running? (action: status)' >&2; exit 1; } echo "Browser https://$name:8443/pair#token=$token" echo "App: host https://$name:8443" echo "App: code $token" diff --git a/provision/ansible/roles/devbox/files/tasks/update.sh b/provision/ansible/roles/devbox/files/tasks/update.sh index 0b2db94..cd12ab2 100644 --- a/provision/ansible/roles/devbox/files/tasks/update.sh +++ b/provision/ansible/roles/devbox/files/tasks/update.sh @@ -4,4 +4,4 @@ export DEBIAN_FRONTEND=noninteractive apt-get update apt-get -y -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold dist-upgrade apt-get -y autoremove -[[ -f /var/run/reboot-required ]] && echo 'A reboot is required to finish (task: reboot).' || echo 'Up to date.' +[[ -f /var/run/reboot-required ]] && echo 'A reboot is required to finish (action: reboot).' || echo 'Up to date.' diff --git a/provision/ansible/roles/devbox/tasks/berth.yml b/provision/ansible/roles/devbox/tasks/berth.yml index 1f8a13e..7e573a1 100644 --- a/provision/ansible/roles/devbox/tasks/berth.yml +++ b/provision/ansible/roles/devbox/tasks/berth.yml @@ -53,12 +53,17 @@ roots: "{{ devbox_berthd_roots }}" units: "{{ devbox_berthd_units }}" agent_env: /usr/local/bin/agent-env - - {name: tasks, value: "{{ devbox_tasks }}"} + - {name: actions, value: "{{ devbox_tasks }}"} - {name: services, value: "{{ devbox_plugin_services }}"} - {name: channels, value: "{{ devbox_plugin_channels }}"} loop_control: label: "{{ item.name }}" register: devbox_berth_files +# berthd read the actions from tasks.json before, and still would if it stayed. +- name: Remove the file of actions of berth 0.5 + ansible.builtin.file: + path: /etc/berth/tasks.json + state: absent # The agent's rights follow the services of plugins, so they are settled here # and not with the accounts. - name: Set what the agent may do as root diff --git a/provision/ansible/roles/devbox/templates/AGENT.md.j2 b/provision/ansible/roles/devbox/templates/AGENT.md.j2 index 2db3072..362e251 100644 --- a/provision/ansible/roles/devbox/templates/AGENT.md.j2 +++ b/provision/ansible/roles/devbox/templates/AGENT.md.j2 @@ -41,10 +41,10 @@ resolved versions and `/etc/devbox/expected-commands` every command this machine is expected to have. `yq` is the Python/jq-based Ubuntu package, not mikefarah/yq. Not listed here means not installed; install what a task needs. -## Tasks +## Actions -`box tasks` lists the named operations of this machine you may run, such as the -self-test; `box run TASK` runs one and shows its output. `box --help` has the +`box actions` lists the named operations of this machine you may run, such as +the self-test; `box run ACTION` runs one and shows its output. `box --help` has the rest: publishing and reading messages on the machine's channel, and calling the services plugins provide. diff --git a/provision/ansible/roles/devbox/vars/main.yml b/provision/ansible/roles/devbox/vars/main.yml index 88e905b..f79af3e 100644 --- a/provision/ansible/roles/devbox/vars/main.yml +++ b/provision/ansible/roles/devbox/vars/main.yml @@ -1,6 +1,6 @@ --- -# berth's own tasks, in the order the overview shows them. berthd reads them -# from /etc/berth/tasks.json, where the actions of the plugins follow. +# berth's own actions, in the order the overview shows them. berthd reads them +# from /etc/berth/actions.json, where the actions of the plugins follow. devbox_task_dir: /usr/local/lib/berth/tasks devbox_core_tasks: - name: status @@ -61,7 +61,7 @@ devbox_core_tasks: agent: true help: "The accounts the tools on this host are signed in to for the agent: the coding agents, GitHub and whatever else the plugins of this host know about." run: "true" -# The tasks of a host with the controller alone, which assume nothing of a +# The actions of a host with the controller alone, which assume nothing of a # desktop, its accounts or plugins. devbox_controller_tasks: - name: status diff --git a/recipes/incus-host/README.md b/recipes/incus-host/README.md index 4f2f519..8fa23f5 100644 --- a/recipes/incus-host/README.md +++ b/recipes/incus-host/README.md @@ -65,9 +65,9 @@ berth host add big 192.0.2.20 --user root --auth ssh berth host install big ``` -`berth host add` saves `big` as a host of the type `ssh`. `--auth ssh` makes berth log in with your own SSH configuration and agent, so the key that works for `ssh root@192.0.2.20` works for berth. The default, `--auth berth`, uses berth's own key, which berth installs on the first contact with a password or a private key that logs in once. `--auth ssh` works with a local berth only. With a berth server set, the server logs in with its own keys. +`berth host add` saves `big` with the type `ssh`. `--auth ssh` makes berth log in with your own SSH configuration and agent, so the key that works for `ssh root@192.0.2.20` works for berth. The default, `--auth berth`, uses berth's own key, which berth installs on the first contact with a password or a private key that logs in once. `--auth ssh` works with a local berth only. With a berth server set, the server logs in with its own keys. -`berth host install big` puts the controller alone on the server. berth can then report its status and run commands there, and it can update and reboot the server. Sessions run as the SSH user, here `root`. berth never applies such a server as a workstation: it stays a host of the type `ssh` or `managed`, and the machines on it are created with the Incus or Docker provisioner. +`berth host install big` puts the controller alone on the server. berth can then report its status and run commands there, and it can update and reboot the server. Sessions run as the SSH user, here `root`. berth never applies such a server as a workstation: its type stays `ssh` or `managed`, and the machines on it are created with the Incus or Docker provisioner. ## Settings diff --git a/tests/container_link.py b/tests/container_link.py index 276dece..29b13c9 100644 --- a/tests/container_link.py +++ b/tests/container_link.py @@ -4,7 +4,7 @@ python3 tests/container_link.py CONTAINER -Starts a session and runs a task, and fails when either does not end well. +Starts a session and runs an action, and fails when either does not end well. Not a unit test: run it against the built image, started with docker compose. """ import base64 @@ -68,13 +68,13 @@ def main(): sys.exit(f'Unexpected session result: {session}') print(f'session {session["id"]}: output and exit code as expected') - names = [task['name'] for task in call(container, 'GET', '/v1/tasks')] + names = [task['name'] for task in call(container, 'GET', '/v1/actions')] if 'sign-in:status' not in names: - sys.exit(f'No sign-in:status among the tasks: {names}') - task = call(container, 'POST', '/v1/tasks/sign-in:status?wait=120s', {}) + sys.exit(f'No sign-in:status among the actions: {names}') + task = call(container, 'POST', '/v1/actions/sign-in:status?wait=120s', {}) if task.get('exit_code') != 0: - sys.exit(f'Task sign-in:status failed: {task}') - print(f'task sign-in:status: ran as session {task["id"]}, steps {[step["name"] for step in task.get("steps", [])]}') + sys.exit(f'Action sign-in:status failed: {task}') + print(f'action sign-in:status: ran as session {task["id"]}, steps {[step["name"] for step in task.get("steps", [])]}') refused = None try: diff --git a/tests/e2e/e2e_access.py b/tests/e2e/e2e_access.py index 42e6ec8..61c6a0d 100644 --- a/tests/e2e/e2e_access.py +++ b/tests/e2e/e2e_access.py @@ -171,7 +171,7 @@ def test_4_a_changed_host_key_is_refused_until_it_is_accepted(self): self.assertNotEqual(refused.returncode, 0) self.assertRegex(refused.stderr, r'HOST IDENTIFICATION HAS CHANGED|Host key verification failed') # berth's own logins say what happened and what to do. - said = self.berth('tasks', HOST, check=False) + said = self.berth('actions', HOST, check=False) self.assertNotEqual(said.returncode, 0) self.assertIn(f'berth key host {HOST} --accept', said.stderr) self.assertEqual(self.berth('key', 'host', HOST).stdout, recorded) diff --git a/tests/e2e/e2e_apply.py b/tests/e2e/e2e_apply.py index 0727105..3d9d722 100644 --- a/tests/e2e/e2e_apply.py +++ b/tests/e2e/e2e_apply.py @@ -23,7 +23,7 @@ def test_the_first_apply_installs_berthd(self): self.assertEqual(version['mode'], 'system') berthd = json.loads(self.station.root_on_host('cat /etc/berth/berthd.json').stdout) self.assertEqual((berthd['agent'], berthd['operator']), (AGENT, OPERATOR)) - tasks = json.loads(self.station.root_on_host('cat /etc/berth/tasks.json').stdout) + tasks = json.loads(self.station.root_on_host('cat /etc/berth/actions.json').stdout) self.assertIn('secrets', [task['name'] for task in tasks]) print(f'\n first apply: {self.station.apply_seconds:.0f}s, {recap}', end=' ') diff --git a/tests/e2e/e2e_client.py b/tests/e2e/e2e_client.py index a20e4ab..7d6ab10 100644 --- a/tests/e2e/e2e_client.py +++ b/tests/e2e/e2e_client.py @@ -25,7 +25,7 @@ def test_the_hosts_are_the_servers(self): self.assertNotIn(self.serve.token, shown) def test_commands_go_through_the_server(self): - self.assertIn('secrets', self.station.berth('tasks', HOST).stdout) + self.assertIn('secrets', self.station.berth('actions', HOST).stdout) self.assertEqual(self.station.berth('exec', HOST, '--', 'id', '-un').stdout.strip(), AGENT) done = self.station.berth('exec', HOST, '--', 'sh', '-c', 'cat; exit 5', input='piped\n', check=False) self.assertEqual((done.returncode, done.stdout), (5, 'piped\n')) diff --git a/tests/e2e/e2e_controller.py b/tests/e2e/e2e_controller.py index 33d683e..f8495a5 100644 --- a/tests/e2e/e2e_controller.py +++ b/tests/e2e/e2e_controller.py @@ -53,7 +53,7 @@ def test_1_a_machine_added_by_its_address_is_only_logged_in_to(self): self.assertEqual(self.station.read_profile(), { 'type': 'ssh', 'access': {'address': HOST, 'user': OPERATOR, 'auth': 'berth'}}) self.assertEqual(self.berth('ssh', HOST, 'id -un').stdout.strip(), OPERATOR) - listed = self.berth('tasks', HOST).stdout + listed = self.berth('actions', HOST).stdout self.assertRegex(listed, r'(?m)^ install-controller\s+Install the controller') # What needs more than a login is refused, and says what changes the type. refused = self.berth('apply', HOST, check=False) @@ -82,7 +82,7 @@ def test_2_installing_the_controller_puts_berthd_and_box_there_alone(self): def test_3_sessions_and_tasks_run_as_the_ssh_user(self): self.assertEqual(self.berth('exec', HOST, '--', 'id', '-un').stdout.strip(), OPERATOR) self.assertEqual(self.berth('exec', HOST, '--user', 'root', '--', 'id', '-un').stdout.strip(), 'root') - listed = self.berth('tasks', HOST).stdout + listed = self.berth('actions', HOST).stdout for name in ('status', 'update', 'secrets'): self.assertRegex(listed, rf'(?m)^ {name}\s+', name) self.assertNotRegex(listed, r'(?m)^ smoke\s+') @@ -112,14 +112,14 @@ class OnAWorkstation(unittest.TestCase): def test_a_workstation_added_again_as_ssh_keeps_its_controller(self): station = provisioned() - files = 'cat /etc/berth/applied.json /etc/berth/berthd.json /etc/berth/tasks.json' + files = 'cat /etc/berth/applied.json /etc/berth/berthd.json /etc/berth/actions.json' before = station.root_on_host(files).stdout added = station.berth('host', 'add', 'adopted', HOST, '--user', OPERATOR, '--type', 'ssh', input='') try: # berth sees what the host is, and says how to adopt it. self.assertIn('adopted is a workstation; its profile here says ssh', added.stdout) self.assertIn('berth adopt adopted', added.stdout) - listed = station.berth('tasks', 'adopted').stdout + listed = station.berth('actions', 'adopted').stdout self.assertIn('adopted is a workstation; its profile here says ssh', listed) self.assertRegex(listed, r'(?m)^ install-controller\s+.*take its controller apart') refused = station.berth('host', 'install', 'adopted', check=False, timeout=600) diff --git a/tests/e2e/e2e_host.py b/tests/e2e/e2e_host.py index 1bf3cd4..01b59da 100644 --- a/tests/e2e/e2e_host.py +++ b/tests/e2e/e2e_host.py @@ -14,7 +14,7 @@ def setUpClass(cls): cls.station = provisioned() def test_tasks_are_listed_by_group(self): - listed = self.station.berth('tasks', HOST).stdout + listed = self.station.berth('actions', HOST).stdout for line in ('System', 'Sync', 'Sign-In'): self.assertRegex(listed, rf'(?m)^{line}$') self.assertRegex(listed, r'(?m)^ secrets\s+Secrets and registry logins') @@ -23,7 +23,7 @@ def test_a_task_runs_and_its_exit_code_is_berths(self): self.assertEqual(self.station.berth('run', HOST, 'sign-in:status').returncode, 0) missing = self.station.berth('run', HOST, 'nothing-like-this', check=False) self.assertEqual(missing.returncode, 1) - self.assertIn('has no task nothing-like-this', missing.stderr) + self.assertIn('has no action nothing-like-this', missing.stderr) def test_the_status_task_copes_without_systemd(self): done = self.station.berth('run', HOST, 'status', check=False, timeout=120) @@ -124,7 +124,7 @@ def test_files_outside_the_roots_are_refused(self): for path in ('/etc/shadow', '/root', f'/home/{AGENT}/../{OPERATOR}/.ssh/authorized_keys'): status, answer = self.link.request('GET', f'/v1/files?path={path}') self.assertIn(status, (403, 404), (path, answer)) - status, _ = self.link.request('PUT', '/v1/files?path=/etc/berth/tasks.json&overwrite=true', b'[]') + status, _ = self.link.request('PUT', '/v1/files?path=/etc/berth/actions.json&overwrite=true', b'[]') self.assertEqual(status, 403) def test_units_without_systemd_are_an_answer_not_a_crash(self): @@ -146,11 +146,11 @@ def test_the_hosts_state(self): self.assertTrue(any('berthd' in process['command'] for process in processes)) def test_a_task_runs_as_steps(self): - tasks = {task['name']: task for task in self.link.get('/v1/tasks')} + tasks = {task['name']: task for task in self.link.get('/v1/actions')} self.assertEqual(tasks['status']['user'], 'root') - session = self.link.post('/v1/tasks/sign-in:status?wait=60s', {}) + session = self.link.post('/v1/actions/sign-in:status?wait=60s', {}) self.assertEqual(session['exit_code'], 0) - self.assertEqual(session['task'], 'sign-in:status') + self.assertEqual(session['action'], 'sign-in:status') def test_the_channel_keeps_what_it_is_told_to(self): topic = random_text('e2e-host/notes') @@ -162,7 +162,7 @@ def test_the_channel_keeps_what_it_is_told_to(self): self.assertEqual([message['body'] for message in messages], [body]) def test_the_agent_sees_its_own_tasks(self): - listed = self.station.berth('exec', HOST, '--', 'box', 'tasks').stdout + listed = self.station.berth('exec', HOST, '--', 'box', 'actions').stdout self.assertIn('sign-in:status', listed) self.assertNotIn('reboot', re.findall(r'^\S+', listed, re.M)) self.assertEqual(self.station.berth('exec', HOST, '--', 'box', 'run', 'sign-in:status').returncode, 0) diff --git a/tests/e2e/e2e_own_key.py b/tests/e2e/e2e_own_key.py index 0f0b718..8e51451 100644 --- a/tests/e2e/e2e_own_key.py +++ b/tests/e2e/e2e_own_key.py @@ -85,7 +85,7 @@ def test_applying_asks_for_nothing_and_again_changes_nothing(self): self.assertEqual(changed_tasks(self.second_apply.stdout), []) def test_tasks_are_listed_and_run(self): - self.assertRegex(self.berth('tasks', HOST).stdout, r'(?m)^ secrets\s+') + self.assertRegex(self.berth('actions', HOST).stdout, r'(?m)^ secrets\s+') self.assertEqual(self.berth('run', HOST, 'sign-in:status').returncode, 0) def test_commands_run_as_each_account(self): @@ -225,7 +225,7 @@ def test_the_server_hands_out_its_key_and_no_sudo_switch(self): self.assertEqual(catalogue['template']['operator_ssh_public_keys'], []) def test_the_agents_files_through_the_server(self): - path = f'/v1/hosts/{HOST}/files?path=/home/{AGENT}/own-key-served.txt' + path = f'/v1/hosts/{HOST}/controller/files?path=/home/{AGENT}/own-key-served.txt' content = random_text('served').encode() status, _ = self.serve.request('PUT', path + '&overwrite=true', content, headers={'Content-Type': 'application/octet-stream'}) diff --git a/tests/e2e/e2e_plugins.py b/tests/e2e/e2e_plugins.py index f8788f5..4d34070 100644 --- a/tests/e2e/e2e_plugins.py +++ b/tests/e2e/e2e_plugins.py @@ -23,17 +23,17 @@ def test_berth_lists_it_with_what_it_brings(self): listed = self.station.berth('plugins').stdout self.assertRegex(listed, rf'(?m)^e2e {PACKAGE} 1\.0\.0 ') self.assertIn('e2e/hello Hello (Testing)', listed) - self.assertIn('task e2e:hello Say hello (as agent; the agent may run it; asks name)', listed) + self.assertIn('action e2e:hello Say hello (as agent; the agent may run it; asks name)', listed) self.assertIn('service e2e/echo as agent: say', listed) self.assertIn('channel e2e/notes', listed) def test_its_task_runs_with_an_argument(self): - self.assertRegex(self.station.berth('tasks', HOST).stdout, r'e2e:hello\s+Say hello\s+name=…') + self.assertRegex(self.station.berth('actions', HOST).stdout, r'e2e:hello\s+Say hello\s+name=…') done = self.station.berth('run', HOST, 'e2e:hello', 'name=ada') self.assertEqual(done.stdout.strip(), f'hello ada from {AGENT}') missing = self.station.berth('run', HOST, 'e2e:hello', check=False) self.assertIn('e2e:hello needs name=VALUE', missing.stderr) - choices = self.link.get('/v1/tasks/e2e:hello/choices/name') + choices = self.link.get('/v1/actions/e2e:hello/choices/name') self.assertEqual(choices['choices'], ['ada', 'grace']) # The agent may run it too. done = self.station.berth('exec', HOST, '--', 'box', 'run', 'e2e:hello', 'name=grace') @@ -86,6 +86,6 @@ def setUpClass(cls): def test_its_tasks_are_gone_from_berth_and_the_host(self): self.assertNotIn('e2e/hello', self.station.berth('plugins').stdout) - self.assertNotIn('e2e:hello', self.station.berth('tasks', HOST).stdout) + self.assertNotIn('e2e:hello', self.station.berth('actions', HOST).stdout) services = json.loads(self.station.root_on_host('cat /etc/berth/services.json').stdout) self.assertEqual(services, []) diff --git a/tests/e2e/e2e_restore.py b/tests/e2e/e2e_restore.py index 2b1fd08..4e9d672 100644 --- a/tests/e2e/e2e_restore.py +++ b/tests/e2e/e2e_restore.py @@ -155,8 +155,8 @@ def test_4_the_secret_and_the_setting_are_there(self): profile['secrets'] = [{'name': self.secret, 'env': 'RESTORED_SECRET'}] self.serve.call('PUT', f'/v1/hosts/{HOST}/profile', profile) session = self.serve.call('POST', f'/v1/hosts/{HOST}/actions/secrets', expect=202)['session'] - wait_for('the secrets task to end', lambda: self.serve.call( - 'GET', f'/v1/hosts/{HOST}/sessions/{session["id"]}').get('exit_code') == 0) + wait_for('the secrets action to end', lambda: self.serve.call( + 'GET', f'/v1/hosts/{HOST}/controller/sessions/{session["id"]}').get('exit_code') == 0) env = self.worker.root_on_host(f'cat /home/{AGENT}/.config/devbox/secrets.env').stdout self.assertIn(f'export RESTORED_SECRET={self.secret_value}', env) diff --git a/tests/e2e/e2e_serve.py b/tests/e2e/e2e_serve.py index 98e484a..d886f4b 100644 --- a/tests/e2e/e2e_serve.py +++ b/tests/e2e/e2e_serve.py @@ -36,18 +36,18 @@ def test_nothing_without_the_token(self): self.assertEqual(answer['error']['code'], 'unauthorized') def test_a_hosts_operations_go_through(self): - started = self.serve.call('POST', f'/v1/hosts/{HOST}/sessions?wait=30s', + started = self.serve.call('POST', f'/v1/hosts/{HOST}/controller/sessions?wait=30s', {'kind': 'process', 'command': ['id', '-un']}) self.assertEqual((started['exit_code'], text_of(started)), (0, f'{AGENT}\n')) - tasks = self.serve.call('GET', f'/v1/hosts/{HOST}/tasks') + tasks = self.serve.call('GET', f'/v1/hosts/{HOST}/controller/actions') self.assertIn('secrets', [task['name'] for task in tasks]) - path = f'/v1/hosts/{HOST}/files?path=/home/{AGENT}/through-serve.txt&overwrite=true' + path = f'/v1/hosts/{HOST}/controller/files?path=/home/{AGENT}/through-serve.txt&overwrite=true' status, _ = self.serve.request('PUT', path, b'written through berth serve', headers={'Content-Type': 'application/octet-stream'}) self.assertEqual(status, 200) status, read, _ = self.serve.request('GET', path.split('&')[0], raw=True) self.assertEqual((status, read), (200, b'written through berth serve')) - status, _ = self.serve.request('GET', '/v1/hosts/nowhere/sessions') + status, _ = self.serve.request('GET', '/v1/hosts/nowhere/controller/sessions') self.assertEqual(status, 404) def test_the_key_value_store(self): @@ -67,7 +67,7 @@ def test_the_key_value_store(self): def test_the_inbox_takes_in_what_the_host_keeps(self): body = {'note': random_text('inbox')} - self.serve.call('POST', f'/v1/hosts/{HOST}/sessions?wait=30s', { + self.serve.call('POST', f'/v1/hosts/{HOST}/controller/sessions?wait=30s', { 'kind': 'process', 'command': ['box', 'publish', 'e2e/inbox', json.dumps(body), '--keep', 'log']}) def arrived(): @@ -134,9 +134,9 @@ def test_each_role_may_do_what_it_names(self): process = {'kind': 'process', 'command': ['true']} asked = [ ('GET', '/v1/hosts', None, 'view'), - ('GET', f'/v1/hosts/{HOST}/sessions', None, 'view'), - ('POST', f'/v1/hosts/{HOST}/sessions?wait=10s', process, 'operate'), - ('GET', f'/v1/hosts/{HOST}/files?path=/home/{AGENT}', None, 'operate'), + ('GET', f'/v1/hosts/{HOST}/controller/sessions', None, 'view'), + ('POST', f'/v1/hosts/{HOST}/controller/sessions?wait=10s', process, 'operate'), + ('GET', f'/v1/hosts/{HOST}/controller/files?path=/home/{AGENT}', None, 'operate'), ('GET', '/v1/secrets', None, 'admin'), ('GET', f'/v1/hosts/{HOST}/profile', None, 'admin'), ] @@ -238,8 +238,8 @@ def test_the_server_sends_its_secrets_to_the_host(self): self.serve.call('PUT', f'/v1/hosts/{HOST}/profile', profile) try: session = self.serve.call('POST', f'/v1/hosts/{HOST}/actions/secrets', expect=202)['session'] - wait_for('the secrets task to end', lambda: self.serve.call( - 'GET', f'/v1/hosts/{HOST}/sessions/{session["id"]}').get('exit_code') == 0) + wait_for('the secrets action to end', lambda: self.serve.call( + 'GET', f'/v1/hosts/{HOST}/controller/sessions/{session["id"]}').get('exit_code') == 0) env = provisioned().root_on_host(f'cat /home/{AGENT}/.config/devbox/secrets.env').stdout self.assertIn(f'export SERVER_TOKEN={value}', env) finally: diff --git a/tests/e2e/e2e_update.py b/tests/e2e/e2e_update.py index e236436..7697eb4 100644 --- a/tests/e2e/e2e_update.py +++ b/tests/e2e/e2e_update.py @@ -119,7 +119,7 @@ def test_an_update_reaches_the_host_and_keeps_what_was_there(self): # What changed is there, and what went is gone. self.assertEqual(station.berth('run', HOST, 'up:hello').stdout.strip(), 'hello from 2.0.0') self.assertEqual(station.berth('run', HOST, 'up:added').stdout.strip(), 'added task') - tasks = station.berth('tasks', HOST).stdout + tasks = station.berth('actions', HOST).stdout self.assertNotIn('up:old', tasks) services = json.loads(station.root_on_host('cat /etc/berth/services.json').stdout) ours = [service['run'] for service in services if 'box serve up/echo' in service['run']] From 2d6dc82ce4332fe72aa7e9a964021dd5a4905eed Mon Sep 17 00:00:00 2001 From: Helight Date: Sun, 15 Nov 2026 00:58:27 +0100 Subject: [PATCH 13/94] feat: berth ui, the screens of berth serve with a server in the process With no server set and no berth serve of the user running, berth ui runs the API in its own process and the screens reach it over pipes in memory. Jobs that still run when the screens close are waited for. --- crates/berth-api/src/client.rs | 14 ++ crates/berth-core/src/runner.rs | 16 +- crates/berth-page/src/app.rs | 75 ++++++-- crates/berth-page/src/device.rs | 60 +++--- crates/berth-page/src/installed.rs | 14 +- crates/berth-page/src/portal.rs | 18 +- crates/berth-remote/src/device.rs | 19 +- crates/berth-remote/src/lib.rs | 1 + crates/berth-remote/src/main.rs | 67 +------ crates/berth-remote/src/net.rs | 160 +++++++++++----- crates/berth-remote/src/screens.rs | 71 +++++++ crates/berth-remote/src/socket.rs | 11 +- crates/berth/Cargo.toml | 5 +- crates/berth/src/main.rs | 57 ++++++ crates/berth/src/serve/auth.rs | 10 + crates/berth/src/serve/here.rs | 250 +++++++++++++++++++++++++ crates/berth/src/serve/mod.rs | 11 +- crates/berth/src/serve/tests/remote.rs | 4 +- 18 files changed, 678 insertions(+), 185 deletions(-) create mode 100644 crates/berth-remote/src/screens.rs create mode 100644 crates/berth/src/serve/here.rs diff --git a/crates/berth-api/src/client.rs b/crates/berth-api/src/client.rs index 910fd1f..20a38f2 100644 --- a/crates/berth-api/src/client.rs +++ b/crates/berth-api/src/client.rs @@ -68,6 +68,20 @@ fn transport(error: impl std::fmt::Display) -> Error { pub type Result = std::result::Result; +/// A connection to a server, whatever carries it: TCP, TLS, a unix socket, +/// or a pipe to a server in the same process. +pub trait Io: AsyncRead + AsyncWrite + Unpin + Send {} +impl Io for T {} +pub type Stream = Box; + +/// How a client reaches its server: each call opens a new connection, for a +/// request or for a WebSocket. +pub type Dial = std::sync::Arc< + dyn Fn() -> std::pin::Pin> + Send>> + + Send + + Sync, +>; + /// A raw answer: status, headers and body. pub struct Response { pub status: u16, diff --git a/crates/berth-core/src/runner.rs b/crates/berth-core/src/runner.rs index 828546d..c03318c 100644 --- a/crates/berth-core/src/runner.rs +++ b/crates/berth-core/src/runner.rs @@ -19,7 +19,7 @@ use std::{ os::unix::fs::OpenOptionsExt, path::{Path, PathBuf}, process::{Command, Stdio}, - sync::Arc, + sync::{Arc, Mutex}, time::{Duration, Instant}, }; @@ -460,6 +460,8 @@ pub struct Runner { store: Arc, jobs_dir: PathBuf, notify: Notify, + /// The jobs this process runs now, which end with it. + running: Arc>>, } /// Where an installation keeps the output of the jobs it runs. @@ -510,9 +512,15 @@ impl Runner { store, jobs_dir, notify, + running: Arc::default(), } } + /// The jobs that run in this process now, as they started. + pub fn running(&self) -> Vec { + self.running.lock().unwrap().clone() + } + /// Start the work as a job, in a thread of its own, and say which job it /// is. A token used before for the same subject and action answers with /// that job, and nothing is started. A refusal, such as a lock that is @@ -605,6 +613,7 @@ impl Ticket { /// Run the work in a thread of its own: the job as it started. pub fn run(self, work: Work) -> store::Job { let job = self.job.clone(); + self.runner.running.lock().unwrap().push(job.clone()); std::thread::spawn(move || { let Ticket { runner, @@ -621,6 +630,11 @@ impl Ticket { }; drop(lock); runner.end(&job.id, exit_code); + runner + .running + .lock() + .unwrap() + .retain(|running| running.id != job.id); }); job } diff --git a/crates/berth-page/src/app.rs b/crates/berth-page/src/app.rs index 0147461..85b86e1 100644 --- a/crates/berth-page/src/app.rs +++ b/crates/berth-page/src/app.rs @@ -144,6 +144,8 @@ pub struct App { qr: Option, /// The token collected with a setup key, until Done. installed: Option, + /// A host to open once the server has listed its hosts. + wanted: Option, } impl App { @@ -164,8 +166,11 @@ impl App { .flatten() }) .unwrap_or_default(); - device::store(Kept::Server, &server); - device::store(Kept::Token, &token); + // A server on this machine is never kept: it is found again each run. + if !device::local(&server) { + device::store(Kept::Server, &server); + device::store(Kept::Token, &token); + } let mut app = App { screen: Screen::Token, portal: None, @@ -207,6 +212,7 @@ impl App { over_links: vec![], qr: None, installed: None, + wanted: None, }; // A setup key signs in with the token it collects, whatever was kept. if let (Some(key), false) = (linked.setup_key, app.server.is_empty()) { @@ -214,18 +220,49 @@ impl App { app.screen = Screen::Installed; return app; } - if !app.token.is_empty() && !app.server.is_empty() { + if (!app.token.is_empty() && !app.server.is_empty()) || device::local(&app.server) { app.connect(); } app } + /// The server is on this machine, and the screens need no token for it. + fn local(&self) -> bool { + device::local(&self.server) + } + + /// Open the host `name` once the server has listed it. + pub fn open_when_listed(&mut self, name: &str) { + self.wanted = Some(name.to_owned()); + } + + /// Open the host that was asked for, once the list has come. + fn open_wanted(&mut self) { + if !self.hosts.borrow().answered || self.screen != Screen::Hosts { + return; + } + let Some(name) = self.wanted.take() else { + return; + }; + let address = self + .hosts + .borrow() + .list + .iter() + .find(|host| host["name"] == name.as_str()) + .map(|host| host["address"].as_str().unwrap_or("").to_owned()); + match address { + Some(address) => self.open_host(&name, &address), + None => self.status = format!("There is no host {name}"), + } + } + /// Open the portal with the token there is. fn connect(&mut self) { self.host.disconnect(); self.asked = None; self.retry = None; - match Portal::open(&device::portal_url(&self.server), &self.token) { + match Portal::open(&self.server, &self.token) { Ok(portal) => { // Who the token is here decides what the page offers. let admin = Admin::new(portal.clone(), self.data.clone()); @@ -320,7 +357,7 @@ impl App { } // A token that never opened the portal is asked for again; one that // has is the right one, and the server is only away. - Some(Link::Refused) if !self.proven => { + Some(Link::Refused) if !self.proven && !self.local() => { self.sign_out("The server did not open its portal for that token."); return; } @@ -339,6 +376,7 @@ impl App { return; } self.take_in(); + self.open_wanted(); if self .asked .is_none_or(|asked| asked.elapsed() >= HOSTS_EVERY) @@ -540,11 +578,14 @@ impl App { rows.push(Row::info("")); } rows.push(heading("Connection")); - rows.push(Row::info(format!( - " {} · through the berth server at {}", - self.address, - device::shown(&self.server) - ))); + rows.push(Row::info(match self.local() { + true => format!(" {}", self.address), + false => format!( + " {} · through the berth server at {}", + self.address, + device::shown(&self.server) + ), + })); for line in host::type_lines(&self.name, &self.host) { rows.push(Row::info(Line::styled( format!(" {line}"), @@ -1125,7 +1166,7 @@ impl App { } _ => {} }, - Code::Char('o') => self.sign_out(""), + Code::Char('o') if !self.local() => self.sign_out(""), _ => {} } } @@ -1395,6 +1436,7 @@ impl App { let text = match (&hosts.error, hosts.answered) { (Some(error), _) => format!("✗ {error}"), (None, false) => "Asking the server for its hosts…".into(), + (None, true) if self.local() => "No hosts yet.".into(), (None, true) => { "The server has no hosts yet. They are set up with berth where it runs, or from here with the role admin.".into() } @@ -1414,12 +1456,15 @@ impl App { if let Some(input) = &self.naming { draw_editor(frame, edit, " New host name ", input, false); } - let keys = match (admin, self.naming.is_some()) { - (_, true) => "Enter create · Esc cancel · Ctrl+O copy", - (true, false) => { + let keys = match (admin, self.naming.is_some(), self.local()) { + (_, true, _) => "Enter create · Esc cancel · Ctrl+O copy", + (true, false, true) => { + "↑↓ select · Enter open · n new host · d default · x remove · r refresh" + } + (true, false, false) => { "↑↓ select · Enter open · n new host · d default · x remove · r refresh · o sign out" } - (false, false) => "↑↓ select · Enter open · r refresh · o sign out", + (false, false, _) => "↑↓ select · Enter open · r refresh · o sign out", }; draw_footer(frame, footer, keys, &self.status, theme::ACCENT); } diff --git a/crates/berth-page/src/device.rs b/crates/berth-page/src/device.rs index 082c0c4..45e5451 100644 --- a/crates/berth-page/src/device.rs +++ b/crates/berth-page/src/device.rs @@ -58,13 +58,15 @@ pub trait Device { /// Keep `value`, or forget what was kept when it is empty. fn store(&self, key: Kept, value: &str); fn linked(&self) -> Linked; - /// One plain HTTP request with a bearer; `then` gets its status and body. - fn request(&self, method: &str, url: &str, bearer: &str, then: Answer); - /// Open a WebSocket to `url` with `token` as its protocol. `said` gets - /// what it says, on the thread that draws, from a later turn on. + /// One plain HTTP request to `path` of `server` with a bearer; `then` + /// gets its status and body. + fn request(&self, method: &str, server: &str, path: &str, bearer: &str, then: Answer); + /// Open a WebSocket to `path` of `server` with `token` as its protocol. + /// `said` gets what it says, on the thread that draws, from a later turn on. fn connect( &self, - url: &str, + server: &str, + path: &str, token: &str, said: Box, ) -> Result, String>; @@ -123,18 +125,32 @@ pub(crate) fn choose_file( pub(crate) fn request( method: &str, - url: &str, + server: &str, + path: &str, bearer: &str, then: impl FnOnce(Result<(u16, String), String>) + 'static, ) { - device().request(method, url, bearer, Box::new(then)) + device().request(method, server, path, bearer, Box::new(then)) +} + +/// The server that runs in the program itself, as the screens name it. +pub const HERE: &str = "here:"; + +/// Whether the server is on this machine, reached without a token: the one +/// in the program, or the socket of a `berth serve` of this user. +pub fn local(server: &str) -> bool { + server == HERE || server.starts_with("unix:") } /// A server's address as typed, made whole: without a scheme it is https, /// or http for this machine itself. pub fn address(typed: &str) -> String { let typed = typed.trim().trim_end_matches('/'); - if typed.is_empty() || typed.starts_with("http://") || typed.starts_with("https://") { + if typed.is_empty() + || typed.starts_with("http://") + || typed.starts_with("https://") + || local(typed) + { return typed.to_owned(); } let local = ["localhost", "127.", "[::1]"] @@ -143,22 +159,19 @@ pub fn address(typed: &str) -> String { format!("{}://{typed}", if local { "http" } else { "https" }) } -/// A server as it is shown: `host:port`. +/// A server as it is shown: `host:port`, or where on this machine it is. pub fn shown(server: &str) -> &str { + if server == HERE { + return "this machine"; + } + if server.starts_with("unix:") { + return "berth serve on this machine"; + } server .trim_start_matches("https://") .trim_start_matches("http://") } -/// The address of the portal of a server. -pub fn portal_url(server: &str) -> String { - let scheme = match server.starts_with("https://") { - true => "wss", - false => "ws", - }; - format!("{scheme}://{}{}", shown(server), berth_api::ops::PORTAL) -} - #[cfg(test)] mod tests { use super::*; @@ -172,13 +185,12 @@ mod tests { assert_eq!(address("127.0.0.1:7878/"), "http://127.0.0.1:7878"); assert_eq!(address(" https://192.0.2.10/ "), "https://192.0.2.10"); assert_eq!(shown("https://studio.example:8080"), "studio.example:8080"); + assert_eq!(address("here:"), "here:"); assert_eq!( - portal_url("https://studio.example"), - "wss://studio.example/v1/portal" - ); - assert_eq!( - portal_url("http://192.0.2.10:7878"), - "ws://192.0.2.10:7878/v1/portal" + address("unix:/run/berth/serve.sock"), + "unix:/run/berth/serve.sock" ); + assert!(local(HERE) && !local("https://studio.example")); + assert_eq!(shown(HERE), "this machine"); } } diff --git a/crates/berth-page/src/installed.rs b/crates/berth-page/src/installed.rs index efb21b5..ba486e1 100644 --- a/crates/berth-page/src/installed.rs +++ b/crates/berth-page/src/installed.rs @@ -49,12 +49,8 @@ impl Installed { pub fn claim(server: &str, key: String) -> Installed { let claim = Rc::new(RefCell::new(Claim::Asking)); let answered = claim.clone(); - device::request( - "POST", - &format!("{server}/v1/setup-key"), - &key, - move |answer| { - *answered.borrow_mut() = match answer { + device::request("POST", server, "/v1/setup-key", &key, move |answer| { + *answered.borrow_mut() = match answer { Ok((200, body)) => { let said: Value = serde_json::from_str(&body).unwrap_or(Value::Null); let text = |name: &str| said[name].as_str().unwrap_or("").to_owned(); @@ -79,8 +75,7 @@ impl Installed { } Err(error) => Claim::Failed(format!("The server did not answer: {error}")), }; - }, - ); + }); Installed { server: server.to_owned(), key, @@ -140,7 +135,8 @@ impl Installed { pub fn done(&self, then: impl FnOnce(Option) + 'static) { device::request( "DELETE", - &format!("{}/v1/setup-key", self.server), + &self.server, + "/v1/setup-key", &self.key, move |answer| { then(match answer { diff --git a/crates/berth-page/src/portal.rs b/crates/berth-page/src/portal.rs index 1170d00..2186917 100644 --- a/crates/berth-page/src/portal.rs +++ b/crates/berth-page/src/portal.rs @@ -172,9 +172,9 @@ fn request(id: u32, op: &str, host: Option<&str>, args: Value, data: Value) -> V } impl Portal { - /// Open the portal at `url`, showing the token as the WebSocket's + /// Open the portal of `server`, showing the token as the WebSocket's /// protocol. - pub fn open(url: &str, token: &str) -> Result { + pub fn open(server: &str, token: &str) -> Result { let inner = Rc::new(Inner { socket: RefCell::default(), link: Cell::new(Link::Connecting), @@ -185,7 +185,8 @@ impl Portal { }); let weak: Weak = Rc::downgrade(&inner); let socket = device::device().connect( - url, + server, + berth_api::ops::PORTAL, token, Box::new(move |said| { if let Some(inner) = weak.upgrade() { @@ -326,18 +327,19 @@ mod tests { fn linked(&self) -> Linked { Linked::default() } - fn request(&self, _: &str, _: &str, _: &str, then: Answer) { + fn request(&self, _: &str, _: &str, _: &str, _: &str, then: Answer) { then(Err("no".into())) } fn connect( &self, - url: &str, + server: &str, + path: &str, token: &str, said: Box, ) -> Result, String> { assert_eq!( - (url, token), - ("ws://192.0.2.10:7878/v1/portal", "the-token") + (server, path, token), + ("http://192.0.2.10:7878", "/v1/portal", "the-token") ); *self.said.borrow_mut() = Some(said); Ok(Box::new(WireSocket(self.sent.clone()))) @@ -347,7 +349,7 @@ mod tests { fn portal() -> (Wire, Portal) { let wire = Wire::default(); device::install(wire.clone()); - let portal = Portal::open("ws://192.0.2.10:7878/v1/portal", "the-token").unwrap(); + let portal = Portal::open("http://192.0.2.10:7878", "the-token").unwrap(); (wire, portal) } diff --git a/crates/berth-remote/src/device.rs b/crates/berth-remote/src/device.rs index 226d875..1e83284 100644 --- a/crates/berth-remote/src/device.rs +++ b/crates/berth-remote/src/device.rs @@ -161,18 +161,27 @@ impl Device for Terminal { self.linked.clone() } - fn request(&self, method: &str, url: &str, bearer: &str, then: Answer) { - let (method, url, bearer) = (method.to_owned(), url.to_owned(), bearer.to_owned()); - net::later(async move { net::http(&method, &url, &bearer).await }, then); + fn request(&self, method: &str, server: &str, path: &str, bearer: &str, then: Answer) { + let (method, server, path, bearer) = ( + method.to_owned(), + server.to_owned(), + path.to_owned(), + bearer.to_owned(), + ); + net::later( + async move { net::http(&method, &server, &path, &bearer).await }, + then, + ); } fn connect( &self, - url: &str, + server: &str, + path: &str, token: &str, said: Box, ) -> Result, String> { - let socket = socket::open(url, token, said)?; + let socket = socket::open(server, path, token, said)?; Ok(Box::new(socket)) } } diff --git a/crates/berth-remote/src/lib.rs b/crates/berth-remote/src/lib.rs index 336f7d4..9708621 100644 --- a/crates/berth-remote/src/lib.rs +++ b/crates/berth-remote/src/lib.rs @@ -9,6 +9,7 @@ pub mod device; pub mod keys; pub mod net; pub mod options; +pub mod screens; pub mod settings; pub mod socket; diff --git a/crates/berth-remote/src/main.rs b/crates/berth-remote/src/main.rs index 782eac4..d5eaec7 100644 --- a/crates/berth-remote/src/main.rs +++ b/crates/berth-remote/src/main.rs @@ -1,9 +1,7 @@ //! berth-remote: the hosts of a berth serve, in this terminal. use berth_remote::options::{self, Parsed}; -use berth_remote::{device, keys, settings}; -use crossterm::event::{self, Event as Native, KeyCode, KeyEventKind, KeyModifiers}; -use std::time::Duration; +use berth_remote::{device, settings}; fn main() { let options = match options::parse(std::env::args().skip(1), |name| std::env::var(name).ok()) { @@ -29,69 +27,8 @@ fn main() { std::process::exit(1); } } - if let Err(error) = run() { + if let Err(error) = berth_remote::screens::run(None) { eprintln!("berth-remote: {error}"); std::process::exit(1); } } - -/// Stop the mouse and paste reports, which ratatui's own restore leaves on. -fn stop_reports() { - let _ = crossterm::execute!( - std::io::stdout(), - event::DisableBracketedPaste, - event::DisableMouseCapture - ); -} - -fn run() -> std::io::Result<()> { - let mut terminal = ratatui::init(); - let restore = std::panic::take_hook(); - std::panic::set_hook(Box::new(move |info| { - stop_reports(); - restore(info); - })); - // Not every terminal of Windows knows bracketed paste: there a paste - // arrives as keys. - let _ = crossterm::execute!( - std::io::stdout(), - event::EnableMouseCapture, - event::EnableBracketedPaste - ); - let outcome = screens(&mut terminal); - stop_reports(); - ratatui::restore(); - outcome -} - -fn screens(terminal: &mut ratatui::DefaultTerminal) -> std::io::Result<()> { - let mut app = berth_page::App::new(); - loop { - berth_remote::pump(); - app.tick(); - terminal.draw(|frame| app.draw(frame))?; - // Wait a little for input; what the network says is taken in on the next turn. - if !keys::poll(Duration::from_millis(30))? { - continue; - } - loop { - match keys::read()? { - Native::Key(key) - if key.kind != KeyEventKind::Release - && key.modifiers.contains(KeyModifiers::CONTROL) - && matches!(key.code, KeyCode::Char('q' | 'Q')) => - { - return Ok(()); - } - native => { - if let Some(event) = keys::event(&native) { - app.event(event); - } - } - } - if !keys::poll(Duration::ZERO)? { - break; - } - } - } -} diff --git a/crates/berth-remote/src/net.rs b/crates/berth-remote/src/net.rs index 7d35485..b4385a1 100644 --- a/crates/berth-remote/src/net.rs +++ b/crates/berth-remote/src/net.rs @@ -5,13 +5,9 @@ use berth_api::client::{self, Error}; use std::cell::RefCell; use std::future::Future; use std::sync::{Arc, OnceLock, mpsc}; -use tokio::io::{AsyncRead, AsyncWrite}; use tokio::net::TcpStream; -/// A connection, over TLS or not. -pub trait Io: AsyncRead + AsyncWrite + Unpin + Send {} -impl Io for T {} -pub type Stream = Box; +pub use berth_api::client::Stream; /// The runtime the connections run on; the screens stay on the main thread. pub fn runtime() -> &'static tokio::runtime::Runtime { @@ -25,34 +21,63 @@ pub fn runtime() -> &'static tokio::runtime::Runtime { }) } -/// Where an address goes: the name and port to connect to, the authority to -/// name in requests, the path after it, and whether over TLS. +/// How a server is reached. +pub enum Way { + /// Over TCP, with TLS when `secure`. + Network { + name: String, + port: u16, + secure: bool, + }, + /// The socket of a `berth serve` on this machine. + Socket(std::path::PathBuf), + /// The server in this process. + Here, +} + +/// Where a request goes: how the server is reached, the authority to name in +/// requests, and the path. pub struct Target { - pub name: String, - pub port: u16, + pub way: Way, pub authority: String, pub path: String, - pub secure: bool, } -/// Take an `http(s)://` or `ws(s)://` address apart. -pub fn target(url: &str) -> Result { - let (secure, rest) = if let Some(rest) = url - .strip_prefix("https://") - .or_else(|| url.strip_prefix("wss://")) - { +/// The server in this process, when the program runs one. +static HERE: OnceLock = OnceLock::new(); + +/// Reach `here:` through `dial`, for the rest of the program. +pub fn serve_here(dial: client::Dial) { + let _ = HERE.set(dial); +} + +/// Where `path` of `server` is: `http(s)://HOST[:PORT]`, `unix:/path` or `here:`. +pub fn target(server: &str, path: &str) -> Result { + if server == berth_page::device::HERE { + return Ok(Target { + way: Way::Here, + authority: "berth".into(), + path: path.to_owned(), + }); + } + if let Some(socket) = server.strip_prefix("unix:") { + return Ok(Target { + way: Way::Socket(socket.into()), + authority: "berth".into(), + path: path.to_owned(), + }); + } + let (secure, rest) = if let Some(rest) = server.strip_prefix("https://") { (true, rest) - } else if let Some(rest) = url - .strip_prefix("http://") - .or_else(|| url.strip_prefix("ws://")) - { + } else if let Some(rest) = server.strip_prefix("http://") { (false, rest) } else { - return Err(format!("{url} is no http:// or https:// address")); + return Err(format!("{server} is no http:// or https:// address")); }; - let (authority, path) = match rest.find('/') { - Some(at) => (&rest[..at], &rest[at..]), - None => (rest, "/"), + // What follows the authority is the server's own prefix, before the path. + let (authority, prefix) = match rest.find('/') { + Some(at) => (&rest[..at], rest[at..].trim_end_matches('/')), + None => (rest, ""), }; let default = if secure { 443 } else { 80 }; let (host, port) = match authority.rsplit_once(':') { @@ -64,14 +89,16 @@ pub fn target(url: &str) -> Result { _ => (authority, default), }; if host.is_empty() { - return Err(format!("{url} names no host")); + return Err(format!("{server} names no host")); } Ok(Target { - name: host.trim_matches(['[', ']']).to_owned(), - port, + way: Way::Network { + name: host.trim_matches(['[', ']']).to_owned(), + port, + secure, + }, authority: format!("{host}:{port}"), - path: path.to_owned(), - secure, + path: format!("{prefix}{path}"), }) } @@ -98,15 +125,36 @@ fn tls() -> Arc { /// Connect to where `target` points, with TLS when it says so. pub async fn connect(target: &Target) -> Result { - let stream = TcpStream::connect((target.name.as_str(), target.port)) + let (name, port, secure) = match &target.way { + Way::Here => { + let dial = HERE.get().ok_or("There is no server in this program")?; + return dial().await.map_err(|error| describe(&error)); + } + #[cfg(unix)] + Way::Socket(path) => { + let stream = tokio::net::UnixStream::connect(path) + .await + .map_err(|error| format!("{}: {error}", path.display()))?; + return Ok(Box::new(stream)); + } + #[cfg(not(unix))] + Way::Socket(path) => { + return Err(format!( + "{} is a socket, which this system has none of", + path.display() + )); + } + Way::Network { name, port, secure } => (name, *port, *secure), + }; + let stream = TcpStream::connect((name.as_str(), port)) .await .map_err(|error| format!("{}: {error}", target.authority))?; let _ = stream.set_nodelay(true); - if !target.secure { + if !secure { return Ok(Box::new(stream)); } - let name = rustls::pki_types::ServerName::try_from(target.name.clone()) - .map_err(|error| error.to_string())?; + let name = + rustls::pki_types::ServerName::try_from(name.clone()).map_err(|error| error.to_string())?; let stream = tokio_rustls::TlsConnector::from(tls()) .connect(name, stream) .await @@ -115,8 +163,13 @@ pub async fn connect(target: &Target) -> Result { } /// One request with a bearer: the status and the body of the answer. -pub async fn http(method: &str, url: &str, bearer: &str) -> Result<(u16, String), String> { - let target = target(url)?; +pub async fn http( + method: &str, + server: &str, + path: &str, + bearer: &str, +) -> Result<(u16, String), String> { + let target = target(server, path)?; let stream = connect(&target).await?; let mut client = client::Client::over(stream) .await @@ -208,28 +261,41 @@ pub fn pump() { mod tests { use super::*; + fn network(target: &Target) -> (&str, u16, bool) { + match &target.way { + Way::Network { name, port, secure } => (name, *port, *secure), + _ => panic!("not over the network"), + } + } + #[test] fn addresses_are_taken_apart() { - let at = target("wss://studio.example/v1/portal").unwrap(); + let at = target("https://studio.example", "/v1/portal").unwrap(); + assert_eq!(network(&at), ("studio.example", 443, true)); assert_eq!( - (at.name.as_str(), at.port, at.authority.as_str()), - ("studio.example", 443, "studio.example:443") + (at.authority.as_str(), at.path.as_str()), + ("studio.example:443", "/v1/portal") ); - assert_eq!((at.path.as_str(), at.secure), ("/v1/portal", true)); - let at = target("http://192.0.2.10:7878").unwrap(); - assert_eq!((at.name.as_str(), at.port), ("192.0.2.10", 7878)); - assert_eq!((at.path.as_str(), at.secure), ("/", false)); - let at = target("ws://[2001:db8::1]:7878/v1/portal").unwrap(); - assert_eq!((at.name.as_str(), at.port), ("2001:db8::1", 7878)); - let at = target("https://[2001:db8::1]/").unwrap(); - assert_eq!((at.name.as_str(), at.port), ("2001:db8::1", 443)); + let at = target("http://192.0.2.10:7878", "/v1/access").unwrap(); + assert_eq!(network(&at), ("192.0.2.10", 7878, false)); + let at = target("http://[2001:db8::1]:7878/berth/", "/v1/portal").unwrap(); + assert_eq!(network(&at), ("2001:db8::1", 7878, false)); + assert_eq!(at.path, "/berth/v1/portal"); + let at = target("https://[2001:db8::1]", "/").unwrap(); + assert_eq!(network(&at).1, 443); + let at = target("unix:/run/user/1000/berth/serve.sock", "/v1/portal").unwrap(); + assert!(matches!(&at.way, Way::Socket(path) if path.ends_with("serve.sock"))); + assert!(matches!( + target("here:", "/v1/portal").unwrap().way, + Way::Here + )); for wrong in [ "studio.example", "ftp://studio.example", "https://", "http://studio:port", ] { - assert!(target(wrong).is_err(), "{wrong}"); + assert!(target(wrong, "/").is_err(), "{wrong}"); } } } diff --git a/crates/berth-remote/src/screens.rs b/crates/berth-remote/src/screens.rs new file mode 100644 index 0000000..bbbcf42 --- /dev/null +++ b/crates/berth-remote/src/screens.rs @@ -0,0 +1,71 @@ +//! The screens in a terminal: drawing, and the keys and mouse taken in. + +use crate::keys; +use crossterm::event::{self, Event as Native, KeyCode, KeyEventKind, KeyModifiers}; +use std::time::Duration; + +/// Stop the mouse and paste reports, which ratatui's own restore leaves on. +fn stop_reports() { + let _ = crossterm::execute!( + std::io::stdout(), + event::DisableBracketedPaste, + event::DisableMouseCapture + ); +} + +/// The screens in this terminal until Ctrl+Q, opening the host `open` once +/// the server has listed it. +pub fn run(open: Option) -> std::io::Result<()> { + let mut terminal = ratatui::init(); + let restore = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + stop_reports(); + restore(info); + })); + // Not every terminal of Windows knows bracketed paste: there a paste + // arrives as keys. + let _ = crossterm::execute!( + std::io::stdout(), + event::EnableMouseCapture, + event::EnableBracketedPaste + ); + let outcome = screens(&mut terminal, open); + stop_reports(); + ratatui::restore(); + outcome +} + +fn screens(terminal: &mut ratatui::DefaultTerminal, open: Option) -> std::io::Result<()> { + let mut app = berth_page::App::new(); + if let Some(host) = open { + app.open_when_listed(&host); + } + loop { + crate::pump(); + app.tick(); + terminal.draw(|frame| app.draw(frame))?; + // Wait a little for input; what the network says is taken in on the next turn. + if !keys::poll(Duration::from_millis(30))? { + continue; + } + loop { + match keys::read()? { + Native::Key(key) + if key.kind != KeyEventKind::Release + && key.modifiers.contains(KeyModifiers::CONTROL) + && matches!(key.code, KeyCode::Char('q' | 'Q')) => + { + return Ok(()); + } + native => { + if let Some(event) = keys::event(&native) { + app.event(event); + } + } + } + if !keys::poll(Duration::ZERO)? { + break; + } + } + } +} diff --git a/crates/berth-remote/src/socket.rs b/crates/berth-remote/src/socket.rs index 30fedc8..e40e1f0 100644 --- a/crates/berth-remote/src/socket.rs +++ b/crates/berth-remote/src/socket.rs @@ -42,9 +42,14 @@ impl Socket for NativeSocket { } } -/// Open a WebSocket to `url`, with `token` as its protocol. -pub fn open(url: &str, token: &str, to: Box) -> Result { - let target = net::target(url)?; +/// Open a WebSocket to `path` of `server`, with `token` as its protocol. +pub fn open( + server: &str, + path: &str, + token: &str, + to: Box, +) -> Result { + let target = net::target(server, path)?; let (out, outgoing) = unbounded_channel(); let (said, heard) = mpsc::channel(); net::runtime().spawn(run(target, token.to_owned(), outgoing, said)); diff --git a/crates/berth/Cargo.toml b/crates/berth/Cargo.toml index e9050e4..19650cb 100644 --- a/crates/berth/Cargo.toml +++ b/crates/berth/Cargo.toml @@ -28,10 +28,9 @@ pulldown-cmark = { version = "0.13", default-features = false } jsonwebtoken = { version = "11", default-features = false, features = ["rust_crypto"] } tui-input = { workspace = true, features = ["crossterm"] } +berth-page.workspace = true +berth-remote = { path = "../berth-remote" } [dev-dependencies] # Signs the access tokens of the tests. ring = "0.17" -# berth-remote signs in to a berth serve of the tests. -berth-page.workspace = true -berth-remote = { path = "../berth-remote" } diff --git a/crates/berth/src/main.rs b/crates/berth/src/main.rs index 782f666..98ccbda 100644 --- a/crates/berth/src/main.rs +++ b/crates/berth/src/main.rs @@ -31,6 +31,9 @@ const USAGE: &str = "berth: set up and look after agent workstations. Usage: berth choose a host, or create one berth HOST open a host (a saved name, or a path to a profile) + berth ui [HOST] the screens of berth serve: of the server this berth + uses, of a berth serve of yours on this machine, or of + one that runs in berth itself until it ends berth list saved hosts berth host add NAME ADDRESS [--user USER] [--port PORT] [--auth AUTH] [--type ssh|managed|workstation] [--no-contact] @@ -280,6 +283,7 @@ fn opens_screen(args: &[&str]) -> bool { "kv", "store", "help", + "ui", ]; match args { [] => true, @@ -543,6 +547,56 @@ fn no_terminal(paths: &Paths, word: Option<&str>) -> String { } } +/// `berth ui [HOST]`: the screens of a server, as `berth-remote` shows +/// them: the server this berth is set to use, a `berth serve` of this user +/// on this machine, or else one in this process for as long as they are open. +fn screens(paths: &Paths, host: Option<&str>) -> Result<()> { + use std::io::IsTerminal; + if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() { + return Err(no_terminal(paths, host).into()); + } + let mut here = None; + let (server, token) = match berth_core::server::Server::configured(paths) { + Some(server) => (server.url, server.token), + None => { + let socket = serve::here::socket(); + if std::os::unix::net::UnixStream::connect(&socket).is_ok() { + (format!("unix:{}", socket.display()), None) + } else { + let started = serve::here::Here::start(paths)?; + berth_remote::net::serve_here(started.dial()); + here = Some(started); + (berth_page::device::HERE.to_owned(), None) + } + } + }; + let linked = berth_page::device::Linked { + server: Some(server), + token, + setup_key: None, + }; + let device = berth_remote::device::Terminal::new( + linked, + berth_remote::settings::Settings::new(None), + false, + )?; + berth_page::device::install(device); + let shown = berth_remote::screens::run(host.map(str::to_owned)); + if let Some(here) = &here { + here.wait_for_jobs(|jobs| { + let names: Vec = jobs + .iter() + .map(|job| format!("{} {}", job.action, job.host).trim().to_owned()) + .collect(); + eprintln!( + "berth: waiting for what runs in this berth to end: {}. Ctrl+C stops it unfinished; berth serve keeps jobs running after the screens close.", + names.join(", ") + ); + }); + } + Ok(shown?) +} + fn main() { end_quietly_on_a_closed_pipe(); if let Err(error) = run() { @@ -608,6 +662,7 @@ fn run() -> Result<()> { "connect", "setup-key", "store", + "ui", ]; // The screen opens at once on what the last mirror left; the commands // that print are given current data. @@ -705,6 +760,8 @@ fn run() -> Result<()> { } ["update", ref rest @ ..] => return update::command(rest), ["serve", ref rest @ ..] => return serve::command(&paths, rest), + ["ui"] => return screens(&paths, None), + ["ui", host] => return screens(&paths, Some(host)), ["setup-key", ref rest @ ..] => return serve::setup_key::command(&paths, rest), ["connect", url] => return commands::connect(&paths, url), ["inbox", ref rest @ ..] => return serve::inbox_command(&paths, rest), diff --git a/crates/berth/src/serve/auth.rs b/crates/berth/src/serve/auth.rs index e0ba061..f0580ee 100644 --- a/crates/berth/src/serve/auth.rs +++ b/crates/berth/src/serve/auth.rs @@ -78,6 +78,16 @@ impl Auth { }) } + /// Nobody over the network, for a server that has no listener there: + /// its one caller is the owner, who sets it up. + pub fn nobody() -> Auth { + Auth { + token: None, + setup: true, + oauth: None, + } + } + /// Only the server's own token, with set-up open. #[cfg(test)] pub fn token(token: Option) -> Auth { diff --git a/crates/berth/src/serve/here.rs b/crates/berth/src/serve/here.rs new file mode 100644 index 0000000..41c7c6a --- /dev/null +++ b/crates/berth/src/serve/here.rs @@ -0,0 +1,250 @@ +//! This installation's API for a client in the same process, which berth's +//! screens use when no server is set: the router of berth serve's own +//! socket, over pipes in memory. Like a caller on that socket, the caller is +//! the user the installation belongs to, so it is an admin and shows no +//! token. Nothing listens anywhere: only this process can reach it. + +use super::{Serve, api, auth}; +use crate::Result; +use berth_api::client::{Dial, Error, Stream}; +use berth_core::{paths::Paths, store}; +use std::sync::Arc; +use std::time::Duration; +use tokio::io::DuplexStream; +use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; + +/// How much a pipe holds in each direction before a writer waits. +const PIPE: usize = 256 * 1024; + +/// The socket a running `berth serve` of this user answers on, which is +/// only its user's. +pub fn socket() -> std::path::PathBuf { + berth_core::link::runtime_dir().join("serve.sock") +} + +/// The pipes clients open, as connections that axum serves. +struct Pipes(UnboundedReceiver); + +impl axum::serve::Listener for Pipes { + type Io = DuplexStream; + type Addr = (); + + async fn accept(&mut self) -> (DuplexStream, ()) { + match self.0.recv().await { + Some(pipe) => (pipe, ()), + // Every client is gone, and none can come. + None => std::future::pending().await, + } + } + + fn local_addr(&self) -> std::io::Result<()> { + Ok(()) + } +} + +pub struct Here { + state: Arc, + connections: UnboundedSender, + /// Runs the server's tasks, and ends them when dropped. + _runtime: tokio::runtime::Runtime, +} + +impl Here { + /// Open the store and serve its API to this process. The hosts' channels + /// are left to `berth serve`, and so are jobs a server before left + /// unfinished, which another berth beside this one may be running. + pub fn start(paths: &Paths) -> Result { + let store = super::open_store(paths)?; + crate::restore_plugins(paths); + let mut state = Serve::with(paths.clone(), store, auth::Auth::nobody()); + if let Some(state) = Arc::get_mut(&mut state) { + state.follows = false; + } + std::fs::create_dir_all(&state.jobs_dir)?; + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .thread_name("berth-here") + .enable_all() + .build()?; + let (connections, pipes) = unbounded_channel(); + let router = api::router(state.clone(), false); + let serving = state.clone(); + runtime.spawn(async move { + serving.refresh(false); + let _ = axum::serve(Pipes(pipes), router).await; + }); + // Another berth beside this one changes the store too. + let watching = state.clone(); + runtime.spawn(async move { + loop { + tokio::time::sleep(Duration::from_secs(5)).await; + if watching.events.receiver_count() > 0 { + watching.notice(); + } + } + }); + Ok(Here { + state, + connections, + _runtime: runtime, + }) + } + + /// A new connection to the server for each call. + pub fn dial(&self) -> Dial { + let connections = self.connections.clone(); + Arc::new(move || { + let connections = connections.clone(); + Box::pin(async move { + let (client, server) = tokio::io::duplex(PIPE); + connections + .send(server) + .map_err(|_| Error::Transport("berth's own server has stopped".into()))?; + Ok(Box::new(client) as Stream) + }) + }) + } + + /// The jobs that run in this process, which end when it does. + pub fn running(&self) -> Vec { + self.state.runner.running() + } + + /// Wait until no job runs in this process, saying first which do. + pub fn wait_for_jobs(&self, say: impl Fn(&[store::Job])) { + let running = self.running(); + if running.is_empty() { + return; + } + say(&running); + while !self.running().is_empty() { + std::thread::sleep(Duration::from_millis(200)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use berth_api::client::{self, Client, Frame}; + use futures_util::StreamExt; + use serde_json::{Value, json}; + + fn scratch() -> (tempfile::TempDir, Paths) { + let dir = tempfile::tempdir().unwrap(); + let paths = Paths { + config_dir: dir.path().join("config"), + data_dir: dir.path().join("data"), + }; + (dir, paths) + } + + #[test] + fn a_client_in_the_process_calls_streams_and_runs_a_job_to_its_end() { + let (_dir, paths) = scratch(); + let profile = json!({"hostname": "dock", "builder": {}, "access": {"address": "192.0.2.7", "link": ["sh", "-c", "exit 1"]}}); + berth_core::profiles::Place::own("dock") + .unwrap() + .save(&paths, &profile) + .unwrap(); + let here = Here::start(&paths).unwrap(); + let dial = here.dial(); + // The client has a runtime of its own, as the screens do. + let client_runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + client_runtime.block_on(async { + // A call, as the owner, with no token. + let mut client = Client::over(dial().await.unwrap()).await.unwrap(); + let access: Value = client.get("/v1/access").await.unwrap(); + assert_eq!( + (&access["role"], &access["setup"]), + (&json!("admin"), &json!(true)) + ); + + // The portal over a connection of its own. + let socket = client::websocket(dial().await.unwrap(), berth_api::ops::PORTAL, "") + .await + .unwrap(); + let portal = berth_api::portal::Portal::over(socket); + let hosts = portal + .call("hosts.list", None, json!({}), None) + .await + .unwrap(); + assert_eq!(hosts[0]["name"], "dock", "{hosts}"); + + // A job, followed on its stream to its end. + let body = json!({"arguments": {"name": "studio", "hostname": "yes"}}); + let answer = client + .send( + "POST", + "/v1/hosts/dock/actions/rename", + &[("content-type", "application/json")], + body.to_string().into(), + ) + .await + .unwrap(); + assert_eq!(answer.status, 202); + let acted: Value = serde_json::from_slice(&answer.body).unwrap(); + let id = acted["job"]["id"].as_str().unwrap().to_owned(); + let mut stream = + client::websocket(dial().await.unwrap(), &format!("/v1/jobs/{id}"), "") + .await + .unwrap(); + let ended = loop { + let frame = tokio::time::timeout(Duration::from_secs(20), stream.next()) + .await + .expect("a frame in time"); + match frame { + Some(Ok(Frame::Text(text))) => { + let said: Value = serde_json::from_str(text.as_str()).unwrap(); + if said["exited"].is_object() { + break said["exited"].clone(); + } + } + Some(Ok(_)) => {} + other => panic!("the stream ended: {other:?}"), + } + }; + assert_eq!(ended["exit_code"], 0, "{ended}"); + }); + here.wait_for_jobs(|_| {}); + assert!(here.running().is_empty()); + assert!( + berth_core::profiles::Place::own("studio") + .unwrap() + .load(&paths) + .unwrap() + .is_some() + ); + } + + #[test] + fn nothing_listens_for_it() { + let (dir, paths) = scratch(); + let _here = Here::start(&paths).unwrap(); + // No socket, no token and no port are made for a server in the process. + assert!(!paths.data_dir.join("serve.token").exists()); + let made: Vec<_> = walk(dir.path()); + assert!( + !made + .iter() + .any(|path| path.extension().is_some_and(|end| end == "sock")), + "{made:?}" + ); + } + + fn walk(dir: &std::path::Path) -> Vec { + let mut found = vec![]; + for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let path = entry.path(); + if path.is_dir() { + found.extend(walk(&path)); + } else { + found.push(path); + } + } + found + } +} diff --git a/crates/berth/src/serve/mod.rs b/crates/berth/src/serve/mod.rs index 21bbe5a..2bcb5a6 100644 --- a/crates/berth/src/serve/mod.rs +++ b/crates/berth/src/serve/mod.rs @@ -6,6 +6,7 @@ mod actions; mod api; mod auth; mod docs; +pub mod here; pub(crate) mod keys; mod provisioners; mod resources; @@ -18,7 +19,7 @@ use crate::Result; use berth_api::{Message, Version, client}; use berth_core::{ host::Host, - link::{Link, LinkSpec, runtime_dir}, + link::{Link, LinkSpec}, paths::Paths, store::{self, Filter, Store, Stored, When}, }; @@ -254,6 +255,9 @@ pub struct Serve { /// How long provisioners may take and how a new machine is waited for, /// which tests make quick. pub provision: fn() -> berth_core::provision::Options, + /// Whether the hosts' channels are taken in, which only `berth serve` + /// does, holding its lock. + pub follows: bool, watch: Arc, } @@ -292,6 +296,7 @@ impl Serve { followers: Mutex::new(BTreeMap::new()), passwords: Mutex::new(BTreeMap::new()), provision: Default::default, + follows: true, watch, }) } @@ -313,7 +318,7 @@ impl Serve { .write() .unwrap() .insert(remote.name.clone(), remote.clone()); - if remote.link.is_some() { + if remote.link.is_some() && self.follows { let follower = tokio::spawn(take_in(self.clone(), remote.clone())); let before = self .followers @@ -635,7 +640,7 @@ pub fn command(paths: &Paths, args: &[&str]) -> Result<()> { } }); - let socket = runtime_dir().join("serve.sock"); + let socket = here::socket(); let _ = std::fs::remove_file(&socket); let unix = tokio::net::UnixListener::bind(&socket)?; { diff --git a/crates/berth/src/serve/tests/remote.rs b/crates/berth/src/serve/tests/remote.rs index f782dc1..5da7ce1 100644 --- a/crates/berth/src/serve/tests/remote.rs +++ b/crates/berth/src/serve/tests/remote.rs @@ -89,7 +89,7 @@ async fn berth_remote_signs_in_with_a_setup_key_and_uses_the_portal() { }); // The portal answers with the token, and a wrong one is refused. - let portal = Portal::open(&berth_page::device::portal_url(&url), "s3cret-token").unwrap(); + let portal = Portal::open(&url, "s3cret-token").unwrap(); let hosts = Rc::new(RefCell::new(None)); let answer = hosts.clone(); portal.call("hosts.list", None, json!({}), Value::Null, move |result| { @@ -98,7 +98,7 @@ async fn berth_remote_signs_in_with_a_setup_key_and_uses_the_portal() { until("answer", || hosts.borrow().is_some()); assert_eq!(portal.link(), Link::Open); assert_eq!(hosts.borrow_mut().take().unwrap(), Ok(json!([]))); - let refused = Portal::open(&berth_page::device::portal_url(&url), "wrong").unwrap(); + let refused = Portal::open(&url, "wrong").unwrap(); until("refusal", || refused.link() != Link::Connecting); assert_eq!(refused.link(), Link::Refused); From 94d0560658fbfc8cbb63d1b390fafff93ee37b3a Mon Sep 17 00:00:00 2001 From: Helight Date: Sun, 15 Nov 2026 01:04:27 +0100 Subject: [PATCH 14/94] refactor(page)!: the screens' terminal, network and settings are berth-page's berth-remote's device becomes plain code in berth-page, with no Device trait. The server and its token are kept as berth's own server and server_token settings; berth ui takes in berth-remote's settings.json once. Ctrl+Q leaves a session and quits elsewhere, q quits from the hosts, and F4 and F5 generate and hash in the set-up, as in berth's terminal UI. BERTH_REMOTE_FILE is BERTH_FILE. --- Cargo.lock | 20 +- crates/berth-page/Cargo.toml | 16 +- crates/berth-page/src/app.rs | 30 +- crates/berth-page/src/device.rs | 158 +++++---- .../{berth-remote => berth-page}/src/keys.rs | 0 crates/berth-page/src/lib.rs | 18 +- .../{berth-remote => berth-page}/src/net.rs | 2 +- crates/berth-page/src/portal.rs | 78 ++--- .../src/screens.rs | 24 +- crates/berth-page/src/settings.rs | 318 ++++++++++++++++++ crates/berth-page/src/setup.rs | 27 +- .../src/socket.rs | 16 +- .../device.rs => berth-page/src/terminal.rs} | 300 +++++------------ crates/berth-remote/Cargo.toml | 13 - crates/berth-remote/src/lib.rs | 19 +- crates/berth-remote/src/main.rs | 18 +- crates/berth-remote/src/settings.rs | 224 ------------ crates/berth-tui/src/screen.rs | 21 +- crates/berth/Cargo.toml | 1 - crates/berth/src/main.rs | 60 ++-- crates/berth/src/serve/tests/remote.rs | 37 +- crates/berth/src/ui.rs | 2 +- 22 files changed, 671 insertions(+), 731 deletions(-) rename crates/{berth-remote => berth-page}/src/keys.rs (100%) rename crates/{berth-remote => berth-page}/src/net.rs (99%) rename crates/{berth-remote => berth-page}/src/screens.rs (68%) create mode 100644 crates/berth-page/src/settings.rs rename crates/{berth-remote => berth-page}/src/socket.rs (92%) rename crates/{berth-remote/src/device.rs => berth-page/src/terminal.rs} (54%) delete mode 100644 crates/berth-remote/src/settings.rs diff --git a/Cargo.lock b/Cargo.lock index c6f9b34..1c54968 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -169,7 +169,6 @@ dependencies = [ "berth-core", "berth-page", "berth-pty", - "berth-remote", "berth-tui", "berthd", "crossterm", @@ -234,9 +233,17 @@ version = "0.5.2" dependencies = [ "berth-api", "berth-tui", + "crossterm", + "futures-util", "ratatui", + "rustls", + "rustls-native-certs", "serde_json", + "tempfile", + "tokio", + "tokio-rustls", "tui-input", + "webpki-roots", ] [[package]] @@ -252,17 +259,6 @@ version = "0.5.2" dependencies = [ "berth-api", "berth-page", - "berth-tui", - "crossterm", - "futures-util", - "ratatui", - "rustls", - "rustls-native-certs", - "serde_json", - "tempfile", - "tokio", - "tokio-rustls", - "webpki-roots", ] [[package]] diff --git a/crates/berth-page/Cargo.toml b/crates/berth-page/Cargo.toml index c071329..fc7fc51 100644 --- a/crates/berth-page/Cargo.toml +++ b/crates/berth-page/Cargo.toml @@ -4,11 +4,21 @@ version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true -description = "The screens of a berth serve elsewhere and its portal, for berth-remote" +description = "The screens of berth in a terminal, over the API of a berth serve, on Linux, macOS and Windows" [dependencies] -berth-api.workspace = true +berth-api = { workspace = true, features = ["client"] } berth-tui.workspace = true serde_json.workspace = true tui-input.workspace = true -ratatui = { version = "=0.30.2", default-features = false } +ratatui = { version = "=0.30.2", default-features = false, features = ["crossterm"] } +crossterm = "=0.29.0" +tokio.workspace = true +futures-util.workspace = true +rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } +tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] } +webpki-roots = "1" +rustls-native-certs = "0.8" + +[dev-dependencies] +tempfile.workspace = true diff --git a/crates/berth-page/src/app.rs b/crates/berth-page/src/app.rs index 85b86e1..5f77bb2 100644 --- a/crates/berth-page/src/app.rs +++ b/crates/berth-page/src/app.rs @@ -35,8 +35,8 @@ const RETRY: Duration = Duration::from_secs(3); const SAID_FOR: Duration = Duration::from_secs(5); /// What the status line says while the server is away. const AWAY: &str = "The berth server does not answer; trying again…"; -/// The key that leaves a running session, as Ctrl+Q quits the program. -const LEAVE: &str = "Alt+Q"; +/// The key that leaves a running session, and elsewhere quits. +const LEAVE: &str = "Ctrl+Q"; #[derive(PartialEq)] enum Screen { @@ -146,6 +146,8 @@ pub struct App { installed: Option, /// A host to open once the server has listed its hosts. wanted: Option, + /// The screens are left. + quit: bool, } impl App { @@ -213,6 +215,7 @@ impl App { qr: None, installed: None, wanted: None, + quit: false, }; // A setup key signs in with the token it collects, whatever was kept. if let (Some(key), false) = (linked.setup_key, app.server.is_empty()) { @@ -231,6 +234,11 @@ impl App { device::local(&self.server) } + /// Whether the screens were left, with Ctrl+Q or q on the list of hosts. + pub fn quit(&self) -> bool { + self.quit + } + /// Open the host `name` once the server has listed it. pub fn open_when_listed(&mut self, name: &str) { self.wanted = Some(name.to_owned()); @@ -1031,7 +1039,7 @@ impl App { }; draw_footer(frame, footer, keys, &self.status, theme::ACCENT); (self.links, self.words) = match &self.host.view { - Some(view) => draw_view(frame, view, &self.status, LEAVE), + Some(view) => draw_view(frame, view, &self.status), None => (vec![], vec![]), }; if let Some((question, _)) = &self.host.question { @@ -1167,6 +1175,7 @@ impl App { _ => {} }, Code::Char('o') if !self.local() => self.sign_out(""), + Code::Char('q') => self.quit = true, _ => {} } } @@ -1459,12 +1468,12 @@ impl App { let keys = match (admin, self.naming.is_some(), self.local()) { (_, true, _) => "Enter create · Esc cancel · Ctrl+O copy", (true, false, true) => { - "↑↓ select · Enter open · n new host · d default · x remove · r refresh" + "↑↓ select · Enter open · n new host · d default · x remove · r refresh · q quit" } (true, false, false) => { - "↑↓ select · Enter open · n new host · d default · x remove · r refresh · o sign out" + "↑↓ select · Enter open · n new host · d default · x remove · r refresh · o sign out · q quit" } - (false, false, _) => "↑↓ select · Enter open · r refresh · o sign out", + (false, false, _) => "↑↓ select · Enter open · r refresh · o sign out · q quit", }; draw_footer(frame, footer, keys, &self.status, theme::ACCENT); } @@ -1738,6 +1747,15 @@ impl App { pub fn event(&mut self, event: Event) { let event = hint_click(event); + // Over a session, Ctrl+Q leaves the session; everywhere else it quits. + let in_session = self.screen == Screen::Host && self.host.view.is_some(); + if let Event::Key(key) = &event + && key.is_ctrl('q') + && !in_session + { + self.quit = true; + return; + } // Alt+R over a panel shows its links as QR codes. let over = self.seed.is_some() || self.data.borrow().job.is_some(); let links = match ( diff --git a/crates/berth-page/src/device.rs b/crates/berth-page/src/device.rs index 45e5451..d569af3 100644 --- a/crates/berth-page/src/device.rs +++ b/crates/berth-page/src/device.rs @@ -1,7 +1,9 @@ -//! What the screens need from the device they run on: the clipboard, links, -//! files, what is kept between runs, plain HTTP and the portal's socket. The program installs its -//! [`Device`] before it makes the [`App`](crate::App). +//! What the screens take from the program and the system they run on: what +//! the program was started with, what is kept between runs, the clipboard, +//! links, files, and plain HTTP. +use crate::settings::{self, Settings}; +use crate::{net, terminal}; use berth_tui::screen::Platform; use std::cell::RefCell; use std::rc::Rc; @@ -24,105 +26,100 @@ pub struct Linked { pub setup_key: Option, } -/// What the portal's socket says, handed over on the thread that draws. -pub enum Said { - Open, - Text(String), - Bytes(Vec), - /// The socket is closed, or never opened. - Closed, -} - -/// An open socket; dropping it closes it. -pub trait Socket { - fn send_text(&self, text: &str) -> bool; - fn send_bytes(&self, bytes: &[u8]) -> bool; -} - -pub type Answer = Box)>; - -pub trait Device { - fn copy(&self, text: &str) -> bool; - /// What is on the clipboard, where it can be read right away. - fn paste(&self) -> Option; - fn open(&self, link: &str) -> Result<(), String>; - /// Let the user choose a file whose name ends with one of `accept` - /// (comma-separated), and hand over its name and bytes. Nothing happens - /// when none is chosen; an error says why this device cannot ask. - fn choose_file( - &self, - accept: &str, - then: Box)>, - ) -> Result<(), String>; - fn stored(&self, key: Kept) -> Option; - /// Keep `value`, or forget what was kept when it is empty. - fn store(&self, key: Kept, value: &str); - fn linked(&self) -> Linked; - /// One plain HTTP request to `path` of `server` with a bearer; `then` - /// gets its status and body. - fn request(&self, method: &str, server: &str, path: &str, bearer: &str, then: Answer); - /// Open a WebSocket to `path` of `server` with `token` as its protocol. - /// `said` gets what it says, on the thread that draws, from a later turn on. - fn connect( - &self, - server: &str, - path: &str, - token: &str, - said: Box, - ) -> Result, String>; +impl Linked { + /// What the environment `var` gives names: `BERTH_SERVER` and + /// `BERTH_TOKEN` this once, and `BERTH_SETUP_KEY`. Secrets come from the + /// environment, not the command line, where other users could read them. + pub fn from(var: impl Fn(&str) -> Option) -> Linked { + let variable = |name: &str| { + var(name) + .map(|value| value.trim().to_owned()) + .filter(|value| !value.is_empty()) + }; + Linked { + server: variable("BERTH_SERVER"), + token: variable("BERTH_TOKEN"), + setup_key: variable("BERTH_SETUP_KEY"), + } + } + + /// Whether no server is named, here or in `settings`, so that the + /// screens use one on this machine. + pub fn local(&self, settings: &Settings) -> bool { + self.server.is_none() && settings.get(settings::SERVER).is_none() + } +} + +/// What the screens keep between runs, and what the program was started +/// with. The program installs it before it makes the [`App`](crate::App). +struct Device { + linked: Linked, + settings: Settings, } thread_local! { - static DEVICE: RefCell>> = const { RefCell::new(None) }; + static DEVICE: RefCell>> = const { RefCell::new(None) }; } -/// Make `device` the one the screens use on this thread. -pub fn install(device: impl Device + 'static) { - DEVICE.set(Some(Rc::new(device))); +/// Start the screens of this thread with `linked`, keeping the server and +/// its token in `settings`. +pub fn install(linked: Linked, settings: Settings) { + DEVICE.set(Some(Rc::new(Device { linked, settings }))); } -pub(crate) fn device() -> Rc { +fn device() -> Rc { DEVICE .with_borrow(Clone::clone) .expect("the program installs its device before the screens start") } -/// The device as the shared screens of berth-tui take it. +/// The system as the shared screens of berth-tui take it. pub(crate) struct Here; impl Platform for Here { fn copy(&mut self, text: &str) -> bool { - device().copy(text) + terminal::copy_text(text) } fn paste(&mut self) -> Option { - device().paste() + terminal::paste_text() } fn open(&mut self, link: &str) -> Result<(), String> { - device().open(link) + terminal::open(link) } } pub(crate) fn linked() -> Linked { - device().linked() + device().linked.clone() +} + +fn setting(key: Kept) -> &'static str { + match key { + Kept::Server => settings::SERVER, + Kept::Token => settings::TOKEN, + } } pub(crate) fn stored(key: Kept) -> Option { - device().stored(key).filter(|value| !value.is_empty()) + device().settings.get(setting(key)) } +/// Keep `value`, or forget what was kept when it is empty. The screens go +/// on without it when it cannot be written: the next run asks again. pub(crate) fn store(key: Kept, value: &str) { - device().store(key, value) + let _ = device().settings.set(&[(setting(key), value)]); } pub(crate) fn choose_file( accept: &str, then: impl FnOnce(String, Vec) + 'static, ) -> Result<(), String> { - device().choose_file(accept, Box::new(then)) + terminal::choose_file(accept, then) } +/// One plain HTTP request to `path` of `server` with a bearer; `then` gets +/// its status and body at a later turn. pub(crate) fn request( method: &str, server: &str, @@ -130,7 +127,16 @@ pub(crate) fn request( bearer: &str, then: impl FnOnce(Result<(u16, String), String>) + 'static, ) { - device().request(method, server, path, bearer, Box::new(then)) + let (method, server, path, bearer) = ( + method.to_owned(), + server.to_owned(), + path.to_owned(), + bearer.to_owned(), + ); + net::later( + async move { net::http(&method, &server, &path, &bearer).await }, + then, + ); } /// The server that runs in the program itself, as the screens name it. @@ -176,6 +182,32 @@ pub fn shown(server: &str) -> &str { mod tests { use super::*; + #[test] + fn a_server_named_or_kept_is_used_and_else_one_here() { + let scratch = tempfile::tempdir().unwrap(); + let settings = Settings::new(Some(scratch.path().to_owned())); + let env = |pairs: &'static [(&'static str, &'static str)]| { + move |name: &str| { + pairs + .iter() + .find(|(key, _)| *key == name) + .map(|(_, value)| value.to_string()) + } + }; + assert!(Linked::from(env(&[])).local(&settings)); + assert!(Linked::from(env(&[("BERTH_SERVER", " ")])).local(&settings)); + let named = Linked::from(env(&[ + ("BERTH_SERVER", "https://studio.example"), + ("BERTH_TOKEN", "s3cret\n"), + ])); + assert!(!named.local(&settings)); + assert_eq!(named.token.as_deref(), Some("s3cret")); + settings + .set(&[(settings::SERVER, "http://192.0.2.10:7878")]) + .unwrap(); + assert!(!Linked::from(env(&[])).local(&settings)); + } + #[test] fn addresses() { assert_eq!( diff --git a/crates/berth-remote/src/keys.rs b/crates/berth-page/src/keys.rs similarity index 100% rename from crates/berth-remote/src/keys.rs rename to crates/berth-page/src/keys.rs diff --git a/crates/berth-page/src/lib.rs b/crates/berth-page/src/lib.rs index b0cb168..e8ef721 100644 --- a/crates/berth-page/src/lib.rs +++ b/crates/berth-page/src/lib.rs @@ -1,14 +1,26 @@ -//! The screens of a `berth serve` elsewhere: the hosts of a server, its -//! plugins, settings and setup, through its portal. berth-remote draws them -//! in a terminal and gives them a [`device::Device`]. +//! The screens of berth: the hosts of a `berth serve`, its plugins, settings +//! and setup, through its portal, in a terminal. The server is elsewhere, +//! the socket of a `berth serve` on this machine, or one in the program. mod admin; mod app; pub mod device; mod home; mod installed; +pub mod keys; +pub mod net; pub mod portal; mod remote; +pub mod screens; +pub mod settings; mod setup; +pub mod socket; +pub mod terminal; pub use app::App; + +/// Take in what the network said since the last turn, on the thread that draws. +pub fn pump() { + net::pump(); + socket::pump(); +} diff --git a/crates/berth-remote/src/net.rs b/crates/berth-page/src/net.rs similarity index 99% rename from crates/berth-remote/src/net.rs rename to crates/berth-page/src/net.rs index b4385a1..448ba98 100644 --- a/crates/berth-remote/src/net.rs +++ b/crates/berth-page/src/net.rs @@ -53,7 +53,7 @@ pub fn serve_here(dial: client::Dial) { /// Where `path` of `server` is: `http(s)://HOST[:PORT]`, `unix:/path` or `here:`. pub fn target(server: &str, path: &str) -> Result { - if server == berth_page::device::HERE { + if server == crate::device::HERE { return Ok(Target { way: Way::Here, authority: "berth".into(), diff --git a/crates/berth-page/src/portal.rs b/crates/berth-page/src/portal.rs index 2186917..6f88998 100644 --- a/crates/berth-page/src/portal.rs +++ b/crates/berth-page/src/portal.rs @@ -1,7 +1,7 @@ //! The server's portal over the device's WebSocket: calls that are answered //! once, and streams that send frames until either side ends them. -use crate::device::{self, Said, Socket}; +use crate::socket::{self, Said, Socket}; use serde_json::{Value, json}; use std::cell::{Cell, RefCell}; use std::collections::HashMap; @@ -175,6 +175,17 @@ impl Portal { /// Open the portal of `server`, showing the token as the WebSocket's /// protocol. pub fn open(server: &str, token: &str) -> Result { + Portal::attach(|said| { + let socket = socket::open(server, berth_api::ops::PORTAL, token, said)?; + Ok(Box::new(socket) as Box) + }) + } + + /// The portal over the socket `connect` opens, which tells `said` what + /// it hears. + pub fn attach( + connect: impl FnOnce(Box) -> Result, String>, + ) -> Result { let inner = Rc::new(Inner { socket: RefCell::default(), link: Cell::new(Link::Connecting), @@ -184,16 +195,11 @@ impl Portal { streams: RefCell::default(), }); let weak: Weak = Rc::downgrade(&inner); - let socket = device::device().connect( - server, - berth_api::ops::PORTAL, - token, - Box::new(move |said| { - if let Some(inner) = weak.upgrade() { - inner.said(said); - } - }), - )?; + let socket = connect(Box::new(move |said| { + if let Some(inner) = weak.upgrade() { + inner.said(said); + } + }))?; *inner.socket.borrow_mut() = Some(socket); Ok(Portal(inner)) } @@ -269,11 +275,10 @@ impl Portal { #[cfg(test)] mod tests { use super::*; - use crate::device::{Answer, Device, Kept, Linked}; type Hears = Box; - /// A device whose socket the test speaks for. + /// A socket the test speaks for. #[derive(Clone, Default)] struct Wire { sent: Rc>>, @@ -307,49 +312,14 @@ mod tests { } } - impl Device for Wire { - fn copy(&self, _: &str) -> bool { - false - } - fn paste(&self) -> Option { - None - } - fn open(&self, _: &str) -> Result<(), String> { - Err("no".into()) - } - fn choose_file(&self, _: &str, _: Box)>) -> Result<(), String> { - Err("no".into()) - } - fn stored(&self, _: Kept) -> Option { - None - } - fn store(&self, _: Kept, _: &str) {} - fn linked(&self) -> Linked { - Linked::default() - } - fn request(&self, _: &str, _: &str, _: &str, _: &str, then: Answer) { - then(Err("no".into())) - } - fn connect( - &self, - server: &str, - path: &str, - token: &str, - said: Box, - ) -> Result, String> { - assert_eq!( - (server, path, token), - ("http://192.0.2.10:7878", "/v1/portal", "the-token") - ); - *self.said.borrow_mut() = Some(said); - Ok(Box::new(WireSocket(self.sent.clone()))) - } - } - fn portal() -> (Wire, Portal) { let wire = Wire::default(); - device::install(wire.clone()); - let portal = Portal::open("http://192.0.2.10:7878", "the-token").unwrap(); + let speaking = wire.clone(); + let portal = Portal::attach(move |said| { + *speaking.said.borrow_mut() = Some(said); + Ok(Box::new(WireSocket(speaking.sent.clone()))) + }) + .unwrap(); (wire, portal) } diff --git a/crates/berth-remote/src/screens.rs b/crates/berth-page/src/screens.rs similarity index 68% rename from crates/berth-remote/src/screens.rs rename to crates/berth-page/src/screens.rs index bbbcf42..dc01505 100644 --- a/crates/berth-remote/src/screens.rs +++ b/crates/berth-page/src/screens.rs @@ -1,7 +1,7 @@ //! The screens in a terminal: drawing, and the keys and mouse taken in. use crate::keys; -use crossterm::event::{self, Event as Native, KeyCode, KeyEventKind, KeyModifiers}; +use crossterm::event; use std::time::Duration; /// Stop the mouse and paste reports, which ratatui's own restore leaves on. @@ -13,7 +13,7 @@ fn stop_reports() { ); } -/// The screens in this terminal until Ctrl+Q, opening the host `open` once +/// The screens in this terminal until they are left, opening the host `open` once /// the server has listed it. pub fn run(open: Option) -> std::io::Result<()> { let mut terminal = ratatui::init(); @@ -36,7 +36,7 @@ pub fn run(open: Option) -> std::io::Result<()> { } fn screens(terminal: &mut ratatui::DefaultTerminal, open: Option) -> std::io::Result<()> { - let mut app = berth_page::App::new(); + let mut app = crate::App::new(); if let Some(host) = open { app.open_when_listed(&host); } @@ -49,19 +49,11 @@ fn screens(terminal: &mut ratatui::DefaultTerminal, open: Option) -> std continue; } loop { - match keys::read()? { - Native::Key(key) - if key.kind != KeyEventKind::Release - && key.modifiers.contains(KeyModifiers::CONTROL) - && matches!(key.code, KeyCode::Char('q' | 'Q')) => - { - return Ok(()); - } - native => { - if let Some(event) = keys::event(&native) { - app.event(event); - } - } + if let Some(event) = keys::event(&keys::read()?) { + app.event(event); + } + if app.quit() { + return Ok(()); } if !keys::poll(Duration::ZERO)? { break; diff --git a/crates/berth-page/src/settings.rs b/crates/berth-page/src/settings.rs new file mode 100644 index 0000000..2ebe87b --- /dev/null +++ b/crates/berth-page/src/settings.rs @@ -0,0 +1,318 @@ +//! The server the screens use and its token, kept between runs as berth's +//! own `server` and `server_token` settings: in `config.json` of berth's +//! folder, a file only its user can read, in a folder only its user can open. +//! The other settings of that file are left as they are. + +use serde_json::{Map, Value}; +use std::io::Write; +use std::path::{Path, PathBuf}; + +/// The settings that say which server berth uses, and with what token. +pub const SERVER: &str = "server"; +pub const TOKEN: &str = "server_token"; + +/// Where the settings of a program are for the environment `var` gives: +/// under `%LOCALAPPDATA%` on Windows, `$XDG_CONFIG_HOME` where it is set, +/// and else `~/Library/Application Support` on macOS and `~/.config` +/// elsewhere. +fn base(var: &impl Fn(&str) -> Option) -> Option { + let var = |name: &str| var(name).filter(|value| !value.is_empty()); + if cfg!(windows) { + // Local rather than roaming, so that the token is not copied to + // other machines with the profile. + return Some(PathBuf::from(var("LOCALAPPDATA")?)); + } + // Only an absolute one, as berth's directories take it. + if let Some(dir) = var("XDG_CONFIG_HOME").filter(|dir| Path::new(dir).is_absolute()) { + return Some(PathBuf::from(dir)); + } + let home = PathBuf::from(var("HOME")?); + match cfg!(target_os = "macos") { + true => Some(home.join("Library/Application Support")), + false => Some(home.join(".config")), + } +} + +/// berth's folder of settings, which on Linux holds the rest of its settings too. +pub fn folder(var: impl Fn(&str) -> Option) -> Option { + Some(base(&var)?.join("berth")) +} + +/// Where berth-remote kept its server and token, before berth took it in. +pub fn old_folder(var: impl Fn(&str) -> Option) -> Option { + Some(base(&var)?.join("berth-remote")) +} + +pub struct Settings { + dir: Option, +} + +impl Settings { + /// The settings in `dir`; with `None`, nothing is read or written. + pub fn new(dir: Option) -> Settings { + Settings { dir } + } + + fn file(&self) -> Option { + Some(self.dir.as_ref()?.join("config.json")) + } + + /// Everything the file holds; nothing when it is missing or unreadable. + fn read(&self) -> Map { + self.file() + .and_then(|file| std::fs::read(file).ok()) + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .and_then(|value| match value { + Value::Object(map) => Some(map), + _ => None, + }) + .unwrap_or_default() + } + + /// A setting's value, when it is set. + pub fn get(&self, key: &str) -> Option { + self.read() + .get(key) + .and_then(Value::as_str) + .map(str::to_owned) + .filter(|value| !value.is_empty()) + } + + /// Set the settings `changes` names, removing those whose value is + /// empty. A file that is there but is not settings is not written over. + pub fn set(&self, changes: &[(&str, &str)]) -> std::io::Result<()> { + let (Some(dir), Some(file)) = (&self.dir, self.file()) else { + return Ok(()); + }; + let mut kept = match std::fs::read(&file) { + Ok(bytes) => match serde_json::from_slice::(&bytes) { + Ok(Value::Object(map)) => map, + _ => { + return Err(std::io::Error::other(format!( + "{} holds no settings, and is left as it is", + file.display() + ))); + } + }, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Map::new(), + Err(error) => return Err(error), + }; + let before = kept.clone(); + for (key, value) in changes { + match value.is_empty() { + true => kept.remove(*key), + false => kept.insert((*key).to_owned(), Value::String((*value).to_owned())), + }; + } + if kept == before { + return Ok(()); + } + private_dir(dir)?; + let text = serde_json::to_string_pretty(&Value::Object(kept))? + "\n"; + private_write(&file, text.as_bytes()) + } + + /// Take in the server and token berth-remote kept in `old`, once: when + /// berth has no server of its own, they become berth's, and the old file + /// goes. Says which server was taken in. + pub fn take_in(&self, old: Option<&Path>) -> std::io::Result> { + let Some(old) = old else { + return Ok(None); + }; + let file = old.join("settings.json"); + let Ok(bytes) = std::fs::read(&file) else { + return Ok(None); + }; + let kept: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null); + let text = |key: &str| kept[key].as_str().unwrap_or("").trim().to_owned(); + let (server, token) = (text("server"), text("token")); + let taken = match (server.is_empty(), self.get(SERVER)) { + (false, None) => { + self.set(&[(SERVER, &server), (TOKEN, &token)])?; + Some(server) + } + _ => None, + }; + // Its token is in berth's settings now, or berth uses another server. + for gone in [file.clone(), file.with_extension("json.partial")] { + match std::fs::remove_file(&gone) { + Err(error) if error.kind() != std::io::ErrorKind::NotFound => return Err(error), + _ => {} + } + } + let _ = std::fs::remove_dir(old); + Ok(taken) + } +} + +/// Make the folder of the settings, which only its owner can open. +fn private_dir(dir: &Path) -> std::io::Result<()> { + let mut builder = std::fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] + std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); + builder.create(dir)?; + // A folder that was there already keeps its mode otherwise. + #[cfg(unix)] + std::fs::set_permissions(dir, std::os::unix::fs::PermissionsExt::from_mode(0o700))?; + Ok(()) +} + +/// Write a file only its owner can read, since it holds the token. On +/// Windows the file takes the access list of the user's profile, which lets +/// in the user, SYSTEM and the administrators. +fn private_write(file: &Path, bytes: &[u8]) -> std::io::Result<()> { + let partial = file.with_extension("json.partial"); + // A file left over would keep its own mode. + match std::fs::remove_file(&partial) { + Err(error) if error.kind() != std::io::ErrorKind::NotFound => return Err(error), + _ => {} + } + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + let mut out = options.open(&partial)?; + out.write_all(bytes)?; + out.sync_all()?; + drop(out); + std::fs::rename(partial, file) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keeps_the_server_beside_the_other_settings() { + let scratch = tempfile::tempdir().unwrap(); + let dir = scratch.path().join("config/berth"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("config.json"), r#"{"store": "/srv/berth.db"}"#).unwrap(); + let settings = Settings::new(Some(dir.clone())); + assert_eq!(settings.get(SERVER), None); + settings + .set(&[(SERVER, "https://studio.example"), (TOKEN, "secret")]) + .unwrap(); + assert_eq!( + settings.get(SERVER).as_deref(), + Some("https://studio.example") + ); + assert_eq!(settings.get(TOKEN).as_deref(), Some("secret")); + settings.set(&[(TOKEN, "")]).unwrap(); + assert_eq!(settings.get(TOKEN), None); + let all: Value = + serde_json::from_slice(&std::fs::read(dir.join("config.json")).unwrap()).unwrap(); + assert_eq!(all["store"], "/srv/berth.db"); + assert!(!dir.join("config.json.partial").exists()); + } + + #[test] + fn a_file_that_is_not_settings_is_left_alone() { + let scratch = tempfile::tempdir().unwrap(); + let settings = Settings::new(Some(scratch.path().to_owned())); + std::fs::write(scratch.path().join("config.json"), "{not json").unwrap(); + assert_eq!(settings.get(SERVER), None); + assert!(settings.set(&[(SERVER, "https://dock.example")]).is_err()); + let left = std::fs::read_to_string(scratch.path().join("config.json")).unwrap(); + assert_eq!(left, "{not json"); + } + + #[test] + fn berth_remotes_server_is_taken_in_once() { + let scratch = tempfile::tempdir().unwrap(); + let old = scratch.path().join("berth-remote"); + std::fs::create_dir_all(&old).unwrap(); + std::fs::write( + old.join("settings.json"), + r#"{"server": "https://studio.example", "token": "s3cret"}"#, + ) + .unwrap(); + let settings = Settings::new(Some(scratch.path().join("berth"))); + assert_eq!( + settings.take_in(Some(&old)).unwrap().as_deref(), + Some("https://studio.example") + ); + assert_eq!(settings.get(TOKEN).as_deref(), Some("s3cret")); + assert!(!old.exists()); + assert_eq!(settings.take_in(Some(&old)).unwrap(), None); + + // A berth that uses a server already keeps it. + std::fs::create_dir_all(&old).unwrap(); + std::fs::write( + old.join("settings.json"), + r#"{"server": "https://dock.example", "token": "other"}"#, + ) + .unwrap(); + assert_eq!(settings.take_in(Some(&old)).unwrap(), None); + assert_eq!( + settings.get(SERVER).as_deref(), + Some("https://studio.example") + ); + assert!(!old.join("settings.json").exists()); + } + + #[cfg(unix)] + #[test] + fn only_the_owner_can_read_them() { + use std::os::unix::fs::PermissionsExt; + let scratch = tempfile::tempdir().unwrap(); + let dir = scratch.path().join("berth"); + // A folder made earlier with a looser mode is made private too. + std::fs::create_dir(&dir).unwrap(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap(); + let settings = Settings::new(Some(dir.clone())); + settings.set(&[(TOKEN, "secret")]).unwrap(); + let mode = |path: &Path| std::fs::metadata(path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(&dir), 0o700); + assert_eq!(mode(&dir.join("config.json")), 0o600); + } + + #[test] + fn the_folder_follows_the_system() { + let env = |pairs: &'static [(&'static str, &'static str)]| { + move |name: &str| { + pairs + .iter() + .find(|(key, _)| *key == name) + .map(|(_, value)| value.to_string()) + } + }; + if cfg!(windows) { + assert_eq!( + folder(env(&[("LOCALAPPDATA", r"C:\Users\ada\AppData\Local")])), + Some(PathBuf::from(r"C:\Users\ada\AppData\Local").join("berth")) + ); + assert_eq!(folder(env(&[])), None); + return; + } + assert_eq!( + folder(env(&[ + ("XDG_CONFIG_HOME", "/scratch/c"), + ("HOME", "/home/ada") + ])), + Some(PathBuf::from("/scratch/c/berth")) + ); + assert_eq!( + old_folder(env(&[ + ("XDG_CONFIG_HOME", "/scratch/c"), + ("HOME", "/home/ada") + ])), + Some(PathBuf::from("/scratch/c/berth-remote")) + ); + let home = match cfg!(target_os = "macos") { + true => "/home/ada/Library/Application Support/berth", + false => "/home/ada/.config/berth", + }; + for relative in ["", "scratch/c"] { + assert_eq!( + folder(env(match relative { + "" => &[("XDG_CONFIG_HOME", ""), ("HOME", "/home/ada")], + _ => &[("XDG_CONFIG_HOME", "scratch/c"), ("HOME", "/home/ada")], + })), + Some(PathBuf::from(home)) + ); + } + assert_eq!(folder(env(&[])), None); + } +} diff --git a/crates/berth-page/src/setup.rs b/crates/berth-page/src/setup.rs index ffd5bf1..caaeb12 100644 --- a/crates/berth-page/src/setup.rs +++ b/crates/berth-page/src/setup.rs @@ -199,18 +199,7 @@ impl Setup { /// Every problem, each on the tab of what it is about. fn problems(&self) -> Vec { let view = self.view(); - // The keys that make these up are other ones here. - let mut problems: Vec = view - .problems_with(&self.machine) - .into_iter() - .map(|problem| Problem { - text: problem - .text - .replace("(F4 generates)", "(g generates)") - .replace("(F4 or F5)", "(g or p)"), - ..problem - }) - .collect(); + let mut problems: Vec = view.problems_with(&self.machine); if self.action == Action::Ssh && view.text(Field::SshHost).is_empty() { problems.push(Problem::new( Step::Install, @@ -253,8 +242,7 @@ impl Setup { fn help(&self) -> String { match self.selected() { - // g and p do what berth's F4 and F5 do. - Some(Entry::Field(field)) => field.spec().help.replace("F4", "g").replace("F5", "p"), + Some(Entry::Field(field)) => field.spec().help.into(), Some(Entry::Key(Account::Operator, Some(_))) => Field::OperatorKey.spec().help.into(), Some(Entry::Key(Account::Agent, Some(_))) => Field::AgentKey.spec().help.into(), Some(Entry::Key(_, None)) => setup::ADD_KEY_HELP.into(), @@ -557,14 +545,11 @@ impl Setup { match key.code { Code::Up => self.move_selection(true), Code::Down => self.move_selection(false), - // g and p do what berth's F4 and F5 do. - Code::Char('g') | Code::F(4) - if self.selected_field().is_some_and(Field::can_generate) => - { + Code::F(4) if self.selected_field().is_some_and(Field::can_generate) => { let field = self.selected_field().unwrap(); say(self.generate(field, admin)); } - Code::Char('p') if self.selected_field().is_some_and(Field::is_password_hash) => { + Code::F(5) if self.selected_field().is_some_and(Field::is_password_hash) => { self.password_entry = true; self.editing = Some(Input::default()); } @@ -770,10 +755,10 @@ impl Setup { let keys = match (&self.editing, field) { (Some(_), _) => "Enter accept · Esc cancel · Ctrl+O copy · Ctrl+S save".to_owned(), (None, Some(field)) if field.is_password_hash() => { - "↑↓ select · g generate · p type a password · x clear · 1-4 tab · Ctrl+S save · Esc back".to_owned() + "↑↓ select · F4 generate · F5 type a password · x clear · 1-4 tab · Ctrl+S save · Esc back".to_owned() } (None, Some(field)) if field.can_generate() => { - "↑↓ select · Enter change · g generate · x clear · 1-4 tab · Ctrl+S save · Esc back".to_owned() + "↑↓ select · Enter change · F4 generate · x clear · 1-4 tab · Ctrl+S save · Esc back".to_owned() } _ => "↑↓ select · Enter change · Space switch · x clear · 1-4 tab · Ctrl+S save · Esc back".to_owned(), }; diff --git a/crates/berth-remote/src/socket.rs b/crates/berth-page/src/socket.rs similarity index 92% rename from crates/berth-remote/src/socket.rs rename to crates/berth-page/src/socket.rs index e40e1f0..186174d 100644 --- a/crates/berth-remote/src/socket.rs +++ b/crates/berth-page/src/socket.rs @@ -3,13 +3,27 @@ use crate::net; use berth_api::client::{self, Frame as Message}; -use berth_page::device::{Said, Socket}; use futures_util::{SinkExt, StreamExt}; use std::cell::RefCell; use std::sync::mpsc; use std::time::Duration; use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; +/// What the portal's socket says, handed over on the thread that draws. +pub enum Said { + Open, + Text(String), + Bytes(Vec), + /// The socket is closed, or never opened. + Closed, +} + +/// An open socket; dropping it closes it. +pub trait Socket { + fn send_text(&self, text: &str) -> bool; + fn send_bytes(&self, bytes: &[u8]) -> bool; +} + /// What a socket says goes to its listener here, a turn at a time. struct Heard { said: mpsc::Receiver, diff --git a/crates/berth-remote/src/device.rs b/crates/berth-page/src/terminal.rs similarity index 54% rename from crates/berth-remote/src/device.rs rename to crates/berth-page/src/terminal.rs index 1e83284..42daf18 100644 --- a/crates/berth-remote/src/device.rs +++ b/crates/berth-page/src/terminal.rs @@ -1,12 +1,6 @@ -//! The device the screens run on, in a terminal: the clipboard, opening -//! links, choosing a file, plain HTTP, the portal's socket, and the server -//! and token it keeps between runs. +//! What the screens do with the system they run on: the clipboard, opening +//! links in the system's browser, and its dialog for choosing a file. -use crate::settings::Settings; -use crate::{net, socket}; -use berth_page::device::{Answer, Device, Kept, Linked, Said, Socket}; -use serde_json::{Map, Value}; -use std::cell::RefCell; use std::io::Write; use std::path::PathBuf; use std::process::{Command, Stdio}; @@ -14,176 +8,82 @@ use std::process::{Command, Stdio}; /// The variables that carry secrets, which no helper program is handed. pub const SECRETS: [&str; 2] = ["BERTH_TOKEN", "BERTH_SETUP_KEY"]; -/// The device of a terminal. -pub struct Terminal { - linked: Linked, - settings: Settings, - /// What is kept, as the screens last set it. - kept: RefCell>, - /// Keep nothing on disk. - forget: bool, -} - -fn name(key: Kept) -> &'static str { - match key { - Kept::Server => "server", - Kept::Token => "token", - } -} - -impl Terminal { - /// With `forget`, what earlier runs kept is removed and nothing new is. - pub fn new(linked: Linked, settings: Settings, forget: bool) -> std::io::Result { - let kept = match forget { - true => { - settings.forget()?; - Map::new() - } - false => settings.read(), - }; - Ok(Terminal { - linked, - settings, - kept: RefCell::new(kept), - forget, - }) - } -} - -impl Device for Terminal { - fn copy(&self, text: &str) -> bool { - copy_text(text) - } - - fn paste(&self) -> Option { - paste_text() - } - - fn open(&self, link: &str) -> Result<(), String> { - let link = openable(link)?; - let mut command = if cfg!(windows) { - // Not through cmd, which would take the & of an address for its own. - let mut command = helper("rundll32"); - command.args(["url.dll,FileProtocolHandler", link]); - command - } else if cfg!(target_os = "macos") { - let mut command = helper("open"); - command.arg(link); - command - } else { - // Without a desktop xdg-open falls back to a browser in this - // very terminal, under the screens. - if !has_display() { - return Err("there is no desktop here to open it on".into()); - } - let mut command = helper("xdg-open"); - command.arg(link); - command - }; +/// Open a web address in the system's browser. +pub fn open(link: &str) -> Result<(), String> { + let link = openable(link)?; + let mut command = if cfg!(windows) { + // Not through cmd, which would take the & of an address for its own. + let mut command = helper("rundll32"); + command.args(["url.dll,FileProtocolHandler", link]); command - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .spawn() - .map(drop) - .map_err(|error| error.to_string()) - } + } else if cfg!(target_os = "macos") { + let mut command = helper("open"); + command.arg(link); + command + } else { + // Without a desktop xdg-open falls back to a browser in this + // very terminal, under the screens. + if !has_display() { + return Err("there is no desktop here to open it on".into()); + } + let mut command = helper("xdg-open"); + command.arg(link); + command + }; + command + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .map(drop) + .map_err(|error| error.to_string()) +} - fn choose_file( - &self, - accept: &str, - then: Box)>, - ) -> Result<(), String> { - let endings = endings(accept); - let given = std::env::var_os("BERTH_REMOTE_FILE").map(PathBuf::from); - let dialog = match given { - Some(_) => None, - None => Some(file_dialog(&endings).ok_or( - "There is no file dialog here: set BERTH_REMOTE_FILE to the package's path", - )?), - }; - net::later_blocking( - move || { - let path = match (given, dialog) { - (Some(path), _) => path, - (None, Some(mut dialog)) => { - let output = dialog - .stdin(Stdio::null()) - .stderr(Stdio::null()) - .output() - .ok()?; - let chosen = String::from_utf8_lossy(&output.stdout).trim().to_owned(); - if !output.status.success() || chosen.is_empty() { - return None; - } - PathBuf::from(chosen) +/// Let the user choose a file whose name ends with one of `accept` +/// (comma-separated), and hand over its name and bytes at a later turn. +/// Nothing happens when none is chosen; an error says why none can be asked for. +pub fn choose_file( + accept: &str, + then: impl FnOnce(String, Vec) + 'static, +) -> Result<(), String> { + let endings = endings(accept); + let given = std::env::var_os("BERTH_FILE").map(PathBuf::from); + let dialog = match given { + Some(_) => None, + None => Some( + file_dialog(&endings) + .ok_or("There is no file dialog here: set BERTH_FILE to the package's path")?, + ), + }; + crate::net::later_blocking( + move || { + let path = match (given, dialog) { + (Some(path), _) => path, + (None, Some(mut dialog)) => { + let output = dialog + .stdin(Stdio::null()) + .stderr(Stdio::null()) + .output() + .ok()?; + let chosen = String::from_utf8_lossy(&output.stdout).trim().to_owned(); + if !output.status.success() || chosen.is_empty() { + return None; } - (None, None) => return None, - }; - let bytes = std::fs::read(&path).ok()?; - let name = path.file_name()?.to_string_lossy().into_owned(); - Some((name, bytes)) - }, - move |chosen| { - if let Some((name, bytes)) = chosen { - then(name, bytes) + PathBuf::from(chosen) } - }, - ); - Ok(()) - } - - fn stored(&self, key: Kept) -> Option { - self.kept - .borrow() - .get(name(key)) - .and_then(Value::as_str) - .map(str::to_owned) - } - - fn store(&self, key: Kept, value: &str) { - let mut kept = self.kept.borrow_mut(); - let had = kept.get(name(key)).and_then(Value::as_str).unwrap_or(""); - if had == value { - return; - } - match value.is_empty() { - true => kept.remove(name(key)), - false => kept.insert(name(key).to_owned(), Value::String(value.to_owned())), - }; - if !self.forget { - // The screens go on without it; the next run asks again. - let _ = self.settings.write(&kept); - } - } - - fn linked(&self) -> Linked { - self.linked.clone() - } - - fn request(&self, method: &str, server: &str, path: &str, bearer: &str, then: Answer) { - let (method, server, path, bearer) = ( - method.to_owned(), - server.to_owned(), - path.to_owned(), - bearer.to_owned(), - ); - net::later( - async move { net::http(&method, &server, &path, &bearer).await }, - then, - ); - } - - fn connect( - &self, - server: &str, - path: &str, - token: &str, - said: Box, - ) -> Result, String> { - let socket = socket::open(server, path, token, said)?; - Ok(Box::new(socket)) - } + (None, None) => return None, + }; + let bytes = std::fs::read(&path).ok()?; + let name = path.file_name()?.to_string_lossy().into_owned(); + Some((name, bytes)) + }, + move |chosen| { + if let Some((name, bytes)) = chosen { + then(name, bytes) + } + }, + ); + Ok(()) } /// A program this one starts, such as a clipboard or a browser: without @@ -282,7 +182,7 @@ fn copiers() -> Vec<(Helper, bool)> { } } -fn copy_text(text: &str) -> bool { +pub fn copy_text(text: &str) -> bool { if copiers() .into_iter() .any(|((program, args), wait)| feed(program, args, text, wait)) @@ -312,7 +212,7 @@ fn base64(bytes: &[u8]) -> String { out } -fn paste_text() -> Option { +pub fn paste_text() -> Option { let pasters: Vec = if cfg!(windows) { vec![( "powershell", @@ -355,7 +255,7 @@ fn paste_text() -> Option { /// environment variable, so that nothing is spliced into the script. const WINDOWS_DIALOG: &str = "Add-Type -AssemblyName System.Windows.Forms; \ $dialog = New-Object System.Windows.Forms.OpenFileDialog; \ - $dialog.Filter = $env:BERTH_REMOTE_FILTER; \ + $dialog.Filter = $env:BERTH_FILTER; \ if ($dialog.ShowDialog() -eq 'OK') { [Console]::OutputEncoding = [Text.Encoding]::UTF8; $dialog.FileName }"; /// The file dialog of this system, given what the accepted names end with; @@ -380,7 +280,7 @@ fn file_dialog(endings: &[String]) -> Option { WINDOWS_DIALOG, ]) .env( - "BERTH_REMOTE_FILTER", + "BERTH_FILTER", format!("Packages ({filter})|{filter}|All files (*.*)|*.*"), ); return Some(command); @@ -454,48 +354,4 @@ mod tests { assert_eq!(endings(".tgz, .tar.gz,"), [".tgz", ".tar.gz"]); assert!(endings("").is_empty()); } - - #[test] - fn forget_removes_what_was_kept() { - let scratch = tempfile::tempdir().unwrap(); - let dir = scratch.path().join("berth-remote"); - let kept = - Terminal::new(Linked::default(), Settings::new(Some(dir.clone())), false).unwrap(); - kept.store(Kept::Server, "https://studio.example"); - kept.store(Kept::Token, "secret"); - assert!(dir.join("settings.json").exists()); - let again = - Terminal::new(Linked::default(), Settings::new(Some(dir.clone())), false).unwrap(); - assert_eq!(again.stored(Kept::Token).as_deref(), Some("secret")); - assert_eq!( - again.stored(Kept::Server).as_deref(), - Some("https://studio.example") - ); - - let forgetting = - Terminal::new(Linked::default(), Settings::new(Some(dir.clone())), true).unwrap(); - assert!(!dir.exists()); - assert_eq!(forgetting.stored(Kept::Token), None); - // What this run is given is used, and still not written. - forgetting.store(Kept::Server, "https://dock.example"); - forgetting.store(Kept::Token, "other"); - assert_eq!(forgetting.stored(Kept::Token).as_deref(), Some("other")); - assert_eq!( - forgetting.stored(Kept::Server).as_deref(), - Some("https://dock.example") - ); - assert!(!dir.exists()); - } - - #[test] - fn an_empty_value_forgets_it() { - let scratch = tempfile::tempdir().unwrap(); - let dir = scratch.path().join("berth-remote"); - let device = - Terminal::new(Linked::default(), Settings::new(Some(dir.clone())), false).unwrap(); - device.store(Kept::Token, "secret"); - device.store(Kept::Token, ""); - assert_eq!(device.stored(Kept::Token), None); - assert!(!dir.exists()); - } } diff --git a/crates/berth-remote/Cargo.toml b/crates/berth-remote/Cargo.toml index 64ea57a..8c77bbb 100644 --- a/crates/berth-remote/Cargo.toml +++ b/crates/berth-remote/Cargo.toml @@ -13,16 +13,3 @@ path = "src/main.rs" [dependencies] berth-api = { workspace = true, features = ["client"] } berth-page.workspace = true -berth-tui.workspace = true -serde_json.workspace = true -ratatui = { version = "=0.30.2", default-features = false, features = ["crossterm"] } -crossterm = "=0.29.0" -tokio.workspace = true -futures-util.workspace = true -rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } -tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] } -webpki-roots = "1" -rustls-native-certs = "0.8" - -[dev-dependencies] -tempfile.workspace = true diff --git a/crates/berth-remote/src/lib.rs b/crates/berth-remote/src/lib.rs index 9708621..cde3e09 100644 --- a/crates/berth-remote/src/lib.rs +++ b/crates/berth-remote/src/lib.rs @@ -1,20 +1,3 @@ -//! berth-remote: the screens of a berth serve in a terminal, for a machine -//! that only looks after the hosts of a berth serve elsewhere. It runs on -//! Linux, macOS and Windows: the screens are berth-page's, and this crate -//! gives them a terminal and a network. It is a -//! library as well as the program so that berth's tests can sign it in to a -//! server of their own. +//! berth-remote: the screens of berth-page, for a berth serve elsewhere. -pub mod device; -pub mod keys; -pub mod net; pub mod options; -pub mod screens; -pub mod settings; -pub mod socket; - -/// Take in what the network said since the last turn, on the thread that draws. -pub fn pump() { - net::pump(); - socket::pump(); -} diff --git a/crates/berth-remote/src/main.rs b/crates/berth-remote/src/main.rs index d5eaec7..03aee00 100644 --- a/crates/berth-remote/src/main.rs +++ b/crates/berth-remote/src/main.rs @@ -1,7 +1,7 @@ //! berth-remote: the hosts of a berth serve, in this terminal. +use berth_page::settings; use berth_remote::options::{self, Parsed}; -use berth_remote::{device, settings}; fn main() { let options = match options::parse(std::env::args().skip(1), |name| std::env::var(name).ok()) { @@ -19,15 +19,13 @@ fn main() { std::process::exit(2); } }; - let settings = settings::Settings::new(settings::folder(|name| std::env::var(name).ok())); - match device::Terminal::new(options.linked, settings, options.forget) { - Ok(terminal) => berth_page::device::install(terminal), - Err(error) => { - eprintln!("berth-remote: could not forget the kept sign-in: {error}"); - std::process::exit(1); - } - } - if let Err(error) = berth_remote::screens::run(None) { + let var = |name: &str| std::env::var(name).ok(); + let settings = match options.forget { + true => settings::Settings::new(None), + false => settings::Settings::new(settings::folder(var)), + }; + berth_page::device::install(options.linked, settings); + if let Err(error) = berth_page::screens::run(None) { eprintln!("berth-remote: {error}"); std::process::exit(1); } diff --git a/crates/berth-remote/src/settings.rs b/crates/berth-remote/src/settings.rs deleted file mode 100644 index 231456b..0000000 --- a/crates/berth-remote/src/settings.rs +++ /dev/null @@ -1,224 +0,0 @@ -//! The server and token berth-remote keeps between runs: a JSON file that -//! only its user can read, in a folder that only its user can open. - -use serde_json::{Map, Value}; -use std::io::Write; -use std::path::{Path, PathBuf}; - -/// The folder of the settings for the environment `var` gives: under -/// `%LOCALAPPDATA%` on Windows, `$XDG_CONFIG_HOME` where it is set, and else -/// `~/Library/Application Support` on macOS and `~/.config` elsewhere. -pub fn folder(var: impl Fn(&str) -> Option) -> Option { - let var = |name: &str| var(name).filter(|value| !value.is_empty()); - let base = if cfg!(windows) { - // Local rather than roaming, so that the token is not copied to - // other machines with the profile. - PathBuf::from(var("LOCALAPPDATA")?) - } else if let Some(dir) = var("XDG_CONFIG_HOME") { - PathBuf::from(dir) - } else if cfg!(target_os = "macos") { - PathBuf::from(var("HOME")?).join("Library/Application Support") - } else { - PathBuf::from(var("HOME")?).join(".config") - }; - Some(base.join("berth-remote")) -} - -pub struct Settings { - dir: Option, -} - -impl Settings { - /// The settings in `dir`; with `None`, nothing is read or written. - pub fn new(dir: Option) -> Settings { - Settings { dir } - } - - fn file(&self) -> Option { - Some(self.dir.as_ref()?.join("settings.json")) - } - - /// What is kept; nothing when the file is missing or unreadable. - pub fn read(&self) -> Map { - self.file() - .and_then(|file| std::fs::read(file).ok()) - .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) - .and_then(|value| match value { - Value::Object(map) => Some(map), - _ => None, - }) - .unwrap_or_default() - } - - /// Keep `kept`, replacing what was. An empty map removes the file. - pub fn write(&self, kept: &Map) -> std::io::Result<()> { - let (Some(dir), Some(file)) = (&self.dir, self.file()) else { - return Ok(()); - }; - if kept.is_empty() { - return self.forget(); - } - private_dir(dir)?; - private_write(&file, Value::Object(kept.clone()).to_string().as_bytes()) - } - - /// Remove what was kept: the file, and its folder when nothing else is in it. - pub fn forget(&self) -> std::io::Result<()> { - let (Some(dir), Some(file)) = (&self.dir, self.file()) else { - return Ok(()); - }; - for gone in [file.clone(), file.with_extension("json.partial")] { - match std::fs::remove_file(&gone) { - Err(error) if error.kind() != std::io::ErrorKind::NotFound => return Err(error), - _ => {} - } - } - // Not an error: a folder with other files in it stays. - let _ = std::fs::remove_dir(dir); - Ok(()) - } -} - -/// Make the folder of the settings, which only its owner can open. -fn private_dir(dir: &Path) -> std::io::Result<()> { - let mut builder = std::fs::DirBuilder::new(); - builder.recursive(true); - #[cfg(unix)] - std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); - builder.create(dir)?; - // A folder that was there already keeps its mode otherwise. - #[cfg(unix)] - std::fs::set_permissions(dir, std::os::unix::fs::PermissionsExt::from_mode(0o700))?; - Ok(()) -} - -/// Write a file only its owner can read, since it holds the token. On -/// Windows the file takes the access list of the user's profile, which lets -/// in the user, SYSTEM and the administrators. -fn private_write(file: &Path, bytes: &[u8]) -> std::io::Result<()> { - let partial = file.with_extension("json.partial"); - // A file left over would keep its own mode. - match std::fs::remove_file(&partial) { - Err(error) if error.kind() != std::io::ErrorKind::NotFound => return Err(error), - _ => {} - } - let mut options = std::fs::OpenOptions::new(); - options.write(true).create_new(true); - #[cfg(unix)] - std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); - let mut out = options.open(&partial)?; - out.write_all(bytes)?; - out.sync_all()?; - drop(out); - std::fs::rename(partial, file) -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn kept(value: Value) -> Map { - value.as_object().unwrap().clone() - } - - #[test] - fn keeps_and_forgets() { - let scratch = tempfile::tempdir().unwrap(); - let dir = scratch.path().join("config/berth-remote"); - let settings = Settings::new(Some(dir.clone())); - assert!(settings.read().is_empty()); - let both = kept(json!({"server": "https://studio.example", "token": "secret"})); - settings.write(&both).unwrap(); - assert_eq!(settings.read(), both); - settings - .write(&kept(json!({"server": "https://dock.example"}))) - .unwrap(); - assert_eq!(settings.read()["server"], "https://dock.example"); - assert!(!settings.read().contains_key("token")); - assert!(!dir.join("settings.json.partial").exists()); - settings.forget().unwrap(); - assert!(!dir.exists()); - assert!(settings.read().is_empty()); - // Forgetting twice, or what was never kept, is no error. - settings.forget().unwrap(); - } - - #[test] - fn an_empty_map_removes_the_file() { - let scratch = tempfile::tempdir().unwrap(); - let settings = Settings::new(Some(scratch.path().join("berth-remote"))); - settings.write(&kept(json!({"token": "secret"}))).unwrap(); - settings.write(&Map::new()).unwrap(); - assert!(!scratch.path().join("berth-remote").exists()); - } - - #[test] - fn a_file_that_is_not_settings_reads_as_nothing() { - let scratch = tempfile::tempdir().unwrap(); - let settings = Settings::new(Some(scratch.path().to_owned())); - std::fs::write(scratch.path().join("settings.json"), "[1, 2]").unwrap(); - assert!(settings.read().is_empty()); - std::fs::write(scratch.path().join("settings.json"), "{not json").unwrap(); - assert!(settings.read().is_empty()); - } - - #[cfg(unix)] - #[test] - fn only_the_owner_can_read_them() { - use std::os::unix::fs::PermissionsExt; - let scratch = tempfile::tempdir().unwrap(); - let dir = scratch.path().join("berth-remote"); - // A folder made earlier with a looser mode is made private too. - std::fs::create_dir(&dir).unwrap(); - std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap(); - // So is a file left over from a write that did not finish. - std::fs::write(dir.join("settings.json.partial"), "{}").unwrap(); - std::fs::set_permissions( - dir.join("settings.json.partial"), - std::fs::Permissions::from_mode(0o644), - ) - .unwrap(); - let settings = Settings::new(Some(dir.clone())); - settings.write(&kept(json!({"token": "secret"}))).unwrap(); - let mode = |path: &Path| std::fs::metadata(path).unwrap().permissions().mode() & 0o777; - assert_eq!(mode(&dir), 0o700); - assert_eq!(mode(&dir.join("settings.json")), 0o600); - } - - #[test] - fn the_folder_follows_the_system() { - let env = |pairs: &'static [(&'static str, &'static str)]| { - move |name: &str| { - pairs - .iter() - .find(|(key, _)| *key == name) - .map(|(_, value)| value.to_string()) - } - }; - if cfg!(windows) { - assert_eq!( - folder(env(&[("LOCALAPPDATA", r"C:\Users\ada\AppData\Local")])), - Some(PathBuf::from(r"C:\Users\ada\AppData\Local").join("berth-remote")) - ); - assert_eq!(folder(env(&[])), None); - return; - } - assert_eq!( - folder(env(&[ - ("XDG_CONFIG_HOME", "/scratch/c"), - ("HOME", "/home/ada") - ])), - Some(PathBuf::from("/scratch/c/berth-remote")) - ); - let home = match cfg!(target_os = "macos") { - true => "/home/ada/Library/Application Support/berth-remote", - false => "/home/ada/.config/berth-remote", - }; - assert_eq!( - folder(env(&[("XDG_CONFIG_HOME", ""), ("HOME", "/home/ada")])), - Some(PathBuf::from(home)) - ); - assert_eq!(folder(env(&[])), None); - } -} diff --git a/crates/berth-tui/src/screen.rs b/crates/berth-tui/src/screen.rs index 80cbec9..de46d80 100644 --- a/crates/berth-tui/src/screen.rs +++ b/crates/berth-tui/src/screen.rs @@ -317,19 +317,18 @@ pub fn words(line: &str) -> Vec<(u16, String)> { } /// Draw a session of the host: the same panel, with what leaving it means -/// there. `leave` is the key that leaves a running one: `Ctrl+Q`, or `Alt+Q` -/// where Ctrl+Q is not the page's to take. -pub fn draw_view(frame: &mut Frame, view: &View, note: &str, leave: &str) -> (Spots, Spots) { +/// there. Ctrl+Q leaves a running one. +pub fn draw_view(frame: &mut Frame, view: &View, note: &str) -> (Spots, Spots) { let running = match view.terminal { - true => format!( - " Ctrl+V paste · {leave} leave it running · Click opens a link · Right-click copies · Wheel scrolls " - ), - false => format!( - " {leave} leave it running · Click opens a link · Right-click copies · Wheel scrolls " - ), + true => { + " Ctrl+V paste · Ctrl+Q leave it running · Click opens a link · Right-click copies · Wheel scrolls " + } + false => { + " Ctrl+Q leave it running · Click opens a link · Right-click copies · Wheel scrolls " + } }; let keys = match (view.outcome(), view.ours) { - (None, _) => running.as_str(), + (None, _) => running, (Some(true), true) => " ✓ Done · Enter close · k keep it in Sessions ", (Some(false), true) => " ✗ It did not finish · Enter close · k keep it in Sessions ", (Some(true), false) => " ✓ Done · Enter close · d forget it ", @@ -660,7 +659,7 @@ pub fn view_event( return Some(pasted(text)); } Event::Key(key) => { - if key.is_ctrl('q') || (key.alt && key.code == Code::Char('q')) { + if key.is_ctrl('q') { let running = view.running(); host.close(false); return running.then(|| "It runs on; open it again from Sessions".into()); diff --git a/crates/berth/Cargo.toml b/crates/berth/Cargo.toml index 19650cb..2af85fb 100644 --- a/crates/berth/Cargo.toml +++ b/crates/berth/Cargo.toml @@ -29,7 +29,6 @@ jsonwebtoken = { version = "11", default-features = false, features = ["rust_cry tui-input = { workspace = true, features = ["crossterm"] } berth-page.workspace = true -berth-remote = { path = "../berth-remote" } [dev-dependencies] # Signs the access tokens of the tests. diff --git a/crates/berth/src/main.rs b/crates/berth/src/main.rs index 98ccbda..3733c5b 100644 --- a/crates/berth/src/main.rs +++ b/crates/berth/src/main.rs @@ -547,41 +547,39 @@ fn no_terminal(paths: &Paths, word: Option<&str>) -> String { } } -/// `berth ui [HOST]`: the screens of a server, as `berth-remote` shows -/// them: the server this berth is set to use, a `berth serve` of this user -/// on this machine, or else one in this process for as long as they are open. -fn screens(paths: &Paths, host: Option<&str>) -> Result<()> { +/// `berth ui [HOST]`: the screens of a server: the one this berth is set to +/// use, a `berth serve` of this user on this machine, or else one in this +/// process for as long as they are open. +fn screens(host: Option<&str>) -> Result<()> { + use berth_page::settings::{self, Settings}; use std::io::IsTerminal; if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() { - return Err(no_terminal(paths, host).into()); + return Err("berth's screens need a terminal, and there is none here. `berth help` lists the commands that need none".into()); } + let var = |name: &str| std::env::var(name).ok(); + let settings = Settings::new(settings::folder(var)); + match settings.take_in(settings::old_folder(var).as_deref()) { + Ok(Some(server)) => eprintln!("berth: berth-remote's server is berth's now: {server}"), + Ok(None) => {} + Err(error) => eprintln!("berth: berth-remote's settings were not taken in: {error}"), + } + let mut linked = berth_page::device::Linked::from(var); let mut here = None; - let (server, token) = match berth_core::server::Server::configured(paths) { - Some(server) => (server.url, server.token), - None => { - let socket = serve::here::socket(); - if std::os::unix::net::UnixStream::connect(&socket).is_ok() { - (format!("unix:{}", socket.display()), None) - } else { - let started = serve::here::Here::start(paths)?; - berth_remote::net::serve_here(started.dial()); + if linked.local(&settings) { + let socket = serve::here::socket(); + linked.server = Some(match std::os::unix::net::UnixStream::connect(&socket) { + Ok(_) => format!("unix:{}", socket.display()), + Err(_) => { + let paths = Paths::locate()?; + let started = serve::here::Here::start(&paths)?; + berth_page::net::serve_here(started.dial()); here = Some(started); - (berth_page::device::HERE.to_owned(), None) + berth_page::device::HERE.to_owned() } - } - }; - let linked = berth_page::device::Linked { - server: Some(server), - token, - setup_key: None, - }; - let device = berth_remote::device::Terminal::new( - linked, - berth_remote::settings::Settings::new(None), - false, - )?; - berth_page::device::install(device); - let shown = berth_remote::screens::run(host.map(str::to_owned)); + }); + } + berth_page::device::install(linked, settings); + let shown = berth_page::screens::run(host.map(str::to_owned)); if let Some(here) = &here { here.wait_for_jobs(|jobs| { let names: Vec = jobs @@ -760,8 +758,8 @@ fn run() -> Result<()> { } ["update", ref rest @ ..] => return update::command(rest), ["serve", ref rest @ ..] => return serve::command(&paths, rest), - ["ui"] => return screens(&paths, None), - ["ui", host] => return screens(&paths, Some(host)), + ["ui"] => return screens(None), + ["ui", host] => return screens(Some(host)), ["setup-key", ref rest @ ..] => return serve::setup_key::command(&paths, rest), ["connect", url] => return commands::connect(&paths, url), ["inbox", ref rest @ ..] => return serve::inbox_command(&paths, rest), diff --git a/crates/berth/src/serve/tests/remote.rs b/crates/berth/src/serve/tests/remote.rs index 5da7ce1..77d1697 100644 --- a/crates/berth/src/serve/tests/remote.rs +++ b/crates/berth/src/serve/tests/remote.rs @@ -1,10 +1,10 @@ -//! berth-remote against a berth serve of its own: a setup key signs it in, -//! and its portal answers. +//! The screens against a berth serve of their own over the network: a setup +//! key signs them in, and its portal answers. use super::*; -use berth_page::device::{Kept, Linked}; +use berth_page::device::Linked; use berth_page::portal::{Link, Portal}; -use berth_remote::{device::Terminal, settings::Settings}; +use berth_page::settings::{self, Settings}; use berth_tui::{Code, Event, Key}; use ratatui::{Terminal as Screen, backend::TestBackend}; use std::cell::RefCell; @@ -32,13 +32,13 @@ fn until(what: &str, mut done: impl FnMut() -> bool) { started.elapsed() < Duration::from_secs(10), "no {what} in time" ); - berth_remote::pump(); + berth_page::pump(); std::thread::sleep(Duration::from_millis(20)); } } #[tokio::test(flavor = "multi_thread")] -async fn berth_remote_signs_in_with_a_setup_key_and_uses_the_portal() { +async fn the_screens_sign_in_with_a_setup_key_and_use_the_portal() { let dir = tempfile::tempdir().unwrap(); let state = state_in(dir.path(), Some("s3cret-token")); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -48,14 +48,13 @@ async fn berth_remote_signs_in_with_a_setup_key_and_uses_the_portal() { let (key, _) = super::super::setup_key::make(&state.paths).unwrap(); let client = tempfile::tempdir().unwrap(); - let kept = client.path().join("berth-remote"); + let kept = client.path().join("berth"); let linked = Linked { server: Some(url.clone()), token: None, setup_key: Some(key), }; - let terminal = Terminal::new(linked, Settings::new(Some(kept.clone())), false).unwrap(); - berth_page::device::install(terminal); + berth_page::device::install(linked, Settings::new(Some(kept.clone()))); // The key collects the token, which is kept for the next run. let mut app = berth_page::App::new(); @@ -63,9 +62,15 @@ async fn berth_remote_signs_in_with_a_setup_key_and_uses_the_portal() { app.tick(); screen(&mut app).contains("is installed and serves at") }); - let settings = Settings::new(Some(kept.clone())).read(); - assert_eq!(settings["token"], "s3cret-token"); - assert_eq!(settings["server"], url.as_str()); + let settings = Settings::new(Some(kept.clone())); + assert_eq!( + settings.get(settings::TOKEN).as_deref(), + Some("s3cret-token") + ); + assert_eq!( + settings.get(settings::SERVER).as_deref(), + Some(url.as_str()) + ); // Done ends the key and shows the hosts of the server. app.event(Event::Key(Key { @@ -101,12 +106,4 @@ async fn berth_remote_signs_in_with_a_setup_key_and_uses_the_portal() { let refused = Portal::open(&url, "wrong").unwrap(); until("refusal", || refused.link() != Link::Connecting); assert_eq!(refused.link(), Link::Refused); - - // Forgetting removes what was kept. - let forgot = Terminal::new(Linked::default(), Settings::new(Some(kept.clone())), true).unwrap(); - assert!(!kept.exists()); - assert_eq!( - berth_page::device::Device::stored(&forgot, Kept::Token), - None - ); } diff --git a/crates/berth/src/ui.rs b/crates/berth/src/ui.rs index 87e2fc2..aed30fc 100644 --- a/crates/berth/src/ui.rs +++ b/crates/berth/src/ui.rs @@ -318,7 +318,7 @@ fn draw(frame: &mut Frame, app: &mut App, rows: &[Row], display: &mut ListState, (app.links, app.words) = draw_session(frame, session, &app.status); } if let Some(view) = &app.host.view { - (app.links, app.words) = draw_view(frame, view, &app.status, "Ctrl+Q"); + (app.links, app.words) = draw_view(frame, view, &app.status); } if let Some((question, _)) = &app.host.question { draw_question(frame, question); From ff3a49ddfead3bf54b644b20b7da889703126c2e Mon Sep 17 00:00:00 2001 From: Helight Date: Sun, 15 Nov 2026 01:13:02 +0100 Subject: [PATCH 15/94] feat(serve): the USB installer and every setting for the server's own user A host gets the action installer, which builds its unattended ISO, downloading Ubuntu's when the profile names none, and writes it to a USB drive with the sudo password given. Like changing settings that are not open to the network, it is offered only on the socket and in the process. The set-up of the screens offers the USB installer again. --- crates/berth-core/src/seed.rs | 95 ++++++++++++++ crates/berth-core/src/server.rs | 18 +++ crates/berth-page/src/app.rs | 39 +++++- crates/berth-page/src/setup.rs | 47 ++++++- crates/berth/src/serve/actions.rs | 202 +++++++++++++++++++++++++++++ crates/berth/src/serve/setup.rs | 17 ++- crates/berth/src/serve/tests.rs | 117 ++++++++++++++++- docs/openapi/berth.openapi.json | 2 +- docs/openapi/berth.operations.json | 2 +- 9 files changed, 520 insertions(+), 19 deletions(-) diff --git a/crates/berth-core/src/seed.rs b/crates/berth-core/src/seed.rs index b81c57b..d8c6af7 100644 --- a/crates/berth-core/src/seed.rs +++ b/crates/berth-core/src/seed.rs @@ -157,3 +157,98 @@ pub fn named(mut config: Value, name: &str) -> Value { } config } + +/// The unattended installer of a saved host: an ISO built from Ubuntu's +/// installer with the host's seed in it, ready to write to a USB drive. +pub struct Installer { + /// The builder, run in the provisioning source. + pub command: Command, + /// The private copy of the profile it reads, removed once it has run. + pub profile: tempfile::NamedTempFile, + /// The ISO it writes. + pub iso: PathBuf, +} + +/// The builder of `name`'s installer from Ubuntu's ISO at `ubuntu`, which +/// is checked against the profile's `iso_sha256` when it has one. +pub fn installer(paths: &Paths, name: &str, ubuntu: &std::path::Path) -> Result { + let host = Host::load(paths, name)?; + crate::host_type::guard(&host, crate::host_type::Capability::Apply)?; + let source = paths.source()?; + let dirs = apply::plugin_dirs(&plugins::found( + &source, + &plugins::own_dir(&paths.config_dir), + )); + let saved = host.config.clone(); + let mut config = named(tailnet::seed_profile(paths, &saved, name)?, name); + crate::kept_profile::for_seed(&mut config, &host.place.title(), &saved); + let hostname = config["hostname"].as_str().unwrap_or(name).to_owned(); + let profile = tailnet::profile_file(&config)?; + let own = crate::keys::operator_keys(paths, &saved)?; + let build = paths.build_dir(); + let mut command = Command::new("python3"); + command + .current_dir(&source) + .args([layout::BUILDER, "iso", "--config"]) + .arg(profile.path()) + .arg("--iso") + .arg(ubuntu) + .arg("--overwrite") + .env("DEVBOX_BUILD_DIR", &build) + .env("BERTH_PLUGINS", dirs.to_string()) + .env("BERTH_SSH_PUBLIC_KEY", own.join("\n")) + .stdin(std::process::Stdio::null()); + if let Some(sha) = saved["builder"]["iso_sha256"] + .as_str() + .filter(|sha| !sha.is_empty()) + { + command.args(["--sha256", sha]); + } + Ok(Installer { + command, + profile, + iso: build.join(format!("{hostname}-autoinstall.iso")), + }) +} + +/// Ubuntu's installer ISO a host's installer is built from: the one its +/// profile names, or none yet. +pub fn ubuntu_iso(config: &Value) -> Option { + config["builder"]["iso"] + .as_str() + .filter(|iso| !iso.is_empty()) + .map(crate::discovery::expand_path) +} + +/// The builder that downloads Ubuntu's current installer ISO into the ISO +/// folder and checks it, printing its path last. +pub fn fetch_iso(paths: &Paths) -> Result { + let mut command = Command::new("python3"); + command + .current_dir(paths.source()?) + .args([layout::BUILDER, "fetch-iso", "--dir"]) + .arg(paths.iso_dir()) + .stdin(std::process::Stdio::null()); + Ok(command) +} + +/// `sudo` writing the ISO to a whole USB drive, which it erases. With a +/// password it is read from standard input, and else sudo must need none. +pub fn write_usb( + paths: &Paths, + iso: &std::path::Path, + device: &str, + password: bool, +) -> Result { + let mut command = Command::new("sudo"); + match password { + true => command.args(["-S", "-p", ""]), + false => command.arg("-n"), + }; + command + .current_dir(paths.source()?) + .args(["bash", layout::WRITE_USB]) + .arg(iso) + .arg(device); + Ok(command) +} diff --git a/crates/berth-core/src/server.rs b/crates/berth-core/src/server.rs index bca5412..63b1c98 100644 --- a/crates/berth-core/src/server.rs +++ b/crates/berth-core/src/server.rs @@ -4,6 +4,7 @@ //! //! - `http://HOST:PORT`, `https://HOST[:PORT]`: over TCP, with the token //! - `unix:/path/to/serve.sock`: the socket of a `berth serve` on this machine +//! - `here:`: the server in this process, which [`serve_here`] gives use crate::{Result, paths::Paths, store::kind}; use berth_api::{ @@ -15,6 +16,16 @@ use serde_json::{Value, json}; use std::sync::Arc; use tokio::net::{TcpStream, UnixStream}; +/// The address of the server in this process. +pub const HERE: &str = "here:"; + +static DIAL: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Reach the server in this process, `here:`, through `dial`. +pub fn serve_here(dial: client::Dial) { + let _ = DIAL.set(dial); +} + #[derive(Debug, Clone, PartialEq)] pub struct Server { pub url: String, @@ -150,6 +161,13 @@ impl Server { /// Open the server's portal, with the configured token if there is one. pub async fn portal(&self) -> client::Result { let token = self.token.as_deref().unwrap_or(""); + if self.url == HERE { + let dial = DIAL + .get() + .ok_or_else(|| Error::Transport("no server runs in this berth".into()))?; + let socket = client::websocket(dial().await?, ops::PORTAL, "").await?; + return Ok(Portal::over(socket)); + } if let Some(path) = self.url.strip_prefix("unix:") { let stream = UnixStream::connect(path) .await diff --git a/crates/berth-page/src/app.rs b/crates/berth-page/src/app.rs index 5f77bb2..0e1c0eb 100644 --- a/crates/berth-page/src/app.rs +++ b/crates/berth-page/src/app.rs @@ -148,6 +148,8 @@ pub struct App { wanted: Option, /// The screens are left. quit: bool, + /// An action of the open host to begin once the server has listed them. + pending: Option<&'static str>, } impl App { @@ -216,6 +218,7 @@ impl App { installed: None, wanted: None, quit: false, + pending: None, }; // A setup key signs in with the token it collects, whatever was kept. if let (Some(key), false) = (linked.setup_key, app.server.is_empty()) { @@ -503,6 +506,7 @@ impl App { .filter(|action| action.runs == berth_api::Runs::Berth) .filter(|action| !["apply", "seed"].contains(&action.name.as_str())) .collect(); + self.begin_pending(); } Arrived::Actions(..) => {} // One that was removed takes its page back to the list. @@ -803,6 +807,28 @@ impl App { self.host.run(&action.name, body); } + /// Begin the action the set-up left the overview for, now that the + /// server has listed the host's actions. + fn begin_pending(&mut self) { + let Some(name) = self.pending else { + return; + }; + // A host saved just now may not be listed yet: its actions come again. + if self.host.own.is_empty() { + return; + } + self.pending = None; + let index = self + .host + .actions() + .iter() + .position(|action| action.name == name); + match index { + Some(index) => self.choose(Entry::Pick(Pick::Action(index))), + None => self.status = format!("The server offers no action {name} for {}", self.name), + } + } + fn choose(&mut self, entry: Entry) { match entry { Entry::Pick(Pick::Action(index)) => { @@ -837,7 +863,7 @@ impl App { } Entry::Setup => { if let Some(admin) = &self.admin { - self.setup = Some(Setup::open(&self.name, admin)); + self.setup = Some(Setup::open(&self.name, admin, self.local())); self.screen = Screen::Setup; } } @@ -1117,7 +1143,7 @@ impl App { self.address.clear(); self.status = format!("{name} is kept on the server once it is saved"); if let Some(admin) = &self.admin { - self.setup = Some(Setup::new(name, template, admin)); + self.setup = Some(Setup::new(name, template, admin, self.local())); self.screen = Screen::Setup; } } @@ -1788,11 +1814,16 @@ impl App { self.screen = Screen::Hosts; return; }; - if let Flow::Leave = setup.event(event, admin, &mut self.status) { + let flow = setup.event(event, admin, &mut self.status); + if let Flow::Leave | Flow::Act(_) = flow { // A host the server never got has no overview to go back to. - let kept = setup.kept(); + let acting = matches!(flow, Flow::Act(_)); + let kept = setup.kept() || acting; self.setup = None; self.asked = None; + if let Flow::Act(action) = flow { + self.pending = Some(action); + } match kept { true => { let (name, address) = (self.name.clone(), self.address.clone()); diff --git a/crates/berth-page/src/setup.rs b/crates/berth-page/src/setup.rs index caaeb12..4e7202a 100644 --- a/crates/berth-page/src/setup.rs +++ b/crates/berth-page/src/setup.rs @@ -20,19 +20,26 @@ use ratatui::{ use serde_json::{Value, json}; use tui_input::Input; -/// The ways the server installs a host itself. -const METHODS: [Action; 4] = [ +/// The ways the server installs a host itself. The USB installer is built +/// on the machine the server runs on. +const METHODS: [Action; 5] = [ Action::Machine, + Action::Iso, Action::CloudSeed, Action::Ssh, Action::Reach, ]; +/// The action of the host that builds its USB installer. +pub const INSTALLER: &str = "installer"; + /// What a key on the set-up pages leads to. pub enum Flow { Stay, /// Back to the host's overview, or to the hosts for one never saved. Leave, + /// To the host's overview, to run its action of this name there. + Act(&'static str), } pub struct Setup { @@ -66,14 +73,19 @@ pub struct Setup { pub panel: (u16, u16), /// The machine the server creates for the host, on the set-up tabs. pub machine: Machine, + /// The server runs on this machine, which builds what is made of its drives. + local: bool, + /// An action of the host to run once the profile is saved. + then: Option<&'static str>, } impl Setup { /// The set-up of a host the server has: its profile is on its way. - pub fn open(name: &str, admin: &Admin) -> Setup { + pub fn open(name: &str, admin: &Admin, local: bool) -> Setup { admin.profile(name); let mut setup = Setup { loading: true, + local, ..Setup::with(name, Value::Null, Value::Null) }; setup.ask_machine(admin); @@ -81,8 +93,11 @@ impl Setup { } /// The set-up of a new host, from the server's starting profile. - pub fn new(name: &str, template: Value, admin: &Admin) -> Setup { - let mut setup = Setup::with(name, template, Value::Null); + pub fn new(name: &str, template: Value, admin: &Admin, local: bool) -> Setup { + let mut setup = Setup { + local, + ..Setup::with(name, template, Value::Null) + }; setup::fit_target(&mut setup.config, setup.action); setup.ask_machine(admin); setup @@ -119,6 +134,8 @@ impl Setup { tabs: vec![], panel: (24, 80), machine: Machine::default(), + local: false, + then: None, } } @@ -200,6 +217,12 @@ impl Setup { fn problems(&self) -> Vec { let view = self.view(); let mut problems: Vec = view.problems_with(&self.machine); + if self.action == Action::Iso && !self.local { + problems.push(Problem::new( + Step::Install, + "The USB installer is built on the machine berth serve runs on: there, with berth ui or berth iso", + )); + } if self.action == Action::Ssh && view.text(Field::SshHost).is_empty() { problems.push(Problem::new( Step::Install, @@ -427,6 +450,9 @@ impl Setup { admin.save(&self.name, &self.config, move |admin| { match (action, host_type) { (Action::CloudSeed, _) => admin.seed(&name), + // Its drive and sudo password are asked for on the host's + // overview, once the server lists the host's actions. + (Action::Iso, _) => admin.actions(&name), (Action::Ssh, berth_api::HostType::Managed) => { admin.act(&name, &install, &Default::default(), size) } @@ -434,6 +460,9 @@ impl Setup { _ => admin.apply(&name, None, size), } }); + if action == Action::Iso { + self.then = Some(INSTALLER); + } Some("Saving…".into()) } @@ -602,6 +631,14 @@ impl Setup { } pub fn event(&mut self, event: Event, admin: &Admin, status: &mut String) -> Flow { + let flow = self.take(event, admin, status); + match self.then.take() { + Some(action) => Flow::Act(action), + None => flow, + } + } + + fn take(&mut self, event: Event, admin: &Admin, status: &mut String) -> Flow { match event { Event::Key(key) => { status.clear(); diff --git a/crates/berth/src/serve/actions.rs b/crates/berth/src/serve/actions.rs index 94ae09b..3924e76 100644 --- a/crates/berth/src/serve/actions.rs +++ b/crates/berth/src/serve/actions.rs @@ -53,6 +53,9 @@ pub(super) struct Seen<'a> { pub observed: Option, /// Why its controller did not answer, when it was asked and did not. pub unanswered: Option<&'a str>, + /// The caller is on the machine the server runs on: in its process, or + /// on its socket. + pub local: bool, } /// berth's own actions that run through the host's controller, so the host @@ -106,6 +109,11 @@ pub(super) static HOST: &[Builtin] = &[ describe: rename_action, run: rename, }, + Builtin { + name: "installer", + describe: installer_action, + run: installer, + }, ]; /// The actions of the installation itself. @@ -245,6 +253,7 @@ fn no_action(subject: &str, action: &str, actions: &[Action]) -> Fail { (status = 404, description = "No such host", body = ErrorBody)))] pub async fn host_actions( State(state): App, + access: Option>, Path(name): Path, ) -> Answer>> { state.refresh(false); @@ -270,6 +279,7 @@ pub async fn host_actions( host_type: host_type::of(&profile), observed, unanswered, + local: access.is_none(), }))) } @@ -326,6 +336,7 @@ pub async fn host_act( host_type: host_type::of(&profile), observed, unanswered: unanswered.as_deref(), + local: access.is_none(), }); let found = actions .iter() @@ -354,6 +365,7 @@ fn installation_list() -> Vec { host_type: HostType::Workstation, observed: None, unanswered: None, + local: false, }; INSTALLATION .iter() @@ -654,6 +666,196 @@ fn seed(state: Arc, name: String, _: Act) -> Run { }) } +/// Why an action that works with this machine's own drives and files is +/// not offered to a caller elsewhere. +fn only_here(what: &str) -> String { + format!("{what} is done on the machine berth serve runs on: there, with berth ui or berth iso") +} + +fn installer_action(seen: &Seen) -> Action { + // The drives are looked for only for a caller who can write them. + let drives = match seen.local { + true => berth_core::discovery::usb_drives(), + false => vec![], + }; + let kept = seen.profile["builder"]["usb_device"].as_str().unwrap_or(""); + let default = match (kept, drives.as_slice()) { + ("", [(_, only)]) => only.clone(), + (kept, _) => kept.to_owned(), + }; + let found = match drives.is_empty() { + true => "No USB drive is connected now.".to_owned(), + false => format!( + "Connected now: {}.", + drives + .iter() + .map(|(label, _)| label.as_str()) + .collect::>() + .join("; ") + ), + }; + let action = Action { + arguments: vec![ + Argument { + name: "device".into(), + label: "USB drive to write it to".into(), + default, + help: format!( + "The whole USB drive the finished ISO is written to, such as /dev/sdb. It is erased. Empty builds the ISO only. {found}" + ), + ..Argument::default() + }, + Argument { + name: "password".into(), + label: "Your sudo password, to write the drive".into(), + help: "Writing the drive runs as root through sudo. Empty when sudo needs none or no drive is written.".into(), + secret: true, + ..Argument::default() + }, + ], + ..set_up( + "installer", + "Build the USB installer", + "For a blank machine: build an installer image from Ubuntu Server's ISO that installs and sets up the host without questions, and write it to a USB drive. Without an ISO in the profile the current one is downloaded and checked first. Booting the drive erases the machine's chosen disk.", + ) + }; + let action = host_type::fit(action, seen.name, seen.host_type, Capability::Apply); + match (seen.local, seen.profile.is_null()) { + (false, _) => unavailable(action, Some(only_here("Building the USB installer"))), + (_, true) => unavailable( + action, + Some(format!("{} has no profile on the server", seen.name)), + ), + _ => action, + } +} + +fn installer(state: Arc, name: String, act: Act) -> Run { + Box::pin(async move { + let bad = + |error: Box| Fail::new(code::BAD_REQUEST, error.to_string()); + let text = |key: &str| act.arguments.get(key).map_or("", |value| value.trim()); + let device = text("device").to_owned(); + let password = act.arguments.get("password").cloned().unwrap_or_default(); + // Only a whole USB drive that is connected now is written, as the script checks again. + if !device.is_empty() + && !berth_core::discovery::usb_drives() + .iter() + .any(|(_, path)| *path == device) + { + return Err(Fail::new( + code::BAD_REQUEST, + format!("{device} is no USB drive connected to this machine"), + )); + } + let profile = profile_of(&state, &name); + let ubuntu = berth_core::seed::ubuntu_iso(&profile); + if let Some(iso) = &ubuntu + && !iso.is_file() + { + return Err(Fail::new( + code::BAD_REQUEST, + format!("The profile's ISO {} is not there", iso.display()), + )); + } + // The host must be one an installer can be built for before a job starts. + let paths = state.paths.clone(); + let fetch = berth_core::seed::fetch_iso(&paths).map_err(bad)?; + let mut request = Request::new(Subject::Host(name.clone()), "installer"); + request.token = act.token; + request.secrets = Some(password.clone()) + .filter(|password| !password.is_empty()) + .into_iter() + .collect(); + let work = Work::Function(Box::new(move |out| { + let ubuntu = match ubuntu { + Some(iso) => iso, + None => { + let _ = writeln!(out, "Downloading Ubuntu's installer ISO…"); + match fetched(fetch, out) { + Some(iso) => iso, + None => return false, + } + } + }; + let built = match berth_core::seed::installer(&paths, &name, &ubuntu) { + Ok(built) => built, + Err(error) => { + let _ = writeln!(out, "✗ {error}"); + return false; + } + }; + let (iso, _profile) = (built.iso.clone(), built.profile); + let program = berth_core::runner::Program { + command: built.command, + input: None, + files: vec![], + }; + if berth_core::runner::run_program(program, out) != Some(0) { + return false; + } + if device.is_empty() { + let _ = writeln!(out, "Built {}", iso.display()); + return true; + } + let write = + match berth_core::seed::write_usb(&paths, &iso, &device, !password.is_empty()) { + Ok(write) => write, + Err(error) => { + let _ = writeln!(out, "✗ {error}"); + return false; + } + }; + let program = berth_core::runner::Program { + command: write, + input: (!password.is_empty()).then(|| format!("{password}\n").into_bytes()), + files: vec![], + }; + let written = berth_core::runner::run_program(program, out) == Some(0); + if written { + let _ = writeln!( + out, + "Next: boot the machine from the USB drive. Booting it erases the chosen disk." + ); + } + written + })); + let job = state.runner.start(request, work).map_err(refused)?; + Ok(Acted { + job: Some(job_info(&state.paths, job)), + ..Acted::default() + }) + }) +} + +/// Download Ubuntu's ISO with the builder: where it is, which it says last. +fn fetched( + command: std::process::Command, + out: &mut berth_core::runner::Output, +) -> Option { + let mut command = command; + let output = match command.stderr(std::process::Stdio::piped()).output() { + Ok(output) => output, + Err(error) => { + let _ = writeln!(out, "✗ python3: {error}"); + return None; + } + }; + let _ = out.write_all(&output.stderr); + let said = String::from_utf8_lossy(&output.stdout); + let iso = said + .lines() + .last() + .map(|line| std::path::PathBuf::from(line.trim())); + match (output.status.success(), iso) { + (true, Some(iso)) if iso.is_file() => Some(iso), + _ => { + let _ = writeln!(out, "✗ Downloading Ubuntu's installer ISO failed"); + None + } + } +} + fn secrets_action(seen: &Seen) -> Action { let kept = seen .host_actions diff --git a/crates/berth/src/serve/setup.rs b/crates/berth/src/serve/setup.rs index 1e62370..fb6d126 100644 --- a/crates/berth/src/serve/setup.rs +++ b/crates/berth/src/serve/setup.rs @@ -5,11 +5,12 @@ use super::{ Serve, api::{Answer, App, Fail, internal}, + auth::Access, }; use axum::{ Json, body::Bytes, - extract::{Path, State}, + extract::{Extension, Path, State}, }; use berth_api::{ Done, ErrorBody, PluginList, PluginOrigin, PluginReport, PluginUpdateSpec, PluginUpdates, code, @@ -367,7 +368,12 @@ pub struct SettingValue { #[utoipa::path(get, path = "/v1/settings", summary = "The server's settings.", tag = "set-up", responses((status = 200, description = "The settings", body = Vec)))] -pub async fn settings(State(state): App) -> Answer>> { +pub async fn settings( + State(state): App, + access: Option>, +) -> Answer>> { + // The user the server runs as changes any of them, as berth config does. + let local = access.is_none(); let saved = state.paths.settings().map_err(internal)?; let settings = SETTINGS .iter() @@ -380,23 +386,24 @@ pub async fn settings(State(state): App) -> Answer>> { None => String::new(), }, meaning: (*meaning).into(), - open: OPEN_SETTINGS.contains(key), + open: local || OPEN_SETTINGS.contains(key), }) .collect(); Ok(Json(settings)) } -#[utoipa::path(put, path = "/v1/settings/{key}", summary = "Change one of the settings that are open to callers.", tag = "set-up", +#[utoipa::path(put, path = "/v1/settings/{key}", summary = "Change one of the settings that are open to callers, or any for the user the server runs as.", tag = "set-up", params(("key" = String, Path, description = "The setting")), request_body(content = SettingValue, description = "The value"), responses((status = 200, description = "Saved", body = Done), (status = 403, description = "This one is set on the server itself", body = ErrorBody)))] pub async fn set_setting( State(state): App, + access: Option>, Path(key): Path, Json(setting): Json, ) -> Answer> { - if !OPEN_SETTINGS.contains(&key.as_str()) { + if access.is_some() && !OPEN_SETTINGS.contains(&key.as_str()) { return Err(Fail::new( code::FORBIDDEN, format!("{key} is set on the server itself, with berth config"), diff --git a/crates/berth/src/serve/tests.rs b/crates/berth/src/serve/tests.rs index a3a5142..2c6834b 100644 --- a/crates/berth/src/serve/tests.rs +++ b/crates/berth/src/serve/tests.rs @@ -821,7 +821,8 @@ async fn a_hosts_actions_are_its_controllers_and_berths_own() { "secrets", "trust-key", "host-key", - "rename" + "rename", + "installer" ] ); let status = &actions[0]; @@ -1437,7 +1438,8 @@ async fn the_server_is_set_up_through_the_api() { .contains("does not answer") ); - // Some settings are a caller's to change, who gets in is not. + // The user the server runs as changes any setting on its socket; over + // the network only some are a caller's to change. let value = |value: &str| json!({"value": value}); assert_eq!( send(client, "PUT", "/v1/settings/retention_days", value("30")) @@ -1454,7 +1456,7 @@ async fn the_server_is_set_up_through_the_api() { ) .await .0, - 403 + 200 ); let (_, settings) = send(client, "GET", "/v1/settings", Value::Null).await; let days = settings @@ -4034,3 +4036,112 @@ fn the_screen_keeps_the_address_a_server_gave_a_new_machine_and_opens_its_overvi let kept = own.load(&served.state.paths).unwrap().unwrap(); assert_eq!(kept["access"]["address"], "192.0.2.40", "{kept}"); } + +/// What works with this machine's own drives and settings is offered to its +/// user, on the socket or in the process, and not over the network. +#[tokio::test(flavor = "multi_thread")] +async fn the_installer_and_every_setting_are_for_the_user_here() { + let dir = tempfile::tempdir().unwrap(); + let state = state_in(dir.path(), Some("s3cret-token")); + let profile = json!({"hostname": "studio", "builder": {}, "access": {"address": "192.0.2.7", "link": ["sh", "-c", "exit 1"]}}); + berth_core::profiles::Place::own("studio") + .unwrap() + .save(&state.paths, &profile) + .unwrap(); + let socket = dir.path().join("serve.sock"); + let unix = tokio::net::UnixListener::bind(&socket).unwrap(); + let local = api::router(state.clone(), false); + tokio::spawn(async move { axum::serve(unix, local).await }); + let tcp = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = tcp.local_addr().unwrap(); + let guarded = api::router(state.clone(), true); + tokio::spawn(async move { axum::serve(tcp, guarded).await }); + let installer = |listed: &Value| { + listed + .as_array() + .unwrap() + .iter() + .find(|action| action["name"] == "installer") + .cloned() + .unwrap() + }; + + let mut client = Client::unix(&socket).await.unwrap(); + let (status, listed) = send(&mut client, "GET", "/v1/hosts/studio/actions", Value::Null).await; + assert_eq!(status, 200, "{listed}"); + let here = installer(&listed); + assert_eq!(here["available"], true, "{here}"); + assert_eq!(here["arguments"][1]["secret"], true); + // Only a USB drive that is connected is written. + let act = json!({"arguments": {"device": "/dev/berth-test-none"}}); + let (status, said) = send( + &mut client, + "POST", + "/v1/hosts/studio/actions/installer", + act, + ) + .await; + assert_eq!(status, 400, "{said}"); + assert!( + said["error"]["message"] + .as_str() + .unwrap() + .contains("no USB drive") + ); + + let (status, listed) = as_bearer( + address, + "s3cret-token", + "GET", + "/v1/hosts/studio/actions", + Value::Null, + ) + .await; + assert_eq!(status, 200, "{listed}"); + let elsewhere = installer(&listed); + assert_eq!(elsewhere["available"], false); + assert!( + elsewhere["why"] + .as_str() + .unwrap() + .contains("berth serve runs on"), + "{elsewhere}" + ); + let (status, _) = as_bearer( + address, + "s3cret-token", + "POST", + "/v1/hosts/studio/actions/installer", + json!({}), + ) + .await; + assert_eq!(status, 501); + + // Settings of the machine itself, such as the ISO folder, change only here. + let iso = json!({"value": "/srv/iso"}); + let (status, _) = as_bearer( + address, + "s3cret-token", + "PUT", + "/v1/settings/iso_dir", + iso.clone(), + ) + .await; + assert_eq!(status, 403); + let (status, said) = send(&mut client, "PUT", "/v1/settings/iso_dir", iso).await; + assert_eq!(status, 200, "{said}"); + assert_eq!(state.paths.setting("iso_dir").as_deref(), Some("/srv/iso")); + let (_, listed) = send(&mut client, "GET", "/v1/settings", Value::Null).await; + let open = |listed: &Value| { + listed + .as_array() + .unwrap() + .iter() + .find(|setting| setting["key"] == "iso_dir") + .unwrap()["open"] + .clone() + }; + assert_eq!(open(&listed), true); + let (_, listed) = as_bearer(address, "s3cret-token", "GET", "/v1/settings", Value::Null).await; + assert_eq!(open(&listed), false); +} diff --git a/docs/openapi/berth.openapi.json b/docs/openapi/berth.openapi.json index 8e9b7bf..80a6560 100644 --- a/docs/openapi/berth.openapi.json +++ b/docs/openapi/berth.openapi.json @@ -7797,7 +7797,7 @@ "description": "This one is set on the server itself" } }, - "summary": "Change one of the settings that are open to callers.", + "summary": "Change one of the settings that are open to callers, or any for the user the server runs as.", "tags": [ "set-up" ] diff --git a/docs/openapi/berth.operations.json b/docs/openapi/berth.operations.json index 8233b36..66cc397 100644 --- a/docs/openapi/berth.operations.json +++ b/docs/openapi/berth.operations.json @@ -2913,7 +2913,7 @@ } }, "role": "admin", - "summary": "Change one of the settings that are open to callers." + "summary": "Change one of the settings that are open to callers, or any for the user the server runs as." }, { "args": [], From adc7cbd8e1df16670ae9730666cf0ab8a46ba667 Mon Sep 17 00:00:00 2001 From: Helight Date: Sun, 15 Nov 2026 01:20:23 +0100 Subject: [PATCH 16/94] feat!: berth's screens are berth-page's, and the old terminal UI is gone berth and berth HOST open the same screens as berth ui. apply, seed and iso go through a server like everything the screens do: the one berth is set to use, a berth serve of the user here, or one in the process, which waits for the jobs it runs. A profile file can no longer be opened by its path; berth profile HOST --set FILE takes it in. --- Cargo.lock | 4 - crates/berth-core/src/server.rs | 12 +- crates/berth-page/src/net.rs | 14 +- crates/berth/Cargo.toml | 8 +- crates/berth/src/app.rs | 2804 ------------ crates/berth/src/commands.rs | 112 +- crates/berth/src/fields.rs | 1 - crates/berth/src/keys.rs | 194 - crates/berth/src/main.rs | 1050 +---- crates/berth/src/mirror.rs | 102 - crates/berth/src/picker.rs | 109 - crates/berth/src/profile.rs | 226 + crates/berth/src/provisioner_command.rs | 8 - crates/berth/src/provisioner_tab.rs | 501 --- crates/berth/src/remote.rs | 532 --- crates/berth/src/serve/here.rs | 110 + crates/berth/src/serve/tests.rs | 126 - crates/berth/src/session.rs | 206 - crates/berth/src/ui.rs | 5276 ----------------------- tests/e2e/e2e_local.py | 6 +- 20 files changed, 639 insertions(+), 10762 deletions(-) delete mode 100644 crates/berth/src/app.rs delete mode 100644 crates/berth/src/fields.rs delete mode 100644 crates/berth/src/keys.rs delete mode 100644 crates/berth/src/mirror.rs delete mode 100644 crates/berth/src/picker.rs create mode 100644 crates/berth/src/profile.rs delete mode 100644 crates/berth/src/provisioner_tab.rs delete mode 100644 crates/berth/src/remote.rs delete mode 100644 crates/berth/src/session.rs delete mode 100644 crates/berth/src/ui.rs diff --git a/Cargo.lock b/Cargo.lock index 1c54968..0ff3ad7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -168,24 +168,20 @@ dependencies = [ "berth-api", "berth-core", "berth-page", - "berth-pty", "berth-tui", "berthd", "crossterm", "futures-util", "jsonwebtoken", "libc", - "pulldown-cmark", "ratatui", "ring", "serde", "serde_json", "tempfile", "tokio", - "tui-input", "utoipa", "utoipa-axum", - "vt100", ] [[package]] diff --git a/crates/berth-core/src/server.rs b/crates/berth-core/src/server.rs index 63b1c98..6f61a47 100644 --- a/crates/berth-core/src/server.rs +++ b/crates/berth-core/src/server.rs @@ -19,11 +19,13 @@ use tokio::net::{TcpStream, UnixStream}; /// The address of the server in this process. pub const HERE: &str = "here:"; -static DIAL: std::sync::OnceLock = std::sync::OnceLock::new(); +static DIAL: std::sync::RwLock> = std::sync::RwLock::new(None); -/// Reach the server in this process, `here:`, through `dial`. +/// Reach the server in this process, `here:`, through `dial`, until another is given. pub fn serve_here(dial: client::Dial) { - let _ = DIAL.set(dial); + *DIAL + .write() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(dial); } #[derive(Debug, Clone, PartialEq)] @@ -163,7 +165,9 @@ impl Server { let token = self.token.as_deref().unwrap_or(""); if self.url == HERE { let dial = DIAL - .get() + .read() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone() .ok_or_else(|| Error::Transport("no server runs in this berth".into()))?; let socket = client::websocket(dial().await?, ops::PORTAL, "").await?; return Ok(Portal::over(socket)); diff --git a/crates/berth-page/src/net.rs b/crates/berth-page/src/net.rs index 448ba98..aea92e6 100644 --- a/crates/berth-page/src/net.rs +++ b/crates/berth-page/src/net.rs @@ -44,11 +44,13 @@ pub struct Target { } /// The server in this process, when the program runs one. -static HERE: OnceLock = OnceLock::new(); +static HERE: std::sync::RwLock> = std::sync::RwLock::new(None); -/// Reach `here:` through `dial`, for the rest of the program. +/// Reach `here:` through `dial`, until another is given. pub fn serve_here(dial: client::Dial) { - let _ = HERE.set(dial); + *HERE + .write() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(dial); } /// Where `path` of `server` is: `http(s)://HOST[:PORT]`, `unix:/path` or `here:`. @@ -127,7 +129,11 @@ fn tls() -> Arc { pub async fn connect(target: &Target) -> Result { let (name, port, secure) = match &target.way { Way::Here => { - let dial = HERE.get().ok_or("There is no server in this program")?; + let dial = HERE + .read() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone() + .ok_or("There is no server in this program")?; return dial().await.map_err(|error| describe(&error)); } #[cfg(unix)] diff --git a/crates/berth/Cargo.toml b/crates/berth/Cargo.toml index 2af85fb..0bef1cb 100644 --- a/crates/berth/Cargo.toml +++ b/crates/berth/Cargo.toml @@ -8,7 +8,6 @@ license.workspace = true [dependencies] berth-core.workspace = true berth-api = { workspace = true, features = ["client"] } -berth-pty.workspace = true berth-tui.workspace = true # For its API document, which berth serve's includes. berthd = { path = "../berthd" } @@ -18,18 +17,15 @@ serde.workspace = true axum.workspace = true utoipa.workspace = true utoipa-axum.workspace = true -ratatui = { version = "=0.30.2", default-features = false, features = ["crossterm"] } crossterm = "=0.29.0" serde_json = "1" tempfile = "3" -vt100 = "=0.16.2" libc = "0.2" -pulldown-cmark = { version = "0.13", default-features = false } jsonwebtoken = { version = "11", default-features = false, features = ["rust_crypto"] } - -tui-input = { workspace = true, features = ["crossterm"] } berth-page.workspace = true [dev-dependencies] # Signs the access tokens of the tests. ring = "0.17" +# Draws the screens of the tests. +ratatui = { version = "=0.30.2", default-features = false } diff --git a/crates/berth/src/app.rs b/crates/berth/src/app.rs deleted file mode 100644 index 1bc651c..0000000 --- a/crates/berth/src/app.rs +++ /dev/null @@ -1,2804 +0,0 @@ -//! Wizard state: the profile being edited, what each step shows, and running the chosen action. - -use crate::{ - Result, credentials, - discovery::{self, Choices, expand_path}, - fields::{Action, Field, Kind, OFFERS, Step}, - job::{Job, Stage}, - picker::Picker, - plugins::{self, Plugin}, - remote::{HostView, State}, - theme, -}; -use berth_core::{ - apply, - host::Host, - host_type, - paths::{Paths, layout}, - profiles::Place, -}; -use berth_tui::host::Pick; -use berth_tui::machine::{self, Machine, Next}; -use berth_tui::setup::{self, set_pointer}; -pub use berth_tui::setup::{FeatureGroup, Item, value_line}; -use ratatui::{style::Style, text::Line, widgets::ListState}; -use serde_json::{Value, json}; -use std::{io::Write, path::PathBuf, process::Command, sync::mpsc}; -use tui_input::Input; - -/// What a selectable row does when activated. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub enum Entry { - Action(Action), - Field(Field), - /// Something the overview of a host offers, by name. - Offer(&'static str), - /// The heading of a group on the Features page. - Group(usize), - /// A plugin's feature, switched on or off for this host: its index among them. - Feature(usize), - /// An action of the host, by index into what it listed. - HostAction(usize), - /// A session on the host, by index into what it listed. - HostSession(usize), - /// A registry this host can be given, by index into `App::registry_names`. - HostRegistry(usize), - /// A secret this host can be given, by index into `App::secret_names`. - HostSecret(usize), - /// One of an account's SSH keys, or the row that adds one. - Key(setup::Account, Option), - /// A row of the machine berth creates for the host. - Machine(machine::Pick), - /// Open the set-up flow. - Setup, - Run, - /// Save the profile, as Ctrl+S does. - Save, -} - -pub struct Row { - pub line: Line<'static>, - /// `None` for headings and other rows the cursor skips. - pub entry: Option, -} - -impl Row { - fn info(line: impl Into>) -> Self { - Row { - line: line.into(), - entry: None, - } - } - fn entry(line: impl Into>, entry: Entry) -> Self { - Row { - line: line.into(), - entry: Some(entry), - } - } -} - -pub struct App { - pub config: Value, - /// The profile as it was last saved, for detecting unsaved changes. - saved: Value, - /// Where the profile is kept. - pub place: Place, - /// The installation this berth is. - pub paths: Paths, - pub step: Step, - /// What Run does: the install method, or `Manage` while on the Manage tab. - pub action: Action, - /// Action for the next `execute`, when it differs from the tab's own. - pub terminal_action: Option, - /// A command of this machine in a terminal inside the UI: `ssh` to a host - /// that is not set up yet. - pub session: Option, - /// What the host itself says it can do, its sessions, and the panel onto one. - pub host: HostView, - /// The password dialog for the host was shown; it is not opened by itself again. - password_asked: bool, - /// The next connection was asked for, by Try again or a changed - /// address: it logs in even after the host refused the login. - force_login: bool, - /// The Terminal row opens the agent's shell and not the SSH user's. - pub as_agent: bool, - /// Plugins found in the source and in the user's plugin directory. - pub plugins: Vec, - /// The public half of this berth's own SSH key, which hosts take. For a - /// server's host it is the server's. - pub own_public: String, - /// The names of the keys of the key ring that logs in to this host: this - /// berth's, or the server's for a server's host. - pub ring_keys: Vec, - /// What those plugins can install, for the Features page. - catalogue: Vec, - /// The registries and secrets the host can be given: of this berth, or - /// what is known of its server's. Without berth's store, as in tests or - /// when it does not open, why there are none; the host is still reached. - pub access: std::result::Result, - /// The registries and secrets that exist, for the Settings tab. - pub registry_names: Vec, - pub secret_names: Vec, - /// Web addresses in the output on screen, and where they are, for clicking. - pub links: Vec<(ratatui::layout::Rect, String)>, - /// The words of that output, for copying. - pub words: Vec<(ratatui::layout::Rect, String)>, - /// The install method to return to when leaving the Manage tab. - method: Action, - /// Index into the selectable rows of the current step. - pub list: ListState, - pub editing: Option, - /// The editor holds a plain password to hash rather than a field value. - pub password_entry: bool, - pub suggestions: Choices, - pub suggestion_list: ListState, - pub suggestion_focus: bool, - pub public_keys: Choices, - pub private_keys: Choices, - pub ssh_hosts: Choices, - /// Machines on this machine's tailnet, as (description, address). - pub tailnet_hosts: Choices, - /// Wi-Fi networks saved on this machine, as (SSID, password). - pub wifi_networks: Choices, - pub status: String, - /// The SSH address is being changed to reach a host again: saving it - /// connects once more. - pub retry_address: bool, - pub picker: Option, - /// sudo is authorised, so the saved Wi-Fi passwords can be read. - pub privileged: bool, - /// The administrator password dialog, while it is open. - pub unlock: Option, - pub unlock_failed: bool, - /// What the administrator password is being asked for. - pub unlock_reason: &'static str, - /// Run the action once the password dialog succeeds. - pub pending_run: bool, - /// The password dialog is for sudo on the managed host, not this machine. - pub unlock_remote: bool, - /// Where the builder writes archives, seeds and installer images. - pub build_dir: PathBuf, - /// Where downloaded installer ISOs are kept. - pub iso_dir: PathBuf, - /// The running job downloads the installer ISO; its last line is the path. - fetching_iso: bool, - /// Only write the ISO that is already built, without building it again. - pub write_only: bool, - /// The dialog for picking one of several USB drives is open. - pub choosing_drive: bool, - /// Question that needs a yes before the action runs. - pub confirm: Option, - /// The action running inside the UI, and its output once it has ended. - pub job: Option, - /// Connected USB drives, as (description, device path). - pub usb_drives: Choices, - /// A link of the panel as a QR code, over everything else. - pub qr: Option, - /// The machine berth creates for the host, on the set-up tabs. - pub machine: Machine, - /// What is being asked of it and of the provisioners, until it answers. - machine_answers: Option>, - /// The running job is one of the machine's. - pub machine_job: bool, - /// What a berth server lists of its own actions on the host, until it answers. - own_answers: Option>>, - /// The berth command one of berth's own actions on the host runs, in - /// the normal terminal, the next time the screen is left. - pub own_command: Option>, - /// The host's new name after one of berth's own actions renamed it, so - /// its screen is opened again under that name. - pub renamed: Option, - /// What the host's controller says the host is, asked in the background - /// once its address is given on the set-up's Install tab. - found_type: Option>>, - /// The type was chosen on the Type row, so what the host says is only told. - type_chosen: bool, -} - -/// What the provisioners there are, and the host's machine, came back as. -type Answers = ( - std::result::Result, String>, - std::result::Result, String>, -); - -/// Ask where provisioners run, as `berth provision` does: the berth server -/// when one is set, otherwise here. The host's machine is its resource of the -/// machine kind, as its provisioner says it is now. -fn machine_answers(paths: &Paths, name: &str) -> Answers { - let text = |error: &dyn std::fmt::Display| error.to_string(); - let source = crate::provisioner_command::Source::of(paths); - let listed = source.list().map_err(|error| text(&error)); - let found = source - .resources(None, Some("machine"), Some(name)) - .map_err(|error| text(&error)) - .and_then(|found| match found.first() { - None => Ok(None), - Some(made) => source - .resource(&made.id) - .map(Some) - .map_err(|error| text(&error)), - }); - let found = match found { - Err(error) if machine::absent(&error) => Ok(None), - found => found, - }; - (listed, found) -} - -/// The rows of a set-up page, as rows of this screen. -fn lift(rows: Vec) -> Vec { - rows.into_iter() - .map(|row| Row { - line: row.line, - entry: row.entry.map(|entry| match entry { - setup::Entry::Action(action) => Entry::Action(action), - setup::Entry::Field(field) => Entry::Field(field), - setup::Entry::Group(index) => Entry::Group(index), - setup::Entry::Feature(index) => Entry::Feature(index), - setup::Entry::Registry(index) => Entry::HostRegistry(index), - setup::Entry::Secret(index) => Entry::HostSecret(index), - setup::Entry::Key(account, index) => Entry::Key(account, index), - setup::Entry::Machine(pick) => Entry::Machine(pick), - setup::Entry::Run => Entry::Run, - setup::Entry::Save => Entry::Save, - }), - }) - .collect() -} - -/// The title of the job that creates a host's machine. -const CREATE_MACHINE: &str = "Create machine"; - -impl App { - pub fn new(paths: Paths, place: Place, config: Value) -> Self { - let mut app = App { - saved: Value::Null, - config, - place, - paths, - step: Step::Install, - action: Action::Iso, - method: Action::Iso, - terminal_action: None, - session: None, - host: HostView::default(), - password_asked: false, - force_login: false, - as_agent: true, - links: vec![], - words: vec![], - list: ListState::default().with_selected(Some(0)), - editing: None, - password_entry: false, - suggestions: vec![], - suggestion_list: ListState::default(), - suggestion_focus: false, - public_keys: vec![], - private_keys: vec![], - ssh_hosts: vec![], - tailnet_hosts: vec![], - wifi_networks: vec![], - plugins: vec![], - own_public: String::new(), - ring_keys: vec![], - catalogue: vec![], - access: Err("berth's store is not open, so there are no secrets or registries".into()), - registry_names: vec![], - secret_names: vec![], - status: String::new(), - retry_address: false, - picker: None, - privileged: false, - unlock: None, - unlock_failed: false, - unlock_reason: "", - pending_run: false, - unlock_remote: false, - build_dir: "build".into(), - iso_dir: "build/iso".into(), - fetching_iso: false, - write_only: false, - choosing_drive: false, - confirm: None, - job: None, - usb_drives: vec![], - qr: None, - machine: Machine::default(), - machine_answers: None, - machine_job: false, - own_answers: None, - own_command: None, - renamed: None, - found_type: None, - type_chosen: false, - }; - app.saved = app.config.clone(); - app - } - - /// The profile as its set-up pages see it. - fn view(&self) -> setup::Profile<'_> { - setup::Profile { - config: &self.config, - step: self.step, - action: self.action, - features: &self.catalogue, - registries: &self.registry_names, - secrets: &self.secret_names, - own_key: &self.own_public, - named: setup::valid_hostname(&self.name()), - } - } - - pub fn text(&self, field: Field) -> &str { - self.view().text(field) - } - - /// State of a toggle. Unset feature switches are on, like the role defaults. - pub fn enabled(&self, field: Field) -> bool { - self.view().enabled(field) - } - - /// Read which registries and secrets exist. They are kept outside the profile. - pub fn load_access(&mut self) { - let Ok(store) = &self.access else { - return; - }; - self.registry_names = store - .registries() - .unwrap_or_default() - .keys() - .cloned() - .collect(); - let names = store.secret_names(); - setup::default_enrollment(&mut self.config, &names); - self.secret_names = berth_tui::setup::host_secrets(names); - } - - /// The registries and secrets, or why there are none. - pub fn access(&self) -> Result<&crate::registry::Store> { - self.access.as_ref().map_err(|error| error.as_str().into()) - } - - pub fn toggle_host_registry(&mut self, index: usize) { - setup::toggle_registry(&mut self.config, &self.registry_names[index]); - } - - /// How this host gets a secret: `GH_TOKEN` for a variable, a path for a - /// file, nothing when it does not get it. - pub fn host_secret(&self, index: usize) -> String { - self.view().secret_how(index) - } - - pub fn set_host_secret(&mut self, index: usize, how: &str) { - if let Err(why) = setup::set_secret(&mut self.config, &self.secret_names[index], how) { - self.status = why.into(); - } - } - - /// Read the plugins of the source (the working directory) and the user's own. - pub fn load_plugins(&mut self, user_dir: PathBuf) { - self.set_plugins(plugins::load(&["plugins".into(), user_dir])); - } - - pub fn set_plugins(&mut self, plugins: Vec) { - self.catalogue = plugins - .iter() - .flat_map(|plugin| { - plugin.features.iter().map(|feature| setup::Feature { - key: format!("{}/{}", plugin.id, feature.id), - label: feature.label.clone(), - group: feature.group.clone(), - help: feature.help.to_owned(), - }) - }) - .collect(); - self.plugins = plugins; - } - - /// What a server's host can have installed: what the server's plugins - /// offer, as `setup.catalogue` lists it. - pub fn set_features(&mut self, features: Vec) { - self.catalogue = features; - } - - /// The groups of the Features page: the built-in ones, with what plugins add - /// to them, then groups only plugins have. - pub fn feature_groups(&self) -> Vec { - self.view().feature_groups() - } - - pub fn item_enabled(&self, item: Item) -> bool { - self.view().item_enabled(item) - } - - pub fn set_item(&mut self, item: Item, on: bool) { - match item { - Item::Field(field) => self.set_toggle(field, on), - Item::Feature(index) => { - setup::set_feature(&mut self.config, &self.catalogue, index, on) - } - } - } - - /// The group whose heading is selected. - pub fn selected_group(&self) -> Option { - match self.selected_entry() { - Some(Entry::Group(index)) => Some(index), - _ => None, - } - } - - /// Whether everything in a group is on, which is when switching it turns it off. - pub fn group_all_on(&self, index: usize) -> bool { - self.view().group_all_on(index) - } - - /// Switch everything in a group on, or off when all of it is on already. - pub fn toggle_group(&mut self, index: usize) { - let on = !self.group_all_on(index); - let group = self.feature_groups().swap_remove(index); - for item in group.items { - self.set_item(item, on); - } - self.status = format!("{}: all {}", group.title, if on { "on" } else { "off" }); - } - - /// Set a toggle. The coding agents share the older switch for all of them, - /// which the role still reads: it is on while any agent is. - fn set_toggle(&mut self, field: Field, on: bool) { - self.set(field, json!(on)); - } - - fn set(&mut self, field: Field, value: Value) { - set_pointer(&mut self.config, field.spec().pointer, value); - // Another address is another host to ask. - use Field::*; - if matches!(field, SshHost | SshUser | SshPort | Login | AskBecomePass) { - self.reconnect_host(); - } - } - - /// The profile as it is kept now, filled in as the screen expects it. - fn stored(&self) -> Option { - let profile = self.place.load(&self.paths).ok()??; - parse_config(profile.to_string().as_bytes()).ok() - } - - /// Take the profile in as it is kept now, when it changed. Without unsaved - /// changes it replaces the one on screen, and the host is asked at its - /// address again if that changed. Returns whether it was taken in, or - /// `None` when nothing changed. - fn take_stored(&mut self) -> Option<(bool, Value)> { - let profile = self.stored()?; - if profile == self.saved { - return None; - } - if self.unsaved() { - return Some((false, profile)); - } - let moved = profile["access"] != self.config["access"]; - self.config = profile.clone(); - self.saved = profile; - if moved { - self.reconnect_host(); - } - Some((true, Value::Null)) - } - - /// Read the profile again, after a mirror rewrote it. Returns what to say - /// when something is worth it. - pub fn take_in_mirror(&mut self) -> Option { - match self.take_stored()? { - (true, _) => Some("Took in the berth server's copy of this host".into()), - (false, _) => { - Some("The berth server's copy of this host changed. Saving sends this one".into()) - } - } - } - - /// Read the profile again after one of berth's own commands ran from the - /// screen, which may have saved what it found: the machine it created - /// gives the host its address. With unsaved changes those fields are - /// taken into the changes, which stay unsaved. - pub fn take_in_command(&mut self) -> Option { - let (taken, profile) = self.take_stored()?; - if taken { - return Some("Took in what the command saved of this host".into()); - } - let mut changed = false; - for pointer in [ - "/access/address", - "/access/port", - "/access/user", - "/access/auth", - "/target", - ] { - let kept = profile.pointer(pointer).cloned().unwrap_or(Value::Null); - if self.config.pointer(pointer) != Some(&kept) && !kept.is_null() { - set_pointer(&mut self.config, pointer, kept); - changed = true; - } - } - // What is saved now is the command's; the rest of the changes are still to save. - self.saved = profile; - if changed { - self.reconnect_host(); - } - Some(match changed { - true => { - "Took in the address the command saved; the other changes are not saved yet".into() - } - false => "The command saved this host too; saving keeps the changes made here".into(), - }) - } - - pub fn unsaved(&self) -> bool { - self.config != self.saved - } - - /// Fields shown by the current step for the chosen action. - #[cfg(test)] - pub fn fields(&self) -> Vec { - self.view().fields() - } - - fn field_rows(&self) -> Vec { - lift(self.view().field_rows()) - } - - /// What the Run tab says besides the shared rows: whether the Wi-Fi - /// password is the one this machine knows. - fn run_notes(&self) -> Vec { - if !(self.action.installer() && self.enabled(Field::Wifi)) { - return vec![]; - } - let (text, color) = match self.wifi_password_matches() { - Some(true) => ( - "✓ Wi-Fi password matches the one saved on this machine", - theme::GOOD, - ), - Some(false) => ( - "! Wi-Fi password differs from the one saved on this machine", - theme::WARN, - ), - None => ( - "· Wi-Fi login not checked: this machine has not saved that network", - theme::MUTED, - ), - }; - vec![setup::Row::info(Line::styled(text, Style::new().fg(color)))] - } - - pub fn rows(&self) -> Vec { - let heading = |text: &'static str| { - Row::info(Line::styled(text, Style::new().fg(theme::ACCENT).bold())) - }; - let mut rows = vec![]; - match self.step { - Step::Install | Step::Features | Step::Settings | Step::Run => { - let problems = self.placed_problems(); - let page = setup::Page { - methods: self.methods(), - machine: &self.machine, - problems: &problems, - notes: self.run_notes(), - }; - rows = lift(self.view().page_rows(page)); - // The drive to write to is named as this machine knows it. - for row in &mut rows { - if row.entry == Some(Entry::Field(Field::UsbDevice)) { - let device = self.text(Field::UsbDevice); - let drive = self.usb_drives.iter().find(|(_, path)| path == device); - let value = match drive { - Some((label, _)) => label.as_str(), - None if device.is_empty() => "no", - None => device, - }; - let mut line = value_line("Then write to USB drive", value, Kind::Text); - line.spans.insert(0, row.line.spans[0].clone()); - row.line = line; - } - } - } - Step::Manage => { - if let Some(line) = self.host.stats_line() { - rows.push(Row::info(Line::styled(line, Style::new().fg(theme::MUTED)))); - rows.push(Row::info("")); - } - // berthd and box come with berth, so a newer berth has newer ones to give. - if let State::Ready(version) = &self.host.state - && version != berth_api::VERSION - && self.served().is_none() - { - rows.push(Row::info(Line::styled( - format!( - "The host's tools are {version}, this berth is {}. Apply this configuration updates them.", - berth_api::VERSION - ), - Style::new().fg(theme::WARN), - ))); - rows.push(Row::info("")); - } - rows.push(heading("Connection")); - for line in berth_tui::host::type_lines(&self.name(), &self.host) { - rows.push(Row::info(Line::styled( - format!(" {line}"), - Style::new().fg(theme::MUTED), - ))); - } - if let Some(server) = self.served() { - rows.push(Row::info(format!( - " {} · through the berth server at {server}", - self.text(Field::SshHost) - ))); - } - if !self.locked() { - rows.extend(self.field_rows()); - } - for problem in self.problems() { - rows.push(Row::info(Line::styled( - format!("✗ {problem}"), - Style::new().fg(theme::BAD), - ))); - } - let mut groups = self.overview_groups(); - // Set-up and applying it are for whoever may set the server up, - // in the group berth's own actions of set-up are in. - if !self.locked() { - let mut setup = vec![Row::entry( - " ▸ Change what is installed, accounts or install method ›", - Entry::Setup, - )]; - // A host without its controller offers Apply above already; - // only a workstation is applied. - if !matches!(self.host.state, State::Missing | State::Old(_)) - && self.host.host_type == host_type::HostType::Workstation - { - setup.push(Row::entry( - " ▸ Apply this configuration", - Entry::Offer("apply"), - )); - } - match groups.iter_mut().find(|(title, _)| title == "Set-Up") { - Some((_, rows)) => { - setup.append(rows); - *rows = setup; - } - None => groups.push(("Set-Up".to_owned(), setup)), - } - } - for (title, group) in groups { - rows.push(Row::info("")); - rows.push(Row::info(Line::styled( - title, - Style::new().fg(theme::ACCENT).bold(), - ))); - rows.extend(group); - } - } - } - rows - } - - /// The groups of the overview under the connection, as the host lists its - /// actions: each in the group it names, with the terminal among the first and - /// the host's sessions after them. A host that cannot be asked says why. - fn overview_groups(&self) -> Vec<(String, Vec)> { - let note = |text: String, colour| { - Row::info(Line::styled(format!(" {text}"), Style::new().fg(colour))) - }; - let fixed = |name: &'static str| { - let label = OFFERS - .iter() - .find(|(offer, ..)| *offer == name) - .map_or(name, |(_, label, _)| label); - Row::entry(format!(" ▸ {label}"), Entry::Offer(name)) - }; - // A host that cannot be worked with yet still has berth's own - // actions, such as first contact and installing the controller. - let host = |rows| { - let mut groups = vec![("Host".to_owned(), rows)]; - groups.extend(self.own_groups()); - groups - }; - match &self.host.state { - State::Ready(_) => {} - State::Idle if !self.problems().is_empty() => return vec![], - State::Idle | State::Connecting => { - return host(vec![note( - "Asking the host what it can do…".into(), - theme::MUTED, - )]); - } - State::Password => { - return host(vec![ - note( - "The SSH user's sudo password is needed to reach the host.".into(), - theme::WARN, - ), - fixed("connect"), - ]); - } - // Below a workstation the controller is installed alone. - State::Missing if self.host.host_type != host_type::HostType::Workstation => { - let rows = vec![ - note("berth's controller is not on this host. Install it for sessions, actions and files here; berth reaches the host over SSH meanwhile.".into(), theme::MUTED), - fixed("ssh"), - ]; - return host(rows); - } - State::Missing => { - return host(vec![ - note("berth's controller is not on this host yet. Applying the configuration installs it.".into(), theme::WARN), - fixed("apply"), - ]); - } - State::Old(version) => { - let raise = match self.host.host_type { - host_type::HostType::Workstation => "apply", - _ => "install-controller", - }; - let mut rows = vec![note( - format!( - "The host's tools ({version}) are older than this berth needs. {} brings them up to date.", - OFFERS - .iter() - .find(|(name, ..)| *name == raise) - .map_or(raise, |(_, label, _)| label) - ), - theme::WARN, - )]; - // berth's own actions list the install already. - if !self.host.own.iter().any(|action| action.name == raise) { - rows.push(fixed(raise)); - } - return host(rows); - } - State::Unreachable(message) => { - // The error whole, as the lines of the list are not wrapped. - let who = match self.served() { - Some(server) => { - format!("The berth server at {server} could not reach the host:") - } - None => "This machine could not reach the host:".to_owned(), - }; - let mut rows = vec![note(who, theme::WARN)]; - for line in message - .lines() - .flat_map(|line| berth_tui::screen::wrap(line, 70)) - { - rows.push(note(format!("✗ {line}"), theme::BAD)); - } - rows.push(fixed("connect")); - // A host that the server keeps is changed by whoever sets the server up. - if !self.locked() { - rows.push(fixed("address")); - } - rows.push(fixed("ssh")); - return host(rows); - } - } - let user = match self.as_agent { - true => self.agent_label().to_owned(), - false => self.operator_label(), - }; - let raise = match self.host.host_type { - host_type::HostType::Workstation => "apply", - _ => "install-controller", - }; - let behind = berth_tui::host::behind_note(&self.host).map(|text| { - ( - "Configuration".to_owned(), - vec![note(text, theme::WARN), fixed(raise)], - ) - }); - behind - .into_iter() - .chain( - berth_tui::host::groups(&self.host, &user) - .into_iter() - .map(|(title, rows)| { - let rows = rows - .into_iter() - .map(|(line, pick)| { - let entry = match pick { - Pick::Action(index) => Entry::HostAction(index), - Pick::Terminal => Entry::Offer("terminal"), - Pick::Session(index) => Entry::HostSession(index), - }; - Row::entry(line, entry) - }) - .collect(); - (title, rows) - }), - ) - .collect() - } - - /// berth's own actions on the host in their groups, without its controller's. - fn own_groups(&self) -> Vec<(String, Vec)> { - berth_tui::page::groups(&self.host.actions(), |index| index) - .into_iter() - .map(|group| { - let rows: Vec = group - .rows - .into_iter() - .filter(|(_, index)| self.host.is_own(*index)) - .map(|(line, index)| Row::entry(line, Entry::HostAction(index))) - .collect(); - (group.title, rows) - }) - .filter(|(_, rows)| !rows.is_empty()) - .collect() - } - - fn agent_label(&self) -> &str { - match self.text(Field::AgentUser) { - "" => "agent", - user => user, - } - } - - fn operator_label(&self) -> String { - match self.text(Field::SshUser) { - "" => "the SSH user".into(), - user => format!("{user}, the SSH user"), - } - } - - pub fn entries(&self) -> Vec { - self.rows() - .into_iter() - .filter_map(|row| row.entry) - .collect() - } - - pub fn selected_entry(&self) -> Option { - self.entries() - .get(self.list.selected().unwrap_or(0)) - .copied() - } - - pub fn selected_field(&self) -> Option { - match self.selected_entry() { - Some(Entry::Field(field)) => Some(field), - _ => None, - } - } - - /// The information box for the selected row, as Markdown. An action that has - /// steps from plugins lists what each of them adds. - pub fn help(&self) -> String { - match self.selected_entry() { - Some(Entry::Feature(index)) => self.catalogue[index].help.clone(), - Some(Entry::HostAction(index)) => berth_tui::host::action_help(&self.host, index), - Some(Entry::HostSession(index)) => berth_tui::host::session_help(&self.host, index), - Some(Entry::Machine(pick)) => self.machine.help(pick), - _ => self.entry_help().to_owned(), - } - } - - fn entry_help(&self) -> &'static str { - match self.selected_entry() { - Some(Entry::Action(action)) => action.help(), - Some(Entry::Field(field)) => field.spec().help, - Some(Entry::Offer(name)) => OFFERS - .iter() - .find(|(offer, ..)| *offer == name) - .map_or("", |(.., help)| help), - Some(Entry::Group(_)) => setup::GROUP_HELP, - Some(Entry::Feature(_)) => "", - Some(Entry::HostAction(_) | Entry::HostSession(_) | Entry::Machine(_)) => "", - Some(Entry::HostRegistry(_)) => { - "Give this host the login of this registry. Its npm repositories become the agent's npm registry with the login in ~/.npmrc, and its Docker addresses get the login in ~/.docker/config.json. Registries are set up on the Registries tab of the home screen." - } - Some(Entry::Key(account, Some(_))) => match account { - setup::Account::Operator => Field::OperatorKey.spec().help, - setup::Account::Agent => Field::AgentKey.spec().help, - }, - Some(Entry::Key(_, None)) => setup::ADD_KEY_HELP, - Some(Entry::HostSecret(_)) => { - "How this host gets the secret. Enter, then type a variable name such as GH_TOKEN to put it in the agent's environment, or a path such as ~/.config/app/token to write it to a file. Empty, or x, means the host does not get it. A secret given as GH_TOKEN also logs git in to GitHub through gh. Values are set on the Secrets tab of the home screen." - } - Some(Entry::Setup) => { - "Opens the set-up tabs of this host: how to install it, what is installed, its settings, and running it. Esc comes back here. Changes reach a running host with Apply this configuration." - } - Some(Entry::Save) => "Saves the profile, as Ctrl+S does, without running anything.", - Some(Entry::Run) | None => self.action.help(), - } - } - - /// The selected row takes a file path, so Browse applies. - pub fn path_selected(&self) -> bool { - match self.selected_entry() { - Some(Entry::Field(field)) => field.spec().kind == Kind::Path, - _ => false, - } - } - - /// The `berth serve` this host belongs to, when it is not a host of this machine. - pub fn served(&self) -> Option<&str> { - self.config["builder"]["served"].as_str() - } - - /// A server's host that this berth may use and not set up. - pub fn locked(&self) -> bool { - self.config["builder"]["served_only"] == true - } - - /// The server a host is set up on through this berth. - fn server(&self) -> Option { - self.served()?; - (!self.locked()) - .then(|| self.host_profile().served(&self.paths)) - .flatten() - } - - fn name(&self) -> String { - self.host_profile().name - } - - /// The ways to install this host: for a server's host those the server - /// does itself. - pub fn methods(&self) -> &'static [Action] { - match self.served() { - Some(_) => &[ - Action::Machine, - Action::CloudSeed, - Action::Ssh, - Action::Reach, - ], - None => &Action::METHODS, - } - } - - pub fn set_step(&mut self, step: Step) { - if let Some(server) = self.served() - && self.locked() - && step != Step::Manage - { - self.status = format!( - "This host is set up on the berth server at {server}, by whoever has the role admin there" - ); - return; - } - self.step = step; - // A berth server offers fewer ways to install than the one a new host starts with. - if step == Step::Install - && self.action != Action::Manage - && !self.methods().contains(&self.action) - { - self.action = self.methods()[0]; - setup::fit_target(&mut self.config, self.action); - } - // The Manage tab acts on the running host; the others on the install method. - if step == Step::Manage { - if self.action != Action::Manage { - self.method = self.action; - } - self.action = Action::Manage; - } else if self.action == Action::Manage { - self.action = self.method; - } - // A profile saved with another kind opens as the machine's. - if step != Step::Manage && self.action == Action::Machine { - setup::fit_target(&mut self.config, self.action); - } - // A host with an address opens on its actions rather than the address. - let offered = |entry: &Entry| matches!(entry, Entry::Offer(_) | Entry::HostAction(_)); - let first = match self.text(Field::SshHost).is_empty() { - false if step == Step::Manage => self.entries().iter().position(offered), - _ => None, - }; - if step == Step::Settings { - self.load_access(); - } - if step == Step::Install { - self.load_machine(); - } - self.list = ListState::default().with_selected(Some(first.unwrap_or(0))); - self.status.clear(); - self.suggestion_focus = false; - } - - /// Open the first tab of the set-up flow, for a host that is not on its - /// overview, and keep what was said on opening it. - pub fn start(&mut self) { - if self.step == Step::Manage || self.locked() { - return; - } - let said = std::mem::take(&mut self.status); - self.set_step(Step::Install); - self.status = said; - } - - pub fn move_selection(&mut self, up: bool) { - let index = self.list.selected().unwrap_or(0); - let last = self.entries().len().saturating_sub(1); - self.list.select(Some(if up { - index.saturating_sub(1) - } else { - (index + 1).min(last) - })); - } - - pub fn open_picker(&mut self) { - if !self.path_selected() { - return; - } - let entry = self.selected_entry(); - if self.editing.is_none() { - match entry { - Some(Entry::Field(field)) => self.activate(field), - _ => self.editing = Some(Input::default()), - } - } - let value = self.editing.as_ref().map_or("", |input| input.value()); - let start = match value.is_empty() { - false => value.to_owned(), - true => ".".into(), - }; - match Picker::new(&start) { - Ok(picker) => self.picker = Some(picker), - Err(error) => self.status = error.to_string(), - } - } - - /// Generate a hostname, or a password whose hash goes into the selected field. - pub fn generate(&mut self) -> Result<()> { - let Some(field) = self.selected_field() else { - return Ok(()); - }; - if field == Field::Iso { - let mut command = Command::new("python3"); - command - .args([layout::BUILDER, "fetch-iso", "--dir"]) - .arg(&self.iso_dir); - let stage = Stage { - title: "Download Ubuntu Server ISO".into(), - command, - source: None, - input: None, - }; - let next = "The ISO path and checksum are filled in."; - self.job = Some(Job::start(vec![stage], next, vec![])?); - self.fetching_iso = true; - } else if field == Field::Hostname { - self.set(field, json!(credentials::hostname()?)); - } else if field == Field::TailscaleKey { - let host = self.text(Field::Hostname).to_owned(); - // A server's host gets its key from the server's control server. - let (key, note) = match self.host_profile().served(&self.paths) { - Some(server) => { - let made = server.call( - "setup.generate", - json!({}), - Some(json!({"what": "tailscale_key", "host": self.name()})), - )?; - let text = |key: &str| made[key].as_str().unwrap_or("").to_owned(); - (text("value"), text("note")) - } - None => berth_core::tailnet::generate(&self.paths, &self.config, &host)?, - }; - self.set(field, json!(key)); - self.status = note; - } else if field == Field::IsoSha { - self.hash_iso()?; - } else if field.is_password_hash() { - let user = self.text(if field == Field::OperatorHash { - Field::OperatorUser - } else { - Field::AgentUser - }); - let user = if user.is_empty() { "account" } else { user }.to_owned(); - // A server's host has its password made and kept on the server, - // which the next mirror would not keep here. - if let Some(server) = self.host_profile().served(&self.paths) { - let made = server.call( - "setup.generate", - json!({}), - Some(json!({"what": "password", "host": self.name(), "user": user})), - )?; - let hash = made["value"].as_str().unwrap_or(""); - if !hash.starts_with("$6$") { - return Err("The berth server made no password".into()); - } - self.set(field, json!(hash)); - self.status = format!( - "Generated password kept on the berth server at {}; see it with: berth credentials {}", - server.url, - self.name() - ); - return Ok(()); - } - let password = credentials::password()?; - let hash = credentials::hash(&password)?; - credentials::save(&self.paths, &self.place, &user, &password)?; - self.set(field, json!(hash)); - self.status = format!( - "Generated password kept in berth's store; see it with: berth credentials {}", - self.place.argument() - ); - } - Ok(()) - } - - pub fn refresh_discovery(&mut self) { - if let Some(home) = std::env::var_os("HOME") { - let ssh = PathBuf::from(home).join(".ssh"); - (self.public_keys, self.private_keys) = discovery::keys(&ssh); - self.ssh_hosts = discovery::hosts(&ssh.join("config")); - } - self.wifi_networks = discovery::wifi_networks(self.privileged); - self.usb_drives = discovery::usb_drives(); - self.tailnet_hosts = discovery::tailnet_hosts(); - for entry in discovery::agent_keys() { - let same_key = |(_, key): &(String, String)| { - key.split_whitespace() - .take(2) - .eq(entry.1.split_whitespace().take(2)) - }; - if !self.public_keys.iter().any(same_key) { - self.public_keys.push(entry); - } - } - } - - pub fn update_suggestions(&mut self) { - let own = |values: &[&str]| -> Choices { - values - .iter() - .map(|value| (value.to_string(), value.to_string())) - .collect() - }; - let choices = match self.selected_entry() { - Some(Entry::Key(..)) => self.public_keys.clone(), - // The provisioner is a choice like a field's, of what there is. - Some(Entry::Machine(machine::Pick::Provisioner)) => self.machine.choices(), - Some(Entry::Machine(machine::Pick::Argument(index))) => { - self.machine.argument_choices(index) - } - Some(Entry::Field(field)) => match (field, field.spec().kind) { - (Field::Login, _) => self - .login_choices() - .into_iter() - .map(|choice| (choice.clone(), choice)) - .collect(), - (_, Kind::Choice(values)) => own(values), - (Field::SshHost, _) => self - .tailnet_hosts - .iter() - .chain(&self.ssh_hosts) - .cloned() - .collect(), - (Field::WifiSsid, _) => self - .wifi_networks - .iter() - .map(|(ssid, _)| (ssid.clone(), ssid.clone())) - .collect(), - _ => vec![], - }, - _ => vec![], - }; - if self.suggestions != choices { - self.suggestions = choices; - self.suggestion_list = ListState::default().with_selected(Some(0)); - self.suggestion_focus = false; - } - // A choice's list starts at what is chosen, and follows it as it changes. - if !self.suggestion_focus - && let Some(current) = self.current_choice() - && let Some(at) = self - .suggestions - .iter() - .position(|(_, value)| *value == current) - { - self.suggestion_list.select(Some(at)); - } - } - - /// What is chosen on the selected row, when it is a choice. - fn current_choice(&self) -> Option { - match self.selected_entry()? { - Entry::Field(field) if matches!(field.spec().kind, Kind::Choice(_)) => { - Some(self.text(field).to_owned()) - } - Entry::Machine(machine::Pick::Provisioner) => self.machine.chosen.clone(), - Entry::Machine(machine::Pick::Argument(index)) => { - self.machine.value(index).map(str::to_owned) - } - _ => None, - } - } - - pub fn select_suggestion(&mut self) { - if let Some((_, value)) = self - .suggestions - .get(self.suggestion_list.selected().unwrap_or(0)) - { - self.editing = Some(Input::new(value.clone())); - self.password_entry = false; - self.accept_edit(); - } - self.suggestion_focus = false; - } - - pub fn cancel_edit(&mut self) { - self.editing = None; - self.password_entry = false; - } - - pub fn accept_edit(&mut self) { - let Some(input) = self.editing.take() else { - return; - }; - let hashing = std::mem::take(&mut self.password_entry); - match self.selected_entry() { - Some(Entry::Field(field)) if hashing => match credentials::hash(input.value()) { - Ok(hash) => self.set(field, json!(hash)), - Err(error) => self.status = error.to_string(), - }, - Some(Entry::Field(field)) => self.commit(field, input.value()), - Some(Entry::HostSecret(index)) => self.set_host_secret(index, input.value()), - Some(Entry::Machine(pick)) => { - let name = self.name(); - let next = self.machine.typed(pick, input.value(), &name); - self.follow(next); - } - Some(Entry::Key(account, index)) => { - // Nothing typed changes nothing: x is what removes a key. - if !input.value().trim().is_empty() - && let Err(why) = - setup::set_key(&mut self.config, account, index, input.value()) - { - self.status = why; - } - } - _ => {} - } - } - - /// Toggle or cycle the field, or open the editor for free text. - pub fn activate(&mut self, field: Field) { - if field == Field::ReleaseStore { - // Cycle through entering an address and the configured stores. - let stores = self - .access - .as_ref() - .map(|store| store.release_stores()) - .unwrap_or_default(); - let next = match stores.iter().position(|store| store == self.text(field)) { - None if self.text(field).is_empty() => stores.first(), - None => None, - Some(index) => stores.get(index + 1), - }; - if stores.is_empty() { - self.status = "No file server or raw repository yet. Add one on the Registries tab of the home screen.".into(); - } - let value = next.cloned().unwrap_or_default(); - self.set(field, json!(value)); - return; - } - if field == Field::UsbDevice { - // Cycle through "no" and the drives connected right now. - self.usb_drives = discovery::usb_drives(); - let current = self - .usb_drives - .iter() - .position(|(_, path)| path == self.text(field)); - let next = match current { - None if self.text(field).is_empty() => self.usb_drives.first(), - None => None, - Some(index) => self.usb_drives.get(index + 1), - }; - let device = next.map_or(String::new(), |(_, path)| path.clone()); - self.status = match device.is_empty() { - true if self.usb_drives.is_empty() => { - "No usable USB drive. Replug one that was ejected.".into() - } - _ => String::new(), - }; - self.set(field, json!(device)); - return; - } - if field == Field::Login { - let choices = self.login_choices(); - let current = choices.iter().position(|choice| choice == self.text(field)); - let next = current.map_or(0, |index| (index + 1) % choices.len()); - self.set(field, json!(choices[next])); - return; - } - match field.spec().kind { - Kind::Toggle => self.set_toggle(field, !self.enabled(field)), - Kind::Choice(choices) => { - let current = choices - .iter() - .position(|choice| *choice == self.text(field)); - let next = current.map_or(0, |index| (index + 1) % choices.len()); - self.set(field, json!(choices[next])); - } - _ => self.editing = Some(Input::new(self.text(field).to_owned())), - } - } - - pub fn commit(&mut self, field: Field, value: &str) { - let spec = field.spec(); - let value = if spec.kind == Kind::Secret { - value - } else { - value.trim() - }; - if field == Field::Login { - if !self.login_choices().iter().any(|choice| choice == value) { - self.status = format!("Choose one of: {}", self.login_choices().join(", ")); - return; - } - } else if let Kind::Choice(choices) = spec.kind - && !choices.contains(&value) - { - self.status = format!("Choose one of: {}", choices.join(", ")); - return; - } - if let Some(name) = spec.pointer.strip_prefix("/ansible_vars/") - && value.is_empty() - { - // An empty override would replace the role default with nothing. - if let Some(vars) = self.config["ansible_vars"].as_object_mut() { - vars.remove(name); - } - return; - } - self.set(field, json!(value)); - if spec.pointer.starts_with("/wifi/") - && self.config["wifi"] - .as_object() - .is_some_and(|wifi| wifi.values().all(|v| v.as_str() == Some(""))) - { - self.config["wifi"] = Value::Null; - } - if field == Field::SshHost && !value.is_empty() { - self.fill_from_ssh_config(value); - } - if field == Field::Type { - self.type_chosen = true; - } - // An existing host over SSH is asked what it is, as berth host add does. - if matches!( - field, - Field::SshHost | Field::SshUser | Field::SshPort | Field::Login - ) && self.action == Action::Ssh - && self.step != Step::Manage - && !self.text(Field::SshHost).is_empty() - { - self.ask_found_type(); - } - if field == Field::WifiSsid - && let Some(password) = self.saved_wifi_password().map(str::to_owned) - { - self.set(Field::WifiPassword, json!(password)); - self.status = "Wi-Fi password filled from this machine".into(); - } - if field == Field::WifiPassword { - match self.wifi_password_matches() { - Some(true) => { - self.status = "Matches the Wi-Fi password saved on this machine".into() - } - Some(false) => { - self.status = "Differs from the Wi-Fi password saved on this machine".into() - } - None => {} - } - } - if field == Field::Iso - && !value.is_empty() - && let Err(error) = self.hash_iso() - { - self.status = error.to_string(); - } - } - - /// Ask the host's controller, in the background, what the host is. - fn ask_found_type(&mut self) { - let (paths, host) = (self.paths.clone(), self.host_profile()); - let (sender, receiver) = mpsc::channel(); - std::thread::spawn(move || { - let _ = sender.send(host_type::observe(&paths, &host, None)); - }); - self.found_type = Some(receiver); - } - - /// Take in what the host said it is, when it has. Called between events. - pub fn watch_found_type(&mut self) { - let Some(answer) = &self.found_type else { - return; - }; - if let Ok(found) = answer.try_recv() { - self.found_type = None; - self.offer_type(found); - } - } - - /// Offer the type the host was found to be: it is taken unless a - /// type was chosen on the Type row, which is only told of it. - pub fn offer_type(&mut self, found: Option) { - let current = host_type::of(&self.config); - let Some(found) = found.filter(|found| *found != current) else { - return; - }; - let name = self.name(); - if self.type_chosen { - self.status = format!( - "{name} answers as a host of the type {found}; its Type here says {current}" - ); - return; - } - berth_api::profile::set_host_type(&mut self.config, found); - self.status = - format!("{name} answers as a host of the type {found}, so its Type is {found} now"); - } - - /// Record the checksum of the chosen ISO so the build can detect a changed file. - fn hash_iso(&mut self) -> Result<()> { - let path = expand_path(self.text(Field::Iso)); - if !path.is_file() { - return Err("Choose the source ISO first".into()); - } - let digest = credentials::sha256(&path)?; - self.set(Field::IsoSha, json!(digest)); - self.status = "ISO SHA256 computed · compare with Ubuntu's SHA256SUMS".into(); - Ok(()) - } - - /// Get administrator rights for reading saved Wi-Fi passwords, asking for the - /// password in a dialog unless sudo needs none. - pub fn request_unlock(&mut self, reason: &'static str) { - self.unlock_reason = reason; - if self.privileged || credentials::sudo_unlock(None) { - self.unlocked(); - } else { - self.unlock_failed = false; - self.unlock = Some(Input::default()); - } - } - - pub fn submit_unlock(&mut self) { - let Some(input) = self.unlock.take() else { - return; - }; - if std::mem::take(&mut self.unlock_remote) { - self.host.password = Some(input.value().to_owned()); - self.connect_host(); - return; - } - if credentials::sudo_unlock(Some(input.value())) { - self.unlocked(); - if self.pending_run { - self.run(true); - } - } else { - self.unlock_failed = true; - self.unlock = Some(Input::default()); - } - } - - fn unlocked(&mut self) { - self.privileged = true; - self.wifi_networks = discovery::wifi_networks(true); - let known = self - .wifi_networks - .iter() - .filter(|(_, password)| !password.is_empty()) - .count(); - self.status = format!("Unlocked {known} saved Wi-Fi passwords"); - if self.text(Field::WifiPassword).is_empty() - && let Some(password) = self.saved_wifi_password().map(str::to_owned) - { - self.set(Field::WifiPassword, json!(password)); - self.status = "Wi-Fi password filled from this machine".into(); - } - } - - /// Password this machine has saved for the profile's SSID, if it knows the network. - fn saved_wifi_password(&self) -> Option<&str> { - let ssid = self.text(Field::WifiSsid); - self.wifi_networks - .iter() - .find(|(known, password)| known == ssid && !password.is_empty()) - .map(|(_, password)| password.as_str()) - } - - /// Whether the profile's Wi-Fi password is the one this machine uses for that - /// network. `None` when this machine has nothing to compare against. - pub fn wifi_password_matches(&self) -> Option { - self.saved_wifi_password() - .map(|saved| saved == self.text(Field::WifiPassword)) - } - - /// Fill blank connection fields with what OpenSSH would use for this host. - fn fill_from_ssh_config(&mut self, host: &str) { - let Ok(output) = Command::new("ssh").args(["-G", "--", host]).output() else { - return; - }; - for line in String::from_utf8_lossy(&output.stdout).lines() { - let Some((name, value)) = line.split_once(' ') else { - continue; - }; - let field = match name { - "user" => Field::SshUser, - "port" => Field::SshPort, - _ => continue, - }; - if self.text(field).is_empty() { - self.set(field, json!(value)); - } - } - } - - /// Fill blank fields from local SSH keys and DEVBOX_* environment variables. - pub fn detect(&mut self) { - self.refresh_discovery(); - let only_key = match self.public_keys.as_slice() { - [(_, key)] => Some(key.clone()), - _ => None, - }; - let env = |name: &str| std::env::var(name).ok(); - let mut filled = Vec::new(); - for (label, field, detected) in [ - ("hostname", Field::Hostname, env("DEVBOX_HOSTNAME")), - ( - "disk serial", - Field::DiskSerial, - env("DEVBOX_TARGET_DISK_SERIAL"), - ), - ("release URL", Field::ReleaseUrl, env("DEVBOX_RELEASE_URL")), - ("ISO path", Field::Iso, env("DEVBOX_ISO")), - ("ISO checksum", Field::IsoSha, env("DEVBOX_ISO_SHA256")), - ("inventory", Field::Inventory, env("DEVBOX_INVENTORY")), - ] { - let Some(value) = detected - .map(|value| value.trim().to_owned()) - .filter(|value| !value.is_empty()) - else { - continue; - }; - if self.text(field).is_empty() { - self.set(field, json!(value)); - filled.push(label); - } - } - // Without this berth's own key the operator needs one of the user's. - if let Some(key) = only_key - && self.view().keys(setup::Account::Operator).is_empty() - && self.own_public.is_empty() - && setup::set_key(&mut self.config, setup::Account::Operator, None, &key).is_ok() - { - filled.push("public key"); - } - self.status = if filled.is_empty() { - format!( - "Found {} public keys, {} private keys and {} SSH hosts. Select a field to choose.", - self.public_keys.len(), - self.private_keys.len(), - self.ssh_hosts.len() - ) - } else { - format!("Review detected values: {}", filled.join(", ")) - }; - } - - /// Reasons the chosen action would fail, checked before leaving the UI. - pub fn problems(&self) -> Vec { - self.placed_problems() - .into_iter() - .map(|problem| problem.text) - .collect() - } - - /// [`App::problems`], each on the tab of what it is about. - pub fn placed_problems(&self) -> Vec { - use Field::*; - use setup::Problem; - let action = self.action; - if action == Action::Manage { - let access = self.host_profile().access(); - return berth_core::keys::check(&access.address, &access.port) - .err() - .map(|error| Problem::new(Step::Manage, error.to_string())) - .into_iter() - .collect(); - } - // A host below a workstation needs only to be reached. - if action == Action::Ssh && host_type::of(&self.config) != host_type::HostType::Workstation - { - let access = self.host_profile().access(); - return berth_core::keys::check(&access.address, &access.port) - .err() - .map(|error| Problem::new(Step::Install, error.to_string())) - .into_iter() - .collect(); - } - let mut problems = self.view().problems_with(&self.machine); - let mut check = |ok: bool, step: Step, message: &str| { - if !ok { - problems.push(Problem::new(step, message)); - } - }; - match action { - Action::Iso => { - check( - expand_path(self.text(Iso)).is_file(), - Step::Run, - "Source ISO file does not exist", - ); - let usb = self.text(UsbDevice); - check( - usb.is_empty() || self.usb_drives.iter().any(|(_, path)| path == usb), - Step::Run, - "The USB drive to write to is not connected", - ); - let sha = self.text(IsoSha); - check( - sha.is_empty() - || sha.len() == 64 - && sha - .chars() - .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)), - Step::Run, - "ISO SHA256 must be 64 lowercase hex characters", - ); - } - Action::Apply => { - let inventory = self.text(Inventory); - check( - inventory.is_empty() || expand_path(inventory).exists(), - Step::Run, - "Ansible inventory file does not exist", - ); - } - Action::Ssh => { - let access = self.host_profile().access(); - if let Err(error) = berth_core::keys::check(&access.address, &access.port) { - problems.push(Problem::new(Step::Install, error.to_string())); - } - } - _ => {} - } - problems - } - - /// The ways this host can be logged in to, with the keys of the ring. - pub fn login_choices(&self) -> Vec { - setup::login_choices( - &self.ring_keys, - self.config["access"]["auth"].as_str().unwrap_or(""), - self.served().is_some(), - ) - } - - /// The public keys a host set up from here takes for berth: this - /// berth's, with the one replacing it while it rotates, or the server's. - fn own_keys(&self) -> Vec { - match self.served() { - Some(_) => vec![self.own_public.clone()] - .into_iter() - .filter(|key| !key.is_empty()) - .collect(), - None => berth_core::keys::operator_keys(&self.paths, &self.config).unwrap_or_default(), - } - } - - /// This host as its profile describes it, for reaching and applying it. - pub fn host_profile(&self) -> Host { - Host { - name: self.place.title(), - place: self.place.clone(), - config: self.config.clone(), - } - } - - /// Start talking to the host's controller. A host whose sudo asks for a - /// password gets the dialog first, once. - pub fn connect_host(&mut self) { - let host = self.host_profile(); - self.host.host_type = host_type::of(&self.config); - self.ask_own_actions(); - let own_link = host.access().link.is_some() || host.served(&self.paths).is_some(); - if host.asks_password() && !own_link && self.host.password.is_none() { - self.host.state = State::Password; - if !std::mem::replace(&mut self.password_asked, true) { - self.ask_host_password(false); - } - return; - } - let asked = std::mem::take(&mut self.force_login); - match host.link(&self.paths, self.host.password.as_deref()) { - // Opening the overview is no reason to repeat a login the host - // refused a moment ago; Try again is. - Ok(spec) - if !asked - && let Some(refused) = - spec.guard.as_ref().and_then(|guard| guard.refused()) => - { - self.host.state = State::Unreachable(refused); - } - Ok(spec) => { - crate::remote::connect_with(&mut self.host, spec, compare(&self.paths, &host)); - } - Err(error) => self.host.state = State::Unreachable(error.to_string()), - } - } - - /// berth's own actions on the host: those of this berth, or what the - /// server lists, asked for in the background, as the server asks the host. - fn ask_own_actions(&mut self) { - let host = self.host_profile(); - let Some(server) = host.served(&self.paths) else { - self.host.own = - host_type::local_actions(&host.name, self.host.host_type, self.host.seen); - return; - }; - let (sender, receiver) = mpsc::channel(); - let name = host.name.clone(); - std::thread::spawn(move || { - let listed = server - .call("hosts.actions", json!({"name": name}), None) - .ok() - .and_then(|listed| serde_json::from_value::>(listed).ok()); - let _ = sender.send(listed.unwrap_or_default()); - }); - self.own_answers = Some(receiver); - } - - /// Of what a server lists, berth's own that the overview has no row of: - /// applying and the seed are on the set-up, sending secrets is an action. - fn take_own_actions(&mut self) { - let Some(answers) = &self.own_answers else { - return; - }; - if let Ok(listed) = answers.try_recv() { - self.own_answers = None; - // A secret is asked for by the command that runs it, not typed here. - self.host.own = listed - .into_iter() - .filter(|action| action.runs == berth_api::Runs::Berth) - .filter(|action| !["apply", "seed"].contains(&action.name.as_str())) - .map(|mut action| { - action.arguments.retain(|argument| !argument.secret); - action - }) - .collect(); - } - } - - fn ask_host_password(&mut self, failed: bool) { - self.unlock_remote = true; - self.unlock_failed = failed; - self.unlock_reason = "Your sudo password on the host, to reach its controller."; - self.unlock = Some(Input::default()); - } - - /// Go to the SSH address of the host to change it. Saving it tries to - /// reach the host again. - pub fn edit_address(&mut self) { - let position = |app: &App| { - app.entries() - .iter() - .position(|entry| *entry == Entry::Field(Field::SshHost)) - }; - // The overview lists the connection's fields itself; if it does not, - // the tab that has them does. - if position(self).is_none() { - self.set_step(Step::Install); - } - match position(self) { - Some(at) => { - self.list.select(Some(at)); - self.activate(Field::SshHost); - self.retry_address = self.editing.is_some(); - } - None => self.status = "This host has no SSH address to change".into(), - } - } - - /// Connect again from nothing, asking for the password again if needed. - pub fn reconnect_host(&mut self) { - self.password_asked = false; - self.force_login = true; - self.host.disconnect(); - } - - /// Keep the overview in step with the host: connect when there is an - /// address, take in what it said. Called between events. - pub fn watch_host(&mut self) { - if self.step != Step::Manage { - return; - } - if self.host.state == State::Idle && self.unlock.is_none() && self.problems().is_empty() { - self.connect_host(); - } - self.take_own_actions(); - let had_password = self.host.password.is_some(); - if let Some(note) = self.host.pump() { - self.status = note; - } - // sudo did not take the password: ask again. - if had_password && self.host.password.is_none() && self.unlock.is_none() { - self.ask_host_password(true); - } - let last = self.entries().len().saturating_sub(1); - if self.list.selected().unwrap_or(0) > last { - self.list.select(Some(last)); - } - } - - /// Run an action of the host: after its question and its arguments, if it has any. - pub fn begin_action(&mut self, index: usize, confirmed: bool) { - if let Some(action) = self.host.actions().get(index) - && !action.available - { - self.status = format!("{} cannot run now: {}", action.title(), action.why); - return; - } - if let Some((index, values)) = self.host.begin_action(index, confirmed) { - self.launch_action(index, values); - } - } - - /// Take the value typed for the argument being asked and go on to the - /// next, or run the action after the last. - pub fn accept_argument(&mut self) { - match self.host.accept_argument() { - Ok(Some((index, values))) => self.launch_action(index, values), - Ok(None) => {} - Err(missing) => self.status = missing, - } - } - - fn launch_action(&mut self, index: usize, values: std::collections::BTreeMap) { - let Some(action) = self.host.actions().get(index).cloned() else { - return; - }; - if self.host.is_own(index) { - let _ = self.save(); - self.own_command = Some(own_command(&self.place.argument(), &action, &values)); - return; - } - let mut body = self.host.action_body(&action, &values); - // Secrets are built here and travel on the action's standard input. A - // server's host is given the server's own, which its action sends. - let secrets = self - .host - .host_action(&action) - .and_then(|kept| kept.input.as_deref()); - if secrets == Some("secrets") && self.served().is_none() { - let payload = self - .access() - .and_then(|store| store.host_payload(&self.config)); - match payload { - Ok(payload) => { - body["input_b64"] = json!(berth_api::b64(format!("{payload}\n").as_bytes())) - } - Err(error) => { - self.status = error.to_string(); - return; - } - } - } - let _ = self.save(); - self.status = format!("Starting {}…", action.title()); - self.host.run(&action.name, body); - } - - /// A shell on the host as one of its sessions: the agent's, or the SSH user's. - pub fn start_host_shell(&mut self) { - let (user, title) = match self.as_agent { - true => ( - "agent", - format!("{} on {}", self.agent_label(), self.text(Field::SshHost)), - ), - false => ("operator", self.ssh_target()), - }; - self.host.shell(user, &title); - self.status = "Starting a shell…".into(); - } - - pub fn save(&mut self) -> Result<()> { - self.place.save(&self.paths, &self.config)?; - // A server's host is the server's to keep. - if let Some(server) = self.server() { - server - .save_host(&self.name(), &self.config) - .map_err(|error| format!("The berth server did not take the profile: {error}"))?; - } - self.saved = self.config.clone(); - Ok(()) - } - - /// What to say once the profile is saved: the host and where it is kept, - /// or the file. - pub fn saved_note(&self) -> String { - match (&self.place, self.server()) { - (Place::Stored { name, .. }, Some(server)) => { - format!("Saved {name} on the berth server at {}", server.url) - } - (Place::Stored { name, .. }, None) => format!("Saved {name} in berth's store"), - (Place::File(path), _) => format!("Saved {}", path.display()), - } - } - - /// Where each plugin is on this machine, by id. - fn plugin_dirs(&self) -> Value { - apply::plugin_dirs(&self.plugins) - } - - /// The command for the chosen action, and the private files it reads. - fn command(&self) -> Result<(Command, Vec)> { - let action = self.action; - // A server's host is installed by the server: berth itself asks it to. - if let Some(server) = self.served() { - let verb = match action { - Action::Ssh => "apply", - Action::CloudSeed => "seed", - _ => { - return Err(format!( - "{} is done on a machine that keeps the host itself, not through the berth server at {server}", - action.label() - ) - .into()); - } - }; - let mut command = Command::new(std::env::current_exe()?); - command.arg(verb).arg(self.place.argument()); - return Ok((command, vec![])); - } - // Secrets go to private files rather than argv. They live until the command ends. - let mut extra = tempfile::NamedTempFile::new()?; - let inventory = tempfile::NamedTempFile::new()?; - // The profile a seed is rendered from, with a new enrollment key in it - // for a host that joins the tailnet automatically. - let seeded = match action { - Action::UsbSeed | Action::CloudSeed | Action::Iso => { - let saved = self - .place - .load(&self.paths)? - .ok_or("The profile is not saved")?; - let config = berth_core::tailnet::seed_profile(&self.paths, &saved, &self.name())?; - let mut config = berth_core::seed::named(config, &self.name()); - berth_core::kept_profile::for_seed(&mut config, &self.name(), &saved); - Some(berth_core::tailnet::profile_file(&config)?) - } - _ => None, - }; - let profile = seeded.as_ref().map(|file| file.path().to_owned()); - let mut command; - match action { - // Reach is only a way to choose, which sets Ssh for a host of the type ssh. - Action::Save | Action::Manage | Action::Machine | Action::Reach => { - return Err("Nothing to run".into()); - } - Action::Release => { - command = Command::new("python3"); - command.args([layout::BUILDER, "release"]); - } - Action::UsbSeed | Action::CloudSeed => { - command = Command::new("python3"); - command - .args([layout::BUILDER, "render", "--kind"]) - .arg(if action == Action::UsbSeed { - "usb" - } else { - "cloud" - }) - .arg("--config") - .args(&profile); - // A release that is not public: the seed carries the login of - // the registry named for it. - let store = self.text(Field::ReleaseStore); - let login = match self.config["release_login"].as_str() { - Some(name) => Some(name), - None if self.enabled(Field::ReleasePrivate) && !store.is_empty() => { - store.split('/').next() - } - None => None, - }; - if let (Action::CloudSeed, Some(name)) = (action, login) { - let login = self.access()?.curl_login(name)?.ok_or_else(|| { - format!("Registry {name} has no stored login for downloading the release") - })?; - command.env("BERTH_RELEASE_LOGIN", login); - } - } - Action::Iso => { - command = Command::new("python3"); - command - .args([layout::BUILDER, "iso", "--config"]) - .args(&profile) - .arg("--iso") - .arg(expand_path(self.text(Field::Iso))) - .arg("--overwrite"); - if !self.text(Field::IsoSha).is_empty() { - command.args(["--sha256", self.text(Field::IsoSha)]); - } - } - // Applying to a host over SSH is berth-core's; the password the - // overview was given saves Ansible asking for it again. - Action::Ssh => { - let prepared = apply::prepare( - &self.paths, - &self.host_profile(), - self.host.password.as_deref(), - )?; - return Ok((prepared.command, prepared.files)); - } - Action::Apply => { - command = apply::playbook(&std::env::current_dir()?); - let mut vars = - apply::ansible_vars(&self.config, &self.plugin_dirs(), &self.own_keys()); - vars["devbox_berth_profile"] = - berth_core::kept_profile::document(&self.name(), &self.config, None); - apply::add_tailnet(&mut vars, &self.paths, &self.config, &self.place)?; - serde_json::to_writer(&mut extra, &vars)?; - extra.flush()?; - command - .args([layout::PLAYBOOK, "--become", "-e"]) - .arg(format!("@{}", extra.path().display())) - .arg("-i"); - if self.text(Field::Inventory).is_empty() { - command.args(["localhost,", "-c", "local"]); - } else { - command.arg(expand_path(self.text(Field::Inventory))); - } - if self.enabled(Field::AskBecomePass) { - command.arg("--ask-become-pass"); - } - } - Action::Docker => { - command = Command::new("docker"); - command.args(["compose", "-f", "container/compose.yml", "build"]); - command.env("OPERATOR_USER", self.text(Field::OperatorUser)); - command.env("AGENT_USER", self.text(Field::AgentUser)); - for (env, field) in [ - ("INSTALL_PLAYWRIGHT", Field::Playwright), - ("INSTALL_WEB_TOOLS", Field::ToolsWeb), - ("INSTALL_NATIVE_TOOLS", Field::ToolsNative), - ("INSTALL_JVM_TOOLS", Field::ToolsJvm), - ("INSTALL_DOTNET_TOOLS", Field::ToolsDotnet), - ("INSTALL_SCRIPTING_TOOLS", Field::ToolsScripting), - ("INSTALL_SCIENTIFIC_TOOLS", Field::ToolsScientific), - ("INSTALL_CHROME_TOOLS", Field::ToolsChrome), - ("SOFTWARE_RENDERING", Field::SoftwareRendering), - ] { - command.env(env, self.enabled(field).to_string()); - } - command.env( - "PLUGIN_FEATURES", - json!(setup::chosen_features(&self.config)).to_string(), - ); - } - } - command.env("DEVBOX_BUILD_DIR", &self.build_dir); - // The release archive packs the user's plugins next to the source's. - command.env("BERTH_PLUGINS", self.plugin_dirs().to_string()); - command.env("BERTH_SSH_PUBLIC_KEY", self.own_keys().join("\n")); - let mut files = vec![extra, inventory]; - files.extend(seeded); - Ok((command, files)) - } - - fn next_hint(&self) -> &'static str { - match self.action { - Action::UsbSeed => { - "Next: build the ISO from this seed with the Build unattended ISO action." - } - Action::Iso => "Booting the installer erases the selected disk.", - Action::CloudSeed => { - "Next: upload the devbox-release.tar.gz shown above unchanged to the release URL, then pass the user-data file when creating the server." - } - Action::Docker => { - "Next: docker compose -f container/compose.yml up -d in the source directory, then open http://127.0.0.1:16080/vnc.html" - } - Action::Apply | Action::Ssh => { - "Next: log in as the agent and run `agent-env devbox-smoke`, then sign in to the coding clients." - } - _ => "", - } - } - - /// Actions that prompt for passwords, so they run in the normal terminal - /// after the UI has closed. Everything else runs inside the UI. - pub fn leaves_ui(&self) -> bool { - matches!(self.action, Action::Save | Action::Apply | Action::Ssh) - } - - /// Save the profile and run the chosen action in the normal terminal. - pub fn execute(&mut self) -> Result<()> { - if let Some(words) = self.own_command.take() { - return self.run_own(&words); - } - let tab_action = self.action; - if let Some(action) = self.terminal_action.take() { - self.action = action; - } - let outcome = self.execute_action(); - self.action = tab_action; - outcome - } - - /// For a cloud seed with a store chosen: upload the release there and take - /// its address, so the seed points at what was just published. - fn publish_release(&mut self) -> Result<()> { - let store = self.text(Field::ReleaseStore).to_owned(); - // A server publishes the release itself when it renders the seed. - if self.action != Action::CloudSeed || store.is_empty() || self.served().is_some() { - return Ok(()); - } - let url = crate::registry::publish_from( - self.access()?, - &self.build_dir, - &self.plugin_dirs(), - &store, - ) - .map_err(|error| format!("Publishing to {store} failed: {error}"))?; - self.set(Field::ReleaseUrl, json!(url)); - Ok(()) - } - - /// Run berth with these words in the normal terminal, as one of berth's - /// own actions on the host does. - fn run_own(&mut self, words: &[String]) -> Result<()> { - println!("berth {}", words.join(" ")); - let status = Command::new(std::env::current_exe()?) - .args(words) - .status()?; - // What the host is and can do may be different afterwards. - if let Ok(Some(saved)) = self.place.load(&self.paths) { - self.config = saved.clone(); - self.saved = saved; - } - self.host.disconnect(); - if let ["host", "rename", _, new, ..] = words - .iter() - .map(String::as_str) - .collect::>() - .as_slice() - && status.success() - { - self.renamed = Some((*new).to_owned()); - } - match status.success() { - true => Ok(()), - false => Err(format!("berth {} failed ({status})", words.join(" ")).into()), - } - } - - fn execute_action(&mut self) -> Result<()> { - self.publish_release()?; - self.save()?; - println!("{}", self.saved_note()); - if self.action == Action::Save { - return Ok(()); - } - // Over SSH, a host below a workstation gets the controller alone, or nothing. - if self.action == Action::Ssh { - match host_type::of(&self.config) { - host_type::HostType::Workstation => {} - host_type::HostType::Managed => { - let words = ["host", "install", &self.place.argument()].map(str::to_owned); - return self.run_own(&words); - } - host_type::HostType::Ssh => { - println!( - "Nothing is installed on a host of the type ssh. If it does not take berth's key yet: berth key trust {}", - self.place.argument() - ); - return Ok(()); - } - } - } - let (command, files) = self.command()?; - self.run_command(command, files)?; - // A successful apply settles how the host is logged in to in the saved profile. - if self.action == Action::Ssh - && let Ok(Some(saved)) = self.place.load(&self.paths) - { - self.config["access"] = saved["access"].clone(); - } - println!("{}", self.next_hint()); - Ok(()) - } - - /// Run the action's command in the normal terminal. Applying a host of - /// this machine holds the host's lock, as berth apply does, so that - /// nothing else changes the host meanwhile. - pub fn run_command( - &self, - mut command: Command, - files: Vec, - ) -> Result<()> { - let failed = |code: String| format!("{} failed ({code})", self.action.label()); - if self.action == Action::Ssh && self.served().is_none() { - use berth_core::runner; - let subject = runner::Subject::Host(self.place.argument()); - let request = runner::Request::new(subject, "apply"); - let work = runner::Work::Program(Box::new(runner::Program { - command, - input: None, - files, - })); - let code = runner::here(&self.paths, request, work, &mut std::io::stdout())?; - return match code { - Some(0) => apply::settle(&self.paths, &self.host_profile()), - Some(code) => Err(failed(format!("exit status: {code}")).into()), - None => Err(failed("ended by a signal".into()).into()), - }; - } - let _files = files; - let status = command.status().map_err(|error| { - format!( - "Could not start {}: {error}", - command.get_program().to_string_lossy() - ) - })?; - match status.success() { - true => Ok(()), - false => Err(failed(status.to_string()).into()), - } - } - - /// Run the chosen action inside the UI. Writing a USB drive first asks for - /// confirmation and for administrator rights. - pub fn run(&mut self, confirmed: bool) { - // The overview has no action of its own: its rows are the host's actions. - if self.action == Action::Manage { - return; - } - let mut usb = String::new(); - if self.action == Action::Iso { - usb = self.text(Field::UsbDevice).to_owned(); - } - if !usb.is_empty() { - self.usb_drives = discovery::usb_drives(); - let Some(drive) = self.usb_drives.iter().find(|(_, path)| *path == usb) else { - self.status = format!("{usb} is not a connected USB drive"); - return; - }; - if !confirmed { - self.confirm = Some(format!("Erase {}?", drive.0)); - return; - } - if !self.privileged { - self.pending_run = true; - self.request_unlock("Write the installer to the USB drive."); - if !self.privileged { - return; - } - } - } - self.pending_run = false; - if let Err(error) = self.start_job(&usb) { - self.status = error.to_string(); - } - } - - /// Close the finished job's screen and take over what it produced. - pub fn close_job(&mut self) { - let Some(job) = self.job.take() else { - return; - }; - let succeeded = job.outcome == Some(Ok(())); - // The machine is another one now, or none, and the command may have - // given the profile the machine's address. - let mut taken = None; - let machine_job = std::mem::take(&mut self.machine_job); - if machine_job { - self.load_machine(); - // A berth server ran the command and saved the profile there: without - // its copy, the next save from here would undo what it saved. - let refreshed = match self.server() { - Some(server) => server.mirror_host(&self.paths, &self.name()), - None => Ok(()), - }; - taken = self.take_in_command(); - if let Err(error) = refreshed { - taken = Some(format!( - "The berth server did not give the profile again: {error}" - )); - } - } - if std::mem::take(&mut self.fetching_iso) { - if let (true, Some(path)) = (succeeded, job.lines.last()) { - self.commit(Field::Iso, path); - } - return; - } - self.status = if succeeded { - format!("{} finished", job.title) - } else { - format!("{} failed", job.title) - }; - if let Some(said) = taken { - self.status = format!("{} · {said}", self.status); - } - // The machine is the host now, so setting it up is over. - if machine_job && succeeded && job.title == CREATE_MACHINE { - let status = std::mem::take(&mut self.status); - self.set_step(Step::Manage); - self.reconnect_host(); - self.status = status; - } - } - - /// A shell over plain SSH in a terminal inside the UI, as the SSH user: for - /// a host whose controller cannot be reached. - pub fn start_shell(&mut self, rows: u16, cols: u16) { - let title = self.ssh_target(); - let started = self.terminal(&[]).and_then(|command| { - let _ = self.save(); - crate::session::Session::start(&title, command, rows, cols) - }); - match started { - Ok(mut session) => { - session.closes = true; - self.session = Some(session); - } - Err(error) => self.status = error.to_string(), - } - } - - /// `ssh` with this host's options. - fn ssh(&self) -> Result { - self.host_profile().ssh(&self.paths) - } - - fn ssh_target(&self) -> String { - self.host_profile().target() - } - - /// An interactive shell on the host, or `remote` run there. - pub fn terminal(&self, remote: &[&str]) -> Result { - if self.text(Field::SshHost).is_empty() { - return Err("SSH host is required".into()); - } - let mut command = self.ssh()?; - command.arg(self.ssh_target()).args(remote); - Ok(command) - } - - /// An interactive shell as the agent. Root login and the agent's own key are - /// not a given, so it goes through the SSH user and sudo. `agent-env` adds the - /// display and tool paths; a host without it still gets a login shell. - pub fn agent_terminal(&self) -> Result { - let agent = self.agent_name()?; - let mut command = self.terminal(&[])?; - command.arg("-t").arg(format!( - "sudo -iu {agent} sh -c 'command -v agent-env >/dev/null && exec agent-env; exec bash -l'" - )); - Ok(command) - } - - /// The agent's account name, checked because it ends up in a remote shell command. - fn agent_name(&self) -> Result<&str> { - let agent = match self.text(Field::AgentUser) { - "" => "agent", - user => user, - }; - if !agent - .chars() - .all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-') - || agent.starts_with('-') - { - return Err("Agent username is not a valid account name".into()); - } - Ok(agent) - } - - /// Remove a field's value. - pub fn clear(&mut self, field: Field) { - if field.can_clear() { - self.commit(field, ""); - if field == Field::Iso { - self.commit(Field::IsoSha, ""); - } - self.status = format!("{} unset", field.spec().label); - } - } - - /// Write the ISO that was just built to a USB drive: the only one connected, - /// the given one, or ask which. - pub fn write_built_iso(&mut self, device: Option) { - self.usb_drives = discovery::usb_drives(); - let device = match (device, self.usb_drives.as_slice()) { - (Some(device), _) => device, - (None, [(_, only)]) => only.clone(), - (None, []) => { - if let Some(job) = &mut self.job { - let hint = "No usable USB drive. Plug one in (replug it if it was ejected) and press w."; - job.lines.push(hint.into()); - } - return; - } - (None, _) => { - self.choosing_drive = true; - return; - } - }; - self.choosing_drive = false; - self.job = None; - self.set(Field::UsbDevice, json!(device)); - self.write_only = true; - self.run(false); - } - - /// Ask for the provisioners and the host's machine again, without - /// waiting for the answer. - pub fn load_machine(&mut self) { - // Without berth's store, as in tests, there is nobody to ask. - if self.access.is_err() { - return; - } - self.machine.asking(); - let name = self.place.argument(); - let paths = self.paths.clone(); - let (send, answers) = mpsc::channel(); - std::thread::spawn(move || { - let _ = send.send(machine_answers(&paths, &name)); - }); - self.machine_answers = Some(answers); - } - - /// Whether the machine's answers are still awaited. - pub fn machine_awaited(&self) -> bool { - self.machine_answers.is_some() - } - - /// Take in the machine's answers once they are there. Called between events. - pub fn watch_machine(&mut self) { - let Some(answers) = &self.machine_answers else { - return; - }; - let (listed, found) = match answers.try_recv() { - Ok(answers) => answers, - Err(mpsc::TryRecvError::Empty) => return, - Err(mpsc::TryRecvError::Disconnected) => ( - Err("Nothing answered".into()), - Err("Nothing answered".into()), - ), - }; - self.machine_answers = None; - self.machine.listed(listed); - self.machine.found(found); - } - - /// Enter on a row of the machine. - pub fn machine_enter(&mut self, pick: machine::Pick) { - // The machine is made from the profile, which has to be whole first, - // and of the kind a created machine is. - if pick == machine::Pick::Create { - setup::fit_target(&mut self.config, Action::Machine); - } - if pick == machine::Pick::Create && !self.problems().is_empty() { - self.status = "Fix the listed problems first".into(); - return; - } - let name = self.name(); - let next = self.machine.enter(pick, &name); - self.follow(next); - } - - /// The answer to the question before creating the machine. - pub fn machine_answer(&mut self, yes: bool) { - let next = self.machine.answer(yes); - self.follow(next); - } - - /// Do what a row of the machine led to. Its jobs are berth's own - /// commands, which go to the berth server when one is set. - fn follow(&mut self, next: Next) { - let name = self.place.argument(); - let (title, args, after) = match next { - Next::Nothing | Next::Confirm => return, - Next::Say(text) => { - self.status = text; - return; - } - Next::Edit(value) => { - self.editing = Some(Input::new(value)); - return; - } - Next::Create(asked) => { - let mut args = vec!["provision".to_owned(), name, asked.provisioner]; - args.extend( - asked - .arguments - .iter() - .map(|(key, value)| format!("{key}={value}")), - ); - args.push("--yes".into()); - ( - CREATE_MACHINE, - args, - "The machine is this host now: its overview reaches it.", - ) - } - Next::Power(verb) => ( - if verb == "start" { - "Start machine" - } else { - "Stop machine" - }, - vec!["instance".to_owned(), name, verb.to_owned()], - "", - ), - Next::Destroy => ( - "Delete machine", - vec![ - "instance".to_owned(), - name, - "destroy".to_owned(), - "--yes".to_owned(), - ], - "", - ), - }; - if let Err(error) = self.machine_job(title, &args, after) { - self.status = error.to_string(); - } - } - - fn machine_job(&mut self, title: &str, args: &[String], next: &str) -> Result<()> { - // The provisioner works from the profile as it is kept. - self.save()?; - let mut command = Command::new(std::env::current_exe()?); - command.args(args); - let stage = Stage { - title: title.into(), - command, - source: None, - input: None, - }; - self.job = Some(Job::start(vec![stage], next, vec![])?); - self.machine_job = true; - Ok(()) - } - - fn start_job(&mut self, usb: &str) -> Result<()> { - self.publish_release()?; - if self.action != Action::Release { - self.save()?; - } - let mut stages = vec![]; - let mut files = vec![]; - if !std::mem::take(&mut self.write_only) { - let command; - (command, files) = self.command()?; - stages.push(Stage { - title: self.action.label().into(), - command, - source: None, - input: None, - }); - } - let mut next = self.next_hint(); - if !usb.is_empty() { - let iso = self - .build_dir - .join(format!("{}-autoinstall.iso", self.text(Field::Hostname))); - let mut write = Command::new("sudo"); - write - .args(["-n", "bash", layout::WRITE_USB]) - .arg(&iso) - .arg(usb); - stages.push(Stage { - title: format!("Write to {usb}"), - command: write, - source: Some(iso), - input: None, - }); - next = "Next: boot the target from the USB drive. Booting it erases the selected disk."; - } - self.job = Some(Job::start(stages, next, files)?); - Ok(()) - } -} - -/// Load a profile and fill in everything the UI expects to be present. -pub fn parse_config(data: &[u8]) -> Result { - let mut config: Value = serde_json::from_slice(data)?; - if !config.is_object() { - return Err("Configuration must be a JSON object".into()); - } - berth_api::profile::take_old_names(&mut config); - berth_api::profile::retire_qemu(&mut config); - for field in ["wifi", "ansible_vars", "builder"] { - if !config[field].is_null() && !config[field].is_object() { - return Err(format!("{field} must be a JSON object or null").into()); - } - } - for key in ["ansible_vars", "builder"] { - if config[key].is_null() { - config[key] = json!({}); - } - } - for (key, value) in [ - ("target", json!("laptop")), - ("keyboard", json!("de")), - ("operator_username", json!("ops")), - ("agent_username", json!("agent")), - ("agent_passwordless_sudo", json!(true)), - ("target_disk_ssd", json!("any")), - ] { - if config[key].is_null() { - config[key] = value; - } - } - // Placeholders from older example profiles count as unset. - for key in [ - "operator_password_hash", - "target_disk_serial", - "release_url", - ] { - if config[key].as_str().is_some_and(|v| v.contains("REPLACE")) { - config[key] = json!(""); - } - } - if config["target_disk_mode"].is_null() { - let has_serial = config["target_disk_serial"] - .as_str() - .is_some_and(|serial| !serial.is_empty()); - config["target_disk_mode"] = json!(if has_serial { "serial" } else { "auto" }); - } - if config["wifi_enabled"].is_null() { - let configured = config["wifi"].as_object().is_some_and(|w| !w.is_empty()); - config["wifi_enabled"] = json!(configured); - } - // The coding agents, T3 Code and GitHub's CLI were switches once and are - // features of plugins that come with berth now. They go first: later - // plugins, such as Unity's, set themselves up for the agents they find. - // Only a profile of that layout is converted: one with the old switches, - // or one with no list of features at all, which had every switch on. A - // profile that lists its features is left as it is, marked or not. - const OLD_AGENT_SWITCHES: [&str; 5] = [ - "devbox_install_agents", - "devbox_agent_claude", - "devbox_agent_codex", - "devbox_agent_pi", - "devbox_install_t3", - ]; - let old_layout = OLD_AGENT_SWITCHES - .iter() - .any(|key| !config["ansible_vars"][*key].is_null()) - || config["ansible_vars"]["devbox_plugin_features"].is_null(); - if config["builder"]["shipped_plugins"] != true && old_layout { - let vars = &config["ansible_vars"]; - let on = |key: &str, default: bool| vars[key].as_bool().unwrap_or(default); - let agents = on("devbox_install_agents", true); - let mut features: Vec = [ - ("claude/cli", agents && on("devbox_agent_claude", true)), - ("codex/cli", agents && on("devbox_agent_codex", true)), - ("github/cli", true), - ("pi/cli", agents && on("devbox_agent_pi", true)), - ("t3/server", on("devbox_install_t3", agents)), - ] - .into_iter() - .filter(|(_, chosen)| *chosen) - .map(|(feature, _)| json!(feature)) - .collect(); - for feature in vars["devbox_plugin_features"] - .as_array() - .into_iter() - .flatten() - { - if !features.contains(feature) { - features.push(feature.clone()); - } - } - if !config["ansible_vars"].is_object() { - config["ansible_vars"] = json!({}); - } - let vars = config["ansible_vars"].as_object_mut().unwrap(); - for old in OLD_AGENT_SWITCHES { - vars.remove(old); - } - vars.insert("devbox_plugin_features".into(), json!(features)); - config["builder"]["shipped_plugins"] = json!(true); - } - // Profiles from before the privilege levels keep what they had: sudo for - // everything without a password is `full`. One whose agent types a - // password stays as it is until a level is chosen. - if config["agent_privileges"].is_null() && config["agent_passwordless_sudo"] == true { - config["agent_privileges"] = json!("full"); - } - // The action last run from the overview was kept once; the host lists its own now. - if let Some(builder) = config["builder"].as_object_mut() { - builder.remove("manage_task"); - } - // Device names change between sessions, so the drive to write is chosen each time. - if let Some(builder) = config["builder"].as_object_mut() { - builder.remove("usb_device"); - } - // The operator always has sudo without a password and always takes the key - // of berth; profiles once had switches for both. - if let Some(profile) = config.as_object_mut() { - profile.remove("operator_passwordless_sudo"); - profile.remove("berth_ssh_key"); - } - let problems = berth_api::profile::Access::problems(&config); - if !problems.is_empty() { - return Err(problems.join("; ").into()); - } - Ok(config) -} - -/// How the overview tells whether a host is behind: a server's host the way -/// the server sees it, another with this machine's plugins. -fn compare(paths: &Paths, host: &Host) -> Option { - if let Some(server) = host.served(paths) { - let name = host.name.clone(); - return Some(std::sync::Arc::new(move |_: &berth_api::Version| { - let found = server - .call("hosts.get", serde_json::json!({"name": name}), None) - .ok()?; - serde_json::from_value(found.get("behind")?.clone()).ok() - })); - } - let now = berth_core::rollout::comparer(paths); - Some(std::sync::Arc::new(move |version: &berth_api::Version| { - now(version.applied.as_ref()?) - })) -} - -/// The berth command that runs one of berth's own actions on a host, with -/// the values given. A secret is asked for by the command itself. -fn own_command( - host: &str, - action: &berth_api::Action, - values: &std::collections::BTreeMap, -) -> Vec { - let given = |name: &str| values.get(name).map(String::as_str).unwrap_or("").trim(); - let mut words: Vec = match action.name.as_str() { - "install-controller" => vec!["host".into(), "install".into(), host.into()], - "trust-key" => { - let mut words = vec!["key".into(), "trust".into(), host.into()]; - if !given("key").is_empty() { - words.extend(["--key".into(), given("key").into()]); - } - if given("keep_password") == "yes" { - words.push("--keep-password".into()); - } - return words; - } - "rename" => { - let mut words = vec![ - "host".into(), - "rename".into(), - host.into(), - given("name").into(), - ]; - if given("hostname") == "yes" { - words.push("--hostname".into()); - } - return words; - } - "host-key" => { - let mut words = vec!["key".into(), "host".into(), host.into()]; - if given("accept") == "yes" { - words.push("--accept".into()); - } - return words; - } - name => vec!["run".into(), host.into(), name.into()], - }; - if words[0] == "run" { - words.extend( - action - .arguments - .iter() - .filter(|argument| !argument.secret && !given(&argument.name).is_empty()) - .map(|argument| format!("{}={}", argument.name, given(&argument.name))), - ); - // The question was answered on the screen. - words.push("--yes".into()); - } - words -} diff --git a/crates/berth/src/commands.rs b/crates/berth/src/commands.rs index 07c03f1..daa0ce6 100644 --- a/crates/berth/src/commands.rs +++ b/crates/berth/src/commands.rs @@ -1,10 +1,7 @@ //! The commands that talk to a host's controller: sessions, actions, the //! channel and services. Each is a plain program that waits on a runtime. -use crate::{ - Result, - remote::{exited, list}, -}; +use crate::Result; use berth_api::{ self as api, client::{Error, Frame, encode, encode_path}, @@ -17,12 +14,18 @@ use berth_core::{ profiles::Place, provision, registry, runner, }; +use berth_tui::host::list; use futures_util::{SinkExt, StreamExt}; use serde_json::{Value, json}; use std::collections::BTreeMap; use std::io::{IsTerminal, Write}; use tokio::io::AsyncReadExt; +/// The exit code an `exited` frame carries, when the text is one. +fn exited(text: &str) -> Option> { + berth_tui::host::exited(&serde_json::from_str(text).ok()?) +} + /// Ctrl+Q, which leaves a terminal session without ending it. const DETACH: u8 = 0x11; @@ -1037,31 +1040,81 @@ pub fn call( /// is a job of the server, whose output is shown as it comes. pub fn apply(paths: &Paths, name: &str) -> Result<()> { let host = Host::load(paths, name)?; - let Some(server) = host.served(paths) else { - let password = host.sudo_password(paths)?; - let prepared = berth_core::apply::prepare(paths, &host, password.as_deref())?; - let work = runner::Work::Program(Box::new(runner::Program { - command: prepared.command, - input: None, - files: prepared.files, - })); - let request = runner::Request::new(runner::Subject::Host(name.to_owned()), "apply"); - let code = runner::here(paths, request, work, &mut std::io::stdout())?; - if code == Some(0) { - berth_core::apply::settle(paths, &host)?; - } - std::process::exit(code.unwrap_or(1)); - }; // The server has no terminal to ask on: a password it needs is asked for here. let act = api::Act { sudo_password: host.sudo_password(paths)?, ..api::Act::default() }; + let (server, here) = crate::serve::here::server(paths)?; let acted = act_on(&server, Some(name), "apply", &act)?; let code = follow_acted(&server, None, acted, &mut std::io::stdout())?; + crate::serve::here::finish(here); + std::process::exit(code); +} + +/// `berth iso HOST [--write DEVICE]`: build the host's USB installer on the +/// server of this machine, and write it to the USB drive `device`, which is +/// erased, after asking. +pub fn installer(paths: &Paths, name: &str, device: Option<&str>) -> Result<()> { + let mut arguments = BTreeMap::new(); + if let Some(device) = device { + print!("Erase {device} and write the installer to it? [y/N] "); + std::io::stdout().flush()?; + let mut answer = String::new(); + std::io::stdin().read_line(&mut answer)?; + if !answer.trim().eq_ignore_ascii_case("y") { + return Err("Not written".into()); + } + let password = registry::read_secret("Your sudo password (empty when sudo needs none)")?; + arguments.insert("device".to_owned(), device.to_owned()); + arguments.insert("password".to_owned(), password); + } + let act = api::Act { + arguments, + ..api::Act::default() + }; + let (server, here) = crate::serve::here::server(paths)?; + let acted = act_on(&server, Some(name), "installer", &act)?; + let code = follow_acted(&server, None, acted, &mut std::io::stdout())?; + crate::serve::here::finish(here); std::process::exit(code); } +/// `ssh` to the host as its profile says, running `remote` there, or a shell. +pub fn terminal(paths: &Paths, name: &str, remote: &[&str]) -> Result { + let host = Host::load(paths, name)?; + if !host.access().reachable() { + return Err(format!("{name} has no SSH address yet").into()); + } + let mut command = host.ssh(paths)?; + command.arg(host.target()).args(remote); + Ok(command) +} + +/// An interactive shell as the agent. Root login and the agent's own key are +/// not a given, so it goes through the SSH user and sudo. `agent-env` adds the +/// display and tool paths; a host without it still gets a login shell. +pub fn agent_terminal(paths: &Paths, name: &str) -> Result { + let host = Host::load(paths, name)?; + let agent = match host.config["agent_username"].as_str().unwrap_or("") { + "" => "agent", + user => user, + }; + // It ends up in a shell command on the host. + if agent.starts_with('-') + || !agent + .chars() + .all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-') + { + return Err("The agent's account name is not a valid one".into()); + } + let mut command = terminal(paths, name, &[])?; + command.arg("-t").arg(format!( + "sudo -iu {agent} sh -c 'command -v agent-env >/dev/null && exec agent-env; exec bash -l'" + )); + Ok(command) +} + /// Run an action of a berth server's: of the host `host`, or of the /// installation without one. pub(crate) fn act_on( @@ -1115,7 +1168,10 @@ fn follow_acted( if let Some(job) = &acted.job { return link::runtime()?.block_on(async { let portal = server.portal().await?; - eprintln!("Job {} on the berth server at {}", job.id, server.url); + match server.url.as_str() { + berth_core::server::HERE => eprintln!("Job {}", job.id), + url => eprintln!("Job {} on the berth server at {url}", job.id), + } follow_job(&portal, &job.id, out).await }); } @@ -1286,11 +1342,11 @@ pub fn update_plugins(paths: &Paths, args: &[&str]) -> Result<()> { /// `berth seed HOST` with a berth server: the server renders the seed, and it /// is written here. pub fn seed(paths: &Paths, name: &str) -> Result<()> { - let host = Host::load(paths, name)?; - let server = host.served(paths).ok_or("Not a host of a berth server")?; + let (server, here) = crate::serve::here::server(paths)?; let seed = act_on(&server, Some(name), "seed", &api::Act::default())? .result .unwrap_or_default(); + drop(here); let dir = paths.build_dir().join(name).join("cloud"); { use std::os::unix::fs::DirBuilderExt; @@ -1407,7 +1463,7 @@ pub fn set_profile(paths: &Paths, name: &str, file: &str) -> Result<()> { } file => std::fs::read(file).map_err(|error| format!("{file}: {error}"))?, }; - crate::app::parse_config(&data).map_err(|error| format!("Not a profile: {error}"))?; + crate::profile::parse_config(&data).map_err(|error| format!("Not a profile: {error}"))?; let mut profile: Value = serde_json::from_slice(&data)?; let place = Place::resolve(paths, name)?; // A profile of an older layout is kept in the one of now. @@ -1926,17 +1982,17 @@ mod tests { set_profile(&paths, "studio", file.to_str().unwrap()).unwrap(); let place = Place::own("studio").unwrap(); let kept = place.load(&paths).unwrap().unwrap(); - let config = crate::app::parse_config(kept.to_string().as_bytes()).unwrap(); - let mut app = crate::app::App::new(paths.clone(), place.clone(), config); - app.save().unwrap(); + let config = crate::profile::parse_config(kept.to_string().as_bytes()).unwrap(); + crate::profile::save(&paths, &place, config).unwrap(); let saved = place.load(&paths).unwrap().unwrap(); assert_eq!( saved["ansible_vars"]["devbox_plugin_features"], json!(["codex/cli"]) ); // One of the old layout is still converted. - let old = crate::app::parse_config(br#"{"ansible_vars": {"devbox_agent_codex": false}}"#) - .unwrap(); + let old = + crate::profile::parse_config(br#"{"ansible_vars": {"devbox_agent_codex": false}}"#) + .unwrap(); assert!( !old["ansible_vars"]["devbox_plugin_features"] .as_array() diff --git a/crates/berth/src/fields.rs b/crates/berth/src/fields.rs deleted file mode 100644 index 4ef2524..0000000 --- a/crates/berth/src/fields.rs +++ /dev/null @@ -1 +0,0 @@ -pub use berth_tui::fields::*; diff --git a/crates/berth/src/keys.rs b/crates/berth/src/keys.rs deleted file mode 100644 index d5837e3..0000000 --- a/crates/berth/src/keys.rs +++ /dev/null @@ -1,194 +0,0 @@ -//! A terminal's keys and mouse as the shared screens take them, and back. - -use berth_tui::{Click, Code, Event, Key, Mouse}; -use crossterm::event::{ - Event as Native, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEventKind, -}; - -pub fn key(key: &KeyEvent) -> Option { - let code = match key.code { - KeyCode::Char(ch) => Code::Char(ch), - KeyCode::Enter => Code::Enter, - KeyCode::Esc => Code::Esc, - KeyCode::Tab => Code::Tab, - KeyCode::BackTab => Code::BackTab, - KeyCode::Backspace => Code::Backspace, - KeyCode::Delete => Code::Delete, - KeyCode::Insert => Code::Insert, - KeyCode::Up => Code::Up, - KeyCode::Down => Code::Down, - KeyCode::Left => Code::Left, - KeyCode::Right => Code::Right, - KeyCode::Home => Code::Home, - KeyCode::End => Code::End, - KeyCode::PageUp => Code::PageUp, - KeyCode::PageDown => Code::PageDown, - KeyCode::F(number) => Code::F(number), - _ => return None, - }; - Some(Key { - code, - ctrl: key.modifiers.contains(KeyModifiers::CONTROL), - alt: key.modifiers.contains(KeyModifiers::ALT), - shift: key.modifiers.contains(KeyModifiers::SHIFT), - }) -} - -/// The key as the terminal would have reported it. -pub fn native(key: Key) -> KeyEvent { - let code = match key.code { - Code::Char(ch) => KeyCode::Char(ch), - Code::Enter => KeyCode::Enter, - Code::Esc => KeyCode::Esc, - Code::Tab => KeyCode::Tab, - Code::BackTab => KeyCode::BackTab, - Code::Backspace => KeyCode::Backspace, - Code::Delete => KeyCode::Delete, - Code::Insert => KeyCode::Insert, - Code::Up => KeyCode::Up, - Code::Down => KeyCode::Down, - Code::Left => KeyCode::Left, - Code::Right => KeyCode::Right, - Code::Home => KeyCode::Home, - Code::End => KeyCode::End, - Code::PageUp => KeyCode::PageUp, - Code::PageDown => KeyCode::PageDown, - Code::F(number) => KeyCode::F(number), - }; - let mut modifiers = KeyModifiers::NONE; - for (on, modifier) in [ - (key.ctrl, KeyModifiers::CONTROL), - (key.alt, KeyModifiers::ALT), - (key.shift, KeyModifiers::SHIFT), - ] { - if on { - modifiers |= modifier; - } - } - KeyEvent::new(code, modifiers) -} - -/// How soon a key has to follow Esc to be read as that key with Alt. A -/// terminal sends Alt+R as Esc and `r` together, but a relay on the way, as -/// between Windows and WSL, can pass them on in two writes. -const ALT_WAIT: std::time::Duration = std::time::Duration::from_millis(25); - -thread_local! { - /// An event read while waiting to see whether Esc was Alt. - static AHEAD: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; -} - -/// Whether an event is waiting, for up to `timeout`. -pub fn poll(timeout: std::time::Duration) -> std::io::Result { - if AHEAD.with_borrow(Option::is_some) { - return Ok(true); - } - crossterm::event::poll(timeout) -} - -/// The next event of the terminal, with Esc and a character that come right -/// after it taken as that character with Alt. -pub fn read() -> std::io::Result { - if let Some(event) = AHEAD.take() { - return Ok(event); - } - read_from(crossterm::event::read, || crossterm::event::poll(ALT_WAIT)) -} - -fn read_from( - mut read: impl FnMut() -> std::io::Result, - mut soon: impl FnMut() -> std::io::Result, -) -> std::io::Result { - let event = read()?; - let escape = matches!(&event, Native::Key(key) - if key.code == KeyCode::Esc && key.modifiers.is_empty() && key.kind == KeyEventKind::Press); - if !escape || !soon()? { - return Ok(event); - } - let next = read()?; - if let Native::Key(key) = &next - && let KeyCode::Char(_) = key.code - && key.kind == KeyEventKind::Press - && (key.modifiers - KeyModifiers::SHIFT).is_empty() - { - return Ok(Native::Key(KeyEvent::new_with_kind( - key.code, - key.modifiers | KeyModifiers::ALT, - key.kind, - ))); - } - AHEAD.set(Some(next)); - Ok(event) -} - -/// The event, when it is one the screens take: a key going down, a click, the -/// wheel, a paste. -pub fn event(event: &Native) -> Option { - match event { - Native::Key(pressed) if pressed.kind != KeyEventKind::Release => { - key(pressed).map(Event::Key) - } - Native::Mouse(mouse) => { - let click = match mouse.kind { - MouseEventKind::Down(MouseButton::Left) => Click::Left, - MouseEventKind::Down(MouseButton::Right) => Click::Right, - MouseEventKind::ScrollUp => Click::ScrollUp, - MouseEventKind::ScrollDown => Click::ScrollDown, - _ => return None, - }; - Some(Event::Mouse(Mouse { - click, - column: mouse.column, - row: mouse.row, - })) - } - Native::Paste(text) => Some(Event::Paste(text.clone())), - _ => None, - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn press(code: KeyCode, modifiers: KeyModifiers) -> Native { - Native::Key(KeyEvent::new(code, modifiers)) - } - - /// What reading gives when the terminal has `events`, each after the - /// first coming soon after the one before when `soon` is set. - fn reads(events: &[Native], soon: bool) -> Vec { - let queue = std::cell::RefCell::new(events.to_vec()); - let mut got = vec![]; - while AHEAD.with_borrow(Option::is_some) || !queue.borrow().is_empty() { - let event = match AHEAD.take() { - Some(event) => event, - None => read_from( - || Ok(queue.borrow_mut().remove(0)), - || Ok(soon && !queue.borrow().is_empty()), - ) - .unwrap(), - }; - got.push(event); - } - got - } - - #[test] - fn esc_and_a_letter_right_after_it_are_alt_and_the_letter() { - let esc = press(KeyCode::Esc, KeyModifiers::NONE); - let r = press(KeyCode::Char('r'), KeyModifiers::NONE); - let alt_r = press(KeyCode::Char('r'), KeyModifiers::ALT); - assert_eq!(reads(&[esc.clone(), r.clone()], true), [alt_r]); - let shifted = press(KeyCode::Char('R'), KeyModifiers::SHIFT); - let alt_shift_r = press(KeyCode::Char('R'), KeyModifiers::SHIFT | KeyModifiers::ALT); - assert_eq!(reads(&[esc.clone(), shifted], true), [alt_shift_r]); - // A letter typed later is a key of its own. - assert_eq!(reads(&[esc.clone(), r.clone()], false), [esc.clone(), r]); - // So is anything but a letter, and it is not lost. - let up = press(KeyCode::Up, KeyModifiers::NONE); - assert_eq!(reads(&[esc.clone(), up.clone()], true), [esc.clone(), up]); - let ctrl_c = press(KeyCode::Char('c'), KeyModifiers::CONTROL); - assert_eq!(reads(&[esc.clone(), ctrl_c.clone()], true), [esc, ctrl_c]); - } -} diff --git a/crates/berth/src/main.rs b/crates/berth/src/main.rs index 3733c5b..f7a65b7 100644 --- a/crates/berth/src/main.rs +++ b/crates/berth/src/main.rs @@ -1,39 +1,26 @@ -mod app; mod commands; -mod fields; mod key_command; -mod keys; -mod mirror; -mod picker; +mod profile; mod provisioner_command; -mod provisioner_tab; -mod remote; mod resource_command; mod serve; -mod session; mod store_command; -mod ui; mod update; -use app::{App, parse_config}; -use berth_core::{credentials, discovery, job, paths, plugins, registry}; -pub(crate) use berth_tui::{markdown, theme}; -use crossterm::{cursor::SetCursorStyle, event}; -use fields::{Action, Field, Step}; -use paths::{Paths, layout}; +use berth_core::{paths, plugins, registry}; +use paths::Paths; use serde_json::json; -use std::{error::Error, fs, io::Write, process::Command}; +use std::{error::Error, process::Command}; type Result = std::result::Result>; const USAGE: &str = "berth: set up and look after agent workstations. Usage: - berth choose a host, or create one - berth HOST open a host (a saved name, or a path to a profile) - berth ui [HOST] the screens of berth serve: of the server this berth - uses, of a berth serve of yours on this machine, or of - one that runs in berth itself until it ends + berth [HOST] berth's screens: the hosts, and the host HOST + berth ui [HOST] the same: of the server this berth uses, of a berth + serve of yours on this machine, or of one that runs in + berth itself until the screens close berth list saved hosts berth host add NAME ADDRESS [--user USER] [--port PORT] [--auth AUTH] [--type ssh|managed|workstation] [--no-contact] @@ -245,55 +232,8 @@ fn change_setting(paths: &Paths, key: &str, value: &str) -> Result<()> { } } -fn enter() -> Result { - let terminal = ratatui::init(); - crossterm::execute!( - std::io::stdout(), - event::EnableBracketedPaste, - event::EnableMouseCapture, - SetCursorStyle::BlinkingBar - )?; - Ok(terminal) -} - -fn leave() { - let _ = crossterm::execute!( - std::io::stdout(), - event::DisableBracketedPaste, - event::DisableMouseCapture, - SetCursorStyle::DefaultUserShape - ); - ratatui::restore(); -} - -/// Load a host's profile, starting from the example for a new one. -/// Whether these arguments open the terminal screen: none, or a host's name. -fn opens_screen(args: &[&str]) -> bool { - // The commands that are one word. - const ALONE: &[&str] = &[ - "list", - "registry", - "secret", - "plugins", - "provisioners", - "provisioner", - "resource", - "inventory", - "inbox", - "kv", - "store", - "help", - "ui", - ]; - match args { - [] => true, - [one] => !one.starts_with('-') && !ALONE.contains(one), - _ => false, - } -} - -/// Whether a command reads this machine's own plugins: the screen, and the -/// commands that apply, build or provision with them or list them. +/// Whether a command reads this machine's own plugins: the commands that +/// apply, build or provision with them or list them. fn loads_plugins(args: &[&str]) -> bool { const VERBS: &[&str] = &[ "apply", @@ -309,7 +249,7 @@ fn loads_plugins(args: &[&str]) -> bool { "publish", "host", ]; - opens_screen(args) || args.first().is_some_and(|verb| VERBS.contains(verb)) + args.first().is_some_and(|verb| VERBS.contains(verb)) } /// Put back the plugins berth's store has and this machine's plugin @@ -322,99 +262,6 @@ pub(crate) fn restore_plugins(paths: &Paths) { } } -fn open(paths: &Paths, host: &str) -> Result { - let place = berth_core::profiles::Place::resolve(paths, host)?; - paths.prepare()?; - // Actions call the builder scripts and playbook by relative path. - std::env::set_current_dir(paths.source()?)?; - let (data, existing) = match place.load(paths)? { - Some(profile) => (profile.to_string().into_bytes(), true), - None => (fs::read(layout::EXAMPLE)?, false), - }; - let served = place.server_url().is_some(); - let mut app = App::new(paths.clone(), place, parse_config(&data)?); - // With a server set, a new host is one of the server's. - if let (false, true, Some(server)) = ( - existing, - served, - berth_core::server::Server::configured(paths), - ) { - if !server.admin(paths) { - return Err(format!( - "No host {host} on the berth server at {}. Adding one needs the role admin there.", - server.url - ) - .into()); - } - app.config["builder"]["served"] = json!(server.url); - } - app.build_dir = paths.build_dir(); - app.iso_dir = paths.iso_dir(); - app.load_plugins(paths.config_dir.join("plugins")); - // A host is reached without the store; what needs it says why it is missing. - app.access = registry::Store::new(paths) - .map_err(|error| format!("berth's store does not open: {error}")); - // A server's host is set up from the server, with the server's plugins. - if app.served().is_some() { - let known = app - .host_profile() - .served(paths) - .and_then(|server| server.call("setup.catalogue", json!({}), None).ok()); - // The server's plugins are what its hosts can have. - if let Some(features) = known - .as_ref() - .and_then(|found| found["features"].as_array()) - { - let text = |feature: &serde_json::Value, key: &str| { - feature[key].as_str().unwrap_or("").to_owned() - }; - app.set_features( - features - .iter() - .map(|feature| berth_tui::setup::Feature { - key: text(feature, "key"), - label: text(feature, "label"), - group: text(feature, "group"), - help: text(feature, "help"), - }) - .collect(), - ); - } - } - // The keys of the ring that logs in to the host: the server's for its hosts. - let ring = match app.host_profile().served(paths) { - Some(server) => key_command::listed(&server).unwrap_or_default(), - None => key_command::local(paths).unwrap_or_default(), - }; - app.own_public = ring - .iter() - .find(|key| key.name == berth_api::profile::BERTH_KEY) - .map(|key| key.public.clone()) - .unwrap_or_default(); - app.ring_keys = ring.into_iter().map(|key| key.name).collect(); - app.load_access(); - app.detect(); - // A host that is installed opens on its maintenance tab. - if existing && !app.text(Field::SshHost).is_empty() { - app.set_step(Step::Manage); - } - Ok(app) -} - -/// Stop with the list of problems when the profile cannot run the action. -fn require_ready(app: &App) -> Result<()> { - // A seed and an installer make a whole workstation. - berth_core::host_type::guard( - &app.host_profile(), - berth_core::host_type::Capability::Apply, - )?; - let problems = app.problems(); - if problems.is_empty() { - return Ok(()); - } - Err(format!("Not ready:\n {}", problems.join("\n ")).into()) -} - fn succeed(mut command: Command) -> Result<()> { let status = command.status()?; if !status.success() { @@ -424,49 +271,101 @@ fn succeed(mut command: Command) -> Result<()> { Ok(()) } -/// `berth iso HOST [--write DEVICE]`: build the installer without the UI. -fn build_installer(paths: &Paths, host: &str, device: Option<&str>) -> Result<()> { - let mut app = open(paths, host)?; - app.action = Action::Iso; - if app.text(Field::Iso).is_empty() { - let output = Command::new("python3") - .args([layout::BUILDER, "fetch-iso", "--dir"]) - .arg(&app.iso_dir) - .stderr(std::process::Stdio::inherit()) - .output()?; - if !output.status.success() { - return Err("Downloading the Ubuntu installer failed".into()); +/// End quietly when what reads berth's output has gone, as `head` does after +/// its lines: printing then panics, which is no fault of berth's to report. +fn end_quietly_on_a_closed_pipe() { + let report = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |panic| { + let said = panic.payload().downcast_ref::(); + if said.is_some_and(|said| said.starts_with("failed printing to std")) { + std::process::exit(141); } - app.commit(Field::Iso, String::from_utf8(output.stdout)?.trim()); + report(panic); + })); +} + +/// Whether these arguments open the screens: none, `ui`, or one word that is +/// no command, taken as the host to open. +fn opens_screens<'a>(args: &[&'a str]) -> Option> { + match args { + [] | ["ui"] => Some(None), + ["ui", host] => Some(Some(host)), + [host] if !host.starts_with('-') && !COMMANDS.contains(host) => Some(Some(host)), + _ => None, } - require_ready(&app)?; - app.execute()?; - let Some(device) = device else { - return Ok(()); - }; - let name = format!("{}-autoinstall.iso", app.text(Field::Hostname)); - print!("Erase {device} and write the installer to it? [y/N] "); - std::io::stdout().flush()?; - let mut answer = String::new(); - std::io::stdin().read_line(&mut answer)?; - if !answer.trim().eq_ignore_ascii_case("y") { - return Err("Not written".into()); +} + +/// The commands that are one word, which no host name can stand for. +const COMMANDS: &[&str] = &[ + "list", + "registry", + "secret", + "plugins", + "provisioners", + "provisioner", + "resource", + "inventory", + "inbox", + "kv", + "store", + "help", + "config", + "serve", + "version", + "openapi", + "asyncapi", + "operations", + "update", + "key", + "setup-key", +]; + +/// `berth [ui] [HOST]`: the screens of a server: the one this berth is set +/// to use, a `berth serve` of this user on this machine, or else one in +/// this process for as long as they are open, which waits for the jobs it +/// runs before berth ends. +fn screens(host: Option<&str>) -> Result<()> { + use berth_page::settings::{self, Settings}; + use std::io::IsTerminal; + if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() { + let said = match host { + Some(word) => format!( + "there is no command `{word}`, and no terminal for the screens of host {word}. `berth help` lists the commands" + ), + None => "berth's screens need a terminal, and there is none here. `berth help` lists the commands that need none".into(), + }; + return Err(said.into()); + } + let var = |name: &str| std::env::var(name).ok(); + let settings = Settings::new(settings::folder(var)); + match settings.take_in(settings::old_folder(var).as_deref()) { + Ok(Some(server)) => eprintln!("berth: berth-remote's server is berth's now: {server}"), + Ok(None) => {} + Err(error) => eprintln!("berth: berth-remote's settings were not taken in: {error}"), + } + let mut linked = berth_page::device::Linked::from(var); + let mut here = None; + if linked.local(&settings) { + let (server, started) = serve::here::local(&Paths::locate()?)?; + if let Some(started) = &started { + berth_page::net::serve_here(started.dial()); + } + linked.server = Some(server); + here = started; } - let mut write = Command::new("sudo"); - write - .args(["bash", layout::WRITE_USB]) - .arg(app.build_dir.join(name)) - .arg(device); - succeed(write) + berth_page::device::install(linked, settings); + let shown = berth_page::screens::run(host.map(str::to_owned)); + serve::here::finish(here); + Ok(shown?) } /// `berth host HOST ...`: the secrets and registries a host is given. fn host_command(paths: &Paths, host: &str, args: &[&str]) -> Result<()> { - let mut app = open(paths, host)?; + let (place, mut config) = profile::load(paths, host)?; let list = |value: &serde_json::Value| value.as_array().cloned().unwrap_or_default(); match *args { [] => { - for secret in list(&app.config["secrets"]) { + for secret in list(&config["secrets"]) { let place = match (secret["env"].as_str(), secret["file"].as_str()) { (Some(variable), _) => format!("env {variable}"), (_, Some(path)) => format!("file {path}"), @@ -477,14 +376,14 @@ fn host_command(paths: &Paths, host: &str, args: &[&str]) -> Result<()> { secret["name"].as_str().unwrap_or("") ); } - for name in list(&app.config["registries"]) { + for name in list(&config["registries"]) { println!("registry {}", name.as_str().unwrap_or("")); } println!("Send them with: berth run {host} secrets"); return Ok(()); } ["secret", name, ref how @ ..] => { - let mut secrets = list(&app.config["secrets"]); + let mut secrets = list(&config["secrets"]); secrets.retain(|known| known["name"] != name); match *how { ["env", variable] => secrets.push(json!({"name": name, "env": variable})), @@ -500,10 +399,10 @@ fn host_command(paths: &Paths, host: &str, args: &[&str]) -> Result<()> { ); } } - app.config["secrets"] = json!(secrets); + config["secrets"] = json!(secrets); } ["registry", name, switch @ ("on" | "off")] => { - let mut registries = list(&app.config["registries"]); + let mut registries = list(&config["registries"]); registries.retain(|known| known != name); if switch == "on" { if !registry::Store::new(paths)? @@ -514,85 +413,12 @@ fn host_command(paths: &Paths, host: &str, args: &[&str]) -> Result<()> { } registries.push(json!(name)); } - app.config["registries"] = json!(registries); + config["registries"] = json!(registries); } _ => return Err("Usage: berth host HOST [secret NAME ... | registry NAME on|off]".into()), } - app.save() -} - -/// End quietly when what reads berth's output has gone, as `head` does after -/// its lines: printing then panics, which is no fault of berth's to report. -fn end_quietly_on_a_closed_pipe() { - let report = std::panic::take_hook(); - std::panic::set_hook(Box::new(move |panic| { - let said = panic.payload().downcast_ref::(); - if said.is_some_and(|said| said.starts_with("failed printing to std")) { - std::process::exit(141); - } - report(panic); - })); -} - -/// What to say instead of opening berth's screens where there is no terminal -/// for them, as in a script or over ssh without one. `word` is what was -/// given for a host, which may have been meant as a command. -fn no_terminal(paths: &Paths, word: Option<&str>) -> String { - let known = |word: &str| paths.hosts().iter().any(|(name, _)| name == word); - match word { - Some(word) if !known(word) => format!( - "there is no command `{word}`, and no terminal to set up a host of that name in. `berth help` lists the commands" - ), - _ => "berth's screens need a terminal, and there is none here. `berth help` lists the commands that need none".into(), - } -} - -/// `berth ui [HOST]`: the screens of a server: the one this berth is set to -/// use, a `berth serve` of this user on this machine, or else one in this -/// process for as long as they are open. -fn screens(host: Option<&str>) -> Result<()> { - use berth_page::settings::{self, Settings}; - use std::io::IsTerminal; - if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() { - return Err("berth's screens need a terminal, and there is none here. `berth help` lists the commands that need none".into()); - } - let var = |name: &str| std::env::var(name).ok(); - let settings = Settings::new(settings::folder(var)); - match settings.take_in(settings::old_folder(var).as_deref()) { - Ok(Some(server)) => eprintln!("berth: berth-remote's server is berth's now: {server}"), - Ok(None) => {} - Err(error) => eprintln!("berth: berth-remote's settings were not taken in: {error}"), - } - let mut linked = berth_page::device::Linked::from(var); - let mut here = None; - if linked.local(&settings) { - let socket = serve::here::socket(); - linked.server = Some(match std::os::unix::net::UnixStream::connect(&socket) { - Ok(_) => format!("unix:{}", socket.display()), - Err(_) => { - let paths = Paths::locate()?; - let started = serve::here::Here::start(&paths)?; - berth_page::net::serve_here(started.dial()); - here = Some(started); - berth_page::device::HERE.to_owned() - } - }); - } - berth_page::device::install(linked, settings); - let shown = berth_page::screens::run(host.map(str::to_owned)); - if let Some(here) = &here { - here.wait_for_jobs(|jobs| { - let names: Vec = jobs - .iter() - .map(|job| format!("{} {}", job.action, job.host).trim().to_owned()) - .collect(); - eprintln!( - "berth: waiting for what runs in this berth to end: {}. Ctrl+C stops it unfinished; berth serve keeps jobs running after the screens close.", - names.join(", ") - ); - }); - } - Ok(shown?) + profile::save(paths, &place, config)?; + Ok(()) } fn main() { @@ -632,13 +458,11 @@ fn run() -> Result<()> { unsafe { std::env::set_var(variable, value) }; args.drain(..2); } - let paths = Paths::locate()?; - // The first open of the store takes in the files of an older berth and - // says so on standard error, which the screen would hide. A store that - // does not open is reported where it is needed. - if opens_screen(&args) { - let _ = berth_core::store::shared(&paths); + // The screens go through a server, and take nothing from this machine's own files. + if let Some(host) = opens_screens(&args) { + return screens(host); } + let paths = Paths::locate()?; if loads_plugins(&args) && berth_core::server::Server::configured(&paths).is_none() { restore_plugins(&paths); } @@ -660,44 +484,28 @@ fn run() -> Result<()> { "connect", "setup-key", "store", - "ui", ]; - // The screen opens at once on what the last mirror left; the commands - // that print are given current data. - let mut mirroring = None; if let Some(server) = berth_core::server::Server::configured(&paths) && !args.first().is_some_and(|verb| local.contains(verb)) { - if opens_screen(&args) { - // A host the last mirror does not have cannot be opened without one. - if let [name] = args[..] - && !paths.hosts().iter().any(|(known, _)| known == name) - { - server - .mirror(&paths) - .map_err(|error| format!("the berth server at {}: {error}", server.url))?; - } - mirroring = Some(mirror::Mirroring::of(&paths, server)); - } else { - server - .mirror(&paths) - .map_err(|error| format!("the berth server at {}: {error}", server.url))?; - } + server + .mirror(&paths) + .map_err(|error| format!("the berth server at {}: {error}", server.url))?; } - let host = match args[..] { + match args[..] { ["list"] => { for (name, address) in paths.hosts() { println!("{name:<24} {address}"); } - return Ok(()); + Ok(()) } - ["registry", ref rest @ ..] => return registry::registry_command(&paths, rest), - ["secret", ref rest @ ..] => return registry::secret_command(&paths, rest), + ["registry", ref rest @ ..] => registry::registry_command(&paths, rest), + ["secret", ref rest @ ..] => registry::secret_command(&paths, rest), ["image", "push", destination, ref rest @ ..] => { let image = registry::push_image(&paths, destination, rest.first().unwrap_or(&"latest"))?; println!("Pushed {image}"); - return Ok(()); + Ok(()) } ["publish", destination, ref rest @ ..] => { std::env::set_current_dir(paths.source()?)?; @@ -715,80 +523,78 @@ fn run() -> Result<()> { ), }; if let Some(host) = host { - let mut app = open(&paths, host)?; - app.config["release_url"] = json!(url); - app.config["release_store"] = json!(destination); - app.config["release_private"] = json!(login.is_some()); + let (place, mut config) = profile::load(&paths, host)?; + config["release_url"] = json!(url); + config["release_store"] = json!(destination); + config["release_private"] = json!(login.is_some()); match login { Some(name) => { if registry::Store::new(&paths)?.curl_login(name)?.is_none() { return Err(format!("Registry {name} has no stored login").into()); } - app.config["release_login"] = json!(name); + config["release_login"] = json!(name); println!("{host} downloads it from there with the login of {name}"); } None => { - if let Some(profile) = app.config.as_object_mut() { + if let Some(profile) = config.as_object_mut() { profile.remove("release_login"); } println!("{host} downloads it from there without a login"); } } - app.save()?; + profile::save(&paths, &place, config)?; } - return Ok(()); + Ok(()) } // A host's own subcommands start with secret or registry. ["host", "add", name, address, ref rest @ ..] if !["secret", "registry"].contains(&name) => { - return commands::add_host(&paths, name, address, rest); + commands::add_host(&paths, name, address, rest) } - ["host", "install", host] => return commands::install_controller(&paths, host), - ["host", "type", host, given] => return commands::set_type(&paths, host, given), - ["host", "rename", host, name] => return commands::rename(&paths, host, name, false), + ["host", "install", host] => commands::install_controller(&paths, host), + ["host", "type", host, given] => commands::set_type(&paths, host, given), + ["host", "rename", host, name] => commands::rename(&paths, host, name, false), ["host", "rename", host, name, "--hostname"] | ["host", "rename", host, "--hostname", name] => { - return commands::rename(&paths, host, name, true); + commands::rename(&paths, host, name, true) } - ["host", host, ref rest @ ..] => return host_command(&paths, host, rest), + ["host", host, ref rest @ ..] => host_command(&paths, host, rest), ["--version" | "-V" | "version"] => { println!("berth {}", berth_api::VERSION); - return Ok(()); + Ok(()) } - ["update", ref rest @ ..] => return update::command(rest), - ["serve", ref rest @ ..] => return serve::command(&paths, rest), - ["ui"] => return screens(None), - ["ui", host] => return screens(Some(host)), - ["setup-key", ref rest @ ..] => return serve::setup_key::command(&paths, rest), - ["connect", url] => return commands::connect(&paths, url), - ["inbox", ref rest @ ..] => return serve::inbox_command(&paths, rest), - ["kv", ref rest @ ..] => return serve::kv_command(&paths, rest), - ["store", ref rest @ ..] => return store_command::command(&paths, rest), + ["update", ref rest @ ..] => update::command(rest), + ["serve", ref rest @ ..] => serve::command(&paths, rest), + ["setup-key", ref rest @ ..] => serve::setup_key::command(&paths, rest), + ["connect", url] => commands::connect(&paths, url), + ["inbox", ref rest @ ..] => serve::inbox_command(&paths, rest), + ["kv", ref rest @ ..] => serve::kv_command(&paths, rest), + ["store", ref rest @ ..] => store_command::command(&paths, rest), ["openapi"] => { println!("{}", serde_json::to_string_pretty(&serve::openapi())?); - return Ok(()); + Ok(()) } ["operations"] => { println!("{}", serde_json::to_string_pretty(&serve::operations())?); - return Ok(()); + Ok(()) } ["asyncapi"] => { println!("{}", serde_json::to_string_pretty(&serve::asyncapi())?); - return Ok(()); + Ok(()) } ["plugins"] => { let listing = plugins::Manager::new(&paths).list()?; print!("{}", plugins::describe(&listing.plugins)); - return Ok(()); + Ok(()) } ["plugins", "add", spec] => { for line in plugins::Manager::new(&paths).add(spec)? { println!("{line}"); } - return Ok(()); + Ok(()) } - ["plugins", "update", ref rest @ ..] => return commands::update_plugins(&paths, rest), + ["plugins", "update", ref rest @ ..] => commands::update_plugins(&paths, rest), ["plugins", "remove", name] => { let manager = plugins::Manager::new(&paths); // A name npm knows that berth does not, such as a broken package. @@ -817,554 +623,86 @@ fn run() -> Result<()> { for line in manager.remove(name)? { println!("{line}"); } - return Ok(()); + Ok(()) } - ["config"] => return show_config(&paths), - ["config", key] => return change_setting(&paths, key, ""), - ["config", key, value] => return change_setting(&paths, key, value), + ["config"] => show_config(&paths), + ["config", key] => change_setting(&paths, key, ""), + ["config", key, value] => change_setting(&paths, key, value), ["tailnet-key", host] => { // An apply runs this on the machine that runs berth, for a host // not on the tailnet yet; the key goes to the role on stdout. println!("{}", berth_core::tailnet::key_for(&paths, host)?); - return Ok(()); + Ok(()) } - ["profile", host] => return commands::show_profile(&paths, host), - ["profile", host, "--set", file] => return commands::set_profile(&paths, host, file), - ["credentials", host] => return commands::credentials(&paths, host, false), + ["profile", host] => commands::show_profile(&paths, host), + ["profile", host, "--set", file] => commands::set_profile(&paths, host, file), + ["credentials", host] => commands::credentials(&paths, host, false), ["credentials", host, "--show"] | ["credentials", "--show", host] => { - return commands::credentials(&paths, host, true); - } - ["iso", host] => return build_installer(&paths, host, None), - ["iso", host, "--write", device] => return build_installer(&paths, host, Some(device)), - ["key", ref rest @ ..] => return key_command::command(&paths, rest), - ["apply", "--behind" | "--all", ..] => return commands::apply_hosts(&paths, &args[1..]), - ["apply", host] => return commands::apply(&paths, host), - ["remove", host] => return commands::remove(&paths, host), - ["adopt", host, ref rest @ ..] => return commands::adopt(&paths, host, rest), - ["provisioners"] => return commands::provisioners(&paths), - ["provisioner", ref rest @ ..] => return provisioner_command::command(&paths, rest), + commands::credentials(&paths, host, true) + } + ["iso", host] => commands::installer(&paths, host, None), + ["iso", host, "--write", device] => commands::installer(&paths, host, Some(device)), + ["key", ref rest @ ..] => key_command::command(&paths, rest), + ["apply", "--behind" | "--all", ..] => commands::apply_hosts(&paths, &args[1..]), + ["apply", host] => commands::apply(&paths, host), + ["remove", host] => commands::remove(&paths, host), + ["adopt", host, ref rest @ ..] => commands::adopt(&paths, host, rest), + ["provisioners"] => commands::provisioners(&paths), + ["provisioner", ref rest @ ..] => provisioner_command::command(&paths, rest), ["provision", host, provisioner, ref rest @ ..] => { - return resource_command::provision(&paths, host, provisioner, rest); - } - ["instance", host, ref rest @ ..] => return resource_command::instance(&paths, host, rest), - ["resource", ref rest @ ..] => return resource_command::command(&paths, rest), - ["deploy", name, ref rest @ ..] => return resource_command::deploy(&paths, name, rest), - ["seed", host] if berth_core::server::Server::configured(&paths).is_some() => { - return commands::seed(&paths, host); + resource_command::provision(&paths, host, provisioner, rest) } - ["seed", host] => { - let mut app = open(&paths, host)?; - app.action = Action::CloudSeed; - require_ready(&app)?; - return app.execute(); - } - ["actions", host] => return commands::actions(&paths, host), + ["instance", host, ref rest @ ..] => resource_command::instance(&paths, host, rest), + ["resource", ref rest @ ..] => resource_command::command(&paths, rest), + ["deploy", name, ref rest @ ..] => resource_command::deploy(&paths, name, rest), + ["seed", host] => commands::seed(&paths, host), + ["actions", host] => commands::actions(&paths, host), ["run" | "manage", host, action, ref rest @ ..] => { - return commands::run(&paths, host, action, rest); - } - ["exec", host, ref rest @ ..] => return commands::exec(&paths, host, rest), - ["attach", host] => return commands::attach(&paths, host, None), - ["attach", host, id] => return commands::attach(&paths, host, Some(id)), - ["sessions", host] => return commands::sessions(&paths, host), - ["output", host, id, ref rest @ ..] => return commands::output(&paths, host, id, rest), - ["channel", host, ref rest @ ..] => return commands::channel(&paths, host, rest), - ["call", host, service, method] => { - return commands::call(&paths, host, service, method, None); - } + commands::run(&paths, host, action, rest) + } + ["exec", host, ref rest @ ..] => commands::exec(&paths, host, rest), + ["attach", host] => commands::attach(&paths, host, None), + ["attach", host, id] => commands::attach(&paths, host, Some(id)), + ["sessions", host] => commands::sessions(&paths, host), + ["output", host, id, ref rest @ ..] => commands::output(&paths, host, id, rest), + ["channel", host, ref rest @ ..] => commands::channel(&paths, host, rest), + ["call", host, service, method] => commands::call(&paths, host, service, method, None), ["call", host, service, method, body] => { - return commands::call(&paths, host, service, method, Some(body)); + commands::call(&paths, host, service, method, Some(body)) } - ["inventory", ref hosts @ ..] => return commands::inventory(&paths, hosts), + ["inventory", ref hosts @ ..] => commands::inventory(&paths, hosts), ["ssh", host, "--agent"] | ["ssh", "--agent", host] => { - let status = open(&paths, host)?.agent_terminal()?.status()?; + let status = commands::agent_terminal(&paths, host)?.status()?; std::process::exit(status.code().unwrap_or(1)); } ["ssh", host, ref remote @ ..] => { - let status = open(&paths, host)?.terminal(remote)?.status()?; + let status = commands::terminal(&paths, host, remote)?.status()?; std::process::exit(status.code().unwrap_or(1)); } - [] => None, - [host] if !host.starts_with('-') && host != "help" => Some(host.to_owned()), _ => { println!("{USAGE}"); - return Ok(()); - } - }; - { - use std::io::IsTerminal; - if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() { - return Err(no_terminal(&paths, host.as_deref()).into()); + Ok(()) } } - // Find the source before the screen is taken over, so the error is readable. - paths.source()?; - if let Some(running) = &mut mirroring { - running.start(); - } - let mut terminal = enter()?; - let outcome = (|| -> Result<()> { - loop { - let name = match &host { - Some(host) => host.clone(), - None => match ui::home(&mut terminal, &paths, &mut mirroring)? { - Some(name) => name, - None => return Ok(()), - }, - }; - let mut app = open(&paths, &name)?; - app.start(); - // Terminal actions (Ansible) suspend the UI and come back to it. - while ui::run(&mut terminal, &mut app, &mut mirroring)? { - leave(); - match app.execute() { - Ok(()) => println!("\nDone."), - Err(error) => println!("\n{error}"), - } - println!("Press Enter to return to berth."); - let _ = std::io::stdin().read_line(&mut String::new()); - terminal = enter()?; - // A host renamed meanwhile is opened again under its new name. - if let Some(new) = app.renamed.take() { - app = open(&paths, &new)?; - app.start(); - } - } - if host.is_some() { - return Ok(()); - } - } - })(); - leave(); - outcome } #[cfg(test)] mod tests { - use super::opens_screen; + use super::opens_screens; #[test] - fn only_the_screen_opens_before_the_mirror_is_made() { - assert!(opens_screen(&[]) && opens_screen(&["studio"])); - assert!(!opens_screen(&["list"]) && !opens_screen(&["--version"])); - assert!(!opens_screen(&["run", "studio", "status"])); - } - - use super::*; - use crate::fields::{Action, Field, Step}; - use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers}; - use tui_input::{Input, backend::crossterm::EventHandler}; - - /// Paths of a folder that is never made, for an app that saves nothing. - fn nowhere() -> Paths { - Paths { - config_dir: "/nonexistent/berth-test/config".into(), - data_dir: "/nonexistent/berth-test/data".into(), - } - } - - /// An app of a new profile that is never saved, in a file whose name is - /// no host name, so that the profile needs a hostname of its own. - fn app(config: &str) -> App { - App::new( - nowhere(), - berth_core::profiles::Place::File("/nonexistent/berth-test/new profile.json".into()), - parse_config(config.as_bytes()).unwrap(), - ) - } - - fn selectable(app: &App) -> Vec { - app.rows() - .iter() - .enumerate() - .filter_map(|(position, row)| row.entry.map(|_| position)) - .collect() - } - - fn demo_plugin() -> plugins::Plugin { - let feature = |id: &str, group: &str, action: &str| plugins::Feature { - id: id.into(), - group: group.into(), - label: id.into(), - help: "", - actions: vec![plugins::PluginAction { - name: action.into(), - label: "Say hello".into(), - help: "", - run: "echo 'hi'".into(), - user: "agent".into(), - terminal: false, - group: String::new(), - extends: vec![], - agent: false, - arguments: vec![], - confirm: None, - }], - services: vec![], - channels: vec![], - }; - plugins::Plugin { - id: "demo".into(), - label: "Demo".into(), - package: "berth-plugin-demo".into(), - version: "1.0.0".into(), - description: String::new(), - dir: "/plugins/demo".into(), - found: "/plugins/demo".into(), - features: vec![ - feature("one", "development tools", "hello"), - feature("two", "Games", "other"), - ], - provisioners: vec![], - } - } - - #[test] - fn plugin_features_join_groups() { - use app::{Entry, Item}; - let mut app = app(r#"{"access":{"address":"box"},"builder":{"shipped_plugins":true}}"#); - app.set_plugins(vec![demo_plugin()]); - app.step = Step::Features; - let groups = app.feature_groups(); - // One feature joins a built-in group, the other brings its own. The - // groups of the coding agents are not shown without their plugins. - assert_eq!(groups[0].title, "Development Tools"); - assert_eq!(groups[0].items.last(), Some(&Item::Feature(0))); - assert_eq!(groups.last().unwrap().title, "Games"); - assert_eq!(groups.last().unwrap().items, [Item::Feature(1)]); - - // Chosen out of order, stored in the plugin's order. - app.set_item(Item::Feature(1), true); - app.set_item(Item::Feature(0), true); - assert_eq!( - app.config["ansible_vars"]["devbox_plugin_features"], - json!(["demo/one", "demo/two"]) - ); - // What the features can do on the host is the host's to say: the - // overview has no rows for them until it has been asked. - app.set_step(Step::Manage); - assert!( - !app.entries() - .iter() - .any(|entry| matches!(entry, Entry::HostAction(_))) - ); - app.set_item(Item::Feature(0), false); - assert_eq!( - app.config["ansible_vars"]["devbox_plugin_features"], - json!(["demo/two"]) - ); - } - - #[test] - fn old_agent_switches_become_plugin_features() { - // Everything was on unless switched off; T3 followed the agents. - let features = |config: &str| app(config).config["ansible_vars"].clone(); - assert_eq!( - features("{}")["devbox_plugin_features"], - json!([ - "claude/cli", - "codex/cli", - "github/cli", - "pi/cli", - "t3/server" - ]) - ); - let old = features( - r#"{"ansible_vars": {"devbox_agent_codex": false, "devbox_install_t3": false, - "devbox_plugin_features": ["unity/cli"], "devbox_tools_web": true}}"#, - ); - assert_eq!( - old, - json!({"devbox_tools_web": true, - "devbox_plugin_features": ["claude/cli", "github/cli", "pi/cli", "unity/cli"]}) - ); - let none = features(r#"{"ansible_vars": {"devbox_install_agents": false}}"#); - assert_eq!(none["devbox_plugin_features"], json!(["github/cli"])); - // Done once: what is switched off afterwards stays off. - let kept = features( - r#"{"builder": {"shipped_plugins": true}, "ansible_vars": {"devbox_plugin_features": []}}"#, - ); - assert_eq!(kept["devbox_plugin_features"], json!([])); - } - - #[test] - fn groups_are_selectable_and_switch_everything_in_them() { - use app::Entry; - let mut app = app(r#"{"builder":{"shipped_plugins":true}}"#); - app.set_plugins(vec![demo_plugin()]); - app.step = Step::Features; - let rows = app.rows(); - assert!( - rows[0] - .line - .to_string() - .starts_with("Development Tools 6 of 7") - ); - assert_eq!(rows[0].entry, Some(Entry::Group(0))); - assert!(rows[7].line.to_string().starts_with(" └─ one")); - - // Not everything is on, so the group is switched on first, then off. - assert!(!app.group_all_on(0)); - app.toggle_group(0); - assert!(app.group_all_on(0)); - assert_eq!( - app.config["ansible_vars"]["devbox_plugin_features"], - json!(["demo/one"]) - ); - app.toggle_group(0); - assert!(!app.enabled(Field::ToolsWeb) && !app.enabled(Field::ToolsScientific)); - assert_eq!( - app.config["ansible_vars"]["devbox_plugin_features"], - json!([]) - ); - - // The accounts on the Settings tab start with a heading. - app.step = Step::Settings; - assert_eq!(selectable(&app)[0], 1); - app.action = Action::Docker; - assert_eq!(app.fields(), [Field::AgentUser]); - } - - #[test] - fn settings_follow_the_action_and_disk_mode() { - let mut app = app("{}"); - app.step = Step::Install; - app.action = Action::Docker; - assert!(app.fields().is_empty()); - // What an installer picks the disk and network with has defaults. - app.action = Action::UsbSeed; - assert!(!app.fields().contains(&Field::DiskMode)); - app.step = Step::Settings; - assert!(app.fields().contains(&Field::DiskType)); - assert!(!app.fields().contains(&Field::DiskSerial)); - assert!(!app.fields().contains(&Field::WifiSsid)); - app.commit(Field::DiskMode, "serial"); - app.activate(Field::Wifi); - let fields = app.fields(); - assert!(fields.contains(&Field::DiskSerial) && !fields.contains(&Field::DiskType)); - assert!(fields.contains(&Field::WifiSsid)); - app.step = Step::Install; - app.action = Action::Ssh; - assert!(app.fields().contains(&Field::SshHost)); - assert!(!app.fields().contains(&Field::Hostname)); - } - - #[test] - fn new_profiles_default_to_auto_with_wifi_off() { - let config = parse_config(br#"{}"#).unwrap(); - assert_eq!(config["target_disk_mode"], "auto"); - assert_eq!(config["wifi_enabled"], false); - assert!(config.get("operator_passwordless_sudo").is_none()); - assert!(config["access"]["sudo"].is_null()); - // The switches of a profile from before are dropped, whatever they said. - let old = parse_config(br#"{"operator_passwordless_sudo": false, "berth_ssh_key": false}"#) - .unwrap(); - assert!( - old.get("operator_passwordless_sudo").is_none() && old.get("berth_ssh_key").is_none() - ); - let legacy = parse_config( - br#"{"target_disk_serial":"OLD_SSD","wifi":{"ssid":"saved"}, - "release_url":"https://REPLACE.example/x"}"#, - ) - .unwrap(); - assert_eq!(legacy["target_disk_mode"], "serial"); - assert_eq!(legacy["wifi_enabled"], true); - assert_eq!(legacy["release_url"], ""); - // A profile of the qemu target there once was shows as cloud, reached from the QEMU host. - let qemu = parse_config(br#"{"target": "qemu"}"#).unwrap(); - assert_eq!(qemu["target"], "cloud"); - assert_eq!( - qemu["ansible_vars"]["devbox_bootstrap_ssh_cidr"], - "10.0.2.2/32" - ); - let app = app(r#"{"target": "qemu"}"#); - assert_eq!(app.text(Field::RecoveryCidr), "10.0.2.2/32"); - } - - #[test] - fn asking_for_the_sudo_password_is_off_until_chosen() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("studio.json"); - let profile = r#"{"access":{"address":"192.0.2.10","user":"ops"}}"#; - let paths = Paths { - config_dir: directory.path().join("config"), - data_dir: directory.path().join("data"), - }; - let mut app = App::new( - paths, - berth_core::profiles::Place::File(path.clone()), - parse_config(profile.as_bytes()).unwrap(), - ); - // An edit elsewhere leaves it unset. - app.commit(Field::Hostname, "studio"); - app.save().unwrap(); - let host = |path: &std::path::Path| berth_core::host::Host { - name: "studio".into(), - place: berth_core::profiles::Place::File(path.to_owned()), - config: serde_json::from_slice(&fs::read(path).unwrap()).unwrap(), - }; - assert!(!app.enabled(Field::AskBecomePass)); - assert!(!host(&path).asks_password()); - assert!(app.config["builder"]["ask_become_pass"].is_null()); - // A first apply as an account whose sudo asks for a password. - app.activate(Field::AskBecomePass); - app.save().unwrap(); - assert!(app.enabled(Field::AskBecomePass) && host(&path).asks_password()); - // Once chosen, the choice stays. - app.activate(Field::AskBecomePass); - app.save().unwrap(); - assert!(!app.enabled(Field::AskBecomePass) && !host(&path).asks_password()); - assert_eq!(app.config["access"]["sudo"], "none"); - } - - #[test] - fn edits_land_in_the_profile() { - let mut app = app(r#"{"ansible_vars":{"devbox_install_dev_tools":false}}"#); - app.commit(Field::WifiSsid, " home "); - assert_eq!(app.config["wifi"]["ssid"], "home"); - app.commit(Field::WifiSsid, ""); - assert!(app.config["wifi"].is_null()); - - app.commit(Field::Geometry, "1920x1080"); - assert_eq!(app.config["ansible_vars"]["devbox_geometry"], "1920x1080"); - app.commit(Field::Geometry, ""); - assert!(app.config["ansible_vars"].get("devbox_geometry").is_none()); - - // Tool categories inherit the older single switch until set themselves. - assert!(!app.enabled(Field::ToolsJvm)); - assert!(app.enabled(Field::Docker)); - app.activate(Field::ToolsJvm); - assert_eq!(app.config["ansible_vars"]["devbox_tools_jvm"], true); - - app.activate(Field::Target); - assert_eq!(app.text(Field::Target), "cloud"); - app.commit(Field::Target, "desktop"); - assert_eq!(app.text(Field::Target), "cloud"); - assert!(app.unsaved()); - } - - #[test] - fn review_reports_what_would_fail() { - let mut app = app("{}"); - app.action = Action::Save; - assert!(app.problems().is_empty()); - app.action = Action::UsbSeed; - let problems = app.problems().join("\n"); - assert!(problems.contains("Hostname")); - assert!(problems.contains("Operator needs an SSH key")); - assert!(problems.contains("Operator password is required")); - // The key of this berth is one, which an older profile cannot turn down. - app.own_public = "ssh-ed25519 AAAA berth@here".into(); - assert!(!app.problems().join("\n").contains("SSH key")); - app.config["berth_ssh_key"] = json!(false); - assert!(!app.problems().join("\n").contains("SSH key")); - app.config.as_object_mut().unwrap().remove("berth_ssh_key"); - app.own_public.clear(); - - app.config["hostname"] = json!("devbox-1"); - app.config["operator_ssh_public_key"] = json!("ssh-ed25519 AAAA me"); - app.config["operator_password_hash"] = json!(format!("$6$salt${}", "a".repeat(86))); - assert_eq!(app.problems(), Vec::::new()); - - // An agent without a privilege level types a password for sudo, so it needs one. - app.commit(Field::AgentPrivileges, "limited"); - app.activate(Field::AgentSudo); - assert_eq!(app.problems(), Vec::::new()); - app.config["agent_privileges"] = json!(null); - assert_eq!(app.problems().len(), 1); - app.activate(Field::AgentSudo); - app.commit(Field::AgentUser, "ops"); - assert_eq!(app.problems().len(), 1); - // Ubuntu already has a system group with this name, so the account cannot be created. - app.commit(Field::AgentUser, "operator"); - assert_eq!(app.problems().len(), 1); - app.commit(Field::AgentUser, "agent"); - - // Only the USB installer insists on an operator password. - let hash = app.config["operator_password_hash"].take(); - assert_eq!(app.problems(), ["Operator password is required (F4 or F5)"]); - app.action = Action::CloudSeed; - assert!(!app.problems().join("\n").contains("password")); - app.action = Action::UsbSeed; - app.config["operator_password_hash"] = hash; - - // A cloud seed needs somewhere to get the release from, but no SSH network. - app.action = Action::CloudSeed; - assert_eq!(app.problems().len(), 1); - let step = std::mem::replace(&mut app.step, Step::Settings); - assert!(app.fields().contains(&Field::ReleaseUrl)); - app.config["release_store"] = json!("nexus/releases"); - assert!(app.problems().is_empty()); - assert!(app.fields().contains(&Field::ReleasePrivate)); - assert!(!app.fields().contains(&Field::ReleaseUrl)); - app.step = step; - app.action = Action::Ssh; - assert_eq!(app.problems().len(), 1); - app.commit(Field::SshPort, "22"); - app.config["access"]["address"] = json!("devbox.example"); - assert!(app.problems().is_empty()); - } - - #[test] - fn choosing_an_iso_records_its_checksum() { - let directory = tempfile::tempdir().unwrap(); - let iso = directory.path().join("ubuntu.iso"); - fs::write(&iso, "abc").unwrap(); - let mut app = app("{}"); - app.commit(Field::Iso, iso.to_str().unwrap()); - assert_eq!( - app.text(Field::IsoSha), - "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" - ); - } - - #[test] - fn wifi_logins_come_from_and_are_checked_against_this_machine() { - let mut app = app("{}"); - app.wifi_networks = vec![("home".into(), "secret".into()), ("cafe".into(), "".into())]; - app.commit(Field::WifiSsid, "cafe"); - assert_eq!(app.text(Field::WifiPassword), ""); - assert_eq!(app.wifi_password_matches(), None); - app.commit(Field::WifiSsid, "home"); - assert_eq!(app.text(Field::WifiPassword), "secret"); - assert_eq!(app.wifi_password_matches(), Some(true)); - app.commit(Field::WifiPassword, "typo"); - assert_eq!(app.wifi_password_matches(), Some(false)); - assert!(app.status.contains("Differs")); - } - - #[test] - fn input_widget_inserts_and_deletes_at_cursor() { - let mut input = Input::new("abde".into()); - for code in [ - KeyCode::Home, - KeyCode::Right, - KeyCode::Right, - KeyCode::Char('c'), - KeyCode::Delete, - KeyCode::End, - KeyCode::Backspace, + fn the_screens_open_with_no_command_or_a_host() { + assert_eq!(opens_screens(&[]), Some(None)); + assert_eq!(opens_screens(&["ui"]), Some(None)); + assert_eq!(opens_screens(&["studio"]), Some(Some("studio"))); + assert_eq!(opens_screens(&["ui", "dock"]), Some(Some("dock"))); + for command in [ + &["list"][..], + &["--version"], + &["run", "studio", "status"], + &["help"], ] { - input.handle_event(&Event::Key(KeyEvent::new(code, KeyModifiers::NONE))); + assert_eq!(opens_screens(command), None, "{command:?}"); } - assert_eq!(input.value(), "abc"); - assert_eq!(input.cursor(), 3); - } - - #[test] - fn discovers_custom_public_key_names_and_config_includes() { - let directory = tempfile::tempdir().unwrap(); - let write = |name: &str, content: &str| { - fs::write(directory.path().join(name), content).unwrap(); - }; - write("storage.pub", "ssh-ed25519 AAAATEST storage\n"); - write("rsa.pub", "ssh-rsa AAAATEST laptop\n"); - write("invalid.pub", "not a key"); - write("config", "Include config.d/*\nHost main * !excluded\n"); - fs::create_dir(directory.path().join("config.d")).unwrap(); - write("config.d/cloud", "Host cloud-server\n User operator\n"); - let (public, _) = discovery::keys(directory.path()); - assert_eq!(public.len(), 2); - assert!(public.iter().any(|(_, key)| key.ends_with("storage"))); - assert_eq!(discovery::hosts(&directory.path().join("config")).len(), 2); } } diff --git a/crates/berth/src/mirror.rs b/crates/berth/src/mirror.rs deleted file mode 100644 index 2e49772..0000000 --- a/crates/berth/src/mirror.rs +++ /dev/null @@ -1,102 +0,0 @@ -//! The mirror of a berth server, made while the screen is open. The server -//! may wait many seconds for a host that does not answer, and the screen -//! shows what the last mirror left until the new one is there. - -use std::sync::{ - Arc, - mpsc::{Receiver, TryRecvError, channel}, -}; - -/// What making a mirror comes to: nothing to say, or why it failed. -pub type Made = Result<(), String>; - -/// A mirror being made on a thread of its own, at most one at a time. -pub struct Mirroring { - make: Arc Made + Send + Sync>, - running: Option>, -} - -impl Mirroring { - /// `make` is the work of one mirror. - pub fn new(make: impl Fn() -> Made + Send + Sync + 'static) -> Mirroring { - Mirroring { - make: Arc::new(make), - running: None, - } - } - - /// The mirror of the berth server this berth uses. - pub fn of(paths: &berth_core::paths::Paths, server: berth_core::server::Server) -> Mirroring { - let paths = paths.clone(); - Mirroring::new(move || { - server - .mirror(&paths) - .map_err(|error| format!("the berth server at {}: {error}", server.url)) - }) - } - - /// Start a mirror, unless one is under way. Returns whether it started. - pub fn start(&mut self) -> bool { - if self.running.is_some() { - return false; - } - let (sender, receiver) = channel(); - let make = self.make.clone(); - std::thread::spawn(move || { - let _ = sender.send(make()); - }); - self.running = Some(receiver); - true - } - - pub fn running(&self) -> bool { - self.running.is_some() - } - - /// How the mirror ended, once, when it has. - pub fn finished(&mut self) -> Option { - let receiver = self.running.as_ref()?; - let made = match receiver.try_recv() { - Ok(made) => made, - Err(TryRecvError::Empty) => return None, - Err(TryRecvError::Disconnected) => Err("the mirror stopped without an answer".into()), - }; - self.running = None; - Some(made) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; - - #[test] - fn one_mirror_runs_at_a_time_and_its_end_is_told_once() { - let (release, wait) = channel::<()>(); - let wait = std::sync::Mutex::new(wait); - let made = Arc::new(AtomicUsize::new(0)); - let count = made.clone(); - let mut mirroring = Mirroring::new(move || { - count.fetch_add(1, Ordering::SeqCst); - wait.lock() - .unwrap() - .recv() - .map_err(|error| error.to_string()) - }); - assert!(mirroring.start() && mirroring.running()); - // Asking again while it runs starts nothing, and nothing has ended. - assert!(!mirroring.start()); - assert!(mirroring.finished().is_none()); - release.send(()).unwrap(); - let ended = loop { - if let Some(ended) = mirroring.finished() { - break ended; - } - std::thread::yield_now(); - }; - assert_eq!(ended, Ok(())); - assert!(mirroring.finished().is_none() && !mirroring.running()); - assert_eq!(made.load(Ordering::SeqCst), 1); - } -} diff --git a/crates/berth/src/picker.rs b/crates/berth/src/picker.rs deleted file mode 100644 index 5313ef5..0000000 --- a/crates/berth/src/picker.rs +++ /dev/null @@ -1,109 +0,0 @@ -use crate::{Result, discovery::expand_path, theme}; -use ratatui::{ - layout::Rect, - style::Style, - widgets::{Clear, List, ListState}, -}; -use std::{fs, path::PathBuf}; - -pub struct Picker { - pub directory: PathBuf, - pub entries: Vec, - pub state: ListState, - pub area: Rect, -} - -impl Picker { - pub fn new(value: &str) -> Result { - let path = expand_path(value); - let directory = if path.is_dir() { - path - } else { - path.parent() - .filter(|p| p.is_dir()) - .unwrap_or(std::path::Path::new(".")) - .to_owned() - }; - let mut picker = Self { - directory, - entries: vec![], - state: ListState::default(), - area: Rect::default(), - }; - picker.reload()?; - Ok(picker) - } - fn reload(&mut self) -> Result<()> { - self.directory = self.directory.canonicalize()?; - let mut entries = fs::read_dir(&self.directory)? - .filter_map(|entry| entry.ok().map(|e| e.path())) - .collect::>(); - entries.sort_by_key(|path| (!path.is_dir(), path.file_name().map(|n| n.to_owned()))); - self.entries = self - .directory - .parent() - .map(|p| vec![p.to_owned()]) - .unwrap_or_default(); - self.entries.extend(entries); - self.state = ListState::default().with_selected(Some(0)); - Ok(()) - } - pub fn choose(&mut self) -> Result> { - let Some(path) = self - .entries - .get(self.state.selected().unwrap_or(0)) - .cloned() - else { - return Ok(None); - }; - if path.is_dir() { - self.directory = path; - self.reload()?; - Ok(None) - } else { - Ok(Some(path.display().to_string())) - } - } - pub fn move_by(&mut self, up: bool) { - let index = self.state.selected().unwrap_or(0); - self.state.select(Some(if up { - index.saturating_sub(1) - } else { - (index + 1).min(self.entries.len().saturating_sub(1)) - })); - } - pub fn draw(&mut self, frame: &mut ratatui::Frame) { - self.area = frame.area().inner(ratatui::layout::Margin { - horizontal: 4, - vertical: 3, - }); - frame.render_widget(Clear, self.area); - let entries = self - .entries - .iter() - .map(|path| { - let name = if path == self.directory.parent().unwrap_or(&self.directory) { - "..".into() - } else { - path.file_name() - .unwrap_or_default() - .to_string_lossy() - .into_owned() - }; - format!("{} {name}", if path.is_dir() { "▸" } else { " " }) - }) - .collect::>(); - frame.render_stateful_widget( - List::new(entries) - .block( - theme::popup(&self.directory.display().to_string(), theme::ACCENT) - .title_bottom(theme::hints( - "Enter open/select · Ctrl+Enter use directory · Esc cancel", - )), - ) - .highlight_style(Style::new().bg(theme::RAISED)), - self.area, - &mut self.state, - ); - } -} diff --git a/crates/berth/src/profile.rs b/crates/berth/src/profile.rs new file mode 100644 index 0000000..26db6eb --- /dev/null +++ b/crates/berth/src/profile.rs @@ -0,0 +1,226 @@ +//! A host's profile as berth reads and keeps it, for the commands that +//! change one. + +use crate::Result; +use berth_core::{paths::Paths, profiles::Place}; +use serde_json::{Value, json}; + +/// The saved profile of `name`, and where it is kept. +pub fn load(paths: &Paths, name: &str) -> Result<(Place, Value)> { + let place = Place::resolve(paths, name)?; + let profile = place + .load(paths)? + .ok_or_else(|| format!("No host {name}. See: berth list"))?; + Ok((place, profile)) +} + +/// Keep `profile` as the host's: on the berth server it belongs to as well, +/// for one of a server. Says where it is kept. +pub fn save(paths: &Paths, place: &Place, mut profile: Value) -> Result { + if let Some(url) = place.server_url() { + let server = berth_core::server::Server::configured(paths) + .filter(|server| server.url == url) + .ok_or("The berth server of this host is not set any more")?; + server.save_host(&place.title(), &profile)?; + profile["builder"]["served"] = json!(url); + } + place.save(paths, &profile)?; + Ok(format!("Saved {}", place.describe())) +} + +/// Read a profile and fill in what a profile of berth has: the defaults of a +/// new one, and the names of now for those of older berths. +pub fn parse_config(data: &[u8]) -> Result { + let mut config: Value = serde_json::from_slice(data)?; + if !config.is_object() { + return Err("Configuration must be a JSON object".into()); + } + berth_api::profile::take_old_names(&mut config); + berth_api::profile::retire_qemu(&mut config); + for field in ["wifi", "ansible_vars", "builder"] { + if !config[field].is_null() && !config[field].is_object() { + return Err(format!("{field} must be a JSON object or null").into()); + } + } + for key in ["ansible_vars", "builder"] { + if config[key].is_null() { + config[key] = json!({}); + } + } + for (key, value) in [ + ("target", json!("laptop")), + ("keyboard", json!("de")), + ("operator_username", json!("ops")), + ("agent_username", json!("agent")), + ("agent_passwordless_sudo", json!(true)), + ("target_disk_ssd", json!("any")), + ] { + if config[key].is_null() { + config[key] = value; + } + } + // Placeholders from older example profiles count as unset. + for key in [ + "operator_password_hash", + "target_disk_serial", + "release_url", + ] { + if config[key].as_str().is_some_and(|v| v.contains("REPLACE")) { + config[key] = json!(""); + } + } + if config["target_disk_mode"].is_null() { + let has_serial = config["target_disk_serial"] + .as_str() + .is_some_and(|serial| !serial.is_empty()); + config["target_disk_mode"] = json!(if has_serial { "serial" } else { "auto" }); + } + if config["wifi_enabled"].is_null() { + let configured = config["wifi"].as_object().is_some_and(|w| !w.is_empty()); + config["wifi_enabled"] = json!(configured); + } + // The coding agents, T3 Code and GitHub's CLI were switches once and are + // features of plugins that come with berth now. They go first: later + // plugins, such as Unity's, set themselves up for the agents they find. + // Only a profile of that layout is converted: one with the old switches, + // or one with no list of features at all, which had every switch on. A + // profile that lists its features is left as it is, marked or not. + const OLD_AGENT_SWITCHES: [&str; 5] = [ + "devbox_install_agents", + "devbox_agent_claude", + "devbox_agent_codex", + "devbox_agent_pi", + "devbox_install_t3", + ]; + let old_layout = OLD_AGENT_SWITCHES + .iter() + .any(|key| !config["ansible_vars"][*key].is_null()) + || config["ansible_vars"]["devbox_plugin_features"].is_null(); + if config["builder"]["shipped_plugins"] != true && old_layout { + let vars = &config["ansible_vars"]; + let on = |key: &str, default: bool| vars[key].as_bool().unwrap_or(default); + let agents = on("devbox_install_agents", true); + let mut features: Vec = [ + ("claude/cli", agents && on("devbox_agent_claude", true)), + ("codex/cli", agents && on("devbox_agent_codex", true)), + ("github/cli", true), + ("pi/cli", agents && on("devbox_agent_pi", true)), + ("t3/server", on("devbox_install_t3", agents)), + ] + .into_iter() + .filter(|(_, chosen)| *chosen) + .map(|(feature, _)| json!(feature)) + .collect(); + for feature in vars["devbox_plugin_features"] + .as_array() + .into_iter() + .flatten() + { + if !features.contains(feature) { + features.push(feature.clone()); + } + } + if !config["ansible_vars"].is_object() { + config["ansible_vars"] = json!({}); + } + let vars = config["ansible_vars"].as_object_mut().unwrap(); + for old in OLD_AGENT_SWITCHES { + vars.remove(old); + } + vars.insert("devbox_plugin_features".into(), json!(features)); + config["builder"]["shipped_plugins"] = json!(true); + } + // Profiles from before the privilege levels keep what they had: sudo for + // everything without a password is `full`. One whose agent types a + // password stays as it is until a level is chosen. + if config["agent_privileges"].is_null() && config["agent_passwordless_sudo"] == true { + config["agent_privileges"] = json!("full"); + } + // The action last run from the overview was kept once; the host lists its own now. + if let Some(builder) = config["builder"].as_object_mut() { + builder.remove("manage_task"); + } + // Device names change between sessions, so the drive to write is chosen each time. + if let Some(builder) = config["builder"].as_object_mut() { + builder.remove("usb_device"); + } + // The operator always has sudo without a password and always takes the key + // of berth; profiles once had switches for both. + if let Some(profile) = config.as_object_mut() { + profile.remove("operator_passwordless_sudo"); + profile.remove("berth_ssh_key"); + } + let problems = berth_api::profile::Access::problems(&config); + if !problems.is_empty() { + return Err(problems.join("; ").into()); + } + Ok(config) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn old_agent_switches_become_plugin_features() { + // Everything was on unless switched off; T3 followed the agents. + let features = + |config: &str| parse_config(config.as_bytes()).unwrap()["ansible_vars"].clone(); + assert_eq!( + features("{}")["devbox_plugin_features"], + json!([ + "claude/cli", + "codex/cli", + "github/cli", + "pi/cli", + "t3/server" + ]) + ); + let old = features( + r#"{"ansible_vars": {"devbox_agent_codex": false, "devbox_install_t3": false, + "devbox_plugin_features": ["unity/cli"], "devbox_tools_web": true}}"#, + ); + assert_eq!( + old, + json!({"devbox_tools_web": true, + "devbox_plugin_features": ["claude/cli", "github/cli", "pi/cli", "unity/cli"]}) + ); + let none = features(r#"{"ansible_vars": {"devbox_install_agents": false}}"#); + assert_eq!(none["devbox_plugin_features"], json!(["github/cli"])); + // Done once: what is switched off afterwards stays off. + let kept = features( + r#"{"builder": {"shipped_plugins": true}, "ansible_vars": {"devbox_plugin_features": []}}"#, + ); + assert_eq!(kept["devbox_plugin_features"], json!([])); + } + + #[test] + fn new_profiles_default_to_auto_with_wifi_off() { + let config = parse_config(br#"{}"#).unwrap(); + assert_eq!(config["target_disk_mode"], "auto"); + assert_eq!(config["wifi_enabled"], false); + assert!(config.get("operator_passwordless_sudo").is_none()); + assert!(config["access"]["sudo"].is_null()); + // The switches of a profile from before are dropped, whatever they said. + let old = parse_config(br#"{"operator_passwordless_sudo": false, "berth_ssh_key": false}"#) + .unwrap(); + assert!( + old.get("operator_passwordless_sudo").is_none() && old.get("berth_ssh_key").is_none() + ); + let legacy = parse_config( + br#"{"target_disk_serial":"OLD_SSD","wifi":{"ssid":"saved"}, + "release_url":"https://REPLACE.example/x"}"#, + ) + .unwrap(); + assert_eq!(legacy["target_disk_mode"], "serial"); + assert_eq!(legacy["wifi_enabled"], true); + assert_eq!(legacy["release_url"], ""); + // A profile of the qemu target there once was shows as cloud, reached from the QEMU host. + let qemu = parse_config(br#"{"target": "qemu"}"#).unwrap(); + assert_eq!(qemu["target"], "cloud"); + assert_eq!( + qemu["ansible_vars"]["devbox_bootstrap_ssh_cidr"], + "10.0.2.2/32" + ); + } +} diff --git a/crates/berth/src/provisioner_command.rs b/crates/berth/src/provisioner_command.rs index 840d6af..1a6b656 100644 --- a/crates/berth/src/provisioner_command.rs +++ b/crates/berth/src/provisioner_command.rs @@ -44,14 +44,6 @@ impl Source { } } - /// Where they are, for people. - pub fn place(&self) -> String { - match self { - Source::Here(_) => "this machine".into(), - Source::Server(server) => format!("the berth server at {}", server.url), - } - } - pub fn list(&self) -> Result> { match self { Source::Here(paths) => Ok(provision::list(paths, ®istry::Store::new(paths)?)), diff --git a/crates/berth/src/provisioner_tab.rs b/crates/berth/src/provisioner_tab.rs deleted file mode 100644 index 10ca11c..0000000 --- a/crates/berth/src/provisioner_tab.rs +++ /dev/null @@ -1,501 +0,0 @@ -//! The Provisioners tab of the terminal's home screen: the shared tab of -//! [`berth_tui::provisioners`], with the provisioners of this machine or of -//! the berth server berth uses. What it asks for runs in a thread of its -//! own, so the screen goes on drawing while a provisioner is asked. - -use crate::provisioner_command::{Change, Ran, Source, answer_lines}; -use berth_api::{Act, Action, ProvisionerInfo, ProvisionerState, Resource}; -use berth_core::paths::Paths; -use berth_tui::host::View as Panel; -use berth_tui::provisioners::{Asked, Shown, Tab}; -use berth_tui::screen::Platform; -use crossterm::event::{KeyCode, KeyEvent}; -use ratatui::Frame; -use std::sync::{ - Arc, - atomic::{AtomicBool, Ordering}, - mpsc::{Receiver, Sender, channel}, -}; - -/// What came back from a thread. -enum Arrived { - List(Result, String>), - Page( - String, - Box>, - Result, String>, - ), - Resource( - String, - Box>, - Result, String>, - ), - /// The types of provisioner, to register one. - Types(Result, String>), - /// A provisioner was registered under this name, or why not. - Saved(Result), - Output(Vec), - /// A job ended: the subject's page to ask again, a resource's or a - /// provisioner's, and how it ended. - Ended(Subject, Option), -} - -/// What a job was of, whose page is asked again when it ends. -enum Subject { - Provisioner(String), - Resource(String), -} - -/// Where a job's output goes: on to the screen, a piece at a time, until -/// the panel is closed. -struct Lines(Sender, Arc); - -impl std::io::Write for Lines { - fn write(&mut self, data: &[u8]) -> std::io::Result { - if self.1.load(Ordering::Relaxed) { - return Err(std::io::ErrorKind::BrokenPipe.into()); - } - let _ = self.0.send(Arrived::Output(data.to_vec())); - Ok(data.len()) - } - - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } -} - -/// What a key on the tab leads to. -pub enum Left { - Stay, - Tab(usize), - Quit, -} - -pub struct View { - pub tab: Tab, - listing: Option, String>>, - asked: bool, - sender: Sender, - arrived: Receiver, - /// A job that runs or ran, in a panel over the tab. - pub job: Option, - /// Set when the panel is closed, so a log that is followed stops. - closed: Arc, - /// The kind to make once the list has come, as [`View::create`] asks. - creating: Option, -} - -impl Default for View { - fn default() -> View { - let (sender, arrived) = channel(); - View { - tab: Tab::default(), - listing: None, - asked: false, - sender, - arrived, - job: None, - closed: Arc::new(AtomicBool::new(false)), - creating: None, - } - } -} - -impl View { - pub fn list(&self) -> &[ProvisionerInfo] { - match &self.listing { - Some(Ok(list)) => list, - _ => &[], - } - } - - /// Ask for the list, unless it was asked for. - pub fn load(&mut self, paths: &Paths) { - if self.listing.is_some() || self.asked { - return; - } - self.asked = true; - let (paths, sender) = (paths.clone(), self.sender.clone()); - std::thread::spawn(move || { - let listed = Source::of(&paths).list().map_err(|error| error.to_string()); - let _ = sender.send(Arrived::List(listed)); - }); - } - - /// Open the form that makes a resource of `kind` that is no host, such - /// as an instance, with the provisioner that makes it; once the list has - /// come, when it has not. - pub fn create(&mut self, paths: &Paths, kind: &str, status: &mut String) { - let list = match &self.listing { - Some(Ok(list)) => list.clone(), - _ => { - self.creating = Some(kind.to_owned()); - self.listing = None; - self.load(paths); - return; - } - }; - match self.tab.create(&list, kind) { - Asked::Open(id) => self.open(paths, id), - Asked::Nothing(Some(said)) => *status = said, - _ => {} - } - } - - fn open(&self, paths: &Paths, id: String) { - let (paths, sender) = (paths.clone(), self.sender.clone()); - std::thread::spawn(move || { - let source = Source::of(&paths); - let state = source - .state(&id, &Default::default()) - .map_err(|error| error.to_string()); - let actions = source.actions(&id).map_err(|error| error.to_string()); - let _ = sender.send(Arrived::Page(id, Box::new(state), actions)); - }); - } - - fn types(&self, paths: &Paths) { - let (paths, sender) = (paths.clone(), self.sender.clone()); - std::thread::spawn(move || { - let types = Source::of(&paths) - .types() - .map_err(|error| error.to_string()); - let _ = sender.send(Arrived::Types(types)); - }); - } - - fn save(&self, paths: &Paths, name: String, kind: String) { - let (paths, sender) = (paths.clone(), self.sender.clone()); - std::thread::spawn(move || { - let saved = berth_api::SavedProvisioner { - kind, - settings: None, - }; - let said = Source::of(&paths) - .save(&name, &saved) - .map(|()| name) - .map_err(|error| error.to_string()); - let _ = sender.send(Arrived::Saved(said)); - }); - } - - fn open_resource(&self, paths: &Paths, id: String) { - let (paths, sender) = (paths.clone(), self.sender.clone()); - std::thread::spawn(move || { - let source = Source::of(&paths); - let seen = source.resource(&id).map_err(|error| error.to_string()); - let actions = source - .resource_actions(&id) - .map_err(|error| error.to_string()); - let _ = sender.send(Arrived::Resource(id, Box::new(seen), actions)); - }); - } - - /// A panel over the tab for what runs, and the flag that says it closed. - fn panel(&mut self, title: &str) -> Arc { - let (cols, rows) = crossterm::terminal::size().unwrap_or((100, 30)); - self.job = Some(Panel::plain( - title, - rows.saturating_sub(6).max(8), - cols.saturating_sub(8).max(20), - )); - self.closed = Arc::new(AtomicBool::new(false)); - self.closed.clone() - } - - /// Show a resource's log in a panel, following it until the panel closes. - fn logs(&mut self, paths: &Paths, id: String) { - let closed = self.panel(&format!("Log · {id}")); - let (paths, sender) = (paths.clone(), self.sender.clone()); - std::thread::spawn(move || { - let mut out = Lines(sender.clone(), closed); - let code = match Source::of(&paths).logs(&id, 200, true, &mut out) { - Ok(()) => Some(0), - Err(error) => { - let _ = sender.send(Arrived::Output(format!("✗ {error}\n").into_bytes())); - None - } - }; - let _ = sender.send(Arrived::Ended(Subject::Resource(id), code)); - }); - } - - /// Run an action of a resource, as `run` does one of a provisioner. - fn run_resource( - &mut self, - paths: &Paths, - id: String, - action: Action, - values: Change, - status: &mut String, - ) { - let (paths, sender) = (paths.clone(), self.sender.clone()); - *status = format!("Asking {id}…"); - let closed = self.panel(&format!("{} · {id}", action.title())); - std::thread::spawn(move || { - let mut out = Lines(sender.clone(), closed); - let code = match Source::of(&paths).resource_run( - &id, - &action.name, - values, - &mut out, - &mut std::io::sink(), - ) { - Ok(Ran::Ended(code)) => Some(code), - Ok(Ran::Answered(answer)) => { - let lines = answer_lines(&answer).join("\n"); - let _ = sender.send(Arrived::Output(format!("{lines}\n").into_bytes())); - Some(0) - } - Err(error) => { - let _ = sender.send(Arrived::Output(format!("✗ {error}\n").into_bytes())); - None - } - }; - let _ = sender.send(Arrived::Ended(Subject::Resource(id), code)); - }); - } - - /// Take in what has come back, and say what there is to say. - pub fn pump(&mut self, paths: &Paths, status: &mut String) { - while let Ok(arrived) = self.arrived.try_recv() { - match arrived { - Arrived::List(listed) => { - if let Err(error) = &listed { - *status = format!("✗ {error}"); - } - let ready = listed.is_ok(); - self.listing = Some(listed); - self.asked = false; - if let Some(kind) = self.creating.take() - && ready - { - self.create(paths, &kind, status); - } - } - // One that was removed takes its page back to the list. - Arrived::Page(_, state, _) - if state - .as_ref() - .as_ref() - .is_err_and(|error| error.starts_with("No provisioner ")) => - { - self.tab.page = None; - self.listing = None; - self.load(paths); - } - Arrived::Page(id, state, actions) => self.tab.opened(&id, *state, actions), - Arrived::Types(types) => { - if let Some(said) = self.tab.adding(types) { - *status = said; - } - } - Arrived::Saved(Ok(name)) => { - *status = format!("Registered {name}. Its page has its settings and secrets"); - self.listing = None; - self.load(paths); - } - Arrived::Saved(Err(error)) => *status = format!("✗ {error}"), - // One that was removed takes its page back to its provisioner's. - Arrived::Resource(id, seen, _) - if seen - .as_ref() - .as_ref() - .is_err_and(|error| error.starts_with("No resource ")) => - { - if let Some(provisioner) = self.tab.back_from(&id) { - self.open(paths, provisioner); - } - } - Arrived::Resource(id, seen, actions) => { - self.tab.opened_resource(&id, *seen, actions) - } - Arrived::Output(data) => { - if let Some(job) = &mut self.job { - job.feed(&data); - } - } - Arrived::Ended(subject, code) => { - if let Some(job) = &mut self.job { - job.ended = Some(code); - } - // What the action changed shows on the page. - match subject { - Subject::Provisioner(id) => self.open(paths, id), - Subject::Resource(id) => self.open_resource(paths, id), - } - } - } - } - } - - pub fn shown(&self, paths: &Paths) -> Shown { - let mut shown = self.tab.shown(self.list(), &Source::of(paths).place()); - if let Some(Err(error)) = &self.listing { - shown.help = format!("✗ {error}\n\n{}", shown.help); - } - shown - } - - /// Draw what is over the tab: a job's panel, a form, a question, the - /// arguments. `status` is the last message, which a form shows itself. - pub fn draw_over(&self, frame: &mut Frame, status: &str) { - if let Some(job) = &self.job { - let keys = match job.outcome() { - None => " It runs · its output comes as it is written ", - Some(true) => " ✓ Done · Enter close ", - Some(false) => " ✗ It did not finish · Enter close ", - }; - berth_tui::screen::draw_panel(frame, &job.title, job.screen(), job.outcome(), keys, ""); - return; - } - if let Some(form) = self.tab.form() { - form.draw(frame, status); - } - if let Some(question) = self.tab.question() { - berth_tui::screen::draw_question(frame, question); - } - if let Some((actions, asked)) = self.tab.arguments() { - berth_tui::screen::draw_action_arguments(frame, actions, asked); - } - } - - /// Run an action, in a thread. Its output, or its answer, fills a panel. - fn run(&mut self, paths: &Paths, id: String, action: Action, values: Act, status: &mut String) { - let (paths, sender) = (paths.clone(), self.sender.clone()); - *status = format!("Asking {id}…"); - let closed = self.panel(&format!("{} · {id}", action.title())); - std::thread::spawn(move || { - let mut out = Lines(sender.clone(), closed); - let code = match Source::of(&paths).run( - &id, - &action.name, - values, - &mut out, - &mut std::io::sink(), - ) { - Ok(Ran::Ended(code)) => Some(code), - Ok(Ran::Answered(answer)) => { - let lines = answer_lines(&answer).join("\n"); - let _ = sender.send(Arrived::Output(format!("{lines}\n").into_bytes())); - Some(0) - } - Err(error) => { - let _ = sender.send(Arrived::Output(format!("✗ {error}\n").into_bytes())); - None - } - }; - let _ = sender.send(Arrived::Ended(Subject::Provisioner(id), code)); - }); - } - - /// Whether keys go to a dialog or a panel, so none of them changes tabs. - pub fn typing(&self) -> bool { - self.job.is_some() || self.tab.typing() - } - - /// Handle a key on the tab. - pub fn key( - &mut self, - paths: &Paths, - key: KeyEvent, - status: &mut String, - platform: &mut dyn Platform, - ) -> Left { - if let Some(job) = &self.job { - // A log goes on until it is closed; a job's panel closes once it ended. - let log = job.title.starts_with("Log · "); - if (log || !job.running()) - && matches!(key.code, KeyCode::Enter | KeyCode::Esc | KeyCode::Char('q')) - { - self.closed.store(true, Ordering::Relaxed); - self.job = None; - } - return Left::Stay; - } - let Some(shared) = crate::keys::key(&key) else { - return Left::Stay; - }; - let list = self.list().to_vec(); - let asked = self.tab.key(shared, &list, platform); - if asked == Asked::Other { - match key.code { - KeyCode::Char(digit @ '1'..='6') => { - return Left::Tab(digit as usize - '1' as usize); - } - // Next to the hosts: Tab goes on to the settings, Shift+Tab back. - KeyCode::Tab => return Left::Tab(2), - KeyCode::BackTab | KeyCode::Esc => return Left::Tab(0), - KeyCode::Char('q') => return Left::Quit, - _ => {} - } - } - self.asked(paths, asked, status) - } - - /// Put pasted text into what is being typed. - pub fn paste(&mut self, text: &str) { - self.tab.paste(text); - } - - /// A click while a form is open, which the form takes. - pub fn click( - &mut self, - paths: &Paths, - (column, row): (u16, u16), - status: &mut String, - platform: &mut dyn Platform, - ) -> Left { - let list = self.list().to_vec(); - let asked = self.tab.click(column, row, &list, platform); - self.asked(paths, asked, status) - } - - /// Do what a key or a click on the tab asked for. - fn asked(&mut self, paths: &Paths, asked: Asked, status: &mut String) -> Left { - match asked { - Asked::Nothing(said) => { - if let Some(said) = said { - *status = said; - } - } - Asked::List => { - self.listing = None; - self.load(paths); - } - Asked::Add => self.types(paths), - Asked::Save { name, kind } => { - *status = format!("Registering {name}…"); - self.save(paths, name, kind); - } - Asked::Open(id) => self.open(paths, id), - Asked::Run { - provisioner, - action, - values, - } => { - let act = Act { - arguments: values, - ..Act::default() - }; - self.run(paths, provisioner, *action, act, status); - } - Asked::OpenResource(id) => self.open_resource(paths, id), - Asked::RunResource { - resource, - action, - values, - } => { - let change = Change { - arguments: values, - ..Change::default() - }; - self.run_resource(paths, resource, *action, change, status); - } - Asked::Logs(id) => self.logs(paths, id), - Asked::Hosts => return Left::Tab(0), - Asked::Other => {} - } - Left::Stay - } -} diff --git a/crates/berth/src/remote.rs b/crates/berth/src/remote.rs deleted file mode 100644 index d790bd7..0000000 --- a/crates/berth/src/remote.rs +++ /dev/null @@ -1,532 +0,0 @@ -//! The host's own API, for the UI: one background thread owns the runtime and -//! the link, takes requests and sends back what happened. The UI never waits -//! for the network. - -use berth_api::{self as api, client::Frame}; -use berth_core::link::{Link, LinkSpec}; -pub use berth_tui::host::{Event, HostView, NEEDS_API, Pending, Request, State, Transport, list}; -use futures_util::{SinkExt, StreamExt}; -use serde_json::{Value, json}; -use std::sync::{Arc, mpsc}; -use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; - -/// The exit code an `exited` frame carries, when the text is one. -pub fn exited(text: &str) -> Option> { - berth_tui::host::exited(&serde_json::from_str(text).ok()?) -} - -enum Out { - Input(Vec), - Resize(u16, u16), -} - -/// How a host's version is compared with what would be applied now. It may -/// wait on the network, and runs off the runtime. -pub type Compare = Arc Option + Send + Sync>; - -async fn refresh( - link: Arc, - events: mpsc::Sender, - all: bool, - compare: Option, -) { - if all { - match link.version().await { - Ok(version) => { - let old = version.api < NEEDS_API; - if let Some(compare) = compare { - let asked = version.clone(); - let events = events.clone(); - tokio::task::spawn_blocking(move || { - let _ = events.send(Event::Behind(compare(&asked))); - }); - } - let _ = events.send(Event::Version(version)); - if old { - return; - } - } - Err(error) => { - let _ = events.send(Event::Failed { - missing: Link::missing(&error), - message: error.to_string(), - }); - return; - } - } - if let Ok(listed) = link.get::("/v1/actions").await { - let _ = events.send(Event::Actions(list(listed, "actions"))); - } - } - if let Ok(sessions) = link.get::("/v1/sessions").await { - let _ = events.send(Event::Sessions(list(sessions, "sessions"))); - } - if let Ok(stats) = link.get::("/v1/stats").await { - let _ = events.send(Event::Stats(Box::new(stats))); - } -} - -async fn follow( - link: Arc, - session: api::Session, - events: mpsc::Sender, - mut out: UnboundedReceiver, -) { - let terminal = session.kind == api::SessionKind::Terminal; - let id = session.id.clone(); - // A terminal replays its screen; a process is read from the start. - let path = match terminal { - true => format!("/v1/sessions/{id}"), - false => format!("/v1/sessions/{id}?since=0"), - }; - let mut stream = match link.stream(&path).await { - Ok(stream) => stream, - Err(error) => { - // An ended session can still be read back. - let output = link - .get::(&format!("/v1/sessions/{id}/output")) - .await; - match output.ok().and_then(|output| api::unb64(&output.data_b64)) { - Some(bytes) if !session.running() => { - let _ = events.send(Event::Output(id.clone(), bytes)); - let _ = events.send(Event::Exited(id, session.exit_code)); - } - _ => { - let _ = events.send(Event::Error(error.to_string())); - let _ = events.send(Event::Closed(id)); - } - } - return; - } - }; - loop { - tokio::select! { - frame = stream.next() => match frame { - Some(Ok(Frame::Binary(bytes))) => { - let event = match (terminal, bytes.split_first()) { - (true, _) => Event::Output(id.clone(), bytes.to_vec()), - (false, Some((_, rest))) => Event::Output(id.clone(), rest.to_vec()), - (false, None) => continue, - }; - if events.send(event).is_err() { - return; - } - } - Some(Ok(Frame::Text(text))) => { - if let Some(code) = exited(text.as_str()) { - let _ = events.send(Event::Exited(id.clone(), code)); - } - } - Some(Ok(_)) => {} - _ => { - let _ = events.send(Event::Closed(id)); - return; - } - }, - message = out.recv() => { - let frame = match message { - Some(Out::Input(bytes)) if terminal => Frame::Binary(bytes.into()), - Some(Out::Input(bytes)) => Frame::Binary([vec![0], bytes].concat().into()), - Some(Out::Resize(rows, cols)) => { - Frame::Text(json!({"resize": {"rows": rows, "cols": cols}}).to_string().into()) - } - None => { - let _ = stream.close().await; - return; - } - }; - if stream.send(frame).await.is_err() { - let _ = events.send(Event::Closed(id)); - return; - } - } - } - } -} - -async fn worker( - link: Arc, - mut requests: UnboundedReceiver, - events: mpsc::Sender, - compare: Option, -) { - let mut stream: Option> = None; - while let Some(request) = requests.recv().await { - let (link, events) = (link.clone(), events.clone()); - match request { - Request::Refresh => drop(tokio::spawn(refresh(link, events, true, compare.clone()))), - Request::Poll => drop(tokio::spawn(refresh(link, events, false, None))), - Request::Run { name, body } => drop(tokio::spawn(async move { - let _ = events.send(match link.run_action(&name, &body).await { - Ok(session) => Event::Opened(Box::new(session)), - Err(error) => Event::Error(error.to_string()), - }); - })), - Request::Start { body } => drop(tokio::spawn(async move { - let _ = events.send( - match link.post::("/v1/sessions", &body).await { - Ok(session) => Event::Opened(Box::new(session)), - Err(error) => Event::Error(error.to_string()), - }, - ); - })), - Request::Open(session) => { - let (sender, receiver) = unbounded_channel(); - stream = Some(sender); - tokio::spawn(follow(link, *session, events, receiver)); - } - Request::Input(bytes) => { - if let Some(stream) = &stream { - let _ = stream.send(Out::Input(bytes)); - } - } - Request::Resize(rows, cols) => { - if let Some(stream) = &stream { - let _ = stream.send(Out::Resize(rows, cols)); - } - } - Request::Close => stream = None, - Request::Delete(id) => drop(tokio::spawn(async move { - let path = format!("/v1/sessions/{id}"); - if let Err(error) = link.call::("DELETE", &path, None).await { - let _ = events.send(Event::Error(error.to_string())); - } - refresh(link, events, false, None).await; - })), - Request::Choices { action, argument } => drop(tokio::spawn(async move { - let path = format!( - "/v1/actions/{}/choices/{}", - api::client::encode(&action), - api::client::encode(&argument) - ); - let choices = match link.get::(&path).await { - Ok(value) => list(value, "choices"), - Err(_) => vec![], - }; - let _ = events.send(Event::Choices { - action, - argument, - choices, - }); - })), - } - } -} - -/// The thread that talks to one host. -pub struct Remote { - requests: UnboundedSender, - events: mpsc::Receiver, -} - -impl Remote { - pub fn start(spec: LinkSpec, compare: Option) -> std::io::Result { - let runtime = berth_core::link::runtime()?; - let (requests, receiver) = unbounded_channel(); - let (sender, events) = mpsc::channel(); - std::thread::spawn(move || { - runtime.block_on(worker(Arc::new(Link::new(spec)), receiver, sender, compare)); - }); - Ok(Remote { requests, events }) - } -} - -impl Transport for Remote { - fn send(&self, request: Request) { - let _ = self.requests.send(request); - } - - fn next(&self) -> Option { - self.events.try_recv().ok() - } -} - -/// Start talking to the host over `spec`. Returns why not, if it cannot be. -#[cfg(test)] -pub fn connect(host: &mut HostView, spec: LinkSpec) -> Option { - connect_with(host, spec, None) -} - -/// The same, comparing the host with what would be applied now. -pub fn connect_with( - host: &mut HostView, - spec: LinkSpec, - compare: Option, -) -> Option { - match Remote::start(spec, compare) { - Ok(remote) => { - host.connect(Box::new(remote)); - None - } - Err(error) => { - host.unreachable(error.to_string()); - Some(error.to_string()) - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use berth_tui::host::{Arguments, View}; - use std::time::Duration; - - #[test] - fn lists_come_bare_or_under_a_key() { - let bare: Vec = list(json!([{"name": "status"}]), "actions"); - let keyed: Vec = list( - json!({"actions": [{"name": "status"}, {"no": "name"}]}), - "actions", - ); - assert_eq!((bare.len(), keyed.len()), (1, 1)); - assert_eq!(exited(r#"{"exited":{"exit_code":3}}"#), Some(Some(3))); - assert_eq!(exited(r#"{"exited":{}}"#), Some(None)); - assert_eq!(exited(r#"{"dropped":{"frames":1}}"#), None); - } - - #[test] - fn a_transcript_is_shown_line_by_line() { - let session: api::Session = serde_json::from_value(json!({ - "id": "s1", "kind": "process", "title": "demo", "command": ["true"], "user": "agent", - "started_by": {"level": "host", "uid": 0}, "started": "2026-11-12T00:00:00Z", - })) - .unwrap(); - let mut view = View::new(&session, 4, 20, true, false); - assert!(view.feed(b"one\ntwo").is_empty()); - view.feed(b"!\nthree\n"); - assert_eq!(view.screen().contents(), "one\ntwo!\nthree"); - assert!(view.running() && view.outcome().is_none()); - view.ended = Some(Some(2)); - assert_eq!(view.outcome(), Some(false)); - // A terminal answers a question about the cursor, also one in two pieces. - let mut terminal = View::new(&session, 4, 20, true, false); - terminal.terminal = true; - assert!(terminal.feed(b"ab\x1b[6").is_empty()); - assert_eq!(terminal.feed(b"n"), b"\x1b[1;3R"); - } - - /// The overview against a real controller, when one has been built - /// (`cargo build -p berthd`): connect, list, run actions, type into one. - #[test] - fn the_overview_talks_to_a_controller() { - let built = std::env::current_exe() - .unwrap() - .parent() - .unwrap() - .parent() - .unwrap() - .join("berthd"); - if !built.is_file() { - eprintln!("skipped: {} is not built", built.display()); - return; - } - let dir = tempfile::tempdir().unwrap(); - std::fs::create_dir_all(dir.path().join("etc")).unwrap(); - let actions = json!([ - {"name": "status", "label": "Status", "group": "System", "user": "agent", "run": "echo up; echo warn >&2"}, - {"name": "demo:status", "label": "Demo", "extends": ["status"], "user": "agent", "run": "echo demo; exit 4"}, - {"name": "greet", "label": "Greet", "user": "agent", "run": "echo \"hello $BERTH_ARG_WHO\"", - "arguments": [{"name": "who", "required": true, "choices": "printf 'ann\\nbob\\n'"}]}, - {"name": "ask", "label": "Ask", "user": "agent", "terminal": true, "run": "printf 'code? '; read c; echo got $c"}, - ]); - std::fs::write(dir.path().join("etc/actions.json"), actions.to_string()).unwrap(); - let mut daemon = std::process::Command::new(&built) - .arg("--single") - .arg(dir.path()) - .spawn() - .unwrap(); - struct Stop<'a>(&'a mut std::process::Child); - impl Drop for Stop<'_> { - fn drop(&mut self) { - let _ = self.0.kill(); - let _ = self.0.wait(); - } - } - let _stop = Stop(&mut daemon); - for _ in 0..100 { - if dir.path().join("control.sock").exists() { - break; - } - std::thread::sleep(Duration::from_millis(50)); - } - let spec = LinkSpec { - program: built.to_string_lossy().into_owned(), - args: vec![ - "connect".into(), - "--dir".into(), - dir.path().to_string_lossy().into_owned(), - ], - first_line: None, - via: None, - ..LinkSpec::default() - }; - let mut host = HostView::default(); - assert!(connect(&mut host, spec).is_none()); - fn until(host: &mut HostView, what: &str, done: impl Fn(&HostView) -> bool) { - for _ in 0..400 { - if let Some(note) = host.pump() { - eprintln!("note: {note}"); - } - if done(host) { - return; - } - std::thread::sleep(Duration::from_millis(25)); - } - panic!("never: {what}; state {:?}", host.state); - } - until(&mut host, "ready with actions", |host| { - matches!(host.state, State::Ready(_)) && host.host_actions.len() == 4 - }); - until(&mut host, "stats", |host| host.stats.is_some()); - assert!(host.stats_line().unwrap().contains("load ")); - assert!(host.host_actions[0].run.is_empty() && host.host_actions[1].extends == ["status"]); - - // An action and the step a plugin adds, as one transcript; the first - // failing step is the outcome. - host.run("status", json!({})); - until(&mut host, "status ended", |host| { - host.view.as_ref().is_some_and(|view| !view.running()) - }); - let view = host.view.as_ref().unwrap(); - assert!(view.ours && !view.terminal && view.title == "Status"); - let text = view.screen().contents(); - assert!( - text.contains("up") && text.contains("warn") && text.contains("demo"), - "{text}" - ); - assert_eq!(view.ended, Some(Some(4))); - let id = view.id.clone(); - // Closing a finished one that was started here forgets it. - host.close(true); - until(&mut host, "forgotten", |host| { - host.sessions.iter().all(|session| session.id != id) - }); - - // Arguments reach the command; the host offers choices for one. - host.send(Request::Choices { - action: "greet".into(), - argument: "who".into(), - }); - host.arguments = Some(Arguments { - action: 1, - index: 0, - values: Default::default(), - input: Default::default(), - choices: vec![], - chosen: None, - secret: false, - text: false, - }); - until(&mut host, "choices", |host| { - host.arguments.as_ref().unwrap().choices == ["ann", "bob"] - }); - host.arguments = None; - host.run("greet", json!({"arguments": {"who": "a 'quoted' b"}})); - until(&mut host, "greet ended", |host| { - host.view.as_ref().is_some_and(|view| !view.running()) - }); - assert!( - host.view - .as_ref() - .unwrap() - .screen() - .contents() - .contains("hello a 'quoted' b") - ); - host.close(false); - until(&mut host, "kept", |host| { - host.sessions.iter().any(|session| session.title == "Greet") - }); - - // A terminal action takes typing; left with Ctrl+Q it runs on and can be - // opened again. - host.run("ask", json!({"rows": 10, "cols": 40})); - until(&mut host, "the question", |host| { - host.view - .as_ref() - .is_some_and(|view| view.screen().contents().contains("code?")) - }); - assert!(host.view.as_ref().unwrap().terminal); - host.close(false); - until(&mut host, "listed as running", |host| { - host.sessions - .iter() - .any(|session| session.title == "Ask" && session.running()) - }); - let session = host - .sessions - .iter() - .find(|session| session.title == "Ask") - .unwrap() - .clone(); - host.open(&session); - until(&mut host, "the question again", |host| { - host.view - .as_ref() - .is_some_and(|view| view.screen().contents().contains("code?")) - }); - host.input(b"42\r".to_vec()); - until(&mut host, "the answer", |host| { - host.view.as_ref().is_some_and(|view| !view.running()) - }); - let view = host.view.as_ref().unwrap(); - assert!(view.screen().contents().contains("got 42") && view.outcome() == Some(true)); - assert!(!view.ours); - - // An action the host does not have says so. - host.close(true); - host.run("nothing", json!({})); - let mut said = None; - for _ in 0..200 { - said = host.pump(); - if said.is_some() { - break; - } - std::thread::sleep(Duration::from_millis(25)); - } - assert!(said.is_some() && host.view.is_none()); - } - - #[test] - fn a_host_without_a_controller_is_told_apart() { - let spec = |script: &str| LinkSpec { - program: "sh".into(), - args: vec!["-c".into(), script.into()], - first_line: None, - via: None, - ..LinkSpec::default() - }; - let state = |script: &str, password: Option<&str>| { - let mut host = HostView::default(); - host.password = password.map(str::to_owned); - connect(&mut host, spec(script)); - for _ in 0..400 { - host.pump(); - if host.state != State::Connecting { - break; - } - std::thread::sleep(Duration::from_millis(25)); - } - (host.state, host.password) - }; - assert_eq!( - state("echo 'sudo: berthd: command not found' >&2; exit 1", None).0, - State::Missing - ); - assert_eq!( - state("echo 'sudo: a password is required' >&2; exit 1", None).0, - State::Password - ); - // A password sudo did not take is forgotten, to be asked for again. - let wrong = state( - "echo 'Sorry, try again.' >&2; echo 'sudo: 1 incorrect password attempt' >&2; exit 1", - Some("x"), - ); - assert_eq!(wrong, (State::Password, None)); - let (other, _) = state( - "echo 'ssh: connect to host box port 22: Connection timed out' >&2; exit 255", - None, - ); - assert!(matches!(other, State::Unreachable(message) if message.contains("timed out"))); - } -} diff --git a/crates/berth/src/serve/here.rs b/crates/berth/src/serve/here.rs index 41c7c6a..124943e 100644 --- a/crates/berth/src/serve/here.rs +++ b/crates/berth/src/serve/here.rs @@ -22,6 +22,46 @@ pub fn socket() -> std::path::PathBuf { berth_core::link::runtime_dir().join("serve.sock") } +/// The server berth goes through when it is set to use none: a `berth +/// serve` of this user on this machine, or else one started in this process, +/// which the caller keeps while it is needed. The address names either. +pub fn local(paths: &Paths) -> Result<(String, Option)> { + let socket = socket(); + if std::os::unix::net::UnixStream::connect(&socket).is_ok() { + return Ok((format!("unix:{}", socket.display()), None)); + } + let here = Here::start(paths)?; + berth_core::server::serve_here(here.dial()); + Ok((berth_core::server::HERE.to_owned(), Some(here))) +} + +/// The server a command goes through: the one berth is set to use, or one +/// on this machine as [`local`] finds it. +pub fn server(paths: &Paths) -> Result<(berth_core::server::Server, Option)> { + if let Some(server) = berth_core::server::Server::configured(paths) { + return Ok((server, None)); + } + let (url, here) = local(paths)?; + Ok((berth_core::server::Server { url, token: None }, here)) +} + +/// Wait for the jobs a command started in its own server, saying on +/// standard error which they are. +pub fn finish(here: Option) { + if let Some(here) = here { + here.wait_for_jobs(|jobs| { + let names: Vec = jobs + .iter() + .map(|job| format!("{} {}", job.action, job.host).trim().to_owned()) + .collect(); + eprintln!( + "berth: waiting for what runs in this berth to end: {}. Ctrl+C stops it unfinished; berth serve keeps jobs running after berth ends.", + names.join(", ") + ); + }); + } +} + /// The pipes clients open, as connections that axum serves. struct Pipes(UnboundedReceiver); @@ -220,6 +260,76 @@ mod tests { ); } + fn screen(app: &mut berth_page::App) -> String { + use ratatui::{Terminal, backend::TestBackend}; + let mut terminal = Terminal::new(TestBackend::new(120, 30)).unwrap(); + terminal.draw(|frame| app.draw(frame)).unwrap(); + let buffer = terminal.backend().buffer(); + (0..30) + .map(|y| { + (0..120) + .map(|x| buffer[(x, y)].symbol()) + .collect::() + }) + .collect::>() + .join("\n") + } + + #[test] + fn the_screens_list_and_open_a_host_through_it() { + let (dir, paths) = scratch(); + for (name, address) in [("studio", "192.0.2.10"), ("dock", "192.0.2.11")] { + let profile = json!({"hostname": name, "builder": {}, "access": {"address": address, "link": ["sh", "-c", "exit 1"]}}); + berth_core::profiles::Place::own(name) + .unwrap() + .save(&paths, &profile) + .unwrap(); + } + let here = Here::start(&paths).unwrap(); + berth_page::net::serve_here(here.dial()); + let kept = dir.path().join("client"); + let linked = berth_page::device::Linked { + server: Some(berth_page::device::HERE.into()), + ..Default::default() + }; + berth_page::device::install( + linked, + berth_page::settings::Settings::new(Some(kept.clone())), + ); + let mut app = berth_page::App::new(); + app.open_when_listed("dock"); + let started = std::time::Instant::now(); + let shown = loop { + berth_page::pump(); + app.tick(); + let shown = screen(&mut app); + if shown.contains("Connection") && shown.contains("192.0.2.11") { + break shown; + } + assert!( + started.elapsed() < Duration::from_secs(10), + "the host did not open:\n{shown}" + ); + std::thread::sleep(Duration::from_millis(20)); + }; + // Its own server needs no token and says where it is, and is never kept. + assert!(!shown.contains("through the berth server"), "{shown}"); + assert!(!kept.join("config.json").exists()); + app.event(berth_tui::Event::Key(berth_tui::Key::plain( + berth_tui::Code::Esc, + ))); + app.tick(); + let home = screen(&mut app); + assert!( + home.contains("this machine") && home.contains("studio"), + "{home}" + ); + app.event(berth_tui::Event::Key(berth_tui::Key::plain( + berth_tui::Code::Char('q'), + ))); + assert!(app.quit()); + } + #[test] fn nothing_listens_for_it() { let (dir, paths) = scratch(); diff --git a/crates/berth/src/serve/tests.rs b/crates/berth/src/serve/tests.rs index 2c6834b..96c6763 100644 --- a/crates/berth/src/serve/tests.rs +++ b/crates/berth/src/serve/tests.rs @@ -3172,24 +3172,6 @@ fn a_setup_key_is_refused_when_the_token_is_off() { assert!(super::setup_key::command(&paths, &["--nothing"]).is_err()); } -/// Generate the password of the operator on the screen of `app`, and what -/// the screen said. -fn generate_operator_password(app: &mut crate::app::App) -> String { - use crate::app::Entry; - use crate::fields::{Field, Step}; - let found = Step::SETUP.into_iter().find_map(|step| { - app.step = step; - app.entries() - .iter() - .position(|entry| *entry == Entry::Field(Field::OperatorHash)) - }); - app.list.select(found); - match app.generate() { - Ok(()) => app.status.clone(), - Err(error) => error.to_string(), - } -} - #[tokio::test(flavor = "multi_thread")] async fn a_host_is_renamed_as_a_job_with_what_the_server_keeps_of_it() { let served = served().await; @@ -3440,51 +3422,6 @@ fn generated_passwords_are_kept_where_the_host_is_and_shown_to_an_admin() { let (status, _) = ask("GET", "/v1/hosts/attic/credentials", Value::Null); assert_eq!(status, 404); - // The screen of a berth that uses this server has the server make the - // password, and keeps none of it itself, where a mirror would erase it. - let elsewhere = tempfile::tempdir().unwrap(); - let paths = Paths { - config_dir: elsewhere.path().join("config"), - data_dir: elsewhere.path().join("data"), - }; - let url = format!("unix:{}", served.socket.display()); - paths.set("server", &url).unwrap(); - let place = Place::resolve(&paths, "studio").unwrap(); - assert_eq!(place.server_url(), Some(url.as_str())); - let mut config = profile.clone(); - config["builder"]["served"] = json!(url); - let mut app = crate::app::App::new( - paths.clone(), - place.clone(), - crate::app::parse_config(config.to_string().as_bytes()).unwrap(), - ); - let said = generate_operator_password(&mut app); - assert!(said.contains("kept on the berth server"), "{said}"); - assert!( - app.config["operator_password_hash"] - .as_str() - .unwrap() - .starts_with("$6$") - ); - assert!(credentials::load(&paths, &place).unwrap().is_empty()); - let kept = credentials::load(&served.state.paths, &own).unwrap(); - assert_ne!(kept["ops"], json!(password), "a new one was made"); - - // A host of this berth's own keeps it in this berth's store. - let local = tempfile::tempdir().unwrap(); - let paths = Paths { - config_dir: local.path().join("config"), - data_dir: local.path().join("data"), - }; - let attic = Place::own("attic").unwrap(); - let mut app = crate::app::App::new( - paths.clone(), - attic.clone(), - crate::app::parse_config(b"{}").unwrap(), - ); - let said = generate_operator_password(&mut app); - assert!(said.contains("berth credentials attic"), "{said}"); - assert_eq!(credentials::load(&paths, &attic).unwrap().len(), 1); runtime.shutdown_background(); } @@ -3974,69 +3911,6 @@ async fn a_host_removed_or_changed_in_the_store_by_another_process_is_not_listed assert_eq!(status, 404); } -// Not on a runtime of the test's: the screen waits for the server on one of its own. -#[test] -fn the_screen_keeps_the_address_a_server_gave_a_new_machine_and_opens_its_overview() { - use crate::fields::Step; - use berth_core::profiles::Place; - let runtime = tokio::runtime::Builder::new_multi_thread() - .enable_all() - .build() - .unwrap(); - let served = runtime.block_on(served()); - let own = Place::own("studio").unwrap(); - let profile = json!({"hostname": "studio", "builder": {}, "operator_username": "ops"}); - own.save(&served.state.paths, &profile).unwrap(); - - let elsewhere = tempfile::tempdir().unwrap(); - let paths = Paths { - config_dir: elsewhere.path().join("config"), - data_dir: elsewhere.path().join("data"), - }; - let url = format!("unix:{}", served.socket.display()); - paths.set("server", &url).unwrap(); - let server = berth_core::server::Server::configured(&paths).unwrap(); - server.mirror(&paths).unwrap(); - let place = Place::resolve(&paths, "studio").unwrap(); - let stored = place.load(&paths).unwrap().unwrap(); - let mut app = crate::app::App::new( - paths.clone(), - place.clone(), - crate::app::parse_config(stored.to_string().as_bytes()).unwrap(), - ); - app.set_step(Step::Install); - - // The server made the machine in a job of its own and gave its profile the address. - let mut made = own.load(&served.state.paths).unwrap().unwrap(); - made["access"] = json!({"address": "192.0.2.40", "user": "ops", "auth": "berth"}); - made["target"] = json!("cloud"); - own.save(&served.state.paths, &made).unwrap(); - let stage = crate::job::Stage { - title: "Create machine".into(), - command: std::process::Command::new("true"), - source: None, - input: None, - }; - app.job = Some(crate::job::Job::start(vec![stage], "", vec![]).unwrap()); - app.machine_job = true; - for _ in 0..500 { - app.job.as_mut().unwrap().tick(); - if !app.job.as_ref().unwrap().running() { - break; - } - std::thread::sleep(Duration::from_millis(10)); - } - app.close_job(); - assert_eq!(app.step, Step::Manage, "{}", app.status); - assert_eq!(app.config["access"]["address"], "192.0.2.40"); - assert!(!app.unsaved()); - - // What the screen saves next, as before it starts the machine, keeps the address. - app.save().unwrap(); - let kept = own.load(&served.state.paths).unwrap().unwrap(); - assert_eq!(kept["access"]["address"], "192.0.2.40", "{kept}"); -} - /// What works with this machine's own drives and settings is offered to its /// user, on the socket or in the process, and not over the network. #[tokio::test(flavor = "multi_thread")] diff --git a/crates/berth/src/session.rs b/crates/berth/src/session.rs deleted file mode 100644 index 49f12ce..0000000 --- a/crates/berth/src/session.rs +++ /dev/null @@ -1,206 +0,0 @@ -//! A command that needs a terminal, run inside the UI: a shell on a host, or a -//! sign-in that shows a link and waits for a code. It gets a pseudo-terminal of -//! its own; what it draws there is kept here and shown in a panel. - -use crate::Result; -use crossterm::event::KeyEvent; -use std::{ - fs::File, - io::{Read, Write}, - process::{Child, Command}, - sync::mpsc::{Receiver, channel}, -}; - -/// Lines kept above the screen, for scrolling back. -const HISTORY: usize = 2000; - -pub struct Session { - pub title: String, - /// Close the panel when the command ends well, as for a shell. - pub closes: bool, - parser: vt100::Parser, - child: Child, - /// Our end of the pseudo-terminal. - terminal: File, - receiver: Receiver>, - /// The last bytes of output, for a question that arrives in two pieces. - tail: Vec, - /// Whether it succeeded, once it has ended. - pub outcome: Option, -} - -impl Session { - pub fn start(title: &str, command: Command, rows: u16, cols: u16) -> Result { - let (ours, child) = berth_pty::spawn(command, rows, cols)?; - let (sender, receiver) = channel(); - let mut reader = ours.try_clone()?; - std::thread::spawn(move || { - let mut buffer = [0; 4096]; - while let Ok(count) = reader.read(&mut buffer) - && count > 0 - && sender.send(buffer[..count].to_vec()).is_ok() - {} - }); - Ok(Session { - title: title.to_owned(), - closes: false, - parser: vt100::Parser::new(rows, cols, HISTORY), - child, - terminal: ours, - receiver, - tail: vec![], - outcome: None, - }) - } - - /// Take in what the command has written and notice when it has ended. - pub fn tick(&mut self) { - while let Ok(bytes) = self.receiver.try_recv() { - self.parser.process(&bytes); - // Prompts ask where the cursor is and wait for the answer. - self.tail.extend_from_slice(&bytes); - let asked = self - .tail - .windows(4) - .filter(|window| window == b"\x1b[6n") - .count(); - let keep = self.tail.len().saturating_sub(3); - self.tail.drain(..keep); - for _ in 0..asked { - let (row, col) = self.screen().cursor_position(); - self.send(format!("\x1b[{};{}R", row + 1, col + 1).as_bytes()); - } - } - if self.outcome.is_none() - && let Ok(Some(status)) = self.child.try_wait() - { - self.outcome = Some(status.success()); - } - } - - pub fn running(&self) -> bool { - self.outcome.is_none() - } - - pub fn screen(&self) -> &vt100::Screen { - self.parser.screen() - } - - /// Give the terminal a new size; the command is told by the system. - pub fn resize(&mut self, rows: u16, cols: u16) { - if self.screen().size() != (rows, cols) { - self.parser.screen_mut().set_size(rows, cols); - berth_pty::resize(&self.terminal, rows, cols); - } - } - - /// Look further back (positive) or forward again, by `lines`. - pub fn scroll(&mut self, lines: isize) { - let now = self.screen().scrollback() as isize; - self.parser - .screen_mut() - .set_scrollback((now + lines).max(0) as usize); - } - - pub fn send(&mut self, bytes: &[u8]) { - if self.running() && !bytes.is_empty() { - self.parser.screen_mut().set_scrollback(0); - let _ = self.terminal.write_all(bytes); - } - } - - pub fn paste(&mut self, text: &str) { - if self.screen().bracketed_paste() { - self.send(format!("\x1b[200~{text}\x1b[201~").as_bytes()); - } else { - self.send(text.as_bytes()); - } - } - - /// What a terminal sends for a key, in the mode the command has asked for. - pub fn key(&mut self, key: &KeyEvent) { - let mut bytes = key_bytes(key); - if self.screen().application_cursor() && bytes.len() == 3 && bytes.starts_with(b"\x1b[") { - bytes[1] = b'O'; - } - self.send(&bytes); - } -} - -impl Drop for Session { - /// Interrupt what still runs, as Ctrl+C would: through sudo on a host a - /// hang-up alone does not reach it. Then end the command. - fn drop(&mut self) { - if self.running() { - self.send(&[3]); - std::thread::sleep(std::time::Duration::from_millis(200)); - } - let _ = self.child.kill(); - let _ = self.child.wait(); - } -} - -/// What a terminal sends for a key. -pub fn key_bytes(key: &KeyEvent) -> Vec { - crate::keys::key(key).map_or(vec![], |key| berth_tui::event::key_bytes(&key)) -} - -#[cfg(test)] -mod tests { - use super::*; - use crossterm::event::{KeyCode, KeyModifiers}; - - #[test] - fn a_session_shows_output_and_takes_input() { - let mut command = Command::new("sh"); - command.args([ - "-c", - "printf 'code? '; read code; printf 'got %s\\r\\n' \"$code\"", - ]); - let mut session = Session::start("demo", command, 5, 40).unwrap(); - let wait = |session: &mut Session, text: &str| { - for _ in 0..200 { - session.tick(); - if session.screen().contents().contains(text) { - return; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } - panic!("no {text:?} in {:?}", session.screen().contents()); - }; - wait(&mut session, "code?"); - assert!(session.running()); - for key in [KeyCode::Char('4'), KeyCode::Char('2'), KeyCode::Enter] { - session.key(&KeyEvent::new(key, KeyModifiers::NONE)); - } - wait(&mut session, "got 42"); - for _ in 0..200 { - session.tick(); - if !session.running() { - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } - assert_eq!(session.outcome, Some(true)); - // A question about the cursor position is answered. - let mut command = Command::new("sh"); - command.args([ - "-c", - "stty raw -echo; printf 'ab\\033[6n'; dd bs=1 count=6 2>/dev/null | od -c", - ]); - let mut session = Session::start("demo", command, 5, 40).unwrap(); - wait(&mut session, "[ 1 ; 3"); - // The command sees the size, and a new one. - let mut command = Command::new("sh"); - command.args(["-c", "stty size; read go; stty size"]); - let mut session = Session::start("demo", command, 5, 40).unwrap(); - wait(&mut session, "5 40"); - session.resize(7, 50); - session.send(b"\r"); - wait(&mut session, "7 50"); - let alt = KeyEvent::new(KeyCode::Char('b'), KeyModifiers::ALT); - assert_eq!(key_bytes(&alt), b"\x1bb"); - let control = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL); - assert_eq!(key_bytes(&control), vec![3]); - } -} diff --git a/crates/berth/src/ui.rs b/crates/berth/src/ui.rs deleted file mode 100644 index aed30fc..0000000 --- a/crates/berth/src/ui.rs +++ /dev/null @@ -1,5276 +0,0 @@ -//! Drawing and input handling for the wizard. - -use crate::{ - Result, - app::{App, Entry, Item, Row}, - fields::{Action, Field, Kind, Step}, - job::Job, - paths::Paths, - registry::Store, - theme, -}; -use berth_tui::provisioners::MAKES; -use berth_tui::screen::{ - Platform, Spots, clear_hints, dialog, draw_arguments, draw_footer, draw_header, draw_panel, - draw_question, draw_view, ellipsize, hint_at, inside, note_hints, pasted, with_links, words, -}; -use crossterm::event::{ - Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind, -}; -use ratatui::{ - DefaultTerminal, Frame, - layout::{Constraint, Layout, Margin, Rect}, - style::Style, - text::{Line, Span}, - widgets::{Block, Clear, Gauge, List, ListItem, ListState, Padding, Paragraph, Wrap}, -}; -use serde_json::json; -use tui_input::{Input, InputRequest, backend::crossterm::EventHandler}; - -/// A clickable region of the last frame. -#[derive(Clone, Copy)] -enum Target { - Step(Step), - /// Index into the selectable rows. - Row(usize), - Suggestion(usize), - Button(KeyCode), - /// Text area of the editor, with its horizontal scroll. - Editor(usize), -} - -type Hits = Vec<(Rect, Target)>; - -enum Flow { - Continue, - Quit, - Run, -} - -fn buttons(app: &App) -> Vec<(&'static str, KeyCode)> { - let mut buttons = vec![]; - if app.path_selected() { - buttons.push(("[Browse F3]", KeyCode::F(3))); - } - if let Some(group) = app.selected_group() { - buttons.push(if app.group_all_on(group) { - ("[All off Space]", KeyCode::Char(' ')) - } else { - ("[All on Space]", KeyCode::Char(' ')) - }); - } - if app.selected_entry() == Some(Entry::Offer("terminal")) { - buttons.push(if app.as_agent { - ("[As the SSH user Space]", KeyCode::Char(' ')) - } else { - ("[As the agent Space]", KeyCode::Char(' ')) - }); - } - if let Some(field) = app.selected_field() { - if field.can_generate() { - buttons.push(("[Generate F4]", KeyCode::F(4))); - } - if field.is_password_hash() { - buttons.push(("[Set password F5]", KeyCode::F(5))); - } - if field.uses_saved_wifi() && !app.privileged { - buttons.push(("[Unlock saved passwords F5]", KeyCode::F(5))); - } - } - buttons -} - -fn draw(frame: &mut Frame, app: &mut App, rows: &[Row], display: &mut ListState, hits: &mut Hits) { - hits.clear(); - clear_hints(); - frame.render_widget(theme::backdrop(), frame.area()); - let area = frame.area().inner(Margin { - horizontal: 2, - vertical: 1, - }); - let [header, _, panel, _, footer] = Layout::vertical([ - Constraint::Length(1), - Constraint::Length(1), - Constraint::Min(4), - Constraint::Length(1), - Constraint::Length(1), - ]) - .areas(area); - let host = app.place.title(); - // The overview has no tabs; the set-up flow under it does. - let setup = app.step != Step::Manage; - let labels = Step::SETUP.map(Step::label); - let current = Step::SETUP.iter().position(|step| *step == app.step); - let tabs = draw_header( - frame, - header, - if setup { &labels[..] } else { &[][..] }, - current.unwrap_or(0), - &if setup { - format!("{host} › set-up") - } else { - host.to_string() - }, - ); - hits.extend( - tabs.into_iter() - .zip(Step::SETUP) - .map(|(rect, step)| (rect, Target::Step(step))), - ); - let [left, _, right] = Layout::horizontal([ - Constraint::Percentage(62), - Constraint::Length(2), - Constraint::Min(0), - ]) - .areas(panel); - - let editing = app.editing.is_some(); - let [body, editor, controls] = Layout::vertical([ - Constraint::Min(1), - Constraint::Length(if editing { 3 } else { 0 }), - Constraint::Length(if editing { 0 } else { 1 }), - ]) - .areas(left); - let buttons = buttons(app); - if !editing { - let mut x = controls.x; - for &(label, code) in &buttons { - let rect = Rect::new( - x, - controls.y, - (label.len() as u16).min(controls.right().saturating_sub(x)), - 1, - ); - frame.render_widget( - Paragraph::new(label).style(Style::new().fg(theme::ACCENT)), - rect, - ); - hits.push((rect, Target::Button(code))); - x += label.len() as u16 + 2; - } - } - - // Right column: detected values for the selected field above its description. - let [choices, help] = Layout::vertical([ - Constraint::Length(if app.suggestions.is_empty() { - 0 - } else { - (app.suggestions.len() as u16 + 2).min(10) - }), - Constraint::Min(3), - ]) - .areas(right); - if !app.suggestions.is_empty() { - let block = theme::panel("Suggestions · → to choose", app.suggestion_focus); - let width = choices.width.saturating_sub(4) as usize; - let labels = app - .suggestions - .iter() - .map(|(label, _)| ellipsize(label, width)) - .collect::>(); - frame.render_stateful_widget( - List::new(labels) - .block(block) - .highlight_style(Style::new().bg(theme::RAISED)), - choices, - &mut app.suggestion_list, - ); - for index in app.suggestion_list.offset()..app.suggestions.len() { - let y = choices.y + 1 + (index - app.suggestion_list.offset()) as u16; - if y + 1 >= choices.bottom() { - break; - } - hits.push(( - Rect::new(choices.x + 1, y, choices.width.saturating_sub(2), 1), - Target::Suggestion(index), - )); - } - } - frame.render_widget( - Paragraph::new(crate::markdown::render(&app.help())) - .block(theme::panel("Information", false)) - .wrap(Wrap { trim: false }), - help, - ); - - // Left column: the rows of the step. The cursor only stops on selectable ones. - let positions = rows - .iter() - .enumerate() - .filter_map(|(position, row)| row.entry.map(|_| position)) - .collect::>(); - display.select( - app.list - .selected() - .and_then(|index| positions.get(index).copied()), - ); - frame.render_stateful_widget( - List::new(rows.iter().map(|row| ListItem::new(row.line.clone()))) - .highlight_symbol(theme::cursor()) - .highlight_style(Style::new().bg(theme::RAISED)), - body, - display, - ); - for (index, &position) in positions.iter().enumerate() { - if position < display.offset() { - continue; - } - let y = body.y + (position - display.offset()) as u16; - if y >= body.bottom() { - break; - } - hits.push((Rect::new(body.x, y, body.width, 1), Target::Row(index))); - } - - if let Some(input) = &app.editing { - let secret = app.password_entry - || app - .selected_field() - .is_some_and(|field| field.spec().kind == Kind::Secret); - let width = editor.width.saturating_sub(2).max(1) as usize; - let (cursor, scroll, value) = if secret { - let cursor = input.cursor(); - ( - cursor, - cursor.saturating_sub(width - 1), - "•".repeat(input.value().chars().count()), - ) - } else { - ( - input.visual_cursor(), - input.visual_scroll(width), - input.value().to_owned(), - ) - }; - let name = match (app.password_entry, app.selected_entry()) { - (true, _) => " New password ".to_owned(), - (false, Some(Entry::Machine(pick))) => berth_tui::machine::editor_title(pick, &host), - _ => " Edit ".to_owned(), - }; - let mut title = vec![Span::raw(name.clone())]; - let mut x = editor.x + 1 + name.len() as u16; - for &(label, code) in &buttons { - title.push(Span::styled( - format!("{label} "), - Style::new().fg(theme::ACCENT).bold(), - )); - hits.push(( - Rect::new( - x, - editor.y, - (label.len() as u16).min(editor.right().saturating_sub(x + 1)), - 1, - ), - Target::Button(code), - )); - x += label.len() as u16 + 1; - } - frame.render_widget( - Paragraph::new(value) - .scroll((0, scroll.min(u16::MAX as usize) as u16)) - .block( - Block::bordered() - .title(Line::from(title)) - .border_style(Style::new().fg(theme::ACCENT)), - ), - editor, - ); - hits.push(( - editor.inner(Margin { - horizontal: 1, - vertical: 1, - }), - Target::Editor(scroll), - )); - if editor.width > 2 && editor.height > 2 && !app.suggestion_focus { - frame.set_cursor_position(( - editor.x + 1 + (cursor - scroll).min(width - 1) as u16, - editor.y + 1, - )); - } - } - - let keys = if editing { - format!( - "Enter accept · ↑↓ field · Tab next tab · Esc cancel · {}", - berth_tui::screen::COPY_FIELD - ) - } else { - match app.step { - Step::Manage => "↑↓ select · Enter choose · x unset · Ctrl+S save · q hosts", - _ => "↑↓ select · Enter choose · 1-4 tab · x unset · Ctrl+S save · Esc overview", - } - .to_owned() - }; - draw_footer(frame, footer, &keys, &app.status, theme::ACCENT); - if let Some(picker) = &mut app.picker { - picker.draw(frame); - } - if let Some(job) = &app.job { - // A job of the machine is named by what it does, not by the install method. - let action = match app.machine_job { - true => job.title.clone(), - false => app.action.label().to_owned(), - }; - (app.links, app.words) = draw_job(frame, job, &action, &app.status, area); - } - if let Some(session) = &app.session { - (app.links, app.words) = draw_session(frame, session, &app.status); - } - if let Some(view) = &app.host.view { - (app.links, app.words) = draw_view(frame, view, &app.status); - } - if let Some((question, _)) = &app.host.question { - draw_question(frame, question); - } - if let Some(question) = &app.machine.question { - draw_question(frame, question); - } - draw_arguments(frame, &app.host); - if app.choosing_drive { - let lines = app - .usb_drives - .iter() - .take(9) - .enumerate() - .map(|(index, (label, _))| Line::raw(ellipsize(&format!("{} {label}", index + 1), 56))) - .collect(); - dialog( - frame, - " Write to which USB drive? ", - " 1-9 choose · Esc cancel ", - lines, - ); - } - if let Some(question) = &app.confirm { - let lines = vec![ - Line::raw(ellipsize(question, 56)), - Line::styled( - "Everything on that drive will be lost.", - Style::new().fg(theme::WARN), - ), - ]; - dialog(frame, " Write to USB drive ", " y erase · n cancel ", lines); - } - if let Some(input) = &app.unlock { - let local = std::env::var("USER").unwrap_or_else(|_| "this user".into()); - let user = match (app.unlock_remote, app.text(Field::SshUser)) { - (false, _) => local, - (true, "") => format!("{local} on {}", app.text(Field::SshHost)), - (true, user) => format!("{user} on {}", app.text(Field::SshHost)), - }; - let kept = match app.unlock_remote { - true => "Kept until berth is closed. It is not stored.", - false => "Used once for sudo. It is not stored.", - }; - draw_unlock( - frame, - input, - app.unlock_failed, - app.unlock_reason, - &user, - kept, - ); - } - if let Some(qr) = &app.qr { - qr.draw(frame); - } -} - -/// Put text on the clipboard: with the desktop's own tool when there is one, -/// otherwise by asking the terminal (OSC 52). -fn copy_text(text: &str) -> bool { - use std::io::Write; - use std::process::{Command, Stdio}; - for (program, args) in [ - ("wl-copy", &[][..]), - ("xclip", &["-selection", "clipboard"][..]), - ("xsel", &["--clipboard", "--input"][..]), - ] { - if program == "wl-copy" && std::env::var_os("WAYLAND_DISPLAY").is_none() { - continue; - } - let child = Command::new(program) - .args(args) - .stdin(Stdio::piped()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .spawn(); - if let Ok(mut child) = child { - let written = child - .stdin - .take() - .is_some_and(|mut stdin| stdin.write_all(text.as_bytes()).is_ok()); - // xclip keeps running to serve the selection; only wl-copy is waited for. - if written - && (program != "wl-copy" || child.wait().is_ok_and(|status| status.success())) - { - return true; - } - } - } - const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - let mut encoded = String::new(); - for chunk in text.as_bytes().chunks(3) { - let bits = chunk.iter().enumerate().fold(0u32, |bits, (index, byte)| { - bits | (*byte as u32) << (16 - 8 * index) - }); - for index in 0..4 { - encoded.push(if index <= chunk.len() { - ALPHABET[(bits >> (18 - 6 * index) & 63) as usize] as char - } else { - '=' - }); - } - } - let mut out = std::io::stdout(); - write!(out, "\x1b]52;c;{encoded}\x07").is_ok() && out.flush().is_ok() -} - -/// What is on the desktop's clipboard, if it can be read. -fn paste_text() -> Option { - for (program, args) in [ - ("wl-paste", &["--no-newline"][..]), - ("xclip", &["-selection", "clipboard", "-o"][..]), - ("xsel", &["--clipboard", "--output"][..]), - ] { - if program == "wl-paste" && std::env::var_os("WAYLAND_DISPLAY").is_none() { - continue; - } - let output = std::process::Command::new(program) - .args(args) - .stdin(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .output(); - if let Ok(output) = output - && output.status.success() - { - return Some(String::from_utf8_lossy(&output.stdout).trim().to_owned()); - } - } - None -} - -/// Draw a running or finished job. Returns where its web addresses and its -/// words are, for opening and copying with the mouse. -fn draw_job(frame: &mut Frame, job: &Job, action: &str, note: &str, area: Rect) -> (Spots, Spots) { - let (keys, color) = match &job.outcome { - None => (" Esc cancel ", theme::ACCENT), - Some(Ok(())) if job.offers_usb(action, Action::Iso.label()) => { - (" w write to USB drive · Enter close ", theme::GOOD) - } - Some(Ok(())) => ( - " Enter close · Click opens a link · Right-click copies a value ", - theme::GOOD, - ), - Some(Err(_)) => (" Enter close · Right-click copies a value ", theme::BAD), - }; - // Output with a web address in it offers its QR code. - let shown = job.lines.iter().rev().take(area.height as usize); - let keys = match berth_tui::qr::any_link(shown.map(String::as_str)) { - true => format!(" {} · {} ", keys.trim(), berth_tui::qr::HINT), - false => keys.to_owned(), - }; - let title = if job.title == action { - format!(" {action} ") - } else { - format!(" {action} · {} ", job.title) - }; - note_hints( - keys.trim(), - area.x + 1, - area.bottom().saturating_sub(1), - true, - ); - let block = theme::popup(title.trim(), color) - .title_bottom(theme::hints(keys.trim())) - .title_bottom( - Line::styled( - if note.is_empty() { - String::new() - } else { - format!(" {note} ") - }, - Style::new().fg(theme::WARN), - ) - .right_aligned(), - ) - .padding(Padding::horizontal(1)); - let [meter, _, log] = Layout::vertical([ - Constraint::Length(2), - Constraint::Length(1), - Constraint::Min(0), - ]) - .areas(block.inner(area)); - frame.render_widget(Clear, area); - frame.render_widget(block, area); - match &job.outcome { - None => match job.progress { - Some(ratio) => frame.render_widget( - Gauge::default() - .ratio(ratio.clamp(0.0, 1.0)) - .gauge_style(Style::new().fg(theme::ACCENT).bg(theme::RAISED)), - Rect { height: 1, ..meter }, - ), - None => frame.render_widget( - Paragraph::new("Working…").style(Style::new().fg(theme::MUTED)), - meter, - ), - }, - Some(Ok(())) => frame.render_widget( - Paragraph::new(format!("✓ Done. {}", job.next)) - .wrap(Wrap { trim: true }) - .style(Style::new().fg(theme::GOOD)), - meter, - ), - Some(Err(error)) => frame.render_widget( - Paragraph::new(format!("✗ {error}")) - .wrap(Wrap { trim: true }) - .style(Style::new().fg(theme::BAD)), - meter, - ), - } - let first = job.lines.len().saturating_sub(log.height as usize); - let (mut links, mut copyable) = (vec![], vec![]); - let lines: Vec = job.lines[first..] - .iter() - .enumerate() - .map(|(row, line)| { - let mut x = log.x; - let shown = ellipsize(line, log.width as usize); - for (column, word) in words(&shown) { - if !word.ends_with('…') { - let width = Span::raw(word.as_str()).width() as u16; - copyable.push(( - Rect::new(log.x + column, log.y + row as u16, width, 1), - word, - )); - } - } - let spans = with_links(&shown) - .into_iter() - .map(|(text, link)| { - let span = if link { - Span::styled(text.clone(), Style::new().fg(theme::ACCENT).underlined()) - } else { - Span::raw(text.clone()) - }; - let width = span.width() as u16; - // A shortened address would open the wrong page. - if link && !text.ends_with('…') { - links.push((Rect::new(x, log.y + row as u16, width, 1), text)); - } - x += width; - span - }) - .collect::>(); - Line::from(spans) - }) - .collect(); - frame.render_widget( - Paragraph::new(lines).style(Style::new().fg(theme::MUTED)), - log, - ); - (links, copyable) -} - -/// Draw a command's terminal. Returns where its web addresses and its words -/// are, for opening and copying with the mouse. -fn draw_session( - frame: &mut Frame, - session: &crate::session::Session, - note: &str, -) -> (Spots, Spots) { - let keys = match session.outcome { - None => { - " Ctrl+V paste · Ctrl+Q close · Click opens a link · Right-click copies · Wheel scrolls " - } - Some(true) => " ✓ Done · Enter close ", - Some(false) => " ✗ It did not finish · Enter close ", - }; - draw_panel( - frame, - &session.title, - session.screen(), - session.outcome, - keys, - note, - ) -} - -/// The desktop this terminal runs on: its clipboard, and its way to open a link. -struct Desktop; - -impl Platform for Desktop { - fn copy(&mut self, text: &str) -> bool { - copy_text(text) - } - - fn paste(&mut self) -> Option { - paste_text() - } - - fn open(&mut self, link: &str) -> std::result::Result<(), String> { - std::process::Command::new("xdg-open") - .arg(link) - .stdin(std::process::Stdio::null()) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .spawn() - .map(drop) - .map_err(|error| error.to_string()) - } -} - -/// A click on a key hint is that key. -fn hint_click(event: Event) -> Event { - if let Event::Mouse(mouse) = &event - && mouse.kind == MouseEventKind::Down(MouseButton::Left) - && let Some(key) = hint_at(mouse.column, mouse.row) - { - return Event::Key(crate::keys::native(key)); - } - event -} - -/// Alt+R over a panel shows its links as QR codes, and the overlay takes -/// every key while it is open. -fn qr_event(app: &mut App, event: &Event) -> bool { - let Some(event) = crate::keys::event(event) else { - return app.qr.is_some(); - }; - let mut said = None; - let taken = berth_tui::qr::take(&mut app.qr, &app.links, &event, &mut said); - if let Some(said) = said { - app.status = said; - } - taken -} - -/// A click on a web address opens it here; a right-click on a word copies it. -fn spot_event(app: &mut App, event: &Event) -> bool { - let said = crate::keys::event(event).and_then(|event| { - berth_tui::screen::spot_event(&app.links, &app.words, &event, &mut Desktop) - }); - match said { - Some(said) => { - if !said.is_empty() { - app.status = said; - } - true - } - None => false, - } -} - -fn session_event(app: &mut App, event: &Event) { - if qr_event(app, event) || spot_event(app, event) { - return; - } - let Some(session) = &mut app.session else { - return; - }; - match event { - Event::Mouse(mouse) if mouse.kind == MouseEventKind::ScrollUp => session.scroll(3), - Event::Mouse(mouse) if mouse.kind == MouseEventKind::ScrollDown => session.scroll(-3), - Event::Paste(text) => { - session.paste(text); - app.status = pasted(text); - } - Event::Key(key) if key.kind != KeyEventKind::Release => { - let control = key.modifiers.contains(KeyModifiers::CONTROL); - if control && key.code == KeyCode::Char('q') { - app.session = None; - } else if control && key.code == KeyCode::Char('v') { - // Terminals that keep Ctrl+V to themselves paste by their own means. - app.status = match paste_text() { - Some(text) => { - session.paste(&text); - pasted(&text) - } - None => "Could not read the clipboard".into(), - }; - } else if session.running() { - session.key(key); - } else if matches!(key.code, KeyCode::Enter | KeyCode::Esc | KeyCode::Char('q')) { - let title = session.title.clone(); - app.status = match session.outcome { - Some(true) => format!("{title} finished"), - _ => format!("{title} did not finish"), - }; - app.session = None; - } - } - _ => {} - } -} - -/// Keys and the mouse while a session of the host is in the panel. -fn view_event(app: &mut App, event: &Event) { - if qr_event(app, event) { - return; - } - if let Some(event) = crate::keys::event(event) - && let Some(said) = berth_tui::screen::view_event( - &mut app.host, - &app.links, - &app.words, - &event, - &mut Desktop, - ) - { - app.status = said; - } -} - -/// The yes-or-no question before an action or before applying. -fn question_event(app: &mut App, event: &Event) -> Flow { - let Event::Key(key) = event else { - return Flow::Continue; - }; - match key.code { - KeyCode::Char('y' | 'Y') => match app.host.question.take() { - Some((_, crate::remote::Pending::Action(index))) => app.begin_action(index, true), - Some((_, crate::remote::Pending::Apply)) => return apply(app, true), - None => {} - }, - KeyCode::Char('n' | 'N') | KeyCode::Esc => app.host.question = None, - _ => {} - } - Flow::Continue -} - -/// The dialog that asks for an action's arguments. -fn arguments_event(app: &mut App, event: &Event, platform: &mut dyn Platform) { - let Some(event) = crate::keys::event(event) else { - return; - }; - let mut said = None; - let accepted = berth_tui::screen::arguments_event(&mut app.host, &event, platform, &mut said); - if let Some(said) = said { - app.status = said; - } - if accepted { - app.accept_argument(); - } -} - -/// Applying the configuration is the SSH install, run from the overview. It -/// may replace the host's controller, which ends the sessions running there. -fn apply(app: &mut App, confirmed: bool) -> Flow { - let running = app - .host - .sessions - .iter() - .filter(|session| session.running()) - .count(); - if running > 0 && !confirmed { - let question = format!( - "{running} session{} on the host. Applying can restart berth's controller there, which ends them. Apply anyway?", - if running == 1 { - " is running" - } else { - "s are running" - } - ); - app.host.question = Some((question, crate::remote::Pending::Apply)); - return Flow::Continue; - } - app.action = Action::Ssh; - let problems = app.problems(); - app.action = Action::Manage; - if problems.is_empty() { - app.terminal_action = Some(Action::Ssh); - // What the host can do may be different afterwards. - app.host.disconnect(); - return Flow::Run; - } - app.status = problems[0].clone(); - Flow::Continue -} - -fn job_event(app: &mut App, event: &Event) { - if qr_event(app, event) || spot_event(app, event) { - return; - } - let (Some(job), Event::Key(key)) = (&mut app.job, event) else { - return; - }; - if key.kind == KeyEventKind::Release { - return; - } - let interrupt = key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL); - if job.running() { - if key.code == KeyCode::Esc || interrupt { - job.cancel(); - } - } else if key.code == KeyCode::Char('w') - && job.offers_usb(app.action.label(), Action::Iso.label()) - { - app.write_built_iso(None); - } else if matches!(key.code, KeyCode::Enter | KeyCode::Esc | KeyCode::Char('q')) || interrupt { - app.close_job(); - } -} - -fn confirm_event(app: &mut App, event: &Event) { - let Event::Key(key) = event else { - return; - }; - match key.code { - KeyCode::Char('y' | 'Y') => { - app.confirm = None; - app.run(true); - } - KeyCode::Char('n' | 'N') | KeyCode::Esc => { - app.confirm = None; - app.write_only = false; - } - _ => {} - } -} - -fn draw_unlock( - frame: &mut Frame, - input: &Input, - failed: bool, - reason: &str, - user: &str, - kept: &'static str, -) { - let typed = input.value().chars().count().min(54); - let note = if failed { - Line::styled("Wrong password. Try again.", Style::new().fg(theme::BAD)) - } else { - Line::styled(kept, Style::new().fg(theme::MUTED)) - }; - let lines = vec![ - Line::raw(reason.to_owned()), - note, - Line::raw(""), - Line::from(vec![ - Span::styled("› ", Style::new().fg(theme::ACCENT)), - Span::raw("•".repeat(typed)), - ]), - ]; - let title = ellipsize(&format!(" Password for {user} "), 58); - let area = dialog( - frame, - &title, - " Enter unlock · Esc cancel · Ctrl+O copy ", - lines, - ); - if area.width > 6 && area.height > 5 { - frame.set_cursor_position((area.x + 4 + typed as u16, area.y + 4)); - } -} - -fn unlock_event(app: &mut App, event: &Event, platform: &mut dyn Platform) { - let Some(input) = &mut app.unlock else { - return; - }; - match event { - Event::Key(key) if key.kind != KeyEventKind::Release => match key.code { - KeyCode::Char('o') if key.modifiers.contains(KeyModifiers::CONTROL) => { - app.status = berth_tui::screen::copy_field(platform, input); - } - KeyCode::Esc => { - app.unlock = None; - app.unlock_remote = false; - app.pending_run = false; - app.write_only = false; - } - KeyCode::Enter => app.submit_unlock(), - KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => input.reset(), - _ => { - input.handle_event(event); - } - }, - Event::Paste(text) => { - for ch in text.chars().filter(|ch| !ch.is_control()) { - input.handle(InputRequest::InsertChar(ch)); - } - } - _ => {} - } -} - -fn picker_event(app: &mut App, event: &Event) { - let Some(picker) = &mut app.picker else { - return; - }; - let mut choose = false; - let mut selected = None; - match event { - Event::Key(key) if key.kind != KeyEventKind::Release => match key.code { - KeyCode::Esc => { - app.picker = None; - return; - } - KeyCode::Up => picker.move_by(true), - KeyCode::Down => picker.move_by(false), - KeyCode::Enter if key.modifiers.contains(KeyModifiers::CONTROL) => { - selected = Some(picker.directory.display().to_string()) - } - KeyCode::Enter => choose = true, - _ => {} - }, - Event::Mouse(mouse) if inside(picker.area, mouse.column, mouse.row) => match mouse.kind { - MouseEventKind::ScrollUp => picker.move_by(true), - MouseEventKind::ScrollDown => picker.move_by(false), - MouseEventKind::Down(MouseButton::Left) - if mouse.row > picker.area.y && mouse.row + 1 < picker.area.bottom() => - { - let index = picker.state.offset() + (mouse.row - picker.area.y - 1) as usize; - if index < picker.entries.len() { - picker.state.select(Some(index)); - choose = true; - } - } - _ => {} - }, - _ => {} - } - if choose { - match picker.choose() { - Ok(value) => selected = value, - Err(error) => app.status = error.to_string(), - } - } - if let Some(path) = selected { - app.picker = None; - app.password_entry = false; - app.editing = Some(Input::new(path)); - app.accept_edit(); - } -} - -fn move_suggestion(app: &mut App, up: bool) { - let index = app.suggestion_list.selected().unwrap_or(0); - app.suggestion_list.select(Some(if up { - index.saturating_sub(1) - } else { - (index + 1).min(app.suggestions.len().saturating_sub(1)) - })); -} - -/// Handle a mouse event. Clicks on rows and buttons come back as the key they stand for. -fn mouse_event(app: &mut App, mouse: MouseEvent, hits: &Hits) -> Option { - let target = hits - .iter() - .rev() - .find(|(rect, _)| inside(*rect, mouse.column, mouse.row)) - .copied(); - let key = |code| Some(KeyEvent::new(code, KeyModifiers::NONE)); - match mouse.kind { - MouseEventKind::ScrollUp | MouseEventKind::ScrollDown => { - let up = mouse.kind == MouseEventKind::ScrollUp; - if matches!(target, Some((_, Target::Suggestion(_)))) { - move_suggestion(app, up); - app.suggestion_focus = true; - } else { - app.accept_edit(); - app.move_selection(up); - } - None - } - MouseEventKind::Down(MouseButton::Left) => match target? { - (_, Target::Step(step)) => { - app.accept_edit(); - app.set_step(step); - None - } - (_, Target::Row(index)) => { - app.accept_edit(); - app.list.select(Some(index)); - app.suggestion_focus = false; - key(KeyCode::Enter) - } - (_, Target::Suggestion(index)) => { - app.suggestion_list.select(Some(index)); - app.select_suggestion(); - None - } - (_, Target::Button(code)) => key(code), - (rect, Target::Editor(scroll)) => { - if let Some(input) = &mut app.editing { - let column = (mouse.column - rect.x) as usize + scroll; - let mut width = 0; - let cursor = input - .value() - .chars() - .take_while(|ch| { - width += Span::raw(ch.to_string()).width(); - width <= column - }) - .count(); - input.handle(InputRequest::SetCursor(cursor)); - } - None - } - }, - _ => None, - } -} - -fn choose(app: &mut App, entry: Entry) -> Flow { - match entry { - Entry::Action(action) => { - app.action = action.choose(&mut app.config); - berth_tui::setup::fit_target(&mut app.config, app.action); - } - Entry::Field(field) => app.activate(field), - Entry::Setup => app.set_step(Step::Install), - Entry::HostRegistry(index) => app.toggle_host_registry(index), - Entry::HostSecret(index) => app.editing = Some(Input::new(app.host_secret(index))), - // A key is pasted whole, not changed letter by letter. - Entry::Key(..) => app.editing = Some(Input::default()), - Entry::Group(_) => app.status = "Space switches the whole group".into(), - Entry::Feature(index) => { - let item = Item::Feature(index); - app.set_item(item, !app.item_enabled(item)); - } - Entry::HostAction(index) => app.begin_action(index, false), - Entry::HostSession(index) => { - if let Some(session) = app.host.sessions.get(index).cloned() { - app.host.open(&session); - } - } - Entry::Offer("terminal") => app.start_host_shell(), - Entry::Offer("ssh") => { - let (rows, cols) = session_size(); - app.start_shell(rows, cols); - } - Entry::Offer("connect") => app.reconnect_host(), - Entry::Offer("address") => app.edit_address(), - Entry::Offer("apply") => return apply(app, false), - Entry::Offer("install-controller") => { - let _ = app.save(); - app.own_command = Some( - ["host", "install", &app.place.argument()] - .map(str::to_owned) - .to_vec(), - ); - } - Entry::Machine(pick) => app.machine_enter(pick), - Entry::Save => { - save(app); - } - Entry::Offer(_) => {} - Entry::Run => { - if !app.problems().is_empty() { - app.status = "Fix the listed problems first".into(); - } else if app.leaves_ui() { - return Flow::Run; - } else { - app.write_only = false; - app.run(false); - } - } - } - Flow::Continue -} - -/// Save the profile and say how that went. -fn save(app: &mut App) -> bool { - let saved = app.save(); - let done = saved.is_ok(); - app.status = match saved { - Ok(()) => app.saved_note(), - Err(error) => format!("Save failed · {error}"), - }; - done -} - -/// The size of the terminal panel for the window as it is now. -fn session_size() -> (u16, u16) { - let (width, height) = crossterm::terminal::size().unwrap_or((100, 30)); - ( - height.saturating_sub(4).max(4), - width.saturating_sub(8).max(20), - ) -} - -fn key_event( - app: &mut App, - key: KeyEvent, - quit_armed: &mut bool, - platform: &mut dyn Platform, -) -> Flow { - let armed = std::mem::take(quit_armed); - let control = key.modifiers.contains(KeyModifiers::CONTROL); - match key.code { - KeyCode::Char('s') if control => { - app.accept_edit(); - save(app); - return Flow::Continue; - } - KeyCode::F(3) => { - app.open_picker(); - return Flow::Continue; - } - KeyCode::F(4) if app.selected_field().is_some_and(Field::can_generate) => { - app.cancel_edit(); - if let Err(error) = app.generate() { - app.status = error.to_string(); - } - return Flow::Continue; - } - KeyCode::F(5) if app.selected_field().is_some_and(Field::is_password_hash) => { - app.password_entry = true; - app.editing = Some(Input::default()); - return Flow::Continue; - } - KeyCode::F(5) - if !app.privileged && app.selected_field().is_some_and(Field::uses_saved_wifi) => - { - app.accept_edit(); - app.request_unlock("Read the Wi-Fi passwords saved on this machine."); - return Flow::Continue; - } - KeyCode::Tab | KeyCode::BackTab => { - app.accept_edit(); - let step = app - .step - .offset(if key.code == KeyCode::Tab { 1 } else { -1 }); - if step != app.step { - app.set_step(step); - } - return Flow::Continue; - } - KeyCode::F(2) if !app.suggestions.is_empty() => { - app.suggestion_focus = !app.suggestion_focus; - return Flow::Continue; - } - _ => {} - } - if app.suggestion_focus { - match key.code { - KeyCode::Up => move_suggestion(app, true), - KeyCode::Down => move_suggestion(app, false), - KeyCode::Enter => app.select_suggestion(), - KeyCode::Left | KeyCode::Esc => app.suggestion_focus = false, - _ => {} - } - return Flow::Continue; - } - if let Some(input) = &mut app.editing { - match key.code { - KeyCode::Esc => { - app.retry_address = false; - app.cancel_edit(); - } - KeyCode::Enter => { - let retry = std::mem::take(&mut app.retry_address); - app.accept_edit(); - if retry && save(app) { - // Back on the overview, which asks the host at its new address. - app.set_step(Step::Manage); - app.reconnect_host(); - } - } - KeyCode::Up | KeyCode::Down => { - app.accept_edit(); - app.move_selection(key.code == KeyCode::Up); - } - KeyCode::Char('u') if control => input.reset(), - KeyCode::Char('o') if control => { - app.status = berth_tui::screen::copy_field(platform, input); - } - _ => { - input.handle_event(&Event::Key(key)); - } - } - return Flow::Continue; - } - match key.code { - KeyCode::Up => app.move_selection(true), - KeyCode::Down => app.move_selection(false), - KeyCode::Right if !app.suggestions.is_empty() => app.suggestion_focus = true, - KeyCode::Char(digit @ '1'..='9') => { - if app.step != Step::Manage - && let Some(&step) = Step::SETUP.get(digit as usize - '1' as usize) - { - app.set_step(step); - } - } - KeyCode::Char(' ') => match app.selected_entry() { - Some(Entry::Group(group)) => app.toggle_group(group), - Some(Entry::Offer("terminal")) => app.as_agent = !app.as_agent, - Some( - entry @ (Entry::Field(_) - | Entry::Feature(..) - | Entry::HostRegistry(_) - | Entry::Machine( - berth_tui::machine::Pick::Provisioner | berth_tui::machine::Pick::Argument(_), - )), - ) => { - return choose(app, entry); - } - _ => {} - }, - KeyCode::Char('x') | KeyCode::Delete => { - if let Some(Entry::Key(account, Some(index))) = app.selected_entry() - && berth_tui::setup::set_key(&mut app.config, account, Some(index), "").is_ok() - { - app.status = "SSH key removed".into(); - } - if let Some(Entry::HostSecret(index)) = app.selected_entry() { - app.set_host_secret(index, ""); - } - if let Some(Entry::HostSession(index)) = app.selected_entry() - && let Some(session) = app.host.sessions.get(index) - { - if session.running() { - app.status = "It is still running. Open it and end it first.".into(); - } else { - app.status = format!("Forgot {}", session.title); - app.host - .send(crate::remote::Request::Delete(session.id.clone())); - } - } - if let Some(field) = app.selected_field() { - app.clear(field); - } - } - // Leaving the set-up flow returns to the host's overview. - KeyCode::Char('q') | KeyCode::Esc if app.step != Step::Manage => app.set_step(Step::Manage), - KeyCode::Char('q') | KeyCode::Esc => { - if armed || !app.unsaved() { - return Flow::Quit; - } - *quit_armed = true; - app.status = "Unsaved changes · Ctrl+S saves, q again discards".into(); - } - KeyCode::Enter => { - if let Some(entry) = app.selected_entry() { - return choose(app, entry); - } - } - _ => {} - } - Flow::Continue -} - -/// What the home screen is showing. -enum HomeMode { - Hosts, - Naming(Input), - /// The selected setting, and its editor while it is being changed. - Settings(usize, Option), - Registries(RegistryView), - Secrets(SecretView), - Plugins(PluginView), - Provisioners(Box), -} - -/// A clickable region of the home screen. -#[derive(Clone, Copy)] -enum HomeTarget { - /// Hosts, Settings or Registries. - Tab(usize), - Row(usize), -} - -/// The Registries tab: the selected row, its editor while something is typed, -/// and whether a registry's removal waits for a second x. -#[derive(Default)] -struct RegistryView { - selected: usize, - editor: Option, - armed: bool, - /// The result of the last check, shown until the selection moves. - report: Vec, -} - -/// A row of the Registries tab. Registries are named, repositories numbered. -#[derive(Clone, PartialEq, Debug)] -enum RegistryRow { - Name(String), - Type(String), - Address(String), - User(String), - Password(String), - Repository(String, usize), - Format(String, usize), - DockerAddress(String, usize), - AddRepository(String), - AddRegistry, -} - -impl RegistryRow { - /// The registry a row belongs to. - fn registry(&self) -> Option<&str> { - use RegistryRow::*; - match self { - Name(name) - | Type(name) - | Address(name) - | User(name) - | Password(name) - | Repository(name, _) - | Format(name, _) - | DockerAddress(name, _) - | AddRepository(name) => Some(name), - AddRegistry => None, - } - } - - fn help(&self) -> &'static str { - use RegistryRow::*; - match self { - Name(_) => { - "A registry: a server packages, files or images come from and go to. Enter renames it, x removes it with its stored login. Hosts get a registry with: berth host HOST registry NAME on." - } - Type(_) => { - "Enter switches the kind. Sonatype Nexus: one server and login with repositories under it. npm registry: any npm-compatible registry at this address. File server: an address files are uploaded to with HTTP PUT, for the release archive. Docker registry: any registry for container images." - } - Address(_) => { - "Where the registry is. With https:// for Nexus, npm and file servers; a Docker registry is HOST or HOST:PORT." - } - User(_) => { - "The account to log in with. Leave it empty when the registry takes a token alone, such as an npm token. x clears it." - } - Password(_) => { - "The password or token. It is kept in berth's store with the secrets, and is never shown. x forgets it." - } - Repository(..) => { - "A repository on the Nexus server, by its name there. Enter renames it, x removes it from this list." - } - Format(..) => { - "Enter switches the format. npm: becomes the agent's npm registry. raw: a place to publish the release archive. docker: container images." - } - DockerAddress(..) => { - "Leave it empty when the repository uses path based routing in Nexus: images are then at HOST/REPOSITORY/IMAGE. With a connector on a port or host name of its own, enter that as HOST:PORT." - } - AddRepository(_) => { - "Add a repository of this Nexus server. Type its name; it starts as npm and Format changes that." - } - AddRegistry => { - "Add a registry. Type a short name for it (lower-case letters, digits, - and _), then set its kind and address." - } - } - } -} - -/// The rows of the Registries tab with what they show. -fn registry_rows(store: Option<&Store>) -> Vec<(RegistryRow, Line<'static>)> { - use RegistryRow::*; - let muted = Style::new().fg(theme::MUTED); - let field = |prefix: &str, label: &str, value: &str| { - let mut line = crate::app::value_line(label, value, Kind::Text); - line.spans.insert(0, Span::styled(prefix.to_owned(), muted)); - line - }; - let mut rows = vec![]; - let registries = store.and_then(|store| store.registries().ok()); - for (name, registry) in registries.unwrap_or_default() { - let text = |key: &str| registry[key].as_str().unwrap_or("").to_owned(); - let nexus = registry["type"] == "nexus"; - rows.push(( - Name(name.clone()), - Line::styled(name.clone(), Style::new().fg(theme::ACCENT).bold()), - )); - rows.push(( - Type(name.clone()), - field(" ├─ ", "Kind", crate::registry::type_label(&text("type"))), - )); - rows.push(( - Address(name.clone()), - field(" ├─ ", "Address", &text("url")), - )); - rows.push(( - User(name.clone()), - field(" ├─ ", "User name", &text("username")), - )); - let stored = store - .and_then(|store| store.has_secret(&format!("registry/{name}")).ok()) - .unwrap_or(false); - let mut password = Line::from(vec![ - Span::styled(if nexus { " ├─ " } else { " └─ " }, muted), - Span::styled("Password or token ", Style::new().fg(theme::TEXT)), - ]); - password.spans.push(match stored { - true => Span::styled("● stored", Style::new().fg(theme::GOOD)), - false => Span::styled("○ not set", muted), - }); - rows.push((Password(name.clone()), password)); - if !nexus { - continue; - } - let repositories = registry["repositories"] - .as_array() - .cloned() - .unwrap_or_default(); - for (index, repository) in repositories.iter().enumerate() { - let repo = repository["name"].as_str().unwrap_or(""); - let format = repository["format"].as_str().unwrap_or(""); - let mut line = field(" ├─ ", "Repository", repo); - if format != "docker" { - line.spans.push(Span::styled( - format!(" {}", crate::registry::repository_url(®istry, repo)), - muted, - )); - } - rows.push((Repository(name.clone(), index), line)); - let last = if format == "docker" { - " │ ├─ " - } else { - " │ └─ " - }; - rows.push((Format(name.clone(), index), field(last, "Format", format))); - if format == "docker" { - let line = match repository["address"] - .as_str() - .filter(|address| !address.is_empty()) - { - Some(address) => field(" │ └─ ", "Docker address", address), - None => Line::from(vec![ - Span::styled(" │ └─ ", muted), - Span::styled("Docker address ", Style::new().fg(theme::TEXT)), - Span::styled( - format!( - "Default · {} (path based routing)", - crate::registry::docker_address(®istry, repository) - ), - muted.italic(), - ), - ]), - }; - rows.push((DockerAddress(name.clone(), index), line)); - } - } - rows.push(( - AddRepository(name.clone()), - Line::from(vec![ - Span::styled(" └─ ", muted), - Span::styled("+ Add repository", Style::new().fg(theme::ACCENT)), - ]), - )); - } - rows.push(( - AddRegistry, - Line::styled("+ Add registry", Style::new().fg(theme::ACCENT)), - )); - rows -} - -/// The Plugins tab: its rows and editor, the plugins of this machine or of -/// the berth server as they were last read, and what the last change said. -#[derive(Default)] -struct PluginView { - tab: berth_tui::plugins::Tab, - editor: Option, - listing: Option>, - report: Vec, - /// The lines of a roll-out that runs, as they come. - rolling: Option>, -} - -/// The lines a roll-out writes, sent on one by one; only its own, not what -/// Ansible says. -struct RolloutLines { - sender: std::sync::mpsc::Sender, - pending: Vec, -} - -impl std::io::Write for RolloutLines { - fn write(&mut self, data: &[u8]) -> std::io::Result { - self.pending.extend_from_slice(data); - while let Some(end) = self.pending.iter().position(|byte| *byte == b'\n') { - let line: Vec = self.pending.drain(..=end).collect(); - let line = String::from_utf8_lossy(&line).trim_end().to_owned(); - if berth_tui::plugins::rollout_line(&line) { - let _ = self.sender.send(line); - } - } - Ok(data.len()) - } - - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } -} - -impl PluginView { - /// Read the plugins, unless they were read since the last change. - fn load(&mut self, paths: &Paths) { - if self.listing.is_none() { - let listed = crate::plugins::Manager::new(paths).list(); - self.listing = Some(listed.map_err(|error| error.to_string())); - } - } - - fn plugins(&self) -> &[berth_api::PluginInfo] { - match &self.listing { - Some(Ok(listing)) => &listing.plugins, - _ => &[], - } - } - - /// Take in what a roll-out that runs has said since. - fn pump(&mut self, status: &mut String) { - let Some(lines) = &self.rolling else { - return; - }; - loop { - match lines.try_recv() { - Ok(line) => { - *status = line.clone(); - self.report.push(line); - } - Err(std::sync::mpsc::TryRecvError::Empty) => return, - Err(std::sync::mpsc::TryRecvError::Disconnected) => { - self.rolling = None; - return; - } - } - } - } - - /// Start a roll-out in the background, its lines shown as they come. - fn roll_out(&mut self, paths: &Paths, options: berth_api::Rollout) { - let (sender, receiver) = std::sync::mpsc::channel(); - let paths = paths.clone(); - self.report = vec!["Rolling out…".into()]; - self.tab.behind.clear(); - self.rolling = Some(receiver); - std::thread::spawn(move || { - let mut out = RolloutLines { - sender: sender.clone(), - pending: vec![], - }; - let said = match crate::commands::rollout(&paths, &options, false, &mut out) { - Ok(report) => crate::commands::rollout_summary(&report), - Err(error) => format!("✗ {error}"), - }; - for line in said.lines() { - let _ = sender.send(line.to_owned()); - } - }); - } - - /// Show what a change said, and read the plugins again. - fn changed(&mut self, done: Result>, status: &mut String) { - self.report = match done { - Ok(lines) => lines, - Err(error) => error.to_string().lines().map(str::to_owned).collect(), - }; - *status = berth_tui::plugins::status(&self.report); - self.listing = None; - } -} - -/// Where the plugins of the Plugins tab are: here, or on the berth server. -fn plugin_place(server: &Option) -> berth_tui::plugins::Place<'_> { - match server { - Some(server) => berth_tui::plugins::Place::Server(&server.url), - None => berth_tui::plugins::Place::Here, - } -} - -/// Handle a key on the Plugins tab. -fn plugins_key( - view: &mut PluginView, - paths: &Paths, - key: KeyEvent, - status: &mut String, -) -> Outcome { - use berth_tui::plugins::Asked; - view.load(paths); - let server = berth_core::server::Server::configured(paths); - let plugins = view.plugins().to_vec(); - let Some(shared) = crate::keys::key(&key) else { - return Outcome::Stay; - }; - let place = plugin_place(&server); - match view - .tab - .key(shared, &mut view.editor, &plugins, &mut view.report, &place) - { - Asked::Nothing(said) => { - if let Some(said) = said { - *status = said; - } - } - Asked::Install(spec) => { - let done = crate::plugins::Manager::new(paths).add(&spec); - view.changed(done, status); - } - Asked::Remove(id) => { - let done = crate::plugins::Manager::new(paths).remove(&id); - view.changed(done, status); - } - Asked::Check => match crate::plugins::Manager::new(paths).check() { - Ok(checked) => { - view.report = view.tab.checked(checked.plugins); - *status = berth_tui::plugins::status(&view.report); - } - Err(error) => view.changed(Err(error), status), - }, - Asked::Update(id) => { - let manager = crate::plugins::Manager::new(paths); - match manager.update(id.as_deref()) { - Ok(mut report) => { - if manager.server().is_none() { - report.behind = berth_core::rollout::survey(paths); - } - let lines = view.tab.updated(report); - view.changed(Ok(lines), status); - } - Err(error) => view.changed(Err(error), status), - } - } - Asked::Rollout(_) if view.rolling.is_some() => { - *status = "A roll-out runs already".into(); - } - Asked::Rollout(options) => view.roll_out(paths, options), - Asked::Other => match leave_tab(key, tabs::PLUGINS) { - Outcome::Stay => {} - outcome => return outcome, - }, - } - Outcome::Stay -} - -/// The Secrets tab: the selected row, the editor, the name a typed value is -/// for, and whether a removal waits for a second x. -#[derive(Default)] -struct SecretView { - selected: usize, - editor: Option, - /// A new secret's name, while its value is being typed. - naming: Option, - armed: bool, -} - -/// Handle a key on the Secrets tab. The row after the last secret adds one. -fn secrets_key( - view: &mut SecretView, - paths: &Paths, - key: KeyEvent, - status: &mut String, -) -> Outcome { - let store = match Store::new(paths) { - Ok(store) => store, - Err(error) => { - *status = error.to_string(); - return leave_tab(key, tabs::SECRETS); - } - }; - let names = store.secret_names(); - view.selected = view.selected.min(names.len()); - let selected = names.get(view.selected).cloned(); - if let Some(input) = &mut view.editor { - match key.code { - KeyCode::Esc => { - view.editor = None; - view.naming = None; - } - KeyCode::Enter => { - let typed = input.value().to_owned(); - // A name was typed for a new secret: its value comes next. - if selected.is_none() && view.naming.is_none() { - let name = typed.trim(); - if !crate::plugins::valid_name(name) { - *status = "Use lower-case letters, digits, - and _, starting with a letter" - .into(); - } else if names.iter().any(|known| known == name) { - *status = format!("There is a secret {name} already"); - } else { - view.naming = Some(name.to_owned()); - view.editor = Some(Input::default()); - *status = format!("Now the value of {name}"); - } - return Outcome::Stay; - } - let name = view.naming.take().or(selected).unwrap_or_default(); - view.editor = None; - if typed.is_empty() { - *status = "Nothing entered, kept as it was".into(); - return Outcome::Stay; - } - *status = match store.set_secret(&name, Some(&typed)) { - Ok(()) => format!("Stored {name}"), - Err(error) => error.to_string(), - }; - let listed = store.secret_names(); - view.selected = listed - .iter() - .position(|known| *known == name) - .unwrap_or(view.selected); - } - _ => { - input.handle_event(&Event::Key(key)); - } - } - return Outcome::Stay; - } - let armed = std::mem::take(&mut view.armed); - match key.code { - KeyCode::Up => view.selected = view.selected.saturating_sub(1), - KeyCode::Down => view.selected = (view.selected + 1).min(names.len()), - KeyCode::Enter => view.editor = Some(Input::default()), - KeyCode::Char('x') | KeyCode::Delete => match selected { - Some(name) if armed => { - *status = match store.set_secret(&name, None) { - Ok(()) => format!("Removed {name}"), - Err(error) => error.to_string(), - } - } - Some(name) => { - view.armed = true; - *status = format!("x again removes {name}"); - } - None => {} - }, - _ => return leave_tab(key, tabs::SECRETS), - } - Outcome::Stay -} - -/// The tabs of the home screen, in their order; a digit key is one more -/// than the index. -pub(crate) mod tabs { - pub const HOSTS: usize = 0; - pub const PROVISIONERS: usize = 1; - pub const SETTINGS: usize = 2; - pub const REGISTRIES: usize = 3; - pub const SECRETS: usize = 4; - pub const PLUGINS: usize = 5; - pub const NAMES: [&str; 6] = berth_tui::screen::HOME_TABS; -} - -/// The keys that leave a tab for another, the same on every tab: a digit, -/// Tab and Shift+Tab, Esc for the hosts, and q. `here` is the tab's index. -fn leave_tab(key: KeyEvent, here: usize) -> Outcome { - let count = tabs::NAMES.len(); - match key.code { - KeyCode::Char(digit @ '1'..='6') => Outcome::Tab(digit as usize - '1' as usize), - KeyCode::Esc => Outcome::Tab(tabs::HOSTS), - KeyCode::Tab => Outcome::Tab((here + 1) % count), - KeyCode::BackTab => Outcome::Tab((here + count - 1) % count), - KeyCode::Char('q') => Outcome::Quit, - _ => Outcome::Stay, - } -} - -/// Where the registries and secrets of `store` are kept, for the help of their tabs. -fn kept_in(paths: &Paths, store: &Store) -> String { - match store.server() { - Some(server) => format!( - "Kept on the berth server at {}. This berth has the registries and the names of the secrets in its store.", - server.url - ), - None => format!( - "Kept in berth's store, the {}, {}. See: berth store", - berth_core::store::Installation::of(paths).target.describe(), - match store.encrypted() { - true => "encrypted", - false => "not encrypted", - } - ), - } -} - -/// What a key on the Registries tab leads to. -enum Outcome { - Stay, - Tab(usize), - Quit, -} - -/// Take what was typed for a row. The message is shown in the footer. -fn registry_accept(store: &Store, row: &RegistryRow, value: &str) -> crate::Result { - use RegistryRow::*; - let mut registries = store.registries()?; - let valid = crate::plugins::valid_name; - let message = match row { - AddRegistry | Name(_) => { - if !valid(value) { - return Err( - "Use lower-case letters, digits, - and _, starting with a letter".into(), - ); - } - if registries.contains_key(value) { - return Err(format!("There is a registry {value} already").into()); - } - if let Name(old) = row { - // The stored login moves with the name, in the same change. - return Ok(match store.rename_registry(old, value)? { - true => format!("Registry {value}"), - false => format!( - "Registry {value}. The berth server drops a login with the old name: enter its password again" - ), - }); - } - registries.insert(value.to_owned(), json!({"type": "nexus", "url": ""})); - format!("Registry {value}") - } - Address(name) => { - let registry = &mut registries[name.as_str()]; - if registry["type"] != "docker" - && !value.starts_with("https://") - && !value.starts_with("http://") - { - return Err("Start the address with https://".into()); - } - registry["url"] = json!(value.trim_end_matches('/')); - "Address saved".into() - } - User(name) => { - match value { - "" => registries[name.as_str()] - .as_object_mut() - .and_then(|registry| registry.remove("username")), - user => registries[name.as_str()] - .as_object_mut() - .and_then(|registry| registry.insert("username".into(), json!(user))), - }; - "User name saved".into() - } - Password(name) => { - if value.is_empty() { - return Ok("Nothing entered, kept as it was".into()); - } - store.set_secret(&format!("registry/{name}"), Some(value))?; - return Ok("Stored".into()); - } - AddRepository(name) | Repository(name, _) => { - if value.is_empty() || value.contains(['/', ' ']) { - return Err("The repository's name on the server, without / or spaces".into()); - } - let registry = &mut registries[name.as_str()]; - let mut repositories = registry["repositories"] - .as_array() - .cloned() - .unwrap_or_default(); - if repositories.iter().any(|known| known["name"] == value) { - return Err(format!("{value} is listed already").into()); - } - match row { - Repository(_, index) => repositories[*index]["name"] = json!(value), - _ => repositories.push(json!({"format": "npm", "name": value})), - } - registry["repositories"] = json!(repositories); - format!("Repository {value}") - } - DockerAddress(name, index) => { - let address = value.split_once("://").map_or(value, |(_, rest)| rest); - let repository = &mut registries[name.as_str()]["repositories"][*index]; - match address.trim_end_matches('/') { - "" => repository - .as_object_mut() - .and_then(|repository| repository.remove("address")), - address => repository - .as_object_mut() - .and_then(|repository| repository.insert("address".into(), json!(address))), - }; - "Docker address saved".into() - } - Type(_) | Format(..) => String::new(), - }; - store.save_registries(registries)?; - Ok(message) -} - -/// Handle a key on the Registries tab. -fn registries_key( - view: &mut RegistryView, - paths: &Paths, - key: KeyEvent, - status: &mut String, -) -> Outcome { - use RegistryRow::*; - let store = match Store::new(paths) { - Ok(store) => store, - Err(error) => { - *status = error.to_string(); - return leave_tab(key, tabs::REGISTRIES); - } - }; - let rows = registry_rows(Some(&store)); - view.selected = view.selected.min(rows.len() - 1); - let row = rows[view.selected].0.clone(); - if let Some(input) = &mut view.editor { - match key.code { - KeyCode::Esc => view.editor = None, - KeyCode::Enter => { - let typed = input.value().trim().to_owned(); - match registry_accept(&store, &row, &typed) { - Ok(message) => { - *status = message; - view.editor = None; - // A new or renamed registry stays selected, ready for its kind and address. - if matches!(row, AddRegistry | Name(_)) { - let named = registry_rows(Some(&store)) - .iter() - .position(|(row, _)| *row == Name(typed.clone())); - view.selected = named.unwrap_or(view.selected); - } - } - Err(error) => *status = error.to_string(), - } - } - _ => { - input.handle_event(&Event::Key(key)); - } - } - return Outcome::Stay; - } - let armed = std::mem::take(&mut view.armed); - let report = std::mem::take(&mut view.report); - if key.code == KeyCode::Char('c') { - match row.registry() { - Some(name) => { - view.report = crate::registry::check(&store, name) - .unwrap_or_else(|error| vec![format!("✗ {error}")]); - view.report.insert(0, format!("Checked {name}")); - *status = format!("Checked {name}"); - } - None => *status = "Select a registry to check".into(), - } - return Outcome::Stay; - } - // Moving on to something else drops the report; other keys keep it on screen. - if !matches!(key.code, KeyCode::Up | KeyCode::Down) { - view.report = report; - } - let change = |edit: &dyn Fn(&mut serde_json::Map)| { - let mut registries = store.registries().unwrap_or_default(); - edit(&mut registries); - store - .save_registries(registries) - .map_or_else(|error| error.to_string(), |()| String::new()) - }; - let cycle = |all: &[&str], current: &str| { - let index = all - .iter() - .position(|known| *known == current) - .map_or(0, |index| index + 1); - all[index % all.len()].to_owned() - }; - match key.code { - KeyCode::Up => view.selected = view.selected.saturating_sub(1), - KeyCode::Down => view.selected = (view.selected + 1).min(rows.len() - 1), - KeyCode::Enter | KeyCode::Char(' ') => match &row { - Type(name) => { - *status = change(&|registries| { - let next = cycle( - crate::registry::TYPES, - registries[name.as_str()]["type"].as_str().unwrap_or(""), - ); - registries[name.as_str()]["type"] = json!(next); - }) - } - Format(name, index) => { - *status = change(&|registries| { - let repository = &mut registries[name.as_str()]["repositories"][*index]; - let next = cycle( - crate::registry::FORMATS, - repository["format"].as_str().unwrap_or(""), - ); - repository["format"] = json!(next); - }) - } - // Editing starts from the current value, except for what is secret or new. - other => { - let registries = store.registries().unwrap_or_default(); - let current = match other { - Name(name) => name.clone(), - Address(name) => registries[name.as_str()]["url"] - .as_str() - .unwrap_or("") - .to_owned(), - User(name) => registries[name.as_str()]["username"] - .as_str() - .unwrap_or("") - .to_owned(), - Repository(name, index) => { - registries[name.as_str()]["repositories"][*index]["name"] - .as_str() - .unwrap_or("") - .to_owned() - } - DockerAddress(name, index) => registries[name.as_str()]["repositories"][*index] - ["address"] - .as_str() - .unwrap_or("") - .to_owned(), - _ => String::new(), - }; - view.editor = Some(Input::new(current)); - } - }, - KeyCode::Char('x') | KeyCode::Delete => match &row { - Name(name) if !armed => { - view.armed = true; - *status = format!("x again removes {name} and its stored login"); - } - Name(name) => { - *status = change(&|registries| { - registries.remove(name.as_str()); - }); - let _ = store.set_secret(&format!("registry/{name}"), None); - } - User(name) => { - *status = change(&|registries| { - if let Some(registry) = registries[name.as_str()].as_object_mut() { - registry.remove("username"); - } - }) - } - Password(name) => { - *status = match store.set_secret(&format!("registry/{name}"), None) { - Ok(()) => "Forgotten".into(), - Err(error) => error.to_string(), - } - } - Repository(name, index) => { - *status = change(&|registries| { - if let Some(repositories) = - registries[name.as_str()]["repositories"].as_array_mut() - { - repositories.remove(*index); - } - }) - } - _ => {} - }, - _ => return leave_tab(key, tabs::REGISTRIES), - } - Outcome::Stay -} - -/// Open one of the home screen's tabs. -fn open_tab(home: &mut Home, tab: usize) { - home.mode = match tab { - tabs::PROVISIONERS => HomeMode::Provisioners(Default::default()), - tabs::SETTINGS => HomeMode::Settings(0, None), - tabs::REGISTRIES => HomeMode::Registries(RegistryView::default()), - tabs::SECRETS => HomeMode::Secrets(SecretView::default()), - tabs::PLUGINS => HomeMode::Plugins(PluginView::default()), - _ => HomeMode::Hosts, - }; -} - -/// Whether the server's last word is that a host answers: a small marker in -/// front of its name. Nothing without a server, and a hollow one when the -/// server has not said. -fn host_marker(known: Option<&berth_core::server::Known>, name: &str) -> Span<'static> { - match known.map(|known| known.hosts.get(name)) { - None => Span::raw(""), - Some(Some(reach)) if reach.reachable => Span::styled("● ", Style::new().fg(theme::GOOD)), - Some(Some(_)) => Span::styled("● ", Style::new().fg(theme::BAD)), - Some(None) => Span::styled("○ ", Style::new().fg(theme::MUTED)), - } -} - -/// What the Information panel says of the selected host on the Hosts tab. -fn host_help(home: &Home) -> String { - let Some(known) = &home.known else { - return String::new(); - }; - let mut help = String::new(); - if let Some(note) = server_note(known) { - help = format!("{note}\n\n"); - } - if let Some((name, _)) = home.hosts.get(home.selected) - && known.hosts.get(name).is_some_and(|reach| reach.rotating) - { - help.push_str(&format!("A key rotation has not reached {name} yet: it is offered the old key and the new one until it has. Run the rotation again when it answers.\n\n")); - } - help.push_str(&match home.hosts.get(home.selected) { - None => "● answers, ● does not answer, ○ not known yet: what the berth server found when it last asked.".to_owned(), - Some((name, _)) => match known.hosts.get(name) { - Some(reach) if reach.reachable => match &reach.version { - Some(version) => format!("{name} answers, with berthd {version}."), - None => format!("{name} answers."), - }, - Some(reach) => format!( - "{name} does not answer the berth server.\n\n{}", - reach.error.as_deref().unwrap_or("It gave no reason.") - ), - None => format!("The berth server has not said yet whether {name} answers."), - }, - }); - help -} - -struct Home { - hosts: Vec<(String, String)>, - selected: usize, - mode: HomeMode, - status: String, - /// The water moves with the time since then. - started: std::time::Instant, - /// The SSH keys of this berth's key ring, or of the berth server it - /// uses, by name and public half, and that server. Asked for when - /// Settings is first shown; empty when unknown. - berth_key: Option, - /// The tailnet settings of the berth server this berth uses, which are - /// the server's to keep. Asked for with the key. - served: Option>, - /// What the last mirror found of the berth server and its hosts, with a - /// server set. - known: Option, - /// Whether a mirror is being made now. - asking: bool, - /// `r` was pressed on the Hosts tab: the loop reloads, which needs the mirror. - refresh: bool, - /// The hosts of this berth a key rotation has not reached yet. - rotating: Vec, -} - -/// The status line while a mirror is being made, if nothing else is said. -const ASKING: &str = "Asking the berth server…"; - -/// What the last mirror left, for the home screen. -fn known_of(paths: &Paths) -> Option { - berth_core::server::Server::configured(paths).map(|server| server.known(paths)) -} - -/// The line for a server older than this berth. -fn server_note(known: &berth_core::server::Known) -> Option { - let version = known.version.as_deref()?; - crate::update::newer(berth_api::VERSION, version).then(|| { - format!( - "The berth server runs {version} and this berth {}. Update the berth server.", - berth_api::VERSION - ) - }) -} - -/// Take in a finished mirror: the hosts and what is known of them are read -/// again, and what came from the server on the Settings tab is asked for again. -fn home_mirror(home: &mut Home, paths: &Paths, mirroring: &mut Option) { - if std::mem::take(&mut home.refresh) { - match mirroring { - Some(mirroring) => { - if !mirroring.start() { - home.status = "Still asking the berth server".into(); - } - } - None => { - reload_hosts(home, paths); - home.status = "Read the hosts again".into(); - } - } - } - let Some(mirroring) = mirroring else { - return; - }; - if let Some(made) = mirroring.finished() { - match made { - Ok(()) => reload_hosts(home, paths), - Err(error) => home.status = error, - } - } - home.asking = mirroring.running(); -} - -/// Read the saved hosts and what is known of them again, keeping the selected -/// host selected. -fn reload_hosts(home: &mut Home, paths: &Paths) { - let chosen = home.hosts.get(home.selected).map(|(name, _)| name.clone()); - home.hosts = paths.hosts(); - home.selected = chosen - .and_then(|name| home.hosts.iter().position(|(known, _)| *known == name)) - .unwrap_or(home.selected.min(home.hosts.len())); - home.known = known_of(paths); - home.rotating = rotating(paths); - home.berth_key = None; - home.served = None; -} - -/// The hosts of this berth that a key rotation has not reached yet: they -/// are offered both keys until it has. A server's hosts are the server's. -fn rotating(paths: &Paths) -> Vec { - if berth_core::server::Server::configured(paths).is_some() { - return vec![]; - } - let Ok(store) = berth_core::store::shared(paths) else { - return vec![]; - }; - // Nothing to look at while no key is being replaced. - let pending = berth_core::keys::ring::names(&store).is_ok_and(|names| { - names.iter().any(|name| { - berth_core::keys::ring::read(&store, name, true).is_ok_and(|next| next.is_some()) - }) - }); - if !pending { - return vec![]; - } - berth_core::host::Host::all(paths) - .into_iter() - .filter(|host| { - berth_core::keys::contact::waiting(&store, &host.place, &host.config) - .is_ok_and(|keys| !keys.is_empty()) - }) - .map(|host| host.name) - .collect() -} - -/// The keys of a key ring by name and public half, and the berth server -/// whose ring it is. -type RingKeys = (Vec<(String, String)>, Option); - -/// The rows of the Settings tab after berth's own settings. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum SettingsRow { - /// A key of the ring, by its place in the list. - Key(usize), -} - -fn settings_extras(home: &Home) -> Vec { - let mut extras = vec![]; - if let Some((keys, _)) = &home.berth_key { - extras.extend((0..keys.len()).map(SettingsRow::Key)); - } - extras -} - -/// The SSH keys hosts set up from here are logged in to with: the server's -/// for a berth that uses one, which only someone who may set the server up -/// is told. -fn berth_key(paths: &Paths) -> RingKeys { - let server = berth_core::server::Server::configured(paths); - let keys = match &server { - Some(server) => crate::key_command::listed(server), - None => crate::key_command::local(paths), - }; - let keys = keys - .unwrap_or_default() - .into_iter() - .map(|key| (key.name, key.public)) - .collect(); - (keys, server.map(|server| server.url)) -} - -/// The tailnet settings of the berth server this berth uses, by key. -fn served_settings(paths: &Paths) -> Option> { - let server = berth_core::server::Server::configured(paths)?; - let listed = server.call("settings.list", json!({}), None).ok()?; - Some( - listed - .as_array()? - .iter() - .filter_map(|setting| { - let key = setting["key"].as_str()?; - berth_core::tailnet::SETTINGS - .contains(&key) - .then(|| (key.to_owned(), setting["value"].clone())) - }) - .collect(), - ) -} - -/// Change a setting: on the berth server this berth uses for one that is -/// the server's, here otherwise. -fn change_setting(home: &mut Home, paths: &Paths, key: &str, value: &str) -> crate::Result<()> { - match ( - berth_core::server::Server::configured(paths), - &mut home.served, - ) { - (Some(server), Some(served)) if berth_core::tailnet::SETTINGS.contains(&key) => { - server.call( - "settings.set", - json!({"key": key}), - Some(json!({"value": value})), - )?; - served.insert(key.into(), json!(value)); - Ok(()) - } - _ => paths.set(key, value), - } -} - -/// What a setting is called on screen. -fn setting_label(key: &str) -> &str { - match key { - "source" => "Provisioning source", - "default_host" => "Default host", - "iso_dir" => "Installer ISO folder", - other => other, - } -} - -/// A setting's stored value, and what applies when it is not set. `served` -/// has the settings a berth server keeps. -fn setting( - paths: &Paths, - served: Option<&serde_json::Map>, - key: &str, -) -> (String, String) { - // One at a time, so a store that does not open leaves the settings of the file. - let stored = match served { - Some(served) if berth_core::tailnet::SETTINGS.contains(&key) => served - .get(key) - .and_then(|value| value.as_str()) - .map(str::to_owned), - _ => paths.setting_with(key, None), - }; - let fallback = match key { - "source" => paths - .source() - .map(|dir| dir.display().to_string()) - .unwrap_or_else(|_| "not found".into()), - "iso_dir" => paths.iso_dir().display().to_string(), - _ => "none".into(), - }; - (stored.unwrap_or_default(), fallback) -} - -/// Clears a status line once it has been showing for a while. -#[derive(Default)] -struct Fade { - text: String, - since: Option, -} - -impl Fade { - const SHOWN: std::time::Duration = std::time::Duration::from_secs(6); - - /// Clear `status` when its time is up. Otherwise, how long it has left. - fn check(&mut self, status: &mut String) -> Option { - if *status != self.text { - self.text = status.clone(); - self.since = Some(std::time::Instant::now()); - } - if status.is_empty() { - return None; - } - let shown = self.since.map_or(Self::SHOWN, |since| since.elapsed()); - if shown >= Self::SHOWN { - status.clear(); - self.text.clear(); - return None; - } - Some(Self::SHOWN - shown) - } -} - -/// While the mirror runs the host's own screen says so, and a failure is told. -/// What the host shows is read again unless it holds changes not yet saved. -fn host_mirror(app: &mut App, mirroring: &mut Option) { - let Some(mirroring) = mirroring else { - return; - }; - if let Some(made) = mirroring.finished() { - match made { - Ok(()) => { - if app.status == ASKING { - app.status.clear(); - } - if let Some(said) = app.take_in_mirror() { - app.status = said; - } - } - Err(error) => app.status = error, - } - } else if app.status.is_empty() { - app.status = ASKING.into(); - } -} - -/// The home screen: pick a saved host, name a new one or change berth's own -/// settings. `None` quits. -pub fn home( - terminal: &mut DefaultTerminal, - paths: &Paths, - mirroring: &mut Option, -) -> Result> { - // A blinking cursor restarts its blink with every frame of the water, which - // reads as flicker; a steady one does not. - use crossterm::cursor::SetCursorStyle; - crossterm::execute!(std::io::stdout(), SetCursorStyle::SteadyBar)?; - let chosen = home_loop(terminal, paths, mirroring); - crossterm::execute!(std::io::stdout(), SetCursorStyle::BlinkingBar)?; - chosen -} - -fn home_loop( - terminal: &mut DefaultTerminal, - paths: &Paths, - mirroring: &mut Option, -) -> Result> { - let hosts = paths.hosts(); - let preferred = setting(paths, None, "default_host").0; - let mut home = Home { - selected: hosts - .iter() - .position(|(name, _)| *name == preferred) - .unwrap_or(0), - hosts, - mode: HomeMode::Hosts, - status: String::new(), - started: std::time::Instant::now(), - berth_key: None, - served: None, - known: None, - asking: false, - refresh: false, - rotating: rotating(paths), - }; - let mut hits = vec![]; - let mut fade = Fade::default(); - home.known = known_of(paths); - loop { - home_mirror(&mut home, paths, mirroring); - fade.check(&mut home.status); - if matches!(home.mode, HomeMode::Settings(..)) && home.berth_key.is_none() { - home.berth_key = Some(berth_key(paths)); - home.served = served_settings(paths); - } - if let HomeMode::Plugins(view) = &mut home.mode { - view.load(paths); - view.pump(&mut home.status); - } - if let HomeMode::Provisioners(view) = &mut home.mode { - view.load(paths); - view.pump(paths, &mut home.status); - } - // The water redraws many times a second. Each frame is applied at once, - // so the text cursor is not seen travelling to the water and back. - crossterm::execute!( - std::io::stdout(), - crossterm::terminal::BeginSynchronizedUpdate - )?; - let drawn = terminal.draw(|frame| draw_home(frame, paths, &home, &mut hits)); - crossterm::execute!( - std::io::stdout(), - crossterm::terminal::EndSynchronizedUpdate - )?; - drawn?; - if !crate::keys::poll(std::time::Duration::from_millis(50))? { - continue; - } - let event = hint_click(crate::keys::read()?); - let left = match event { - Event::Key(key) if key.kind != KeyEventKind::Release => { - if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) { - return Ok(None); - } - home_key(&mut home, paths, key, &mut Desktop) - } - Event::Mouse(mouse) => home_mouse(&mut home, paths, mouse, &hits, &mut Desktop), - Event::Paste(text) => { - if let Some(input) = home_editor(&mut home.mode) { - for ch in text.chars().filter(|ch| !ch.is_control()) { - input.handle(InputRequest::InsertChar(ch)); - } - } else if let HomeMode::Provisioners(view) = &mut home.mode { - view.paste(&text); - } - None - } - _ => None, - }; - if let Some(host) = left { - return Ok(host); - } - } -} - -/// The text field of the home screen that is being edited, if one is. -fn home_editor(mode: &mut HomeMode) -> Option<&mut Input> { - match mode { - HomeMode::Naming(input) => Some(input), - HomeMode::Settings(_, editor) => editor.as_mut(), - HomeMode::Registries(view) => view.editor.as_mut(), - HomeMode::Secrets(view) => view.editor.as_mut(), - HomeMode::Plugins(view) => view.editor.as_mut(), - HomeMode::Hosts | HomeMode::Provisioners(_) => None, - } -} - -/// Handle the mouse on the home screen: the wheel moves the selection, a click -/// switches tab or chooses a row. -fn home_mouse( - home: &mut Home, - paths: &Paths, - mouse: MouseEvent, - hits: &[(Rect, HomeTarget)], - platform: &mut dyn Platform, -) -> Option> { - let key = |code| KeyEvent::new(code, KeyModifiers::NONE); - match mouse.kind { - MouseEventKind::ScrollUp => home_key(home, paths, key(KeyCode::Up), platform), - MouseEventKind::ScrollDown => home_key(home, paths, key(KeyCode::Down), platform), - MouseEventKind::Down(MouseButton::Left) => { - // A form covers the tab, and takes the click itself. - if let HomeMode::Provisioners(view) = &mut home.mode - && view.tab.form().is_some() - { - let at = (mouse.column, mouse.row); - let left = view.click(paths, at, &mut home.status, platform); - if let crate::provisioner_tab::Left::Tab(tab) = left { - open_tab(home, tab); - } - return None; - } - let (_, target) = hits - .iter() - .find(|(rect, _)| inside(*rect, mouse.column, mouse.row))?; - match *target { - HomeTarget::Tab(1) if matches!(home.mode, HomeMode::Settings(..)) => None, - HomeTarget::Tab(2) if matches!(home.mode, HomeMode::Registries(..)) => None, - HomeTarget::Tab(3) if matches!(home.mode, HomeMode::Secrets(..)) => None, - HomeTarget::Tab(4) if matches!(home.mode, HomeMode::Plugins(..)) => None, - HomeTarget::Tab(5) if matches!(home.mode, HomeMode::Provisioners(..)) => None, - HomeTarget::Tab(tab) => { - open_tab(home, tab); - None - } - HomeTarget::Row(index) => { - // A click elsewhere drops what was being typed. - match &mut home.mode { - HomeMode::Registries(view) => { - view.selected = index; - view.editor = None; - } - HomeMode::Secrets(view) => { - view.selected = index; - view.editor = None; - view.naming = None; - } - HomeMode::Plugins(view) => { - view.tab.selected = index; - view.editor = None; - } - // A click selects a row, and on the row selected chooses it. - HomeMode::Provisioners(view) => { - if view.typing() { - return None; - } - let before = view.tab.selected_row(); - view.tab.select_row(index); - if view.tab.page.is_some() && before != index { - return None; - } - } - HomeMode::Settings(selected, editor) => { - *selected = index; - *editor = None; - } - mode => { - *mode = HomeMode::Hosts; - home.selected = index; - } - } - home_key(home, paths, key(KeyCode::Enter), platform) - } - } - } - _ => None, - } -} - -/// Handle a key on the home screen. `Some` leaves it: with a host, or to quit. -fn home_key( - home: &mut Home, - paths: &Paths, - key: KeyEvent, - platform: &mut dyn Platform, -) -> Option> { - let extras = match home.mode { - HomeMode::Settings(..) => settings_extras(home), - _ => vec![], - }; - let extra = |selected: usize| { - let index = selected.checked_sub(crate::paths::SETTINGS.len())?; - extras.get(index).copied() - }; - if let Some(typed) = crate::keys::key(&key) - && berth_tui::screen::is_copy_field(&typed) - && let Some(input) = home_editor(&mut home.mode) - { - home.status = berth_tui::screen::copy_field(platform, input); - return None; - } - let outcome = match &mut home.mode { - HomeMode::Registries(view) => Some(registries_key(view, paths, key, &mut home.status)), - HomeMode::Secrets(view) => Some(secrets_key(view, paths, key, &mut home.status)), - HomeMode::Plugins(view) => Some(plugins_key(view, paths, key, &mut home.status)), - HomeMode::Provisioners(view) => { - Some(match view.key(paths, key, &mut home.status, platform) { - crate::provisioner_tab::Left::Stay => Outcome::Stay, - crate::provisioner_tab::Left::Tab(tab) => Outcome::Tab(tab), - crate::provisioner_tab::Left::Quit => Outcome::Quit, - }) - } - _ => None, - }; - match outcome { - Some(Outcome::Stay) => return None, - Some(Outcome::Tab(tab)) => { - open_tab(home, tab); - return None; - } - Some(Outcome::Quit) => return Some(None), - None => {} - } - match &mut home.mode { - HomeMode::Registries(_) - | HomeMode::Secrets(_) - | HomeMode::Plugins(_) - | HomeMode::Provisioners(_) => {} - HomeMode::Naming(input) => match key.code { - KeyCode::Esc => home.mode = HomeMode::Hosts, - KeyCode::Enter => { - let name = input.value().trim().to_owned(); - if name.contains('/') || name.ends_with(".json") { - home.status = "Use letters, digits, - and _".into(); - } else if let Err(error) = berth_core::profiles::Place::resolve(paths, &name) { - home.status = error.to_string(); - } else { - return Some(Some(name)); - } - } - _ => { - input.handle_event(&Event::Key(key)); - } - }, - HomeMode::Settings(selected, editor @ Some(_)) => match key.code { - KeyCode::Esc => *editor = None, - KeyCode::Enter => { - let (name, _) = crate::paths::SETTINGS[*selected]; - let value = editor.take().unwrap_or_default(); - home.status = match change_setting(home, paths, name, value.value().trim()) { - Ok(()) => format!("Saved {}", setting_label(name)), - Err(error) => error.to_string(), - }; - } - _ => { - if let Some(input) = editor { - input.handle_event(&Event::Key(key)); - } - } - }, - HomeMode::Settings(selected, editor) => match key.code { - KeyCode::Up => *selected = selected.saturating_sub(1), - KeyCode::Down => { - // The keys of berth come after the settings. - let last = crate::paths::SETTINGS.len() + extras.len() - 1; - *selected = (*selected + 1).min(last); - } - KeyCode::Enter if *selected < crate::paths::SETTINGS.len() => { - let (name, _) = crate::paths::SETTINGS[*selected]; - *editor = Some(Input::new(setting(paths, home.served.as_ref(), name).0)); - } - KeyCode::Enter | KeyCode::Char('c') - if matches!(extra(*selected), Some(SettingsRow::Key(_))) => - { - if let (Some(SettingsRow::Key(index)), Some((keys, _))) = - (extra(*selected), &home.berth_key) - && let Some((_, public)) = keys.get(index) - { - home.status = berth_tui::berth_key::copy(platform, public); - } - } - _ => match leave_tab(key, tabs::SETTINGS) { - Outcome::Tab(tab) => open_tab(home, tab), - Outcome::Quit => return Some(None), - Outcome::Stay => {} - }, - }, - HomeMode::Hosts => match key.code { - KeyCode::Up => home.selected = home.selected.saturating_sub(1), - KeyCode::Down => { - home.selected = (home.selected + 1).min(home.hosts.len() + MAKES.len()) - } - KeyCode::Char('n') => home.mode = HomeMode::Naming(Input::default()), - KeyCode::Char('s') => open_tab(home, tabs::SETTINGS), - KeyCode::Char('r') => home.refresh = true, - KeyCode::Char('1'..='6') | KeyCode::Tab | KeyCode::BackTab => { - if let Outcome::Tab(tab) = leave_tab(key, tabs::HOSTS) { - open_tab(home, tab); - } - } - KeyCode::Char('d') => { - if let Some((name, _)) = home.hosts.get(home.selected) { - home.status = match paths.set("default_host", name) { - Ok(()) => format!("{name} is selected first from now on"), - Err(error) => error.to_string(), - }; - } - } - KeyCode::Enter => match home.hosts.get(home.selected) { - Some((name, _)) => return Some(Some(name.clone())), - None => match home.selected.checked_sub(home.hosts.len() + 1) { - // An instance or a compose project is made on its - // provisioner's page, whose form opens at once. - Some(index) if index < MAKES.len() => { - let mut view = Box::::default(); - view.create(paths, MAKES[index].0, &mut home.status); - home.mode = HomeMode::Provisioners(view); - } - _ => home.mode = HomeMode::Naming(Input::default()), - }, - }, - KeyCode::Char('q') | KeyCode::Esc => return Some(None), - _ => {} - }, - } - None -} - -fn draw_home(frame: &mut Frame, paths: &Paths, home: &Home, hits: &mut Vec<(Rect, HomeTarget)>) { - hits.clear(); - clear_hints(); - frame.render_widget(theme::backdrop(), frame.area()); - let area = frame.area().inner(Margin { - horizontal: 2, - vertical: 1, - }); - let [header, _, logo, main, water, footer] = Layout::vertical([ - Constraint::Length(1), - Constraint::Length(1), - Constraint::Length(4), - Constraint::Min(1), - Constraint::Length(2), - Constraint::Length(1), - ]) - .areas(area); - let tab = match home.mode { - HomeMode::Provisioners(..) => tabs::PROVISIONERS, - HomeMode::Settings(..) => tabs::SETTINGS, - HomeMode::Registries(..) => tabs::REGISTRIES, - HomeMode::Secrets(..) => tabs::SECRETS, - HomeMode::Plugins(..) => tabs::PLUGINS, - _ => tabs::HOSTS, - }; - // The Information panel is for the settings, and for a host with a server's word on it. - let settings = tab != 0 || home.known.is_some(); - let tabs = draw_header( - frame, - header, - &tabs::NAMES, - tab, - home.known - .as_ref() - .and_then(server_note) - .as_deref() - .unwrap_or(""), - ); - hits.extend( - tabs.into_iter() - .enumerate() - .map(|(tab, rect)| (rect, HomeTarget::Tab(tab))), - ); - // What is typed for a password is not shown. - let mut masked = false; - frame.render_widget(Paragraph::new(theme::logo()), logo); - frame.render_widget( - Paragraph::new(theme::swell( - water.width, - home.started.elapsed().as_secs_f32(), - )), - water, - ); - - // Settings use the same arrangement as a host's tabs: rows on the left with - // the editor under them, what the selected row means on the right. - let [left, right] = Layout::horizontal([ - Constraint::Percentage(if settings { 64 } else { 100 }), - Constraint::Min(0), - ]) - .areas(main); - let muted = Style::new().fg(theme::MUTED); - let (rows, selected, editor, help, keys): (Vec, usize, _, String, _) = match &home.mode { - HomeMode::Settings(selected, editor) => { - let extras = settings_extras(home); - let (keys, server) = home.berth_key.clone().unwrap_or_default(); - let mut rows: Vec = crate::paths::SETTINGS - .iter() - .map(|(name, _)| { - let (stored, fallback) = setting(paths, home.served.as_ref(), name); - if stored.is_empty() { - Line::from(vec![ - Span::styled( - format!("{} ", setting_label(name)), - Style::new().fg(theme::TEXT), - ), - Span::styled(format!("Default · {fallback}"), muted.italic()), - ]) - } else if crate::paths::is_secret(name) { - // A secret is not shown whole in a list; its field shows it. - crate::app::value_line( - setting_label(name), - &berth_tui::screen::short_secret(&stored), - Kind::Text, - ) - } else { - crate::app::value_line(setting_label(name), &stored, Kind::Text) - } - }) - .collect(); - for extra in &extras { - rows.push(match extra { - SettingsRow::Key(index) => { - let (name, public) = &keys[*index]; - berth_tui::berth_key::row(name, public) - } - }); - } - let selected = (*selected).min(rows.len() - 1); - let extra = selected - .checked_sub(crate::paths::SETTINGS.len()) - .and_then(|index| extras.get(index)); - let (help, keys) = match (crate::paths::SETTINGS.get(selected), extra) { - (Some((name, help)), ..) => ( - format!( - "{}.\n\nLeave it empty to use the default. Also: berth config {name} VALUE\n\nKept {}", - berth_tui::screen::describe_setting(help), - match (&home.served, berth_core::tailnet::SETTINGS.contains(name)) { - (Some(_), true) => format!( - "on the berth server at {server}", - server = server.as_deref().unwrap_or("") - ), - _ if crate::paths::is_local(name) => { - format!("in {}", paths.settings_file().display()) - } - _ => format!( - "in berth's store, the {}", - berth_core::store::Installation::of(paths).target.describe() - ), - } - ), - "↑↓ select · Enter change · q quit", - ), - (None, Some(SettingsRow::Key(index))) => ( - berth_tui::berth_key::help(&keys[*index].0, &keys[*index].1, server.as_deref()), - "↑↓ select · Enter copy the key · q quit", - ), - _ => (String::new(), ""), - }; - ( - rows, - selected, - editor.as_ref().map(|input| (" Edit ", input)), - help, - if editor.is_some() { - "Enter accept · Esc cancel · Ctrl+O copy" - } else { - keys - }, - ) - } - HomeMode::Registries(view) => { - let store = Store::new(paths); - let listed = registry_rows(store.as_ref().ok()); - let selected = view.selected.min(listed.len() - 1); - let row = &listed[selected].0; - masked = matches!(row, RegistryRow::Password(_)); - let title = match row { - RegistryRow::AddRegistry => " Name of the new registry ", - RegistryRow::AddRepository(_) => " Name of the repository on the server ", - RegistryRow::Password(_) => " Password or token ", - _ => " Edit ", - }; - let help = match view.report.is_empty() { - true => format!( - "{}\n\nc checks that this registry answers and accepts its login.\n\n{}", - row.help(), - match &store { - Ok(store) => kept_in(paths, store), - Err(error) => error.to_string(), - } - ), - false => view.report.join("\n\n"), - }; - ( - listed.iter().map(|(_, line)| line.clone()).collect(), - selected, - view.editor.as_ref().map(|input| (title, input)), - help, - if view.editor.is_some() { - "Enter accept · Esc cancel · Ctrl+O copy" - } else { - "↑↓ select · Enter change · c check · x remove · q quit" - }, - ) - } - HomeMode::Secrets(view) => { - let store = Store::new(paths); - let names = store - .as_ref() - .map(|store| store.secret_names()) - .unwrap_or_default(); - let selected = view.selected.min(names.len()); - let mut rows: Vec = names - .iter() - .map(|name| { - Line::from(vec![ - Span::styled(format!("{name} "), Style::new().fg(theme::TEXT)), - Span::styled("● stored", Style::new().fg(theme::GOOD)), - ]) - }) - .collect(); - rows.push(Line::styled("+ Add secret", Style::new().fg(theme::ACCENT))); - // A value is not shown while it is typed; a new secret's name is. - masked = view.naming.is_some() || selected < names.len(); - let title = match (&view.naming, names.get(selected)) { - (Some(_), _) => " Value of the new secret ", - (None, Some(_)) => " New value ", - (None, None) => " Name of the new secret ", - }; - let about = match names.get(selected) { - Some(name) if let Some(help) = berth_tui::setup::own_secret_help(name) => help, - Some(_) => { - "A token, password or key file. Enter replaces its value, x twice removes it. Values are never shown." - } - None => { - "Add a secret: first a short name (lower-case letters, digits, - and _), then its value. Paste works. The name tailnet_api_key is for the API key of the tailnet's control server, which berth keeps for itself." - } - }; - let help = format!( - "{about}\n\nWhich host gets a secret, and whether as an environment variable or a file, is chosen on the Secrets page of that host.\n\n{}", - match &store { - Ok(store) => kept_in(paths, store), - Err(error) => error.to_string(), - } - ); - ( - rows, - selected, - view.editor.as_ref().map(|input| (title, input)), - help, - if view.editor.is_some() { - "Enter accept · Esc cancel · Ctrl+O copy" - } else { - "↑↓ select · Enter set value · x remove · q quit" - }, - ) - } - HomeMode::Provisioners(view) => { - let shown = view.shown(paths); - (shown.rows, shown.selected, None, shown.help, shown.keys) - } - HomeMode::Plugins(view) => { - let plugins = view.plugins(); - let listed = berth_tui::plugins::rows(plugins, &view.tab.updates); - let selected = view.tab.selected.min(listed.len() - 1); - let server = berth_core::server::Server::configured(paths); - let place = plugin_place(&server); - let report = match &view.listing { - Some(Err(error)) if view.report.is_empty() => vec![format!("✗ {error}")], - _ => view.report.clone(), - }; - let dir = match &view.listing { - Some(Ok(listing)) => listing.dir.clone(), - _ => crate::plugins::own_dir(&paths.config_dir) - .display() - .to_string(), - }; - let help = berth_tui::plugins::help( - listed[selected].0.map(|index| &plugins[index]), - &report, - &place.adding(&dir), - ); - ( - listed.into_iter().map(|(_, line)| line).collect(), - selected, - view.editor - .as_ref() - .map(|input| (place.editor_title(), input)), - help, - if view.editor.is_some() { - "Enter install · Esc cancel · Ctrl+O copy" - } else { - "↑↓ select · Enter add · c check · U update · A all · x remove · q quit" - }, - ) - } - mode => { - let preferred = setting(paths, None, "default_host").0; - let mut rows: Vec = home - .hosts - .iter() - .map(|(name, address)| { - let address = if address.is_empty() { - "no address yet" - } else { - address - }; - let mut line = vec![ - host_marker(home.known.as_ref(), name), - Span::styled(format!("{name:<24}"), Style::new().fg(theme::TEXT)), - Span::styled(format!("{address:<28}"), muted), - ]; - if *name == preferred { - line.push(Span::styled("default ", Style::new().fg(theme::STEEL))); - } - let served = home - .known - .as_ref() - .and_then(|known| known.hosts.get(name)) - .is_some_and(|reach| reach.rotating); - if served || home.rotating.contains(name) { - line.push(Span::styled( - "key rotation pending", - Style::new().fg(theme::WARN), - )); - } - Line::from(line) - }) - .collect(); - rows.push(Line::styled("+ New host", Style::new().fg(theme::ACCENT))); - for (_, label) in MAKES { - rows.push(Line::styled( - format!("+ New {label}"), - Style::new().fg(theme::ACCENT), - )); - } - let help = host_help(home); - let naming = match mode { - HomeMode::Naming(input) => Some((" New host name ", input)), - _ => None, - }; - ( - rows, - home.selected, - naming, - help, - if naming.is_some() { - "Enter create · Esc cancel · Ctrl+O copy" - } else { - "↑↓ select · Enter open · n new host · d default · r refresh · q quit" - }, - ) - } - }; - let [body, edit] = Layout::vertical([ - Constraint::Min(1), - Constraint::Length(if editor.is_some() { 3 } else { 0 }), - ]) - .areas(left); - for index in 0..(rows.len() as u16).min(body.height) { - hits.push(( - Rect::new(body.x, body.y + index, body.width, 1), - HomeTarget::Row(index as usize), - )); - } - frame.render_stateful_widget( - List::new(rows) - .highlight_symbol(theme::cursor()) - .highlight_style(Style::new().bg(theme::RAISED)), - body, - &mut ListState::default().with_selected(Some(selected)), - ); - if settings { - frame.render_widget( - Paragraph::new(crate::markdown::render(&help)) - .block(theme::panel("Information", false)) - .wrap(Wrap { trim: false }), - right, - ); - } - if let Some((title, input)) = editor { - // The panel has a border and one column of padding on each side. - let width = edit.width.saturating_sub(4).max(1) as usize; - let scroll = input.visual_scroll(width); - frame.render_widget( - Paragraph::new(match masked { - true => "•".repeat(input.value().chars().count()), - false => input.value().to_owned(), - }) - .scroll((0, scroll.min(u16::MAX as usize) as u16)) - .block(theme::panel(title.trim(), true)), - edit, - ); - frame.set_cursor_position(( - edit.x + 2 + (input.visual_cursor() - scroll).min(width) as u16, - edit.y + 1, - )); - } - let status = match home.status.is_empty() && home.asking { - true => ASKING, - false => &home.status, - }; - draw_footer(frame, footer, keys, status, theme::WARN); - if let HomeMode::Provisioners(view) = &home.mode { - view.draw_over(frame, status); - } -} - -/// Run a host's screen. Returns true when the chosen action has to run in the -/// normal terminal, and false when the user left the host. -pub fn run( - terminal: &mut DefaultTerminal, - app: &mut App, - mirroring: &mut Option, -) -> Result { - let mut display = ListState::default(); - let mut hits: Hits = vec![]; - let mut quit_armed = false; - let mut fade = Fade::default(); - loop { - host_mirror(app, mirroring); - // "x again to quit" and the like stay until the next key. - let fading = match quit_armed { - true => None, - false => fade.check(&mut app.status), - }; - app.update_suggestions(); - app.watch_host(); - app.watch_machine(); - app.watch_found_type(); - // One of berth's own actions on the host runs in the normal terminal. - if app.own_command.is_some() { - return Ok(true); - } - let (panel_rows, panel_cols) = session_size(); - app.host.resize(panel_rows, panel_cols); - let rows = app.rows(); - terminal.draw(|frame| draw(frame, app, &rows, &mut display, &mut hits))?; - if let Some(job) = &mut app.job { - let running = job.running(); - job.tick(); - if running && !crate::keys::poll(std::time::Duration::from_millis(100))? { - continue; - } - } - if let Some(session) = &mut app.session { - session.tick(); - let (rows, cols) = session_size(); - session.resize(rows, cols); - // A shell that was left needs no key to close its panel. - if session.closes && session.outcome == Some(true) { - app.session = None; - continue; - } - if !crate::keys::poll(std::time::Duration::from_millis(40))? { - continue; - } - let event = hint_click(crate::keys::read()?); - session_event(app, &event); - continue; - } - if let Some(view) = &app.host.view { - // A shell that was left needs no key to close its panel. - if view.shell && view.outcome() == Some(true) { - app.host.close(true); - continue; - } - if !crate::keys::poll(std::time::Duration::from_millis(40))? { - continue; - } - let event = hint_click(crate::keys::read()?); - view_event(app, &event); - continue; - } - // While the overview talks to the host, what it says is taken in - // without waiting for a key. - if app.step == Step::Manage - && app.host.connected() - && !crate::keys::poll(std::time::Duration::from_millis(200))? - { - continue; - } - // The machine's state is taken in when it comes, too. - if app.machine_awaited() && !crate::keys::poll(std::time::Duration::from_millis(200))? { - continue; - } - if let Some(left) = fading - && !crate::keys::poll(left)? - { - continue; - } - let event = hint_click(crate::keys::read()?); - // The overlay can outlast the panel it came from. - if app.qr.is_some() { - qr_event(app, &event); - continue; - } - if app.unlock.is_some() { - unlock_event(app, &event, &mut Desktop); - continue; - } - if app.choosing_drive { - if let Event::Key(key) = event { - let chosen = match key.code { - KeyCode::Char(digit @ '1'..='9') => { - app.usb_drives.get(digit as usize - '1' as usize).cloned() - } - KeyCode::Esc => { - app.choosing_drive = false; - None - } - _ => None, - }; - if let Some((_, device)) = chosen { - app.write_built_iso(Some(device)); - } - } - continue; - } - if app.job.is_some() { - job_event(app, &event); - continue; - } - if app.confirm.is_some() { - confirm_event(app, &event); - continue; - } - if app.machine.question.is_some() { - if let Event::Key(key) = &event { - match key.code { - KeyCode::Char('y' | 'Y') => app.machine_answer(true), - KeyCode::Char('n' | 'N') | KeyCode::Esc => app.machine_answer(false), - _ => {} - } - } - continue; - } - if app.host.question.is_some() { - if let Flow::Run = question_event(app, &event) { - return Ok(true); - } - continue; - } - if app.host.arguments.is_some() { - arguments_event(app, &event, &mut Desktop); - continue; - } - if app.picker.is_some() { - picker_event(app, &event); - continue; - } - let key = match event { - Event::Key(key) if key.kind != KeyEventKind::Release => key, - Event::Mouse(mouse) => match mouse_event(app, mouse, &hits) { - Some(key) => key, - None => continue, - }, - Event::Paste(text) => { - if let Some(input) = &mut app.editing { - for ch in text.chars().filter(|ch| !ch.is_control()) { - input.handle(InputRequest::InsertChar(ch)); - } - } - continue; - } - _ => continue, - }; - match key_event(app, key, &mut quit_armed, &mut Desktop) { - Flow::Continue => {} - Flow::Quit => return Ok(false), - Flow::Run => return Ok(true), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::app::parse_config; - use berth_core::profiles::Place; - use ratatui::{Terminal, backend::TestBackend}; - - /// Paths of a folder that is never made, for an app that saves nothing. - fn nowhere() -> Paths { - Paths { - config_dir: "/nonexistent/berth-test/config".into(), - data_dir: "/nonexistent/berth-test/data".into(), - } - } - - /// An app of a new profile that is never saved. - fn unsaved_app(config: &[u8]) -> App { - App::new( - nowhere(), - Place::File("/nonexistent/berth-test/studio.json".into()), - parse_config(config).unwrap(), - ) - } - - /// An app of a profile in the file `name` of `directory`, which also - /// holds the installation. - fn file_app(directory: &std::path::Path, name: &str, config: &[u8]) -> App { - App::new( - Paths { - config_dir: directory.join("config"), - data_dir: directory.join("data"), - }, - Place::File(directory.join(name)), - parse_config(config).unwrap(), - ) - } - - #[test] - fn applying_from_the_ui_holds_the_hosts_lock() { - use berth_core::runner::{Subject, lock}; - use std::process::Command; - let dir = tempfile::tempdir().unwrap(); - let mut app = file_app(dir.path(), "studio.json", b"{}"); - app.action = Action::Ssh; - let subject = Subject::Host(app.place.argument()); - let held = lock(&app.paths, &subject, "rollout").unwrap(); - let refused = app - .run_command(Command::new("true"), vec![]) - .unwrap_err() - .to_string(); - assert!(refused.contains("(rollout, process "), "{refused}"); - drop(held); - app.run_command(Command::new("true"), vec![]).unwrap(); - let failed = app.run_command(Command::new("false"), vec![]).unwrap_err(); - assert!(failed.to_string().contains("exit status: 1"), "{failed}"); - // Once it has ended, the lock is free for the next one. - lock(&app.paths, &subject, "apply").unwrap(); - } - - /// A clipboard of the test's own, so none of the desktop's is touched. - #[derive(Default)] - struct Clipboard(Option); - - impl Platform for Clipboard { - fn copy(&mut self, text: &str) -> bool { - self.0 = Some(text.to_owned()); - true - } - - fn paste(&mut self) -> Option { - self.0.clone() - } - - fn open(&mut self, _: &str) -> std::result::Result<(), String> { - Err("no browser in tests".into()) - } - } - - fn screen(app: &mut App) -> String { - let mut terminal = Terminal::new(TestBackend::new(100, 24)).unwrap(); - app.update_suggestions(); - let rows = app.rows(); - let (mut display, mut hits) = (ListState::default(), vec![]); - terminal - .draw(|frame| draw(frame, app, &rows, &mut display, &mut hits)) - .unwrap(); - let buffer = terminal.backend().buffer(); - (0..24) - .map(|y| { - (0..100) - .map(|x| buffer[(x, y)].symbol()) - .collect::() - }) - .collect::>() - .join("\n") - } - - #[test] - fn space_on_a_group_heading_switches_the_group() { - let mut app = unsaved_app(b"{}"); - // The coding agents are plugins that come with berth. - app.set_plugins(crate::plugins::load(&["../../plugins".into()])); - let chosen = |app: &App| app.config["ansible_vars"]["devbox_plugin_features"].to_string(); - app.set_step(Step::Features); - // The heading itself is selected first and offers the key. - assert_eq!(app.selected_group(), Some(0)); - let shown = screen(&mut app); - println!("{shown}"); - assert!(shown.contains("Coding Agents 3 of 3")); - assert!(shown.contains("[All off Space]")); - press(&mut app, &[KeyCode::Char(' ')]); - assert!(!chosen(&app).contains("claude/cli") && !chosen(&app).contains("pi/cli")); - assert!(chosen(&app).contains("t3/server")); - assert!(screen(&mut app).contains("[All on Space]")); - // Enter leaves a heading alone; on an entry Space and Enter both switch it. - press(&mut app, &[KeyCode::Enter]); - assert!(!chosen(&app).contains("claude/cli")); - press(&mut app, &[KeyCode::Down, KeyCode::Char(' ')]); - assert!(chosen(&app).contains("claude/cli") && !chosen(&app).contains("codex/cli")); - } - - #[test] - fn secrets_are_stored_on_the_home_screen_and_given_on_a_host_page() { - let directory = tempfile::tempdir().unwrap(); - let paths = Paths { - config_dir: directory.path().join("config"), - data_dir: directory.path().join("data"), - }; - let mut home = Home { - hosts: vec![], - selected: 0, - mode: HomeMode::Hosts, - status: String::new(), - started: std::time::Instant::now(), - berth_key: None, - served: None, - known: None, - asking: false, - refresh: false, - rotating: vec![], - }; - let keys = |home: &mut Home, codes: &[KeyCode]| { - for &code in codes { - home_key( - home, - &paths, - KeyEvent::new(code, KeyModifiers::NONE), - &mut Clipboard::default(), - ); - } - }; - let typed = |text: &str| text.chars().map(KeyCode::Char).collect::>(); - // The Secrets tab: a name, then the value, which the screen does not show. - keys(&mut home, &[KeyCode::Char('5'), KeyCode::Enter]); - keys(&mut home, &typed("github")); - keys(&mut home, &[KeyCode::Enter]); - keys(&mut home, &typed("ghp_value")); - let mut terminal = Terminal::new(TestBackend::new(110, 24)).unwrap(); - terminal - .draw(|frame| draw_home(frame, &paths, &home, &mut vec![])) - .unwrap(); - let buffer = terminal.backend().buffer(); - let screen: String = (0..24) - .flat_map(|y| (0..110).map(move |x| (x, y))) - .map(|position| buffer[position].symbol()) - .collect(); - assert!(screen.contains("•••••••••") && !screen.contains("ghp_value")); - keys(&mut home, &[KeyCode::Enter]); - let store = Store::new(&paths).unwrap(); - assert_eq!( - store.secret("github").unwrap().as_deref(), - Some("ghp_value") - ); - store.set_secret("registry/nexus", Some("pw")).unwrap(); - assert_eq!(store.secret_names(), ["github"]); - - // On a host: its Settings tab lists it, and takes how the host gets it. - let mut app = unsaved_app(b"{}"); - app.access = Ok(store.clone()); - app.set_step(Step::Settings); - let secrets: Vec = app - .entries() - .into_iter() - .filter(|entry| matches!(entry, Entry::HostSecret(_))) - .collect(); - assert_eq!(secrets, [Entry::HostSecret(0)]); - let at = app - .entries() - .iter() - .position(|entry| *entry == Entry::HostSecret(0)); - app.list.select(at); - press(&mut app, &[KeyCode::Enter]); - for code in typed("GH_TOKEN") { - press(&mut app, &[code]); - } - press(&mut app, &[KeyCode::Enter]); - assert_eq!( - app.config["secrets"], - json!([{"name": "github", "env": "GH_TOKEN"}]) - ); - assert!(screen_text(&mut app).contains("github ● variable GH_TOKEN")); - app.set_host_secret(0, "~/.config/gh/token"); - assert_eq!( - app.config["secrets"], - json!([{"name": "github", "file": "~/.config/gh/token"}]) - ); - app.set_host_secret(0, "not a name or path"); - assert_eq!(app.config["secrets"][0]["file"], "~/.config/gh/token"); - press(&mut app, &[KeyCode::Char('x')]); - assert_eq!(app.config["secrets"], json!([])); - - // Removing the secret takes x twice. - keys(&mut home, &[KeyCode::Char('x')]); - assert!(store.secret("github").unwrap().is_some()); - keys(&mut home, &[KeyCode::Char('x')]); - assert!(store.secret("github").unwrap().is_none()); - } - - #[test] - fn plugins_tab_lists_and_removes_a_copied_plugin() { - let directory = tempfile::tempdir().unwrap(); - let paths = Paths { - config_dir: directory.path().join("config"), - data_dir: directory.path().join("data"), - }; - let own = paths.config_dir.join("plugins/aa-hello"); - std::fs::create_dir_all(&own).unwrap(); - std::fs::write( - own.join("package.json"), - r#"{"name":"berth-plugin-aa-hello","version":"1.2.3","displayName":"Hello", - "berth":{"features":[{"id":"cow","label":"cowsay","group":"Development Tools"}]}}"#, - ) - .unwrap(); - let mut home = Home { - hosts: vec![], - selected: 0, - mode: HomeMode::Hosts, - status: String::new(), - started: std::time::Instant::now(), - berth_key: None, - served: None, - known: None, - asking: false, - refresh: false, - rotating: vec![], - }; - let key = |home: &mut Home, code| { - home_key( - home, - &paths, - KeyEvent::new(code, KeyModifiers::NONE), - &mut Clipboard::default(), - ); - }; - key(&mut home, KeyCode::Char('6')); - if let HomeMode::Plugins(view) = &mut home.mode { - view.load(&paths); - } - let mut terminal = Terminal::new(TestBackend::new(120, 40)).unwrap(); - terminal - .draw(|frame| draw_home(frame, &paths, &home, &mut vec![])) - .unwrap(); - let buffer = terminal.backend().buffer(); - let text: String = (0..40) - .flat_map(|y| (0..120).map(move |x| (x, y))) - .map(|position| buffer[position].symbol()) - .collect(); - // The plugin of the source this program carries, and the copied one. - assert!(text.contains("Unity") && text.contains("comes with berth")); - assert!(text.contains("Hello berth-plugin-aa-hello 1.2.3 · yours")); - assert!(text.contains("cowsay in Development Tools") && text.contains("+ Add plugin")); - // Hello sorts first. Shipped plugins stay; a copied one goes after x twice. - key(&mut home, KeyCode::Char('x')); - assert!(own.exists()); - key(&mut home, KeyCode::Char('x')); - assert!(!own.exists()); - key(&mut home, KeyCode::Char('x')); - assert!(home.status.contains("comes with berth")); - } - - #[test] - fn the_provisioners_tab_opens_a_page_and_runs_its_actions_here() { - use std::os::unix::fs::PermissionsExt; - let directory = tempfile::tempdir().unwrap(); - let paths = Paths { - config_dir: directory.path().join("config"), - data_dir: directory.path().join("data"), - }; - paths.prepare().unwrap(); - // The checkout is the provisioning source, so none is unpacked behind the test's back. - let checkout = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); - paths - .set("source", checkout.canonicalize().unwrap().to_str().unwrap()) - .unwrap(); - let own = paths.config_dir.join("plugins/aa-lab"); - std::fs::create_dir_all(own.join("bin")).unwrap(); - std::fs::write( - own.join("bin/provision"), - "#!/bin/sh\ncat > /dev/null\n[ -f \"say.$1\" ] && cat \"say.$1\" >&2\n[ -f \"answer.$1\" ] && cat \"answer.$1\"\nexit 0\n", - ) - .unwrap(); - std::fs::set_permissions( - own.join("bin/provision"), - std::fs::Permissions::from_mode(0o755), - ) - .unwrap(); - std::fs::write( - own.join("package.json"), - r#"{"name": "berth-plugin-aa-lab", "berth": {"provisioners": [ - {"id": "box", "label": "Lab box", "command": "bin/provision", "protocol": 2, - "kinds": [{"id": "machine", "setup": "apply"}, - {"id": "instance", "label": "Instance", "arguments": [ - {"name": "image", "label": "Image", "default": "debian:12"}, - {"name": "notes", "label": "Notes", "kind": "text"}]}], - "actions": [{"name": "look", "label": "Look around", "changes": false}, - {"name": "sweep", "label": "Sweep", "confirm": "Sweep the lab?"}]}]}}"#, - ) - .unwrap(); - std::fs::write( - own.join("answer.status"), - r#"{"message": "The lab answers", "details": [{"label": "Benches", "value": "3"}]}"#, - ) - .unwrap(); - std::fs::write(own.join("answer.act"), r#"{"message": "All clean"}"#).unwrap(); - std::fs::write(own.join("say.act"), "sweeping\n").unwrap(); - let mut home = Home { - hosts: vec![], - selected: 0, - mode: HomeMode::Hosts, - status: String::new(), - started: std::time::Instant::now(), - berth_key: None, - served: None, - known: None, - asking: false, - refresh: false, - rotating: vec![], - }; - let key = |home: &mut Home, code| { - home_key( - home, - &paths, - KeyEvent::new(code, KeyModifiers::NONE), - &mut Clipboard::default(), - ); - }; - // What runs in a thread is taken in as the screen would, until `done` says so. - let settle = |home: &mut Home, done: &dyn Fn(&str) -> bool| -> String { - for _ in 0..500 { - if let HomeMode::Provisioners(view) = &mut home.mode { - view.load(&paths); - view.pump(&paths, &mut home.status); - } - let screen = home_screen(&paths, home).join("\n"); - if done(&screen) { - return screen; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } - panic!( - "the screen did not settle:\n{}", - home_screen(&paths, home).join("\n") - ); - }; - // The hosts' list makes instances and compose projects too, with - // the provisioner that makes them; here none does yet. - let screen = settle(&mut home, &|screen| { - screen.contains("+ New compose project") - }); - assert!(screen.contains("+ New instance"), "{screen}"); - home.selected = home.hosts.len() + 1; - key(&mut home, KeyCode::Enter); - assert!(matches!(home.mode, HomeMode::Provisioners(_))); - settle(&mut home, &|screen| { - screen.contains("No provisioner makes instances") - }); - key(&mut home, KeyCode::Char('2')); - settle(&mut home, &|screen| screen.contains("+ Add provisioner")); - // A provisioner is registered under a name of its own, of a type a plugin brings. - key(&mut home, KeyCode::Char('a')); - settle(&mut home, &|screen| { - screen.contains("Add provisioner · 1 of 2") - }); - for ch in "lab".chars() { - key(&mut home, KeyCode::Char(ch)); - } - key(&mut home, KeyCode::Enter); - // The lab's type sorts first, so it is offered first. - let screen = settle(&mut home, &|screen| { - screen.contains("Add provisioner · 2 of 2") - }); - assert!(screen.contains("aa-lab/box"), "{screen}"); - key(&mut home, KeyCode::Enter); - let screen = settle(&mut home, &|screen| screen.contains("Lab box")); - // Its type's label names it; the type itself is on its page. - assert!( - screen.contains("lab") && !screen.contains("(aa-lab/box)"), - "{screen}" - ); - assert_eq!( - berth_core::provisioner::entry(&paths, "lab") - .unwrap() - .unwrap() - .kind, - "aa-lab/box" - ); - // Its page asks it how it is. - key(&mut home, KeyCode::Enter); - let screen = settle(&mut home, &|screen| screen.contains("The lab answers")); - assert!( - screen.contains("● ready") && screen.contains("Benches 3"), - "{screen}" - ); - assert!(screen.contains("▸ Look around") && screen.contains("▸ Sweep")); - // What it makes is asked for in a form over the whole screen, laid - // out as a host's set-up is. Esc goes back to the page. - assert!(screen.contains("▸ New instance"), "{screen}"); - key(&mut home, KeyCode::Enter); - let screen = home_screen(&paths, &home).join("\n"); - assert!(screen.contains("lab › new instance"), "{screen}"); - assert!( - screen.contains("Image debian:12") && screen.contains("Notes Not set"), - "{screen}" - ); - assert!( - screen.contains("[Run · New instance]") && screen.contains("╭ Information "), - "{screen}" - ); - assert!(!screen.contains("1 Hosts"), "{screen}"); - // A text is edited in the editor, which has the screen to itself. - for code in [KeyCode::Down, KeyCode::Down, KeyCode::Enter] { - key(&mut home, code); - } - key(&mut home, KeyCode::Char('1')); - let screen = home_screen(&paths, &home).join("\n"); - assert!( - screen.contains("╭ Notes · line 1 of 1, column 2 "), - "{screen}" - ); - assert!(!screen.contains("Information"), "{screen}"); - key(&mut home, KeyCode::Esc); - key(&mut home, KeyCode::Esc); - let screen = home_screen(&paths, &home).join("\n"); - assert!(screen.contains("▸ Look around"), "{screen}"); - // One that only reads answers in a panel too, which Esc closes. - key(&mut home, KeyCode::Down); - key(&mut home, KeyCode::Enter); - let screen = settle(&mut home, &|screen| screen.contains("All clean")); - assert!(!screen.contains("sweeping"), "{screen}"); - key(&mut home, KeyCode::Esc); - assert!(matches!(home.mode, HomeMode::Provisioners(_))); - // One that changes something asks first, and is a job in a panel. - key(&mut home, KeyCode::Down); - key(&mut home, KeyCode::Enter); - assert!( - home_screen(&paths, &home) - .join("\n") - .contains("Sweep the lab?") - ); - key(&mut home, KeyCode::Char('y')); - let screen = settle(&mut home, &|screen| screen.contains("✓ Done")); - assert!( - screen.contains("sweeping") && screen.contains("✓ All clean"), - "{screen}" - ); - // Keys go to the panel until it is closed, and then back to the page. - key(&mut home, KeyCode::Char('1')); - assert!(matches!(home.mode, HomeMode::Provisioners(_))); - key(&mut home, KeyCode::Enter); - key(&mut home, KeyCode::Esc); - key(&mut home, KeyCode::Esc); - assert!(matches!(home.mode, HomeMode::Hosts)); - // The hosts' list opens the same form, which chooses the provisioner - // too; Esc there goes back to the hosts. - home.selected = home.hosts.len() + 1; - key(&mut home, KeyCode::Enter); - let screen = settle(&mut home, &|screen| screen.contains("[Run · New instance]")); - assert!( - screen.contains("Provisioner Lab box · lab") && screen.contains("Name * Not set"), - "{screen}" - ); - key(&mut home, KeyCode::Esc); - assert!(matches!(home.mode, HomeMode::Hosts)); - } - - #[test] - fn hints_can_be_clicked() { - let keys = - "↑↓ select · Enter open · Ctrl+V paste · x remove · F3 browse · Click opens a link"; - note_hints(keys, 4, 9, true); - let click = |column| { - hint_click(Event::Mouse(MouseEvent { - kind: MouseEventKind::Down(MouseButton::Left), - column, - row: 9, - modifiers: KeyModifiers::NONE, - })) - }; - let key = |code, modifiers| Event::Key(KeyEvent::new(code, modifiers)); - // The arrows are not one key, so a click there stays a click. - assert!(matches!(click(5), Event::Mouse(_))); - assert_eq!(click(15), key(KeyCode::Enter, KeyModifiers::NONE)); - assert_eq!(click(27), key(KeyCode::Char('v'), KeyModifiers::CONTROL)); - assert_eq!(click(45), key(KeyCode::Char('x'), KeyModifiers::NONE)); - // Between two hints. - assert!(matches!(click(49), Event::Mouse(_))); - assert_eq!(click(51), key(KeyCode::F(3), KeyModifiers::NONE)); - assert!(matches!(click(70), Event::Mouse(_))); - assert_eq!(pasted("AB12-CD34"), "Pasted 9 characters"); - } - - #[test] - fn a_session_draws_its_terminal_and_finds_a_wrapped_link() { - let address = format!("https://example.com/login?code={}", "a".repeat(40)); - let mut command = std::process::Command::new("printf"); - command - .arg("Open %s now\\r\\ncode: AB12-CD34\\r\\n") - .arg(&address); - let mut session = crate::session::Session::start("demo", command, 6, 30).unwrap(); - for _ in 0..200 { - session.tick(); - if !session.running() { - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } - // The last output can arrive a moment after the process has ended. - for _ in 0..5 { - std::thread::sleep(std::time::Duration::from_millis(10)); - session.tick(); - } - let mut terminal = Terminal::new(TestBackend::new(60, 12)).unwrap(); - let (mut links, mut words) = (vec![], vec![]); - terminal - .draw(|frame| (links, words) = draw_session(frame, &session, "")) - .unwrap(); - // Every cell of the address opens the whole of it, over three rows. - assert_eq!(links.len(), address.len()); - assert!(links.iter().all(|(_, link)| *link == address)); - assert_eq!(links.last().unwrap().0.y - links[0].0.y, 2); - assert!(words.iter().any(|(_, word)| word == "AB12-CD34")); - } - - fn screen_text(app: &mut App) -> String { - screen(app) - } - - #[test] - fn registries_are_edited_on_their_own_tab() { - let directory = tempfile::tempdir().unwrap(); - let paths = Paths { - config_dir: directory.path().join("config"), - data_dir: directory.path().join("data"), - }; - let mut home = Home { - hosts: vec![], - selected: 0, - mode: HomeMode::Hosts, - status: String::new(), - started: std::time::Instant::now(), - berth_key: None, - served: None, - known: None, - asking: false, - refresh: false, - rotating: vec![], - }; - let keys = |home: &mut Home, codes: &[KeyCode]| { - for &code in codes { - home_key( - home, - &paths, - KeyEvent::new(code, KeyModifiers::NONE), - &mut Clipboard::default(), - ); - } - }; - let typed = |text: &str| text.chars().map(KeyCode::Char).collect::>(); - use KeyCode::{Down, Enter, Up}; - // Hosts, then the Registries tab: only "+ Add registry" is there. - keys(&mut home, &[KeyCode::Char('4'), Enter]); - keys(&mut home, &typed("Bad Name")); - keys(&mut home, &[Enter]); - assert!(home.status.starts_with("Use lower-case")); - for _ in 0..8 { - keys(&mut home, &[KeyCode::Backspace]); - } - keys(&mut home, &typed("nexus")); - keys(&mut home, &[Enter, Down, Down, Enter]); - keys(&mut home, &typed("https://nexus.example/")); - // User name, then the password, which the screen does not show. - keys(&mut home, &[Enter, Down, Enter]); - keys(&mut home, &typed("ci")); - keys(&mut home, &[Enter, Down, Enter]); - keys(&mut home, &typed("hunter2")); - let mut terminal = Terminal::new(TestBackend::new(110, 30)).unwrap(); - let mut shown = |home: &Home| { - terminal - .draw(|frame| draw_home(frame, &paths, home, &mut vec![])) - .unwrap(); - let buffer = terminal.backend().buffer(); - (0..30) - .map(|y| { - (0..110) - .map(|x| buffer[(x, y)].symbol()) - .collect::() - }) - .collect::>() - .join("\n") - }; - let screen = shown(&home); - assert!(screen.contains("•••••••") && !screen.contains("hunter2")); - keys(&mut home, &[Enter]); - // A repository: added as npm, switched to raw and on to docker, which asks for an address. - keys(&mut home, &[Down, Enter]); - keys(&mut home, &typed("images")); - keys(&mut home, &[Enter, Down, Enter, Enter, Down, Enter]); - keys(&mut home, &typed("nexus.example:8083")); - keys(&mut home, &[Enter]); - let store = Store::new(&paths).unwrap(); - assert_eq!( - store.registries().unwrap()["nexus"], - json!({"type": "nexus", "url": "https://nexus.example", "username": "ci", "repositories": [ - {"format": "docker", "name": "images", "address": "nexus.example:8083"}]}) - ); - assert_eq!( - store.secret("registry/nexus").unwrap().as_deref(), - Some("hunter2") - ); - let screen = shown(&home); - println!("{screen}"); - assert!(screen.contains("Registries") && screen.contains("● stored")); - assert!(screen.contains("Docker address nexus.example:8083")); - - // A second registry of another kind: a plain npm registry with a token. - keys(&mut home, &[Down, Down, Enter]); - keys(&mut home, &typed("verdaccio")); - keys(&mut home, &[Enter, Down, Enter]); - assert_eq!(store.registries().unwrap()["verdaccio"]["type"], "npm"); - // Removing a registry takes x twice and forgets its login. - for _ in 0..12 { - keys(&mut home, &[Up]); - } - keys(&mut home, &[KeyCode::Char('x')]); - assert!(store.registries().unwrap().contains_key("nexus")); - keys(&mut home, &[KeyCode::Char('x')]); - assert!(!store.registries().unwrap().contains_key("nexus")); - assert_eq!(store.secret("registry/nexus").unwrap(), None); - } - - fn press(app: &mut App, codes: &[KeyCode]) -> bool { - let mut armed = false; - for &code in codes { - app.update_suggestions(); - let key = KeyEvent::new(code, KeyModifiers::NONE); - if matches!( - key_event(app, key, &mut armed, &mut Clipboard::default()), - Flow::Run - ) { - return true; - } - } - false - } - - #[test] - fn alt_r_shows_the_links_of_a_panel_as_qr_codes() { - let mut app = unsaved_app(b"{}"); - app.links = vec![( - Rect::new(0, 0, 1, 1), - "https://studio.example.ts.net/vnc.html".into(), - )]; - let alt_r = Event::Key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::ALT)); - assert!(qr_event(&mut app, &alt_r)); - assert_eq!( - app.qr.as_ref().map(|qr| qr.link()), - Some("https://studio.example.ts.net/vnc.html") - ); - assert!(qr_event( - &mut app, - &Event::Key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)) - )); - assert!(app.qr.is_none()); - // A plain r is the panel's. - let r = Event::Key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE)); - assert!(!qr_event(&mut app, &r)); - } - - #[test] - fn settings_are_edited_from_the_home_screen() { - let directory = tempfile::tempdir().unwrap(); - let paths = Paths { - config_dir: directory.path().join("config"), - data_dir: directory.path().join("data"), - }; - let mut home = Home { - hosts: vec![("laptop".into(), "100.64.0.1".into())], - selected: 0, - mode: HomeMode::Hosts, - status: String::new(), - started: std::time::Instant::now(), - berth_key: None, - served: None, - known: None, - asking: false, - refresh: false, - rotating: vec![], - }; - let press = |home: &mut Home, code| { - home_key( - home, - &paths, - KeyEvent::new(code, KeyModifiers::NONE), - &mut Clipboard::default(), - ) - }; - assert!(press(&mut home, KeyCode::Char('d')).is_none()); - assert_eq!(paths.settings().unwrap()["default_host"], "laptop"); - for code in [ - KeyCode::Char('3'), - KeyCode::Down, - KeyCode::Down, - KeyCode::Enter, - ] { - press(&mut home, code); - } - for ch in "/srv/iso".chars() { - press(&mut home, KeyCode::Char(ch)); - } - press(&mut home, KeyCode::Enter); - assert_eq!(paths.settings().unwrap()["iso_dir"], "/srv/iso"); - let mut terminal = Terminal::new(TestBackend::new(100, 24)).unwrap(); - terminal - .draw(|frame| draw_home(frame, &paths, &home, &mut vec![])) - .unwrap(); - let text = format!("{:?}", terminal.backend().buffer()); - assert!(text.contains("█ ▄▄ █") && text.contains("▂") && text.contains("/srv/iso")); - // Clicking the Hosts tab and then the host opens it. - let mut hits = vec![]; - let mut click = |home: &mut Home, column, row| { - terminal - .draw(|frame| draw_home(frame, &paths, home, &mut hits)) - .unwrap(); - let mouse = MouseEvent { - kind: MouseEventKind::Down(MouseButton::Left), - column, - row, - modifiers: KeyModifiers::NONE, - }; - home_mouse(home, &paths, mouse, &hits, &mut Clipboard::default()) - }; - assert!(click(&mut home, 15, 1).is_none()); - assert!(matches!(home.mode, HomeMode::Hosts)); - assert_eq!(click(&mut home, 10, 7), Some(Some("laptop".into()))); - } - - /// A home screen on the Settings tab of fresh scratch directories, and the - /// text of the screen after drawing it. - fn settings_home(directory: &std::path::Path) -> (Paths, Home) { - let paths = Paths { - config_dir: directory.join("config"), - data_dir: directory.join("data"), - }; - let home = Home { - hosts: vec![], - selected: 0, - mode: HomeMode::Settings(0, None), - status: String::new(), - started: std::time::Instant::now(), - berth_key: None, - served: None, - known: None, - asking: false, - refresh: false, - rotating: vec![], - }; - (paths, home) - } - - fn home_screen(paths: &Paths, home: &Home) -> Vec { - let mut terminal = Terminal::new(TestBackend::new(140, 30)).unwrap(); - terminal - .draw(|frame| draw_home(frame, paths, home, &mut vec![])) - .unwrap(); - let buffer = terminal.backend().buffer(); - (0..30) - .map(|y| (0..140).map(|x| buffer[(x, y)].symbol()).collect()) - .collect() - } - - #[test] - fn the_footers_leave_the_tabs_to_the_tab_bar() { - let directory = tempfile::tempdir().unwrap(); - let (paths, mut home) = settings_home(directory.path()); - for mode in [ - HomeMode::Hosts, - HomeMode::Settings(0, None), - HomeMode::Registries(RegistryView::default()), - HomeMode::Secrets(SecretView::default()), - HomeMode::Plugins(PluginView::default()), - ] { - home.mode = mode; - let rows = home_screen(&paths, &home); - let footer = rows - .iter() - .rev() - .find(|row| !row.trim().is_empty()) - .unwrap(); - for tab in &berth_tui::screen::HOME_TABS[1..] { - assert!( - !footer.to_lowercase().contains(&tab.to_lowercase()), - "{footer}" - ); - } - } - // The tab bar has them all, with the digit that opens each. - let rows = home_screen(&paths, &home).join("\n"); - for tab in berth_tui::screen::HOME_TABS { - assert!(rows.contains(tab), "{tab}"); - } - } - - #[test] - fn the_text_of_a_field_is_copied_with_its_hint_or_its_key() { - let directory = tempfile::tempdir().unwrap(); - let (paths, mut home) = settings_home(directory.path()); - let mut clipboard = Clipboard::default(); - home.mode = HomeMode::Settings(0, Some(Input::new("/srv/provision".into()))); - let rows = home_screen(&paths, &home); - let last = rows - .iter() - .position(|row| row.contains("Ctrl+O copy")) - .expect("the hint is shown"); - let column = rows[last].find("Ctrl+O copy").unwrap(); - assert!(rows[last].contains("Enter accept") && rows[last].contains("Esc cancel")); - // The rows hold only one-cell characters up to the hint, so a byte is a column. - let click = |column: usize| { - hint_click(Event::Mouse(MouseEvent { - kind: MouseEventKind::Down(MouseButton::Left), - column: column as u16, - row: last as u16, - modifiers: KeyModifiers::NONE, - })) - }; - // Enter and Esc are hints like it. - assert_eq!( - click(rows[last].find("Esc cancel").unwrap()), - Event::Key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)) - ); - let Event::Key(copy) = click(column + 2) else { - panic!("a click on the hint is a key"); - }; - assert_eq!( - copy, - KeyEvent::new(KeyCode::Char('o'), KeyModifiers::CONTROL) - ); - assert!(home_key(&mut home, &paths, copy, &mut clipboard).is_none()); - assert_eq!(clipboard.0.as_deref(), Some("/srv/provision")); - assert_eq!(home.status, "Copied the text of the field"); - // The field is still open and unchanged, and the status does not say the text. - assert!( - matches!(&home.mode, HomeMode::Settings(0, Some(input)) if input.value() == "/srv/provision") - ); - } - - #[test] - fn a_secret_setting_is_shortened_in_the_list_and_whole_in_its_field() { - let directory = tempfile::tempdir().unwrap(); - let (paths, mut home) = settings_home(directory.path()); - let token = "tok-0123456789abcdefghijklmnopqrstuvwxyz"; - paths.set("server_token", token).unwrap(); - paths.set("default_host", "studio").unwrap(); - let rows = home_screen(&paths, &home).join("\n"); - assert!(!rows.contains(token) && !rows.contains("0123456789abcdef")); - assert!(rows.contains("server_token …wxyz")); - // What is not a secret stays whole. - assert!(rows.contains("Default host studio")); - // The description reads right, with no "The" in front. - let at = crate::paths::SETTINGS - .iter() - .position(|(name, _)| *name == "server_token") - .unwrap(); - home.mode = HomeMode::Settings(at, None); - home_key( - &mut home, - &paths, - KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE), - &mut Clipboard::default(), - ); - let edited = home_screen(&paths, &home).join("\n"); - assert!(edited.contains(token)); - // The description reads right, with no "The" in front of "the token". - assert!(!edited.contains("The the") && edited.contains("The token of that berth")); - assert!(crate::paths::is_secret("store")); - assert!(!crate::paths::is_secret("serve_token")); - } - - #[test] - fn the_home_screen_draws_while_the_mirror_has_not_returned() { - let directory = tempfile::tempdir().unwrap(); - let (paths, mut home) = settings_home(directory.path()); - home.mode = HomeMode::Hosts; - // A mirror that waits for the test to let it end. - let (release, wait) = std::sync::mpsc::channel::(); - let wait = std::sync::Mutex::new(wait); - let mut mirroring = Some(crate::mirror::Mirroring::new(move || { - wait.lock().unwrap().recv().unwrap() - })); - mirroring.as_mut().unwrap().start(); - home_mirror(&mut home, &paths, &mut mirroring); - assert!(home.asking); - assert!(home_screen(&paths, &home).join("\n").contains(ASKING)); - // Starting another while one runs starts nothing. - assert!(!mirroring.as_mut().unwrap().start()); - // A host the mirror brings is listed once it is there, and not before. - Place::own("studio") - .unwrap() - .save(&paths, &json!({"access": {"address": "192.0.2.10"}})) - .unwrap(); - assert!(home.hosts.is_empty()); - release.send(Ok(())).unwrap(); - while mirroring.as_ref().unwrap().running() { - home_mirror(&mut home, &paths, &mut mirroring); - std::thread::yield_now(); - } - assert!(!home.asking); - assert_eq!(home.hosts, [("studio".to_owned(), "192.0.2.10".to_owned())]); - assert!(!home_screen(&paths, &home).join("\n").contains(ASKING)); - // A mirror that fails says why and keeps what was there. - mirroring.as_mut().unwrap().start(); - release - .send(Err( - "the berth server at http://192.0.2.7:7777: timed out".into() - )) - .unwrap(); - while mirroring.as_ref().unwrap().running() { - home_mirror(&mut home, &paths, &mut mirroring); - std::thread::yield_now(); - } - assert!(home.status.contains("timed out") && home.hosts.len() == 1); - } - - #[test] - fn hosts_show_whether_the_server_reaches_them() { - let directory = tempfile::tempdir().unwrap(); - let (paths, mut home) = settings_home(directory.path()); - home.mode = HomeMode::Hosts; - paths.set("server", "http://192.0.2.7:7777").unwrap(); - let server = berth_core::server::Server::configured(&paths).unwrap(); - for (name, address) in [ - ("attic", "192.0.2.20"), - ("studio", "192.0.2.10"), - ("yard", "192.0.2.30"), - ] { - Place::stored(&server.scope(), name) - .unwrap() - .save(&paths, &json!({"access": {"address": address}})) - .unwrap(); - } - let state = |version: &str| { - format!( - r#"{{"version":"{version}","hosts":{{"studio":{{"reachable":true,"error":null,"version":"0.3.0"}},"attic":{{"reachable":false,"error":"ssh: connect to host 192.0.2.20: timed out","version":null}}}}}}"# - ) - }; - // What a mirror keeps of the server's state is in the store, under its scope. - let store = berth_core::store::shared(&paths).unwrap(); - let mirrored = |state: String| { - store - .write( - berth_core::store::kind::MIRROR, - &server.scope(), - "state", - state.as_bytes(), - ) - .unwrap() - }; - mirrored(state("0.3.0")); - home.hosts = paths.hosts(); - home.known = known_of(&paths); - let rows = home_screen(&paths, &home); - let line = |name: &str| rows.iter().find(|row| row.contains(name)).unwrap().clone(); - assert!(line("studio").contains("● studio")); - assert!(line("attic").contains("● attic")); - assert!(line("yard").contains("○ yard")); - // The selected host, the first, is attic: its error is in the panel. - let text = rows.join("\n"); - assert!(text.contains("does not answer") && text.contains("timed out")); - // The server is older than this berth, so the screen says so. - assert!(text.contains("The berth server runs 0.3.0")); - assert!(text.contains("Update the berth server")); - for same in [berth_api::VERSION.to_owned(), "99.0.0".to_owned()] { - mirrored(state(&same)); - home.known = known_of(&paths); - let text = home_screen(&paths, &home).join("\n"); - assert!(!text.contains("The berth server runs")); - } - // With no server there is no marker and no panel. - paths.set("server", "").unwrap(); - home.known = known_of(&paths); - assert!(home.known.is_none()); - assert!(!home_screen(&paths, &home).join("\n").contains('●')); - } - - #[test] - fn an_unreachable_host_can_have_its_address_changed() { - use crate::remote::State; - let directory = tempfile::tempdir().unwrap(); - let mut app = file_app(directory.path(), "studio.json", b"{}"); - app.set_step(Step::Manage); - app.commit(Field::SshHost, "192.0.2.20"); - let error = "ssh: connect to host 192.0.2.20 port 22: Connection timed out and a long text that goes on past the width of the list so that it has to be wrapped over lines\nsecond line of the error"; - app.host.state = State::Unreachable(error.into()); - let text = screen_text(&mut app); - assert!(text.contains("This machine could not reach the host")); - assert!(text.contains("second line of the error") && text.contains("wrapped over lines")); - assert!(text.contains("Change the SSH address") && text.contains("Try again")); - // A host of the berth server is reached by the server. - app.config["builder"]["served"] = json!("http://192.0.2.7:7777"); - let text = screen_text(&mut app); - assert!(text.contains("The berth server at http://192.0.2.7:7777 could not")); - app.config["builder"] - .as_object_mut() - .unwrap() - .remove("served"); - // The action opens the address for editing. - choose(&mut app, Entry::Offer("address")); - assert!(app.retry_address && app.editing.is_some(), "{}", app.status); - assert_eq!(app.selected_field(), Some(Field::SshHost)); - let mut armed = false; - let mut clipboard = Clipboard::default(); - for code in [KeyCode::Char('9'), KeyCode::Enter] { - let event = KeyEvent::new(code, KeyModifiers::NONE); - key_event(&mut app, event, &mut armed, &mut clipboard); - } - // Saved, and the overview asks the host again. - assert!(!app.retry_address && app.step == Step::Manage); - assert!(app.text(Field::SshHost).ends_with('9')); - assert!(directory.path().join("studio.json").is_file()); - assert!(matches!(app.host.state, State::Idle | State::Connecting)); - } - - #[test] - fn the_hosts_tab_refreshes_with_r_and_the_hint_is_clickable() { - let directory = tempfile::tempdir().unwrap(); - let (paths, mut home) = settings_home(directory.path()); - home.mode = HomeMode::Hosts; - let press = |home: &mut Home, ch| { - home_key( - home, - &paths, - KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE), - &mut Clipboard::default(), - ) - }; - // Without a server it reads the saved hosts again. - Place::own("studio") - .unwrap() - .save(&paths, &json!({"access": {"address": "192.0.2.10"}})) - .unwrap(); - let rows = home_screen(&paths, &home); - let last = rows - .iter() - .position(|row| row.contains("r refresh")) - .unwrap(); - let column = rows[last].find("r refresh").unwrap(); - let Event::Key(clicked) = hint_click(Event::Mouse(MouseEvent { - kind: MouseEventKind::Down(MouseButton::Left), - column: column as u16, - row: last as u16, - modifiers: KeyModifiers::NONE, - })) else { - panic!("a click on the hint is a key"); - }; - assert_eq!(clicked.code, KeyCode::Char('r')); - assert!(home.hosts.is_empty()); - home_key(&mut home, &paths, clicked, &mut Clipboard::default()); - home_mirror(&mut home, &paths, &mut None); - assert_eq!(home.hosts.len(), 1); - // With a server it starts the mirror, and not a second while one runs. - let (release, wait) = std::sync::mpsc::channel::(); - let wait = std::sync::Mutex::new(wait); - let mut mirroring = Some(crate::mirror::Mirroring::new(move || { - wait.lock().unwrap().recv().unwrap() - })); - press(&mut home, 'r'); - home_mirror(&mut home, &paths, &mut mirroring); - assert!(home.asking); - press(&mut home, 'r'); - home_mirror(&mut home, &paths, &mut mirroring); - assert!(home.status.contains("Still asking")); - release.send(Ok(())).unwrap(); - while mirroring.as_ref().unwrap().running() { - home_mirror(&mut home, &paths, &mut mirroring); - std::thread::yield_now(); - } - // Typing a name is not a refresh, and r is no longer the Registries tab. - press(&mut home, 'n'); - press(&mut home, 'r'); - assert!(matches!(&home.mode, HomeMode::Naming(input) if input.value() == "r")); - assert!(!home.refresh); - home.mode = HomeMode::Hosts; - press(&mut home, 'r'); - assert!(matches!(home.mode, HomeMode::Hosts)); - home.mode = HomeMode::Settings(0, None); - press(&mut home, 'r'); - assert!(matches!(home.mode, HomeMode::Settings(..))); - } - - #[test] - fn the_copy_hint_of_a_host_edit_can_be_clicked() { - let directory = tempfile::tempdir().unwrap(); - let mut app = file_app(directory.path(), "studio.json", b"{}"); - app.commit(Field::SshHost, "192.0.2.20"); - app.editing = Some(Input::new("192.0.2.20".into())); - let rows: Vec = screen(&mut app).lines().map(str::to_owned).collect(); - let at = rows - .iter() - .position(|row| row.contains("Ctrl+O copy")) - .unwrap(); - let column = rows[at].find("Ctrl+O copy").unwrap(); - let click = |column: usize| { - hint_click(Event::Mouse(MouseEvent { - kind: MouseEventKind::Down(MouseButton::Left), - column: column as u16, - row: at as u16, - modifiers: KeyModifiers::NONE, - })) - }; - let Event::Key(copy) = click(column + 1) else { - panic!("a click on the hint is a key"); - }; - let mut clipboard = Clipboard::default(); - key_event(&mut app, copy, &mut false, &mut clipboard); - assert_eq!(clipboard.0.as_deref(), Some("192.0.2.20")); - assert!(app.editing.is_some()); - // Enter is a hint of the line too. - let enter = rows[at].find("Enter accept").unwrap(); - assert!(matches!(click(enter), Event::Key(key) if key.code == KeyCode::Enter)); - } - - #[test] - fn a_mirror_is_taken_in_unless_the_host_has_unsaved_changes() { - let directory = tempfile::tempdir().unwrap(); - let paths = Paths { - config_dir: directory.path().join("config"), - data_dir: directory.path().join("data"), - }; - let place = Place::stored("served:http://192.0.2.7:7777", "studio").unwrap(); - // What a mirror writes: the profile under the server's scope. - let write = |address: &str| { - place - .save(&paths, &json!({"access": {"address": address}})) - .unwrap() - }; - write("192.0.2.20"); - let stored = place.load(&paths).unwrap().unwrap(); - let mut app = App::new( - paths.clone(), - place.clone(), - parse_config(stored.to_string().as_bytes()).unwrap(), - ); - assert_eq!(app.take_in_mirror(), None); - // A new address in the mirror is taken in. - write("192.0.2.21"); - assert!(app.take_in_mirror().unwrap().contains("Took in")); - assert_eq!(app.text(Field::SshHost), "192.0.2.21"); - assert!(!app.unsaved()); - // With a change of its own the screen keeps it and says so. - app.commit(Field::SshHost, "192.0.2.99"); - write("192.0.2.22"); - let said = app.take_in_mirror().unwrap(); - assert!(said.contains("Saving sends this one")); - assert_eq!(app.text(Field::SshHost), "192.0.2.99"); - } - - #[test] - fn what_a_command_saved_of_the_host_is_not_overwritten_by_the_screen() { - let directory = tempfile::tempdir().unwrap(); - let paths = Paths { - config_dir: directory.path().join("config"), - data_dir: directory.path().join("data"), - }; - let place = Place::own("studio").unwrap(); - place - .save(&paths, &json!({"access": {"user": "ops"}})) - .unwrap(); - let open = || { - let stored = place.load(&paths).unwrap().unwrap(); - App::new( - paths.clone(), - place.clone(), - parse_config(stored.to_string().as_bytes()).unwrap(), - ) - }; - // What `berth provision` does from the screen: the machine's address - // and the cloud target go into the stored profile. - let provisioned = |port: &str| { - let mut kept = place.load(&paths).unwrap().unwrap(); - kept["access"]["address"] = json!("192.0.2.40"); - kept["access"]["port"] = json!(port); - kept["target"] = json!("cloud"); - place.save(&paths, &kept).unwrap(); - }; - let mut app = open(); - assert_eq!(app.take_in_command(), None); - provisioned("2222"); - assert!(app.take_in_command().unwrap().contains("Took in")); - assert!(!app.unsaved()); - app.save().unwrap(); - let kept = place.load(&paths).unwrap().unwrap(); - assert_eq!(kept["access"]["address"], "192.0.2.40"); - - // With changes not saved yet the address joins them, and saving keeps both. - let mut app = open(); - app.commit(Field::Keyboard, "us"); - provisioned("2200"); - let said = app.take_in_command().unwrap(); - assert!(said.contains("not saved yet"), "{said}"); - assert!(app.unsaved()); - assert_eq!(app.text(Field::SshPort), "2200"); - app.save().unwrap(); - let kept = place.load(&paths).unwrap().unwrap(); - assert_eq!( - (&kept["access"]["port"], &kept["keyboard"], &kept["target"]), - (&json!("2200"), &json!("us"), &json!("cloud")) - ); - } - - #[test] - fn words_of_output_can_be_copied() { - assert_eq!( - words("App: code K79HUTDTLL75"), - [ - (0, "App".to_owned()), - (5, "code".to_owned()), - (15, "K79HUTDTLL75".to_owned()) - ] - ); - // The address inside brackets, without them or the semicolon. - assert_eq!( - words("(or https://100.64.0.1:9090; log in)")[1], - (4, "https://100.64.0.1:9090".to_owned()) - ); - } - - #[test] - fn web_addresses_in_output_are_found() { - let parts = - with_links("Cockpit https://box.ts.net:9090 (or https://100.64.0.1:9090; log in)"); - let links: Vec<_> = parts - .iter() - .filter(|part| part.1) - .map(|part| &part.0) - .collect(); - assert_eq!( - links, - ["https://box.ts.net:9090", "https://100.64.0.1:9090"] - ); - let text: String = parts.iter().map(|part| part.0.as_str()).collect(); - assert!(text.ends_with("; log in)") && text.starts_with("Cockpit ")); - assert_eq!( - with_links("ssh ops@host"), - [("ssh ops@host".to_owned(), false)] - ); - } - - /// The text of the rows of the current tab. - fn lines(app: &App) -> Vec { - app.rows().iter().map(|row| row.line.to_string()).collect() - } - - fn select(app: &mut App, entry: Entry) { - let at = app.entries().iter().position(|known| *known == entry); - app.list - .select(Some(at.unwrap_or_else(|| panic!("no {entry:?}")))); - } - - #[test] - fn the_set_up_tabs_go_from_install_to_a_blocked_run() { - let directory = tempfile::tempdir().unwrap(); - let mut app = file_app(directory.path(), "profile.json", b"{}"); - use KeyCode::*; - // A new host opens on Install; the tabs say nothing but their names. - assert_eq!(app.step, Step::Install); - let install = screen(&mut app); - let header = install.lines().nth(1).unwrap(); - let place = |text: &str| header.find(text).unwrap(); - assert!(place("Install") < place("Features") && place("Features") < place("Settings")); - assert!(place("Settings") < place("Run") && !header.contains('✗')); - assert!(install.contains("1-4 tab")); - // The USB installer is the default method; what it needs chosen follows. - press(&mut app, &[Down, Enter, Down, Down, Down, Down, Down, Down]); - assert_eq!(app.action, Action::Iso); - let install = screen(&mut app); - assert!(install.contains("● USB installer")); - assert!(install.contains("▌ Target laptop"), "{install}"); - assert!(install.contains("Suggestions")); - assert!(!install.contains("Disk selection") && !install.contains("Source ISO")); - - // Type a hostname here, then cycle the disk mode on Settings from the suggestions. - press( - &mut app, - &[Down, Enter, Char('b'), Char('o'), Char('x'), Enter], - ); - assert_eq!(app.text(Field::Hostname), "box"); - press(&mut app, &[Char('3')]); - assert_eq!(app.step, Step::Settings); - select(&mut app, Entry::Field(Field::DiskMode)); - press(&mut app, &[Right, Down, Enter]); - assert_eq!(app.text(Field::DiskMode), "serial"); - let settings = lines(&app); - assert!(settings.contains(&" │ └─ Target disk serial Not set".to_owned())); - assert_eq!( - settings.last().unwrap(), - "✗ Serial disk selection needs the target disk serial" - ); - - // Run has the ISO, every problem under its tab, and a button that refuses. - press(&mut app, &[Char('4')]); - let run = lines(&app); - assert!(run[0].starts_with("Source ISO")); - let at = |text: &str| run.iter().position(|row| row.contains(text)).unwrap(); - assert!(at("Settings") < at(" ✗ Serial disk selection needs the target disk serial")); - assert!(at("Run") < at(" ✗ Source ISO file does not exist")); - select(&mut app, Entry::Run); - assert!(!press(&mut app, &[Enter])); - assert!(screen(&mut app).contains("[Run · USB installer]")); - assert!(app.status.contains("Fix the listed problems")); - // Save does what Ctrl+S does. - select(&mut app, Entry::Save); - press(&mut app, &[Enter]); - assert!(directory.path().join("profile.json").is_file() && !app.unsaved()); - app.commit(Field::Keyboard, "us"); - - // Unsaved changes need a second q; Ctrl+S clears that. - let mut armed = false; - let q = KeyEvent::new(Char('q'), KeyModifiers::NONE); - // The first q only leaves the set-up pages for the host's overview. - assert!(matches!( - key_event(&mut app, q, &mut armed, &mut Clipboard::default()), - Flow::Continue - )); - assert!(!armed && app.step == Step::Manage); - assert!(matches!( - key_event(&mut app, q, &mut armed, &mut Clipboard::default()), - Flow::Continue - )); - assert!(armed); - let save = KeyEvent::new(Char('s'), KeyModifiers::CONTROL); - key_event(&mut app, save, &mut armed, &mut Clipboard::default()); - assert!(directory.path().join("profile.json").is_file() && !app.unsaved()); - assert!(matches!( - key_event(&mut app, q, &mut armed, &mut Clipboard::default()), - Flow::Quit - )); - } - - #[test] - fn unlock_dialog_masks_the_password_and_closes_on_escape() { - let mut app = unsaved_app(b"{}"); - app.unlock = Some(Input::new("hunter2".into())); - app.unlock_failed = true; - let text = screen(&mut app); - assert!(text.contains("Password for ")); - assert!(text.contains("› •••••••")); - assert!(text.contains("Wrong password")); - assert!(!text.contains("hunter2")); - let escape = Event::Key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - unlock_event(&mut app, &escape, &mut Desktop); - assert!(app.unlock.is_none()); - } - - #[test] - fn a_running_action_shows_its_progress_and_output() { - let mut app = unsaved_app(b"{}"); - app.action = Action::Iso; - let mut command = std::process::Command::new("sh"); - command.args([ - "-c", - "echo copying; echo 'xorriso : UPDATE : Writing: 1s 46.4% fifo'; sleep 5", - ]); - let stage = crate::job::Stage { - title: "Build unattended ISO".into(), - command, - source: None, - input: None, - }; - app.job = Some(Job::start(vec![stage], "", vec![]).unwrap()); - let mut text = String::new(); - for _ in 0..200 { - app.job.as_mut().unwrap().tick(); - text = screen(&mut app); - if text.contains("46%") { - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } - assert!(text.contains("46%") && text.contains("copying"), "{text}"); - assert!(text.contains("Esc cancel")); - let escape = Event::Key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - job_event(&mut app, &escape); - for _ in 0..200 { - app.job.as_mut().unwrap().tick(); - if !app.job.as_ref().unwrap().running() { - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } - assert!(screen(&mut app).contains("Enter close")); - job_event( - &mut app, - &Event::Key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)), - ); - assert!(app.job.is_none()); - } - - #[test] - fn writing_a_usb_drive_asks_before_erasing() { - let mut app = unsaved_app(b"{}"); - app.confirm = Some("Erase /dev/sdz · Stick · 14.6G?".into()); - let text = screen(&mut app); - assert!(text.contains("Erase /dev/sdz") && text.contains("y erase")); - confirm_event( - &mut app, - &Event::Key(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE)), - ); - assert!(app.confirm.is_none() && app.job.is_none()); - } - - /// A host that has answered, with a few actions as it would list them. - fn controller_actions() -> Vec { - serde_json::from_value(json!([ - {"name": "status", "label": "Status", "group": "System", "user": "root", "help": "How the host is."}, - {"name": "claude:status", "label": "Claude Code sign-in", "extends": ["sign-in:status"], "help": "Whether Claude is signed in."}, - {"name": "sign-in:status", "label": "Show who is signed in", "group": "Sign-In", "help": "Accounts."}, - {"name": "claude:login", "label": "Sign in to Claude Code", "group": "sign-in", "terminal": true}, - {"name": "reboot", "label": "Reboot", "group": "System", "user": "root", "confirm": "Restart the host?"}, - {"name": "backup:restore", "label": "Restore", "group": "Backup", - "arguments": [{"name": "snapshot", "label": "Snapshot", "required": true, "choices": "restic snapshots"}, - {"name": "target", "default": "/"}]}, - ])) - .unwrap() - } - - #[test] - fn a_host_that_is_not_a_workstation_is_offered_the_controller_and_no_apply() { - use crate::remote::State; - let mut app = unsaved_app(br#"{"type": "ssh", "access": {"address": "192.0.2.4"}}"#); - app.set_step(Step::Manage); - app.host.host_type = berth_api::HostType::Ssh; - app.host.state = State::Missing; - app.host.seen = Some(berth_api::HostType::Ssh); - app.host.own = - berth_core::host_type::local_actions("devbox", berth_api::HostType::Ssh, None); - let text = screen_text(&mut app); - assert!(text.contains("Type · ssh"), "{text}"); - assert!(text.contains("▸ Install the controller") && text.contains("▸ Terminal over SSH")); - assert!(!app.entries().contains(&Entry::Offer("apply"))); - // Choosing it, and saying yes, runs berth host install in the normal terminal. - let at = app - .entries() - .iter() - .position(|entry| *entry == Entry::HostAction(0)) - .unwrap(); - app.list.select(Some(at)); - press(&mut app, &[KeyCode::Enter]); - question_event( - &mut app, - &Event::Key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)), - ); - let words = app.own_command.clone().unwrap(); - assert_eq!(words[..2], ["host".to_owned(), "install".to_owned()]); - app.own_command = None; - - // A host that cannot be reached still lists berth's own actions. - app.host.state = State::Unreachable( - "ssh: connect to host 192.0.2.4 port 22: Network is unreachable".into(), - ); - let rows: Vec = app.rows().iter().map(|row| row.line.to_string()).collect(); - let text = rows.join("\n"); - assert!( - text.contains("Network is unreachable") && text.contains("▸ Install the controller"), - "{text}" - ); - assert!(app.entries().contains(&Entry::HostAction(0))); - - // A managed host lists berth's own beside its actions; one it cannot - // run is marked, and its reason is in the information box. - app.own_command = None; - app.config["type"] = json!("managed"); - app.host.host_type = berth_api::HostType::Managed; - app.host.state = State::Ready(berth_api::VERSION.into()); - app.host.host_actions = controller_actions(); - app.host.own = vec![ - berth_core::host_type::install_controller_action( - "devbox", - berth_api::HostType::Managed, - None, - ), - berth_api::Action { - name: "host-key".into(), - label: "Host key".into(), - group: "Access".into(), - available: false, - why: "devbox has no profile on the server".into(), - ..berth_api::Action::default() - }, - ]; - let rows: Vec = app.rows().iter().map(|row| row.line.to_string()).collect(); - assert!( - rows.iter() - .any(|row| row.contains("▸ Update the controller")) - ); - assert!(rows.iter().any(|row| row.contains("▸ Host key · not now"))); - assert_eq!( - rows.iter().filter(|row| row.as_str() == "Set-Up").count(), - 1, - "{rows:?}" - ); - assert!(!app.entries().contains(&Entry::Offer("apply"))); - let index = app - .host - .actions() - .iter() - .position(|action| action.name == "host-key") - .unwrap(); - app.begin_action(index, false); - assert!(app.status.contains("cannot run now: devbox has no profile")); - assert!(app.own_command.is_none()); - } - - #[test] - fn an_existing_host_is_offered_the_type_it_says_it_has() { - let mut app = unsaved_app(br#"{"access": {"address": "192.0.2.4"}}"#); - app.offer_type(Some(berth_api::HostType::Managed)); - assert_eq!(app.config["type"], "managed"); - assert!(app.status.contains("answers as a host of the type managed")); - // Nothing found, or what it is already, changes nothing. - app.offer_type(None); - app.offer_type(Some(berth_api::HostType::Managed)); - assert_eq!(app.config["type"], "managed"); - // A type chosen on its row stays; the host's answer is only told. - app.commit(Field::Type, "ssh"); - app.offer_type(Some(berth_api::HostType::Workstation)); - assert_eq!(app.config["type"], "ssh"); - assert!( - app.status.contains("its Type here says ssh"), - "{}", - app.status - ); - } - - #[test] - fn the_overview_is_what_the_host_lists() { - use crate::remote::{Pending, State}; - let mut app = unsaved_app(b"{}"); - app.set_step(Step::Manage); - assert_eq!(app.action, Action::Manage); - // Without an address there is nothing to ask. - let manage = screen(&mut app); - assert!(manage.contains("✗ Enter an SSH hostname") && !manage.contains("▸ Status")); - assert!(app.entries().contains(&Entry::Offer("apply"))); - - app.commit(Field::SshHost, "devbox.example"); - app.config["agent_username"] = json!("robot"); - assert!(screen_text(&mut app).contains("Asking the host")); - // A host without berth's controller offers to apply, once. - app.host.state = State::Missing; - let applies = |app: &App| { - app.entries() - .iter() - .filter(|entry| **entry == Entry::Offer("apply")) - .count() - }; - assert!(screen_text(&mut app).contains("not on this host yet") && applies(&app) == 1); - app.host.state = - State::Unreachable("ssh: connect to host devbox.example: timed out\nmore".into()); - let text = screen_text(&mut app); - assert!(text.contains("✗ ssh: connect to host") && text.contains("▸ Terminal over SSH")); - assert!(app.entries().contains(&Entry::Offer("connect"))); - - // One that answered lists its actions in their groups. - app.host.state = State::Ready("0.2.0".into()); - app.host.host_actions = controller_actions(); - let rows: Vec = app.rows().iter().map(|row| row.line.to_string()).collect(); - let place = |text: &str| rows.iter().position(|row| row.contains(text)).unwrap(); - assert!( - place("System") < place("▸ Status") - && place("▸ Status") < place("▸ Terminal · as robot") - ); - assert!(place("▸ Terminal") < place("▸ Reboot")); - // Groups are matched whatever their case; a step has no row of its own. - assert!(place("Sign-In") < place("▸ Show who is signed in")); - assert!(place("▸ Show who is signed in") < place("▸ Sign in to Claude Code")); - assert!(place("Backup") > place("▸ Sign in to Claude Code")); - assert!(!rows.iter().any(|row| row.contains("Claude Code sign-in"))); - assert!(!rows.iter().any(|row| row.contains("Sessions"))); - let select = |app: &mut App, entry: Entry| { - let at = app.entries().iter().position(|known| *known == entry); - app.list.select(Some(at.unwrap())); - }; - // The information box says what the plugins' steps add. - select(&mut app, Entry::HostAction(1)); - let help = app.help(); - assert!( - help.contains("### From plugins") && help.contains("**Claude Code sign-in**: Whether") - ); - assert!(help.contains("berth run HOST sign-in:status")); - - // An action with a question waits for the yes. - select(&mut app, Entry::HostAction(3)); - assert!(!press(&mut app, &[KeyCode::Enter])); - assert_eq!( - app.host.question, - Some(("Restart the host?".into(), Pending::Action(3))) - ); - assert!(screen_text(&mut app).contains("Restart the host?")); - question_event( - &mut app, - &Event::Key(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE)), - ); - assert!(app.host.question.is_none()); - - // An action with arguments asks for each; a needed one cannot be left empty. - select(&mut app, Entry::HostAction(4)); - press(&mut app, &[KeyCode::Enter]); - let key = |app: &mut App, code| { - arguments_event( - app, - &Event::Key(KeyEvent::new(code, KeyModifiers::NONE)), - &mut Desktop, - ) - }; - assert!(screen_text(&mut app).contains("Restore · 1 of 2")); - key(&mut app, KeyCode::Enter); - assert!(app.status.contains("Snapshot is needed")); - app.host.arguments.as_mut().unwrap().choices = vec!["abc123".into(), "def456".into()]; - assert!(screen_text(&mut app).contains("○ def456")); - key(&mut app, KeyCode::Down); - key(&mut app, KeyCode::Down); - key(&mut app, KeyCode::Enter); - let asked = app.host.arguments.as_ref().unwrap(); - assert_eq!((asked.index, asked.input.value()), (1, "/")); - assert_eq!(asked.values["snapshot"], "def456"); - key(&mut app, KeyCode::Esc); - assert!(app.host.arguments.is_none()); - - // Sessions of the host get a group; a running one is not forgotten with x. - app.host.sessions = serde_json::from_value(json!([ - {"id": "sabc", "kind": "terminal", "title": "robot on devbox", "command": ["bash", "-l"], "user": "agent", - "started_by": {"level": "host", "uid": 0}, "started": "2026-11-12T10:00:00Z"}, - {"id": "sdef", "kind": "process", "title": "Update", "command": ["update"], "user": "root", - "started_by": {"level": "host", "uid": 0}, "started": "2026-11-12T10:00:00Z", - "ended": "2026-11-12T10:05:00Z", "exit_code": 2}, - ])) - .unwrap(); - let text: String = app - .rows() - .iter() - .map(|row| row.line.to_string() + "\n") - .collect(); - assert!( - text.contains("▸ robot on devbox · running") && text.contains("▸ Update · failed (2)") - ); - select(&mut app, Entry::HostSession(0)); - assert!( - app.help().contains("still running") && app.help().contains("berth attach HOST sabc") - ); - press(&mut app, &[KeyCode::Char('x')]); - assert!(app.status.contains("still running")); - // Opening one puts it in the panel; a transcript takes its lines. - select(&mut app, Entry::HostSession(1)); - press(&mut app, &[KeyCode::Enter]); - let view = app.host.view.as_ref().unwrap(); - assert!(view.id == "sdef" && !view.terminal && !view.ours); - assert!(screen_text(&mut app).contains("Ctrl+Q leave it running")); - view_event( - &mut app, - &Event::Key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::CONTROL)), - ); - assert!(app.host.view.is_none()); - - // Applying with a session running asks first; then it is the SSH install. - app.config["hostname"] = json!("devbox-1"); - app.config["operator_ssh_public_key"] = json!("ssh-ed25519 AAAA me"); - select(&mut app, Entry::Offer("apply")); - assert!(!press(&mut app, &[KeyCode::Enter])); - assert!(matches!(app.host.question, Some((_, Pending::Apply)))); - let yes = Event::Key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); - assert!(matches!(question_event(&mut app, &yes), Flow::Run)); - assert_eq!(app.terminal_action, Some(Action::Ssh)); - assert_eq!(app.host.state, State::Idle); - app.terminal_action = None; - - // Space switches the Terminal row between the two accounts. - app.host.state = State::Ready("0.2.0".into()); - select(&mut app, Entry::Offer("terminal")); - press(&mut app, &[KeyCode::Char(' ')]); - assert!(!app.as_agent && screen_text(&mut app).contains("the SSH user")); - press(&mut app, &[KeyCode::Char(' ')]); - // ssh's options come from berth's key ring, which is in a store. - let scratch = tempfile::tempdir().unwrap(); - app.paths = Paths { - config_dir: scratch.path().join("config"), - data_dir: scratch.path().join("data"), - }; - let command = format!("{:?}", app.agent_terminal().unwrap()); - assert!(command.contains("devbox.example") && command.contains("sudo -iu robot ")); - // The set-up tabs are a flow under the overview, opening on Install. - select(&mut app, Entry::Setup); - press(&mut app, &[KeyCode::Enter]); - assert_eq!((app.step, app.action), (Step::Install, Action::Iso)); - press(&mut app, &[KeyCode::Char('4')]); - assert_eq!(app.step, Step::Run); - press(&mut app, &[KeyCode::Esc]); - assert_eq!(app.step, Step::Manage); - // x removes the value of the selected field, and with the address - // gone what was known of the host is too. - app.host.state = State::Ready("0.2.0".into()); - select(&mut app, Entry::Field(Field::SshHost)); - press(&mut app, &[KeyCode::Char('x')]); - assert_eq!(app.text(Field::SshHost), ""); - assert_eq!(app.host.state, State::Idle); - } - - const BERTH_KEY: &str = - "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExampleKeyOfBerth1234 berth@studio"; - - #[test] - fn settings_show_the_key_of_berth_and_copy_it() { - let directory = tempfile::tempdir().unwrap(); - let paths = Paths { - config_dir: directory.path().join("config"), - data_dir: directory.path().join("data"), - }; - paths.set("server", "https://192.0.2.7:8443").unwrap(); - paths.set("server_token", "a1b2").unwrap(); - let mut home = Home { - hosts: vec![], - selected: 0, - mode: HomeMode::Settings(0, None), - status: String::new(), - started: std::time::Instant::now(), - berth_key: Some(( - vec![("berth".into(), BERTH_KEY.into())], - Some("https://192.0.2.7:8443".into()), - )), - served: None, - known: None, - asking: false, - refresh: false, - rotating: vec![], - }; - let mut clipboard = Clipboard::default(); - let settings = berth_core::paths::SETTINGS.len(); - for _ in 0..settings { - home_key( - &mut home, - &paths, - KeyEvent::new(KeyCode::Down, KeyModifiers::NONE), - &mut clipboard, - ); - } - // The key comes after the settings. - assert!(matches!(home.mode, HomeMode::Settings(index, _) if index == settings)); - let mut terminal = Terminal::new(TestBackend::new(130, 50)).unwrap(); - terminal - .draw(|frame| draw_home(frame, &paths, &home, &mut vec![])) - .unwrap(); - let buffer = terminal.backend().buffer(); - let screen = (0..50) - .map(|y| { - (0..130) - .map(|x| buffer[(x, y)].symbol()) - .collect::() - }) - .collect::>() - .join("\n"); - assert!( - screen.contains("This berth's SSH key ssh-ed25519 …erth1234 berth@studio"), - "{screen}" - ); - assert!(screen.contains("Enter copy the key") && screen.contains("berth server at")); - home_key( - &mut home, - &paths, - KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE), - &mut clipboard, - ); - assert_eq!(clipboard.0.as_deref(), Some(BERTH_KEY)); - assert_eq!(home.status, "Copied this berth's SSH public key"); - // Without a key to give there is no row for it. - home.berth_key = Some((vec![], None)); - home.mode = HomeMode::Settings(settings, None); - home_key( - &mut home, - &paths, - KeyEvent::new(KeyCode::Down, KeyModifiers::NONE), - &mut clipboard, - ); - assert!(matches!(home.mode, HomeMode::Settings(index, _) if index == settings - 1)); - } - - fn lab(id: &str, label: &str, resources: &[&str]) -> berth_api::ProvisionerInfo { - let mut arguments = vec![berth_api::Argument { - name: "server".into(), - label: "Lab server".into(), - required: true, - ..Default::default() - }]; - arguments.extend(resources.iter().map(|name| berth_api::Argument { - name: (*name).into(), - label: format!("Lab {name}"), - default: "4".into(), - kind: berth_api::Argument::RESOURCE.into(), - ..Default::default() - })); - berth_api::ProvisionerInfo { - id: id.into(), - label: label.into(), - setup: "apply".into(), - arguments, - ..Default::default() - } - } - - #[test] - fn the_tabs_create_and_delete_the_machine() { - use berth_tui::machine::Pick; - let profile = format!( - r#"{{"hostname": "studio", "operator_password_hash": "$6${}", - "operator_ssh_public_keys": ["ssh-ed25519 AAAA studio"]}}"#, - "a".repeat(40) - ); - let mut app = unsaved_app(profile.as_bytes()); - app.set_step(Step::Install); - app.action = Action::Machine; - let machine_rows = |app: &App| -> Vec { - app.entries() - .into_iter() - .filter(|entry| matches!(entry, Entry::Machine(_))) - .collect() - }; - // Nothing was asked without berth's own folders, so nothing shows. - assert!(machine_rows(&app).is_empty()); - app.machine.asking(); - app.machine.listed(Ok(vec![ - lab("lab/vm", "Lab machine", &["cpus", "memory"]), - lab("lab/box", "Lab box", &["cpus"]), - ])); - app.machine.found(Ok(None)); - // The provisioner is one row, and what it requires is under it. - assert!(lines(&app).contains( - &"Provisioner Lab machine · berth applies the profile over SSH".to_owned() - )); - assert_eq!( - machine_rows(&app), - [ - Entry::Machine(Pick::Provisioner), - Entry::Machine(Pick::Argument(0)) - ] - ); - let install = lines(&app); - assert!(install.contains(&" └─ Lab server * Not set".to_owned())); - assert_eq!(install.last().unwrap(), "✗ Lab server is required"); - // Its size is under Machine on Settings, and goes with the provisioner. - press(&mut app, &[KeyCode::Char('3')]); - let settings = lines(&app); - assert_eq!( - settings[..3], - ["Machine", " ├─ Lab cpus 4", " └─ Lab memory 4"] - ); - press(&mut app, &[KeyCode::Char('1')]); - select(&mut app, Entry::Machine(Pick::Provisioner)); - press(&mut app, &[KeyCode::Enter, KeyCode::Char('3')]); - assert_eq!(lines(&app)[..2], ["Machine", " └─ Lab cpus 4"]); - press(&mut app, &[KeyCode::Char('1')]); - select(&mut app, Entry::Machine(Pick::Provisioner)); - press(&mut app, &[KeyCode::Enter]); - assert!( - lines(&app) - .iter() - .any(|row| row.contains("Provisioner Lab machine")) - ); - - // Creating with a required argument empty is refused before asking. - press(&mut app, &[KeyCode::Char('4')]); - let run = lines(&app); - assert!(run.contains(&" ✗ Lab server is required".to_owned())); - select(&mut app, Entry::Machine(Pick::Create)); - press(&mut app, &[KeyCode::Enter]); - assert!(app.machine.question.is_none() && app.status.contains("Fix the listed problems")); - press(&mut app, &[KeyCode::Char('1')]); - select(&mut app, Entry::Machine(Pick::Argument(0))); - press(&mut app, &[KeyCode::Enter]); - for ch in "192.0.2.10".chars() { - press(&mut app, &[KeyCode::Char(ch)]); - } - press(&mut app, &[KeyCode::Enter]); - assert_eq!(app.machine.values["server"], "192.0.2.10"); - // A size that is no size is a problem of Settings, and blocks Create. - press(&mut app, &[KeyCode::Char('3')]); - select(&mut app, Entry::Machine(Pick::Argument(2))); - press( - &mut app, - &[KeyCode::Enter, KeyCode::Char('x'), KeyCode::Enter], - ); - let settings = lines(&app); - assert_eq!( - settings.last().unwrap(), - "✗ Lab memory must be a size with its unit, such as 8GiB, 512MiB or 4g" - ); - press(&mut app, &[KeyCode::Char('4')]); - assert!( - lines(&app) - .iter() - .any(|row| row.contains(" ✗ Lab memory must be a size")) - ); - select(&mut app, Entry::Machine(Pick::Create)); - press(&mut app, &[KeyCode::Enter]); - assert!(app.machine.question.is_none() && app.status.contains("Fix the listed problems")); - press(&mut app, &[KeyCode::Char('3')]); - select(&mut app, Entry::Machine(Pick::Argument(2))); - press(&mut app, &[KeyCode::Enter, KeyCode::Backspace]); - for ch in "8GiB".chars() { - press(&mut app, &[KeyCode::Char(ch)]); - } - press(&mut app, &[KeyCode::Enter, KeyCode::Char('4')]); - assert!(lines(&app).contains(&"✓ Ready".to_owned())); - select(&mut app, Entry::Machine(Pick::Create)); - press(&mut app, &[KeyCode::Enter]); - let shown = screen_text(&mut app); - assert!( - shown.contains("Create a machine for studio with Lab machine?"), - "{shown}" - ); - app.machine_answer(false); - assert!(app.machine.question.is_none() && app.job.is_none()); - - // Another way to install has no provisioner to choose. - app.action = Action::Ssh; - app.set_step(Step::Install); - assert!(machine_rows(&app).is_empty()); - // With a machine, its state and what can be done to it are on Run, whatever the way. - app.machine.found(Ok(Some(berth_api::Resource { - provisioner: "lab/vm".into(), - id: "r-studio".into(), - external_id: "studio".into(), - state: "stopped".into(), - verbs: vec!["start".into()], - ..Default::default() - }))); - app.set_step(Step::Run); - assert_eq!( - machine_rows(&app), - [Entry::Machine(Pick::Start), Entry::Machine(Pick::Delete)] - ); - select(&mut app, Entry::Machine(Pick::Delete)); - press(&mut app, &[KeyCode::Enter]); - assert!(screen_text(&mut app).contains("Type studio to delete its machine")); - for ch in "studi".chars() { - press(&mut app, &[KeyCode::Char(ch)]); - } - press(&mut app, &[KeyCode::Enter]); - assert!(app.status.starts_with("Not deleted") && app.job.is_none()); - } - - #[test] - fn the_provisioner_is_a_choice_like_the_others() { - use KeyCode::*; - use berth_tui::machine::Pick; - let mut app = unsaved_app(br#"{"target": "laptop"}"#); - app.machine.asking(); - app.machine.listed(Ok(vec![ - lab("lab/vm", "Lab machine", &["cpus"]), - lab("lab/box", "Lab box", &[]), - ])); - app.machine.found(Ok(None)); - // Choosing the way makes the target cloud, and offers none to choose. - select(&mut app, Entry::Action(Action::Machine)); - press(&mut app, &[Enter]); - assert_eq!(app.config["target"], "cloud"); - assert!(!lines(&app).iter().any(|row| row.contains("Target"))); - // The row offers the provisioners in the panel, at the chosen one. - select(&mut app, Entry::Machine(Pick::Provisioner)); - let shown = screen(&mut app); - assert!( - shown.contains("Suggestions") && shown.contains("Lab box"), - "{shown}" - ); - assert_eq!( - app.suggestions, - [ - ("Lab machine".to_owned(), "lab/vm".to_owned()), - ("Lab box".to_owned(), "lab/box".to_owned()) - ] - ); - assert_eq!(app.suggestion_list.selected(), Some(0)); - // Space goes on to the next, and the panel follows it. - press(&mut app, &[Char(' ')]); - assert_eq!(app.machine.chosen.as_deref(), Some("lab/box")); - app.update_suggestions(); - assert_eq!(app.suggestion_list.selected(), Some(1)); - // → enters the panel, and Enter there chooses. - press(&mut app, &[Right, Up, Enter]); - assert_eq!(app.machine.chosen.as_deref(), Some("lab/vm")); - assert!(!app.suggestion_focus); - assert!( - app.help() - .contains("Space or Enter switches to the next provisioner") - ); - } -} diff --git a/tests/e2e/e2e_local.py b/tests/e2e/e2e_local.py index 36e9f3c..3a7c34a 100644 --- a/tests/e2e/e2e_local.py +++ b/tests/e2e/e2e_local.py @@ -106,7 +106,8 @@ def test_the_hosts_of_an_older_berth_move_into_the_store(self): @needs_e2e class Screens(unittest.TestCase): - """The terminal UI starts, shows the host and what berthd says of it, and quits.""" + """The screens start with a server in berth itself, show the host and what + berthd says of it, and quit.""" @classmethod def setUpClass(cls): @@ -126,6 +127,9 @@ def test_the_overview_shows_the_hosts_tasks(self): try: # The rows of the tasks come from berthd on the host. terminal.expect('Secrets and registry logins') + # q goes back to the hosts, and there it quits. + terminal.send('q') + terminal.expect('New host') terminal.send('q') self.assertEqual(terminal.wait(), 0) finally: From a70ffa938942d7f9167c103ab8e66ee5171039b3 Mon Sep 17 00:00:00 2001 From: Helight Date: Sun, 15 Nov 2026 01:29:31 +0100 Subject: [PATCH 17/94] feat!: berth for macOS and Windows, and no berth-remote berth is built for Linux, macOS and Windows. Its installation, berth serve and the commands are in its Linux build alone, behind one cfg; elsewhere it is the screens, berth connect and berth update. The release packs berth for five systems, install.sh installs it on Linux and macOS and install.ps1 on Windows; install-remote.sh is gone. --- .github/workflows/release.yml | 150 +++--- AGENTS.md | 15 +- Cargo.lock | 8 - Cargo.toml | 4 +- ci/checks.sh | 4 +- crates/berth-remote/Cargo.toml | 15 - crates/berth-remote/README.md | 66 --- crates/berth-remote/src/lib.rs | 3 - crates/berth-remote/src/main.rs | 32 -- crates/berth-remote/src/options.rs | 165 ------- crates/berth-tui/Cargo.toml | 2 +- crates/berth-tui/src/lib.rs | 6 +- crates/berth-tui/src/machine.rs | 2 +- crates/berth-tui/src/page.rs | 4 +- crates/berth-tui/src/plugins.rs | 7 +- crates/berth-tui/src/provisioners.rs | 5 +- crates/berth-tui/src/setup.rs | 2 +- crates/berth/Cargo.toml | 19 +- crates/berth/src/client_only.rs | 30 ++ crates/berth/src/connect.rs | 121 +++++ crates/berth/src/{ => local}/commands.rs | 100 +--- crates/berth/src/{ => local}/key_command.rs | 12 +- crates/berth/src/local/mod.rs | 426 +++++++++++++++++ crates/berth/src/{ => local}/profile.rs | 0 .../src/{ => local}/provisioner_command.rs | 2 +- .../berth/src/{ => local}/resource_command.rs | 4 +- crates/berth/src/{ => local}/serve/actions.rs | 0 crates/berth/src/{ => local}/serve/api.rs | 0 crates/berth/src/{ => local}/serve/auth.rs | 0 crates/berth/src/{ => local}/serve/docs.rs | 0 crates/berth/src/{ => local}/serve/here.rs | 2 +- crates/berth/src/{ => local}/serve/keys.rs | 0 crates/berth/src/{ => local}/serve/mod.rs | 2 +- .../src/{ => local}/serve/provisioners.rs | 0 .../berth/src/{ => local}/serve/resources.rs | 0 crates/berth/src/{ => local}/serve/setup.rs | 0 .../berth/src/{ => local}/serve/setup_key.rs | 4 +- crates/berth/src/{ => local}/serve/tests.rs | 9 +- .../berth/src/{ => local}/serve/tests/keys.rs | 0 .../src/{ => local}/serve/tests/remote.rs | 0 crates/berth/src/{ => local}/store_command.rs | 4 +- crates/berth/src/main.rs | 436 ++---------------- crates/berth/src/update.rs | 47 +- install-remote.sh | 59 --- install.ps1 | 22 +- install.sh | 29 +- 46 files changed, 802 insertions(+), 1016 deletions(-) delete mode 100644 crates/berth-remote/Cargo.toml delete mode 100644 crates/berth-remote/README.md delete mode 100644 crates/berth-remote/src/lib.rs delete mode 100644 crates/berth-remote/src/main.rs delete mode 100644 crates/berth-remote/src/options.rs create mode 100644 crates/berth/src/client_only.rs create mode 100644 crates/berth/src/connect.rs rename crates/berth/src/{ => local}/commands.rs (95%) rename crates/berth/src/{ => local}/key_command.rs (95%) create mode 100644 crates/berth/src/local/mod.rs rename crates/berth/src/{ => local}/profile.rs (100%) rename crates/berth/src/{ => local}/provisioner_command.rs (99%) rename crates/berth/src/{ => local}/resource_command.rs (99%) rename crates/berth/src/{ => local}/serve/actions.rs (100%) rename crates/berth/src/{ => local}/serve/api.rs (100%) rename crates/berth/src/{ => local}/serve/auth.rs (100%) rename crates/berth/src/{ => local}/serve/docs.rs (100%) rename crates/berth/src/{ => local}/serve/here.rs (99%) rename crates/berth/src/{ => local}/serve/keys.rs (100%) rename crates/berth/src/{ => local}/serve/mod.rs (99%) rename crates/berth/src/{ => local}/serve/provisioners.rs (100%) rename crates/berth/src/{ => local}/serve/resources.rs (100%) rename crates/berth/src/{ => local}/serve/setup.rs (100%) rename crates/berth/src/{ => local}/serve/setup_key.rs (97%) rename crates/berth/src/{ => local}/serve/tests.rs (99%) rename crates/berth/src/{ => local}/serve/tests/keys.rs (100%) rename crates/berth/src/{ => local}/serve/tests/remote.rs (100%) rename crates/berth/src/{ => local}/store_command.rs (99%) delete mode 100755 install-remote.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 39b399a..fa65a69 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -8,87 +8,30 @@ on: permissions: contents: read jobs: + # berth for each system, built on that system so that its version can be + # run there. On Linux it carries berthd and box for the hosts, which are + # built for x86_64 wherever berth is; on macOS and Windows it is a client + # of a berth serve elsewhere. binary: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - # A tag vX.Y.Z builds version X.Y.Z. Any other build says the version in - # Cargo.toml, which is that of the latest release. - - name: The version - run: | - if [ "$GITHUB_REF_TYPE" = tag ]; then - version=${GITHUB_REF_NAME#v} - if ! echo "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$'; then - echo "::error::$GITHUB_REF_NAME is not a version tag such as v1.2.0 or v1.2.0-rc.1" - exit 1 - fi - echo "BERTH_BUILD_VERSION=$version" >> "$GITHUB_ENV" - fi - - uses: dtolnay/rust-toolchain@stable - with: - targets: x86_64-unknown-linux-musl - - name: musl compiler for the bundled SQLite - run: sudo apt-get update && sudo apt-get install -y --no-install-recommends musl-tools - - uses: Swatinem/rust-cache@v2 - - name: Build berth, with berthd and box inside - run: cargo build --release --locked --target x86_64-unknown-linux-musl -p berth - - name: Pack - run: | - mkdir dist - cp target/x86_64-unknown-linux-musl/release/berth LICENSE-MIT LICENSE-APACHE dist/ - tar -czf berth-x86_64-linux.tar.gz -C dist berth LICENSE-MIT LICENSE-APACHE - sha256sum berth-x86_64-linux.tar.gz > berth-x86_64-linux.tar.gz.sha256 - cp target/host/x86_64-unknown-linux-musl/release/berthd target/host/x86_64-unknown-linux-musl/release/box dist/ - - name: Check the versions - # berth in the archive, and the berthd and box it carries, all say the same. - run: | - want=${BERTH_BUILD_VERSION:-$(sed -n '/^\[workspace.package\]/,/^\[/s/^version = "\(.*\)"/\1/p' Cargo.toml)} - mkdir check - tar -xzf berth-x86_64-linux.tar.gz -C check berth - for program in check/berth dist/berthd dist/box; do - said=$("$program" --version) - echo "$program: $said" - case "$said" in - "${program##*/} $want" | "${program##*/} $want "*) ;; - *) echo "::error::$program says $said, not $want"; exit 1 ;; - esac - done - rm -r check - - uses: actions/upload-artifact@v4 - with: - name: berth-x86_64-linux - path: | - berth-x86_64-linux.tar.gz - berth-x86_64-linux.tar.gz.sha256 - - uses: actions/upload-artifact@v4 - with: - name: host-programs-x86_64-linux - path: | - dist/berthd - dist/box - # berth-remote, the screens of berth serve in a terminal, to use a server's - # hosts from another machine. Each is built on the system it is for, so - # that its version can be run there. - remote: strategy: fail-fast: false matrix: include: - - runner: windows-latest - target: x86_64-pc-windows-msvc - asset: berth-remote-x86_64-windows.zip - - runner: macos-15 - target: aarch64-apple-darwin - asset: berth-remote-aarch64-macos.tar.gz - - runner: macos-15-intel - target: x86_64-apple-darwin - asset: berth-remote-x86_64-macos.tar.gz - runner: ubuntu-latest target: x86_64-unknown-linux-musl - asset: berth-remote-x86_64-linux.tar.gz + asset: berth-x86_64-linux.tar.gz - runner: ubuntu-24.04-arm target: aarch64-unknown-linux-musl - asset: berth-remote-aarch64-linux.tar.gz + asset: berth-aarch64-linux.tar.gz + - runner: macos-15 + target: aarch64-apple-darwin + asset: berth-aarch64-macos.tar.gz + - runner: macos-15-intel + target: x86_64-apple-darwin + asset: berth-x86_64-macos.tar.gz + - runner: windows-latest + target: x86_64-pc-windows-msvc + asset: berth-x86_64-windows.zip runs-on: ${{ matrix.runner }} defaults: run: @@ -96,11 +39,14 @@ jobs: env: # The C runtime goes into the program, so that Windows needs nothing installed. CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS: -C target-feature=+crt-static - # ring's C is built against musl too, so that the program runs on any Linux. + # The bundled SQLite and ring's C are built against musl too, so that + # the program runs on any Linux. CC_x86_64_unknown_linux_musl: musl-gcc CC_aarch64_unknown_linux_musl: musl-gcc steps: - uses: actions/checkout@v7 + # A tag vX.Y.Z builds version X.Y.Z. Any other build says the version in + # Cargo.toml, which is that of the latest release. - name: The version run: | if [ "$GITHUB_REF_TYPE" = tag ]; then @@ -113,20 +59,26 @@ jobs: fi - uses: dtolnay/rust-toolchain@stable with: - targets: ${{ matrix.target }} - - name: musl compiler for ring + # On Linux the host programs are built for x86_64 as well. + targets: ${{ matrix.target }}${{ runner.os == 'Linux' && ',x86_64-unknown-linux-musl' || '' }} + - name: musl compiler if: runner.os == 'Linux' run: sudo apt-get update && sudo apt-get install -y --no-install-recommends musl-tools + # berthd and box have no C in them: on an arm runner they are linked + # for x86_64 by Rust's own linker. + - name: A linker for the host programs + if: matrix.target == 'aarch64-unknown-linux-musl' + run: echo "CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_LINKER=rust-lld" >> "$GITHUB_ENV" - uses: Swatinem/rust-cache@v2 with: key: ${{ matrix.target }} - - name: Build berth-remote - run: cargo build --release --locked --target ${{ matrix.target }} -p berth-remote + - name: Build berth + run: cargo build --release --locked --target ${{ matrix.target }} -p berth - name: Pack run: | mkdir dist - program=berth-remote - [ "$RUNNER_OS" = Windows ] && program=berth-remote.exe + program=berth + [ "$RUNNER_OS" = Windows ] && program=berth.exe cp "target/${{ matrix.target }}/release/$program" LICENSE-MIT LICENSE-APACHE dist/ case "${{ matrix.asset }}" in *.zip) (cd dist && 7z a -tzip -bso0 "../${{ matrix.asset }}" "$program" LICENSE-MIT LICENSE-APACHE) ;; @@ -137,21 +89,39 @@ jobs: else shasum -a 256 "${{ matrix.asset }}" > "${{ matrix.asset }}.sha256" fi - - name: Check the version + - name: Check the versions + # berth, and on Linux the berthd and box it carries, all say the same. run: | want=${BERTH_BUILD_VERSION:-$(sed -n '/^\[workspace.package\]/,/^\[/s/^version = "\(.*\)"/\1/p' Cargo.toml)} - said=$(dist/berth-remote --version) - echo "berth-remote: $said" - [ "$said" = "berth-remote $want" ] || { echo "::error::berth-remote says $said, not $want"; exit 1; } + programs=dist/berth + if [ "$RUNNER_OS" = Linux ]; then + cp target/host/x86_64-unknown-linux-musl/release/berthd target/host/x86_64-unknown-linux-musl/release/box dist/ + [ "${{ matrix.target }}" = x86_64-unknown-linux-musl ] && programs="$programs dist/berthd dist/box" + fi + for program in $programs; do + said=$("$program" --version) + echo "$program: $said" + case "$said" in + "${program##*/} $want" | "${program##*/} $want "*) ;; + *) echo "::error::$program says $said, not $want"; exit 1 ;; + esac + done - uses: actions/upload-artifact@v4 with: - name: berth-remote-${{ matrix.target }} + name: berth-${{ matrix.target }} path: | ${{ matrix.asset }} ${{ matrix.asset }}.sha256 + - uses: actions/upload-artifact@v4 + if: matrix.target == 'x86_64-unknown-linux-musl' + with: + name: host-programs-x86_64-linux + path: | + dist/berthd + dist/box release: if: startsWith(github.ref, 'refs/tags/v') - needs: [binary, remote] + needs: [binary] runs-on: ubuntu-latest permissions: contents: write @@ -159,10 +129,7 @@ jobs: - uses: actions/checkout@v7 - uses: actions/download-artifact@v4 with: - name: berth-x86_64-linux - - uses: actions/download-artifact@v4 - with: - pattern: berth-remote-* + pattern: berth-* merge-multiple: true - name: Publish the release env: @@ -176,9 +143,8 @@ jobs: # A release made on GitHub's page exists already, and only lacks the files. gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1 \ || gh release create "$GITHUB_REF_NAME" --verify-tag --generate-notes $prerelease - gh release upload "$GITHUB_REF_NAME" --clobber berth-x86_64-linux.tar.gz berth-x86_64-linux.tar.gz.sha256 \ - berth-remote-*.zip berth-remote-*.zip.sha256 berth-remote-*.tar.gz berth-remote-*.tar.gz.sha256 \ - install.sh install-remote.sh install.ps1 VERSION + gh release upload "$GITHUB_REF_NAME" --clobber berth-*.tar.gz berth-*.tar.gz.sha256 \ + berth-*.zip berth-*.zip.sha256 install.sh install.ps1 VERSION image: runs-on: ubuntu-latest permissions: diff --git a/AGENTS.md b/AGENTS.md index 84b651e..bbeaf04 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,14 +6,13 @@ berth sets up and looks after agent workstations. These are Ubuntu machines with | Path | What it is | | --- | --- | -| `crates/berth/` | The `berth` program: terminal UI, commands and `berth serve` (`crates/berth/src/serve/`). In `serve/`, `actions.rs` has the actions of hosts and of the installation, `keys.rs` the key ring's routes, `provisioners.rs` and `resources.rs` those of provisioners and resources | +| `crates/berth/` | The `berth` program, for Linux, macOS and Windows. `main.rs` opens the screens, the same on every system. On Linux, `src/local/` adds the commands and `berth serve` (`src/local/serve/`), behind one `#[cfg(target_os = "linux")]`, and `client_only.rs` stands in for it elsewhere. In `serve/`, `here.rs` is the server in berth's own process that the screens and commands use when no other is set, `actions.rs` has the actions of hosts and of the installation, `keys.rs` the key ring's routes, `provisioners.rs` and `resources.rs` those of provisioners and resources | | `crates/berth-api/` | Types and the operations table shared by every program (`ops.rs` names each operation, its HTTP route and its role) | | `crates/berth-core/` | Hosts, profiles, links to hosts, registries and secrets, and plugins. The store is in `store/`. `kept.rs` and `plugin_state.rs` write files from it, and `import.rs` takes in the files of older versions. `kept_profile.rs` is the profile a host keeps of itself and `berth adopt`. `runner.rs` runs every action as a job. `keys/` is the key ring and how berth logs in to hosts. `host_type.rs` says what a host of each type can do. `provisioner.rs` and `resource.rs` are the provisioners of plugins and what they made | -| `crates/berth-tui/` | The parts of the UI that `berth` and `berth-remote` share | +| `crates/berth-tui/` | The parts of the screens with no terminal in them | | `crates/berth-pty/` | Terminals for sessions | | `crates/berthd/`, `crates/box/` | The controller on each host and the agent's own tool there | -| `crates/berth-page/` | The screens of `berth-remote` for a `berth serve` elsewhere. `device.rs` is what the program gives them, and `portal.rs` the server's portal over it | -| `crates/berth-remote/` | `berth-remote`, those screens in a terminal on Linux, macOS and Windows, for a `berth serve` on another machine | +| `crates/berth-page/` | berth's screens in a terminal. They do everything through the API of a server: one elsewhere, a `berth serve` on its socket, or the one in the process. `net.rs` reaches it, `portal.rs` is its portal, `settings.rs` keeps the server and its token, and `device.rs` is what the program starts them with | | `crates/vendor/` | The vendored `tui-input` crate | | `provision/` | The installer side of the provisioning source: the role in `ansible/`, first-boot provisioning in `bootstrap/`, the builder of seeds and releases in `bin/devbox.py` and the example profile in `config/`. berth names these paths in `layout` in `crates/berth-core/src/paths.rs` | | `plugins/` | The plugins that come with berth, each an npm-format package with a `guide.md`. With `provision/` they make the provisioning source, which berth carries and unpacks with the same layout | @@ -47,12 +46,14 @@ Use cargo for everything Rust. These are what CI runs: ```bash cargo test --locked -cargo fmt --check -p berth-api -p berth-pty -p berth-core -p berth-tui -p berth -p berthd -p box -p berth-page -p berth-remote +cargo fmt --check -p berth-api -p berth-pty -p berth-core -p berth-tui -p berth -p berthd -p box -p berth-page cargo clippy --locked --all-targets -- -D warnings python3 -m unittest discover -s tests -v vale --minAlertLevel=warning README.md docs/content/docs plugins/*/guide.md ``` +On macOS and Windows berth is the client alone. Check that it still builds there with `cargo check -p berth --target x86_64-pc-windows-msvc` or `--target aarch64-apple-darwin`; the release builds it on those systems. + Development and test builds embed quick builds of berthd and box (the `host-dev` profile). Only `--release` embeds the release builds. The Python tests skip their YAML checks without PyYAML, so install `provision/requirements.txt` in a virtual environment to run them all. ### In containers @@ -97,12 +98,12 @@ Give a new thing a host, the installation, a provisioner or a resource can do an | Subject | Where its actions are | | --- | --- | -| A host | `HOST` in `crates/berth/src/serve/actions.rs`, besides the actions its controller lists | +| A host | `HOST` in `crates/berth/src/local/serve/actions.rs`, besides the actions its controller lists | | The installation | `INSTALLATION` in the same file | | A provisioner | `provisioner::actions` in `crates/berth-core/src/provisioner.rs`: its plugin's actions and berth's own | | A resource | `resource::actions` in `crates/berth-core/src/resource.rs`: those of its kind and its plugin's | -An action that changes something runs as a job through `runner.rs`. +An action that changes something runs as a job through `runner.rs`. The screens do everything through the API. What works only with the server's own machine, such as writing a USB drive, is an action that is available to a caller there alone (`Seen::local`: the socket or the process), and says why not to one over the network. ## Versions and releases diff --git a/Cargo.lock b/Cargo.lock index 0ff3ad7..a4983b0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -249,14 +249,6 @@ dependencies = [ "libc", ] -[[package]] -name = "berth-remote" -version = "0.5.2" -dependencies = [ - "berth-api", - "berth-page", -] - [[package]] name = "berth-tui" version = "0.5.2" diff --git a/Cargo.toml b/Cargo.toml index daaeaca..1fd468f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,9 +1,9 @@ [workspace] resolver = "3" -members = ["crates/berth-api", "crates/berth-pty", "crates/berth-core", "crates/berth-tui", "crates/berth", "crates/berthd", "crates/box", "crates/berth-page", "crates/berth-remote"] +members = ["crates/berth-api", "crates/berth-pty", "crates/berth-core", "crates/berth-tui", "crates/berth", "crates/berthd", "crates/box", "crates/berth-page"] # The vendored crate is a member because it lives inside; it is left out of what # is built, tested and linted by default. -default-members = ["crates/berth-api", "crates/berth-pty", "crates/berth-core", "crates/berth-tui", "crates/berth", "crates/berthd", "crates/box", "crates/berth-page", "crates/berth-remote"] +default-members = ["crates/berth-api", "crates/berth-pty", "crates/berth-core", "crates/berth-tui", "crates/berth", "crates/berthd", "crates/box", "crates/berth-page"] [workspace.package] version = "0.5.2" diff --git a/ci/checks.sh b/ci/checks.sh index 61fff7f..bea86ab 100755 --- a/ci/checks.sh +++ b/ci/checks.sh @@ -4,7 +4,7 @@ set -euo pipefail cd /src -crates=(-p berth-api -p berth-pty -p berth-core -p berth-tui -p berth -p berthd -p box -p berth-page -p berth-remote) +crates=(-p berth-api -p berth-pty -p berth-core -p berth-tui -p berth -p berthd -p box -p berth-page) # Each runs as the condition of an if, where set -e does not stop it: the # steps are joined with && instead. @@ -12,7 +12,7 @@ rust-tests() { cargo test --locked; } python-tests() { python3 -m unittest discover -s tests -v; } shell-syntax() { local script bad=0 - for script in install.sh install-remote.sh provision/bin/*.sh provision/bootstrap/*.sh container/*.sh ci/*.sh \ + for script in install.sh provision/bin/*.sh provision/bootstrap/*.sh container/*.sh ci/*.sh \ provision/ansible/roles/devbox/files/*.sh provision/ansible/roles/devbox/files/tasks/*.sh plugins/*/files/*.sh \ recipes/*/*.sh; do bash -n "$script" || bad=1 diff --git a/crates/berth-remote/Cargo.toml b/crates/berth-remote/Cargo.toml deleted file mode 100644 index 8c77bbb..0000000 --- a/crates/berth-remote/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "berth-remote" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -description = "The screens of a berth serve in a terminal: the hosts of a berth serve elsewhere, on Linux, macOS or Windows" - -[[bin]] -name = "berth-remote" -path = "src/main.rs" - -[dependencies] -berth-api = { workspace = true, features = ["client"] } -berth-page.workspace = true diff --git a/crates/berth-remote/README.md b/crates/berth-remote/README.md deleted file mode 100644 index cda5862..0000000 --- a/crates/berth-remote/README.md +++ /dev/null @@ -1,66 +0,0 @@ -# berth-remote - -berth-remote shows the hosts of a `berth serve` on another machine, in a terminal. It runs on Windows, macOS and Linux. - -It is only a client. Setting up hosts, Ansible and SSH stay on the server. - -## Install - -On Windows, in PowerShell: - -```powershell -irm https://raw.githubusercontent.com/helightdev/berth/main/install.ps1 | iex -``` - -On macOS or Linux: - -```bash -curl -fsSL https://raw.githubusercontent.com/helightdev/berth/main/install-remote.sh | sh -``` - -Each script checks the download against its SHA-256. It installs to `%LOCALAPPDATA%\Programs\berth-remote` on Windows and to `~/.local/bin` elsewhere. `BERTH_INSTALL_DIR` and `BERTH_VERSION` change where and which release. - -## Use - -Start the server on an address of your network: - -```bash -berth serve --listen 0.0.0.0:7878 --expose -``` - -Then on your own machine: - -```bash -berth-remote --server http://192.0.2.10:7878 -``` - -berth-remote asks for the token and keeps it for the next run. The token is in `serve.token` in the server's data directory. A setup key from `berth setup-key` works too. - -| Option or variable | What it does | -| --- | --- | -| `--server ADDRESS`, `BERTH_SERVER` | The server. An address without a scheme is https, or http for `localhost` | -| `BERTH_TOKEN` | The token, so that it is not asked for | -| `BERTH_SETUP_KEY` | A setup key, which collects the token once | -| `--forget` | Remove the kept server and token, and keep nothing from this run | -| `BERTH_REMOTE_FILE` | The plugin package to send, on a system without a file dialog | -| `--version` | Say the version | - -A token or a setup key never goes on the command line, where other users of the machine could read it, and berth-remote does not pass either on to the programs it starts. - -The settings are in `settings.json` in `%LOCALAPPDATA%\berth-remote` on Windows, `~/Library/Application Support/berth-remote` on macOS and `~/.config/berth-remote` elsewhere (`$XDG_CONFIG_HOME` where it is set). On macOS and Linux the folder is mode 0700 and the file 0600. On Windows the file takes the access list of your profile, which lets in you, SYSTEM and the administrators. - -A server over https needs a certificate that the system or the Mozilla roots trust. There is no way to turn the check off. Only `http` and `https` links are opened, in the system's browser. - -Ctrl+Q quits. - -## How it is built - -The screens are in `crates/berth-page`. This crate gives them a terminal: `device.rs` has the clipboard, links, the file dialog and the kept settings, `net.rs` and `socket.rs` the HTTP requests and the portal's WebSocket over TCP or TLS. - -On the system it is for: - -```bash -cargo build --release --locked -p berth-remote -``` - -On Windows, that needs Rust from rustup and the Visual Studio build tools. Use Windows Terminal or the console of Windows 10 or later, which draw its colours. diff --git a/crates/berth-remote/src/lib.rs b/crates/berth-remote/src/lib.rs deleted file mode 100644 index cde3e09..0000000 --- a/crates/berth-remote/src/lib.rs +++ /dev/null @@ -1,3 +0,0 @@ -//! berth-remote: the screens of berth-page, for a berth serve elsewhere. - -pub mod options; diff --git a/crates/berth-remote/src/main.rs b/crates/berth-remote/src/main.rs deleted file mode 100644 index 03aee00..0000000 --- a/crates/berth-remote/src/main.rs +++ /dev/null @@ -1,32 +0,0 @@ -//! berth-remote: the hosts of a berth serve, in this terminal. - -use berth_page::settings; -use berth_remote::options::{self, Parsed}; - -fn main() { - let options = match options::parse(std::env::args().skip(1), |name| std::env::var(name).ok()) { - Ok(Parsed::Run(options)) => options, - Ok(Parsed::Version) => { - println!("berth-remote {}", berth_api::VERSION); - return; - } - Ok(Parsed::Help) => { - println!("{}", options::USAGE); - return; - } - Err(error) => { - eprintln!("berth-remote: {error}\n\n{}", options::USAGE); - std::process::exit(2); - } - }; - let var = |name: &str| std::env::var(name).ok(); - let settings = match options.forget { - true => settings::Settings::new(None), - false => settings::Settings::new(settings::folder(var)), - }; - berth_page::device::install(options.linked, settings); - if let Err(error) = berth_page::screens::run(None) { - eprintln!("berth-remote: {error}"); - std::process::exit(1); - } -} diff --git a/crates/berth-remote/src/options.rs b/crates/berth-remote/src/options.rs deleted file mode 100644 index 6fbff85..0000000 --- a/crates/berth-remote/src/options.rs +++ /dev/null @@ -1,165 +0,0 @@ -//! What berth-remote is started with: its options, and from the environment -//! a token or a setup key, which never go on a command line. - -use berth_page::device::Linked; - -pub const USAGE: &str = "\ -berth-remote: the hosts of a berth serve, in this terminal - -Usage: berth-remote [--server ADDRESS] [--forget] - - --server ADDRESS the berth serve to use, such as https://berth.example - or http://192.0.2.10:7878 (also BERTH_SERVER) - --forget remove the kept server and token, and keep nothing - from this run - --version say the version - -The token comes from BERTH_TOKEN, or is asked for. A setup key from -`berth setup-key` comes from BERTH_SETUP_KEY. Neither goes on the command -line, where other users of the machine could read it. - -A plugin package is chosen in the file dialog of the system: on Linux that -of zenity or kdialog. Without one, BERTH_REMOTE_FILE names the file. - -The server and the token are kept for this user: in -%LOCALAPPDATA%\\berth-remote on Windows, ~/Library/Application Support/berth-remote -on macOS and ~/.config/berth-remote elsewhere ($XDG_CONFIG_HOME where it is set). - -Ctrl+Q quits."; - -pub struct Options { - pub linked: Linked, - /// Remove what was kept, and keep nothing. - pub forget: bool, -} - -pub enum Parsed { - Run(Options), - Version, - Help, -} - -/// Read the arguments, and the variables `var` gives. An argument that is -/// not an option is not repeated in the error, since it could be a token. -pub fn parse( - args: impl IntoIterator, - var: impl Fn(&str) -> Option, -) -> Result { - let variable = |name: &str| { - var(name) - .map(|value| value.trim().to_owned()) - .filter(|value| !value.is_empty()) - }; - let mut options = Options { - linked: Linked { - server: variable("BERTH_SERVER"), - token: variable("BERTH_TOKEN"), - setup_key: variable("BERTH_SETUP_KEY"), - }, - forget: false, - }; - let mut args = args.into_iter(); - while let Some(arg) = args.next() { - let (name, value) = match arg.split_once('=') { - Some((name, value)) if name.starts_with("--") => (name, Some(value.to_owned())), - _ => (arg.as_str(), None), - }; - match name { - "--server" | "-s" => { - let server = value - .or_else(|| args.next()) - .filter(|server| !server.trim().is_empty()) - .ok_or("--server needs an address")?; - options.linked.server = Some(server.trim().to_owned()); - } - "--forget" if value.is_none() => options.forget = true, - "--version" | "-V" if value.is_none() => return Ok(Parsed::Version), - "--help" | "-h" if value.is_none() => return Ok(Parsed::Help), - "--forget" | "--version" | "--help" => return Err(format!("{name} takes no value")), - other if other.starts_with('-') => { - return Err(format!("{other} is no option of berth-remote")); - } - _ => { - return Err( - "berth-remote takes no arguments but its options: a token comes from BERTH_TOKEN" - .into(), - ); - } - } - } - Ok(Parsed::Run(options)) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn run(args: &[&str], vars: &[(&str, &str)]) -> Result { - let vars: Vec<(String, String)> = vars - .iter() - .map(|(name, value)| (name.to_string(), value.to_string())) - .collect(); - let parsed = parse(args.iter().map(|arg| arg.to_string()), |name| { - vars.iter() - .find(|(key, _)| key == name) - .map(|(_, value)| value.clone()) - })?; - match parsed { - Parsed::Run(options) => Ok(options), - _ => Err("not a run".into()), - } - } - - #[test] - fn the_server_comes_from_an_option_or_the_environment() { - let options = run(&[], &[("BERTH_SERVER", " https://studio.example ")]).unwrap(); - assert_eq!( - options.linked.server.as_deref(), - Some("https://studio.example") - ); - assert!(!options.forget); - let options = run( - &["--server", "http://192.0.2.10:7878"], - &[("BERTH_SERVER", "https://studio.example")], - ) - .unwrap(); - assert_eq!( - options.linked.server.as_deref(), - Some("http://192.0.2.10:7878") - ); - let options = run(&["--server=https://dock.example", "--forget"], &[]).unwrap(); - assert_eq!( - options.linked.server.as_deref(), - Some("https://dock.example") - ); - assert!(options.forget); - assert!(run(&["--server"], &[]).is_err()); - assert!(run(&["--server="], &[]).is_err()); - } - - #[test] - fn secrets_come_from_the_environment_only() { - let options = run( - &[], - &[("BERTH_TOKEN", "the-token\n"), ("BERTH_SETUP_KEY", "")], - ) - .unwrap(); - assert_eq!(options.linked.token.as_deref(), Some("the-token")); - assert_eq!(options.linked.setup_key, None); - // A token given as an argument is refused, and not repeated. - let error = run(&["s3cr3t-token"], &[]).err().unwrap(); - assert!(!error.contains("s3cr3t"), "{error}"); - let error = run(&["--token=s3cr3t-token"], &[]).err().unwrap(); - assert!(!error.contains("s3cr3t"), "{error}"); - assert!(error.contains("--token"), "{error}"); - } - - #[test] - fn version_and_help() { - let parsed = |args: &[&str]| parse(args.iter().map(|arg| arg.to_string()), |_| None); - assert!(matches!(parsed(&["--version"]), Ok(Parsed::Version))); - assert!(matches!(parsed(&["-V"]), Ok(Parsed::Version))); - assert!(matches!(parsed(&["--help"]), Ok(Parsed::Help))); - assert!(parsed(&["--forget=yes"]).is_err()); - } -} diff --git a/crates/berth-tui/Cargo.toml b/crates/berth-tui/Cargo.toml index 7aed47f..041985e 100644 --- a/crates/berth-tui/Cargo.toml +++ b/crates/berth-tui/Cargo.toml @@ -4,7 +4,7 @@ version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true -description = "The screens of a host with no terminal in them, for berth and berth-remote" +description = "The parts of berth's screens with no terminal in them" [dependencies] berth-api.workspace = true diff --git a/crates/berth-tui/src/lib.rs b/crates/berth-tui/src/lib.rs index 10a9007..bfdf612 100644 --- a/crates/berth-tui/src/lib.rs +++ b/crates/berth-tui/src/lib.rs @@ -1,6 +1,6 @@ -//! The screens of a host with no terminal in them: they draw into ratatui -//! frames and take keys of their own type, which berth and berth-remote turn -//! a terminal's events into. +//! The parts of berth's screens with no terminal in them: they draw into +//! ratatui frames and take keys of their own type, which berth-page turns a +//! terminal's events into. pub mod berth_key; pub mod event; diff --git a/crates/berth-tui/src/machine.rs b/crates/berth-tui/src/machine.rs index 05985bc..e01b7f4 100644 --- a/crates/berth-tui/src/machine.rs +++ b/crates/berth-tui/src/machine.rs @@ -4,7 +4,7 @@ //! rest of its arguments on the Settings tab, and creating it, or the machine //! once there is one, on the Run tab. The machine is the host's resource of //! the machine kind, and starting, stopping and deleting it are its actions. -//! berth and berth-remote ask for these and run the jobs each their own way. +//! The screens ask the server for these, which runs the jobs. use crate::fields::{Kind, Step}; use crate::setup::{Entry, Problem, Row, value_line}; diff --git a/crates/berth-tui/src/page.rs b/crates/berth-tui/src/page.rs index f3f58ca..b68590f 100644 --- a/crates/berth-tui/src/page.rs +++ b/crates/berth-tui/src/page.rs @@ -1,8 +1,8 @@ //! The page of a subject: lines that say how it is, what can be done to it //! in groups, and the dialogs before an action runs, its question and then //! its arguments one after another. A host's page is one. A page of another -//! subject is its state and its actions given to the same functions; the -//! berth and berth-remote draw the rows each their own way. +//! subject is its state and its actions given to the same functions, which +//! the screens draw the rows of. use berth_api::{Action, Argument}; use std::collections::BTreeMap; diff --git a/crates/berth-tui/src/plugins.rs b/crates/berth-tui/src/plugins.rs index aab81e0..21ff3e1 100644 --- a/crates/berth-tui/src/plugins.rs +++ b/crates/berth-tui/src/plugins.rs @@ -1,8 +1,7 @@ //! The Plugins tab of the home screen: the plugins there are with their //! features, installing, updating and removing one, and bringing the hosts -//! that are behind up to date afterwards. berth shows those of this -//! machine or of its berth server, berth-remote those of the server it is -//! signed in to. What the tab asks for, each of them does its own way. +//! that are behind up to date afterwards: those of the server the screens +//! use. What the tab asks for goes to the server. use crate::event::{self, Code, Key}; use crate::theme; @@ -19,7 +18,7 @@ pub enum Place<'a> { Here, /// The server's at this address, for berth in a terminal. Server(&'a str), - /// The server's, for berth-remote. + /// The server's, for the screens. Page, } diff --git a/crates/berth-tui/src/provisioners.rs b/crates/berth-tui/src/provisioners.rs index f5a9d0c..9c0375c 100644 --- a/crates/berth-tui/src/provisioners.rs +++ b/crates/berth-tui/src/provisioners.rs @@ -2,9 +2,8 @@ //! with whether it can be used here, and the page of one, built with //! [`crate::page`]: how it is now, what it says of itself, what it holds by //! kind, and its actions. A resource berth made with it has a page of its own -//! with its state, its actions and its log. berth shows those of this machine or of its -//! berth server, berth-remote those of the server it is signed in to. What -//! the tab asks for, each of them does its own way, and tells the tab what +//! with its state, its actions and its log: those of the server the screens +//! use. What the tab asks for goes to the server, which tells the tab what //! came back. use crate::event::{Code, Event, Key}; diff --git a/crates/berth-tui/src/setup.rs b/crates/berth-tui/src/setup.rs index 5635437..be442f1 100644 --- a/crates/berth-tui/src/setup.rs +++ b/crates/berth-tui/src/setup.rs @@ -1,6 +1,6 @@ //! The set-up pages of a host: what its profile holds, the rows each page //! shows of it, and what changing a row does to it. Nothing here reads a file -//! or runs a command, so berth and berth-remote share it. +//! or runs a command: the server keeps the profile and does what it says. use crate::fields::{Action, Field, Group, Kind, Step}; use crate::theme; diff --git a/crates/berth/Cargo.toml b/crates/berth/Cargo.toml index 0bef1cb..cb63d16 100644 --- a/crates/berth/Cargo.toml +++ b/crates/berth/Cargo.toml @@ -5,26 +5,31 @@ edition.workspace = true rust-version.workspace = true license.workspace = true +# The screens and the client of a berth serve, on every system. [dependencies] -berth-core.workspace = true berth-api = { workspace = true, features = ["client"] } +berth-page.workspace = true berth-tui.workspace = true +tokio.workspace = true +serde_json = "1" +tempfile = "3" +crossterm = "=0.29.0" + +# The installation, berth serve and the commands, on Linux, where hosts are +# set up from. +[target.'cfg(target_os = "linux")'.dependencies] +berth-core.workspace = true # For its API document, which berth serve's includes. berthd = { path = "../berthd" } -tokio.workspace = true futures-util.workspace = true serde.workspace = true axum.workspace = true utoipa.workspace = true utoipa-axum.workspace = true -crossterm = "=0.29.0" -serde_json = "1" -tempfile = "3" libc = "0.2" jsonwebtoken = { version = "11", default-features = false, features = ["rust_crypto"] } -berth-page.workspace = true -[dev-dependencies] +[target.'cfg(target_os = "linux")'.dev-dependencies] # Signs the access tokens of the tests. ring = "0.17" # Draws the screens of the tests. diff --git a/crates/berth/src/client_only.rs b/crates/berth/src/client_only.rs new file mode 100644 index 0000000..ff8eb23 --- /dev/null +++ b/crates/berth/src/client_only.rs @@ -0,0 +1,30 @@ +//! berth on a system other than Linux, where it is a client of a berth +//! serve elsewhere: the screens, `berth connect` and `berth update`. + +use crate::Result; + +/// Only berth on Linux answers for ssh. +pub fn askpass(_: &[&str]) -> Result { + Ok(false) +} + +/// No server runs here: the screens ask for one and its token. +pub fn server() -> Result> { + Ok(None) +} + +/// The commands that need an installation are berth's on Linux, beside its +/// server. +pub fn command(args: &[&str]) -> Result<()> { + match args { + ["help" | "--help" | "-h", ..] => { + println!("{}", crate::USAGE); + Ok(()) + } + [verb, ..] => Err(format!( + "berth {verb} runs on Linux, where berth serve and its hosts are. On this system berth is a client: berth opens the screens of a server, which berth connect URL or BERTH_SERVER names" + ) + .into()), + [] => Ok(()), + } +} diff --git a/crates/berth/src/connect.rs b/crates/berth/src/connect.rs new file mode 100644 index 0000000..4b8b297 --- /dev/null +++ b/crates/berth/src/connect.rs @@ -0,0 +1,121 @@ +//! `berth connect URL`: use the berth server at URL, with the token a setup +//! key collects. The key comes on standard input, so it is in no argv, and +//! the server and token are kept as berth's settings. + +use crate::Result; +use berth_page::net; +use berth_page::settings::{self, Settings}; +use serde_json::Value; +use std::io::{IsTerminal, Read}; + +/// `berth connect URL`, keeping the server in the settings of this user. +pub fn command(url: &str) -> Result<()> { + if !(url.starts_with("https://") || url.starts_with("http://")) { + return Err(format!( + "{url} is no address of a berth server: https://HOST or http://HOST:PORT" + ) + .into()); + } + let key = read_secret("Setup key")?; + let settings = Settings::new(settings::folder(|name| std::env::var(name).ok())); + let (url, version) = connect_with(&settings, url, key.trim())?; + println!("This berth now uses the berth server at {url}, berth {version}"); + if std::env::var_os("BERTH_SERVER").is_some() { + eprintln!("BERTH_SERVER is set in this shell and is used before the setting"); + } + Ok(()) +} + +/// A secret from the terminal without showing it, or all of standard input. +fn read_secret(prompt: &str) -> Result { + let mut value = String::new(); + if std::io::stdin().is_terminal() { + use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers}; + eprint!("{prompt}: "); + crossterm::terminal::enable_raw_mode()?; + let read = (|| -> std::io::Result { + loop { + if let Event::Key(key) = event::read()? + && key.kind != KeyEventKind::Release + { + match key.code { + KeyCode::Enter => return Ok(true), + KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => { + return Ok(false); + } + KeyCode::Char(ch) => value.push(ch), + KeyCode::Backspace => { + value.pop(); + } + _ => {} + } + } + } + })(); + let _ = crossterm::terminal::disable_raw_mode(); + eprintln!(); + if !read? { + return Err("Nothing entered".into()); + } + } else { + std::io::stdin().read_to_string(&mut value)?; + } + let value = value.trim_end_matches(['\n', '\r']).to_owned(); + match value.is_empty() { + true => Err("Nothing entered".into()), + false => Ok(value), + } +} + +/// [`command`] with the key in hand: the server's address and version. +/// Nothing is kept unless all of it works. +pub fn connect_with(settings: &Settings, url: &str, key: &str) -> Result<(String, String)> { + let url = url.trim().trim_end_matches('/').to_owned(); + let key = key.to_owned(); + let ask = |method: &'static str| { + let (url, key) = (url.clone(), key.clone()); + async move { + let (status, body) = net::http(method, &url, "/v1/setup-key", &key).await?; + let said: Value = serde_json::from_str(&body).unwrap_or(Value::Null); + match status { + 200 => Ok(said), + 401 => Err( + "The server did not take the setup key: it is wrong, used up or expired. Make a new one where the server runs: berth setup-key".to_owned(), + ), + 404 | 405 => Err("The server knows no setup keys: it is an older berth".to_owned()), + status => Err(match said["error"]["message"].as_str() { + Some(message) => format!("HTTP {status}: {message}"), + None => format!("HTTP {status}"), + }), + } + } + }; + let (version, token) = net::runtime().block_on(async { + let checked = ask("GET").await?; + let claimed = ask("POST").await?; + let token = claimed["token"].as_str().unwrap_or("").to_owned(); + if token.is_empty() { + return Err("The server sent no token".to_owned()); + } + // Kept only once the token is seen to open the server. + let target = net::target(&url, berth_api::ops::PORTAL)?; + let stream = net::connect(&target).await?; + let socket = + berth_api::client::websocket_at(stream, &target.authority, &target.path, &token) + .await + .map_err(|error| net::describe(&error))?; + berth_api::portal::Portal::over(socket) + .call("access", None, Value::Null, None) + .await + .map_err(|error| net::describe(&error))?; + let version = checked["version"].as_str().unwrap_or("").to_owned(); + Ok::<_, String>((version, token)) + })?; + settings.set(&[(settings::SERVER, &url), (settings::TOKEN, &token)])?; + if let Err(error) = net::runtime().block_on(ask("DELETE")) { + eprintln!( + "The setup key could not be ended ({error}). It stops by itself within a day, or with berth setup-key --remove where the server runs." + ); + } + Ok((url, version)) +} diff --git a/crates/berth/src/commands.rs b/crates/berth/src/local/commands.rs similarity index 95% rename from crates/berth/src/commands.rs rename to crates/berth/src/local/commands.rs index daa0ce6..85f9928 100644 --- a/crates/berth/src/commands.rs +++ b/crates/berth/src/local/commands.rs @@ -909,7 +909,7 @@ pub fn add_host(paths: &Paths, name: &str, address: &str, args: &[&str]) -> Resu if !contact { return Ok(()); } - crate::key_command::trust(paths, name, &[]).map_err(|error| -> Box { + crate::local::key_command::trust(paths, name, &[]).map_err(|error| -> Box { format!("{name} is saved, but logging in to it did not work yet: {error}. Try again with: berth key trust {name}").into() })?; offer_found_type(paths, name, host_type) @@ -1045,10 +1045,10 @@ pub fn apply(paths: &Paths, name: &str) -> Result<()> { sudo_password: host.sudo_password(paths)?, ..api::Act::default() }; - let (server, here) = crate::serve::here::server(paths)?; + let (server, here) = crate::local::serve::here::server(paths)?; let acted = act_on(&server, Some(name), "apply", &act)?; let code = follow_acted(&server, None, acted, &mut std::io::stdout())?; - crate::serve::here::finish(here); + crate::local::serve::here::finish(here); std::process::exit(code); } @@ -1073,10 +1073,10 @@ pub fn installer(paths: &Paths, name: &str, device: Option<&str>) -> Result<()> arguments, ..api::Act::default() }; - let (server, here) = crate::serve::here::server(paths)?; + let (server, here) = crate::local::serve::here::server(paths)?; let acted = act_on(&server, Some(name), "installer", &act)?; let code = follow_acted(&server, None, acted, &mut std::io::stdout())?; - crate::serve::here::finish(here); + crate::local::serve::here::finish(here); std::process::exit(code); } @@ -1342,7 +1342,7 @@ pub fn update_plugins(paths: &Paths, args: &[&str]) -> Result<()> { /// `berth seed HOST` with a berth server: the server renders the seed, and it /// is written here. pub fn seed(paths: &Paths, name: &str) -> Result<()> { - let (server, here) = crate::serve::here::server(paths)?; + let (server, here) = crate::local::serve::here::server(paths)?; let seed = act_on(&server, Some(name), "seed", &api::Act::default())? .result .unwrap_or_default(); @@ -1463,7 +1463,8 @@ pub fn set_profile(paths: &Paths, name: &str, file: &str) -> Result<()> { } file => std::fs::read(file).map_err(|error| format!("{file}: {error}"))?, }; - crate::profile::parse_config(&data).map_err(|error| format!("Not a profile: {error}"))?; + crate::local::profile::parse_config(&data) + .map_err(|error| format!("Not a profile: {error}"))?; let mut profile: Value = serde_json::from_slice(&data)?; let place = Place::resolve(paths, name)?; // A profile of an older layout is kept in the one of now. @@ -1761,80 +1762,6 @@ pub fn provisioners(paths: &Paths) -> Result<()> { Ok(()) } -/// `berth connect URL`: use the berth server at URL, with the token a setup -/// key collects. The key comes on standard input, so it is in no argv. -pub fn connect(paths: &Paths, url: &str) -> Result<()> { - if !(url.starts_with("https://") || url.starts_with("http://")) { - return Err(format!( - "{url} is no address of a berth server: https://HOST or http://HOST:PORT" - ) - .into()); - } - let key = registry::read_secret("Setup key")?; - connect_with(paths, url, key.trim()) -} - -/// [`connect`] with the key in hand. Nothing is saved unless all of it works. -pub fn connect_with(paths: &Paths, url: &str, key: &str) -> Result<()> { - use berth_core::server::{Server, http_as}; - let url = url.trim().trim_end_matches('/').to_owned(); - let key = key.to_owned(); - let at = format!("{url}/v1/setup-key"); - let ask = |method: &'static str| { - let (at, key) = (at.clone(), key.clone()); - async move { - let (status, body) = http_as(method, &at, Some(&key), None, vec![]).await?; - match status { - 200 => Ok(serde_json::from_slice::(&body)?), - 401 => Err( - "The server did not take the setup key: it is wrong, used up or expired. Make a new one where the server runs: berth setup-key".into(), - ), - 404 | 405 => Err("The server knows no setup keys: it is an older berth".into()), - _ => Err(answer_error(status, &body)), - } - } - }; - let (version, token) = link::runtime()?.block_on(async { - let checked: api::SetupKey = serde_json::from_value(ask("GET").await?)?; - let claimed: api::SetupClaim = serde_json::from_value(ask("POST").await?)?; - // Saved only once the token is seen to open the server. - Server { - url: url.clone(), - token: Some(claimed.token.clone()), - } - .portal() - .await? - .call("access", None, Value::Null, None) - .await?; - Ok::<_, Box>((checked.version, claimed.token)) - })?; - let before = paths.setting("server"); - paths.set("server", &url)?; - if let Err(error) = paths.set("server_token", &token) { - paths.set("server", before.as_deref().unwrap_or(""))?; - return Err(error); - } - if let Err(error) = link::runtime()?.block_on(ask("DELETE")) { - eprintln!( - "The setup key could not be ended ({error}). It stops by itself within a day, or with berth setup-key --remove where the server runs." - ); - } - println!("This berth now uses the berth server at {url}, berth {version}"); - if std::env::var_os("BERTH_SERVER").is_some() { - eprintln!("BERTH_SERVER is set in this shell and is used before the setting"); - } - Ok(()) -} - -/// What an answer that is not a 200 says. -fn answer_error(status: u16, body: &[u8]) -> Box { - let said: Value = serde_json::from_slice(body).unwrap_or(Value::Null); - match said["error"]["message"].as_str() { - Some(message) => format!("HTTP {status}: {message}").into(), - None => format!("HTTP {status}").into(), - } -} - #[cfg(test)] mod tests { use super::*; @@ -1982,17 +1909,18 @@ mod tests { set_profile(&paths, "studio", file.to_str().unwrap()).unwrap(); let place = Place::own("studio").unwrap(); let kept = place.load(&paths).unwrap().unwrap(); - let config = crate::profile::parse_config(kept.to_string().as_bytes()).unwrap(); - crate::profile::save(&paths, &place, config).unwrap(); + let config = crate::local::profile::parse_config(kept.to_string().as_bytes()).unwrap(); + crate::local::profile::save(&paths, &place, config).unwrap(); let saved = place.load(&paths).unwrap().unwrap(); assert_eq!( saved["ansible_vars"]["devbox_plugin_features"], json!(["codex/cli"]) ); // One of the old layout is still converted. - let old = - crate::profile::parse_config(br#"{"ansible_vars": {"devbox_agent_codex": false}}"#) - .unwrap(); + let old = crate::local::profile::parse_config( + br#"{"ansible_vars": {"devbox_agent_codex": false}}"#, + ) + .unwrap(); assert!( !old["ansible_vars"]["devbox_plugin_features"] .as_array() diff --git a/crates/berth/src/key_command.rs b/crates/berth/src/local/key_command.rs similarity index 95% rename from crates/berth/src/key_command.rs rename to crates/berth/src/local/key_command.rs index 08e7752..0ce11a5 100644 --- a/crates/berth/src/key_command.rs +++ b/crates/berth/src/local/key_command.rs @@ -3,7 +3,7 @@ //! stay there; first contact and host keys are then the server's to do. use crate::Result; -use crate::serve::keys::{KeyInfo, KeyList, listing}; +use crate::local::serve::keys::{KeyInfo, KeyList, listing}; use berth_core::host::Host; use berth_core::keys::{Once, contact, ring}; use berth_core::paths::Paths; @@ -106,8 +106,8 @@ pub fn command(paths: &Paths, args: &[&str]) -> Result<()> { arguments: [("name".to_owned(), name.to_owned())].into(), ..berth_api::Act::default() }; - let acted = crate::commands::act_on(server, None, "rotate-key", &act)?; - let code = crate::commands::follow_server_job(server, acted, out)?; + let acted = crate::local::commands::act_on(server, None, "rotate-key", &act)?; + let code = crate::local::commands::follow_server_job(server, acted, out)?; std::process::exit(code); } None => { @@ -261,9 +261,9 @@ fn trust_served(server: &Server, name: &str, key: Option<&str>, keep: bool) -> R arguments, ..berth_api::Act::default() }; - let acted = crate::commands::act_on(server, Some(name), "trust-key", &act)?; + let acted = crate::local::commands::act_on(server, Some(name), "trust-key", &act)?; let mut said = vec![]; - let code = crate::commands::follow_server_job(server, acted, &mut said)?; + let code = crate::local::commands::follow_server_job(server, acted, &mut said)?; let said = String::from_utf8_lossy(&said).into_owned(); print!("{said}"); Ok((code, said)) @@ -294,7 +294,7 @@ fn host_key(paths: &Paths, name: &str, accept: bool) -> Result<()> { .into(), ..berth_api::Act::default() }; - let acted = crate::commands::act_on(&server, Some(name), "host-key", &act)?; + let acted = crate::local::commands::act_on(&server, Some(name), "host-key", &act)?; let result = acted.result.unwrap_or_default(); result["host_keys"] .as_array() diff --git a/crates/berth/src/local/mod.rs b/crates/berth/src/local/mod.rs new file mode 100644 index 0000000..3e4c622 --- /dev/null +++ b/crates/berth/src/local/mod.rs @@ -0,0 +1,426 @@ +//! What berth does on the machine its installation is on, which is Linux: +//! `berth serve`, the server the screens use when no other is set, and the +//! commands that work with the store, the hosts and the provisioning source. + +pub mod commands; +mod key_command; +mod profile; +mod provisioner_command; +mod resource_command; +pub mod serve; +mod store_command; + +use crate::Result; +use berth_core::{paths, plugins, registry}; +use paths::Paths; +use serde_json::json; +use std::process::Command; + +/// The server of this machine for the screens: a `berth serve` of this +/// user, or one in this process, whose jobs `finish` waits for. +pub fn server() -> Result> { + let (server, here) = serve::here::local(&Paths::locate()?)?; + if let Some(here) = &here { + berth_page::net::serve_here(here.dial()); + } + Ok(Some((server, Box::new(move || serve::here::finish(here))))) +} + +/// ssh runs berth as its askpass helper, the program of SSH_ASKPASS, with +/// the prompt as its one argument and the variable that says where the +/// password is; the answer is all that may go to standard output. Whether +/// this run was one. +pub fn askpass(args: &[&str]) -> Result { + let Ok(source) = std::env::var(berth_core::keys::askpass::SOURCE) else { + return Ok(false); + }; + let prompt = match args { + ["askpass", prompt @ ..] => prompt.join(" "), + [prompt] => (*prompt).to_owned(), + _ => return Ok(false), + }; + let answer = berth_core::keys::askpass::answer(&prompt, &source, None)?; + println!("{answer}"); + Ok(true) +} + +fn show_config(paths: &Paths) -> Result<()> { + // The settings of the file are shown when the store does not open. + let (settings, unopened) = match paths.settings() { + Ok(settings) => (settings, None), + Err(error) => (paths.local_settings()?, Some(error)), + }; + println!( + "Settings {}, and the store", + paths.settings_file().display() + ); + let store = berth_core::store::Installation::of(paths).target.describe(); + match &unopened { + None => println!("Store {store}: settings, hosts, registries and secrets"), + Some(error) => println!("Store {store}, which does not open: {error}"), + } + match berth_core::server::Server::configured(paths) { + Some(server) => println!( + "Hosts on the berth server at {}, with a copy in the store", + server.url + ), + None => println!("Hosts in the store, with their passwords and machines"), + } + println!("Builds {}", paths.build_dir().display()); + match paths.source() { + Ok(source) => println!("Source {}", source.display()), + Err(error) => println!("Source {error}"), + } + println!(); + for (key, help) in paths::SETTINGS { + // What lets someone in is not for a screen. + let value = match settings.get(*key).and_then(|value| value.as_str()) { + Some(_) if paths::is_secret(key) => Some("(set)"), + value => value, + }; + let value = match (&unopened, paths::is_local(key)) { + (Some(_), false) => Some("(in the store, which does not open)"), + _ => value, + }; + println!("{key} = {}\n {help}", value.unwrap_or("(not set)")); + } + Ok(()) +} + +/// `berth config KEY VALUE`: the tailnet settings of a berth server this +/// berth uses are the server's, and change there. +fn change_setting(paths: &Paths, key: &str, value: &str) -> Result<()> { + match berth_core::server::Server::configured(paths) { + Some(server) if berth_core::tailnet::SETTINGS.contains(&key) => { + server.call( + "settings.set", + json!({"key": key}), + Some(json!({"value": value})), + )?; + println!("Changed {key} on the berth server at {}", server.url); + Ok(()) + } + _ => paths.set(key, value), + } +} + +/// Whether a command reads this machine's own plugins: the commands that +/// apply, build or provision with them or list them. +fn loads_plugins(args: &[&str]) -> bool { + const VERBS: &[&str] = &[ + "apply", + "plugins", + "provisioners", + "provisioner", + "provision", + "instance", + "resource", + "deploy", + "seed", + "iso", + "publish", + "host", + ]; + args.first().is_some_and(|verb| VERBS.contains(verb)) +} + +/// Put back the plugins berth's store has and this machine's plugin +/// directory lacks, as on a machine restored from the store, and say so on +/// standard error. +pub(crate) fn restore_plugins(paths: &Paths) { + match berth_core::plugin_state::restore(paths) { + Ok(notices) => notices.iter().for_each(|notice| eprintln!("{notice}")), + Err(error) => eprintln!("berth: the plugins in berth's store were not checked: {error}"), + } +} + +fn succeed(mut command: Command) -> Result<()> { + let status = command.status()?; + if !status.success() { + let program = command.get_program().to_string_lossy().into_owned(); + return Err(format!("{program} failed ({status})").into()); + } + Ok(()) +} + +/// `berth host HOST ...`: the secrets and registries a host is given. +fn host_command(paths: &Paths, host: &str, args: &[&str]) -> Result<()> { + let (place, mut config) = profile::load(paths, host)?; + let list = |value: &serde_json::Value| value.as_array().cloned().unwrap_or_default(); + match *args { + [] => { + for secret in list(&config["secrets"]) { + let place = match (secret["env"].as_str(), secret["file"].as_str()) { + (Some(variable), _) => format!("env {variable}"), + (_, Some(path)) => format!("file {path}"), + _ => String::new(), + }; + println!( + "secret {} {place}", + secret["name"].as_str().unwrap_or("") + ); + } + for name in list(&config["registries"]) { + println!("registry {}", name.as_str().unwrap_or("")); + } + println!("Send them with: berth run {host} secrets"); + return Ok(()); + } + ["secret", name, ref how @ ..] => { + let mut secrets = list(&config["secrets"]); + secrets.retain(|known| known["name"] != name); + match *how { + ["env", variable] => secrets.push(json!({"name": name, "env": variable})), + ["file", path] => secrets.push(json!({"name": name, "file": path})), + ["file", path, mode] => { + secrets.push(json!({"name": name, "file": path, "mode": mode})) + } + ["off"] => {} + _ => { + return Err( + "Usage: berth host HOST secret NAME env VARIABLE | file PATH [MODE] | off" + .into(), + ); + } + } + config["secrets"] = json!(secrets); + } + ["registry", name, switch @ ("on" | "off")] => { + let mut registries = list(&config["registries"]); + registries.retain(|known| known != name); + if switch == "on" { + if !registry::Store::new(paths)? + .registries()? + .contains_key(name) + { + return Err(format!("No registry {name}. See: berth registry").into()); + } + registries.push(json!(name)); + } + config["registries"] = json!(registries); + } + _ => return Err("Usage: berth host HOST [secret NAME ... | registry NAME on|off]".into()), + } + profile::save(paths, &place, config)?; + Ok(()) +} + +/// Run a command of berth that needs this machine's installation. +pub fn command(args: &[&str]) -> Result<()> { + let paths = Paths::locate()?; + if loads_plugins(args) && berth_core::server::Server::configured(&paths).is_none() { + restore_plugins(&paths); + } + // With a server set, the hosts are the server's: fetch them before anything looks. + let local = [ + "config", + "serve", + "--version", + "-V", + "version", + "openapi", + "asyncapi", + "operations", + "update", + "key", + "askpass", + "tailnet-key", + "credentials", + "connect", + "setup-key", + "store", + ]; + if let Some(server) = berth_core::server::Server::configured(&paths) + && !args.first().is_some_and(|verb| local.contains(verb)) + { + server + .mirror(&paths) + .map_err(|error| format!("the berth server at {}: {error}", server.url))?; + } + match args[..] { + ["list"] => { + for (name, address) in paths.hosts() { + println!("{name:<24} {address}"); + } + Ok(()) + } + ["registry", ref rest @ ..] => registry::registry_command(&paths, rest), + ["secret", ref rest @ ..] => registry::secret_command(&paths, rest), + ["image", "push", destination, ref rest @ ..] => { + let image = + registry::push_image(&paths, destination, rest.first().unwrap_or(&"latest"))?; + println!("Pushed {image}"); + Ok(()) + } + ["publish", destination, ref rest @ ..] => { + std::env::set_current_dir(paths.source()?)?; + let url = registry::publish(&paths, destination)?; + println!("Published {url}"); + let (host, login) = + match *rest { + [] => (None, None), + [host] => (Some(host), None), + [host, "--login"] => (Some(host), destination.split('/').next()), + [host, "--login", registry] => (Some(host), Some(registry)), + _ => return Err( + "Usage: berth publish REGISTRY[/REPOSITORY] [HOST [--login [REGISTRY]]]" + .into(), + ), + }; + if let Some(host) = host { + let (place, mut config) = profile::load(&paths, host)?; + config["release_url"] = json!(url); + config["release_store"] = json!(destination); + config["release_private"] = json!(login.is_some()); + match login { + Some(name) => { + if registry::Store::new(&paths)?.curl_login(name)?.is_none() { + return Err(format!("Registry {name} has no stored login").into()); + } + config["release_login"] = json!(name); + println!("{host} downloads it from there with the login of {name}"); + } + None => { + if let Some(profile) = config.as_object_mut() { + profile.remove("release_login"); + } + println!("{host} downloads it from there without a login"); + } + } + profile::save(&paths, &place, config)?; + } + Ok(()) + } + // A host's own subcommands start with secret or registry. + ["host", "add", name, address, ref rest @ ..] + if !["secret", "registry"].contains(&name) => + { + commands::add_host(&paths, name, address, rest) + } + ["host", "install", host] => commands::install_controller(&paths, host), + ["host", "type", host, given] => commands::set_type(&paths, host, given), + ["host", "rename", host, name] => commands::rename(&paths, host, name, false), + ["host", "rename", host, name, "--hostname"] + | ["host", "rename", host, "--hostname", name] => { + commands::rename(&paths, host, name, true) + } + ["host", host, ref rest @ ..] => host_command(&paths, host, rest), + ["serve", ref rest @ ..] => serve::command(&paths, rest), + ["setup-key", ref rest @ ..] => serve::setup_key::command(&paths, rest), + ["inbox", ref rest @ ..] => serve::inbox_command(&paths, rest), + ["kv", ref rest @ ..] => serve::kv_command(&paths, rest), + ["store", ref rest @ ..] => store_command::command(&paths, rest), + ["openapi"] => { + println!("{}", serde_json::to_string_pretty(&serve::openapi())?); + Ok(()) + } + ["operations"] => { + println!("{}", serde_json::to_string_pretty(&serve::operations())?); + Ok(()) + } + ["asyncapi"] => { + println!("{}", serde_json::to_string_pretty(&serve::asyncapi())?); + Ok(()) + } + ["plugins"] => { + let listing = plugins::Manager::new(&paths).list()?; + print!("{}", plugins::describe(&listing.plugins)); + Ok(()) + } + ["plugins", "add", spec] => { + for line in plugins::Manager::new(&paths).add(spec)? { + println!("{line}"); + } + Ok(()) + } + ["plugins", "update", ref rest @ ..] => commands::update_plugins(&paths, rest), + ["plugins", "remove", name] => { + let manager = plugins::Manager::new(&paths); + // A name npm knows that berth does not, such as a broken package. + let known = manager + .list()? + .plugins + .iter() + .any(|plugin| plugin.id == *name || plugin.package == *name); + if !known && manager.server().is_none() { + let mut npm = Command::new("npm"); + npm.args([ + "uninstall", + "--ignore-scripts", + "--no-audit", + "--no-fund", + "--prefix", + ]) + .arg(plugins::own_dir(&paths.config_dir)) + .arg(name); + let done = succeed(npm); + if let Some(line) = plugins::remembered(&paths) { + eprintln!("{line}"); + } + return done; + } + for line in manager.remove(name)? { + println!("{line}"); + } + Ok(()) + } + ["config"] => show_config(&paths), + ["config", key] => change_setting(&paths, key, ""), + ["config", key, value] => change_setting(&paths, key, value), + ["tailnet-key", host] => { + // An apply runs this on the machine that runs berth, for a host + // not on the tailnet yet; the key goes to the role on stdout. + println!("{}", berth_core::tailnet::key_for(&paths, host)?); + Ok(()) + } + ["profile", host] => commands::show_profile(&paths, host), + ["profile", host, "--set", file] => commands::set_profile(&paths, host, file), + ["credentials", host] => commands::credentials(&paths, host, false), + ["credentials", host, "--show"] | ["credentials", "--show", host] => { + commands::credentials(&paths, host, true) + } + ["iso", host] => commands::installer(&paths, host, None), + ["iso", host, "--write", device] => commands::installer(&paths, host, Some(device)), + ["key", ref rest @ ..] => key_command::command(&paths, rest), + ["apply", "--behind" | "--all", ..] => commands::apply_hosts(&paths, &args[1..]), + ["apply", host] => commands::apply(&paths, host), + ["remove", host] => commands::remove(&paths, host), + ["adopt", host, ref rest @ ..] => commands::adopt(&paths, host, rest), + ["provisioners"] => commands::provisioners(&paths), + ["provisioner", ref rest @ ..] => provisioner_command::command(&paths, rest), + ["provision", host, provisioner, ref rest @ ..] => { + resource_command::provision(&paths, host, provisioner, rest) + } + ["instance", host, ref rest @ ..] => resource_command::instance(&paths, host, rest), + ["resource", ref rest @ ..] => resource_command::command(&paths, rest), + ["deploy", name, ref rest @ ..] => resource_command::deploy(&paths, name, rest), + ["seed", host] => commands::seed(&paths, host), + ["actions", host] => commands::actions(&paths, host), + ["run" | "manage", host, action, ref rest @ ..] => { + commands::run(&paths, host, action, rest) + } + ["exec", host, ref rest @ ..] => commands::exec(&paths, host, rest), + ["attach", host] => commands::attach(&paths, host, None), + ["attach", host, id] => commands::attach(&paths, host, Some(id)), + ["sessions", host] => commands::sessions(&paths, host), + ["output", host, id, ref rest @ ..] => commands::output(&paths, host, id, rest), + ["channel", host, ref rest @ ..] => commands::channel(&paths, host, rest), + ["call", host, service, method] => commands::call(&paths, host, service, method, None), + ["call", host, service, method, body] => { + commands::call(&paths, host, service, method, Some(body)) + } + ["inventory", ref hosts @ ..] => commands::inventory(&paths, hosts), + ["ssh", host, "--agent"] | ["ssh", "--agent", host] => { + let status = commands::agent_terminal(&paths, host)?.status()?; + std::process::exit(status.code().unwrap_or(1)); + } + ["ssh", host, ref remote @ ..] => { + let status = commands::terminal(&paths, host, remote)?.status()?; + std::process::exit(status.code().unwrap_or(1)); + } + _ => { + println!("{}", crate::USAGE); + Ok(()) + } + } +} diff --git a/crates/berth/src/profile.rs b/crates/berth/src/local/profile.rs similarity index 100% rename from crates/berth/src/profile.rs rename to crates/berth/src/local/profile.rs diff --git a/crates/berth/src/provisioner_command.rs b/crates/berth/src/local/provisioner_command.rs similarity index 99% rename from crates/berth/src/provisioner_command.rs rename to crates/berth/src/local/provisioner_command.rs index 1a6b656..18da4cd 100644 --- a/crates/berth/src/provisioner_command.rs +++ b/crates/berth/src/local/provisioner_command.rs @@ -4,7 +4,7 @@ //! The Provisioners tab of the terminal screen goes the same way. use crate::Result; -use crate::commands::{follow_job, parse_arguments, ready}; +use crate::local::commands::{follow_job, parse_arguments, ready}; use berth_api::{ self as api, Act, Action, NewResource, ProvisionerInfo, ProvisionerState, Resource, ResourceSecret, SavedProvisioner, diff --git a/crates/berth/src/resource_command.rs b/crates/berth/src/local/resource_command.rs similarity index 99% rename from crates/berth/src/resource_command.rs rename to crates/berth/src/local/resource_command.rs index e856f1b..6f13c02 100644 --- a/crates/berth/src/resource_command.rs +++ b/crates/berth/src/local/resource_command.rs @@ -4,8 +4,8 @@ //! otherwise here, with this berth's secrets. use crate::Result; -use crate::commands::{parse_arguments, ready}; -use crate::provisioner_command::{Change, Ran, Source, answer_lines}; +use crate::local::commands::{parse_arguments, ready}; +use crate::local::provisioner_command::{Change, Ran, Source, answer_lines}; use berth_api::{Action, NewResource, Resource, ResourceSecret}; use berth_core::{paths::Paths, resource}; use std::io::{IsTerminal, Read, Write}; diff --git a/crates/berth/src/serve/actions.rs b/crates/berth/src/local/serve/actions.rs similarity index 100% rename from crates/berth/src/serve/actions.rs rename to crates/berth/src/local/serve/actions.rs diff --git a/crates/berth/src/serve/api.rs b/crates/berth/src/local/serve/api.rs similarity index 100% rename from crates/berth/src/serve/api.rs rename to crates/berth/src/local/serve/api.rs diff --git a/crates/berth/src/serve/auth.rs b/crates/berth/src/local/serve/auth.rs similarity index 100% rename from crates/berth/src/serve/auth.rs rename to crates/berth/src/local/serve/auth.rs diff --git a/crates/berth/src/serve/docs.rs b/crates/berth/src/local/serve/docs.rs similarity index 100% rename from crates/berth/src/serve/docs.rs rename to crates/berth/src/local/serve/docs.rs diff --git a/crates/berth/src/serve/here.rs b/crates/berth/src/local/serve/here.rs similarity index 99% rename from crates/berth/src/serve/here.rs rename to crates/berth/src/local/serve/here.rs index 124943e..dc6d108 100644 --- a/crates/berth/src/serve/here.rs +++ b/crates/berth/src/local/serve/here.rs @@ -95,7 +95,7 @@ impl Here { /// unfinished, which another berth beside this one may be running. pub fn start(paths: &Paths) -> Result { let store = super::open_store(paths)?; - crate::restore_plugins(paths); + crate::local::restore_plugins(paths); let mut state = Serve::with(paths.clone(), store, auth::Auth::nobody()); if let Some(state) = Arc::get_mut(&mut state) { state.follows = false; diff --git a/crates/berth/src/serve/keys.rs b/crates/berth/src/local/serve/keys.rs similarity index 100% rename from crates/berth/src/serve/keys.rs rename to crates/berth/src/local/serve/keys.rs diff --git a/crates/berth/src/serve/mod.rs b/crates/berth/src/local/serve/mod.rs similarity index 99% rename from crates/berth/src/serve/mod.rs rename to crates/berth/src/local/serve/mod.rs index 2bcb5a6..137b4c4 100644 --- a/crates/berth/src/serve/mod.rs +++ b/crates/berth/src/local/serve/mod.rs @@ -607,7 +607,7 @@ pub fn command(paths: &Paths, args: &[&str]) -> Result<()> { "berth serve: the PostgreSQL database holds this installation's keys and passwords readable; berth store encrypt seals them" ); } - crate::restore_plugins(paths); + crate::local::restore_plugins(paths); let token = match listen { Some(_) => Some(token(paths)?), None => None, diff --git a/crates/berth/src/serve/provisioners.rs b/crates/berth/src/local/serve/provisioners.rs similarity index 100% rename from crates/berth/src/serve/provisioners.rs rename to crates/berth/src/local/serve/provisioners.rs diff --git a/crates/berth/src/serve/resources.rs b/crates/berth/src/local/serve/resources.rs similarity index 100% rename from crates/berth/src/serve/resources.rs rename to crates/berth/src/local/serve/resources.rs diff --git a/crates/berth/src/serve/setup.rs b/crates/berth/src/local/serve/setup.rs similarity index 100% rename from crates/berth/src/serve/setup.rs rename to crates/berth/src/local/serve/setup.rs diff --git a/crates/berth/src/serve/setup_key.rs b/crates/berth/src/local/serve/setup_key.rs similarity index 97% rename from crates/berth/src/serve/setup_key.rs rename to crates/berth/src/local/serve/setup_key.rs index c194653..b1fb99c 100644 --- a/crates/berth/src/serve/setup_key.rs +++ b/crates/berth/src/local/serve/setup_key.rs @@ -82,8 +82,8 @@ pub fn command(paths: &Paths, args: &[&str]) -> Result<()> { println!("{key}"); eprintln!( "This setup key lets the first user collect the token of this berth server, until {} or until they are done.\n\ - With berth: berth connect URL and paste the key when asked.\n\ - With berth-remote: berth-remote --server URL with the key in BERTH_SETUP_KEY.\n\ + With berth: berth connect URL and paste the key when asked,\n\ + or open the screens with the key in BERTH_SETUP_KEY: BERTH_SERVER=URL berth\n\ URL is the server's address, such as https://studio.example.ts.net.", rfc3339(expires) ); diff --git a/crates/berth/src/serve/tests.rs b/crates/berth/src/local/serve/tests.rs similarity index 99% rename from crates/berth/src/serve/tests.rs rename to crates/berth/src/local/serve/tests.rs index 96c6763..fc69e34 100644 --- a/crates/berth/src/serve/tests.rs +++ b/crates/berth/src/local/serve/tests.rs @@ -3132,9 +3132,12 @@ async fn berth_connect_saves_the_server_and_its_token() { data_dir: client.path().join("data"), }; let connect = |key: String| { - let (paths, url) = (paths.clone(), url.clone()); + let (dir, url) = (paths.config_dir.clone(), url.clone()); tokio::task::spawn_blocking(move || { - crate::commands::connect_with(&paths, &url, &key).map_err(|error| error.to_string()) + let settings = berth_page::settings::Settings::new(Some(dir)); + crate::connect::connect_with(&settings, &url, &key) + .map(drop) + .map_err(|error| error.to_string()) }) }; // A wrong key saves nothing. @@ -3477,7 +3480,7 @@ fn pruning_removes_a_jobs_output_and_its_report() { /// The routes of the key ring, with the helpers of these tests. mod keys; -/// berth-remote signed in to a server of the tests. +/// The screens signed in to a server of the tests over the network. mod remote; #[tokio::test(flavor = "multi_thread")] diff --git a/crates/berth/src/serve/tests/keys.rs b/crates/berth/src/local/serve/tests/keys.rs similarity index 100% rename from crates/berth/src/serve/tests/keys.rs rename to crates/berth/src/local/serve/tests/keys.rs diff --git a/crates/berth/src/serve/tests/remote.rs b/crates/berth/src/local/serve/tests/remote.rs similarity index 100% rename from crates/berth/src/serve/tests/remote.rs rename to crates/berth/src/local/serve/tests/remote.rs diff --git a/crates/berth/src/store_command.rs b/crates/berth/src/local/store_command.rs similarity index 99% rename from crates/berth/src/store_command.rs rename to crates/berth/src/local/store_command.rs index 1dc4186..350f0e1 100644 --- a/crates/berth/src/store_command.rs +++ b/crates/berth/src/local/store_command.rs @@ -601,7 +601,7 @@ mod tests { ) .unwrap(); paths.own_key().unwrap(); - let token = crate::serve::token(paths).unwrap(); + let token = crate::local::serve::token(paths).unwrap(); // A plugin from an upload and one copied in as a folder. let own = berth_core::plugins::own_dir(&paths.config_dir); fs::create_dir_all(own.join("uploads")).unwrap(); @@ -656,7 +656,7 @@ mod tests { let file = paths.own_key().unwrap(); assert_eq!(file, paths.data_dir.join("keys/berth")); assert_eq!(fs::read(&file).unwrap(), key); - assert_eq!(crate::serve::token(paths).unwrap(), token); + assert_eq!(crate::local::serve::token(paths).unwrap(), token); assert_eq!( fs::read_to_string(paths.data_dir.join("serve.token")) .unwrap() diff --git a/crates/berth/src/main.rs b/crates/berth/src/main.rs index f7a65b7..40ca31d 100644 --- a/crates/berth/src/main.rs +++ b/crates/berth/src/main.rs @@ -1,19 +1,23 @@ -mod commands; -mod key_command; -mod profile; -mod provisioner_command; -mod resource_command; -mod serve; -mod store_command; +//! berth: set up and look after agent workstations. On Linux the program +//! has its installation in it: `berth serve`, the commands and a server for +//! the screens. Elsewhere it is a client of a `berth serve` on another +//! machine, with the same screens. + +mod connect; +#[cfg(target_os = "linux")] +mod local; +#[cfg(not(target_os = "linux"))] +#[path = "client_only.rs"] +mod local; mod update; -use berth_core::{paths, plugins, registry}; -use paths::Paths; -use serde_json::json; -use std::{error::Error, process::Command}; +use std::error::Error; type Result = std::result::Result>; +/// A server on this machine for the screens, and what to do once they close. +type Local = (String, Box); + const USAGE: &str = "berth: set up and look after agent workstations. Usage: @@ -172,105 +176,6 @@ Usage: berth openapi | asyncapi | operations the API documents of berth serve"; -fn show_config(paths: &Paths) -> Result<()> { - // The settings of the file are shown when the store does not open. - let (settings, unopened) = match paths.settings() { - Ok(settings) => (settings, None), - Err(error) => (paths.local_settings()?, Some(error)), - }; - println!( - "Settings {}, and the store", - paths.settings_file().display() - ); - let store = berth_core::store::Installation::of(paths).target.describe(); - match &unopened { - None => println!("Store {store}: settings, hosts, registries and secrets"), - Some(error) => println!("Store {store}, which does not open: {error}"), - } - match berth_core::server::Server::configured(paths) { - Some(server) => println!( - "Hosts on the berth server at {}, with a copy in the store", - server.url - ), - None => println!("Hosts in the store, with their passwords and machines"), - } - println!("Builds {}", paths.build_dir().display()); - match paths.source() { - Ok(source) => println!("Source {}", source.display()), - Err(error) => println!("Source {error}"), - } - println!(); - for (key, help) in paths::SETTINGS { - // What lets someone in is not for a screen. - let value = match settings.get(*key).and_then(|value| value.as_str()) { - Some(_) if paths::is_secret(key) => Some("(set)"), - value => value, - }; - let value = match (&unopened, paths::is_local(key)) { - (Some(_), false) => Some("(in the store, which does not open)"), - _ => value, - }; - println!("{key} = {}\n {help}", value.unwrap_or("(not set)")); - } - Ok(()) -} - -/// `berth config KEY VALUE`: the tailnet settings of a berth server this -/// berth uses are the server's, and change there. -fn change_setting(paths: &Paths, key: &str, value: &str) -> Result<()> { - match berth_core::server::Server::configured(paths) { - Some(server) if berth_core::tailnet::SETTINGS.contains(&key) => { - server.call( - "settings.set", - json!({"key": key}), - Some(json!({"value": value})), - )?; - println!("Changed {key} on the berth server at {}", server.url); - Ok(()) - } - _ => paths.set(key, value), - } -} - -/// Whether a command reads this machine's own plugins: the commands that -/// apply, build or provision with them or list them. -fn loads_plugins(args: &[&str]) -> bool { - const VERBS: &[&str] = &[ - "apply", - "plugins", - "provisioners", - "provisioner", - "provision", - "instance", - "resource", - "deploy", - "seed", - "iso", - "publish", - "host", - ]; - args.first().is_some_and(|verb| VERBS.contains(verb)) -} - -/// Put back the plugins berth's store has and this machine's plugin -/// directory lacks, as on a machine restored from the store, and say so on -/// standard error. -pub(crate) fn restore_plugins(paths: &Paths) { - match berth_core::plugin_state::restore(paths) { - Ok(notices) => notices.iter().for_each(|notice| eprintln!("{notice}")), - Err(error) => eprintln!("berth: the plugins in berth's store were not checked: {error}"), - } -} - -fn succeed(mut command: Command) -> Result<()> { - let status = command.status()?; - if !status.success() { - let program = command.get_program().to_string_lossy().into_owned(); - return Err(format!("{program} failed ({status})").into()); - } - Ok(()) -} - /// End quietly when what reads berth's output has gone, as `head` does after /// its lines: printing then panics, which is no fault of berth's to report. fn end_quietly_on_a_closed_pipe() { @@ -344,83 +249,20 @@ fn screens(host: Option<&str>) -> Result<()> { Err(error) => eprintln!("berth: berth-remote's settings were not taken in: {error}"), } let mut linked = berth_page::device::Linked::from(var); - let mut here = None; - if linked.local(&settings) { - let (server, started) = serve::here::local(&Paths::locate()?)?; - if let Some(started) = &started { - berth_page::net::serve_here(started.dial()); - } + let mut finish: Box = Box::new(|| {}); + // Without a server here, the screens ask for one and its token. + if linked.local(&settings) + && let Some((server, then)) = local::server()? + { linked.server = Some(server); - here = started; + finish = then; } berth_page::device::install(linked, settings); let shown = berth_page::screens::run(host.map(str::to_owned)); - serve::here::finish(here); + finish(); Ok(shown?) } -/// `berth host HOST ...`: the secrets and registries a host is given. -fn host_command(paths: &Paths, host: &str, args: &[&str]) -> Result<()> { - let (place, mut config) = profile::load(paths, host)?; - let list = |value: &serde_json::Value| value.as_array().cloned().unwrap_or_default(); - match *args { - [] => { - for secret in list(&config["secrets"]) { - let place = match (secret["env"].as_str(), secret["file"].as_str()) { - (Some(variable), _) => format!("env {variable}"), - (_, Some(path)) => format!("file {path}"), - _ => String::new(), - }; - println!( - "secret {} {place}", - secret["name"].as_str().unwrap_or("") - ); - } - for name in list(&config["registries"]) { - println!("registry {}", name.as_str().unwrap_or("")); - } - println!("Send them with: berth run {host} secrets"); - return Ok(()); - } - ["secret", name, ref how @ ..] => { - let mut secrets = list(&config["secrets"]); - secrets.retain(|known| known["name"] != name); - match *how { - ["env", variable] => secrets.push(json!({"name": name, "env": variable})), - ["file", path] => secrets.push(json!({"name": name, "file": path})), - ["file", path, mode] => { - secrets.push(json!({"name": name, "file": path, "mode": mode})) - } - ["off"] => {} - _ => { - return Err( - "Usage: berth host HOST secret NAME env VARIABLE | file PATH [MODE] | off" - .into(), - ); - } - } - config["secrets"] = json!(secrets); - } - ["registry", name, switch @ ("on" | "off")] => { - let mut registries = list(&config["registries"]); - registries.retain(|known| known != name); - if switch == "on" { - if !registry::Store::new(paths)? - .registries()? - .contains_key(name) - { - return Err(format!("No registry {name}. See: berth registry").into()); - } - registries.push(json!(name)); - } - config["registries"] = json!(registries); - } - _ => return Err("Usage: berth host HOST [secret NAME ... | registry NAME on|off]".into()), - } - profile::save(paths, &place, config)?; - Ok(()) -} - fn main() { end_quietly_on_a_closed_pipe(); if let Err(error) = run() { @@ -432,20 +274,8 @@ fn main() { fn run() -> Result<()> { let args: Vec = std::env::args().skip(1).collect(); let mut args: Vec<&str> = args.iter().map(String::as_str).collect(); - // ssh runs berth as its askpass helper, the program of SSH_ASKPASS, with - // the prompt as its one argument and the variable that says where the - // password is; the answer is all that may go to standard output. - if let Ok(source) = std::env::var(berth_core::keys::askpass::SOURCE) { - let prompt = match args[..] { - ["askpass", ref prompt @ ..] => Some(prompt.join(" ")), - [prompt] => Some(prompt.to_owned()), - _ => None, - }; - if let Some(prompt) = prompt { - let answer = berth_core::keys::askpass::answer(&prompt, &source, None)?; - println!("{answer}"); - return Ok(()); - } + if local::askpass(&args)? { + return Ok(()); } // `--server URL [--token TOKEN]` first: this run only, through that berth serve. while let [flag @ ("--server" | "--token"), value, ..] = args[..] { @@ -458,231 +288,17 @@ fn run() -> Result<()> { unsafe { std::env::set_var(variable, value) }; args.drain(..2); } - // The screens go through a server, and take nothing from this machine's own files. if let Some(host) = opens_screens(&args) { return screens(host); } - let paths = Paths::locate()?; - if loads_plugins(&args) && berth_core::server::Server::configured(&paths).is_none() { - restore_plugins(&paths); - } - // With a server set, the hosts are the server's: fetch them before anything looks. - let local = [ - "config", - "serve", - "--version", - "-V", - "version", - "openapi", - "asyncapi", - "operations", - "update", - "key", - "askpass", - "tailnet-key", - "credentials", - "connect", - "setup-key", - "store", - ]; - if let Some(server) = berth_core::server::Server::configured(&paths) - && !args.first().is_some_and(|verb| local.contains(verb)) - { - server - .mirror(&paths) - .map_err(|error| format!("the berth server at {}: {error}", server.url))?; - } match args[..] { - ["list"] => { - for (name, address) in paths.hosts() { - println!("{name:<24} {address}"); - } - Ok(()) - } - ["registry", ref rest @ ..] => registry::registry_command(&paths, rest), - ["secret", ref rest @ ..] => registry::secret_command(&paths, rest), - ["image", "push", destination, ref rest @ ..] => { - let image = - registry::push_image(&paths, destination, rest.first().unwrap_or(&"latest"))?; - println!("Pushed {image}"); - Ok(()) - } - ["publish", destination, ref rest @ ..] => { - std::env::set_current_dir(paths.source()?)?; - let url = registry::publish(&paths, destination)?; - println!("Published {url}"); - let (host, login) = - match *rest { - [] => (None, None), - [host] => (Some(host), None), - [host, "--login"] => (Some(host), destination.split('/').next()), - [host, "--login", registry] => (Some(host), Some(registry)), - _ => return Err( - "Usage: berth publish REGISTRY[/REPOSITORY] [HOST [--login [REGISTRY]]]" - .into(), - ), - }; - if let Some(host) = host { - let (place, mut config) = profile::load(&paths, host)?; - config["release_url"] = json!(url); - config["release_store"] = json!(destination); - config["release_private"] = json!(login.is_some()); - match login { - Some(name) => { - if registry::Store::new(&paths)?.curl_login(name)?.is_none() { - return Err(format!("Registry {name} has no stored login").into()); - } - config["release_login"] = json!(name); - println!("{host} downloads it from there with the login of {name}"); - } - None => { - if let Some(profile) = config.as_object_mut() { - profile.remove("release_login"); - } - println!("{host} downloads it from there without a login"); - } - } - profile::save(&paths, &place, config)?; - } - Ok(()) - } - // A host's own subcommands start with secret or registry. - ["host", "add", name, address, ref rest @ ..] - if !["secret", "registry"].contains(&name) => - { - commands::add_host(&paths, name, address, rest) - } - ["host", "install", host] => commands::install_controller(&paths, host), - ["host", "type", host, given] => commands::set_type(&paths, host, given), - ["host", "rename", host, name] => commands::rename(&paths, host, name, false), - ["host", "rename", host, name, "--hostname"] - | ["host", "rename", host, "--hostname", name] => { - commands::rename(&paths, host, name, true) - } - ["host", host, ref rest @ ..] => host_command(&paths, host, rest), ["--version" | "-V" | "version"] => { println!("berth {}", berth_api::VERSION); Ok(()) } ["update", ref rest @ ..] => update::command(rest), - ["serve", ref rest @ ..] => serve::command(&paths, rest), - ["setup-key", ref rest @ ..] => serve::setup_key::command(&paths, rest), - ["connect", url] => commands::connect(&paths, url), - ["inbox", ref rest @ ..] => serve::inbox_command(&paths, rest), - ["kv", ref rest @ ..] => serve::kv_command(&paths, rest), - ["store", ref rest @ ..] => store_command::command(&paths, rest), - ["openapi"] => { - println!("{}", serde_json::to_string_pretty(&serve::openapi())?); - Ok(()) - } - ["operations"] => { - println!("{}", serde_json::to_string_pretty(&serve::operations())?); - Ok(()) - } - ["asyncapi"] => { - println!("{}", serde_json::to_string_pretty(&serve::asyncapi())?); - Ok(()) - } - ["plugins"] => { - let listing = plugins::Manager::new(&paths).list()?; - print!("{}", plugins::describe(&listing.plugins)); - Ok(()) - } - ["plugins", "add", spec] => { - for line in plugins::Manager::new(&paths).add(spec)? { - println!("{line}"); - } - Ok(()) - } - ["plugins", "update", ref rest @ ..] => commands::update_plugins(&paths, rest), - ["plugins", "remove", name] => { - let manager = plugins::Manager::new(&paths); - // A name npm knows that berth does not, such as a broken package. - let known = manager - .list()? - .plugins - .iter() - .any(|plugin| plugin.id == *name || plugin.package == *name); - if !known && manager.server().is_none() { - let mut npm = Command::new("npm"); - npm.args([ - "uninstall", - "--ignore-scripts", - "--no-audit", - "--no-fund", - "--prefix", - ]) - .arg(plugins::own_dir(&paths.config_dir)) - .arg(name); - let done = succeed(npm); - if let Some(line) = plugins::remembered(&paths) { - eprintln!("{line}"); - } - return done; - } - for line in manager.remove(name)? { - println!("{line}"); - } - Ok(()) - } - ["config"] => show_config(&paths), - ["config", key] => change_setting(&paths, key, ""), - ["config", key, value] => change_setting(&paths, key, value), - ["tailnet-key", host] => { - // An apply runs this on the machine that runs berth, for a host - // not on the tailnet yet; the key goes to the role on stdout. - println!("{}", berth_core::tailnet::key_for(&paths, host)?); - Ok(()) - } - ["profile", host] => commands::show_profile(&paths, host), - ["profile", host, "--set", file] => commands::set_profile(&paths, host, file), - ["credentials", host] => commands::credentials(&paths, host, false), - ["credentials", host, "--show"] | ["credentials", "--show", host] => { - commands::credentials(&paths, host, true) - } - ["iso", host] => commands::installer(&paths, host, None), - ["iso", host, "--write", device] => commands::installer(&paths, host, Some(device)), - ["key", ref rest @ ..] => key_command::command(&paths, rest), - ["apply", "--behind" | "--all", ..] => commands::apply_hosts(&paths, &args[1..]), - ["apply", host] => commands::apply(&paths, host), - ["remove", host] => commands::remove(&paths, host), - ["adopt", host, ref rest @ ..] => commands::adopt(&paths, host, rest), - ["provisioners"] => commands::provisioners(&paths), - ["provisioner", ref rest @ ..] => provisioner_command::command(&paths, rest), - ["provision", host, provisioner, ref rest @ ..] => { - resource_command::provision(&paths, host, provisioner, rest) - } - ["instance", host, ref rest @ ..] => resource_command::instance(&paths, host, rest), - ["resource", ref rest @ ..] => resource_command::command(&paths, rest), - ["deploy", name, ref rest @ ..] => resource_command::deploy(&paths, name, rest), - ["seed", host] => commands::seed(&paths, host), - ["actions", host] => commands::actions(&paths, host), - ["run" | "manage", host, action, ref rest @ ..] => { - commands::run(&paths, host, action, rest) - } - ["exec", host, ref rest @ ..] => commands::exec(&paths, host, rest), - ["attach", host] => commands::attach(&paths, host, None), - ["attach", host, id] => commands::attach(&paths, host, Some(id)), - ["sessions", host] => commands::sessions(&paths, host), - ["output", host, id, ref rest @ ..] => commands::output(&paths, host, id, rest), - ["channel", host, ref rest @ ..] => commands::channel(&paths, host, rest), - ["call", host, service, method] => commands::call(&paths, host, service, method, None), - ["call", host, service, method, body] => { - commands::call(&paths, host, service, method, Some(body)) - } - ["inventory", ref hosts @ ..] => commands::inventory(&paths, hosts), - ["ssh", host, "--agent"] | ["ssh", "--agent", host] => { - let status = commands::agent_terminal(&paths, host)?.status()?; - std::process::exit(status.code().unwrap_or(1)); - } - ["ssh", host, ref remote @ ..] => { - let status = commands::terminal(&paths, host, remote)?.status()?; - std::process::exit(status.code().unwrap_or(1)); - } - _ => { - println!("{USAGE}"); - Ok(()) - } + ["connect", url] => connect::command(url), + _ => local::command(&args), } } diff --git a/crates/berth/src/update.rs b/crates/berth/src/update.rs index 934eaae..a5112d4 100644 --- a/crates/berth/src/update.rs +++ b/crates/berth/src/update.rs @@ -9,7 +9,17 @@ use crate::Result; use std::{fs, path::Path, process::Command}; const REPOSITORY: &str = "https://github.com/helightdev/berth"; -const ASSET: &str = "berth-x86_64-linux.tar.gz"; + +/// The archive of the release for this system, when there is one. +fn asset() -> Option<&'static str> { + match (std::env::consts::OS, std::env::consts::ARCH) { + ("linux", "x86_64") => Some("berth-x86_64-linux.tar.gz"), + ("linux", "aarch64") => Some("berth-aarch64-linux.tar.gz"), + ("macos", "aarch64") => Some("berth-aarch64-macos.tar.gz"), + ("macos", "x86_64") => Some("berth-x86_64-macos.tar.gz"), + _ => None, + } +} /// Where the releases are: GitHub's, or `BERTH_RELEASES` for a mirror. fn releases() -> String { @@ -73,12 +83,15 @@ pub fn command(args: &[&str]) -> Result<()> { ["--check"] => true, _ => return Err("Usage: berth update [--check]".into()), }; - if !cfg!(all(target_os = "linux", target_arch = "x86_64")) { + if cfg!(windows) { + return Err("On Windows the new release is installed with install.ps1: irm https://raw.githubusercontent.com/helightdev/berth/main/install.ps1 | iex".into()); + } + let Some(asset) = asset() else { return Err(format!( - "Releases are built for Linux on x86_64. Update this one with: cargo install --locked --git {REPOSITORY} berth" + "No release is built for this system. Update this one with: cargo install --locked --git {REPOSITORY} berth" ) .into()); - } + }; let current = berth_api::VERSION; let latest = latest()?; if !newer(&latest, current) { @@ -101,8 +114,8 @@ pub fn command(args: &[&str]) -> Result<()> { let to = work.path().join(name); curl(&["-o", &to.to_string_lossy(), &format!("{url}/{name}")]).map(|_| ()) }; - fetch(ASSET)?; - fetch(&format!("{ASSET}.sha256"))?; + fetch(asset)?; + fetch(&format!("{asset}.sha256"))?; let run = |program: &str, args: &[&str]| -> Result<()> { let status = Command::new(program) .args(args) @@ -115,20 +128,30 @@ pub fn command(args: &[&str]) -> Result<()> { false => Err(format!("{program} failed ({status})").into()), } }; - run("sha256sum", &["-c", &format!("{ASSET}.sha256")]) - .map_err(|_| "the download does not match its checksum; nothing was changed")?; - run("tar", &["-xzf", ASSET, "berth"])?; + let sums = format!("{asset}.sha256"); + // macOS has shasum rather than sha256sum. + let checked = match cfg!(target_os = "macos") { + true => run("shasum", &["-a", "256", "-c", &sums]), + false => run("sha256sum", &["-c", &sums]), + }; + checked.map_err(|_| "the download does not match its checksum; nothing was changed")?; + run("tar", &["-xzf", asset, "berth"])?; replace(&work.path().join("berth"), &program)?; println!("berth {current} → {latest}"); - println!("Hosts get the new berthd and box when their configuration is applied again."); + if cfg!(target_os = "linux") { + println!("Hosts get the new berthd and box when their configuration is applied again."); + } Ok(()) } /// Put the new program in the old one's place in one step, so a running /// berth keeps the file it has open and the next start finds the new one. fn replace(new: &Path, program: &Path) -> Result<()> { - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(new, fs::Permissions::from_mode(0o755))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(new, fs::Permissions::from_mode(0o755))?; + } fs::rename(new, program).map_err(|error| format!("{}: {error}", program.display()))?; Ok(()) } diff --git a/install-remote.sh b/install-remote.sh deleted file mode 100755 index 7defe7d..0000000 --- a/install-remote.sh +++ /dev/null @@ -1,59 +0,0 @@ -#!/bin/sh -# Installs berth-remote for this user on macOS or Linux: the released program -# for this machine, checked against its SHA-256, into ~/.local/bin (or -# BERTH_INSTALL_DIR). berth-remote uses the hosts of a berth serve elsewhere. -# -# curl -fsSL https://raw.githubusercontent.com/helightdev/berth/main/install-remote.sh | sh -# -# BERTH_VERSION picks a release tag such as v0.5.0; the default is the latest. -set -eu - -repo=helightdev/berth -dir=${BERTH_INSTALL_DIR:-$HOME/.local/bin} -version=${BERTH_VERSION:-latest} - -fail() { printf 'install: %s\n' "$1" >&2; exit 1; } - -case "$(uname -s)" in - Linux) system=linux ;; - Darwin) system=macos ;; - *) fail "no released program for $(uname -s): on Windows use install.ps1" ;; -esac -case "$(uname -m)" in - x86_64|amd64) arch=x86_64 ;; - arm64|aarch64) arch=aarch64 ;; - *) fail "no released program for $(uname -m): build it with cargo install --locked --git https://github.com/$repo berth-remote" ;; -esac -asset=berth-remote-$arch-$system.tar.gz -for tool in curl tar; do - command -v "$tool" >/dev/null || fail "$tool is needed" -done -# macOS has shasum rather than sha256sum. -if command -v sha256sum >/dev/null; then - check() { sha256sum -c "$1"; } -elif command -v shasum >/dev/null; then - check() { shasum -a 256 -c "$1"; } -else - fail "sha256sum or shasum is needed" -fi - -if [ "$version" = latest ]; then - url=https://github.com/$repo/releases/latest/download -else - url=https://github.com/$repo/releases/download/$version -fi - -work=$(mktemp -d) -trap 'rm -rf "$work"' EXIT -curl -fsSL -o "$work/$asset" "$url/$asset" || fail "could not download $url/$asset" -curl -fsSL -o "$work/$asset.sha256" "$url/$asset.sha256" || fail "could not download the checksum" -(cd "$work" && check "$asset.sha256" >/dev/null) || fail "the download does not match its checksum" -tar -xzf "$work/$asset" -C "$work" berth-remote -mkdir -p "$dir" -install -m 755 "$work/berth-remote" "$dir/berth-remote" - -printf 'Installed %s to %s\n' "$("$dir/berth-remote" --version 2>/dev/null || echo berth-remote)" "$dir/berth-remote" -case ":$PATH:" in - *":$dir:"*) ;; - *) printf 'Add %s to your PATH to run it as berth-remote.\n' "$dir" ;; -esac diff --git a/install.ps1 b/install.ps1 index d3dc03f..c01323d 100644 --- a/install.ps1 +++ b/install.ps1 @@ -1,6 +1,6 @@ -# Installs berth-remote for this user on Windows: the released program, -# checked against its SHA-256, into %LOCALAPPDATA%\Programs\berth-remote (or -# BERTH_INSTALL_DIR). berth-remote uses the hosts of a berth serve elsewhere. +# Installs berth for this user on Windows: the released program, checked +# against its SHA-256, into %LOCALAPPDATA%\Programs\berth (or +# BERTH_INSTALL_DIR). On Windows berth uses the hosts of a berth serve elsewhere. # # irm https://raw.githubusercontent.com/helightdev/berth/main/install.ps1 | iex # @@ -9,8 +9,8 @@ $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' $repo = 'helightdev/berth' -$asset = 'berth-remote-x86_64-windows.zip' -$dir = if ($env:BERTH_INSTALL_DIR) { $env:BERTH_INSTALL_DIR } else { Join-Path $env:LOCALAPPDATA 'Programs\berth-remote' } +$asset = 'berth-x86_64-windows.zip' +$dir = if ($env:BERTH_INSTALL_DIR) { $env:BERTH_INSTALL_DIR } else { Join-Path $env:LOCALAPPDATA 'Programs\berth' } $version = if ($env:BERTH_VERSION) { $env:BERTH_VERSION } else { 'latest' } function Fail([string] $message) { @@ -20,7 +20,7 @@ function Fail([string] $message) { } if (-not [Environment]::Is64BitOperatingSystem -or $env:PROCESSOR_ARCHITECTURE -eq 'ARM64') { - Fail "no released program for this processor: build it with cargo install --locked --git https://github.com/$repo berth-remote" + Fail "no released program for this processor: build it with cargo install --locked --git https://github.com/$repo berth" } $url = if ($version -eq 'latest') { @@ -29,7 +29,7 @@ $url = if ($version -eq 'latest') { "https://github.com/$repo/releases/download/$version" } -$work = Join-Path ([IO.Path]::GetTempPath()) ("berth-remote-" + [Guid]::NewGuid()) +$work = Join-Path ([IO.Path]::GetTempPath()) ("berth-" + [Guid]::NewGuid()) New-Item -ItemType Directory -Path $work | Out-Null try { $zip = Join-Path $work $asset @@ -39,16 +39,16 @@ try { if ((Get-FileHash -Algorithm SHA256 $zip).Hash -ne $want) { Fail 'the download does not match its checksum' } Expand-Archive -Path $zip -DestinationPath (Join-Path $work 'unpacked') New-Item -ItemType Directory -Force -Path $dir | Out-Null - $program = Join-Path $dir 'berth-remote.exe' - Copy-Item -Force (Join-Path $work 'unpacked\berth-remote.exe') $program + $program = Join-Path $dir 'berth.exe' + Copy-Item -Force (Join-Path $work 'unpacked\berth.exe') $program } finally { Remove-Item -Recurse -Force $work -ErrorAction SilentlyContinue } -$said = try { & $program --version } catch { 'berth-remote' } +$said = try { & $program --version } catch { 'berth' } Write-Host "Installed $said to $program" $path = [Environment]::GetEnvironmentVariable('Path', 'User') if (-not (($path -split ';') -contains $dir)) { - Write-Host "Add $dir to your Path to run it as berth-remote:" + Write-Host "Add $dir to your Path to run it as berth:" Write-Host " [Environment]::SetEnvironmentVariable('Path', [Environment]::GetEnvironmentVariable('Path', 'User') + ';$dir', 'User')" } diff --git a/install.sh b/install.sh index 2a80113..6c8bbc4 100755 --- a/install.sh +++ b/install.sh @@ -1,6 +1,8 @@ #!/bin/sh -# Installs berth for this user: the released program for this machine, checked -# against its SHA-256, into ~/.local/bin (or BERTH_INSTALL_DIR). +# Installs berth for this user on Linux or macOS: the released program for +# this machine, checked against its SHA-256, into ~/.local/bin (or +# BERTH_INSTALL_DIR). On macOS berth is a client of a berth serve elsewhere; +# on Windows use install.ps1. # # curl -fsSL https://raw.githubusercontent.com/helightdev/berth/main/install.sh | sh # @@ -13,15 +15,28 @@ version=${BERTH_VERSION:-latest} fail() { printf 'install: %s\n' "$1" >&2; exit 1; } -[ "$(uname -s)" = Linux ] || fail "berth runs on Linux; on another system use the container image ghcr.io/$repo, or install-remote.sh for berth-remote, which uses a berth server elsewhere" +case "$(uname -s)" in + Linux) system=linux ;; + Darwin) system=macos ;; + *) fail "no released program for $(uname -s): on Windows use install.ps1" ;; +esac case "$(uname -m)" in x86_64|amd64) arch=x86_64 ;; + arm64|aarch64) arch=aarch64 ;; *) fail "no released program for $(uname -m): build it with cargo install --locked --git https://github.com/$repo berth" ;; esac -asset=berth-$arch-linux.tar.gz -for tool in curl tar sha256sum; do +asset=berth-$arch-$system.tar.gz +for tool in curl tar; do command -v "$tool" >/dev/null || fail "$tool is needed" done +# macOS has shasum rather than sha256sum. +if command -v sha256sum >/dev/null; then + check() { sha256sum -c "$1"; } +elif command -v shasum >/dev/null; then + check() { shasum -a 256 -c "$1"; } +else + fail "sha256sum or shasum is needed" +fi if [ "$version" = latest ]; then url=https://github.com/$repo/releases/latest/download @@ -33,7 +48,7 @@ work=$(mktemp -d) trap 'rm -rf "$work"' EXIT curl -fsSL -o "$work/$asset" "$url/$asset" || fail "could not download $url/$asset" curl -fsSL -o "$work/$asset.sha256" "$url/$asset.sha256" || fail "could not download the checksum" -(cd "$work" && sha256sum -c "$asset.sha256" >/dev/null) || fail "the download does not match its checksum" +(cd "$work" && check "$asset.sha256" >/dev/null) || fail "the download does not match its checksum" tar -xzf "$work/$asset" -C "$work" berth mkdir -p "$dir" install -m 755 "$work/berth" "$dir/berth" @@ -43,6 +58,8 @@ case ":$PATH:" in *":$dir:"*) ;; *) printf 'Add %s to your PATH to run it as berth.\n' "$dir" ;; esac +# The hosts are set up from Linux; elsewhere berth uses a server. +[ "$system" = linux ] || exit 0 missing= for tool in ssh python3 ansible-playbook; do command -v "$tool" >/dev/null || missing="$missing $tool" From 8f4d553a350a2a7348798cb91fc6676edd5d3841 Mon Sep 17 00:00:00 2001 From: Helight Date: Sun, 15 Nov 2026 01:42:55 +0100 Subject: [PATCH 18/94] fix(page): ask for hosts' sudo passwords before the screens, and say a host has no address The server in the process asks in the terminal, as berth serve does when it starts. The help of the USB installer's fields says the build downloads the ISO, as F4 no longer does. --- crates/berth-page/src/app.rs | 9 ++++++--- crates/berth-page/src/setup.rs | 2 +- crates/berth-tui/src/fields.rs | 13 +++++-------- crates/berth/src/local/mod.rs | 2 +- crates/berth/src/local/serve/here.rs | 21 +++++++++++---------- 5 files changed, 24 insertions(+), 23 deletions(-) diff --git a/crates/berth-page/src/app.rs b/crates/berth-page/src/app.rs index 0e1c0eb..5ccc235 100644 --- a/crates/berth-page/src/app.rs +++ b/crates/berth-page/src/app.rs @@ -590,11 +590,14 @@ impl App { rows.push(Row::info("")); } rows.push(heading("Connection")); + let address = match self.address.as_str() { + "" => "no SSH address yet", + address => address, + }; rows.push(Row::info(match self.local() { - true => format!(" {}", self.address), + true => format!(" {address}"), false => format!( - " {} · through the berth server at {}", - self.address, + " {address} · through the berth server at {}", device::shown(&self.server) ), })); diff --git a/crates/berth-page/src/setup.rs b/crates/berth-page/src/setup.rs index 4e7202a..2f507c6 100644 --- a/crates/berth-page/src/setup.rs +++ b/crates/berth-page/src/setup.rs @@ -220,7 +220,7 @@ impl Setup { if self.action == Action::Iso && !self.local { problems.push(Problem::new( Step::Install, - "The USB installer is built on the machine berth serve runs on: there, with berth ui or berth iso", + "The USB installer is built where berth serve runs, with berth ui there", )); } if self.action == Action::Ssh && view.text(Field::SshHost).is_empty() { diff --git a/crates/berth-tui/src/fields.rs b/crates/berth-tui/src/fields.rs index eef5419..34aa6ea 100644 --- a/crates/berth-tui/src/fields.rs +++ b/crates/berth-tui/src/fields.rs @@ -158,7 +158,7 @@ impl Action { "Generate the NoCloud files and provisioning bundle for an unattended installer." } Action::Iso => { - "For a blank machine: build an installer image from the Ubuntu Server ISO that installs and sets up the host without questions, and write it to a USB drive. F4 on the ISO field downloads the ISO." + "For a blank machine: build an installer image from the Ubuntu Server ISO that installs and sets up the host without questions, and write it to a USB drive. Without an ISO the current one is downloaded and checked first. It is built on the machine berth serve runs on." } Action::CloudSeed => { "Generate cloud-init user data. Upload the generated release archive to the configured URL." @@ -528,13 +528,13 @@ impl Field { "Source ISO", "/builder/iso", Path, - "Ubuntu Server 26.04 amd64 installer ISO to build from. F4 downloads the current one and checks it against Ubuntu's published SHA256SUMS.", + "Ubuntu Server 26.04 amd64 installer ISO to build from, a path on the machine berth serve runs on. Left empty, the build downloads the current one and checks it against Ubuntu's published SHA256SUMS.", ), IsoSha => ( "ISO SHA256", "/builder/iso_sha256", Text, - "SHA-256 the source ISO must have. Filled in from the file when you choose the ISO, and F4 recomputes it. Compare it with Ubuntu's published SHA256SUMS before trusting the image.", + "SHA-256 the source ISO must have, which the build checks. Take it from Ubuntu's published SHA256SUMS.", ), Inventory => ( "Ansible inventory", @@ -582,7 +582,7 @@ impl Field { "Then write to USB drive", "/builder/usb_device", Text, - "Enter switches between not writing and each connected USB drive. The chosen drive is erased and gets the finished ISO; that asks for confirmation and your sudo password. You can also press w after the build instead.", + "The USB drive the finished ISO is written to, such as /dev/sdb, on the machine berth serve runs on. It is erased. The host's overview asks for it again, with your sudo password, when the installer is built.", ), }; Spec { @@ -629,9 +629,6 @@ impl Field { /// Fields with a Generate (F4) action. pub fn can_generate(self) -> bool { - matches!( - self, - Field::Hostname | Field::Iso | Field::IsoSha | Field::TailscaleKey - ) || self.is_password_hash() + matches!(self, Field::Hostname | Field::TailscaleKey) || self.is_password_hash() } } diff --git a/crates/berth/src/local/mod.rs b/crates/berth/src/local/mod.rs index 3e4c622..fda0507 100644 --- a/crates/berth/src/local/mod.rs +++ b/crates/berth/src/local/mod.rs @@ -19,7 +19,7 @@ use std::process::Command; /// The server of this machine for the screens: a `berth serve` of this /// user, or one in this process, whose jobs `finish` waits for. pub fn server() -> Result> { - let (server, here) = serve::here::local(&Paths::locate()?)?; + let (server, here) = serve::here::local(&Paths::locate()?, true)?; if let Some(here) = &here { berth_page::net::serve_here(here.dial()); } diff --git a/crates/berth/src/local/serve/here.rs b/crates/berth/src/local/serve/here.rs index dc6d108..1a3423c 100644 --- a/crates/berth/src/local/serve/here.rs +++ b/crates/berth/src/local/serve/here.rs @@ -25,12 +25,12 @@ pub fn socket() -> std::path::PathBuf { /// The server berth goes through when it is set to use none: a `berth /// serve` of this user on this machine, or else one started in this process, /// which the caller keeps while it is needed. The address names either. -pub fn local(paths: &Paths) -> Result<(String, Option)> { +pub fn local(paths: &Paths, ask: bool) -> Result<(String, Option)> { let socket = socket(); if std::os::unix::net::UnixStream::connect(&socket).is_ok() { return Ok((format!("unix:{}", socket.display()), None)); } - let here = Here::start(paths)?; + let here = Here::start(paths, ask)?; berth_core::server::serve_here(here.dial()); Ok((berth_core::server::HERE.to_owned(), Some(here))) } @@ -41,7 +41,7 @@ pub fn server(paths: &Paths) -> Result<(berth_core::server::Server, Option if let Some(server) = berth_core::server::Server::configured(paths) { return Ok((server, None)); } - let (url, here) = local(paths)?; + let (url, here) = local(paths, false)?; Ok((berth_core::server::Server { url, token: None }, here)) } @@ -92,8 +92,10 @@ pub struct Here { impl Here { /// Open the store and serve its API to this process. The hosts' channels /// are left to `berth serve`, and so are jobs a server before left - /// unfinished, which another berth beside this one may be running. - pub fn start(paths: &Paths) -> Result { + /// unfinished, which another berth beside this one may be running. With + /// `ask`, a host whose sudo asks for a password has it asked for on the + /// terminal first, as `berth serve` does when it starts. + pub fn start(paths: &Paths, ask: bool) -> Result { let store = super::open_store(paths)?; crate::local::restore_plugins(paths); let mut state = Serve::with(paths.clone(), store, auth::Auth::nobody()); @@ -107,10 +109,9 @@ impl Here { .enable_all() .build()?; let (connections, pipes) = unbounded_channel(); + runtime.block_on(async { state.refresh(ask) }); let router = api::router(state.clone(), false); - let serving = state.clone(); runtime.spawn(async move { - serving.refresh(false); let _ = axum::serve(Pipes(pipes), router).await; }); // Another berth beside this one changes the store too. @@ -187,7 +188,7 @@ mod tests { .unwrap() .save(&paths, &profile) .unwrap(); - let here = Here::start(&paths).unwrap(); + let here = Here::start(&paths, false).unwrap(); let dial = here.dial(); // The client has a runtime of its own, as the screens do. let client_runtime = tokio::runtime::Builder::new_current_thread() @@ -285,7 +286,7 @@ mod tests { .save(&paths, &profile) .unwrap(); } - let here = Here::start(&paths).unwrap(); + let here = Here::start(&paths, false).unwrap(); berth_page::net::serve_here(here.dial()); let kept = dir.path().join("client"); let linked = berth_page::device::Linked { @@ -333,7 +334,7 @@ mod tests { #[test] fn nothing_listens_for_it() { let (dir, paths) = scratch(); - let _here = Here::start(&paths).unwrap(); + let _here = Here::start(&paths, false).unwrap(); // No socket, no token and no port are made for a server in the process. assert!(!paths.data_dir.join("serve.token").exists()); let made: Vec<_> = walk(dir.path()); From 61635a3adfd7851d240c6e97bc553a3fa67e9963 Mon Sep 17 00:00:00 2001 From: Helight Date: Sun, 15 Nov 2026 01:42:55 +0100 Subject: [PATCH 19/94] docs: one berth with its screens on every system The terminal UI, server, install, USB and building pages describe the screens over a server, the one inside berth on Linux, and berth on macOS and Windows. The screenshots are made again. --- .agents/skills/install-berth/SKILL.md | 2 +- .github/CONTRIBUTING.md | 6 +- .github/PULL_REQUEST_TEMPLATE.md | 2 +- README.md | 12 +-- .../docs/(guide)/deploy/deployments.mdx | 2 +- docs/content/docs/(guide)/deploy/index.mdx | 4 +- .../docs/(guide)/deploy/provisioners.mdx | 4 +- .../content/docs/(guide)/deploy/resources.mdx | 2 +- docs/content/docs/(guide)/deploy/ssh.mdx | 2 +- docs/content/docs/(guide)/deploy/usb.mdx | 10 +- docs/content/docs/(guide)/extend/plugins.mdx | 2 +- docs/content/docs/(guide)/extend/serve.mdx | 2 +- .../docs/(guide)/reference/building.mdx | 30 +++--- .../docs/(guide)/reference/profile.mdx | 4 +- docs/content/docs/(guide)/start/install.mdx | 34 +++--- .../docs/(guide)/start/quick-start.mdx | 2 +- docs/content/docs/(guide)/use/accounts.mdx | 2 +- docs/content/docs/(guide)/use/cli.mdx | 6 +- docs/content/docs/(guide)/use/moving.mdx | 2 +- docs/content/docs/(guide)/use/server.mdx | 66 ++++-------- docs/content/docs/(guide)/use/terminal-ui.mdx | 97 ++++++++++-------- docs/content/docs/(guide)/use/types.mdx | 6 +- docs/public/screens/accounts.png | Bin 180060 -> 190082 bytes docs/public/screens/features.png | Bin 208954 -> 215377 bytes docs/public/screens/home-plugins.png | Bin 301919 -> 325073 bytes docs/public/screens/home.png | Bin 81395 -> 115513 bytes docs/public/screens/install-cloud.png | Bin 209900 -> 123064 bytes docs/public/screens/overview.png | Bin 264603 -> 265494 bytes docs/public/screens/secrets.png | Bin 158786 -> 197939 bytes docs/public/screens/sessions.png | Bin 30392 -> 29960 bytes docs/public/screens/tasks.png | Bin 154889 -> 199160 bytes docs/public/screens/terminal.png | Bin 82928 -> 103756 bytes docs/scripts/screens.py | 26 +++-- recipes/README.md | 2 +- recipes/berth-server/README.md | 8 +- recipes/incus-host/README.md | 4 +- recipes/shared/berth-server.yml | 4 +- 37 files changed, 161 insertions(+), 182 deletions(-) diff --git a/.agents/skills/install-berth/SKILL.md b/.agents/skills/install-berth/SKILL.md index 3c5a273..067f21c 100644 --- a/.agents/skills/install-berth/SKILL.md +++ b/.agents/skills/install-berth/SKILL.md @@ -161,7 +161,7 @@ The recipes make a key on the first run and print it at the end. Give the user the key and the address, which `tailscale serve status` shows: 1. On their own machine they run `berth connect https://THIS-MACHINE.YOUR-TAILNET.ts.net` and enter the key. -2. Or they run `berth-remote --server https://THIS-MACHINE.YOUR-TAILNET.ts.net` with the key in `BERTH_SETUP_KEY`. It works on Windows and macOS too. +2. Or they run `berth --server https://THIS-MACHINE.YOUR-TAILNET.ts.net` with the key in `BERTH_SETUP_KEY`, which opens the screens. It works on Windows and macOS too. The key ends when they choose Done, or when `berth connect` has saved the token. diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 8ef6200..eda4ac5 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -109,9 +109,9 @@ A pull request is ready when: vale --minAlertLevel=warning "docs/content/docs/(guide)" README.md AGENTS.md ``` -- berth and berth-remote do the same things with a server's hosts. A feature - added to one is added to the other, with the shared part in - `crates/berth-tui`. +- The screens do everything through the API of a server, whichever it is. A + feature of theirs is an operation or an action of the server first, and + then their part in `crates/berth-page` and `crates/berth-tui`. - Commits follow [Conventional Commits](https://www.conventionalcommits.org/), with a short subject that says what changed. - The pull request links its issue and stays within it. Leave unrelated diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index b28a811..d38fad9 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -11,5 +11,5 @@ Issue: # - [ ] `ci/run.sh all` passes - [ ] Tried on a real host as well as in the containers (say which kind above) - [ ] Documentation is updated and Vale doesn't report warnings -- [ ] berth and berth-remote both have it, where it applies +- [ ] The screens do it through the API, and the client build for macOS and Windows still checks - [ ] I read every line of this change myself diff --git a/README.md b/README.md index 70257c8..e677992 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ installer on real hardware: **the installer erases the disk it selects.** ## Install -On Linux x86_64: +On Linux or macOS: ```bash curl -fsSL https://raw.githubusercontent.com/helightdev/berth/main/install.sh | sh @@ -37,15 +37,11 @@ Setting up hosts also needs `ssh`, `python3` and `ansible-playbook` on your machine. berth is also an image, `ghcr.io/helightdev/berth`, which runs its local API server by default. -`berth-remote` uses the hosts of a berth server from a terminal on Windows, -macOS or Linux: +On macOS and Windows berth uses the hosts of a berth server elsewhere, with the +same screens. `install.sh` installs it on macOS too, and on Windows: ```powershell -irm https://raw.githubusercontent.com/helightdev/berth/main/install.ps1 | iex # Windows -``` - -```bash -curl -fsSL https://raw.githubusercontent.com/helightdev/berth/main/install-remote.sh | sh # macOS, Linux +irm https://raw.githubusercontent.com/helightdev/berth/main/install.ps1 | iex ``` ## Quick start diff --git a/docs/content/docs/(guide)/deploy/deployments.mdx b/docs/content/docs/(guide)/deploy/deployments.mdx index ed174fe..08caa53 100644 --- a/docs/content/docs/(guide)/deploy/deployments.mdx +++ b/docs/content/docs/(guide)/deploy/deployments.mdx @@ -61,7 +61,7 @@ berth refuses before anything is made when a secret has no value, or when the na ### From the provisioner's page -The Hosts tab has the row **+ New compose project**, and the provisioner's page the action of that name, `new-deployment`, in the terminal UI and in [berth-remote](/docs/use/server#with-berth-remote). Both open a form laid out like a host's set-up, with the provisioner, the name, the Compose file, the secrets and the deployment's own arguments each on a row. Enter on a row edits it, and Enter on **Run** makes the deployment. The Compose file opens in a text editor that takes the whole screen. Ctrl+S keeps the file, and Esc leaves it as it was. The file is kept in berth's store, so no file on your machine is needed. Give the secrets as `NAME` or `NAME:VARIABLE`, separated by commas. The deployment is made as a job of the provisioner, and is listed on its page when the job ends. +The Hosts tab has the row **+ New compose project**, and the provisioner's page the action of that name, `new-deployment`, on every system. Both open a form laid out like a host's set-up, with the provisioner, the name, the Compose file, the secrets and the deployment's own arguments each on a row. Enter on a row edits it, and Enter on **Run** makes the deployment. The Compose file opens in a text editor that takes the whole screen. Ctrl+S keeps the file, and Esc leaves it as it was. The file is kept in berth's store, so no file on your machine is needed. Give the secrets as `NAME` or `NAME:VARIABLE`, separated by commas. The deployment is made as a job of the provisioner, and is listed on its page when the job ends. From the command line the action takes the same values: diff --git a/docs/content/docs/(guide)/deploy/index.mdx b/docs/content/docs/(guide)/deploy/index.mdx index e29a396..b81a57c 100644 --- a/docs/content/docs/(guide)/deploy/index.mdx +++ b/docs/content/docs/(guide)/deploy/index.mdx @@ -62,8 +62,8 @@ The set-up of a host has four tabs. Each tab depends only on the tabs before it. A setting shows only when the method and features it belongs to are chosen. Each of the first three tabs lists its own problems at the bottom. **Run** lists all of them under the name of their tab, and does not start while one is listed. Warnings, such as SSH being open to any address, are listed too but do not stop it. **Save** on Run, or Ctrl+S anywhere, saves the profile. -Builds run inside berth with their output and a progress bar. Esc cancels and Enter returns. Installing over SSH and *This machine or an inventory* continue in the normal terminal, where Ansible and SSH can ask for passwords, and return to berth when they finish. +What Run starts is a job of the server, whose output fills a panel. Esc hides the panel and the job goes on. It stays in the server's list. A password the job needs, such as a sudo password, is asked for in a dialog first. To provision this machine or an inventory, run the role [with Ansible directly](/docs/deploy/ansible). - The role installs services, changes the firewall and grants the agent sudo. With a blank inventory, *This machine or an inventory* provisions **the machine you are sitting at**. Only do that on a dedicated box. + The role installs services, changes the firewall and grants the agent sudo. Applied to `localhost`, it provisions **the machine you are sitting at**. Only do that on a dedicated box. diff --git a/docs/content/docs/(guide)/deploy/provisioners.mdx b/docs/content/docs/(guide)/deploy/provisioners.mdx index 425b391..286642f 100644 --- a/docs/content/docs/(guide)/deploy/provisioners.mdx +++ b/docs/content/docs/(guide)/deploy/provisioners.mdx @@ -151,7 +151,7 @@ berth provisioner docker run prune volumes=yes In a terminal, `run` prompts for a required argument you leave out. It puts the action's question first, unless `--yes` is given. An action that only reads, such as `images`, answers at once. One that changes something runs as a job and shows its output as it comes. Only one such job runs at a time for a provisioner. -In the terminal UI, the **Provisioners** tab of the home screen (`2`) lists the provisioners, and `a` registers one. Enter opens a page, which lists the actions in their groups and what berth made there, by kind. Enter on an action shows its question and then a dialog for its arguments. A job's output fills a panel. An argument of several lines, such as a Compose file, keeps the line breaks of what you paste. Each shows as `⏎`. Enter on something berth made opens its [resource's page](/docs/deploy/resources#in-the-terminal-ui), and Esc comes back. [berth-remote](/docs/use/server#with-berth-remote) has the same tab. +In the terminal UI, the **Provisioners** tab of the home screen (`2`) lists the provisioners, and `a` registers one. Enter opens a page, which lists the actions in their groups and what berth made there, by kind. Enter on an action shows its question and then a dialog for its arguments. A job's output fills a panel. An argument of several lines, such as a Compose file, keeps the line breaks of what you paste. Each shows as `⏎`. Enter on something berth made opens its [resource's page](/docs/deploy/resources#in-the-terminal-ui), and Esc comes back. ## Seed and apply @@ -247,7 +247,7 @@ In the terminal UI, choose **Create a machine** under **How To Install** on the | Settings | Under **Machine**, the resources it has, such as CPUs, memory and disk. Under **Provisioner Options**, its other arguments | | Run | **Create machine**, and every problem | -The first provisioner is chosen when the list arrives. There is no **Target** row. A created machine always has the target `cloud`. berth writes that into the profile before it creates the machine, on the command line as well. Enter on an argument changes it. A missing secret is a problem of the Install tab, and a bad resource value one of the Settings tab. **Create machine** on the Run tab asks once before it saves the profile and starts, and does not start while a problem is listed. The output is shown as it runs. [berth-remote](/docs/use/server#with-berth-remote) has the same tabs. +The first provisioner is chosen when the list arrives. There is no **Target** row. A created machine always has the target `cloud`. berth writes that into the profile before it creates the machine, on the command line as well. Enter on an argument changes it. A missing secret is a problem of the Install tab, and a bad resource value one of the Settings tab. **Create machine** on the Run tab asks once before it saves the profile and starts, and does not start while a problem is listed. The output is shown as it runs. The screens are the same with a [berth server](/docs/use/server) elsewhere. Only one thing runs at a time for a host. A second command for the same host is refused until the first ends. diff --git a/docs/content/docs/(guide)/deploy/resources.mdx b/docs/content/docs/(guide)/deploy/resources.mdx index 1eae969..b521c35 100644 --- a/docs/content/docs/(guide)/deploy/resources.mdx +++ b/docs/content/docs/(guide)/deploy/resources.mdx @@ -145,7 +145,7 @@ Compose project berth made with it An entry the provisioner lists with berth's labels, but that berth has no record of, is marked *no record of it*. berth does not remove it. -Enter on an entry opens the resource's page. It shows the resource's state and fields, and its actions in their groups. **Show its log** is there when its kind gives logs, and follows the log in a panel until you close it. Esc goes back to the provisioner's page. [berth-remote](/docs/use/server#with-berth-remote) has the same tab. +Enter on an entry opens the resource's page. It shows the resource's state and fields, and its actions in their groups. **Show its log** is there when its kind gives logs, and follows the log in a panel until you close it. Esc goes back to the provisioner's page. berth on macOS and Windows has the same tab ([On other systems](/docs/use/server#on-other-systems)). A host's machine is also on the host's Run tab, with its state and rows to start, stop and delete it. diff --git a/docs/content/docs/(guide)/deploy/ssh.mdx b/docs/content/docs/(guide)/deploy/ssh.mdx index f4959bf..85ec56f 100644 --- a/docs/content/docs/(guide)/deploy/ssh.mdx +++ b/docs/content/docs/(guide)/deploy/ssh.mdx @@ -34,7 +34,7 @@ On the host's **Install** tab, choose **Existing host over SSH**. The SSH rows f ### Give the address -Enter a hostname, an IP address or a `Host` alias from your SSH configuration in **SSH host**. Machines on your tailnet and aliases from `~/.ssh/config` are suggested. Accepting the host fills blank user and port fields from OpenSSH's effective configuration. +Enter a hostname, an IP address or a `Host` alias from your SSH configuration in **SSH host**. berth logs in from the machine its server runs on, with that machine's SSH configuration and its aliases. diff --git a/docs/content/docs/(guide)/deploy/usb.mdx b/docs/content/docs/(guide)/deploy/usb.mdx index 5e641ce..ab93a3b 100644 --- a/docs/content/docs/(guide)/deploy/usb.mdx +++ b/docs/content/docs/(guide)/deploy/usb.mdx @@ -57,21 +57,23 @@ Under **Installer** on **Settings**, set **Disk selection**. `auto`, the default ### Set up the network -Wired DHCP is always configured. To add Wi-Fi, switch **Wi-Fi** on under **Installer** and give the SSID and password. Networks saved in NetworkManager on your machine are suggested, and F5 unlocks their saved passwords so choosing one fills in its password. Leave the interface blank: the installer finds the wireless interface on the target and falls back to wired networking when there is none. +Wired DHCP is always configured. To add Wi-Fi, switch **Wi-Fi** on under **Installer** and give the SSID and password. Leave the interface blank: the installer finds the wireless interface on the target and falls back to wired networking when there is none. ### Choose the ISO -On **Run**, F4 on **Source ISO** downloads the current Ubuntu Server ISO and checks it against Ubuntu's `SHA256SUMS`. When you choose a file you already have, berth computes its SHA-256. Compare that with Ubuntu's signed `SHA256SUMS`, because a checksum taken from the file only proves it has not changed since. +**Source ISO** on **Run** is the Ubuntu Server ISO to build from, a path on the machine the server runs on. Left empty, the build downloads the current one and checks it against Ubuntu's `SHA256SUMS`. For a file you already have, put the SHA-256 from Ubuntu's signed `SHA256SUMS` in **ISO SHA256**. The build checks the file against it. ### Build and write -Choose the drive under **Then write to USB drive** on **Run**, or press `w` when the build has finished. Then press Enter on **Run · USB installer**. berth asks which drive to use when several are connected and asks you to confirm erasing it. It then asks for your `sudo` password and writes the image with a progress bar. +Press Enter on **Run · USB installer**. berth saves the profile and opens the host's overview with its action **Build the USB installer**. Its dialog takes the drive to write and your `sudo` password for writing it. The help of the drive lists the USB drives connected now. When one drive is connected, it's filled in. Leave the drive empty to build the ISO alone. The build and the writing run as a job, whose output fills a panel. + +The installer is built on the machine the server runs on, which writes one of its own drives. berth on your machine does it with the server inside berth, or with a `berth serve` of yours there. From another machine the action is listed as unavailable, with that reason. @@ -120,7 +122,7 @@ sudo systemctl start devbox-provision.service # start it again after a failu | `largest` / `smallest` | By capacity among eligible disks | | `ssd` / `hdd` | The only eligible non-rotating or rotating disk | -For `auto`, `model`, `path`, `largest` and `smallest`, `target_disk_ssd` narrows the candidates to `any`, `ssd` or `hdd`. Each mode needs exactly one final candidate, including when capacities tie. The Settings tab shows the fields of the chosen mode and offers the values in Suggestions. +For `auto`, `model`, `path`, `largest` and `smallest`, `target_disk_ssd` narrows the candidates to `any`, `ssd` or `hdd`. Each mode needs exactly one final candidate, including when capacities tie. The Settings tab shows the fields of the chosen mode. ```json title="In the host profile" { diff --git a/docs/content/docs/(guide)/extend/plugins.mdx b/docs/content/docs/(guide)/extend/plugins.mdx index bc52f48..0506249 100644 --- a/docs/content/docs/(guide)/extend/plugins.mdx +++ b/docs/content/docs/(guide)/extend/plugins.mdx @@ -76,7 +76,7 @@ A host keeps what it was applied with until it is applied again. After an update ### On a berth server -With a [berth server](/docs/use/server) set, the Plugins tab and `berth plugins` show the server's plugins and change those, which needs the role `admin` there. The server installs a package name or an `https://` address with its own npm and npm configuration. A `.tgz` or a folder on your machine is packed and sent to the server. berth-remote has the same tab, and `u` there sends a `.tgz` from its machine. +With a [berth server](/docs/use/server) set, the Plugins tab and `berth plugins` show the server's plugins and change those, which needs the role `admin` there. The server installs a package name or an `https://` address with its own npm and npm configuration. `berth plugins add` packs a `.tgz` or a folder on your machine and sends it to the server, and `u` on the tab sends a `.tgz` chosen in the file dialog. The server's hosts can have a new plugin's features as soon as it is installed. Its Ansible tasks run on the server when a host is applied, so installing is part of set-up. A server with `serve_setup off` takes it only on its own socket ([Closing set-up](/docs/extend/serve#closing-set-up)). diff --git a/docs/content/docs/(guide)/extend/serve.mdx b/docs/content/docs/(guide)/extend/serve.mdx index 66327a4..39fbdeb 100644 --- a/docs/content/docs/(guide)/extend/serve.mdx +++ b/docs/content/docs/(guide)/extend/serve.mdx @@ -166,7 +166,7 @@ curl -H "Authorization: Bearer $ACCESS_TOKEN" https://berth.example.ts.net/v1/ac # {"role":"operate","setup":true,"subject":"ada"} ``` -An access token is used like the server's token. It works as a bearer and as the WebSocket protocol. berth takes it as `--token` or `server_token`, and berth-remote as `BERTH_TOKEN` or when it asks. +An access token is used like the server's token. It works as a bearer and as the WebSocket protocol. berth takes it as `--token`, `BERTH_TOKEN` or `server_token`, and the screens when they ask for it. The server says which issuer it trusts at `/.well-known/oauth-protected-resource`, without a token. diff --git a/docs/content/docs/(guide)/reference/building.mdx b/docs/content/docs/(guide)/reference/building.mdx index b26c196..659791b 100644 --- a/docs/content/docs/(guide)/reference/building.mdx +++ b/docs/content/docs/(guide)/reference/building.mdx @@ -8,10 +8,10 @@ icon: Hammer | Folder | Holds | | --- | --- | -| `crates/berth/` | `berth`: the terminal UI, the commands and `berth serve` | -| `crates/berth-core/`, `berth-api/`, `berth-pty/`, `berth-tui/` | Shared libraries. `berth-tui` has the screens berth and `berth-remote` share | +| `crates/berth/` | `berth`. On Linux the commands and `berth serve`, in `src/local/`; on every system the screens | +| `crates/berth-page/` | The screens in a terminal, which do everything through the API of a server | +| `crates/berth-core/`, `berth-api/`, `berth-pty/`, `berth-tui/` | Shared libraries. `berth-tui` has the parts of the screens with no terminal in them | | `crates/vendor/` | The vendored `tui-input` crate | -| `crates/berth-page/`, `crates/berth-remote/` | `berth-remote` and its screens, for a berth server elsewhere | | `crates/berthd/`, `crates/box/` | `berthd` and `box`, built static for hosts | | `provision/ansible/` | The devbox role | | `provision/bootstrap/` | First-boot provisioning | @@ -125,37 +125,35 @@ GitHub Actions build on every push: | CI | The checks above and the end-to-end tests, both with `ci/run.sh`, and Vale. berth is built once, and the tests of each test host run in a job of their own | | Boot | The boot tests. `boot cloud` runs for changes to provisioning. `boot iso` runs once a week and when started by hand, because the installer takes longest and is used least | | Docs | The docs build, and publishing it to GitHub Pages from `main` | -| Build | The static `berth` for Linux x86_64 as artifact `berth-x86_64-linux`, the host programs as `host-programs-x86_64-linux`, `berth-remote` for each system as `berth-remote-`; the container image `ghcr.io/helightdev/berth`, tagged `edge` from `main` | +| Build | `berth` for each system as artifact `berth-`, the host programs as `host-programs-x86_64-linux`, and the container image `ghcr.io/helightdev/berth`, tagged `edge` from `main` | To release, push a tag such as `v0.3.0`, or create the release on GitHub's release page with a new tag. Build then: 1. Builds `berth`, `berthd` and `box` with the version of the tag, and checks that each says it. Runs `boot cloud`. When it fails, nothing is published. -2. Publishes the release with the archive of `berth`, the archives of `berth-remote`, their checksum files, `install.sh`, `install-remote.sh`, `install.ps1` and `VERSION`. A release made on the page gets the files added. +2. Publishes the release with the archives of `berth`, their checksum files, `install.sh`, `install.ps1` and `VERSION`. A release made on the page gets the files added. 3. Pushes the image tagged `0.3.0`, `0.3` and `latest`. 4. Opens a pull request that sets the version on `main` in `Cargo.toml`, `Cargo.lock` and `docs/openapi/`. Merge it once its checks have passed. -You don't edit a version anywhere. A build from a checkout says the version in `Cargo.toml`, which is that of the latest release. That way `berth update` never offers an older version. `berth`, `berthd`, `box` and `berth-remote` take the version from `berth_api::VERSION`. A release build sets it with `BERTH_BUILD_VERSION`, and `docker build` takes the same name as a build argument. +You don't edit a version anywhere. A build from a checkout says the version in `Cargo.toml`, which is that of the latest release. That way `berth update` never offers an older version. `berth`, `berthd` and `box` take the version from `berth_api::VERSION`. A release build sets it with `BERTH_BUILD_VERSION`, and `docker build` takes the same name as a build argument. A tag with a suffix, such as `v0.4.0-rc.1`, makes a pre-release. Its programs say `0.4.0-rc.1` and its image is tagged only with that. `main` stays as it is. The install scripts and `berth update` pass over pre-releases, and `BERTH_VERSION=v0.4.0-rc.1` installs one. -## berth-remote +## On every system -`berth-remote` is the client for a [berth server](/docs/use/server#with-berth-remote) in a terminal. Its screens are in `crates/berth-page/`, and `crates/berth-remote/` gives them a terminal through a `Device`, from `crates/berth-page/src/device.rs`. It covers the clipboard, links, files, what is kept and the portal's socket. - -It builds on the system it is for: +`berth` builds on Linux, macOS and Windows. Its installation, `berth serve` and the commands are compiled for Linux alone, in `crates/berth/src/local/`. On macOS and Windows it is the screens, `berth connect` and `berth update`, a client of a server elsewhere. The program builds on the system it is for: ```bash -cargo build --release --locked -p berth-remote +cargo build --release --locked -p berth ``` A release builds it on a runner of each system and checks that it says its version: | System | Target | Archive | | --- | --- | --- | -| Windows x86_64 | `x86_64-pc-windows-msvc`, with the C runtime linked in | `berth-remote-x86_64-windows.zip` | -| macOS on Apple silicon | `aarch64-apple-darwin` | `berth-remote-aarch64-macos.tar.gz` | -| macOS on Intel | `x86_64-apple-darwin` | `berth-remote-x86_64-macos.tar.gz` | -| Linux x86_64 | `x86_64-unknown-linux-musl` | `berth-remote-x86_64-linux.tar.gz` | -| Linux arm64 | `aarch64-unknown-linux-musl` | `berth-remote-aarch64-linux.tar.gz` | +| Linux x86_64 | `x86_64-unknown-linux-musl`, with berthd and box | `berth-x86_64-linux.tar.gz` | +| Linux arm64 | `aarch64-unknown-linux-musl`, with berthd and box for x86_64 hosts | `berth-aarch64-linux.tar.gz` | +| macOS on Apple silicon | `aarch64-apple-darwin` | `berth-aarch64-macos.tar.gz` | +| macOS on Intel | `x86_64-apple-darwin` | `berth-x86_64-macos.tar.gz` | +| Windows x86_64 | `x86_64-pc-windows-msvc`, with the C runtime linked in | `berth-x86_64-windows.zip` | On Windows, the build needs Rust from rustup and the Visual Studio build tools. diff --git a/docs/content/docs/(guide)/reference/profile.mdx b/docs/content/docs/(guide)/reference/profile.mdx index 830a657..49243c9 100644 --- a/docs/content/docs/(guide)/reference/profile.mdx +++ b/docs/content/docs/(guide)/reference/profile.mdx @@ -13,7 +13,7 @@ berth profile studio --set studio.json `--set -` reads the profile from standard input. berth checks it as the terminal UI reads a profile and saves it as it is. The profile of a berth server's host is saved on the server. -A profile can also stay in a file of its own. berth reads a host given as a path, such as `berth ./studio.json`, from that file and saves it there. +A profile can also stay in a file of its own. The commands read a host given as a path, such as `berth host ./studio.json`, from that file and save it there. The screens work with saved hosts: `berth profile studio --set studio.json` saves one from a file. Settings of the Ansible role go under `ansible_vars`, and how berth reaches and installs the host under `builder`. @@ -169,7 +169,7 @@ A profile of berth 0.5 or earlier names two fields differently: | `level`: `workstation` | No `type`, which means a workstation | | `profile` | `target` | -berth converts its stored profiles once, the profiles of a berth server's hosts with them. It reads the old names wherever a profile comes from: a file such as `berth ./studio.json`, `berth profile HOST --set FILE`, and the profile a host keeps, which [`berth adopt`](/docs/use/moving) reads. A file keeps the old names until you save it. berth writes `type` and `target` and nothing else, and the API of `berth serve` takes no other spelling. +berth converts its stored profiles once, the profiles of a berth server's hosts with them. It reads the old names wherever a profile comes from: a file such as `berth host ./studio.json`, `berth profile HOST --set FILE`, and the profile a host keeps, which [`berth adopt`](/docs/use/moving) reads. A file keeps the old names until you save it. berth writes `type` and `target` and nothing else, and the API of `berth serve` takes no other spelling. ## Install (`builder`) diff --git a/docs/content/docs/(guide)/start/install.mdx b/docs/content/docs/(guide)/start/install.mdx index 4f6e890..2bd2d90 100644 --- a/docs/content/docs/(guide)/start/install.mdx +++ b/docs/content/docs/(guide)/start/install.mdx @@ -4,16 +4,16 @@ description: Put the berth command on the machine you work from. It is one file. icon: Download --- -berth runs on Linux. The program contains everything it puts on a host, so installing it means placing one file on your `PATH`. On Windows and macOS, `berth-remote` uses the hosts of a berth server. +berth sets hosts up from Linux. The program contains everything it puts on a host, so installing it means placing one file on your `PATH`. On macOS and Windows the same program is a client of a [berth server](/docs/use/server) on another machine. - + -```bash title="Linux x86_64" +```bash title="Linux and macOS" curl -fsSL https://raw.githubusercontent.com/helightdev/berth/main/install.sh | sh ``` -The script downloads the latest release for Linux x86_64 from GitHub, checks it against its SHA-256 and installs it to `~/.local/bin/berth`. +The script downloads the latest release for this machine from GitHub, checks it against its SHA-256 and installs it to `~/.local/bin/berth`. Releases have it for Linux on x86_64 and arm64, and for macOS on Apple silicon and Intel. | Variable | Effect | | --- | --- | @@ -22,6 +22,15 @@ The script downloads the latest release for Linux x86_64 from GitHub, checks it On other architectures, build it with cargo. + + + +```powershell title="Windows, in PowerShell" +irm https://raw.githubusercontent.com/helightdev/berth/main/install.ps1 | iex +``` + +The script installs `berth.exe` to `%LOCALAPPDATA%\Programs\berth`, checked in the same way. `BERTH_INSTALL_DIR` and `BERTH_VERSION` work as for `install.sh`. See [From macOS or Windows](/docs/use/server#on-other-systems). + @@ -32,7 +41,7 @@ rustup target add x86_64-unknown-linux-musl cargo install --locked --git https://github.com/helightdev/berth berth ``` -From a checkout, `cargo install --locked --path crates/berth` does the same. +From a checkout, `cargo install --locked --path crates/berth` does the same. On macOS and Windows the build is the client alone, which only needs Rust. @@ -62,21 +71,6 @@ berth --server http://127.0.0.1:7777 --token "$(docker exec berth cat /data/bert See [A berth server](/docs/use/server). - - - -berth itself needs Linux. `berth-remote` is the client for a [berth server](/docs/use/server) on another machine, in a terminal. It runs on Windows, macOS and Linux: - -```powershell title="Windows, in PowerShell" -irm https://raw.githubusercontent.com/helightdev/berth/main/install.ps1 | iex -``` - -```bash title="macOS and Linux" -curl -fsSL https://raw.githubusercontent.com/helightdev/berth/main/install-remote.sh | sh -``` - -Each script downloads the latest release for this machine, checks it against its SHA-256 and installs it: to `%LOCALAPPDATA%\Programs\berth-remote` on Windows, and to `~/.local/bin/berth-remote` elsewhere. `BERTH_INSTALL_DIR` and `BERTH_VERSION` work as for `install.sh`. Releases have it for Windows x86_64, macOS on Apple silicon and Intel, and Linux x86_64 and arm64. See [With berth-remote](/docs/use/server#with-berth-remote). - diff --git a/docs/content/docs/(guide)/start/quick-start.mdx b/docs/content/docs/(guide)/start/quick-start.mdx index 406bc9a..9529904 100644 --- a/docs/content/docs/(guide)/start/quick-start.mdx +++ b/docs/content/docs/(guide)/start/quick-start.mdx @@ -53,7 +53,7 @@ Tab and Shift+Tab switch tabs too. Ctrl+S saves the profile at any point. ### Check the settings -**Settings** (key `3`) holds what has a default. That covers the *operator*, your account on the host, and the *agent* account the coding agents use. SSH keys found in `~/.ssh` and in ssh-agent are offered as suggestions (Right or F2). Each account can take several, and the operator also takes [the key of berth itself](/docs/reference/profile#the-key-of-berth-itself). `c` on that field copies it. +**Settings** (key `3`) holds what has a default. That covers the *operator*, your account on the host, and the *agent* account the coding agents use. Paste an SSH public key into an account's key row. Each account can take several, and the operator also takes [the key of berth itself](/docs/reference/profile#the-key-of-berth-itself). `c` on that field copies it. On a password hash field, F4 generates a password and stores its hash, and F5 hashes one you type. berth keeps a generated password in its store, and `berth credentials studio` shows it. diff --git a/docs/content/docs/(guide)/use/accounts.mdx b/docs/content/docs/(guide)/use/accounts.mdx index 3697e99..f5ed06b 100644 --- a/docs/content/docs/(guide)/use/accounts.mdx +++ b/docs/content/docs/(guide)/use/accounts.mdx @@ -143,7 +143,7 @@ The SSH host key of studio is not the one berth recorded: the machine was set up 1. berth makes a new key and stores it beside the current one as pending. 2. On each host that takes the key, it logs in and adds the new key. Once a login with the new key works, it removes the old one. -3. A host that does not answer stays pending. berth offers it both keys until then, and an apply gives the operator both. The Hosts tab marks it, in the terminal UI and in berth-remote. +3. A host that does not answer stays pending. berth offers it both keys until then, and an apply gives the operator both. The Hosts tab marks it. 4. When no host is pending, the new key replaces the old one, which is deleted. Running it again goes on where it stopped. With a berth server set, the rotation runs as a job on the server, and its output is shown as it comes. diff --git a/docs/content/docs/(guide)/use/cli.mdx b/docs/content/docs/(guide)/use/cli.mdx index 563a7b0..3589b5d 100644 --- a/docs/content/docs/(guide)/use/cli.mdx +++ b/docs/content/docs/(guide)/use/cli.mdx @@ -4,7 +4,7 @@ description: berth's commands, grouped by what they are for. Everything the term icon: Terminal --- -`berth --help` prints the full list. Commands that take a `HOST` accept a saved host's name or a path to a profile. +`berth --help` prints the full list. Commands that take a `HOST` accept a saved host's name or a path to a profile. The screens take a saved host's name. With a [berth server](/docs/use/server) set, by `--server` or the `server` setting, the host commands use the server's hosts. Installing, secrets and registries then stay on the server. @@ -14,8 +14,8 @@ With a [berth server](/docs/use/server) set, by `--server` or the `server` setti | Command | Does | | --- | --- | -| `berth` | The home screen | -| `berth HOST` | Open a host in the terminal UI; a new name starts a new host | +| `berth`, `berth ui` | The home screen ([The terminal UI](/docs/use/terminal-ui)) | +| `berth HOST`, `berth ui HOST` | Open a saved host in the terminal UI | | `berth list` | Saved hosts and their addresses | | `berth host add NAME ADDRESS [--user USER] [--port PORT] [--auth AUTH] [--type TYPE] [--no-contact]` | Save a machine that exists by its address, of the type `ssh` unless `--type` says otherwise, and install berth's key there ([Host types](/docs/use/types#adding-a-machine-that-exists)) | | `berth profile HOST` | The host's profile, as JSON on standard output | diff --git a/docs/content/docs/(guide)/use/moving.mdx b/docs/content/docs/(guide)/use/moving.mdx index 3dead46..23dd50f 100644 --- a/docs/content/docs/(guide)/use/moving.mdx +++ b/docs/content/docs/(guide)/use/moving.mdx @@ -122,4 +122,4 @@ berth moves everything it keeps under the old name to the new one, in one change With `--hostname`, the new name becomes the profile's hostname as well. The machine takes it at its next apply, which also writes the profile the host keeps with the new name. The name has to suit a hostname then: lower-case letters, digits and `-`. -berth refuses when a host has the new name already. A job that is creating the host's machine blocks the rename until that job ends. When a [berth server](/docs/use/server) keeps the host, the server renames it as a job. In berth-remote and over the server's API it's the host's action **Rename**, `rename`. +berth refuses when a host has the new name already. A job that is creating the host's machine blocks the rename until that job ends. When a [berth server](/docs/use/server) keeps the host, the server renames it as a job. On its overview and over the server's API it's the host's action **Rename**, `rename`. diff --git a/docs/content/docs/(guide)/use/server.mdx b/docs/content/docs/(guide)/use/server.mdx index 99d7c0e..8d20133 100644 --- a/docs/content/docs/(guide)/use/server.mdx +++ b/docs/content/docs/(guide)/use/server.mdx @@ -4,7 +4,7 @@ description: Run berth serve on one machine and use its hosts from berth on othe icon: ServerCog --- -A server machine keeps the hosts with their profiles and secrets, and runs `berth serve`. berth on another machine, such as your laptop, then uses that server's hosts instead of its own: the terminal UI, `berth list`, `berth run` and the other host commands go through the server's [portal](/docs/api/portal). +A server machine keeps the hosts with their profiles and secrets, and runs `berth serve`. berth on another machine, such as your laptop, then uses that server's hosts instead of its own: the [screens](/docs/use/terminal-ui), `berth list`, `berth run` and the other host commands go through the server's [portal](/docs/api/portal). On macOS and Windows berth is only that: a client of a server. ```text your laptop the server hosts @@ -83,14 +83,14 @@ It prints the key. On your own machine, give it to berth when it asks: berth connect https://berth.example.ts.net ``` -berth checks the key, collects the token and saves `server` and `server_token`. [berth-remote](#with-berth-remote) takes the key in `BERTH_SETUP_KEY` instead: +berth checks the key, collects the token and saves `server` and `server_token`. The screens take the key in `BERTH_SETUP_KEY` instead: ```bash read -rs BERTH_SETUP_KEY && export BERTH_SETUP_KEY -berth-remote --server https://berth.example.ts.net +berth --server https://berth.example.ts.net ``` -berth-remote signs in and shows the token, with the two `berth config` commands for berth. The key lasts 24 hours. It ends sooner when you choose **Done** there, or when `berth connect` has saved the token. Until then it's as good as the token, so keep it to yourself. A new key replaces the old one, and `berth setup-key --remove` ends it. A server with `serve_token` off has no token to hand out, so it doesn't make a key. +The screens sign in, keep the server and the token, and show the token. The key lasts 24 hours. It ends sooner when you choose **Done** there, or when `berth connect` has saved the token. Until then it's as good as the token, so keep it to yourself. A new key replaces the old one, and `berth setup-key --remove` ends it. A server with `serve_token` off has no token to hand out, so it doesn't make a key. | Address | Reaches | | --- | --- | @@ -98,76 +98,50 @@ berth-remote signs in and shows the token, with the two `berth config` commands | `http://HOST:PORT` | A server's port directly | | `unix:/path/to/serve.sock` | A `berth serve` on this machine, without a token | -## With berth-remote +## On other systems -berth runs on Linux. `berth-remote` uses the hosts of a server from a terminal on Windows, macOS or Linux. Install it on Windows in PowerShell: +berth on macOS and Windows is the client of a server: the screens, `berth connect` and `berth update`. Install it on Windows in PowerShell: ```powershell irm https://raw.githubusercontent.com/helightdev/berth/main/install.ps1 | iex ``` -On macOS or Linux: +On macOS: ```bash -curl -fsSL https://raw.githubusercontent.com/helightdev/berth/main/install-remote.sh | sh +curl -fsSL https://raw.githubusercontent.com/helightdev/berth/main/install.sh | sh ``` -Each script downloads the latest release for this machine, checks it against its SHA-256 and installs it, to `%LOCALAPPDATA%\Programs\berth-remote` on Windows and to `~/.local/bin` elsewhere. `BERTH_INSTALL_DIR` and `BERTH_VERSION` work as for `install.sh`. To download it by hand, take the archive for your system and its `.sha256` file from the [latest release](https://github.com/helightdev/berth/releases/latest). +Each script downloads the latest release for this machine, checks it against its SHA-256 and installs it, to `%LOCALAPPDATA%\Programs\berth` on Windows and to `~/.local/bin` on macOS. `BERTH_INSTALL_DIR` and `BERTH_VERSION` work as on Linux. To download it by hand, take the archive for your system and its `.sha256` file from the [latest release](https://github.com/helightdev/berth/releases/latest). -Then start it with the server's address. On Windows, use Windows Terminal or the console of Windows 10 or later. +Then connect it with a setup key, or start the screens and give the server's address and its token. On Windows, use Windows Terminal or the console of Windows 10 or later. ```bash -berth-remote --server https://berth.example.ts.net +berth connect https://berth.example.ts.net +berth ``` -It asks for the token and keeps the server and the token for the next run. A token never goes on the command line: +The screens keep the server and the token for the next run, in the folder of [berth's settings](/docs/use/terminal-ui#your-machine-and-the-server). A token never goes on the command line: -| Variable or option | Effect | +| Variable | Effect | | --- | --- | | `BERTH_TOKEN` | The token, so it isn't asked for | | `BERTH_SETUP_KEY` | A [setup key](#with-a-setup-key), which collects the token | -| `BERTH_SERVER` | The server, instead of `--server` | -| `--forget` | Remove the kept server and token, and keep nothing from this run | -| `BERTH_REMOTE_FILE` | The plugin package to send, where there is no file dialog | -| `--version` | Say the version | - -The server and the token are in `settings.json` in a folder of your own: - -| System | Folder | -| --- | --- | -| Windows | `%LOCALAPPDATA%\berth-remote`. Its access list lets in you, SYSTEM and the administrators | -| macOS | `~/Library/Application Support/berth-remote`, which only you can open | -| Linux | `~/.config/berth-remote`, or under `$XDG_CONFIG_HOME`, which only you can open | - -It talks to a server over `https` only with a certificate that the system or the Mozilla roots trust. It opens only `http` and `https` links, in the system's browser. +| `BERTH_SERVER` | The server, for this run | +| `BERTH_FILE` | The plugin package to send, where there is no file dialog | -berth-remote has the host list and the overview of each host, where actions run and sessions open in the terminal panel. **o** on the host list signs out. - -With the role `admin` it also sets the server up, with the same screens as the terminal UI: - -- **Provisioners**, **Settings**, **Registries**, **Secrets** and **Plugins** are tabs of the home screen. On **Plugins**, `u` opens the system's file dialog to send a `.tgz`: on Linux that of zenity or kdialog. A provisioner's page opens the pages of what berth made with it ([Resources](/docs/deploy/resources#in-the-terminal-ui)). -- **New host** starts a profile, and a host's overview opens its Install, Features, Settings and Run tabs. A new host opens on Install with **Create a machine** chosen, and offers only Create a machine, Cloud-init seed and Existing host over SSH. -- **Run** does what the chosen method does on the server. That is creating the machine, a cloud-init seed to copy, or an apply over SSH. The output is shown as it runs. -- **Install secrets and registry logins** sends a host what its profile names. - -Some keys differ from the terminal UI: - -| In berth-remote | Instead of | -| --- | --- | -| **Ctrl+Q** quits | `q` on the home screen | -| **Alt+Q** leaves a running session | `Ctrl+Q` | -| **g** generates and **p** takes a password to hash | `F4` and `F5` | +berth talks to a server over `https` only with a certificate that the system or the Mozilla roots trust. It opens only `http` and `https` links, in the system's browser. **o** on the host list signs out. A password the server makes up is shown once. The server keeps a copy in its store, and `berth credentials HOST` shows it again to an admin of the server. -What needs berth on your own machine stays in the terminal UI. That is the USB installer and the container image, values read from your local keys, and sending a plugin's folder. +What works with the server's own machine is offered there only. That is the USB installer, which writes a drive of that machine, and the settings that aren't open to the network. Elsewhere the screens list them as unavailable, with the reason. ## What works from another machine | Works through the server | Stays on a machine with the host's profile | | --- | --- | -| `berth list`, and the host list of the home screen and of berth-remote | USB installers: `berth iso` and writing a drive | -| The host's overview with its actions, sessions and terminal panel | Applying to this machine or an inventory, and container images | +| `berth list`, and the host list of the home screen | USB installers: `berth iso` and writing a drive, which the screens there do too | +| The host's overview with its actions, sessions and terminal panel | Container images and applying to an inventory, from the source with `docker compose` and `ansible-playbook` | | The host commands such as `berth run`, `exec`, `attach` and `channel` | Publishing a release or an image by hand | | The set-up tabs of a host, new hosts, and `berth remove` | | | `berth profile` and `berth credentials` | | diff --git a/docs/content/docs/(guide)/use/terminal-ui.mdx b/docs/content/docs/(guide)/use/terminal-ui.mdx index 46ea315..7a8e3bb 100644 --- a/docs/content/docs/(guide)/use/terminal-ui.mdx +++ b/docs/content/docs/(guide)/use/terminal-ui.mdx @@ -1,28 +1,44 @@ --- title: The terminal UI -description: The screens of berth's terminal UI and the keys that move between them. +description: The screens of berth, the server they use, and the keys that move between them. icon: AppWindow --- -`berth` with no arguments opens the home screen. `berth NAME` opens a host directly: its overview when it has an SSH address, its set-up tabs when it is new. +`berth` with no arguments opens the home screen. `berth NAME` opens a host directly, on its overview. `berth ui` and `berth ui NAME` do the same. ```bash berth # home screen: pick a host or create one berth studio # open a host directly ``` +The screens do everything through the API of a berth server, the same one on every system. Which server that is: + +| When | The screens use | +| --- | --- | +| `--server`, or `BERTH_SERVER` is set | That server, for this run | +| A server is kept, by `berth connect` or `berth config server` | That server ([A berth server](/docs/use/server)) | +| Neither, and a `berth serve` of yours runs on this machine | Its socket, with no token | +| Neither, on Linux | A server inside berth itself, for as long as the screens are open | +| Neither, on macOS or Windows | The Connect dialog, for a server's address and its token | + +The server inside berth is the one `berth serve` runs, served to that berth alone over pipes in memory. It's yours, so it takes no token. It doesn't take in the hosts' channels, which is what `berth serve` is for. A host whose sudo asks for a password has it asked for in the terminal before the screens open. + +A job that still runs when you quit, such as an apply, would end with berth. berth waits for it instead and says so. Ctrl+C there stops it unfinished. With `berth serve` running, the screens use it, and its jobs go on after they close. + ## The home screen The home screen has six tabs, switched with the number keys, or with Tab and Shift+Tab in this order. | Tab | Holds | | --- | --- | -| `1` Hosts | The saved hosts and their addresses. With a berth server, a dot shows whether each host answered the server, and the Information panel says why not. A host that still takes the old key of a [key rotation](/docs/use/accounts#rekeying) is marked `key rotation pending`. `n` creates one, `d` makes the selected one the default, `r` asks the server again, or reads the saved hosts again when there is no server | -| `2` Provisioners | The provisioners of the plugins, and whether each can be used here. Enter opens the page of one, with how it is and what berth made with it, grouped by kind. Enter on one of its actions runs it. Enter on something it made opens that [resource's page](/docs/deploy/resources#in-the-terminal-ui), with its state, its actions and its log. Esc goes back a page ([Provisioners](/docs/deploy/provisioners#a-provisioners-page)). With a server set, the server's | -| `3` Settings | The settings of `berth config` and the SSH keys of berth's key ring to copy. With a server, the `tailnet_` settings are the server's | +| `1` Hosts | The server's hosts and their addresses, with a dot for whether each answered and why not. A host that still takes the old key of a [key rotation](/docs/use/accounts#rekeying) is marked `key rotation pending`. `n` creates one, `d` makes the selected one the default, `x` twice removes one, `r` asks again | +| `2` Provisioners | The provisioners of the plugins, and whether each can be used. Enter opens the page of one, with how it is and what berth made with it, grouped by kind. Enter on one of its actions runs it. Enter on something it made opens that [resource's page](/docs/deploy/resources#in-the-terminal-ui), with its state, its actions and its log. Esc goes back a page ([Provisioners](/docs/deploy/provisioners#a-provisioners-page)) | +| `3` Settings | The settings of `berth config` and the SSH keys of the server's key ring to copy. Over the network, only some settings change there; on the server's own machine, every one | | `4` Registries | npm, Docker, file and Nexus registries ([Registries](/docs/use/registries)) | -| `5` Secrets | Secret values, kept in berth's store ([Secrets](/docs/use/secrets)) | -| `6` Plugins | Built-in and installed plugins, and adding, updating and removing your own ([Plugins](/docs/extend/plugins#updating-a-plugin)). With a server set, the server's | +| `5` Secrets | Secret values, kept in the server's store ([Secrets](/docs/use/secrets)) | +| `6` Plugins | Built-in and installed plugins, and adding, updating and removing your own ([Plugins](/docs/extend/plugins#updating-a-plugin)) | + +The tabs after Hosts are for the role `admin`, which you have on your own machine. @@ -37,7 +53,17 @@ Each tab depends only on the tabs before it. Install holds what you have to choo | `1` Install | How to install, with the target (not for a created machine, which is always `cloud`), the provisioner and its required arguments, the SSH address, the hostname and Tailscale | | `2` Features | The coding agents and T3 Code, with tool categories, browsers, graphics, Cockpit, Docker on the host and plugin features | | `3` Settings | Everything with a default. See the list below | -| `4` Run | The last files for the method, every problem grouped by tab, warnings, and the Run, Create machine and Save buttons | +| `4` Run | The last fields for the method, every problem grouped by tab, warnings, and the Run, Create machine and Save buttons | + +The ways to install a host: + +| Method | Run does, on the server | +| --- | --- | +| Create a machine | Has a provisioner create it, and sets it up ([Provisioners](/docs/deploy/provisioners)) | +| USB installer | Builds the unattended installer and writes it to a USB drive, on the server's own machine ([USB installer](/docs/deploy/usb)) | +| Cloud-init seed | Renders the seed to paste into a provider's user data field ([Cloud](/docs/deploy/cloud)) | +| Existing host over SSH | Applies the profile over SSH, or installs the controller alone on a managed host | +| Existing host, SSH only | Saves the host, which berth only logs in to ([Host types](/docs/use/types)) | The Settings tab has these groups, in this order: @@ -45,14 +71,14 @@ The Settings tab has these groups, in this order: | --- | --- | --- | | Machine | The provisioner's CPUs, memory and disk | Create a machine | | Provisioner Options | The provisioner's other arguments | Create a machine | -| Operator Account, Agent Account | The accounts. Container image has only the agent's username | Every method | -| Access | SSH hardening, and Recovery SSH CIDR | Every method but Container image. No recovery CIDR for Create a machine | +| Operator Account, Agent Account | The accounts | Every method | +| Access | SSH hardening, and Recovery SSH CIDR | Every method. No recovery CIDR for Create a machine | | Registries, Secrets | The logins and secrets the host gets | Every method | -| Desktop | Desktop size | Every method but Container image | +| Desktop | Desktop size | Every method | | Installer | Disk selection, keyboard layout and Wi-Fi | USB installer | | Release | Where the release is published | Cloud-init seed | -A row shows only when the method and features it belongs to are chosen. Each of the first three tabs lists its own problems at the bottom. Run lists all of them, grouped by tab, and does not start while one is listed. +A row shows only when the method and features it belongs to are chosen. Each of the first three tabs lists its own problems at the bottom. Run lists all of them, grouped by tab, and doesn't start while one is listed. The **Information** panel on the right explains the selected row. **Apply this configuration** on the overview sends changes to a running host. @@ -64,47 +90,30 @@ The **Information** panel on the right explains the selected row. **Apply this c | --- | --- | | Up, Down, Enter | Select a row. Enter edits the row or runs it | | Tab, Shift+Tab, number keys | Next or previous tab, or a tab by number; also accepts the current edit | -| Right or F2, Left | Into the *Suggestions* list (detected keys, hosts, choices) and back | -| F3 | Browse for a file on path fields; Ctrl+Enter picks the directory itself | -| F4 | Generate a value, such as a hostname, a password hash or a Tailscale key, or download the ISO | -| F5 | Type a password and store its hash; on Wi-Fi fields, unlock the saved passwords | +| F4 | Generate a value, such as a hostname, a password hash or a Tailscale key | +| F5 | Type a password and store its hash | | c | On a key of the key ring, such as **This berth's SSH key**, copy its public half to the clipboard | | Alt+R | In a panel, show its links as QR codes to scan with a phone. Left and Right go to the other links, any other key closes it. Where Alt+R is taken by other software, click its hint at the bottom of the panel | +| Ctrl+O | Copy the text of the field being edited | | Ctrl+S | Save the profile, as **Save** on the Run tab does | | Ctrl+U, Esc | Clear the field being edited, cancel the edit | | x or Delete | Unset the selected text, path or secret field | | q or Esc | From set-up back to the overview, from there to the home screen; asks again when there are unsaved changes | +| q | On the hosts of the home screen, quit | +| Ctrl+Q | In a session, leave it running. Anywhere else, quit | -Tabs, rows, buttons and suggestions take mouse clicks, and lists scroll with the wheel. +Tabs, rows and buttons take mouse clicks, and lists scroll with the wheel. On Plugins, `u` opens the system's file dialog to send a `.tgz` to the server. On Linux that is zenity's or kdialog's; without one, `BERTH_FILE` names the package. -## What berth reads from your machine +## Your machine and the server -berth fills suggestions and blank fields from what it finds locally. It reads, and never changes: +The screens take what they show from the server. Of your machine they use the clipboard and the file you choose to send. The server reads what its own machine has: its keys, its plugins and its USB drives. A path in a profile, such as the Ubuntu ISO of a USB installer, is a path on the server's machine. - - +The server and its token are kept as the settings `server` and `server_token`, in `config.json` of berth's folder of settings. Only you can read the file. -Every `.pub` file in `~/.ssh`, keys held by ssh-agent, the ways to log in with the keys of berth's key ring, and `Host` aliases from the SSH configuration, including `Include` files. - - - - -The Linux machines in `tailscale status`, as address suggestions. With the secret `tailnet_api_key` or `TS_API_KEY` set, F4 on the Tailscale key field creates a one-use enrollment key through the API of Tailscale or of the Headscale server in `tailnet_login_server`. - - - - -The names of networks saved in NetworkManager. Their passwords only after F5 on a Wi-Fi field, which asks for your password, passes it to `sudo` once and keeps that authorisation alive while berth runs. berth never asks for it on its own. - - - - -Connected USB disks, for **Then write to USB drive**. - - - - -Blank fields can be filled from `DEVBOX_HOSTNAME`, `DEVBOX_TARGET_DISK_SERIAL`, `DEVBOX_RELEASE_URL`, `DEVBOX_ISO` and `DEVBOX_INVENTORY`. +| System | Folder | +| --- | --- | +| Linux | `~/.config/berth`, or under `$XDG_CONFIG_HOME` | +| macOS | `~/Library/Application Support/berth` | +| Windows | `%LOCALAPPDATA%\berth`. Its access list lets in you, SYSTEM and the administrators | - - +The first time berth starts its screens it takes in the server and token that `berth-remote` kept, and removes that program's file. diff --git a/docs/content/docs/(guide)/use/types.mdx b/docs/content/docs/(guide)/use/types.mdx index ef76c54..8504e7d 100644 --- a/docs/content/docs/(guide)/use/types.mdx +++ b/docs/content/docs/(guide)/use/types.mdx @@ -29,7 +29,7 @@ A profile of berth 0.5 or earlier calls the type `level`, with the values `reach | Apply, roll-out, cloud seed, USB installer | no | no | yes | | Desktop and access links | no | no | yes | -The terminal UI, berth-remote, the commands and the API all use the same check in berth. An action the type rules out is still listed, as unavailable, with the reason and what changes the type. Asked for anyway, the server refuses it with `501 not_available`. A roll-out leaves hosts that aren't workstations and says how many it left. +The screens, the commands and the API all use the same check in berth. An action the type rules out is still listed, as unavailable, with the reason and what changes the type. Asked for anyway, the server refuses it with `501 not_available`. A roll-out leaves hosts that aren't workstations and says how many it left. ## Adding a machine that exists @@ -65,7 +65,7 @@ berth host type dock managed `berth host type HOST TYPE` only changes the profile here. A host's page says the same when its controller reports more than its profile says. berth refuses to install the controller alone on a host that is a workstation, whatever its profile here says. It asks the host's controller first, and the playbook checks the host's own record and the profile it keeps. -In the terminal UI, create a host on the home screen and choose **Existing host, SSH only** on the **Install** tab. The address and the login are all the set-up asks for, and **Run** saves the host. For a managed host, choose **Existing host over SSH** and set **Type** to `managed`. **Run** then installs the controller. berth-remote does the same through the server. +In the terminal UI, create a host on the home screen and choose **Existing host, SSH only** on the **Install** tab. The address and the login are all the set-up asks for, and **Run** saves the host. For a managed host, choose **Existing host over SSH** and set **Type** to `managed`. **Run** then installs the controller. Over the API, `hosts.save` takes a profile with only the type and `access`: @@ -100,7 +100,7 @@ berth host install dock The controller is berthd and box with the files they read, from the same part of the role that a full apply runs. Nothing else of a workstation is installed: no accounts, desktop, agents or plugins. The SSH user is the account sessions run as, and its home is where the file calls may go. The host's type becomes `managed`, and its actions are status, update, reboot and secrets. -The same is the host's action **Install the controller** on its overview, in berth-remote and over the API as `install-controller`. On a managed host it's called **Update the controller**: run it after updating berth, as berth's own version is all such a host is compared with. A workstation's controller comes with applying its configuration, so the action is not offered there. +The same is the host's action **Install the controller** on its overview, and over the API as `install-controller`. On a managed host it's called **Update the controller**: run it after updating berth, as berth's own version is all such a host is compared with. A workstation's controller comes with applying its configuration, so the action is not offered there. berth also refuses it on a host that is a workstation whatever its profile here says. It asks the host's controller first. The role checks again on the host before it changes anything. It stops when the host's record says workstation. It also stops when berthd there serves an account other than the SSH user. Installing the controller alone on such a host would take the workstation's controller apart. The overview and `berth actions` say when a host is more than its profile, and how to adopt it. diff --git a/docs/public/screens/accounts.png b/docs/public/screens/accounts.png index bcda744f572adfaa79fb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