Compare commits
No files matched your search
@@ -89,6 +89,12 @@ otherwise `git add -N`) before `nix build` can use it.
|
||||
one commit even when it touches code, modules and docs; split only when a reader would ask why two
|
||||
things arrived together.
|
||||
|
||||
## Work in progress
|
||||
|
||||
Plans, status, next steps and handoffs go in Gitea issues on `dev/slop-broker`, one per piece of
|
||||
work with its description kept current, not in files in the repository or on branches. When the
|
||||
work is done, move what lasts into `docs/` or this file and close the issue.
|
||||
|
||||
## Writing
|
||||
|
||||
- In prose and commit messages, quote code-like identifiers (commands, options, paths, crate and
|
||||
|
||||
Generated
+67
-1
@@ -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"
|
||||
@@ -3859,7 +3891,7 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "slop-broker"
|
||||
version = "0.2.2"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"age",
|
||||
"anyhow",
|
||||
@@ -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"
|
||||
|
||||
+4
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "slop-broker"
|
||||
version = "0.2.2"
|
||||
version = "0.4.0"
|
||||
edition = "2024"
|
||||
description = "Approval broker that runs privileged operations for coding agents"
|
||||
license = "MIT"
|
||||
@@ -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"
|
||||
@@ -14,7 +14,7 @@ OpenID Connect, passkeys, Web Push).
|
||||
## Trying it
|
||||
|
||||
```sh
|
||||
devenv up # the broker, its web app, Pocket ID and a box VM for the SSH targets
|
||||
devenv up # the broker, its web app (without sign-in) and a box VM for the SSH targets
|
||||
demo # in another terminal: the agents' VM, signed in as an agent that can send requests
|
||||
```
|
||||
|
||||
@@ -52,8 +52,10 @@ compatible fixes and the minor for compatible features. While the major is zero,
|
||||
use a minor bump for breaking changes and document how to upgrade. After `1.0.0`,
|
||||
bump the major for breaking changes.
|
||||
|
||||
1. Set `package.version` in `Cargo.toml` and run `cargo check` to refresh
|
||||
`Cargo.lock`. The Nix package reads the version from `Cargo.toml`.
|
||||
1. In a release pull request of its own, once the changes for it have merged, set
|
||||
`package.version` in `Cargo.toml` and run `cargo check` to refresh `Cargo.lock`. Feature and
|
||||
fix pull requests leave the version alone. The Nix package reads the version from
|
||||
`Cargo.toml`.
|
||||
2. After the release commit lands on `main` and passes CI, tag it `v<version>` and
|
||||
push the tag. Keep published tags fixed.
|
||||
3. Update the `slop-broker` input in nixfiles to `ref=refs/tags/v<version>` and run
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Adds the commit to the version of builds from a Git checkout, like Nix builds (see `VERSION`).
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-env-changed=SLOP_BROKER_VERSION");
|
||||
if std::env::var_os("SLOP_BROKER_VERSION").is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Outside a checkout, or without `git`, the version is the package's alone.
|
||||
let Some(rev) = git(&["rev-parse", "--short=7", "HEAD"]) else {
|
||||
return;
|
||||
};
|
||||
let dirty = git(&["status", "--porcelain", "--untracked-files=no"]).is_some_and(|s| !s.is_empty());
|
||||
let version = std::env::var("CARGO_PKG_VERSION").unwrap();
|
||||
println!("cargo:rustc-env=SLOP_BROKER_VERSION={version}+{rev}{}", if dirty { "-dirty" } else { "" });
|
||||
|
||||
// Again when the commit changes (`HEAD`, or the branch it's on), or the files do.
|
||||
for path in ["HEAD", "packed-refs"] {
|
||||
if let Some(path) = git(&["rev-parse", "--git-path", path]) {
|
||||
println!("cargo:rerun-if-changed={path}");
|
||||
}
|
||||
}
|
||||
if let Some(branch) = git(&["symbolic-ref", "-q", "HEAD"])
|
||||
&& let Some(path) = git(&["rev-parse", "--git-path", &branch])
|
||||
{
|
||||
println!("cargo:rerun-if-changed={path}");
|
||||
}
|
||||
for entry in Path::new(".").read_dir().into_iter().flatten().flatten() {
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
let generated = [".git", ".jj", "target", ".devenv", ".direnv"].contains(&name.as_str());
|
||||
if !generated && !name.starts_with("result") {
|
||||
println!("cargo:rerun-if-changed={name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a `git` command prints, without the newline, if it succeeds.
|
||||
fn git(args: &[&str]) -> Option<String> {
|
||||
let output = Command::new("git").args(args).output().ok()?;
|
||||
output.status.success().then(|| String::from_utf8_lossy(&output.stdout).trim_end().to_owned())
|
||||
}
|
||||
+7
-334
@@ -1,347 +1,20 @@
|
||||
# The development environment: `devenv shell`, or direnv with `.envrc`. The package, modules and
|
||||
# checks are in `flake.nix`.
|
||||
#
|
||||
# `devenv up` runs the demo's host side (see `docs/demo.md`): the broker from this checkout, with
|
||||
# its web app and builder, Pocket ID for approvers to sign in with, the box VM its SSH targets
|
||||
# reach, and the Git repository the agent pushes to.
|
||||
{ pkgs, lib, config, ... }:
|
||||
let
|
||||
demo = import ./nix/demo/settings.nix;
|
||||
state = "${config.devenv.state}/slop-demo";
|
||||
# Sockets, whose paths must be short
|
||||
run = "${config.devenv.runtime}/slop-demo";
|
||||
issuer = "http://localhost:${toString demo.ports.pocketId}";
|
||||
# Bare repositories the agents' VM reaches with `git://`
|
||||
repositories = "${state}/git";
|
||||
appUrl = "http://localhost:${toString demo.ports.web}";
|
||||
|
||||
# The builder: `slop-broker builder`, which the broker reaches through `ssh` (see `ssh` below).
|
||||
# The repository is a local path, so its key is never used.
|
||||
builderConfig = (pkgs.formats.toml { }).generate "slop-demo-builder.toml" {
|
||||
repository = "${repositories}/repo.git";
|
||||
key = "/nonexistent";
|
||||
branch = "master";
|
||||
directory = "${state}/builder";
|
||||
# The host's own Nix first, so builds go through its daemon as the user
|
||||
path = [
|
||||
"${pkgs.git}/bin"
|
||||
"${pkgs.openssh}/bin"
|
||||
"/run/current-system/sw/bin"
|
||||
"/nix/var/nix/profiles/default/bin"
|
||||
"${pkgs.nix}/bin"
|
||||
];
|
||||
};
|
||||
|
||||
# The broker's `ssh`: the host `builder` runs the builder from this checkout's build directly, as
|
||||
# its forced command would; everything else is the real `ssh`.
|
||||
ssh = pkgs.writeShellScript "slop-demo-ssh" ''
|
||||
host="" previous=""
|
||||
for arg; do
|
||||
if [ "$previous" = -- ]; then host=$arg; break; fi
|
||||
previous=$arg
|
||||
done
|
||||
|
||||
if [ "$host" = builder ]; then
|
||||
exec ${config.devenv.root}/target/debug/slop-broker builder --config ${builderConfig}
|
||||
fi
|
||||
exec ${pkgs.openssh}/bin/ssh "$@"
|
||||
'';
|
||||
|
||||
# Only `demo-merge` moves `master`, standing in for branch protection and a person merging
|
||||
preReceive = pkgs.writeShellScript "slop-demo-pre-receive" ''
|
||||
while read -r old new ref; do
|
||||
if [ "$ref" = refs/heads/master ]; then
|
||||
echo "master is protected: push a branch, and merge it with \`demo-merge <branch>\` on the host" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
'';
|
||||
|
||||
# `@group@` becomes the user's primary group, whose members may approve, and `@dev@` the demo
|
||||
# person's age public key
|
||||
brokerConfig = (pkgs.formats.toml { }).generate "slop-demo.toml" {
|
||||
requesters.agent = { vsock_cid = demo.agentCid; policy = "agent"; };
|
||||
policies.agent.ops = {
|
||||
query.action = "auto";
|
||||
ssh = {
|
||||
action = "ask";
|
||||
leases = [ "5m" "1h" ];
|
||||
rules = [
|
||||
{ match.target = "router"; action = "ask"; confirm = "passkey"; }
|
||||
{ match.target = "vault"; action = "deny"; }
|
||||
];
|
||||
};
|
||||
# Agent-written Nix runs in the builder once its use is approved; `master` is reviewed
|
||||
builder = {
|
||||
action = "ask";
|
||||
leases = [ "5m" "1h" ];
|
||||
rules = [{ match.on_branch = "true"; action = "auto"; }];
|
||||
};
|
||||
deploy = {
|
||||
action = "ask";
|
||||
leases = [ "5m" ];
|
||||
};
|
||||
# Approvals show whether the file and its recipients match `master`; reading always asks
|
||||
secret = {
|
||||
action = "ask";
|
||||
leases = [ "5m" ];
|
||||
rules = [{ match.action = "keys"; action = "auto"; }];
|
||||
};
|
||||
};
|
||||
|
||||
vsock_port = 6262;
|
||||
approve_socket = "${run}/approve.sock";
|
||||
approver_group = "@group@";
|
||||
audit_log = "${state}/audit.jsonl";
|
||||
|
||||
ssh = {
|
||||
ssh = "${ssh}";
|
||||
key = "${state}/broker-key";
|
||||
known_hosts = "${state}/known_hosts";
|
||||
};
|
||||
|
||||
deploy = {
|
||||
builder = { hostname = "builder"; user = "builder"; };
|
||||
nix = "${pkgs.nix}/bin/nix";
|
||||
cache = "${state}/nix-cache";
|
||||
};
|
||||
|
||||
secrets = {
|
||||
identity = "${state}/broker-age.key";
|
||||
names.dev = "@dev@";
|
||||
};
|
||||
|
||||
web = {
|
||||
listen = "127.0.0.1:${toString demo.ports.web}";
|
||||
url = appUrl;
|
||||
inherit issuer;
|
||||
client_id = "slop-approve";
|
||||
client_secret = "${state}/oidc-secret";
|
||||
group = "slop-approvers";
|
||||
state_dir = "${state}/web";
|
||||
};
|
||||
};
|
||||
|
||||
# Pocket ID's admin API, with the key `devenv up` made
|
||||
pocketIdApi = ''
|
||||
api() {
|
||||
local method=$1 path=$2
|
||||
shift 2
|
||||
curl -sS --fail-with-body -X "$method" "${issuer}/api/$path" \
|
||||
-H "X-API-Key: $(sed -n 's/^STATIC_API_KEY=//p' ${state}/pocket-id.env)" -H 'Content-Type: application/json' "$@"
|
||||
}
|
||||
'';
|
||||
in
|
||||
# `devenv up` runs the demo's host side, from `nix/demo/host.nix` (see `docs/demo.md`).
|
||||
{ pkgs, ... }:
|
||||
{
|
||||
imports = [ ./nix/demo/host.nix ];
|
||||
|
||||
languages.rust.enable = true;
|
||||
|
||||
# `pkg-config` with OpenSSL for Web Push's payload encryption and SQLite for the web app's
|
||||
# sessions, `git` for the builder's tests
|
||||
packages = with pkgs; [ pkg-config openssl sqlite git nixpkgs-fmt curl jq rage ];
|
||||
|
||||
# For `slop-approve` in this shell
|
||||
env.SLOP_APPROVE = "unix:${run}/approve.sock";
|
||||
|
||||
scripts = {
|
||||
slop-approve = {
|
||||
description = "Answer the demo's requests (built from this checkout)";
|
||||
exec = ''exec cargo run -q --manifest-path "$DEVENV_ROOT/Cargo.toml" --bin slop-broker -- approve "$@"'';
|
||||
};
|
||||
demo = {
|
||||
description = "Boot the demo's agents' VM on this terminal; needs `devenv up` running";
|
||||
exec = ''
|
||||
if [ ! -S ${run}/approve.sock ]; then
|
||||
echo "The broker isn't running: start \`devenv up\` first." >&2
|
||||
exit 1
|
||||
fi
|
||||
# Git from the VM: connections to 10.0.2.100:9418, an address only the guest sees, each
|
||||
# run a `git daemon` on the host serving the demo's repositories. Commas are doubled for
|
||||
# QEMU.
|
||||
daemon="${pkgs.git}/bin/git daemon --inetd --export-all --enable=receive-pack --base-path=${repositories}"
|
||||
export QEMU_NET_OPTS="guestfwd=tcp:10.0.2.100:9418-cmd:''${daemon//,/,,}"
|
||||
exec nix run "$DEVENV_ROOT#demo" -- "$@"
|
||||
'';
|
||||
};
|
||||
demo-merge = {
|
||||
description = "Fast-forward the demo repository's `master` to a branch, as a person merging";
|
||||
exec = ''
|
||||
set -eu
|
||||
branch=''${1:?usage: demo-merge <branch>}
|
||||
cd ${repositories}/repo.git
|
||||
if ! git rev-parse --verify --quiet "refs/heads/$branch" >/dev/null; then
|
||||
echo "there's no branch $branch; the agent pushes one with \`git push origin <branch>\`" >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! git merge-base --is-ancestor master "refs/heads/$branch"; then
|
||||
echo "$branch isn't master plus new commits; rebase it on master first" >&2
|
||||
exit 1
|
||||
fi
|
||||
git update-ref refs/heads/master "refs/heads/$branch"
|
||||
echo "master is now at $(git rev-parse --short master)"
|
||||
'';
|
||||
};
|
||||
demo-box = {
|
||||
description = "SSH into the demo's box VM as `box`, with the broker's key";
|
||||
exec = ''
|
||||
exec ${pkgs.openssh}/bin/ssh -F none -i ${state}/broker-key -o IdentitiesOnly=yes \
|
||||
-o UserKnownHostsFile=${state}/known_hosts -o StrictHostKeyChecking=accept-new \
|
||||
-p ${toString demo.ports.boxSsh} box@localhost "$@"
|
||||
'';
|
||||
};
|
||||
demo-sign-in = {
|
||||
description = "Print a one-time link that signs in to the demo's Pocket ID as the approver";
|
||||
exec = ''
|
||||
${pocketIdApi}
|
||||
user=$(api GET 'users?search=demo' | jq -r '.data[] | select(.username == "demo") | .id')
|
||||
echo "${issuer}/lc/$(api POST "users/$user/one-time-access-token" -d '{"ttl":"1h"}' | jq -r .token)"
|
||||
'';
|
||||
};
|
||||
demo-reset = {
|
||||
description = "Delete the demo's state (Pocket ID's users and passkeys, keys, repository, audit log)";
|
||||
exec = ''rm -rf ${state}'';
|
||||
};
|
||||
vm-test = {
|
||||
description = "Run the NixOS VM test of the broker module (needs KVM)";
|
||||
exec = ''nix build -L --no-link "$DEVENV_ROOT#checks.x86_64-linux.vm" "$@"'';
|
||||
};
|
||||
};
|
||||
|
||||
# The demo's host side; not for `devenv test`
|
||||
tasks = lib.mkIf (!config.devenv.isTesting) {
|
||||
"slop-demo:keys" = {
|
||||
description = "Make the demo's secrets and SSH keys";
|
||||
exec = ''
|
||||
set -eu
|
||||
umask 077
|
||||
mkdir -p ${state}/box ${state}/pocket-id ${state}/web ${state}/builder ${run}
|
||||
|
||||
if [ ! -e ${state}/pocket-id.env ]; then
|
||||
key() { ${pkgs.openssl}/bin/openssl rand -hex 32; }
|
||||
printf 'ENCRYPTION_KEY=%s\nSTATIC_API_KEY=%s\n' "$(key)" "$(key)" > ${state}/pocket-id.env
|
||||
fi
|
||||
|
||||
# The box VM gets the broker's public key and its own host key through its shared directory
|
||||
[ -e ${state}/broker-key ] || ${pkgs.openssh}/bin/ssh-keygen -q -t ed25519 -N "" -C slop-demo -f ${state}/broker-key
|
||||
cp ${state}/broker-key.pub ${state}/box/broker.pub
|
||||
[ -e ${state}/box/host-key ] || ${pkgs.openssh}/bin/ssh-keygen -q -t ed25519 -N "" -C slop-demo-box -f ${state}/box/host-key
|
||||
'';
|
||||
};
|
||||
|
||||
# Once: the repository, with secrets encrypted to the demo person and the broker. The hook is
|
||||
# installed every time, so it follows changes here.
|
||||
"slop-demo:repo" = {
|
||||
description = "Seed the demo's repository and age identities";
|
||||
after = [ "slop-demo:keys" ];
|
||||
exec = ''
|
||||
set -eu
|
||||
umask 077
|
||||
export PATH=${lib.makeBinPath (with pkgs; [ coreutils gnused git rage openssl wireguard-tools jq ])}
|
||||
|
||||
if [ ! -d ${repositories}/repo.git ]; then
|
||||
for name in dev broker; do
|
||||
[ -e ${state}/$name-age.key ] || rage-keygen -o ${state}/$name-age.key 2>/dev/null
|
||||
rage-keygen -y ${state}/$name-age.key > ${state}/$name-age.pub
|
||||
done
|
||||
dev=$(cat ${state}/dev-age.pub) broker=$(cat ${state}/broker-age.pub)
|
||||
|
||||
work=$(mktemp -d)
|
||||
cp -r ${./nix/demo/repo}/. "$work"
|
||||
chmod -R u+w "$work"
|
||||
sed -i "s/@boxSsh@/${toString demo.ports.boxSsh}/" "$work/flake.nix"
|
||||
mkdir "$work/secrets"
|
||||
# nixpkgs as this repository locks it, so the builder already has it
|
||||
jq '{nodes: {root: {inputs: {nixpkgs: "nixpkgs"}}, nixpkgs: .nodes[.nodes.root.inputs.nixpkgs]}, root: "root", version: 7}' \
|
||||
${./flake.lock} > "$work/flake.lock"
|
||||
cat > "$work/secrets.nix" <<EOF
|
||||
# The agenix rules: who each secret is encrypted to.
|
||||
let
|
||||
dev = "$dev";
|
||||
broker = "$broker";
|
||||
in
|
||||
{
|
||||
"secrets/app.env.age".publicKeys = [ dev broker ];
|
||||
"secrets/wg.key.age".publicKeys = [ dev broker ];
|
||||
}
|
||||
EOF
|
||||
printf 'DB_USER=app\nDB_PASSWORD=%s\n' "$(openssl rand -hex 12)" |
|
||||
rage -a -r "$dev" -r "$broker" -o "$work/secrets/app.env.age"
|
||||
wg genkey | rage -a -r "$dev" -r "$broker" -o "$work/secrets/wg.key.age"
|
||||
|
||||
export GIT_AUTHOR_NAME=Dev GIT_AUTHOR_EMAIL=dev@example.org
|
||||
export GIT_COMMITTER_NAME=Dev GIT_COMMITTER_EMAIL=dev@example.org
|
||||
git -C "$work" init -q --initial-branch=master
|
||||
git -C "$work" add .
|
||||
git -C "$work" commit -q -m "Start the demo repository"
|
||||
mkdir -p ${repositories}
|
||||
git init -q --bare --initial-branch=master ${repositories}/repo.git
|
||||
git -C "$work" push -q ${repositories}/repo.git master
|
||||
rm -rf "$work"
|
||||
fi
|
||||
|
||||
ln -sf ${preReceive} ${repositories}/repo.git/hooks/pre-receive
|
||||
'';
|
||||
};
|
||||
|
||||
# Once: the approver `demo` in the group `slop-approvers`, and the broker's OIDC client
|
||||
"slop-demo:pocket-id" = {
|
||||
description = "Set up the demo's approver and OIDC client in Pocket ID";
|
||||
after = [ "devenv:processes:pocket-id" ];
|
||||
status = "test -s ${state}/oidc-secret";
|
||||
exec = ''
|
||||
set -eu
|
||||
umask 077
|
||||
${pocketIdApi}
|
||||
|
||||
user=$(api POST users -d '{"username":"demo","email":"demo@example.org","firstName":"Demo","lastName":"Approver","displayName":"Demo Approver","isAdmin":false}' | jq -r .id)
|
||||
group=$(api POST user-groups -d '{"name":"slop-approvers","friendlyName":"slop approvers"}' | jq -r .id)
|
||||
api PUT "user-groups/$group/users" -d "$(jq -n --arg u "$user" '{userIds: [$u]}')" >/dev/null
|
||||
|
||||
api POST oidc/clients -d '{"id":"slop-approve","name":"slop-broker demo","callbackURLs":["${appUrl}/auth/callback"],"isPublic":false,"pkceEnabled":true,"isGroupRestricted":true}' >/dev/null
|
||||
api PUT oidc/clients/slop-approve/allowed-user-groups -d "$(jq -n --arg g "$group" '{userGroupIds: [$g]}')" >/dev/null
|
||||
api POST oidc/clients/slop-approve/secrets | jq -j .secret > ${state}/oidc-secret.new
|
||||
mv ${state}/oidc-secret.new ${state}/oidc-secret
|
||||
'';
|
||||
};
|
||||
};
|
||||
|
||||
processes = lib.mkIf (!config.devenv.isTesting) {
|
||||
pocket-id = {
|
||||
exec = ''
|
||||
set -a
|
||||
. ${state}/pocket-id.env
|
||||
exec ${pkgs.pocket-id}/bin/pocket-id
|
||||
'';
|
||||
cwd = "${state}/pocket-id";
|
||||
env = {
|
||||
APP_URL = issuer;
|
||||
HOST = "127.0.0.1";
|
||||
PORT = toString demo.ports.pocketId;
|
||||
ANALYTICS_DISABLED = "true";
|
||||
};
|
||||
after = [ "slop-demo:keys" ];
|
||||
ready = {
|
||||
http.get = { port = demo.ports.pocketId; path = "/.well-known/openid-configuration"; };
|
||||
period = 1;
|
||||
};
|
||||
};
|
||||
|
||||
slop-broker = {
|
||||
exec = ''
|
||||
sed -e "s/@group@/$(id -gn)/" -e "s/@dev@/$(cat ${state}/dev-age.pub)/" ${brokerConfig} > ${state}/broker.toml
|
||||
exec cargo run -q --bin slop-broker -- serve --config ${state}/broker.toml
|
||||
'';
|
||||
cwd = config.devenv.root;
|
||||
after = [ "slop-demo:pocket-id" "slop-demo:repo" ];
|
||||
ready = {
|
||||
exec = "test -S ${run}/approve.sock";
|
||||
period = 1;
|
||||
};
|
||||
};
|
||||
|
||||
box = {
|
||||
exec = ''SHARED_DIR=${state}/box exec nix run "$DEVENV_ROOT#demo-box"'';
|
||||
after = [ "slop-demo:keys" ];
|
||||
};
|
||||
scripts.vm-test = {
|
||||
description = "Run the NixOS VM test of the broker module (needs KVM)";
|
||||
exec = ''nix build -L --no-link "$DEVENV_ROOT#checks.x86_64-linux.vm" "$@"'';
|
||||
};
|
||||
|
||||
# `devenv test`
|
||||
|
||||
+69
-10
@@ -87,7 +87,44 @@ 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, `slop-approve` polls it through `ApproveRequest::Running`, 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.
|
||||
- `slop-approve` shows several requests on one `Board`, each labelled with its short ID. Waiting
|
||||
for requests, it polls the running ones once a second and passes on the phases that changed
|
||||
(`approve::Watch`); when one ends, its audit event has the phases it missed and the outcome.
|
||||
The bars pause while a request and its prompt are on the terminal.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
@@ -131,21 +168,24 @@ What each request runs, and whose code, decides whether it needs an approval fir
|
||||
| `src/server.rs` | Listeners (vsock, Unix), the per-connection handler, `authorize` |
|
||||
| `src/exec.rs` | Running processes on the requester's framed stdio; cancellation |
|
||||
| `src/ops/mod.rs` | `plan` (request → `Parsed`: scope, approval detail), `execute`, quoting |
|
||||
| `src/targets.rs` | SSH targets: the main branch's deploy-rs nodes from the builder, looked up again when stale or when a request names an unknown node |
|
||||
| `src/targets.rs` | SSH targets: the main branch's deploy-rs nodes from the builder, looked up again when stale or when a request names an unknown node; each request's pick of nodes' addresses (`reach`) |
|
||||
| `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` and `slop-approve` show 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` |
|
||||
| `tests/broker.rs` | Handler tests over an in-memory duplex stream with a fake `ssh` |
|
||||
| `src/web/` | The approvals web app: routes (`mod.rs`), OIDC sign-in and passkey confirmation (`auth.rs`), Web Push (`push.rs`), the audit log by request (`history.rs`), the pages (`page.rs`) and static assets |
|
||||
| `src/web/` | The approvals web app: routes (`mod.rs`), each page's Server-Sent Events (`events.rs`), OIDC sign-in and passkey confirmation (`auth.rs`; `[web.no_sign_in]` goes without, for the demo and tests), Web Push (`push.rs`), the audit log by request (`history.rs`), the pages (`page.rs`) and static assets, among them the page script (`assets/app.js`) and idiomorph, vendored (`assets/idiomorph.js`) |
|
||||
| `templates/`, `askama.toml` | The web app's HTML, as [askama](https://askama.rs) templates compiled into the broker; `askama.toml` passes everything they show through `ops::printable` before escaping it |
|
||||
| `nix/` | The package, NixOS modules (`modules/nixos`), home-manager module (`modules/home-manager`), the VM test (`vm-test.nix`, `checks.<system>.vm`), clippy and rustfmt checks (`lints.nix`) and the demo's VMs and repository template (`demo/`, `packages.<system>.demo` and `demo-box`) |
|
||||
| `devenv.nix` | The development environment, its scripts and the demo's host side (`devenv up`); `nix develop` gives a plainer shell from `flake.nix` without them |
|
||||
| `nix/` | The package, NixOS modules (`modules/nixos`), home-manager module (`modules/home-manager`), the VM test (`vm-test.nix`, `checks.<system>.vm`), clippy and rustfmt checks (`lints.nix`) and the demo's VMs, host side and repository template (`demo/`, `packages.<system>.demo` and `demo-box`, and `host.nix`, which `devenv.nix` imports) |
|
||||
| `devenv.nix` | The development environment and its scripts, with the demo's host side (`devenv up`) from `nix/demo/host.nix`; `nix develop` gives a plainer shell from `flake.nix` without them |
|
||||
| `.gitea/workflows/ci.yaml` | CI: `nix flake check` |
|
||||
|
||||
## Request lifecycle
|
||||
@@ -248,7 +288,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,14 +374,15 @@ 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,
|
||||
}
|
||||
|
||||
enum Destination {
|
||||
Node(NodeName), // a target
|
||||
Container { node: NodeName, name: ContainerName }, // `node.container-<name>`
|
||||
Host { user: UserName, host: HostName, port: u16 }, // `--host`
|
||||
}
|
||||
|
||||
@@ -367,6 +408,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:
|
||||
@@ -392,15 +434,25 @@ enum ApproveRequest {
|
||||
List,
|
||||
Decide { id: String, decision: Decision }, // Decision: Once, Lease(seconds) or Deny
|
||||
Log { count: usize }, // at most 200 records
|
||||
Running, // requests that build, copy or activate
|
||||
}
|
||||
|
||||
enum ApproveResponse {
|
||||
Pending(Vec<PendingInfo>),
|
||||
Recorded,
|
||||
Log(Vec<audit::Record>),
|
||||
Running(Vec<RunInfo>), // the oldest first
|
||||
Error(String),
|
||||
}
|
||||
|
||||
struct RunInfo {
|
||||
id: String,
|
||||
requester: String,
|
||||
summary: String,
|
||||
elapsed: u64,
|
||||
phases: Vec<Progress>, // each phase's latest
|
||||
}
|
||||
|
||||
struct PendingInfo {
|
||||
id: String,
|
||||
requester: String,
|
||||
@@ -422,7 +474,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 }
|
||||
@@ -509,7 +562,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.
|
||||
@@ -527,6 +581,7 @@ none can be read as an option, and `--` comes before the hostname.
|
||||
| `slop-approve` on the broker's box | `approve.sock`, for the `slop-broker-approve` group | The user name |
|
||||
| `slop-approve` on another box | SSH, a key in `sshApprovers` | `<name> (ssh)` |
|
||||
| The web app | OpenID Connect | `<name> (web)`, or `<name> (web, passkey)` |
|
||||
| The web app without sign-in, for the demo and tests | `[web.no_sign_in]`, only on a loopback address | `<name> (web, no sign-in)` |
|
||||
|
||||
- A requester's UID is refused on `approve.sock` even if it's in the group.
|
||||
- All of them call `approve::approve`, which records the decision and audits it. The approver's
|
||||
@@ -613,6 +668,10 @@ none can be read as an option, and `--` comes before the hostname.
|
||||
- ssh keeps the first value of an option. `nix copy` to `ssh://` adds `PermitLocalCommand=yes` and
|
||||
waits for `echo started`, so the broker's `PermitLocalCommand=no` would hang it forever (see
|
||||
`copy_options`).
|
||||
- A copy from the builder's store to a node has one `NIX_SSHOPTS` for both connections.
|
||||
The builder's store URL therefore carries its port and key (`ssh-ng://user@host:port?ssh-key=`):
|
||||
Nix puts them after `NIX_SSHOPTS`, and for `-p` the last value wins (see
|
||||
`DeployConfig::builder_store`).
|
||||
- A tokio program that reads stdin can't return from `main` while that read blocks; the builder
|
||||
worker calls `std::process::exit` after writing its result.
|
||||
- Session variables from home-manager only reach shells started after the next login
|
||||
|
||||
+62
-23
@@ -31,7 +31,7 @@ flowchart TB
|
||||
shell["devenv shell:<br>slop-approve, demo-merge"]
|
||||
|
||||
subgraph host["Host (devenv up)"]
|
||||
pocket["Pocket ID<br>localhost:1411"]
|
||||
pocket["Pocket ID, with sign-in<br>localhost:1411"]
|
||||
broker["Broker, with the web app<br>localhost:8095"]
|
||||
daemon["git daemon"]
|
||||
builder["Builder"]
|
||||
@@ -40,6 +40,7 @@ flowchart TB
|
||||
|
||||
subgraph boxvm["Box VM"]
|
||||
sshd["sshd, as box<br>(nodes web, router, vault, box)"]
|
||||
cache["sshd, as cache<br>(the binary cache's store)"]
|
||||
end
|
||||
|
||||
slop -- "vsock" --> broker
|
||||
@@ -50,47 +51,53 @@ flowchart TB
|
||||
shell -- "moves master" --> repo
|
||||
broker -- "SSH, through a wrapper" --> builder -- "fetches" --> repo
|
||||
broker -- "SSH, localhost:2222" --> sshd
|
||||
broker -- "SSH, localhost:2222" --> cache
|
||||
```
|
||||
|
||||
| Part | Where | Runs |
|
||||
|---|---|---|
|
||||
| Broker, from this checkout (`cargo run`) | Host | `devenv up` (process `slop-broker`) |
|
||||
| Web app | <http://localhost:8095> | Part of the broker |
|
||||
| [Pocket ID](https://pocket-id.org), for approvers to sign in | <http://localhost:1411> | `devenv up` (process `pocket-id`) |
|
||||
| Box VM ([`box.nix`](../nix/demo/box.nix)): `sshd` for the targets, and the deploy target | `localhost:2222`, as `box` | `devenv up` (process `box`) |
|
||||
| [Pocket ID](https://pocket-id.org), for approvers to sign in, if they do (see [Approving](#approving)) | <http://localhost:1411> | `devenv up` with `slopDemo.signIn` (process `pocket-id`) |
|
||||
| Box VM ([`box.nix`](../nix/demo/box.nix)): `sshd` for the targets, the deploy target and the binary cache | `localhost:2222`, as `box`, and as `cache` for the cache | `devenv up` (process `box`) |
|
||||
| Agents' VM ([`agent.nix`](../nix/demo/agent.nix)), signed in as `agent` | Your terminal | `demo` |
|
||||
| The repository, seeded from [`repo/`](../nix/demo/repo) | `.devenv/state/slop-demo/git/repo.git` | `git daemon`, one per connection from the agents' VM |
|
||||
| The builder (`slop-broker builder`, from this checkout) | Host | The broker, through its `ssh` |
|
||||
|
||||
The ports are on the host's loopback, so they must be free there; they and the agents' VM's vsock
|
||||
CID are in [`settings.nix`](../nix/demo/settings.nix). The broker's configuration is in
|
||||
[`devenv.nix`](../devenv.nix):
|
||||
[`host.nix`](../nix/demo/host.nix), the devenv module with the demo's host side:
|
||||
|
||||
- **Requester:** `agent`, the agents' VM's vsock CID. The VMs have no network beyond their
|
||||
forwarded ports, and only vsock and Git link the agents' VM to the host (see
|
||||
[the repository](#the-repository)).
|
||||
- **Approvers:** members of your primary group, through `slop-approve` in the devenv shell, and the
|
||||
Pocket ID user `demo` (in the group `slop-approvers`) through the web app.
|
||||
- **Approvers:** members of your primary group, through `slop-approve` in the devenv shell, and
|
||||
`demo` through the web app: everyone who opens it, or with sign-in, the Pocket ID user `demo` (in
|
||||
the group `slop-approvers`).
|
||||
- **Targets:** the repository's deploy-rs nodes on `master`, `box`, `web`, `router` and `vault`,
|
||||
which all reach the box VM. Only `box` has a profile to deploy.
|
||||
- **Policy:**
|
||||
- The box queries (`slop status`, `slop logs`, `slop failed`) run without asking.
|
||||
- `slop ssh web` asks, and offers leases of 5 minutes or an hour.
|
||||
- `slop ssh router` asks and needs a passkey (`confirm = "passkey"`), so only the web app can
|
||||
approve it.
|
||||
- `slop ssh router` asks and needs a passkey (`confirm = "passkey"`), so only the web app with
|
||||
sign-in can approve it.
|
||||
- `slop ssh vault` is denied.
|
||||
- `slop secret keys` runs without asking; the other secret requests ask, with a 5-minute
|
||||
lease, except reading, which asks every time.
|
||||
- Using the builder asks, with leases, except for commits already on `master`; deploys ask.
|
||||
There's no binary cache, so `slop build` says it isn't configured.
|
||||
- Using the builder asks, with leases, except for commits already on `master`; deploys and
|
||||
builds into the binary cache ask, with a 5-minute lease.
|
||||
|
||||
## Approving
|
||||
|
||||
- **Terminal:** `slop-approve` in the devenv shell lists pending requests; answer one with
|
||||
`slop-approve <id> once|<lease>|deny`.
|
||||
- **Web app:** `demo-sign-in` prints a one-time link that signs in to Pocket ID as `demo`. Add a
|
||||
passkey when Pocket ID asks, then sign in to <http://localhost:8095>; the passkey also approves
|
||||
`router` requests. Web Push works when the broker can reach the browser's push service.
|
||||
- **Web app:** <http://localhost:8095>, without sign-in: everyone who opens it approves as `demo`,
|
||||
which every page says, and it can't approve requests that need a passkey. Web Push works when
|
||||
the broker can reach the browser's push service.
|
||||
- **Sign-in and passkeys:** add `slopDemo.signIn = true;` to `devenv.local.nix` (see
|
||||
[`sign-in.nix`](../nix/demo/sign-in.nix)) and restart `devenv up`, which then runs Pocket ID too.
|
||||
`demo-sign-in` prints a one-time link that signs in to Pocket ID as `demo`. Add a passkey when
|
||||
Pocket ID asks, then sign in to the web app; the passkey also approves `router` requests.
|
||||
|
||||
A request blocks until it's answered, and `slop ssh` reads stdin to its end before asking. To keep
|
||||
the agent's shell, run requests in the background with stdin closed:
|
||||
@@ -121,6 +128,9 @@ slop ssh web -- uptime </dev/null &
|
||||
- **The builder** is reached over SSH, as in a real deployment.
|
||||
- The broker's `ssh` is a wrapper that runs `slop-broker builder` from this checkout's build
|
||||
when the host is `builder`, and the real `ssh` otherwise.
|
||||
- It's named `ssh`, so the broker's `nix copy` and `nix path-info` use it too when they read
|
||||
built paths from the builder's store (`ssh-ng://builder@builder`), which the builder serves
|
||||
as `nix-daemon --stdio`.
|
||||
- The builder fetches from the repository's path and evaluates with the host's Nix.
|
||||
|
||||
### Secrets
|
||||
@@ -146,13 +156,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 &
|
||||
```
|
||||
|
||||
@@ -164,6 +185,25 @@ profile). `demo-box cat /run/demo/version` on the host shows what's active.
|
||||
The box VM lets `box` use `sudo` without a password and copy unsigned paths into its store, which
|
||||
lives in memory, like everything else in the VMs.
|
||||
|
||||
### The binary cache
|
||||
|
||||
The box VM holds the binary cache's store, at `/var/lib/slop-cache`, owned by its `cache`
|
||||
account, as [`services.slop-broker-cache`](../nix/modules/nixos/cache.nix) sets it up: the
|
||||
broker's key may only run `nix-daemon --stdio` on that store and add GC roots. Nothing serves it
|
||||
to other boxes; it's for seeing what `slop build` pushes. In `~/repo` on the agents' VM:
|
||||
|
||||
```sh
|
||||
slop build packages.x86_64-linux.default </dev/null &
|
||||
```
|
||||
|
||||
As with a deploy, the builder's use is approved first (or covered by a lease), then the build
|
||||
request shows the outputs and their closure sizes, and once approved the broker pushes them and
|
||||
prints their paths. To see them on the host:
|
||||
|
||||
```sh
|
||||
demo-box ls /var/lib/slop-cache/nix/var/nix/gcroots/slop-broker
|
||||
```
|
||||
|
||||
## The box VM
|
||||
|
||||
`demo-box` in the devenv shell logs in to the box VM as `box`, with the broker's key, to see what
|
||||
@@ -173,11 +213,10 @@ approved commands did; `demo-box <command>` runs one command there. Its console
|
||||
## State
|
||||
|
||||
The VMs keep nothing: `poweroff` (or Ctrl-A X) stops the agents' VM, and each boot starts from
|
||||
scratch. The host side keeps its state in `.devenv/state/slop-demo` between runs: Pocket ID's
|
||||
database (so passkeys survive), the keys, the repository and the builder's mirror, the audit log
|
||||
and the web app's sessions. `demo-reset`
|
||||
deletes it while `devenv up` isn't running; the next `devenv up` sets Pocket ID up again and seeds
|
||||
a new repository. The repository is seeded only once, so after changing
|
||||
scratch. The host side keeps its state in `.devenv/state/slop-demo` between runs: the keys, the
|
||||
repository and the builder's mirror, the audit log, the web app's sessions, and with sign-in,
|
||||
Pocket ID's database (so passkeys survive). `demo-reset` deletes it while `devenv up` isn't
|
||||
running; the next `devenv up` seeds a new repository, and sets Pocket ID up again. The repository is seeded only once, so after changing
|
||||
[`nix/demo/repo`](../nix/demo/repo), reset (or delete `git`, `builder` and the `*-age.*` keys in the
|
||||
state directory) to use the new version.
|
||||
|
||||
|
||||
+64
-8
@@ -102,7 +102,8 @@ and `slop-approve`. How the code does it is in
|
||||
- **One connection per request**, carrying in order:
|
||||
1. the request;
|
||||
2. the operation's stdin, only after approval and only for operations that read it (`ssh`
|
||||
carries its stdin in the request instead, below);
|
||||
carries its stdin in the request instead, below). The broker drops stdin an operation
|
||||
doesn't read, and treats a requester sending more than 1 MiB as gone;
|
||||
3. its stdout and stderr;
|
||||
4. a final message with the exit status and any structured result.
|
||||
|
||||
@@ -195,8 +196,8 @@ own fields. The module and the broker refuse any other operation or field.
|
||||
|
||||
| Operation | Fields rules can match |
|
||||
|---|---|
|
||||
| `query` (`status`, `logs`, `failed`) | `target` (a node), or `host` and `port` (`--host`); `query` |
|
||||
| `ssh` | `target`, or `host` and `port` |
|
||||
| `query` (`status`, `logs`, `failed`) | `target` (a node) and `container` (only for a container on it), or `host` and `port` (`--host`); `query` |
|
||||
| `ssh` | `target` and `container`, or `host` and `port` |
|
||||
| `deploy` | `node`, `profile`, `mode` (`switch` or `boot`), `commit`; checked per target, and the strictest answer applies |
|
||||
| `builder` | `commit`, `on_branch` (`true` or `false`), `for` (`deploy` or `build`) |
|
||||
| `build` | `attr`, `commit`; checked per attribute |
|
||||
@@ -226,13 +227,36 @@ 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.
|
||||
- `slop-approve list` lists running requests below the pending ones, with what each is doing.
|
||||
While `slop-approve` waits for requests, it shows the same bars as `slop`, labelled with each
|
||||
request's ID, and how each request ended.
|
||||
- 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.
|
||||
- Each request's page shows its full timeline, including the detail approvers saw, so a
|
||||
notification for a request that's since been answered still leads somewhere useful.
|
||||
- **Front end.** Server-rendered HTML that works without JavaScript.
|
||||
- A small script refreshes the list and manages notifications, and a service worker shows them.
|
||||
- A small script keeps the page current and manages notifications, and a service worker shows
|
||||
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, 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.
|
||||
- A region comes when the stream starts, so a page that lost its connection catches up when
|
||||
the browser reconnects, and then when it changes. Signing out ends the stream.
|
||||
- Everything shown passes through the same filter as `slop-approve` for control and
|
||||
bidirectional characters.
|
||||
- A strict content security policy allows only the app's own scripts.
|
||||
@@ -339,11 +363,36 @@ ciphertext they were sent, never values.
|
||||
|
||||
- **Targets** are the deploy-rs nodes on the main branch, by name, so a new box needs a commit
|
||||
there rather than a new broker config. SSH therefore needs deploys set up.
|
||||
- The builder evaluates each node's `hostname`, `sshUser`, `sshOpts` and `sudo`, falling back to
|
||||
the flake-wide `sshUser` and `sudo`. Only the protected branch's Nix runs, as for secrets.
|
||||
- The builder evaluates each node's `hostname`, `sshHostnames`, `sshUser`, `sshOpts` and
|
||||
`sudo`, falling back to the flake-wide `sshUser` and `sudo`, and its profiles' names. Only the
|
||||
protected branch's Nix runs, as for secrets.
|
||||
- The broker looks them up again when they're stale, or when a request names a node it doesn't
|
||||
know.
|
||||
- **Several addresses.** A node can list `sshHostnames`, addresses to try in order instead of
|
||||
`hostname`, for a box that moves between networks (at home, or through a VPN). It's an
|
||||
extension to deploy-rs's node settings, which deploy-rs ignores.
|
||||
- Each request picks one address for each such node, and uses it for every connection: the
|
||||
first whose SSH port (as `ssh -G` works it out with the node's options) accepts a TCP
|
||||
connection within two seconds, else the last. A deploy picks once it's built, before its
|
||||
copies.
|
||||
- The requester gets a line saying which, and approvers and the audit log see it in the
|
||||
request's `Addresses`.
|
||||
- The probe connects to the address directly, so it can't tell through a `ProxyJump`.
|
||||
- `--host` covers boxes outside them (OpenWrt, switches) with an explicit `user@host` and port.
|
||||
- **Containers** are targets too, as `node.container-<name>`, the same name `slop deploy` takes:
|
||||
a node's `container-<name>` profiles say which containers it has, and `<name>` is the machine
|
||||
name `systemd-machined` knows the container by (a NixOS container, or any `systemd-nspawn`
|
||||
machine).
|
||||
- The broker reaches the node as usual and runs the command there as root, through the node's
|
||||
`sudo`: `systemctl --machine`, `journalctl --machine` and, for `ssh`, `systemd-run --machine
|
||||
--pipe --wait` with `/bin/sh -l -c <line>`. Stdin, output and the exit status pass through.
|
||||
- Approvers see the container and the remote command, including `sudo … root` and
|
||||
`--machine`.
|
||||
- A container's scope has the node as `target` and the container as `container`. Rules for a
|
||||
node therefore apply to its containers (match `container = "*"` to tell them apart), but a
|
||||
lease covers only the target it was granted for.
|
||||
- Commands go to the node's login shell as one string, quoted so that a POSIX shell and `fish`
|
||||
read the same words.
|
||||
- **Fixed options.** SSH runs with `-F none`, the key with `IdentitiesOnly`, no agent,
|
||||
`BatchMode`, no forwarding or local commands, and the broker's own `known_hosts` (new hosts are
|
||||
accepted, changed ones refused).
|
||||
@@ -385,10 +434,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.
|
||||
|
||||
@@ -10,6 +10,9 @@
|
||||
systems = [ "x86_64-linux" "aarch64-linux" ];
|
||||
forSystems = f: lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system});
|
||||
|
||||
# The commit the package's version shows, if the flake is from Git
|
||||
rev = self.shortRev or self.dirtyShortRev or null;
|
||||
|
||||
# Each module defaults its `package` to this flake's build for the system it's used on
|
||||
withPackage = path: option: { lib, pkgs, ... }: {
|
||||
imports = [ path ];
|
||||
@@ -19,7 +22,7 @@
|
||||
in
|
||||
{
|
||||
packages = forSystems (pkgs: rec {
|
||||
slop-broker = pkgs.callPackage ./nix/package.nix { };
|
||||
slop-broker = pkgs.callPackage ./nix/package.nix { inherit rev; };
|
||||
default = slop-broker;
|
||||
# The demo's VMs (see `docs/demo.md`)
|
||||
demo = import ./nix/demo/agent.nix { inherit pkgs slop-broker; };
|
||||
@@ -27,7 +30,7 @@
|
||||
});
|
||||
|
||||
overlays.default = final: _prev: {
|
||||
slop-broker = final.callPackage ./nix/package.nix { };
|
||||
slop-broker = final.callPackage ./nix/package.nix { inherit rev; };
|
||||
};
|
||||
|
||||
nixosModules = {
|
||||
@@ -48,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
|
||||
|
||||
+20
-10
@@ -8,17 +8,18 @@ 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'
|
||||
|
||||
slop-broker demo. You're `agent` on the agents' VM; the broker runs on the host, and the
|
||||
targets `web`, `router` and `vault` are all the box VM.
|
||||
targets `web`, `router`, `vault` and `box` are all the box VM.
|
||||
|
||||
slop status web sshd.service runs without asking (policy: auto)
|
||||
slop logs web sshd.service -n 20
|
||||
slop ssh web -- uptime asks an approver; leases of 5m or 1h are offered
|
||||
slop ssh router -- uptime asks too, and approving needs a passkey in the web app
|
||||
slop ssh router -- uptime asks too, and approving needs a passkey (web app sign-in)
|
||||
slop ssh vault -- true denied by policy
|
||||
slop requests your pending requests and leases
|
||||
slop guide the guide agents get
|
||||
@@ -34,14 +35,21 @@ 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):
|
||||
|
||||
slop build packages.x86_64-linux.default </dev/null &
|
||||
asks to use the builder, builds, then asks to push
|
||||
|
||||
Approve on the host: `slop-approve` in the devenv shell, or the web app at
|
||||
http://localhost:${toString settings.ports.web} (`demo-sign-in` prints a sign-in link).
|
||||
http://localhost:${toString settings.ports.web}, which has no sign-in unless it's turned on.
|
||||
|
||||
A request blocks until it's answered. To keep this shell, run it in the background with stdin
|
||||
closed (`slop ssh` forwards stdin): `slop ssh web -- uptime </dev/null &`. `poweroff` (or
|
||||
@@ -65,11 +73,12 @@ in
|
||||
qemu.options = [ "-device vhost-vsock-pci,guest-cid=${toString settings.agentCid}" ];
|
||||
};
|
||||
|
||||
# `agent`, signed in on the serial console, the only one `demo` shows. A second autologin on
|
||||
# `tty1` would also run the login script below, and its clone would race this one's.
|
||||
users.users.agent.isNormalUser = true;
|
||||
services.getty.autologinUser = "agent";
|
||||
# The serial console is the only one `demo` shows. A second autologin on `tty1` would also run
|
||||
# the login script below, and its clone would race this one's.
|
||||
systemd.services."autovt@tty1".enable = false;
|
||||
|
||||
# So `poweroff` works from the serial console
|
||||
security.polkit = {
|
||||
enable = true;
|
||||
@@ -82,8 +91,8 @@ in
|
||||
'';
|
||||
};
|
||||
|
||||
environment.systemPackages = [ slop-broker help pkgs.git ];
|
||||
# For `slop secret`, which evaluates `secrets.nix`
|
||||
# `slop`, and Git and Nix for working in the repository. `slop secret` evaluates `secrets.nix`.
|
||||
environment.systemPackages = [ slop-broker help bump pkgs.git ];
|
||||
nix.settings.experimental-features = [ "nix-command" "flakes" ];
|
||||
environment.etc.gitconfig.text = ''
|
||||
[user]
|
||||
@@ -91,6 +100,7 @@ in
|
||||
email = agent@example.org
|
||||
'';
|
||||
|
||||
# At login: the clone, once, then the help
|
||||
programs.bash.loginShellInit = ''
|
||||
if [ "$USER" = agent ]; then
|
||||
if [ ! -d ~/repo ] && ! git clone -q ${repository} ~/repo; then
|
||||
|
||||
+43
-11
@@ -1,15 +1,22 @@
|
||||
# The box the demo's SSH targets reach: `sshd` with a `box` account for the broker's key, which may
|
||||
# use `sudo` and copy store paths, so the broker can deploy to it. `devenv up` runs it with
|
||||
# `SHARED_DIR` holding the broker's public key and the box's host key, which it keeps between runs
|
||||
# so the broker's `known_hosts` stays valid.
|
||||
# The box the demo's SSH targets reach, over `sshd` on a port forwarded to the host's loopback:
|
||||
#
|
||||
# - `box`, for the broker's key, which may use `sudo` and copy store paths, so the broker can
|
||||
# deploy to it;
|
||||
# - `cache`, holding the binary cache's store, which `slop build` pushes to.
|
||||
#
|
||||
# `devenv up` runs it with `SHARED_DIR` holding the broker's public key and the box's host key,
|
||||
# which it keeps between runs so the broker's `known_hosts` stays valid.
|
||||
{ pkgs }:
|
||||
let
|
||||
inherit (pkgs) lib;
|
||||
settings = import ./settings.nix;
|
||||
|
||||
hostKey = "/etc/ssh/ssh_host_ed25519_key";
|
||||
cacheStore = "/var/lib/slop-cache";
|
||||
cacheHome = "/var/lib/slop-cache-home";
|
||||
in
|
||||
(pkgs.nixos ({ config, modulesPath, ... }: {
|
||||
imports = [ "${modulesPath}/virtualisation/qemu-vm.nix" ];
|
||||
imports = [ "${modulesPath}/virtualisation/qemu-vm.nix" ../modules/nixos/cache.nix ];
|
||||
|
||||
system.stateVersion = lib.trivial.release;
|
||||
networking.hostName = "slop-demo-box";
|
||||
@@ -17,8 +24,8 @@ in
|
||||
virtualisation = {
|
||||
graphics = false;
|
||||
diskImage = null;
|
||||
# Copied closures live in memory
|
||||
memorySize = 1024;
|
||||
# Copied closures live in memory, the cache's too
|
||||
memorySize = 2048;
|
||||
restrictNetwork = true;
|
||||
forwardPorts = [{
|
||||
from = "host";
|
||||
@@ -27,9 +34,9 @@ in
|
||||
}];
|
||||
};
|
||||
|
||||
users.users.box.isNormalUser = true;
|
||||
# Deploys: activation as root, and closures copied in unsigned (the store is the VM runner's
|
||||
# writable overlay). Nothing is substituted, since the VM has no network.
|
||||
users.users.box.isNormalUser = true;
|
||||
security.sudo.extraRules = [{
|
||||
users = [ "box" ];
|
||||
commands = [{ command = "ALL"; options = [ "NOPASSWD" ]; }];
|
||||
@@ -38,12 +45,28 @@ in
|
||||
trusted-users = [ "root" "box" ];
|
||||
substituters = lib.mkForce [ ];
|
||||
};
|
||||
|
||||
# The binary cache: a store of its own, owned by `cache`. Nothing serves it to other boxes; it's
|
||||
# for seeing what `slop build` pushes. The broker's key is authorized at boot, below.
|
||||
users.users.cache = {
|
||||
isNormalUser = true;
|
||||
home = cacheHome;
|
||||
createHome = true;
|
||||
};
|
||||
systemd.tmpfiles.rules = [ "d ${cacheStore} 0755 cache users -" ];
|
||||
services.slop-broker-cache = {
|
||||
enable = true;
|
||||
user = "cache";
|
||||
store = cacheStore;
|
||||
home = cacheHome;
|
||||
};
|
||||
|
||||
services.openssh = {
|
||||
enable = true;
|
||||
hostKeys = [{ path = hostKey; type = "ed25519"; }];
|
||||
};
|
||||
|
||||
# The shared directory is mounted at `/tmp/shared`
|
||||
# The keys from the shared directory, which is mounted at `/tmp/shared`, before `sshd` starts
|
||||
systemd.services.slop-demo-keys = {
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
before = [ "sshd.service" "sshd-keygen.service" ];
|
||||
@@ -52,8 +75,17 @@ in
|
||||
serviceConfig = { Type = "oneshot"; RemainAfterExit = true; };
|
||||
script = ''
|
||||
install -m 600 /tmp/shared/host-key ${hostKey}
|
||||
install -d -m 700 -o box -g users ${config.users.users.box.home}/.ssh
|
||||
install -m 600 -o box -g users /tmp/shared/broker.pub ${config.users.users.box.home}/.ssh/authorized_keys
|
||||
|
||||
# The broker logs in as `box` with its key, for anything
|
||||
box=${config.users.users.box.home}/.ssh
|
||||
install -d -m 700 -o box -g users $box
|
||||
install -m 600 -o box -g users /tmp/shared/broker.pub $box/authorized_keys
|
||||
|
||||
# and as `cache`, only through the cache's forced command
|
||||
cache=${cacheHome}/.ssh
|
||||
install -d -m 700 -o cache -g users $cache
|
||||
echo "restrict,command=\"${config.services.slop-broker-cache.forcedCommand}\" $(cat /tmp/shared/broker.pub)" |
|
||||
install -m 600 -o cache -g users /dev/stdin $cache/authorized_keys
|
||||
'';
|
||||
};
|
||||
})).vm
|
||||
@@ -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\`."
|
||||
'';
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
# The demo's host side, a devenv module that `devenv.nix` imports (see `docs/demo.md`). `devenv up`
|
||||
# runs the broker from this checkout, with its web app and builder, the box VM its SSH targets
|
||||
# reach, and the Git repository the agent pushes to. The web app has no sign-in unless
|
||||
# `sign-in.nix` adds Pocket ID. The devenv shell gets the commands to drive it (`demo`,
|
||||
# `slop-approve`, `demo-merge` and the like).
|
||||
{ pkgs, lib, config, ... }:
|
||||
let
|
||||
settings = import ./settings.nix;
|
||||
|
||||
# State kept between runs, and sockets, whose paths must be short
|
||||
state = "${config.devenv.state}/slop-demo";
|
||||
run = "${config.devenv.runtime}/slop-demo";
|
||||
# Bare repositories the agents' VM reaches with `git://`
|
||||
repositories = "${state}/git";
|
||||
|
||||
appUrl = "http://localhost:${toString settings.ports.web}";
|
||||
|
||||
# The builder: `slop-broker builder`, which the broker reaches through `ssh` (see `ssh` below).
|
||||
# The repository is a local path, so its key is never used.
|
||||
builderConfig = (pkgs.formats.toml { }).generate "slop-demo-builder.toml" {
|
||||
repository = "${repositories}/repo.git";
|
||||
key = "/nonexistent";
|
||||
branch = "master";
|
||||
directory = "${state}/builder";
|
||||
# The host's own Nix first, so builds go through its daemon as the user
|
||||
path = [
|
||||
"${pkgs.git}/bin"
|
||||
"${pkgs.openssh}/bin"
|
||||
"/run/current-system/sw/bin"
|
||||
"/nix/var/nix/profiles/default/bin"
|
||||
"${pkgs.nix}/bin"
|
||||
];
|
||||
};
|
||||
|
||||
# The broker's `ssh`, also `ssh` on the `PATH` of its `nix` (which takes it from the same
|
||||
# directory): the host `builder` runs the builder from this checkout's build directly, as its
|
||||
# forced command would, with the remote command in `SSH_ORIGINAL_COMMAND`. Everything else is
|
||||
# the real `ssh`.
|
||||
#
|
||||
# - The broker passes the host after `--`, then the command.
|
||||
# - Nix passes `builder@builder` and the command after `--`, first checks for a control master,
|
||||
# and waits for the `LocalCommand` it asks for.
|
||||
ssh = pkgs.writeShellScriptBin "ssh" ''
|
||||
builder="" master=0 remote=() after=0 started=0
|
||||
for arg; do
|
||||
if [ "$after" = 1 ]; then
|
||||
remote+=("$arg")
|
||||
elif [ "$arg" = -- ]; then
|
||||
after=1
|
||||
elif [ "$arg" = builder@builder ]; then
|
||||
builder=nix
|
||||
elif [ "$arg" = "-oLocalCommand=echo started" ]; then
|
||||
started=1
|
||||
elif [ "$arg" = -O ]; then
|
||||
master=1
|
||||
fi
|
||||
done
|
||||
if [ "''${#remote[@]}" -gt 0 ] && [ "''${remote[0]}" = builder ] && [ -z "$builder" ]; then
|
||||
builder=broker
|
||||
remote=("''${remote[@]:1}")
|
||||
fi
|
||||
|
||||
if [ -n "$builder" ]; then
|
||||
# The builder has no control master
|
||||
[ "$master" = 1 ] && exit 255
|
||||
[ "$started" = 1 ] && echo started
|
||||
SSH_ORIGINAL_COMMAND="''${remote[*]}" exec ${config.devenv.root}/target/debug/slop-broker builder --config ${builderConfig}
|
||||
fi
|
||||
exec ${pkgs.openssh}/bin/ssh "$@"
|
||||
'';
|
||||
|
||||
# Only `demo-merge` moves `master`, standing in for branch protection and a person merging
|
||||
preReceive = pkgs.writeShellScript "slop-demo-pre-receive" ''
|
||||
while read -r old new ref; do
|
||||
if [ "$ref" = refs/heads/master ]; then
|
||||
echo "master is protected: push a branch, and merge it with \`demo-merge <branch>\` on the host" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
'';
|
||||
|
||||
# The broker's configuration. `@group@` becomes the user's primary group, whose members may
|
||||
# approve, and `@dev@` the demo person's age public key.
|
||||
brokerConfig = (pkgs.formats.toml { }).generate "slop-demo.toml" {
|
||||
requesters.agent = { vsock_cid = settings.agentCid; policy = "agent"; };
|
||||
|
||||
policies.agent.ops = {
|
||||
query.action = "auto";
|
||||
ssh = {
|
||||
action = "ask";
|
||||
leases = [ "5m" "1h" ];
|
||||
rules = [
|
||||
{ match.target = "router"; action = "ask"; confirm = "passkey"; }
|
||||
{ match.target = "vault"; action = "deny"; }
|
||||
];
|
||||
};
|
||||
|
||||
# Agent-written Nix runs in the builder once its use is approved; `master` is reviewed
|
||||
builder = {
|
||||
action = "ask";
|
||||
leases = [ "5m" "1h" ];
|
||||
rules = [{ match.on_branch = "true"; action = "auto"; }];
|
||||
};
|
||||
deploy = {
|
||||
action = "ask";
|
||||
leases = [ "5m" ];
|
||||
};
|
||||
build = {
|
||||
action = "ask";
|
||||
leases = [ "5m" ];
|
||||
};
|
||||
|
||||
# Approvals show whether the file and its recipients match `master`; reading always asks
|
||||
secret = {
|
||||
action = "ask";
|
||||
leases = [ "5m" ];
|
||||
rules = [{ match.action = "keys"; action = "auto"; }];
|
||||
};
|
||||
};
|
||||
|
||||
vsock_port = 6262;
|
||||
approve_socket = "${run}/approve.sock";
|
||||
approver_group = "@group@";
|
||||
audit_log = "${state}/audit.jsonl";
|
||||
|
||||
# SSH to the box VM, and to the builder through the wrapper
|
||||
ssh = {
|
||||
ssh = "${ssh}/bin/ssh";
|
||||
key = "${state}/broker-key";
|
||||
known_hosts = "${state}/known_hosts";
|
||||
};
|
||||
deploy = {
|
||||
builder = { hostname = "builder"; user = "builder"; };
|
||||
nix = "${pkgs.nix}/bin/nix";
|
||||
cache = "${state}/nix-cache";
|
||||
};
|
||||
# The box VM's `cache` account, which holds the binary cache's store
|
||||
cache = {
|
||||
hostname = "localhost";
|
||||
user = "cache";
|
||||
ssh_opts = [ "-p" (toString settings.ports.boxSsh) ];
|
||||
key = "${state}/broker-key";
|
||||
};
|
||||
|
||||
secrets = {
|
||||
identity = "${state}/broker-age.key";
|
||||
names.dev = "@dev@";
|
||||
};
|
||||
|
||||
# Without sign-in unless `slopDemo.signIn` (see `sign-in.nix`)
|
||||
web = {
|
||||
listen = "127.0.0.1:${toString settings.ports.web}";
|
||||
url = appUrl;
|
||||
state_dir = "${state}/web";
|
||||
} // (if config.slopDemo.signIn then {
|
||||
issuer = "http://localhost:${toString settings.ports.pocketId}";
|
||||
client_id = "slop-approve";
|
||||
client_secret = "${state}/oidc-secret";
|
||||
group = "slop-approvers";
|
||||
} else {
|
||||
no_sign_in.approver = "demo";
|
||||
});
|
||||
};
|
||||
|
||||
in
|
||||
{
|
||||
imports = [ ./sign-in.nix ];
|
||||
|
||||
# For `slop-approve` in this shell
|
||||
env.SLOP_APPROVE = "unix:${run}/approve.sock";
|
||||
|
||||
scripts = {
|
||||
slop-approve = {
|
||||
description = "Answer the demo's requests (built from this checkout)";
|
||||
exec = ''exec cargo run -q --manifest-path "$DEVENV_ROOT/Cargo.toml" --bin slop-broker -- approve "$@"'';
|
||||
};
|
||||
|
||||
demo = {
|
||||
description = "Boot the demo's agents' VM on this terminal; needs `devenv up` running";
|
||||
exec = ''
|
||||
if [ ! -S ${run}/approve.sock ]; then
|
||||
echo "The broker isn't running: start \`devenv up\` first." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Git from the VM: connections to 10.0.2.100:9418, an address only the guest sees, each
|
||||
# run a `git daemon` on the host serving the demo's repositories. Commas are doubled for
|
||||
# QEMU.
|
||||
daemon="${pkgs.git}/bin/git daemon --inetd --export-all --enable=receive-pack --base-path=${repositories}"
|
||||
export QEMU_NET_OPTS="guestfwd=tcp:10.0.2.100:9418-cmd:''${daemon//,/,,}"
|
||||
exec nix run "$DEVENV_ROOT#demo" -- "$@"
|
||||
'';
|
||||
};
|
||||
|
||||
demo-merge = {
|
||||
description = "Fast-forward the demo repository's `master` to a branch, as a person merging";
|
||||
exec = ''
|
||||
set -eu
|
||||
branch=''${1:?usage: demo-merge <branch>}
|
||||
cd ${repositories}/repo.git
|
||||
|
||||
if ! git rev-parse --verify --quiet "refs/heads/$branch" >/dev/null; then
|
||||
echo "there's no branch $branch; the agent pushes one with \`git push origin <branch>\`" >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! git merge-base --is-ancestor master "refs/heads/$branch"; then
|
||||
echo "$branch isn't master plus new commits; rebase it on master first" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git update-ref refs/heads/master "refs/heads/$branch"
|
||||
echo "master is now at $(git rev-parse --short master)"
|
||||
'';
|
||||
};
|
||||
|
||||
demo-box = {
|
||||
description = "SSH into the demo's box VM as `box`, with the broker's key";
|
||||
exec = ''
|
||||
exec ${pkgs.openssh}/bin/ssh -F none -i ${state}/broker-key -o IdentitiesOnly=yes \
|
||||
-o UserKnownHostsFile=${state}/known_hosts -o StrictHostKeyChecking=accept-new \
|
||||
-p ${toString settings.ports.boxSsh} box@localhost "$@"
|
||||
'';
|
||||
};
|
||||
|
||||
demo-reset = {
|
||||
description = "Delete the demo's state (keys, repository, audit log, and Pocket ID's users and passkeys)";
|
||||
exec = ''rm -rf ${state}'';
|
||||
};
|
||||
};
|
||||
|
||||
# Not for `devenv test`
|
||||
tasks = lib.mkIf (!config.devenv.isTesting) {
|
||||
"slop-demo:keys" = {
|
||||
description = "Make the demo's secrets and SSH keys";
|
||||
exec = ''
|
||||
set -eu
|
||||
umask 077
|
||||
mkdir -p ${state}/box ${state}/web ${state}/builder ${run}
|
||||
|
||||
# The box VM gets the broker's public key and its own host key through its shared directory
|
||||
[ -e ${state}/broker-key ] || ${pkgs.openssh}/bin/ssh-keygen -q -t ed25519 -N "" -C slop-demo -f ${state}/broker-key
|
||||
cp ${state}/broker-key.pub ${state}/box/broker.pub
|
||||
[ -e ${state}/box/host-key ] || ${pkgs.openssh}/bin/ssh-keygen -q -t ed25519 -N "" -C slop-demo-box -f ${state}/box/host-key
|
||||
'';
|
||||
};
|
||||
|
||||
# Once: the repository, with secrets encrypted to the demo person and the broker. The hook is
|
||||
# installed every time, so it follows changes here.
|
||||
"slop-demo:repo" = {
|
||||
description = "Seed the demo's repository and age identities";
|
||||
after = [ "slop-demo:keys" ];
|
||||
exec = ''
|
||||
set -eu
|
||||
umask 077
|
||||
export PATH=${lib.makeBinPath (with pkgs; [ coreutils gnused git rage openssl wireguard-tools jq ])}
|
||||
|
||||
if [ ! -d ${repositories}/repo.git ]; then
|
||||
# Age identities for the demo person and the broker
|
||||
for name in dev broker; do
|
||||
[ -e ${state}/$name-age.key ] || rage-keygen -o ${state}/$name-age.key 2>/dev/null
|
||||
rage-keygen -y ${state}/$name-age.key > ${state}/$name-age.pub
|
||||
done
|
||||
dev=$(cat ${state}/dev-age.pub) broker=$(cat ${state}/broker-age.pub)
|
||||
|
||||
# The files from `repo/`, with the box VM's SSH port
|
||||
work=$(mktemp -d)
|
||||
cp -r ${./repo}/. "$work"
|
||||
chmod -R u+w "$work"
|
||||
sed -i "s/@boxSsh@/${toString settings.ports.boxSsh}/" "$work/flake.nix"
|
||||
|
||||
# nixpkgs as this repository locks it, so the builder already has it
|
||||
jq '{nodes: {root: {inputs: {nixpkgs: "nixpkgs"}}, nixpkgs: .nodes[.nodes.root.inputs.nixpkgs]}, root: "root", version: 7}' \
|
||||
${../../flake.lock} > "$work/flake.lock"
|
||||
|
||||
# The agenix rules and the secrets, encrypted to both
|
||||
cat > "$work/secrets.nix" <<EOF
|
||||
# The agenix rules: who each secret is encrypted to.
|
||||
let
|
||||
dev = "$dev";
|
||||
broker = "$broker";
|
||||
in
|
||||
{
|
||||
"secrets/app.env.age".publicKeys = [ dev broker ];
|
||||
"secrets/wg.key.age".publicKeys = [ dev broker ];
|
||||
}
|
||||
EOF
|
||||
mkdir "$work/secrets"
|
||||
printf 'DB_USER=app\nDB_PASSWORD=%s\n' "$(openssl rand -hex 12)" |
|
||||
rage -a -r "$dev" -r "$broker" -o "$work/secrets/app.env.age"
|
||||
wg genkey | rage -a -r "$dev" -r "$broker" -o "$work/secrets/wg.key.age"
|
||||
|
||||
# Committed to `master` as Dev, and pushed to the bare repository
|
||||
export GIT_AUTHOR_NAME=Dev GIT_AUTHOR_EMAIL=dev@example.org
|
||||
export GIT_COMMITTER_NAME=Dev GIT_COMMITTER_EMAIL=dev@example.org
|
||||
git -C "$work" init -q --initial-branch=master
|
||||
git -C "$work" add .
|
||||
git -C "$work" commit -q -m "Start the demo repository"
|
||||
mkdir -p ${repositories}
|
||||
git init -q --bare --initial-branch=master ${repositories}/repo.git
|
||||
git -C "$work" push -q ${repositories}/repo.git master
|
||||
rm -rf "$work"
|
||||
fi
|
||||
|
||||
ln -sf ${preReceive} ${repositories}/repo.git/hooks/pre-receive
|
||||
'';
|
||||
};
|
||||
};
|
||||
|
||||
processes = lib.mkIf (!config.devenv.isTesting) {
|
||||
slop-broker = {
|
||||
exec = ''
|
||||
sed -e "s/@group@/$(id -gn)/" -e "s/@dev@/$(cat ${state}/dev-age.pub)/" ${brokerConfig} > ${state}/broker.toml
|
||||
exec cargo run -q --bin slop-broker -- serve --config ${state}/broker.toml
|
||||
'';
|
||||
cwd = config.devenv.root;
|
||||
after = [ "slop-demo:repo" ] ++ lib.optional config.slopDemo.signIn "slop-demo:pocket-id";
|
||||
ready = {
|
||||
exec = "test -S ${run}/approve.sock";
|
||||
period = 1;
|
||||
};
|
||||
};
|
||||
|
||||
box = {
|
||||
exec = ''SHARED_DIR=${state}/box exec nix run "$DEVENV_ROOT#demo-box"'';
|
||||
after = [ "slop-demo:keys" ];
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -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"
|
||||
'';
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Shared by the demo's VMs and its host side in `devenv.nix`
|
||||
# Shared by the demo's VMs and its host side in `host.nix`
|
||||
{
|
||||
# The agents' VM's vsock CID: anything above 2 that no other VM on the host uses
|
||||
agentCid = 3626;
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
# Sign-in for the demo's web app, with Pocket ID, a devenv module that `host.nix` imports. Without
|
||||
# it the web app has no sign-in. Turn it on with `slopDemo.signIn = true;` in `devenv.local.nix`
|
||||
# to try signing in and passkeys, which approving `router` needs.
|
||||
{ pkgs, lib, config, ... }:
|
||||
let
|
||||
settings = import ./settings.nix;
|
||||
state = "${config.devenv.state}/slop-demo";
|
||||
issuer = "http://localhost:${toString settings.ports.pocketId}";
|
||||
appUrl = "http://localhost:${toString settings.ports.web}";
|
||||
|
||||
# Pocket ID's admin API, with the key `devenv up` made
|
||||
pocketIdApi = ''
|
||||
api() {
|
||||
local method=$1 path=$2
|
||||
shift 2
|
||||
curl -sS --fail-with-body -X "$method" "${issuer}/api/$path" \
|
||||
-H "X-API-Key: $(sed -n 's/^STATIC_API_KEY=//p' ${state}/pocket-id.env)" -H 'Content-Type: application/json' "$@"
|
||||
}
|
||||
'';
|
||||
in
|
||||
{
|
||||
options.slopDemo.signIn = lib.mkEnableOption "sign-in to the demo's web app, with Pocket ID";
|
||||
|
||||
config = lib.mkIf (config.slopDemo.signIn && !config.devenv.isTesting) {
|
||||
scripts.demo-sign-in = {
|
||||
description = "Print a one-time link that signs in to the demo's Pocket ID as the approver";
|
||||
exec = ''
|
||||
${pocketIdApi}
|
||||
user=$(api GET 'users?search=demo' | jq -r '.data[] | select(.username == "demo") | .id')
|
||||
echo "${issuer}/lc/$(api POST "users/$user/one-time-access-token" -d '{"ttl":"1h"}' | jq -r .token)"
|
||||
'';
|
||||
};
|
||||
|
||||
tasks = {
|
||||
"slop-demo:pocket-id-keys" = {
|
||||
description = "Make Pocket ID's keys for the demo";
|
||||
exec = ''
|
||||
set -eu
|
||||
umask 077
|
||||
mkdir -p ${state}/pocket-id
|
||||
if [ ! -e ${state}/pocket-id.env ]; then
|
||||
key() { ${pkgs.openssl}/bin/openssl rand -hex 32; }
|
||||
printf 'ENCRYPTION_KEY=%s\nSTATIC_API_KEY=%s\n' "$(key)" "$(key)" > ${state}/pocket-id.env
|
||||
fi
|
||||
'';
|
||||
};
|
||||
|
||||
# Once: the approver `demo` in the group `slop-approvers`, and the broker's OIDC client
|
||||
"slop-demo:pocket-id" = {
|
||||
description = "Set up the demo's approver and OIDC client in Pocket ID";
|
||||
after = [ "devenv:processes:pocket-id" ];
|
||||
status = "test -s ${state}/oidc-secret";
|
||||
exec = ''
|
||||
set -eu
|
||||
umask 077
|
||||
${pocketIdApi}
|
||||
|
||||
user=$(api POST users -d '{"username":"demo","email":"demo@example.org","firstName":"Demo","lastName":"Approver","displayName":"Demo Approver","isAdmin":false}' | jq -r .id)
|
||||
group=$(api POST user-groups -d '{"name":"slop-approvers","friendlyName":"slop approvers"}' | jq -r .id)
|
||||
api PUT "user-groups/$group/users" -d "$(jq -n --arg u "$user" '{userIds: [$u]}')" >/dev/null
|
||||
|
||||
api POST oidc/clients -d '{"id":"slop-approve","name":"slop-broker demo","callbackURLs":["${appUrl}/auth/callback"],"isPublic":false,"pkceEnabled":true,"isGroupRestricted":true}' >/dev/null
|
||||
api PUT oidc/clients/slop-approve/allowed-user-groups -d "$(jq -n --arg g "$group" '{userGroupIds: [$g]}')" >/dev/null
|
||||
api POST oidc/clients/slop-approve/secrets | jq -j .secret > ${state}/oidc-secret.new
|
||||
mv ${state}/oidc-secret.new ${state}/oidc-secret
|
||||
'';
|
||||
};
|
||||
};
|
||||
|
||||
processes.pocket-id = {
|
||||
exec = ''
|
||||
set -a
|
||||
. ${state}/pocket-id.env
|
||||
exec ${pkgs.pocket-id}/bin/pocket-id
|
||||
'';
|
||||
cwd = "${state}/pocket-id";
|
||||
env = {
|
||||
APP_URL = issuer;
|
||||
HOST = "127.0.0.1";
|
||||
PORT = toString settings.ports.pocketId;
|
||||
ANALYTICS_DISABLED = "true";
|
||||
};
|
||||
after = [ "slop-demo:pocket-id-keys" ];
|
||||
ready = {
|
||||
http.get = { port = settings.ports.pocketId; path = "/.well-known/openid-configuration"; };
|
||||
period = 1;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -37,8 +37,8 @@ let
|
||||
# The operations a policy can allow, as the broker names them (`OpName`), and the scope fields
|
||||
# their rules can match (`OpName::fields`)
|
||||
opFields = {
|
||||
query = [ "target" "host" "port" "query" ];
|
||||
ssh = [ "target" "host" "port" ];
|
||||
query = [ "target" "container" "host" "port" "query" ];
|
||||
ssh = [ "target" "container" "host" "port" ];
|
||||
deploy = [ "node" "profile" "mode" "commit" ];
|
||||
builder = [ "commit" "on_branch" "for" ];
|
||||
build = [ "attr" "commit" ];
|
||||
@@ -127,11 +127,15 @@ let
|
||||
|
||||
web = if web.enable then {
|
||||
listen = "${if hasInfix ":" web.address then "[${web.address}]" else web.address}:${toString web.port}";
|
||||
inherit (web) url issuer group;
|
||||
inherit (web) url;
|
||||
state_dir = "/var/lib/slop-broker/web";
|
||||
} // (if web.noSignIn == null then {
|
||||
inherit (web) issuer group;
|
||||
client_id = web.clientId;
|
||||
client_secret = "oidc-secret";
|
||||
state_dir = "/var/lib/slop-broker/web";
|
||||
} else null;
|
||||
} else {
|
||||
no_sign_in.approver = web.noSignIn;
|
||||
}) else null;
|
||||
|
||||
secrets = if secrets.enable then {
|
||||
identity = "age-identity";
|
||||
@@ -169,7 +173,7 @@ in
|
||||
hostname = mkOpt' str "localhost" "Box running the builder (`services.slop-broker-builder`).";
|
||||
user = mkOpt' str "slop-broker-build" "The builder's user.";
|
||||
sshOpts = mkOpt' (listOf str) [ "-p" (toString (head config.services.openssh.ports)) ]
|
||||
"Extra SSH arguments for reaching the builder.";
|
||||
"SSH arguments for reaching the builder: only `-p <port>`, which goes in the store URL built paths are copied from.";
|
||||
};
|
||||
};
|
||||
|
||||
@@ -190,6 +194,12 @@ in
|
||||
clientId = mkOpt' str "slop-approve" "OpenID Connect client ID.";
|
||||
clientSecretFile = mkOpt' str "" "Runtime path to the client secret; never a Nix store path.";
|
||||
group = mkOpt' str "slop-approvers" "Group (the ID token's `groups` claim) whose members may approve.";
|
||||
noSignIn = mkOption {
|
||||
type = lib.types.nullOr lib.types.str;
|
||||
default = null;
|
||||
internal = true;
|
||||
description = "For tests only: no sign-in, with everyone who reaches the web app approving as this name.";
|
||||
};
|
||||
};
|
||||
|
||||
secrets = {
|
||||
@@ -229,7 +239,8 @@ in
|
||||
message = "slop-broker SSH keys must be distinct; use separate keys for requesting and approving.";
|
||||
}
|
||||
{
|
||||
assertion = web.enable -> (web.url != "" && web.issuer != "" && isRuntimePath web.clientSecretFile);
|
||||
assertion = web.enable -> (web.url != ""
|
||||
&& (web.noSignIn != null || (web.issuer != "" && isRuntimePath web.clientSecretFile)));
|
||||
message = "slop-broker's web app needs a URL, an issuer and a runtime client secret file.";
|
||||
}
|
||||
{
|
||||
@@ -278,7 +289,7 @@ in
|
||||
LoadCredential =
|
||||
optional cfg.ssh.enable "ssh-key:${cfg.ssh.keyFile}" ++
|
||||
optional cfg.cache.enable "cache-key:${cfg.cache.keyFile}" ++
|
||||
optional web.enable "oidc-secret:${web.clientSecretFile}" ++
|
||||
optional (web.enable && web.noSignIn == null) "oidc-secret:${web.clientSecretFile}" ++
|
||||
optional secrets.enable "age-identity:${secrets.identityFile}";
|
||||
|
||||
User = "slop-broker";
|
||||
|
||||
@@ -51,6 +51,12 @@ in
|
||||
home = mkOpt' str null "`HOME` for the store's commands; a directory `user` can write to.";
|
||||
keepDays = mkOpt' ints.positive 14 "Days a pushed path stays rooted after its last push.";
|
||||
brokerKeys = mkOpt' (listOf str) [ ] "SSH public keys of brokers that may push.";
|
||||
forcedCommand = lib.mkOption {
|
||||
type = path;
|
||||
default = forcedCommand;
|
||||
readOnly = true;
|
||||
description = "The forced command for brokers' keys, for keys `brokerKeys` can't list, such as ones made at boot.";
|
||||
};
|
||||
};
|
||||
|
||||
config = mkIf cfg.enable {
|
||||
@@ -62,7 +68,7 @@ in
|
||||
];
|
||||
|
||||
users.users.${cfg.user}.openssh.authorizedKeys.keys =
|
||||
map (k: ''restrict,command="${forcedCommand}" ${k}'') cfg.brokerKeys;
|
||||
map (k: ''restrict,command="${cfg.forcedCommand}" ${k}'') cfg.brokerKeys;
|
||||
|
||||
# Expired roots go daily; the store's own garbage collection then takes their paths
|
||||
systemd = {
|
||||
|
||||
+10
-3
@@ -1,14 +1,17 @@
|
||||
{ lib, rustPlatform, pkg-config, openssl, sqlite }:
|
||||
# `rev` is the commit the build is from, like `2d59b59` or `2d59b59-dirty`, which the version
|
||||
# shows. It's part of the build, so every commit rebuilds the package.
|
||||
{ lib, rustPlatform, pkg-config, openssl, sqlite, rev ? null }:
|
||||
let
|
||||
inherit (lib.fileset) toSource unions;
|
||||
inherit ((builtins.fromTOML (builtins.readFile ../Cargo.toml)).package) version;
|
||||
in
|
||||
rustPlatform.buildRustPackage {
|
||||
pname = "slop-broker";
|
||||
inherit ((builtins.fromTOML (builtins.readFile ../Cargo.toml)).package) version;
|
||||
inherit version;
|
||||
|
||||
src = toSource {
|
||||
root = ../.;
|
||||
fileset = unions [ ../Cargo.toml ../Cargo.lock ../askama.toml ../src ../templates ../tests ../slop-tools.md ];
|
||||
fileset = unions [ ../Cargo.toml ../Cargo.lock ../build.rs ../askama.toml ../src ../templates ../tests ../slop-tools.md ];
|
||||
};
|
||||
cargoLock.lockFile = ../Cargo.lock;
|
||||
|
||||
@@ -16,6 +19,10 @@ rustPlatform.buildRustPackage {
|
||||
nativeBuildInputs = [ pkg-config ];
|
||||
buildInputs = [ openssl sqlite ];
|
||||
|
||||
env = lib.optionalAttrs (rev != null) {
|
||||
SLOP_BROKER_VERSION = "${version}+${rev}";
|
||||
};
|
||||
|
||||
postInstall = ''
|
||||
ln -s slop-broker $out/bin/slop-approve
|
||||
install -Dm644 slop-tools.md $out/share/slop-broker/slop-tools.md
|
||||
|
||||
+351
-96
@@ -1,172 +1,427 @@
|
||||
# Runs the broker through the `services.slop-broker` module, with its real service hardening, over
|
||||
# vsock loopback, against a local sshd. Build it as `checks.x86_64-linux.vm` (see `README.md`).
|
||||
#
|
||||
# - `machine` runs the broker, its builder and the requesters, and is also the deploy node `local`
|
||||
# (and `other` and `denied`), with a container, `web`.
|
||||
# - `box` is a second deploy node with a store of its own, and holds the binary cache's store.
|
||||
{ pkgs, slop-broker }:
|
||||
let
|
||||
inherit (pkgs) lib;
|
||||
|
||||
# SSH keys: the broker's own (`key`), a requester's and an approver's on other boxes
|
||||
key = pkgs.runCommand "test-key" { nativeBuildInputs = [ pkgs.openssh ]; } ''
|
||||
mkdir $out
|
||||
for k in key requester approver; do ssh-keygen -q -t ed25519 -N "" -f $out/$k; done
|
||||
'';
|
||||
publicKey = name: builtins.readFile "${key}/${name}.pub";
|
||||
# The broker's key at runtime: not a store path, as the module requires
|
||||
keyFile = "/etc/slop-broker-test/key";
|
||||
|
||||
# The builder's repository: a flake whose deploy-rs nodes are the broker's SSH targets
|
||||
# The builder's repository: a flake whose deploy-rs nodes are the broker's SSH targets, with a
|
||||
# profile it can build without nixpkgs. Two commits, `one` and `two`, differ only in the profile.
|
||||
repository = pkgs.runCommand "test-repository" { nativeBuildInputs = [ pkgs.git ]; } ''
|
||||
mkdir $out
|
||||
cat > $out/flake.nix <<'EOF'
|
||||
{
|
||||
outputs = _: {
|
||||
deploy.sshUser = "deploy";
|
||||
deploy.nodes = {
|
||||
local.hostname = "localhost";
|
||||
other.hostname = "localhost";
|
||||
denied.hostname = "localhost";
|
||||
};
|
||||
};
|
||||
}
|
||||
EOF
|
||||
install -m755 ${pkgs.pkgsStatic.busybox}/bin/busybox $out/busybox
|
||||
git -C $out init --quiet --initial-branch=master
|
||||
git -C $out add flake.nix
|
||||
git -C $out -c user.name=test -c user.email=test@example.org commit --quiet -m "Add nodes"
|
||||
|
||||
for version in one two; do
|
||||
sed "s/@version@/$version/g" ${./vm-test/flake.nix} > $out/flake.nix
|
||||
git -C $out add flake.nix busybox
|
||||
git -C $out -c user.name=test -c user.email=test@example.org commit --quiet -m "Profile $version"
|
||||
git -C $out rev-parse HEAD > $out/commit-$version
|
||||
done
|
||||
'';
|
||||
|
||||
# A deploy node: the broker logs in as `deploy`, which may use `sudo` (for activation and
|
||||
# container commands) and copy unsigned paths into the store. Nothing is substituted, since the
|
||||
# test is offline: everything is built or already in the store.
|
||||
deployNode = {
|
||||
services.openssh.enable = true;
|
||||
|
||||
users.users.deploy = {
|
||||
isNormalUser = true;
|
||||
openssh.authorizedKeys.keyFiles = [ "${key}/key.pub" ];
|
||||
};
|
||||
security.sudo.extraRules = [{
|
||||
users = [ "deploy" ];
|
||||
commands = [{ command = "ALL"; options = [ "NOPASSWD" ]; }];
|
||||
}];
|
||||
|
||||
nix.settings = {
|
||||
trusted-users = [ "deploy" ];
|
||||
substituters = lib.mkForce [ ];
|
||||
};
|
||||
};
|
||||
in
|
||||
pkgs.testers.runNixOSTest {
|
||||
name = "slop-broker";
|
||||
nodes.machine = { ... }: {
|
||||
imports = [ ./modules/nixos/broker.nix ./modules/nixos/builder.nix ];
|
||||
|
||||
config = {
|
||||
boot.kernelModules = [ "vsock_loopback" ];
|
||||
services.openssh.enable = true;
|
||||
users.users.deploy = { isNormalUser = true; openssh.authorizedKeys.keyFiles = [ "${key}/key.pub" ]; };
|
||||
users.users.reviewer.isNormalUser = true;
|
||||
users.users.agent.isNormalUser = true;
|
||||
environment.systemPackages = [ pkgs.util-linux ];
|
||||
programs.ssh.extraConfig = ''
|
||||
StrictHostKeyChecking no
|
||||
UserKnownHostsFile /dev/null
|
||||
LogLevel ERROR
|
||||
'';
|
||||
# Not a store path, as the module requires
|
||||
environment.etc."slop-broker-test/key".source = "${key}/key";
|
||||
nodes.box = { ... }: {
|
||||
imports = [ deployNode ./modules/nixos/cache.nix ];
|
||||
|
||||
services.slop-broker = {
|
||||
enable = true;
|
||||
package = slop-broker;
|
||||
approvers = [ "reviewer" ];
|
||||
|
||||
policies.agent.ops = {
|
||||
query.action = "auto";
|
||||
ssh = { action = "ask"; leases = [ "5m" ]; rules = [ { match.target = "denied"; action = "deny"; } ]; };
|
||||
};
|
||||
policies.workstation.ops.query.action = "auto";
|
||||
|
||||
requesters.agent = {
|
||||
vsockCid = 1;
|
||||
policy = "agent";
|
||||
};
|
||||
requesters.workstation = {
|
||||
sshKeys = [ (publicKey "requester") ];
|
||||
policy = "workstation";
|
||||
};
|
||||
|
||||
sshApprovers.laptop = [ (publicKey "approver") ];
|
||||
|
||||
ssh = {
|
||||
enable = true;
|
||||
keyFile = "/etc/slop-broker-test/key";
|
||||
};
|
||||
deploy.enable = true;
|
||||
};
|
||||
|
||||
# Only reads the repository, so its key is never used
|
||||
services.slop-broker-builder = {
|
||||
enable = true;
|
||||
package = slop-broker;
|
||||
repository = "/var/lib/slop-test-repository";
|
||||
keyFile = "/etc/slop-broker-test/key";
|
||||
brokerKeys = [ (publicKey "key") ];
|
||||
};
|
||||
systemd.tmpfiles.rules = [ "C /var/lib/slop-test-repository - - - - ${repository}" "Z /var/lib/slop-test-repository - slop-broker-build - - -" ];
|
||||
# The binary cache: a store of its own, owned by `cache`, which the broker's key may only use
|
||||
# through the cache's forced command
|
||||
users.users.cache = {
|
||||
isNormalUser = true;
|
||||
home = "/var/lib/slop-cache-home";
|
||||
createHome = true;
|
||||
};
|
||||
systemd.tmpfiles.rules = [ "d /var/lib/slop-cache 0755 cache users -" ];
|
||||
services.slop-broker-cache = {
|
||||
enable = true;
|
||||
user = "cache";
|
||||
store = "/var/lib/slop-cache";
|
||||
home = "/var/lib/slop-cache-home";
|
||||
brokerKeys = [ (publicKey "key") ];
|
||||
};
|
||||
};
|
||||
|
||||
nodes.machine = { ... }: {
|
||||
imports = [ deployNode ./modules/nixos/broker.nix ./modules/nixos/builder.nix ];
|
||||
|
||||
# The agent reaches the broker over vsock loopback (CID 1); `reviewer` approves
|
||||
boot.kernelModules = [ "vsock_loopback" ];
|
||||
users.users.reviewer.isNormalUser = true;
|
||||
users.users.agent.isNormalUser = true;
|
||||
virtualisation.memorySize = 2048;
|
||||
# `script`, for answering on a terminal
|
||||
environment.systemPackages = [ pkgs.util-linux ];
|
||||
|
||||
# A container for the container commands, which go through `systemd-machined` as root
|
||||
containers.web = {
|
||||
autoStart = true;
|
||||
config.system.stateVersion = lib.trivial.release;
|
||||
};
|
||||
|
||||
# The broker's SSH connections trust any host key, and say nothing about it
|
||||
programs.ssh.extraConfig = ''
|
||||
StrictHostKeyChecking no
|
||||
UserKnownHostsFile /dev/null
|
||||
LogLevel ERROR
|
||||
'';
|
||||
environment.etc."slop-broker-test/key".source = "${key}/key";
|
||||
|
||||
services.slop-broker = {
|
||||
enable = true;
|
||||
package = slop-broker;
|
||||
approvers = [ "reviewer" ];
|
||||
|
||||
# Everything runs without asking except `slop ssh`, which tests the approvals
|
||||
policies.agent.ops = {
|
||||
query.action = "auto";
|
||||
builder.action = "auto";
|
||||
deploy.action = "auto";
|
||||
build.action = "auto";
|
||||
ssh = {
|
||||
action = "ask";
|
||||
leases = [ "5m" ];
|
||||
rules = [{ match.target = "denied"; action = "deny"; }];
|
||||
};
|
||||
};
|
||||
policies.workstation.ops.query.action = "auto";
|
||||
|
||||
requesters.agent = {
|
||||
vsockCid = 1;
|
||||
policy = "agent";
|
||||
};
|
||||
requesters.workstation = {
|
||||
sshKeys = [ (publicKey "requester") ];
|
||||
policy = "workstation";
|
||||
};
|
||||
sshApprovers.laptop = [ (publicKey "approver") ];
|
||||
|
||||
ssh = {
|
||||
enable = true;
|
||||
inherit keyFile;
|
||||
};
|
||||
deploy.enable = true;
|
||||
cache = {
|
||||
enable = true;
|
||||
hostname = "box";
|
||||
user = "cache";
|
||||
inherit keyFile;
|
||||
};
|
||||
|
||||
# The web app without sign-in, which the test reaches with `curl`
|
||||
web = {
|
||||
enable = true;
|
||||
url = "http://localhost:8095";
|
||||
noSignIn = "tester";
|
||||
};
|
||||
};
|
||||
|
||||
# The builder only reads the repository, a local copy, so its key is never used
|
||||
services.slop-broker-builder = {
|
||||
enable = true;
|
||||
package = slop-broker;
|
||||
repository = "/var/lib/slop-test-repository";
|
||||
inherit keyFile;
|
||||
brokerKeys = [ (publicKey "key") ];
|
||||
};
|
||||
systemd.tmpfiles.rules = [
|
||||
"C /var/lib/slop-test-repository - - - - ${repository}"
|
||||
"Z /var/lib/slop-test-repository - slop-broker-build - - -"
|
||||
];
|
||||
};
|
||||
|
||||
testScript = ''
|
||||
import json
|
||||
import re
|
||||
|
||||
# Commands as the agent, sending requests over vsock (or `broker`)
|
||||
vsock = "SLOP_BROKER=vsock:1:6262 SLOP_LABEL='vm test'"
|
||||
|
||||
def agent(command, broker=vsock):
|
||||
return f"su agent -c \"{broker} {command}\""
|
||||
|
||||
def slop(args, broker=vsock):
|
||||
"""Runs `slop`, which must succeed; returns its stdout."""
|
||||
return machine.succeed(agent(f"slop {args}", broker))
|
||||
|
||||
def try_slop(args, broker=vsock):
|
||||
"""Runs `slop`; returns its exit status and output, stderr included."""
|
||||
return machine.execute(agent(f"slop {args}", broker) + " 2>&1")
|
||||
|
||||
def slop_in_background(command, output):
|
||||
"""Starts an agent's command that waits for an answer, writing its output to a file."""
|
||||
machine.execute(agent(command) + f" > {output} 2>&1 &")
|
||||
|
||||
# Commands as the reviewer
|
||||
def approve(args):
|
||||
return machine.succeed(f"su reviewer -c 'slop-approve {args}'")
|
||||
|
||||
def wait_for_request(summary):
|
||||
machine.wait_until_succeeds(f"su reviewer -c 'slop-approve list' | grep -q '{summary}'")
|
||||
|
||||
|
||||
start_all()
|
||||
machine.wait_for_unit("sshd.service")
|
||||
machine.wait_for_unit("slop-broker.service")
|
||||
machine.wait_for_file("/run/slop-broker/approve.sock")
|
||||
env = "SLOP_BROKER=vsock:1:6262 SLOP_LABEL='vm test'"
|
||||
|
||||
# Policy
|
||||
|
||||
# Denied by policy, without asking
|
||||
status, out = machine.execute(f"su agent -c \"{env} slop ssh denied -- true\" 2>&1")
|
||||
status, out = try_slop("ssh denied -- true")
|
||||
assert status == 125 and "denied by policy" in out, (status, out)
|
||||
|
||||
# Fixed queries run without asking
|
||||
out = machine.succeed(f"su agent -c \"{env} slop status local sshd.service\"")
|
||||
out = slop("status local sshd.service")
|
||||
assert "sshd.service" in out, out
|
||||
out = machine.succeed(f"su agent -c \"{env} slop logs local sshd.service -n 5 --since 1h\"")
|
||||
print(out)
|
||||
print(slop("logs local sshd.service -n 5 --since 1h"))
|
||||
|
||||
# Ask, approve from a terminal, and see the real ssh run
|
||||
machine.execute(f"su agent -c \"{env} slop ssh local -- 'echo hi from \\$(whoami)'\" > /tmp/out 2>&1 &")
|
||||
machine.wait_until_succeeds("su reviewer -c 'slop-approve list' | grep -q 'ssh local'")
|
||||
listing = machine.succeed("su reviewer -c 'slop-approve list'")
|
||||
# A node with several addresses is reached at the first that answers, which the requester
|
||||
# and the audit log see.
|
||||
status, out = try_slop("status moving sshd.service")
|
||||
assert status == 0 and "slop: reaching moving at 127.0.0.1" in out, (status, out)
|
||||
assert "moving at 127.0.0.1" in approve("log -n 5"), "the pick isn't in the audit log"
|
||||
|
||||
# Approvals and leases
|
||||
|
||||
# Ask, approve from a terminal, and see the real ssh run. Only approvers can answer.
|
||||
slop_in_background("slop ssh local -- 'echo hi from \\$(whoami)'", "/tmp/out")
|
||||
wait_for_request("ssh local")
|
||||
listing = approve("list")
|
||||
print(listing)
|
||||
assert "vm test" in listing
|
||||
request = listing.split()[0][:4]
|
||||
status, out = machine.execute("su agent -c 'slop-approve " + request + " once' 2>&1")
|
||||
status, out = machine.execute(f"su agent -c 'slop-approve {request} once' 2>&1")
|
||||
assert status != 0, out
|
||||
machine.succeed(f"su reviewer -c 'slop-approve {request} 5m'")
|
||||
approve(f"{request} 5m")
|
||||
machine.wait_until_succeeds("grep -q 'hi from deploy' /tmp/out")
|
||||
out = machine.succeed("cat /tmp/out")
|
||||
print(out)
|
||||
assert "Permanently added" not in out, out
|
||||
|
||||
# Covered by the lease now; stdin goes with the request
|
||||
out = machine.succeed(f"echo piped | su agent -c \"{env} slop ssh local -- cat\"")
|
||||
out = machine.succeed("echo piped | " + agent("slop ssh local -- cat"))
|
||||
assert "piped" in out, out
|
||||
out = machine.succeed(f"su agent -c \"{env} slop requests\"")
|
||||
out = slop("requests")
|
||||
assert "ssh" in out and "lease" in out, out
|
||||
|
||||
# Containers
|
||||
|
||||
# Queries run without asking, as for nodes
|
||||
machine.wait_for_unit("container@web.service")
|
||||
out = slop("status local.container-web systemd-journald.service")
|
||||
assert "systemd-journald.service" in out, out
|
||||
print(slop("failed local.container-web"))
|
||||
print(slop("logs local.container-web systemd-journald.service -n 5"))
|
||||
|
||||
# Only `container-*` profiles are containers
|
||||
status, out = try_slop("failed local.container-nope")
|
||||
assert status == 125 and "unknown container local.container-nope" in out, (status, out)
|
||||
status, out = try_slop("failed local.system")
|
||||
assert status == 125 and "only containers" in out, (status, out)
|
||||
|
||||
# `slop ssh` asks again, since the lease is for the host, and runs in the container as root,
|
||||
# with stdin and the command's exit status
|
||||
machine.execute(
|
||||
"echo from stdin | "
|
||||
+ agent("slop ssh local.container-web -- 'cat; echo in \\$(hostname) as \\$(whoami); exit 3'; echo exit \\$?")
|
||||
+ " > /tmp/out5 2>&1 &"
|
||||
)
|
||||
wait_for_request("ssh local.container-web")
|
||||
approve("once")
|
||||
machine.wait_until_succeeds("grep -q 'exit 3' /tmp/out5")
|
||||
out = machine.succeed("cat /tmp/out5")
|
||||
print(out)
|
||||
assert "from stdin" in out and "in web as root" in out, out
|
||||
|
||||
# Errors
|
||||
|
||||
# Unknown nodes are named plainly; usage errors exit 125 like other refusals
|
||||
status, out = machine.execute(f"su agent -c \"{env} slop ssh nope -- true\" 2>&1")
|
||||
status, out = try_slop("ssh nope -- true")
|
||||
assert status == 125 and "unknown node nope;" in out, (status, out)
|
||||
status, out = machine.execute(f"su agent -c \"{env} slop ssh\" 2>&1")
|
||||
status, out = try_slop("ssh")
|
||||
assert status == 125, (status, out)
|
||||
|
||||
# Interactive answering on a terminal
|
||||
machine.execute(f"su agent -c \"{env} slop ssh other -- echo interactive\" > /tmp/out2 2>&1 &")
|
||||
machine.wait_until_succeeds("su reviewer -c 'slop-approve list' | grep -q 'ssh other'")
|
||||
# Answering
|
||||
|
||||
# Interactively on a terminal, where a wrong answer is asked again
|
||||
slop_in_background("slop ssh other -- echo interactive", "/tmp/out2")
|
||||
wait_for_request("ssh other")
|
||||
out = machine.succeed("(sleep 1; echo x; sleep 1; echo o) | timeout 5 su reviewer -c \"script -qec slop-approve /dev/null\" || true")
|
||||
print(out)
|
||||
assert "Not an option" in out and "Recorded: once" in out, out
|
||||
machine.wait_until_succeeds("grep -q interactive /tmp/out2")
|
||||
|
||||
# The only pending request can be answered without its ID
|
||||
machine.execute(f"su agent -c \"{env} slop ssh other -- true; echo \\$?\" > /tmp/out3 2>&1 &")
|
||||
machine.wait_until_succeeds("su reviewer -c 'slop-approve list' | grep -q 'ssh other'")
|
||||
machine.succeed("su reviewer -c 'slop-approve deny'")
|
||||
slop_in_background("slop ssh other -- true; echo \\$?", "/tmp/out3")
|
||||
wait_for_request("ssh other")
|
||||
approve("deny")
|
||||
machine.wait_until_succeeds("grep -q 'denied by approver' /tmp/out3")
|
||||
machine.wait_until_succeeds("grep -qx 125 /tmp/out3", timeout=30)
|
||||
|
||||
# Over SSH: each key names its owner and role
|
||||
# Over SSH
|
||||
|
||||
# Each key names its owner and role: the agent's key here is the workstation's, which may
|
||||
# only query, and can't approve
|
||||
for user, k in [("agent", "requester"), ("reviewer", "approver")]:
|
||||
machine.succeed(f"install -D -m600 -o {user} ${key}/{k} /home/{user}/.ssh/id_ed25519")
|
||||
remote = "SLOP_BROKER=ssh:slop@localhost"
|
||||
out = machine.succeed(f"su agent -c \"{remote} slop status local sshd.service\"")
|
||||
out = slop("status local sshd.service", broker=remote)
|
||||
assert "sshd.service" in out, out
|
||||
status, out = machine.execute(f"su agent -c \"{remote} slop ssh local -- true\" 2>&1")
|
||||
status, out = try_slop("ssh local -- true", broker=remote)
|
||||
assert status == 125 and "denied by policy" in out, (status, out)
|
||||
status, out = machine.execute("su agent -c 'SLOP_APPROVE=ssh:slop@localhost slop-approve list' 2>&1")
|
||||
assert status != 0 and "for sending requests" in out, (status, out)
|
||||
|
||||
machine.execute(f"su agent -c \"{env} slop ssh other -- echo remote approval\" > /tmp/out4 2>&1 &")
|
||||
machine.wait_until_succeeds("su reviewer -c 'slop-approve list' | grep -q 'ssh other'")
|
||||
# The approver's key answers as `laptop`
|
||||
slop_in_background("slop ssh other -- echo remote approval", "/tmp/out4")
|
||||
wait_for_request("ssh other")
|
||||
machine.succeed("su reviewer -c 'SLOP_APPROVE=ssh:slop@localhost slop-approve once'")
|
||||
machine.wait_until_succeeds("grep -q 'remote approval' /tmp/out4")
|
||||
|
||||
audit = machine.succeed("su reviewer -c 'slop-approve log'")
|
||||
# Deploys
|
||||
|
||||
# A builder with a store of its own serves it to the broker's key as `nix-daemon --stdio`
|
||||
machine.succeed("install -m600 ${keyFile} /root/builder-key")
|
||||
system = machine.succeed("readlink -f /run/current-system").strip()
|
||||
store = "ssh-ng://slop-broker-build@localhost:22?ssh-key=/root/builder-key"
|
||||
out = machine.succeed(f"nix --extra-experimental-features nix-command path-info --store '{store}' {system}")
|
||||
assert out.strip() == system, out
|
||||
|
||||
# Deploys build, copy, compare and activate, on both nodes at once, though their profiles are
|
||||
# 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()
|
||||
two = machine.succeed(f"cat {repository}/commit-two").strip()
|
||||
|
||||
status, out = try_slop(f"deploy box.system local.system --commit {one}")
|
||||
print(out)
|
||||
assert status == 0, (status, out)
|
||||
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: reaching box at box",
|
||||
"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")
|
||||
profile = box.succeed("ls -d /nix/store/*-test-profile-one").strip()
|
||||
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, 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
|
||||
|
||||
# Builds go to the cache's store on `box`, closure and all, with a GC root; the output path
|
||||
# is the last line
|
||||
status, out = try_slop(f"build packages.x86_64-linux.profile --commit {two}")
|
||||
print(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}")
|
||||
assert len(out.split()) == 2, out
|
||||
box.succeed(f"test -L /var/lib/slop-cache/nix/var/nix/gcroots/slop-broker/{path.removeprefix('/nix/store/')}")
|
||||
|
||||
# The audit log
|
||||
|
||||
# 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 and "activated box in" in audit, audit
|
||||
|
||||
# The web app, without sign-in: everyone who reaches it approves as `tester`
|
||||
|
||||
app = "http://localhost:8095"
|
||||
def page(path):
|
||||
return machine.succeed(f"curl -sf -c /tmp/cookies -b /tmp/cookies {app}{path}")
|
||||
|
||||
def found(pattern, text):
|
||||
"""The first group of `pattern` in `text`, which must match."""
|
||||
match = re.search(pattern, text)
|
||||
assert match, (pattern, text)
|
||||
return match.group(1)
|
||||
|
||||
machine.wait_for_open_port(8095)
|
||||
out = page("/")
|
||||
assert "No sign-in" in out and "tester" in out and "Sign out" not in out, out
|
||||
|
||||
# A finished deploy's page keeps how each phase ended
|
||||
records = [json.loads(line) for line in approve("log -n 200 --json").splitlines()]
|
||||
deploy = next(
|
||||
r["id"] for r in records
|
||||
if r["event"] == "request" and r["summary"].startswith("deploy box.system, local.system ")
|
||||
)
|
||||
out = page(f"/requests/{deploy}")
|
||||
for line in ["evaluated in", "built: 1 derivation in", "copied to box: 2 paths (", "activated box in"]:
|
||||
assert line in out, (line, out)
|
||||
|
||||
# The main page's event stream starts with its regions
|
||||
status, out = machine.execute(f"curl -sN --max-time 3 -b /tmp/cookies {app}/events")
|
||||
assert "event: morph" in out and 'id="pending"' in out and 'id="running"' in out, out
|
||||
|
||||
# Answering a request from its page, which needs the session's token
|
||||
slop_in_background("slop ssh other -- echo answered on the web", "/tmp/out5")
|
||||
wait_for_request("ssh other")
|
||||
request = found(r'/requests/([0-9a-f]{16})', page("/"))
|
||||
csrf = found(r'name="csrf" value="([0-9a-f]+)"', page(f"/requests/{request}"))
|
||||
answer = f"curl -sf -o /dev/null -b /tmp/cookies -H 'Origin: {app}' -d decision=once {app}/requests/{request}"
|
||||
machine.fail(answer + " -d csrf=wrong")
|
||||
machine.succeed(answer + f" -d csrf={csrf}")
|
||||
machine.wait_until_succeeds("grep -q 'answered on the web' /tmp/out5")
|
||||
assert "answered once by tester (web, no sign-in)" in approve("log -n 5"), approve("log -n 5")
|
||||
'';
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
# The VM test's repository, committed once for each version of its profile (`@version@`).
|
||||
{
|
||||
outputs = _:
|
||||
let
|
||||
# A stand-in for deploy-rs's activation wrapper, built with only a static busybox, whose
|
||||
# `activate-rs` leaves a mark. It refers to busybox, so its closure is two paths.
|
||||
profile = derivation {
|
||||
name = "test-profile-@version@";
|
||||
system = "x86_64-linux";
|
||||
builder = ./busybox;
|
||||
args = [
|
||||
"sh"
|
||||
"-c"
|
||||
''
|
||||
b=${./busybox}
|
||||
echo "build line @version@"
|
||||
$b mkdir $out
|
||||
printf '#!/bin/sh\n# %s\necho activating @version@\ntouch /tmp/slop-activated-@version@\n' $b > $out/activate-rs
|
||||
$b chmod +x $out/activate-rs
|
||||
''
|
||||
];
|
||||
};
|
||||
# Its own profile path, so comparing doesn't take in the box's own system
|
||||
system = { path = profile; profilePath = "/nix/var/nix/profiles/slop-test"; };
|
||||
in
|
||||
{
|
||||
# For `slop build`
|
||||
packages.x86_64-linux.profile = profile;
|
||||
|
||||
deploy.sshUser = "deploy";
|
||||
deploy.nodes = {
|
||||
local = {
|
||||
hostname = "localhost";
|
||||
profiles = {
|
||||
inherit system;
|
||||
# Only its name is used: it says which containers there are
|
||||
container-web = { };
|
||||
};
|
||||
};
|
||||
# Another box, with a store of its own to copy to, reached at the last of its addresses
|
||||
box = { hostname = "box"; sshHostnames = [ "nowhere.invalid" "box" ]; profiles = { inherit system; }; };
|
||||
other.hostname = "localhost";
|
||||
denied.hostname = "localhost";
|
||||
# A box that moves between networks: its first address doesn't resolve, its second answers
|
||||
moving = { hostname = "localhost"; sshHostnames = [ "nowhere.invalid" "127.0.0.1" "localhost" ]; };
|
||||
};
|
||||
};
|
||||
}
|
||||
+10
-1
@@ -34,6 +34,10 @@ applies a policy, and asks a human to approve most requests.
|
||||
|
||||
- Prefer `status`, `logs` and `failed` to `slop ssh` for looking at a box: they don't wait for a
|
||||
human.
|
||||
- Every box command (`status`, `logs`, `failed`, `ssh`) also takes a container instead of a node,
|
||||
as `<node>.container-<name>` (the name `slop deploy` takes, such as `host.container-web`). It
|
||||
runs in the container as root, and `slop ssh` runs the command with `/bin/sh -l`. A lease for
|
||||
the node doesn't cover its containers.
|
||||
- Every box command also takes `--host <user>@<host> [-p <port>]` instead of a node, for hosts
|
||||
outside the deploy nodes.
|
||||
- `--json` prints structured results (such as `slop requests`) as JSON.
|
||||
@@ -55,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`.
|
||||
|
||||
|
||||
+167
-11
@@ -1,5 +1,6 @@
|
||||
//! Approvers' connections and the `slop-approve` client, using the same framing and encoding as
|
||||
//! requesters: any number of [`ApproveRequest`]s, each answered with an [`ApproveResponse`].
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -7,13 +8,16 @@ use anyhow::{Result, anyhow, bail};
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio::net::UnixListener;
|
||||
|
||||
use crate::audit::{Event, short};
|
||||
use crate::audit::{Event, Record, short};
|
||||
use crate::config::user_name;
|
||||
use crate::ops::printable;
|
||||
use crate::proto::{ApproveRequest, ApproveResponse, MAX_LOG_RECORDS, Transport, receive, send, transport};
|
||||
use crate::progress::{Phases, Progress, elapsed};
|
||||
use crate::proto::{ApproveRequest, ApproveResponse, MAX_LOG_RECORDS, RunInfo, Transport, receive, send, transport};
|
||||
use crate::queue::{Decision, PendingInfo};
|
||||
use crate::remote::{Role, Stream, connect};
|
||||
use crate::runs::Run;
|
||||
use crate::server::Broker;
|
||||
use crate::terminal::Board;
|
||||
|
||||
pub const DEFAULT_ADDRESS: &str = "unix:/run/slop-broker/approve.sock";
|
||||
|
||||
@@ -66,6 +70,7 @@ fn answer(broker: &Broker, approver: &str, request: ApproveRequest) -> Result<Ap
|
||||
Ok(ApproveResponse::Recorded)
|
||||
}
|
||||
ApproveRequest::Log { count } => Ok(ApproveResponse::Log(broker.audit.tail(count.min(MAX_LOG_RECORDS))?)),
|
||||
ApproveRequest::Running => Ok(ApproveResponse::Running(broker.runs.list().iter().map(Run::info).collect())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,6 +111,20 @@ impl Client {
|
||||
_ => bail!("unexpected response from the broker"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn log(&mut self, count: usize) -> Result<Vec<Record>> {
|
||||
match self.call(ApproveRequest::Log { count }).await? {
|
||||
ApproveResponse::Log(records) => Ok(records),
|
||||
_ => bail!("unexpected response from the broker"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn running(&mut self) -> Result<Vec<RunInfo>> {
|
||||
match self.call(ApproveRequest::Running).await? {
|
||||
ApproveResponse::Running(runs) => Ok(runs),
|
||||
_ => bail!("unexpected response from the broker"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn format(entry: &PendingInfo, full: bool) -> String {
|
||||
@@ -146,9 +165,10 @@ fn resolve<'a>(entries: &'a [PendingInfo], prefix: &str) -> Result<&'a PendingIn
|
||||
}
|
||||
}
|
||||
|
||||
const USAGE: &str = "usage: slop-approve answer requests one by one, waiting for new ones
|
||||
const USAGE: &str = "usage: slop-approve answer requests one by one, waiting for new ones and
|
||||
showing the progress of running ones meanwhile
|
||||
(lists them instead when not on a terminal or piped)
|
||||
slop-approve list list pending requests
|
||||
slop-approve list list pending and running requests
|
||||
slop-approve show <id> show a request in full
|
||||
slop-approve <id> <decision> answer a request: once, deny or an offered lease (e.g. 5m)
|
||||
slop-approve <decision> answer the only pending request
|
||||
@@ -205,6 +225,17 @@ async fn print_list(client: &mut Client) -> Result<()> {
|
||||
print!("{}", printable(&format(&entry, false)));
|
||||
println!(" Answer: slop-approve {} {}", short(&entry.id), offers(&entry));
|
||||
}
|
||||
|
||||
let runs = client.running().await?;
|
||||
if !runs.is_empty() {
|
||||
println!("\nRunning:");
|
||||
}
|
||||
for run in runs {
|
||||
let status = run.phases.into_iter().collect::<Phases>().status();
|
||||
let text =
|
||||
format!("{} {} {} ({})\n {status}\n", run.id, run.requester, run.summary, elapsed(run.elapsed));
|
||||
print!("{}", printable(&text));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -225,11 +256,7 @@ async fn print_log(client: &mut Client, options: &[String]) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
let ApproveResponse::Log(records) = client.call(ApproveRequest::Log { count }).await? else {
|
||||
bail!("unexpected response from the broker");
|
||||
};
|
||||
|
||||
for record in records {
|
||||
for record in client.log(count).await? {
|
||||
if json {
|
||||
println!("{}", serde_json::to_string(&record)?);
|
||||
} else {
|
||||
@@ -245,26 +272,40 @@ async fn decide(client: &mut Client, id: &str, decision: Decision) -> Result<()>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Shows pending requests one at a time and asks for an answer, then waits for more.
|
||||
/// Shows pending requests one at a time and asks for an answer, then waits for more, showing
|
||||
/// the progress of running requests meanwhile.
|
||||
async fn interactive(client: &mut Client) -> Result<()> {
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
let mut input = BufReader::new(tokio::io::stdin()).lines();
|
||||
let mut skipped = std::collections::HashSet::new();
|
||||
let mut waiting = false;
|
||||
let mut board = Board::new();
|
||||
let mut watch = Watch::default();
|
||||
|
||||
loop {
|
||||
let entries = client.list().await?;
|
||||
skipped.retain(|id| entries.iter().any(|e| &e.id == id));
|
||||
let Some(entry) = entries.iter().find(|e| !skipped.contains(&e.id)) else {
|
||||
board.resume();
|
||||
if !waiting {
|
||||
println!("Waiting for requests (Ctrl-C to quit)…");
|
||||
board.say("Waiting for requests (Ctrl-C to quit)…");
|
||||
waiting = true;
|
||||
}
|
||||
let ended = watch.show(&mut board, &client.running().await?);
|
||||
if !ended.is_empty() {
|
||||
// How they ended, if the log still has it
|
||||
let records = client.log(MAX_LOG_RECORDS).await.unwrap_or_default();
|
||||
for id in ended {
|
||||
watch.end(&mut board, &id, &records);
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
continue;
|
||||
};
|
||||
|
||||
// The request and its prompt take the terminal from the bars.
|
||||
waiting = false;
|
||||
board.pause();
|
||||
|
||||
// Bell, so a new request is noticed in another window.
|
||||
print!("\x07\n{}", printable(&format(entry, true)));
|
||||
@@ -307,6 +348,63 @@ async fn interactive(client: &mut Client) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Running requests' progress on a [`Board`], from what changed since the last poll.
|
||||
#[derive(Default)]
|
||||
struct Watch {
|
||||
/// Each run's phases as last shown, by ID.
|
||||
shown: HashMap<String, Vec<Progress>>,
|
||||
}
|
||||
|
||||
impl Watch {
|
||||
/// Shows what changed in `runs`, and returns the IDs of those that ended since, for
|
||||
/// [`Watch::end`].
|
||||
fn show(&mut self, board: &mut Board, runs: &[RunInfo]) -> Vec<String> {
|
||||
for run in runs {
|
||||
let id = short(&run.id);
|
||||
let shown = self.shown.entry(run.id.clone()).or_insert_with(|| {
|
||||
board.say(&printable(&format!("{id}: {} for {}", run.summary, run.requester)));
|
||||
Vec::new()
|
||||
});
|
||||
for progress in run.phases.iter().filter(|p| !shown.contains(p)) {
|
||||
board.update_run(Some(id), progress);
|
||||
}
|
||||
*shown = run.phases.clone();
|
||||
}
|
||||
|
||||
self.shown.keys().filter(|id| !runs.iter().any(|r| r.id == **id)).cloned().collect()
|
||||
}
|
||||
|
||||
/// Shows how a run ended, from its record in `records`: the phases that ended since the
|
||||
/// last poll, and the outcome.
|
||||
fn end(&mut self, board: &mut Board, id: &str, records: &[Record]) {
|
||||
let shown = self.shown.remove(id).unwrap_or_default();
|
||||
let run = short(id);
|
||||
let ending = records.iter().rev().find_map(|record| ending(&record.event, id));
|
||||
|
||||
if let Some((_, phases)) = &ending {
|
||||
for progress in phases.iter().filter(|p| !shown.contains(p)) {
|
||||
board.update_run(Some(run), progress);
|
||||
}
|
||||
}
|
||||
board.end_run(run);
|
||||
board.say(&printable(&format!("{run}: {}", ending.map_or("ended".into(), |(outcome, _)| outcome))));
|
||||
}
|
||||
}
|
||||
|
||||
/// How request `id` ended, with its phases, if `event` is its end.
|
||||
fn ending<'a>(event: &'a Event, id: &str) -> Option<(String, &'a [Progress])> {
|
||||
match event {
|
||||
Event::Finished { id: i, exit, phases, .. } if i == id => {
|
||||
Some((format!("finished with exit status {exit}"), phases))
|
||||
}
|
||||
Event::Failed { id: i, error, phases } if i == id => Some((format!("failed: {error}"), phases)),
|
||||
Event::Denied { id: i, reason } if i == id => Some((reason.clone(), &[])),
|
||||
Event::Expired { id: i } if i == id => Some(("expired without an answer".into(), &[])),
|
||||
Event::Disconnected { id: i } if i == id => Some(("cancelled: the requester disconnected".into(), &[])),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -326,6 +424,64 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shows_what_changed_in_running_requests() {
|
||||
use crate::progress::{Counts, Phase, State};
|
||||
use crate::terminal::testing::{on_screen, screen};
|
||||
|
||||
let (mut board, term) = on_screen();
|
||||
let mut watch = Watch::default();
|
||||
let phase = |phase, state| Progress { phase, state, elapsed: 1, counts: Counts::default() };
|
||||
let run = |phases| RunInfo {
|
||||
id: "a1b2c3d4".into(),
|
||||
requester: "agent".into(),
|
||||
summary: "deploy river".into(),
|
||||
elapsed: 5,
|
||||
phases,
|
||||
};
|
||||
|
||||
// Polls that find nothing new add nothing.
|
||||
let built = phase(Phase::Build, State::Done);
|
||||
let copying = phase(Phase::Copy("river".into()), State::Running);
|
||||
for _ in 0..3 {
|
||||
watch.show(&mut board, &[run(vec![built.clone(), copying.clone()])]);
|
||||
}
|
||||
let running = [
|
||||
"a1b2c3: deploy river for agent",
|
||||
"a1b2c3: built in 1s",
|
||||
"a1b2c3 river ▕ ▏ copying · 1s",
|
||||
];
|
||||
assert_eq!(screen(&term, |l| l == running), running);
|
||||
|
||||
// Ended, with the rest from the audit log, even if the last polls missed it
|
||||
assert_eq!(watch.show(&mut board, &[]), ["a1b2c3d4"]);
|
||||
let activated = phase(Phase::Activate("river".into()), State::Done);
|
||||
let finished = |id: &str| Record {
|
||||
time: String::new(),
|
||||
event: Event::Finished {
|
||||
id: id.into(),
|
||||
exit: 0,
|
||||
seconds: 62.5,
|
||||
phases: vec![built.clone(), activated.clone()],
|
||||
},
|
||||
};
|
||||
watch.end(&mut board, "a1b2c3d4", &[finished("a1b2c3d4"), finished("other")]);
|
||||
let ended = [
|
||||
"a1b2c3: deploy river for agent",
|
||||
"a1b2c3: built in 1s",
|
||||
"a1b2c3: activated river in 1s",
|
||||
"a1b2c3: finished with exit status 0",
|
||||
];
|
||||
assert_eq!(screen(&term, |l| l == ended), ended);
|
||||
assert!(watch.shown.is_empty());
|
||||
|
||||
// Without its record, it only ended.
|
||||
watch.show(&mut board, &[run(vec![])]);
|
||||
watch.show(&mut board, &[]);
|
||||
watch.end(&mut board, "a1b2c3d4", &[]);
|
||||
assert_eq!(screen(&term, |l| l.last().is_some_and(|l| l == "a1b2c3: ended")).last().unwrap(), "a1b2c3: ended");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_unique_prefixes() {
|
||||
let entries = [entry("abc123"), entry("abd456")];
|
||||
|
||||
+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"));
|
||||
}
|
||||
|
||||
|
||||
+15
-6
@@ -6,13 +6,13 @@ use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use nix::sys::signal::{SigHandler, Signal, signal};
|
||||
|
||||
use slop_broker::config::{Config, credential, group_id, user_id};
|
||||
use slop_broker::config::{Config, SignIn, credential, group_id, user_id};
|
||||
use slop_broker::remote::{self, Role};
|
||||
use slop_broker::server::{self, Broker};
|
||||
use slop_broker::{approve, web};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(about = "Approval broker for coding agents")]
|
||||
#[command(version = slop_broker::VERSION, about = "Approval broker for coding agents")]
|
||||
enum Command {
|
||||
/// Run the broker.
|
||||
Serve {
|
||||
@@ -85,10 +85,19 @@ async fn serve(path: &Path) -> Result<()> {
|
||||
|
||||
let web = match &config.web {
|
||||
Some(settings) => {
|
||||
let secret = std::fs::read_to_string(credential(&settings.client_secret))
|
||||
.context("reading the OIDC client secret")?;
|
||||
let secret = secret.trim().to_owned();
|
||||
anyhow::ensure!(!secret.is_empty(), "the OIDC client secret is empty");
|
||||
let secret = match &settings.sign_in {
|
||||
SignIn::Oidc(oidc) => {
|
||||
let secret = std::fs::read_to_string(credential(&oidc.client_secret))
|
||||
.context("reading the OIDC client secret")?;
|
||||
let secret = secret.trim().to_owned();
|
||||
anyhow::ensure!(!secret.is_empty(), "the OIDC client secret is empty");
|
||||
Some(secret)
|
||||
}
|
||||
SignIn::None { approver } => {
|
||||
eprintln!("<4>the web app has no sign-in: everyone who reaches it approves as {approver}");
|
||||
None
|
||||
}
|
||||
};
|
||||
Some((settings.clone(), secret))
|
||||
}
|
||||
None => None,
|
||||
|
||||
+44
-18
@@ -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,
|
||||
@@ -27,6 +28,8 @@ const GUIDE: &str = include_str!("../../slop-tools.md");
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
name = "slop",
|
||||
version = slop_broker::VERSION,
|
||||
about = "Ask the slop broker to run privileged operations",
|
||||
after_help = "Requests wait for an approver for as long as the broker allows (it says how long);\n\
|
||||
don't retry them in a loop.\n\
|
||||
@@ -47,7 +50,7 @@ struct Cli {
|
||||
|
||||
#[derive(Args)]
|
||||
struct Target {
|
||||
/// Deploy node, or user@host with --host.
|
||||
/// Deploy node, a container on one (node.container-<name>), or user@host with --host.
|
||||
target: String,
|
||||
/// Treat TARGET as user@host instead of a deploy node.
|
||||
#[arg(long)]
|
||||
@@ -63,6 +66,12 @@ impl Target {
|
||||
if self.port.is_some() {
|
||||
bail!("--port needs --host; deploy nodes use their configured port");
|
||||
}
|
||||
if let Some((node, profile)) = self.target.split_once('.') {
|
||||
let name = profile.strip_prefix("container-").with_context(|| {
|
||||
format!("{}: only containers can be named after a node (node.container-<name>)", self.target)
|
||||
})?;
|
||||
return Ok(Destination::Container { node: parse(node)?, name: parse(name)? });
|
||||
}
|
||||
return Ok(Destination::Node(parse::<NodeName>(&self.target)?));
|
||||
}
|
||||
|
||||
@@ -121,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 {
|
||||
@@ -130,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 {
|
||||
@@ -367,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!(),
|
||||
})
|
||||
@@ -471,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.
|
||||
|
||||
+167
-35
@@ -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};
|
||||
|
||||
@@ -79,6 +80,13 @@ pub struct Node {
|
||||
/// Only the node's own: the flake-wide ones usually name the operator's key.
|
||||
pub ssh_opts: Vec<String>,
|
||||
pub sudo: Option<String>,
|
||||
/// Its profiles' names, such as `system` and `container-<name>`.
|
||||
#[serde(default)]
|
||||
pub profiles: Vec<String>,
|
||||
/// Addresses to try in order instead of `hostname`, for a box that moves between networks:
|
||||
/// an extension to deploy-rs's node settings, which deploy-rs ignores.
|
||||
#[serde(default)]
|
||||
pub ssh_hostnames: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
@@ -133,6 +141,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)]
|
||||
@@ -203,10 +225,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,
|
||||
@@ -214,9 +237,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`.
|
||||
@@ -226,7 +253,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`.
|
||||
@@ -237,7 +264,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>(
|
||||
@@ -245,6 +272,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"]);
|
||||
@@ -265,10 +293,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"),
|
||||
};
|
||||
@@ -276,21 +322,39 @@ 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
|
||||
|
||||
/// The forced command: one build per connection, one at a time.
|
||||
/// The forced command: one build per connection, one at a time. A broker whose builder has a
|
||||
/// store of its own also reads built paths from it, as `nix-daemon --stdio` (`ssh-ng`).
|
||||
pub async fn worker(config: &Path) -> Result<()> {
|
||||
let text = std::fs::read_to_string(config).with_context(|| format!("reading {}", config.display()))?;
|
||||
let config: BuilderConfig = toml::from_str(&text)?;
|
||||
|
||||
if std::env::var("SSH_ORIGINAL_COMMAND").is_ok_and(|c| c == "nix-daemon --stdio") {
|
||||
use std::os::unix::process::CommandExt;
|
||||
let daemon = config.path.iter().map(|d| d.join("nix-daemon")).find(|p| p.exists());
|
||||
let daemon = daemon.context("no nix-daemon in the builder's path")?;
|
||||
return Err(std::process::Command::new(daemon).arg("--stdio").exec()).context("running nix-daemon");
|
||||
}
|
||||
|
||||
let mut stdin = FramedRead::new(tokio::io::stdin(), codec());
|
||||
let request: BuilderRequest = decode(&stdin.next().await.context("no request")??)?;
|
||||
// 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 {
|
||||
@@ -299,12 +363,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)
|
||||
@@ -457,6 +522,10 @@ async fn fetch_all(config: &BuilderConfig) -> Result<()> {
|
||||
]))
|
||||
.await
|
||||
.context("fetching")?;
|
||||
|
||||
// Nix reads HEAD for a commit's flake; the mirror only has remote branches.
|
||||
let branch = format!("refs/remotes/origin/{}", config.branch);
|
||||
output(git(config, &repository).args(["symbolic-ref", "HEAD", &branch])).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -594,7 +663,8 @@ async fn rules(config: &BuilderConfig, commit: &CommitId, rules: &RulesPath) ->
|
||||
async fn branch_nodes(config: &BuilderConfig) -> Result<Nodes> {
|
||||
let commit = branch_tip(config).await?;
|
||||
let cache = config.directory.join("deploy-nodes");
|
||||
let file = cache.join(format!("{commit}.json"));
|
||||
// Named for what's evaluated, so a broker reading more evaluates again.
|
||||
let file = cache.join(format!("{commit}.hostnames.json"));
|
||||
if let Ok(text) = std::fs::read_to_string(&file) {
|
||||
return Ok(Nodes { commit, nodes: serde_json::from_str(&text)? });
|
||||
}
|
||||
@@ -606,6 +676,8 @@ async fn branch_nodes(config: &BuilderConfig) -> Result<Nodes> {
|
||||
sshUser = n.sshUser or d.sshUser or null; \
|
||||
sshOpts = n.sshOpts or [ ]; \
|
||||
sudo = n.sudo or d.sudo or null; \
|
||||
profiles = builtins.attrNames (n.profiles or { }); \
|
||||
sshHostnames = n.sshHostnames or [ ]; \
|
||||
}) d.nodes";
|
||||
let evaluated = output(
|
||||
command(config, "nix")
|
||||
@@ -625,7 +697,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);
|
||||
|
||||
@@ -659,36 +735,59 @@ 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 {
|
||||
#[serde(rename = "drvPath")]
|
||||
drv_path: String,
|
||||
outputs: BTreeMap<String, String>,
|
||||
}
|
||||
let built: Vec<Built> = serde_json::from_slice(&built.stdout).context("reading nix build's result")?;
|
||||
ensure!(
|
||||
built.len() == installables.len(),
|
||||
"nix build returned {} results for {} installables",
|
||||
built.len(),
|
||||
installables.len()
|
||||
);
|
||||
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.
|
||||
if built.len() != installables.len() {
|
||||
let mut matched = Vec::new();
|
||||
for installable in &installables {
|
||||
let drv_path = output(
|
||||
command(config, "nix").args(["eval", "--raw"]).args(NIX_OPTIONS).arg(format!("{installable}.drvPath")),
|
||||
)
|
||||
.await
|
||||
.with_context(|| format!("finding the derivation of {installable}"))?;
|
||||
let result = built.iter().find(|b| b.drv_path == drv_path.trim());
|
||||
let result = result.with_context(|| format!("nix build returned nothing for {installable}"))?;
|
||||
matched.push(Built { drv_path: result.drv_path.clone(), outputs: result.outputs.clone() });
|
||||
}
|
||||
built = matched;
|
||||
}
|
||||
let (built_profiles, built_attrs) = built.split_at(profiles.len());
|
||||
for (profile, built) in profiles.iter_mut().zip(built_profiles) {
|
||||
profile.path = built.outputs.get("out").context("no out output")?.clone();
|
||||
@@ -705,6 +804,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::*;
|
||||
|
||||
+159
-6
@@ -85,13 +85,32 @@ fn default_rules() -> crate::types::RulesPath {
|
||||
/// The approvals web app (see [`crate::web`]): approvers sign in through an OpenID Connect
|
||||
/// provider, and get Web Push notifications.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
#[serde(try_from = "RawWebConfig")]
|
||||
pub struct WebConfig {
|
||||
/// Address to listen on, like `[::]:8095`; only the reverse proxy should reach it.
|
||||
pub listen: std::net::SocketAddr,
|
||||
/// Public URL of the app, like `https://approve.example.org`.
|
||||
pub url: String,
|
||||
pub sign_in: SignIn,
|
||||
/// How long a session lasts without being used.
|
||||
pub session: u64,
|
||||
/// Where sessions, push subscriptions and the push signing key are kept.
|
||||
pub state_dir: PathBuf,
|
||||
}
|
||||
|
||||
/// How approvers sign in to the web app.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum SignIn {
|
||||
Oidc(OidcConfig),
|
||||
/// Not at all: everyone who reaches the app is `approver`, for the demo and tests. Only on a
|
||||
/// loopback address, and it can't approve requests that need a passkey.
|
||||
None {
|
||||
approver: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct OidcConfig {
|
||||
/// OpenID Connect issuer.
|
||||
pub issuer: String,
|
||||
pub client_id: String,
|
||||
@@ -99,12 +118,55 @@ pub struct WebConfig {
|
||||
pub client_secret: PathBuf,
|
||||
/// Only members of this group (the ID token's `groups` claim) may sign in.
|
||||
pub group: String,
|
||||
}
|
||||
|
||||
/// How long a session lasts without being used.
|
||||
/// `[web]` as written: the OIDC settings, or `[web.no_sign_in]`.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct RawWebConfig {
|
||||
listen: std::net::SocketAddr,
|
||||
url: String,
|
||||
issuer: Option<String>,
|
||||
client_id: Option<String>,
|
||||
client_secret: Option<PathBuf>,
|
||||
group: Option<String>,
|
||||
no_sign_in: Option<NoSignIn>,
|
||||
#[serde(default = "default_session", deserialize_with = "duration")]
|
||||
pub session: u64,
|
||||
/// Where sessions, push subscriptions and the push signing key are kept.
|
||||
pub state_dir: PathBuf,
|
||||
session: u64,
|
||||
state_dir: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct NoSignIn {
|
||||
approver: String,
|
||||
}
|
||||
|
||||
impl TryFrom<RawWebConfig> for WebConfig {
|
||||
type Error = String;
|
||||
|
||||
fn try_from(raw: RawWebConfig) -> Result<WebConfig, String> {
|
||||
let sign_in = match (raw.no_sign_in, raw.issuer, raw.client_id, raw.client_secret, raw.group) {
|
||||
(None, Some(issuer), Some(client_id), Some(client_secret), Some(group)) => {
|
||||
SignIn::Oidc(OidcConfig { issuer, client_id, client_secret, group })
|
||||
}
|
||||
(Some(NoSignIn { approver }), None, None, None, None) => {
|
||||
if !raw.listen.ip().is_loopback() {
|
||||
return Err(format!(
|
||||
"the web app only goes without sign-in on a loopback address, not {}",
|
||||
raw.listen
|
||||
));
|
||||
}
|
||||
if approver.trim().is_empty() {
|
||||
return Err("no_sign_in needs the name of its approver".into());
|
||||
}
|
||||
SignIn::None { approver }
|
||||
}
|
||||
(None, ..) => return Err("the web app needs issuer, client_id, client_secret and group".into()),
|
||||
(Some(_), ..) => return Err("no_sign_in can't have issuer, client_id, client_secret or group".into()),
|
||||
};
|
||||
Ok(WebConfig { listen: raw.listen, url: raw.url, sign_in, session: raw.session, state_dir: raw.state_dir })
|
||||
}
|
||||
}
|
||||
|
||||
fn default_session() -> u64 {
|
||||
@@ -124,6 +186,32 @@ pub struct DeployConfig {
|
||||
pub cache: PathBuf,
|
||||
}
|
||||
|
||||
impl DeployConfig {
|
||||
/// The builder's store, which built paths are copied from, as a `nix` store URL reached with
|
||||
/// the broker's `key`; the builder's forced command serves it. That works whether the builder
|
||||
/// is on this box (the same store) or another. The port is always given: it comes after
|
||||
/// `NIX_SSHOPTS`, so a node's `-p` can't send the builder's connection elsewhere when one copy
|
||||
/// uses both.
|
||||
pub fn builder_store(&self, key: &Path) -> anyhow::Result<String> {
|
||||
let builder = &self.builder;
|
||||
let port: u16 = match builder.ssh_opts.as_slice() {
|
||||
[] => 22,
|
||||
[flag, port] if flag == "-p" => port.parse().context("the builder's port")?,
|
||||
_ => anyhow::bail!("the builder's ssh_opts can only set a port (-p <port>)"),
|
||||
};
|
||||
let host =
|
||||
if builder.hostname.contains(':') { format!("[{}]", builder.hostname) } else { builder.hostname.clone() };
|
||||
|
||||
let key = credential(key);
|
||||
let key = key.to_str().context("the SSH key's path isn't UTF-8")?;
|
||||
anyhow::ensure!(
|
||||
!key.contains(|c: char| c.is_whitespace() || "?&#%".contains(c)),
|
||||
"the SSH key's path can't go in a store URL: {key}"
|
||||
);
|
||||
Ok(format!("ssh-ng://{}@{host}:{port}?ssh-key={key}", builder.user))
|
||||
}
|
||||
}
|
||||
|
||||
/// The binary cache that `slop build` pushes to: a Nix store reached over SSH (`ssh-ng`), whose
|
||||
/// key's forced command allows only the store protocol and adding GC roots. Needs `deploy`, whose
|
||||
/// builder it uses.
|
||||
@@ -210,6 +298,13 @@ pub struct SshTarget {
|
||||
/// How `user` becomes root, followed by the user name (deploy-rs's `sudo`); nodes only.
|
||||
#[serde(default = "default_sudo")]
|
||||
pub sudo: String,
|
||||
/// The containers on it that requests can name; nodes only.
|
||||
#[serde(default)]
|
||||
pub containers: std::collections::BTreeSet<String>,
|
||||
/// Addresses to pick `hostname` from for each request, in order of preference, when a node
|
||||
/// has several (see `targets::Targets::reach`); nodes only.
|
||||
#[serde(skip)]
|
||||
pub addresses: Vec<String>,
|
||||
}
|
||||
|
||||
/// deploy-rs's default.
|
||||
@@ -309,6 +404,9 @@ impl Config {
|
||||
self.ssh.is_none() || self.deploy.is_some(),
|
||||
"ssh needs deploy, whose builder reads the main branch's deploy-rs nodes"
|
||||
);
|
||||
if let (Some(ssh), Some(deploy)) = (&self.ssh, &self.deploy) {
|
||||
deploy.builder_store(&ssh.key)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -338,6 +436,29 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::policy::OpName;
|
||||
|
||||
fn web(text: &str) -> Result<WebConfig, String> {
|
||||
toml::from_str::<WebConfig>(text).map_err(|e| e.message().to_owned())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_signs_in_or_not() {
|
||||
let common = "url = \"http://localhost:8095\"\nstate_dir = \"/var/lib/web\"\n";
|
||||
let oidc = "issuer = \"https://id.example.org\"\nclient_id = \"c\"\nclient_secret = \"s\"\ngroup = \"g\"\n";
|
||||
let none = "[no_sign_in]\napprover = \"demo\"\n";
|
||||
|
||||
let config = web(&format!("listen = \"[::]:8095\"\n{common}{oidc}")).unwrap();
|
||||
assert!(matches!(config.sign_in, SignIn::Oidc(ref o) if o.group == "g"));
|
||||
|
||||
let config = web(&format!("listen = \"127.0.0.1:8095\"\n{common}{none}")).unwrap();
|
||||
assert_eq!(config.sign_in, SignIn::None { approver: "demo".into() });
|
||||
|
||||
// Without sign-in only on loopback, and not mixed with OIDC settings
|
||||
let refused = web(&format!("listen = \"[::]:8095\"\n{common}{none}")).unwrap_err();
|
||||
assert!(refused.contains("loopback"), "{refused}");
|
||||
assert!(web(&format!("listen = \"[::1]:8095\"\n{common}{oidc}{none}")).is_err());
|
||||
assert!(web(&format!("listen = \"[::1]:8095\"\n{common}")).is_err());
|
||||
}
|
||||
|
||||
/// The layout the NixOS module writes.
|
||||
#[test]
|
||||
fn parses_generated_config() {
|
||||
@@ -386,7 +507,39 @@ mod tests {
|
||||
let rules = &mut misspelt.policies.get_mut("agent").unwrap().ops.get_mut(&OpName::Ssh).unwrap().rules;
|
||||
rules[0].matches = BTreeMap::from([("node".to_owned(), "river".to_owned())]);
|
||||
let error = misspelt.validate().unwrap_err().to_string();
|
||||
assert!(error.contains("ssh rules can't match \"node\"; its fields are target, host, port"), "{error}");
|
||||
assert!(
|
||||
error.contains("ssh rules can't match \"node\"; its fields are target, container, host, port"),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builder_stores() {
|
||||
let builder = |hostname: &str, ssh_opts: &[&str]| SshTarget {
|
||||
hostname: hostname.into(),
|
||||
user: "build".into(),
|
||||
ssh_opts: ssh_opts.iter().map(|o| o.to_string()).collect(),
|
||||
sudo: default_sudo(),
|
||||
containers: Default::default(),
|
||||
addresses: Vec::new(),
|
||||
};
|
||||
let deploy = |builder| DeployConfig { builder, nix: "/nix".into(), cache: "/cache".into() };
|
||||
let key = Path::new("/run/key");
|
||||
|
||||
assert_eq!(
|
||||
deploy(builder("localhost", &["-p", "2222"])).builder_store(key).unwrap(),
|
||||
"ssh-ng://build@localhost:2222?ssh-key=/run/key"
|
||||
);
|
||||
assert_eq!(
|
||||
deploy(builder("builder.example", &[])).builder_store(key).unwrap(),
|
||||
"ssh-ng://build@builder.example:22?ssh-key=/run/key"
|
||||
);
|
||||
assert_eq!(
|
||||
deploy(builder("fd00::1", &["-p", "22"])).builder_store(key).unwrap(),
|
||||
"ssh-ng://build@[fd00::1]:22?ssh-key=/run/key"
|
||||
);
|
||||
assert!(deploy(builder("b", &["-o", "ProxyJump=x"])).builder_store(key).is_err());
|
||||
assert!(deploy(builder("b", &[])).builder_store(Path::new("/run/a key")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+80
-4
@@ -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>) {
|
||||
@@ -32,7 +51,7 @@ impl Output {
|
||||
pub struct Io {
|
||||
/// Chunks of the requester's stdin, which it sends after approval for operations that ask for
|
||||
/// it; closed at EOF.
|
||||
pub stdin: mpsc::Receiver<Vec<u8>>,
|
||||
pub stdin: mpsc::UnboundedReceiver<Vec<u8>>,
|
||||
pub out: Output,
|
||||
/// Cancelled when the requester disconnects.
|
||||
pub cancel: CancellationToken,
|
||||
@@ -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);
|
||||
|
||||
+11
@@ -8,10 +8,21 @@ 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;
|
||||
|
||||
/// The version, like `0.3.0+2d59b59`, with the commit it's built from (and `-dirty` for
|
||||
/// uncommitted changes) in `SLOP_BROKER_VERSION`: Nix builds set it, and `build.rs` does for
|
||||
/// builds from a Git checkout.
|
||||
pub const VERSION: &str = match option_env!("SLOP_BROKER_VERSION") {
|
||||
Some(version) => version,
|
||||
None => env!("CARGO_PKG_VERSION"),
|
||||
};
|
||||
+25
-8
@@ -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,16 +62,16 @@ 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();
|
||||
let sizes = closure_sizes(deploy, &paths, &io.cancel).await?;
|
||||
let sizes = closure_sizes(ssh, deploy, &paths, &io.cancel).await?;
|
||||
|
||||
let description = parsed.prepared.description.as_ref().context("the commit wasn't described")?;
|
||||
let mut detail = Detail::new();
|
||||
@@ -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);
|
||||
@@ -135,10 +140,14 @@ fn copy_command(ssh: &SshConfig, deploy: &DeployConfig, cache: &CacheConfig, pat
|
||||
let options = nix_ssh_options(ssh::options_with_key(ssh, &cache.key), &cache.ssh_opts);
|
||||
ensure!(!options.iter().any(|o| o.contains(char::is_whitespace)), "SSH options can't contain spaces for nix copy");
|
||||
|
||||
let from = deploy.builder_store(&ssh.key)?;
|
||||
|
||||
let mut command = nix(deploy, ssh.ssh.parent());
|
||||
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))
|
||||
.args(paths);
|
||||
@@ -156,14 +165,17 @@ fn nix(deploy: &DeployConfig, ssh_directory: Option<&Path>) -> Command {
|
||||
command
|
||||
}
|
||||
|
||||
/// Each path's closure size, human-readable, from the local store.
|
||||
/// Each path's closure size, human-readable, from the builder's store.
|
||||
async fn closure_sizes(
|
||||
ssh: &SshConfig,
|
||||
deploy: &DeployConfig,
|
||||
paths: &[&str],
|
||||
cancel: &CancellationToken,
|
||||
) -> Result<Vec<(String, String)>> {
|
||||
let mut command = nix(deploy, None);
|
||||
let mut command = nix(deploy, ssh.ssh.parent());
|
||||
command.env("NIX_SSHOPTS", nix_ssh_options(ssh::options(ssh), &[]).join(" "));
|
||||
command.args(["--extra-experimental-features", "nix-command", "path-info", "--closure-size", "--human-readable"]);
|
||||
command.args(["--store", &deploy.builder_store(&ssh.key)?]);
|
||||
command.args(paths);
|
||||
|
||||
let (exit, stdout, stderr) = exec::capture(command, cancel).await?;
|
||||
@@ -219,6 +231,11 @@ mod tests {
|
||||
assert!(options.contains("-i /cache-key") && options.ends_with("-p 2222"), "{options}");
|
||||
assert!(!options.contains("PermitLocalCommand=no"), "{options}");
|
||||
assert!(args(©).contains(&"ssh-ng://harmonia@object.example".to_owned()));
|
||||
|
||||
// From the builder's store, with the broker's key
|
||||
let copy = args(©);
|
||||
let from = copy.iter().position(|a| a == "--from").unwrap();
|
||||
assert_eq!(copy[from + 1], "ssh-ng://deploy@river.example.org:2222?ssh-key=/key");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+53
-47
@@ -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,31 +85,45 @@ 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.clone() 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 built = builder::build(ssh, deploy, &request, &io.out, &io.cancel).await?;
|
||||
let request = BuildRequest { commit: commit.clone(), targets, attrs: Vec::new(), logs };
|
||||
io.out.info(format!("building {} for {}", commit.short(), parsed.summary)).await;
|
||||
let built = builder::build(&ssh, deploy, &request, &io.out, &io.cancel).await?;
|
||||
|
||||
// The nodes' addresses, picked once it's built, for the copies, the comparisons and the
|
||||
// activations
|
||||
let addresses = super::reach(broker, parsed, io).await?;
|
||||
let ssh = &*super::ssh_config(broker, parsed)?;
|
||||
let boot = &boot;
|
||||
|
||||
io.out.info("copying to the nodes and comparing with what they run").await;
|
||||
let by_node = group(&built.profiles);
|
||||
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;
|
||||
|
||||
let description = parsed.prepared.description.as_ref().context("the commit wasn't described")?;
|
||||
let mut detail = Detail::new();
|
||||
super::source(&mut detail, commit, description);
|
||||
super::source(&mut detail, &commit, description);
|
||||
if let Some(addresses) = addresses {
|
||||
detail.field(addresses);
|
||||
}
|
||||
for report in reports {
|
||||
detail.extend(report?);
|
||||
}
|
||||
@@ -123,8 +138,7 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
|
||||
/// [`super::outlives_requester`]).
|
||||
pub async fn execute(broker: &Broker, id: &str, parsed: &Parsed, io: &mut Io) -> Result<i32> {
|
||||
let Operation::Deploy { boot, .. } = &parsed.operation else { unreachable!() };
|
||||
let (ssh, _) = configs(broker)?;
|
||||
let ssh = &*ssh;
|
||||
let ssh = &*super::ssh_config(broker, parsed)?;
|
||||
let built = parsed.prepared.build.as_ref().context("nothing was built")?;
|
||||
|
||||
// Never cancelled: activations run to the end, and their output is dropped once the
|
||||
@@ -132,17 +146,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 +190,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,
|
||||
@@ -183,6 +203,8 @@ async fn copy(
|
||||
let options = copy_options(ssh, node)?;
|
||||
ensure!(!options.iter().any(|o| o.contains(char::is_whitespace)), "SSH options can't contain spaces for nix copy");
|
||||
|
||||
let from = deploy.builder_store(&ssh.key)?;
|
||||
|
||||
let ssh_directory = ssh.ssh.parent().map(|p| p.display().to_string()).unwrap_or_default();
|
||||
let mut command = Command::new(&deploy.nix);
|
||||
command
|
||||
@@ -197,13 +219,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(())
|
||||
}
|
||||
|
||||
@@ -274,26 +301,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 {
|
||||
@@ -315,7 +322,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`.
|
||||
@@ -483,7 +490,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"]);
|
||||
|
||||
+74
-21
@@ -1,13 +1,16 @@
|
||||
//! Operations the broker carries out. [`plan`] checks a request against the broker's
|
||||
//! configuration and works out its scope and what approvers are shown; [`execute`] runs it.
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::builder::Description;
|
||||
use crate::config::SshConfig;
|
||||
use crate::detail::{Detail, Field, Section, Tone};
|
||||
use crate::exec::Io;
|
||||
use crate::policy::{Limits, OpName};
|
||||
use crate::proto::{LeaseSummary, OpResult, Operation, PendingSummary};
|
||||
use crate::proto::{Destination, LeaseSummary, OpResult, Operation, PendingSummary};
|
||||
use crate::server::Broker;
|
||||
use crate::types::CommitId;
|
||||
|
||||
@@ -39,6 +42,8 @@ pub struct Parsed {
|
||||
pub stdin: bool,
|
||||
/// What was looked up or built before approval.
|
||||
pub prepared: Prepared,
|
||||
/// The SSH settings with the addresses [`reach`] picked for its nodes.
|
||||
pub ssh: Option<Arc<SshConfig>>,
|
||||
pub operation: Operation,
|
||||
}
|
||||
|
||||
@@ -54,6 +59,7 @@ impl Parsed {
|
||||
sensitive: false,
|
||||
stdin: false,
|
||||
prepared: Prepared::default(),
|
||||
ssh: None,
|
||||
operation,
|
||||
}
|
||||
}
|
||||
@@ -105,7 +111,11 @@ fn plan_op(broker: &Broker, operation: Operation) -> Result<Parsed> {
|
||||
ssh::check(config, destination)?;
|
||||
|
||||
let summary = format!("ssh {}", ssh::describe(destination));
|
||||
let detail = ssh::detail(command, stdin.as_deref())?;
|
||||
let mut detail = ssh::detail(command, stdin.as_deref())?;
|
||||
if let Destination::Container { node, name } = destination {
|
||||
let how = format!("as root, by /bin/sh -l in the container (systemd-run --machine={name} on {node})");
|
||||
detail.field(Field::new("Runs", how));
|
||||
}
|
||||
Ok(Parsed::new(OpName::Ssh, ssh::scope(destination), summary, detail, operation))
|
||||
}
|
||||
Operation::Query { destination, query } => {
|
||||
@@ -115,7 +125,7 @@ fn plan_op(broker: &Broker, operation: Operation) -> Result<Parsed> {
|
||||
scope.insert("query".into(), Value::from(query::name(query)));
|
||||
|
||||
let summary = format!("{} on {}", query::name(query), ssh::describe(destination));
|
||||
let detail = Detail::code("Command", shell_quote(&query::remote_command(query)));
|
||||
let detail = Detail::code("Command", shell_quote(&query::remote_command(config, destination, query)?));
|
||||
Ok(Parsed::new(OpName::Query, scope, summary, detail, operation))
|
||||
}
|
||||
Operation::Deploy { .. } => deploy::plan(broker, operation),
|
||||
@@ -208,6 +218,32 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
|
||||
}
|
||||
}
|
||||
|
||||
/// Picks an address for each node `parsed` reaches that has several, once for the whole request,
|
||||
/// before it first connects to them. The requester gets a line for each pick; the field returned
|
||||
/// shows them to approvers and the audit log.
|
||||
pub async fn reach(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<Option<Field>> {
|
||||
let nodes: Vec<String> = crate::targets::nodes(&parsed.operation).into_iter().map(|(n, _)| n.to_owned()).collect();
|
||||
if nodes.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let (ssh, picks) = broker.targets.reach(&nodes.iter().map(String::as_str).collect::<Vec<_>>()).await?;
|
||||
parsed.ssh = Some(ssh);
|
||||
for (node, address) in &picks {
|
||||
io.out.info(format!("reaching {node} at {address}")).await;
|
||||
}
|
||||
let picked: Vec<String> = picks.iter().map(|(node, address)| format!("{node} at {address}")).collect();
|
||||
Ok((!picked.is_empty()).then(|| Field::new("Addresses", picked.join(", "))))
|
||||
}
|
||||
|
||||
/// The SSH settings `parsed` runs with: those [`reach`] picked addresses in, else the broker's.
|
||||
fn ssh_config(broker: &Broker, parsed: &Parsed) -> Result<Arc<SshConfig>> {
|
||||
match &parsed.ssh {
|
||||
Some(ssh) => Ok(ssh.clone()),
|
||||
None => broker.targets.ssh(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs an approved request; `id` is its ID.
|
||||
pub async fn execute(broker: &Broker, id: &str, requester: &str, parsed: Parsed, io: &mut Io) -> Result<Outcome> {
|
||||
match parsed.operation {
|
||||
@@ -218,11 +254,13 @@ pub async fn execute(broker: &Broker, id: &str, requester: &str, parsed: Parsed,
|
||||
}
|
||||
|
||||
match parsed.operation {
|
||||
Operation::Ssh { destination, command, stdin } => {
|
||||
ssh::execute(broker, &destination, &command, stdin.as_deref(), io).await.map(Into::into)
|
||||
Operation::Ssh { ref destination, ref command, ref stdin } => {
|
||||
let config = ssh_config(broker, &parsed)?;
|
||||
ssh::execute(&config, destination, command, stdin.as_deref(), io).await.map(Into::into)
|
||||
}
|
||||
Operation::Query { destination, query } => {
|
||||
query::execute(broker, &destination, &query, io).await.map(Into::into)
|
||||
Operation::Query { ref destination, ref query } => {
|
||||
let config = ssh_config(broker, &parsed)?;
|
||||
query::execute(&config, destination, query, io).await.map(Into::into)
|
||||
}
|
||||
Operation::Requests => {
|
||||
let pending = broker
|
||||
@@ -244,20 +282,34 @@ pub async fn execute(broker: &Broker, id: &str, requester: &str, parsed: Parsed,
|
||||
}
|
||||
}
|
||||
|
||||
/// Quotes words for a POSIX shell, for showing commands and for remote commands built here.
|
||||
/// Quotes words for a POSIX shell or `fish`, for showing commands and for remote commands built
|
||||
/// here. `fish` reads `\\` and `\'` as escapes even in single quotes, so quotes and backslashes are
|
||||
/// escaped outside them, which both read the same way.
|
||||
pub fn shell_quote<S: AsRef<str>>(words: &[S]) -> String {
|
||||
words
|
||||
.iter()
|
||||
.map(|w| {
|
||||
let w = w.as_ref();
|
||||
if !w.is_empty() && w.bytes().all(|c| c.is_ascii_alphanumeric() || b"_-./=:@%+,".contains(&c)) {
|
||||
w.to_owned()
|
||||
} else {
|
||||
format!("'{}'", w.replace('\'', r"'\''"))
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
words.iter().map(|w| quote_word(w.as_ref())).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
fn quote_word(word: &str) -> String {
|
||||
if !word.is_empty() && word.bytes().all(|c| c.is_ascii_alphanumeric() || b"_-./=:@%+,".contains(&c)) {
|
||||
return word.to_owned();
|
||||
}
|
||||
|
||||
let (mut quoted, mut open) = (String::new(), false);
|
||||
for c in word.chars() {
|
||||
let escaped = matches!(c, '\'' | '\\');
|
||||
if escaped == open {
|
||||
quoted.push('\'');
|
||||
open = !open;
|
||||
}
|
||||
if escaped {
|
||||
quoted.push('\\');
|
||||
}
|
||||
quoted.push(c);
|
||||
}
|
||||
if open {
|
||||
quoted.push('\'');
|
||||
}
|
||||
if quoted.is_empty() { "''".into() } else { quoted }
|
||||
}
|
||||
|
||||
/// Text that can't control a terminal, for showing approvers what agents wrote (commit messages,
|
||||
@@ -287,7 +339,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 {
|
||||
@@ -320,5 +372,6 @@ mod tests {
|
||||
#[test]
|
||||
fn quotes_for_the_shell() {
|
||||
assert_eq!(shell_quote(&["systemctl", "status", "a b", "it's", ""]), r"systemctl status 'a b' 'it'\''s' ''");
|
||||
assert_eq!(shell_quote(&[r"a\\b", "'", r"\x2d"]), r"'a'\\\\'b' \' \\'x2d'");
|
||||
}
|
||||
}
|
||||
+43
-11
@@ -1,11 +1,11 @@
|
||||
//! Fixed read-only queries on boxes over SSH. The broker builds and quotes the remote command
|
||||
//! from validated values, so policy can safely approve these by itself.
|
||||
//! Fixed read-only queries on boxes and their containers over SSH. The broker builds and quotes
|
||||
//! the remote command from validated values, so policy can safely approve these by itself.
|
||||
use anyhow::Result;
|
||||
|
||||
use super::{shell_quote, ssh};
|
||||
use crate::config::SshConfig;
|
||||
use crate::exec::{self, Io};
|
||||
use crate::proto::{Destination, Query};
|
||||
use crate::server::Broker;
|
||||
|
||||
pub fn name(query: &Query) -> &'static str {
|
||||
match query {
|
||||
@@ -15,7 +15,20 @@ pub fn name(query: &Query) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remote_command(query: &Query) -> Vec<String> {
|
||||
/// The command to run on the destination's box. A container's runs on its host, as root, with
|
||||
/// `--machine`.
|
||||
pub fn remote_command(config: &SshConfig, destination: &Destination, query: &Query) -> Result<Vec<String>> {
|
||||
match destination {
|
||||
Destination::Container { node, name } => {
|
||||
let mut words = command(query);
|
||||
words.insert(1, format!("--machine={name}"));
|
||||
ssh::as_root(config, node, words)
|
||||
}
|
||||
_ => Ok(command(query)),
|
||||
}
|
||||
}
|
||||
|
||||
fn command(query: &Query) -> Vec<String> {
|
||||
let mut words: Vec<String> = match query {
|
||||
Query::Status { .. } => vec!["systemctl".into(), "status".into(), "--no-pager".into()],
|
||||
Query::Failed => vec!["systemctl".into(), "list-units".into(), "--failed".into(), "--no-pager".into()],
|
||||
@@ -35,11 +48,10 @@ pub fn remote_command(query: &Query) -> Vec<String> {
|
||||
words
|
||||
}
|
||||
|
||||
pub async fn execute(broker: &Broker, destination: &Destination, query: &Query, io: &mut Io) -> Result<i32> {
|
||||
let config = broker.targets.ssh()?;
|
||||
pub async fn execute(config: &SshConfig, destination: &Destination, query: &Query, io: &mut Io) -> Result<i32> {
|
||||
// One quoted string, so the remote login shell (POSIX or fish) sees exactly these words.
|
||||
let remote = [shell_quote(&remote_command(query))];
|
||||
exec::run(ssh::command(&config, destination, &remote)?, io, None).await
|
||||
let remote = [shell_quote(&remote_command(config, destination, query)?)];
|
||||
exec::run(ssh::command(config, destination, &remote)?, io, None).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -55,11 +67,31 @@ mod tests {
|
||||
since: Some("2026-01-31 12:00".parse().unwrap()),
|
||||
};
|
||||
assert_eq!(
|
||||
shell_quote(&remote_command(&logs)),
|
||||
shell_quote(&command(&logs)),
|
||||
"journalctl --no-pager --output=short-iso --lines=50 '--since=2026-01-31 12:00' --unit=nginx.service"
|
||||
);
|
||||
let status = Query::Status { unit: Some("nginx.service".parse().unwrap()) };
|
||||
assert_eq!(shell_quote(&remote_command(&status)), "systemctl status --no-pager -- nginx.service");
|
||||
assert_eq!(shell_quote(&remote_command(&Query::Failed)), "systemctl list-units --failed --no-pager");
|
||||
assert_eq!(shell_quote(&command(&status)), "systemctl status --no-pager -- nginx.service");
|
||||
assert_eq!(shell_quote(&command(&Query::Failed)), "systemctl list-units --failed --no-pager");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn container_commands_run_on_the_host_as_root() {
|
||||
let config = ssh::tests::config();
|
||||
let node = Destination::Node("river".parse().unwrap());
|
||||
let web = Destination::Container { node: "river".parse().unwrap(), name: "web".parse().unwrap() };
|
||||
|
||||
let status = Query::Status { unit: Some("nginx.service".parse().unwrap()) };
|
||||
assert_eq!(shell_quote(&remote_command(&config, &node, &status).unwrap()), shell_quote(&command(&status)));
|
||||
assert_eq!(
|
||||
shell_quote(&remote_command(&config, &web, &status).unwrap()),
|
||||
"doas -u root systemctl --machine=web status --no-pager -- nginx.service"
|
||||
);
|
||||
let logs =
|
||||
Query::Logs { unit: "nginx.service".parse().unwrap(), lines: Lines::try_from(5).unwrap(), since: None };
|
||||
assert_eq!(
|
||||
shell_quote(&remote_command(&config, &web, &logs).unwrap()),
|
||||
"doas -u root journalctl --machine=web --no-pager --output=short-iso --lines=5 --unit=nginx.service"
|
||||
);
|
||||
}
|
||||
}
|
||||
+111
-10
@@ -1,5 +1,5 @@
|
||||
//! Commands over SSH with the broker's key, to the main branch's deploy-rs nodes or explicit
|
||||
//! `user@host`s.
|
||||
//! Commands over SSH with the broker's key, to the main branch's deploy-rs nodes, containers on
|
||||
//! them, or explicit `user@host`s.
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde_json::{Map, Value, json};
|
||||
use tokio::process::Command;
|
||||
@@ -8,22 +8,29 @@ use crate::config::{SshConfig, SshTarget, credential};
|
||||
use crate::detail::{Detail, Field, Section};
|
||||
use crate::exec::{self, Io};
|
||||
use crate::proto::{Destination, MAX_SSH_SHOWN};
|
||||
use crate::server::Broker;
|
||||
use crate::types::Arg;
|
||||
use crate::types::{Arg, ContainerName};
|
||||
|
||||
/// Fails if `destination` names a target the broker doesn't know.
|
||||
pub fn check(config: &SshConfig, destination: &Destination) -> Result<()> {
|
||||
if let Destination::Node(node) = destination
|
||||
if let Some(node) = destination.node()
|
||||
&& !config.targets.contains_key(&**node)
|
||||
{
|
||||
bail!("unknown node {node}; nodes are the main branch's deploy-rs nodes, and --host reaches other boxes");
|
||||
}
|
||||
if let Destination::Container { node, name } = destination
|
||||
&& !config.targets[&**node].containers.contains(&**name)
|
||||
{
|
||||
bail!("unknown container {node}.container-{name}; containers are a node's container-* deploy-rs profiles");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What an approval covers. A container's has the node as `target`, so rules for a node apply
|
||||
/// to its containers too, but leases for one don't cover the other.
|
||||
pub fn scope(destination: &Destination) -> Map<String, Value> {
|
||||
let value = match destination {
|
||||
Destination::Node(node) => json!({ "target": node }),
|
||||
Destination::Container { node, name } => json!({ "target": node, "container": name }),
|
||||
Destination::Host { user, host, port } => json!({ "host": format!("{user}@{host}"), "port": port.get() }),
|
||||
};
|
||||
value.as_object().unwrap().clone()
|
||||
@@ -32,10 +39,43 @@ pub fn scope(destination: &Destination) -> Map<String, Value> {
|
||||
pub fn describe(destination: &Destination) -> String {
|
||||
match destination {
|
||||
Destination::Node(node) => node.to_string(),
|
||||
Destination::Container { node, name } => format!("{node}.container-{name}"),
|
||||
Destination::Host { user, host, port } => format!("{user}@{host} port {port} (host)"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The words that run `words` as root on a node: its `sudo` (deploy-rs's, such as `sudo -u`)
|
||||
/// and `root`. Commands for its containers go through `systemd-machined`, which needs root.
|
||||
pub fn as_root(config: &SshConfig, node: &str, words: impl IntoIterator<Item = String>) -> Result<Vec<String>> {
|
||||
let mut all: Vec<String> = target(config, node)?.sudo.split_whitespace().map(Into::into).collect();
|
||||
all.push("root".into());
|
||||
all.extend(words);
|
||||
Ok(all)
|
||||
}
|
||||
|
||||
/// The command on the host that runs `line` in container `name` as root, with a login shell
|
||||
/// the way `ssh` runs it on a node: stdin, output and the exit status pass through.
|
||||
pub fn container_shell(config: &SshConfig, node: &str, name: &ContainerName, line: &str) -> Result<Vec<String>> {
|
||||
let mut words: Vec<String> = [
|
||||
"systemd-run",
|
||||
&format!("--machine={name}"),
|
||||
"--quiet",
|
||||
"--wait",
|
||||
"--collect",
|
||||
"--pipe",
|
||||
"--expand-environment=no",
|
||||
"--",
|
||||
"/bin/sh",
|
||||
"-l",
|
||||
]
|
||||
.map(Into::into)
|
||||
.into();
|
||||
if !line.is_empty() {
|
||||
words.extend(["-c".into(), line.into()]);
|
||||
}
|
||||
as_root(config, node, words)
|
||||
}
|
||||
|
||||
/// What approvers see: the line the remote shell runs and all of its stdin, in full, since nothing
|
||||
/// else reaches the box. Requests too long to show whole are refused.
|
||||
pub fn detail(command: &[Arg], stdin: Option<&[u8]>) -> Result<Detail> {
|
||||
@@ -107,7 +147,7 @@ pub fn command<S: AsRef<str>>(config: &SshConfig, destination: &Destination, rem
|
||||
command.arg("-T").args(options(config));
|
||||
|
||||
match destination {
|
||||
Destination::Node(node) => {
|
||||
Destination::Node(node) | Destination::Container { node, .. } => {
|
||||
let target = target(config, node)?;
|
||||
command.args(&target.ssh_opts).args(["-l", &target.user, "--", &target.hostname]);
|
||||
}
|
||||
@@ -120,6 +160,24 @@ pub fn command<S: AsRef<str>>(config: &SshConfig, destination: &Destination, rem
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
/// Where `ssh` would connect for `address` with `target`'s options, as `ssh -G` works it out.
|
||||
pub async fn endpoint(config: &SshConfig, target: &SshTarget, address: &str) -> Option<(String, u16)> {
|
||||
let mut command = Command::new(&config.ssh);
|
||||
command.env_clear().env("PATH", "/run/current-system/sw/bin").env("HOME", "/var/empty");
|
||||
command.arg("-G").args(options(config)).args(&target.ssh_opts).args(["-l", &target.user, "--", address]);
|
||||
let output = command.stdin(std::process::Stdio::null()).stderr(std::process::Stdio::null()).output().await.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
resolved(&String::from_utf8_lossy(&output.stdout))
|
||||
}
|
||||
|
||||
/// The host name and port in `ssh -G`'s output.
|
||||
fn resolved(config: &str) -> Option<(String, u16)> {
|
||||
let value = |key: &str| config.lines().find_map(|l| l.strip_prefix(key)?.strip_prefix(' ')).map(str::to_owned);
|
||||
Some((value("hostname")?, value("port")?.parse().ok()?))
|
||||
}
|
||||
|
||||
/// A node's settings. Nodes can disappear from the main branch between planning a request and
|
||||
/// running it.
|
||||
pub fn target<'a>(config: &'a SshConfig, node: &str) -> Result<&'a SshTarget> {
|
||||
@@ -137,14 +195,22 @@ pub fn command_to<S: AsRef<str>>(config: &SshConfig, target: &SshTarget, remote:
|
||||
}
|
||||
|
||||
pub async fn execute(
|
||||
broker: &Broker,
|
||||
config: &SshConfig,
|
||||
destination: &Destination,
|
||||
remote: &[Arg],
|
||||
stdin: Option<&[u8]>,
|
||||
io: &mut Io,
|
||||
) -> Result<i32> {
|
||||
let config = broker.targets.ssh()?;
|
||||
exec::run(command(&config, destination, remote)?, io, Some(stdin.unwrap_or_default())).await
|
||||
let command = match destination {
|
||||
Destination::Container { node, name } => {
|
||||
// `ssh` joins the words with spaces; so does this, and the container's shell runs it.
|
||||
let line = remote.iter().map(|w| &**w).collect::<Vec<_>>().join(" ");
|
||||
let words = container_shell(config, node, name, &line)?;
|
||||
self::command(config, destination, &[super::shell_quote(&words)])?
|
||||
}
|
||||
_ => command(config, destination, remote)?,
|
||||
};
|
||||
exec::run(command, io, Some(stdin.unwrap_or_default())).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -152,6 +218,14 @@ pub(crate) mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[test]
|
||||
fn reads_where_ssh_connects() {
|
||||
let config = "user deploy\nhostname 192.0.2.7\nport 2222\nhostkeyalias tower\n";
|
||||
assert_eq!(resolved(config), Some(("192.0.2.7".to_owned(), 2222)));
|
||||
assert_eq!(resolved("hostname x\n"), None);
|
||||
assert_eq!(resolved("hostnamex y\nhostname x\nport z\n"), None);
|
||||
}
|
||||
|
||||
pub fn config() -> SshConfig {
|
||||
let mut targets = BTreeMap::new();
|
||||
targets.insert(
|
||||
@@ -161,15 +235,42 @@ pub(crate) mod tests {
|
||||
user: "deploy".into(),
|
||||
ssh_opts: vec!["-p".into(), "2222".into()],
|
||||
sudo: "doas -u".into(),
|
||||
containers: ["web".to_owned()].into(),
|
||||
addresses: vec![],
|
||||
},
|
||||
);
|
||||
SshConfig { ssh: "ssh".into(), key: "/key".into(), known_hosts: "/kh".into(), targets }
|
||||
}
|
||||
|
||||
fn container(node: &str, name: &str) -> Destination {
|
||||
Destination::Container { node: node.parse().unwrap(), name: name.parse().unwrap() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_nodes_are_refused() {
|
||||
fn unknown_nodes_and_containers_are_refused() {
|
||||
assert!(check(&config(), &Destination::Node("river".parse().unwrap())).is_ok());
|
||||
assert!(check(&config(), &Destination::Node("sfh".parse().unwrap())).is_err());
|
||||
assert!(check(&config(), &container("river", "web")).is_ok());
|
||||
assert!(check(&config(), &container("river", "db")).is_err());
|
||||
assert!(check(&config(), &container("sfh", "web")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn containers_have_their_own_scope() {
|
||||
assert_eq!(Value::Object(scope(&container("river", "web"))), json!({ "target": "river", "container": "web" }));
|
||||
assert_eq!(describe(&container("river", "web")), "river.container-web");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn container_commands_run_as_root_through_systemd_run() {
|
||||
let words = container_shell(&config(), "river", &"web".parse().unwrap(), "echo $HOME").unwrap();
|
||||
assert_eq!(
|
||||
super::super::shell_quote(&words),
|
||||
"doas -u root systemd-run --machine=web --quiet --wait --collect --pipe --expand-environment=no -- /bin/sh \
|
||||
-l -c 'echo $HOME'"
|
||||
);
|
||||
let words = container_shell(&config(), "river", &"web".parse().unwrap(), "").unwrap();
|
||||
assert_eq!(words.last().unwrap(), "-l");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+2
-2
@@ -53,8 +53,8 @@ impl OpName {
|
||||
/// targets, a build's attributes), that scope's fields.
|
||||
pub fn fields(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
OpName::Query => &["target", "host", "port", "query"],
|
||||
OpName::Ssh => &["target", "host", "port"],
|
||||
OpName::Query => &["target", "container", "host", "port", "query"],
|
||||
OpName::Ssh => &["target", "container", "host", "port"],
|
||||
OpName::Deploy => &["node", "profile", "mode", "commit"],
|
||||
OpName::Builder => &["commit", "on_branch", "for"],
|
||||
OpName::Build => &["attr", "commit"],
|
||||
|
||||
+768
@@ -0,0 +1,768 @@
|
||||
//! 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 FromIterator<Progress> for Phases {
|
||||
fn from_iter<I: IntoIterator<Item = Progress>>(progress: I) -> Phases {
|
||||
let mut phases = Phases::default();
|
||||
for progress in progress {
|
||||
phases.record(&progress);
|
||||
}
|
||||
phases
|
||||
}
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
+45
-4
@@ -14,14 +14,15 @@ 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, DeployTarget, FlakeAttr, HostName, Lines, NodeName, Recipient, SecretKey, SecretPath, Since,
|
||||
UnitName, UserName,
|
||||
Arg, CommitId, ContainerName, DeployTarget, FlakeAttr, HostName, Lines, NodeName, Recipient, SecretKey, SecretPath,
|
||||
Since, UnitName, UserName,
|
||||
};
|
||||
|
||||
/// Bumped on any incompatible change; the broker refuses other versions.
|
||||
pub const PROTOCOL_VERSION: u32 = 2;
|
||||
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),
|
||||
@@ -196,6 +204,12 @@ impl GenKind {
|
||||
pub enum Destination {
|
||||
/// A configured target (normally a deploy-rs node), with its configured user and options.
|
||||
Node(NodeName),
|
||||
/// A container on a node, reached through the node's host: one of the node's
|
||||
/// `container-<name>` deploy-rs profiles.
|
||||
Container {
|
||||
node: NodeName,
|
||||
name: ContainerName,
|
||||
},
|
||||
Host {
|
||||
user: UserName,
|
||||
host: HostName,
|
||||
@@ -203,6 +217,16 @@ pub enum Destination {
|
||||
},
|
||||
}
|
||||
|
||||
impl Destination {
|
||||
/// The node it's reached through, if any.
|
||||
pub fn node(&self) -> Option<&NodeName> {
|
||||
match self {
|
||||
Destination::Node(node) | Destination::Container { node, .. } => Some(node),
|
||||
Destination::Host { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
|
||||
pub enum Query {
|
||||
@@ -233,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.
|
||||
@@ -305,6 +331,8 @@ pub enum ApproveRequest {
|
||||
Log {
|
||||
count: usize,
|
||||
},
|
||||
/// Requests that are building, copying or activating.
|
||||
Running,
|
||||
}
|
||||
|
||||
/// Keeps a `Log` response well within [`MAX_MESSAGE`].
|
||||
@@ -316,9 +344,22 @@ pub enum ApproveResponse {
|
||||
Pending(Vec<PendingInfo>),
|
||||
Recorded,
|
||||
Log(Vec<Record>),
|
||||
Running(Vec<RunInfo>),
|
||||
Error(String),
|
||||
}
|
||||
|
||||
/// A running request, the oldest first in [`ApproveResponse::Running`].
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RunInfo {
|
||||
pub id: String,
|
||||
pub requester: String,
|
||||
pub summary: String,
|
||||
pub elapsed: u64,
|
||||
/// Each phase's latest progress.
|
||||
pub phases: Vec<Progress>,
|
||||
}
|
||||
|
||||
pub type Transport<S> = Framed<S, LengthDelimitedCodec>;
|
||||
|
||||
pub fn codec() -> LengthDelimitedCodec {
|
||||
|
||||
@@ -279,11 +279,6 @@ impl Queue {
|
||||
leases.sort();
|
||||
leases
|
||||
}
|
||||
|
||||
/// The current version of the pending set, which [`Queue::subscribe`] reports changes of.
|
||||
pub fn version(&self) -> u64 {
|
||||
self.state.lock().unwrap().sequence
|
||||
}
|
||||
}
|
||||
|
||||
fn info(id: &str, entry: &Entry, now: Instant) -> PendingInfo {
|
||||
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
//! 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};
|
||||
use crate::proto::RunInfo;
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
/// What approvers' clients get.
|
||||
pub fn info(&self) -> RunInfo {
|
||||
RunInfo {
|
||||
id: self.id.clone(),
|
||||
requester: self.requester.clone(),
|
||||
summary: self.summary.clone(),
|
||||
elapsed: self.elapsed(),
|
||||
phases: self.phases.as_slice().to_vec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
+53
-11
@@ -21,13 +21,19 @@ 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;
|
||||
/// a requester sending more than this is treated as gone.
|
||||
const MAX_STDIN: usize = 1 << 20;
|
||||
|
||||
pub struct Broker {
|
||||
pub config: Config,
|
||||
pub queue: Queue,
|
||||
pub audit: Audit,
|
||||
pub targets: Targets,
|
||||
pub runs: Arc<Runs>,
|
||||
}
|
||||
|
||||
impl Broker {
|
||||
@@ -36,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() })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,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 {
|
||||
@@ -123,18 +129,25 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Send + 'static>(broker: Arc<Brok
|
||||
};
|
||||
|
||||
// After the request, the requester only sends stdin; anything else, or the connection
|
||||
// closing, means it's gone.
|
||||
// closing, means it's gone. The reader never waits on the operation, so it always notices:
|
||||
// stdin is buffered up to a limit, and dropped once the operation can't take it.
|
||||
let cancel = CancellationToken::new();
|
||||
let (stdin_tx, stdin_rx) = mpsc::channel(16);
|
||||
let (stdin_tx, stdin_rx) = mpsc::unbounded_channel();
|
||||
let reader = {
|
||||
let cancel = cancel.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut stdin_tx = Some(stdin_tx);
|
||||
let (mut stdin_tx, mut total) = (Some(stdin_tx), 0);
|
||||
while let Some(Ok(frame)) = source.next().await {
|
||||
match decode::<ClientMessage>(&frame) {
|
||||
Ok(ClientMessage::Stdin(data)) => {
|
||||
if let Some(tx) = &stdin_tx {
|
||||
let _ = tx.send(data).await;
|
||||
total += data.len();
|
||||
if total > MAX_STDIN {
|
||||
break;
|
||||
}
|
||||
if tx.send(data).is_err() {
|
||||
stdin_tx = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(ClientMessage::StdinEnd) => stdin_tx = None,
|
||||
@@ -165,8 +178,9 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Send + 'static>(broker: Arc<Brok
|
||||
async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io) -> Option<ServerMessage> {
|
||||
if request.version != PROTOCOL_VERSION {
|
||||
return Some(ServerMessage::Error(format!(
|
||||
"protocol version {} is not supported (the broker uses {PROTOCOL_VERSION}); update slop",
|
||||
request.version
|
||||
"protocol version {} is not supported (slop-broker {} uses {PROTOCOL_VERSION}); update slop",
|
||||
request.version,
|
||||
crate::VERSION
|
||||
)));
|
||||
}
|
||||
|
||||
@@ -182,6 +196,26 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
|
||||
}
|
||||
};
|
||||
|
||||
// Nodes with several addresses get one picked for the whole request, shown to approvers.
|
||||
// Requests that build pick theirs once built, before connecting.
|
||||
if !ops::builds(&parsed) {
|
||||
match ops::reach(broker, &mut parsed, io).await {
|
||||
Ok(Some(addresses)) => {
|
||||
parsed.detail.field(addresses);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => {
|
||||
let error = format!("{error:#}");
|
||||
broker.audit.log(Event::Invalid { id, requester: requester.to_owned(), error: error.clone() });
|
||||
return Some(ServerMessage::Error(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !parsed.stdin {
|
||||
io.stdin.close();
|
||||
}
|
||||
|
||||
// Built-in operations only read the broker's own state, so they aren't logged.
|
||||
let builtin = parsed.op.builtin();
|
||||
let log = |event| {
|
||||
@@ -199,6 +233,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
|
||||
@@ -226,7 +263,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))
|
||||
};
|
||||
|
||||
@@ -257,6 +294,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 {
|
||||
@@ -300,12 +340,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))
|
||||
}
|
||||
}
|
||||
|
||||
+161
-9
@@ -1,10 +1,16 @@
|
||||
//! SSH targets: the main branch's deploy-rs nodes. The builder reads them from the branch only
|
||||
//! people can push to, so a new box needs a commit there rather than a new broker config.
|
||||
//!
|
||||
//! A node can list several addresses (`sshHostnames`), for a box that moves between networks.
|
||||
//! Each request picks one for each such node it reaches, before it first connects, and uses it
|
||||
//! throughout.
|
||||
use std::collections::BTreeMap;
|
||||
use std::future::Future;
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use futures_util::future::join_all;
|
||||
use tokio::sync::{Mutex, mpsc};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
@@ -17,6 +23,8 @@ use crate::proto::{Destination, Operation};
|
||||
const FRESH: Duration = Duration::from_secs(60);
|
||||
/// The shortest time between lookups, so unknown names can't make the builder fetch nonstop.
|
||||
const RETRY: Duration = Duration::from_secs(10);
|
||||
/// How long an address's SSH port has to accept a connection to be picked.
|
||||
const PROBE: Duration = Duration::from_secs(2);
|
||||
|
||||
pub struct Targets {
|
||||
/// The SSH settings with the branch's nodes; `None` without SSH.
|
||||
@@ -46,7 +54,11 @@ impl Targets {
|
||||
}
|
||||
|
||||
let mut looked = self.looked.lock().await;
|
||||
let known = self.ssh().is_ok_and(|ssh| names.iter().all(|n| ssh.targets.contains_key(*n)));
|
||||
let known = self.ssh().is_ok_and(|ssh| {
|
||||
names.iter().all(|(node, container)| {
|
||||
ssh.targets.get(*node).is_some_and(|t| container.is_none_or(|c| t.containers.contains(c)))
|
||||
})
|
||||
});
|
||||
let due = match *looked {
|
||||
None => true,
|
||||
Some((at, succeeded)) => {
|
||||
@@ -59,7 +71,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 {
|
||||
@@ -68,6 +80,32 @@ impl Targets {
|
||||
}
|
||||
}
|
||||
|
||||
/// The SSH settings for one request that reaches `nodes`, with an address picked for each
|
||||
/// that has several, and the picks.
|
||||
pub async fn reach(&self, nodes: &[&str]) -> Result<(Arc<SshConfig>, Vec<(String, String)>)> {
|
||||
let ssh = self.ssh()?;
|
||||
let mut several: Vec<&str> =
|
||||
nodes.iter().copied().filter(|n| ssh.targets.get(*n).is_some_and(|t| !t.addresses.is_empty())).collect();
|
||||
several.sort();
|
||||
several.dedup();
|
||||
if several.is_empty() {
|
||||
return Ok((ssh, Vec::new()));
|
||||
}
|
||||
|
||||
let picks = join_all(several.into_iter().map(|node| {
|
||||
let (ssh, target) = (&ssh, &ssh.targets[node]);
|
||||
let answers = move |address: String| async move { answers(ssh, target, &address).await };
|
||||
async move { (node.to_owned(), pick(&target.addresses, answers).await) }
|
||||
}))
|
||||
.await;
|
||||
|
||||
let mut picked = (*ssh).clone();
|
||||
for (node, address) in &picks {
|
||||
picked.targets.get_mut(node).expect("a known node").hostname = address.clone();
|
||||
}
|
||||
Ok((Arc::new(picked), picks))
|
||||
}
|
||||
|
||||
/// Replaces the nodes, as a lookup does.
|
||||
fn set(&self, ssh: &SshConfig, nodes: BTreeMap<String, Node>) {
|
||||
*self.current.write().unwrap() = Some(Arc::new(with_nodes(ssh, nodes)));
|
||||
@@ -82,16 +120,48 @@ impl Targets {
|
||||
}
|
||||
}
|
||||
|
||||
/// The node names an operation reaches.
|
||||
fn nodes(operation: &Operation) -> Vec<&str> {
|
||||
/// The first of `addresses` that `answers`, else the last, as nixfiles' `ssh-machine` does.
|
||||
async fn pick<F: Future<Output = bool>>(addresses: &[String], answers: impl Fn(String) -> F) -> String {
|
||||
let (last, preferred) = addresses.split_last().expect("addresses to pick from");
|
||||
for address in preferred {
|
||||
if answers(address.clone()).await {
|
||||
return address.clone();
|
||||
}
|
||||
}
|
||||
last.clone()
|
||||
}
|
||||
|
||||
/// Whether SSH's port at `address` accepts a connection soon, where `ssh` would connect with
|
||||
/// `target`'s options.
|
||||
async fn answers(ssh: &SshConfig, target: &SshTarget, address: &str) -> bool {
|
||||
let Some((host, port)) = crate::ops::ssh::endpoint(ssh, target, address).await else { return false };
|
||||
let connect = tokio::net::TcpStream::connect((host.as_str(), port));
|
||||
matches!(tokio::time::timeout(PROBE, connect).await, Ok(Ok(_)))
|
||||
}
|
||||
|
||||
/// The nodes an operation reaches, each with the container on it it names, if any.
|
||||
pub fn nodes(operation: &Operation) -> Vec<(&str, Option<&str>)> {
|
||||
match operation {
|
||||
Operation::Ssh { destination: Destination::Node(node), .. }
|
||||
| Operation::Query { destination: Destination::Node(node), .. } => vec![&**node],
|
||||
Operation::Deploy { targets, .. } => targets.iter().map(|t| t.node()).collect(),
|
||||
Operation::Ssh { destination, .. } | Operation::Query { destination, .. } => match destination {
|
||||
Destination::Node(node) => vec![(&**node, None)],
|
||||
Destination::Container { node, name } => vec![(&**node, Some(&**name))],
|
||||
Destination::Host { .. } => Vec::new(),
|
||||
},
|
||||
Operation::Deploy { targets, .. } => targets.iter().map(|t| (t.node(), None)).collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The containers a node's `container-<name>` profiles deploy.
|
||||
fn containers(profiles: &[String]) -> std::collections::BTreeSet<String> {
|
||||
profiles
|
||||
.iter()
|
||||
.filter_map(|p| p.strip_prefix("container-"))
|
||||
.filter(|name| name.parse::<crate::types::ContainerName>().is_ok())
|
||||
.map(Into::into)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The SSH settings with `nodes` as targets. Nodes without an SSH user or with an invalid name are
|
||||
/// left out, since nothing could reach them.
|
||||
fn with_nodes(ssh: &SshConfig, nodes: BTreeMap<String, Node>) -> SshConfig {
|
||||
@@ -102,7 +172,16 @@ fn with_nodes(ssh: &SshConfig, nodes: BTreeMap<String, Node>) -> SshConfig {
|
||||
}
|
||||
let Some(user) = node.ssh_user else { continue };
|
||||
let sudo = node.sudo.unwrap_or_else(default_sudo);
|
||||
targets.insert(name, SshTarget { hostname: node.hostname, user, ssh_opts: node.ssh_opts, sudo });
|
||||
let containers = containers(&node.profiles);
|
||||
|
||||
// The last address is used until a request picks one.
|
||||
let (hostname, addresses) = match node.ssh_hostnames.as_slice() {
|
||||
[] => (node.hostname, Vec::new()),
|
||||
[only] => (only.clone(), Vec::new()),
|
||||
[.., last] => (last.clone(), node.ssh_hostnames.clone()),
|
||||
};
|
||||
let target = SshTarget { hostname, user, ssh_opts: node.ssh_opts, sudo, containers, addresses };
|
||||
targets.insert(name, target);
|
||||
}
|
||||
SshConfig { targets, ..ssh.clone() }
|
||||
}
|
||||
@@ -117,6 +196,8 @@ mod tests {
|
||||
ssh_user: user.map(Into::into),
|
||||
ssh_opts: vec!["-p".into(), "2222".into()],
|
||||
sudo: sudo.map(Into::into),
|
||||
profiles: vec!["system".into(), "container-web".into(), "container--x".into(), "containerx".into()],
|
||||
ssh_hostnames: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +217,71 @@ mod tests {
|
||||
assert_eq!(ssh.targets["web"].sudo, "doas -u");
|
||||
assert_eq!(ssh.targets["plain"].sudo, "sudo -u");
|
||||
assert_eq!(ssh.targets["web"].ssh_opts, ["-p", "2222"]);
|
||||
assert_eq!(ssh.targets["web"].containers.iter().collect::<Vec<_>>(), ["web"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_addresses_replace_the_hostname() {
|
||||
let ssh =
|
||||
SshConfig { ssh: "ssh".into(), key: "/key".into(), known_hosts: "/kh".into(), targets: BTreeMap::new() };
|
||||
let with = |hostnames: &[&str]| Node {
|
||||
ssh_hostnames: hostnames.iter().map(|h| h.to_string()).collect(),
|
||||
..node(Some("deploy"), None)
|
||||
};
|
||||
let nodes = [("plain", with(&[])), ("one", with(&["one.example"])), ("two", with(&["home.lan", "ts.example"]))];
|
||||
|
||||
let ssh = with_nodes(&ssh, nodes.map(|(name, node)| (name.to_owned(), node)).into());
|
||||
let address = |name: &str| (ssh.targets[name].hostname.as_str(), ssh.targets[name].addresses.len());
|
||||
assert_eq!(address("plain"), ("box.example", 0));
|
||||
assert_eq!(address("one"), ("one.example", 0));
|
||||
// Until a request picks one
|
||||
assert_eq!(address("two"), ("ts.example", 2));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn picks_the_first_address_that_answers() {
|
||||
let addresses: Vec<String> = ["home.lan", "office.lan", "ts.example"].map(Into::into).into();
|
||||
let up = |up: &'static [&'static str]| move |address: String| async move { up.contains(&address.as_str()) };
|
||||
assert_eq!(pick(&addresses, up(&["office.lan", "ts.example"])).await, "office.lan");
|
||||
assert_eq!(pick(&addresses, up(&["home.lan"])).await, "home.lan");
|
||||
// The last is the fallback, without trying it.
|
||||
assert_eq!(pick(&addresses, up(&[])).await, "ts.example");
|
||||
}
|
||||
|
||||
/// Picks with a stand-in for `ssh -G` that sends `up` to a port that's listening, and other
|
||||
/// addresses to one that isn't.
|
||||
#[tokio::test]
|
||||
async fn reaching_picks_for_each_request() {
|
||||
let listening = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
let open = listening.local_addr().unwrap().port();
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let fake = directory.path().join("ssh");
|
||||
let script = format!(
|
||||
"#!/bin/sh\nfor a; do last=$a; done\necho hostname 127.0.0.1\n\
|
||||
if [ \"$last\" = up ]; then echo port {open}; else echo port {closed}; fi\n"
|
||||
);
|
||||
std::fs::write(&fake, script).unwrap();
|
||||
std::fs::set_permissions(&fake, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
|
||||
|
||||
let targets = Targets { current: RwLock::new(None), looked: Mutex::new(None) };
|
||||
let ssh = SshConfig { ssh: fake, key: "/key".into(), known_hosts: "/kh".into(), targets: BTreeMap::new() };
|
||||
let with = |hostnames: &[&str]| Node {
|
||||
ssh_hostnames: hostnames.iter().map(|h| h.to_string()).collect(),
|
||||
..node(Some("deploy"), None)
|
||||
};
|
||||
let nodes = [("tower", with(&["down", "up", "last"])), ("away", with(&["down", "last"])), ("web", with(&[]))];
|
||||
targets.set(&ssh, nodes.map(|(name, node)| (name.to_owned(), node)).into());
|
||||
|
||||
let (picked, picks) = targets.reach(&["web", "tower", "away", "tower"]).await.unwrap();
|
||||
assert_eq!(picks, [("away".to_owned(), "last".to_owned()), ("tower".to_owned(), "up".to_owned())]);
|
||||
assert_eq!(picked.targets["tower"].hostname, "up");
|
||||
assert_eq!(picked.targets["away"].hostname, "last");
|
||||
// The broker's own settings don't change.
|
||||
assert_eq!(targets.ssh().unwrap().targets["tower"].hostname, "last");
|
||||
|
||||
let (_, picks) = targets.reach(&["web"]).await.unwrap();
|
||||
assert!(picks.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -144,8 +290,14 @@ mod tests {
|
||||
targets: vec!["web".parse().unwrap(), "river.system".parse().unwrap()],
|
||||
commit: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(),
|
||||
boot: false,
|
||||
logs: false,
|
||||
};
|
||||
assert_eq!(nodes(&deploy), ["web", "river"]);
|
||||
assert_eq!(nodes(&deploy), [("web", None), ("river", None)]);
|
||||
let query = Operation::Query {
|
||||
destination: Destination::Container { node: "shill".parse().unwrap(), name: "web".parse().unwrap() },
|
||||
query: crate::proto::Query::Failed,
|
||||
};
|
||||
assert_eq!(nodes(&query), [("shill", Some("web"))]);
|
||||
assert!(nodes(&Operation::Requests).is_empty());
|
||||
}
|
||||
}
|
||||
+487
@@ -0,0 +1,487 @@
|
||||
//! What `slop` shows of progress on stderr, and `slop-approve` of every running request.
|
||||
//!
|
||||
//! - 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.
|
||||
//!
|
||||
//! `slop` shows one request's progress; `slop-approve` shows several at once, each labelled with
|
||||
//! its run (the request's short ID) on its lines and bars.
|
||||
use std::collections::HashMap;
|
||||
use std::io::Write;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use indicatif::{MultiProgress, ProgressBar, ProgressDrawTarget, ProgressStyle};
|
||||
|
||||
use crate::ops::printable;
|
||||
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 of each run last had a line, without a terminal.
|
||||
said: HashMap<(Run, Phase), Instant>,
|
||||
}
|
||||
|
||||
/// Which request progress is about: `slop`'s own (`None`), or one of those `slop-approve` shows.
|
||||
type Run = Option<String>;
|
||||
|
||||
struct Bars {
|
||||
multi: MultiProgress,
|
||||
/// Where they're drawn: stderr, except in tests.
|
||||
target: Box<dyn Fn() -> ProgressDrawTarget + Send>,
|
||||
phases: HashMap<Run, Phases>,
|
||||
bars: Vec<Bar>,
|
||||
/// Whether other output stopped mid-line, which hides the bars.
|
||||
mid_line: bool,
|
||||
/// Whether something else has the terminal, which hides them too.
|
||||
paused: bool,
|
||||
}
|
||||
|
||||
struct Bar {
|
||||
run: Run,
|
||||
key: Key,
|
||||
label: String,
|
||||
bar: ProgressBar,
|
||||
}
|
||||
|
||||
/// What a bar is for, in its run.
|
||||
#[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.
|
||||
pub(crate) 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: HashMap::new(),
|
||||
bars: Vec::new(),
|
||||
mid_line: false,
|
||||
paused: 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) {
|
||||
self.update_run(None, progress);
|
||||
}
|
||||
|
||||
/// Shows the progress of `run` (one of several requests, by its short ID), or `slop`'s own.
|
||||
pub fn update_run(&mut self, run: Option<&str>, progress: &Progress) {
|
||||
let ended = progress.state != State::Running;
|
||||
let line = printable(&format!("{}: {}", run.unwrap_or("slop"), progress.line()));
|
||||
let run: Run = run.map(str::to_owned);
|
||||
|
||||
let Some(bars) = &mut self.bars else {
|
||||
let said = (run, progress.phase.clone());
|
||||
let due = self.said.get(&said).is_none_or(|said| said.elapsed() >= SUMMARY_INTERVAL);
|
||||
if ended {
|
||||
self.said.remove(&said);
|
||||
eprintln!("{line}");
|
||||
} else if due {
|
||||
// Not the first: a phase starting doesn't need a line of its own
|
||||
if self.said.contains_key(&said) {
|
||||
eprintln!("{line}");
|
||||
}
|
||||
self.said.insert(said, Instant::now());
|
||||
}
|
||||
return;
|
||||
};
|
||||
|
||||
// Progress always starts on a line of its own.
|
||||
bars.line_ended(true);
|
||||
let phases = bars.phases.entry(run.clone()).or_default();
|
||||
phases.record(progress);
|
||||
let row = progress.phase.node().map(|node| phases.node(node).expect("just recorded"));
|
||||
if ended {
|
||||
let _ = bars.multi.println(line);
|
||||
}
|
||||
|
||||
match row {
|
||||
None if ended => bars.remove(&run, &Key::Phase(progress.phase.clone())),
|
||||
None => {
|
||||
let bar = bars.bar(&run, Key::Phase(progress.phase.clone()), progress.phase.doing());
|
||||
show(&bar, progress, details(progress));
|
||||
}
|
||||
Some(row) if row.ended() => bars.remove(&run, &Key::Node(row.node)),
|
||||
Some(row) => {
|
||||
let bar = bars.bar(&run, Key::Node(row.node.clone()), row.node.clone());
|
||||
show(&bar, &row.latest, node_details(&row));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Forgets a run that ended, taking its bars off the terminal.
|
||||
pub fn end_run(&mut self, run: &str) {
|
||||
let run: Run = Some(run.to_owned());
|
||||
self.said.retain(|(r, _), _| *r != run);
|
||||
if let Some(bars) = &mut self.bars {
|
||||
bars.phases.remove(&run);
|
||||
let keys: Vec<Key> = bars.bars.iter().filter(|b| b.run == run).map(|b| b.key.clone()).collect();
|
||||
for key in keys {
|
||||
bars.remove(&run, &key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes the bars off the terminal while something else uses it, such as a prompt, until
|
||||
/// [`Board::resume`]. Updates meanwhile aren't shown, lines included.
|
||||
pub fn pause(&mut self) {
|
||||
if let Some(bars) = &mut self.bars
|
||||
&& !bars.paused
|
||||
{
|
||||
let _ = bars.multi.clear();
|
||||
bars.paused = true;
|
||||
bars.retarget();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resume(&mut self) {
|
||||
if let Some(bars) = &mut self.bars
|
||||
&& bars.paused
|
||||
{
|
||||
bars.paused = false;
|
||||
bars.retarget();
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.bar.finish_and_clear();
|
||||
}
|
||||
let _ = bars.multi.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Board {
|
||||
fn default() -> Board {
|
||||
Board::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Bars {
|
||||
/// The bar for `key` in `run`, added with `label` (after the run's) if there isn't one.
|
||||
fn bar(&mut self, run: &Run, key: Key, label: String) -> ProgressBar {
|
||||
if let Some(bar) = self.bars.iter().find(|b| b.run == *run && b.key == key) {
|
||||
return bar.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);
|
||||
let label = printable(&match run {
|
||||
Some(run) => format!("{run} {label}"),
|
||||
None => label,
|
||||
});
|
||||
self.bars.push(Bar { run: run.clone(), key, label, bar: bar.clone() });
|
||||
self.align();
|
||||
bar
|
||||
}
|
||||
|
||||
fn remove(&mut self, run: &Run, key: &Key) {
|
||||
if let Some(index) = self.bars.iter().position(|b| b.run == *run && b.key == *key) {
|
||||
let bar = self.bars.remove(index).bar;
|
||||
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(|b| b.label.chars().count()).max().unwrap_or(0);
|
||||
for bar in &self.bars {
|
||||
bar.bar.set_prefix(format!("{:width$}", bar.label));
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws on the terminal unless something hides the bars.
|
||||
fn retarget(&self) {
|
||||
let hidden = self.mid_line || self.paused;
|
||||
self.multi.set_draw_target(if hidden { ProgressDrawTarget::hidden() } else { (self.target)() });
|
||||
}
|
||||
|
||||
/// 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.mid_line = true;
|
||||
self.retarget();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.mid_line {
|
||||
// The line other output left unfinished, for what comes next
|
||||
eprintln!();
|
||||
self.mid_line = false;
|
||||
self.retarget();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(printable(&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(" · ")
|
||||
}
|
||||
|
||||
/// Boards on a terminal in memory, for tests.
|
||||
#[cfg(test)]
|
||||
pub(crate) mod testing {
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use indicatif::{InMemoryTerm, ProgressDrawTarget};
|
||||
|
||||
use super::{Board, TICK};
|
||||
|
||||
/// A board drawing on a terminal in memory, 80 columns wide, at most 20 times a second like
|
||||
/// on stderr.
|
||||
pub(crate) 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, without trailing spaces, once it's what `want` waits for or a few
|
||||
/// seconds have gone by: the bars tick on their own threads, which a busy box can hold up.
|
||||
pub(crate) fn screen(term: &InMemoryTerm, want: impl Fn(&[String]) -> bool) -> Vec<String> {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
std::thread::sleep(TICK);
|
||||
let lines: Vec<String> =
|
||||
term.contents().lines().map(|l| l.trim_end().to_owned()).filter(|l| !l.is_empty()).collect();
|
||||
if want(&lines) || Instant::now() > deadline {
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::testing::{on_screen, screen};
|
||||
use super::*;
|
||||
use crate::progress::{Count, Counts};
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
#[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].bar.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(|b| b.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].bar.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(&(None, 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));
|
||||
let copying = ["river ▕█████▏ ▏ copying · 1/4 paths · 2s"];
|
||||
assert_eq!(screen(&term, |l| l == copying), copying);
|
||||
|
||||
// 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));
|
||||
let comparing = ["slop: copied to river: 4 paths in 2s", "river ▕ ▏ comparing · 1s"];
|
||||
assert_eq!(screen(&term, |l| l == comparing), comparing);
|
||||
|
||||
// Compared, and waiting for the deploy's approval
|
||||
board.update(&phase(Phase::Compare("river".into()), State::Done));
|
||||
let ready = "river ▕████████████████████▏ ready";
|
||||
let lines = screen(&term, |l| l.get(2).is_some_and(|l| l == ready));
|
||||
assert_eq!(lines.get(2).map(String::as_str), Some(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));
|
||||
let activated = "slop: activated river in 1s";
|
||||
let lines = screen(&term, |l| l.last().is_some_and(|l| l == activated));
|
||||
assert_eq!(lines.last().map(String::as_str), Some(activated));
|
||||
}
|
||||
#[test]
|
||||
fn draws_several_runs() {
|
||||
let (mut board, term) = on_screen();
|
||||
let phase = |phase, state| Progress { phase, state, elapsed: 1, counts: Counts::default() };
|
||||
|
||||
board.update_run(Some("a1b2c3"), &phase(Phase::Build, State::Running));
|
||||
board.update_run(Some("d4e5f6"), &phase(Phase::Copy("river".into()), State::Running));
|
||||
let both = ["a1b2c3 building ▕ ▏ 1s", "d4e5f6 river ▕ ▏ copying · 1s"];
|
||||
assert_eq!(screen(&term, |l| l == both), both);
|
||||
|
||||
// Requests' text comes from agents, so control characters don't reach the terminal.
|
||||
board.update_run(Some("d4e5f6"), &phase(Phase::Copy("x\x1b[2J".into()), State::Running));
|
||||
let label = board.bars.as_ref().unwrap().bars[2].bar.prefix();
|
||||
assert_eq!(label.trim_end(), "d4e5f6 x\u{fffd}[2J");
|
||||
board.end_run("d4e5f6");
|
||||
|
||||
// A run's lines say which it is, and its bars go when it ends.
|
||||
board.update_run(Some("a1b2c3"), &phase(Phase::Build, State::Done));
|
||||
assert_eq!(screen(&term, |l| l.len() == 1), ["a1b2c3: built in 1s"]);
|
||||
|
||||
// Paused, nothing is drawn until it resumes.
|
||||
board.update_run(Some("a1b2c3"), &phase(Phase::Push, State::Running));
|
||||
board.pause();
|
||||
assert_eq!(screen(&term, |l| l.len() == 1), ["a1b2c3: built in 1s"]);
|
||||
board.resume();
|
||||
let pushing = ["a1b2c3: built in 1s", "a1b2c3 pushing to the cache ▕ ▏ 1s"];
|
||||
assert_eq!(screen(&term, |l| l == pushing), pushing);
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,20 @@ validated_string!(
|
||||
}
|
||||
);
|
||||
|
||||
validated_string!(
|
||||
/// A container's machine name (as `machinectl` lists it), such as a deploy-rs node's
|
||||
/// `container-<name>` profile names.
|
||||
ContainerName,
|
||||
"container name",
|
||||
|s| {
|
||||
let b = s.as_bytes();
|
||||
!b.is_empty()
|
||||
&& b.len() <= 64
|
||||
&& b[0].is_ascii_alphanumeric()
|
||||
&& b.iter().all(|&c| c.is_ascii_alphanumeric() || b"_.-".contains(&c))
|
||||
}
|
||||
);
|
||||
|
||||
validated_string!(
|
||||
/// A remote login name.
|
||||
UserName,
|
||||
|
||||
+43
-26
@@ -18,36 +18,48 @@ function formatLeft(seconds) {
|
||||
return `${seconds}s`;
|
||||
}
|
||||
|
||||
setInterval(() => {
|
||||
function showCountdowns() {
|
||||
for (const element of document.querySelectorAll(".expires[data-until]")) {
|
||||
const seconds = Math.max(0, Math.round((Number(element.dataset.until) - Date.now()) / 1000));
|
||||
element.textContent = seconds > 0 ? `expires in ${formatLeft(seconds)}` : "expired";
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
// Polls for changes to the pending set while the page is visible.
|
||||
async function refresh() {
|
||||
const pending = document.getElementById("pending");
|
||||
setInterval(showCountdowns, 1000);
|
||||
|
||||
// Follows the broker's events for this page. Each `morph` event is a region of the page, a whole
|
||||
// element with its `id`, which is morphed into the one here (with idiomorph) rather than replacing
|
||||
// it, so open details, the focus and what's being typed stay.
|
||||
function listen() {
|
||||
const request = document.getElementById("request");
|
||||
const container = pending || request;
|
||||
if (!container || document.hidden) return;
|
||||
if ((!document.getElementById("pending") && !request) || !("EventSource" in window)) return;
|
||||
|
||||
const response = await fetch("/api/version", { credentials: "same-origin" });
|
||||
if (response.status === 401) return location.reload();
|
||||
if (!response.ok) return;
|
||||
const { version } = await response.json();
|
||||
if (String(version) === container.dataset.version) return;
|
||||
const path = request ? `/events?request=${encodeURIComponent(request.dataset.id)}` : "/events";
|
||||
const source = new EventSource(path);
|
||||
source.addEventListener("morph", (event) => {
|
||||
const template = document.createElement("template");
|
||||
template.innerHTML = event.data;
|
||||
for (const region of template.content.children) {
|
||||
const current = document.getElementById(region.id);
|
||||
if (!current) continue;
|
||||
Idiomorph.morph(current, region, { ignoreActiveValue: true, callbacks: { beforeAttributeUpdated: keepOpen } });
|
||||
ready(document.getElementById(region.id));
|
||||
}
|
||||
});
|
||||
// Signed out: reloading leads to signing in again.
|
||||
source.addEventListener("signed-out", () => {
|
||||
source.close();
|
||||
location.reload();
|
||||
});
|
||||
// The browser reconnects by itself, unless the broker refused; then start again later.
|
||||
source.addEventListener("error", () => {
|
||||
if (source.readyState === EventSource.CLOSED) setTimeout(() => location.reload(), 30000);
|
||||
});
|
||||
}
|
||||
|
||||
if (request) return location.reload();
|
||||
|
||||
// Swap in the new list, keeping open details open.
|
||||
const open = new Set([...pending.querySelectorAll("article details[open]")].map((d) => d.closest("article").id));
|
||||
const fragment = await fetch("/pending", { credentials: "same-origin" });
|
||||
if (!fragment.ok) return;
|
||||
pending.innerHTML = await fragment.text();
|
||||
pending.dataset.version = String(version);
|
||||
for (const id of open) document.getElementById(id)?.querySelector("details")?.setAttribute("open", "");
|
||||
startCountdowns(pending);
|
||||
// Whether a details element stays open or closed is the approver's.
|
||||
function keepOpen(attribute, element) {
|
||||
return !(attribute === "open" && element.tagName === "DETAILS");
|
||||
}
|
||||
|
||||
function base64urlToBytes(text) {
|
||||
@@ -128,8 +140,13 @@ function localTimes(root) {
|
||||
}
|
||||
}
|
||||
|
||||
localTimes(document);
|
||||
startCountdowns(document);
|
||||
setInterval(() => refresh().catch(() => {}), 3000);
|
||||
document.addEventListener("visibilitychange", () => refresh().catch(() => {}));
|
||||
// What rendered times need, for the page or a region of it
|
||||
function ready(root) {
|
||||
localTimes(root);
|
||||
startCountdowns(root);
|
||||
showCountdowns();
|
||||
}
|
||||
|
||||
ready(document);
|
||||
listen();
|
||||
setUpPush().catch(() => {});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -68,10 +68,23 @@ header {
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
/* Without sign-in (the demo and tests), on every page */
|
||||
.no-sign-in {
|
||||
margin: 0;
|
||||
padding: 6px 16px;
|
||||
background: var(--bad-bg);
|
||||
color: var(--bad);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
nav a {
|
||||
margin-right: 16px;
|
||||
}
|
||||
|
||||
.account .version {
|
||||
font-size: 0.875em;
|
||||
}
|
||||
|
||||
main {
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
@@ -470,3 +483,127 @@ 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%;
|
||||
}
|
||||
|
||||
/* The other columns keep to one line rather than wrapping to make room. */
|
||||
table.nodes th,
|
||||
table.nodes td:not(.copy) {
|
||||
overflow-wrap: normal;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
#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);
|
||||
}
|
||||
+7
-5
@@ -16,7 +16,7 @@ use openidconnect::{
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::config::WebConfig;
|
||||
use crate::config::OidcConfig;
|
||||
use crate::queue::Decision;
|
||||
|
||||
/// The `groups` claim, which providers such as Pocket ID add for the `groups` scope.
|
||||
@@ -102,7 +102,9 @@ pub struct Identity {
|
||||
}
|
||||
|
||||
pub struct Oidc {
|
||||
config: WebConfig,
|
||||
config: OidcConfig,
|
||||
/// The web app's URL, for the provider to send approvers back to.
|
||||
url: String,
|
||||
secret: String,
|
||||
http: reqwest::Client,
|
||||
client: tokio::sync::Mutex<Option<(Instant, Client)>>,
|
||||
@@ -113,13 +115,13 @@ pub fn now() -> i64 {
|
||||
}
|
||||
|
||||
impl Oidc {
|
||||
pub fn new(config: WebConfig, secret: String) -> Result<Oidc> {
|
||||
pub fn new(config: OidcConfig, url: String, secret: String) -> Result<Oidc> {
|
||||
// Following redirects would let the provider's metadata send requests anywhere.
|
||||
let http = reqwest::ClientBuilder::new()
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.timeout(Duration::from_secs(10))
|
||||
.build()?;
|
||||
Ok(Oidc { config, secret, http, client: tokio::sync::Mutex::new(None) })
|
||||
Ok(Oidc { config, url, secret, http, client: tokio::sync::Mutex::new(None) })
|
||||
}
|
||||
|
||||
/// The client, discovering the provider when it isn't known yet or is due for a refresh. A
|
||||
@@ -147,7 +149,7 @@ impl Oidc {
|
||||
async fn discover(&self) -> Result<Client> {
|
||||
let issuer = IssuerUrl::new(self.config.issuer.clone())?;
|
||||
let metadata = CoreProviderMetadata::discover_async(issuer, &self.http).await?;
|
||||
let redirect = RedirectUrl::new(format!("{}/auth/callback", self.config.url.trim_end_matches('/')))?;
|
||||
let redirect = RedirectUrl::new(format!("{}/auth/callback", self.url.trim_end_matches('/')))?;
|
||||
|
||||
Ok(Client::from_provider_metadata(
|
||||
metadata,
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
//! Keeps open pages current with one stream of Server-Sent Events each.
|
||||
//!
|
||||
//! - 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
|
||||
//! 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;
|
||||
use std::sync::Arc;
|
||||
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;
|
||||
|
||||
/// How often a page gets updates at most.
|
||||
const INTERVAL: Duration = Duration::from_secs(1);
|
||||
|
||||
/// The signed-in approver's CSRF token, or `None` once they've signed out.
|
||||
type SignedIn = Box<dyn FnMut() -> Pin<Box<dyn Future<Output = Option<String>> + Send>> + Send>;
|
||||
|
||||
pub fn stream(broker: Arc<Broker>, session: Session, request: Option<String>) -> Response {
|
||||
let signed_in: SignedIn = Box::new(move || {
|
||||
let session = session.clone();
|
||||
Box::pin(async move { session.get::<User>(super::USER).await.ok().flatten().map(|user| user.csrf) })
|
||||
});
|
||||
let updates = Updates::new(broker, signed_in, request);
|
||||
|
||||
let events = futures_util::stream::unfold(updates, |mut updates| async move {
|
||||
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.
|
||||
response.headers_mut().insert("x-accel-buffering", axum::http::HeaderValue::from_static("no"));
|
||||
response
|
||||
}
|
||||
|
||||
struct Updates {
|
||||
broker: Arc<Broker>,
|
||||
signed_in: SignedIn,
|
||||
/// The request whose page it is, or none for the main page.
|
||||
request: Option<String>,
|
||||
queue: watch::Receiver<u64>,
|
||||
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, 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 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 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 {
|
||||
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(vec![("signed-out", "signed out".into())]);
|
||||
};
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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))]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use super::*;
|
||||
use crate::detail::Detail;
|
||||
use crate::progress::{Counts, Phase, Progress, State};
|
||||
use crate::queue::NewRequest;
|
||||
|
||||
fn broker() -> Arc<Broker> {
|
||||
let config = serde_json::from_value(serde_json::json!({
|
||||
"requesters": {},
|
||||
"policies": {},
|
||||
"approve_socket": "/unused",
|
||||
"approver_group": "root",
|
||||
}))
|
||||
.unwrap();
|
||||
Arc::new(Broker::new(config).unwrap())
|
||||
}
|
||||
|
||||
fn submit(broker: &Broker, id: &str) -> tokio::sync::oneshot::Receiver<crate::queue::Outcome> {
|
||||
let request = NewRequest {
|
||||
requester: "agent".into(),
|
||||
op: "ssh".into(),
|
||||
lease_key: "k".into(),
|
||||
summary: "ssh river".into(),
|
||||
detail: Detail::new(),
|
||||
label: None,
|
||||
sensitive: false,
|
||||
passkey: false,
|
||||
leases: vec![300],
|
||||
};
|
||||
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_regions_as_they_change() {
|
||||
let broker = broker();
|
||||
let signed_out = Arc::new(AtomicBool::new(false));
|
||||
let check = signed_out.clone();
|
||||
let signed_in: SignedIn = Box::new(move || {
|
||||
let out = check.load(Ordering::SeqCst);
|
||||
Box::pin(async move { (!out).then(|| "token".to_owned()) })
|
||||
});
|
||||
let mut updates = Updates::new(broker.clone(), signed_in, None);
|
||||
|
||||
// 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 changes only the pending list, and its leaving too
|
||||
let _reply = submit(&broker, "abc");
|
||||
let events = updates.next().await.unwrap();
|
||||
assert!(events.len() == 1 && events[0].1.contains("ssh river"), "{events:?}");
|
||||
broker.queue.cancel("abc");
|
||||
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, "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_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 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 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);
|
||||
}
|
||||
|
||||
+110
-53
@@ -2,6 +2,7 @@
|
||||
//! for approvers signed in through an OpenID Connect provider, plus Web Push notifications. It
|
||||
//! sits behind a reverse proxy, which is the only thing that should reach its listener.
|
||||
mod auth;
|
||||
mod events;
|
||||
mod history;
|
||||
mod page;
|
||||
mod push;
|
||||
@@ -22,7 +23,7 @@ use tower_sessions::{ExpiredDeletion, Expiry, Session, SessionManagerLayer};
|
||||
use tower_sessions_rusqlite_store::{RusqliteStore, tokio_rusqlite};
|
||||
|
||||
use crate::approve;
|
||||
use crate::config::WebConfig;
|
||||
use crate::config::{SignIn, WebConfig};
|
||||
use crate::queue::{Decision, PendingInfo};
|
||||
use crate::server::Broker;
|
||||
use auth::{Flow, Oidc, Purpose};
|
||||
@@ -33,10 +34,18 @@ struct Web {
|
||||
broker: Arc<Broker>,
|
||||
/// The app's origin, which every POST must come from.
|
||||
origin: String,
|
||||
oidc: Oidc,
|
||||
approvers: Approvers,
|
||||
push: Arc<Push>,
|
||||
}
|
||||
|
||||
/// Who approvers are.
|
||||
enum Approvers {
|
||||
/// Whoever signs in through the provider.
|
||||
Oidc(Box<Oidc>),
|
||||
/// Everyone who reaches the app, as this name (`no_sign_in`).
|
||||
Fixed(String),
|
||||
}
|
||||
|
||||
/// The signed-in approver, kept in the session.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct User {
|
||||
@@ -58,9 +67,20 @@ fn origin(url: &str) -> Result<String> {
|
||||
Ok(url.origin().ascii_serialization())
|
||||
}
|
||||
|
||||
pub async fn run(broker: Arc<Broker>, config: WebConfig, secret: String) -> Result<()> {
|
||||
/// Serves the web app. `secret` is the OIDC client's, when approvers sign in.
|
||||
pub async fn run(broker: Arc<Broker>, config: WebConfig, secret: Option<String>) -> Result<()> {
|
||||
let origin = origin(&config.url)?;
|
||||
let issuer = url::Url::parse(&config.issuer)?.origin().ascii_serialization();
|
||||
let (approvers, issuer) = match config.sign_in.clone() {
|
||||
SignIn::Oidc(oidc) => {
|
||||
let issuer = url::Url::parse(&oidc.issuer)?.origin().ascii_serialization();
|
||||
let secret = secret.context("no OIDC client secret")?;
|
||||
(Approvers::Oidc(Box::new(Oidc::new(oidc, config.url.clone(), secret)?)), issuer)
|
||||
}
|
||||
SignIn::None { approver } => {
|
||||
page::set_no_sign_in();
|
||||
(Approvers::Fixed(approver), String::new())
|
||||
}
|
||||
};
|
||||
// Sessions outlive the broker restarting, so signing in on a phone lasts.
|
||||
let database = tokio_rusqlite::Connection::open(config.state_dir.join("sessions.sqlite")).await?;
|
||||
let store = RusqliteStore::new(database);
|
||||
@@ -76,15 +96,14 @@ pub async fn run(broker: Arc<Broker>, config: WebConfig, secret: String) -> Resu
|
||||
.with_http_only(true)
|
||||
.with_expiry(Expiry::OnInactivity(Duration::seconds(config.session as i64)));
|
||||
|
||||
let web = Arc::new(Web { oidc: Oidc::new(config.clone(), secret)?, broker: broker.clone(), origin, push });
|
||||
let web = Arc::new(Web { approvers, broker: broker.clone(), origin, push });
|
||||
tokio::spawn(web.push.clone().run(broker));
|
||||
|
||||
let app = Router::new()
|
||||
.route("/", get(index))
|
||||
.route("/pending", get(pending_fragment))
|
||||
.route("/requests/{id}", get(request_page).post(answer))
|
||||
.route("/log", get(log_page))
|
||||
.route("/api/version", get(version))
|
||||
.route("/events", get(page_events))
|
||||
.route("/api/csrf", get(csrf))
|
||||
.route("/push/key", get(push_key))
|
||||
.route("/push/subscribe", post(subscribe))
|
||||
@@ -94,6 +113,7 @@ pub async fn run(broker: Arc<Broker>, config: WebConfig, secret: String) -> Resu
|
||||
.route("/auth/logout", post(logout))
|
||||
.route("/signed-out", get(signed_out))
|
||||
.route("/app.js", get(|| async { page::asset("text/javascript", include_str!("assets/app.js")) }))
|
||||
.route("/idiomorph.js", get(|| async { page::asset("text/javascript", include_str!("assets/idiomorph.js")) }))
|
||||
.route("/sw.js", get(|| async { page::asset("text/javascript", include_str!("assets/sw.js")) }))
|
||||
.route("/style.css", get(|| async { page::asset("text/css", include_str!("assets/style.css")) }))
|
||||
.route("/icon.svg", get(|| async { page::asset("image/svg+xml", include_str!("assets/icon.svg")) }))
|
||||
@@ -147,21 +167,41 @@ fn failure(status: StatusCode, message: &str) -> Failure {
|
||||
Failure(status, message.to_owned())
|
||||
}
|
||||
|
||||
async fn user(session: &Session) -> Result<Option<User>, Failure> {
|
||||
Ok(session.get::<User>(USER).await?)
|
||||
/// The signed-in approver. Without sign-in, every session is the configured approver.
|
||||
async fn user(web: &Web, session: &Session) -> Result<Option<User>, Failure> {
|
||||
if let Some(user) = session.get::<User>(USER).await? {
|
||||
return Ok(Some(user));
|
||||
}
|
||||
let Approvers::Fixed(name) = &web.approvers else { return Ok(None) };
|
||||
|
||||
let user = User { subject: format!("no-sign-in:{name}"), name: name.clone(), csrf: new_csrf() };
|
||||
session.insert(USER, user.clone()).await?;
|
||||
Ok(Some(user))
|
||||
}
|
||||
|
||||
fn new_csrf() -> String {
|
||||
hex::encode(rand::random::<[u8; 32]>())
|
||||
}
|
||||
|
||||
/// The provider approvers sign in with, if they do.
|
||||
fn oidc(web: &Web) -> Result<&Oidc, Failure> {
|
||||
match &web.approvers {
|
||||
Approvers::Oidc(oidc) => Ok(oidc),
|
||||
Approvers::Fixed(_) => Err(failure(StatusCode::NOT_FOUND, "this web app has no sign-in")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The signed-in approver, or a redirect to sign in and come back to `here`.
|
||||
async fn signed_in(session: &Session, here: &str) -> Result<Result<User, Response>, Failure> {
|
||||
Ok(match user(session).await? {
|
||||
async fn signed_in(web: &Web, session: &Session, here: &str) -> Result<Result<User, Response>, Failure> {
|
||||
Ok(match user(web, session).await? {
|
||||
Some(user) => Ok(user),
|
||||
None => Err(Redirect::to(&format!("/auth/login?next={}", urlencode(here))).into_response()),
|
||||
})
|
||||
}
|
||||
|
||||
/// The signed-in approver, for API calls, which can't follow a sign-in.
|
||||
async fn api_user(session: &Session) -> Result<User, Failure> {
|
||||
user(session).await?.ok_or_else(|| failure(StatusCode::UNAUTHORIZED, "sign in first"))
|
||||
async fn api_user(web: &Web, session: &Session) -> Result<User, Failure> {
|
||||
user(web, session).await?.ok_or_else(|| failure(StatusCode::UNAUTHORIZED, "sign in first"))
|
||||
}
|
||||
|
||||
/// Checks a POST came from the app itself: the browser's `Origin` and the session's token.
|
||||
@@ -188,8 +228,13 @@ fn fingerprint(entry: &PendingInfo) -> String {
|
||||
hex::encode(hash.finalize())
|
||||
}
|
||||
|
||||
fn approver(user: &User, passkey: bool) -> String {
|
||||
if passkey { format!("{} (web, passkey)", user.name) } else { format!("{} (web)", user.name) }
|
||||
/// The approver as the audit log names them, like `dev (web, passkey)`.
|
||||
fn approver(web: &Web, user: &User, passkey: bool) -> String {
|
||||
match (&web.approvers, passkey) {
|
||||
(Approvers::Fixed(_), _) => format!("{} (web, no sign-in)", user.name),
|
||||
(_, true) => format!("{} (web, passkey)", user.name),
|
||||
(_, false) => format!("{} (web)", user.name),
|
||||
}
|
||||
}
|
||||
|
||||
fn pending(web: &Web, id: &str) -> Option<PendingInfo> {
|
||||
@@ -197,21 +242,14 @@ fn pending(web: &Web, id: &str) -> Option<PendingInfo> {
|
||||
}
|
||||
|
||||
async fn index(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
|
||||
let user = match signed_in(&session, "/").await? {
|
||||
let user = match signed_in(&web, &session, "/").await? {
|
||||
Ok(user) => user,
|
||||
Err(redirect) => return Ok(redirect),
|
||||
};
|
||||
|
||||
let entries = web.broker.queue.list();
|
||||
let leases = web.broker.queue.all_leases();
|
||||
Ok(page::index(&user.name, &user.csrf, &entries, &leases, web.broker.queue.version()).into_response())
|
||||
}
|
||||
|
||||
async fn pending_fragment(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
|
||||
let user = api_user(&session).await?;
|
||||
let entries = web.broker.queue.list();
|
||||
let leases = web.broker.queue.all_leases();
|
||||
Ok(page::pending(&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(
|
||||
@@ -219,18 +257,36 @@ async fn request_page(
|
||||
session: Session,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Response, Failure> {
|
||||
let user = match signed_in(&session, &format!("/requests/{id}")).await? {
|
||||
let user = match signed_in(&web, &session, &format!("/requests/{id}")).await? {
|
||||
Ok(user) => user,
|
||||
Err(redirect) => return Ok(redirect),
|
||||
};
|
||||
// The log may be missing or unreadable; the request itself still shows.
|
||||
let past = web.broker.audit.tail(LOG_RECORDS).ok().and_then(|records| {
|
||||
let (histories, _) = history::gather(records);
|
||||
histories.into_iter().find(|h| h.id == id)
|
||||
});
|
||||
let current = pending(&web, &id);
|
||||
Ok(page::request(&user.name, &user.csrf, &id, current.as_ref(), past.as_ref(), web.broker.queue.version())
|
||||
.into_response())
|
||||
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())
|
||||
}
|
||||
|
||||
/// What the audit log has of a request. The log may be missing or unreadable; the request itself
|
||||
/// still shows.
|
||||
fn past(broker: &Broker, id: &str) -> Option<History> {
|
||||
let records = broker.audit.tail(LOG_RECORDS).ok()?;
|
||||
let (histories, _) = history::gather(records);
|
||||
histories.into_iter().find(|h| h.id == id)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct EventsQuery {
|
||||
request: Option<String>,
|
||||
}
|
||||
|
||||
/// The page's stream of updates (see [`events`]): the main page's, or a request's.
|
||||
async fn page_events(
|
||||
State(web): State<Arc<Web>>,
|
||||
session: Session,
|
||||
Query(query): Query<EventsQuery>,
|
||||
) -> Result<Response, Failure> {
|
||||
api_user(&web, &session).await?;
|
||||
Ok(events::stream(web.broker.clone(), session, query.request))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -248,7 +304,7 @@ async fn answer(
|
||||
Path(id): Path<String>,
|
||||
axum::Form(form): axum::Form<AnswerForm>,
|
||||
) -> Result<Response, Failure> {
|
||||
let user = api_user(&session).await?;
|
||||
let user = api_user(&web, &session).await?;
|
||||
check_post(&web, &headers, &user, form.csrf.as_deref())?;
|
||||
// Scripts send the token as a header and want a status rather than a page.
|
||||
let script = headers.contains_key("x-csrf-token");
|
||||
@@ -260,6 +316,12 @@ async fn answer(
|
||||
}
|
||||
|
||||
if entry.passkey && decision != Decision::Deny {
|
||||
if let Approvers::Fixed(_) = web.approvers {
|
||||
return Err(failure(
|
||||
StatusCode::FORBIDDEN,
|
||||
"this request needs a passkey, which needs a web app with sign-in",
|
||||
));
|
||||
}
|
||||
if script {
|
||||
return Err(failure(StatusCode::FORBIDDEN, "this request needs a passkey; open it to approve"));
|
||||
}
|
||||
@@ -267,7 +329,7 @@ async fn answer(
|
||||
return start(&web, &session, purpose).await;
|
||||
}
|
||||
|
||||
approve::approve(&web.broker, &id, decision, &approver(&user, false), false)
|
||||
approve::approve(&web.broker, &id, decision, &approver(&web, &user, false), false)
|
||||
.map_err(|e| failure(StatusCode::CONFLICT, &format!("{e:#}")))?;
|
||||
Ok(if script { StatusCode::NO_CONTENT.into_response() } else { Redirect::to("/").into_response() })
|
||||
}
|
||||
@@ -283,7 +345,7 @@ async fn log_page(
|
||||
session: Session,
|
||||
Query(filters): Query<page::Filters>,
|
||||
) -> Result<Response, Failure> {
|
||||
let user = match signed_in(&session, "/log").await? {
|
||||
let user = match signed_in(&web, &session, "/log").await? {
|
||||
Ok(user) => user,
|
||||
Err(redirect) => return Ok(redirect),
|
||||
};
|
||||
@@ -310,18 +372,13 @@ async fn log_page(
|
||||
Ok(page::log(&user.name, &user.csrf, &view).into_response())
|
||||
}
|
||||
|
||||
async fn version(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
|
||||
api_user(&session).await?;
|
||||
Ok(axum::Json(serde_json::json!({ "version": web.broker.queue.version() })).into_response())
|
||||
}
|
||||
|
||||
async fn csrf(session: Session) -> Result<Response, Failure> {
|
||||
let user = api_user(&session).await?;
|
||||
async fn csrf(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
|
||||
let user = api_user(&web, &session).await?;
|
||||
Ok(axum::Json(serde_json::json!({ "csrf": user.csrf })).into_response())
|
||||
}
|
||||
|
||||
async fn push_key(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
|
||||
api_user(&session).await?;
|
||||
api_user(&web, &session).await?;
|
||||
Ok(web.push.public_key().to_owned().into_response())
|
||||
}
|
||||
|
||||
@@ -344,7 +401,7 @@ async fn subscribe(
|
||||
headers: HeaderMap,
|
||||
axum::Json(subscription): axum::Json<BrowserSubscription>,
|
||||
) -> Result<Response, Failure> {
|
||||
let user = api_user(&session).await?;
|
||||
let user = api_user(&web, &session).await?;
|
||||
check_post(&web, &headers, &user, None)?;
|
||||
|
||||
let subscription = Subscription {
|
||||
@@ -375,7 +432,7 @@ async fn unsubscribe(
|
||||
headers: HeaderMap,
|
||||
axum::Json(request): axum::Json<Unsubscription>,
|
||||
) -> Result<Response, Failure> {
|
||||
let user = api_user(&session).await?;
|
||||
let user = api_user(&web, &session).await?;
|
||||
check_post(&web, &headers, &user, None)?;
|
||||
web.push.unsubscribe(&request.endpoint, &user.subject)?;
|
||||
Ok(StatusCode::NO_CONTENT.into_response())
|
||||
@@ -383,7 +440,7 @@ async fn unsubscribe(
|
||||
|
||||
/// Sends the approver to the sign-in provider, remembering why.
|
||||
async fn start(web: &Web, session: &Session, purpose: Purpose) -> Result<Response, Failure> {
|
||||
let (url, flow) = web.oidc.begin(purpose).await?;
|
||||
let (url, flow) = oidc(web)?.begin(purpose).await?;
|
||||
|
||||
let mut flows = session.get::<Vec<Flow>>(FLOWS).await?.unwrap_or_default();
|
||||
flows.retain(|f| auth::now() - f.started < auth::FLOW_LIFETIME as i64);
|
||||
@@ -437,7 +494,8 @@ async fn callback(
|
||||
return Err(Failure(StatusCode::FORBIDDEN, format!("the sign-in provider refused: {error} {description}")));
|
||||
}
|
||||
let code = query.code.ok_or_else(|| failure(StatusCode::BAD_REQUEST, "the sign-in provider sent no code"))?;
|
||||
let identity = web.oidc.finish(&flow, code).await.map_err(|e| Failure(StatusCode::FORBIDDEN, format!("{e:#}")))?;
|
||||
let identity =
|
||||
oidc(&web)?.finish(&flow, code).await.map_err(|e| Failure(StatusCode::FORBIDDEN, format!("{e:#}")))?;
|
||||
|
||||
match flow.purpose {
|
||||
Purpose::SignIn { ref next } => {
|
||||
@@ -445,12 +503,11 @@ async fn callback(
|
||||
|
||||
// A new session ID, so one planted before signing in is useless.
|
||||
session.cycle_id().await?;
|
||||
let csrf = hex::encode(rand::random::<[u8; 32]>());
|
||||
session.insert(USER, User { subject: identity.subject, name: identity.name, csrf }).await?;
|
||||
session.insert(USER, User { subject: identity.subject, name: identity.name, csrf: new_csrf() }).await?;
|
||||
Ok(Redirect::to(next).into_response())
|
||||
}
|
||||
Purpose::Confirm { ref id, decision, ref shown } => {
|
||||
let user = api_user(&session).await?;
|
||||
let user = api_user(&web, &session).await?;
|
||||
auth::confirmed(&flow, &identity, &user.subject)
|
||||
.map_err(|e| Failure(StatusCode::FORBIDDEN, format!("{e:#}")))?;
|
||||
|
||||
@@ -460,7 +517,7 @@ async fn callback(
|
||||
return Err(failure(StatusCode::CONFLICT, "this request changed since you answered it; look again"));
|
||||
}
|
||||
|
||||
approve::approve(&web.broker, id, decision, &approver(&user, true), true)
|
||||
approve::approve(&web.broker, id, decision, &approver(&web, &user, true), true)
|
||||
.map_err(|e| failure(StatusCode::CONFLICT, &format!("{e:#}")))?;
|
||||
Ok(Redirect::to("/").into_response())
|
||||
}
|
||||
@@ -478,7 +535,7 @@ async fn logout(
|
||||
headers: HeaderMap,
|
||||
axum::Form(form): axum::Form<LogoutForm>,
|
||||
) -> Result<Response, Failure> {
|
||||
if let Some(user) = user(&session).await? {
|
||||
if let Some(user) = session.get::<User>(USER).await? {
|
||||
check_post(&web, &headers, &user, form.csrf.as_deref())?;
|
||||
}
|
||||
session.flush().await?;
|
||||
|
||||
+129
-35
@@ -11,7 +11,23 @@ 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;
|
||||
|
||||
/// Whether the web app runs without sign-in, which every page says.
|
||||
static NO_SIGN_IN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
pub fn set_no_sign_in() {
|
||||
NO_SIGN_IN.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn no_sign_in() -> bool {
|
||||
NO_SIGN_IN.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// HTML escaping, after replacing what [`printable`] replaces.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -32,15 +48,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
|
||||
}
|
||||
@@ -67,6 +74,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)
|
||||
}
|
||||
@@ -82,7 +107,7 @@ pub fn message(title: &str, text: &str) -> Html<String> {
|
||||
render(Message { title, text })
|
||||
}
|
||||
|
||||
/// The pending requests and leases, which the page script swaps in when they change.
|
||||
/// The pending requests and leases: the main page's region that the page script keeps current.
|
||||
#[derive(Template)]
|
||||
#[template(path = "pending.html")]
|
||||
struct Pending<'a> {
|
||||
@@ -91,8 +116,8 @@ struct Pending<'a> {
|
||||
leases: &'a [(String, String, u64)],
|
||||
}
|
||||
|
||||
pub fn pending(csrf: &str, entries: &[PendingInfo], leases: &[(String, String, u64)]) -> Html<String> {
|
||||
render(Pending { csrf, entries, leases })
|
||||
pub fn pending(csrf: &str, entries: &[PendingInfo], leases: &[(String, String, u64)]) -> String {
|
||||
render(Pending { csrf, entries, leases }).0
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
@@ -102,7 +127,7 @@ struct Index<'a> {
|
||||
csrf: &'a str,
|
||||
entries: &'a [PendingInfo],
|
||||
leases: &'a [(String, String, u64)],
|
||||
version: u64,
|
||||
runs: &'a [Run],
|
||||
}
|
||||
|
||||
pub fn index(
|
||||
@@ -110,9 +135,41 @@ pub fn index(
|
||||
csrf: &str,
|
||||
entries: &[PendingInfo],
|
||||
leases: &[(String, String, u64)],
|
||||
version: u64,
|
||||
runs: &[Run],
|
||||
) -> Html<String> {
|
||||
render(Index { name, csrf, entries, leases, version })
|
||||
render(Index { name, csrf, entries, leases, runs })
|
||||
}
|
||||
|
||||
/// 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.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)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
@@ -120,26 +177,23 @@ pub fn index(
|
||||
struct Request<'a> {
|
||||
name: &'a str,
|
||||
csrf: &'a str,
|
||||
heading: String,
|
||||
entry: Option<&'a PendingInfo>,
|
||||
past: Option<&'a History>,
|
||||
version: u64,
|
||||
view: &'a RequestView<'a>,
|
||||
}
|
||||
|
||||
pub fn request(
|
||||
name: &str,
|
||||
csrf: &str,
|
||||
id: &str,
|
||||
entry: Option<&PendingInfo>,
|
||||
past: Option<&History>,
|
||||
version: u64,
|
||||
) -> Html<String> {
|
||||
let heading = match (entry, past) {
|
||||
(Some(entry), _) => entry.summary.clone(),
|
||||
(None, Some(past)) if !past.summary.is_empty() => past.summary.clone(),
|
||||
_ => format!("Request {}", short(id)),
|
||||
};
|
||||
render(Request { name, csrf, heading, entry, past, version })
|
||||
pub fn request(name: &str, csrf: &str, view: &RequestView) -> Html<String> {
|
||||
render(Request { name, csrf, view })
|
||||
}
|
||||
|
||||
/// A request's page without the rest: the region that the page script keeps current.
|
||||
#[derive(Template)]
|
||||
#[template(path = "request_region.html")]
|
||||
struct RequestRegion<'a> {
|
||||
csrf: &'a str,
|
||||
view: &'a RequestView<'a>,
|
||||
}
|
||||
|
||||
pub fn request_region(csrf: &str, view: &RequestView) -> String {
|
||||
render(RequestRegion { csrf, view }).0
|
||||
}
|
||||
|
||||
/// What the log page is filtered by.
|
||||
@@ -256,7 +310,8 @@ mod tests {
|
||||
offers: vec![Decision::Once, Decision::Lease(300), Decision::Deny],
|
||||
expires_in: 125,
|
||||
};
|
||||
let html = pending("token", &[entry], &[]).0;
|
||||
let html = pending("token", &[entry], &[]);
|
||||
assert!(html.starts_with("<div id=\"pending\">") && html.trim_end().ends_with("</div>"), "{html}");
|
||||
assert!(html.contains(r#"value="5m""#));
|
||||
assert!(html.contains("For 5m"));
|
||||
assert!(html.contains("ssh river <x>"));
|
||||
@@ -296,9 +351,48 @@ mod tests {
|
||||
];
|
||||
let (histories, _) = super::history::gather(records);
|
||||
|
||||
let html = request("broker", "token", "abc", None, Some(&histories[0]), 0).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}");
|
||||
assert!(html.contains("<dt>Command</dt><dd class=\"neutral\"><code>uptime</code></dd>"), "{html}");
|
||||
assert!(html.contains("<span class=\"diff-add\">+a</span>"), "{html}");
|
||||
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}");
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
<link rel="stylesheet" href="/style.css">
|
||||
<link rel="manifest" href="/manifest.webmanifest">
|
||||
<link rel="icon" href="/icon.svg">
|
||||
<script src="/idiomorph.js" defer></script>
|
||||
<script src="/app.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
@@ -14,11 +15,17 @@
|
||||
<header>
|
||||
<nav><a href="/">Pending</a> <a href="/log">Log</a></nav>
|
||||
<form method="post" action="/auth/logout" class="account">
|
||||
<span class="version">slop-broker {{ crate::web::page::VERSION }}</span>
|
||||
<span>{{ name }}</span>
|
||||
{% if !crate::web::page::no_sign_in() -%}
|
||||
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||
<button type="submit" class="quiet">Sign out</button>
|
||||
{%- endif %}
|
||||
</form>
|
||||
</header>
|
||||
{% if crate::web::page::no_sign_in() -%}
|
||||
<p class="no-sign-in">No sign-in: everyone who reaches this app approves as {{ name }}. For the demo and tests only.</p>
|
||||
{%- endif %}
|
||||
{%- endblock %}
|
||||
<main>
|
||||
{% block main %}{% endblock %}
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
<section id="push" hidden>
|
||||
<p><span id="push-state"></span> <button type="button" id="push-toggle" class="quiet"></button></p>
|
||||
</section>
|
||||
<div id="pending" data-version="{{ version }}">
|
||||
{% include "pending.html" %}
|
||||
</div>
|
||||
{% 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 %}
|
||||
@@ -1,4 +1,5 @@
|
||||
{%- import "macros.html" as m -%}
|
||||
<div id="pending">
|
||||
{% if entries.is_empty() %}
|
||||
<p class="empty">Nothing is waiting for an answer.</p>
|
||||
{% endif %}
|
||||
@@ -9,7 +10,8 @@
|
||||
<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 %}
|
||||
</div>
|
||||
@@ -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 %}
|
||||
+1
-16
@@ -1,20 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% import "macros.html" as m %}
|
||||
{% block title %}Approval request{% endblock %}
|
||||
{% block main %}
|
||||
<h1>{{ heading }}</h1>
|
||||
<div id="request" data-version="{{ version }}">
|
||||
{% if let Some(entry) = entry %}
|
||||
{% call m::card(entry, csrf, true) %}{% endcall %}
|
||||
{% endif %}
|
||||
{% if let Some(past) = past %}
|
||||
{% if entry.is_none() %}
|
||||
<p class="meta">{{ past.requester }} · {{ past.op }} · {% call m::outcome(past.outcome) %}{% endcall %}</p>
|
||||
{% endif %}
|
||||
<h2>History</h2>
|
||||
{% call m::timeline(past.records.as_slice()) %}{% endcall %}
|
||||
{% else if entry.is_none() %}
|
||||
<p class="empty">The audit log has nothing about this request.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% include "request_region.html" %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,30 @@
|
||||
{%- import "macros.html" as m -%}
|
||||
<div id="request" data-id="{{ view.id }}">
|
||||
<h1>{{ view.heading() }}</h1>
|
||||
{% 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>
|
||||
{% endif %}
|
||||
<h2>History</h2>
|
||||
{% call m::timeline(past.records.as_slice()) %}{% endcall %}
|
||||
{% else if view.entry.is_none() %}
|
||||
<p class="empty">The audit log has nothing about this request.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
@@ -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>
|
||||
+78
-3
@@ -57,8 +57,14 @@ fn broker(directory: &Path, ops: serde_json::Value) -> Arc<Broker> {
|
||||
|
||||
// The main branch's nodes, as the builder would have found them
|
||||
let broker = Broker::new(config).unwrap();
|
||||
let river =
|
||||
Node { hostname: "river.example.org".into(), ssh_user: Some("deploy".into()), ssh_opts: vec![], sudo: None };
|
||||
let river = Node {
|
||||
hostname: "river.example.org".into(),
|
||||
ssh_user: Some("deploy".into()),
|
||||
ssh_opts: vec![],
|
||||
sudo: None,
|
||||
profiles: vec!["system".into(), "container-web".into()],
|
||||
ssh_hostnames: vec![],
|
||||
};
|
||||
broker.targets.assume(&broker.config, [("river".to_owned(), river)].into());
|
||||
Arc::new(broker)
|
||||
}
|
||||
@@ -168,6 +174,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")));
|
||||
@@ -182,6 +189,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);
|
||||
@@ -261,9 +269,13 @@ async fn stdin_that_cant_be_shown_is_refused() {
|
||||
}
|
||||
|
||||
async fn pending_id(client: &mut Client) -> String {
|
||||
pending_for(client, "ssh river").await
|
||||
}
|
||||
|
||||
async fn pending_for(client: &mut Client, expected: &str) -> String {
|
||||
match client.next(&mut String::new()).await {
|
||||
ServerMessage::Pending { id, summary } => {
|
||||
assert_eq!(summary, "ssh river");
|
||||
assert_eq!(summary, expected);
|
||||
// Then how long approvers have, so agents know how long to wait.
|
||||
let window = client.next(&mut String::new()).await;
|
||||
assert!(matches!(&window, ServerMessage::Info(m) if m.starts_with("approvers have ")), "{window:?}");
|
||||
@@ -362,6 +374,34 @@ async fn disconnecting_kills_the_process() {
|
||||
assert!(!alive, "process {pid} survived its requester");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stdin_an_operation_doesnt_read_doesnt_hide_a_disconnect() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } }));
|
||||
|
||||
let mut client = Client::start(&broker, ssh_with(&["true"], Some(b"block\n"))).await;
|
||||
client.next(&mut String::new()).await;
|
||||
for _ in 0..64 {
|
||||
client.send(ClientMessage::Stdin(b"ignored\n".to_vec())).await;
|
||||
}
|
||||
|
||||
let pid_file = directory.path().join("pid");
|
||||
let mut pid = None;
|
||||
for _ in 0..50 {
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
pid = std::fs::read_to_string(&pid_file).ok().and_then(|p| p.trim().parse::<i32>().ok());
|
||||
if pid.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let pid = pid.expect("fake ssh started");
|
||||
|
||||
drop(client);
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
let alive = kill(Pid::from_raw(pid), None).is_ok();
|
||||
assert!(!alive, "process {pid} survived its requester");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queries_run_a_fixed_quoted_command_without_stdin() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
@@ -387,6 +427,41 @@ async fn queries_run_a_fixed_quoted_command_without_stdin() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn containers_are_queried_through_their_host_and_must_be_known() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let broker = broker(
|
||||
directory.path(),
|
||||
json!({ "query": { "action": "auto", "rules": [
|
||||
{ "match": { "container": "*" }, "action": "ask" },
|
||||
] } }),
|
||||
);
|
||||
let container = |name: &str| Destination::Container { node: "river".parse().unwrap(), name: name.parse().unwrap() };
|
||||
|
||||
// Rules can tell container queries apart.
|
||||
let mut client =
|
||||
Client::start(&broker, Operation::Query { destination: container("web"), query: Query::Failed }).await;
|
||||
let id = pending_for(&mut client, "failed on river.container-web").await;
|
||||
assert_eq!(
|
||||
broker.queue.list()[0].detail.to_text(),
|
||||
"Command: sudo -u root systemctl --machine=web list-units --failed --no-pager"
|
||||
);
|
||||
|
||||
slop_broker::approve::approve(&broker, &id, Decision::Once, "test", false).unwrap();
|
||||
let mut output = String::new();
|
||||
client.next(&mut output).await;
|
||||
assert_eq!(client.next(&mut output).await, finished(3));
|
||||
assert!(
|
||||
output.contains("river.example.org sudo -u root systemctl --machine=web list-units --failed --no-pager"),
|
||||
"{output}"
|
||||
);
|
||||
|
||||
let mut client =
|
||||
Client::start(&broker, Operation::Query { destination: container("db"), query: Query::Failed }).await;
|
||||
let ServerMessage::Error(error) = client.next(&mut String::new()).await else { panic!() };
|
||||
assert!(error.contains("unknown container river.container-db"), "{error}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn requests_lists_pending_and_leases() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
|
||||
+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