1use 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
62pub const SNAPSHOT_GROUP: &str = "snapshot.storage.k8s.io";
64pub const SNAPSHOT_VERSION: &str = "v1";
66pub const SNAPSHOT_DRIVER: &str = "engenho.io/local-path";
69
70pub trait SnapshotEnv: Send + Sync {
75 fn copy_tree(&self, src: &str, dst: &str) -> Result<(), String>;
82
83 fn exists(&self, path: &str) -> bool;
86
87 fn size_bytes(&self, path: &str) -> Result<u64, String>;
93}
94
95#[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
117fn 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
133fn 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
150pub struct VolumeSnapshotController {
152 store: Arc<StoreMesh>,
153 snapshot_root: String,
156 env: Arc<dyn SnapshotEnv>,
157}
158
159impl VolumeSnapshotController {
160 #[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 #[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 #[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 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
196impl 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 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 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 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 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 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 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#[derive(Default)]
369pub struct FakeSnapshotEnv {
370 copies: std::sync::Mutex<Vec<(String, String)>>,
371 missing: std::sync::Mutex<Vec<String>>,
375}
376
377impl FakeSnapshotEnv {
378 #[must_use]
380 pub fn copies(&self) -> Vec<(String, String)> {
381 self.copies.lock().unwrap().clone()
382 }
383
384 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 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 let ready = json!({"status": {"readyToUse": true}});
447 assert!(VolumeSnapshotController::is_ready(&ready));
448 }
449
450 #[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}