diff --git a/docs/architecture.md b/docs/architecture.md index 8d2d110..8cff61f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -101,9 +101,13 @@ a time: the evaluation and the build, then a copy, comparison and activation for 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`. + (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. @@ -162,7 +166,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/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 | diff --git a/src/progress.rs b/src/progress.rs index bf0cc52..da34369 100644 --- a/src/progress.rs +++ b/src/progress.rs @@ -2,9 +2,9 @@ //! 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 indicatif::BinaryBytes; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -44,28 +44,37 @@ impl Phase { } } + /// 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 { - match self { - Phase::Evaluate => "evaluating".into(), - 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(), - } + format!("{}{}", self.verbs().0, self.object()) } /// What it did, like `copied to river`. pub fn done(&self) -> String { - match self { - Phase::Evaluate => "evaluated".into(), - 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(), - } + format!("{}{}", self.verbs().1, self.object()) } } @@ -154,9 +163,9 @@ impl Progress { } if let Some(bytes) = counts.bytes.filter(|c| c.total > 0) { part += &if finished { - format!(" ({})", Bytes(bytes.done)) + format!(" ({})", BinaryBytes(bytes.done)) } else { - format!(" ({}/{})", Bytes(bytes.done), Bytes(bytes.total)) + format!(" ({}/{})", BinaryBytes(bytes.done), BinaryBytes(bytes.total)) }; } parts.push(part); @@ -164,6 +173,11 @@ impl Progress { 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 { @@ -174,8 +188,8 @@ impl Progress { if !counted.is_empty() { line = format!("{line}: {counted}"); } - if !self.counts.current.is_empty() { - line = format!("{line} ({})", self.counts.current.join(", ")); + if let Some(current) = self.current() { + line = format!("{line} ({current})"); } format!("{line}, {}", elapsed(self.elapsed)) } @@ -195,28 +209,114 @@ fn plural(count: u64, word: &str) -> String { if count == 1 { word.to_owned() } else { format!("{word}s") } } -/// A duration, like `4m 10s`. +/// A duration, like `4m 10s`, or to the minute from an hour, like `1h 2m`. 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"), + 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, + } } } -/// 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; +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(), } - if unit == 0 { write!(f, "{} B", self.0) } else { write!(f, "{value:.1} {}", units[unit]) } } } @@ -632,12 +732,12 @@ mod tests { }; assert_eq!( progress.line(), - "building: 37/120 derivations, 10/40 paths fetched (3.0 MiB/3.0 GiB) (firefox-147.0), 4m 10s" + "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.0 MiB) in 4m 10s"); + assert_eq!(progress.line(), "built: 37 derivations, 10 paths fetched (3.00 MiB) in 4m 10s"); let copy = Progress { phase: Phase::Copy("river".into()), @@ -648,4 +748,11 @@ mod tests { 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/runs.rs b/src/runs.rs index 830d09f..e60b398 100644 --- a/src/runs.rs +++ b/src/runs.rs @@ -6,7 +6,7 @@ use std::time::Instant; use tokio::sync::watch; -use crate::progress::{Count, Phase, Progress, State}; +use crate::progress::{Phases, Progress}; pub struct Runs { runs: Mutex>, @@ -23,89 +23,13 @@ pub struct Run { pub op: String, pub summary: String, started: Instant, - /// The latest progress of each phase, in the order they started. - pub phases: Vec, -} - -/// How a node is getting on, from its phases. -#[derive(Debug, Clone, PartialEq)] -pub struct NodeRow { - pub node: String, - 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, + pub phases: Phases, } impl Run { pub fn elapsed(&self) -> u64 { self.started.elapsed().as_secs() } - - /// Phases that aren't about one node: the build and the push. - pub fn overall(&self) -> Vec<&Progress> { - self.phases.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.phases.iter().filter_map(|p| p.phase.node()) { - if !order.contains(&node) { - order.push(node); - } - } - - order - .into_iter() - .map(|node| { - let phases: Vec<&Progress> = self.phases.iter().filter(|p| p.phase.node() == Some(node)).collect(); - let latest = (*phases.last().unwrap()).clone(); - let copy = phases.iter().find(|p| matches!(p.phase, Phase::Copy(_))).map(|p| (*p).clone()); - let (state, tone) = match (&latest.phase, latest.state) { - (_, State::Failed) => ("failed", "bad"), - (Phase::Copy(_), State::Running) => ("copying", "active"), - (Phase::Copy(_), State::Done) => ("copied", "neutral"), - (Phase::Compare(_), State::Running) => ("comparing", "active"), - (Phase::Compare(_), State::Done) => ("ready", "neutral"), - (Phase::Activate(_), State::Running) => ("activating", "active"), - (Phase::Activate(_), State::Done) => ("done", "good"), - _ => ("", "neutral"), - }; - NodeRow { node: node.to_owned(), state, tone, copy, latest } - }) - .collect() - } - - /// One bar for the whole request, for lists: the build, then the share of nodes past each - /// step. - pub fn bar(&self) -> Option { - let nodes = self.nodes(); - if nodes.is_empty() { - return self.overall().last().and_then(|p| p.bar()); - } - - let steps = |row: &NodeRow| match (&row.latest.phase, row.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, - }; - let total = nodes.len() as u64 * 3; - Some(Count { done: nodes.iter().map(steps).sum(), total }) - } - - /// What it's doing now, in a line. - pub fn status(&self) -> String { - match self.phases.iter().rev().find(|p| p.state == State::Running).or(self.phases.last()) { - Some(progress) => progress.line(), - None => "starting".into(), - } - } } impl Default for Runs { @@ -123,7 +47,7 @@ impl Runs { op: op.into(), summary: summary.into(), started: Instant::now(), - phases: Vec::new(), + phases: Phases::default(), }; self.runs.lock().unwrap().insert(id.into(), run); self.bump(true); @@ -134,17 +58,14 @@ impl Runs { { let mut runs = self.runs.lock().unwrap(); let Some(run) = runs.get_mut(id) else { return }; - match run.phases.iter_mut().find(|p| p.phase == progress.phase) { - Some(phase) => *phase = progress.clone(), - None => run.phases.push(progress.clone()), - } + 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.clone()).unwrap_or_default() + self.runs.lock().unwrap().get(id).map(|r| r.phases.as_slice().to_vec()).unwrap_or_default() } pub fn get(&self, id: &str) -> Option { @@ -192,7 +113,7 @@ impl Drop for Tracked { #[cfg(test)] mod tests { use super::*; - use crate::progress::Counts; + use crate::progress::{Count, Counts, Phase, State}; fn progress(phase: Phase, state: State) -> Progress { Progress { phase, state, elapsed: 1, counts: Counts::default() } @@ -211,16 +132,16 @@ mod tests { runs.record("nope", &progress(Phase::Build, State::Running)); assert_eq!(runs.members(), members); - let run = runs.get("a").unwrap(); - assert_eq!(run.overall().len(), 1); - let nodes = run.nodes(); + 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!(run.bar(), Some(Count { done: 1, total: 6 })); - assert_eq!(run.status(), "copying to stream, 1s"); + 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()); diff --git a/src/terminal.rs b/src/terminal.rs index dafd9bb..2964574 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -11,7 +11,7 @@ use std::time::{Duration, Instant}; use indicatif::{MultiProgress, ProgressBar, ProgressDrawTarget, ProgressStyle}; -use crate::progress::{Bytes, Phase, Progress, State, elapsed}; +use crate::progress::{Phase, Progress, State, elapsed}; /// How often a running phase gets a line without a terminal. pub const SUMMARY_INTERVAL: Duration = Duration::from_secs(30); @@ -166,25 +166,16 @@ impl Bars { } } -/// A bar's layout, like `building ▕████▌ ▏ 37/120 · 3.0 MiB/3.0 GiB · firefox-147.0 · 1m 2s`. +/// 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("█▉▊▋▌▍▎▏ ") } -/// What follows a bar: the count, bytes, what's running now and the time. +/// What follows a bar: the counts, what's running now and the time. fn details(progress: &Progress) -> String { - let mut parts = Vec::new(); - if let Some(count) = progress.bar() { - parts.push(format!("{}/{}", count.done, count.total)); - } - if let Some(bytes) = progress.counts.bytes.filter(|b| b.total > 0) { - parts.push(format!("{}/{}", Bytes(bytes.done), Bytes(bytes.total))); - } - if !progress.counts.current.is_empty() { - parts.push(progress.counts.current.join(", ")); - } - parts.push(elapsed(progress.elapsed)); - parts.join(" · ") + 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)] @@ -208,7 +199,7 @@ mod tests { #[test] fn details_follow_the_bar() { - assert_eq!(details(&running(3)), "3/8 · 1.0 KiB/4.0 KiB · firefox-147.0 · 1m 2s"); + 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"); } diff --git a/src/web/page.rs b/src/web/page.rs index 8f057c6..d520dc4 100644 --- a/src/web/page.rs +++ b/src/web/page.rs @@ -37,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 } @@ -72,6 +63,7 @@ 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()) } diff --git a/templates/macros.html b/templates/macros.html index 92f2936..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 %} @@ -104,7 +104,7 @@ {# A request's whole progress in one bar, for lists. #} {% macro run_meter(run) -%} -{% if let Some(count) = run.bar() -%} +{% if let Some(count) = run.phases.bar() -%} {%- else -%} 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 index 28d3bba..38bacd3 100644 --- a/templates/progress.html +++ b/templates/progress.html @@ -1,7 +1,7 @@ {%- import "macros.html" as m -%}

Progress

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

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

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

{% call m::meter(phase) %}{% endcall %} @@ -10,7 +10,7 @@ {% if !phase.counts.current.is_empty() %}

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

{% endif %}
{% endfor %} -{% let nodes = run.nodes() %} +{% let nodes = run.phases.nodes() %} {% if !nodes.is_empty() %}
diff --git a/templates/running.html b/templates/running.html index 7c77428..2f5720f 100644 --- a/templates/running.html +++ b/templates/running.html @@ -6,7 +6,7 @@ {% for run in runs %}
  • {{ run.summary }} {{ run.requester }} {% call m::run_meter(run) %}{% endcall %} -{{ run.status() }}
  • +{{ run.phases.status() }} {% endfor %} {% endif %}
    NodeStateCopyTime