Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

fix(storage): share QCOW2 copies for online clones and snapshots (#3012)

ltstriker2ddd519ee941
diff --git a/docs/concepts/storage.md b/docs/concepts/storage.md
index 9335e2550..f3f91d833 100644
--- a/docs/concepts/storage.md
+++ b/docs/concepts/storage.md
@@ -57,6 +57,39 @@ configuration references that id. See [Mounting volumes](../guides/volumes.md).
- Snapshot support
- Shared base images across Boxes
+## Online disk snapshots
+
+A local libkrun box can take a snapshot of its managed ext4 container disk while it runs.
+BoxLite attempts to freeze guest filesystems, sends `SIGSTOP` to the shim, and
+copies the writable QCOW2 layer to `snapshots/<name>/disk.qcow2` before sending
+`SIGCONT`. The box continues to write its original disk.
+
+Online copies share the source disk's existing backing images. Administrators must
+keep those images available and read-only for the lifetime of the snapshot.
+
+Guest filesystem freezing is best effort. Snapshot restore requires a stopped box.
+
+An interruption before registration in SQLite can leave a snapshot directory
+behind. Online and stopped snapshot creation both reject an existing directory
+with the requested name, even if the directory has no snapshot record.
+
+## Online disk clones
+
+Cloning a running box uses the same QCOW2 copy operation. A batch shares one
+base copy under `bases/`, and each clone writes to its own COW layer. The source
+box resumes writing its original disk before the base and clones are registered.
+
+```text
+Attempt guest freeze → SIGSTOP → synchronous QCOW2 copy → SIGCONT → thaw if frozen
+```
+
+On a single-threaded Tokio runtime, other tasks on that thread wait for the copy to finish.
+
+Removing a box can reclaim its clone base when no registered box or managed
+disk still uses it. A clone being registered or an incomplete disk check leaves
+the base in place. If the batch fails before any clone registers, the base can
+remain on disk.
+
## File copy conflicts
With `CopyOptions::no_overwrite()`, local copies add new files into existing
diff --git a/docs/contributing/architecture/README.md b/docs/contributing/architecture/README.md
index 245a835fd..e13a011f4 100644
--- a/docs/contributing/architecture/README.md
+++ b/docs/contributing/architecture/README.md
@@ -226,9 +226,10 @@ It rejects QCOW2 layers with `extended_l2` (subcluster bitmaps) enabled and QCOW
backing chains with mismatched `cluster_size` across layers before creating the output
image.
-Snapshot, clone, and export execute in the caller's future, so cancellation does not guarantee
-completion of disk work or resume/thaw cleanup: a blocking worker may continue
+Snapshot, clone, and export run in the caller's future. Cancellation while awaiting
+a guest freeze or thaw can interrupt cleanup. Export's blocking worker can continue
after the caller drops its guards.
+
Lifecycle-read/disk-write composition is not provided.
Run `BOXLITE_DEPS_STUB=1 make test:unit:rust FILTER=operation_lock` for host
diff --git a/docs/reference/file-formats.md b/docs/reference/file-formats.md
index 6e8d06024..e8313f61e 100644
--- a/docs/reference/file-formats.md
+++ b/docs/reference/file-formats.md
@@ -9,8 +9,8 @@ BoxLite keeps boxes, images, and its database under its home directory, `~/.boxl
├── boxes/ # Per-Box runtime data
│ └── {box-id}/
│ ├── disks/ # disk.qcow2 (container disk), guest-rootfs.qcow2
-│ ├── snapshots/ # {name}/disk.qcow2 for each snapshot
-│ ├── .snapshot_pending # Crash-recovery marker while a snapshot runs
+│ ├── snapshots/ # Online and stopped snapshots by name
+│ ├── .snapshot_pending # Crash-recovery marker for stopped snapshot disk moves
│ ├── sockets/ # Unix sockets: control, guest ready, network
│ ├── shared/ # Files shared with the guest over virtio-fs
│ ├── mounts/ # Host side of shared/ (isolate_mounts, Linux)
@@ -78,8 +78,8 @@ BoxLite uses QCOW2 (QEMU Copy-On-Write version 2) for box disks.
**Locations:**
- `~/.boxlite/boxes/{box-id}/disks/disk.qcow2`: the container disk
- `~/.boxlite/boxes/{box-id}/disks/guest-rootfs.qcow2`: the guest root filesystem
-- `~/.boxlite/boxes/{box-id}/snapshots/{name}/disk.qcow2`: a snapshot of the container disk,
- recorded in the snapshot table
+- `~/.boxlite/boxes/{box-id}/snapshots/{name}/disk.qcow2`: the container disk snapshot
+ for an online or stopped box. The snapshot table records its path and name.
- `~/.boxlite/bases/{id}.qcow2`: an immutable clone base, tracked in the `base_disk` table
**Format:** QCOW2, a copy-on-write image format with thin provisioning
diff --git a/src/boxlite/src/disk/base_disk.rs b/src/boxlite/src/disk/base_disk.rs
index c2692d2b5..5bfe64d6b 100644
--- a/src/boxlite/src/disk/base_disk.rs
+++ b/src/boxlite/src/disk/base_disk.rs
@@ -105,6 +105,84 @@ impl BaseDiskManager {
&self.bases_dir
}
+ pub(crate) fn reserve_clone_base(
+ &self,
+ ) -> BoxliteResult<(BaseDiskID, tempfile::NamedTempFile)> {
+ let id = BaseDiskIDMint::mint();
+ let file = tempfile::Builder::new()
+ .prefix(id.as_str())
+ .suffix(".qcow2")
+ .rand_bytes(0)
+ .tempfile_in(&self.bases_dir)?;
+ Ok((id, file))
+ }
+
+ pub(crate) fn publish_clone_base(
+ &self,
+ id: BaseDiskID,
+ file: tempfile::NamedTempFile,
+ disk_info: super::DiskInfo,
+ source_box_id: &str,
+ ) -> BoxliteResult<BaseDisk> {
+ file.as_file().sync_all()?;
+ fs::File::open(&self.bases_dir)?.sync_all()?;
+ let (_, path) = file.keep().map_err(|error| error.error)?;
+ let base = BaseDisk {
+ id,
+ source_box_id: source_box_id.to_owned(),
+ name: None,
+ kind: BaseDiskKind::CloneBase,
+ disk_info,
+ created_at: chrono::Utc::now().timestamp(),
+ };
+ if let Err(error) = self.store.insert(&base) {
+ if matches!(self.store.find_by_id(&base.id), Ok(None)) {
+ let _ = fs::remove_file(path);
+ }
+ return Err(error);
+ }
+ Ok(base)
+ }
+
+ /// Caller holds disk admission for the boxes whose backing relationships can change.
+ /// A scan error leaves the candidate in place; an empty result must cover every root.
+ pub(crate) fn has_backing_dependency(
+ &self,
+ boxes_dir: &Path,
+ candidate: &Path,
+ ) -> BoxliteResult<bool> {
+ let candidate = candidate.canonicalize()?;
+ let boxes = walkdir::WalkDir::new(boxes_dir)
+ .min_depth(1)
+ .into_iter()
+ .filter_entry(|entry| {
+ entry.depth() != 2
+ || entry.file_name() == "disks"
+ || entry.file_name() == super::constants::dirs::SNAPSHOTS_DIR
+ });
+ let bases = walkdir::WalkDir::new(&self.bases_dir)
+ .min_depth(1)
+ .max_depth(1);
+ for entry in boxes.chain(bases) {
+ let entry = entry.map_err(std::io::Error::from)?;
+ let path = entry.path();
+ if entry.file_type().is_symlink() && fs::metadata(path)?.is_dir() {
+ return Err(boxlite_shared::errors::BoxliteError::Storage(format!(
+ "Cannot verify disk dependencies beneath symlink {}",
+ path.display()
+ )));
+ }
+ if path != candidate
+ && path.extension().is_some_and(|ext| ext == "qcow2")
+ && !entry.file_type().is_dir()
+ && super::qcow2::chain_references(path, &candidate)?
+ {
+ return Ok(true);
+ }
+ }
+ Ok(false)
+ }
+
/// Every base file something still depends on, following chains to the end.
///
/// Three dimensions have to be covered or live data becomes reachable:
@@ -333,8 +411,9 @@ impl BaseDiskManager {
/// Attempt to garbage-collect a clone base by ID and cascade to parent.
///
/// Queries the `base_disk_ref` table for dependents. If none exist,
- /// deletes the base (DB record + file) and cascades to the parent base.
- pub(crate) fn try_gc_base(&self, base_disk_id: &BaseDiskID) {
+ /// checks on-disk dependencies before deleting. The caller holds disk admissions
+ /// for the registered boxes throughout collection, including the parent cascade.
+ pub(crate) fn try_gc_base(&self, base_disk_id: &BaseDiskID, boxes_dir: &Path) {
let record = match self.store.find_by_id(base_disk_id) {
Ok(Some(r)) => r,
_ => return,
@@ -352,11 +431,25 @@ impl BaseDiskManager {
// Read parent BEFORE deleting file (we need the qcow2 header)
let base_file = record.disk_info().to_path_buf();
+ match self.has_backing_dependency(boxes_dir, &base_file) {
+ Ok(false) => {}
+ Ok(true) => return,
+ Err(error) => {
+ tracing::debug!(%base_disk_id, %error, "Keeping base after incomplete disk inspection");
+ return;
+ }
+ }
let parent = self.find_parent_base(&base_file);
// Delete DB record and file
- let _ = self.store.delete(record.id());
- let _ = std::fs::remove_file(record.disk_info().as_path());
+ if let Err(error) = self.store.delete(record.id()) {
+ tracing::warn!(%base_disk_id, %error, "Could not remove base record");
+ return;
+ }
+ if let Err(error) = fs::remove_file(&base_file) {
+ tracing::warn!(%base_disk_id, %error, "Could not remove base file");
+ return;
+ }
tracing::info!(
base_disk_id = %record.id(),
@@ -368,7 +461,7 @@ impl BaseDiskManager {
&& let Ok(Some(parent_record)) =
self.store.find_by_base_path(&parent_path.to_string_lossy())
{
- self.try_gc_base(parent_record.id());
+ self.try_gc_base(parent_record.id(), boxes_dir);
}
}
@@ -430,6 +523,7 @@ mod tests {
let db = Database::open(&db_path).unwrap();
let bases_dir = dir.path().join("bases");
std::fs::create_dir_all(&bases_dir).unwrap();
+ std::fs::create_dir(dir.path().join("boxes")).unwrap();
let store = BaseDiskStore::new(db);
let mgr = BaseDiskManager::new(bases_dir, store);
(dir, mgr)
@@ -611,7 +705,7 @@ mod tests {
#[test]
fn test_try_gc_base_single_level() {
- let (_dir, mgr) = setup();
+ let (dir, mgr) = setup();
let base_file = mgr.bases_dir.join("base0001.qcow2");
write_qcow2_with_backing(&base_file, None);
@@ -637,7 +731,7 @@ mod tests {
mgr.store().remove_all_refs_for_box("clone-1").unwrap();
// GC should delete the base (no dependents)
- mgr.try_gc_base(&base_id("base0001"));
+ mgr.try_gc_base(&base_id("base0001"), &dir.path().join("boxes"));
assert!(
mgr.store()
@@ -650,7 +744,7 @@ mod tests {
#[test]
fn test_try_gc_base_cascade_nested() {
- let (_dir, mgr) = setup();
+ let (dir, mgr) = setup();
// Create base-1 (no parent)
let base1_file = mgr.bases_dir.join("base0001.qcow2");
@@ -687,7 +781,7 @@ mod tests {
mgr.store().insert(&bd2).unwrap();
// No refs → GC base-2 → cascades to base-1
- mgr.try_gc_base(&base_id("base0002"));
+ mgr.try_gc_base(&base_id("base0002"), &dir.path().join("boxes"));
assert!(
mgr.store()
@@ -710,7 +804,7 @@ mod tests {
#[test]
fn test_try_gc_base_skips_snapshots() {
- let (_dir, mgr) = setup();
+ let (dir, mgr) = setup();
let base_file = mgr.bases_dir.join("snap0001.qcow2");
write_qcow2_with_backing(&base_file, None);
@@ -730,7 +824,7 @@ mod tests {
mgr.store().insert(&disk).unwrap();
// GC should NOT delete the snapshot (kind=Snapshot is excluded from GC)
- mgr.try_gc_base(&base_id("snap0001"));
+ mgr.try_gc_base(&base_id("snap0001"), &dir.path().join("boxes"));
assert!(
mgr.store()
@@ -744,7 +838,7 @@ mod tests {
#[test]
fn test_try_gc_base_preserves_with_dependents() {
- let (_dir, mgr) = setup();
+ let (dir, mgr) = setup();
let base_file = mgr.bases_dir.join("shared01.qcow2");
write_qcow2_with_backing(&base_file, None);
@@ -773,7 +867,7 @@ mod tests {
// Remove clone-1's ref: base should survive (clone-2 still depends)
mgr.store().remove_all_refs_for_box("clone-1").unwrap();
- mgr.try_gc_base(&base_id("shared01"));
+ mgr.try_gc_base(&base_id("shared01"), &dir.path().join("boxes"));
assert!(
mgr.store()
@@ -786,7 +880,7 @@ mod tests {
// Remove clone-2's ref: now base should be GC'd
mgr.store().remove_all_refs_for_box("clone-2").unwrap();
- mgr.try_gc_base(&base_id("shared01"));
+ mgr.try_gc_base(&base_id("shared01"), &dir.path().join("boxes"));
assert!(
mgr.store()
diff --git a/src/boxlite/src/disk/mod.rs b/src/boxlite/src/disk/mod.rs
index 1f82d791b..3f3b0fb60 100644
--- a/src/boxlite/src/disk/mod.rs
+++ b/src/boxlite/src/disk/mod.rs
@@ -194,6 +194,36 @@ impl From<&Disk> for DiskInfo {
}
}
+/// Copy the writable QCOW2 layer to a destination reserved by the caller.
+pub(crate) fn copy_qcow2(source: &Path, dest: &Path) -> BoxliteResult<DiskInfo> {
+ fn backing(path: &Path) -> BoxliteResult<Option<PathBuf>> {
+ let Some(backing) = read_backing_file_path(path)? else {
+ return Ok(None);
+ };
+ let backing = PathBuf::from(backing);
+ if !backing.is_absolute() {
+ return Err(BoxliteError::Unsupported(
+ "online disk copy requires an absolute QCOW2 backing path".into(),
+ ));
+ }
+ Ok(Some(backing.canonicalize()?))
+ }
+
+ let container_disk_bytes = Qcow2Helper::qcow2_virtual_size(source)?;
+ let source_backing = backing(source)?;
+ let size_bytes = std::fs::copy(source, dest)?;
+ if backing(dest)? != source_backing {
+ return Err(BoxliteError::Storage(
+ "disk copy has a different backing path".into(),
+ ));
+ }
+ Ok(DiskInfo {
+ base_path: dest.to_string_lossy().into_owned(),
+ container_disk_bytes,
+ size_bytes,
+ })
+}
+
/// Fork a qcow2 disk: move original to a new location, create COW child at the original path.
///
/// This is the atomic "make immutable base + keep running" operation:
diff --git a/src/boxlite/src/disk/qcow2.rs b/src/boxlite/src/disk/qcow2.rs
index 2fa7c3022..427f7399f 100644
--- a/src/boxlite/src/disk/qcow2.rs
+++ b/src/boxlite/src/disk/qcow2.rs
@@ -1156,6 +1156,35 @@ fn has_qcow2_magic(path: &Path) -> BoxliteResult<bool> {
}
}
+/// Test a chain against a canonical candidate without treating failed reads as a negative.
+pub(super) fn chain_references(root: &Path, candidate: &Path) -> BoxliteResult<bool> {
+ let mut current = root.to_owned();
+ let mut seen = std::collections::HashSet::new();
+ loop {
+ let canonical = current.canonicalize()?;
+ if canonical == candidate {
+ return Ok(true);
+ }
+ if !seen.insert(canonical) || !current.metadata()?.is_file() {
+ return Err(BoxliteError::Storage(format!(
+ "Cannot verify QCOW2 backing chain at {}",
+ current.display()
+ )));
+ }
+ // Managed roots are QCOW2; their backing chains can terminate in raw images.
+ if current != root
+ && !current.extension().is_some_and(|ext| ext == "qcow2")
+ && !has_qcow2_magic(&current)?
+ {
+ return Ok(false);
+ }
+ let Some(backing) = read_backing_file_path(&current)? else {
+ return Ok(false);
+ };
+ current.set_file_name(backing);
+ }
+}
+
/// Check if `target` appears in the backing chain of `chain_root`.
///
/// Walks the full qcow2 backing chain from `chain_root` and returns `true`
diff --git a/src/boxlite/src/litebox/box_impl.rs b/src/boxlite/src/litebox/box_impl.rs
index 9deae5b2c..590b47815 100644
--- a/src/boxlite/src/litebox/box_impl.rs
+++ b/src/boxlite/src/litebox/box_impl.rs
@@ -1643,6 +1643,15 @@ impl BoxImpl {
self.with_operation(self.quiesce_inner(fut)).await
}
+ /// The caller holds lifecycle admission. A synchronous copy keeps SIGSTOP
+ /// and SIGCONT in the same poll of the calling task.
+ pub(super) async fn copy_with_quiesce<R>(
+ &self,
+ copy: impl FnOnce() -> BoxliteResult<R>,
+ ) -> BoxliteResult<R> {
+ self.quiesce_inner(async { copy() }).await
+ }
+
async fn quiesce_inner<Fut, R>(&self, fut: Fut) -> BoxliteResult<R>
where
Fut: Future<Output = BoxliteResult<R>>,
diff --git a/src/boxlite/src/litebox/box_impl/tests/operation_lock.rs b/src/boxlite/src/litebox/box_impl/tests/operation_lock.rs
index 30205e794..21877bb27 100644
--- a/src/boxlite/src/litebox/box_impl/tests/operation_lock.rs
+++ b/src/boxlite/src/litebox/box_impl/tests/operation_lock.rs
@@ -530,61 +530,6 @@ async fn implicit_job_rechecks_after_admission() {
);
}
-#[tokio::test]
-async fn disk_lock_serializes_snapshot_markers_across_handles() {
- let home = TempDir::new_in("/tmp").unwrap();
- let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
- home_dir: home.path().to_owned(),
- ..Default::default()
- })
- .unwrap();
- let a = runtime
- .create(
- BoxOptions {
- auto_delete: Some(0),
- ..Default::default()
- },
- None,
- )
- .await
- .unwrap();
- a.stop().await.unwrap();
- let b = runtime.get(a.id().as_str()).await.unwrap().unwrap();
- assert!(!Arc::ptr_eq(&a.box_backend, &b.box_backend));
- let bx = Arc::clone(&a.box_backend)
- .as_any_arc()
- .downcast::<BoxImpl>()
- .ok()
- .unwrap();
- std::fs::create_dir_all(&bx.config.box_home).unwrap();
- let locker = runtime
- .lock_manager
- .retrieve(bx.state.read().lock_id.unwrap())
- .unwrap();
- let lifecycle = LockGuard::new(locker.as_ref());
- let snapshots_a = a.snapshots();
- let snapshots_b = b.snapshots();
- let mut first = Box::pin(snapshots_a.create(Default::default(), "first"));
- let mut second = Box::pin(snapshots_b.create(Default::default(), "second"));
- assert!(futures::poll!(&mut first).is_pending());
- let marker_path = bx.config.box_home.join(".snapshot_pending");
- let read_marker = || -> serde_json::Value {
- serde_json::from_slice(&std::fs::read(&marker_path).unwrap()).unwrap()
- };
- let expected = bx.config.box_home.join("snapshots/first");
- assert_eq!(
- read_marker()["snapshot_dir"],
- expected.to_string_lossy().as_ref()
- );
- assert!(futures::poll!(&mut second).is_pending());
- let marker = read_marker();
- // Cancel both waiters before releasing lifecycle admission, even on failure.
- drop(first);
- drop(second);
- drop(lifecycle);
- assert_eq!(marker["snapshot_dir"], expected.to_string_lossy().as_ref());
-}
-
fn disk_test_backend(handle: &crate::LiteBox) -> Arc<BoxImpl> {
Arc::clone(&handle.box_backend)
.as_any_arc()
@@ -918,9 +863,20 @@ fn snapshot_restore_test_disk(bx: &BoxImpl) -> std::path::PathBuf {
crate::disk::Qcow2Helper::create_disk(&disk, true)
.unwrap()
.leak();
+ let snapshot_dir = crate::litebox::snapshot_mgr::SnapshotManager::reserve_directory(
+ &bx.config.box_home,
+ "restore-point",
+ )
+ .unwrap()
+ .keep();
bx.runtime
.snapshot_mgr
- .create(&bx.config.box_home, "restore-point", bx.id().as_str())
+ .create(
+ &bx.config.box_home,
+ &snapshot_dir,
+ "restore-point",
+ bx.id().as_str(),
+ )
.unwrap();
// Distinguish the current disk from the COW child restore would create.
std::fs::write(&disk, b"current disk must survive rejected restore").unwrap();
@@ -1094,6 +1050,195 @@ fn assert_disk_admission_released(bx: &BoxImpl) {
assert!(LockGuard::try_new(lifecycle.as_ref()).is_some());
}
+async fn remove_clone_while_sibling_is_registering(moved: bool) {
+ use crate::disk::{BackingFormat, Qcow2Helper, read_backing_chain};
+ use crate::lock::OwnedLockGuard;
+ use crate::runtime::options::VolumeSpec;
+ use crate::runtime::rt_impl::CloneDependency;
+
+ let fixture = running_box_for_start_test(Arc::new(StartGate::default())).await;
+ let bx = &fixture.box_impl;
+ let shim = ChildGuard(
+ std::process::Command::new("sleep")
+ .arg("60")
+ .spawn()
+ .unwrap(),
+ );
+ bx.state.write().set_pid(Some(shim.0.id()));
+ bx.runtime
+ .box_manager
+ .save_box(bx.id(), &bx.state.read())
+ .unwrap();
+ create_disk_for_test(bx);
+ let clone = bx.clone_box(Default::default(), None).await.unwrap();
+ let child_disk = disk_test_backend(&clone)
+ .config
+ .box_home
+ .join("disks/disk.qcow2");
+ let base = read_backing_chain(&child_disk).pop().unwrap();
+ let record = bx
+ .runtime
+ .base_disk_mgr
+ .store()
+ .find_by_base_path(base.to_str().unwrap())
+ .unwrap()
+ .unwrap();
+ let source_admission = Arc::new(OwnedLockGuard::new_async(bx.disk_locker().unwrap()).await);
+ let stage = TempDir::new_in(bx.runtime.layout.boxes_dir()).unwrap();
+ let staged = stage.path().join("disks/disk.qcow2");
+ std::fs::create_dir(staged.parent().unwrap()).unwrap();
+ Qcow2Helper::create_cow_child_disk(
+ &base,
+ BackingFormat::Qcow2,
+ &staged,
+ record.container_disk_bytes(),
+ )
+ .unwrap()
+ .leak();
+
+ let volume = bx
+ .runtime
+ .local_volume_store
+ .create(Some("blocked"))
+ .unwrap();
+ let mut options = bx.config.options.clone();
+ options.volumes = vec![VolumeSpec::managed_volume(&volume.id, "/data")];
+ // The registry lock pauses the real persistence worker after the directory move.
+ let lock_file =
+ std::fs::File::open(bx.runtime.layout.volumes_dir().join(".registry.lock")).unwrap();
+ let gate = nix::fcntl::Flock::lock(lock_file, nix::fcntl::FlockArg::LockExclusive).unwrap();
+ let mut publish = Box::pin(bx.runtime.provision_box(
+ stage.path().to_owned(),
+ Some("sibling".into()),
+ options,
+ BoxStatus::Stopped,
+ None,
+ Some(CloneDependency {
+ base_disk_id: record.id().clone(),
+ source_admission: source_admission.clone(),
+ }),
+ ));
+ if moved {
+ assert!(futures::poll!(&mut publish).is_pending());
+ }
+ assert_eq!(staged.exists(), !moved);
+ bx.runtime.remove_box(clone.id(), false).unwrap();
+ assert!(
+ base.exists(),
+ "GC deleted a base while the creating source was admitted"
+ );
+
+ drop(gate);
+ let sibling = publish.await.unwrap();
+ let sibling_disk = disk_test_backend(&sibling)
+ .config
+ .box_home
+ .join("disks/disk.qcow2");
+ assert_eq!(read_backing_chain(&sibling_disk), vec![base.clone()]);
+ drop(source_admission);
+ bx.runtime.remove_box(sibling.id(), false).unwrap();
+ assert!(
+ !base.exists(),
+ "the last registered clone released the base"
+ );
+}
+
+#[tokio::test]
+async fn clone_gc_preserves_a_staged_siblings_base() {
+ remove_clone_while_sibling_is_registering(false).await;
+}
+
+#[tokio::test]
+async fn clone_gc_preserves_an_uncommitted_siblings_base() {
+ remove_clone_while_sibling_is_registering(true).await;
+}
+
+#[tokio::test]
+async fn clone_gc_preserves_a_base_used_only_by_another_base() {
+ let home = TempDir::new().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_owned(),
+ ..Default::default()
+ })
+ .unwrap();
+ let root = persistent_disk_test_box(&runtime).await;
+ create_disk_for_test(&disk_test_backend(&root));
+ let child = root.clone_box(Default::default(), None).await.unwrap();
+ let grandchild = child.clone_box(Default::default(), None).await.unwrap();
+ let disk = disk_test_backend(&grandchild)
+ .config
+ .box_home
+ .join("disks/disk.qcow2");
+ let chain = crate::disk::read_backing_chain(&disk);
+ assert_eq!(chain.len(), 2);
+
+ runtime.remove_box(root.id(), true).unwrap();
+ runtime.remove_box(child.id(), true).unwrap();
+
+ assert_eq!(
+ crate::disk::read_backing_chain(&disk),
+ chain,
+ "removing a clone broke the surviving grandchild's backing chain"
+ );
+ runtime.remove_box(grandchild.id(), false).unwrap();
+ assert!(chain.iter().all(|path| !path.exists()));
+}
+
+async fn remove_clone_with_snapshot_dependency(unreadable_header: bool) {
+ use crate::disk::{copy_qcow2, read_backing_chain};
+ use crate::litebox::snapshot_mgr::SnapshotManager;
+
+ let home = TempDir::new().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_owned(),
+ ..Default::default()
+ })
+ .unwrap();
+ let root = persistent_disk_test_box(&runtime).await;
+ create_disk_for_test(&disk_test_backend(&root));
+ let child = root.clone_box(Default::default(), None).await.unwrap();
+ let child_disk = disk_test_backend(&child)
+ .config
+ .box_home
+ .join("disks/disk.qcow2");
+
+ let keeper = persistent_disk_test_box(&runtime).await;
+ let keeper_home = &disk_test_backend(&keeper).config.box_home;
+ let keeper_disk = keeper_home.join("disks/disk.qcow2");
+ std::fs::create_dir_all(keeper_disk.parent().unwrap()).unwrap();
+ copy_qcow2(&child_disk, &keeper_disk).unwrap();
+ let copy = runtime
+ .snapshot_mgr
+ .prepare_copy(keeper_home, "saved", keeper.id().as_str())
+ .unwrap();
+ let copy = SnapshotManager::copy_disk(copy).unwrap();
+ let saved = runtime.snapshot_mgr.publish_copy(copy).unwrap();
+ std::fs::remove_file(&keeper_disk).unwrap();
+ create_disk_for_test(&disk_test_backend(&keeper));
+
+ let chain = read_backing_chain(saved.disk_info.as_path());
+ assert_eq!(chain.len(), 1);
+ if unreadable_header {
+ std::fs::write(saved.disk_info.as_path(), b"QFI\xfb").unwrap();
+ }
+ runtime.remove_box(child.id(), false).unwrap();
+ runtime.remove_box(root.id(), true).unwrap();
+ assert!(
+ chain[0].exists(),
+ "deleting the last registered user broke a retained snapshot"
+ );
+}
+
+#[tokio::test]
+async fn clone_gc_preserves_a_base_used_only_by_a_snapshot() {
+ remove_clone_with_snapshot_dependency(false).await;
+}
+
+#[tokio::test]
+async fn clone_gc_preserves_a_base_if_a_snapshot_header_is_unreadable() {
+ remove_clone_with_snapshot_dependency(true).await;
+}
+
#[tokio::test]
async fn batch_clone_shares_base_and_records_refs_until_last_removal() {
enable_disk_operation_logs();
@@ -1452,6 +1597,33 @@ async fn export_cancellation_and_phase_errors_release_admissions() {
);
}
+#[tokio::test]
+async fn stopped_snapshot_preserves_unregistered_destination() {
+ let home = TempDir::new_in("/tmp").unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_owned(),
+ ..Default::default()
+ })
+ .unwrap();
+ let source = persistent_disk_test_box(&runtime).await;
+ let bx = disk_test_backend(&source);
+ let active_disk = create_disk_for_test(&bx);
+ let original_disk = std::fs::read(&active_disk).unwrap();
+ let existing_disk = bx.config.box_home.join("snapshots/point/disk.qcow2");
+ std::fs::create_dir_all(existing_disk.parent().unwrap()).unwrap();
+ std::fs::write(&existing_disk, b"interrupted copy").unwrap();
+
+ let snapshots = source.snapshots();
+ assert!(matches!(
+ snapshots.create(Default::default(), "point").await,
+ Err(BoxliteError::AlreadyExists(_))
+ ));
+ assert_eq!(std::fs::read(&existing_disk).unwrap(), b"interrupted copy");
+ assert_eq!(std::fs::read(&active_disk).unwrap(), original_disk);
+ assert!(snapshots.list().await.unwrap().is_empty());
+ assert!(!bx.config.box_home.join(".snapshot_pending").exists());
+}
+
#[tokio::test]
async fn snapshot_create_restore_remove_and_marker_failure_release_admission() {
enable_disk_operation_logs();
diff --git a/src/boxlite/src/litebox/box_impl/tests/resize.rs b/src/boxlite/src/litebox/box_impl/tests/resize.rs
index 1ac347a56..5cd42cae0 100644
--- a/src/boxlite/src/litebox/box_impl/tests/resize.rs
+++ b/src/boxlite/src/litebox/box_impl/tests/resize.rs
@@ -428,6 +428,18 @@ async fn clone_copy_uses_latest_saved_disk_size() {
);
}
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn online_capture_clones_from_local_set() {
+ let (fixture, _shim) = copy_fixture().await;
+ let local = tokio::task::LocalSet::new();
+ let clone = local
+ .run_until(fixture.bx.clone_box(Default::default(), None))
+ .await
+ .unwrap();
+ assert_ne!(fixture.bx.id(), clone.id());
+ assert_eq!(fixture.inner.state.read().status, BoxStatus::Running);
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn resize_persists_after_guest_success_when_caller_cancels() {
let gate = GuestGate::new();
diff --git a/src/boxlite/src/litebox/clone_export.rs b/src/boxlite/src/litebox/clone_export.rs
index 92259a241..58043a6fc 100644
--- a/src/boxlite/src/litebox/clone_export.rs
+++ b/src/boxlite/src/litebox/clone_export.rs
@@ -59,10 +59,8 @@ impl BoxImpl {
/// Batch clone: create N clones sharing a single base disk layer.
///
- /// Three-phase flow (snapshot-as-base):
- /// A. Inside quiesce bracket (VM paused): create disk layer (rename + COW child).
- /// B. Outside quiesce bracket (VM resumed): create N thin overlay headers.
- /// C. Provision each clone atomically with its layer dependency.
+ /// Copy the running box's top layer under quiesce, or fork the disk of a stopped box.
+ /// Then create N thin overlays and provision each clone with its layer dependency.
pub(crate) async fn clone_boxes(
&self,
_options: crate::runtime::options::CloneOptions,
@@ -97,29 +95,39 @@ impl BoxImpl {
)));
}
- // Phase A: Create shared base layer inside quiesce bracket (VM paused).
- // This is the same operation as snapshot creation: rename + COW child.
- let source_box_id = self.id().to_string();
- let layer = {
- let src_disks = src_disks.clone();
- let source_box_id = source_box_id.clone();
-
- self.with_quiesce_async(async {
- rt.base_disk_mgr.create_base_disk(
- &src_disks,
- BaseDiskKind::CloneBase,
- None,
- &source_box_id,
- )
+ let layer = self
+ .with_operation(async {
+ let status = self.state.read().status;
+ let base_manager = &rt.base_disk_mgr;
+ match status {
+ BoxStatus::Running => {
+ let (id, file) = base_manager.reserve_clone_base()?;
+ let disk_info = self
+ .copy_with_quiesce(|| {
+ crate::disk::copy_qcow2(&src_container, file.path())
+ })
+ .await?;
+ base_manager.publish_clone_base(id, file, disk_info, self.id().as_str())
+ }
+ BoxStatus::Paused | BoxStatus::Stopping | BoxStatus::Unknown => {
+ Err(BoxliteError::InvalidState(format!(
+ "cannot clone a box in state {status}; stop the box first"
+ )))
+ }
+ _ => base_manager.create_base_disk(
+ &src_disks,
+ BaseDiskKind::CloneBase,
+ None,
+ self.id().as_str(),
+ ),
+ }
})
- .await?
- };
+ .await?;
// base_path is a flat file (e.g., bases/{nanoid}.qcow2)
let shared_container = layer.disk_info.to_path_buf();
- // Read virtual size from the shared base for overlay creation.
- let container_vsize = Qcow2Helper::qcow2_virtual_size(&shared_container)?;
+ let container_vsize = layer.disk_info.container_disk_bytes;
// Before any staging directory exists: once one does, a caller that
// gives up must still get its clone, so nothing may await between
// staging and provisioning.
diff --git a/src/boxlite/src/litebox/local_snapshot.rs b/src/boxlite/src/litebox/local_snapshot.rs
index 091f62446..4c827a2f0 100644
--- a/src/boxlite/src/litebox/local_snapshot.rs
+++ b/src/boxlite/src/litebox/local_snapshot.rs
@@ -11,7 +11,8 @@ use boxlite_shared::errors::{BoxliteError, BoxliteResult};
use crate::disk::constants::filenames as disk_filenames;
use crate::litebox::box_impl::BoxImpl;
-use crate::litebox::snapshot_mgr::{SnapshotInfo, validate_snapshot_name};
+use crate::litebox::snapshot_mgr::{SnapshotInfo, SnapshotManager, validate_snapshot_name};
+use crate::litebox::state::BoxStatus;
use crate::runtime::options::SnapshotOptions;
pub(crate) struct LocalSnapshotBackend {
@@ -31,7 +32,7 @@ impl LocalSnapshotBackend {
validate_snapshot_name(name)?;
let t0 = Instant::now();
self.inner
- .with_disk_admission(async {
+ .with_disk_admission(self.inner.with_operation(async {
let box_id = self.inner.id().as_str();
let snap_mgr = &self.inner.runtime.snapshot_mgr;
@@ -43,30 +44,23 @@ impl LocalSnapshotBackend {
)));
}
- // Write crash-recovery marker before moving disks (point of no return).
- let box_home = &self.inner.config.box_home;
- let disks_dir = box_home.join("disks");
- let container_disk = disks_dir.join(disk_filenames::CONTAINER_DISK);
- let pending_marker = box_home.join(".snapshot_pending");
- let snapshot_dir = box_home.join("snapshots").join(name);
- let marker_data = serde_json::json!({
- "snapshot_dir": snapshot_dir.to_string_lossy(),
- "container_disk": container_disk.to_string_lossy(),
- });
- std::fs::write(&pending_marker, marker_data.to_string()).map_err(|e| {
- BoxliteError::Storage(format!("Failed to write snapshot marker: {}", e))
- })?;
-
- // Quiesce VM for point-in-time snapshot consistency.
- let result = self
- .inner
- .with_quiesce_async(async { snap_mgr.create(box_home, name, box_id) })
- .await;
-
- // Remove marker on success.
- let _ = std::fs::remove_file(&pending_marker);
-
- let info = result?;
+ let status = self.inner.state.read().status;
+ let info = match status {
+ BoxStatus::Running
+ if self.inner.config.engine_kind == crate::vmm::VmmKind::Libkrun =>
+ {
+ self.create_online(name).await?
+ }
+ BoxStatus::Running
+ | BoxStatus::Paused
+ | BoxStatus::Stopping
+ | BoxStatus::Unknown => {
+ return Err(BoxliteError::InvalidState(format!(
+ "cannot snapshot a box in state {status}; stop the box first"
+ )));
+ }
+ _ => self.create_offline(name)?,
+ };
tracing::info!(
box_id = %self.inner.id(),
@@ -75,12 +69,60 @@ impl LocalSnapshotBackend {
elapsed_ms = t0.elapsed().as_millis() as u64,
"Created snapshot"
);
-
Ok(info)
- })
+ }))
.await
}
+ async fn create_online(&self, name: &str) -> BoxliteResult<SnapshotInfo> {
+ let manager = &self.inner.runtime.snapshot_mgr;
+ let copy =
+ manager.prepare_copy(&self.inner.config.box_home, name, self.inner.id().as_str())?;
+ let copy = self
+ .inner
+ .copy_with_quiesce(|| SnapshotManager::copy_disk(copy))
+ .await?;
+ manager.publish_copy(copy)
+ }
+
+ fn create_offline(&self, name: &str) -> BoxliteResult<SnapshotInfo> {
+ let box_id = self.inner.id().as_str();
+ let snap_mgr = &self.inner.runtime.snapshot_mgr;
+ let box_home = &self.inner.config.box_home;
+ if crate::util::PidFileReader::at(box_home.join("shim.pid")).process_identity()
+ != crate::util::ProcessIdentity::Absent
+ {
+ return Err(BoxliteError::InvalidState(
+ "disk snapshot requires a stopped shim".into(),
+ ));
+ }
+
+ let snapshot_dir = SnapshotManager::reserve_directory(box_home, name)?;
+ // Write the recovery marker before moving the disk into the reserved directory.
+ let disks_dir = box_home.join("disks");
+ let container_disk = disks_dir.join(disk_filenames::CONTAINER_DISK);
+ let pending_marker = box_home.join(".snapshot_pending");
+ let marker_data = serde_json::json!({
+ "snapshot_dir": snapshot_dir.path().to_string_lossy(),
+ "container_disk": container_disk.to_string_lossy(),
+ });
+ std::fs::write(&pending_marker, marker_data.to_string()).map_err(|e| {
+ BoxliteError::Storage(format!("Failed to write snapshot marker: {}", e))
+ })?;
+
+ // A partially completed fork can leave the original disk in this directory.
+ let snapshot_dir = snapshot_dir.keep();
+ let result = snap_mgr.create(box_home, &snapshot_dir, name, box_id);
+ if result.is_err() {
+ let _ = std::fs::remove_dir(&snapshot_dir);
+ }
+
+ // The stopped snapshot call has returned.
+ let _ = std::fs::remove_file(&pending_marker);
+
+ result
+ }
+
async fn snapshot_list(&self) -> BoxliteResult<Vec<SnapshotInfo>> {
let box_id = self.inner.id().as_str();
self.inner.runtime.snapshot_mgr.list(box_id)
@@ -348,6 +390,8 @@ pub(crate) fn recover_pending_snapshot(box_home: &Path) {
mod tests {
use super::*;
+ mod marker;
+
// ── recover_pending_snapshot tests ────────────────────────────────
#[test]
diff --git a/src/boxlite/src/litebox/local_snapshot/tests/marker.rs b/src/boxlite/src/litebox/local_snapshot/tests/marker.rs
new file mode 100644
index 000000000..149e92402
--- /dev/null
+++ b/src/boxlite/src/litebox/local_snapshot/tests/marker.rs
@@ -0,0 +1,83 @@
+use super::*;
+use crate::disk::{Qcow2Helper, read_backing_chain};
+use crate::lock::LockGuard;
+use crate::runtime::options::{BoxOptions, BoxliteOptions};
+use crate::runtime::rt_impl::RuntimeImpl;
+use std::time::Duration;
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn disk_lock_serializes_snapshot_markers_across_handles() {
+ let home = tempfile::tempdir_in("/tmp").unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_owned(),
+ ..Default::default()
+ })
+ .unwrap();
+ let a = runtime
+ .create(
+ BoxOptions {
+ auto_delete: Some(0),
+ ..Default::default()
+ },
+ None,
+ )
+ .await
+ .unwrap();
+ a.stop().await.unwrap();
+ let b = runtime.get(a.id().as_str()).await.unwrap().unwrap();
+ assert!(!Arc::ptr_eq(&a.box_backend, &b.box_backend));
+ let bx = b
+ .box_backend
+ .clone()
+ .as_any_arc()
+ .downcast::<BoxImpl>()
+ .ok()
+ .unwrap();
+ let disk = bx.config.box_home.join("disks/disk.qcow2");
+ Qcow2Helper::create_disk(&disk, true).unwrap().leak();
+ let snapshots_dir = bx.config.box_home.join("snapshots");
+ let first_dir = snapshots_dir.join("first");
+ let first_disk = first_dir.join("disk.qcow2");
+ let marker = bx.config.box_home.join(".snapshot_pending");
+
+ // WAL permits snapshot reads and the disk fork, but holds the first INSERT.
+ let mut db = rusqlite::Connection::open(runtime.layout.db_dir().join("boxlite.db")).unwrap();
+ let writer = db
+ .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
+ .unwrap();
+ let first =
+ tokio::spawn(async move { a.snapshots().create(Default::default(), "first").await });
+ tokio::time::timeout(Duration::from_secs(10), async {
+ while !first_disk.exists() {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("first snapshot did not reach the disk fork");
+
+ let locker = bx.disk_locker().unwrap();
+ assert!(LockGuard::try_new(locker.as_ref()).is_none());
+ let snapshots = b.snapshots();
+ let mut second = Box::pin(snapshots.create(Default::default(), "second"));
+ assert!(futures::poll!(&mut second).is_pending());
+ let pending: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(&marker).unwrap()).unwrap();
+ assert_eq!(pending["snapshot_dir"], first_dir.to_str().unwrap());
+ assert!(!snapshots_dir.join("second").exists());
+
+ writer.commit().unwrap();
+ let (first, second) = tokio::time::timeout(Duration::from_secs(10), async {
+ tokio::try_join!(async { first.await.unwrap() }, second)
+ })
+ .await
+ .expect("snapshot requests stalled after releasing the database writer")
+ .unwrap();
+ assert_eq!(
+ read_backing_chain(&disk),
+ vec![
+ second.disk_info.as_path().canonicalize().unwrap(),
+ first.disk_info.as_path().canonicalize().unwrap(),
+ ]
+ );
+ assert!(!marker.exists());
+}
diff --git a/src/boxlite/src/litebox/snapshot_mgr.rs b/src/boxlite/src/litebox/snapshot_mgr.rs
index 5b615bb55..bf9829bf6 100644
--- a/src/boxlite/src/litebox/snapshot_mgr.rs
+++ b/src/boxlite/src/litebox/snapshot_mgr.rs
@@ -25,7 +25,8 @@
//! The only interaction is that snapshot files may reference clone bases in
//! `bases/` via qcow2 backing chains, which index-find GC accounts for.
-use std::path::Path;
+use std::fs::{self, File};
+use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
@@ -35,6 +36,12 @@ use crate::db::snapshot::SnapshotStore;
use crate::disk::constants::filenames as disk_filenames;
use crate::disk::{BackingFormat, Qcow2Helper};
+pub(crate) struct SnapshotCopy {
+ source: PathBuf,
+ directory: tempfile::TempDir,
+ info: SnapshotInfo,
+}
+
// ============================================================================
// Domain Type
// ============================================================================
@@ -136,16 +143,81 @@ impl SnapshotManager {
self.store.find(box_id, name)
}
- /// Create a snapshot from a box's live container disk.
- ///
- /// 1. Create `box_home/snapshots/{name}/` directory
- /// 2. Read virtual size from container disk
- /// 3. Rename container disk → `snapshots/{name}/disk.qcow2`
- /// 4. Create COW child at original path (box keeps running)
- /// 5. Insert DB record via `SnapshotStore`
- pub(crate) fn create(
+ pub(super) fn reserve_directory(
+ box_home: &Path,
+ name: &str,
+ ) -> BoxliteResult<tempfile::TempDir> {
+ let parent = box_home.join("snapshots");
+ fs::create_dir_all(&parent)?;
+ // Use the exact snapshot name and clean up until the directory is retained.
+ tempfile::Builder::new()
+ .prefix(name)
+ .rand_bytes(0)
+ .tempdir_in(&parent)
+ .map_err(|error| match error.kind() {
+ std::io::ErrorKind::AlreadyExists => BoxliteError::AlreadyExists(format!(
+ "snapshot directory '{}' already exists",
+ parent.join(name).display()
+ )),
+ _ => error.into(),
+ })
+ }
+
+ pub(crate) fn prepare_copy(
+ &self,
+ box_home: &Path,
+ name: &str,
+ box_id: &str,
+ ) -> BoxliteResult<SnapshotCopy> {
+ let source = box_home.join("disks").join(disk_filenames::CONTAINER_DISK);
+ let directory = Self::reserve_directory(box_home, name)?;
+ let path = directory.path().join(disk_filenames::CONTAINER_DISK);
+ let info = SnapshotInfo {
+ id: nanoid::nanoid!(8),
+ box_id: box_id.to_owned(),
+ name: name.to_owned(),
+ created_at: chrono::Utc::now().timestamp(),
+ disk_info: crate::disk::DiskInfo {
+ base_path: path.to_string_lossy().into_owned(),
+ container_disk_bytes: 0,
+ size_bytes: 0,
+ },
+ };
+ Ok(SnapshotCopy {
+ source,
+ directory,
+ info,
+ })
+ }
+
+ pub(crate) fn copy_disk(mut copy: SnapshotCopy) -> BoxliteResult<SnapshotCopy> {
+ copy.info.disk_info = crate::disk::copy_qcow2(&copy.source, copy.info.disk_info.as_path())?;
+ Ok(copy)
+ }
+
+ pub(crate) fn publish_copy(&self, copy: SnapshotCopy) -> BoxliteResult<SnapshotInfo> {
+ File::open(copy.info.disk_info.as_path())?.sync_all()?;
+ // Persist the entry at each level up to the already-created box directory.
+ for dir in copy.directory.path().ancestors().take(3) {
+ File::open(dir)?.sync_all()?;
+ }
+
+ let directory = copy.directory.keep();
+ let info = copy.info;
+ if let Err(error) = self.store.save(&info) {
+ if matches!(self.get(&info.box_id, &info.name), Ok(None)) {
+ let _ = fs::remove_dir_all(&directory);
+ }
+ return Err(error);
+ }
+ Ok(info)
+ }
+
+ /// Move a stopped box's disk into its reserved snapshot directory and register it.
+ pub(super) fn create(
&self,
box_home: &Path,
+ snapshot_dir: &Path,
name: &str,
box_id: &str,
) -> BoxliteResult<SnapshotInfo> {
@@ -159,23 +231,13 @@ impl SnapshotManager {
)));
}
- // 1. Create snapshot directory
- let snapshot_dir = box_home.join("snapshots").join(name);
- std::fs::create_dir_all(&snapshot_dir).map_err(|e| {
- BoxliteError::Storage(format!(
- "Failed to create snapshot directory {}: {}",
- snapshot_dir.display(),
- e
- ))
- })?;
-
- // 2-4. Fork: move container → snapshot dir, create COW child at original path
+ // Move the disk into the snapshot and create a COW child at the original path.
let snap_disk = snapshot_dir.join(disk_filenames::CONTAINER_DISK);
let forked = crate::disk::fork_qcow2(&container_disk, &snap_disk)?;
let disk_info = crate::disk::DiskInfo::from(&forked);
// forked is persistent (won't be deleted on drop)
- // 5. Insert DB record
+ // Register the new snapshot.
let snapshot_id = nanoid::nanoid!(8);
let now = chrono::Utc::now().timestamp();
let info = SnapshotInfo {
@@ -363,6 +425,69 @@ impl SnapshotManager {
mod tests {
use super::*;
+ #[test]
+ fn test_snapshot_copy_publication_and_cleanup() {
+ let home = tempfile::tempdir().unwrap();
+ let manager = SnapshotManager::new(SnapshotStore::new(
+ crate::db::Database::open(&home.path().join("boxlite.db")).unwrap(),
+ ));
+ let source = home
+ .path()
+ .join("disks")
+ .join(disk_filenames::CONTAINER_DISK);
+ Qcow2Helper::create_disk(&source, true).unwrap();
+
+ let copy = manager
+ .prepare_copy(home.path(), "published", "box")
+ .unwrap();
+ let copy = SnapshotManager::copy_disk(copy).unwrap();
+ assert!(manager.get("box", "published").unwrap().is_none());
+ let published = manager.publish_copy(copy).unwrap();
+ assert_eq!(
+ published.disk_info.as_path(),
+ home.path().join("snapshots/published/disk.qcow2")
+ );
+ assert_eq!(
+ manager.get("box", "published").unwrap().unwrap().id,
+ published.id
+ );
+
+ let interrupted = manager
+ .prepare_copy(home.path(), "interrupted", "box")
+ .unwrap();
+ let interrupted = SnapshotManager::copy_disk(interrupted).unwrap();
+ let interrupted_path = interrupted
+ .directory
+ .keep()
+ .join(disk_filenames::CONTAINER_DISK);
+ assert!(manager.get("box", "interrupted").unwrap().is_none());
+ assert!(matches!(
+ manager.prepare_copy(home.path(), "interrupted", "box"),
+ Err(BoxliteError::AlreadyExists(_))
+ ));
+ assert!(interrupted_path.is_file());
+ assert!(published.disk_info.as_path().is_file());
+
+ let copy = manager
+ .prepare_copy(home.path(), "copy-error", "box")
+ .unwrap();
+ let obstructed_path = copy.info.disk_info.to_path_buf();
+ fs::create_dir(&obstructed_path).unwrap();
+ assert!(SnapshotManager::copy_disk(copy).is_err());
+ assert!(!obstructed_path.exists());
+ assert!(manager.get("box", "copy-error").unwrap().is_none());
+
+ let copy = manager
+ .prepare_copy(home.path(), "cancelled", "box")
+ .unwrap();
+ let copy = SnapshotManager::copy_disk(copy).unwrap();
+ let cancelled_path = copy.info.disk_info.to_path_buf();
+ drop(copy);
+ assert!(manager.get("box", "cancelled").unwrap().is_none());
+ assert!(!cancelled_path.exists());
+ assert!(source.exists());
+ }
+
// ── validate_snapshot_name tests ──────────────────────────────────
#[test]
diff --git a/src/boxlite/src/runtime/rt_impl.rs b/src/boxlite/src/runtime/rt_impl.rs
index d0a6059a9..a30e37ca6 100644
--- a/src/boxlite/src/runtime/rt_impl.rs
+++ b/src/boxlite/src/runtime/rt_impl.rs
@@ -1220,7 +1220,7 @@ impl RuntimeImpl {
// 4. GC each affected base (may cascade to parents)
for base_id in affected_base_ids {
- self.base_disk_mgr.try_gc_base(&base_id);
+ self.gc_removed_box_base(id, &base_id);
}
// Invalidate cache (removes from in-memory maps)
@@ -1248,6 +1248,62 @@ impl RuntimeImpl {
Err(BoxliteError::NotFound(id.to_string()))
}
+ /// Other boxes can fork or move a backing file between directories. Keep their
+ /// disk admissions stable from the first header read through the final unlink.
+ /// Removal owns the victim's admission; a busy clone keeps its creator's admission
+ /// through registration, even if its client has dropped the request.
+ fn gc_removed_box_base(&self, removed: &BoxID, base_id: &crate::BaseDiskID) {
+ let store = self.base_disk_mgr.store();
+ if store.has_dependents(base_id).unwrap_or(true) {
+ return;
+ }
+ let Ok(Some(base)) = store.find_by_id(base_id) else {
+ return;
+ };
+
+ let disk_admissions = || -> Option<Vec<_>> {
+ let mut admissions: Vec<_> = self
+ .box_manager
+ .all_boxes(true)
+ .ok()?
+ .into_iter()
+ .filter(|(config, _)| &config.id != removed)
+ .map(|(config, state)| Some((config.id, state.lock_id?)))
+ .collect::<Option<_>>()?;
+ if let Some(creator) = admissions
+ .iter()
+ .position(|(id, _)| id.as_str() == base.source_box_id())
+ {
+ admissions.swap(0, creator);
+ }
+ Some(admissions)
+ };
+ let Some(admissions) = disk_admissions() else {
+ return;
+ };
+ let Some(lockers) = admissions
+ .iter()
+ .map(|(_, id)| self.disk_lock_manager.retrieve(*id).ok())
+ .collect::<Option<Vec<_>>>()
+ else {
+ return;
+ };
+ let Some(_guards) = lockers
+ .iter()
+ .map(|locker| crate::lock::ReadLockGuard::try_new(locker.as_ref()))
+ .collect::<Option<Vec<_>>>()
+ else {
+ return;
+ };
+
+ // A clone can commit or a lock ID can be recycled while acquiring the guards.
+ if disk_admissions().as_ref() != Some(&admissions) {
+ return;
+ }
+ let boxes_dir = self.layout.boxes_dir();
+ self.base_disk_mgr.try_gc_base(base_id, &boxes_dir);
+ }
+
/// Caller must hold this box's lifecycle and disk write admissions and pass
/// its refreshed config/state and the admitted lock ID.
pub(crate) fn remove_box_holding_admissions(
@@ -1318,7 +1374,7 @@ impl RuntimeImpl {
// 4. GC each affected base (may cascade to parents)
for base_id in affected_base_ids {
- self.base_disk_mgr.try_gc_base(&base_id);
+ self.gc_removed_box_base(id, &base_id);
}
// Delete box directory + its socket binding symlink
diff --git a/src/boxlite/tests/snapshot_clone_deep.rs b/src/boxlite/tests/snapshot_clone_deep.rs
index 8fff80918..836e9372f 100644
--- a/src/boxlite/tests/snapshot_clone_deep.rs
+++ b/src/boxlite/tests/snapshot_clone_deep.rs
@@ -702,6 +702,8 @@ async fn test_snapshot_remove_middle_of_three() {
#[tokio::test]
async fn test_snapshot_running_box_with_quiesce() {
+ use std::os::unix::fs::MetadataExt;
+
let home = boxlite_test_utils::home::PerTestBoxHome::new();
let runtime = BoxliteRuntime::new(BoxliteOptions {
home_dir: home.path.clone(),
@@ -715,12 +717,30 @@ async fn test_snapshot_running_box_with_quiesce() {
// Write marker data
write_file(&litebox, "/root/marker.txt", "running-snap").await;
- // Snapshot while running (should use quiesce bracket)
- litebox
+ let disk = home
+ .path
+ .join("boxes")
+ .join(litebox.id().as_str())
+ .join("disks/disk.qcow2");
+ let original_inode = std::fs::metadata(&disk).unwrap().ino();
+ let original_pid = litebox.info().await.unwrap().pid;
+ let snapshot = litebox
.snapshots()
.create(SnapshotOptions::default(), "live")
.await
.expect("snapshot on running box should succeed");
+ assert_eq!(
+ std::fs::metadata(&disk).unwrap().ino(),
+ original_inode,
+ "creating an online snapshot replaced the active disk"
+ );
+ assert_ne!(
+ std::fs::metadata(snapshot.disk_info.as_path())
+ .unwrap()
+ .ino(),
+ original_inode
+ );
+ assert_eq!(litebox.info().await.unwrap().pid, original_pid);
// Source still running
assert_eq!(
@@ -732,6 +752,14 @@ async fn test_snapshot_running_box_with_quiesce() {
let out = exec_stdout(&litebox, BoxCommand::new("echo").args(["alive"])).await;
assert_eq!(out.trim(), "alive");
+ write_and_verify(&litebox, "/root/marker.txt", "written-after-snapshot").await;
+ let litebox = stop_and_refresh(&runtime, litebox, "snap-running").await;
+ litebox.snapshots().restore("live").await.unwrap();
+ litebox.start().await.unwrap();
+ assert_eq!(
+ read_file(&litebox, "/root/marker.txt").await,
+ "running-snap"
+ );
litebox.stop().await.unwrap();
let _ = runtime.shutdown(Some(common::TEST_SHUTDOWN_TIMEOUT)).await;
@@ -781,7 +809,9 @@ async fn test_snapshot_remove_while_running() {
})
.expect("create runtime");
- let litebox = create_stopped_box(&runtime, "rm-while-running").await;
+ let litebox = create_running_box(&runtime, "rm-while-running").await;
+ write_file(&litebox, "/root/inherited.txt", "from-v1").await;
+ let litebox = stop_and_refresh(&runtime, litebox, "rm-while-running").await;
// Create v1 while stopped
litebox
@@ -798,23 +828,105 @@ async fn test_snapshot_remove_while_running() {
.await
.unwrap();
- // Try remove v1 while box is running
- // v1 should not be the current backing (v2 is newer), so removal may succeed
- let result = litebox.snapshots().remove("v1").await;
- eprintln!(
- "Remove v1 while running: {}",
- if result.is_ok() {
- "allowed"
- } else {
- "rejected"
- }
+ let error = litebox.snapshots().remove("v1").await.unwrap_err();
+ assert!(
+ error
+ .to_string()
+ .contains("current disk depends on this snapshot")
);
-
+ let litebox = stop_and_refresh(&runtime, litebox, "rm-while-running").await;
+ litebox.snapshots().restore("v2").await.unwrap();
+ litebox.start().await.unwrap();
+ assert_eq!(read_file(&litebox, "/root/inherited.txt").await, "from-v1");
litebox.stop().await.unwrap();
let _ = runtime.shutdown(Some(common::TEST_SHUTDOWN_TIMEOUT)).await;
}
+#[tokio::test]
+async fn test_online_clone_then_snapshot_preserves_original_data() {
+ use std::os::unix::fs::MetadataExt;
+
+ let home = boxlite_test_utils::home::PerTestBoxHome::new();
+ let runtime = BoxliteRuntime::new(BoxliteOptions {
+ home_dir: home.path.clone(),
+ image_registries: common::test_registries(),
+ ..Default::default()
+ })
+ .unwrap();
+ let source = create_running_box(&runtime, "live-clone-source").await;
+ let source_disk = home
+ .path
+ .join("boxes")
+ .join(source.id().as_str())
+ .join("disks/disk.qcow2");
+ let source_inode = std::fs::metadata(&source_disk).unwrap().ino();
+ write_and_verify(&source, "/root/marker.txt", "at-clone").await;
+
+ let clone = source
+ .clone_box(CloneOptions::default(), Some("live-clone".into()))
+ .await
+ .unwrap();
+ assert_eq!(
+ std::fs::metadata(&source_disk).unwrap().ino(),
+ source_inode,
+ "online clone replaced the source box's active disk"
+ );
+ write_and_verify(&source, "/root/marker.txt", "at-snapshot").await;
+ source
+ .snapshots()
+ .create(SnapshotOptions::default(), "after-clone")
+ .await
+ .unwrap();
+ assert_eq!(std::fs::metadata(&source_disk).unwrap().ino(), source_inode);
+ write_and_verify(&source, "/root/marker.txt", "after-snapshot").await;
+
+ let source = stop_and_refresh(&runtime, source, "live-clone-source").await;
+ source.snapshots().restore("after-clone").await.unwrap();
+ source.start().await.unwrap();
+ assert_eq!(read_file(&source, "/root/marker.txt").await, "at-snapshot");
+ source.stop().await.unwrap();
+ runtime.remove("live-clone-source", true).await.unwrap();
+
+ clone.start().await.unwrap();
+ assert_eq!(read_file(&clone, "/root/marker.txt").await, "at-clone");
+ clone.stop().await.unwrap();
+ runtime.remove("live-clone", true).await.unwrap();
+ runtime
+ .shutdown(Some(common::TEST_SHUTDOWN_TIMEOUT))
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn test_online_clone_data_survives_removing_intermediate_clone() {
+ let home = boxlite_test_utils::home::PerTestBoxHome::new();
+ let runtime = BoxliteRuntime::new(BoxliteOptions {
+ home_dir: home.path.clone(),
+ image_registries: common::test_registries(),
+ ..Default::default()
+ })
+ .unwrap();
+ let source = create_running_box(&runtime, "origin").await;
+ write_and_verify(&source, "/root/ancestor.txt", "from-origin").await;
+ let branch = source
+ .clone_box(Default::default(), Some("branch".into()))
+ .await
+ .unwrap();
+ branch.start().await.unwrap();
+ let leaf = branch.clone_box(Default::default(), None).await.unwrap();
+ runtime.remove("branch", true).await.unwrap();
+
+ leaf.start()
+ .await
+ .expect("the leaf's backing chain must survive deleting its parent");
+ assert_eq!(read_file(&leaf, "/root/ancestor.txt").await, "from-origin");
+ runtime
+ .shutdown(Some(common::TEST_SHUTDOWN_TIMEOUT))
+ .await
+ .unwrap();
+}
+
#[tokio::test]
async fn test_two_snapshots_while_running() {
let home = boxlite_test_utils::home::PerTestBoxHome::new();