diff --git a/docs/architecture.md b/docs/architecture.md index e713431..dd25200 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -87,7 +87,22 @@ 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 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. 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. ```mermaid flowchart LR @@ -135,6 +150,7 @@ 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`), and the `Progress` messages (`Reporter`) | | `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) | @@ -248,7 +264,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 +350,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 +384,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 +440,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 +528,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/design.md b/docs/design.md index 037102d..fcae7dc 100644 --- a/docs/design.md +++ b/docs/design.md @@ -411,14 +411,17 @@ broker runs it over SSH. 3. **Build.** The builder evaluates the targets' deploy-rs profiles and builds them with the box's Nix daemon. - Only `git` gets the repository key, never the evaluator. - - Build logs stream to the agent. One build runs at a time. + - The agent gets progress: derivations built and paths fetched out of the totals, and what's + building now. Build logs stream only if it asks (`--logs`); a failed build's error ends + with the last lines of its log either way, as Nix shows it. One build runs at a time. - The broker reads built paths from the builder's store, `nix copy --from ssh-ng://` its user with the broker's key; the builder key's forced command serves `nix-daemon --stdio` for that. So the builder can be on another box with a store of its own, and nothing lands in the broker's store. The builder never holds a key to the nodes or the cache. 4. **Compare, before approval.** The broker copies the closures to each node, as deploy-rs does, and compares each profile with the one installed. - - Nodes substitute what the caches have; progress streams to the agent. + - Nodes substitute what the caches have; the agent gets each node's progress (paths and bytes + copied). - The comparison is a fixed read-only script. Nothing runs as root, and no agent-written code runs. 5. **Approve the deploy.** One approval covers every target, the commit and the mode. diff --git a/slop-tools.md b/slop-tools.md index b648801..232a7a3 100644 --- a/slop-tools.md +++ b/slop-tools.md @@ -59,8 +59,10 @@ 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. +- 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/bin/slop.rs b/src/bin/slop.rs index 30ee16b..745643c 100644 --- a/src/bin/slop.rs +++ b/src/bin/slop.rs @@ -9,6 +9,7 @@ use futures_util::{SinkExt, StreamExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::sync::mpsc; +use slop_broker::progress::State; use slop_broker::proto::{ ApprovedBy, ClientMessage, DEFAULT_VSOCK_PORT, Destination, GenKind, HOST_CID, MAX_SSH_SHOWN, OpResult, Operation, PROTOCOL_VERSION, Query, Request, SecretFile, SecretOp, ServerMessage, Target as SecretTarget, decode, encode, @@ -127,6 +128,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 { @@ -136,6 +140,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 { @@ -373,8 +380,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!(), }) @@ -495,6 +504,11 @@ async fn run(cli: Cli) -> Result { } } ServerMessage::Info(message) => eprintln!("slop: {message}"), + ServerMessage::Progress(progress) => { + if progress.state != State::Running { + eprintln!("slop: {}", progress.line()); + } + } ServerMessage::Stdout(data) => { stdout.write_all(&data).await?; stdout.flush().await?; diff --git a/src/builder.rs b/src/builder.rs index b7dacb4..3ccad57 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,18 @@ 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), + /// The result, encoded; the last frame. + Done(#[serde(with = "serde_bytes")] Vec), } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -206,10 +219,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 +231,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::Build).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 +247,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 +258,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 +266,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 +287,23 @@ 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::Done(data) => { + result = Some(data); + break; + } + } + } + anyhow::Ok((result, child.wait().await?)) } => result?, _ = cancel.cancelled() => bail!("requester disconnected"), }; @@ -279,7 +311,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 +334,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 +352,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 +685,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 +723,30 @@ 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) + }); + 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"); #[derive(Deserialize)] struct Built { @@ -701,7 +754,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 +788,29 @@ async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result, +) { + use tokio::io::AsyncBufReadExt; + + let mut lines = tokio::io::BufReader::new(stderr).lines(); + let mut sent: Option = None; + while let Ok(Some(line)) = lines.next_line().await { + if let Some(text) = log.line(&line) { + eprintln!("{text}"); + } + 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())); +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/exec.rs b/src/exec.rs index 4154c30..8be5582 100644 --- a/src/exec.rs +++ b/src/exec.rs @@ -12,6 +12,7 @@ use tokio::process::Command; use tokio::sync::mpsc; use tokio_util::sync::CancellationToken; +use crate::progress::{NixLog, Reporter}; use crate::proto::ServerMessage; /// Messages on their way back to the requester. @@ -126,6 +127,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 013b07a..aed261b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,6 +8,7 @@ pub mod detail; pub mod exec; pub mod ops; pub mod policy; +pub mod progress; pub mod proto; pub mod queue; pub mod remote; 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..0036f43 --- /dev/null +++ b/src/progress.rs @@ -0,0 +1,613 @@ +//! 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::fmt; +use std::time::{Duration, Instant}; + +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 and building, 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::Build | Phase::Push => None, + } + } + + /// What it's doing, like `copying to river`. + pub fn doing(&self) -> String { + match self { + Phase::Build => "building".into(), + Phase::Copy(node) => format!("copying to {node}"), + Phase::Compare(node) => format!("comparing on {node}"), + Phase::Activate(node) => format!("activating {node}"), + Phase::Push => "pushing to the cache".into(), + } + } + + /// What it did, like `copied to river`. + pub fn done(&self) -> String { + match self { + Phase::Build => "built".into(), + Phase::Copy(node) => format!("copied to {node}"), + Phase::Compare(node) => format!("compared on {node}"), + Phase::Activate(node) => format!("activated {node}"), + Phase::Push => "pushed to the cache".into(), + } + } +} + +#[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), + } + } + + /// The counts in words, like `37/120 derivations, 10/40 paths (1.2/3.4 GiB)`. + 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!(" ({})", Bytes(bytes.done)) + } else { + format!(" ({}/{})", Bytes(bytes.done), Bytes(bytes.total)) + }; + } + parts.push(part); + } + parts.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 !self.counts.current.is_empty() { + line = format!("{line} ({})", self.counts.current.join(", ")); + } + format!("{line}, {}", elapsed(self.elapsed)) + } + State::Done | State::Failed => { + let counted = self.counted(true); + let mut line = match self.state { + State::Done => self.phase.done(), + _ => format!("{} failed", self.phase.doing()), + }; + 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`. +pub fn elapsed(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"), + } +} + +/// A size in binary units, like `1.2 GiB`. +pub struct Bytes(pub u64); + +impl fmt::Display for Bytes { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let units = ["B", "KiB", "MiB", "GiB", "TiB"]; + let mut value = self.0 as f64; + let mut unit = 0; + while value >= 1024.0 && unit < units.len() - 1 { + value /= 1024.0; + unit += 1; + } + if unit == 0 { write!(f, "{} B", self.0) } else { write!(f, "{value:.1} {}", units[unit]) } + } +} + +/// 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; + } + } + + 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 COPY_PATHS: u64 = 103; +const BUILDS: u64 = 104; +const BUILD: u64 = 105; + +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, +} + +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() }); + // 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) } + } + + 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 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.0 MiB/3.0 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.0 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); + } +} 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/targets.rs b/src/targets.rs index f257a3a..43289cf 100644 --- a/src/targets.rs +++ b/src/targets.rs @@ -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/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]