Skip to main content

schedr_agent/
supervise.rs

1//! Supervising a task process: waiting for it, its timeout, cancellation, and stopping it
2//! with SIGTERM, then SIGKILL after the grace time (see archive/PROJECT.md, Master–worker protocol:
3//! cancellation).
4//!
5//! The logic works on the [`Process`] trait, so it is tested with a fake process and a
6//! paused clock; [`crate::process::OsProcess`] is the real one.
7
8use std::future::Future;
9use std::io;
10use std::time::Duration;
11
12use tokio::sync::mpsc;
13
14use crate::status::{StopReason, Termination};
15
16#[cfg(test)]
17mod tests;
18
19/// A signal the agent sends to a task's whole process group.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum Signal {
22    /// Ask it to stop (SIGTERM).
23    Term,
24    /// Stop it (SIGKILL).
25    Kill,
26}
27
28/// A running task process.
29pub trait Process {
30    /// Waits until the process ends.
31    fn wait(&mut self) -> impl Future<Output = io::Result<Termination>> + Send;
32
33    /// Sends a signal to the process's whole group; a group that is already gone is fine.
34    ///
35    /// # Errors
36    ///
37    /// Returns the operating system's error for anything but a group that is gone.
38    fn signal(&mut self, signal: Signal) -> io::Result<()>;
39    /// Whether anything of its group still runs, after its leader ended (no default: a
40    /// wrapper that forgot to forward it would leave a stopped task's children behind).
41    fn group_alive(&self) -> bool;
42    /// What it used and whether it dumped core, once [`Process::wait`] returned; nothing
43    /// known by default.
44    fn ended(&self) -> crate::usage::Ended {
45        crate::usage::Ended::default()
46    }
47}
48
49/// The limits of one attempt.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub struct Limits {
52    /// The attempt's timeout; `None` for none.
53    pub timeout: Option<Duration>,
54    /// The time between SIGTERM and SIGKILL (the master's cancel grace time).
55    pub grace: Duration,
56    /// The same for a draining worker's interrupt, which must end before the pod is killed
57    /// (`[worker] drain_terminate_period`).
58    pub interrupt_grace: Duration,
59    /// How often a stopped process's group is looked at, until it is gone.
60    pub poll: Duration,
61}
62
63/// How often a stopped process's group is looked at, unless `stop_poll` says.
64pub const STOP_POLL: Duration = Duration::from_millis(100);
65
66/// The reasons to stop an attempt, in the order they come: the first decides its status;
67/// a drain's interrupt after it only hurries its SIGKILL (B9). The agent keeps a
68/// [`StopSender`] for as long as the attempt runs.
69#[derive(Debug)]
70pub struct Stops {
71    reasons: mpsc::UnboundedReceiver<StopReason>,
72    sender: StopSender,
73    /// A reason taken already and given back: the next one.
74    first: Option<StopReason>,
75}
76
77/// Sends an attempt its reasons to stop (cheap to clone).
78pub type StopSender = mpsc::UnboundedSender<StopReason>;
79
80impl Stops {
81    /// A new channel of reasons, and its sender.
82    #[must_use]
83    pub fn new() -> (StopSender, Self) {
84        let (sender, reasons) = mpsc::unbounded_channel();
85        (
86            sender.clone(),
87            Self {
88                reasons,
89                sender,
90                first: None,
91            },
92        )
93    }
94
95    /// Another sender to this channel (the memory watchdog's).
96    #[must_use]
97    pub fn sender(&self) -> StopSender {
98        self.sender.clone()
99    }
100
101    /// Gives back `reason`, taken already: it is the next one, before those queued since.
102    pub const fn give_back(&mut self, reason: StopReason) {
103        self.first = Some(reason);
104    }
105
106    /// The next reason; never ready while none comes (the channel keeps a sender of its own,
107    /// so it never ends).
108    pub async fn next_reason(&mut self) -> StopReason {
109        if let Some(reason) = self.first.take() {
110            return reason;
111        }
112        match self.reasons.recv().await {
113            Some(reason) => reason,
114            None => std::future::pending().await,
115        }
116    }
117}
118
119/// How a supervised process ended.
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub struct Supervised {
122    /// How it ended.
123    pub termination: Termination,
124    /// Why the agent stopped it, if it did.
125    pub stopped: Option<StopReason>,
126    /// Whether it needed SIGKILL (it didn't end within the grace time after SIGTERM).
127    pub killed: bool,
128}
129
130/// Waits for `process`; on timeout, or at the first reason from `stop` (cancel, drain), sends
131/// SIGTERM to its group, and SIGKILL if it hasn't ended after the grace time (the interrupt
132/// grace for a drain's interrupt, also when the interrupt comes during another reason's
133/// grace); over its memory budget ([`StopReason::OomKilled`]), SIGKILL at once.
134///
135/// # Errors
136///
137/// Returns an I/O error from waiting or signalling.
138pub async fn supervise<P: Process>(
139    process: &mut P,
140    limits: Limits,
141    mut stops: Stops,
142) -> io::Result<Supervised> {
143    let deadline = async {
144        match limits.timeout {
145            Some(timeout) => tokio::time::sleep(timeout).await,
146            None => std::future::pending::<()>().await,
147        }
148    };
149    // Reasons first: the memory watchdog sends its reason before its SIGKILL, so an attempt
150    // it killed is `oom_killed`, not just a process that ended.
151    let reason = tokio::select! {
152        biased;
153        reason = stops.next_reason() => reason,
154        () = deadline => StopReason::TimedOut,
155        termination = process.wait() => return Ok(ended(termination?, None, false)),
156    };
157    if reason == StopReason::OomKilled {
158        // Over its memory budget: a spike can't wait for a grace period.
159        process.signal(Signal::Kill)?;
160        return Ok(ended(process.wait().await?, Some(reason), true));
161    }
162    process.signal(Signal::Term)?;
163    let grace = if reason == StopReason::Interrupted {
164        limits.interrupt_grace
165    } else {
166        limits.grace
167    };
168    let mut kill_at = tokio::time::Instant::now() + grace;
169    // Until it ends or the grace is over, a later reason can only hurry the SIGKILL: a
170    // drain's interrupt to at most `interrupt_grace` from now (B9), the memory watchdog to
171    // now. The status stays the first reason's.
172    loop {
173        tokio::select! {
174            biased;
175            later = stops.next_reason() => match later {
176                StopReason::Interrupted => {
177                    let hurried = tokio::time::Instant::now() + limits.interrupt_grace;
178                    kill_at = kill_at.min(hurried);
179                }
180                StopReason::OomKilled => break,
181                StopReason::TimedOut | StopReason::Cancelled | StopReason::CutOff => {}
182            },
183            termination = process.wait() => {
184                let termination = termination?;
185                left_after_leader(process, &mut stops, limits, kill_at).await?;
186                return Ok(ended(termination, Some(reason), false));
187            }
188            () = tokio::time::sleep_until(kill_at) => break,
189        }
190    }
191    process.signal(Signal::Kill)?;
192    Ok(ended(process.wait().await?, Some(reason), true))
193}
194
195/// The leader ended while its task is being stopped: what is left of its group (a child still
196/// shutting down, or one ignoring SIGTERM and holding the output open, B55) keeps the rest of
197/// the grace, then is killed (decision 100); with nothing left, this returns at once. A later
198/// reason still hurries it, as for the leader.
199async fn left_after_leader<P: Process>(
200    process: &mut P,
201    stops: &mut Stops,
202    limits: Limits,
203    mut kill_at: tokio::time::Instant,
204) -> io::Result<()> {
205    while process.group_alive() {
206        let now = tokio::time::Instant::now();
207        if now >= kill_at {
208            return process.signal(Signal::Kill);
209        }
210        tokio::select! {
211            biased;
212            later = stops.next_reason() => match later {
213                StopReason::Interrupted => {
214                    // From its arrival, not from the poll before it.
215                    let arrived = tokio::time::Instant::now();
216                    kill_at = kill_at.min(arrived + limits.interrupt_grace);
217                }
218                StopReason::OomKilled => return process.signal(Signal::Kill),
219                StopReason::TimedOut | StopReason::Cancelled | StopReason::CutOff => {}
220            },
221            () = tokio::time::sleep_until((now + limits.poll).min(kill_at)) => {}
222        }
223    }
224    Ok(())
225}
226
227fn ended(termination: Termination, stopped: Option<StopReason>, killed: bool) -> Supervised {
228    Supervised {
229        termination,
230        stopped,
231        killed,
232    }
233}