engenho_controllers/
rollout.rs1use serde_json::Value;
39
40use crate::error::ControllerError;
41use crate::meta::{ShapeError, object_mut};
42use crate::pod_template::NormalizedTemplate;
43
44pub const CONTROLLER_REVISION_HASH_LABEL: &str = "controller-revision-hash";
47
48pub const POD_TEMPLATE_GENERATION_LABEL: &str = "pod-template-generation";
51
52#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct TemplateRevision(String);
55
56impl TemplateRevision {
57 #[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 #[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 #[must_use]
77 pub fn is_current(&self, pod: &Value) -> bool {
78 Self::of_pod(pod) == Some(self.0.as_str())
79 }
80
81 #[must_use]
83 pub fn as_str(&self) -> &str {
84 &self.0
85 }
86
87 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum MaxUnavailable {
113 Count(u32),
115 Percent(u32),
117}
118
119impl MaxUnavailable {
120 pub const DEFAULT: Self = Self::Count(1);
122
123 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum UpdateStrategy {
159 RollingUpdate {
162 max_unavailable: MaxUnavailable,
164 partition: u32,
166 },
167 OnDelete,
169}
170
171impl UpdateStrategy {
172 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#[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}