use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;
use process_wrap::tokio::ChildWrapper;
#[cfg(unix)]
use process_wrap::tokio::CommandWrap;
#[cfg(unix)]
use tokio::process::Command;
use super::stopping::{GRACE, Removal, Stopping};
use super::{Exit, OnLine, ProcessError, ProcessRunner, ProcessSpec, ledger, lines, locale, shim};
use crate::BoxFuture;
#[derive(Debug, Clone)]
pub struct SystemProcesses {
strip_engine_overrides: bool,
stopping: Arc<Stopping>,
running: Arc<std::sync::Mutex<RunningSet>>,
}
impl Default for SystemProcesses {
fn default() -> SystemProcesses {
SystemProcesses::for_host(|v| std::env::var_os(v), std::env::home_dir().as_deref())
}
}
fn read_cli_config(path: &Path) -> Option<String> {
crate::store::if_there(std::fs::read_to_string(path)).unwrap_or_else(|e| {
tracing::warn!(
path = %path.display(),
error = %e,
"the Docker CLI's config couldn't be read: DOCKER_HOST and DOCKER_CONTEXT are kept for docker"
);
None
})
}
impl SystemProcesses {
fn for_host(var: impl Fn(&str) -> Option<std::ffi::OsString>, home: Option<&Path>) -> SystemProcesses {
let dir = var("DOCKER_CONFIG").map(std::path::PathBuf::from).or_else(|| home.map(|h| h.join(".docker")));
let config = dir.and_then(|d| read_cli_config(&d.join("config.json")));
SystemProcesses {
strip_engine_overrides: shim::strips_engine_overrides(config.as_deref()),
stopping: Arc::new(Stopping::new(GRACE)),
running: Arc::default(),
}
}
#[must_use]
pub fn is_stopping(&self) -> bool {
self.stopping.any()
}
pub async fn stopped(&self) {
self.stopping.stopped().await;
}
pub fn end_stopping(&self) {
self.stopping.end_now();
}
pub fn end_all_now(&self) {
self.stopping.end_now();
let running = std::mem::take(&mut *self.running.lock().unwrap_or_else(std::sync::PoisonError::into_inner));
for (pid, removal) in running {
kill_tree(pid);
if let Some(removal) = removal {
removal.run();
}
}
}
async fn run_to_end(&self, spec: &ProcessSpec, on_line: OnLine<'_>) -> Result<Exit, ProcessError> {
if let Some(arg) = shim::refused_arg(&spec.program, &spec.args) {
return Err(ProcessError::Refused {
program: spec.program.clone(),
why: format!("its argument `{}` holds a character cmd.exe would interpret", arg.escape_debug()),
});
}
let io = |source| ProcessError::Io {
program: spec.program.clone(),
source,
};
tracing::debug!(program = %spec.program, args = ?spec.args, "starting a process");
let launch = self.launch(spec).map_err(io)?;
let child = start(launch).map_err(|e| spawned(spec, e))?;
let removal = self.removal(spec);
let _running = child.id().map(|pid| Running::enter(&self.running, pid, removal.clone()));
let recorded = spec
.ledger_dir
.as_deref()
.zip(child.id())
.and_then(|(dir, pid)| ledger::Recorded::write(dir, pid, spec.container.as_deref()));
let mut tree = Tree {
child: Some(child),
stopping: Arc::clone(&self.stopping),
recorded,
removal,
};
let Some(started) = tree.child.as_deref_mut() else {
return Err(io(std::io::Error::other("the process went away")));
};
let status = tokio::select! {
biased;
status = lines::forward_lines(started, on_line) => status.map_err(io)?,
never = ledger::note_group(tree.recorded.as_ref()) => match never {},
};
tree.child = None;
tracing::debug!(program = %spec.program, code = ?status.code(), "process exited");
if shim::missing_behind_cmd(&spec.program, status.code()) {
return Err(ProcessError::Missing { program: spec.program.clone() });
}
Ok(Exit { code: status.code() })
}
fn removal(&self, spec: &ProcessSpec) -> Option<Removal> {
let name = spec.container.as_deref()?;
let inherited = std::env::vars_os().filter_map(|(k, _)| k.into_string().ok());
let withheld = shim::withheld(&spec.program, inherited);
let strip = self.strip_engine_overrides && shim::uses_engine(&spec.program);
let stripped = if strip {
shim::ENGINE_OVERRIDES.iter().map(|v| (*v).to_owned()).collect()
} else {
Vec::new()
};
Some(Removal {
program: spec.program.clone(),
name: name.to_owned(),
withheld,
env: spec.env.clone(),
stripped,
})
}
fn launch(&self, spec: &ProcessSpec) -> std::io::Result<Launch> {
let stdin = spec.stdin.as_ref().map(std::fs::File::open).transpose()?;
let strip = self.strip_engine_overrides && shim::uses_engine(&spec.program);
let inherited = std::env::vars_os().filter_map(|(k, _)| k.into_string().ok());
let mut env: Vec<(OsString, Option<OsString>)> = shim::withheld(&spec.program, inherited).into_iter().map(|var| (var.into(), None)).collect();
env.extend(
locale::settings(|name| std::env::var_os(name))
.into_iter()
.map(|(var, value)| (var.into(), value)),
);
env.extend(spec.env.iter().map(|(k, v)| (k.into(), Some(v.into()))));
if strip {
env.extend(shim::ENGINE_OVERRIDES.iter().map(|var| ((*var).into(), None)));
}
let (program, args) = wrapped(spec);
Ok(Launch {
program: program.to_owned(),
args: args.into_iter().map(str::to_owned).collect(),
env,
cwd: spec.cwd.clone(),
stdin,
})
}
}
#[derive(Debug)]
pub(super) struct Launch {
pub(super) program: String,
pub(super) args: Vec<String>,
pub(super) env: Vec<(OsString, Option<OsString>)>,
pub(super) cwd: Option<PathBuf>,
pub(super) stdin: Option<std::fs::File>,
}
#[cfg(unix)]
#[expect(clippy::disallowed_methods, reason = "the process module's spawner: every tool call of the runner starts here")]
fn start(launch: Launch) -> std::io::Result<Box<dyn ChildWrapper>> {
let stdin = launch.stdin.map_or_else(Stdio::null, Stdio::from);
let mut cmd = CommandWrap::with_new(&launch.program, |c: &mut Command| {
c.args(&launch.args).stdin(stdin).stdout(Stdio::piped()).stderr(Stdio::piped());
for (var, value) in &launch.env {
match value {
Some(value) => c.env(var, value),
None => c.env_remove(var),
};
}
if let Some(dir) = &launch.cwd {
c.current_dir(dir);
}
});
cmd.wrap(process_wrap::tokio::ProcessGroup::leader());
cmd.spawn()
}
#[cfg(windows)]
fn start(launch: Launch) -> std::io::Result<Box<dyn ChildWrapper>> {
super::job::spawn(launch)
}
impl ProcessRunner for SystemProcesses {
fn run<'a>(&'a self, spec: &'a ProcessSpec, on_line: OnLine<'a>) -> BoxFuture<'a, Result<Exit, ProcessError>> {
Box::pin(self.run_to_end(spec, on_line))
}
}
struct Tree {
child: Option<Box<dyn ChildWrapper>>,
stopping: Arc<Stopping>,
recorded: Option<ledger::Recorded>,
removal: Option<Removal>,
}
impl Drop for Tree {
fn drop(&mut self) {
if let Some(child) = self.child.take() {
self.stopping.stop(child, self.recorded.take(), self.removal.take());
}
}
}
type RunningSet = std::collections::BTreeMap<u32, Option<Removal>>;
struct Running(Arc<std::sync::Mutex<RunningSet>>, u32);
impl Running {
fn enter(set: &Arc<std::sync::Mutex<RunningSet>>, pid: u32, removal: Option<Removal>) -> Running {
set.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(pid, removal);
Running(Arc::clone(set), pid)
}
}
impl Drop for Running {
fn drop(&mut self) {
self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).remove(&self.1);
}
}
#[cfg(unix)]
fn kill_tree(pid: u32) {
use nix::sys::signal::{Signal, killpg};
use nix::unistd::Pid;
if let Some(group) = i32::try_from(pid).ok().filter(|p| *p > 1).map(Pid::from_raw)
&& let Err(e) = killpg(group, Signal::SIGKILL)
{
tracing::debug!(pid, error = %e, "a running tool's process group had ended");
}
}
#[cfg(windows)]
#[expect(clippy::disallowed_methods, reason = "the process module's own ending of a process tree")]
fn kill_tree(pid: u32) {
use std::os::windows::process::CommandExt as _;
use windows::Win32::System::Threading::CREATE_NO_WINDOW;
let ended = std::process::Command::new("taskkill")
.args(["/PID", &pid.to_string(), "/T", "/F"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.creation_flags(CREATE_NO_WINDOW.0)
.status();
if let Err(e) = ended {
tracing::warn!(pid, error = %e, "taskkill couldn't run to end a running tool");
}
}
fn wrapped(spec: &ProcessSpec) -> (&str, Vec<&str>) {
let args = spec.args.iter().map(String::as_str);
if cfg!(windows) && shim::SHIMMED.contains(&spec.program.as_str()) {
return ("cmd", ["/C", spec.program.as_str()].into_iter().chain(args).collect());
}
(spec.program.as_str(), args.collect())
}
fn spawned(spec: &ProcessSpec, e: std::io::Error) -> ProcessError {
let program = spec.program.clone();
let folder_gone = spec.cwd.as_deref().filter(|dir| !dir.is_dir());
match (e.kind(), folder_gone) {
(_, Some(dir)) => ProcessError::Io {
program,
source: std::io::Error::new(std::io::ErrorKind::NotFound, format!("its working folder {} doesn't exist", dir.display())),
},
(std::io::ErrorKind::NotFound, None) => ProcessError::Missing { program },
_ => ProcessError::Io { program, source: e },
}
}
#[cfg(test)]
mod tests;