Skip to main content

schedr_agent/
process.rs

1//! The real task process: started in its own process group with a clean environment, its
2//! stdout and stderr written to the task's log file and kept (their tail) for the
3//! `ProcessResult`.
4//!
5//! This is the thin operating-system layer under [`crate::supervise`]; it is exercised by
6//! the integration tests (`tests/processes.rs`), the logic around it by unit tests.
7
8use std::collections::BTreeMap;
9use std::io;
10use std::os::fd::OwnedFd;
11use std::os::unix::process::ExitStatusExt;
12use std::path::{Path, PathBuf};
13use std::process::Stdio;
14use std::sync::Arc;
15use std::time::Duration;
16
17use rustix::process::{Pid, kill_process_group, test_kill_process_group};
18use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
19use tokio::process::{Child, Command};
20use tokio::sync::Mutex;
21use tokio::task::JoinHandle;
22
23use crate::mask::{Mask, MaskSet};
24use crate::output::TailBuffer;
25use crate::status::Termination;
26use crate::supervise::{Process, Signal};
27use crate::usage::{Ended, clock_ticks, exited, zombie_usage};
28
29#[cfg(test)]
30mod tests;
31
32/// What to start.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct ProcessSpec {
35    /// The program.
36    pub program: PathBuf,
37    /// Its arguments.
38    pub args: Vec<String>,
39    /// Its whole environment (see [`crate::env::task_environment`]).
40    pub env: BTreeMap<String, String>,
41    /// Its working directory.
42    pub working_dir: PathBuf,
43    /// The task's log file; stdout and stderr are appended to it.
44    pub log_file: PathBuf,
45    /// The output size limit per stream, in bytes.
46    pub max_output_size: usize,
47    /// The secret values masked in its output, on their way to the log and the tail.
48    pub mask: Mask,
49    /// How long a runner has to say hello, if it is one (`[worker] runner_start_timeout`).
50    pub start_timeout: Duration,
51    /// How long its output may take to reach its log once it is stopped.
52    pub output_drain: Duration,
53}
54
55/// A started task process.
56#[derive(Debug)]
57pub struct OsProcess {
58    child: Child,
59    group: Pid,
60    stdout: JoinHandle<io::Result<TailBuffer>>,
61    stderr: JoinHandle<io::Result<TailBuffer>>,
62    ended: Ended,
63    /// Whether its zombie was read already (`wait` may be called again).
64    read: bool,
65}
66
67/// Processes are started one at a time: a descriptor made inheritable for one child (see
68/// [`spawn_passing`]) must not leak into another started at the same moment.
69pub(crate) static SPAWNING: Mutex<()> = Mutex::const_new(());
70
71/// Starts a task process.
72///
73/// # Errors
74///
75/// Returns an I/O error if the log file can't be opened or the program can't be started.
76pub async fn spawn(spec: &ProcessSpec) -> io::Result<OsProcess> {
77    spawn_passing(spec, None).await
78}
79
80/// Starts a process that inherits `pass` (open, at the same descriptor number); the parent's
81/// copy is closed once the child has it. Used to hand a runner its end of the agent's socket
82/// pair.
83///
84/// # Errors
85///
86/// Returns an I/O error if the log file can't be opened, the descriptor can't be made
87/// inheritable, or the program can't be started.
88pub async fn spawn_passing(spec: &ProcessSpec, pass: Option<OwnedFd>) -> io::Result<OsProcess> {
89    let log = open_log(spec).await?;
90    let spawning = SPAWNING.lock().await;
91    if let Some(fd) = &pass {
92        rustix::io::fcntl_setfd(fd, rustix::io::FdFlags::empty())?;
93    }
94    let child = Command::new(&spec.program)
95        .args(&spec.args)
96        .env_clear()
97        .envs(&spec.env)
98        .current_dir(&spec.working_dir)
99        .stdin(Stdio::null())
100        .stdout(Stdio::piped())
101        .stderr(Stdio::piped())
102        .process_group(0)
103        .kill_on_drop(true)
104        .spawn();
105    drop(pass);
106    drop(spawning);
107    let mut child = child?;
108    let pid = child
109        .id()
110        .and_then(|id| i32::try_from(id).ok())
111        .and_then(Pid::from_raw);
112    let group = pid.ok_or_else(|| io::Error::other("the started process has no pid"))?;
113    let stdout = child
114        .stdout
115        .take()
116        .ok_or_else(|| io::Error::other("no stdout pipe"))?;
117    let stderr = child
118        .stderr
119        .take()
120        .ok_or_else(|| io::Error::other("no stderr pipe"))?;
121    Ok(OsProcess {
122        ended: Ended::default(),
123        read: false,
124        child,
125        group,
126        stdout: tokio::spawn(collect(
127            stdout,
128            Arc::clone(&log),
129            spec.max_output_size,
130            spec.mask.clone(),
131        )),
132        stderr: tokio::spawn(collect(
133            stderr,
134            log,
135            spec.max_output_size,
136            spec.mask.clone(),
137        )),
138    })
139}
140
141/// The mode of the log files the worker creates (`[worker] log_mode`, B182): set once when the
142/// worker starts (one per process), owner-only until then.
143static LOG_MODE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0o600);
144
145/// Sets the mode the worker's log files get (`[worker] log_mode`): set on each file as it is
146/// opened, so the umask doesn't change it.
147pub fn set_log_mode(mode: u32) {
148    LOG_MODE.store(mode, std::sync::atomic::Ordering::Relaxed);
149}
150
151/// Readies the worker's log directory for `mode` (B182), at its start: made if missing, its own
152/// mode the log mode's readers' (0700 for 0600, 0750 for 0640, 0755 for 0644), and every log
153/// already in it given `mode`, so those written before (an upgrade, a looser mode then) aren't
154/// left readable until retention deletes them. A link in it is left alone, never followed.
155///
156/// # Errors
157///
158/// The I/O error of making the directory or setting a mode.
159pub fn secure_log_dir(dir: &Path, mode: u32) -> io::Result<()> {
160    use std::os::unix::fs::PermissionsExt as _;
161    std::fs::create_dir_all(dir)?;
162    let readers = |bit: u32, both: u32| if mode & bit == 0 { 0 } else { both };
163    let dir_mode = 0o700 | readers(0o040, 0o050) | readers(0o004, 0o005);
164    std::fs::set_permissions(dir, std::fs::Permissions::from_mode(dir_mode))?;
165    for entry in std::fs::read_dir(dir)? {
166        let entry = entry?;
167        let metadata = entry.metadata()?;
168        if metadata.is_file() && metadata.permissions().mode() & 0o7777 != mode {
169            std::fs::set_permissions(entry.path(), std::fs::Permissions::from_mode(mode))?;
170        }
171    }
172    Ok(())
173}
174
175/// Opens a log at `path` for appending, as [`open_regular`] does, with the worker's log mode:
176/// set on the file itself, so neither the umask nor a mode from before (an upgrade, a mode
177/// tightened since) decides who reads it.
178///
179/// # Errors
180///
181/// The open's I/O error, or setting the mode's.
182pub(crate) async fn open_log_file(path: &Path) -> io::Result<tokio::fs::File> {
183    use std::os::unix::fs::PermissionsExt as _;
184    let mode = LOG_MODE.load(std::sync::atomic::Ordering::Relaxed);
185    let mut options = tokio::fs::OpenOptions::new();
186    options.create(true).append(true).mode(mode);
187    let file = open_regular(options, path).await?;
188    file.set_permissions(std::fs::Permissions::from_mode(mode))
189        .await?;
190    Ok(file)
191}
192
193/// The task's log file, opened for appending, shared by its stdout and stderr collectors.
194///
195/// # Errors
196///
197/// Returns an I/O error if it can't be opened.
198pub(crate) async fn open_log(spec: &ProcessSpec) -> io::Result<SharedLog> {
199    let log = open_log_file(&spec.log_file).await?;
200    Ok(Arc::new(Mutex::new(log)))
201}
202
203/// Opens `path` with `options` only if it is a regular file with no other name, never
204/// following a symbolic link (B62): a link planted where a log goes, symbolic or hard, would
205/// make the agent read or write its target, and a FIFO would block the open (`O_NONBLOCK`,
206/// which a regular file ignores).
207///
208/// # Errors
209///
210/// Returns the I/O error of the open (`ELOOP` for a symbolic link), or `InvalidInput` for a
211/// file that isn't regular or has another hard link.
212pub(crate) async fn open_regular(
213    mut options: tokio::fs::OpenOptions,
214    path: &Path,
215) -> io::Result<tokio::fs::File> {
216    use rustix::fs::OFlags;
217    options.custom_flags((OFlags::NOFOLLOW | OFlags::NONBLOCK).bits().cast_signed());
218    let file = options.open(path).await?;
219    let metadata = file.metadata().await?;
220    if !metadata.is_file() {
221        return Err(io::Error::new(
222            io::ErrorKind::InvalidInput,
223            format!("`{}` isn't a regular file", path.display()),
224        ));
225    }
226    if std::os::unix::fs::MetadataExt::nlink(&metadata) != 1 {
227        return Err(io::Error::new(
228            io::ErrorKind::InvalidInput,
229            format!("`{}` has another hard link", path.display()),
230        ));
231    }
232    Ok(file)
233}
234
235/// A log file written by a process's two output collectors.
236pub(crate) type SharedLog = Arc<Mutex<tokio::fs::File>>;
237
238/// Copies a pipe into the log file, keeping its tail; secret values are masked on the way.
239pub(crate) async fn collect(
240    mut pipe: impl AsyncRead + Unpin,
241    log: SharedLog,
242    limit: usize,
243    mask: Mask,
244) -> io::Result<TailBuffer> {
245    let mut tail = TailBuffer::new(limit);
246    let mut chunk = vec![0; 64 * 1024];
247    let mut stream = mask.0.as_deref().map(MaskSet::stream);
248    loop {
249        let n = pipe.read(&mut chunk).await?;
250        if n == 0 {
251            if let Some(stream) = &mut stream {
252                let rest = stream.finish();
253                tail.push(&rest);
254                log.lock().await.write_all(&rest).await?;
255            }
256            // A tokio file write may still be in flight when `write_all` returns: the log is
257            // complete only once flushed.
258            log.lock().await.flush().await?;
259            return Ok(tail);
260        }
261        let masked;
262        let bytes = match &mut stream {
263            Some(stream) => {
264                masked = stream.push(&chunk[..n]);
265                masked.as_slice()
266            }
267            None => &chunk[..n],
268        };
269        tail.push(bytes);
270        log.lock().await.write_all(bytes).await?;
271    }
272}
273
274impl OsProcess {
275    /// Its process ID, which is also its process group's ID.
276    #[must_use]
277    pub fn id(&self) -> i32 {
278        self.group.as_raw_nonzero().get()
279    }
280
281    /// The captured stdout and stderr, once both pipes are closed.
282    ///
283    /// # Errors
284    ///
285    /// Returns an I/O error from reading a pipe or writing the log file.
286    pub async fn output(self) -> io::Result<(TailBuffer, TailBuffer)> {
287        let stdout = self.stdout.await.map_err(io::Error::other)??;
288        let stderr = self.stderr.await.map_err(io::Error::other)??;
289        Ok((stdout, stderr))
290    }
291}
292
293/// Whether a process of `group` still runs. A zombie (ended, not yet reaped) doesn't: a forked
294/// task's shim holds its leader as one, and an agent that is a container's first process (or
295/// a subreaper) adopts its tasks' orphans, which stay zombies until it reaps them. A process
296/// whose main thread ended (`pthread_exit`) shows as a zombie too while its other threads run:
297/// it still runs. Read from `/proc`; without it, whether the group has any process at all.
298#[must_use]
299pub fn group_running(group: Pid) -> bool {
300    if test_kill_process_group(group).is_err() {
301        return false;
302    }
303    let Ok(entries) = std::fs::read_dir("/proc") else {
304        return true;
305    };
306    let group = group.as_raw_nonzero().get();
307    entries.flatten().any(|entry| {
308        let is_pid = entry
309            .file_name()
310            .to_str()
311            .is_some_and(|name| name.bytes().all(|b| b.is_ascii_digit()));
312        is_pid
313            && std::fs::read_to_string(entry.path().join("stat")).is_ok_and(|stat| {
314                stat_fields(&stat).is_some_and(|(state, pgrp)| {
315                    pgrp == group && (!ended(state) || a_thread_runs(&entry.path()))
316                })
317            })
318    })
319}
320
321/// Whether a thread of the process at `/proc/<pid>` hasn't ended; if its threads can't be
322/// listed, it may still run.
323fn a_thread_runs(process: &Path) -> bool {
324    live_thread(process).map_or(true, |thread| thread.is_some())
325}
326
327/// A thread of the process at `/proc/<pid>` that hasn't ended, as `/proc/<pid>/task/<tid>`;
328/// `None` if every one has.
329///
330/// # Errors
331///
332/// If its threads can't be listed.
333pub(crate) fn live_thread(process: &Path) -> io::Result<Option<std::path::PathBuf>> {
334    Ok(std::fs::read_dir(process.join("task"))?
335        .flatten()
336        .map(|thread| thread.path())
337        .find(|thread| {
338            std::fs::read_to_string(thread.join("stat"))
339                .is_ok_and(|stat| stat_fields(&stat).is_some_and(|(state, _)| !ended(state)))
340        }))
341}
342
343/// The state (field 3) and process group (field 5) of a `/proc/.../stat` line.
344pub(crate) fn stat_fields(stat: &str) -> Option<(&str, i32)> {
345    // The command name (field 2) is in parentheses and may contain anything: the fields
346    // after it start at its closing parenthesis.
347    let (_, rest) = stat.rsplit_once(')')?;
348    let mut fields = rest.split_whitespace();
349    let state = fields.next()?;
350    let pgrp = fields.nth(1)?.parse().ok()?;
351    Some((state, pgrp))
352}
353
354/// Whether a state means ended: a zombie, or dead.
355pub(crate) fn ended(state: &str) -> bool {
356    matches!(state, "Z" | "X" | "x")
357}
358
359impl Process for OsProcess {
360    async fn wait(&mut self) -> io::Result<Termination> {
361        // Its zombie is read before `wait` reaps it (decision 18A).
362        if !self.read {
363            if exited(self.group).await.is_ok() {
364                self.ended.usage = zombie_usage(Path::new("/proc"), self.id(), clock_ticks());
365            }
366            self.read = true;
367        }
368        let status = self.child.wait().await?;
369        self.ended.core_dumped = status.core_dumped();
370        Ok(match (status.code(), status.signal()) {
371            (Some(code), _) => Termination::Exited(code),
372            (None, Some(signal)) => Termination::Signaled(signal),
373            (None, None) => Termination::Exited(-1),
374        })
375    }
376
377    fn signal(&mut self, signal: Signal) -> io::Result<()> {
378        let sig = match signal {
379            Signal::Term => rustix::process::Signal::TERM,
380            Signal::Kill => rustix::process::Signal::KILL,
381        };
382        match kill_process_group(self.group, sig) {
383            Ok(()) | Err(rustix::io::Errno::SRCH) => Ok(()),
384            Err(e) => Err(e.into()),
385        }
386    }
387
388    fn group_alive(&self) -> bool {
389        group_running(self.group)
390    }
391
392    fn ended(&self) -> Ended {
393        self.ended
394    }
395}