Progress for builds, copies and deploys #22
No files matched your search
Generated
+66
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
+44
-6
@@ -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 `<progress>` 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<Arg>, stdin: Option<bytes> },
|
||||
Query { destination: Destination, query: Query },
|
||||
Deploy { targets: Vec<DeployTarget>, commit: CommitId, boot: bool },
|
||||
Build { attrs: Vec<FlakeAttr>, commit: CommitId },
|
||||
Deploy { targets: Vec<DeployTarget>, commit: CommitId, boot: bool, logs: bool },
|
||||
Build { attrs: Vec<FlakeAttr>, 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.
|
||||
|
||||
+16
-5
@@ -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 </dev/null &
|
||||
```
|
||||
|
||||
|
||||
+17
-4
@@ -227,6 +227,15 @@ on a desktop shows what `slop-approve` can only print.
|
||||
leases, and updates itself.
|
||||
- A dismissed or missed notification costs nothing; a notification only points at its request.
|
||||
- Requests that need a passkey are marked, with a padlock on their approve buttons.
|
||||
- **Progress.** Builds and deploys show how they're going while they run, to approvers as well
|
||||
as in `slop`.
|
||||
- A running request's page shows how long evaluating has taken, then has a bar for the build
|
||||
(derivations built, paths fetched, what's building now) and a row for each node: copying,
|
||||
comparing, ready, activating, done or failed, with its copy's bar and how long it's taken.
|
||||
- The main page lists running requests with one bar each.
|
||||
- Without JavaScript, a reload shows the latest.
|
||||
- Once a request finishes, its page and the audit log keep how each phase ended, such as
|
||||
`built: 12 derivations in 4m 10s`.
|
||||
- **Audit log.** The log page groups the audit file by request: who asked, what, the outcome and
|
||||
who approved it.
|
||||
- Filters by requester, operation and outcome, and a search.
|
||||
@@ -237,8 +246,9 @@ on a desktop shows what `slop-approve` can only print.
|
||||
them.
|
||||
- **Live updates.** Each open page follows one stream of Server-Sent Events (`/events`).
|
||||
- Each event carries a region of the page as HTML: a whole element with its `id`, such as the
|
||||
pending list or a request, rendered by the same templates as the page. Agent-supplied text
|
||||
is only ever escaped by them, never in the browser.
|
||||
pending list, the running requests or a request with its progress, rendered by the same
|
||||
templates as the page. Agent-supplied text is only ever escaped by them, never in the
|
||||
browser.
|
||||
- The script morphs each region into the page with
|
||||
[idiomorph](https://github.com/bigskysoftware/idiomorph) (vendored), so open details, the
|
||||
focus and what's being typed stay.
|
||||
@@ -411,14 +421,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.
|
||||
|
||||
@@ -51,6 +51,7 @@
|
||||
checks = forSystems (pkgs: {
|
||||
package = self.packages.${pkgs.stdenv.hostPlatform.system}.default;
|
||||
vm = pkgs.callPackage ./nix/vm-test.nix { slop-broker = self.packages.${pkgs.stdenv.hostPlatform.system}.default; };
|
||||
demo-bump = import ./nix/demo/bump-test.nix { inherit pkgs; };
|
||||
} // import ./nix/lints.nix { inherit pkgs; slop-broker = self.packages.${pkgs.stdenv.hostPlatform.system}.default; });
|
||||
|
||||
# A plain alternative to the devenv shell, for `nix develop`: the toolchain and the build's
|
||||
|
||||
+6
-4
@@ -8,6 +8,7 @@ let
|
||||
settings = import ./settings.nix;
|
||||
# Only the guest sees this address; the `demo` script forwards it to the host
|
||||
repository = "git://10.0.2.100/repo.git";
|
||||
bump = import ./bump.nix { inherit pkgs; };
|
||||
|
||||
help = pkgs.writeShellScriptBin "demo-help" ''
|
||||
cat <<'EOF'
|
||||
@@ -34,11 +35,12 @@ let
|
||||
git switch -c secrets && git commit -am "Rotate secrets" && git push origin secrets
|
||||
|
||||
Deploys, of the profile `demo` in flake.nix to the box VM (`demo-box cat /run/demo/version`
|
||||
on the host shows what's active):
|
||||
on the host shows what's active). Only a version that hasn't been built before rebuilds the
|
||||
app's parts, so `demo-bump` sets a new one each time and pushes it on a branch of its own:
|
||||
|
||||
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 or `demo-bump 1.1` for a version of your own
|
||||
slop deploy box </dev/null & asks to use the builder, builds, then asks again
|
||||
slop deploy box --logs </dev/null & the same, with the build's log as well as its progress
|
||||
|
||||
Builds into the binary cache, which is on the box VM (its GC roots, under
|
||||
/var/lib/slop-cache/nix/var/nix/gcroots/slop-broker, show what's been pushed):
|
||||
@@ -90,7 +92,7 @@ in
|
||||
};
|
||||
|
||||
# `slop`, and Git and Nix for working in the repository. `slop secret` evaluates `secrets.nix`.
|
||||
environment.systemPackages = [ slop-broker help pkgs.git ];
|
||||
environment.systemPackages = [ slop-broker help bump pkgs.git ];
|
||||
nix.settings.experimental-features = [ "nix-command" "flakes" ];
|
||||
environment.etc.gitconfig.text = ''
|
||||
[user]
|
||||
|
||||
+1
-1
@@ -25,7 +25,7 @@ in
|
||||
graphics = false;
|
||||
diskImage = null;
|
||||
# Copied closures live in memory, the cache's too
|
||||
memorySize = 1024;
|
||||
memorySize = 2048;
|
||||
restrictNetwork = true;
|
||||
forwardPorts = [{
|
||||
from = "host";
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# Checks `demo-bump` against a bare copy of the demo repository: twice in one clone, then again in a
|
||||
# fresh clone, as after the agents' VM restarts, when earlier branches are already on the remote.
|
||||
{ pkgs }:
|
||||
let
|
||||
bump = import ./bump.nix { inherit pkgs; };
|
||||
in
|
||||
pkgs.runCommand "slop-broker-demo-bump" { nativeBuildInputs = [ bump pkgs.git ]; } ''
|
||||
export HOME=$TMPDIR
|
||||
git config --global user.name Agent
|
||||
git config --global user.email agent@example.org
|
||||
git config --global init.defaultBranch master
|
||||
|
||||
git init --quiet --bare origin.git
|
||||
git clone --quiet origin.git seed
|
||||
cp ${./repo/flake.nix} seed/flake.nix
|
||||
git -C seed add flake.nix
|
||||
git -C seed commit --quiet -m "Start the demo repository"
|
||||
git -C seed push --quiet origin master
|
||||
|
||||
git clone --quiet origin.git one
|
||||
(cd one && demo-bump 1.1 && demo-bump 1.2)
|
||||
git clone --quiet origin.git two
|
||||
(cd two && demo-bump)
|
||||
|
||||
# Each version on its own branch, and only the version changed
|
||||
for version in 1.1 1.2; do
|
||||
git -C origin.git show "bump-$version:flake.nix" | grep -q "version = \"$version\";"
|
||||
done
|
||||
test "$(git -C origin.git branch --list 'bump-*' | wc -l)" = 3
|
||||
git -C origin.git diff --stat master bump-1.1 | grep -q "1 file changed, 1 insertion(+), 1 deletion(-)"
|
||||
touch $out
|
||||
''
|
||||
@@ -0,0 +1,20 @@
|
||||
# `demo-bump` on the agents' VM: sets a new version of the demo app in the repository it's run in,
|
||||
# commits it on a branch of its own and pushes that, ready for `slop deploy box`. Only a version
|
||||
# that hasn't been built before rebuilds the app's parts, so it defaults to one from the time.
|
||||
{ pkgs }:
|
||||
pkgs.writeShellApplication {
|
||||
name = "demo-bump";
|
||||
runtimeInputs = with pkgs; [ coreutils git gnugrep gnused ];
|
||||
text = ''
|
||||
version=''${1:-1.$(date +%s)}
|
||||
branch=bump-$version
|
||||
|
||||
sed -i "s/version = \".*\";/version = \"$version\";/" flake.nix
|
||||
grep -q "version = \"$version\";" flake.nix
|
||||
|
||||
git switch --quiet -c "$branch"
|
||||
git commit --quiet -am "Bump the app to $version"
|
||||
git push --quiet origin "$branch"
|
||||
echo "Pushed $branch, with the app at $version; deploy it with \`slop deploy box\`."
|
||||
'';
|
||||
}
|
||||
@@ -8,8 +8,10 @@ only `demo-merge <branch>` 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`.
|
||||
+33
-1
@@ -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"
|
||||
'';
|
||||
};
|
||||
|
||||
|
||||
+21
-7
@@ -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
|
||||
'';
|
||||
}
|
||||
+6
-1
@@ -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`.
|
||||
|
||||
|
||||
+26
-5
@@ -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<Progress>,
|
||||
},
|
||||
Failed {
|
||||
id: String,
|
||||
error: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
phases: Vec<Progress>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
|
||||
|
||||
+35
-17
@@ -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> {
|
||||
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<i32> {
|
||||
});
|
||||
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::<ServerMessage>(&frame)? {
|
||||
let message = decode::<ServerMessage>(&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.
|
||||
|
||||
+124
-27
@@ -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<DeployTarget>,
|
||||
/// Flake attributes to build.
|
||||
pub attrs: Vec<FlakeAttr>,
|
||||
/// 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<u8>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
@@ -206,10 +221,11 @@ pub async fn describe(
|
||||
out: &Output,
|
||||
cancel: &CancellationToken,
|
||||
) -> Result<Description> {
|
||||
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<BuildResult> {
|
||||
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::<BuildResult>(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<Nodes> {
|
||||
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<SecretContext> {
|
||||
call(ssh, deploy, &BuilderRequest::Secret(request.clone()), out, cancel).await
|
||||
call(ssh, deploy, &BuilderRequest::Secret(request.clone()), out, None, cancel).await
|
||||
}
|
||||
|
||||
async fn call<R: DeserializeOwned>(
|
||||
@@ -248,6 +268,7 @@ async fn call<R: DeserializeOwned>(
|
||||
deploy: &crate::config::DeployConfig,
|
||||
request: &BuilderRequest,
|
||||
out: &Output,
|
||||
mut reporter: Option<&mut Reporter>,
|
||||
cancel: &CancellationToken,
|
||||
) -> Result<R> {
|
||||
let mut command = crate::ops::ssh::command_to(ssh, &deploy.builder, &["build"]);
|
||||
@@ -268,10 +289,28 @@ async fn call<R: DeserializeOwned>(
|
||||
});
|
||||
|
||||
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<R: DeserializeOwned>(
|
||||
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::<Reply>();
|
||||
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<Nodes> {
|
||||
Ok(Nodes { commit, nodes })
|
||||
}
|
||||
|
||||
async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result<BuildResult> {
|
||||
async fn run(
|
||||
config: &BuilderConfig,
|
||||
request: &BuildRequest,
|
||||
replies: &tokio::sync::mpsc::UnboundedSender<Reply>,
|
||||
) -> Result<BuildResult> {
|
||||
let commit = &request.commit;
|
||||
let repository = mirror(config);
|
||||
|
||||
@@ -676,24 +730,34 @@ async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result<BuildResu
|
||||
}
|
||||
}
|
||||
|
||||
// Logs go to the broker as they happen; only the result is read.
|
||||
// Text goes to the broker as it happens, and progress as replies; only the result is read.
|
||||
eprintln!("Building…");
|
||||
let installables: Vec<String> = 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<BuildResu
|
||||
drv_path: String,
|
||||
outputs: BTreeMap<String, String>,
|
||||
}
|
||||
let mut built: Vec<Built> = serde_json::from_slice(&built.stdout).context("reading nix build's result")?;
|
||||
let mut built: Vec<Built> = 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<BuildResu
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Reads `nix`'s log until it closes: what it would show goes to stderr, and its progress to
|
||||
/// `replies`, at most every [`progress::INTERVAL`] and once at the end, with
|
||||
/// [`Reply::Evaluated`] when Nix starts building. Returns whether it did.
|
||||
async fn follow(
|
||||
stderr: impl tokio::io::AsyncRead + Unpin,
|
||||
mut log: NixLog,
|
||||
replies: &tokio::sync::mpsc::UnboundedSender<Reply>,
|
||||
) -> bool {
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
|
||||
let mut lines = tokio::io::BufReader::new(stderr).lines();
|
||||
let mut sent: Option<std::time::Instant> = 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::*;
|
||||
|
||||
+79
-3
@@ -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<ServerMessage>);
|
||||
pub struct Output {
|
||||
tx: mpsc::Sender<ServerMessage>,
|
||||
run: Option<(Arc<Runs>, String)>,
|
||||
}
|
||||
|
||||
impl Output {
|
||||
pub fn new(tx: mpsc::Sender<ServerMessage>) -> Output {
|
||||
Output { tx, run: None }
|
||||
}
|
||||
|
||||
/// The same output, with progress recorded in `runs` for request `id`.
|
||||
pub fn tracking(&self, runs: Arc<Runs>, 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<String>) {
|
||||
@@ -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<i32> {
|
||||
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<u8>, Vec<u8>)> {
|
||||
command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).process_group(0).kill_on_drop(true);
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
+11
-5
@@ -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<SshConfig>, &DeployConfig, &CacheConf
|
||||
}
|
||||
|
||||
pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
|
||||
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<Parsed> {
|
||||
|
||||
/// 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<i3
|
||||
}
|
||||
|
||||
io.out.info("pushing to the binary cache").await;
|
||||
let exit = exec::run_prefixed(copy_command(ssh, deploy, cache, &paths)?, &io.out, "[cache] ", &io.cancel).await?;
|
||||
let command = copy_command(ssh, deploy, cache, &paths)?;
|
||||
let mut reporter = Reporter::start(&io.out, Phase::Push).await;
|
||||
let exit = exec::run_nix(command, &io.out, "[cache] ", NixLog::new(false), &mut reporter, &io.cancel).await;
|
||||
reporter.finish(matches!(exit, Ok(0))).await;
|
||||
let exit = exit?;
|
||||
if exit != 0 {
|
||||
io.out.info(format!("pushing failed (exit status {exit})")).await;
|
||||
return Ok(exit);
|
||||
@@ -141,6 +146,7 @@ fn copy_command(ssh: &SshConfig, deploy: &DeployConfig, cache: &CacheConfig, pat
|
||||
command
|
||||
.env("NIX_SSHOPTS", options.join(" "))
|
||||
.args(["--extra-experimental-features", "nix-command", "copy", "--no-check-sigs"])
|
||||
.args(["--log-format", "internal-json"])
|
||||
.args(["--from", &from])
|
||||
.arg("--to")
|
||||
.arg(format!("ssh-ng://{}@{}", cache.user, cache.hostname))
|
||||
|
||||
+38
-42
@@ -21,6 +21,7 @@ use crate::config::{DeployConfig, SshConfig};
|
||||
use crate::detail::{Column, Detail, Field, Row, Section, Tone};
|
||||
use crate::exec::{self, Io, Output};
|
||||
use crate::policy::OpName;
|
||||
use crate::progress::{NixLog, Phase, Reporter};
|
||||
use crate::proto::{Destination, Operation};
|
||||
use crate::server::Broker;
|
||||
|
||||
@@ -37,7 +38,7 @@ fn mode(boot: bool) -> &'static str {
|
||||
}
|
||||
|
||||
pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
|
||||
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 `path<TAB>target`.
|
||||
@@ -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"]);
|
||||
|
||||
+1
-1
@@ -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 {
|
||||
|
||||
+758
@@ -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<Count>,
|
||||
/// Paths fetched (when building) or copied.
|
||||
pub paths: Option<Count>,
|
||||
/// Bytes of those paths.
|
||||
pub bytes: Option<Count>,
|
||||
/// What's building or copying now.
|
||||
pub current: Vec<String>,
|
||||
}
|
||||
|
||||
/// 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<Count> {
|
||||
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<String> {
|
||||
(!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<Progress>);
|
||||
|
||||
/// 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<Progress>,
|
||||
/// 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<NodeRow> {
|
||||
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<NodeRow> {
|
||||
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<Count> {
|
||||
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<Instant>,
|
||||
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<u64, u64>,
|
||||
/// The derivation or path it's for.
|
||||
name: Option<String>,
|
||||
/// A build's phase, like `buildPhase`.
|
||||
step: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<u64, Activity>,
|
||||
/// What finished activities did, by kind.
|
||||
finished: HashMap<u64, u64>,
|
||||
/// 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<String> {
|
||||
self.read(line).map(|text| strip_escapes(&text))
|
||||
}
|
||||
|
||||
fn read(&mut self, line: &str) -> Option<String> {
|
||||
let Some(json) = line.strip_prefix("@nix ") else { return Some(line.to_owned()) };
|
||||
let Ok(entry) = serde_json::from_str::<Value>(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::<u64>();
|
||||
let expected = finished + running.map(|a| a.expected).sum::<u64>();
|
||||
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<String> {
|
||||
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<String> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
+12
-2
@@ -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<FlakeAttr>, commit: CommitId },
|
||||
Build {
|
||||
attrs: Vec<FlakeAttr>,
|
||||
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<Progress>),
|
||||
Stdout(#[serde(with = "serde_bytes")] Vec<u8>),
|
||||
Stderr(#[serde(with = "serde_bytes")] Vec<u8>),
|
||||
/// The operation ran; `exit` is its status and `result` any structured output.
|
||||
|
||||
+150
@@ -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<HashMap<String, Run>>,
|
||||
/// Bumped on every change, progress included.
|
||||
changed: watch::Sender<u64>,
|
||||
/// Bumped when a run starts or ends.
|
||||
members: watch::Sender<u64>,
|
||||
}
|
||||
|
||||
#[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<Runs>, 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<Progress> {
|
||||
self.runs.lock().unwrap().get(id).map(|r| r.phases.as_slice().to_vec()).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn get(&self, id: &str) -> Option<Run> {
|
||||
self.runs.lock().unwrap().get(id).cloned()
|
||||
}
|
||||
|
||||
/// Every run, the oldest first.
|
||||
pub fn list(&self) -> Vec<Run> {
|
||||
let mut runs: Vec<Run> = 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<u64> {
|
||||
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<Runs>,
|
||||
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::<Vec<_>>(),
|
||||
[("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);
|
||||
}
|
||||
}
|
||||
+15
-5
@@ -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<Runs>,
|
||||
}
|
||||
|
||||
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<S: AsyncRead + AsyncWrite + Send + 'static>(broker: Arc<Brok
|
||||
let _ = sink.close().await;
|
||||
});
|
||||
|
||||
let out = Output(tx);
|
||||
let out = Output::new(tx);
|
||||
|
||||
let first = tokio::time::timeout(Duration::from_secs(10), source.next()).await;
|
||||
let request = match first {
|
||||
@@ -215,6 +217,9 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
|
||||
label: label.clone(),
|
||||
});
|
||||
|
||||
// Requests that build are tracked from the build on, for the web app and the audit log.
|
||||
let mut _tracked = None;
|
||||
|
||||
// Operations that build run agent-written Nix in the builder, which needs its own approval;
|
||||
// approvers first see the commits and their diff, which only takes Git. Then they build, so
|
||||
// the request's own approval can show what it changes. Others look things up the same way
|
||||
@@ -242,7 +247,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
|
||||
return None;
|
||||
}
|
||||
let error = format!("{error:#}");
|
||||
log(Event::Failed { id: id.clone(), error: error.clone() });
|
||||
log(Event::Failed { id: id.clone(), error: error.clone(), phases: broker.runs.phases(&id) });
|
||||
Some(ServerMessage::Error(error))
|
||||
};
|
||||
|
||||
@@ -273,6 +278,9 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
|
||||
.info(format!("use of the builder approved by {}", approver.as_deref().unwrap_or(approved_by_name(by))))
|
||||
.await;
|
||||
parsed.prepared.description = Some(description);
|
||||
|
||||
_tracked = Some(broker.runs.start(&id, requester, &parsed.op.to_string(), &parsed.summary));
|
||||
io.out = io.out.tracking(broker.runs.clone(), &id);
|
||||
}
|
||||
|
||||
if let Err(error) = ops::prepare(broker, &mut parsed, io).await {
|
||||
@@ -316,12 +324,14 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
|
||||
|
||||
match result {
|
||||
Ok(outcome) => {
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -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 {
|
||||
|
||||
+374
@@ -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<Bars>,
|
||||
/// When each running phase last had a line, without a terminal.
|
||||
said: HashMap<Phase, Instant>,
|
||||
}
|
||||
|
||||
struct Bars {
|
||||
multi: MultiProgress,
|
||||
/// Where they're drawn: stderr, except in tests.
|
||||
target: Box<dyn Fn() -> 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::<Vec<_>>().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<String> {
|
||||
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<String> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
+113
-43
@@ -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<Broker>, session: Session, request: Option<String>) ->
|
||||
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<String>,
|
||||
queue: watch::Receiver<u64>,
|
||||
/// The region last sent.
|
||||
sent: Option<String>,
|
||||
runs: watch::Receiver<u64>,
|
||||
/// 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<History>,
|
||||
members: Option<u64>,
|
||||
/// Each region last sent, by `id`.
|
||||
sent: HashMap<&'static str, String>,
|
||||
last: Option<Instant>,
|
||||
ended: bool,
|
||||
}
|
||||
|
||||
impl Updates {
|
||||
fn new(broker: Arc<Broker>, signed_in: SignedIn, request: Option<String>) -> 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<Vec<(&'static str, String)>> {
|
||||
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<Broker> {
|
||||
@@ -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#"<div id="pending">"#) && 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#"<div id="pending">"#) && events[0].1.contains("Nothing is waiting"));
|
||||
assert!(events[1].1.starts_with(r#"<section id="running">"#), "{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#"<div id="request" data-id="abc">"#), "{data}");
|
||||
assert!(data.contains("The audit log has nothing"), "{data}");
|
||||
let events = updates.next().await.unwrap();
|
||||
assert!(events[0].1.starts_with(r#"<div id="request" data-id="abc">"#), "{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("<h1>ssh river</h1>"), "{data}");
|
||||
let events = updates.next().await.unwrap();
|
||||
assert!(events[0].1.contains("<h1>ssh river</h1>"), "{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:?}");
|
||||
}
|
||||
}
|
||||
+27
-9
@@ -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<String>,
|
||||
/// How each phase of a build or deploy ended.
|
||||
pub phases: Vec<Progress>,
|
||||
pub records: Vec<Record>,
|
||||
}
|
||||
|
||||
@@ -124,6 +127,7 @@ fn summarize(id: String, records: Vec<Record>) -> 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<Record>) -> 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<Detail>) {
|
||||
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<Detail> {
|
||||
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<Detail> {
|
||||
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);
|
||||
}
|
||||
|
||||
+3
-3
@@ -205,7 +205,7 @@ async fn index(State(web): State<Arc<Web>>, session: Session) -> Result<Response
|
||||
|
||||
let entries = web.broker.queue.list();
|
||||
let leases = web.broker.queue.all_leases();
|
||||
Ok(page::index(&user.name, &user.csrf, &entries, &leases).into_response())
|
||||
Ok(page::index(&user.name, &user.csrf, &entries, &leases, &web.broker.runs.list()).into_response())
|
||||
}
|
||||
|
||||
async fn request_page(
|
||||
@@ -217,8 +217,8 @@ async fn request_page(
|
||||
Ok(user) => 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())
|
||||
}
|
||||
|
||||
|
||||
+84
-16
@@ -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<String> {
|
||||
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::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
/// A duration, like `4m 10s`: time taken or time left.
|
||||
fn elapsed(seconds: impl std::borrow::Borrow<u64>) -> 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<Detail>) {
|
||||
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<String> {
|
||||
render(Index { name, csrf, entries, leases })
|
||||
pub fn index(
|
||||
name: &str,
|
||||
csrf: &str,
|
||||
entries: &[PendingInfo],
|
||||
leases: &[(String, String, u64)],
|
||||
runs: &[Run],
|
||||
) -> Html<String> {
|
||||
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#"<div id="request" data-id="abc">"#), "{html}");
|
||||
assert!(html.contains(request_region("token", &view).trim()), "{html}");
|
||||
@@ -316,4 +349,39 @@ mod tests {
|
||||
assert!(html.contains("Details (Text)") && html.contains("<pre>Old: text</pre>"), "{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 <river>");
|
||||
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("<h1>deploy <river></h1>"), "{html}");
|
||||
assert!(html.contains(r#"<progress class="active" max="8" value="3"></progress>"#), "{html}");
|
||||
assert!(html.contains("<strong>building</strong> <span class=\"meta\">1m 10s</span>"), "{html}");
|
||||
assert!(html.contains("Now: <code>hello-2.12</code>"), "{html}");
|
||||
assert!(html.contains(r#"<span class="outcome neutral">copied</span>"#), "{html}");
|
||||
assert!(html.contains(r#"<progress class="good" max="2" value="2"></progress>"#), "{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("<progress"), "{list}");
|
||||
let empty = running_list(&[]);
|
||||
assert!(empty.starts_with(r#"<section id="running">"#) && !empty.contains("Running"), "{empty}");
|
||||
}
|
||||
}
|
||||
@@ -6,4 +6,5 @@
|
||||
<p><span id="push-state"></span> <button type="button" id="push-toggle" class="quiet"></button></p>
|
||||
</section>
|
||||
{% include "pending.html" %}
|
||||
{% include "running.html" %}
|
||||
{% endblock %}
|
||||
+21
-1
@@ -6,7 +6,7 @@
|
||||
{% macro card(entry, csrf, open) %}
|
||||
<article class="request{% if entry.passkey %} needs-passkey{% endif %}" id="r-{{ entry.id }}">
|
||||
<h2><a href="/requests/{{ entry.id }}">{{ entry.summary }}</a></h2>
|
||||
<p class="meta">{{ entry.requester }} · {{ entry.op }} · <span class="expires" data-left="{{ entry.expires_in }}">expires in {{ self::left(entry.expires_in) }}</span>
|
||||
<p class="meta">{{ entry.requester }} · {{ entry.op }} · <span class="expires" data-left="{{ entry.expires_in }}">expires in {{ self::elapsed(*entry.expires_in) }}</span>
|
||||
{%- if entry.passkey %} <span class="badge passkey">{% call lock() %}{% endcall %}Needs passkey</span>{% endif %}
|
||||
{%- if entry.sensitive %} <span class="badge warn">Sensitive</span>{% endif %}</p>
|
||||
{% if let Some(label) = entry.label %}
|
||||
@@ -90,3 +90,23 @@
|
||||
{%- for (value, text) in options %}<option value="{{ value }}"{% if value.as_str() == chosen.as_str() %} selected{% endif %}>{{ text }}</option>{% endfor -%}
|
||||
</select></label>
|
||||
{%- 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() -%}
|
||||
<progress class="{{ self::state_class(progress) }}" max="{{ count.total }}" value="{{ count.done }}"></progress>
|
||||
{%- else if self::running(progress) -%}
|
||||
<progress class="active"></progress>
|
||||
{%- else -%}
|
||||
<progress class="{{ self::state_class(progress) }}" max="1" value="1"></progress>
|
||||
{%- endif %}
|
||||
{%- endmacro %}
|
||||
|
||||
{# A request's whole progress in one bar, for lists. #}
|
||||
{% macro run_meter(run) -%}
|
||||
{% if let Some(count) = run.phases.bar() -%}
|
||||
<progress class="active" max="{{ count.total }}" value="{{ count.done }}"></progress>
|
||||
{%- else -%}
|
||||
<progress class="active"></progress>
|
||||
{%- endif %}
|
||||
{%- endmacro %}
|
||||
@@ -10,7 +10,7 @@
|
||||
<h2>Active leases</h2>
|
||||
<table><thead><tr><th>Requester</th><th>Scope</th><th>Left</th></tr></thead><tbody>
|
||||
{% for (requester, scope, seconds) in leases %}
|
||||
<tr><td>{{ requester }}</td><td><code>{{ scope }}</code></td><td>{{ self::left(seconds) }}</td></tr>
|
||||
<tr><td>{{ requester }}</td><td><code>{{ scope }}</code></td><td>{{ self::elapsed(**seconds) }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody></table>
|
||||
{% endif %}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
{%- import "macros.html" as m -%}
|
||||
<h2>Progress</h2>
|
||||
<p class="meta">Running for {{ self::elapsed(run.elapsed()) }}</p>
|
||||
{% for phase in run.phases.overall() %}
|
||||
<div class="phase {{ self::state_class(phase) }}">
|
||||
<p class="phase-title"><strong>{{ phase.title() }}</strong> <span class="meta">{{ self::elapsed(phase.elapsed) }}</span></p>
|
||||
{% call m::meter(phase) %}{% endcall %}
|
||||
{% let counted = phase.counted(false) %}
|
||||
{% if !counted.is_empty() %}<p class="meta">{{ counted }}</p>{% endif %}
|
||||
{% if !phase.counts.current.is_empty() %}<p class="meta current">Now: {% for name in phase.counts.current %}<code>{{ name }}</code>{% if !loop.last %}, {% endif %}{% endfor %}</p>{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% let nodes = run.phases.nodes() %}
|
||||
{% if !nodes.is_empty() %}
|
||||
<div class="scroll"><table class="nodes">
|
||||
<thead><tr><th>Node</th><th>State</th><th>Copy</th><th>Time</th></tr></thead>
|
||||
<tbody>
|
||||
{% for row in nodes %}
|
||||
<tr><td><code>{{ row.node }}</code></td><td><span class="outcome {{ row.tone }}">{{ row.state }}</span></td>
|
||||
<td class="copy">{% if let Some(copy) = row.copy %}{% call m::meter(copy) %}{% endcall %}{% let counted = copy.counted(false) %}{% if !counted.is_empty() %}<span class="meta">{{ counted }}</span>{% endif %}{% endif %}</td>
|
||||
<td>{{ self::elapsed(row.latest.elapsed) }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody></table></div>
|
||||
{% endif %}
|
||||
@@ -4,6 +4,20 @@
|
||||
{% if let Some(entry) = view.entry %}
|
||||
{% call m::card(entry, csrf, true) %}{% endcall %}
|
||||
{% endif %}
|
||||
{% if let Some(run) = view.run %}
|
||||
<section class="progress">
|
||||
{% include "progress.html" %}
|
||||
</section>
|
||||
{% else if let Some(past) = view.past %}
|
||||
{% if !past.phases.is_empty() %}
|
||||
<h2>Progress</h2>
|
||||
<ul class="phases">
|
||||
{% for phase in past.phases %}
|
||||
<li class="{{ self::state_class(phase) }}">{{ phase.line() }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% if let Some(past) = view.past %}
|
||||
{% if view.entry.is_none() %}
|
||||
<p class="meta">{{ past.requester }} · {{ past.op }} · {% call m::outcome(past.outcome) %}{% endcall %}</p>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{%- import "macros.html" as m -%}
|
||||
<section id="running">
|
||||
{% if !runs.is_empty() %}
|
||||
<h2>Running</h2>
|
||||
<ul class="runs">
|
||||
{% for run in runs %}
|
||||
<li><a href="/requests/{{ run.id }}">{{ run.summary }}</a> <span class="meta">{{ run.requester }}</span>
|
||||
{% call m::run_meter(run) %}{% endcall %}
|
||||
<span class="meta">{{ run.phases.status() }}</span></li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</section>
|
||||
@@ -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);
|
||||
|
||||
+12
-4
@@ -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<T: DeserializeOwned>(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<T: DeserializeOwned>(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]
|
||||
|
||||
Reference in new issue
Block a user