Skip to main content

engenho_controllers/
rollout.rs

1//! Template revisions and update strategies — how a controller that keeps
2//! pods under STABLE names (`DaemonSet`, `StatefulSet`) knows a pod is out of
3//! date, and how many it may replace at once.
4//!
5//! ## The defect this closes
6//!
7//! Both controllers used to decide a pod's fate by its NAME alone: a node (or
8//! an ordinal) with a pod was covered, whatever template the pod was made
9//! from. A template change therefore reached no running pod, ever. Measured on
10//! a native node when the daemon restarted onto a new release: every
11//! `DaemonSet` was re-rendered with the new closure as its image, the eight
12//! existing pods kept the old one, the old closure was garbage-collected, and
13//! the pods sat `ContainerCreating` for five and a half hours with nothing
14//! replacing them. Deleting them by hand was the only way out.
15//!
16//! Upstream stamps every pod with the revision of the template it was built
17//! from — the `controller-revision-hash` label, and for a `DaemonSet` also
18//! `pod-template-generation` — and replaces the pods whose revision differs,
19//! as the parent's `updateStrategy` allows. This module is that vocabulary,
20//! once, for both controllers.
21//!
22//! ## What the revision is
23//!
24//! [`TemplateRevision`] is the naming hash of the parent's normalized
25//! template ([`crate::pod_template::NormalizedTemplate`]), the hash a
26//! Deployment already names its `ReplicaSet`s by. Normalized, so a template
27//! whose bytes change without its meaning changing (`labels: null` dropped,
28//! `env: []` omitted) does not roll every pod in the cluster. Upstream hashes
29//! a `ControllerRevision`; engenho does not keep `ControllerRevision` objects
30//! (see `docs/QUALIFICATION.md`), so the hash value differs from upstream's
31//! while the label, and the rule it drives, are the same.
32//!
33//! A pod with NO revision label is out of date, as upstream reads it. Pods
34//! created before this module existed carry none, so the first reconcile
35//! after an upgrade rolls every such pod once — within the strategy's budget,
36//! which is the behaviour an upgrade should have.
37
38use serde_json::Value;
39
40use crate::error::ControllerError;
41use crate::meta::{ShapeError, object_mut};
42use crate::pod_template::NormalizedTemplate;
43
44/// The label naming the template revision a pod was built from. Upstream's
45/// `apps.ControllerRevisionHashLabelKey`.
46pub const CONTROLLER_REVISION_HASH_LABEL: &str = "controller-revision-hash";
47
48/// The label naming the `DaemonSet` generation a daemon pod was built at.
49/// Upstream's `extensions.DaemonSetTemplateGenerationKey`.
50pub const POD_TEMPLATE_GENERATION_LABEL: &str = "pod-template-generation";
51
52/// The revision of a parent's pod template.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct TemplateRevision(String);
55
56impl TemplateRevision {
57    /// The revision of `parent`'s `spec.template`. `None` when it declares no
58    /// template.
59    #[must_use]
60    pub fn of(parent: &Value) -> Option<Self> {
61        NormalizedTemplate::of_spec_template(parent)
62            .and_then(|t| t.naming_hash())
63            .map(|h| Self(h.to_string()))
64    }
65
66    /// The revision label a pod carries, if any.
67    #[must_use]
68    pub fn of_pod(pod: &Value) -> Option<&str> {
69        pod.pointer("/metadata/labels")
70            .and_then(|l| l.get(CONTROLLER_REVISION_HASH_LABEL))
71            .and_then(Value::as_str)
72    }
73
74    /// Whether `pod` was built from this revision. A pod with no revision
75    /// label was not.
76    #[must_use]
77    pub fn is_current(&self, pod: &Value) -> bool {
78        Self::of_pod(pod) == Some(self.0.as_str())
79    }
80
81    /// The label value.
82    #[must_use]
83    pub fn as_str(&self) -> &str {
84        &self.0
85    }
86
87    /// Stamp this revision (and, for a `DaemonSet`, the parent's
88    /// `generation`) onto a pod built from the template.
89    ///
90    /// # Errors
91    ///
92    /// [`ShapeError`] when the pod's `metadata.labels` is not an object.
93    pub fn stamp(&self, pod: &mut Value, generation: Option<i64>) -> Result<(), ShapeError> {
94        let labels = object_mut(pod, &["metadata", "labels"])?;
95        labels.insert(
96            CONTROLLER_REVISION_HASH_LABEL.into(),
97            Value::from(self.0.as_str()),
98        );
99        if let Some(g) = generation {
100            labels.insert(
101                POD_TEMPLATE_GENERATION_LABEL.into(),
102                Value::from(g.to_string()),
103            );
104        }
105        Ok(())
106    }
107}
108
109/// How many pods an update may take down at once: `maxUnavailable`, an
110/// integer or a percentage (`IntOrString`).
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum MaxUnavailable {
113    /// An absolute count.
114    Count(u32),
115    /// A percentage of the desired pod count.
116    Percent(u32),
117}
118
119impl MaxUnavailable {
120    /// Upstream's default for both `DaemonSet` and `StatefulSet`.
121    pub const DEFAULT: Self = Self::Count(1);
122
123    /// Resolve against `desired` pods, rounding a percentage UP as the
124    /// `DaemonSet` controller does, and never below one: a budget of zero
125    /// would stall every update forever (upstream turns `0` into `1` when
126    /// `maxSurge` is also `0`, and engenho has no surge).
127    #[must_use]
128    pub fn resolve(self, desired: usize) -> usize {
129        let n = match self {
130            Self::Count(c) => c as usize,
131            Self::Percent(p) => (desired * p as usize).div_ceil(100),
132        };
133        n.max(1)
134    }
135
136    fn parse(v: &Value) -> Result<Self, String> {
137        match v {
138            Value::Number(n) => n
139                .as_u64()
140                .and_then(|n| u32::try_from(n).ok())
141                .map(Self::Count)
142                .ok_or_else(|| format!("maxUnavailable {n} is not a non-negative integer")),
143            Value::String(s) => s
144                .strip_suffix('%')
145                .and_then(|p| p.parse::<u32>().ok())
146                .filter(|p| *p <= 100)
147                .map(Self::Percent)
148                .ok_or_else(|| format!("maxUnavailable {s:?} is not an integer or a percentage")),
149            other => Err(format!(
150                "maxUnavailable is {other}, not an integer or a percentage"
151            )),
152        }
153    }
154}
155
156/// A parent's `spec.updateStrategy`.
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum UpdateStrategy {
159    /// Replace out-of-date pods, at most `max_unavailable` down at once.
160    /// Upstream's default for both kinds.
161    RollingUpdate {
162        /// The budget.
163        max_unavailable: MaxUnavailable,
164        /// `StatefulSet` only: ordinals below this are never updated.
165        partition: u32,
166    },
167    /// Replace a pod only once something else deletes it.
168    OnDelete,
169}
170
171impl UpdateStrategy {
172    /// Read `spec.updateStrategy` from `parent`. Absent is
173    /// `RollingUpdate` with `maxUnavailable: 1` — upstream's default.
174    ///
175    /// # Errors
176    ///
177    /// [`ControllerError::InvalidResource`] for an unknown `type` or a
178    /// malformed `rollingUpdate`. Item-scoped: that one parent is refused
179    /// (an Event on it) and every other parent reconciles.
180    pub fn of(parent: &Value) -> Result<Self, ControllerError> {
181        let Some(s) = parent
182            .pointer("/spec/updateStrategy")
183            .filter(|v| !v.is_null())
184        else {
185            return Ok(Self::default());
186        };
187        let invalid = |why: String| ControllerError::InvalidResource(why);
188        match s
189            .get("type")
190            .and_then(Value::as_str)
191            .unwrap_or("RollingUpdate")
192        {
193            "OnDelete" => Ok(Self::OnDelete),
194            "RollingUpdate" => {
195                let ru = s.get("rollingUpdate").filter(|v| !v.is_null());
196                let max_unavailable = match ru.and_then(|r| r.get("maxUnavailable")) {
197                    None | Some(Value::Null) => MaxUnavailable::DEFAULT,
198                    Some(v) => MaxUnavailable::parse(v).map_err(invalid)?,
199                };
200                let partition = match ru.and_then(|r| r.get("partition")) {
201                    None | Some(Value::Null) => 0,
202                    Some(v) => v
203                        .as_u64()
204                        .and_then(|p| u32::try_from(p).ok())
205                        .ok_or_else(|| {
206                            invalid(format!("partition {v} is not a non-negative integer"))
207                        })?,
208                };
209                Ok(Self::RollingUpdate {
210                    max_unavailable,
211                    partition,
212                })
213            }
214            other => Err(invalid(format!(
215                "updateStrategy.type {other:?} is neither RollingUpdate nor OnDelete"
216            ))),
217        }
218    }
219}
220
221impl Default for UpdateStrategy {
222    fn default() -> Self {
223        Self::RollingUpdate {
224            max_unavailable: MaxUnavailable::DEFAULT,
225            partition: 0,
226        }
227    }
228}
229
230/// Whether a pod has reached phase `Failed`: terminal, and replaced by a
231/// controller that keeps one pod per slot.
232#[must_use]
233pub fn pod_is_failed(pod: &Value) -> bool {
234    pod.pointer("/status/phase").and_then(Value::as_str) == Some("Failed")
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240    use serde_json::json;
241
242    fn parent(template: &Value) -> Value {
243        json!({"spec": {"template": template}})
244    }
245
246    #[test]
247    fn the_revision_follows_the_template_and_ignores_meaningless_bytes() {
248        let a = TemplateRevision::of(&parent(
249            &json!({"spec": {"containers": [{"name": "c", "image": "nix:/nix/store/p27v2-engenho"}]}}),
250        ))
251        .unwrap();
252        let b = TemplateRevision::of(&parent(
253            &json!({"spec": {"containers": [{"name": "c", "image": "nix:/nix/store/q91n8-engenho"}]}}),
254        ))
255        .unwrap();
256        assert_ne!(a, b, "a new image is a new revision");
257        let a_again = TemplateRevision::of(&parent(&json!({
258            "metadata": {"labels": null},
259            "spec": {"containers": [{"name": "c", "image": "nix:/nix/store/p27v2-engenho", "env": []}]}
260        })))
261        .unwrap();
262        assert_eq!(
263            a, a_again,
264            "bytes that mean the same template are the same revision"
265        );
266        assert!(TemplateRevision::of(&json!({"spec": {}})).is_none());
267    }
268
269    #[test]
270    fn a_pod_without_a_revision_label_is_out_of_date() {
271        let rev = TemplateRevision::of(&parent(&json!({"spec": {}}))).unwrap();
272        assert!(!rev.is_current(&json!({"metadata": {"name": "p"}})));
273        let mut pod = json!({"metadata": {"name": "p"}});
274        rev.stamp(&mut pod, Some(3)).unwrap();
275        assert!(rev.is_current(&pod));
276        assert_eq!(
277            pod["metadata"]["labels"][POD_TEMPLATE_GENERATION_LABEL],
278            "3"
279        );
280    }
281
282    #[test]
283    fn the_default_strategy_is_upstreams_rolling_update_of_one() {
284        assert_eq!(
285            UpdateStrategy::of(&json!({"spec": {}})).unwrap(),
286            UpdateStrategy::RollingUpdate {
287                max_unavailable: MaxUnavailable::Count(1),
288                partition: 0
289            }
290        );
291        assert_eq!(
292            UpdateStrategy::of(&json!({"spec": {"updateStrategy": {"type": "RollingUpdate"}}}))
293                .unwrap(),
294            UpdateStrategy::default()
295        );
296    }
297
298    #[test]
299    fn on_delete_and_explicit_budgets_are_read() {
300        assert_eq!(
301            UpdateStrategy::of(&json!({"spec": {"updateStrategy": {"type": "OnDelete"}}})).unwrap(),
302            UpdateStrategy::OnDelete
303        );
304        let s = UpdateStrategy::of(&json!({"spec": {"updateStrategy": {
305            "type": "RollingUpdate", "rollingUpdate": {"maxUnavailable": "25%", "partition": 2}
306        }}}))
307        .unwrap();
308        assert_eq!(
309            s,
310            UpdateStrategy::RollingUpdate {
311                max_unavailable: MaxUnavailable::Percent(25),
312                partition: 2
313            }
314        );
315    }
316
317    #[test]
318    fn an_unknown_strategy_refuses_that_parent() {
319        for bad in [
320            json!({"type": "Recreate"}),
321            json!({"type": "RollingUpdate", "rollingUpdate": {"maxUnavailable": "x%"}}),
322            json!({"type": "RollingUpdate", "rollingUpdate": {"maxUnavailable": -1}}),
323            json!({"type": "RollingUpdate", "rollingUpdate": {"partition": "1"}}),
324        ] {
325            let err = UpdateStrategy::of(&json!({"spec": {"updateStrategy": bad}})).unwrap_err();
326            assert!(matches!(err, ControllerError::InvalidResource(_)), "{err}");
327        }
328    }
329
330    #[test]
331    fn a_budget_resolves_rounding_up_and_never_to_zero() {
332        assert_eq!(MaxUnavailable::Count(1).resolve(8), 1);
333        assert_eq!(MaxUnavailable::Count(0).resolve(8), 1);
334        assert_eq!(MaxUnavailable::Percent(25).resolve(8), 2);
335        assert_eq!(MaxUnavailable::Percent(10).resolve(8), 1);
336        assert_eq!(MaxUnavailable::Percent(100).resolve(8), 8);
337        assert_eq!(MaxUnavailable::Percent(0).resolve(8), 1);
338    }
339}