1use 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#[derive(Debug, Clone)]
32pub struct SystemProcesses {
33 strip_engine_overrides: bool,
35 stopping: Arc<Stopping>,
37 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
48fn 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 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 #[must_use]
79 pub fn is_stopping(&self) -> bool {
80 self.stopping.any()
81 }
82
83 pub async fn stopped(&self) {
86 self.stopping.stopped().await;
87 }
88
89 pub fn end_stopping(&self) {
91 self.stopping.end_now();
92 }
93
94 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 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 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 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 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 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 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 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#[derive(Debug)]
206pub(super) struct Launch {
207 pub(super) program: String,
209 pub(super) args: Vec<String>,
210 pub(super) env: Vec<(OsString, Option<OsString>)>,
212 pub(super) cwd: Option<PathBuf>,
213 pub(super) stdin: Option<std::fs::File>,
215}
216
217#[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#[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
251struct Tree {
255 child: Option<Box<dyn ChildWrapper>>,
257 stopping: Arc<Stopping>,
259 recorded: Option<ledger::Recorded>,
261 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
273type RunningSet = std::collections::BTreeMap<u32, Option<Removal>>;
275
276struct 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#[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#[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
322fn 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
331fn 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;