diff --git a/Cargo.lock b/Cargo.lock index 7c2a584..d8e8d81 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -697,6 +697,18 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "console" +version = "0.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" +dependencies = [ + "encode_unicode", + "libc", + "unicode-width", + "windows-sys 0.61.2", +] + [[package]] name = "const-oid" version = "0.6.2" @@ -1210,6 +1222,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + [[package]] name = "equivalent" version = "1.0.3" @@ -2055,6 +2073,20 @@ dependencies = [ "serde_core", ] +[[package]] +name = "indicatif" +version = "0.18.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9433806cd6b4ec1aba79c021c7e4c58fb4c3b9977c085062e611ac929998fb0c" +dependencies = [ + "console", + "portable-atomic", + "unicode-width", + "unit-prefix", + "vt100", + "web-time", +] + [[package]] name = "inout" version = "0.1.4" @@ -3873,6 +3905,7 @@ dependencies = [ "futures-util", "hex", "humantime", + "indicatif", "nix", "openidconnect", "rand 0.9.5", @@ -4532,12 +4565,24 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + [[package]] name = "unicode-xid" version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "unit-prefix" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3" + [[package]] name = "universal-hash" version = "0.5.1" @@ -4620,6 +4665,27 @@ dependencies = [ "nix", ] +[[package]] +name = "vt100" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "054ff75fb8fa83e609e685106df4faeffdf3a735d3c74ebce97ec557d5d36fd9" +dependencies = [ + "itoa", + "unicode-width", + "vte", +] + +[[package]] +name = "vte" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5924018406ce0063cd67f8e008104968b74b563ee1b85dde3ed1f7cb87d3dbd" +dependencies = [ + "arrayvec", + "memchr", +] + [[package]] name = "walkdir" version = "2.5.1" diff --git a/Cargo.toml b/Cargo.toml index b77b257..4dcc737 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ clap = { version = "4", features = ["derive", "env"] } futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] } hex = "0.4" humantime = "2" +indicatif = "0.18" # Already a dependency of `tokio-vsock` nix = { version = "0.31", default-features = false, features = ["signal", "user"] } openidconnect = "4.1" @@ -40,4 +41,6 @@ web-push = { version = "0.11", default-features = false } x25519-dalek = { version = "3.0.0", features = ["static_secrets"] } [dev-dependencies] +# Its in-memory terminal, for testing what `slop` draws +indicatif = { version = "0.18", features = ["in_memory"] } tempfile = "3" diff --git a/docs/architecture.md b/docs/architecture.md index e713431..ea1b92e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -87,7 +87,39 @@ flowchart TB `slop-broker builder` (`builder::worker`) is the forced command of the builder user's `authorized_keys`, so every SSH connection from the broker runs it once: it reads one `BuilderRequest` on stdin, answers on stdout, and exits. Its log goes to stderr, which the broker -passes on to the requester, if one is waiting. It holds nothing but a read-only Git key. +passes on to the requester, if one is waiting. A build also sends progress frames on stdout before +its answer. It holds nothing but a read-only Git key. + +### Progress + +`src/progress.rs` turns Nix's `--log-format internal-json` into `Progress` messages, one `Phase` at +a time: the evaluation and the build, then a copy, comparison and activation for each node, or the push to the cache. + +- `NixLog` follows Nix's activities as Nix's own progress bar does, and returns the text Nix would + have shown: errors and warnings, plus build logs when the request asks for them. +- Totals of derivations and paths come from Nix's `these N derivations will be built` messages + when there are some; the totals its activities expect move around while it works out what to do. +- The builder sends `Reply::Progress` frames at most once a second, then `Reply::Done` with its + answer. `Reply::Evaluated` ends the evaluation, when Nix starts its first build, fetch or copy + (or, with nothing to build, when it's finished). The broker's own copies read Nix's log with + `exec::run_nix`. +- `Reporter` sends a phase's progress to the requester when it starts, at most once a second while + it runs, and when it ends. +- `Phases` keeps the latest progress of each phase of one request, and works out how each node + is getting on (`NodeRow`) and one bar for the whole request. `slop` and the web app both show + progress from it. +- `runs::Runs` keeps the latest progress of each phase of requests that build, from the build on; + `exec::Output` records each `Progress` message it carries for a tracked request. The web app reads + it, and the request's `finished` or `failed` audit event keeps its phases. +- The web app shows a request's progress (`templates/progress.html`) in its page's region, and + the running requests (`templates/running.html`) in a region of the main page, both kept current + by the page's event stream (`web/events.rs`). The bars are `` elements, since the + content security policy allows no inline styles. +- `slop` shows it with `terminal::Board`. On a terminal, `indicatif` draws bars below other + output: one for each running phase that isn't about a node, and one for each node through its + copy, comparison and activation, from `Phases` like the web app's rows. The bars hide while + other output is mid-line, which they would overwrite. Otherwise (for agents) a running phase gets a plain line every 30 seconds, and one + when it ends. ```mermaid flowchart LR @@ -135,9 +167,12 @@ What each request runs, and whose code, decides whether it needs an approval fir | `src/detail.rs` | What approvers see of a request (`Detail`: fields, tables, lists, text) and its text rendering | | `src/ops/ssh.rs`, `src/ops/query.rs`, `src/ops/deploy.rs`, `src/ops/build.rs` | Operations; `deploy.rs` also parses the comparison script, `src/ops/inspect.sh` | | `src/ops/secret.rs`, `src/ops/secret/format.rs` | Age secrets: what approvers see, encryption, generated values; env and JSON fields | +| `src/progress.rs` | Progress of builds, copies and deploys: Nix's JSON log read into counts (`NixLog`), the `Progress` messages (`Reporter`), and a request's phases (`Phases`) | +| `src/terminal.rs` | How `slop` shows progress: bars on a terminal, with `indicatif`, or plain lines (`Board`) | | `src/builder.rs` | Both sides of the builder: the worker (forced command) and the broker's client; also reads secrets and deploy nodes on the main branch | | `src/approve.rs` | Approver connections (many requests each), `slop-approve` client, `approve()` used by every approver | | `src/remote.rs` | SSH transport: the `slop-broker remote` forced command, the remote socket, `connect` for both clients, and `address` (environment, then `~/.config/slop/config.toml`, then the default) | +| `src/runs.rs` | Requests that build, copy or activate, with their phases' latest progress, while they run | | `src/audit.rs` | Typed audit events: a text line to the journal, a JSON line to the file; `tail` for `slop-approve log` | | `src/bin/slop-broker.rs` | Daemon (`serve`); `slop-approve` when run under that name | | `src/bin/slop.rs` | Agent client; `slop guide` prints `slop-tools.md` | @@ -248,7 +283,7 @@ sequenceDiagram B->>A: "builder" request: commits and diff A-->>B: once / lease B->>G: Build(targets) - G-->>S: build logs + G-->>S: progress (build logs with --logs) G-->>B: built profiles B->>N: copy closures, compare (read-only) B->>A: "deploy" request: packages, units, files @@ -334,8 +369,8 @@ struct Request { enum Operation { Ssh { destination: Destination, command: Vec, stdin: Option }, Query { destination: Destination, query: Query }, - Deploy { targets: Vec, commit: CommitId, boot: bool }, - Build { attrs: Vec, commit: CommitId }, + Deploy { targets: Vec, commit: CommitId, boot: bool, logs: bool }, + Build { attrs: Vec, commit: CommitId, logs: bool }, Secret(SecretOp), Requests, } @@ -368,6 +403,7 @@ enum ServerMessage { Pending { id: String, summary: String }, Approved { by: ApprovedBy, stdin: bool }, // ApprovedBy: Policy, Lease or Approver Info(String), + Progress(Progress), // src/progress.rs Stdout(bytes), Stderr(bytes), // terminal: @@ -423,7 +459,8 @@ struct PendingInfo { // nothing after it is read ahead; either protocol above follows. struct Hello { role: Role, name: String } // Role: Requester or Approver -// One request on the builder's stdin, one answer on its stdout; logs on stderr. +// One request on the builder's stdin; on its stdout, Reply::Progress frames for a build, then +// Reply::Done with the answer, encoded; logs on stderr. enum BuilderRequest { Describe(CommitId), // -> Description { log, stat, diff, on_branch } Build(BuildRequest), // -> BuildResult { profiles, outputs } @@ -510,7 +547,8 @@ Every process the broker starts goes through `src/exec.rs`: |---|---|---| | `exec::run` | Operations the requester watches | The given stdin, or none; stdout and stderr as frames | | `exec::capture` | The broker's own steps | Captured, none of the requester's stdio | -| `exec::run_prefixed` | Several nodes sharing the output (deploy copies and activations) | No stdin; each line prefixed with its node | +| `exec::run_prefixed` | Several nodes sharing the output (deploy activations) | No stdin; each line prefixed with its node | +| `exec::run_nix` | `nix copy` to nodes and the cache | As `run_prefixed`, with Nix's JSON log read into progress | - Each process runs in its own process group. On cancellation the group gets `SIGTERM`, then `SIGKILL` after five seconds. diff --git a/docs/demo.md b/docs/demo.md index 98cde2c..60e1a07 100644 --- a/docs/demo.md +++ b/docs/demo.md @@ -151,13 +151,24 @@ rage -d -i .devenv/state/slop-demo/dev-age.key <(git -C .devenv/state/slop-demo/ ### Deploys The repository's `flake.nix` has a deploy-rs node, `box`, with one profile, `demo`, deployed as -root: a small app whose activation writes its version to `/run/demo/version`. Its `nixpkgs` is -locked to this repository's, so the builder has it already, and it uses nixpkgs' build of -deploy-rs, so a build takes moments. In `~/repo` on the agents' VM: +root: an app whose activation writes its version to `/run/demo/version`. + +- **Its `nixpkgs`** is locked to this repository's, so the builder has it already, and it uses + nixpkgs' build of deploy-rs, so nothing big needs building. +- **Its parts** stand in for a bigger build, so the progress in `slop` and the web app has + something to show. There are `layers` of `width` parts, and each layer builds once the one + below it has, so a build takes about a minute and a half. Each part takes 15 to 30 seconds and + adds a few MiB to copy. +- **Their contents** follow from `version` alone, and the builder keeps what it built in the + host's store. So a version that's been built before only evaluates, and copies what the box VM + doesn't have. A version that hasn't been built yet rebuilds every part, so `demo-bump` (in + [`bump.nix`](../nix/demo/bump.nix)) sets a new one each time, from the time unless you give + one, and pushes it on a branch of its own. + +In `~/repo` on the agents' VM: ```sh -sed -i 's/version = "1.0"/version = "1.1"/' flake.nix -git switch -c bump && git commit -am "Bump the app" && git push origin bump +demo-bump slop deploy box ` on the host moves it, standing in for a person mergin - `secrets/app.env.age` holds `DB_USER` and `DB_PASSWORD`; `secrets/wg.key.age` is a WireGuard private key, as a whole file. -`flake.nix` has a deploy-rs node, `box`, with one profile, `demo`: a small app whose activation -writes its version to `/run/demo/version`. +`flake.nix` has a deploy-rs node, `box`, with one profile, `demo`: an app whose activation writes +its version to `/run/demo/version`. Its parts take a while to build and add a few MiB each, so +builds and copies show their progress. They follow from the version, so only a version that +hasn't been built before rebuilds them. Change secrets with `slop secret` (`slop guide` explains it), commit, and push a branch. Deploy a pushed commit with `slop deploy box`. diff --git a/nix/demo/repo/flake.nix b/nix/demo/repo/flake.nix index df7f8cc..cdf4c21 100644 --- a/nix/demo/repo/flake.nix +++ b/nix/demo/repo/flake.nix @@ -13,13 +13,45 @@ # Change this, push a branch and `slop deploy box`: the approval shows the version change version = "1.0"; + # Stand-ins for a bigger build, so its progress and the copy's have something to show: + # `layers` of `width` parts, each layer built once the one before it is, like a chain of + # dependencies. Each part takes 15 to 30 seconds and adds a few MiB to copy. Their contents + # follow from the version alone, so a version that's been built before is already in the + # builder's store, and only a new one rebuilds them all. + layers = 3; + width = 4; + partCount = layers * width; + + # Layer `n`, whose parts each depend on all of the layer below + layer = n: below: builtins.genList + (i: + let + index = n * width + i; + name = "demo-part-${toString index}-${version}"; + size = 2 + pkgs.lib.mod index 6; + in + pkgs.runCommand name { inherit below; } '' + for step in 1 2 3 4 5 6; do + echo "part ${toString index}: step $step" + sleep ${toString (3 + pkgs.lib.mod index 3)} + done + head -c ${toString size}M < <(yes "demo app ${version}, part ${toString index}") > $out + '') + width; + layered = builtins.foldl' + (built: n: let next = layer n built.last; in { all = built.all ++ next; last = next; }) + { all = [ ]; last = [ ]; } + (builtins.genList (n: n) layers); + parts = layered.all; + app = pkgs.writeTextFile { name = "demo-app-${version}"; destination = "/bin/demo-app"; executable = true; text = '' #!${pkgs.runtimeShell} - echo "demo app ${version}" + # Its parts: ${toString parts} + echo "demo app ${version}, in ${toString partCount} parts" ''; }; diff --git a/nix/vm-test.nix b/nix/vm-test.nix index 96d6ccc..417afe7 100644 --- a/nix/vm-test.nix +++ b/nix/vm-test.nix @@ -307,7 +307,8 @@ pkgs.testers.runNixOSTest { assert out.strip() == system, out # Deploys build, copy, compare and activate, on both nodes at once, though their profiles are - # the same derivation. Copying to `box` fills a store of its own: the profile and busybox. + # the same derivation, showing progress rather than build logs, which only come with --logs. + # Copying to `box` fills a store of its own: the profile and busybox. box.wait_for_unit("sshd.service") repository = "/var/lib/slop-test-repository" one = machine.succeed(f"cat {repository}/commit-one").strip() @@ -316,7 +317,19 @@ pkgs.testers.runNixOSTest { status, out = try_slop(f"deploy box.system local.system --commit {one}") print(out) assert status == 0, (status, out) - for line in ["[box.system] activating one", "[local.system] activating one"]: + assert "build line one" not in out and "warning:" not in out, out + assert "\x1b" not in out, repr(out) + expected = [ + "slop: evaluated in", + "slop: built: 1 derivation in", + "slop: copied to box: 2 paths (", + "slop: copied to local in", + "slop: compared on box", + "[box.system] activating one", + "[local.system] activating one", + "slop: activated box", + ] + for line in expected: assert line in out, (line, out) box.succeed("test -e /tmp/slop-activated-one") machine.succeed("test -e /tmp/slop-activated-one") @@ -324,10 +337,11 @@ pkgs.testers.runNixOSTest { out = box.succeed(f"nix --extra-experimental-features nix-command path-info -r {profile}") assert len(out.split()) == 2, out - # The second commit, with its build's log - status, out = try_slop(f"deploy box.system --commit {two}") + # The second commit, with its build's log, copies only the new profile: busybox is there + status, out = try_slop(f"deploy box.system --commit {two} --logs") print(out) assert status == 0 and "build line two" in out, (status, out) + assert "slop: copied to box: 1 path (" in out, out box.succeed("test -e /tmp/slop-activated-two") # The binary cache @@ -336,7 +350,7 @@ pkgs.testers.runNixOSTest { # is the last line status, out = try_slop(f"build packages.x86_64-linux.profile --commit {two}") print(out) - assert status == 0, (status, out) + assert status == 0 and "slop: pushed to the cache: 2 paths (" in out, (status, out) path = out.strip().splitlines()[-1] assert path.startswith("/nix/store/") and path.endswith("-test-profile-two"), out out = box.succeed(f"nix --extra-experimental-features nix-command path-info --store /var/lib/slop-cache -r {path}") @@ -345,11 +359,11 @@ pkgs.testers.runNixOSTest { # The audit log - # It has the answers and the outcomes; the default 50 records don't reach back far enough + # It has the answers and how deploys went; the default 50 records don't reach back far enough audit = approve("log -n 200") print(audit) assert "agent asks: ssh local" in audit and "answered 5m by reviewer" in audit, audit assert "answered once by laptop (ssh)" in audit, audit - assert "finished with exit status 0" in audit, audit + assert "finished with exit status 0" in audit and "activated box in" in audit, audit ''; } diff --git a/slop-tools.md b/slop-tools.md index b648801..aa08051 100644 --- a/slop-tools.md +++ b/slop-tools.md @@ -59,8 +59,13 @@ applies a policy, and asks a human to approve most requests. at a time. - Before anything is built, a human approves your use of the builder after seeing your commits and their diff; that may be covered by a lease from an earlier request. Then the build and the - copy to the nodes happen, their output streaming to you, and the deploy itself waits for + copy to the nodes happen, with their progress shown as they go, and the deploy itself waits for approval. Keep commits focused so the diff is quick to review. +- Progress comes as a `slop:` line for each step (evaluating, building, and copying, comparing + and activating on each node) every 30 seconds or so while it runs and when it ends, such as + `slop: building: 37/120 derivations (firefox-147.0), 4m 10s`. +- Build logs aren't shown, only progress; a failed build shows the end of its log. `--logs` (on + `slop deploy` and `slop build`) shows them all as they happen, which is a lot of output. - `--boot` makes it the boot default without switching; the box uses it after its next reboot. - Check the result afterwards with `slop failed` and `slop status`. diff --git a/src/audit.rs b/src/audit.rs index 7d37c4c..009372c 100644 --- a/src/audit.rs +++ b/src/audit.rs @@ -11,6 +11,7 @@ use anyhow::Result; use serde::{Deserialize, Serialize}; use crate::detail::{Detail, Section}; +use crate::progress::Progress; use crate::proto::ApprovedBy; /// One line of the audit file. @@ -87,10 +88,15 @@ pub enum Event { id: String, exit: i32, seconds: f64, + /// How each phase of a build or deploy ended. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + phases: Vec, }, Failed { id: String, error: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + phases: Vec, }, } @@ -185,14 +191,26 @@ impl fmt::Display for Event { Event::Detached { id } => { write!(f, "{} the requester disconnected; waiting for it to finish anyway", short(id)) } - Event::Finished { id, exit, seconds } => { - write!(f, "{} finished with exit status {exit} after {seconds:.1}s", short(id)) + Event::Finished { id, exit, seconds, phases } => { + write!(f, "{} finished with exit status {exit} after {seconds:.1}s", short(id))?; + phase_lines(f, phases) + } + Event::Failed { id, error, phases } => { + write!(f, "{} failed: {error}", short(id))?; + phase_lines(f, phases) } - Event::Failed { id, error } => write!(f, "{} failed: {error}", short(id)), } } } +/// Phases as `; built: 12 derivations in 4m 10s; …`. +fn phase_lines(f: &mut fmt::Formatter, phases: &[Progress]) -> fmt::Result { + for phase in phases { + write!(f, "; {}", phase.line())?; + } + Ok(()) +} + impl Record { /// For reviewing: the journal's line, with the time and the rest of a request's detail. pub fn describe(&self) -> String { @@ -265,11 +283,14 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let audit = Audit::new(Some(&directory.path().join("audit.jsonl"))).unwrap(); for exit in 0..5 { - audit.log(Event::Finished { id: "0123456789abcdef".into(), exit, seconds: 1.5 }); + audit.log(Event::Finished { id: "0123456789abcdef".into(), exit, seconds: 1.5, phases: vec![] }); } let records = audit.tail(2).unwrap(); assert_eq!(records.len(), 2); - assert_eq!(records[1].event, Event::Finished { id: "0123456789abcdef".into(), exit: 4, seconds: 1.5 }); + assert_eq!( + records[1].event, + Event::Finished { id: "0123456789abcdef".into(), exit: 4, seconds: 1.5, phases: vec![] } + ); assert!(records[1].describe().ends_with("012345 finished with exit status 4 after 1.5s\n")); } diff --git a/src/bin/slop.rs b/src/bin/slop.rs index 32b86b5..4764522 100644 --- a/src/bin/slop.rs +++ b/src/bin/slop.rs @@ -6,7 +6,7 @@ use std::process::exit; use anyhow::{Context, Result, bail}; use clap::{Args, Parser, Subcommand}; use futures_util::{SinkExt, StreamExt}; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::io::AsyncReadExt; use tokio::sync::mpsc; use slop_broker::proto::{ @@ -15,6 +15,7 @@ use slop_broker::proto::{ transport, }; use slop_broker::remote::{self, Role, Stream}; +use slop_broker::terminal::Board; use slop_broker::types::{ Arg, CommitId, DeployTarget, FlakeAttr, HostName, Lines, NodeName, Recipient, SecretKey, SecretPath, Since, UnitName, UserName, @@ -129,6 +130,9 @@ enum Command { /// Make it the boot default instead of switching to it now. #[arg(long)] boot: bool, + /// Show build logs as they happen, not only progress. + #[arg(long)] + logs: bool, }, /// Build flake attributes of a pushed commit and, once approved, push them to the binary cache. Build { @@ -138,6 +142,9 @@ enum Command { /// The commit, resolved in this checkout; it must already be pushed to the Git server the builder fetches from. #[arg(long, default_value = "HEAD")] commit: String, + /// Show build logs as they happen, not only progress. + #[arg(long)] + logs: bool, }, /// Work with an age secret: list its keys, set or generate a value, re-encrypt or read it. Secret { @@ -375,8 +382,10 @@ fn operation(command: Command) -> Result { Operation::Query { destination: target.destination()?, query: Query::Logs { unit, lines, since } } } Command::Failed { target } => Operation::Query { destination: target.destination()?, query: Query::Failed }, - Command::Deploy { targets, commit, boot } => Operation::Deploy { targets, commit: resolve(&commit)?, boot }, - Command::Build { attrs, commit } => Operation::Build { attrs, commit: resolve(&commit)? }, + Command::Deploy { targets, commit, boot, logs } => { + Operation::Deploy { targets, commit: resolve(&commit)?, boot, logs } + } + Command::Build { attrs, commit, logs } => Operation::Build { attrs, commit: resolve(&commit)?, logs }, Command::Requests => Operation::Requests, Command::Guide | Command::Secret { .. } => unreachable!(), }) @@ -479,32 +488,41 @@ async fn run(cli: Cli) -> Result { }); tx.send(ClientMessage::Request(request)).await?; - let (mut stdout, mut stderr) = (tokio::io::stdout(), tokio::io::stderr()); + // Progress bars stay below other output on a terminal; `slop`'s own lines go above them. + let mut board = Board::new(); loop { let frame = source.next().await.context("the broker closed the connection")??; - match decode::(&frame)? { + let message = decode::(&frame)?; + + // The end: no more bars + if matches!( + message, + ServerMessage::Finished { .. } + | ServerMessage::Denied(_) + | ServerMessage::Expired + | ServerMessage::Error(_) + ) { + board.clear(); + } + + match message { ServerMessage::Pending { id, summary } => { - eprintln!("slop: waiting for approval of `{summary}` (request {id})…") + board.say(&format!("slop: waiting for approval of `{summary}` (request {id})…")) } ServerMessage::Approved { by, stdin } => { match by { - ApprovedBy::Lease => eprintln!("slop: approved (lease)"), - ApprovedBy::Approver => eprintln!("slop: approved"), + ApprovedBy::Lease => board.say("slop: approved (lease)"), + ApprovedBy::Approver => board.say("slop: approved"), ApprovedBy::Policy => {} } if stdin { tokio::spawn(forward_stdin(tx.clone())); } } - ServerMessage::Info(message) => eprintln!("slop: {message}"), - ServerMessage::Stdout(data) => { - stdout.write_all(&data).await?; - stdout.flush().await?; - } - ServerMessage::Stderr(data) => { - stderr.write_all(&data).await?; - stderr.flush().await?; - } + ServerMessage::Info(message) => board.say(&format!("slop: {message}")), + ServerMessage::Progress(progress) => board.update(&progress), + ServerMessage::Stdout(data) => board.write(&mut std::io::stdout().lock(), &data)?, + ServerMessage::Stderr(data) => board.write(&mut std::io::stderr().lock(), &data)?, ServerMessage::Finished { exit, result } => { match (result, &secret) { // New ciphertext goes back into the file, never to the terminal. diff --git a/src/builder.rs b/src/builder.rs index b7dacb4..506866c 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -1,7 +1,7 @@ //! Builds commits for deploys and `slop build`. The broker runs `slop-broker builder` over SSH as //! a user without keys (the key's forced command). It sends one [`BuilderRequest`] on stdin and -//! gets the result back on stdout, each one frame like the rest of the protocol; logs come on -//! stderr and go to the requester. +//! gets [`Reply`] frames back on stdout, like the rest of the protocol: progress, then the +//! result. Logs come on stderr and go to the requester. //! //! The builder fetches the commit from the Git server itself, so the requester never supplies //! the source. [`BuilderRequest::Describe`] runs only Git, so approvers can see the commits before @@ -24,6 +24,7 @@ use tokio_util::codec::{FramedRead, FramedWrite}; use tokio_util::sync::CancellationToken; use crate::exec::Output; +use crate::progress::{self, Counts, NixLog, Phase, Reporter}; use crate::proto::{ServerMessage, codec, decode, encode}; use crate::types::{CommitId, DeployTarget, FlakeAttr, ObjectId, RulesPath, SecretPath}; @@ -136,6 +137,20 @@ pub struct BuildRequest { pub targets: Vec, /// Flake attributes to build. pub attrs: Vec, + /// Pass build logs through, not only progress. + pub logs: bool, +} + +/// What the builder sends on stdout. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +pub enum Reply { + /// How a build is going, at most every [`progress::INTERVAL`]. + Progress(Counts), + /// Evaluation is over; the progress that follows is building. + Evaluated, + /// The result, encoded; the last frame. + Done(#[serde(with = "serde_bytes")] Vec), } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -206,10 +221,11 @@ pub async fn describe( out: &Output, cancel: &CancellationToken, ) -> Result { - call(ssh, deploy, &BuilderRequest::Describe(commit.clone()), out, cancel).await + call(ssh, deploy, &BuilderRequest::Describe(commit.clone()), out, None, cancel).await } -/// Runs a build and returns what it built. Build output goes to `out` as it happens. +/// Runs a build and returns what it built. Its progress, and its logs if the request asks for +/// them, go to `out` as it happens. pub async fn build( ssh: &crate::config::SshConfig, deploy: &crate::config::DeployConfig, @@ -217,9 +233,13 @@ pub async fn build( out: &Output, cancel: &CancellationToken, ) -> Result { - let result: BuildResult = call(ssh, deploy, &BuilderRequest::Build(request.clone()), out, cancel).await?; - result.check()?; - Ok(result) + let mut reporter = Reporter::start(out, Phase::Evaluate).await; + let result = + call::(ssh, deploy, &BuilderRequest::Build(request.clone()), out, Some(&mut reporter), cancel) + .await + .and_then(|result| result.check().map(|()| result)); + reporter.finish(result.is_ok()).await; + result } /// The main branch's deploy-rs nodes. Its progress goes to `out`. @@ -229,7 +249,7 @@ pub async fn nodes( out: &Output, cancel: &CancellationToken, ) -> Result { - call(ssh, deploy, &BuilderRequest::Nodes, out, cancel).await + call(ssh, deploy, &BuilderRequest::Nodes, out, None, cancel).await } /// What the main branch says about a secret. Its progress goes to `out`. @@ -240,7 +260,7 @@ pub async fn secret( out: &Output, cancel: &CancellationToken, ) -> Result { - call(ssh, deploy, &BuilderRequest::Secret(request.clone()), out, cancel).await + call(ssh, deploy, &BuilderRequest::Secret(request.clone()), out, None, cancel).await } async fn call( @@ -248,6 +268,7 @@ async fn call( deploy: &crate::config::DeployConfig, request: &BuilderRequest, out: &Output, + mut reporter: Option<&mut Reporter>, cancel: &CancellationToken, ) -> Result { let mut command = crate::ops::ssh::command_to(ssh, &deploy.builder, &["build"]); @@ -268,10 +289,28 @@ async fn call( }); let mut stdout = FramedRead::new(child.stdout.take().unwrap(), codec()); - let (frame, status) = tokio::select! { + let (result, status) = tokio::select! { result = async { - let frame = stdout.next().await.transpose()?; - anyhow::Ok((frame, child.wait().await?)) + let mut result = None; + while let Some(frame) = stdout.next().await.transpose()? { + match decode(&frame)? { + Reply::Progress(counts) => { + if let Some(reporter) = reporter.as_deref_mut() { + reporter.update(counts).await; + } + } + Reply::Evaluated => { + if let Some(reporter) = reporter.as_deref_mut() { + reporter.next(Phase::Build).await; + } + } + Reply::Done(data) => { + result = Some(data); + break; + } + } + } + anyhow::Ok((result, child.wait().await?)) } => result?, _ = cancel.cancelled() => bail!("requester disconnected"), }; @@ -279,7 +318,7 @@ async fn call( let _ = tokio::time::timeout(Duration::from_secs(5), logs).await; ensure!(status.success(), "the builder failed; its output is above"); - decode(&frame.context("the builder sent no result")?) + decode(&result.context("the builder sent no result")?) } // The builder's side @@ -302,6 +341,16 @@ pub async fn worker(config: &Path) -> Result<()> { // Nothing else comes on stdin; it closing means the broker gave up. let closed = async move { while let Some(Ok(_)) = stdin.next().await {} }; + // One writer for progress and the result + let (replies, mut queued) = tokio::sync::mpsc::unbounded_channel::(); + let writer = tokio::spawn(async move { + let mut stdout = FramedWrite::new(tokio::io::stdout(), codec()); + while let Some(reply) = queued.recv().await { + stdout.send(encode(&reply)?).await?; + } + anyhow::Ok(()) + }); + tokio::select! { result = async { match &request { @@ -310,12 +359,13 @@ pub async fn worker(config: &Path) -> Result<()> { BuilderRequest::Nodes => encode(&branch_nodes(&config).await?), BuilderRequest::Build(request) => { let _lock = lock(&config.directory.join("build.lock")).await?; - encode(&run(&config, request).await?) + encode(&run(&config, request, &replies).await?) } } } => { - let mut stdout = FramedWrite::new(tokio::io::stdout(), codec()); - stdout.send(result?).await?; + let _ = replies.send(Reply::Done(result?.to_vec())); + drop(replies); + writer.await??; // Not a return: the runtime would wait for the blocked read of stdin, which the broker // keeps open until this exits. std::process::exit(0) @@ -642,7 +692,11 @@ async fn branch_nodes(config: &BuilderConfig) -> Result { Ok(Nodes { commit, nodes }) } -async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result { +async fn run( + config: &BuilderConfig, + request: &BuildRequest, + replies: &tokio::sync::mpsc::UnboundedSender, +) -> Result { let commit = &request.commit; let repository = mirror(config); @@ -676,24 +730,34 @@ async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result = profiles .iter() .map(|p| format!("{flake}#deploy.nodes.\"{}\".profiles.\"{}\".path", p.node, p.profile)) .chain(request.attrs.iter().map(|attr| format!("{flake}#{attr}"))) .collect(); - // Not `output()`, which would capture stderr too, whatever it's set to. - let built = command(config, "nix") - .args(["build", "--no-link", "--json", "--print-build-logs"]) + let mut child = command(config, "nix") + .args(["build", "--no-link", "--json", "--log-format", "internal-json"]) .args(NIX_OPTIONS) .args(&installables) .stdout(Stdio::piped()) - .stderr(Stdio::inherit()) - .spawn()? - .wait_with_output() - .await?; - ensure!(built.status.success(), "nix build failed"); + .stderr(Stdio::piped()) + .spawn()?; + + let mut stdout = child.stdout.take().unwrap(); + let result = tokio::spawn(async move { + let mut data = Vec::new(); + stdout.read_to_end(&mut data).await.map(|_| data) + }); + let realised = follow(child.stderr.take().unwrap(), NixLog::new(request.logs), replies).await; + let status = child.wait().await?; + let stdout = result.await??; + ensure!(status.success(), "nix build failed"); + // With everything already built, Nix has nothing to start + if !realised { + let _ = replies.send(Reply::Evaluated); + } #[derive(Deserialize)] struct Built { @@ -701,7 +765,7 @@ async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result, } - let mut built: Vec = serde_json::from_slice(&built.stdout).context("reading nix build's result")?; + let mut built: Vec = serde_json::from_slice(&stdout).context("reading nix build's result")?; // One result per installable, in order, except that some versions of Nix repeat the results // of installables that are the same derivation; then they're matched by derivation. @@ -735,6 +799,39 @@ async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result, +) -> bool { + use tokio::io::AsyncBufReadExt; + + let mut lines = tokio::io::BufReader::new(stderr).lines(); + let mut sent: Option = None; + let mut realising = false; + while let Ok(Some(line)) = lines.next_line().await { + if let Some(text) = log.line(&line) { + eprintln!("{text}"); + } + + // The build's progress starts as soon as Nix starts building + if log.realising() && !realising { + realising = true; + let _ = replies.send(Reply::Evaluated); + sent = None; + } + if sent.is_none_or(|s| s.elapsed() >= progress::INTERVAL) { + sent = Some(std::time::Instant::now()); + let _ = replies.send(Reply::Progress(log.counts())); + } + } + let _ = replies.send(Reply::Progress(log.counts())); + realising +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/exec.rs b/src/exec.rs index 4154c30..c23ed5a 100644 --- a/src/exec.rs +++ b/src/exec.rs @@ -1,6 +1,7 @@ //! Runs processes for approved requests, wired to the requester's stdout and stderr (carried as //! messages). use std::process::{ExitStatus, Stdio}; +use std::sync::Arc; use std::time::Duration; use anyhow::{Context, Result, bail}; @@ -12,15 +13,33 @@ use tokio::process::Command; use tokio::sync::mpsc; use tokio_util::sync::CancellationToken; +use crate::progress::{NixLog, Reporter}; use crate::proto::ServerMessage; +use crate::runs::Runs; -/// Messages on their way back to the requester. +/// Messages on their way back to the requester. Progress also goes to the request's run, if +/// it's tracked. #[derive(Clone)] -pub struct Output(pub mpsc::Sender); +pub struct Output { + tx: mpsc::Sender, + run: Option<(Arc, String)>, +} impl Output { + pub fn new(tx: mpsc::Sender) -> Output { + Output { tx, run: None } + } + + /// The same output, with progress recorded in `runs` for request `id`. + pub fn tracking(&self, runs: Arc, id: &str) -> Output { + Output { tx: self.tx.clone(), run: Some((runs, id.to_owned())) } + } + pub async fn send(&self, message: ServerMessage) { - let _ = self.0.send(message).await; + if let (ServerMessage::Progress(progress), Some((runs, id))) = (&message, &self.run) { + runs.record(id, progress); + } + let _ = self.tx.send(message).await; } pub async fn info(&self, message: impl Into) { @@ -126,6 +145,63 @@ pub async fn run_prefixed(mut command: Command, out: &Output, prefix: &str, canc Ok(exit_code(status)) } +/// Runs a `nix` command that logs with `--log-format internal-json`, without stdin. Each line of +/// its output and of what its log would show goes to the requester with `prefix`, and its +/// progress to `reporter`. +pub async fn run_nix( + mut command: Command, + out: &Output, + prefix: &str, + mut log: NixLog, + reporter: &mut Reporter, + cancel: &CancellationToken, +) -> Result { + command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).process_group(0).kill_on_drop(true); + let mut child = spawn(&mut command).await?; + let pid = child.id().context("process exited immediately")? as i32; + + let stdout = { + let (out, prefix) = (out.clone(), prefix.to_owned()); + let mut lines = tokio::io::BufReader::new(child.stdout.take().unwrap()).lines(); + tokio::spawn(async move { + while let Ok(Some(line)) = lines.next_line().await { + out.send(ServerMessage::Stdout(format!("{prefix}{line}\n").into_bytes())).await; + } + }) + }; + + let mut stderr = tokio::io::BufReader::new(child.stderr.take().unwrap()).lines(); + loop { + let line = tokio::select! { + line = stderr.next_line() => line, + _ = cancel.cancelled() => { + terminate(pid, &mut child).await; + bail!("requester disconnected"); + } + }; + let Ok(Some(line)) = line else { break }; + + if let Some(text) = log.line(&line) { + out.send(ServerMessage::Stderr(format!("{prefix}{text}\n").into_bytes())).await; + } + if reporter.due() { + reporter.update(log.counts()).await; + } + } + reporter.update(log.counts()).await; + + let status = tokio::select! { + status = child.wait() => status?, + _ = cancel.cancelled() => { + terminate(pid, &mut child).await; + bail!("requester disconnected"); + } + }; + + let _ = tokio::time::timeout(Duration::from_secs(5), stdout).await; + Ok(exit_code(status)) +} + /// Runs `command` without the requester's stdio and returns its stdout. pub async fn capture(mut command: Command, cancel: &CancellationToken) -> Result<(i32, Vec, Vec)> { command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).process_group(0).kill_on_drop(true); diff --git a/src/lib.rs b/src/lib.rs index 7b57057..34ea1a1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,11 +8,14 @@ pub mod detail; pub mod exec; pub mod ops; pub mod policy; +pub mod progress; pub mod proto; pub mod queue; pub mod remote; +pub mod runs; pub mod server; pub mod targets; +pub mod terminal; pub mod types; pub mod web; diff --git a/src/ops/build.rs b/src/ops/build.rs index 188de43..2d89e41 100644 --- a/src/ops/build.rs +++ b/src/ops/build.rs @@ -20,6 +20,7 @@ use crate::config::{CacheConfig, DeployConfig, SshConfig}; use crate::detail::{Column, Detail, Row, Section, Tone}; use crate::exec::{self, Io}; use crate::policy::OpName; +use crate::progress::{NixLog, Phase, Reporter}; use crate::proto::{Operation, ServerMessage}; use crate::server::Broker; @@ -33,7 +34,7 @@ fn configs(broker: &Broker) -> Result<(Arc, &DeployConfig, &CacheConf } pub fn plan(broker: &Broker, operation: Operation) -> Result { - let Operation::Build { attrs, commit } = &operation else { unreachable!() }; + let Operation::Build { attrs, commit, .. } = &operation else { unreachable!() }; configs(broker)?; ensure!(!attrs.is_empty(), "nothing to build"); @@ -61,12 +62,12 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result { /// Builds; fills in the approval detail with the outputs and their closure sizes. pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()> { - let Operation::Build { attrs, commit } = &parsed.operation else { return Ok(()) }; + let Operation::Build { attrs, commit, logs } = &parsed.operation else { return Ok(()) }; let (ssh, deploy, _) = configs(broker)?; let ssh = &*ssh; - let request = BuildRequest { commit: commit.clone(), targets: Vec::new(), attrs: attrs.clone() }; - io.out.info(format!("{}; output follows", parsed.summary)).await; + let request = BuildRequest { commit: commit.clone(), targets: Vec::new(), attrs: attrs.clone(), logs: *logs }; + io.out.info(parsed.summary.clone()).await; let built = builder::build(ssh, deploy, &request, &io.out, &io.cancel).await?; let paths: Vec<&str> = built.outputs.iter().flat_map(|o| &o.paths).map(String::as_str).collect(); @@ -108,7 +109,11 @@ pub async fn execute(broker: &Broker, parsed: &Parsed, io: &mut Io) -> Result &'static str { } pub fn plan(broker: &Broker, operation: Operation) -> Result { - let Operation::Deploy { targets, commit, boot } = &operation else { unreachable!() }; + let Operation::Deploy { targets, commit, boot, .. } = &operation else { unreachable!() }; let (ssh, _) = configs(broker)?; let ssh = &*ssh; @@ -84,12 +85,12 @@ pub fn building(commit: &crate::types::CommitId, label: &str) -> Detail { /// Builds, copies and compares; fills in the approval detail. pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()> { - let Operation::Deploy { targets, commit, boot } = &parsed.operation else { return Ok(()) }; + let Operation::Deploy { targets, commit, boot, logs } = &parsed.operation else { return Ok(()) }; let (ssh, deploy) = configs(broker)?; let ssh = &*ssh; - let request = BuildRequest { commit: commit.clone(), targets: targets.clone(), attrs: Vec::new() }; - io.out.info(format!("building {} for {}; output follows", commit.short(), parsed.summary)).await; + let request = BuildRequest { commit: commit.clone(), targets: targets.clone(), attrs: Vec::new(), logs: *logs }; + io.out.info(format!("building {} for {}", commit.short(), parsed.summary)).await; let built = builder::build(ssh, deploy, &request, &io.out, &io.cancel).await?; io.out.info("copying to the nodes and comparing with what they run").await; @@ -97,12 +98,18 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<() let reports = join_all(by_node.iter().map(|(node, profiles)| async move { copy(ssh, deploy, node, profiles, &io.out, &io.cancel).await?; - let mut detail = Detail::new(); - for profile in profiles { - let changes = inspect(ssh, node, profile, &io.cancel).await?; - changes.describe(&format!("{node}.{} ({})", profile.profile, mode(*boot)), &mut detail); + let reporter = Reporter::start(&io.out, Phase::Compare(node.clone())).await; + let compared = async { + let mut detail = Detail::new(); + for profile in profiles { + let changes = inspect(ssh, node, profile, &io.cancel).await?; + changes.describe(&format!("{node}.{} ({})", profile.profile, mode(*boot)), &mut detail); + } + anyhow::Ok(detail) } - anyhow::Ok(detail) + .await; + reporter.finish(compared.is_ok()).await; + compared })) .await; @@ -132,17 +139,23 @@ pub async fn execute(broker: &Broker, id: &str, parsed: &Parsed, io: &mut Io) -> let never = CancellationToken::new(); let (out, cancel) = (&io.out, &never); let results = join_all(group(&built.profiles).into_iter().map(|(node, profiles)| async move { - for profile in profiles { - let remote = [shell_quote(&activate_command(ssh, &node, profile, *boot, id)?)]; - let command = ssh::command(ssh, &Destination::Node(node.parse().unwrap()), &remote)?; - let prefix = format!("[{node}.{}] ", profile.profile); + let reporter = Reporter::start(out, Phase::Activate(node.clone())).await; + let activated = async { + for profile in profiles { + let remote = [shell_quote(&activate_command(ssh, &node, profile, *boot, id)?)]; + let command = ssh::command(ssh, &Destination::Node(node.parse().unwrap()), &remote)?; + let prefix = format!("[{node}.{}] ", profile.profile); - let exit = exec::run_prefixed(command, out, &prefix, cancel).await?; - if exit != 0 { - return anyhow::Ok((node, format!("{} failed (exit status {exit})", profile.profile), exit)); + let exit = exec::run_prefixed(command, out, &prefix, cancel).await?; + if exit != 0 { + return anyhow::Ok((format!("{} failed (exit status {exit})", profile.profile), exit)); + } } + anyhow::Ok(("done".to_owned(), 0)) } - anyhow::Ok((node, "done".to_owned(), 0)) + .await; + reporter.finish(matches!(activated, Ok((_, 0)))).await; + activated.map(|(outcome, exit)| (node, outcome, exit)) })) .await; @@ -170,7 +183,7 @@ fn group(profiles: &[BuiltProfile]) -> Vec<(String, Vec<&BuiltProfile>)> { } /// Copies closures to a node like deploy-rs does, letting it substitute what caches have. Its -/// progress (one line per path) goes to the requester. +/// progress goes to the requester. async fn copy( ssh: &SshConfig, deploy: &DeployConfig, @@ -199,14 +212,18 @@ async fn copy( "copy", "--no-check-sigs", "--substitute-on-destination", + "--log-format", + "internal-json", ]) .args(["--from", &from]) .arg("--to") .arg(format!("ssh://{}@{}", target.user, target.hostname)) .args(profiles.iter().map(|p| &p.path)); - let exit = exec::run_prefixed(command, out, &format!("[{node}] "), cancel).await?; - ensure!(exit == 0, "copying to {node} failed; its output is above"); + let mut reporter = Reporter::start(out, Phase::Copy(node.to_owned())).await; + let exit = exec::run_nix(command, out, &format!("[{node}] "), NixLog::new(false), &mut reporter, cancel).await; + reporter.finish(matches!(exit, Ok(0))).await; + ensure!(exit? == 0, "copying to {node} failed; its output is above"); Ok(()) } @@ -277,26 +294,6 @@ fn activate_command(ssh: &SshConfig, node: &str, profile: &BuiltProfile, boot: b Ok(words) } -/// Drops terminal escape sequences, which `nix` can print even into a pipe. -fn strip_escapes(text: &str) -> String { - let mut result = String::with_capacity(text.len()); - let mut chars = text.chars(); - while let Some(c) = chars.next() { - if c == '\x1b' { - if chars.next() == Some('[') { - for c in chars.by_ref() { - if c.is_ascii_alphabetic() { - break; - } - } - } - } else { - result.push(c); - } - } - result -} - /// What a deploy changes on one profile. #[derive(Debug, Default, PartialEq)] struct Changes { @@ -318,7 +315,7 @@ struct Diff { impl Changes { fn parse(output: &str) -> Changes { - let output = strip_escapes(output); + let output = crate::progress::strip_escapes(output); let mut changes = Changes { new: !output.contains("@@packages"), ..Changes::default() }; // Sections start with `@@name` lines; the /etc listings are `pathtarget`. @@ -486,7 +483,6 @@ mod tests { let changes = Changes::parse(output); assert_eq!(changes.packages, ["home-assistant: 2026.11.1 → 2026.11.2, +3.4 MiB"]); - assert_eq!(strip_escapes("source: \x1b[31;1m3.6 GiB\x1b[0m"), "source: 3.6 GiB"); assert_eq!(changes.boot, ["kernel"]); assert_eq!(changes.units.changed, ["a.service"]); assert_eq!(changes.units.added, ["c.service"]); diff --git a/src/ops/mod.rs b/src/ops/mod.rs index 9adf040..7cd48fe 100644 --- a/src/ops/mod.rs +++ b/src/ops/mod.rs @@ -305,7 +305,7 @@ mod tests { #[test] fn the_builder_gate_shows_the_diff_and_leases_cover_any_commit() { let commit: CommitId = "0123456789abcdef0123456789abcdef01234567".parse().unwrap(); - let operation = Operation::Build { attrs: vec!["hello".parse().unwrap()], commit }; + let operation = Operation::Build { attrs: vec!["hello".parse().unwrap()], commit, logs: false }; let parsed = Parsed::new(OpName::Build, Map::new(), "build hello at 0123456789ab".into(), Detail::new(), operation); let description = Description { diff --git a/src/progress.rs b/src/progress.rs new file mode 100644 index 0000000..da34369 --- /dev/null +++ b/src/progress.rs @@ -0,0 +1,758 @@ +//! Progress of the long parts of a request: building, copying closures, comparing and +//! activating. The builder and the broker read it from Nix's `--log-format internal-json` +//! ([`NixLog`]), and the broker sends it to the requester as [`Progress`] messages. +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +use indicatif::BinaryBytes; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::exec::Output; +use crate::proto::ServerMessage; + +/// How often a phase's progress is sent while it runs. +pub const INTERVAL: Duration = Duration::from_secs(1); + +/// What's running now, at most this many names. +const MAX_CURRENT: usize = 3; + +/// One part of a request. +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +pub enum Phase { + /// Evaluating, on the builder, until Nix starts building and fetching. + Evaluate, + /// Building and fetching, on the builder. + Build, + /// Copying closures to a node. + Copy(String), + /// Comparing what a node runs with what it will. + Compare(String), + /// Activating on a node. + Activate(String), + /// Pushing to the binary cache. + Push, +} + +impl Phase { + /// The node it's about, if any. + pub fn node(&self) -> Option<&str> { + match self { + Phase::Copy(node) | Phase::Compare(node) | Phase::Activate(node) => Some(node), + Phase::Evaluate | Phase::Build | Phase::Push => None, + } + } + + /// Its verb while it runs, and once it's done, like `copying` and `copied`. + pub fn verbs(&self) -> (&'static str, &'static str) { + match self { + Phase::Evaluate => ("evaluating", "evaluated"), + Phase::Build => ("building", "built"), + Phase::Copy(_) => ("copying", "copied"), + Phase::Compare(_) => ("comparing", "compared"), + Phase::Activate(_) => ("activating", "activated"), + Phase::Push => ("pushing", "pushed"), + } + } + + /// What it's about, after the verb, like ` to river`. + fn object(&self) -> String { + match self { + Phase::Evaluate | Phase::Build => String::new(), + Phase::Copy(node) => format!(" to {node}"), + Phase::Compare(node) => format!(" on {node}"), + Phase::Activate(node) => format!(" {node}"), + Phase::Push => " to the cache".into(), + } + } + + /// What it's doing, like `copying to river`. + pub fn doing(&self) -> String { + format!("{}{}", self.verbs().0, self.object()) + } + + /// What it did, like `copied to river`. + pub fn done(&self) -> String { + format!("{}{}", self.verbs().1, self.object()) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum State { + Running, + Done, + Failed, +} + +/// Done out of a total, which can grow as Nix finds more to do. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Count { + pub done: u64, + pub total: u64, +} + +impl Count { + /// From 0 to 1; nothing to do counts as finished. + pub fn fraction(&self) -> f64 { + if self.total == 0 { 1.0 } else { (self.done as f64 / self.total as f64).min(1.0) } + } +} + +/// What Nix reports of a build or copy. Names are store path names, checked like store paths. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Counts { + /// Derivations built. + pub builds: Option, + /// Paths fetched (when building) or copied. + pub paths: Option, + /// Bytes of those paths. + pub bytes: Option, + /// What's building or copying now. + pub current: Vec, +} + +/// One phase's progress. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Progress { + pub phase: Phase, + pub state: State, + /// Seconds since the phase started. + pub elapsed: u64, + pub counts: Counts, +} + +impl Progress { + /// The main count, for a bar: derivations when building, paths when copying. + pub fn bar(&self) -> Option { + let counts = &self.counts; + match self.phase { + Phase::Build => counts.builds.filter(|c| c.total > 0).or(counts.paths.filter(|c| c.total > 0)), + _ => counts.paths.filter(|c| c.total > 0), + } + } + + /// What it's doing or did, like `copying to river` or `building failed`. + pub fn title(&self) -> String { + match self.state { + State::Running => self.phase.doing(), + State::Done => self.phase.done(), + State::Failed => format!("{} failed", self.phase.doing()), + } + } + + /// The counts in words, like `37/120 derivations, 10/40 paths (1.2/3.4 GiB)`, or only what + /// was done once it's `finished`. + pub fn counted(&self, finished: bool) -> String { + let counts = &self.counts; + let count = |c: Count| if finished { c.done.to_string() } else { format!("{}/{}", c.done, c.total) }; + let fetched = if self.phase == Phase::Build { "fetched" } else { "" }; + + let mut parts = Vec::new(); + if let Some(builds) = counts.builds.filter(|c| c.total > 0) { + parts.push(format!("{} {}", count(builds), plural(builds.total, "derivation"))); + } + if let Some(paths) = counts.paths.filter(|c| c.total > 0) { + let mut part = format!("{} {}", count(paths), plural(paths.total, "path")); + if !fetched.is_empty() { + part = format!("{part} {fetched}"); + } + if let Some(bytes) = counts.bytes.filter(|c| c.total > 0) { + part += &if finished { + format!(" ({})", BinaryBytes(bytes.done)) + } else { + format!(" ({}/{})", BinaryBytes(bytes.done), BinaryBytes(bytes.total)) + }; + } + parts.push(part); + } + parts.join(", ") + } + + /// What's building or copying now, like `firefox-147.0, glibc-2.42`. + pub fn current(&self) -> Option { + (!self.counts.current.is_empty()).then(|| self.counts.current.join(", ")) + } + + /// One line for a person or an agent, like `building: 37/120 derivations (firefox-147.0)` or + /// `built 120 derivations in 4m 10s`. + pub fn line(&self) -> String { + match self.state { + State::Running => { + let mut line = self.phase.doing(); + let counted = self.counted(false); + if !counted.is_empty() { + line = format!("{line}: {counted}"); + } + if let Some(current) = self.current() { + line = format!("{line} ({current})"); + } + format!("{line}, {}", elapsed(self.elapsed)) + } + State::Done | State::Failed => { + let counted = self.counted(self.state == State::Done); + let mut line = self.title(); + if !counted.is_empty() { + line = format!("{line}: {counted}"); + } + format!("{line} in {}", elapsed(self.elapsed)) + } + } + } +} + +fn plural(count: u64, word: &str) -> String { + if count == 1 { word.to_owned() } else { format!("{word}s") } +} + +/// A duration, like `4m 10s`, or to the minute from an hour, like `1h 2m`. +pub fn elapsed(seconds: u64) -> String { + let seconds = if seconds >= 3600 { seconds - seconds % 60 } else { seconds }; + humantime::format_duration(Duration::from_secs(seconds)).to_string() +} + +/// The latest progress of each phase of a request, in the order they started. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Phases(Vec); + +/// How a node is getting on, from its phases. +#[derive(Debug, Clone, PartialEq)] +pub struct NodeRow { + pub node: String, + /// What it's doing or did, like `copying` or `ready`. + pub state: &'static str, + /// For styling: `active`, `good`, `bad` or `neutral`. + pub tone: &'static str, + /// Its copy, for a bar. + pub copy: Option, + /// Its phase now, or its last. + pub latest: Progress, +} + +impl NodeRow { + /// Whether it's got as far as it will: activated, or failed. + pub fn ended(&self) -> bool { + self.latest.state == State::Failed + || (matches!(self.latest.phase, Phase::Activate(_)) && self.latest.state == State::Done) + } + + /// How many of its three steps (copy, compare, activate) are behind it. + fn steps(&self) -> u64 { + match (&self.latest.phase, self.latest.state) { + (_, State::Failed) => 3, + (Phase::Copy(_), State::Running) => 0, + (Phase::Copy(_), _) | (Phase::Compare(_), State::Running) => 1, + (Phase::Compare(_), _) | (Phase::Activate(_), State::Running) => 2, + _ => 3, + } + } +} + +impl Phases { + /// Takes a phase's latest progress. + pub fn record(&mut self, progress: &Progress) { + match self.0.iter_mut().find(|p| p.phase == progress.phase) { + Some(phase) => *phase = progress.clone(), + None => self.0.push(progress.clone()), + } + } + + pub fn as_slice(&self) -> &[Progress] { + &self.0 + } + + /// Phases that aren't about one node: evaluating, building and pushing. + pub fn overall(&self) -> Vec<&Progress> { + self.0.iter().filter(|p| p.phase.node().is_none()).collect() + } + + /// The nodes, in the order their first phase started. + pub fn nodes(&self) -> Vec { + let mut order: Vec<&str> = Vec::new(); + for node in self.0.iter().filter_map(|p| p.phase.node()) { + if !order.contains(&node) { + order.push(node); + } + } + + order.into_iter().map(|node| self.node(node).unwrap()).collect() + } + + /// One node's row, if it has a phase. + pub fn node(&self, node: &str) -> Option { + let phases: Vec<&Progress> = self.0.iter().filter(|p| p.phase.node() == Some(node)).collect(); + let latest = (*phases.last()?).clone(); + let copy = phases.iter().find(|p| matches!(p.phase, Phase::Copy(_))).map(|p| (*p).clone()); + + let (running, done) = latest.phase.verbs(); + let (state, tone) = match (&latest.phase, latest.state) { + (_, State::Failed) => ("failed", "bad"), + (_, State::Running) => (running, "active"), + // Compared, and waiting for the deploy's approval + (Phase::Compare(_), State::Done) => ("ready", "neutral"), + (Phase::Activate(_), State::Done) => ("done", "good"), + (_, State::Done) => (done, "neutral"), + }; + Some(NodeRow { node: node.to_owned(), state, tone, copy, latest }) + } + + /// One bar for the whole request: the latest overall phase's, or the share of the nodes' + /// steps behind them. + pub fn bar(&self) -> Option { + let nodes = self.nodes(); + if nodes.is_empty() { + return self.overall().last().and_then(|p| p.bar()); + } + let total = nodes.len() as u64 * 3; + Some(Count { done: nodes.iter().map(NodeRow::steps).sum(), total }) + } + + /// What it's doing now, in a line. + pub fn status(&self) -> String { + match self.0.iter().rev().find(|p| p.state == State::Running).or(self.0.last()) { + Some(progress) => progress.line(), + None => "starting".into(), + } + } +} + +/// Sends a phase's progress to the requester: when it starts, at most every [`INTERVAL`] while +/// it runs, and when it ends. +pub struct Reporter { + out: Output, + phase: Phase, + started: Instant, + sent: Option, + counts: Counts, +} + +impl Reporter { + pub async fn start(out: &Output, phase: Phase) -> Reporter { + let mut reporter = + Reporter { out: out.clone(), phase, started: Instant::now(), sent: None, counts: Counts::default() }; + reporter.send(State::Running).await; + reporter + } + + /// Whether an update would be sent now. + pub fn due(&self) -> bool { + self.sent.is_none_or(|sent| sent.elapsed() >= INTERVAL) + } + + pub async fn update(&mut self, counts: Counts) { + self.counts = counts; + if self.due() { + self.send(State::Running).await; + } + } + + /// Ends the phase and starts the next. + pub async fn next(&mut self, phase: Phase) { + self.send(State::Done).await; + (self.phase, self.started, self.counts) = (phase, Instant::now(), Counts::default()); + self.send(State::Running).await; + } + + pub async fn finish(mut self, ok: bool) { + self.send(if ok { State::Done } else { State::Failed }).await; + } + + async fn send(&mut self, state: State) { + self.sent = Some(Instant::now()); + let progress = Progress { + phase: self.phase.clone(), + state, + elapsed: self.started.elapsed().as_secs(), + counts: self.counts.clone(), + }; + self.out.send(ServerMessage::Progress(Box::new(progress))).await; + } +} + +// Nix's activity and result types (`libutil/logging.hh`) +const COPY_PATH: u64 = 100; +const REALISE: u64 = 102; +const COPY_PATHS: u64 = 103; +const BUILDS: u64 = 104; +const BUILD: u64 = 105; +const SUBSTITUTE: u64 = 108; + +const BUILD_LOG_LINE: u64 = 101; +const SET_PHASE: u64 = 104; +const PROGRESS: u64 = 105; +const SET_EXPECTED: u64 = 106; + +/// A running activity. +#[derive(Default)] +struct Activity { + kind: u64, + done: u64, + expected: u64, + /// What it expects of other kinds of activity, like the bytes its copies will take. + expected_of: HashMap, + /// The derivation or path it's for. + name: Option, + /// A build's phase, like `buildPhase`. + step: Option, +} + +/// Reads Nix's `internal-json` log: keeps track of its activities, as its own progress bar +/// does, and gives back the text it would print. +#[derive(Default)] +pub struct NixLog { + activities: HashMap, + /// What finished activities did, by kind. + finished: HashMap, + /// How many derivations and paths Nix said it would build and fetch, which is steadier than + /// what its activities expect. + announced_builds: u64, + announced_paths: u64, + /// Paths whose copy finished: Nix can stop a copy without counting its last path. + copied: u64, + /// Whether to pass build logs through, like `--print-build-logs`. + logs: bool, + /// Whether Nix has started building and fetching, which it does once it's evaluated. + realising: bool, +} + +impl NixLog { + pub fn new(logs: bool) -> NixLog { + NixLog { logs, ..NixLog::default() } + } + + /// Takes one line of Nix's stderr; returns what to show of it, if anything, without + /// terminal escapes, which Nix prints even into a pipe. + pub fn line(&mut self, line: &str) -> Option { + self.read(line).map(|text| strip_escapes(&text)) + } + + fn read(&mut self, line: &str) -> Option { + let Some(json) = line.strip_prefix("@nix ") else { return Some(line.to_owned()) }; + let Ok(entry) = serde_json::from_str::(json) else { return Some(line.to_owned()) }; + let number = |key: &str| entry.get(key).and_then(Value::as_u64); + let fields = entry.get("fields").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); + let field = |index: usize| fields.get(index).and_then(Value::as_u64).unwrap_or(0); + + match entry.get("action").and_then(Value::as_str)? { + "msg" => { + let message = entry.get("msg").and_then(Value::as_str)?; + let level = number("level").unwrap_or(0); + self.announcement(message); + // Errors and warnings; the rest is what the progress shows + (level <= 1 || self.logs).then(|| message.to_owned()) + } + "start" => { + let (id, kind) = (number("id")?, number("type")?); + let name = fields.first().and_then(Value::as_str).and_then(store_name); + let text = entry.get("text").and_then(Value::as_str).filter(|t| !t.is_empty()); + self.activities.insert(id, Activity { kind, name, ..Activity::default() }); + self.realising |= matches!(kind, REALISE | COPY_PATHS | BUILDS | BUILD | SUBSTITUTE); + // Only builds and copies have text worth repeating in logs. + (self.logs && matches!(kind, BUILD | COPY_PATH)).then(|| text.map(str::to_owned)).flatten() + } + "stop" => { + if let Some(activity) = self.activities.remove(&number("id")?) { + *self.finished.entry(activity.kind).or_default() += activity.done; + self.copied += u64::from(activity.kind == COPY_PATH); + } + None + } + "result" => { + let activity = self.activities.get_mut(&number("id")?)?; + match number("type")? { + PROGRESS => (activity.done, activity.expected) = (field(0), field(1)), + SET_EXPECTED => { + activity.expected_of.insert(field(0), field(1)); + } + SET_PHASE => activity.step = fields.first().and_then(Value::as_str).map(str::to_owned), + BUILD_LOG_LINE if self.logs => { + let text = fields.first().and_then(Value::as_str)?; + let name = activity.name.as_deref().unwrap_or("build"); + return Some(format!("{name}> {text}")); + } + _ => {} + } + None + } + _ => None, + } + } + + /// Picks up `these 12 derivations will be built:` and the like. + fn announcement(&mut self, message: &str) { + let words: Vec<&str> = message.split_whitespace().collect(); + let count = match words.as_slice() { + ["this", ..] => 1, + ["these", count, ..] => match count.parse() { + Ok(count) => count, + Err(_) => return, + }, + _ => return, + }; + if message.contains("will be built") { + self.announced_builds += count; + } else if message.contains("will be fetched") || message.contains("will be copied") { + self.announced_paths += count; + } + } + + /// Done and expected of a kind of activity, as Nix's progress bar works them out. + fn total(&self, kind: u64) -> Count { + let finished = self.finished.get(&kind).copied().unwrap_or(0); + let running = self.activities.values().filter(|a| a.kind == kind); + let done = finished + running.clone().map(|a| a.done).sum::(); + let expected = finished + running.map(|a| a.expected).sum::(); + let expected_of: u64 = self.activities.values().filter_map(|a| a.expected_of.get(&kind)).sum(); + Count { done, total: expected.max(expected_of).max(done) } + } + + /// Whether evaluation is over: Nix has started building and fetching. + pub fn realising(&self) -> bool { + self.realising + } + + pub fn counts(&self) -> Counts { + let mut builds = self.total(BUILDS); + if self.announced_builds > 0 { + builds.total = self.announced_builds.max(builds.done); + } + let mut paths = self.total(COPY_PATHS); + paths.done = paths.done.max(self.copied); + paths.total = paths.total.max(paths.done); + if self.announced_paths > 0 { + paths.total = self.announced_paths.max(paths.done); + } + let bytes = self.total(COPY_PATH); + + let mut current: Vec<(u64, String)> = self + .activities + .iter() + .filter(|(_, a)| matches!(a.kind, BUILD | COPY_PATH)) + .filter_map(|(id, a)| { + let name = a.name.clone()?; + Some(( + *id, + match &a.step { + Some(step) if a.kind == BUILD => format!("{name}: {step}"), + _ => name, + }, + )) + }) + .collect(); + // The longest running first: activity IDs only grow. + current.sort(); + let current = current.into_iter().take(MAX_CURRENT).map(|(_, name)| name).collect(); + + let some = |count: Count| (count.total > 0).then_some(count); + Counts { builds: some(builds), paths: some(paths), bytes: some(bytes), current } + } +} + +/// Drops terminal escape sequences, which `nix` can print even into a pipe. +pub fn strip_escapes(text: &str) -> String { + let mut result = String::with_capacity(text.len()); + let mut chars = text.chars(); + while let Some(c) = chars.next() { + if c == '\x1b' { + if chars.next() == Some('[') { + for c in chars.by_ref() { + if c.is_ascii_alphabetic() { + break; + } + } + } + } else { + result.push(c); + } + } + result +} + +/// The name of a store path or derivation, like `hello-2.12` for +/// `/nix/store/…-hello-2.12.drv`, if it is one. +fn store_name(path: &str) -> Option { + let path = path.strip_suffix(".drv").unwrap_or(path); + crate::builder::is_store_path(path).then(|| path["/nix/store/".len() + 33..].to_owned()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A build of two derivations, `pt-c` then `pt-d`, recorded from Nix 2.35. + const BUILD_LOG: &str = r#"@nix {"action":"start","id":1,"level":4,"name":"BuildInstallables","parent":0,"payload":{},"text":"","type":10113} +@nix {"action":"msg","level":3,"msg":"these 2 derivations will be built:"} +@nix {"action":"msg","level":3,"msg":" /nix/store/3cpgbbhzid2g158s3dk19yaj0pjdqimg-pt-c.drv"} +@nix {"action":"msg","level":3,"msg":" /nix/store/7bhx8c640rvvnm411bq22cznbjdm735x-pt-d.drv"} +@nix {"action":"start","id":10,"level":0,"parent":0,"text":"","type":102} +@nix {"action":"start","id":11,"level":0,"parent":10,"text":"","type":104} +@nix {"action":"start","id":12,"level":0,"parent":10,"text":"","type":103} +@nix {"action":"result","fields":[0,4,0,0],"id":11,"type":105} +@nix {"action":"start","fields":["/nix/store/3cpgbbhzid2g158s3dk19yaj0pjdqimg-pt-c.drv","",1,1],"id":13,"level":3,"parent":11,"text":"building '/nix/store/3cpgbbhzid2g158s3dk19yaj0pjdqimg-pt-c.drv'","type":105} +@nix {"action":"result","fields":["buildPhase"],"id":13,"type":104} +@nix {"action":"result","fields":["line 1"],"id":13,"type":101} +@nix {"action":"result","fields":[0,2,1,0],"id":11,"type":105} +"#; + + const BUILD_END: &str = r#"@nix {"action":"stop","id":13} +@nix {"action":"result","fields":[1,3,0,0],"id":11,"type":105} +@nix {"action":"start","fields":["/nix/store/7bhx8c640rvvnm411bq22cznbjdm735x-pt-d.drv","",1,1],"id":14,"level":3,"parent":11,"text":"building","type":105} +@nix {"action":"stop","id":14} +@nix {"action":"result","fields":[2,3,0,0],"id":11,"type":105} +@nix {"action":"msg","level":1,"msg":"\u001b[35;1mwarning:\u001b[0m something"} +@nix {"action":"stop","id":11} +@nix {"action":"stop","id":12} +@nix {"action":"stop","id":10} +"#; + + /// A copy of five paths, cut short, recorded from Nix 2.35. + const COPY_LOG: &str = r#"@nix {"action":"start","id":21,"level":3,"parent":0,"text":"copying 5 paths","type":103} +@nix {"action":"result","fields":[100,38515520],"id":21,"type":106} +@nix {"action":"result","fields":[0,5,1,0],"id":21,"type":105} +@nix {"action":"start","fields":["/nix/store/r3hvhzl5fxhrgn0rfy5g7rda17702pj4-glibc-2.44-57","daemon","local://"],"id":22,"level":3,"parent":0,"text":"copying path","type":100} +@nix {"action":"start","fields":["/nix/store/sd779x86bjaqxj2lzh2jsir4h0zjz6d1-hello-2.12.3","daemon","local://"],"id":25,"level":3,"parent":0,"text":"copying path","type":100} +@nix {"action":"result","fields":[131668,279592,0,0],"id":25,"type":105} +@nix {"action":"result","fields":[279592,279592,0,0],"id":25,"type":105} +@nix {"action":"stop","id":25} +@nix {"action":"result","fields":[1,5,1,0],"id":21,"type":105} +@nix {"action":"result","fields":[162592,35578240,0,0],"id":22,"type":105} +"#; + + /// The end of a copy of two paths over `ssh-ng`, whose last count comes before the last path, + /// recorded from Nix 2.35. + const COPY_END: &str = r#"@nix {"action":"start","id":31,"level":3,"parent":0,"text":"copying 2 paths","type":103} +@nix {"action":"result","fields":[100,1495320],"id":31,"type":106} +@nix {"action":"result","fields":[0,2,1,0],"id":31,"type":105} +@nix {"action":"start","fields":["/nix/store/kxhfhki8cb10qn0sc7yz9cm7dpv5ggiy-busybox-static-x86_64-unknown-linux-musl-1.37.0","daemon","ssh-ng://cache@localhost"],"id":32,"level":3,"parent":0,"text":"copying path","type":100} +@nix {"action":"result","fields":[1495112,1495112,0,0],"id":32,"type":105} +@nix {"action":"stop","id":32} +@nix {"action":"result","fields":[1,2,1,0],"id":31,"type":105} +@nix {"action":"start","fields":["/nix/store/glccdj94cq8mgjyw12pz0mqashz50wrh-two-paths-x","daemon","ssh-ng://cache@localhost"],"id":33,"level":3,"parent":0,"text":"copying path","type":100} +@nix {"action":"result","fields":[208,208,0,0],"id":33,"type":105} +@nix {"action":"stop","id":33} +@nix {"action":"stop","id":31} +"#; + + fn feed(log: &mut NixLog, text: &str) -> Vec { + text.lines().filter_map(|line| log.line(line)).collect() + } + + #[test] + fn counts_builds() { + let mut log = NixLog::new(false); + assert!(feed(&mut log, BUILD_LOG).is_empty()); + let counts = log.counts(); + assert_eq!(counts.builds, Some(Count { done: 0, total: 2 })); + assert_eq!(counts.paths, None); + assert_eq!(counts.current, ["pt-c: buildPhase"]); + + assert_eq!(feed(&mut log, BUILD_END), ["warning: something"]); + let counts = log.counts(); + assert_eq!(counts.builds, Some(Count { done: 2, total: 2 })); + assert!(counts.current.is_empty()); + } + + #[test] + fn notices_when_evaluation_ends() { + let mut log = NixLog::new(false); + let evaluating = r#"@nix {"action":"start","id":1,"level":4,"type":0,"text":"evaluating derivation 'x'"}"#; + log.line(evaluating); + assert!(!log.realising()); + log.line(r#"@nix {"action":"start","id":2,"level":0,"type":102,"text":""}"#); + assert!(log.realising()); + } + + #[test] + fn passes_build_logs_through_when_asked() { + let mut log = NixLog::new(true); + let shown = feed(&mut log, BUILD_LOG); + assert!(shown.contains(&"these 2 derivations will be built:".to_owned()), "{shown:?}"); + assert!(shown.contains(&"pt-c> line 1".to_owned()), "{shown:?}"); + assert!(shown.iter().any(|l| l.starts_with("building '")), "{shown:?}"); + } + + #[test] + fn counts_copies() { + let mut log = NixLog::new(false); + feed(&mut log, COPY_LOG); + let counts = log.counts(); + assert_eq!(counts.paths, Some(Count { done: 1, total: 5 })); + assert_eq!(counts.bytes, Some(Count { done: 279592 + 162592, total: 38515520 })); + assert_eq!(counts.current, ["glibc-2.44-57"]); + } + + #[test] + fn counts_the_last_path_copied() { + let mut log = NixLog::new(false); + feed(&mut log, COPY_END); + let counts = log.counts(); + assert_eq!(counts.paths, Some(Count { done: 2, total: 2 })); + assert_eq!(counts.bytes, Some(Count { done: 1495320, total: 1495320 })); + } + + #[test] + fn keeps_other_output() { + let mut log = NixLog::new(false); + assert_eq!( + log.line("ssh: connect to host river: refused").as_deref(), + Some("ssh: connect to host river: refused") + ); + assert_eq!(log.line("@nix {not json").as_deref(), Some("@nix {not json")); + assert_eq!(log.line(r#"@nix {"action":"result","id":99,"type":105,"fields":[1,2]}"#), None); + } + + #[test] + fn strips_escapes() { + assert_eq!(strip_escapes("source: \x1b[31;1m3.6 GiB\x1b[0m"), "source: 3.6 GiB"); + } + + #[test] + fn names_only_store_paths() { + assert_eq!(store_name("/nix/store/3cpgbbhzid2g158s3dk19yaj0pjdqimg-pt-c.drv").as_deref(), Some("pt-c")); + assert_eq!(store_name("/nix/store/3cpgbbhzid2g158s3dk19yaj0pjdqimg-a\x1b[31m"), None); + assert_eq!(store_name("/etc/passwd"), None); + } + + #[test] + fn describes_progress() { + let mut progress = Progress { + phase: Phase::Build, + state: State::Running, + elapsed: 250, + counts: Counts { + builds: Some(Count { done: 37, total: 120 }), + paths: Some(Count { done: 10, total: 40 }), + bytes: Some(Count { done: 3 << 20, total: 3 << 30 }), + current: vec!["firefox-147.0".into()], + }, + }; + assert_eq!( + progress.line(), + "building: 37/120 derivations, 10/40 paths fetched (3.00 MiB/3.00 GiB) (firefox-147.0), 4m 10s" + ); + assert_eq!(progress.bar(), Some(Count { done: 37, total: 120 })); + + progress.state = State::Done; + assert_eq!(progress.line(), "built: 37 derivations, 10 paths fetched (3.00 MiB) in 4m 10s"); + + let copy = Progress { + phase: Phase::Copy("river".into()), + state: State::Failed, + elapsed: 3, + counts: Counts::default(), + }; + assert_eq!(copy.line(), "copying to river failed in 3s"); + assert_eq!(copy.bar(), None); + } + + #[test] + fn formats_times() { + assert_eq!(elapsed(0), "0s"); + assert_eq!(elapsed(250), "4m 10s"); + assert_eq!(elapsed(3725), "1h 2m"); + } +} diff --git a/src/proto.rs b/src/proto.rs index e62b25d..b6171c8 100644 --- a/src/proto.rs +++ b/src/proto.rs @@ -14,6 +14,7 @@ use tokio::io::{AsyncRead, AsyncWrite}; use tokio_util::codec::{Framed, LengthDelimitedCodec}; use crate::audit::Record; +use crate::progress::Progress; use crate::queue::{Decision, PendingInfo}; use crate::types::{ Arg, CommitId, ContainerName, DeployTarget, FlakeAttr, HostName, Lines, NodeName, Recipient, SecretKey, SecretPath, @@ -21,7 +22,7 @@ use crate::types::{ }; /// Bumped on any incompatible change; the broker refuses other versions. -pub const PROTOCOL_VERSION: u32 = 3; +pub const PROTOCOL_VERSION: u32 = 4; pub const MAX_MESSAGE: usize = 1 << 20; /// Bytes of an `ssh` request's command and stdin together: all of it is shown to approvers. pub const MAX_SSH_SHOWN: usize = 32 * 1024; @@ -67,10 +68,17 @@ pub enum Operation { commit: CommitId, /// Make it the boot default without switching to it. boot: bool, + /// Stream build logs, not only progress. + logs: bool, }, /// Builds flake attributes of a pushed commit and, once approved, pushes them to the binary /// cache. - Build { attrs: Vec, commit: CommitId }, + Build { + attrs: Vec, + commit: CommitId, + /// Stream build logs, not only progress. + logs: bool, + }, /// Works with an age secret the requester sends; the broker returns new ciphertext and never /// writes to a checkout. Secret(SecretOp), @@ -249,6 +257,8 @@ pub enum ServerMessage { }, /// Progress from the broker itself. Info(String), + /// How a phase of a build, copy or deploy is going. + Progress(Box), Stdout(#[serde(with = "serde_bytes")] Vec), Stderr(#[serde(with = "serde_bytes")] Vec), /// The operation ran; `exit` is its status and `result` any structured output. diff --git a/src/runs.rs b/src/runs.rs new file mode 100644 index 0000000..e60b398 --- /dev/null +++ b/src/runs.rs @@ -0,0 +1,150 @@ +//! Requests that build, copy or activate, with each phase's latest progress, while they run. +//! The web app shows them, and their final phases go in the audit log. +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::Instant; + +use tokio::sync::watch; + +use crate::progress::{Phases, Progress}; + +pub struct Runs { + runs: Mutex>, + /// Bumped on every change, progress included. + changed: watch::Sender, + /// Bumped when a run starts or ends. + members: watch::Sender, +} + +#[derive(Debug, Clone)] +pub struct Run { + pub id: String, + pub requester: String, + pub op: String, + pub summary: String, + started: Instant, + pub phases: Phases, +} + +impl Run { + pub fn elapsed(&self) -> u64 { + self.started.elapsed().as_secs() + } +} + +impl Default for Runs { + fn default() -> Runs { + Runs { runs: Mutex::default(), changed: watch::Sender::new(0), members: watch::Sender::new(0) } + } +} + +impl Runs { + /// Tracks a request until the guard is dropped. + pub fn start(self: &Arc, id: &str, requester: &str, op: &str, summary: &str) -> Tracked { + let run = Run { + id: id.into(), + requester: requester.into(), + op: op.into(), + summary: summary.into(), + started: Instant::now(), + phases: Phases::default(), + }; + self.runs.lock().unwrap().insert(id.into(), run); + self.bump(true); + Tracked { runs: self.clone(), id: id.into() } + } + + pub fn record(&self, id: &str, progress: &Progress) { + { + let mut runs = self.runs.lock().unwrap(); + let Some(run) = runs.get_mut(id) else { return }; + run.phases.record(progress); + } + self.bump(false); + } + + /// A run's phases so far, for the audit log. + pub fn phases(&self, id: &str) -> Vec { + self.runs.lock().unwrap().get(id).map(|r| r.phases.as_slice().to_vec()).unwrap_or_default() + } + + pub fn get(&self, id: &str) -> Option { + self.runs.lock().unwrap().get(id).cloned() + } + + /// Every run, the oldest first. + pub fn list(&self) -> Vec { + let mut runs: Vec = self.runs.lock().unwrap().values().cloned().collect(); + runs.sort_by_key(|r| r.started); + runs + } + + /// Changes on every update. + pub fn subscribe(&self) -> watch::Receiver { + self.changed.subscribe() + } + + /// Changes when a run starts or ends. + pub fn members(&self) -> u64 { + *self.members.borrow() + } + + fn bump(&self, members: bool) { + self.changed.send_modify(|v| *v += 1); + if members { + self.members.send_modify(|v| *v += 1); + } + } +} + +/// A run in [`Runs`], until it's dropped. +pub struct Tracked { + runs: Arc, + id: String, +} + +impl Drop for Tracked { + fn drop(&mut self) { + self.runs.runs.lock().unwrap().remove(&self.id); + self.runs.bump(true); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::progress::{Count, Counts, Phase, State}; + + fn progress(phase: Phase, state: State) -> Progress { + Progress { phase, state, elapsed: 1, counts: Counts::default() } + } + + #[test] + fn follows_nodes_through_their_phases() { + let runs = Arc::new(Runs::default()); + let tracked = runs.start("a", "agent", "deploy", "deploy river, stream"); + let members = runs.members(); + + runs.record("a", &progress(Phase::Build, State::Done)); + runs.record("a", &progress(Phase::Copy("river".into()), State::Done)); + runs.record("a", &progress(Phase::Compare("river".into()), State::Running)); + runs.record("a", &progress(Phase::Copy("stream".into()), State::Running)); + runs.record("nope", &progress(Phase::Build, State::Running)); + assert_eq!(runs.members(), members); + + let phases = runs.get("a").unwrap().phases; + assert_eq!(phases.overall().len(), 1); + let nodes = phases.nodes(); + assert_eq!( + nodes.iter().map(|n| (n.node.as_str(), n.state)).collect::>(), + [("river", "comparing"), ("stream", "copying")] + ); + assert!(nodes[0].copy.is_some()); + assert_eq!(phases.bar(), Some(Count { done: 1, total: 6 })); + assert_eq!(phases.status(), "copying to stream, 1s"); + + drop(tracked); + assert!(runs.get("a").is_none() && runs.phases("a").is_empty()); + assert_ne!(runs.members(), members); + } +} diff --git a/src/server.rs b/src/server.rs index b05c04d..c0ec48c 100644 --- a/src/server.rs +++ b/src/server.rs @@ -21,6 +21,7 @@ use crate::ops; use crate::policy::{self, Action}; use crate::proto::{ApprovedBy, ClientMessage, PROTOCOL_VERSION, Request, ServerMessage, decode, encode, transport}; use crate::queue::{NewRequest, Outcome, Queue, new_id}; +use crate::runs::Runs; use crate::targets::Targets; /// The most stdin a requester may send. Operations that read it have their own, smaller limits; @@ -32,6 +33,7 @@ pub struct Broker { pub queue: Queue, pub audit: Audit, pub targets: Targets, + pub runs: Arc, } impl Broker { @@ -40,7 +42,7 @@ impl Broker { let queue = Queue::new(Duration::from_secs(config.timeout), config.max_pending); let audit = Audit::new(config.audit_log.as_deref())?; let targets = Targets::new(&config); - Ok(Broker { config, queue, audit, targets }) + Ok(Broker { config, queue, audit, targets, runs: Arc::default() }) } } @@ -113,7 +115,7 @@ pub async fn handle(broker: Arc { - log(Event::Finished { id, exit: outcome.exit, seconds: start.elapsed().as_secs_f64() }); + let (seconds, phases) = (start.elapsed().as_secs_f64(), broker.runs.phases(&id)); + log(Event::Finished { id, exit: outcome.exit, seconds, phases }); Some(ServerMessage::Finished { exit: outcome.exit, result: outcome.result }) } Err(error) => { let error = format!("{error:#}"); - log(Event::Failed { id, error: error.clone() }); + let phases = broker.runs.phases(&id); + log(Event::Failed { id, error: error.clone(), phases }); Some(ServerMessage::Error(error)) } } diff --git a/src/targets.rs b/src/targets.rs index f257a3a..211b631 100644 --- a/src/targets.rs +++ b/src/targets.rs @@ -63,7 +63,7 @@ impl Targets { } // Nobody sees the builder's progress: this is the broker's own business. - let out = Output(mpsc::channel(1).0); + let out = Output::new(mpsc::channel(1).0); let result = crate::builder::nodes(ssh, deploy, &out, &CancellationToken::new()).await; *looked = Some((Instant::now(), result.is_ok())); match result { @@ -164,6 +164,7 @@ mod tests { targets: vec!["web".parse().unwrap(), "river.system".parse().unwrap()], commit: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(), boot: false, + logs: false, }; assert_eq!(nodes(&deploy), [("web", None), ("river", None)]); let query = Operation::Query { diff --git a/src/terminal.rs b/src/terminal.rs new file mode 100644 index 0000000..6288bae --- /dev/null +++ b/src/terminal.rs @@ -0,0 +1,374 @@ +//! What `slop` shows of progress on stderr. +//! +//! - On a terminal, bars stay below other output, drawn by `indicatif`: one for each running +//! phase that isn't about a node (evaluating, building, pushing), and one for each node, through +//! its copy, comparison and activation. Other output can stop mid-line, and bars drawn then +//! would overwrite the rest of the line, so they're hidden until the line ends. +//! - Otherwise (for agents), a phase gets a plain line every [`SUMMARY_INTERVAL`] while it runs, +//! and one when it ends, with no control characters. +use std::collections::HashMap; +use std::io::Write; +use std::time::{Duration, Instant}; + +use indicatif::{MultiProgress, ProgressBar, ProgressDrawTarget, ProgressStyle}; + +use crate::progress::{NodeRow, Phase, Phases, Progress, State, elapsed}; + +/// How often a running phase gets a line without a terminal. +pub const SUMMARY_INTERVAL: Duration = Duration::from_secs(30); + +/// How often the bars are drawn again. +const TICK: Duration = Duration::from_millis(100); + +pub struct Board { + /// The bars, on a terminal. + bars: Option, + /// When each running phase last had a line, without a terminal. + said: HashMap, +} + +struct Bars { + multi: MultiProgress, + /// Where they're drawn: stderr, except in tests. + target: Box ProgressDrawTarget + Send>, + phases: Phases, + /// The bars, with what they're for and their labels. + bars: Vec<(Key, String, ProgressBar)>, + /// Whether other output stopped mid-line, which hides the bars. + mid_line: bool, +} + +/// What a bar is for. +#[derive(Debug, Clone, PartialEq)] +enum Key { + Phase(Phase), + Node(String), +} + +impl Board { + /// Bars if `indicatif` would draw them on stderr, lines otherwise: it draws nothing at all, + /// not even lines above the bars, if stderr isn't a terminal or `TERM` is `dumb`. + pub fn new() -> Board { + Board::with_target(ProgressDrawTarget::stderr) + } + + /// Bars drawn on `target`, unless it's hidden. + fn with_target(target: impl Fn() -> ProgressDrawTarget + Send + 'static) -> Board { + let bars = (!target().is_hidden()).then(|| Bars { + multi: MultiProgress::with_draw_target(target()), + target: Box::new(target), + phases: Phases::default(), + bars: Vec::new(), + mid_line: false, + }); + Board { bars, said: HashMap::new() } + } + + /// Shows a phase's progress: its bar, or a line when it's due or the phase ends. + pub fn update(&mut self, progress: &Progress) { + let ended = progress.state != State::Running; + let line = format!("slop: {}", progress.line()); + + let Some(bars) = &mut self.bars else { + let due = self.said.get(&progress.phase).is_none_or(|said| said.elapsed() >= SUMMARY_INTERVAL); + if ended { + self.said.remove(&progress.phase); + eprintln!("{line}"); + } else if due { + // Not the first: a phase starting doesn't need a line of its own + if self.said.contains_key(&progress.phase) { + eprintln!("{line}"); + } + self.said.insert(progress.phase.clone(), Instant::now()); + } + return; + }; + + // Progress always starts on a line of its own. + bars.line_ended(true); + bars.phases.record(progress); + if ended { + let _ = bars.multi.println(line); + } + + match progress.phase.node() { + None if ended => bars.remove(&Key::Phase(progress.phase.clone())), + None => { + let bar = bars.bar(Key::Phase(progress.phase.clone()), progress.phase.doing()); + show(&bar, progress, details(progress)); + } + Some(node) => { + let row = bars.phases.node(node).expect("just recorded"); + let key = Key::Node(node.to_owned()); + if row.ended() { + bars.remove(&key); + } else { + let bar = bars.bar(key, node.to_owned()); + show(&bar, &row.latest, node_details(&row)); + } + } + } + } + + /// Writes other output, keeping it clear of the bars. + pub fn write(&mut self, out: &mut impl Write, data: &[u8]) -> std::io::Result<()> { + let Some(bars) = &mut self.bars else { + out.write_all(data)?; + return out.flush(); + }; + if data.is_empty() { + return Ok(()); + } + + bars.multi.suspend(|| { + out.write_all(data)?; + out.flush() + })?; + bars.line_ended(data.ends_with(b"\n")); + Ok(()) + } + + /// Writes a line of `slop`'s own, above the bars. + pub fn say(&mut self, line: &str) { + match &mut self.bars { + Some(bars) => { + bars.line_ended(true); + let _ = bars.multi.println(line); + } + None => eprintln!("{line}"), + } + } + + /// Takes the bars off the terminal, before `slop` exits. + pub fn clear(&mut self) { + if let Some(bars) = &mut self.bars { + for (_, _, bar) in bars.bars.drain(..) { + bar.finish_and_clear(); + } + let _ = bars.multi.clear(); + } + } +} + +impl Default for Board { + fn default() -> Board { + Board::new() + } +} + +impl Bars { + /// The bar for `key`, added with `label` if there isn't one. + fn bar(&mut self, key: Key, label: String) -> ProgressBar { + if let Some((_, _, bar)) = self.bars.iter().find(|(k, _, _)| *k == key) { + return bar.clone(); + } + let bar = self.multi.add(ProgressBar::no_length().with_style(style())); + // `indicatif` drops draws that come too close together, which would leave a stale bar + // until the next update; ticking draws the latest soon after. + bar.enable_steady_tick(TICK); + self.bars.push((key, label, bar.clone())); + self.align(); + bar + } + + fn remove(&mut self, key: &Key) { + if let Some(index) = self.bars.iter().position(|(k, _, _)| k == key) { + let (_, _, bar) = self.bars.remove(index); + bar.finish_and_clear(); + self.multi.remove(&bar); + self.align(); + } + } + + /// Pads the labels to the longest, so the bars line up. + fn align(&self) { + let width = self.bars.iter().map(|(_, label, _)| label.chars().count()).max().unwrap_or(0); + for (_, label, bar) in &self.bars { + bar.set_prefix(format!("{label:width$}")); + } + } + + /// Notes whether other output ended its line, hiding the bars until it does. When a line is + /// due and the last one didn't end, it ends it. + fn line_ended(&mut self, ended: bool) { + if !ended { + if !self.mid_line { + self.multi.set_draw_target(ProgressDrawTarget::hidden()); + self.mid_line = true; + } + return; + } + if self.mid_line { + // The line other output left unfinished, for what comes next + eprintln!(); + self.multi.set_draw_target((self.target)()); + self.mid_line = false; + } + } +} + +/// A bar's layout, like `building ▕████▌ ▏ 37/120 derivations · firefox-147.0 · 1m 2s`. +fn style() -> ProgressStyle { + ProgressStyle::with_template("{prefix} ▕{bar:20}▏ {wide_msg}").unwrap().progress_chars("█▉▊▋▌▍▎▏ ") +} + +/// Moves a bar to a phase's progress: its count, empty while it has none, or full once it's +/// done. The length and position change together. +fn show(bar: &ProgressBar, progress: &Progress, message: String) { + // The text first, so the bar and its count move together + bar.set_message(message); + match (progress.state, progress.bar()) { + (State::Running, Some(count)) => bar.update(|state| { + state.set_len(count.total); + state.set_pos(count.done); + }), + (State::Running, None) => bar.unset_length(), + _ => bar.update(|state| { + state.set_len(1); + state.set_pos(1); + }), + } +} + +/// What follows a node's bar: what it's doing, and while it runs, the counts and the time. +fn node_details(row: &NodeRow) -> String { + match row.latest.state { + State::Running => format!("{} · {}", row.state, details(&row.latest)), + _ => row.state.to_owned(), + } +} + +/// What follows a bar: the counts, what's running now and the time. +fn details(progress: &Progress) -> String { + let counted = progress.counted(false); + let parts = [(!counted.is_empty()).then_some(counted), progress.current(), Some(elapsed(progress.elapsed))]; + parts.into_iter().flatten().collect::>().join(" · ") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::progress::{Count, Counts}; + use indicatif::InMemoryTerm; + + fn running(done: u64) -> Progress { + Progress { + phase: Phase::Build, + state: State::Running, + elapsed: 62, + counts: Counts { + builds: Some(Count { done, total: 8 }), + bytes: Some(Count { done: 1024, total: 4096 }), + current: vec!["firefox-147.0".into()], + ..Counts::default() + }, + } + } + + #[test] + fn details_follow_the_bar() { + assert_eq!(details(&running(3)), "3/8 derivations · firefox-147.0 · 1m 2s"); + let starting = Progress { counts: Counts::default(), elapsed: 0, ..running(0) }; + assert_eq!(details(&starting), "0s"); + } + + /// A board drawing on a terminal in memory, 80 columns wide, at most 20 times a second like + /// on stderr. + fn on_screen() -> (Board, InMemoryTerm) { + let term = InMemoryTerm::new(12, 80); + let target = term.clone(); + (Board::with_target(move || ProgressDrawTarget::term_like_with_hz(Box::new(target.clone()), 20)), term) + } + + /// What's on the screen once the bars have ticked, without trailing spaces. + fn screen(term: &InMemoryTerm) -> Vec { + std::thread::sleep(TICK * 3); + term.contents().lines().map(|l| l.trim_end().to_owned()).filter(|l| !l.is_empty()).collect() + } + + #[test] + fn keeps_track_of_bars() { + let (mut board, _term) = on_screen(); + board.update(&running(3)); + board.update(&running(4)); + let bars = board.bars.as_ref().unwrap(); + assert_eq!(bars.bars.len(), 1); + assert_eq!(bars.bars[0].2.position(), 4); + + // Output stopping mid-line hides the bars until the line ends. + board.write(&mut Vec::new(), b"partial").unwrap(); + assert!(board.bars.as_ref().unwrap().mid_line); + board.write(&mut Vec::new(), b" line\n").unwrap(); + assert!(!board.bars.as_ref().unwrap().mid_line); + + board.update(&Progress { state: State::Done, ..running(8) }); + assert!(board.bars.as_ref().unwrap().bars.is_empty()); + } + + #[test] + fn keeps_a_bar_for_each_node() { + let (mut board, _term) = on_screen(); + let phase = |phase, state| Progress { phase, state, elapsed: 1, counts: Counts::default() }; + let labels = |board: &Board| -> Vec { + board.bars.as_ref().unwrap().bars.iter().map(|(_, _, bar)| bar.prefix()).collect() + }; + + board.update(&phase(Phase::Copy("river".into()), State::Running)); + board.update(&phase(Phase::Copy("stream".into()), State::Running)); + board.update(&phase(Phase::Copy("river".into()), State::Done)); + board.update(&phase(Phase::Compare("river".into()), State::Running)); + board.update(&phase(Phase::Push, State::Running)); + assert_eq!(labels(&board), ["river ", "stream ", "pushing to the cache"]); + assert_eq!(board.bars.as_ref().unwrap().bars[0].2.message(), "comparing · 1s"); + + // A node's bar goes once it's activated, or failed. + board.update(&phase(Phase::Activate("river".into()), State::Done)); + board.update(&phase(Phase::Copy("stream".into()), State::Failed)); + assert_eq!(labels(&board), ["pushing to the cache"]); + } + + #[test] + fn says_little_without_a_terminal() { + // As when stderr isn't a terminal, or `TERM` is `dumb` + let mut board = Board::with_target(ProgressDrawTarget::hidden); + assert!(board.bars.is_none()); + board.update(&running(3)); + board.update(&running(4)); + assert!(board.said.contains_key(&Phase::Build)); + board.update(&Progress { state: State::Failed, ..running(4) }); + assert!(board.said.is_empty()); + } + + #[test] + fn draws_a_node_through_its_steps() { + let (mut board, term) = on_screen(); + let paths = |done| Counts { paths: Some(Count { done, total: 4 }), ..Counts::default() }; + let copy = + |state, done| Progress { phase: Phase::Copy("river".into()), state, elapsed: 2, counts: paths(done) }; + let phase = |phase, state| Progress { phase, state, elapsed: 1, counts: Counts::default() }; + + board.update(©(State::Running, 1)); + assert_eq!(screen(&term), ["river ▕█████▏ ▏ copying · 1/4 paths · 2s"]); + + // Comparing has no count, so its bar is empty, not the copy's. Updates coming fast use up + // the draws `indicatif` allows, which mustn't leave the screen behind. + for _ in 0..50 { + board.update(©(State::Running, 3)); + } + board.update(©(State::Done, 4)); + board.update(&phase(Phase::Compare("river".into()), State::Running)); + assert_eq!( + screen(&term), + ["slop: copied to river: 4 paths in 2s", "river ▕ ▏ comparing · 1s"] + ); + + // Compared, and waiting for the deploy's approval + board.update(&phase(Phase::Compare("river".into()), State::Done)); + assert_eq!(screen(&term)[2], "river ▕████████████████████▏ ready"); + + // Activated: the bar goes, and the line stays. + board.update(&phase(Phase::Activate("river".into()), State::Running)); + board.update(&phase(Phase::Activate("river".into()), State::Done)); + assert_eq!(screen(&term).last().unwrap(), "slop: activated river in 1s"); + } +} diff --git a/src/web/assets/style.css b/src/web/assets/style.css index 946f19a..305e1b0 100644 --- a/src/web/assets/style.css +++ b/src/web/assets/style.css @@ -474,3 +474,120 @@ table.log .label { color: var(--muted); font-size: 0.85rem; } + +/* Progress of running requests: native bars, coloured by state. */ +progress { + appearance: none; + width: 100%; + max-width: 24rem; + height: 10px; + border: none; + border-radius: 5px; + background: var(--code-bg); + vertical-align: middle; + overflow: hidden; +} + +progress::-webkit-progress-bar { + background: var(--code-bg); + border-radius: 5px; +} + +progress::-webkit-progress-value { + background: var(--active); + border-radius: 5px; +} + +progress::-moz-progress-bar { + background: var(--active); + border-radius: 5px; +} + +progress.good::-webkit-progress-value { + background: var(--good); +} + +progress.good::-moz-progress-bar { + background: var(--good); +} + +progress.bad::-webkit-progress-value { + background: var(--bad); +} + +progress.bad::-moz-progress-bar { + background: var(--bad); +} + +section.progress { + background: var(--surface); + border: 1px solid var(--border); + border-radius: 8px; + padding: 12px 14px; + margin-bottom: 14px; +} + +.phase { + margin: 10px 0; +} + +.phase-title { + margin: 0 0 4px; +} + +/* A phase's bar spans its section, like a running request's in the list. */ +.phase progress { + display: block; + max-width: none; +} + +.phase .current code { + overflow-wrap: anywhere; +} + +table.nodes { + width: 100%; + margin-top: 8px; +} + +table.nodes td { + vertical-align: middle; +} + +/* The copy column takes the table's spare width, its counts under the bar. */ +table.nodes progress { + display: block; + min-width: 8rem; + max-width: none; +} + +table.nodes td.copy { + width: 100%; +} + +#running h2 { + margin-top: 20px; +} + +ul.runs { + list-style: none; + padding: 0; +} + +ul.runs li { + background: var(--surface); + border: 1px solid var(--border); + border-radius: 8px; + padding: 8px 12px; + margin-bottom: 8px; +} + +ul.runs progress { + display: block; + max-width: none; + margin: 6px 0 2px; +} + +ul.phases li.bad { + color: var(--bad); +} diff --git a/src/web/events.rs b/src/web/events.rs index 3c27590..ff2ff17 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -2,10 +2,12 @@ //! //! - Each `morph` event carries a region of the page: a whole element with its `id`, which the //! page script morphs into the one it has, so open details and the focus stay. The main page's -//! region is the pending list (`#pending`), and a request's page's is the request (`#request`). +//! regions are the pending list (`#pending`) and the running requests (`#running`), and a +//! request's page's is the request (`#request`), with its progress while it runs. //! - A region comes when the stream starts, so a page catches up after reconnecting, and then //! whenever it changes. //! - `signed-out` ends the stream, when the approver signs out or the session expires. +use std::collections::HashMap; use std::convert::Infallible; use std::future::Future; use std::pin::Pin; @@ -14,9 +16,11 @@ use std::time::{Duration, Instant}; use axum::response::sse::{Event, KeepAlive, Sse}; use axum::response::{IntoResponse, Response}; +use futures_util::StreamExt; use tokio::sync::watch; use tower_sessions::Session; +use super::history::History; use super::{User, page}; use crate::server::Broker; @@ -34,9 +38,11 @@ pub fn stream(broker: Arc, session: Session, request: Option) -> let updates = Updates::new(broker, signed_in, request); let events = futures_util::stream::unfold(updates, |mut updates| async move { - let (name, data) = updates.next().await?; - Some((Ok::<_, Infallible>(Event::default().event(name).data(data)), updates)) - }); + let events = updates.next().await?; + Some((futures_util::stream::iter(events), updates)) + }) + .flatten() + .map(|(name, data)| Ok::<_, Infallible>(Event::default().event(name).data(data))); let mut response = Sse::new(events).keep_alive(KeepAlive::default()).into_response(); // Proxies such as nginx would otherwise hold events back. @@ -50,57 +56,96 @@ struct Updates { /// The request whose page it is, or none for the main page. request: Option, queue: watch::Receiver, - /// The region last sent. - sent: Option, + runs: watch::Receiver, + /// What the audit log has of the request, read again when the queue changes or a run starts + /// or ends, rather than with every bit of progress. + past: Option, + members: Option, + /// Each region last sent, by `id`. + sent: HashMap<&'static str, String>, last: Option, ended: bool, } impl Updates { fn new(broker: Arc, signed_in: SignedIn, request: Option) -> Updates { - let queue = broker.queue.subscribe(); - Updates { broker, signed_in, request, queue, sent: None, last: None, ended: false } + let (queue, runs) = (broker.queue.subscribe(), broker.runs.subscribe()); + Updates { + broker, + signed_in, + request, + queue, + runs, + past: None, + members: None, + sent: HashMap::new(), + last: None, + ended: false, + } } - /// The next event, as a name and data, once something changes; `None` ends the stream. - async fn next(&mut self) -> Option<(&'static str, String)> { + /// The next events, as names and data, once something changes; `None` ends the stream. + async fn next(&mut self) -> Option> { if self.ended { return None; } loop { - // The region at first, then when it changes, at most once an interval + // The regions at first, then the ones that change, at most once an interval + let mut queue_changed = self.last.is_none(); if let Some(last) = self.last { - self.queue.changed().await.ok()?; + queue_changed = tokio::select! { + changed = self.queue.changed() => changed.map(|()| true).ok()?, + changed = self.runs.changed() => changed.map(|()| false).ok()?, + }; tokio::time::sleep(INTERVAL.saturating_sub(last.elapsed())).await; } self.last = Some(Instant::now()); + queue_changed |= self.queue.has_changed().unwrap_or(false); self.queue.borrow_and_update(); + self.runs.borrow_and_update(); // Signing out, or the session expiring, ends it. let Some(csrf) = (self.signed_in)().await else { self.ended = true; - return Some(("signed-out", "signed out".into())); + return Some(vec![("signed-out", "signed out".into())]); }; - let region = self.region(&csrf); - if self.sent.as_ref() != Some(®ion) { - self.sent = Some(region.clone()); - return Some(("morph", region)); + let events: Vec<_> = self + .regions(&csrf, queue_changed) + .into_iter() + .filter(|(id, region)| self.sent.get(id) != Some(region)) + .collect(); + for (id, region) in &events { + self.sent.insert(id, region.clone()); + } + if !events.is_empty() { + return Some(events.into_iter().map(|(_, region)| ("morph", region)).collect()); } } } - fn region(&self, csrf: &str) -> String { - match &self.request { - None => page::pending(csrf, &self.broker.queue.list(), &self.broker.queue.all_leases()), - Some(id) => { - let entry = self.broker.queue.list().into_iter().find(|e| &e.id == id); - let past = super::past(&self.broker, id); - let view = page::RequestView { id, entry: entry.as_ref(), past: past.as_ref() }; - page::request_region(csrf, &view) + /// The page's regions now, by `id`. + fn regions(&mut self, csrf: &str, queue_changed: bool) -> Vec<(&'static str, String)> { + let queue = &self.broker.queue; + let Some(id) = self.request.clone() else { + let mut regions = Vec::new(); + if queue_changed { + regions.push(("pending", page::pending(csrf, &queue.list(), &queue.all_leases()))); } + regions.push(("running", page::running_list(&self.broker.runs.list()))); + return regions; + }; + + let members = self.broker.runs.members(); + if queue_changed || self.members != Some(members) { + self.members = Some(members); + self.past = super::past(&self.broker, &id); } + let entry = queue.list().into_iter().find(|e| e.id == id); + let run = self.broker.runs.get(&id); + let view = page::RequestView { id: &id, entry: entry.as_ref(), run: run.as_ref(), past: self.past.as_ref() }; + vec![("request", page::request_region(csrf, &view))] } } @@ -110,6 +155,7 @@ mod tests { use super::*; use crate::detail::Detail; + use crate::progress::{Counts, Phase, Progress, State}; use crate::queue::NewRequest; fn broker() -> Arc { @@ -138,8 +184,12 @@ mod tests { broker.queue.submit(id, request, 4).unwrap() } + fn names(events: &[(&'static str, String)]) -> Vec<&'static str> { + events.iter().map(|(name, _)| *name).collect() + } + #[tokio::test] - async fn the_main_page_gets_its_list_as_it_changes() { + async fn the_main_page_gets_its_regions_as_they_change() { let broker = broker(); let signed_out = Arc::new(AtomicBool::new(false)); let check = signed_out.clone(); @@ -149,39 +199,59 @@ mod tests { }); let mut updates = Updates::new(broker.clone(), signed_in, None); - // The list to start with, as a whole element - let (name, data) = updates.next().await.unwrap(); - assert_eq!(name, "morph"); - assert!(data.starts_with(r#"
"#) && data.contains("Nothing is waiting"), "{data}"); + // Both regions to start with, as whole elements + let events = updates.next().await.unwrap(); + assert_eq!(names(&events), ["morph", "morph"]); + assert!(events[0].1.starts_with(r#"
"#) && events[0].1.contains("Nothing is waiting")); + assert!(events[1].1.starts_with(r#"
"#), "{events:?}"); - // A new request, then its leaving + // A new request changes only the pending list, and its leaving too let _reply = submit(&broker, "abc"); - let (_, data) = updates.next().await.unwrap(); - assert!(data.contains("ssh river"), "{data}"); + let events = updates.next().await.unwrap(); + assert!(events.len() == 1 && events[0].1.contains("ssh river"), "{events:?}"); broker.queue.cancel("abc"); - let (_, data) = updates.next().await.unwrap(); - assert!(data.contains("Nothing is waiting"), "{data}"); + let events = updates.next().await.unwrap(); + assert!(events.len() == 1 && events[0].1.contains("Nothing is waiting"), "{events:?}"); + + // A run starting, its progress and its end change only the running list + let tracked = broker.runs.start("def", "agent", "deploy", "deploy river"); + let events = updates.next().await.unwrap(); + assert!(events.len() == 1 && events[0].1.contains("deploy river"), "{events:?}"); + let progress = Progress { phase: Phase::Build, state: State::Running, elapsed: 1, counts: Counts::default() }; + broker.runs.record("def", &progress); + let events = updates.next().await.unwrap(); + assert!(events.len() == 1 && events[0].1.contains("building"), "{events:?}"); + drop(tracked); + let events = updates.next().await.unwrap(); + assert!(events.len() == 1 && !events[0].1.contains("deploy river"), "{events:?}"); signed_out.store(true, Ordering::SeqCst); - let _reply = submit(&broker, "def"); - assert_eq!(updates.next().await.unwrap().0, "signed-out"); + let _reply = submit(&broker, "ghi"); + assert_eq!(names(&updates.next().await.unwrap()), ["signed-out"]); assert!(updates.next().await.is_none()); } #[tokio::test] - async fn a_request_page_gets_its_request() { + async fn a_request_page_gets_its_request_and_progress() { let broker = broker(); let signed_in: SignedIn = Box::new(|| Box::pin(async { Some("token".to_owned()) })); let mut updates = Updates::new(broker.clone(), signed_in, Some("abc".into())); - let (_, data) = updates.next().await.unwrap(); - assert!(data.starts_with(r#"
"#), "{data}"); - assert!(data.contains("The audit log has nothing"), "{data}"); + let events = updates.next().await.unwrap(); + assert!(events[0].1.starts_with(r#"
"#), "{events:?}"); + assert!(events[0].1.contains("The audit log has nothing"), "{events:?}"); // Other requests change nothing here, so nothing comes until this one does let _other = submit(&broker, "xyz"); let _reply = submit(&broker, "abc"); - let (_, data) = updates.next().await.unwrap(); - assert!(data.contains("

