Skip to main content

isothrum_runner/process/
system.rs

1//! Real processes: each tool in its own process group (unix, through `process-wrap`) or created
2//! inside a kill-on-close job object of its own (Windows, the `job` module), so a timeout, a
3//! cancellation or this process's death ends the whole tree it started (`vagrant` is a wrapper
4//! around `ruby`, `cmd /C az` around `python`), headless on Windows. A
5//! tool cut short is asked to stop first (see [`super::stopping`]). Each tool speaks in the C
6//! locale ([`super::locale`]).
7
8use std::ffi::OsString;
9use std::path::{Path, PathBuf};
10use std::process::Stdio;
11use std::sync::Arc;
12
13use process_wrap::tokio::ChildWrapper;
14#[cfg(unix)]
15use process_wrap::tokio::CommandWrap;
16#[cfg(unix)]
17use tokio::process::Command;
18
19use super::stopping::{GRACE, Removal, Stopping};
20use super::{Exit, OnLine, ProcessError, ProcessRunner, ProcessSpec, ledger, lines, locale, shim};
21use crate::BoxFuture;
22
23/// Starts real processes. [`SystemProcesses::default`] reads the Docker CLI's config
24/// (`$DOCKER_CONFIG/config.json`, else `~/.docker/config.json`) to learn whether the user picked
25/// an engine context of their own.
26///
27/// A tool cut short (its operation's future dropped: a cancel, a step's timeout) is asked to stop
28/// (SIGINT to its process group on Unix, Ctrl-C on its console on Windows, so Terraform saves its
29/// state) and ended once it has exited, or 30 seconds later. Its clones share the tools
30/// stopping: a process about to exit waits for them with [`SystemProcesses::stopped`].
31#[derive(Debug, Clone)]
32pub struct SystemProcesses {
33    /// Drop `DOCKER_HOST` and `DOCKER_CONTEXT` for `docker` (the user picked a context).
34    strip_engine_overrides: bool,
35    /// The tools cut short that are still stopping.
36    stopping: Arc<Stopping>,
37    /// The process groups (unix) or trees (Windows) of the tools running now, by leader pid, each
38    /// with the removal of the container it runs in, if any.
39    running: Arc<std::sync::Mutex<RunningSet>>,
40}
41
42impl Default for SystemProcesses {
43    fn default() -> SystemProcesses {
44        SystemProcesses::for_host(|v| std::env::var_os(v), std::env::home_dir().as_deref())
45    }
46}
47
48/// The Docker CLI's config at `path`: none when there is none, and when it can't be read, which is
49/// traced (whether the user picked a context is then unknown, so the inherited engine variables
50/// stay).
51fn read_cli_config(path: &Path) -> Option<String> {
52    crate::store::if_there(std::fs::read_to_string(path)).unwrap_or_else(|e| {
53        tracing::warn!(
54            path = %path.display(),
55            error = %e,
56            "the Docker CLI's config couldn't be read: DOCKER_HOST and DOCKER_CONTEXT are kept for docker"
57        );
58        None
59    })
60}
61
62impl SystemProcesses {
63    /// Real processes, the Docker CLI's config read from `$DOCKER_CONFIG/config.json`, else
64    /// `<home>/.docker/config.json` (`var` reads the environment, `home` is the user's): it says
65    /// whether the user picked an engine context of their own. A `DOCKER_CONFIG` that isn't UTF-8
66    /// is a path like any other.
67    fn for_host(var: impl Fn(&str) -> Option<std::ffi::OsString>, home: Option<&Path>) -> SystemProcesses {
68        let dir = var("DOCKER_CONFIG").map(std::path::PathBuf::from).or_else(|| home.map(|h| h.join(".docker")));
69        let config = dir.and_then(|d| read_cli_config(&d.join("config.json")));
70        SystemProcesses {
71            strip_engine_overrides: shim::strips_engine_overrides(config.as_deref()),
72            stopping: Arc::new(Stopping::new(GRACE)),
73            running: Arc::default(),
74        }
75    }
76
77    /// Whether a tool cut short is still stopping.
78    #[must_use]
79    pub fn is_stopping(&self) -> bool {
80        self.stopping.any()
81    }
82
83    /// Once every tool cut short has ended: at the latest 30 seconds after the last was cut short.
84    /// At once when none is stopping.
85    pub async fn stopped(&self) {
86        self.stopping.stopped().await;
87    }
88
89    /// Ends every tool cut short that is still stopping, at once (a second Ctrl-C).
90    pub fn end_stopping(&self) {
91        self.stopping.end_now();
92    }
93
94    /// Ends every tool running now and every one still stopping, at once: for an embedder about to
95    /// exit, whose futures are never dropped (a status read's `docker compose ps` would outlive it).
96    pub fn end_all_now(&self) {
97        self.stopping.end_now();
98        let running = std::mem::take(&mut *self.running.lock().unwrap_or_else(std::sync::PoisonError::into_inner));
99        for (pid, removal) in running {
100            kill_tree(pid);
101            if let Some(removal) = removal {
102                removal.run();
103            }
104        }
105    }
106
107    async fn run_to_end(&self, spec: &ProcessSpec, on_line: OnLine<'_>) -> Result<Exit, ProcessError> {
108        if let Some(arg) = shim::refused_arg(&spec.program, &spec.args) {
109            return Err(ProcessError::Refused {
110                program: spec.program.clone(),
111                why: format!("its argument `{}` holds a character cmd.exe would interpret", arg.escape_debug()),
112            });
113        }
114        let io = |source| ProcessError::Io {
115            program: spec.program.clone(),
116            source,
117        };
118        // The program and its arguments only: values reach a tool through its environment,
119        // which is never logged.
120        tracing::debug!(program = %spec.program, args = ?spec.args, "starting a process");
121        let launch = self.launch(spec).map_err(io)?;
122        let child = start(launch).map_err(|e| spawned(spec, e))?;
123        // Declared before the tree, so dropped after it: the tree's own stop runs first.
124        let removal = self.removal(spec);
125        let _running = child.id().map(|pid| Running::enter(&self.running, pid, removal.clone()));
126        let recorded = spec
127            .ledger_dir
128            .as_deref()
129            .zip(child.id())
130            .and_then(|(dir, pid)| ledger::Recorded::write(dir, pid, spec.container.as_deref()));
131        let mut tree = Tree {
132            child: Some(child),
133            stopping: Arc::clone(&self.stopping),
134            recorded,
135            removal,
136        };
137        let Some(started) = tree.child.as_deref_mut() else {
138            return Err(io(std::io::Error::other("the process went away")));
139        };
140        // While it runs, what it starts in its group is recorded beside it.
141        let status = tokio::select! {
142            biased;
143            status = lines::forward_lines(started, on_line) => status.map_err(io)?,
144            never = ledger::note_group(tree.recorded.as_ref()) => match never {},
145        };
146        // It exited on its own: what it left running is its business.
147        tree.child = None;
148        tracing::debug!(program = %spec.program, code = ?status.code(), "process exited");
149        if shim::missing_behind_cmd(&spec.program, status.code()) {
150            return Err(ProcessError::Missing { program: spec.program.clone() });
151        }
152        Ok(Exit { code: status.code() })
153    }
154
155    /// The removal of the container `spec`'s tool runs in, when it names one, with the
156    /// environment the tool gets, so it reaches the same engine.
157    fn removal(&self, spec: &ProcessSpec) -> Option<Removal> {
158        let name = spec.container.as_deref()?;
159        let inherited = std::env::vars_os().filter_map(|(k, _)| k.into_string().ok());
160        let withheld = shim::withheld(&spec.program, inherited);
161        let strip = self.strip_engine_overrides && shim::uses_engine(&spec.program);
162        let stripped = if strip {
163            shim::ENGINE_OVERRIDES.iter().map(|v| (*v).to_owned()).collect()
164        } else {
165            Vec::new()
166        };
167        Some(Removal {
168            program: spec.program.clone(),
169            name: name.to_owned(),
170            withheld,
171            env: spec.env.clone(),
172            stripped,
173        })
174    }
175
176    /// What starting `spec`'s tool takes: its program and arguments (a shimmed tool through
177    /// `cmd /C`), its input, and the changes to this process's environment it gets, in order.
178    fn launch(&self, spec: &ProcessSpec) -> std::io::Result<Launch> {
179        let stdin = spec.stdin.as_ref().map(std::fs::File::open).transpose()?;
180        let strip = self.strip_engine_overrides && shim::uses_engine(&spec.program);
181        let inherited = std::env::vars_os().filter_map(|(k, _)| k.into_string().ok());
182        // Before the spec's own: what the run delivers is set again after.
183        let mut env: Vec<(OsString, Option<OsString>)> = shim::withheld(&spec.program, inherited).into_iter().map(|var| (var.into(), None)).collect();
184        env.extend(
185            locale::settings(|name| std::env::var_os(name))
186                .into_iter()
187                .map(|(var, value)| (var.into(), value)),
188        );
189        env.extend(spec.env.iter().map(|(k, v)| (k.into(), Some(v.into()))));
190        if strip {
191            env.extend(shim::ENGINE_OVERRIDES.iter().map(|var| ((*var).into(), None)));
192        }
193        let (program, args) = wrapped(spec);
194        Ok(Launch {
195            program: program.to_owned(),
196            args: args.into_iter().map(str::to_owned).collect(),
197            env,
198            cwd: spec.cwd.clone(),
199            stdin,
200        })
201    }
202}
203
204/// What starting a tool takes, whatever the OS.
205#[derive(Debug)]
206pub(super) struct Launch {
207    /// The program, as started (`cmd` for a shimmed tool).
208    pub(super) program: String,
209    pub(super) args: Vec<String>,
210    /// Changes to this process's environment, in order: a value sets the variable, none removes it.
211    pub(super) env: Vec<(OsString, Option<OsString>)>,
212    pub(super) cwd: Option<PathBuf>,
213    /// Its input, else none (the null device).
214    pub(super) stdin: Option<std::fs::File>,
215}
216
217/// Starts `launch` as the leader of a process group of its own, its output piped.
218#[cfg(unix)]
219#[expect(clippy::disallowed_methods, reason = "the process module's spawner: every tool call of the runner starts here")]
220fn start(launch: Launch) -> std::io::Result<Box<dyn ChildWrapper>> {
221    let stdin = launch.stdin.map_or_else(Stdio::null, Stdio::from);
222    let mut cmd = CommandWrap::with_new(&launch.program, |c: &mut Command| {
223        c.args(&launch.args).stdin(stdin).stdout(Stdio::piped()).stderr(Stdio::piped());
224        for (var, value) in &launch.env {
225            match value {
226                Some(value) => c.env(var, value),
227                None => c.env_remove(var),
228            };
229        }
230        if let Some(dir) = &launch.cwd {
231            c.current_dir(dir);
232        }
233    });
234    cmd.wrap(process_wrap::tokio::ProcessGroup::leader());
235    cmd.spawn()
236}
237
238/// Starts `launch` inside a kill-on-close job object of its own, headless, its output piped
239/// ([`super::job`]).
240#[cfg(windows)]
241fn start(launch: Launch) -> std::io::Result<Box<dyn ChildWrapper>> {
242    super::job::spawn(launch)
243}
244
245impl ProcessRunner for SystemProcesses {
246    fn run<'a>(&'a self, spec: &'a ProcessSpec, on_line: OnLine<'a>) -> BoxFuture<'a, Result<Exit, ProcessError>> {
247        Box::pin(self.run_to_end(spec, on_line))
248    }
249}
250
251/// A spawned tool's tree, stopped when dropped before the tool exited (a timeout, a
252/// cancellation), with its entry in the run's tools when it was recorded (removed once the tool
253/// ended) and the removal of the container it runs in, if any.
254struct Tree {
255    /// The process, until it is waited for.
256    child: Option<Box<dyn ChildWrapper>>,
257    /// What stops it (and its group) when it is dropped unwaited.
258    stopping: Arc<Stopping>,
259    /// Its ledger entry, taken by the stop.
260    recorded: Option<ledger::Recorded>,
261    /// The removal of the container it runs in, taken by the stop.
262    removal: Option<Removal>,
263}
264
265impl Drop for Tree {
266    fn drop(&mut self) {
267        if let Some(child) = self.child.take() {
268            self.stopping.stop(child, self.recorded.take(), self.removal.take());
269        }
270    }
271}
272
273/// The tools running now, by leader pid, each with the removal of its container, if any.
274type RunningSet = std::collections::BTreeMap<u32, Option<Removal>>;
275
276/// A tool in [`SystemProcesses`]'s running set while this lives.
277struct Running(Arc<std::sync::Mutex<RunningSet>>, u32);
278
279impl Running {
280    fn enter(set: &Arc<std::sync::Mutex<RunningSet>>, pid: u32, removal: Option<Removal>) -> Running {
281        set.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(pid, removal);
282        Running(Arc::clone(set), pid)
283    }
284}
285
286impl Drop for Running {
287    fn drop(&mut self) {
288        self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).remove(&self.1);
289    }
290}
291
292/// Kills the process group `pid` leads, at once.
293#[cfg(unix)]
294fn kill_tree(pid: u32) {
295    use nix::sys::signal::{Signal, killpg};
296    use nix::unistd::Pid;
297    if let Some(group) = i32::try_from(pid).ok().filter(|p| *p > 1).map(Pid::from_raw)
298        && let Err(e) = killpg(group, Signal::SIGKILL)
299    {
300        tracing::debug!(pid, error = %e, "a running tool's process group had ended");
301    }
302}
303
304/// Kills process `pid` and its tree (`taskkill /T /F`), waiting for taskkill.
305#[cfg(windows)]
306#[expect(clippy::disallowed_methods, reason = "the process module's own ending of a process tree")]
307fn kill_tree(pid: u32) {
308    use std::os::windows::process::CommandExt as _;
309    use windows::Win32::System::Threading::CREATE_NO_WINDOW;
310    let ended = std::process::Command::new("taskkill")
311        .args(["/PID", &pid.to_string(), "/T", "/F"])
312        .stdin(Stdio::null())
313        .stdout(Stdio::null())
314        .stderr(Stdio::null())
315        .creation_flags(CREATE_NO_WINDOW.0)
316        .status();
317    if let Err(e) = ended {
318        tracing::warn!(pid, error = %e, "taskkill couldn't run to end a running tool");
319    }
320}
321
322/// The program and arguments to start: a Windows `.cmd` tool through `cmd /C`.
323fn wrapped(spec: &ProcessSpec) -> (&str, Vec<&str>) {
324    let args = spec.args.iter().map(String::as_str);
325    if cfg!(windows) && shim::SHIMMED.contains(&spec.program.as_str()) {
326        return ("cmd", ["/C", spec.program.as_str()].into_iter().chain(args).collect());
327    }
328    (spec.program.as_str(), args.collect())
329}
330
331/// The error of the tool `spec` that couldn't start: missing, or the OS's reason. A start in a
332/// working folder that isn't there is said of the folder, whatever the OS answers (Unix:
333/// `NotFound`, as for a program; Windows: "The directory name is invalid"), never taken for a
334/// tool that isn't installed.
335fn spawned(spec: &ProcessSpec, e: std::io::Error) -> ProcessError {
336    let program = spec.program.clone();
337    let folder_gone = spec.cwd.as_deref().filter(|dir| !dir.is_dir());
338    match (e.kind(), folder_gone) {
339        (_, Some(dir)) => ProcessError::Io {
340            program,
341            source: std::io::Error::new(std::io::ErrorKind::NotFound, format!("its working folder {} doesn't exist", dir.display())),
342        },
343        (std::io::ErrorKind::NotFound, None) => ProcessError::Missing { program },
344        _ => ProcessError::Io { program, source: e },
345    }
346}
347
348#[cfg(test)]
349mod tests;