isothrum_runner/process/
system.rs1use 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#[derive(Debug, Clone)]
26pub struct SystemProcesses {
27 strip_engine_overrides: bool,
29 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
39fn 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 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 #[must_use]
69 pub fn is_stopping(&self) -> bool {
70 self.stopping.any()
71 }
72
73 pub async fn stopped(&self) {
76 self.stopping.stopped().await;
77 }
78
79 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 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 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 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 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
152struct 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
165fn 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 cmd.wrap(process_wrap::tokio::CreationFlags(CREATE_NO_WINDOW));
184 cmd.wrap(process_wrap::tokio::JobObject);
185}
186
187fn 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;