Skip to main content

engenho_controllers/
volume_snapshot.rs

1//! `VolumeSnapshotController` — snapshot and restore for local-path volumes.
2//!
3//! ## Why this exists
4//!
5//! `snapshot.storage.k8s.io/v1` is not part of Kubernetes proper: upstream
6//! ships it as CRDs plus the external-snapshotter controller, and every CSI
7//! driver implements the actual copy. engenho serves CRDs and owns a
8//! local-path provisioner ([`crate::pv_binder`]), so the honest local
9//! implementation is to own the snapshot half of that same provisioner rather
10//! than to pretend a CSI driver is present.
11//!
12//! The concrete driver: a PITR drill is snapshot → restore → verify, and the
13//! restore vector on a real cluster is a CSI `VolumeSnapshot`. Without this,
14//! that whole shape is unrunnable here and the drill logic can only ever be
15//! exercised against a cloud.
16//!
17//! ## What it does, each tick
18//!
19//! For every `VolumeSnapshot` not yet `status.readyToUse`:
20//!
21//!   1. Resolve `spec.source.persistentVolumeClaimName` → the PVC in the same
22//!      namespace → its bound PV → that PV's `hostPath.path`.
23//!   2. Copy that directory to `<snapshot_root>/<ns>-<name>`.
24//!   3. Create the `VolumeSnapshotContent` describing it.
25//!   4. Stamp `status` — `readyToUse`, `boundVolumeSnapshotContentName`,
26//!      `creationTime`, `restoreSize`.
27//!
28//! ## What it deliberately does NOT do
29//!
30//! **It does not quiesce.** The copy is of a live directory, so a writer
31//! mid-write yields a torn file exactly as an un-quiesced disk snapshot does.
32//! That is stated rather than hidden: a caller who needs consistency stops the
33//! workload first (the same discipline camelot's real drill uses, where MySQL
34//! is scaled to 0 so the volume is cold). Claiming crash-consistency we do not
35//! implement would be the worse failure.
36//!
37//! **It snapshots ONLY local-path volumes.** A PV with no `hostPath` is
38//! skipped with a typed note, never reported ready — a snapshot that claims
39//! success while copying nothing is precisely the "ten clean receipts, real
40//! residue underneath" failure the PITR programme already recorded once.
41//!
42//! ## The filesystem seam
43//!
44//! Every host effect sits behind [`SnapshotEnv`], so the controller is
45//! unit-testable without touching a disk ([`FakeSnapshotEnv`]).
46
47use std::sync::Arc;
48
49use async_trait::async_trait;
50use engenho_store::{
51    StoreMesh,
52    command::{Reason, ResourceCommand},
53    resource::ResourceKey,
54};
55use serde_json::{Value, json};
56
57use crate::controller::{Controller, ReconcileOutcome, ReconcileReport};
58use crate::effect::Effect;
59use crate::error::ControllerError;
60use crate::reads::{DeclaresReads, Reads, gvk};
61
62/// The snapshot API group.
63pub const SNAPSHOT_GROUP: &str = "snapshot.storage.k8s.io";
64/// The served version.
65pub const SNAPSHOT_VERSION: &str = "v1";
66/// The driver name stamped into a `VolumeSnapshotContent`, matching the
67/// provisioner that owns the underlying directory.
68pub const SNAPSHOT_DRIVER: &str = "engenho.io/local-path";
69
70/// The host-effect seam — the side-effecting half of snapshotting.
71///
72/// Mirrors [`crate::pv_binder::ProvisionerEnv`] deliberately: one trait, only
73/// the effects, so the reconcile logic is pure and testable.
74pub trait SnapshotEnv: Send + Sync {
75    /// Recursively copy `src` to `dst`, replacing `dst` if it exists.
76    ///
77    /// # Errors
78    ///
79    /// A human-readable message on any failure. A failed copy leaves the
80    /// snapshot NOT ready — never ready-with-no-data.
81    fn copy_tree(&self, src: &str, dst: &str) -> Result<(), String>;
82
83    /// Whether a path exists (used to refuse a snapshot of a missing source
84    /// rather than creating an empty one).
85    fn exists(&self, path: &str) -> bool;
86
87    /// Total bytes under `path`, for `status.restoreSize`.
88    ///
89    /// # Errors
90    ///
91    /// A human-readable message on any failure.
92    fn size_bytes(&self, path: &str) -> Result<u64, String>;
93}
94
95/// The real filesystem implementation.
96#[derive(Debug, Default, Clone, Copy)]
97pub struct HostSnapshotEnv;
98
99impl SnapshotEnv for HostSnapshotEnv {
100    fn copy_tree(&self, src: &str, dst: &str) -> Result<(), String> {
101        let dst_path = std::path::Path::new(dst);
102        if dst_path.exists() {
103            std::fs::remove_dir_all(dst_path).map_err(|e| e.to_string())?;
104        }
105        copy_dir_recursive(std::path::Path::new(src), dst_path).map_err(|e| e.to_string())
106    }
107
108    fn exists(&self, path: &str) -> bool {
109        std::path::Path::new(path).exists()
110    }
111
112    fn size_bytes(&self, path: &str) -> Result<u64, String> {
113        dir_size(std::path::Path::new(path)).map_err(|e| e.to_string())
114    }
115}
116
117/// Recursive directory copy. `std::fs` has no recursive copy, and shelling out
118/// to `cp -r` is banned (★ NO SHELL) — this is the typed equivalent.
119fn copy_dir_recursive(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {
120    std::fs::create_dir_all(dst)?;
121    for entry in std::fs::read_dir(src)? {
122        let entry = entry?;
123        let target = dst.join(entry.file_name());
124        if entry.file_type()?.is_dir() {
125            copy_dir_recursive(&entry.path(), &target)?;
126        } else {
127            std::fs::copy(entry.path(), &target)?;
128        }
129    }
130    Ok(())
131}
132
133/// Recursive byte count, the size half of the same walk.
134fn dir_size(path: &std::path::Path) -> std::io::Result<u64> {
135    let mut total = 0;
136    if path.is_file() {
137        return Ok(path.metadata()?.len());
138    }
139    for entry in std::fs::read_dir(path)? {
140        let entry = entry?;
141        if entry.file_type()?.is_dir() {
142            total += dir_size(&entry.path())?;
143        } else {
144            total += entry.metadata()?.len();
145        }
146    }
147    Ok(total)
148}
149
150/// The snapshot controller.
151pub struct VolumeSnapshotController {
152    store: Arc<StoreMesh>,
153    /// Root under which snapshot copies live:
154    /// `<snapshot_root>/<snapshot-ns>-<snapshot-name>`.
155    snapshot_root: String,
156    env: Arc<dyn SnapshotEnv>,
157}
158
159impl VolumeSnapshotController {
160    /// Build the controller over a store, a snapshot root, and a host seam.
161    #[must_use]
162    pub fn new(store: Arc<StoreMesh>, snapshot_root: String, env: Arc<dyn SnapshotEnv>) -> Self {
163        Self {
164            store,
165            snapshot_root,
166            env,
167        }
168    }
169
170    /// The directory a given snapshot's data lives in, derived from a root.
171    ///
172    /// Free of `self` so it is testable without standing up a store — the
173    /// path derivation is the part with a rule in it (namespacing), and a
174    /// helper that needs a whole cluster to test is a helper nobody tests.
175    #[must_use]
176    pub fn snapshot_path_in(root: &str, namespace: &str, name: &str) -> String {
177        [root.trim_end_matches('/'), "/", namespace, "-", name].concat()
178    }
179
180    /// The directory this controller stores a given snapshot's data in.
181    #[must_use]
182    pub fn snapshot_path(&self, namespace: &str, name: &str) -> String {
183        Self::snapshot_path_in(&self.snapshot_root, namespace, name)
184    }
185
186    /// Is this snapshot already done? Idempotence: a ready snapshot is never
187    /// re-copied, so a tick over a settled cluster performs no host effect.
188    fn is_ready(snap: &Value) -> bool {
189        snap.get("status")
190            .and_then(|s| s.get("readyToUse"))
191            .and_then(Value::as_bool)
192            .unwrap_or(false)
193    }
194}
195
196/// The snapshots it takes, and the claim and volume each one copies. The
197/// `VolumeSnapshotContent` it writes is output, not input.
198impl DeclaresReads for VolumeSnapshotController {
199    fn reads(&self) -> Reads {
200        Reads::of(&[
201            gvk(SNAPSHOT_GROUP, SNAPSHOT_VERSION, "VolumeSnapshot"),
202            gvk("", "v1", "PersistentVolumeClaim"),
203            gvk("", "v1", "PersistentVolume"),
204        ])
205    }
206}
207
208#[async_trait]
209impl Controller for VolumeSnapshotController {
210    fn name(&self) -> &'static str {
211        "volume-snapshot"
212    }
213
214    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
215        let snaps = self
216            .store
217            .list(SNAPSHOT_GROUP, SNAPSHOT_VERSION, "VolumeSnapshot", None)
218            .await;
219        let pvcs = self
220            .store
221            .list("", "v1", "PersistentVolumeClaim", None)
222            .await;
223        let pvs = self.store.list("", "v1", "PersistentVolume", None).await;
224
225        let mut report = ReconcileReport::default();
226        report.objects_examined = snaps.len();
227
228        for (key, snap) in &snaps {
229            if Self::is_ready(snap) {
230                report.objects_skipped += 1;
231                continue;
232            }
233            let ns = key.namespace.as_deref().unwrap_or("default");
234            let name = &key.name;
235
236            // ── Resolve source PVC → PV → hostPath ───────────────────────
237            let Some(pvc_name) = snap
238                .get("spec")
239                .and_then(|s| s.get("source"))
240                .and_then(|s| s.get("persistentVolumeClaimName"))
241                .and_then(Value::as_str)
242            else {
243                report.objects_skipped += 1;
244                report.note = Some(
245                    "a VolumeSnapshot with no spec.source.persistentVolumeClaimName cannot be \
246                     resolved; pre-provisioned content sources are not served"
247                        .to_string(),
248                );
249                continue;
250            };
251            let Some((_, pvc)) = pvcs
252                .iter()
253                .find(|(k, _)| k.namespace.as_deref() == Some(ns) && k.name == pvc_name)
254            else {
255                report.objects_skipped += 1;
256                continue;
257            };
258            let Some(volume_name) = pvc
259                .get("spec")
260                .and_then(|s| s.get("volumeName"))
261                .and_then(Value::as_str)
262            else {
263                // An unbound PVC has nothing to copy. Left not-ready.
264                report.objects_skipped += 1;
265                continue;
266            };
267            let Some((_, pv)) = pvs.iter().find(|(k, _)| k.name == volume_name) else {
268                report.objects_skipped += 1;
269                continue;
270            };
271            let Some(src) = pv
272                .get("spec")
273                .and_then(|s| s.get("hostPath"))
274                .and_then(|h| h.get("path"))
275                .and_then(Value::as_str)
276            else {
277                // Not a local-path volume. Skipped with a NOTE rather than
278                // marked ready — a snapshot that copies nothing must never
279                // report success.
280                report.objects_skipped += 1;
281                report.note = Some(
282                    "only local-path (hostPath) volumes can be snapshotted by this controller; \
283                     the source PV has no hostPath and was left not-ready"
284                        .to_string(),
285                );
286                continue;
287            };
288            if !self.env.exists(src) {
289                report.objects_skipped += 1;
290                continue;
291            }
292
293            // ── Copy ─────────────────────────────────────────────────────
294            let dst = self.snapshot_path(ns, name);
295            self.env
296                .copy_tree(src, &dst)
297                .map_err(|e| ControllerError::Internal(["snapshot copy failed: ", &e].concat()))?;
298            let size = self.env.size_bytes(&dst).unwrap_or(0);
299
300            // ── The VolumeSnapshotContent ────────────────────────────────
301            let content_name = ["snapcontent-", ns, "-", name].concat();
302            let api_version = [SNAPSHOT_GROUP, "/", SNAPSHOT_VERSION].concat();
303            let content = json!({
304                "apiVersion": api_version,
305                "kind": "VolumeSnapshotContent",
306                "metadata": { "name": content_name },
307                "spec": {
308                    "driver": SNAPSHOT_DRIVER,
309                    "deletionPolicy": "Delete",
310                    "source": { "volumeHandle": volume_name },
311                    "volumeSnapshotRef": {
312                        "name": name,
313                        "namespace": ns,
314                    },
315                },
316                "status": {
317                    "readyToUse": true,
318                    "restoreSize": size,
319                    "snapshotHandle": dst.clone(),
320                },
321            });
322            self.store
323                .propose(ResourceCommand::Put {
324                    key: ResourceKey::cluster_scoped(
325                        SNAPSHOT_GROUP,
326                        SNAPSHOT_VERSION,
327                        "VolumeSnapshotContent",
328                        content_name.clone(),
329                    ),
330                    value: content,
331                    expected: None,
332                    reason: Reason::Controller,
333                })
334                .await?;
335
336            // ── Stamp the snapshot's status ──────────────────────────────
337            let mut updated = snap.clone();
338            updated["status"] = json!({
339                "readyToUse": true,
340                "boundVolumeSnapshotContentName": content_name,
341                "creationTime": engenho_types::time::now_rfc3339_utc(),
342                "restoreSize": size,
343            });
344            let applied = self
345                .store
346                .propose(ResourceCommand::Put {
347                    key: ResourceKey::namespaced(
348                        SNAPSHOT_GROUP,
349                        SNAPSHOT_VERSION,
350                        "VolumeSnapshot",
351                        ns.to_string(),
352                        name.clone(),
353                    ),
354                    value: updated,
355                    expected: None,
356                    reason: Reason::Controller,
357                })
358                .await?;
359            report.record(Effect::of(applied.op));
360        }
361
362        Ok(report.into())
363    }
364}
365
366/// Deterministic mock [`SnapshotEnv`] — records every copy it was asked to
367/// make and never touches a disk. The trait IS the testability contract.
368#[derive(Default)]
369pub struct FakeSnapshotEnv {
370    copies: std::sync::Mutex<Vec<(String, String)>>,
371    /// Paths the fake reports as existing. Empty ⇒ everything exists, which
372    /// keeps the common case terse; push a path to test the missing-source
373    /// refusal.
374    missing: std::sync::Mutex<Vec<String>>,
375}
376
377impl FakeSnapshotEnv {
378    /// The `(src, dst)` copies requested, in order.
379    #[must_use]
380    pub fn copies(&self) -> Vec<(String, String)> {
381        self.copies.lock().unwrap().clone()
382    }
383
384    /// Mark a path as absent, so [`SnapshotEnv::exists`] reports false for it.
385    pub fn mark_missing(&self, path: &str) {
386        self.missing.lock().unwrap().push(path.to_string());
387    }
388}
389
390impl SnapshotEnv for FakeSnapshotEnv {
391    fn copy_tree(&self, src: &str, dst: &str) -> Result<(), String> {
392        self.copies
393            .lock()
394            .unwrap()
395            .push((src.to_string(), dst.to_string()));
396        Ok(())
397    }
398
399    fn exists(&self, path: &str) -> bool {
400        !self.missing.lock().unwrap().iter().any(|p| p == path)
401    }
402
403    fn size_bytes(&self, _path: &str) -> Result<u64, String> {
404        Ok(0)
405    }
406}
407
408#[cfg(test)]
409mod snapshot_paths {
410    use super::*;
411
412    const ROOT: &str = "/data/snapshots";
413
414    #[test]
415    fn a_snapshot_path_is_namespaced_so_two_namespaces_cannot_collide() {
416        // Without the namespace in the path, `a/snap` and `b/snap` would share
417        // one directory and the second snapshot would silently overwrite the
418        // first — two clusters' worth of data behind one name.
419        assert_ne!(
420            VolumeSnapshotController::snapshot_path_in(ROOT, "team-a", "nightly"),
421            VolumeSnapshotController::snapshot_path_in(ROOT, "team-b", "nightly")
422        );
423    }
424
425    #[test]
426    fn the_path_is_rooted_where_configured() {
427        assert!(
428            VolumeSnapshotController::snapshot_path_in(ROOT, "default", "s")
429                .starts_with("/data/snapshots/")
430        );
431    }
432
433    #[test]
434    fn a_trailing_slash_on_the_root_does_not_double_up() {
435        assert!(
436            !VolumeSnapshotController::snapshot_path_in("/data/snapshots/", "default", "s")
437                .contains("//")
438        );
439    }
440
441    #[test]
442    fn a_ready_snapshot_is_not_recopied() {
443        // Idempotence: without this a settled cluster would re-copy every
444        // snapshot on every tick, which is unbounded disk IO proportional to
445        // uptime rather than to change.
446        let ready = json!({"status": {"readyToUse": true}});
447        assert!(VolumeSnapshotController::is_ready(&ready));
448    }
449
450    /// ★ NEGATIVE CONTROL. `readyToUse` absent or false must both read as
451    /// not-ready; treating a missing status as ready would skip the copy and
452    /// leave an empty snapshot marked good.
453    #[test]
454    fn an_unfinished_snapshot_reads_as_not_ready() {
455        assert!(!VolumeSnapshotController::is_ready(&json!({})));
456        assert!(!VolumeSnapshotController::is_ready(&json!({"status": {}})));
457        assert!(!VolumeSnapshotController::is_ready(
458            &json!({"status": {"readyToUse": false}})
459        ));
460    }
461
462    #[test]
463    fn the_fake_env_reports_missing_paths_as_absent() {
464        let env = FakeSnapshotEnv::default();
465        assert!(env.exists("/anything"));
466        env.mark_missing("/gone");
467        assert!(!env.exists("/gone"));
468        assert!(env.exists("/still-here"));
469    }
470}