uv_command_support/child.rs
1use std::path::PathBuf;
2
3use anyhow::bail;
4use tokio::process::Child;
5use tracing::debug;
6use uv_fs::Simplified;
7use uv_warnings::warn_user;
8
9use crate::ExitStatus;
10
11/// Read dotenv files into an overlay for a spawned process.
12///
13/// These values intentionally do not mutate uv's process environment and cannot mutate
14/// the current uv process' settings.
15pub fn read_env_files(env_files: &[PathBuf]) -> anyhow::Result<Vec<(String, String)>> {
16 let mut environment = Vec::new();
17
18 for env_file_path in env_files.iter().rev().map(PathBuf::as_path) {
19 let iter = match dotenvy::from_path_iter(env_file_path) {
20 Err(dotenvy::Error::Io(err)) if err.kind() == std::io::ErrorKind::NotFound => {
21 bail!(
22 "No environment file found at: {}",
23 env_file_path.simplified_display()
24 );
25 }
26 Err(dotenvy::Error::Io(err)) => {
27 bail!(
28 "Failed to read environment file `{}`: {err}",
29 env_file_path.simplified_display()
30 );
31 }
32 Err(dotenvy::Error::LineParse(content, position)) => {
33 warn_user!(
34 "Failed to parse environment file `{}` at position {position}: {content}",
35 env_file_path.simplified_display(),
36 );
37 continue;
38 }
39 Err(err) => {
40 warn_user!(
41 "Failed to parse environment file `{}`: {err}",
42 env_file_path.simplified_display(),
43 );
44 continue;
45 }
46 Ok(iter) => iter,
47 };
48
49 let mut parsed = true;
50 for item in iter {
51 match item {
52 Ok((key, value)) => {
53 if std::env::var(&key).is_err() {
54 environment.push((key, value));
55 }
56 }
57 Err(dotenvy::Error::Io(err)) => {
58 bail!(
59 "Failed to read environment file `{}`: {err}",
60 env_file_path.simplified_display()
61 );
62 }
63 Err(dotenvy::Error::LineParse(content, position)) => {
64 warn_user!(
65 "Failed to parse environment file `{}` at position {position}: {content}",
66 env_file_path.simplified_display(),
67 );
68 parsed = false;
69 break;
70 }
71 Err(err) => {
72 warn_user!(
73 "Failed to parse environment file `{}`: {err}",
74 env_file_path.simplified_display(),
75 );
76 parsed = false;
77 break;
78 }
79 }
80 }
81
82 if parsed {
83 debug!(
84 "Read environment file at: {}",
85 env_file_path.simplified_display()
86 );
87 }
88 }
89
90 // `dotenvy::from_path` preserves the first loaded value, while `Command::envs` preserves the
91 // last value set for the child process.
92 environment.reverse();
93
94 Ok(environment)
95}
96
97/// Wait for the child process to complete, handling signals and error codes.
98///
99/// Note that this registers handles to ignore some signals in the parent process. This is safe as
100/// long as the command is the last thing that runs in this process; otherwise, we'd need to restore
101/// the default signal handlers after the command completes.
102pub async fn run_to_completion(mut handle: Child) -> anyhow::Result<ExitStatus> {
103 // On Unix, the terminal driver will send SIGINT to the active process group when a user presses
104 // `Ctrl-C`. In general, this means that uv should ignore SIGINT, allowing the child process to
105 // cleanly exit instead. If uv forwarded the SIGINT immediately, the child process would receive
106 // _two_ SIGINT signals which has semantic meaning for some programs, i.e., slow exit on the
107 // first signal and fast exit on the second. The exception to this is if a child process changes
108 // its process group, in which case the terminal driver will _not_ send SIGINT to the child
109 // process and uv must take ownership of forwarding the signal.
110 //
111 // Note the above only applies in an interactive terminal. If a signal is sent directly to the
112 // uv parent process (e.g., `kill -2 <pid>`), the process group is not involved and a signal is
113 // not sent to the child by default. In this context, uv must forward the signal to the child.
114 // uv checks if stdin is a TTY as a heuristic to determine if uv is running in an interactive
115 // terminal. When not in an interactive terminal, uv will forward SIGINT to the child.
116 //
117 // Use of SIGTERM is also a bit complicated. If a terminal receives a SIGTERM, it just waits for
118 // its children to exit — multiple SIGTERMs do not have any effect and the signals are not
119 // forwarded to the children. Consequently, the description for SIGINT above does not apply to
120 // SIGTERM in the terminal driver. It is _possible_ to have a parent process that sends a
121 // SIGTERM to the process group; for example, `tini` supports this via a `-g` option. In this
122 // case, it's possible that uv will improperly send a second SIGTERM to the child process.
123 // However, this seems preferable to not forwarding it in the first place. In the Docker case,
124 // if `uv` is invoked directly (instead of via an init system), it's PID 1 which has a
125 // special-cased default signal handler for SIGTERM by default. Generally, if a process receives
126 // a SIGTERM and does not have a SIGTERM handler, it is terminated. However, if PID 1 receives a
127 // SIGTERM, it is not terminated. In this context, it is essential for uv to forward the SIGTERM
128 // to the child process or the process will not be killable.
129 #[cfg(unix)]
130 let status = {
131 use std::io::{IsTerminal, stdin};
132 use std::ops::Deref;
133
134 use anyhow::Context;
135 use nix::sys::signal;
136 use nix::unistd::{Pid, getpgid};
137 use tokio::select;
138 use tokio::signal::unix::{Signal, SignalKind, signal as handle_signal};
139
140 /// A wrapper for a signal handler that is not available on all platforms, `recv` never
141 /// returns on unsupported platforms.
142 #[allow(dead_code)]
143 enum PlatformSpecificSignal {
144 Signal(Signal),
145 Dummy,
146 }
147
148 impl PlatformSpecificSignal {
149 async fn recv(&mut self) -> Option<()> {
150 match self {
151 Self::Signal(signal) => signal.recv().await,
152 Self::Dummy => std::future::pending().await,
153 }
154 }
155 }
156
157 /// Simple new type for `Pid` allowing construction from [`Child`].
158 ///
159 /// `None` if the child process has exited or the PID is invalid.
160 struct ChildPid(Option<Pid>);
161
162 impl Deref for ChildPid {
163 type Target = Option<Pid>;
164 fn deref(&self) -> &Self::Target {
165 &self.0
166 }
167 }
168
169 impl From<&Child> for ChildPid {
170 fn from(child: &Child) -> Self {
171 Self(
172 child
173 .id()
174 .and_then(|id| id.try_into().ok())
175 .map(Pid::from_raw),
176 )
177 }
178 }
179
180 // Get the parent PGID
181 let parent_pgid = getpgid(None).context("Failed to get current PID")?;
182 if let Some(child_pid) = *ChildPid::from(&handle) {
183 debug!("Spawned child {child_pid} in process group {parent_pgid}");
184 }
185
186 let mut sigterm_handle = handle_signal(SignalKind::terminate())?;
187 let mut sigint_handle = handle_signal(SignalKind::interrupt())?;
188
189 // The following signals are terminal by default, but can have user defined handlers.
190 // Forward them to the child process for handling.
191 let mut sigusr1_handle = handle_signal(SignalKind::user_defined1())?;
192 let mut sigusr2_handle = handle_signal(SignalKind::user_defined2())?;
193 let mut sighup_handle = handle_signal(SignalKind::hangup())?;
194 let mut sigalrm_handle = handle_signal(SignalKind::alarm())?;
195 let mut sigquit_handle = handle_signal(SignalKind::quit())?;
196
197 // The following signals are ignored by default, but can be have user defined handlers.
198 // Forward them to the child process for handling.
199 let mut sigwinch_handle = handle_signal(SignalKind::window_change())?;
200 let mut sigpipe_handle = handle_signal(SignalKind::pipe())?;
201
202 // This signal is only available on some platforms, copied from `tokio::signal::unix`
203 #[cfg(any(
204 target_os = "dragonfly",
205 target_os = "freebsd",
206 target_os = "macos",
207 target_os = "netbsd",
208 target_os = "openbsd",
209 target_os = "illumos",
210 ))]
211 let mut siginfo_handle = PlatformSpecificSignal::Signal(handle_signal(SignalKind::info())?);
212
213 #[cfg(not(any(
214 target_os = "dragonfly",
215 target_os = "freebsd",
216 target_os = "macos",
217 target_os = "netbsd",
218 target_os = "openbsd",
219 target_os = "illumos",
220 )))]
221 let mut siginfo_handle = PlatformSpecificSignal::Dummy;
222
223 // Use TTY detection as a heuristic
224 let is_interactive = stdin().is_terminal();
225
226 // Notably, we do not handle `SIGCHLD` (sent when a child process status changes) and
227 // `SIGIO` or `SIGPOLL` (sent when a file descriptor is ready for io) as they don't make
228 // sense for this parent / child relationship.
229
230 loop {
231 select! {
232 result = handle.wait() => {
233 break result;
234 },
235 _ = sigint_handle.recv() => {
236 // See above for commentary on handling of SIGINT.
237
238 // If the child has already exited, we can't send it signals
239 let Some(child_pid) = *ChildPid::from(&handle) else {
240 debug!("Received SIGINT, but the child has already exited");
241 continue;
242 };
243
244 // Check if the child pgid has changed
245 let child_pgid = getpgid(Some(child_pid)).context("Failed to get PID of child process")?;
246
247 // If the pgid _differs_ from the parent, the child will not receive a SIGINT
248 // and we should forward it. If we think we're not in an interactive terminal,
249 // forward the signal unconditionally.
250 if child_pgid == parent_pgid && is_interactive {
251 debug!("Received SIGINT, assuming the child received it from the terminal driver");
252 continue;
253 }
254
255 // The terminal may still be forwarding these signals, give the child a moment
256 // to handle that signal before hitting it with another one
257 debug!("Received SIGINT, forwarding to child at {child_pid} in 200ms");
258 tokio::time::sleep(std::time::Duration::from_millis(200)).await;
259 let _ = signal::kill(child_pid, signal::Signal::SIGINT);
260 },
261 _ = sigterm_handle.recv() => {
262 // If the child has already exited, we can't send it signals
263 let Some(child_pid) = *ChildPid::from(&handle) else {
264 debug!("Received SIGTERM, but the child has already exited");
265 continue;
266 };
267
268 // We unconditionally forward SIGTERM to the child process; unlike SIGINT, this
269 // isn't usually handled by the terminal.
270 debug!("Received SIGTERM, forwarding to child at {child_pid}");
271 let _ = signal::kill(child_pid, signal::Signal::SIGTERM);
272 }
273 _ = sigusr1_handle.recv() => {
274 let Some(child_pid) = *ChildPid::from(&handle) else {
275 debug!("Received SIGUSR1, but the child has already exited");
276 continue;
277 };
278
279 // We unconditionally forward SIGUSR1 to the child process.
280 debug!("Received SIGUSR1, forwarding to child at {child_pid}");
281 let _ = signal::kill(child_pid, signal::Signal::SIGUSR1);
282 }
283 _ = sigusr2_handle.recv() => {
284 let Some(child_pid) = *ChildPid::from(&handle) else {
285 debug!("Received SIGUSR2, but the child has already exited");
286 continue;
287 };
288
289 // We unconditionally forward SIGUSR2 to the child process.
290 debug!("Received SIGUSR2, forwarding to child at {child_pid}");
291 let _ = signal::kill(child_pid, signal::Signal::SIGUSR2);
292 }
293 _ = sighup_handle.recv() => {
294 let Some(child_pid) = *ChildPid::from(&handle) else {
295 debug!("Received SIGHUP, but the child has already exited");
296 continue;
297 };
298
299 // We unconditionally forward SIGHUP to the child process.
300 debug!("Received SIGHUP, forwarding to child at {child_pid}");
301 let _ = signal::kill(child_pid, signal::Signal::SIGHUP);
302 }
303 _ = sigalrm_handle.recv() => {
304 let Some(child_pid) = *ChildPid::from(&handle) else {
305 debug!("Received SIGALRM, but the child has already exited");
306 continue;
307 };
308
309 // We unconditionally forward SIGALRM to the child process.
310 debug!("Received SIGALRM, forwarding to child at {child_pid}");
311 let _ = signal::kill(child_pid, signal::Signal::SIGALRM);
312 }
313 _ = sigquit_handle.recv() => {
314 let Some(child_pid) = *ChildPid::from(&handle) else {
315 debug!("Received SIGQUIT, but the child has already exited");
316 continue;
317 };
318
319 // We unconditionally forward SIGQUIT to the child process.
320 debug!("Received SIGQUIT, forwarding to child at {child_pid}");
321 let _ = signal::kill(child_pid, signal::Signal::SIGQUIT);
322 }
323 _ = sigwinch_handle.recv() => {
324 let Some(child_pid) = *ChildPid::from(&handle) else {
325 debug!("Received SIGWINCH, but the child has already exited");
326 continue;
327 };
328
329 // We unconditionally forward SIGWINCH to the child process.
330 debug!("Received SIGWINCH, forwarding to child at {child_pid}");
331 let _ = signal::kill(child_pid, signal::Signal::SIGWINCH);
332 }
333 _ = sigpipe_handle.recv() => {
334 let Some(child_pid) = *ChildPid::from(&handle) else {
335 debug!("Received SIGPIPE, but the child has already exited");
336 continue;
337 };
338
339 // We unconditionally forward SIGPIPE to the child process.
340 debug!("Received SIGPIPE, forwarding to child at {child_pid}");
341 let _ = signal::kill(child_pid, signal::Signal::SIGPIPE);
342 }
343 _ = siginfo_handle.recv() => {
344 let Some(child_pid) = *ChildPid::from(&handle) else {
345 debug!("Received SIGINFO, but the child has already exited");
346 continue;
347 };
348
349 // We unconditionally forward SIGINFO to the child process.
350 debug!("Received SIGINFO, forwarding to child at {child_pid}");
351 #[cfg(any(
352 target_os = "dragonfly",
353 target_os = "freebsd",
354 target_os = "macos",
355 target_os = "netbsd",
356 target_os = "openbsd",
357 target_os = "illumos",
358 ))]
359 let _ = signal::kill(child_pid, signal::Signal::SIGINFO);
360 }
361 };
362 }
363 }?;
364
365 // On Windows, we just ignore the console CTRL_C_EVENT and assume it will always be sent to the
366 // child by the console. There's not a clear programmatic way to forward the signal anyway.
367 #[cfg(not(unix))]
368 let status = {
369 let _ctrl_c_handler =
370 tokio::spawn(async { while tokio::signal::ctrl_c().await.is_ok() {} });
371 handle.wait().await?
372 };
373
374 // Exit based on the result of the command.
375 if let Some(code) = status.code() {
376 debug!("Command exited with code: {code}");
377 if let Ok(code) = u8::try_from(code) {
378 Ok(ExitStatus::External(code))
379 } else {
380 #[expect(clippy::exit)]
381 std::process::exit(code);
382 }
383 } else {
384 #[cfg(unix)]
385 {
386 use std::os::unix::process::ExitStatusExt;
387 debug!("Command exited with signal: {:?}", status.signal());
388 // Following https://tldp.org/LDP/abs/html/exitcodes.html, a fatal signal n gets the
389 // exit code 128+n
390 if let Some(mapped_code) = status
391 .signal()
392 .and_then(|signal| u8::try_from(signal).ok())
393 .and_then(|signal| 128u8.checked_add(signal))
394 {
395 return Ok(ExitStatus::External(mapped_code));
396 }
397 }
398 Ok(ExitStatus::Failure)
399 }
400}