eb_pipeline/
tools.rs

1//! Sibling tools: binaries, versions, code mapping.
2
3use crate::exit::{self, Fail};
4use crate::schema::{Site, ToolSpec};
5use crate::util::{cmp_version, find_version, parse_version};
6use std::collections::BTreeMap;
7use std::process::{Command, Stdio};
8
9/// A sibling tool that eb-pipeline starts as a subprocess.
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub enum Tool {
12    /// eb-stack, for `stack shard` and `stack admit`.
13    EbStack,
14    /// eb-keep-logs, for `failed` and `rotate`.
15    EbKeepLogs,
16    /// eb-staged-rebuild, for `run` on a line that rebuilds a live install.
17    EbStagedRebuild,
18}
19
20impl Tool {
21    /// Every tool, in the order `[site.tools]` documents them.
22    pub const ALL: [Tool; 3] = [Tool::EbStack, Tool::EbKeepLogs, Tool::EbStagedRebuild];
23
24    /// The tool's key under `[site.tools]`: `eb_stack`, `eb_keep_logs` or
25    /// `eb_staged_rebuild`.
26    pub fn key(self) -> &'static str {
27        match self {
28            Tool::EbStack => "eb_stack",
29            Tool::EbKeepLogs => "eb_keep_logs",
30            Tool::EbStagedRebuild => "eb_staged_rebuild",
31        }
32    }
33
34    /// The program name looked up on `PATH` when the site file sets no `bin`.
35    pub fn default_bin(self) -> &'static str {
36        match self {
37            Tool::EbStack => "eb-stack",
38            Tool::EbKeepLogs => "eb-keep-logs",
39            Tool::EbStagedRebuild => "eb-staged-rebuild",
40        }
41    }
42
43    /// The tool's `[site.tools.<tool>]` table, when the site file has one.
44    pub fn spec(self, site: &Site) -> Option<&ToolSpec> {
45        let t = site.site.tools.as_ref()?;
46        match self {
47            Tool::EbStack => t.eb_stack.as_ref(),
48            Tool::EbKeepLogs => t.eb_keep_logs.as_ref(),
49            Tool::EbStagedRebuild => t.eb_staged_rebuild.as_ref(),
50        }
51    }
52
53    /// The program to start: the site file's `bin`, else
54    /// [`Tool::default_bin`].
55    pub fn bin(self, site: &Site) -> String {
56        self.spec(site)
57            .and_then(|s| s.bin.clone())
58            .unwrap_or_else(|| self.default_bin().to_string())
59    }
60
61    /// The site file's `min_version` for the tool, as written.
62    pub fn min_version(self, site: &Site) -> Option<String> {
63        self.spec(site).and_then(|s| s.min_version.clone())
64    }
65}
66
67/// Tools that an enabled phase calls.
68pub fn needed(site: &Site) -> Vec<Tool> {
69    let mut v = Vec::new();
70    if site.shards_on().is_some() || site.admission_on().is_some() {
71        v.push(Tool::EbStack);
72    }
73    if site.logs_on().is_some() {
74        v.push(Tool::EbKeepLogs);
75    }
76    if site.rebuild_on().is_some() {
77        v.push(Tool::EbStagedRebuild);
78    }
79    v
80}
81
82/// Run `bin --version` and return the parsed version.
83pub fn probe(bin: &str) -> Result<Vec<u64>, String> {
84    let out = Command::new(bin)
85        .arg("--version")
86        .output()
87        .map_err(|e| format!("cannot run `{bin} --version`: {e}"))?;
88    let text = format!(
89        "{}{}",
90        String::from_utf8_lossy(&out.stdout),
91        String::from_utf8_lossy(&out.stderr)
92    );
93    find_version(&text)
94        .ok_or_else(|| format!("`{bin} --version` printed no version: {}", text.trim()))
95}
96
97/// Whether `bin --help`, run with `env`, lists `option` on stdout.
98/// eb-keep-logs took `rotate --lock-timeout` without a version of its own:
99/// its Zig build says 0.2.1, and its shell script 0.1.0, with the option
100/// and without it.
101pub fn help_lists(bin: &str, env: &BTreeMap<String, String>, option: &str) -> Result<bool, String> {
102    let out = Command::new(bin)
103        .arg("--help")
104        .envs(env)
105        .stdin(Stdio::null())
106        .output()
107        .map_err(|e| format!("cannot run `{bin} --help`: {e}"))?;
108    if !out.status.success() {
109        let code = out
110            .status
111            .code()
112            .map_or_else(|| out.status.to_string(), |c| c.to_string());
113        return Err(format!("`{bin} --help` exited {code}"));
114    }
115    Ok(String::from_utf8_lossy(&out.stdout).contains(option))
116}
117
118/// Check minimum versions of the tools the site needs. With `probe_all`,
119/// tools without a minimum are probed for existence too.
120pub fn check_versions(site: &Site, probe_all: bool) -> Result<(), Fail> {
121    let mut problems = Vec::new();
122    for t in needed(site) {
123        let min = t.min_version(site);
124        if min.is_none() && !probe_all {
125            continue;
126        }
127        let bin = t.bin(site);
128        match probe(&bin) {
129            Err(e) => problems.push(format!("{}: {e}", t.key())),
130            Ok(found) => {
131                if let Some(m) = min.as_deref().and_then(parse_version) {
132                    if cmp_version(&found, &m) == std::cmp::Ordering::Less {
133                        problems.push(format!(
134                            "{}: version {} is below min_version {}",
135                            t.key(),
136                            join(&found),
137                            join(&m)
138                        ));
139                    }
140                }
141            }
142        }
143    }
144    if problems.is_empty() {
145        Ok(())
146    } else {
147        Err(Fail::new(exit::USAGE, problems.join("; ")))
148    }
149}
150
151fn join(v: &[u64]) -> String {
152    v.iter().map(u64::to_string).collect::<Vec<_>>().join(".")
153}
154
155/// Outcome of a staged-rebuild exit code.
156#[derive(Debug, PartialEq, Eq, Clone, Copy)]
157pub enum StagedOutcome {
158    /// Exit 0: the staged rebuild succeeded.
159    Ok,
160    /// Exit 2 in eb-staged-rebuild: refusal.
161    Refused,
162    /// Exit 75: a required ledger event is pending.
163    Pending,
164    /// Any other exit code.
165    Failed,
166}
167
168/// Read an `eb-staged-rebuild run` exit code: 0 is [`StagedOutcome::Ok`],
169/// 2 [`StagedOutcome::Refused`], 75 [`StagedOutcome::Pending`], and any other
170/// [`StagedOutcome::Failed`].
171pub fn map_staged(code: i32) -> StagedOutcome {
172    match code {
173        0 => StagedOutcome::Ok,
174        2 => StagedOutcome::Refused,
175        75 => StagedOutcome::Pending,
176        _ => StagedOutcome::Failed,
177    }
178}
179
180/// Outcome of an `eb-keep-logs rotate` exit code.
181#[derive(Debug, PartialEq, Eq, Clone, Copy)]
182pub enum RotateOutcome {
183    /// Exit 0: the log tree was rotated.
184    Ok,
185    /// Exit 75: another rotate of the tree held eb-keep-logs' lock past
186    /// `--lock-timeout`, and this one changed nothing.
187    Locked,
188    /// Any other exit code.
189    Failed,
190}
191
192/// Read an `eb-keep-logs rotate` exit code: 0 is [`RotateOutcome::Ok`], 75
193/// [`RotateOutcome::Locked`], and any other [`RotateOutcome::Failed`].
194pub fn map_rotate(code: i32) -> RotateOutcome {
195    match code {
196        0 => RotateOutcome::Ok,
197        75 => RotateOutcome::Locked,
198        _ => RotateOutcome::Failed,
199    }
200}