Skip to main content

schedr_agent/
status.rs

1//! How an attempt ended: from the process's termination and why the agent stopped it.
2
3use schedr_model::AttemptStatus;
4
5#[cfg(test)]
6mod tests;
7
8/// How a process ended, as the operating system reports it.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum Termination {
11    /// It exited with this code.
12    Exited(i32),
13    /// It was killed by this signal.
14    Signaled(i32),
15    /// It ended, but how isn't known: a forked process whose shim died before reporting
16    /// (the agent kills its group then). It counts as a failure.
17    Unknown,
18}
19
20/// Why the agent stopped a process before it ended by itself.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum StopReason {
23    /// It exceeded its timeout.
24    TimedOut,
25    /// A user cancelled it.
26    Cancelled,
27    /// A draining worker's grace period ended.
28    Interrupted,
29    /// The worker has had no word from the master for the worker lease, and the task's cleanup
30    /// may run on another worker (decision 252): `lost`.
31    CutOff,
32    /// It exceeded its memory budget (the watchdog, see [`crate::memory`]).
33    OomKilled,
34}
35
36impl Termination {
37    /// The exit code reported in a `ProcessResult` (`128 + signal` for a signal).
38    #[must_use]
39    pub const fn exit_code(self) -> i32 {
40        match self {
41            Self::Exited(code) => code,
42            Self::Signaled(signal) => crate::output::signal_exit_code(signal),
43            Self::Unknown => -1,
44        }
45    }
46}
47
48/// The attempt's status.
49///
50/// A process the agent stopped gets the status of the reason, however it then ended (a task
51/// that exits 0 on SIGTERM after a timeout still timed out). Otherwise it succeeded if it
52/// exited with one of `success_codes` (`[0]`, or the codes of a declared outcome enum), and
53/// failed for any other exit code or a signal.
54#[must_use]
55pub fn attempt_status(
56    termination: Termination,
57    stopped: Option<StopReason>,
58    success_codes: &[i32],
59) -> AttemptStatus {
60    match (stopped, termination) {
61        (Some(StopReason::TimedOut), _) => AttemptStatus::TimedOut,
62        (Some(StopReason::Cancelled), _) => AttemptStatus::Cancelled,
63        (Some(StopReason::Interrupted), _) => AttemptStatus::Interrupted,
64        (Some(StopReason::CutOff), _) => AttemptStatus::Lost,
65        (Some(StopReason::OomKilled), _) => AttemptStatus::OomKilled,
66        (None, Termination::Exited(code)) if success_codes.contains(&code) => {
67            AttemptStatus::Success
68        }
69        (None, _) => AttemptStatus::Failed,
70    }
71}