ssh river

"), "{data}"); + let events = updates.next().await.unwrap(); + assert!(events[0].1.contains("

ssh river

"), "{events:?}"); + + // Its run shows while it's waiting too, as for a deploy that's built + let _tracked = broker.runs.start("abc", "agent", "deploy", "deploy river"); + let progress = Progress { phase: Phase::Build, state: State::Done, elapsed: 1, counts: Counts::default() }; + broker.runs.record("abc", &progress); + let events = updates.next().await.unwrap(); + assert!(events[0].1.contains("ssh river") && events[0].1.contains("built"), "{events:?}"); } } diff --git a/src/web/history.rs b/src/web/history.rs index 83a5428..4583b33 100644 --- a/src/web/history.rs +++ b/src/web/history.rs @@ -2,7 +2,8 @@ use std::collections::HashMap; use crate::audit::{Event, Record, Shown}; -use crate::detail::Detail; +use crate::detail::{Detail, Section}; +use crate::progress::Progress; use crate::proto::ApprovedBy; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -70,6 +71,8 @@ pub struct History { pub outcome: Outcome, /// Who approved it (the request itself, not a step before it), with the answer they gave. pub approved_by: Option, + /// How each phase of a build or deploy ended. + pub phases: Vec, pub records: Vec, } @@ -124,6 +127,7 @@ fn summarize(id: String, records: Vec) -> History { label: None, outcome: Outcome::Waiting, approved_by: None, + phases: vec![], records: vec![], }; let mut answer = None; @@ -155,9 +159,14 @@ fn summarize(id: String, records: Vec) -> History { Event::Denied { .. } => history.outcome = Outcome::Denied, Event::Expired { .. } => history.outcome = Outcome::Expired, Event::Disconnected { .. } => history.outcome = Outcome::Cancelled, - Event::Finished { exit: 0, .. } => history.outcome = Outcome::Succeeded, - Event::Finished { exit, .. } => history.outcome = Outcome::ExitedWith(*exit), - Event::Failed { .. } => history.outcome = Outcome::Failed, + Event::Finished { exit, phases, .. } => { + history.outcome = if *exit == 0 { Outcome::Succeeded } else { Outcome::ExitedWith(*exit) }; + history.phases = phases.clone(); + } + Event::Failed { phases, .. } => { + history.outcome = Outcome::Failed; + history.phases = phases.clone(); + } Event::Unknown { .. } | Event::Prepared { .. } | Event::Approved { .. } | Event::Detached { .. } => {} } } @@ -196,13 +205,22 @@ pub fn describe(event: &Event) -> (String, Option) { Event::Expired { .. } => ("Expired without an answer".into(), None), Event::Disconnected { .. } => ("Cancelled: the requester disconnected".into(), None), Event::Detached { .. } => ("The requester disconnected; carried on to the end".into(), None), - Event::Finished { exit, seconds, .. } => { - (format!("Finished with exit status {exit} after {seconds:.1}s"), None) + Event::Finished { exit, seconds, phases, .. } => { + (format!("Finished with exit status {exit} after {seconds:.1}s"), phase_list(phases)) } - Event::Failed { error, .. } => (format!("Failed: {error}"), None), + Event::Failed { error, phases, .. } => (format!("Failed: {error}"), phase_list(phases)), } } +fn phase_list(phases: &[Progress]) -> Option { + if phases.is_empty() { + return None; + } + let mut detail = Detail::new(); + detail.section(Section::list("Phases", phases.iter().map(Progress::line))); + Some(detail) +} + fn shown(detail: &Shown) -> Option { Some(detail.to_detail()).filter(|d| !d.fields.is_empty() || !d.sections.is_empty()) } @@ -251,7 +269,7 @@ mod tests { step: None, }, ), - record("6", Event::Finished { id: "a".into(), exit: 1, seconds: 0.5 }), + record("6", Event::Finished { id: "a".into(), exit: 1, seconds: 0.5, phases: vec![] }), record("7", Event::Expired { id: "b".into() }), record("8", request("c")), record("9", Event::Approved { id: "c".into(), by: ApprovedBy::Lease, approver: None, step: None }), @@ -293,7 +311,7 @@ mod tests { let (histories, _) = gather(records.clone()); assert_eq!(histories[0].outcome, Outcome::Running); - records.push(record("4", Event::Finished { id: "a".into(), exit: 0, seconds: 30.0 })); + records.push(record("4", Event::Finished { id: "a".into(), exit: 0, seconds: 30.0, phases: vec![] })); let (histories, _) = gather(records); assert_eq!(histories[0].outcome, Outcome::Succeeded); } diff --git a/src/web/mod.rs b/src/web/mod.rs index c580c28..1229fe4 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -205,7 +205,7 @@ async fn index(State(web): State>, session: Session) -> Result user, Err(redirect) => return Ok(redirect), }; - let (entry, past) = (pending(&web, &id), past(&web.broker, &id)); - let view = page::RequestView { id: &id, entry: entry.as_ref(), past: past.as_ref() }; + let (entry, run, past) = (pending(&web, &id), web.broker.runs.get(&id), past(&web.broker, &id)); + let view = page::RequestView { id: &id, entry: entry.as_ref(), run: run.as_ref(), past: past.as_ref() }; Ok(page::request(&user.name, &user.csrf, &view).into_response()) } diff --git a/src/web/page.rs b/src/web/page.rs index f0ee27c..d520dc4 100644 --- a/src/web/page.rs +++ b/src/web/page.rs @@ -11,7 +11,9 @@ use super::history::{self, History}; use crate::audit::{Record, short}; use crate::detail::{Column, Detail, Section}; use crate::ops::printable; +use crate::progress::{Progress, State}; use crate::queue::{Decision, PendingInfo}; +use crate::runs::Run; /// The broker's version, which signed-in pages show. pub use crate::VERSION; @@ -35,15 +37,6 @@ fn render(template: impl Template) -> Html { Html(template.render().unwrap_or_else(|error| format!("rendering the page failed: {error}"))) } -/// Time left, like `4m 10s`. -fn left(seconds: &u64) -> String { - match *seconds { - s if s >= 3600 => format!("{}h {}m", s / 3600, s % 3600 / 60), - s if s >= 60 => format!("{}m {}s", s / 60, s % 60), - s => format!("{s}s"), - } -} - fn is_deny(decision: &Decision) -> bool { *decision == Decision::Deny } @@ -70,6 +63,24 @@ fn section_titles(detail: &Detail) -> String { detail.sections.iter().map(Section::title).collect::>().join(", ") } +/// A duration, like `4m 10s`: time taken or time left. +fn elapsed(seconds: impl std::borrow::Borrow) -> String { + crate::progress::elapsed(*seconds.borrow()) +} + +/// For styling a phase: `active`, `good` or `bad`. +fn state_class(progress: &Progress) -> &'static str { + match progress.state { + State::Running => "active", + State::Done => "good", + State::Failed => "bad", + } +} + +fn running(progress: &Progress) -> bool { + progress.state == State::Running +} + fn describe(record: &Record) -> (String, Option) { history::describe(&record.event) } @@ -105,24 +116,46 @@ struct Index<'a> { csrf: &'a str, entries: &'a [PendingInfo], leases: &'a [(String, String, u64)], + runs: &'a [Run], } -pub fn index(name: &str, csrf: &str, entries: &[PendingInfo], leases: &[(String, String, u64)]) -> Html { - render(Index { name, csrf, entries, leases }) +pub fn index( + name: &str, + csrf: &str, + entries: &[PendingInfo], + leases: &[(String, String, u64)], + runs: &[Run], +) -> Html { + render(Index { name, csrf, entries, leases, runs }) } -/// What a request's page shows: the request while it waits, and what the audit log has of it. +/// The requests that are running: the main page's other region that the page script keeps +/// current. +#[derive(Template)] +#[template(path = "running.html")] +struct Running<'a> { + runs: &'a [Run], +} + +pub fn running_list(runs: &[Run]) -> String { + render(Running { runs }).0 +} + +/// What a request's page shows: the request while it waits, its progress while it runs, and what +/// the audit log has of it. pub struct RequestView<'a> { pub id: &'a str, pub entry: Option<&'a PendingInfo>, + pub run: Option<&'a Run>, pub past: Option<&'a History>, } impl RequestView<'_> { fn heading(&self) -> String { - match (self.entry, self.past) { - (Some(entry), _) => entry.summary.clone(), - (None, Some(past)) if !past.summary.is_empty() => past.summary.clone(), + match (self.entry, self.run, self.past) { + (Some(entry), _, _) => entry.summary.clone(), + (None, Some(run), _) => run.summary.clone(), + (None, None, Some(past)) if !past.summary.is_empty() => past.summary.clone(), _ => format!("Request {}", short(self.id)), } } @@ -307,7 +340,7 @@ mod tests { ]; let (histories, _) = super::history::gather(records); - let view = RequestView { id: "abc", entry: None, past: Some(&histories[0]) }; + let view = RequestView { id: "abc", entry: None, run: None, past: Some(&histories[0]) }; let html = request("broker", "token", &view).0; assert!(html.contains(r#"
"#), "{html}"); assert!(html.contains(request_region("token", &view).trim()), "{html}"); @@ -316,4 +349,39 @@ mod tests { assert!(html.contains("Details (Text)") && html.contains("
Old: text
"), "{html}"); assert!(html.contains(&format!("slop-broker {VERSION}")), "{html}"); } + + #[test] + fn shows_progress_of_running_requests() { + use crate::progress::{Count, Counts, Phase}; + use crate::runs::Runs; + + let runs = std::sync::Arc::new(Runs::default()); + let _tracked = runs.start("abc", "slop-cannon", "deploy", "deploy "); + let progress = |phase, state, counts| Progress { phase, state, elapsed: 70, counts }; + let building = Counts { + builds: Some(Count { done: 3, total: 8 }), + current: vec!["hello-2.12".into()], + ..Counts::default() + }; + runs.record("abc", &progress(Phase::Build, State::Running, building)); + let copied = Counts { paths: Some(Count { done: 2, total: 2 }), ..Counts::default() }; + runs.record("abc", &progress(Phase::Copy("river".into()), State::Done, copied)); + let run = runs.get("abc").unwrap(); + + // The request's page, with its heading from the run + let view = RequestView { id: "abc", entry: None, run: Some(&run), past: None }; + let html = request_region("token", &view); + assert!(html.contains("

