Skip to main content

isothrum_runner/process/
system.rs

1//! Real processes, through `process-wrap` (no `unsafe` here): each tool in its own process group
2//! (unix) or job object (Windows), so a timeout or a cancellation ends the whole tree it started
3//! (`vagrant` is a wrapper around `ruby`, `cmd /C az` around `python`), headless on Windows. A
4//! tool cut short is asked to stop first, on Unix (see [`super::stopping`]).
5
6use std::path::Path;
7use std::process::Stdio;
8use std::sync::Arc;
9
10use process_wrap::tokio::{ChildWrapper, CommandWrap};
11use tokio::process::Command;
12
13use super::stopping::{GRACE, Stopping};
14use super::{Exit, OnLine, ProcessError, ProcessRunner, ProcessSpec, ledger, lines, shim};
15use crate::BoxFuture;
16
17/// Starts real processes. [`SystemProcesses::default`] reads the Docker CLI's config
18/// (`$DOCKER_CONFIG/config.json`, else `~/.docker/config.json`) to learn whether the user picked
19/// an engine context of their own.
20///
21/// A tool cut short (its operation's future dropped: a cancel, a step's timeout) is asked to stop
22/// on Unix (SIGINT to its process group, so Terraform saves its state) and ended once it has
23/// exited, or 30 seconds later; on Windows it is ended at once. Its clones share the tools
24/// stopping: a process about to exit waits for them with [`SystemProcesses::stopped`].
25#[derive(Debug, Clone)]
26pub struct SystemProcesses {
27    /// Drop `DOCKER_HOST` and `DOCKER_CONTEXT` for `docker` (the user picked a context).
28    strip_engine_overrides: bool,
29    /// The tools cut short that are still stopping.
30    stopping: Arc<Stopping>,
31}
32
33impl Default for SystemProcesses {
34    fn default() -> SystemProcesses {
35        SystemProcesses::for_host(|v| std::env::var_os(v), std::env::home_dir().as_deref())
36    }
37}
38
39/// The Docker CLI's config at `path`: none when there is none, and when it can't be read, which is
40/// traced (whether the user picked a context is then unknown, so the inherited engine variables
41/// stay).
42fn read_cli_config(path: &Path) -> Option<String> {
43    crate::store::if_there(std::fs::read_to_string(path)).unwrap_or_else(|e| {
44        tracing::warn!(
45            path = %path.display(),
46            error = %e,
47            "the Docker CLI's config couldn't be read: DOCKER_HOST and DOCKER_CONTEXT are kept for docker"
48        );
49        None
50    })
51}
52
53impl SystemProcesses {
54    /// Real processes, the Docker CLI's config read from `$DOCKER_CONFIG/config.json`, else
55    /// `<home>/.docker/config.json` (`var` reads the environment, `home` is the user's): it says
56    /// whether the user picked an engine context of their own. A `DOCKER_CONFIG` that isn't UTF-8
57    /// is a path like any other.
58    fn for_host(var: impl Fn(&str) -> Option<std::ffi::OsString>, home: Option<&Path>) -> SystemProcesses {
59        let dir = var("DOCKER_CONFIG").map(std::path::PathBuf::from).or_else(|| home.map(|h| h.join(".docker")));
60        let config = dir.and_then(|d| read_cli_config(&d.join("config.json")));
61        SystemProcesses {
62            strip_engine_overrides: shim::strips_engine_overrides(config.as_deref()),
63            stopping: Arc::new(Stopping::new(GRACE)),
64        }
65    }
66
67    /// Whether a tool cut short is still stopping.
68    #[must_use]
69    pub fn is_stopping(&self) -> bool {
70        self.stopping.any()
71    }
72
73    /// Once every tool cut short has ended: at the latest 30 seconds after the last was cut short.
74    /// At once when none is stopping.
75    pub async fn stopped(&self) {
76        self.stopping.stopped().await;
77    }
78
79    /// Ends every tool cut short that is still stopping, at once (a second Ctrl-C).
80    pub fn end_stopping(&self) {
81        self.stopping.end_now();
82    }
83
84    async fn run_to_end(&self, spec: &ProcessSpec, on_line: OnLine<'_>) -> Result<Exit, ProcessError> {
85        if let Some(arg) = shim::refused_arg(&spec.program, &spec.args) {
86            return Err(ProcessError::Refused {
87                program: spec.program.clone(),
88                why: format!("its argument `{}` holds a character cmd.exe would interpret", arg.escape_debug()),
89            });
90        }
91        let io = |source| ProcessError::Io {
92            program: spec.program.clone(),
93            source,
94        };
95        // The program and its arguments only: values reach a tool through its environment,
96        // which is never logged.
97        tracing::debug!(program = %spec.program, args = ?spec.args, "starting a process");
98        let mut cmd = self.command(spec).map_err(io)?;
99        let child = cmd.spawn().map_err(|e| spawned(&spec.program, e))?;
100        let recorded = spec.tools.as_deref().zip(child.id()).and_then(|(dir, pid)| ledger::Recorded::write(dir, pid));
101        let mut tree = Tree(Some(child), Arc::clone(&self.stopping), recorded);
102        let status = match tree.0.as_deref_mut() {
103            Some(started) => lines::forward_lines(started, on_line).await.map_err(io)?,
104            None => return Err(io(std::io::Error::other("the process went away"))),
105        };
106        // It exited on its own: what it left running is its business.
107        tree.0 = None;
108        tracing::debug!(program = %spec.program, code = ?status.code(), "process exited");
109        if shim::missing_behind_cmd(&spec.program, status.code()) {
110            return Err(ProcessError::Missing { program: spec.program.clone() });
111        }
112        Ok(Exit { code: status.code() })
113    }
114
115    /// The command for `spec`: its own group or job, its output piped, headless.
116    fn command(&self, spec: &ProcessSpec) -> std::io::Result<CommandWrap> {
117        let stdin = match &spec.stdin {
118            Some(path) => Stdio::from(std::fs::File::open(path)?),
119            None => Stdio::null(),
120        };
121        let strip = self.strip_engine_overrides && shim::uses_engine(&spec.program);
122        let inherited = std::env::vars_os().filter_map(|(k, _)| k.into_string().ok());
123        let withheld = shim::withheld(&spec.program, inherited);
124        let (program, args) = wrapped(spec);
125        let mut cmd = CommandWrap::with_new(program, |c: &mut Command| {
126            c.args(args).stdin(stdin).stdout(Stdio::piped()).stderr(Stdio::piped());
127            // Before the spec's own: what the run delivers is set again after.
128            for var in &withheld {
129                c.env_remove(var);
130            }
131            c.envs(spec.env.iter().map(|(k, v)| (k.as_str(), v.as_str())));
132            if let Some(dir) = &spec.cwd {
133                c.current_dir(dir);
134            }
135            if strip {
136                for var in shim::ENGINE_OVERRIDES {
137                    c.env_remove(var);
138                }
139            }
140        });
141        group(&mut cmd);
142        Ok(cmd)
143    }
144}
145
146impl ProcessRunner for SystemProcesses {
147    fn run<'a>(&'a self, spec: &'a ProcessSpec, on_line: OnLine<'a>) -> BoxFuture<'a, Result<Exit, ProcessError>> {
148        Box::pin(self.run_to_end(spec, on_line))
149    }
150}
151
152/// A spawned tool's tree, stopped when dropped before the tool exited (a timeout, a
153/// cancellation), with its entry in the run's tools when it was recorded: removed once the tool
154/// ended.
155struct Tree(Option<Box<dyn ChildWrapper>>, Arc<Stopping>, Option<ledger::Recorded>);
156
157impl Drop for Tree {
158    fn drop(&mut self) {
159        if let Some(child) = self.0.take() {
160            self.1.stop(child, self.2.take());
161        }
162    }
163}
164
165/// The program and arguments to start: a Windows `.cmd` tool through `cmd /C`.
166fn wrapped(spec: &ProcessSpec) -> (&str, Vec<&str>) {
167    let args = spec.args.iter().map(String::as_str);
168    if cfg!(windows) && shim::SHIMMED.contains(&spec.program.as_str()) {
169        return ("cmd", ["/C", spec.program.as_str()].into_iter().chain(args).collect());
170    }
171    (spec.program.as_str(), args.collect())
172}
173
174#[cfg(unix)]
175fn group(cmd: &mut CommandWrap) {
176    cmd.wrap(process_wrap::tokio::ProcessGroup::leader());
177}
178
179#[cfg(windows)]
180fn group(cmd: &mut CommandWrap) {
181    use windows::Win32::System::Threading::CREATE_NO_WINDOW;
182    // Headless: a status poll would otherwise flash a console window every few seconds.
183    cmd.wrap(process_wrap::tokio::CreationFlags(CREATE_NO_WINDOW));
184    cmd.wrap(process_wrap::tokio::JobObject);
185}
186
187/// The error of a tool that couldn't start: missing, or the OS's reason.
188fn spawned(program: &str, e: std::io::Error) -> ProcessError {
189    match e.kind() {
190        std::io::ErrorKind::NotFound => ProcessError::Missing { program: program.to_owned() },
191        _ => ProcessError::Io {
192            program: program.to_owned(),
193            source: e,
194        },
195    }
196}
197
198#[cfg(test)]
199#[path = "system_tests.rs"]
200mod tests;