1use std::sync::Arc;
47
48use async_trait::async_trait;
49use engenho_store::{
50 StoreMesh,
51 command::{Reason, ResourceCommand},
52 resource::ResourceKey,
53};
54use serde_json::{Value, json};
55use tracing::debug;
56
57use crate::controller::{Controller, ReconcileOutcome};
58use crate::effect::Effect;
59use crate::error::ControllerError;
60use crate::event_recorder::Reason as EventReason;
61use crate::meta::{ObjectMeta, array_mut};
62use crate::owner::is_owned_by;
63use crate::reads::{DeclaresReads, Reads, gvk};
64use crate::status::resource_version_of;
65use crate::sweep::{ObjectOutcome, Sweep, impl_sweep_event_sink};
66
67pub const PVC_PROTECTION_FINALIZER: &str = "kubernetes.io/pvc-protection";
69
70const COMPONENT: &str = "pvc-protection-controller";
72
73const FINALIZERS: &[&str] = &["metadata", "finalizers"];
75
76const IN_USE: &str = "PVC is Terminating and a scheduled pod still uses it; the pvc-protection \
78 finalizer holds it until no pod does";
79
80const NO_REVISION: &str = "PVC carries no resourceVersion, so its finalizers cannot be written at \
83 the revision it was read at; left for the next pass";
84
85const NO_NAMESPACE: &str = "PVC has no namespace, so no pod can be asked whether it uses it; \
87 left as it is";
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92enum Protection {
93 Protect,
95 ReleaseWhenUnused,
98 Settled,
100}
101
102impl Protection {
103 fn of(claim: &Value) -> Self {
104 match (
105 claim.is_terminating(),
106 claim.has_finalizer(PVC_PROTECTION_FINALIZER),
107 ) {
108 (false, false) => Self::Protect,
109 (true, true) => Self::ReleaseWhenUnused,
110 (false, true) | (true, false) => Self::Settled,
111 }
112 }
113}
114
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117enum FinalizerEdit {
118 Add,
119 Remove,
120}
121
122fn pod_uses_claim(pod: &Value, claim_name: &str, claim: &Value) -> bool {
127 let spec = pod.get("spec");
128 let scheduled = spec
129 .and_then(|s| s.get("nodeName"))
130 .and_then(Value::as_str)
131 .is_some_and(|node| !node.is_empty());
132 if !scheduled {
133 return false;
134 }
135 let Some(volumes) = spec
136 .and_then(|s| s.get("volumes"))
137 .and_then(Value::as_array)
138 else {
139 return false;
140 };
141 volumes.iter().any(|volume| {
142 names_claim(volume, claim_name)
143 || (!is_shut_down(pod) && ephemeral_claim_is(pod, volume, claim_name, claim))
144 })
145}
146
147fn names_claim(volume: &Value, claim_name: &str) -> bool {
149 volume
150 .get("persistentVolumeClaim")
151 .and_then(|p| p.get("claimName"))
152 .and_then(Value::as_str)
153 == Some(claim_name)
154}
155
156fn ephemeral_claim_is(pod: &Value, volume: &Value, claim_name: &str, claim: &Value) -> bool {
161 if volume.get("ephemeral").is_none_or(Value::is_null) {
162 return false;
163 }
164 let (Some(pod_name), Some(volume_name)) =
165 (pod.name(), volume.get("name").and_then(Value::as_str))
166 else {
167 return false;
168 };
169 let named = claim_name
170 .strip_prefix(pod_name)
171 .and_then(|rest| rest.strip_prefix('-'))
172 == Some(volume_name);
173 named && pod.uid().is_some_and(|uid| is_owned_by(claim, uid))
174}
175
176fn is_shut_down(pod: &Value) -> bool {
180 pod.is_terminating()
181 && pod
182 .get("metadata")
183 .and_then(|m| m.get("deletionGracePeriodSeconds"))
184 .and_then(Value::as_i64)
185 == Some(0)
186}
187
188fn in_use(pods: &[(ResourceKey, Value)], namespace: &str, claim_name: &str, claim: &Value) -> bool {
190 pods.iter()
191 .filter(|(key, _)| key.namespace.as_deref() == Some(namespace))
192 .any(|(_, pod)| pod_uses_claim(pod, claim_name, claim))
193}
194
195pub struct PvcProtectionController {
197 store: Arc<StoreMesh>,
198 namespace: Option<String>,
199 sweep: Sweep,
201}
202
203impl_sweep_event_sink!(PvcProtectionController);
204
205impl PvcProtectionController {
206 #[must_use]
209 pub fn new(store: Arc<StoreMesh>, namespace: Option<String>) -> Self {
210 Self {
211 store,
212 namespace,
213 sweep: Sweep::new(COMPONENT, EventReason::FailedUpdate),
214 }
215 }
216
217 async fn reconcile_claim(
219 &self,
220 key: &ResourceKey,
221 claim: &Value,
222 pods: &[(ResourceKey, Value)],
223 ) -> Result<ObjectOutcome, ControllerError> {
224 match Protection::of(claim) {
225 Protection::Settled => Ok(ObjectOutcome::Unchanged),
226 Protection::Protect => self.edit_finalizers(key, claim, FinalizerEdit::Add).await,
227 Protection::ReleaseWhenUnused => {
228 let Some(namespace) = key.namespace.as_deref() else {
229 return Ok(ObjectOutcome::skipped_because(NO_NAMESPACE));
230 };
231 if in_use(pods, namespace, &key.name, claim) {
232 return Ok(ObjectOutcome::skipped_because(IN_USE));
233 }
234 let fresh = self.store.list("", "v1", "Pod", Some(namespace)).await;
237 if in_use(&fresh, namespace, &key.name, claim) {
238 return Ok(ObjectOutcome::skipped_because(IN_USE));
239 }
240 debug!(pvc = %key.label(), "no pod uses the claim; releasing pvc-protection");
241 self.edit_finalizers(key, claim, FinalizerEdit::Remove)
242 .await
243 }
244 }
245 }
246
247 async fn edit_finalizers(
250 &self,
251 key: &ResourceKey,
252 claim: &Value,
253 edit: FinalizerEdit,
254 ) -> Result<ObjectOutcome, ControllerError> {
255 let Some(revision) = resource_version_of(claim) else {
256 return Ok(ObjectOutcome::skipped_because(NO_REVISION));
257 };
258 let mut edited = claim.clone();
259 let finalizers = array_mut(&mut edited, FINALIZERS)?;
260 match edit {
261 FinalizerEdit::Add => finalizers.push(Value::from(PVC_PROTECTION_FINALIZER)),
262 FinalizerEdit::Remove => {
263 finalizers.retain(|f| f.as_str() != Some(PVC_PROTECTION_FINALIZER));
264 }
265 }
266 let patch = json!({ "metadata": { "finalizers": std::mem::take(finalizers) } });
267 let applied = self
268 .store
269 .propose(ResourceCommand::patch_cas(
270 key.clone(),
271 patch,
272 Some(revision),
273 Reason::Controller,
274 ))
275 .await?;
276 Ok(ObjectOutcome::from(Effect::of(applied.op)))
277 }
278}
279
280impl DeclaresReads for PvcProtectionController {
283 fn reads(&self) -> Reads {
284 Reads::of(&[gvk("", "v1", "PersistentVolumeClaim"), gvk("", "v1", "Pod")])
285 }
286}
287
288#[async_trait]
289impl Controller for PvcProtectionController {
290 fn name(&self) -> &'static str {
291 "pvc-protection"
292 }
293
294 async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
295 let namespace = self.namespace.as_deref();
296 let claims = self
297 .store
298 .list("", "v1", "PersistentVolumeClaim", namespace)
299 .await;
300 let pods = if claims
303 .iter()
304 .any(|(_, c)| Protection::of(c) == Protection::ReleaseWhenUnused)
305 {
306 self.store.list("", "v1", "Pod", namespace).await
307 } else {
308 Vec::new()
309 };
310 let (this, pods) = (self, &pods);
311 let report = self
312 .sweep
313 .run(&claims, |key, claim| async move {
314 ObjectOutcome::settle(this.reconcile_claim(key, claim, pods).await)
315 })
316 .await?;
317 Ok(report.into())
318 }
319}
320
321#[cfg(test)]
322mod tests {
323 use super::*;
324 use std::time::Duration;
325
326 async fn live_store() -> Arc<StoreMesh> {
327 use engenho_store::{InProcessRouter, default_config};
328 let router = InProcessRouter::new();
329 let cfg = default_config("controllers-pvc-protection").unwrap();
330 let store = Arc::new(
331 StoreMesh::start(1, "in-process://1".into(), router, cfg)
332 .await
333 .unwrap(),
334 );
335 store.initialize_singleton().await.unwrap();
336 assert!(store.wait_for_leadership(Duration::from_secs(3)).await);
337 store
338 }
339
340 fn claim_key(ns: &str, name: &str) -> ResourceKey {
341 ResourceKey::namespaced("", "v1", "PersistentVolumeClaim", ns, name)
342 }
343
344 fn pod_key(ns: &str, name: &str) -> ResourceKey {
345 ResourceKey::namespaced("", "v1", "Pod", ns, name)
346 }
347
348 async fn put(store: &StoreMesh, key: ResourceKey, value: Value) {
349 store
350 .propose(ResourceCommand::put(key, value, Reason::Operator))
351 .await
352 .unwrap();
353 }
354
355 async fn delete(store: &StoreMesh, key: ResourceKey) {
356 store
357 .propose(ResourceCommand::delete(key, Reason::Operator))
358 .await
359 .unwrap();
360 }
361
362 async fn put_claim(store: &StoreMesh, ns: &str, name: &str, finalizers: Value) {
363 put(
364 store,
365 claim_key(ns, name),
366 json!({"apiVersion": "v1", "kind": "PersistentVolumeClaim",
367 "metadata": {"name": name, "namespace": ns, "uid": (["uid-", name].concat()),
368 "finalizers": finalizers},
369 "spec": {"accessModes": ["ReadWriteOnce"],
370 "resources": {"requests": {"storage": "1Gi"}}}}),
371 )
372 .await;
373 }
374
375 fn pod_mounting(ns: &str, name: &str, claim: &str, node: Option<&str>) -> Value {
377 let mut spec = json!({"volumes": [
378 {"name": "data", "persistentVolumeClaim": {"claimName": claim}}
379 ]});
380 if let Some(node) = node {
381 spec["nodeName"] = json!(node);
382 }
383 json!({"apiVersion": "v1", "kind": "Pod",
384 "metadata": {"name": name, "namespace": ns, "uid": (["uid-", name].concat())},
385 "spec": spec})
386 }
387
388 fn controller(store: &Arc<StoreMesh>) -> PvcProtectionController {
389 PvcProtectionController::new(store.clone(), None)
390 }
391
392 async fn finalizers(store: &StoreMesh, ns: &str, name: &str) -> Option<Value> {
393 store
394 .get(&claim_key(ns, name))
395 .await
396 .map(|c| c["metadata"]["finalizers"].clone())
397 }
398
399 #[test]
402 fn protection_follows_deletion_state_and_the_finalizer() {
403 let claim = |ts: Option<&str>, fin: Value| json!({"metadata": {"deletionTimestamp": ts, "finalizers": fin}});
404 let ts = Some("2026-09-19T00:00:00Z");
405 assert_eq!(Protection::of(&claim(None, json!([]))), Protection::Protect);
406 assert_eq!(
407 Protection::of(&claim(None, json!(["example.com/x"]))),
408 Protection::Protect
409 );
410 assert_eq!(
411 Protection::of(&claim(None, json!([PVC_PROTECTION_FINALIZER]))),
412 Protection::Settled
413 );
414 assert_eq!(
415 Protection::of(&claim(ts, json!([PVC_PROTECTION_FINALIZER]))),
416 Protection::ReleaseWhenUnused
417 );
418 assert_eq!(
419 Protection::of(&claim(ts, json!(["example.com/x"]))),
420 Protection::Settled,
421 "a deletion that has started is never protected after the fact"
422 );
423 }
424
425 #[test]
426 fn only_a_scheduled_pod_naming_the_claim_uses_it() {
427 let claim = json!({"metadata": {"name": "data"}});
428 let scheduled = pod_mounting("ns1", "web", "data", Some("node-a"));
429 assert!(pod_uses_claim(&scheduled, "data", &claim));
430 assert!(!pod_uses_claim(&scheduled, "other", &claim));
431 let unscheduled = pod_mounting("ns1", "web", "data", None);
432 assert!(!pod_uses_claim(&unscheduled, "data", &claim));
433 let mut empty_node = scheduled.clone();
434 empty_node["spec"]["nodeName"] = json!("");
435 assert!(!pod_uses_claim(&empty_node, "data", &claim));
436 let mut completed = scheduled;
438 completed["status"] = json!({"phase": "Succeeded"});
439 assert!(pod_uses_claim(&completed, "data", &claim));
440 }
441
442 #[test]
443 fn an_ephemeral_claim_is_used_only_by_the_pod_that_controls_it() {
444 let pod = json!({"metadata": {"name": "web", "uid": "uid-web"},
445 "spec": {"nodeName": "node-a",
446 "volumes": [{"name": "scratch", "ephemeral": {
447 "volumeClaimTemplate": {"spec": {}}}}]}});
448 let owned = json!({"metadata": {"name": "web-scratch", "ownerReferences": [
449 {"apiVersion": "v1", "kind": "Pod", "name": "web", "uid": "uid-web",
450 "controller": true}]}});
451 let foreign = json!({"metadata": {"name": "web-scratch", "ownerReferences": [
452 {"apiVersion": "v1", "kind": "Pod", "name": "web", "uid": "uid-other",
453 "controller": true}]}});
454 assert!(pod_uses_claim(&pod, "web-scratch", &owned));
455 assert!(
456 !pod_uses_claim(&pod, "web-scratch", &foreign),
457 "a claim of the same name the pod does not control is not its"
458 );
459 assert!(!pod_uses_claim(&pod, "web-other", &owned));
460
461 let mut shut_down = pod.clone();
462 shut_down["metadata"]["deletionTimestamp"] = json!("2026-09-19T00:00:00Z");
463 shut_down["metadata"]["deletionGracePeriodSeconds"] = json!(0);
464 assert!(
465 !pod_uses_claim(&shut_down, "web-scratch", &owned),
466 "a pod the kubelet is done with no longer holds its ephemeral claim"
467 );
468 let mut terminating = pod;
469 terminating["metadata"]["deletionTimestamp"] = json!("2026-09-19T00:00:00Z");
470 terminating["metadata"]["deletionGracePeriodSeconds"] = json!(30);
471 assert!(pod_uses_claim(&terminating, "web-scratch", &owned));
472 }
473
474 #[tokio::test]
478 async fn a_live_claim_gains_the_finalizer_beside_its_own() {
479 let store = live_store().await;
480 put_claim(&store, "ns1", "bare", Value::Null).await;
481 put_claim(&store, "ns1", "held", json!(["example.com/hold"])).await;
482
483 let outcome = controller(&store).tick().await.unwrap();
484
485 assert_eq!(
486 finalizers(&store, "ns1", "bare").await,
487 Some(json!([PVC_PROTECTION_FINALIZER]))
488 );
489 assert_eq!(
490 finalizers(&store, "ns1", "held").await,
491 Some(json!(["example.com/hold", PVC_PROTECTION_FINALIZER]))
492 );
493 assert_eq!(outcome.sweep.unwrap().changed(), 2);
494
495 let again = controller(&store).tick().await.unwrap();
496 let sweep = again.sweep.unwrap();
497 assert_eq!(
498 (sweep.changed(), sweep.unchanged()),
499 (0, 2),
500 "a protected claim is left alone"
501 );
502 }
503
504 #[tokio::test]
507 async fn a_claim_in_use_outlives_its_delete_until_the_pod_is_gone() {
508 let store = live_store().await;
509 put_claim(&store, "ns1", "data", Value::Null).await;
510 put(
511 &store,
512 pod_key("ns1", "web"),
513 pod_mounting("ns1", "web", "data", Some("node-a")),
514 )
515 .await;
516 let c = controller(&store);
517 c.tick().await.unwrap();
518
519 delete(&store, claim_key("ns1", "data")).await;
520 let held = c.tick().await.unwrap();
521
522 let claim = store
523 .get(&claim_key("ns1", "data"))
524 .await
525 .expect("a claim in use survives its delete");
526 assert!(claim.is_terminating());
527 assert!(claim.has_finalizer(PVC_PROTECTION_FINALIZER));
528 assert_eq!(held.sweep.unwrap().note(), Some(IN_USE));
529
530 delete(&store, pod_key("ns1", "web")).await;
531 c.tick().await.unwrap();
532
533 assert!(
534 store.get(&claim_key("ns1", "data")).await.is_none(),
535 "the claim goes once no pod uses it"
536 );
537 }
538
539 #[tokio::test]
541 async fn an_unscheduled_or_foreign_pod_does_not_hold_the_claim() {
542 let store = live_store().await;
543 put_claim(&store, "ns1", "data", json!([PVC_PROTECTION_FINALIZER])).await;
544 put(
545 &store,
546 pod_key("ns1", "pending"),
547 pod_mounting("ns1", "pending", "data", None),
548 )
549 .await;
550 put(
551 &store,
552 pod_key("ns2", "elsewhere"),
553 pod_mounting("ns2", "elsewhere", "data", Some("node-a")),
554 )
555 .await;
556 delete(&store, claim_key("ns1", "data")).await;
557 assert!(store.get(&claim_key("ns1", "data")).await.is_some());
558
559 controller(&store).tick().await.unwrap();
560
561 assert!(store.get(&claim_key("ns1", "data")).await.is_none());
562 }
563
564 #[tokio::test]
567 async fn release_keeps_every_other_finalizer() {
568 let store = live_store().await;
569 put_claim(
570 &store,
571 "ns1",
572 "data",
573 json!(["example.com/hold", PVC_PROTECTION_FINALIZER]),
574 )
575 .await;
576 delete(&store, claim_key("ns1", "data")).await;
577
578 controller(&store).tick().await.unwrap();
579
580 let claim = store.get(&claim_key("ns1", "data")).await.unwrap();
581 assert!(claim.is_terminating());
582 assert_eq!(claim["metadata"]["finalizers"], json!(["example.com/hold"]));
583 }
584
585 #[tokio::test]
588 async fn a_terminating_claim_is_never_given_the_finalizer() {
589 let store = live_store().await;
590 put_claim(&store, "ns1", "data", json!(["example.com/hold"])).await;
591 put(
592 &store,
593 pod_key("ns1", "web"),
594 pod_mounting("ns1", "web", "data", Some("node-a")),
595 )
596 .await;
597 delete(&store, claim_key("ns1", "data")).await;
598
599 controller(&store).tick().await.unwrap();
600
601 assert_eq!(
602 finalizers(&store, "ns1", "data").await,
603 Some(json!(["example.com/hold"]))
604 );
605 }
606
607 #[tokio::test]
610 async fn a_stale_claim_is_not_written() {
611 let store = live_store().await;
612 put_claim(&store, "ns1", "data", Value::Null).await;
613 let stale = store.get(&claim_key("ns1", "data")).await.unwrap();
614 put_claim(&store, "ns1", "data", json!(["example.com/late"])).await;
615
616 let outcome = controller(&store)
617 .edit_finalizers(&claim_key("ns1", "data"), &stale, FinalizerEdit::Add)
618 .await
619 .unwrap();
620
621 assert!(
622 matches!(outcome, ObjectOutcome::Skipped { .. }),
623 "{outcome:?}"
624 );
625 assert_eq!(
626 finalizers(&store, "ns1", "data").await,
627 Some(json!(["example.com/late"]))
628 );
629 }
630}