Skip to main content

rig_tools/
process.rs

1//! Child processes started in a session of their own, such as `shell`
2//! commands, so they never read the terminal and are killed as a group, and
3//! the [`Launcher`] that says how every tool starts them. A [`Process`] it
4//! [spawns](Launcher::spawn) takes its input, hands its output over line
5//! by line, and is stopped gently or killed with its whole group.
6//!
7//! A process that dies without stopping its children, such as on
8//! `SIGKILL`, leaves their groups running. [`record_groups`] keeps the
9//! groups not reaped yet in a file, for a supervisor that outlives it to
10//! kill.
11
12use std::collections::BTreeSet;
13use std::ffi::{OsStr, OsString};
14use std::io::{self, Read, Write as _};
15use std::path::{Path, PathBuf};
16use std::process::{Child, Command, ExitStatus, Output, Stdio};
17use std::sync::atomic::{AtomicU32, Ordering};
18use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel};
19use std::sync::{Arc, Mutex, PoisonError};
20use std::thread;
21use std::time::{Duration, Instant};
22
23/// How tools start processes: under a wrapper program (a sandbox such as
24/// `bwrap … --`, `nice -n 10`, a container's `exec`), in a directory, with
25/// variables set and removed. Every command it builds is [`detach`]ed. A
26/// host that hands one launcher to every tool that starts processes
27/// ([`Shell`](crate::Shell), a background job, a formatter) puts them all
28/// under the same policy.
29///
30/// ```
31/// use rig_tools::process::Launcher;
32///
33/// let launcher = Launcher::default()
34///     .wrapped(["nice", "-n", "10"])
35///     .in_dir("/srv/project")
36///     .with_env("CI", "1")
37///     .without_env(["AGENT_TOKEN"]);
38/// let mut command = launcher.command("sh");
39/// command.args(["-c", "make test"]);
40/// assert_eq!(command.get_program(), "nice");
41/// let args: Vec<_> = command.get_args().collect();
42/// assert_eq!(args, ["-n", "10", "sh", "-c", "make test"]);
43/// assert_eq!(command.get_current_dir(), Some(std::path::Path::new("/srv/project")));
44/// ```
45#[derive(Clone, Debug, Default, PartialEq, Eq)]
46pub struct Launcher {
47    /// The program and arguments every command runs under; empty runs the
48    /// command itself.
49    pub prefix: Vec<OsString>,
50    /// The directory commands start in; `None` is this process's.
51    pub cwd: Option<PathBuf>,
52    /// Variables set for every command.
53    pub env: Vec<(OsString, OsString)>,
54    /// Variables no command inherits, such as those that make a program
55    /// act as the agent that runs it.
56    pub unset_env: Vec<OsString>,
57}
58
59impl Launcher {
60    /// The same launcher, running every command under `prefix`.
61    pub fn wrapped(mut self, prefix: impl IntoIterator<Item = impl Into<OsString>>) -> Self {
62        self.prefix = prefix.into_iter().map(Into::into).collect();
63        self
64    }
65
66    /// The same launcher, starting commands in `dir`.
67    pub fn in_dir(mut self, dir: impl Into<PathBuf>) -> Self {
68        self.cwd = Some(dir.into());
69        self
70    }
71
72    /// The same launcher, setting `name` to `value` for every command.
73    pub fn with_env(mut self, name: impl Into<OsString>, value: impl Into<OsString>) -> Self {
74        self.env.push((name.into(), value.into()));
75        self
76    }
77
78    /// The same launcher, keeping `names` from every command.
79    pub fn without_env(mut self, names: impl IntoIterator<Item = impl Into<OsString>>) -> Self {
80        self.unset_env.extend(names.into_iter().map(Into::into));
81        self
82    }
83
84    /// A detached command that runs `program` under this launcher's policy;
85    /// add the program's arguments to it.
86    pub fn command(&self, program: impl AsRef<OsStr>) -> Command {
87        let mut command = match self.prefix.split_first() {
88            Some((wrapper, arguments)) => {
89                let mut command = Command::new(wrapper);
90                command.args(arguments).arg(program);
91                command
92            }
93            None => Command::new(program),
94        };
95        if let Some(dir) = &self.cwd {
96            command.current_dir(dir);
97        }
98        for name in &self.unset_env {
99            command.env_remove(name);
100        }
101        command.envs(self.env.iter().map(|(name, value)| (name, value)));
102        if let Some(ledger) = ledger_path() {
103            command.env(LEDGER_VARIABLE, ledger);
104        }
105        detach(&mut command);
106        command
107    }
108
109    /// Starts `program` with `args` under this launcher's policy, as
110    /// [`command`](Self::command) builds it, with stdin and output as `how`
111    /// says.
112    ///
113    /// ```
114    /// # #[cfg(unix)] {
115    /// use rig_tools::process::{Launcher, OutputLine, Spawn};
116    ///
117    /// let how = Spawn { stdin: Some(b"hello\n".to_vec()), ..Spawn::default() };
118    /// let mut process = Launcher::default().spawn("cat", ["-"], how)?;
119    /// let status = process.wait_for(std::time::Duration::from_secs(5))?;
120    /// assert!(status.is_some_and(|status| status.success()));
121    /// let lines: Vec<OutputLine> = process.lines().iter().collect();
122    /// assert_eq!(lines, [OutputLine::Out("hello\n".to_owned())]);
123    /// # }
124    /// # Ok::<(), std::io::Error>(())
125    /// ```
126    pub fn spawn(
127        &self,
128        program: impl AsRef<OsStr>,
129        args: impl IntoIterator<Item = impl AsRef<OsStr>>,
130        how: Spawn,
131    ) -> io::Result<Process> {
132        self.spawn_holding(program, args, how, false)
133    }
134
135    /// [`spawn`](Self::spawn), and with `hold` and no input, a stdin that
136    /// stays open, with nothing written to it, until the process is
137    /// stopped or dropped: so a transport's end on the other machine sees
138    /// it close when this end goes, however it goes.
139    pub(crate) fn spawn_holding(
140        &self,
141        program: impl AsRef<OsStr>,
142        args: impl IntoIterator<Item = impl AsRef<OsStr>>,
143        how: Spawn,
144        hold: bool,
145    ) -> io::Result<Process> {
146        let mut command = self.command(program);
147        command.args(args).stdin(match how.stdin {
148            Some(_) => Stdio::piped(),
149            None if hold => Stdio::piped(),
150            None => Stdio::null(),
151        });
152        let (sender, lines) = channel();
153        let mut pipes: Vec<(Box<dyn Read + Send>, Tag)> = Vec::new();
154        if how.merge_stderr {
155            // One pipe for both keeps their order.
156            let (reader, writer) = io::pipe()?;
157            command.stdout(writer.try_clone()?).stderr(writer);
158            pipes.push((Box::new(reader), OutputLine::Out));
159        } else {
160            command.stdout(Stdio::piped()).stderr(Stdio::piped());
161        }
162        let spawned = command.spawn();
163        // The parent's copies of a shared pipe's write end must close, or
164        // reading never ends.
165        drop(command);
166        let child = spawned?;
167        record(child.id(), true);
168        let group = Group(Arc::new(AtomicU32::new(child.id())));
169        // From here on, an error drops the process, which kills it.
170        let mut process = Process {
171            child,
172            lines,
173            group,
174            remote: None,
175        };
176        let (stdout, stderr) = (process.child.stdout.take(), process.child.stderr.take());
177        #[cfg(unix)]
178        let (stdout, stderr) = match (stdout, stderr) {
179            (Some(stdout), Some(stderr)) => {
180                let sender = sender.clone();
181                thread::Builder::new()
182                    .name("rig-process-output".to_owned())
183                    .spawn(move || forward_both(stdout, stderr, &sender))?;
184                (None, None)
185            }
186            apart => apart,
187        };
188        if let Some(stdout) = stdout {
189            pipes.push((Box::new(stdout), OutputLine::Out));
190        }
191        if let Some(stderr) = stderr {
192            pipes.push((Box::new(stderr), OutputLine::Err));
193        }
194        for (pipe, tag) in pipes {
195            let sender = sender.clone();
196            thread::Builder::new()
197                .name("rig-process-output".to_owned())
198                .spawn(move || forward(pipe, tag, &sender))?;
199        }
200        if let Some(bytes) = how.stdin
201            && let Some(mut stdin) = process.child.stdin.take()
202        {
203            // Written on a thread of its own, so a child that reads slowly,
204            // or not at all, never blocks the caller; closed once written.
205            thread::Builder::new()
206                .name("rig-process-input".to_owned())
207                .spawn(move || {
208                    stdin.write_all(&bytes).ok();
209                })?;
210        }
211        Ok(process)
212    }
213}
214
215/// How [`Launcher::spawn`] connects a process.
216#[derive(Clone, Debug, Default, PartialEq, Eq)]
217pub struct Spawn {
218    /// What the process reads on stdin, which is closed after it; `None`
219    /// gives it an empty stdin.
220    pub stdin: Option<Vec<u8>>,
221    /// Whether stderr goes into stdout's pipe, so the two keep their order
222    /// and every line arrives as [`OutputLine::Out`].
223    pub merge_stderr: bool,
224}
225
226/// A piece of a process's output, as [`Process::lines`] hands it over: a
227/// line with its `\n`, or the end of the output without one. A line longer
228/// than 64 KB comes in pieces. Bytes that are not UTF-8 are replaced.
229#[derive(Clone, Debug, PartialEq, Eq)]
230pub enum OutputLine {
231    /// From stdout.
232    Out(String),
233    /// From stderr.
234    Err(String),
235}
236
237impl OutputLine {
238    /// The text, whichever stream it came from.
239    pub fn text(&self) -> &str {
240        match self {
241            Self::Out(text) | Self::Err(text) => text,
242        }
243    }
244}
245
246type Tag = fn(String) -> OutputLine;
247
248/// How often a waiting [`Process`] is checked.
249const POLL: Duration = Duration::from_millis(10);
250
251/// How long [`Process::run`] reads on after the process exited, for output
252/// something it left running still writes, and again after a kill.
253const PIPE_GRACE: Duration = Duration::from_millis(100);
254
255/// How long a process asked to stop (`SIGTERM`) has to end before it is
256/// killed: time for a transport that hangs up the command it runs on
257/// another machine when it is stopped to do so.
258pub const STOP_GRACE: Duration = Duration::from_secs(2);
259
260/// The longest piece of a line [`forward`] hands over at once.
261const MAX_PIECE: usize = 64 * 1024;
262
263/// Reads `pipe` until every writer closed it, or the receiver is gone,
264/// and sends what it reads on line by line.
265///
266/// When the receiver stops listening while a process that left the group
267/// still holds the pipe, this thread stays blocked in `read` until that
268/// process writes again or exits; its next write then finds the receiver
269/// gone, the read end is dropped, and the process gets `EPIPE` or
270/// `SIGPIPE`, as after any closed pipe.
271fn forward(mut pipe: impl Read, tag: Tag, lines: &Sender<OutputLine>) {
272    let mut pending = Vec::new();
273    let mut buffer = [0; 8192];
274    loop {
275        let read = match pipe.read(&mut buffer) {
276            Ok(0) => break,
277            Ok(read) => read,
278            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
279            Err(_) => break,
280        };
281        pending.extend_from_slice(buffer.get(..read).unwrap_or_default());
282        let mut start = 0;
283        while let Some(end) = pending.get(start..).and_then(piece_end) {
284            let piece = pending.get(start..start + end).unwrap_or_default();
285            if lines
286                .send(tag(String::from_utf8_lossy(piece).into_owned()))
287                .is_err()
288            {
289                return;
290            }
291            start += end;
292        }
293        pending.drain(..start);
294    }
295    if !pending.is_empty() {
296        lines
297            .send(tag(String::from_utf8_lossy(&pending).into_owned()))
298            .ok();
299    }
300}
301
302/// Reads a process's stdout and stderr on one thread, whichever has data
303/// first, stdout first when both have, and sends each on line by line as
304/// [`forward`] does: so the lines of the two keep the order they were
305/// written in, as far as one reader can tell, and a line one writes in
306/// pieces is never split by the other's.
307#[cfg(unix)]
308fn forward_both(
309    stdout: std::process::ChildStdout,
310    stderr: std::process::ChildStderr,
311    lines: &Sender<OutputLine>,
312) {
313    use std::os::fd::AsRawFd;
314
315    let fds = [stdout.as_raw_fd(), stderr.as_raw_fd()];
316    let mut pipes: [(Box<dyn Read>, Tag, Vec<u8>, bool); 2] = [
317        (Box::new(stdout), OutputLine::Out, Vec::new(), true),
318        (Box::new(stderr), OutputLine::Err, Vec::new(), true),
319    ];
320    let mut buffer = [0; 8192];
321    while pipes.iter().any(|(.., open)| *open) {
322        let mut polled = fds.map(|fd| libc::pollfd {
323            fd,
324            events: libc::POLLIN,
325            revents: 0,
326        });
327        for (poll, (.., open)) in polled.iter_mut().zip(&pipes) {
328            if !*open {
329                poll.fd = -1;
330            }
331        }
332        // SAFETY: `polled` is an array of two initialized `pollfd`s that
333        // outlives the call, and its length is passed with it.
334        let ready = unsafe { libc::poll(polled.as_mut_ptr(), 2, -1) };
335        if ready < 0 {
336            if io::Error::last_os_error().kind() == io::ErrorKind::Interrupted {
337                continue;
338            }
339            break;
340        }
341        for (poll, (pipe, tag, pending, open)) in polled.iter().zip(&mut pipes) {
342            if !*open || poll.revents == 0 {
343                continue;
344            }
345            let read = match pipe.read(&mut buffer) {
346                Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
347                Ok(0) | Err(_) => None,
348                Ok(read) => Some(read),
349            };
350            let Some(read) = read else {
351                *open = false;
352                if !pending.is_empty() {
353                    let text = String::from_utf8_lossy(pending).into_owned();
354                    pending.clear();
355                    if lines.send(tag(text)).is_err() {
356                        return;
357                    }
358                }
359                continue;
360            };
361            pending.extend_from_slice(buffer.get(..read).unwrap_or_default());
362            let mut start = 0;
363            while let Some(end) = pending.get(start..).and_then(piece_end) {
364                let piece = pending.get(start..start + end).unwrap_or_default();
365                if lines
366                    .send(tag(String::from_utf8_lossy(piece).into_owned()))
367                    .is_err()
368                {
369                    return;
370                }
371                start += end;
372            }
373            pending.drain(..start);
374        }
375    }
376}
377
378/// Where the first piece of `bytes` ends: after its first `\n`, else after
379/// [`MAX_PIECE`] bytes, not inside a character; `None` while it is shorter.
380fn piece_end(bytes: &[u8]) -> Option<usize> {
381    if let Some(at) = bytes.iter().position(|&byte| byte == b'\n') {
382        return Some(at + 1);
383    }
384    let head = bytes.get(..MAX_PIECE)?;
385    match std::str::from_utf8(head) {
386        Err(error) if error.error_len().is_none() && error.valid_up_to() > 0 => {
387            Some(error.valid_up_to())
388        }
389        _ => Some(head.len()),
390    }
391}
392
393/// A process [`Launcher::spawn`] started, the leader of a process group of
394/// its own. Dropping it while it runs kills the group and reaps it.
395pub struct Process {
396    child: Child,
397    lines: Receiver<OutputLine>,
398    group: Group,
399    /// The machine it is the local end of a transport to, if it is one.
400    remote: Option<String>,
401}
402
403impl Process {
404    /// The process's id, which is also its group's.
405    pub fn id(&self) -> u32 {
406        self.child.id()
407    }
408
409    /// The same process, marked as the local end of a transport that runs
410    /// the command on the machine `host`, whose end there stops the command
411    /// when this end stops.
412    pub fn through(mut self, host: impl Into<String>) -> Self {
413        self.remote = Some(host.into());
414        self
415    }
416
417    /// The machine it runs the command on through a transport, if it was
418    /// marked so ([`through`](Self::through)).
419    pub fn remote(&self) -> Option<&str> {
420        self.remote.as_deref()
421    }
422
423    /// Its output, line by line, as it comes. Lines wait here until they
424    /// are received; the channel disconnects once every process holding
425    /// the output closed it.
426    pub fn lines(&self) -> &Receiver<OutputLine> {
427        &self.lines
428    }
429
430    /// A handle that stops its group from another thread, such as the one
431    /// dropping the call that waits for it.
432    pub fn group(&self) -> Group {
433        self.group.clone()
434    }
435
436    /// How it ended, if it has.
437    pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
438        let status = self.child.try_wait();
439        if !matches!(status, Ok(None)) {
440            // Reaped, or about to be: its id may be reused.
441            self.group.0.store(0, Ordering::SeqCst);
442            record(self.child.id(), false);
443        }
444        status
445    }
446
447    /// Waits at most `timeout` for it to end, and says how it ended if it
448    /// did. Its output keeps arriving at [`lines`](Self::lines) meanwhile.
449    /// A timeout too long for the clock, such as `Duration::MAX`, waits
450    /// until it ends.
451    pub fn wait_for(&mut self, timeout: Duration) -> io::Result<Option<ExitStatus>> {
452        let deadline = Instant::now().checked_add(timeout);
453        // A process whose output just closed is usually a moment from
454        // ending, so the first naps are short.
455        let mut nap = Duration::from_millis(1);
456        loop {
457            if let Some(status) = self.try_wait()? {
458                return Ok(Some(status));
459            }
460            let left = deadline.map_or(POLL, |deadline| {
461                deadline.saturating_duration_since(Instant::now())
462            });
463            if left.is_zero() {
464                return Ok(None);
465            }
466            thread::sleep(left.min(nap));
467            nap = (nap * 2).min(POLL);
468        }
469    }
470
471    /// Runs it to its end, at most `timeout` (`None` waits as long as it
472    /// takes), and returns what it printed on stdout and on stderr (with
473    /// [`Spawn::merge_stderr`], all of it on stdout) and how it ended. A
474    /// blocking call: run it on a thread of its own, such as inside
475    /// [`blocking`](crate::blocking). Past `timeout` the error is
476    /// [`io::ErrorKind::TimedOut`]; otherwise as [`run`](Self::run).
477    ///
478    /// ```
479    /// # #[cfg(unix)] {
480    /// use rig_tools::process::{Launcher, Spawn};
481    ///
482    /// let process = Launcher::default().spawn("sh", ["-c", "echo hi"], Spawn::default())?;
483    /// let output = process.output(Some(std::time::Duration::from_secs(5)))?;
484    /// assert_eq!(output.stdout, b"hi\n");
485    /// assert!(output.status.success());
486    /// # }
487    /// # Ok::<(), std::io::Error>(())
488    /// ```
489    pub fn output(mut self, timeout: Option<Duration>) -> io::Result<Output> {
490        let deadline = timeout.and_then(|timeout| Instant::now().checked_add(timeout));
491        let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
492        let ended = self.run(deadline, |line| {
493            match line {
494                OutputLine::Out(text) => stdout.extend(text.into_bytes()),
495                OutputLine::Err(text) => stderr.extend(text.into_bytes()),
496            }
497            true
498        })?;
499        match ended {
500            Ended::Exited(status) => Ok(Output {
501                status,
502                stdout,
503                stderr,
504            }),
505            Ended::TimedOut | Ended::Stopped => Err(io::Error::new(
506                io::ErrorKind::TimedOut,
507                "the process ran past its timeout and was killed",
508            )),
509        }
510    }
511
512    /// Waits for it to end, at most until `deadline` (`None` waits as long
513    /// as it takes), handing each piece of its output to `sink`; `sink`
514    /// returning `false` stops the wait. A blocking call.
515    ///
516    /// After an exit, something it left running that still holds its
517    /// output gets a moment (100 ms) to finish, then the rest of its group
518    /// is killed; past the deadline or stopped, the group is
519    /// [stopped](Self::stop) with [`STOP_GRACE`]. After a kill, reading
520    /// goes on for that moment: a process that left the group survives the
521    /// kill and may hold the pipe for good.
522    pub fn run(
523        &mut self,
524        deadline: Option<Instant>,
525        mut sink: impl FnMut(OutputLine) -> bool,
526    ) -> io::Result<Ended> {
527        let mut more = true;
528        let ended = loop {
529            if let Some(status) = self.try_wait()? {
530                break Ended::Exited(status);
531            }
532            if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
533                break Ended::TimedOut;
534            }
535            if !more {
536                break Ended::Stopped;
537            }
538            match self.lines.recv_timeout(POLL) {
539                Ok(line) => more = sink(line),
540                Err(RecvTimeoutError::Timeout) => {}
541                // It closed its output but still runs.
542                Err(RecvTimeoutError::Disconnected) => {
543                    self.wait_for(POLL)?;
544                }
545            }
546        };
547        if !matches!(ended, Ended::Exited(_)) {
548            self.stop(STOP_GRACE).ok();
549            self.read_rest(&mut sink);
550        } else if !self.read_rest(&mut sink) {
551            self.kill().ok();
552            self.read_rest(&mut sink);
553        }
554        Ok(ended)
555    }
556
557    /// Hands output to `sink` until the pipe's end, for at most
558    /// [`PIPE_GRACE`]; whether the end came.
559    fn read_rest(&self, sink: &mut impl FnMut(OutputLine) -> bool) -> bool {
560        let deadline = Instant::now() + PIPE_GRACE;
561        loop {
562            match self
563                .lines
564                .recv_timeout(deadline.saturating_duration_since(Instant::now()))
565            {
566                Ok(line) => {
567                    sink(line);
568                }
569                Err(RecvTimeoutError::Disconnected) => return true,
570                Err(RecvTimeoutError::Timeout) => return false,
571            }
572        }
573    }
574
575    /// Closes its stdin if it is still open, asks its group to stop
576    /// (`SIGTERM`), waits at most `grace` for it to end, then
577    /// [kills](Self::kill) the group. Elsewhere than unix it is killed at
578    /// once.
579    pub fn stop(&mut self, grace: Duration) -> io::Result<ExitStatus> {
580        drop(self.child.stdin.take());
581        if self.try_wait()?.is_none() {
582            self.group.terminate();
583            self.wait_for(grace)?;
584        }
585        self.kill()
586    }
587
588    /// Kills its group (`SIGKILL`), also what is left of it after the
589    /// process itself ended, and says how the process ended. Kill within
590    /// moments of the end: once the group is empty its id is free again.
591    pub fn kill(&mut self) -> io::Result<ExitStatus> {
592        self.group.0.store(0, Ordering::SeqCst);
593        #[cfg(unix)]
594        kill_group_of(self.child.id());
595        #[cfg(not(unix))]
596        if self.child.try_wait()?.is_none() {
597            self.child.kill()?;
598        }
599        // Off the ledger before the reap frees its id.
600        record(self.child.id(), false);
601        self.child.wait()
602    }
603}
604
605/// How [`Process::run`]'s wait ended.
606#[derive(Clone, Copy, Debug, PartialEq, Eq)]
607pub enum Ended {
608    /// It exited.
609    Exited(ExitStatus),
610    /// It ran past the deadline, and its group was stopped.
611    TimedOut,
612    /// The sink stopped the wait, and its group was stopped.
613    Stopped,
614}
615
616impl Drop for Process {
617    fn drop(&mut self) {
618        if self.group.0.load(Ordering::SeqCst) != 0 {
619            self.kill().ok();
620        }
621    }
622}
623
624/// A [`Process`]'s group, to stop from another thread. It acts only while
625/// the process runs: once it was reaped, its id may name another process.
626#[derive(Clone, Debug)]
627pub struct Group(Arc<AtomicU32>);
628
629impl Group {
630    /// Kills the group (`SIGKILL`); elsewhere than unix, nothing.
631    pub fn kill(&self) {
632        self.signal(Signal::Kill);
633    }
634
635    /// Asks the group to stop (`SIGTERM`); elsewhere than unix, nothing.
636    pub fn terminate(&self) {
637        self.signal(Signal::Terminate);
638    }
639
640    fn signal(&self, signal: Signal) {
641        let leader = self.0.load(Ordering::SeqCst);
642        #[cfg(unix)]
643        if leader != 0 {
644            signal_group(leader, signal);
645        }
646        #[cfg(not(unix))]
647        let _ = (leader, signal);
648    }
649}
650
651/// Stops a [`Process`]'s group when dropped: kept in a future that waits
652/// for the process on another thread ([`blocking`](crate::blocking)), it
653/// asks the group to stop (`SIGTERM`) the moment the future is dropped,
654/// such as when a call is interrupted or the app quits, and kills it
655/// [`STOP_GRACE`] later if it still runs. The thread waiting for the
656/// process must go on reaping it meanwhile, as [`Process::run`] does.
657pub struct KillOnDrop(pub Group);
658
659impl Drop for KillOnDrop {
660    fn drop(&mut self) {
661        self.0.terminate();
662        let group = self.0.clone();
663        let later = thread::Builder::new()
664            .name("rig-process-stop".to_owned())
665            .spawn(move || {
666                thread::sleep(STOP_GRACE);
667                group.kill();
668            });
669        if later.is_err() {
670            self.0.kill();
671        }
672    }
673}
674
675/// The signals a [`Group`] sends.
676#[derive(Clone, Copy)]
677enum Signal {
678    Terminate,
679    Kill,
680}
681
682/// The file [`record_groups`] keeps, and the groups it lists.
683static LEDGER: Mutex<Option<(PathBuf, BTreeSet<u32>)>> = Mutex::new(None);
684
685/// The variable every command a [`Launcher`] builds carries while
686/// [`record_groups`] keeps a ledger: the ledger's path.
687pub const LEDGER_VARIABLE: &str = "RIG_PROCESS_LEDGER";
688
689/// From now on keeps the id of each process group a [`Launcher`] spawned
690/// and this process has not reaped yet in the file at `path`, one per line,
691/// rewritten whole on each change, and marks every command a launcher
692/// builds with [`LEDGER_VARIABLE`] set to `path`. A supervisor that
693/// outlives this process, such as rig's launcher, kills the groups listed
694/// once it died without stopping them, each only while its leader still
695/// carries the mark: a listed id that names another process by then, its
696/// own reaped, is left alone. A file that cannot be written lists nothing
697/// new.
698pub fn record_groups(path: impl Into<PathBuf>) {
699    let mut ledger = LEDGER.lock().unwrap_or_else(PoisonError::into_inner);
700    let (path, groups) = ledger.insert((path.into(), BTreeSet::new()));
701    write_ledger(path, groups).ok();
702}
703
704/// The ledger's path, while [`record_groups`] keeps one.
705fn ledger_path() -> Option<PathBuf> {
706    let ledger = LEDGER.lock().unwrap_or_else(PoisonError::into_inner);
707    ledger.as_ref().map(|(path, _)| path.clone())
708}
709
710/// Lists the group `leader` leads in the ledger [`record_groups`] keeps,
711/// for a process started outside [`Launcher::spawn`], such as an MCP
712/// server's: the supervisor then kills it should this process die without
713/// stopping it. [`unlist_group`] takes it off once it is killed.
714pub fn list_group(leader: u32) {
715    record(leader, true);
716}
717
718/// Takes the group `leader` leads off the ledger ([`list_group`]).
719pub fn unlist_group(leader: u32) {
720    record(leader, false);
721}
722
723/// Lists the group `id` leads in the ledger, or takes it off once reaped.
724fn record(id: u32, live: bool) {
725    let mut ledger = LEDGER.lock().unwrap_or_else(PoisonError::into_inner);
726    if let Some((path, groups)) = ledger.as_mut() {
727        let changed = match live {
728            true => groups.insert(id),
729            false => groups.remove(&id),
730        };
731        if changed {
732            write_ledger(path, groups).ok();
733        }
734    }
735}
736
737/// Replaces the file at `path` with `groups`, one per line.
738fn write_ledger(path: &Path, groups: &BTreeSet<u32>) -> io::Result<()> {
739    let text: String = groups.iter().map(|id| format!("{id}\n")).collect();
740    let written = path.with_extension("tmp");
741    std::fs::write(&written, text)?;
742    std::fs::rename(&written, path)
743}
744
745/// Starts `command` in a new session, which also makes it the leader of a
746/// new process group. With no controlling terminal, a program that opens
747/// `/dev/tty` for a prompt (ssh, git, sudo) fails at once instead of
748/// drawing over the view and stopping on a terminal read. Git is also told
749/// not to prompt.
750pub fn detach(command: &mut Command) {
751    command.env("GIT_TERMINAL_PROMPT", "0");
752    #[cfg(unix)]
753    {
754        use std::os::unix::process::CommandExt;
755        // SAFETY: the closure runs in the forked child before `exec` and
756        // only calls `setsid`, which is async-signal-safe.
757        unsafe {
758            command.pre_exec(|| {
759                if libc::setsid() == -1 {
760                    Err(std::io::Error::last_os_error())
761                } else {
762                    Ok(())
763                }
764            });
765        }
766    }
767}
768
769/// Kills the process group `child` leads, created by [`detach`];
770/// elsewhere, the child alone.
771#[cfg(unix)]
772pub fn kill_group(child: &mut Child) {
773    kill_group_of(child.id());
774}
775
776/// Kills the process group led by the process `leader`. Its id names that
777/// group while the leader is not reaped or any member lives: the kernel
778/// does not reuse the id of a process group that exists. Once the leader
779/// was reaped and the group emptied, the id is free again, so callers kill
780/// within moments of the reap.
781#[cfg(unix)]
782pub fn kill_group_of(leader: u32) {
783    signal_group(leader, Signal::Kill);
784}
785
786/// Sends `signal` to the process group led by the process `leader`.
787#[cfg(unix)]
788fn signal_group(leader: u32, signal: Signal) {
789    let signal = match signal {
790        Signal::Terminate => libc::SIGTERM,
791        Signal::Kill => libc::SIGKILL,
792    };
793    if let Ok(group) = i32::try_from(leader) {
794        // SAFETY: `kill` takes plain integers; a negative pid names the
795        // process group the child leads, created by `detach`.
796        unsafe {
797            libc::kill(-group, signal);
798        }
799    }
800}
801
802#[cfg(not(unix))]
803pub fn kill_group(child: &mut Child) {
804    child.kill().ok();
805}
806
807#[cfg(test)]
808mod tests;