Snapshots and forks
This page tells you how the daemon saves the files of a sandbox as a snapshot, and how it makes new sandboxes from a snapshot. It is for a contributor who must change internal/sandbox/snapshot.go.
Three other pages use the same code and give more detail on their part:
- suspend.md: a suspend is a temporary snapshot plus the removal of the container.
- pools.md: a pool can keep waiting sandboxes that the daemon created from a snapshot.
- manager.md:
Manager.Create,boot, the state file and the sweep.
What a snapshot is
Section titled “What a snapshot is”A snapshot is the saved files of one sandbox at one moment. The engine keeps it as a local image.
The daemon makes it with the Commit call of the engine, see engine.md.
The Docker implementation sends pause=true, thus the engine freezes the container while it reads the files.
After the commit the sandbox continues, with its processes.
The name of the image is boxfork-snapshot:<id>, where <id> is the snapshot id without the prefix snap_.
The function snapshotRef makes this name. The constant snapshotRepo is the first part.
The daemon keeps one snapRecord for each snapshot, in Manager.snaps and in the state file.
| Field | JSON name | Meaning |
|---|---|---|
ID |
id |
snap_ plus random characters, from randID. |
SandboxID |
sandbox_id |
The sandbox that the daemon took it from. That sandbox can be gone. |
Image |
image |
The image that the sandbox came from. |
Metadata |
metadata |
Text values that the client gave. |
CreatedAt |
created_at |
The time after the commit. |
Temporary |
temporary |
True for a snapshot that a fork or a suspend made for itself. |
ExcludedPaths |
excluded_paths |
The directories of the sandbox that are not in the snapshot. |
refs |
not saved | The number of users of the snapshot. |
dying |
not saved | True while the daemon deletes the image. |
What a snapshot contains and what it leaves out
Section titled “What a snapshot contains and what it leaves out”A snapshot contains the files of the container itself: the files of the image plus the changes that the sandbox made.
A snapshot does not contain these items:
- Processes and memory. A new sandbox from a snapshot starts with only its first process.
- The data on a volume that the sandbox mounts. See volumes.md.
- A directory that the image keeps in a volume of its own, if the sandbox mounts no volume there. A
VOLUMEline in the image makes such a directory.
The function excluded in internal/sandbox/volume.go makes the excluded_paths list.
It adds the UnsavedPaths of the sandbox to the mount paths of its volumes and sorts the result.
The client can read the list to see which directories the snapshot does not hold.
README.md also says that a snapshot leaves out /dev/shm.
The daemon has no code for /dev/shm in a snapshot. This is the behavior of the engine, and excluded_paths does not list it.
Labels on the image
Section titled “Labels on the image”The daemon sets no label on a snapshot image. The Commit call sends an empty body.
The comments in New and boot in internal/sandbox/manager.go say that the image carries the labels of the container.
A container that starts from a snapshot thus gets the labels boxfork.managed, boxfork.id and boxfork.gpus of the source sandbox, unless something replaces them.
Four parts of the code make this safe:
| Part | What it does |
|---|---|
boot |
Sets all three labels on each container. A copy does not keep the id or the GPUs of its source. |
boot |
Sets the variable NVIDIA_VISIBLE_DEVICES on each container. Without GPUs the value is void. |
New |
Treats a container as its own only when the name starts with boxfork-. A container that a person starts from a snapshot image by hand stays. |
Create and SetPool |
Refuse an image reference whose name is boxfork-snapshot (isSnapshotImage). The client must use the snapshot option. |
The last rule keeps the count of users correct.
A sandbox that starts from the image by name is not a user of the snapshot in refs.
A client can then delete the snapshot while that sandbox uses it.
The daemon finds snapshot images by name, from its records. It does not ask the engine for a list of images.
How the daemon creates a snapshot
Section titled “How the daemon creates a snapshot”Manager.Snapshot is the public function. It calls snapshot with temporary false and held false.
sequenceDiagram participant C as Client participant M as Manager.snapshot participant S as State file participant E as Engine C->>M: POST /v1/sandboxes/{id}/snapshot M->>M: checks under m.mu M->>S: save: discarded[snap] = zero time M->>M: take rec.opMu M->>M: wakeLocked (if the sandbox is suspended) M->>E: Commit(container, boxfork-snapshot:id) Note over E: the engine freezes the container, reads the files, continues E-->>M: done M->>M: release rec.opMu M->>S: save: snapshot record, discarded[snap] removed M-->>C: 201 and the snapshotThe steps in the code are these:
- Under
m.mu: refuse ifnoSnapshotsis set. Refuse if the record is hidden or missing. - For a snapshot that is not temporary, do the check of
MaxSnapshotsand add one tosnapsPending. - Set
lastUsedof the sandbox, and make thesnapRecordwith a new id. - Put the id in
m.trashwith the zero time and inm.committing. Save the state file. - Take
rec.opMu. A pause, a resume, a suspend and a second snapshot of the same sandbox wait for this lock. - Call
wakeLocked. A suspended sandbox gets a container again before the commit. - Call
Engine.Commitwith a time limit of 15 minutes. The context has no cancel from the request. - Release
rec.opMu. - Under
m.mu: remove the id fromm.committing, setlastUsedagain and subtract one fromsnapsPending. - If the commit was successful: remove the id from
m.trash, add the record tom.snapsand save the state file. - If a step failed: set the time in
m.trash, save, and callemptyTrashone time.
Why the id goes into the trash first
Section titled “Why the id goes into the trash first”The daemon writes the id to the state file before it tells the engine to save files.
The daemon can stop in the middle, the request can end, or the engine can finish after the daemon stopped the wait.
In each of these cases an image can exist that no snapshot record names.
Because the id is in discarded, the daemon knows the name of that image and deletes it.
emptyTrash deletes the image of each id in m.trash that is not in m.committing.
It keeps an id for trashGrace (one hour) after the failure and deletes the image again on each pass.
The reason is in the code: an engine can finish a commit after the daemon stopped the wait.
sweepSnapshots calls emptyTrash. Reconcile calls sweepSnapshots each 20 seconds, and New calls it at startup.
The check at startup
Section titled “The check at startup”A runtime can keep the file changes of a container to itself.
The engine then saves a snapshot without those changes and reports success.
Manager.CheckSnapshots finds this at startup. cmd/boxfork/main.go calls it one time.
- It starts a trial container from the default image, with the helper as its first process.
- It makes a directory in the container with the
fsmode of the helper. - It commits the container and starts a second container from that image.
- It does a
statof the directory in the second container.
If the directory is missing, or if a step fails, CheckSnapshots stores the reason in m.noSnapshots.
While noSnapshots is set, Snapshot and Fork return an UnsupportedError, and the API sends status 501 with the code unsupported.
Under gVisor the reason text tells the operator to give runsc the argument --overlay2=none.
The trial containers have the sandbox labels, and the trial image is in the trash from the start. Thus a daemon that stops in the middle of the check leaves no container and no image.
Create a sandbox from a snapshot
Section titled “Create a sandbox from a snapshot”A client sends POST /v1/sandboxes with "snapshot": "<id>". Manager.Create does the work.
Createrefuses a request that has an image and a snapshot.- Under
m.mu,refSnapshotadds one torefs. It fails withErrSnapshotNotFoundif the snapshot is missing ordying. Createsetsrec.Imageto theImageof the snapshot and usessnapshotRefas the source of the container.bootcallsEngine.LocalImage. It never pulls a snapshot image.bootmakes and starts the container in the same way as for an image.- The record keeps the snapshot id in
Snapshot. The API shows it assnapshot.
The new sandbox takes its CPU, memory, network and volume settings from the request and the defaults of the daemon. It does not take them from the source sandbox. The engine makes the container on top of the image, thus the new sandbox shares the data that it does not change.
When the sandbox goes away, forget calls unrefSnapshot for rec.Snapshot and for rec.Disk.
If boot fails, Create calls unrefSnapshot itself.
If the image of the snapshot is gone from the machine, boot returns errFilesGone.
Create then returns an error that wraps ErrSnapshotNotFound, and forgetLostSnapshot removes the record if no sandbox uses it.
A fork is one temporary snapshot plus n creates from it. Manager.Fork does the work.
sequenceDiagram participant C as Client participant F as Manager.Fork participant E as Engine C->>F: POST /v1/sandboxes/{id}/fork (count n) F->>F: checks, and the request for each copy F->>F: snapshot(temporary): refs = 1 F->>F: forks[snap] = true par a maximum of 8 at the same time F->>E: Create (Snapshot = snap, fork = snap) end F->>F: forks[snap] removed alt each create was successful F->>F: clear Fork on each copy, save F-->>C: 201, snapshot_id and the sandboxes else one create failed F->>E: kill each copy F-->>C: the first error end F->>F: unrefSnapshot: the hold of the fork endsWhat a copy gets
Section titled “What a copy gets”Fork makes one CreateRequest for all copies from the record of the source sandbox.
| Setting | Value for each copy |
|---|---|
| CPU, memory, network | The same as the source. |
| Metadata | The metadata of the source, or the metadata of the request when the request gives it. |
| Timeout | From the request, or the default of the daemon. |
| Volumes | The same volumes as the source, and no others (volumesFinal). They are the same volumes, not copies. |
| GPUs | As many as the source has, unless the request gives a number. Zero means none. See gpu.md. |
| Idle time for suspend | The same as the source, when the source has one or has GPUs. See suspend.md. |
| Files | The files of the temporary snapshot. |
| Processes | None. A copy starts with only its first process. |
A copy is a normal create. It counts for --max-sandboxes, and a pool never serves it.
All copies or none
Section titled “All copies or none”Until the fork is done, a copy has the snapshot id in its Fork field.
A record with Fork set is hidden: Get, List, Kill and use behave as if it does not exist.
When each create was successful, Fork clears the Fork field on all copies under one hold of m.mu and saves the state file.
This is the moment when the copies become real sandboxes, all at the same time.
If that save fails, Fork sets the field again and the fork fails.
When the fork fails, Fork kills each copy that it created, with a time limit of 2 minutes.
A copy that it cannot kill stays hidden. Sweep kills each record whose Fork id is not in m.forks.
Sweep runs each second, thus it tries again until the copy is gone.
The Fork field is in the state file.
After a restart m.forks is empty, thus Sweep kills each copy of a fork that was in progress when the daemon stopped.
The API handler also calls unheard. If the client is gone when the fork is done, the handler kills the copies.
Temporary snapshots and when the daemon deletes them
Section titled “Temporary snapshots and when the daemon deletes them”A temporary snapshot is one that snapshot made with temporary true. Two callers do this: Fork and suspend.
A temporary snapshot does not count for MaxSnapshots. It shows in the list of snapshots with temporary true.
snapshot gives a new temporary snapshot refs of 1. This is the hold of the caller.
For a fork, each copy adds one hold in Create, and Fork releases its own hold at its end with unrefSnapshot.
For a suspend, the hold becomes the Disk of the suspended sandbox.
unrefSnapshot deletes a temporary snapshot when refs gets to zero:
- After a successful fork, the snapshot stays while one copy exists. The kill of the last copy deletes it.
- After a failed fork with no copy left, the end of
Forkdeletes it. unrefSnapshotgives the engine 30 seconds. If the delete fails, the snapshot stays withrefszero.sweepSnapshotsdeletes each temporary snapshot withrefszero, each 20 seconds and at startup.
SetPool refuses a pool of a temporary snapshot.
Delete a snapshot
Section titled “Delete a snapshot”Manager.DeleteSnapshot applies these rules in this order, under m.mu:
| Check | Result | HTTP |
|---|---|---|
No record, or dying |
ErrSnapshotNotFound |
404 snapshot_not_found |
A pool uses the snapshot (poolOn) |
InUseError: delete the pool first |
409 in_use |
refs is more than zero |
InUseError: kill the sandboxes first |
409 in_use |
| No user | Set dying, then call dropSnapshot |
204 |
The source sandbox does not hold the snapshot. A client can delete a snapshot while its source sandbox still exists.
refs counts these users:
- Each sandbox that the daemon created from the snapshot (
rec.Snapshot). - Each create from the snapshot that is in progress.
- Each suspended or woken sandbox whose
Diskis the snapshot. - A fork that is in progress.
dropSnapshot tells the engine to remove the image, with a time limit of 2 minutes.
If the engine fails, dropSnapshot clears dying, and the snapshot stays.
If the engine reports ErrInUse, the client gets an InUseError. This occurs when a container that refs does not count still uses the image.
After a successful removal, dropSnapshot deletes the record and saves the state file.
While dying is set, GetSnapshot and ListSnapshots do not show the snapshot, and refSnapshot refuses it.
Thus a create and a delete of the same snapshot cannot both be successful. TestDeleteAndCreateDoNotBothWin holds this.
Reference: limits
Section titled “Reference: limits”| Limit | Value | Name |
|---|---|---|
| Copies in one fork | 64 | MaxFork |
| Creates of one fork at the same time | 8 | forkParallel |
| Kept snapshots on one daemon | No limit by default | Config.MaxSnapshots, flag --max-snapshots |
| Time for one commit | 15 minutes | A literal in snapshot |
| Time to delete an image, client request and sweep | 2 minutes | A literal in DeleteSnapshot and sweepSnapshots |
| Time to delete a temporary image at an unref | 30 seconds | A literal in unrefSnapshot |
| Time to delete one image from the trash | 30 seconds | A literal in emptyTrash |
| Time to kill the copies of a failed fork | 2 minutes | A literal in Fork |
| Time that a failed snapshot id stays in the trash | 1 hour | trashGrace |
| Layers of an image for a suspend | 100 | MaxLayers in suspend.go |
MaxSnapshots counts the kept snapshots plus snapsPending. A request at the limit gets a LimitError, and the API sends status 429.
Each commit adds one layer to the image chain. MaxLayers stops only a suspend.
For a chain of snapshots and creates, the limit is the limit of the engine. The comment in suspend.go gives it as about 125 layers.
What a restart does
Section titled “What a restart does”New in manager.go reads the state file and compares it with the engine.
| Item | What New does |
|---|---|
| A snapshot whose image exists | Keeps the record. |
| A snapshot whose image the engine reports as not found | Drops the record and writes a line to the log. |
| A snapshot for which the engine returns a different error | Keeps the record. |
refs |
Counts them again from Snapshot and Disk of each sandbox record that it keeps. |
An id in discarded with the zero time |
The commit was in progress when the daemon stopped. New gives it the current time. |
| A pool whose snapshot is gone | Drops the pool. |
A suspended sandbox whose Disk snapshot is gone |
Drops the sandbox. |
A copy with Fork set |
Keeps the record hidden. The first Sweep kills it. |
A temporary snapshot with refs zero |
sweepSnapshots at the end of New deletes it. |
m.committing and m.forks are only in memory. After a restart both are empty.
Invariants that a change must keep
Section titled “Invariants that a change must keep”- No image of a snapshot exists that the state file does not name, in
snapshotsor indiscarded. - The id of a new snapshot is in the state file before the engine gets the commit.
- The daemon never deletes a snapshot image while
refsis more than zero or a pool uses the snapshot. - Each
refSnapshothas exactly oneunrefSnapshot, on each path. - A fork gives the client all copies or none. A copy is hidden until the fork is done.
- A failed fork leaves no copy, also after a restart and also when a kill fails at first.
- The commit runs under
rec.opMu. A pause or a suspend of the same sandbox does not run in the middle of it. - The freeze of a commit does not change the
pausedstate of the record.syncPausedskips a sandbox whoseopMuis held. - A sandbox never starts from a snapshot image by its name. It starts through the snapshot option only.
bootsets all three labels andNVIDIA_VISIBLE_DEVICESon each container.
Failure cases and what the daemon undoes
Section titled “Failure cases and what the daemon undoes”| Failure | What the daemon does |
|---|---|
| The save before the commit fails | Removes the id from m.trash and m.committing, subtracts snapsPending. No commit runs. |
| The sandbox is suspended and the wake fails | Returns the error of the wake. The id gets a time in the trash. |
| The commit fails | Returns “saving the sandbox’s files”. The id gets a time in the trash, and emptyTrash deletes a possible image. |
| The engine reports that the container does not exist | engineErr forgets the sandbox. The client gets ErrNotFound. |
| The save after the commit fails | Removes the record from m.snaps. The id stays in the trash, and the daemon deletes the image. |
| The client stops the request in the middle of the commit | The commit continues. The daemon keeps the snapshot. The client does not get its id. |
| The daemon stops in the middle of the commit | The id is in discarded with the zero time. The next start deletes the image. |
| One create of a fork fails | Fork kills the other copies and releases its hold. The temporary snapshot goes with the last hold. |
| A copy of a failed fork cannot be killed | The copy stays hidden. Sweep tries again each second. |
| A GPU is missing for a copy of a GPU sandbox | The fork fails with gpu.ErrUnavailable, and the message tells the client about gpu 0. |
| The image of a snapshot is gone when a create uses it | The create fails with ErrSnapshotNotFound. forgetLostSnapshot drops the record if refs is zero. |
| The engine cannot delete a snapshot image | The snapshot stays, and the client gets the error. |
| The check at startup fails for a reason of the engine or the network | noSnapshots is set until the next start of the daemon. Snapshot, fork and suspend are off. |
How to change it
Section titled “How to change it”- Read
snapshot,unrefSnapshotandForkinsnapshot.gobefore you change one of them. - If you add a caller of
snapshot, decide if the snapshot is temporary and who holds the first reference. - If you add a user of a snapshot, call
refSnapshotunderm.mubefore the engine uses the image. - Call
unrefSnapshoton each path that ends that use. Do not call it withm.muheld. - If you add an engine call that can make an image, put its id in
m.trashand save first. - If you add a field to
Snapshot, give it a JSON name. A field without a capital letter is not in the state file. - If a new field must survive a restart, make sure that
Newreads it and that old state files load. - If you change what a copy gets, change the
baserequest inFork, notCreate. - If you add a new state between “created” and “visible”, make
hiddenreturn true for it. - Add a test to
snapshot_test.go. UseSetFailandLoseof the test engine to make each engine call fail. - Do a break-it check for each new undo step.
- Run
make test.
Caution: Do not call Engine.Commit without rec.opMu. A pause in the middle of a commit can be lost when the engine continues the container.
Where the tests are
Section titled “Where the tests are”internal/sandbox/snapshot_test.go has most of the tests.
| Test | What it holds |
|---|---|
TestSnapshotAndCreateFromIt |
The basic flow: the record, the image name, and a new container that starts from the snapshot image without a pull. |
TestASnapshotInUseCannotBeDeleted, TestTheManagerItselfKnowsWhichSnapshotsAreInUse |
The delete rules and the refs count. |
TestDeleteAndCreateDoNotBothWin |
A delete and a create at the same time. |
TestAFailedSnapshotLeavesNothing, TestNoSnapshotFilesAreEverOrphaned |
The trash, also across a restart. |
TestFork, TestForkIsAllOrNothing, TestAFailedForkNeverLeavesCopies |
The fork and its undo. |
TestATemporarySnapshotIsEventuallyDeleted |
The delete of a temporary snapshot in the sweep and at startup. |
TestSnapshotsSurviveARestart, TestASnapshotWhoseFilesAreGone |
The restart. |
TestASnapshotIsNotMistakenForAPause |
The freeze of a commit and rec.opMu. |
TestASandboxCannotBeStartedFromASnapshotsImageByName |
The rule about the image name. |
TestMaxSnapshots, TestCheckSnapshots |
The limit and the check at startup. |
Other files have tests that touch this code:
- internal/sandbox/faults_test.go:
TestAContainerThatDiesWhileItsFilesAreSaved,TestAnImageThatKeepsFilesInAVolume. - internal/sandbox/pool_test.go:
TestAPoolOfASnapshot,TestNoPoolOfASnapshotThatGoesByItself. - internal/sandbox/review5_test.go:
TestACopyDoesNotTakeUpTheHostsNewerDefaults.
The proof script scripts/proof/pool.sh creates a snapshot and a pool of it on a real engine, and deletes the two at its end.
Not proven
Section titled “Not proven”- The real-engine runs were on Docker with gVisor on arm64, in a nested virtual machine, and on Podman. Nothing ran on x86_64.
- Nothing ran on a machine with an NVIDIA GPU. A fork or a snapshot of a sandbox with a real GPU is not proven.
- The test engine does not copy the files of a container at a commit. It records which container made which image. Only the check at startup and the proof scripts compare file content on a real engine.
- The claim that an image carries the labels of its container comes from comments in the code. No test of this repository reads the labels of a real image.
- The behavior for
/dev/shmcomes from README.md and from the engine, not from code in this repository. - No test covers a snapshot or a fork of a paused sandbox. The code does not refuse it.
- No test covers a chain of snapshots that gets to the layer limit of the engine.
- README.md and ROADMAP.md give no measured time for a snapshot or a fork. The time of a commit for a large sandbox is not known.
CheckSnapshotsruns only at startup. If it fails because the engine cannot pull the default image, snapshots stay off until a restart.- A client that stops the request in the middle of a snapshot leaves a kept snapshot. The API does not delete it.