1use std::sync::Arc;
32
33use async_trait::async_trait;
34use engenho_store::{
35 StoreMesh,
36 command::{Reason, ResourceCommand},
37};
38use serde_json::{Value, json};
39
40use crate::controller::{Controller, ReconcileOutcome, ReconcileReport};
41use crate::effect::Effect;
42use crate::error::ControllerError;
43use crate::meta::warn_unreadable;
44use crate::reads::{DeclaresReads, Reads, gvk};
45use crate::selector::{matches_labels, selector_match_labels};
46use crate::status::{generation_of, pod_is_ready};
47
48pub const DISRUPTED_POD_TTL: std::time::Duration = std::time::Duration::from_secs(120);
51
52#[must_use]
57pub fn pdb_selects(pdb: &Value, pod: &Value) -> bool {
58 selector_match_labels(pdb).is_some_and(|sel| matches_labels(pod, sel))
59}
60
61#[must_use]
67pub fn counts_healthy(pdb: &Value, pod: &Value) -> bool {
68 let name = pod.pointer("/metadata/name").and_then(Value::as_str);
69 let disrupted = name.is_some_and(|n| {
70 pdb.pointer("/status/disruptedPods")
71 .and_then(|m| m.get(n))
72 .and_then(Value::as_str)
73 .and_then(engenho_types::time::age_since_rfc3339)
74 .is_some_and(|age| age < DISRUPTED_POD_TTL)
75 });
76 pod_is_ready(pod) && pod.pointer("/metadata/deletionTimestamp").is_none() && !disrupted
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub struct PdbStatus {
85 pub current_healthy: i64,
87 pub desired_healthy: i64,
89 pub expected_pods: i64,
91 pub disruptions_allowed: i64,
93 pub observed_generation: i64,
95}
96
97pub struct PodDisruptionBudgetController {
99 store: Arc<StoreMesh>,
100 namespace: Option<String>,
101}
102
103impl PodDisruptionBudgetController {
104 #[must_use]
106 pub fn new(store: Arc<StoreMesh>, namespace: Option<String>) -> Self {
107 Self { store, namespace }
108 }
109
110 fn min_available(pdb: &Value) -> Option<&Value> {
111 pdb.get("spec").and_then(|s| s.get("minAvailable"))
112 }
113
114 fn max_unavailable(pdb: &Value) -> Option<&Value> {
115 pdb.get("spec").and_then(|s| s.get("maxUnavailable"))
116 }
117
118 #[must_use]
127 pub fn resolve_int_or_percent(value: &Value, total: i64) -> Option<i64> {
128 if let Some(n) = value.as_i64() {
129 return Some(n);
130 }
131 let s = value.as_str()?;
132 let pct_str = s.strip_suffix('%')?;
133 let pct: i64 = pct_str.trim().parse().ok()?;
134 let numer = pct.saturating_mul(total);
136 Some(numer.div_euclid(100) + i64::from(numer.rem_euclid(100) != 0))
137 }
138
139 #[must_use]
152 pub fn compute_status(
153 min_available: Option<&Value>,
154 max_unavailable: Option<&Value>,
155 healthy: i64,
156 total: i64,
157 generation: i64,
158 ) -> PdbStatus {
159 let desired_healthy = if let Some(min) = min_available {
160 Self::resolve_int_or_percent(min, total).unwrap_or(0)
161 } else if let Some(max) = max_unavailable {
162 let allowed_unavailable = Self::resolve_int_or_percent(max, total).unwrap_or(0);
163 total - allowed_unavailable
164 } else {
165 0
167 }
168 .max(0);
169
170 let disruptions_allowed = (healthy - desired_healthy).max(0);
171
172 PdbStatus {
173 current_healthy: healthy,
174 desired_healthy,
175 expected_pods: total,
176 disruptions_allowed,
177 observed_generation: generation,
178 }
179 }
180
181 fn current_status(pdb: &Value) -> Option<PdbStatus> {
186 let status = pdb.get("status")?;
187 let read = |k: &str| status.get(k).and_then(serde_json::Value::as_i64);
188 Some(PdbStatus {
189 current_healthy: read("currentHealthy")?,
190 desired_healthy: read("desiredHealthy")?,
191 expected_pods: read("expectedPods")?,
192 disruptions_allowed: read("disruptionsAllowed")?,
193 observed_generation: read("observedGeneration")?,
194 })
195 }
196}
197
198impl DeclaresReads for PodDisruptionBudgetController {
200 fn reads(&self) -> Reads {
201 Reads::of(&[
202 gvk("policy", "v1", "PodDisruptionBudget"),
203 gvk("", "v1", "Pod"),
204 ])
205 }
206}
207
208#[async_trait]
209impl Controller for PodDisruptionBudgetController {
210 fn name(&self) -> &'static str {
211 "pdb"
212 }
213
214 async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
215 let pdbs = self
216 .store
217 .list(
218 "policy",
219 "v1",
220 "PodDisruptionBudget",
221 self.namespace.as_deref(),
222 )
223 .await;
224 let mut report = ReconcileReport::default();
225 report.objects_examined = pdbs.len();
226
227 for (pdb_key, pdb_value) in &pdbs {
228 if selector_match_labels(pdb_value).is_none() {
232 report.objects_skipped += 1;
233 continue;
234 }
235 let generation = match generation_of(pdb_value) {
238 Ok(generation) => generation,
239 Err(e) => {
240 warn_unreadable("pdb", &pdb_key.label(), &e);
241 report.objects_skipped += 1;
242 continue;
243 }
244 };
245 let ns = pdb_key.namespace.as_deref();
246 let pods = self.store.list("", "v1", "Pod", ns).await;
247 let matching: Vec<&Value> = pods
248 .iter()
249 .filter_map(|(_, p)| pdb_selects(pdb_value, p).then_some(p))
250 .collect();
251 let total = matching.len() as i64;
252 let healthy = matching
253 .iter()
254 .filter(|p| counts_healthy(pdb_value, p))
255 .count() as i64;
256
257 let desired = Self::compute_status(
258 Self::min_available(pdb_value),
259 Self::max_unavailable(pdb_value),
260 healthy,
261 total,
262 generation,
263 );
264
265 if Self::current_status(pdb_value) == Some(desired) {
268 continue;
269 }
270
271 let applied = self
272 .store
273 .propose(ResourceCommand::patch(
274 pdb_key.clone(),
275 json!({
276 "status": {
277 "currentHealthy": desired.current_healthy,
278 "desiredHealthy": desired.desired_healthy,
279 "expectedPods": desired.expected_pods,
280 "disruptionsAllowed": desired.disruptions_allowed,
281 "observedGeneration": desired.observed_generation,
282 }
283 }),
284 Reason::Controller,
285 ))
286 .await?;
287 report.record(Effect::of(applied.op));
288 }
289 Ok(report.into())
290 }
291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296 use engenho_store::resource::ResourceKey;
297 use serde_json::json;
298
299 #[test]
302 fn min_available_reads_spec_field() {
303 let pdb = json!({"spec": {"minAvailable": 2}});
304 assert_eq!(
305 PodDisruptionBudgetController::min_available(&pdb).and_then(serde_json::Value::as_i64),
306 Some(2)
307 );
308 }
309
310 #[test]
311 fn max_unavailable_reads_spec_field() {
312 let pdb = json!({"spec": {"maxUnavailable": 1}});
313 assert_eq!(
314 PodDisruptionBudgetController::max_unavailable(&pdb)
315 .and_then(serde_json::Value::as_i64),
316 Some(1)
317 );
318 }
319
320 #[test]
321 fn pod_is_ready_true_when_condition_true() {
322 let p = json!({"status": {"conditions": [{"type": "Ready", "status": "True"}]}});
323 assert!(crate::status::pod_is_ready(&p));
324 }
325
326 #[test]
327 fn pod_is_ready_false_when_condition_false() {
328 let p = json!({"status": {"conditions": [{"type": "Ready", "status": "False"}]}});
329 assert!(!crate::status::pod_is_ready(&p));
330 }
331
332 #[test]
333 fn pod_is_ready_false_when_no_status() {
334 let p = json!({"metadata": {"name": "x"}});
335 assert!(!crate::status::pod_is_ready(&p));
336 }
337
338 #[test]
341 fn resolve_int_or_percent_bare_int() {
342 assert_eq!(
343 PodDisruptionBudgetController::resolve_int_or_percent(&json!(2), 10),
344 Some(2)
345 );
346 }
347
348 #[test]
349 fn resolve_int_or_percent_percent_ceils() {
350 assert_eq!(
352 PodDisruptionBudgetController::resolve_int_or_percent(&json!("50%"), 4),
353 Some(2)
354 );
355 assert_eq!(
357 PodDisruptionBudgetController::resolve_int_or_percent(&json!("50%"), 3),
358 Some(2)
359 );
360 assert_eq!(
362 PodDisruptionBudgetController::resolve_int_or_percent(&json!("30%"), 10),
363 Some(3)
364 );
365 assert_eq!(
367 PodDisruptionBudgetController::resolve_int_or_percent(&json!("100%"), 5),
368 Some(5)
369 );
370 }
371
372 #[test]
373 fn resolve_int_or_percent_malformed_is_none() {
374 assert_eq!(
375 PodDisruptionBudgetController::resolve_int_or_percent(&json!("abc"), 4),
376 None
377 );
378 assert_eq!(
379 PodDisruptionBudgetController::resolve_int_or_percent(&json!("50"), 4),
380 None
381 );
382 assert_eq!(
383 PodDisruptionBudgetController::resolve_int_or_percent(&json!(null), 4),
384 None
385 );
386 }
387
388 #[test]
391 fn compute_status_min_available_int() {
392 let s = PodDisruptionBudgetController::compute_status(Some(&json!(2)), None, 3, 3, 7);
394 assert_eq!(s.expected_pods, 3);
395 assert_eq!(s.current_healthy, 3);
396 assert_eq!(s.desired_healthy, 2);
397 assert_eq!(s.disruptions_allowed, 1);
398 assert_eq!(s.observed_generation, 7);
399 }
400
401 #[test]
402 fn compute_status_min_available_percent() {
403 let s = PodDisruptionBudgetController::compute_status(Some(&json!("50%")), None, 3, 4, 1);
405 assert_eq!(s.expected_pods, 4);
406 assert_eq!(s.current_healthy, 3);
407 assert_eq!(s.desired_healthy, 2);
408 assert_eq!(s.disruptions_allowed, 1);
409 }
410
411 #[test]
412 fn compute_status_max_unavailable_int() {
413 let s = PodDisruptionBudgetController::compute_status(None, Some(&json!(1)), 3, 3, 1);
415 assert_eq!(s.desired_healthy, 2);
416 assert_eq!(s.disruptions_allowed, 1);
417 }
418
419 #[test]
420 fn compute_status_max_unavailable_percent() {
421 let s = PodDisruptionBudgetController::compute_status(None, Some(&json!("25%")), 4, 4, 1);
424 assert_eq!(s.desired_healthy, 3);
425 assert_eq!(s.disruptions_allowed, 1);
426 }
427
428 #[test]
429 fn compute_status_clamps_disruptions_allowed_at_zero() {
430 let s = PodDisruptionBudgetController::compute_status(Some(&json!(3)), None, 2, 3, 1);
432 assert_eq!(s.desired_healthy, 3);
433 assert_eq!(s.disruptions_allowed, 0);
434 let s = PodDisruptionBudgetController::compute_status(Some(&json!(2)), None, 2, 2, 1);
436 assert_eq!(s.disruptions_allowed, 0);
437 }
438
439 #[test]
440 fn compute_status_max_unavailable_cannot_drive_desired_negative() {
441 let s = PodDisruptionBudgetController::compute_status(None, Some(&json!(5)), 3, 3, 1);
443 assert_eq!(s.desired_healthy, 0);
444 assert_eq!(s.disruptions_allowed, 3);
445 }
446
447 #[test]
448 fn compute_status_neither_defaults_to_zero_desired() {
449 let s = PodDisruptionBudgetController::compute_status(None, None, 5, 5, 1);
450 assert_eq!(s.desired_healthy, 0);
451 assert_eq!(s.disruptions_allowed, 5);
452 }
453
454 #[test]
455 fn controller_name_is_stable() {
456 struct F;
457 #[async_trait]
458 impl Controller for F {
459 fn name(&self) -> &'static str {
460 "pdb"
461 }
462 async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
463 Ok(ReconcileReport::default().into())
464 }
465 }
466 assert_eq!(F.name(), "pdb");
467 }
468
469 async fn live_store() -> Arc<StoreMesh> {
472 use engenho_store::{InProcessRouter, default_config};
473 use std::time::Duration;
474 let router = InProcessRouter::new();
475 let cfg = default_config("controllers-pdb").unwrap();
476 let store = Arc::new(
477 StoreMesh::start(1, "in-process://1".into(), router, cfg)
478 .await
479 .unwrap(),
480 );
481 store.initialize_singleton().await.unwrap();
482 assert!(store.wait_for_leadership(Duration::from_secs(3)).await);
483 store
484 }
485
486 async fn put_pod(store: &Arc<StoreMesh>, ns: &str, name: &str, labels: Value, ready: bool) {
488 let conditions = if ready {
489 json!([{"type": "Ready", "status": "True"}])
490 } else {
491 json!([{"type": "Ready", "status": "False"}])
492 };
493 store
494 .propose(ResourceCommand::put(
495 ResourceKey::namespaced("", "v1", "Pod", ns, name),
496 json!({
497 "kind": "Pod", "apiVersion": "v1",
498 "metadata": {"name": name, "namespace": ns, "labels": labels},
499 "status": {"conditions": conditions}
500 }),
501 Reason::Operator,
502 ))
503 .await
504 .unwrap();
505 }
506
507 async fn put_pdb(store: &Arc<StoreMesh>, ns: &str, name: &str, spec: Value) -> ResourceKey {
509 let key = ResourceKey::namespaced("policy", "v1", "PodDisruptionBudget", ns, name);
510 store
511 .propose(ResourceCommand::put(
512 key.clone(),
513 json!({
514 "kind": "PodDisruptionBudget", "apiVersion": "policy/v1",
515 "metadata": {"name": name, "namespace": ns},
516 "spec": spec
517 }),
518 Reason::Operator,
519 ))
520 .await
521 .unwrap();
522 key
523 }
524
525 fn status_of(pdb: &Value) -> (i64, i64, i64, i64) {
526 let s = pdb.get("status").expect("status patched");
527 (
528 s["currentHealthy"].as_i64().unwrap(),
529 s["desiredHealthy"].as_i64().unwrap(),
530 s["expectedPods"].as_i64().unwrap(),
531 s["disruptionsAllowed"].as_i64().unwrap(),
532 )
533 }
534
535 #[tokio::test]
536 async fn min_available_two_three_ready_pods() {
537 let store = live_store().await;
538 let key = put_pdb(
539 &store,
540 "ns1",
541 "pdb",
542 json!({"minAvailable": 2, "selector": {"matchLabels": {"app": "x"}}}),
543 )
544 .await;
545 for n in ["p1", "p2", "p3"] {
546 put_pod(&store, "ns1", n, json!({"app": "x"}), true).await;
547 }
548
549 let c = PodDisruptionBudgetController::new(store.clone(), None);
550 let out = c.tick().await.unwrap();
551 assert_eq!(out.objects_changed, 1);
552
553 let pdb = store.get(&key).await.unwrap();
554 assert_eq!(status_of(&pdb), (3, 2, 3, 1));
556 let generation = pdb["metadata"]["generation"].as_i64().unwrap();
558 assert_eq!(
559 pdb["status"]["observedGeneration"].as_i64().unwrap(),
560 generation
561 );
562 }
563
564 #[tokio::test]
565 async fn min_available_percent_50_of_four() {
566 let store = live_store().await;
567 let key = put_pdb(
568 &store,
569 "ns1",
570 "pdb",
571 json!({"minAvailable": "50%", "selector": {"matchLabels": {"app": "x"}}}),
572 )
573 .await;
574 put_pod(&store, "ns1", "p1", json!({"app": "x"}), true).await;
576 put_pod(&store, "ns1", "p2", json!({"app": "x"}), true).await;
577 put_pod(&store, "ns1", "p3", json!({"app": "x"}), true).await;
578 put_pod(&store, "ns1", "p4", json!({"app": "x"}), false).await;
579
580 PodDisruptionBudgetController::new(store.clone(), None)
581 .tick()
582 .await
583 .unwrap();
584
585 let pdb = store.get(&key).await.unwrap();
586 assert_eq!(status_of(&pdb), (3, 2, 4, 1));
588 }
589
590 #[tokio::test]
591 async fn max_unavailable_one_three_ready_pods() {
592 let store = live_store().await;
593 let key = put_pdb(
594 &store,
595 "ns1",
596 "pdb",
597 json!({"maxUnavailable": 1, "selector": {"matchLabels": {"app": "x"}}}),
598 )
599 .await;
600 for n in ["p1", "p2", "p3"] {
601 put_pod(&store, "ns1", n, json!({"app": "x"}), true).await;
602 }
603
604 PodDisruptionBudgetController::new(store.clone(), None)
605 .tick()
606 .await
607 .unwrap();
608
609 let pdb = store.get(&key).await.unwrap();
610 assert_eq!(status_of(&pdb), (3, 2, 3, 1));
612 }
613
614 #[tokio::test]
615 async fn disruptions_allowed_clamped_to_zero() {
616 let store = live_store().await;
617 let key = put_pdb(
620 &store,
621 "ns1",
622 "pdb",
623 json!({"minAvailable": 3, "selector": {"matchLabels": {"app": "x"}}}),
624 )
625 .await;
626 put_pod(&store, "ns1", "p1", json!({"app": "x"}), true).await;
627 put_pod(&store, "ns1", "p2", json!({"app": "x"}), true).await;
628 put_pod(&store, "ns1", "p3", json!({"app": "x"}), false).await;
629
630 PodDisruptionBudgetController::new(store.clone(), None)
631 .tick()
632 .await
633 .unwrap();
634
635 let pdb = store.get(&key).await.unwrap();
636 assert_eq!(status_of(&pdb), (2, 3, 3, 0));
638 }
639
640 #[tokio::test]
641 async fn unready_pods_do_not_count_toward_current_healthy() {
642 let store = live_store().await;
643 let key = put_pdb(
644 &store,
645 "ns1",
646 "pdb",
647 json!({"minAvailable": 1, "selector": {"matchLabels": {"app": "x"}}}),
648 )
649 .await;
650 put_pod(&store, "ns1", "p1", json!({"app": "x"}), true).await;
652 put_pod(&store, "ns1", "p2", json!({"app": "x"}), false).await;
653 put_pod(&store, "ns1", "p3", json!({"app": "x"}), false).await;
654
655 PodDisruptionBudgetController::new(store.clone(), None)
656 .tick()
657 .await
658 .unwrap();
659
660 let pdb = store.get(&key).await.unwrap();
661 assert_eq!(status_of(&pdb), (1, 1, 3, 0));
663 }
664
665 #[tokio::test]
666 async fn selector_only_counts_matching_pods() {
667 let store = live_store().await;
668 let key = put_pdb(
669 &store,
670 "ns1",
671 "pdb",
672 json!({"minAvailable": 1, "selector": {"matchLabels": {"app": "x"}}}),
673 )
674 .await;
675 put_pod(&store, "ns1", "p1", json!({"app": "x"}), true).await;
677 put_pod(&store, "ns1", "p2", json!({"app": "x"}), true).await;
678 put_pod(&store, "ns1", "other", json!({"app": "y"}), true).await;
679
680 PodDisruptionBudgetController::new(store.clone(), None)
681 .tick()
682 .await
683 .unwrap();
684
685 let pdb = store.get(&key).await.unwrap();
686 assert_eq!(status_of(&pdb), (2, 1, 2, 1));
688 }
689
690 #[tokio::test]
691 async fn re_tick_is_idempotent_no_change() {
692 let store = live_store().await;
693 let key = put_pdb(
694 &store,
695 "ns1",
696 "pdb",
697 json!({"minAvailable": 2, "selector": {"matchLabels": {"app": "x"}}}),
698 )
699 .await;
700 for n in ["p1", "p2", "p3"] {
701 put_pod(&store, "ns1", n, json!({"app": "x"}), true).await;
702 }
703
704 let c = PodDisruptionBudgetController::new(store.clone(), None);
705 let first = c.tick().await.unwrap();
706 assert_eq!(first.objects_changed, 1);
707 let rv_after_first = store.get(&key).await.unwrap()["metadata"]["resourceVersion"].clone();
708
709 let second = c.tick().await.unwrap();
711 assert_eq!(
712 second.objects_changed, 0,
713 "idempotent re-tick writes nothing"
714 );
715 let rv_after_second = store.get(&key).await.unwrap()["metadata"]["resourceVersion"].clone();
716 assert_eq!(
717 rv_after_first, rv_after_second,
718 "no status churn on a steady re-tick"
719 );
720 }
721}