1use std::sync::Arc;
27
28use async_trait::async_trait;
29use engenho_store::{
30 StoreMesh,
31 command::{Reason, ResourceCommand},
32 resource::ResourceKey,
33};
34use serde_json::{Value, json};
35
36use crate::error::ControllerError;
37use crate::event_recorder::Reason as EventReason;
38use crate::meta::{DefaultedInt, ObjectMeta, REPLICAS, ShapeError, warn_unreadable};
39use crate::owned_children::{OwnedChildrenReconciler, ParentGvk, ReconcileDelta};
40use crate::owner::{owner_ref_for, set_owner_reference};
41use crate::pod_template::{NormalizedTemplate, POD_TEMPLATE_HASH_LABEL, TemplateHash};
42use crate::reads::gvk;
43use crate::sweep::{Sweep, impl_sweep_event_sink};
44use engenho_types::kind::GroupVersionKind;
45
46const RS_STATUS_REPLICAS: DefaultedInt = DefaultedInt::new(&["status", "replicas"], 0);
50const RS_STATUS_READY: DefaultedInt = DefaultedInt::new(&["status", "readyReplicas"], 0);
51const RS_STATUS_AVAILABLE: DefaultedInt = DefaultedInt::new(&["status", "availableReplicas"], 0);
52
53pub struct DeploymentController {
54 store: Arc<StoreMesh>,
55 namespace: Option<String>,
56 sweep: Sweep,
61}
62
63impl_sweep_event_sink!(DeploymentController);
64
65impl DeploymentController {
66 #[must_use]
67 pub fn new(store: Arc<StoreMesh>, namespace: Option<String>) -> Self {
68 Self {
69 store,
70 namespace,
71 sweep: Sweep::new("deployment-controller", EventReason::ReplicaSetCreateError),
72 }
73 }
74
75 fn build_replicaset_from(
83 d: &Value,
84 hash: TemplateHash,
85 replicas: i64,
86 ) -> Option<(String, Value)> {
87 let d_name = d.name()?;
88 let d_namespace = d
94 .namespace()
95 .map_or_else(|| "default".to_string(), std::borrow::ToOwned::to_owned);
96 let template = d.get("spec").and_then(|s| s.get("template"))?.clone();
97 let rs_name = format!("{d_name}-{hash}");
98 let value = json!({
99 "kind": "ReplicaSet",
100 "apiVersion": "apps/v1",
101 "metadata": {
102 "name": rs_name,
103 "namespace": d_namespace,
104 "labels": {
105 "app.kubernetes.io/managed-by": "engenho-deployment-controller",
106 POD_TEMPLATE_HASH_LABEL: hash.to_string()
107 }
108 },
109 "spec": {
110 "replicas": replicas,
111 "selector": d.get("spec").and_then(|s| s.get("selector")).cloned(),
112 "template": template
113 }
114 });
115 Some((rs_name, value))
116 }
117
118 fn rs_status_counts(rs: &Value) -> Result<(i64, i64, i64), ShapeError> {
125 Ok((
126 RS_STATUS_REPLICAS.read(rs)?,
127 RS_STATUS_READY.read(rs)?,
128 RS_STATUS_AVAILABLE.read(rs)?,
129 ))
130 }
131}
132
133#[async_trait]
134impl OwnedChildrenReconciler for DeploymentController {
135 fn name(&self) -> &'static str {
136 "deployment"
137 }
138
139 fn parent_gvk(&self) -> ParentGvk {
140 ParentGvk::new("apps", "v1", "Deployment", "apps/v1")
141 }
142
143 fn child_kinds(&self) -> &'static [GroupVersionKind] {
144 const CHILD_KINDS: &[GroupVersionKind] = &[gvk("apps", "v1", "ReplicaSet")];
145 CHILD_KINDS
146 }
147
148 fn also_reads(&self) -> &'static [GroupVersionKind] {
149 &[]
150 }
151
152 fn store(&self) -> &StoreMesh {
153 &self.store
154 }
155
156 fn namespace(&self) -> Option<&str> {
157 self.namespace.as_deref()
158 }
159
160 fn sweep(&self) -> &Sweep {
161 &self.sweep
162 }
163
164 async fn reconcile_one(
165 &self,
166 d_value: &Value,
167 owned_rs: &[(ResourceKey, Value)],
168 ) -> Result<ReconcileDelta, ControllerError> {
169 let desired_replicas = REPLICAS.read(d_value)?;
173 let Some(template) = NormalizedTemplate::of_spec_template(d_value) else {
176 return Ok(ReconcileDelta::none());
177 };
178 let Some(owner_ref) = owner_ref_for(d_value, "apps/v1", "Deployment") else {
179 return Ok(ReconcileDelta::none());
180 };
181
182 let ns = self.namespace.as_deref();
183 let mut commands = Vec::new();
184 let current = current_replicaset(&template, owned_rs);
185 let current_key = current.map(|(k, _)| k);
186
187 for (rs_key, rs_value) in owned_rs {
195 if current_key == Some(rs_key) {
196 continue;
197 }
198 let current_replicas = match REPLICAS.read(rs_value) {
199 Ok(n) => n,
200 Err(e) => {
201 warn_unreadable("deployment", &rs_key.label(), &e);
202 continue;
203 }
204 };
205 if current_replicas != 0 {
206 commands.push(ResourceCommand::patch(
207 rs_key.clone(),
208 json!({"spec": {"replicas": 0}}),
209 Reason::Controller,
210 ));
211 }
212 }
213
214 match current {
217 Some((rs_key, rs_value)) => match REPLICAS.read(rs_value) {
218 Ok(current_replicas) => {
219 if current_replicas != desired_replicas {
220 commands.push(ResourceCommand::patch(
221 rs_key.clone(),
222 json!({"spec": {"replicas": desired_replicas}}),
223 Reason::Controller,
224 ));
225 }
226 }
227 Err(e) => warn_unreadable("deployment", &rs_key.label(), &e),
228 },
229 None => {
230 if let Some((rs_name, mut rs_value)) = template
233 .naming_hash()
234 .and_then(|hash| Self::build_replicaset_from(d_value, hash, desired_replicas))
235 {
236 set_owner_reference(&mut rs_value, owner_ref.clone())?;
237 let rs_ns = crate::owned_children::child_namespace(d_value, ns);
241 let rs_key =
242 ResourceKey::namespaced("apps", "v1", "ReplicaSet", &rs_ns, &rs_name);
243 commands.push(ResourceCommand::Put {
244 key: rs_key,
245 value: rs_value,
246 expected: None,
247 reason: Reason::Controller,
248 });
249 }
250 }
251 }
252
253 Ok(ReconcileDelta::from_commands(commands))
254 }
255
256 fn compute_status(
257 &self,
258 d_value: &Value,
259 owned_rs_after: &[(ResourceKey, Value)],
260 observed_generation: i64,
261 ) -> Option<Value> {
262 let template = NormalizedTemplate::of_spec_template(d_value)?;
270 let (mut replicas, mut ready, mut available) = (0_i64, 0_i64, 0_i64);
271 for (rs_key, rs) in owned_rs_after
272 .iter()
273 .filter(|(_, r)| runs_template(r, &template))
274 {
275 match Self::rs_status_counts(rs) {
276 Ok((r, rd, av)) => {
277 replicas = replicas.saturating_add(r);
278 ready = ready.saturating_add(rd);
279 available = available.saturating_add(av);
280 }
281 Err(e) => {
282 warn_unreadable("deployment", &rs_key.label(), &e);
283 return None;
284 }
285 }
286 }
287 let updated = replicas;
288 let desired = REPLICAS.read(d_value).ok()?;
289 let current_rs =
290 current_replicaset(&template, owned_rs_after).and_then(|(_, rs)| rs.name());
291 let conditions = conditions(
292 d_value,
293 Counts {
294 desired,
295 replicas,
296 updated,
297 available,
298 },
299 current_rs,
300 &engenho_types::time::now_rfc3339_utc(),
301 );
302 Some(json!({
303 "replicas": replicas,
304 "readyReplicas": ready,
305 "availableReplicas": available,
306 "updatedReplicas": updated,
307 "observedGeneration": observed_generation,
308 "conditions": conditions,
309 }))
310 }
311}
312
313#[derive(Clone, Copy)]
314struct Counts {
315 desired: i64,
316 replicas: i64,
317 updated: i64,
318 available: i64,
319}
320
321fn scaled(value: Option<&Value>, total: i64, round_up: bool, default_percent: i64) -> i64 {
322 let percent = match value {
323 Some(Value::Number(n)) => return n.as_i64().unwrap_or(0).max(0),
324 Some(Value::String(s)) => s
325 .strip_suffix('%')
326 .and_then(|p| p.parse::<i64>().ok())
327 .unwrap_or(default_percent),
328 _ => default_percent,
329 };
330 let numer = percent.saturating_mul(total);
331 if round_up {
332 numer.div_euclid(100) + i64::from(numer.rem_euclid(100) != 0)
333 } else {
334 numer.div_euclid(100)
335 }
336}
337
338fn max_unavailable(d: &Value, desired: i64) -> i64 {
339 let strategy = d.pointer("/spec/strategy");
340 let recreate = strategy
341 .and_then(|s| s.get("type"))
342 .and_then(Value::as_str)
343 .is_some_and(|t| t == "Recreate");
344 if recreate || desired == 0 {
345 return 0;
346 }
347 let rolling = strategy.and_then(|s| s.get("rollingUpdate"));
348 let surge = scaled(rolling.and_then(|r| r.get("maxSurge")), desired, true, 25);
349 let mut unavailable = scaled(
350 rolling.and_then(|r| r.get("maxUnavailable")),
351 desired,
352 false,
353 25,
354 );
355 if surge == 0 && unavailable == 0 {
356 unavailable = 1;
357 }
358 unavailable.min(desired)
359}
360
361fn conditions(d: &Value, counts: Counts, current_rs: Option<&str>, now: &str) -> Vec<Value> {
362 let prior = d
363 .pointer("/status/conditions")
364 .and_then(Value::as_array)
365 .cloned()
366 .unwrap_or_default();
367 let carried = |kind: &str, status: &str, reason: &str, message: String| {
368 let old = prior.iter().find(|c| c["type"] == kind);
369 if let Some(old) = old
370 && old["status"] == status
371 && old["reason"] == reason
372 {
373 return old.clone();
374 }
375 let since = old
376 .filter(|o| o["status"] == status)
377 .and_then(|o| o.get("lastTransitionTime"))
378 .cloned()
379 .unwrap_or_else(|| Value::String(now.to_string()));
380 json!({
381 "type": kind,
382 "status": status,
383 "lastUpdateTime": now,
384 "lastTransitionTime": since,
385 "reason": reason,
386 "message": message,
387 })
388 };
389 let mut out = Vec::new();
390 if counts.available >= counts.desired - max_unavailable(d, counts.desired) {
391 out.push(carried(
392 "Available",
393 "True",
394 "MinimumReplicasAvailable",
395 "Deployment has minimum availability.".to_string(),
396 ));
397 } else {
398 out.push(carried(
399 "Available",
400 "False",
401 "MinimumReplicasUnavailable",
402 "Deployment does not have minimum availability.".to_string(),
403 ));
404 }
405 if let Some(rs) = current_rs {
406 let complete = counts.updated == counts.desired
407 && counts.replicas == counts.desired
408 && counts.available == counts.desired;
409 out.push(if complete {
410 carried(
411 "Progressing",
412 "True",
413 "NewReplicaSetAvailable",
414 format!("ReplicaSet {rs:?} has successfully progressed."),
415 )
416 } else {
417 carried(
418 "Progressing",
419 "True",
420 "ReplicaSetUpdated",
421 format!("ReplicaSet {rs:?} is progressing."),
422 )
423 });
424 }
425 out
426}
427
428fn runs_template(rs: &Value, template: &NormalizedTemplate) -> bool {
432 NormalizedTemplate::of_spec_template(rs).as_ref() == Some(template)
433}
434
435#[must_use]
448pub fn current_replicaset<'a>(
449 template: &NormalizedTemplate,
450 owned_rs: &'a [(ResourceKey, Value)],
451) -> Option<&'a (ResourceKey, Value)> {
452 owned_rs
453 .iter()
454 .filter(|(_, rs)| runs_template(rs, template))
455 .max_by(|(key_a, a), (key_b, b)| {
456 REPLICAS
457 .read(a)
458 .ok()
459 .cmp(&REPLICAS.read(b).ok())
460 .then_with(|| key_b.name.cmp(&key_a.name))
461 })
462}
463
464#[cfg(test)]
465mod tests {
466 use super::*;
467
468 fn hash_of(d: &Value) -> TemplateHash {
469 NormalizedTemplate::of_spec_template(d)
470 .and_then(|t| t.naming_hash())
471 .expect("a Deployment with a template has a naming hash")
472 }
473
474 fn rs(
475 name: &str,
476 replicas: Option<i64>,
477 hash_label: &str,
478 template: &Value,
479 ) -> (ResourceKey, Value) {
480 let mut v = json!({
481 "metadata": {"name": name, "labels": {"pod-template-hash": hash_label}},
482 "spec": {"template": template}
483 });
484 if let Some(n) = replicas {
485 v["spec"]["replicas"] = json!(n);
486 }
487 (
488 ResourceKey::namespaced("apps", "v1", "ReplicaSet", "default", name),
489 v,
490 )
491 }
492
493 fn web(image: &str) -> Value {
494 json!({
495 "metadata": {"labels": {"app": "web"}},
496 "spec": {"containers": [{"name": "c", "image": image}]}
497 })
498 }
499
500 fn name_of(found: Option<&(ResourceKey, Value)>) -> Option<&str> {
501 found.map(|(k, _)| k.name.as_str())
502 }
503
504 #[test]
505 fn the_current_replicaset_is_found_by_template_whatever_its_hash_label() {
506 let owned = vec![
507 rs("web-old", Some(0), "aaaaaaaaaa", &web("web:1")),
508 rs(
509 "web-cur",
510 Some(3),
511 "not-a-hash-this-code-made",
512 &web("web:2"),
513 ),
514 ];
515 let t = NormalizedTemplate::of(&web("web:2"));
516 assert_eq!(name_of(current_replicaset(&t, &owned)), Some("web-cur"));
517 }
518
519 #[test]
520 fn a_template_no_owned_replicaset_runs_has_no_current_replicaset() {
521 let owned = vec![rs("web-old", Some(3), "aaaaaaaaaa", &web("web:1"))];
522 let t = NormalizedTemplate::of(&web("web:2"));
523 assert!(current_replicaset(&t, &owned).is_none());
524 }
525
526 #[test]
527 fn a_replicaset_with_no_template_runs_no_template() {
528 let (key, mut v) = rs("web-bare", Some(3), "x", &web("web:1"));
529 v["spec"]["template"] = Value::Null;
530 let t = NormalizedTemplate::of(&Value::Null);
531 assert!(current_replicaset(&t, &[(key, v)]).is_none());
532 }
533
534 #[test]
535 fn of_two_replicasets_running_the_template_the_one_holding_the_pods_is_current() {
536 let mut byte_different = web("web:1");
540 byte_different["spec"]["volumes"] = json!([]);
541 let owned = vec![
542 rs("web-aaaa", Some(0), "aaaa", &web("web:1")),
543 rs("web-bbbb", Some(3), "bbbb", &byte_different),
544 ];
545 let t = NormalizedTemplate::of(&web("web:1"));
546 assert_eq!(name_of(current_replicaset(&t, &owned)), Some("web-bbbb"));
547 }
548
549 #[test]
550 fn a_tie_goes_to_the_name_that_sorts_first_in_any_order() {
551 let a = rs("web-aaaa", Some(2), "aaaa", &web("web:1"));
552 let b = rs("web-bbbb", Some(2), "bbbb", &web("web:1"));
553 let t = NormalizedTemplate::of(&web("web:1"));
554 let forward = vec![a.clone(), b.clone()];
555 let backward = vec![b, a];
556 assert_eq!(name_of(current_replicaset(&t, &forward)), Some("web-aaaa"));
557 assert_eq!(name_of(current_replicaset(&t, &backward)), Some("web-aaaa"));
558 }
559
560 #[test]
561 fn an_absent_count_is_the_api_one_and_outranks_zero() {
562 let owned = vec![
563 rs("web-aaaa", Some(0), "aaaa", &web("web:1")),
564 rs("web-bbbb", None, "bbbb", &web("web:1")),
565 ];
566 let t = NormalizedTemplate::of(&web("web:1"));
567 assert_eq!(name_of(current_replicaset(&t, &owned)), Some("web-bbbb"));
568 }
569
570 #[test]
571 fn max_unavailable_resolves_as_upstreams_fenceposts() {
572 let rolling = |ru: Value| json!({"spec": {"strategy": {"type": "RollingUpdate", "rollingUpdate": ru}}});
573 assert_eq!(max_unavailable(&json!({"spec": {}}), 2), 0);
574 assert_eq!(max_unavailable(&json!({"spec": {}}), 4), 1);
575 assert_eq!(max_unavailable(&json!({"spec": {}}), 10), 2);
576 assert_eq!(
577 max_unavailable(&rolling(json!({"maxSurge": 0, "maxUnavailable": 0})), 3),
578 1
579 );
580 assert_eq!(
581 max_unavailable(&rolling(json!({"maxUnavailable": 9})), 3),
582 3
583 );
584 assert_eq!(
585 max_unavailable(&rolling(json!({"maxUnavailable": "50%"})), 3),
586 1
587 );
588 assert_eq!(
589 max_unavailable(&json!({"spec": {"strategy": {"type": "Recreate"}}}), 3),
590 0
591 );
592 assert_eq!(max_unavailable(&json!({"spec": {}}), 0), 0);
593 }
594
595 #[test]
596 fn build_replicaset_carries_replicas_and_selector() {
597 let d = json!({
598 "metadata": {"name": "podinfo"},
599 "spec": {
600 "replicas": 5,
601 "selector": {"matchLabels": {"app": "podinfo"}},
602 "template": {"metadata": {"labels": {"app": "podinfo"}}, "spec": {}}
603 }
604 });
605 let hash = hash_of(&d);
606 let (name, rs) =
607 DeploymentController::build_replicaset_from(&d, hash, REPLICAS.read(&d).unwrap())
608 .unwrap();
609 assert_eq!(name, format!("podinfo-{hash}"));
610 assert_eq!(rs.get("spec").unwrap().get("replicas").unwrap(), 5);
611 let selector = rs.get("spec").unwrap().get("selector").unwrap();
612 assert_eq!(
613 selector.get("matchLabels").unwrap().get("app").unwrap(),
614 "podinfo"
615 );
616 let labels = rs.get("metadata").unwrap().get("labels").unwrap();
617 assert_eq!(
618 labels.get("pod-template-hash").unwrap(),
619 &json!(hash.to_string())
620 );
621 }
622
623 #[test]
624 fn build_replicaset_from_inherits_the_deployments_namespace() {
625 let d = json!({
630 "kind": "Deployment", "apiVersion": "apps/v1",
631 "metadata": {"name": "web", "namespace": "team-a", "uid": "u1"},
632 "spec": {
633 "replicas": 3,
634 "selector": {"matchLabels": {"app": "web"}},
635 "template": {
636 "metadata": {"labels": {"app": "web"}},
637 "spec": {"containers": [{"name": "c", "image": "img"}]}
638 }
639 }
640 });
641 let hash = hash_of(&d);
642 let (rs_name, rs) =
643 DeploymentController::build_replicaset_from(&d, hash, REPLICAS.read(&d).unwrap())
644 .unwrap();
645 assert_eq!(rs_name, format!("web-{hash}"));
646 assert_eq!(
647 rs.get("metadata").unwrap().get("namespace").unwrap(),
648 "team-a"
649 );
650 assert_eq!(rs.get("spec").unwrap().get("replicas").unwrap(), 3);
651 }
652
653 #[test]
654 fn build_replicaset_from_defaults_namespace_when_parent_has_none() {
655 let d = json!({
656 "metadata": {"name": "web"},
657 "spec": {"replicas": 1, "selector": {}, "template": {"spec": {"containers": []}}}
658 });
659 let (_, rs) = DeploymentController::build_replicaset_from(&d, hash_of(&d), 1).unwrap();
660 assert_eq!(
661 rs.get("metadata").unwrap().get("namespace").unwrap(),
662 "default"
663 );
664 }
665}