deploy: Log how a deploy ends when its requester leaves
CI / Check (pull_request) Successful in 4m54s
CI / Check (push) Successful in 4m44s

A requester leaving cancelled the request, so the audit log said
"cancelled" while the activation it had started finished on the box.
Deploys now outlive their requester: the broker logs `detached`,
keeps waiting for the activations, and logs how they finished.

If the broker itself goes away, the activations still finish, and
their units are now named after the request ID
(`slop-deploy-<id>-<profile>`), so the audit record leads to their
journals.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit was merged in pull request #4.
This commit is contained in:
jackos1998andClaude Opus 5.5 committed 2026-11-25 10:39:34 +00:00
1 parent ebf22a932d
commit 7c577051ba
7 files changed
+123 -22

No files matched your search

+6 -1
View File
@@ -186,6 +186,9 @@ sections after this one describe each kind on its own.
`stdin` is set (`secret set`). `ssh` carries its stdin in the request instead.
- `ops::execute` runs the operation with `Io` (the stdin channel, the output sender and the
cancel token) and returns an exit status and an optional `OpResult`.
- If the requester leaves, most operations notice the cancel token and stop. Those
`ops::outlives_requester` names (deploys) ignore it: `see_through` logs `detached` and
keeps waiting, so the outcome is still audited.
7. **Finish.** One terminal message (`Finished`, `Denied`, `Expired` or `Error`), or none if the
requester went away, then the connection closes.
@@ -277,6 +280,7 @@ sequenceDiagram
through `systemd-run`. Each line of output is prefixed with `[node.profile]`; the exit status is
the first failure's. Inside the unit, `activate-rs`'s output goes through a `cat` that, once
the connection is gone, gives way to one discarding it, so a lost connection can't stop it.
Each unit is `slop-deploy-<request ID>-<profile>`.
### Builds
@@ -299,7 +303,8 @@ Built in: the requester's own pending requests and leases. Always allowed, and n
Every step is audited as an `audit::Event` carrying the request's ID (the same ID approvers see):
`request`, `prepared`, `approved` (with the approver's name), `decision`, `denied`, `expired`,
`finished`, `failed`, `disconnected`, plus `invalid` and `unknown` peers.
`finished`, `failed`, `disconnected` (cancelled), `detached` (the requester left an operation
that carries on), plus `invalid` and `unknown` peers.
## Protocol
+8 -1
View File
@@ -106,7 +106,9 @@ and `slop-approve`. How the code does it is in
3. its stdout and stderr;
4. a final message with the exit status and any structured result.
If the connection closes, the broker cancels the request or kills the process it started.
If the connection closes, the broker cancels the request or kills the process it started. A
deploy's activation is the exception: stopping it partway would leave boxes half changed, so
the broker waits for it and logs how it ended.
### Other requesters and approvers
@@ -400,6 +402,11 @@ broker runs it over SSH.
- Switching doesn't restart the broker (`restartIfChanged = false`), so it can deploy its own
box and report the result. A new version or configuration of the broker takes effect when
it's next restarted.
- **If the agent goes away,** the broker keeps waiting for the activations and logs their
outcome. The audit log says the requester left, then how the deploy finished.
- **If the broker goes away** (a crash, or its box rebooting), the activations still finish.
Their units are named `slop-deploy-<request ID>-<profile>`, so the audit record leads to
their journals on each node.
- Output comes back prefixed with the node.
- Deploys run in parallel; an agent that needs an order sends separate requests.
+8
View File
@@ -77,6 +77,11 @@ pub enum Event {
Disconnected {
id: String,
},
/// The requester left while an operation that can't be stopped partway (a deploy's
/// activation) ran; the broker still waits for it and logs how it ended.
Detached {
id: String,
},
Finished {
id: String,
exit: i32,
@@ -143,6 +148,9 @@ impl fmt::Display for Event {
Event::Denied { id, reason } => write!(f, "{} {reason}", short(id)),
Event::Expired { id } => write!(f, "{} expired without an answer", short(id)),
Event::Disconnected { id } => write!(f, "{} cancelled: the requester disconnected", short(id)),
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))
}
+15 -14
View File
@@ -13,6 +13,7 @@ use anyhow::{Context, Result, bail, ensure};
use futures_util::future::join_all;
use serde_json::json;
use tokio::process::Command;
use tokio_util::sync::CancellationToken;
use super::{Parsed, shell_quote, ssh};
use crate::builder::{self, BuildRequest, BuiltProfile};
@@ -117,17 +118,22 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
Ok(())
}
pub async fn execute(broker: &Broker, parsed: &Parsed, io: &mut Io) -> Result<i32> {
/// Activates every node; its transient units are named after the request `id`, so its audit
/// record leads to their journals. It ignores the requester leaving (see
/// [`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 built = parsed.prepared.build.as_ref().context("nothing was built")?;
let run = &crate::queue::new_id();
let (out, cancel) = (&io.out, &io.cancel);
// Never cancelled: activations run to the end, and their output is dropped once the
// requester has gone.
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, run)?)];
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);
@@ -171,7 +177,7 @@ async fn copy(
node: &str,
profiles: &[&BuiltProfile],
out: &Output,
cancel: &tokio_util::sync::CancellationToken,
cancel: &CancellationToken,
) -> Result<()> {
let target = ssh::target(ssh, node)?;
let options = copy_options(ssh, node)?;
@@ -222,12 +228,7 @@ pub(super) fn nix_ssh_options(mut options: Vec<String>, extra: &[String]) -> Vec
/// Compares a profile on a node with the new one; see the script for its output.
const INSPECT: &str = include_str!("inspect.sh");
async fn inspect(
ssh: &SshConfig,
node: &str,
profile: &BuiltProfile,
cancel: &tokio_util::sync::CancellationToken,
) -> Result<Changes> {
async fn inspect(ssh: &SshConfig, node: &str, profile: &BuiltProfile, cancel: &CancellationToken) -> Result<Changes> {
let words = ["bash", "-c", INSPECT, "bash", &profile.profile_path, &profile.path];
let command = ssh::command(ssh, &Destination::Node(node.parse().unwrap()), &[shell_quote(&words)])?;
@@ -242,7 +243,7 @@ async fn inspect(
/// connection can't stop an activation halfway: `activate-rs` panics when it can't write.
const UNTIL_DISCONNECTED: &str = r#"set -o pipefail; "$@" 2>&1 | { cat || cat >/dev/null; }"#;
fn activate_command(ssh: &SshConfig, node: &str, profile: &BuiltProfile, boot: bool, run: &str) -> Result<Vec<String>> {
fn activate_command(ssh: &SshConfig, node: &str, profile: &BuiltProfile, boot: bool, id: &str) -> Result<Vec<String>> {
let mut words: Vec<String> = ssh::target(ssh, node)?.sudo.split_whitespace().map(Into::into).collect();
words.push("root".into());
@@ -260,7 +261,7 @@ fn activate_command(ssh: &SshConfig, node: &str, profile: &BuiltProfile, boot: b
]
.map(Into::into),
);
words.push(format!("--unit=slop-deploy-{}-{}", &run[..8], profile.profile));
words.push(format!("--unit=slop-deploy-{id}-{}", profile.profile));
words.extend(["/run/current-system/sw/bin/bash", "-c", UNTIL_DISCONNECTED, "slop-deploy"].map(Into::into));
// What deploy-rs runs, without magic rollback
@@ -495,7 +496,7 @@ mod tests {
};
let words = activate_command(&config, "river", &profile, true, "0123456789abcdef").unwrap();
assert_eq!(&words[..3], ["doas", "-u", "root"]);
assert!(words.contains(&"--unit=slop-deploy-01234567-system".to_owned()));
assert!(words.contains(&"--unit=slop-deploy-0123456789abcdef-system".to_owned()));
assert_eq!(words.last().unwrap(), "--boot");
}
+9 -2
View File
@@ -144,6 +144,12 @@ fn commit(operation: &Operation) -> Result<&CommitId> {
}
}
/// Operations that carry on when their requester leaves, since stopping them partway would leave
/// boxes half changed: the broker waits for them and logs how they ended.
pub fn outlives_requester(parsed: &Parsed) -> bool {
matches!(parsed.operation, Operation::Deploy { .. })
}
/// Fetches and describes the commit an operation builds; runs only Git.
pub async fn describe(broker: &Broker, parsed: &Parsed, io: &Io) -> Result<Description> {
let commit = commit(&parsed.operation)?;
@@ -202,9 +208,10 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
}
}
pub async fn execute(broker: &Broker, requester: &str, parsed: Parsed, io: &mut Io) -> Result<Outcome> {
/// 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 {
Operation::Deploy { .. } => return deploy::execute(broker, &parsed, io).await.map(Into::into),
Operation::Deploy { .. } => return deploy::execute(broker, id, &parsed, io).await.map(Into::into),
Operation::Build { .. } => return build::execute(broker, &parsed, io).await.map(Into::into),
Operation::Secret(_) => return secret::execute(broker, &parsed, io).await,
_ => {}
+60 -3
View File
@@ -282,15 +282,18 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
io.out.send(ServerMessage::Approved { by: approved_by, stdin: parsed.stdin }).await;
let (start, builtin) = (std::time::Instant::now(), parsed.op.builtin());
let result = ops::execute(broker, requester, parsed, io).await;
let log = |event| {
if !builtin {
broker.audit.log(event)
}
};
if io.cancel.is_cancelled() {
// Some operations carry on if the requester leaves, and their outcome is still logged.
let (outlives, cancel) = (ops::outlives_requester(&parsed), io.cancel.clone());
let execution = ops::execute(broker, &id, requester, parsed, io);
let result = see_through(execution, outlives, &cancel, || log(Event::Detached { id: id.clone() })).await;
if cancel.is_cancelled() && !outlives {
log(Event::Disconnected { id });
return None;
}
@@ -308,6 +311,24 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
}
}
/// Runs an operation to the end. If the requester leaves and the operation `outlives` it, this
/// calls `detached` and keeps waiting; otherwise the operation notices `cancel` itself.
async fn see_through<T>(
execution: impl Future<Output = T>,
outlives: bool,
cancel: &CancellationToken,
detached: impl FnOnce(),
) -> T {
tokio::pin!(execution);
tokio::select! {
result = &mut execution => result,
_ = cancel.cancelled(), if outlives => {
detached();
execution.await
}
}
}
/// What policy says about a request.
fn verdict(broker: &Broker, requester: &str, parsed: &ops::Parsed) -> Result<policy::Verdict, ServerMessage> {
let settings = broker.config.policy(requester).ok_or_else(|| denied("unknown requester"))?;
@@ -418,3 +439,39 @@ pub fn check_runtime_dir(path: &Path) -> Result<()> {
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
/// Finishes after a while, unless it notices `cancel` first.
async fn operation(cancel: CancellationToken) -> &'static str {
tokio::select! {
_ = tokio::time::sleep(Duration::from_millis(200)) => "finished",
_ = cancel.cancelled() => "stopped",
}
}
#[tokio::test]
async fn operations_that_outlive_the_requester_are_seen_through() {
for (outlives, expected) in [(true, "finished"), (false, "stopped")] {
let (cancel, detached) = (CancellationToken::new(), Cell::new(0));
let leave = {
let cancel = cancel.clone();
async move {
tokio::time::sleep(Duration::from_millis(50)).await;
cancel.cancel();
}
};
// Operations that outlive their requester don't watch its token.
let watched = if outlives { CancellationToken::new() } else { cancel.clone() };
let execution = see_through(operation(watched), outlives, &cancel, || detached.set(detached.get() + 1));
let (result, ()) = tokio::join!(execution, leave);
assert_eq!(result, expected);
assert_eq!(detached.get(), usize::from(outlives));
}
}
}
+17 -1
View File
@@ -83,6 +83,7 @@ fn id_of(event: &Event) -> Option<&str> {
| Event::Denied { id, .. }
| Event::Expired { id }
| Event::Disconnected { id }
| Event::Detached { id }
| Event::Finished { id, .. }
| Event::Failed { id, .. } => Some(id),
}
@@ -156,7 +157,7 @@ fn summarize(id: String, records: Vec<Record>) -> History {
Event::Finished { exit: 0, .. } => history.outcome = Outcome::Succeeded,
Event::Finished { exit, .. } => history.outcome = Outcome::ExitedWith(*exit),
Event::Failed { .. } => history.outcome = Outcome::Failed,
Event::Unknown { .. } | Event::Prepared { .. } | Event::Approved { .. } => {}
Event::Unknown { .. } | Event::Prepared { .. } | Event::Approved { .. } | Event::Detached { .. } => {}
}
}
@@ -195,6 +196,7 @@ pub fn describe(event: &Event) -> (String, Option<String>) {
Event::Denied { reason, .. } => (format!("Refused: {reason}"), None),
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)
}
@@ -278,4 +280,18 @@ mod tests {
assert_eq!(histories[0].outcome, Outcome::Waiting);
assert_eq!(histories[0].approved_by, None);
}
#[test]
fn a_requester_leaving_doesnt_hide_how_a_deploy_ended() {
let approved = Event::Approved { id: "a".into(), by: ApprovedBy::Policy, approver: None, step: None };
let mut records =
vec![record("1", request("a")), record("2", approved), record("3", Event::Detached { id: "a".into() })];
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 }));
let (histories, _) = gather(records);
assert_eq!(histories[0].outcome, Outcome::Succeeded);
}
}