deploy <river>

"), "{html}"); + assert!(html.contains(r#""#), "{html}"); + assert!(html.contains("building 1m 10s"), "{html}"); + assert!(html.contains("Now: hello-2.12"), "{html}"); + assert!(html.contains(r#"copied"#), "{html}"); + assert!(html.contains(r#""#), "{html}"); + + // The main page's list, which is there even when nothing runs + let list = running_list(&runs.list()); + assert!(list.contains("deploy <river>") && list.contains(""#) && !empty.contains("Running"), "{empty}"); + } } diff --git a/templates/index.html b/templates/index.html index 2758630..d2d543f 100644 --- a/templates/index.html +++ b/templates/index.html @@ -6,4 +6,5 @@

{% include "pending.html" %} +{% include "running.html" %} {% endblock %} diff --git a/templates/macros.html b/templates/macros.html index 382ad97..a24c7e5 100644 --- a/templates/macros.html +++ b/templates/macros.html @@ -6,7 +6,7 @@ {% macro card(entry, csrf, open) %}

{{ entry.summary }}

-

{{ entry.requester }} · {{ entry.op }} · expires in {{ self::left(entry.expires_in) }} +

{{ entry.requester }} · {{ entry.op }} · expires in {{ self::elapsed(*entry.expires_in) }} {%- if entry.passkey %} {% call lock() %}{% endcall %}Needs passkey{% endif %} {%- if entry.sensitive %} Sensitive{% endif %}

