Skip to main content

engenho_controllers/pv_binder/
lifecycle.rs

1//! The volume half of the persistentvolume-controller: a PV whose claim is
2//! gone goes `Released`, and its reclaim policy decides what follows.
3//!
4//! ★ THE DEFECT. The binder only ever looked at claims. Delete a claim and
5//! its PV stayed `Bound` forever to an object that no longer existed, and
6//! its local-path directory stayed on the host with nothing left to say
7//! whose it was — although the seeded default `StorageClass` says `Delete`,
8//! nothing deleted.
9//!
10//! ★ THE SHAPE. Upstream's `syncVolume`, the subset engenho runs:
11//!
12//! ```text
13//!   Bound ──claim gone──▶ Released ──Delete──▶ backing storage removed, PV deleted
14//!                                   ──Retain──▶ stays Released
15//!                                   ──(cannot)─▶ Failed, one VolumeFailedDelete Event
16//!   Released | Failed ──operator clears claimRef (or its uid)──▶ Available
17//! ```
18//!
19//! One step per pass: the write that releases a volume wakes the binder
20//! again, and the reclaim runs on the volume as that write left it.
21//!
22//! ★ "THE CLAIM IS GONE" DESTROYS DATA, SO IT IS NEVER READ OFF A LIST.
23//!
24//!   * A claim is identified by the uid its PV's `claimRef` recorded. Its
25//!     namespace and name alone are not the claim: a claim recreated under
26//!     the same name is a different claim, and the old volume is Released.
27//!   * The tick's claim list only rules the claim alive. When it says the
28//!     claim is gone the store is asked again for that one claim before
29//!     anything is written (upstream re-reads from the apiserver for the
30//!     same reason).
31//!   * A binder scoped to one namespace never judges a volume whose claim
32//!     lives in another: it did not list that namespace's claims.
33//!   * A claim that is Terminating still exists. pvc-protection holds it
34//!     while a pod uses it, and its volume stays Bound until it is gone.
35//!   * Before backing storage is removed the PV is read again; one that
36//!     moved since it was listed waits for the next pass, and the PV delete
37//!     itself is at the revision read.
38//!
39//! ★ WHAT MAY BE DELETED IS A TYPE. The local-path deleter removes a
40//! [`LocalPathDir`], and the only constructor of one derives it from the
41//! uid, namespace and name the claimRef recorded ([`ClaimUid::recorded`],
42//! [`PvName::local_path_dir`]). A PV whose name or `hostPath` is not that
43//! derivation — a legacy `pvc-<ns>-<name>` volume, or a hand-written PV
44//! pointing at `/` — is not this provisioner's to delete: it goes `Failed`
45//! and its directory is left alone. A PV provisioned by a CSI driver is
46//! deleted through that driver when this node serves it; one provisioned
47//! by anything else is left `Released` for its own deleter, as upstream
48//! leaves an external provisioner's volume.
49//!
50//! Tier-honest: the directory being derivable is a type; the checks that
51//! the claim is gone and the volume unmoved are reads, which narrow the
52//! window a concurrent writer has but, as upstream's, cannot close it.
53//! Not run: `Recycle` (deprecated upstream, and it needs a scrubber pod)
54//! goes `Failed`; a claim that exists but is bound to another volume
55//! leaves this one as it is.
56
57use std::fmt;
58
59use engenho_store::{
60    command::{Reason, ResourceCommand},
61    resource::ResourceKey,
62};
63use serde_json::{Value, json};
64use shigoto_types::failure::FailureKind;
65use tracing::debug;
66
67use super::{ClaimUid, ENGENHO_LOCAL_PATH_PROVISIONER, PvBinderController, PvName};
68use crate::effect::Effect;
69use crate::error::ControllerError;
70use crate::meta::ObjectMeta;
71use crate::status::resource_version_of;
72use crate::sweep::ObjectOutcome;
73
74/// The annotation a provisioner signs the PVs it creates with.
75pub(super) const PROVISIONED_BY: &str = "pv.kubernetes.io/provisioned-by";
76
77const RELEASED: &str = "Released";
78const FAILED: &str = "Failed";
79const AVAILABLE: &str = "Available";
80
81/// The report note for a PV whose claim lives outside this binder's scope.
82const OUT_OF_SCOPE: &str = "PV's claim lives in a namespace this binder does not watch; its \
83     lifecycle is left to the binder that does";
84
85/// The report note for a PV whose `claimRef` cannot be read as a claim.
86const UNREADABLE_CLAIM_REF: &str = "PV's spec.claimRef is not an object naming a namespace, a \
87     name and a string uid; nothing is released or reclaimed on an unreadable reference";
88
89/// The report note for a PV that cannot be written at a known revision.
90const NO_REVISION: &str = "PV carries no resourceVersion, so it cannot be written at the \
91     revision it was read at; left for the next pass";
92
93/// The report note for a PV that moved between its listing and its reclaim.
94const VOLUME_MOVED: &str = "PV changed since it was listed; its reclaim waits for the next pass";
95
96/// The report note for a Released PV another provisioner deletes.
97const EXTERNAL_DELETER: &str = "PV was provisioned by a provisioner this node does not run; it \
98     stays Released for that provisioner to delete";
99
100/// A PV's `spec.persistentVolumeReclaimPolicy`.
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub enum ReclaimPolicy {
103    /// Keep the volume, Released, until an operator frees it.
104    Retain,
105    /// Remove the backing storage, then the PV.
106    Delete,
107    /// `Recycle`, or a policy with no meaning: nothing engenho runs.
108    Unsupported,
109}
110
111impl ReclaimPolicy {
112    /// The policy `pv` declares. Absent means `Retain`: the API's default
113    /// for a PV, and the one reading of a missing field that never
114    /// destroys data.
115    #[must_use]
116    pub fn of(pv: &Value) -> Self {
117        match pv
118            .get("spec")
119            .and_then(|s| s.get("persistentVolumeReclaimPolicy"))
120        {
121            None | Some(Value::Null) => Self::Retain,
122            Some(Value::String(p)) if p == "Retain" => Self::Retain,
123            Some(Value::String(p)) if p == "Delete" => Self::Delete,
124            Some(_) => Self::Unsupported,
125        }
126    }
127}
128
129/// Why a Released volume cannot be reclaimed at all. It goes `Failed`
130/// with [`message`](Self::message) as its `status.message`.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum Unreclaimable {
133    /// The reclaim policy is `Recycle`, or no policy engenho knows.
134    UnsupportedPolicy,
135    /// No provisioner signed the PV and engenho knows no deleter for its
136    /// source.
137    NoDeleter,
138    /// Signed by the local-path provisioner, but its name or `hostPath` is
139    /// not the one that provisioner derives from its `claimRef`.
140    ForeignDirectory,
141}
142
143impl Unreclaimable {
144    /// A fixed description: the volume's `status.message`, and the Event's.
145    #[must_use]
146    pub const fn message(self) -> &'static str {
147        match self {
148            Self::UnsupportedPolicy => {
149                "persistentVolumeReclaimPolicy is neither Retain nor Delete; engenho does not \
150                 recycle volumes, so the volume is left for an operator"
151            }
152            Self::NoDeleter => {
153                "no provisioner signed this volume and engenho has no deleter for its source; \
154                 the backing storage is left for an operator"
155            }
156            Self::ForeignDirectory => {
157                "the volume's name or hostPath is not the directory the local-path provisioner \
158                 derives from its claimRef, so it is not the provisioner's to delete"
159            }
160        }
161    }
162}
163
164impl fmt::Display for Unreclaimable {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        f.write_str(self.message())
167    }
168}
169
170/// Why a Released volume was not reclaimed this pass.
171#[derive(Debug, thiserror::Error)]
172pub enum ReclaimError {
173    /// It cannot be reclaimed at all; it has gone `Failed`.
174    #[error("{0}")]
175    Unreclaimable(Unreclaimable),
176    /// Removing its local-path directory failed.
177    #[error("removing the local-path directory failed: {0}")]
178    RemoveDir(#[source] std::io::Error),
179    /// The CSI driver refused `DeleteVolume`.
180    #[error("CSI DeleteVolume through {driver} failed: {reason}")]
181    CsiDelete { driver: String, reason: String },
182}
183
184impl ReclaimError {
185    /// Its retry class, by variant: a volume that cannot be reclaimed stays
186    /// that way until it is edited; a deleter that failed may not next time.
187    #[must_use]
188    pub const fn class(&self) -> FailureKind {
189        match self {
190            Self::Unreclaimable(_) => FailureKind::Declarative,
191            Self::RemoveDir(_) | Self::CsiDelete { .. } => FailureKind::Transient,
192        }
193    }
194}
195
196/// Where a PV's `claimRef` points, read from the volume's side.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198enum Holder<'v> {
199    /// No claimRef, or one without a uid: reserved by name at most, bound
200    /// to no claim object.
201    Nobody,
202    /// The claim the volume was bound to.
203    Claim(RecordedClaim<'v>),
204    /// A claimRef that does not read as a claim. Nothing is done on it.
205    Unreadable,
206}
207
208/// A claim as a PV's `claimRef` recorded it.
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210struct RecordedClaim<'v> {
211    namespace: &'v str,
212    name: &'v str,
213    uid: &'v str,
214}
215
216impl<'v> Holder<'v> {
217    fn of(pv: &'v Value) -> Self {
218        let claim_ref = match pv.get("spec").and_then(|s| s.get("claimRef")) {
219            None | Some(Value::Null) => return Self::Nobody,
220            Some(Value::Object(claim_ref)) => claim_ref,
221            Some(_) => return Self::Unreadable,
222        };
223        let uid = match claim_ref.get("uid") {
224            None | Some(Value::Null) => return Self::Nobody,
225            Some(Value::String(uid)) if uid.is_empty() => return Self::Nobody,
226            Some(Value::String(uid)) => uid.as_str(),
227            Some(_) => return Self::Unreadable,
228        };
229        let field = |k: &str| {
230            claim_ref
231                .get(k)
232                .and_then(Value::as_str)
233                .filter(|s| !s.is_empty())
234        };
235        match (field("namespace"), field("name")) {
236            (Some(namespace), Some(name)) => Self::Claim(RecordedClaim {
237                namespace,
238                name,
239                uid,
240            }),
241            _ => Self::Unreadable,
242        }
243    }
244}
245
246/// Is the recorded claim among `claims`, with its uid?
247fn listed_alive(claims: &[(ResourceKey, Value)], claim: &RecordedClaim<'_>) -> bool {
248    claims.iter().any(|(key, value)| {
249        key.namespace.as_deref() == Some(claim.namespace)
250            && key.name == claim.name
251            && value.uid() == Some(claim.uid)
252    })
253}
254
255/// What removing a volume's backing storage came to.
256enum Removal {
257    /// Removed (or already absent): the PV can go.
258    Removed,
259    /// Another provisioner's: left for it.
260    External,
261    /// Not removable by anyone engenho knows of.
262    Unreclaimable(Unreclaimable),
263}
264
265/// The phases this module writes without a message.
266#[derive(Debug, Clone, Copy)]
267enum Phase {
268    Available,
269    Released,
270}
271
272impl Phase {
273    const fn as_str(self) -> &'static str {
274        match self {
275            Self::Available => AVAILABLE,
276            Self::Released => RELEASED,
277        }
278    }
279}
280
281impl PvBinderController {
282    /// One step of `pv`'s lifecycle against the claims listed this tick.
283    pub(super) async fn reconcile_volume(
284        &self,
285        pv_key: &ResourceKey,
286        pv: &Value,
287        claims: &[(ResourceKey, Value)],
288    ) -> Result<ObjectOutcome, ControllerError> {
289        let released = matches!(Self::pv_phase(pv), RELEASED | FAILED);
290        let claim = match Holder::of(pv) {
291            // An operator freed a Released volume (upstream's manual
292            // reclaim): it is available again, to the claim it still names
293            // if it names one.
294            Holder::Nobody if released => {
295                return self.set_phase(pv_key, pv, Phase::Available).await;
296            }
297            Holder::Nobody => return Ok(ObjectOutcome::Unchanged),
298            Holder::Unreadable => return Ok(ObjectOutcome::skipped_because(UNREADABLE_CLAIM_REF)),
299            Holder::Claim(claim) => claim,
300        };
301        if self
302            .namespace
303            .as_deref()
304            .is_some_and(|scope| scope != claim.namespace)
305        {
306            return Ok(ObjectOutcome::skipped_because(OUT_OF_SCOPE));
307        }
308        if listed_alive(claims, &claim) || self.claim_exists(&claim).await {
309            return Ok(ObjectOutcome::Unchanged);
310        }
311        if !released {
312            debug!(pv = %pv_key.name, claim = claim.name, "claim is gone; volume released");
313            return self.set_phase(pv_key, pv, Phase::Released).await;
314        }
315        match ReclaimPolicy::of(pv) {
316            ReclaimPolicy::Retain => Ok(ObjectOutcome::Unchanged),
317            ReclaimPolicy::Delete => self.delete_volume(pv_key, pv, &claim).await,
318            ReclaimPolicy::Unsupported => {
319                self.fail(pv_key, pv, Unreclaimable::UnsupportedPolicy)
320                    .await
321            }
322        }
323    }
324
325    /// Ask the store itself whether the recorded claim exists. The tick's
326    /// list said it does not; that list is not allowed to be the reason a
327    /// volume is released.
328    async fn claim_exists(&self, claim: &RecordedClaim<'_>) -> bool {
329        let key = ResourceKey::namespaced(
330            "",
331            "v1",
332            "PersistentVolumeClaim",
333            claim.namespace,
334            claim.name,
335        );
336        self.store
337            .get(&key)
338            .await
339            .is_some_and(|live| live.uid() == Some(claim.uid))
340    }
341
342    /// Remove a Released volume under `Delete`: its backing storage first,
343    /// then the PV, at the revision it was listed at.
344    async fn delete_volume(
345        &self,
346        pv_key: &ResourceKey,
347        pv: &Value,
348        claim: &RecordedClaim<'_>,
349    ) -> Result<ObjectOutcome, ControllerError> {
350        let Some(revision) = resource_version_of(pv) else {
351            return Ok(ObjectOutcome::skipped_because(NO_REVISION));
352        };
353        let live = self.store.get(pv_key).await;
354        if live.as_ref().and_then(resource_version_of) != Some(revision) {
355            return Ok(ObjectOutcome::skipped_because(VOLUME_MOVED));
356        }
357        match self.remove_backing(pv_key, pv, claim).await? {
358            Removal::External => Ok(ObjectOutcome::skipped_because(EXTERNAL_DELETER)),
359            Removal::Unreclaimable(why) => self.fail(pv_key, pv, why).await,
360            Removal::Removed => {
361                debug!(pv = %pv_key.name, "backing storage removed; deleting the volume");
362                let applied = self
363                    .store
364                    .propose(ResourceCommand::delete_at(
365                        pv_key.clone(),
366                        Some(revision),
367                        Reason::Controller,
368                        Some(engenho_types::time::now_rfc3339_utc()),
369                    ))
370                    .await?;
371                Ok(ObjectOutcome::from(Effect::of(applied.op)))
372            }
373        }
374    }
375
376    /// Remove the storage behind `pv`, through the deleter its provisioner
377    /// names (upstream's `findDeletablePlugin`).
378    async fn remove_backing(
379        &self,
380        pv_key: &ResourceKey,
381        pv: &Value,
382        claim: &RecordedClaim<'_>,
383    ) -> Result<Removal, ReclaimError> {
384        let provisioner = pv
385            .get("metadata")
386            .and_then(|m| m.get("annotations"))
387            .and_then(|a| a.get(PROVISIONED_BY))
388            .and_then(Value::as_str);
389        let spec = pv.get("spec");
390        match provisioner {
391            None => Ok(Removal::Unreclaimable(Unreclaimable::NoDeleter)),
392            Some(ENGENHO_LOCAL_PATH_PROVISIONER) => {
393                let host_path = spec
394                    .and_then(|s| s.get("hostPath"))
395                    .and_then(|h| h.get("path"))
396                    .and_then(Value::as_str);
397                let Ok(uid) = ClaimUid::recorded(claim.uid) else {
398                    return Ok(Removal::Unreclaimable(Unreclaimable::ForeignDirectory));
399                };
400                let volume = PvName::for_claim(&uid);
401                let Ok(dir) =
402                    volume.local_path_dir(&self.local_path_root, claim.namespace, claim.name)
403                else {
404                    return Ok(Removal::Unreclaimable(Unreclaimable::ForeignDirectory));
405                };
406                if !volume.names(&pv_key.name) || host_path != Some(dir.to_string().as_str()) {
407                    return Ok(Removal::Unreclaimable(Unreclaimable::ForeignDirectory));
408                }
409                self.env.remove_dir(&dir).map_err(ReclaimError::RemoveDir)?;
410                Ok(Removal::Removed)
411            }
412            Some(provisioner) => {
413                let csi = spec.and_then(|s| s.get("csi"));
414                let driver = csi.and_then(|c| c.get("driver")).and_then(Value::as_str);
415                let handle = csi
416                    .and_then(|c| c.get("volumeHandle"))
417                    .and_then(Value::as_str);
418                match (driver, handle) {
419                    (Some(driver), Some(handle))
420                        if driver == provisioner && self.csi.can_provision(driver).await =>
421                    {
422                        self.csi
423                            .delete_volume(driver, handle)
424                            .await
425                            .map_err(|reason| ReclaimError::CsiDelete {
426                                driver: driver.to_owned(),
427                                reason,
428                            })?;
429                        Ok(Removal::Removed)
430                    }
431                    _ => Ok(Removal::External),
432                }
433            }
434        }
435    }
436
437    /// Write `phase` at the revision `pv` was read at, clearing any message
438    /// a `Failed` left.
439    async fn set_phase(
440        &self,
441        pv_key: &ResourceKey,
442        pv: &Value,
443        phase: Phase,
444    ) -> Result<ObjectOutcome, ControllerError> {
445        let patch = json!({ "status": { "phase": phase.as_str(), "message": null } });
446        self.patch_status(pv_key, pv, patch).await
447    }
448
449    /// Mark `pv` Failed with `why` as its message. The pass that writes it
450    /// reports the failure, so the sweep puts one `VolumeFailedDelete`
451    /// Event on the volume; a volume already Failed for the same reason is
452    /// converged, and says nothing more.
453    async fn fail(
454        &self,
455        pv_key: &ResourceKey,
456        pv: &Value,
457        why: Unreclaimable,
458    ) -> Result<ObjectOutcome, ControllerError> {
459        let status = pv.get("status");
460        let already = status.and_then(|s| s.get("phase")).and_then(Value::as_str) == Some(FAILED)
461            && status
462                .and_then(|s| s.get("message"))
463                .and_then(Value::as_str)
464                == Some(why.message());
465        if already {
466            return Ok(ObjectOutcome::Unchanged);
467        }
468        let patch = json!({ "status": { "phase": FAILED, "message": why.message() } });
469        match self.patch_status(pv_key, pv, patch).await? {
470            ObjectOutcome::Changed(_) => Err(ReclaimError::Unreclaimable(why).into()),
471            other => Ok(other),
472        }
473    }
474
475    async fn patch_status(
476        &self,
477        pv_key: &ResourceKey,
478        pv: &Value,
479        patch: Value,
480    ) -> Result<ObjectOutcome, ControllerError> {
481        let Some(revision) = resource_version_of(pv) else {
482            return Ok(ObjectOutcome::skipped_because(NO_REVISION));
483        };
484        let applied = self
485            .store
486            .propose(ResourceCommand::patch_cas(
487                pv_key.clone(),
488                patch,
489                Some(revision),
490                Reason::Controller,
491            ))
492            .await?;
493        Ok(ObjectOutcome::from(Effect::of(applied.op)))
494    }
495}
496
497#[cfg(test)]
498mod tests {
499    use super::*;
500
501    #[test]
502    fn an_absent_policy_retains_and_only_delete_deletes() {
503        let pv = |p: Value| json!({"spec": {"persistentVolumeReclaimPolicy": p}});
504        assert_eq!(ReclaimPolicy::of(&json!({})), ReclaimPolicy::Retain);
505        assert_eq!(ReclaimPolicy::of(&pv(Value::Null)), ReclaimPolicy::Retain);
506        assert_eq!(
507            ReclaimPolicy::of(&pv(json!("Retain"))),
508            ReclaimPolicy::Retain
509        );
510        assert_eq!(
511            ReclaimPolicy::of(&pv(json!("Delete"))),
512            ReclaimPolicy::Delete
513        );
514        for other in [json!("Recycle"), json!("delete"), json!(""), json!(1)] {
515            assert_eq!(
516                ReclaimPolicy::of(&pv(other.clone())),
517                ReclaimPolicy::Unsupported,
518                "{other}"
519            );
520        }
521    }
522
523    #[test]
524    fn a_claim_ref_is_a_claim_only_with_a_uid_namespace_and_name() {
525        let pv = |cr: Value| json!({"spec": {"claimRef": cr}});
526        assert_eq!(Holder::of(&json!({"spec": {}})), Holder::Nobody);
527        assert_eq!(Holder::of(&pv(Value::Null)), Holder::Nobody);
528        assert_eq!(
529            Holder::of(&pv(json!({"namespace": "ns1", "name": "data"}))),
530            Holder::Nobody,
531            "reserved by name is bound to no claim object"
532        );
533        assert_eq!(
534            Holder::of(&pv(json!({"namespace": "ns1", "name": "data", "uid": ""}))),
535            Holder::Nobody
536        );
537        assert_eq!(
538            Holder::of(&pv(
539                json!({"namespace": "ns1", "name": "data", "uid": "u-1"})
540            )),
541            Holder::Claim(RecordedClaim {
542                namespace: "ns1",
543                name: "data",
544                uid: "u-1"
545            })
546        );
547        for unreadable in [
548            json!("ns1/data"),
549            json!({"namespace": "ns1", "name": "data", "uid": 7}),
550            json!({"name": "data", "uid": "u-1"}),
551            json!({"namespace": "ns1", "name": "", "uid": "u-1"}),
552        ] {
553            assert_eq!(
554                Holder::of(&pv(unreadable.clone())),
555                Holder::Unreadable,
556                "{unreadable}"
557            );
558        }
559    }
560}