Skip to main content

a3s_box_runtime/rootfs/
provider.rs

1//! Rootfs provider — abstracts how a rootfs directory is prepared for a box.
2//!
3//! Two built-in providers:
4//! - `CopyProvider` — full recursive copy (works everywhere, current default)
5//! - `OverlayProvider` — Linux overlayfs mount (near-instant, CoW)
6
7use std::path::{Path, PathBuf};
8
9use a3s_box_core::error::{BoxError, Result};
10
11/// Abstracts how a rootfs directory is prepared for a box from a cached lower layer.
12pub trait RootfsProvider: Send + Sync {
13    /// Prepare a rootfs at `box_dir` from the cached read-only layer at `cache_dir`.
14    /// Returns the path to use as `InstanceSpec.rootfs_path`.
15    fn prepare(&self, box_dir: &Path, cache_dir: &Path) -> Result<PathBuf>;
16
17    /// Prepare an empty writable rootfs for an OCI cache miss.
18    fn prepare_empty(&self, box_dir: &Path) -> Result<PathBuf> {
19        let rootfs = box_dir.join("rootfs");
20        std::fs::create_dir_all(&rootfs).map_err(|error| {
21            BoxError::BuildError(format!(
22                "Failed to create rootfs {}: {error}",
23                rootfs.display()
24            ))
25        })?;
26        Ok(rootfs)
27    }
28
29    /// Cleanup after box stops.
30    ///
31    /// When `persistent` is true, the writable layer (overlay upper dir or copy
32    /// rootfs) is preserved on disk so changes survive the next start.
33    /// When false, the writable layer is wiped for a clean slate.
34    fn cleanup(&self, box_dir: &Path, persistent: bool) -> Result<()>;
35
36    /// Human-readable name for logging.
37    fn name(&self) -> &'static str;
38}
39
40/// Full recursive copy provider — works on all platforms.
41///
42/// This is the original behavior: copies the entire cached rootfs into
43/// `box_dir/rootfs/`. Safe but slow for large images.
44pub struct CopyProvider;
45
46impl RootfsProvider for CopyProvider {
47    fn prepare(&self, box_dir: &Path, cache_dir: &Path) -> Result<PathBuf> {
48        let rootfs = box_dir.join("rootfs");
49        // Reuse existing rootfs when persistent and already populated
50        if rootfs.exists() {
51            tracing::info!(path = %rootfs.display(), "Reusing persistent rootfs");
52            return Ok(rootfs);
53        }
54        crate::cache::layer_cache::copy_dir_recursive(cache_dir, &rootfs)?;
55        Ok(rootfs)
56    }
57
58    fn cleanup(&self, box_dir: &Path, persistent: bool) -> Result<()> {
59        if persistent {
60            tracing::info!("Persistent box: keeping rootfs on disk");
61            return Ok(());
62        }
63        let rootfs = box_dir.join("rootfs");
64        if rootfs.exists() {
65            std::fs::remove_dir_all(&rootfs).map_err(|e| {
66                BoxError::BuildError(format!(
67                    "Failed to remove rootfs {}: {}",
68                    rootfs.display(),
69                    e
70                ))
71            })?;
72        }
73        Ok(())
74    }
75
76    fn name(&self) -> &'static str {
77        "copy"
78    }
79}
80
81/// A copy provider backed by a case-sensitive APFS sparse image.
82///
83/// macOS commonly stores `~/.a3s` on case-insensitive APFS. Passing a normal
84/// host directory to libkrun as the guest root would then make Linux paths such
85/// as `/bin` and `/BIN` aliases. Each box therefore owns a sparse, dynamically
86/// allocated case-sensitive APFS image and exposes its mountpoint via virtiofs.
87#[cfg(target_os = "macos")]
88pub struct CaseSensitiveApfsProvider;
89
90#[cfg(target_os = "macos")]
91impl CaseSensitiveApfsProvider {
92    // v2 stores the Linux tree below a private directory inside the volume.
93    // APFS creates volume-management entries such as `.fseventsd` at the
94    // volume root; exposing that root to the guest both leaks host artifacts
95    // and can make recursive rootfs walks fail with EACCES.
96    const IMAGE_STEM: &'static str = "rootfs-apfs-v2";
97    const IMAGE_NAME: &'static str = "rootfs-apfs-v2.sparseimage";
98    const DATA_DIR: &'static str = ".a3s-rootfs";
99
100    fn clone_image(source: &Path, destination: &Path) -> Result<()> {
101        let output = std::process::Command::new("cp")
102            .arg("-c")
103            .arg(source)
104            .arg(destination)
105            .output()
106            .map_err(|error| {
107                BoxError::BuildError(format!("Failed to start APFS clone: {error}"))
108            })?;
109        if !output.status.success() {
110            return Err(BoxError::BuildError(format!(
111                "Failed to clone cached APFS rootfs {}: {}",
112                source.display(),
113                String::from_utf8_lossy(&output.stderr).trim()
114            )));
115        }
116        Ok(())
117    }
118
119    fn mount(&self, box_dir: &Path) -> Result<PathBuf> {
120        use std::process::Command;
121
122        std::fs::create_dir_all(box_dir).map_err(|error| {
123            BoxError::BuildError(format!(
124                "Failed to create box directory {}: {error}",
125                box_dir.display()
126            ))
127        })?;
128        let rootfs = box_dir.join("rootfs");
129        std::fs::create_dir_all(&rootfs).map_err(|error| {
130            BoxError::BuildError(format!(
131                "Failed to create APFS mountpoint {}: {error}",
132                rootfs.display()
133            ))
134        })?;
135        if super::is_mountpoint(&rootfs) {
136            return Self::data_dir(&rootfs);
137        }
138
139        let image = box_dir.join(Self::IMAGE_NAME);
140        if !image.exists() {
141            let stem = box_dir.join(Self::IMAGE_STEM);
142            let output = Command::new("hdiutil")
143                .args([
144                    "create",
145                    "-quiet",
146                    "-size",
147                    "64g",
148                    "-type",
149                    "SPARSE",
150                    "-fs",
151                    "Case-sensitive APFS",
152                    "-volname",
153                    "A3SRootfs",
154                ])
155                .arg(&stem)
156                .output()
157                .map_err(|error| {
158                    BoxError::BuildError(format!("Failed to start hdiutil create: {error}"))
159                })?;
160            if !output.status.success() {
161                return Err(BoxError::BuildError(format!(
162                    "Failed to create case-sensitive APFS rootfs image: {}",
163                    String::from_utf8_lossy(&output.stderr).trim()
164                )));
165            }
166        }
167
168        let output = Command::new("hdiutil")
169            .args([
170                "attach",
171                "-quiet",
172                "-nobrowse",
173                "-owners",
174                "on",
175                "-mountpoint",
176            ])
177            .arg(&rootfs)
178            .arg(&image)
179            .output()
180            .map_err(|error| {
181                BoxError::BuildError(format!("Failed to start hdiutil attach: {error}"))
182            })?;
183        if !output.status.success() {
184            return Err(BoxError::BuildError(format!(
185                "Failed to mount case-sensitive APFS rootfs image {}: {}",
186                image.display(),
187                String::from_utf8_lossy(&output.stderr).trim()
188            )));
189        }
190        if !super::is_mountpoint(&rootfs) {
191            return Err(BoxError::BuildError(format!(
192                "hdiutil did not mount the rootfs image at {}",
193                rootfs.display()
194            )));
195        }
196        Self::data_dir(&rootfs)
197    }
198
199    fn data_dir(mountpoint: &Path) -> Result<PathBuf> {
200        let data = mountpoint.join(Self::DATA_DIR);
201        std::fs::create_dir_all(&data).map_err(|error| {
202            BoxError::BuildError(format!(
203                "Failed to create APFS rootfs data directory {}: {error}",
204                data.display()
205            ))
206        })?;
207        Ok(data)
208    }
209}
210
211#[cfg(target_os = "macos")]
212impl RootfsProvider for CaseSensitiveApfsProvider {
213    fn prepare(&self, box_dir: &Path, cache_dir: &Path) -> Result<PathBuf> {
214        let image = box_dir.join(Self::IMAGE_NAME);
215        if cache_dir.is_file() && !image.exists() {
216            std::fs::create_dir_all(box_dir).map_err(BoxError::IoError)?;
217            Self::clone_image(cache_dir, &image)?;
218        }
219        let rootfs = self.mount(box_dir)?;
220        if cache_dir.is_file() {
221            return Ok(rootfs);
222        }
223        if std::fs::read_dir(&rootfs)
224            .map_err(|error| BoxError::BuildError(error.to_string()))?
225            .next()
226            .is_none()
227        {
228            crate::cache::layer_cache::copy_dir_recursive(cache_dir, &rootfs)?;
229        } else {
230            tracing::info!(path = %rootfs.display(), "Reusing persistent APFS rootfs");
231        }
232        Ok(rootfs)
233    }
234
235    fn prepare_empty(&self, box_dir: &Path) -> Result<PathBuf> {
236        self.mount(box_dir)
237    }
238
239    fn cleanup(&self, box_dir: &Path, persistent: bool) -> Result<()> {
240        super::unmount_box_rootfs(&box_dir.join("rootfs"));
241        if !persistent {
242            let image = box_dir.join(Self::IMAGE_NAME);
243            if image.exists() {
244                std::fs::remove_file(&image).map_err(|error| {
245                    BoxError::BuildError(format!(
246                        "Failed to remove rootfs image {}: {error}",
247                        image.display()
248                    ))
249                })?;
250            }
251        }
252        Ok(())
253    }
254
255    fn name(&self) -> &'static str {
256        "case-sensitive-apfs"
257    }
258}
259
260/// Overlayfs provider — near-instant CoW mounts (Linux only).
261///
262/// Layout:
263/// ```text
264/// cache_dir/           ← lower (read-only, shared across boxes)
265/// box_dir/upper/       ← upper (per-box writes)
266/// box_dir/work/        ← overlayfs workdir
267/// box_dir/merged/      ← merged view → InstanceSpec.rootfs_path
268/// ```
269pub struct OverlayProvider;
270
271impl OverlayProvider {
272    fn lower_dir(box_dir: &Path, cache_dir: &Path) -> Result<PathBuf> {
273        let rootfs = box_dir.join("rootfs");
274        match std::fs::read_dir(&rootfs) {
275            Ok(mut entries) => {
276                if entries.next().is_some() {
277                    // A cache miss builds the first generation directly in `rootfs`.
278                    // Once that generation has run, the cache will usually be warm.
279                    // Keep the original writable tree as the overlay lower instead
280                    // of switching the next generation to the immutable image cache;
281                    // otherwise persistent guest writes silently disappear on restart.
282                    Ok(rootfs)
283                } else {
284                    Ok(cache_dir.to_path_buf())
285                }
286            }
287            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
288                Ok(cache_dir.to_path_buf())
289            }
290            Err(error) => Err(BoxError::BuildError(format!(
291                "Failed to inspect existing rootfs {}: {error}",
292                rootfs.display()
293            ))),
294        }
295    }
296}
297
298impl RootfsProvider for OverlayProvider {
299    fn prepare(&self, box_dir: &Path, cache_dir: &Path) -> Result<PathBuf> {
300        let lower = Self::lower_dir(box_dir, cache_dir)?;
301        let upper = box_dir.join("upper");
302        let work = box_dir.join("work");
303        let merged = box_dir.join("merged");
304
305        for dir in [&upper, &work, &merged] {
306            std::fs::create_dir_all(dir).map_err(|e| {
307                BoxError::BuildError(format!(
308                    "Failed to create overlay dir {}: {}",
309                    dir.display(),
310                    e
311                ))
312            })?;
313        }
314
315        // Idempotent: a restart re-runs prepare(); without this guard each call
316        // stacks another overlay on `merged` (the leaked double/triple mounts).
317        if super::is_mountpoint(&merged) {
318            tracing::debug!(merged = %merged.display(), "Overlay already mounted; reusing");
319            return Ok(merged);
320        }
321
322        super::overlay::overlay_mount(&lower, &upper, &work, &merged)?;
323
324        tracing::info!(
325            lower = %lower.display(),
326            merged = %merged.display(),
327            "Overlay mount ready"
328        );
329
330        Ok(merged)
331    }
332
333    fn cleanup(&self, box_dir: &Path, persistent: bool) -> Result<()> {
334        let merged = box_dir.join("merged");
335        // Bounded unmount-retry rather than a single attempt: a transient EBUSY
336        // must not leave the overlay mounted, or the remove_dir_all below would
337        // recurse into the live mount and leak it. Mirrors the cleanup paths in
338        // cleanup_stopped_box/cleanup_removed_box.
339        super::unmount_box_overlay(&merged);
340
341        if persistent {
342            // Keep both possible persistent generations: a cache-miss generation
343            // lives in `rootfs`, while later overlay writes live in `upper`.
344            // The next prepare mounts their union again.
345            tracing::info!("Persistent box: keeping rootfs and overlay upper on disk");
346            for dir_name in &["merged", "work"] {
347                let dir = box_dir.join(dir_name);
348                if dir.exists() {
349                    if let Err(e) = std::fs::remove_dir_all(&dir) {
350                        tracing::warn!(path = %dir.display(), error = %e, "Failed to remove overlay dir");
351                    }
352                }
353            }
354            return Ok(());
355        }
356
357        for dir_name in &["rootfs", "upper", "work", "merged"] {
358            let dir = box_dir.join(dir_name);
359            if dir.exists() {
360                if let Err(e) = std::fs::remove_dir_all(&dir) {
361                    tracing::warn!(
362                        path = %dir.display(),
363                        error = %e,
364                        "Failed to remove overlay dir"
365                    );
366                }
367            }
368        }
369
370        Ok(())
371    }
372
373    fn name(&self) -> &'static str {
374        "overlay"
375    }
376}
377
378/// Auto-detect the best available rootfs provider for the current platform.
379pub fn default_provider() -> Box<dyn RootfsProvider> {
380    #[cfg(target_os = "macos")]
381    {
382        tracing::info!("Using case-sensitive APFS rootfs provider");
383        Box::new(CaseSensitiveApfsProvider)
384    }
385
386    #[cfg(not(target_os = "macos"))]
387    {
388        if super::overlay::is_overlay_supported() {
389            tracing::info!("Using overlayfs rootfs provider");
390            return Box::new(OverlayProvider);
391        }
392
393        tracing::info!("Overlayfs not available, using copy provider");
394        Box::new(CopyProvider)
395    }
396}
397
398#[cfg(test)]
399mod tests {
400    use super::*;
401    use tempfile::TempDir;
402
403    fn make_sample_rootfs(dir: &Path) {
404        std::fs::create_dir_all(dir.join("etc")).unwrap();
405        std::fs::create_dir_all(dir.join("bin")).unwrap();
406        std::fs::write(dir.join("etc/hostname"), "testbox").unwrap();
407        std::fs::write(dir.join("bin/hello"), "#!/bin/sh\necho hi").unwrap();
408    }
409
410    #[test]
411    fn test_copy_provider_prepare() {
412        let tmp = TempDir::new().unwrap();
413        let cache_dir = tmp.path().join("cache");
414        let box_dir = tmp.path().join("box");
415        std::fs::create_dir_all(&cache_dir).unwrap();
416        std::fs::create_dir_all(&box_dir).unwrap();
417        make_sample_rootfs(&cache_dir);
418
419        let provider = CopyProvider;
420        let rootfs = provider.prepare(&box_dir, &cache_dir).unwrap();
421
422        assert_eq!(rootfs, box_dir.join("rootfs"));
423        assert!(rootfs.join("etc/hostname").exists());
424        assert_eq!(
425            std::fs::read_to_string(rootfs.join("etc/hostname")).unwrap(),
426            "testbox"
427        );
428        assert!(rootfs.join("bin/hello").exists());
429    }
430
431    #[test]
432    fn test_copy_provider_prepare_reuses_existing_rootfs_without_overwriting() {
433        let tmp = TempDir::new().unwrap();
434        let cache_dir = tmp.path().join("cache");
435        let box_dir = tmp.path().join("box");
436        let rootfs = box_dir.join("rootfs");
437        std::fs::create_dir_all(&cache_dir).unwrap();
438        std::fs::create_dir_all(rootfs.join("etc")).unwrap();
439        make_sample_rootfs(&cache_dir);
440        std::fs::write(rootfs.join("etc/hostname"), "persistent-host").unwrap();
441
442        let provider = CopyProvider;
443        let prepared = provider.prepare(&box_dir, &cache_dir).unwrap();
444
445        assert_eq!(prepared, rootfs);
446        assert_eq!(
447            std::fs::read_to_string(prepared.join("etc/hostname")).unwrap(),
448            "persistent-host"
449        );
450        assert!(
451            !prepared.join("bin/hello").exists(),
452            "existing persistent rootfs must not be overwritten from cache"
453        );
454    }
455
456    #[test]
457    fn test_copy_provider_cleanup() {
458        let tmp = TempDir::new().unwrap();
459        let cache_dir = tmp.path().join("cache");
460        let box_dir = tmp.path().join("box");
461        std::fs::create_dir_all(&cache_dir).unwrap();
462        std::fs::create_dir_all(&box_dir).unwrap();
463        make_sample_rootfs(&cache_dir);
464
465        let provider = CopyProvider;
466        let rootfs = provider.prepare(&box_dir, &cache_dir).unwrap();
467        assert!(rootfs.exists());
468
469        provider.cleanup(&box_dir, false).unwrap();
470        assert!(!rootfs.exists());
471    }
472
473    #[test]
474    fn test_copy_provider_cleanup_persistent_keeps_rootfs() {
475        let tmp = TempDir::new().unwrap();
476        let box_dir = tmp.path().join("box");
477        let rootfs = box_dir.join("rootfs");
478        std::fs::create_dir_all(rootfs.join("etc")).unwrap();
479        std::fs::write(rootfs.join("etc/hostname"), "kept").unwrap();
480
481        CopyProvider.cleanup(&box_dir, true).unwrap();
482
483        assert_eq!(
484            std::fs::read_to_string(rootfs.join("etc/hostname")).unwrap(),
485            "kept"
486        );
487    }
488
489    #[test]
490    fn test_copy_provider_cleanup_nonexistent() {
491        let tmp = TempDir::new().unwrap();
492        let provider = CopyProvider;
493        // Should not error on missing dir
494        provider.cleanup(tmp.path(), false).unwrap();
495    }
496
497    #[test]
498    fn test_copy_provider_name() {
499        assert_eq!(CopyProvider.name(), "copy");
500    }
501
502    #[test]
503    fn test_overlay_provider_name() {
504        assert_eq!(OverlayProvider.name(), "overlay");
505    }
506
507    #[test]
508    fn test_overlay_provider_uses_populated_rootfs_as_persistent_lower() {
509        let tmp = TempDir::new().unwrap();
510        let cache_dir = tmp.path().join("cache");
511        let box_dir = tmp.path().join("box");
512        let rootfs = box_dir.join("rootfs");
513        std::fs::create_dir_all(&cache_dir).unwrap();
514        std::fs::create_dir_all(&rootfs).unwrap();
515        std::fs::write(rootfs.join("restart-proof"), "generation-one").unwrap();
516
517        assert_eq!(
518            OverlayProvider::lower_dir(&box_dir, &cache_dir).unwrap(),
519            rootfs
520        );
521    }
522
523    #[test]
524    fn test_overlay_provider_ignores_empty_rootfs_as_lower() {
525        let tmp = TempDir::new().unwrap();
526        let cache_dir = tmp.path().join("cache");
527        let box_dir = tmp.path().join("box");
528        std::fs::create_dir_all(&cache_dir).unwrap();
529        std::fs::create_dir_all(box_dir.join("rootfs")).unwrap();
530
531        assert_eq!(
532            OverlayProvider::lower_dir(&box_dir, &cache_dir).unwrap(),
533            cache_dir
534        );
535    }
536
537    #[test]
538    fn test_overlay_provider_cleanup_persistent_keeps_rootfs_and_upper() {
539        let tmp = TempDir::new().unwrap();
540        let box_dir = tmp.path().join("box");
541        for dir in ["rootfs", "upper", "work", "merged"] {
542            std::fs::create_dir_all(box_dir.join(dir)).unwrap();
543        }
544        std::fs::write(box_dir.join("rootfs/restart-proof"), "generation-one").unwrap();
545        std::fs::write(box_dir.join("upper/data.txt"), "state").unwrap();
546        std::fs::write(box_dir.join("work/scratch.txt"), "work").unwrap();
547        std::fs::write(box_dir.join("merged/view.txt"), "merged").unwrap();
548
549        OverlayProvider.cleanup(&box_dir, true).unwrap();
550
551        assert_eq!(
552            std::fs::read_to_string(box_dir.join("upper/data.txt")).unwrap(),
553            "state"
554        );
555        assert_eq!(
556            std::fs::read_to_string(box_dir.join("rootfs/restart-proof")).unwrap(),
557            "generation-one"
558        );
559        assert!(!box_dir.join("work").exists());
560        assert!(!box_dir.join("merged").exists());
561    }
562
563    #[test]
564    fn test_overlay_provider_cleanup_nonpersistent_removes_all_overlay_dirs() {
565        let tmp = TempDir::new().unwrap();
566        let box_dir = tmp.path().join("box");
567        for dir in ["rootfs", "upper", "work", "merged"] {
568            std::fs::create_dir_all(box_dir.join(dir)).unwrap();
569            std::fs::write(box_dir.join(dir).join("file.txt"), "data").unwrap();
570        }
571
572        OverlayProvider.cleanup(&box_dir, false).unwrap();
573
574        assert!(!box_dir.join("rootfs").exists());
575        assert!(!box_dir.join("upper").exists());
576        assert!(!box_dir.join("work").exists());
577        assert!(!box_dir.join("merged").exists());
578    }
579
580    #[test]
581    fn test_default_provider_returns_something() {
582        let provider = default_provider();
583        // On any platform, we should get a provider
584        assert!(!provider.name().is_empty());
585    }
586
587    #[cfg(target_os = "macos")]
588    #[test]
589    fn case_sensitive_apfs_provider_preserves_distinct_names() {
590        use std::os::unix::fs::MetadataExt;
591
592        let tmp = TempDir::new().unwrap();
593        let box_dir = tmp.path().join("box");
594        let provider = CaseSensitiveApfsProvider;
595        let rootfs = provider.prepare_empty(&box_dir).unwrap();
596        std::fs::write(rootfs.join("Foo"), "upper").unwrap();
597        std::fs::write(rootfs.join("foo"), "lower").unwrap();
598
599        assert_eq!(
600            std::fs::read_to_string(rootfs.join("Foo")).unwrap(),
601            "upper"
602        );
603        assert_eq!(
604            std::fs::read_to_string(rootfs.join("foo")).unwrap(),
605            "lower"
606        );
607        assert_ne!(
608            std::fs::metadata(rootfs.join("Foo")).unwrap().ino(),
609            std::fs::metadata(rootfs.join("foo")).unwrap().ino()
610        );
611
612        provider.cleanup(&box_dir, false).unwrap();
613        assert!(!box_dir.join(CaseSensitiveApfsProvider::IMAGE_NAME).exists());
614    }
615
616    #[cfg(target_os = "linux")]
617    #[test]
618    fn test_overlay_provider_prepare_and_cleanup() {
619        if !super::super::overlay::is_overlay_supported() {
620            // Skip if overlay not available (e.g., in container without privileges)
621            return;
622        }
623
624        let tmp = TempDir::new().unwrap();
625        let cache_dir = tmp.path().join("cache");
626        let box_dir = tmp.path().join("box");
627        std::fs::create_dir_all(&cache_dir).unwrap();
628        std::fs::create_dir_all(&box_dir).unwrap();
629        make_sample_rootfs(&cache_dir);
630
631        let provider = OverlayProvider;
632        let merged = provider.prepare(&box_dir, &cache_dir).unwrap();
633
634        assert_eq!(merged, box_dir.join("merged"));
635        assert!(merged.join("etc/hostname").exists());
636        assert_eq!(
637            std::fs::read_to_string(merged.join("etc/hostname")).unwrap(),
638            "testbox"
639        );
640
641        // Write to merged — should go to upper
642        std::fs::write(merged.join("etc/newfile"), "overlay write").unwrap();
643        assert!(box_dir.join("upper/etc/newfile").exists());
644
645        provider.cleanup(&box_dir, false).unwrap();
646        assert!(!box_dir.join("merged").exists());
647        assert!(!box_dir.join("upper").exists());
648        assert!(!box_dir.join("work").exists());
649    }
650}