dance-ops 0.1.0

Deploy NixOS hosts safely from a local inventory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
//! Subprocess execution and output reporting.

mod streams;

use std::{
    error::Error as StdError, ffi::OsString, future::IntoFuture, process::ExitStatus,
    string::FromUtf8Error, time::Duration,
};

use indicatif::ProgressBar;
use thiserror::Error;
use tokio::process::Command;
use tokio_process_tools::{
    ConsumerError, DEFAULT_MAX_BUFFERED_CHUNKS, DEFAULT_READ_CHUNK_SIZE, GracefulShutdown,
    OutputStream, Process, ProcessHandle, SpawnError, TerminationError,
    WaitForCompletionOrTerminateResult, WaitOrTerminateError,
};
use tokio_util::sync::CancellationToken;

use self::streams::OutputConsumers;
use crate::{
    error::Error,
    logs::{CommandLog, CommandLogs, LogSession},
};

/// Associates a failure with the command that encountered it.
#[derive(Debug, Error)]
#[error("`{command}` failed")]
pub(crate) struct CommandError<E>
where
    E: StdError + 'static,
{
    /// Shows the attempted command.
    command: String,
    /// Contains the underlying error.
    #[source]
    source: E,
}

impl<E> CommandError<E>
where
    E: StdError + 'static,
{
    /// Associates a failure with its command.
    fn new(command: String, source: E) -> Self {
        Self { command, source }
    }
}