{% if let Some(label) = entry.label %} @@ -90,3 +90,23 @@ {%- for (value, text) in options %}{% endfor -%} {%- endmacro %} + +{# A bar for a phase: its count if it has one, otherwise just whether it's going. #} +{% macro meter(progress) -%} +{% if let Some(count) = progress.bar() -%} + +{%- else if self::running(progress) -%} + +{%- else -%} + +{%- endif %} +{%- endmacro %} + +{# A request's whole progress in one bar, for lists. #} +{% macro run_meter(run) -%} +{% if let Some(count) = run.phases.bar() -%} + +{%- else -%} + +{%- endif %} +{%- endmacro %} diff --git a/templates/pending.html b/templates/pending.html index 7a80873..6e91979 100644 --- a/templates/pending.html +++ b/templates/pending.html @@ -10,7 +10,7 @@

Active leases

{% for (requester, scope, seconds) in leases %} - + {% endfor %}
RequesterScopeLeft
{{ requester }}{{ scope }}{{ self::left(seconds) }}
{{ requester }}{{ scope }}{{ self::elapsed(**seconds) }}
{% endif %} diff --git a/templates/progress.html b/templates/progress.html new file mode 100644 index 0000000..38bacd3 --- /dev/null +++ b/templates/progress.html @@ -0,0 +1,24 @@ +{%- import "macros.html" as m -%} +

Progress

+

Running for {{ self::elapsed(run.elapsed()) }}

+{% for phase in run.phases.overall() %} +
+

{{ phase.title() }} {{ self::elapsed(phase.elapsed) }}

+{% call m::meter(phase) %}{% endcall %} +{% let counted = phase.counted(false) %} +{% if !counted.is_empty() %}

{{ counted }}

{% endif %} +{% if !phase.counts.current.is_empty() %}

Now: {% for name in phase.counts.current %}{{ name }}{% if !loop.last %}, {% endif %}{% endfor %}

{% endif %} +
+{% endfor %} +{% let nodes = run.phases.nodes() %} +{% if !nodes.is_empty() %} +
+ + +{% for row in nodes %} + + + +{% endfor %} +
NodeStateCopyTime
{{ row.node }}{{ row.state }}{% if let Some(copy) = row.copy %}{% call m::meter(copy) %}{% endcall %}{% let counted = copy.counted(false) %}{% if !counted.is_empty() %}{{ counted }}{% endif %}{% endif %}{{ self::elapsed(row.latest.elapsed) }}
+{% endif %} diff --git a/templates/request_region.html b/templates/request_region.html index 5c07b48..3de7053 100644 --- a/templates/request_region.html +++ b/templates/request_region.html @@ -4,6 +4,20 @@ {% if let Some(entry) = view.entry %} {% call m::card(entry, csrf, true) %}{% endcall %} {% endif %} +{% if let Some(run) = view.run %} +
+{% include "progress.html" %} +
+{% else if let Some(past) = view.past %} +{% if !past.phases.is_empty() %} +

Progress

+
    +{% for phase in past.phases %} +
  • {{ phase.line() }}
  • +{% endfor %} +
+{% endif %} +{% endif %} {% if let Some(past) = view.past %} {% if view.entry.is_none() %}

{{ past.requester }} · {{ past.op }} · {% call m::outcome(past.outcome) %}{% endcall %}

diff --git a/templates/running.html b/templates/running.html new file mode 100644 index 0000000..2f5720f --- /dev/null +++ b/templates/running.html @@ -0,0 +1,13 @@ +{%- import "macros.html" as m -%} +
+{% if !runs.is_empty() %} +

Running

+
    +{% for run in runs %} +
  • {{ run.summary }} {{ run.requester }} +{% call m::run_meter(run) %}{% endcall %} +{{ run.phases.status() }}
  • +{% endfor %} +
+{% endif %} +
diff --git a/tests/broker.rs b/tests/broker.rs index d6862ed..fc02fe7 100644 --- a/tests/broker.rs +++ b/tests/broker.rs @@ -173,6 +173,7 @@ async fn builds_need_a_cache() { let operation = Operation::Build { attrs: vec!["packages.x86_64-linux.hello".parse().unwrap()], commit: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(), + logs: false, }; let mut client = Client::start(&broker, operation).await; assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("not configured"))); @@ -187,6 +188,7 @@ async fn deploys_have_a_rule_scope_per_target() { targets: vec!["river".parse().unwrap()], commit: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(), boot: true, + logs: false, }; let parsed = slop_broker::ops::plan(&broker, operation).unwrap(); assert_eq!(parsed.rule_scopes.len(), 1); diff --git a/tests/builder.rs b/tests/builder.rs index 965aaf4..ef64225 100644 --- a/tests/builder.rs +++ b/tests/builder.rs @@ -5,7 +5,7 @@ use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use serde::de::DeserializeOwned; -use slop_broker::builder::{BuilderRequest, Description, MAX_DIFF, Nodes, SecretContext, SecretRequest}; +use slop_broker::builder::{BuilderRequest, Description, MAX_DIFF, Nodes, Reply, SecretContext, SecretRequest}; use slop_broker::proto::{decode, encode}; use slop_broker::types::ObjectId; @@ -34,7 +34,7 @@ fn git(directory: &Path, args: &[&str]) -> String { String::from_utf8(output.stdout).unwrap().trim().to_owned() } -/// Sends one request to `slop-broker builder` and reads its one-frame answer. +/// Sends one request to `slop-broker builder` and reads its answer. fn ask(config: &Path, request: &BuilderRequest) -> T { let mut child = Command::new(env!("CARGO_BIN_EXE_slop-broker")) .args(["builder", "--config"]) @@ -56,8 +56,16 @@ fn ask(config: &Path, request: &BuilderRequest) -> T { assert!(child.wait().unwrap().success()); drop(stdin); - let length = u32::from_be_bytes(answer[..4].try_into().unwrap()) as usize; - decode(&answer[4..4 + length]).unwrap() + // Progress frames, if any, then the result + let mut rest = &answer[..]; + loop { + let length = u32::from_be_bytes(rest[..4].try_into().unwrap()) as usize; + let (frame, after) = rest[4..].split_at(length); + if let Reply::Done(result) = decode(frame).unwrap() { + return decode(&result).unwrap(); + } + rest = after; + } } #[test]