Skip to main content

schedr_agent/
drain.rs

1//! Draining the worker on shutdown (SIGTERM): what happens when, decided apart from the agent
2//! so it is tested with plain instants (see archive/PROJECT.md, Worker lifecycle: drain).
3//!
4//! - The running attempts get until the **termination grace period** minus the drain's
5//!   terminate and report periods ([`DrainPeriods`]); whatever still runs then gets SIGTERM,
6//!   SIGKILL after the terminate period, and ends `interrupted` (run again without using a
7//!   retry). The report period is left for the results to reach the master before the pod is
8//!   killed (B8). A second shutdown request moves the deadline to now.
9//! - Once nothing runs, the agent waits (at most [`ACK_WAIT`], never past half the report
10//!   period before the end of the grace period) for the master to acknowledge the last
11//!   results, then deregisters, waiting for the master to take it until a quarter of the report
12//!   period before the end, and ends: the rest is for exiting within the grace (B237). Without
13//!   a master it ends at once (the journal keeps the results for the next start).
14
15use std::time::{Duration, Instant};
16
17#[cfg(test)]
18mod tests;
19
20/// How a drain's time is split (`[worker] termination_grace_period`, `drain_terminate_period`,
21/// `drain_report_period`; the configuration checks that the last two fit in the first).
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct DrainPeriods {
24    /// The whole drain: the pod's `terminationGracePeriodSeconds`.
25    pub grace: Duration,
26    /// From the SIGTERM of a task still running when the time is up to its SIGKILL.
27    pub terminate_period: Duration,
28    /// From that SIGKILL to the end of the grace period: reporting and deregistering.
29    pub report_period: Duration,
30    /// How long the last results may wait for the master's acknowledgement (`drain_ack_wait`).
31    pub ack_wait: Duration,
32}
33
34impl DrainPeriods {
35    /// Whether a cleanup try of `room` fits in the grace period, after what a drain keeps for
36    /// itself. One that doesn't still runs on: the agent waits for it, but whatever ends the
37    /// worker at the end of the grace period (a pod's kill, a service manager) would lose it.
38    #[must_use]
39    pub fn cleanup_fits(&self, room: Duration) -> bool {
40        room.saturating_add(self.terminate_period)
41            .saturating_add(self.report_period)
42            <= self.grace
43    }
44
45    /// What to say at a worker's start when `[worker] cleanup_timeout`, what a task's cleanup
46    /// gets unless it says otherwise, doesn't fit: said once, not for each task using it.
47    #[must_use]
48    pub fn default_cleanup_warning(&self, default_timeout: Duration) -> Option<String> {
49        (!self.cleanup_fits(default_timeout)).then(|| {
50            format!(
51                "`[worker] cleanup_timeout` ({default_timeout:?}) doesn't fit in \
52                 `termination_grace_period` ({:?}): whatever ends the worker at the end of a \
53                 drain (a pod's kill, a service manager) would lose a cleanup still running",
54                self.grace
55            )
56        })
57    }
58}
59
60impl Default for DrainPeriods {
61    /// 30 s (Kubernetes' default), of which 3 s to SIGKILL and 2 s to report.
62    fn default() -> Self {
63        Self {
64            grace: Duration::from_secs(30),
65            terminate_period: Duration::from_secs(3),
66            report_period: Duration::from_secs(2),
67            ack_wait: ACK_WAIT,
68        }
69    }
70}
71
72/// How long a drained agent waits for the master to acknowledge the last results.
73pub const ACK_WAIT: Duration = Duration::from_secs(5);
74
75/// What a draining agent does next.
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum DrainStep {
78    /// Keep waiting for the running attempts (or the acknowledgements).
79    Wait,
80    /// Stop the attempts still running: the deadline passed.
81    Interrupt,
82    /// Done: deregister and end.
83    Finish,
84}
85
86/// A drain in progress.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub struct Drain {
89    deadline: Instant,
90    end: Instant,
91    finish_by: Instant,
92    deregister_by: Instant,
93    interrupted: bool,
94    idle_since: Option<Instant>,
95    ack_wait: Duration,
96}
97
98impl Drain {
99    /// A drain starting at `now`, its time split as `periods` says.
100    #[must_use]
101    pub fn new(now: Instant, periods: DrainPeriods) -> Self {
102        let stop_and_report = periods.terminate_period + periods.report_period;
103        Self {
104            deadline: now + periods.grace.saturating_sub(stop_and_report),
105            end: now + periods.grace,
106            finish_by: now + periods.grace.saturating_sub(periods.report_period / 2),
107            deregister_by: now + periods.grace.saturating_sub(periods.report_period / 4),
108            interrupted: false,
109            idle_since: None,
110            ack_wait: periods.ack_wait,
111        }
112    }
113
114    /// When the grace period ends (the pod is killed then).
115    #[must_use]
116    pub const fn end(&self) -> Instant {
117        self.end
118    }
119
120    /// When waiting for the master ends at the latest: half the report period before the end,
121    /// left for deregistering and exiting (B237: a wait to the very end left the exit after it,
122    /// where a pod's kill came first).
123    #[must_use]
124    pub const fn finish_by(&self) -> Instant {
125        self.finish_by
126    }
127
128    /// How long, at most, the master gets to take the `Deregister`: a quarter of the report
129    /// period before the end, the rest left for exiting (B237).
130    #[must_use]
131    pub const fn deregister_by(&self) -> Instant {
132        self.deregister_by
133    }
134
135    /// Whether an attempt whose cleanup needs `room` must be stopped now, leaving that room
136    /// for one try of it (see archive/PROJECT.md, Per-task cleanup).
137    #[must_use]
138    pub fn stop_due(&self, now: Instant, room: Duration) -> bool {
139        now.checked_add(room)
140            .is_none_or(|latest| latest >= self.deadline)
141    }
142
143    /// A second shutdown request: the remaining attempts are stopped at once.
144    pub fn force(&mut self, now: Instant) {
145        self.deadline = self.deadline.min(now);
146    }
147
148    /// The next step at `now`, with `running` attempts, `unacked` results and whether the
149    /// master is connected.
150    pub fn step(
151        &mut self,
152        now: Instant,
153        running: usize,
154        unacked: usize,
155        connected: bool,
156    ) -> DrainStep {
157        if running > 0 {
158            self.idle_since = None;
159            if !self.interrupted && now >= self.deadline {
160                self.interrupted = true;
161                return DrainStep::Interrupt;
162            }
163            return DrainStep::Wait;
164        }
165        if unacked == 0 || !connected {
166            return DrainStep::Finish;
167        }
168        let idle = *self.idle_since.get_or_insert(now);
169        if now.duration_since(idle) >= self.ack_wait || now >= self.finish_by {
170            DrainStep::Finish
171        } else {
172            DrainStep::Wait
173        }
174    }
175}