Skip to main content

tinsel/live/
command.rs

1//! Commands run as steps, with timeouts and retries, and why one failed.
2
3use super::*;
4
5/// How long to wait before retry number `attempt` (from 1).
6pub(super) fn backoff(attempt: u32) -> Duration {
7    Duration::from_millis(500 * 2u64.pow(attempt.saturating_sub(1).min(4)))
8}
9
10pub(super) fn attempts_note(error: &str, retries: u32) -> String {
11    match retries {
12        0 => error.to_string(),
13        n => {
14            let (first, rest) = error.split_once('\n').unwrap_or((error, ""));
15            let rest = if rest.is_empty() {
16                String::new()
17            } else {
18                format!("\n{rest}")
19            };
20            format!("{first} (after {} attempts){rest}", n + 1)
21        }
22    }
23}
24
25/// A command to run as a [`Step`], from [`Step::command`]: set a timeout, retries or what it
26/// reads, then [`run`](StepCommand::run) it.
27///
28/// ```no_run
29/// use std::process::Command;
30/// use std::time::Duration;
31///
32/// let live = tinsel::Live::new("deploy", "my-app");
33/// live.step("Push image")
34///     .command(Command::new("docker").args(["push", "my-app:latest"]))
35///     .timeout(Duration::from_secs(120))
36///     .retries(2)
37///     .run()?;
38/// # Ok::<(), tinsel::RunError>(())
39/// ```
40#[must_use = "the command only runs when `run` is called"]
41pub struct StepCommand<'a, 'c> {
42    pub(super) step: &'a Step,
43    pub(super) command: Box<dyn BorrowMut<Command> + Send + Sync + 'c>,
44    pub(super) stdin: Option<Stdio>,
45    pub(super) timeout: Option<Duration>,
46    pub(super) retries: u32,
47    pub(super) tail: usize,
48}
49
50impl std::fmt::Debug for StepCommand<'_, '_> {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.debug_struct("StepCommand")
53            .field("step", self.step)
54            .field("command", (*self.command).borrow())
55            .field("timeout", &self.timeout)
56            .field("retries", &self.retries)
57            .field("tail", &self.tail)
58            .finish_non_exhaustive()
59    }
60}
61
62impl StepCommand<'_, '_> {
63    /// Kill the command if it's still running after this long. Each retry gets the full time.
64    pub fn timeout(mut self, limit: Duration) -> Self {
65        self.timeout = Some(limit);
66        self
67    }
68
69    /// Run it again, up to `n` more times, if it fails or times out, waiting a little longer
70    /// each time. Succeeding after a retry ends the step on a warning.
71    pub fn retries(mut self, n: u32) -> Self {
72        self.retries = n;
73        self
74    }
75
76    /// How many of the last lines of output to show under the step if it fails (default 12).
77    pub fn tail(mut self, lines: usize) -> Self {
78        self.tail = lines;
79        self
80    }
81
82    /// What the command reads as its input. Nothing unless this says otherwise, so a command
83    /// that stops to ask something fails rather than waiting unseen; `Stdio::inherit()` hands
84    /// it the terminal's input, for one that reads what's typed. Prompts written straight to
85    /// the terminal, as `sudo` and `ssh` ask for passwords, work either way.
86    ///
87    /// ```no_run
88    /// use std::process::{Command, Stdio};
89    ///
90    /// let live = tinsel::Live::new("setup", "my-app");
91    /// live.step("Install").command(Command::new("./install.sh")).stdin(Stdio::inherit()).run()?;
92    /// # Ok::<(), tinsel::RunError>(())
93    /// ```
94    pub fn stdin(mut self, stdin: Stdio) -> Self {
95        self.stdin = Some(stdin);
96        self
97    }
98
99    /// Run the command, marking the step done or failed. Returns everything the command
100    /// printed, stdout and stderr together.
101    ///
102    /// # Errors
103    ///
104    /// A [`RunError`] if the command can't be started, exits unsuccessfully or runs past its timeout,
105    /// on its last attempt.
106    pub fn run(mut self) -> Result<String, RunError> {
107        self.step.start_if_pending();
108        let stdin = self.stdin.take().unwrap_or_else(Stdio::null);
109        (*self.command).borrow_mut().stdin(stdin);
110        let mut attempt = 0;
111        loop {
112            match self.once() {
113                Ok(output) => {
114                    self.step.settle_after(attempt);
115                    return Ok(output);
116                }
117                Err(e) if attempt < self.retries && e.kind.retryable() => {
118                    attempt += 1;
119                    self.step
120                        .detail(format!("attempt {} of {} ยท {e}", attempt + 1, self.retries + 1));
121                    thread::sleep(backoff(attempt));
122                }
123                Err(e) => {
124                    let mut note = e.to_string();
125                    let lines: Vec<&str> = e.output.lines().filter(|l| !l.trim().is_empty()).collect();
126                    for line in &lines[lines.len().saturating_sub(self.tail)..] {
127                        note += "\n";
128                        note += line;
129                    }
130                    self.step.fail(attempts_note(&note, attempt));
131                    return Err(e);
132                }
133            }
134        }
135    }
136
137    fn once(&mut self) -> Result<String, RunError> {
138        let command = (*self.command).borrow_mut();
139        let program = command.get_program().to_string_lossy().into_owned();
140        let mut child = command
141            .stdout(Stdio::piped())
142            .stderr(Stdio::piped())
143            .spawn()
144            .map_err(|e| RunError {
145                program: program.clone(),
146                output: String::new(),
147                kind: RunErrorKind::Spawn(e),
148            })?;
149        let lines = Arc::new(Mutex::new(Vec::<String>::new()));
150        let readers: Vec<JoinHandle<()>> = [
151            child.stdout.take().map(|p| Box::new(p) as Box<dyn Read + Send>),
152            child.stderr.take().map(|p| Box::new(p) as Box<dyn Read + Send>),
153        ]
154        .into_iter()
155        .flatten()
156        .map(|pipe| {
157            let (lines, step) = (lines.clone(), self.step.clone());
158            thread::spawn(move || read_lines(pipe, &lines, &step))
159        })
160        .collect();
161
162        let started = Instant::now();
163        let outcome = loop {
164            match child.try_wait() {
165                Ok(Some(status)) => break Ok(status),
166                Ok(None) if self.timeout.is_some_and(|t| started.elapsed() >= t) => {
167                    let _ = child.kill();
168                    let _ = child.wait();
169                    break Err(RunErrorKind::TimedOut(self.timeout.unwrap_or_default()));
170                }
171                Ok(None) => thread::sleep(Duration::from_millis(30)),
172                Err(e) => break Err(RunErrorKind::Spawn(e)),
173            }
174        };
175        // anything the command started and left running (a background job, or the children
176        // of a killed shell) can hold its output open for ever, so stop waiting soon after
177        // the command itself has gone
178        let grace = Instant::now() + Duration::from_millis(250);
179        while readers.iter().any(|r| !r.is_finished()) && Instant::now() < grace {
180            thread::sleep(Duration::from_millis(10));
181        }
182        for reader in readers.into_iter().filter(JoinHandle::is_finished) {
183            let _ = reader.join();
184        }
185        let output = lock(&lines).join("\n");
186        let kind = match outcome {
187            Ok(status) if status.success() => return Ok(output),
188            Ok(status) => RunErrorKind::Exit(status),
189            Err(kind) => kind,
190        };
191        Err(RunError { program, output, kind })
192    }
193}
194
195/// Collect a command's output line by line, showing the latest as the step's detail. Lines
196/// end at `\n` or `\r`, so progress output that redraws itself shows its latest state.
197pub(super) fn read_lines(mut pipe: Box<dyn Read + Send>, lines: &Mutex<Vec<String>>, step: &Step) {
198    let mut pending = Vec::new();
199    let mut buf = [0u8; 4096];
200    let finish = |bytes: &mut Vec<u8>| {
201        let line = crate::text::strip_ansi(&String::from_utf8_lossy(bytes));
202        bytes.clear();
203        let line = line.trim_end().to_string();
204        if line.trim().is_empty() {
205            return;
206        }
207        step.detail(crate::text::truncate(line.trim(), 60));
208        lock(lines).push(line);
209    };
210    loop {
211        let n = match pipe.read(&mut buf) {
212            Ok(0) | Err(_) => break,
213            Ok(n) => n,
214        };
215        for &b in &buf[..n] {
216            if b == b'\n' || b == b'\r' {
217                finish(&mut pending);
218            } else {
219                pending.push(b);
220            }
221        }
222    }
223    finish(&mut pending);
224}
225
226/// Why a command run as a step didn't succeed. Shows as `cargo exited with status 101`.
227#[derive(Debug)]
228pub struct RunError {
229    program: String,
230    output: String,
231    kind: RunErrorKind,
232}
233
234/// What went wrong running a command, from [`RunError::kind`].
235#[derive(Debug)]
236#[non_exhaustive]
237pub enum RunErrorKind {
238    /// It couldn't be started: not installed, say, or not allowed to run.
239    Spawn(std::io::Error),
240    /// It ran and failed, ending with this status.
241    Exit(ExitStatus),
242    /// It was stopped for running past its [`timeout`](StepCommand::timeout), this long.
243    TimedOut(Duration),
244}
245
246impl RunErrorKind {
247    /// A program that isn't there won't appear on a second try.
248    fn retryable(&self) -> bool {
249        !matches!(self, RunErrorKind::Spawn(_))
250    }
251}
252
253impl RunError {
254    /// The program that was run, as it was named: `cargo`, `./deploy.sh`.
255    pub fn program(&self) -> &str {
256        &self.program
257    }
258
259    /// What went wrong.
260    pub fn kind(&self) -> &RunErrorKind {
261        &self.kind
262    }
263
264    /// The exit code, if the command ran to the end and exited with one (rather than being
265    /// stopped by a signal).
266    pub fn code(&self) -> Option<i32> {
267        self.status().and_then(|s| s.code())
268    }
269
270    /// Everything the command printed before it stopped, stdout and stderr together.
271    pub fn output(&self) -> &str {
272        &self.output
273    }
274
275    /// How the command exited, if it ran to the end.
276    pub fn status(&self) -> Option<ExitStatus> {
277        match self.kind {
278            RunErrorKind::Exit(status) => Some(status),
279            _ => None,
280        }
281    }
282
283    /// Whether it was stopped for running past its [`timeout`](StepCommand::timeout).
284    pub fn timed_out(&self) -> bool {
285        matches!(self.kind, RunErrorKind::TimedOut(_))
286    }
287}
288
289impl std::fmt::Display for RunError {
290    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
291        let program = &self.program;
292        match &self.kind {
293            RunErrorKind::Spawn(e) => write!(f, "couldn't run {program}: {e}"),
294            RunErrorKind::Exit(status) => match status.code() {
295                Some(code) => write!(f, "{program} exited with status {code}"),
296                None => write!(f, "{program} was stopped by a signal"),
297            },
298            RunErrorKind::TimedOut(limit) => write!(f, "{program} timed out after {}", format::duration(*limit)),
299        }
300    }
301}
302
303impl std::error::Error for RunError {
304    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
305        match &self.kind {
306            RunErrorKind::Spawn(e) => Some(e),
307            _ => None,
308        }
309    }
310}
311
312// a command can be set up on one thread and run on another, as it could before
313const _: fn() = || {
314    fn send_sync<T: Send + Sync>() {}
315    send_sync::<StepCommand<'static, 'static>>();
316};