/// Describes a failure encountered while running a subprocess.
#[derive(Debug, Error)]
pub(crate) enum ProcessError {
    /// Indicates that a command could not be started.
    #[error("failed to run command")]
    Spawn(#[source] CommandError<SpawnError>),
    /// Indicates that a command could not be awaited or cleaned up.
    #[error("failed to wait for command")]
    Wait(#[source] CommandError<WaitOrTerminateError>),
    /// Indicates that a command could not be terminated after interruption.
    #[error("failed to terminate command")]
    Terminate(#[source] CommandError<TerminationError>),
    /// Indicates that command output could not be read.
    #[error("failed to read command output")]
    OutputRead(#[source] CommandError<ConsumerError>),
    /// Indicates that command output did not close after process exit.
    #[error("output from `{command}` did not close after {seconds} seconds")]
    OutputDrainTimedOut {
        /// Shows the attempted command.
        command: String,
        /// Contains the output drain deadline in seconds.
        seconds: u64,
    },
    /// Indicates that a command returned a failure status.
    #[error("`{command}` exited with {status}: {stderr}")]
    Failed {
        /// Shows the attempted command.
        command: String,
        /// Contains the command's exit status.
        status: ExitStatus,
        /// Contains standard error from the command.
        stderr: String,
    },
    /// Indicates that a command exceeded its execution deadline.
    #[error("`{command}` timed out after {seconds} seconds")]
    TimedOut {
        /// Shows the attempted command.
        command: String,
        /// Contains the configured deadline in seconds.
        seconds: u64,
    },
    /// Indicates that command execution was interrupted.
    #[error("`{command}` was interrupted")]
    Interrupted {
        /// Shows the attempted command.
        command: String,
    },
    /// Indicates that command output was not UTF-8.
    #[error("`{command}` returned non-UTF-8 output")]
    Output {
        /// Shows the attempted command.
        command: String,
        /// Contains the decoding error.
        #[source]
        source: FromUtf8Error,
    },
}

/// Limits subprocess diagnostics included in terminal errors.
const ERROR_OUTPUT_LINES: usize = 20;
/// Bounds commands without a routine execution deadline.
const MAX_COMMAND_RUNTIME: Duration = Duration::from_secs(365 * 24 * 60 * 60);
/// Allows subprocesses to handle graceful termination.
const TERMINATION_GRACE: Duration = Duration::from_secs(2);

/// Shares subprocess services across one application run.
pub(crate) struct ProcessContext<'a> {
    /// Provides persistent command diagnostics.
    logs: &'a LogSession,
    /// Signals that active commands should terminate.
    cancellation: CancellationToken,
}

impl<'a> ProcessContext<'a> {
    /// Creates subprocess services for one application run.
    pub(crate) fn new(logs: &'a LogSession, cancellation: CancellationToken) -> Self {
        Self { logs, cancellation }
    }

    /// Creates subprocess services isolated from workflow cancellation for bounded recovery.
    pub(crate) fn recovery(&self) -> Self {
        Self {
            logs: self.logs,
            cancellation: CancellationToken::new(),
        }
    }
}

/// Describes how a process wait completed.
enum Completion {
    /// Contains a normal child exit status.
    Exited(ExitStatus),
    /// Indicates that the execution deadline initiated termination.
    TimedOut,
    /// Indicates that application interruption initiated termination.
    Interrupted,
}

/// Configures process-group termination for a timeout or interruption.
fn graceful_shutdown(interrupted: bool) -> GracefulShutdown {
    if interrupted {
        GracefulShutdown::builder()
            .unix_sigint(TERMINATION_GRACE)
            .windows_ctrl_break(TERMINATION_GRACE)
            .build()
    } else {
        GracefulShutdown::builder()
            .unix_sigterm(TERMINATION_GRACE)
            .windows_ctrl_break(TERMINATION_GRACE)
            .build()
    }
}

/// Waits for process exit while refreshing progress and honoring cancellation.
async fn wait_for_process<Stdout, Stderr>(
    process: &mut ProcessHandle<Stdout, Stderr>,
    consumers: &OutputConsumers,
    progress: &ProgressBar,
    cancellation: &CancellationToken,
    limit: Duration,
    command: &str,
) -> Result<Completion, ProcessError>
where
    Stdout: OutputStream + Send,
    Stderr: OutputStream + Send,
{
    let mut refresh = consumers.refresh_interval();
    let wait_result = {
        let wait = process
            .wait_for_completion(limit)
            .or_terminate(graceful_shutdown(false))
            .into_future();
        tokio::pin!(wait);
        loop {
            tokio::select! {
                result = &mut wait => break Some(result),
                () = cancellation.cancelled() => break None,
                _ = refresh.tick() => consumers.refresh(progress),
            }
        }
    };
    match wait_result {
        Some(Ok(WaitForCompletionOrTerminateResult::Completed(status))) => {
            Ok(Completion::Exited(status))
        }
        Some(Ok(WaitForCompletionOrTerminateResult::TerminatedAfterTimeout { .. })) => {
            Ok(Completion::TimedOut)
        }
        Some(Err(source)) => {
            process.must_not_be_terminated();
            Err(ProcessError::Wait(CommandError::new(
                command.to_owned(),
                source,
            )))
        }
        None => match process.terminate(graceful_shutdown(true)).await {
            Ok(_status) => Ok(Completion::Interrupted),
            Err(source) => {
                process.must_not_be_terminated();
                Err(ProcessError::Terminate(CommandError::new(
                    command.to_owned(),
                    source,
                )))
            }
        },
    }
}

/// Returns the trailing standard-error lines for concise diagnostics.
fn error_output(stderr: &[u8]) -> String {
    let value = String::from_utf8_lossy(stderr);
    let mut lines = value
        .lines()
        .rev()
        .take(ERROR_OUTPUT_LINES)
        .collect::<Vec<_>>();
    lines.reverse();
    let summary = lines.join("\n");
    if summary.is_empty() {
        "no standard error output".to_owned()
    } else {
        summary
    }
}

/// Records an execution failure before returning it.
fn fail_command<T>(log: CommandLog<'_>, error: Error) -> Result<T, Error> {
    log.fail(&error.to_string());
    Err(error)
}

/// Configures and executes one logged subprocess.
pub(crate) struct Invocation<'a> {
    /// Shares run-scoped process services.
    context: &'a ProcessContext<'a>,
    /// Describes the command's role in the workflow.
    label: String,
    /// Identifies the executable.
    program: OsString,
    /// Contains the executable arguments.
    arguments: Vec<OsString>,
    /// Contains environment additions for the child process.
    environment: Vec<(OsString, OsString)>,
    /// Limits command execution when configured.
    timeout: Option<Duration>,
    /// Receives live command output.
    progress: &'a ProgressBar,
}

impl<'a> Invocation<'a> {
    /// Creates a command without arguments or environment additions.
    pub(crate) fn new(
        context: &'a ProcessContext<'a>,
        label: impl Into<String>,
        program: impl Into<OsString>,
        progress: &'a ProgressBar,
    ) -> Self {
        Self {
            context,
            label: label.into(),
            program: program.into(),
            arguments: Vec::new(),
            environment: Vec::new(),
            timeout: None,
            progress,
        }
    }

    /// Adds one argument to the child process.
    #[must_use]
    pub(crate) fn argument(mut self, argument: impl Into<OsString>) -> Self {
        self.arguments.push(argument.into());
        self
    }

    /// Adds arguments to the child process.
    #[must_use]
    pub(crate) fn arguments(
        mut self,
        arguments: impl IntoIterator<Item = impl Into<OsString>>,
    ) -> Self {
        self.arguments.extend(arguments.into_iter().map(Into::into));
        self
    }

    /// Adds an environment variable to the child process.
    #[must_use]
    pub(crate) fn environment(
        mut self,
        name: impl Into<OsString>,
        value: impl Into<OsString>,
    ) -> Self {
        self.environment.push((name.into(), value.into()));
        self
    }

    /// Limits command execution time.
    #[must_use]
    pub(crate) fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Runs the command and discards its successful standard output.
    pub(crate) async fn status(self) -> Result<(), Error> {
        self.execute(false, |_output| Ok(())).await
    }

    /// Runs the command and returns its successful standard output.
    pub(crate) async fn output(self) -> Result<String, Error> {
        self.execute(true, String::from_utf8).await
    }

    /// Executes the configured command and consumes successful standard output.
    async fn execute<T>(
        self,
        capture_stdout: bool,
        consume: impl FnOnce(Vec<u8>) -> Result<T, FromUtf8Error>,
    ) -> Result<T, Error> {
        let CommandLogs {
            lifecycle: command_log,
            output: output_logs,
        } = self
            .context
            .logs
            .command(&self.label, &self.program, &self.arguments)
            .map_err(Error::Log)?;
        let mut command = Command::new(&self.program);
        command
            .args(&self.arguments)
            .envs(self.environment.iter().map(|(name, value)| (name, value)));
        let command_display = format!("{:?}", command.as_std());
        if self.context.cancellation.is_cancelled() {
            return fail_command(
                command_log,
                Error::Process(ProcessError::Interrupted {
                    command: command_display,
                }),
            );
        }
        let mut process = match Process::new(command)
            .name(self.label.clone())
            .stdout_and_stderr(|stream| {
                stream
                    .single_subscriber()
                    .reliable_with_backpressure()
                    .replay_all()
                    .read_chunk_size(DEFAULT_READ_CHUNK_SIZE)
                    .max_buffered_chunks(DEFAULT_MAX_BUFFERED_CHUNKS)
            })
            .spawn()
        {
            Ok(process) => process,
            Err(source) => {
                return fail_command(
                    command_log,
                    Error::Process(ProcessError::Spawn(CommandError::new(
                        command_display,
                        source,
                    ))),
                );
            }
        };
        let consumers = OutputConsumers::attach(
            process.stdout(),
            process.stderr(),
            output_logs,
            capture_stdout,
        );
        process.seal_output_replay();
        let limit = self.timeout.unwrap_or(MAX_COMMAND_RUNTIME);
        let completion = match wait_for_process(
            &mut process,
            &consumers,
            self.progress,
            &self.context.cancellation,
            limit,
            &command_display,
        )
        .await
        {
            Ok(completion) => completion,
            Err(error) => return fail_command(command_log, Error::Process(error)),
        };
        let output = match consumers.finish(&command_display, self.progress).await {
            Ok(output) => output,
            Err(error) => return fail_command(command_log, error),
        };
        let status = match completion {
            Completion::TimedOut => {
                return fail_command(
                    command_log,
                    Error::Process(ProcessError::TimedOut {
                        command: command_display,
                        seconds: limit.as_secs(),
                    }),
                );
            }
            Completion::Interrupted => {
                return fail_command(
                    command_log,
                    Error::Process(ProcessError::Interrupted {
                        command: command_display,
                    }),
                );
            }
            Completion::Exited(status) => status,
        };
        if !status.success() {
            command_log.complete(status);
            return Err(Error::Process(ProcessError::Failed {
                command: command_display,
                status,
                stderr: error_output(&output.stderr),
            }));
        }

        match consume(output.stdout) {
            Ok(output) => {
                command_log.complete(status);
                Ok(output)
            }
            Err(source) => fail_command(
                command_log,
                Error::Process(ProcessError::Output {
                    command: command_display,
                    source,
                }),
            ),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{fs, time::Duration};

    use indicatif::ProgressBar;
    use tempfile::tempdir;
    use tokio_util::sync::CancellationToken;

    use super::{Invocation, ProcessContext, ProcessError};
    use crate::{
        error::Error,
        logs::{LogMode, LogSession, with_test_log_session},
    };

    /// Checks bounded termination and explicit cancellation reporting.
    #[tokio::test]
    async fn commands_report_timeouts_and_interruption() {
        let logs = LogSession::start(LogMode::Never, None).expect("disabled logs should start");
        let progress = ProgressBar::hidden();
        let timeout_cancellation = CancellationToken::new();
        let timeout_context = ProcessContext::new(&logs, timeout_cancellation);
        let timeout = Invocation::new(&timeout_context, "timeout", "sh", &progress)
            .arguments(["-c", "sleep 10"])
            .timeout(Duration::from_millis(20))
            .status()
            .await;
        assert!(matches!(
            timeout,
            Err(Error::Process(ProcessError::TimedOut { .. }))
        ));

        let cancellation = CancellationToken::new();
        let interrupted_context = ProcessContext::new(&logs, cancellation.clone());
        let interrupt = async move {
            tokio::time::sleep(Duration::from_millis(20)).await;
            cancellation.cancel();
        };
        let command = Invocation::new(&interrupted_context, "interrupted", "sh", &progress)
            .arguments(["-c", "sleep 10"])
            .status();
        let ((), interrupted) = tokio::join!(interrupt, command);
        assert!(matches!(
            interrupted,
            Err(Error::Process(ProcessError::Interrupted { .. }))
        ));

        let recovery_context = interrupted_context.recovery();
        Invocation::new(&recovery_context, "recovery", "true", &progress)
            .status()
            .await
            .expect("recovery command should ignore prior cancellation");
        drop((timeout_context, interrupted_context, recovery_context));
        logs.finish(Some("timed out or interrupted"))
            .expect("disabled logs should finish");
    }

    /// Checks that output decoding failures are reported.
    #[test]
    fn invalid_command_output_is_reported() {
        let base = tempdir().expect("temporary directory should be created");
        let directory = with_test_log_session(LogMode::Always, base.path(), |logs| {
            let runtime = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .expect("Tokio runtime should start");
            runtime.block_on(async {
                let progress = ProgressBar::hidden();
                let context = ProcessContext::new(&logs, CancellationToken::new());
                Invocation::new(&context, "ignored-output", "sh", &progress)
                    .arguments(["-c", "printf '\\377'"])
                    .status()
                    .await
                    .expect("discarded output should not require UTF-8");
                let result = Invocation::new(&context, "invalid-output", "sh", &progress)
                    .arguments(["-c", "printf '\\377'"])
                    .output()
                    .await;
                let error = result.expect_err("non-UTF-8 output should fail");
                assert!(matches!(error, Error::Process(ProcessError::Output { .. })));
            });
            logs.finish(Some("invalid output"))
                .expect("enabled logs should finish")
                .expect("always logs should be retained")
        });
        assert_eq!(
            fs::read(directory.join("001.stdout")).expect("ignored output log should be readable"),
            [0xff]
        );
        assert_eq!(
            fs::read(directory.join("002.stdout")).expect("invalid output log should be readable"),
            [0xff]
        );
    }
}