Skip to main content

helm_rs/cli/
mod.rs

1//! The `helm` binary backend.
2//!
3//! [`Cli`] runs the `helm` executable (Helm 4 only) once per command. Every run inherits the parent
4//! environment (exec credential plugins need `PATH` and `HOME`), except that all `HELM_*`
5//! variables are removed first; the [`GlobalOptions`] then set what Helm should see, so a run does
6//! not depend on the caller's Helm settings. `KUBECONFIG` is inherited: without
7//! [`GlobalOptions::kubeconfig`], helm resolves the cluster exactly like `kubectl` and
8//! `kube::Client::try_default` in the same process, so the two never target different clusters.
9//! The kube token travels only as `HELM_KUBETOKEN`, never in argv.
10//!
11//! Cancellation: dropping the future of a read-only command kills the process. Commands that
12//! mutate a release (install, upgrade, rollback, uninstall, test) are not killed on drop and run
13//! to completion in the background, because killing an upgrade leaves the release
14//! `pending-upgrade`. That background
15//! task also owns the invocation's `0600` values files, so they are deleted only after the process
16//! has exited, never while helm may still read them.
17//!
18//! ```no_run
19//! # async fn demo() -> helm_rs::Result<()> {
20//! use helm_rs::{Helm, command::Version};
21//!
22//! let helm = Helm::detect().await?.with_namespace("prod");
23//! let version = helm.run(Version).await?;
24//!
25//! println!("{}", version.version);
26//! # Ok(()) }
27//! ```
28
29#[cfg(test)]
30#[macro_use]
31mod chart_rows;
32mod chart_path;
33mod classify;
34mod dependency;
35mod env;
36mod fetch;
37mod invocation;
38mod plugin;
39mod registry;
40mod release;
41mod render;
42mod repo;
43mod search;
44mod show;
45mod verification;
46mod version;
47
48#[cfg(test)]
49mod testing;
50
51#[cfg(test)]
52mod tests;
53
54use std::ffi::OsStr;
55use std::io;
56use std::path::PathBuf;
57use std::process::Stdio;
58
59use tokio::io::AsyncWriteExt;
60use tokio::process::{Child, Command as Process};
61use tracing::debug;
62
63use crate::backend::{Backend, Command, Execute};
64use crate::command::Version;
65use crate::error::{Error, Result};
66use crate::options::GlobalOptions;
67
68pub(crate) use chart_path::{chart_path, oci_host, oci_hosts, registry_auth};
69pub(crate) use invocation::{Invocation, flags, parse_json};
70
71/// A command the CLI backend can run: how to build its argv and how to read its stdout.
72pub(crate) trait CliCommand: Command {
73    /// True when the command changes a release. Such a run is executed in a detached tokio task
74    /// that owns the child process and the invocation's temporary values files: dropping the
75    /// caller's future neither kills helm nor deletes the files; they are removed when the process
76    /// exits. Read-only commands run inline and are killed on drop.
77    const MUTATES: bool = false;
78
79    /// Adds the arguments (after the global flags), stdin and values to the invocation.
80    fn build(&self, inv: &mut Invocation) -> Result<()>;
81
82    /// Parses the standard output of a successful run.
83    fn parse(&self, stdout: String) -> Result<Self::Output>;
84
85    /// Reads the output of a run that exited non-zero, for commands whose exit status reports a
86    /// finding rather than a failure (`helm lint`). `None`, the default, leaves the run an error.
87    fn parse_failure(&self, _stdout: &str, _stderr: &str) -> Option<Result<Self::Output>> {
88        None
89    }
90}
91
92/// The `helm` binary backend. Obtain one with [`Cli::detect`] or [`Cli::new`], which check the
93/// version.
94#[derive(Debug, Clone)]
95pub struct Cli {
96    /// The `helm` executable.
97    pub binary: PathBuf,
98    /// The version it reported.
99    pub version: semver::Version,
100}
101
102impl Cli {
103    /// Finds `helm` on `PATH` and checks that it is Helm 4.
104    pub async fn detect() -> Result<Self> {
105        Self::new("helm").await
106    }
107
108    /// Uses `binary`, running `helm version` to check that it is Helm 4 or newer.
109    pub async fn new(binary: impl Into<PathBuf>) -> Result<Self> {
110        let binary = binary.into();
111        let found = run(&binary, &GlobalOptions::default(), &Version)
112            .await?
113            .version;
114
115        if found.major < 4 {
116            return Err(Error::UnsupportedVersion { found });
117        }
118
119        Ok(Self {
120            binary,
121            version: found,
122        })
123    }
124}
125
126impl Backend for Cli {}
127
128impl<C: CliCommand> Execute<C> for Cli {
129    async fn execute(&self, options: &GlobalOptions, command: &C) -> Result<C::Output> {
130        run(&self.binary, options, command).await
131    }
132}
133
134/// True for the variables a run must not inherit: `HELM_*`, which [`GlobalOptions`] models.
135fn is_helm_var(key: &OsStr) -> bool {
136    key.to_string_lossy().starts_with("HELM_")
137}
138
139/// Runs one command: builds the invocation, spawns `binary`, classifies failures, parses stdout.
140async fn run<C: CliCommand>(
141    binary: &PathBuf,
142    options: &GlobalOptions,
143    command: &C,
144) -> Result<C::Output> {
145    let mut inv = Invocation::default();
146    let mut process = Process::new(binary);
147
148    inv.globals(options)?;
149    command.build(&mut inv)?;
150
151    for (key, _) in std::env::vars_os().filter(|(key, _)| is_helm_var(key)) {
152        process.env_remove(key);
153    }
154
155    process
156        .args(&inv.args)
157        .envs(inv.env.iter().map(|(k, v)| (k, v)))
158        .stdin(if inv.stdin.is_some() {
159            Stdio::piped()
160        } else {
161            Stdio::null()
162        })
163        .stdout(Stdio::piped())
164        .stderr(Stdio::piped())
165        .kill_on_drop(!C::MUTATES);
166
167    debug!(binary = %binary.display(), args = ?inv.args, "running helm");
168
169    let child = process.spawn().map_err(|e| match e.kind() {
170        io::ErrorKind::NotFound => Error::BinaryNotFound(binary.clone()),
171        _ => Error::Io(e),
172    })?;
173    let finished = if C::MUTATES {
174        tokio::spawn(finish(child, inv))
175            .await
176            .map_err(|e| Error::Io(io::Error::other(e)))??
177    } else {
178        finish(child, inv).await?
179    };
180
181    if !finished.success {
182        if let Some(parsed) = command.parse_failure(&finished.stdout, &finished.stderr) {
183            return parsed;
184        }
185
186        return Err(classify::classify(finished.exit_code, finished.stderr));
187    }
188
189    command.parse(finished.stdout)
190}
191
192/// What a finished process left behind.
193struct Finished {
194    success: bool,
195    exit_code: Option<i32>,
196    stdout: String,
197    stderr: String,
198}
199
200/// Feeds stdin while collecting the output (so neither side can block the other on a full pipe)
201/// and returns what the process printed. Owns the invocation, so its temporary files live until
202/// the process has exited.
203async fn finish(mut child: Child, inv: Invocation) -> Result<Finished> {
204    let mut stdin = child.stdin.take();
205    let input = inv.stdin.as_deref().unwrap_or_default();
206    let feed = async {
207        if let Some(stdin) = stdin.as_mut() {
208            // A helm that exits before reading its stdin is reported through its exit status.
209            let _ = stdin.write_all(input).await;
210        }
211
212        drop(stdin.take());
213    };
214    let ((), output) = tokio::join!(feed, child.wait_with_output());
215    let output = output?;
216
217    debug!(status = %output.status, "helm finished");
218
219    if !output.status.success() {
220        return Ok(Finished {
221            success: false,
222            exit_code: output.status.code(),
223            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
224            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
225        });
226    }
227
228    let stdout = String::from_utf8(output.stdout)
229        .map_err(|e| Error::Io(io::Error::new(io::ErrorKind::InvalidData, e)))?;
230
231    Ok(Finished {
232        success: true,
233        exit_code: output.status.code(),
234        stdout,
235        stderr: String::new(),
236    })
237}