Skip to content

The sandbox manager

This page describes the sandbox manager: the part of the daemon that owns all sandboxes on one machine. It is for a contributor who must change how the daemon creates, kills, pauses or restores a sandbox. When you know this page, you can change the code in these two files:

The other files of the package sandbox have their own pages:

Topic Source Page
Commands and file operations run.go, files.go commands-and-files.md
The kept connection kept.go kept-connection.md
Snapshots and forks snapshot.go snapshots-and-forks.md
Pools pool.go pools.md
Idle suspension and wake suspend.go suspend.md
Volumes volume.go volumes.md
The engine interface internal/engine engine.md
The helper internal/guest helper.md
The GPU allocator internal/gpu gpu.md
The sandbox network internal/hostfw, cmd/boxfork network.md

For the place of the manager in the full system, see architecture.md.

The manager is one Go value of the type Manager. The daemon makes one manager when it starts. The HTTP API calls the methods of the manager. The manager calls the engine, the GPU allocator and the helper.

The manager has these jobs:

  • It keeps one record for each sandbox, each snapshot and each pool.
  • It writes the records to the state file after each change.
  • It creates and removes the container of each sandbox through the engine.
  • It gives GPUs to sandboxes through the GPU allocator, and it gives them back.
  • It kills a sandbox when the timeout of the sandbox ends.
  • It compares its records with the containers of the engine and corrects the differences.

The manager does not know HTTP. It returns Go errors, and internal/api/server.go changes them to HTTP answers.

All fields of Manager are private. The lock mu protects all maps and counters in this table, and all fields of all records.

Field Type Content
cfg Config The configuration, after Config.defaults filled the empty fields.
mu sync.Mutex The lock of the manager. See Locks.
boxes map[string]*record All sandboxes by ID. It also contains the hidden sandboxes: waiting sandboxes and the copies of a fork in progress.
pending int The number of creates in progress. MaxSandboxes counts them.
orphans map[string]string Containers that the daemon must remove but could not remove. The key is the ID or the name of the container. The value is the owner that holds its GPUs.
snaps map[string]*snapRecord All snapshots by ID.
snapsPending int The number of kept snapshots in progress. MaxSnapshots counts them.
trash map[string]time.Time IDs of snapshots whose image the daemon must delete, with the time of the decision.
committing map[string]bool IDs in trash for which the engine commit is in progress.
forks map[string]bool The forks in progress, by the ID of their snapshot.
noSnapshots string The reason why snapshots do not work on this host. It is empty when they work.
volMu sync.Mutex The lock for the creation and the deletion of a volume.
volPending map[string]int For each volume, the number of creates in progress that mount it.
volDeleting map[string]bool The volumes whose deletion is in progress.
dnsWarned sync.Once It makes the warning about name servers occur one time only.
helloWait, stall time.Duration Time limits of the kept connection. The tests change them.
pools map[string]*poolRecord All pools by ID.
poolKick chan struct{} A signal that asks the pool loop for a pass.
setup string The result of setupOf, calculated one time. See pools.md.

New gets a Config. Config.defaults replaces each zero value that has a default. The column “Flag” gives the flag of boxfork serve that sets the field, in cmd/boxfork/main.go.

Field Default Flag Meaning
Engine none --docker-host The engine. New returns an error if it is nil.
GPUs nil none The GPU allocator. Nil means that the host has no GPU.
Helper none none A function that returns the helper binary for an image architecture. New returns an error if it is nil.
StatePath empty --data-dir The path of the state file. The daemon uses <data-dir>/state.json. If the path is empty, the manager does not read or write a state file.
Runtime empty --isolation The OCI runtime of each container: runsc for gVisor. Empty means the default of the engine. Detect selects it.
Isolation container --isolation The value that each sandbox reports: gvisor or container.
GPUDriver nvidia --gpu-driver nvidia or cdi. It selects how the manager names GPUs to the engine.
GPUCheck auto --gpu-check auto, require or off. See gpu.md.
GPUIdleSuspend 0 --gpu-idle-suspend The idle time before the daemon suspends a GPU sandbox that did not set its own time. Zero means never.
DefaultImage ubuntu:24.04 --default-image The image of a sandbox that names no image.
DefaultTimeout 5 minutes --default-timeout The timeout of a sandbox that gives no timeout. If it is larger than MaxTimeout, defaults decreases it to MaxTimeout.
MaxTimeout 0 --max-timeout The maximum timeout. Zero means no maximum. Only then can a sandbox have no timeout.
DefaultCPUs 2 none The CPU limit of a sandbox that gives none.
DefaultMemoryMB 1024 none The memory limit of a sandbox that gives none.
PidsLimit 4096 none The maximum number of processes in each container.
MaxSandboxes 0 --max-sandboxes The maximum number of sandboxes. Zero means no maximum. Waiting sandboxes are not in the count.
MaxSnapshots 0 --max-snapshots The maximum number of kept snapshots. Zero means no maximum. Temporary snapshots are not in the count.
MaxPooled 64 (DefaultMaxPooled) --max-pooled The maximum number of waiting sandboxes in all pools. A negative value means none.
Version empty none The name of the build of the daemon. It is part of the setup mark.
ConnectionIdle 1 minute (DefaultConnectionIdle) --connection-idle The time that the daemon keeps a kept connection after its last command. A negative value means no kept connection.
NetworkReady nil none A function that the manager calls before it puts a sandbox on the sandbox network. An error refuses the sandbox. See network.md.
MaxVolumes 0 --max-volumes The maximum number of volumes. Zero means no maximum.
DefaultVolumes nil --volume The mounts that each new sandbox gets. See volumes.md.
DNS nil --dns The name servers of each sandbox that has a network.
Log a logger that discards none The logger.
Now time.Now none The clock. The tests replace it.

Note: For MaxPooled and ConnectionIdle, zero means “the default” in Config. The command line changes --max-pooled 0 and --connection-idle 0 to -1.

A record is the data that the daemon keeps for one sandbox. The type is record. A record contains the public description Sandbox and the private data of the daemon. The API returns only the Sandbox part.

Field JSON name Content
ID id sbx_ and 16 random characters. newID makes it from 10 random bytes.
Image image The image of the sandbox. For a sandbox from a snapshot, it is the image of the sandbox that the snapshot came from.
State state running, paused or suspended.
Isolation isolation gvisor or container, from Config.Isolation.
CPUs cpus The CPU limit.
MemoryMB memory_mb The memory limit in MiB.
GPUs gpus The GPUs that the sandbox holds now. A suspended sandbox holds none.
Network network True if the sandbox is on the sandbox network.
Metadata metadata The labels that the client gave.
CreatedAt created_at The time of the creation, or of the hand-out for a sandbox from a pool.
GPUVerified gpu_verified True if the sandbox named exactly its own GPUs when the daemon asked.
SuspendAfterSeconds suspend_after_seconds The idle time before a suspension. Zero means never.
UnsavedPaths unsaved_paths The directories that the image keeps in its own volumes. A snapshot does not contain them.
Volumes volumes The mounts of the sandbox, sorted by path.
Snapshot snapshot The snapshot from which the daemon created the sandbox, if there is one.
ExpiresAt expires_at The time at which the daemon kills the sandbox. It is absent for a sandbox with no timeout and for a paused sandbox.

The column “Saved” tells you if the field is in the state file.

Field Saved Content
ContainerID yes, container_id The ID of the container. It is empty for a suspended sandbox.
Fork yes, fork The ID of the fork that makes this copy. The fork clears it when all copies exist.
Pool yes, pool The ID of the pool in which this sandbox waits. The hand-out clears it.
Setup yes, setup The setup mark of the daemon that started this waiting sandbox.
RemainingNS yes, remaining_ns The time that a paused sandbox had left, in nanoseconds.
Disk yes, disk The temporary snapshot that holds the files of a suspended sandbox. After a wake, the container is built on it.
Want yes, gpu_request The GPU request of the create. A wake uses it to get the same type of GPU.
Layers yes, layers The number of image layers below the container. See MaxLayers in suspend.md.
dying no True while the daemon removes the container.
opMu no A lock for one sandbox. See Locks.
draining no True for a waiting sandbox that its pool does not keep.
claimed no True for a waiting sandbox while a create asks the engine about it.
suspendAsked no True during a create if the client gave an idle time larger than zero.
tooDeep no True after the daemon logged that it cannot suspend this sandbox again.
inUse no The number of commands and file operations in progress.
lastUsed no The time of the last use.
conn, connGate, noConnIn, openFailed, frozen, thawedAt no The kept connection and the freezes. See kept-connection.md.

Two small methods classify a record:

  • unowned is true if Fork or Pool is not empty. No client owns the sandbox.
  • hidden is true if dying is true or unowned is true.

Get and List leave out the records for which unowned is true. All calls that change a sandbox return ErrNotFound for a record for which hidden is true.

The other record types are snapRecord in snapshot.go and poolRecord in pool.go. Their pages describe them. There is no record type for a volume: the engine keeps the volumes.

The field State has three values. The diagram also shows two phases that are not values of State: starting is a create in progress, and dying is the flag record.dying.

stateDiagram-v2
[*] --> starting: Create
starting --> running: the record is in the state file
starting --> [*]: a step fails
running --> paused: Pause
paused --> running: Resume
running --> suspended: Reclaim finds it idle
suspended --> running: wake
running --> dying: Kill or timeout
paused --> dying: Kill
suspended --> dying: Kill or timeout
dying --> [*]: the container is gone
running --> [*]: Reconcile finds no container
paused --> [*]: Reconcile finds no container
State Container Processes GPUs Timeout clock
running exists run held runs
paused exists frozen, memory stays held stopped
suspended removed lost released runs

If the engine cannot remove the container, a sandbox goes from dying back to the state that it had.

serve in cmd/boxfork/main.go calls these functions in this sequence:

  1. Detect selects the runtime.
  2. New reads the state file and does the reconciliation.
  3. Manager.CheckNetwork makes the sandbox network and reports if the engine isolates the sandboxes from each other.
  4. Manager.CheckSnapshots tests if a snapshot contains the files of a sandbox.
  5. Manager.Watch starts the background loops.

Detect gets the requested isolation: auto, gvisor or container. For container it returns immediately. For the other two values it asks the engine for its runtimes. If the engine lists runsc, tryRuntime starts one container with that runtime and removes it. Detect reports gVisor only if the container started and the engine says that it used runsc.

The reason is that some engines list a runtime that is not installed. With auto, a failure gives plain containers and a note for the log. With gvisor, a failure is an error and the daemon does not start.

The engine and the state file can disagree after a stop of the daemon. New makes them agree before the daemon accepts a request. New does these steps:

  1. It fills the defaults of Config and calculates the setup mark.
  2. It makes the default volumes that do not exist (ensureDefaultVolumes).
  3. It reads the state file with loadState.
  4. It copies the discarded IDs to trash. An entry with the zero time gets the current time.
  5. It keeps each snapshot record, unless the engine says that the image of the snapshot is not there.
  6. It keeps each pool record, unless its size is less than 1 or its snapshot is gone.
  7. It lists the containers that have the label boxfork.managed=true.
  8. It examines each sandbox record. The table below gives the rules.
  9. It removes each container that is left without a record.
  10. It writes the state file.
  11. It calls sweepSnapshots, which deletes the temporary snapshots that no sandbox uses.

New considers a container only if it has the label boxfork.managed=true and a name that starts with boxfork-. The image of a snapshot has the labels of its sandbox. A person can start a container from that image by hand. The name check keeps that container safe from the daemon.

What New finds What New does
A record whose container runs It keeps the record and counts its snapshots as used.
A record whose container is gone or stopped It drops the record. A stopped container is then a container without a record.
A record with no container and the state suspended, and the snapshot in Disk exists It keeps the record as suspended and clears GPUs.
A record with no container and the state suspended, and the snapshot in Disk is gone It drops the record.
A record with no container and a different state It drops the record.
A record with a container and the state suspended It sets the state to running. The suspension did not complete.
A record with GPUs on a host that now has no GPU It drops the record.
A record with a GPU that a different sandbox holds It drops the record (Allocator.Restore returns an error).
A record with a GPU that the driver does not list now It keeps the record and writes a warning.
A record that says paused, but the container is not paused, or the opposite It believes the engine and corrects the record.
A container with the label and the name prefix, but with no record It removes the container.
A container that it cannot remove It puts the container in orphans with the owner leftover-<container ID>. It holds the GPUs from the label boxfork.gpus.
A null entry or an entry with no ID in the state file It ignores the entry.
A damaged state file It returns an error. The daemon does not start.

New sets lastUsed of each record to the current time. No sandbox is idle immediately after a restart.

A daemon of a different build or with different settings

Section titled “A daemon of a different build or with different settings”

New keeps a sandbox that a different build of the daemon created, if its container runs. Three mechanisms handle the differences:

  • A waiting sandbox has the setup mark of the daemon that started it. setupOf makes the mark from the version, the isolation, the runtime, the name servers, the default mounts, the limit of processes and the helper binaries. If the mark is different from the mark of the current daemon, drainPools removes the waiting sandbox. See pools.md.
  • A sandbox keeps the helper that it got when the daemon created it. If that helper does not know the command serve, the manager sets noConnIn to that container, and each command gets its own connection. See kept-connection.md.
  • A copy of a fork that was in progress has Fork set. forks is empty after a start, thus the first Sweep removes the copy.

loadState does not examine the field version of the state file.

CheckNetwork calls Engine.EnsureNetwork for the network boxfork. It returns true if the engine blocks traffic between the sandboxes. See network.md.

CheckSnapshots commits a trial container and looks for a file in a second container from that commit. It stores the result in noSnapshots. If the result is not empty, snapshot, fork and suspension are off. See snapshots-and-forks.md.

Manager.Create gets a CreateRequest and returns a Sandbox. The rule is: if a step fails, nothing stays. Create does the checks and the bookkeeping. boot talks to the engine. Create, a wake and a fork all use boot.

On the test machine, a create without a pool took a median of 139 ms.

flowchart TD
A[Create] --> B{request valid?}
B -- no --> E1[InvalidError]
B -- yes --> C{at MaxSandboxes?}
C -- yes --> E2[LimitError]
C -- no --> D{waiting sandbox in a pool?}
D -- yes --> H[handOut] --> Z[return the sandbox]
D -- no --> F[hold volumes and snapshot, pending + 1]
F --> G[boot]
G -- fails --> U[discard: remove the container, release the GPUs]
U --> E3[error]
G -- ok --> S[add the record and save]
S -- save fails --> U
S -- ok --> Z

Create does these checks before the bookkeeping. Each failure is an InvalidError, unless the list says something different.

  1. If the sandbox is not for a pool, timeout calculates the timeout. See Timeouts.
  2. CPUs and MemoryMB must not be negative.
  3. The name of an environment variable must not be empty and must not contain = or a NUL byte.
  4. The name NVIDIA_VISIBLE_DEVICES is not permitted. The manager sets this variable.
  5. An image name must match imageRef and must not contain ... The name goes into a URL of the engine API.
  6. An image name must not point to the repository boxfork-snapshot. The client must use the snapshot option.
  7. The request must not give an image and a snapshot together.
  8. A GPU request with a count of zero or less becomes no GPU request.
  9. A GPU request on a host with no GPU allocator returns gpu.ErrUnavailable.
  10. The request must not have more than MaxMounts volumes.
  11. withDefaults adds the default mounts, and checkMounts examines the full set. See volumes.md.
  12. The idle time must be 0, or MinSuspendAfter or more.
  13. An idle time larger than 0 on a host where snapshots do not work returns an UnsupportedError.

The idle time comes from the request. If the request gives none, a GPU sandbox gets GPUIdleSuspend and a sandbox with no GPU gets zero. The manager rounds the idle time up to full seconds.

Then Create makes the record and fills the defaults: the image, the CPU limit and the memory limit. A GPU sandbox that gives no memory limit gets a minimum of 8192 MiB.

Create takes m.mu and does these steps:

  1. atLimit compares owned() + pending with MaxSandboxes. At the limit, it returns a LimitError. It does not count a sandbox for a pool.
  2. fromPool looks for a waiting sandbox that is the same as the request. If there is one, handOut gives it to the client. See pools.md.
  3. atLimit runs again, because fromPool can release the lock while it asks the engine.
  4. holdVolumes adds 1 to volPending for each mount. It refuses a volume whose deletion is in progress.
  5. For a snapshot, refSnapshot adds 1 to the user count of the snapshot.
  6. It adds 1 to pending, unless the sandbox is for a pool.

Create then releases the lock. A deferred function decreases pending and calls releaseVolumes when Create returns.

boot makes, starts and checks one container. It reads from the record only the fields that never change.

  1. It copies the environment of the request and sets NVIDIA_VISIBLE_DEVICES to void.
  2. It prepares the engine.CreateSpec. The table below gives the values.
  3. For a GPU request, it calls Allocator.Allocate with the sandbox ID as the owner.
  4. It gets the image: Engine.LocalImage for a snapshot, Engine.EnsureImage for an image. EnsureImage can pull the image.
  5. It refuses an image that is not for Linux.
  6. It calculates the unsaved paths and the number of layers from the image.
  7. If the client asked for an idle time and the image gives unsaved paths, it refuses the sandbox.
  8. engineMounts makes sure that each volume exists and belongs to boxfork.
  9. It gets the helper binary for the architecture of the image.
  10. For a sandbox with a network, it calls Engine.EnsureNetwork and then Config.NetworkReady.
  11. It calls Engine.Create.
  12. It copies the helper to /.boxfork/guest in the container with Engine.CopyIn.
  13. It calls Engine.Start.
  14. If Config.Runtime is set, it inspects the container. It fails if the engine used a different runtime.
  15. probe runs guest version in the container and waits a maximum of 30 seconds for the answer.
  16. setDNS sets the name servers. See the conditions below.
  17. giveVolumes gives each new writable volume to the user of the sandbox.
  18. checkGPUs asks the sandbox which GPUs it sees, unless GPUCheck is off.
Field of CreateSpec Value
Name boxfork- and the sandbox ID
Image The image name, or boxfork-snapshot:<id> for a snapshot
Entrypoint /.boxfork/guest init. The helper is the first process.
Env The environment of the request, and NVIDIA_VISIBLE_DEVICES
Labels boxfork.managed=true, boxfork.id=<sandbox ID>, boxfork.gpus=<UUIDs>
CPUs, MemoryMB From the record
ShmMB Half of MemoryMB
PidsLimit Config.PidsLimit
Runtime Config.Runtime
Network none, or boxfork for a sandbox with a network
GPU The driver and the device names. See below.
Mounts One engine.Mount for each volume

boot sets all three labels on each container, also when the GPU list is empty. The image of a snapshot has the labels of its first sandbox, and a copy must not inherit the GPUs of that sandbox.

GPUs. With the driver cdi, the device names are nvidia.com/gpu=<index>. With the driver nvidia, they are the UUIDs. With nvidia, boot also sets NVIDIA_VISIBLE_DEVICES to the UUIDs. A sandbox with no GPU always gets void.

On a host where the NVIDIA runtime is the default, the value all gives all GPUs to a container. Thus the manager always sets the variable itself, and a client cannot set it. See gpu.md for the allocator and for checkGPUs.

Name servers. setDNS runs only for a sandbox with a network, and only if the runtime is runsc or Config.DNS is not empty. It runs guest dns <servers> as the user 0 and waits a maximum of 30 seconds. A failure does not fail the create. The daemon writes a warning, and the sandbox reaches the network by address only.

If the helper answers that it found no server, the daemon writes one warning for the life of the process. See helper.md.

Volumes. giveVolumes runs guest own <paths> as the user 0 for the mounts that are not read-only. A failure does not fail the create. The daemon writes a warning. See volumes.md.

After the GPU allocation, each failure in boot goes through the local function fail. fail calls discard.

discard removes the container and then releases the GPUs of the owner. It uses a context that the request cannot cancel, with a limit of 30 seconds. If the engine cannot remove the container, discard puts the container in orphans and does not release the GPUs. retryOrphans removes the container later and releases the GPUs then.

Engine.Create can make a container and lose the answer. Then boot has no container ID. boot knows the name of the container, thus fail removes the container by name.

Step that fails What the manager undoes
A check in Create Nothing exists.
The limit check, holdVolumes or refSnapshot Create releases the volume counts that it took.
Image, mounts, helper or network in boot discard releases the GPUs. No container exists.
Engine.Create, CopyIn, Start, the runtime check, probe discard removes the container and releases the GPUs.
checkGPUs Allocator.Distrust marks the GPUs. Then discard removes the container and releases the GPUs.
The save of the state file Create deletes the record from boxes, calls discard, and releases the snapshot.
A step of boot for a sandbox from a snapshot unrefSnapshot decreases the user count of the snapshot.

If the image of a snapshot is gone, boot returns errFilesGone. Create changes it to ErrSnapshotNotFound. forgetLostSnapshot then deletes the snapshot record, if no sandbox uses it.

When boot succeeds, Create copies the container ID, the GPUs, the layers and the unsaved paths to the record. If the list of unsaved paths is not empty, Create sets SuspendAfterSeconds to zero. It sets CreatedAt and lastUsed to the current time, and ExpiresAt to the current time plus the timeout. The clock of the timeout thus starts after the container started.

Create takes the lock, adds the record to boxes and calls save. Only then can a client see the sandbox.

The API has one more step. If the client closed the connection before the answer, Server.unheard kills the new sandbox.

Manager.Kill removes a sandbox on the request of a client. It returns ErrNotFound for an unowned record. Kill, Sweep, drainPools and a fork that failed all call remove.

remove does these steps:

  1. It takes the lock. It returns ErrNotFound if there is no record or if dying is true.
  2. With onlyExpired, it stops if ExpiresAt is nil or in the future.
  3. For a suspended sandbox, it takes opMu first. Then it does steps 1 and 2 again.
  4. It sets dying and releases the lock.
  5. It calls Engine.Remove, unless the record has no container.
  6. If the engine fails, it clears dying and returns the error. The sandbox stays.
  7. It calls forget.

In step 3, a suspension or a wake can be in progress. remove waits for it, because the container can be on its way in or out. Kill waits for opMu. Sweep tries the lock one time and comes back on its next pass.

forget does the cleanup after the container is gone:

  1. It deletes the record from boxes and closes the kept connection.
  2. It writes the state file.
  3. It releases the GPUs of the sandbox, unless a container of this sandbox is in orphans.
  4. It decreases the user count of the snapshots in Snapshot and Disk.

The GPU allocator gets the GPUs back only after the engine removed the container. If two sandboxes held one GPU at the same time, they shared it.

engineErr is a second way to forget. When the engine answers “not found” for a container during a command, a pause or a snapshot, engineErr forgets the sandbox and returns ErrNotFound.

Each sandbox has a timeout, unless the client asked for none. Sweep kills a sandbox when its timeout ends.

Manager.timeout calculates the timeout of a request:

  • No value gives DefaultTimeout.
  • A negative value is an InvalidError.
  • If MaxTimeout is larger than zero, a value of zero and a value larger than MaxTimeout are each an InvalidError.
  • If MaxTimeout is zero, a value of zero means that the sandbox never expires.

The record keeps the timeout as the absolute time ExpiresAt. A nil ExpiresAt means that the sandbox does not expire now.

Case Clock
A new sandbox ExpiresAt is the time after boot plus the timeout.
A sandbox from a pool handOut sets ExpiresAt at the hand-out. A waiting sandbox has no timeout.
A copy of a fork Each copy gets the timeout of the fork request, or the default.
A paused sandbox The clock stops. See Pause and resume.
A suspended sandbox The clock runs. Sweep kills a suspended sandbox when its timeout ends.

Manager.SetTimeout(id, d) starts the clock again. The API route is POST /v1/sandboxes/{id}/timeout.

  • The new ExpiresAt is the current time plus d. It is not the old time plus d.
  • A d of zero clears ExpiresAt, if MaxTimeout permits it.
  • For a paused sandbox, SetTimeout sets RemainingNS to d. The clock stays stopped.
  • SetTimeout does not wake a suspended sandbox.

After the create, only SetTimeout, a pause and a resume change ExpiresAt. A command or a file operation does not extend the timeout.

Sweep runs one time each second. It does three things:

  1. closeIdleConns closes each kept connection that was idle for ConnectionIdle.
  2. It removes each copy of a fork whose fork is not in forks. Such a copy comes from a fork that failed or from a stop of the daemon.
  3. It removes each sandbox whose ExpiresAt is not in the future.

Sweep makes its list under the lock and then releases the lock. The list is old when Sweep uses it. Thus remove(ctx, id, true) reads ExpiresAt again under the lock. A timeout that a client extended one moment before stays valid, and so does a pause. If the engine cannot remove a container, Sweep writes an error and tries again on its next pass.

Pause and Resume both call setPaused. A pause freezes all processes of the sandbox. The memory stays.

  1. setPaused replaces the context of the request with a context that the client cannot cancel. The limit is 1 minute.
  2. It finds the record. A hidden record returns ErrNotFound.
  3. It takes opMu of the record. It waits there for a snapshot or a suspension in progress.
  4. wakeLocked wakes the sandbox if it is suspended.
  5. It sets lastUsed. If the sandbox is in the requested state, it returns the sandbox with no engine call.
  6. It calls Engine.Pause or Engine.Unpause.
  7. It calls mark and writes the state file.

The client cannot cancel the operation, because a cancel in the middle makes the record and the container disagree.

In step 6 the engine can do the work and lose the answer. If the engine returns an error, setPaused inspects the container. If the container runs and its paused state is the requested state, setPaused continues as for a success. If the engine says that the container is gone, engineErr forgets the sandbox.

markPaused stops the clock: it stores the time left in RemainingNS, with a minimum of 1 second, and clears ExpiresAt. markResumed starts the clock: it sets ExpiresAt to the current time plus RemainingNS. A sandbox with no timeout has a RemainingNS of zero, and it has no timeout after the resume.

A paused sandbox has these properties:

  • use returns ErrPaused, thus the daemon refuses commands and file operations.
  • Sweep does not kill it, because ExpiresAt is nil.
  • Reclaim does not suspend it, because only a sandbox in the state running can be idle.
  • It holds its memory and its GPUs for an unlimited time.
  • Kill removes it as it removes each other sandbox.

The daemon must know if a sandbox does work. Idle suspension depends on the answer. Two fields of the record hold the answer. No field in the code has the name “busy”.

Manager.use in internal/sandbox/suspend.go is the one entry point for work in a sandbox:

  • It returns ErrNotFound for a hidden record and ErrPaused for a paused sandbox.
  • It wakes a suspended sandbox and then tries again.
  • It adds 1 to inUse and returns the container ID and a function done.

done subtracts 1 from inUse and sets lastUsed to the current time. A sync.Once makes a second call of done do nothing. released connects done to the close of an engine.ExecStream. The use ends when the caller closes the stream.

Caller of use When the use ends
Exec (a command that the daemon streams) The close of the stream
fsOp (each file operation) The close of the stream
runKept (a command on the kept connection) The return of runKept

These places also set lastUsed: Create, handOut, New, setPaused, the start and the end of a snapshot, a wake, and a suspension that stops.

Neither field is in the state file. After a restart, inUse is zero and lastUsed is the time of the start. suspend.md describes how idle reads the two fields.

Manager.Watch runs until its context ends. It starts two more goroutines and then runs the sweep loop itself.

Loop Period Function Work
Sweep 1 second Sweep Idle kept connections, copies of unfinished forks, timeouts
Reconcile 20 seconds Reconcile Orphans, unused temporary snapshots, the trash of snapshots, dead containers, paused state
Reclaim 2 seconds Reclaim Suspension of idle sandboxes. See suspend.md.
Pools 10 seconds, and each signal on poolKick WatchPools, FillPools Removal and start of waiting sandboxes. See pools.md.

Reclaim has its own goroutine because a suspension saves files, and that can take a long time. Timeouts must not wait for it. WatchPools has its own goroutine because the start of a sandbox takes time. Sweep and Reconcile share one goroutine. A slow Reconcile delays the next Sweep.

The daemon has one more loop that is not in the manager: the metadata guard in cmd/boxfork runs each 30 seconds. See network.md.

Reconcile makes the records agree with the engine while the daemon runs. It returns the IDs of the sandboxes that it forgot.

  1. retryOrphans tries again to remove each container in orphans.
  2. sweepSnapshots deletes the temporary snapshots with no user and calls emptyTrash.
  3. It lists the containers with the label boxfork.managed=true. If the list fails, it stops.
  4. Under the lock, it compares each record with the list.
  5. syncPaused corrects each record whose paused state is different from the container.
  6. reap forgets each sandbox whose container does not run.

Step 4 ignores a record that is dying and a record with no container.

The list is old when Reconcile uses it. Thus reap and syncPaused each look again:

  • Both try opMu and stop if a different operation holds it. The next pass looks again.
  • reap makes sure that the record is the same record with the same container ID.
  • reap inspects the container. It forgets the sandbox only if the container does not run or does not exist.
  • reap removes the dead container before it calls forget.
  • syncPaused inspects the container and changes the record only if they still disagree.

retryOrphans releases the GPUs of an owner only when no container of that owner is left. It keeps the GPUs if the owner is a sandbox that has a container again.

The state file keeps the records when the daemon stops. The code is in internal/sandbox/state.go. When the daemon stops, it leaves the sandboxes as they are. The next start finds them through the state file.

The file is one JSON object of the type stateFile, with an indent of two spaces.

Key Content
version The number 1.
sandboxes All records in boxes, sorted by ID. Each entry has the fields of Sandbox and the saved private fields.
snapshots All records in snaps, sorted by ID.
pools All records in pools, sorted by ID.
discarded The map trash: snapshot IDs whose image the daemon must delete, with the time. The zero time means that the commit was in progress.

What the file contains and what it does not contain

Section titled “What the file contains and what it does not contain”
  • The file contains the hidden records: waiting sandboxes and copies of a fork in progress.
  • The file contains the metadata and the mounts of each sandbox.
  • The file contains no environment variable of a sandbox. A variable can be a secret.
  • The file contains no private field of a record that the table of fields marks “no”.
  • The file contains no volume. The engine keeps the volumes, thus a lost state file loses no volume.
  • The file does not contain orphans, forks, pending, volPending or noSnapshots.
  • A pool record contains ready and last_error, but New sets them to zero and empty.

save does an atomic write. A stop of the machine leaves the old file or the new file, never a part of one.

  1. It makes the JSON text from the three maps and trash.
  2. It makes the directory of the file with the mode 0700, if the directory is not there.
  3. It makes a temporary file .state-* in the same directory.
  4. It writes the text, calls Sync and closes the file.
  5. It renames the temporary file to the path of the state file.

If a step fails, save deletes the temporary file and returns the error. Sync comes before the rename. Without it, a loss of power can leave an empty file with the real name. os.CreateTemp makes the file with the mode 0600, and the test TestStateFileHoldsNoEnvironment makes sure of this mode.

The caller of save must hold m.mu. save writes all records each time, also when one field changed.

A caller that makes a promise to a client undoes its change in memory when save fails, and returns an error. Create, handOut, wakeLocked, suspend, snapshot, Fork, SetPool, resize and DeletePool do this. A caller that only records a fact writes an error to the log and continues. forget, setPaused, SetTimeout and syncPaused do this.

An empty path or a file that does not exist gives an empty state. JSON that is not valid gives the error “the state file … is damaged”. New returns that error, and the daemon does not start. loadState does not repair the file and does not move it.

The manager returns sentinel errors and typed errors. Server.writeErr in internal/api/server.go changes each one to an HTTP status and a code.

Error Defined in Meaning HTTP answer
ErrNotFound manager.go No sandbox has that ID, or the record is hidden. 404 sandbox_not_found
ErrPaused manager.go The sandbox is paused. Resume it first. 409 sandbox_paused
*InvalidError manager.go The request is wrong. invalid makes it. 400 invalid_request
*LimitError manager.go The host is at a limit of its configuration. 429 limit_reached
*gpu.ErrUnavailable internal/gpu The host cannot give the requested GPUs now. 409 gpu_unavailable
ErrSnapshotNotFound snapshot.go No snapshot has that ID, or its image is gone. 404 snapshot_not_found
*InUseError snapshot.go The daemon cannot delete a snapshot or a volume, because a sandbox depends on it. 409 in_use
*StuckError snapshot.go A suspended sandbox cannot wake as things are. The sandbox and its files stay. 409 sandbox_stuck
*UnsupportedError snapshot.go This host cannot do the operation. 501 unsupported
ErrVolumeNotFound volume.go No boxfork volume has that name. 404 volume_not_found
*ExistsError volume.go A volume with that name exists. 409 already_exists
ErrPoolNotFound pool.go No pool has that ID. 404 pool_not_found
*FSError files.go The helper refused a file operation. The status of its code
errFilesGone manager.go Internal. The image of a snapshot is not on the machine. Not sent as it is
errKeptOver kept.go Internal. The kept connection ended before the command started. Not sent
All other errors An engine failure or a failure of the state file. 500 internal

writeErr examines the error types in a fixed sequence. *StuckError comes before the “not found” errors. A StuckError can wrap ErrVolumeNotFound, and the client must not read it as “no such volume”.

When you return an error from the engine, wrap it with %w. engineErr and errors.Is need the chain.

The manager has one main lock, m.mu, and three smaller locks.

Lock Protects Held during
m.mu All maps and counters of Manager, and all fields of all records Short work in memory, and save
record.opMu The container of one sandbox against two operations at the same time Pause, resume, the commit of a snapshot, a suspension, a wake, reap, syncPaused, the kill of a suspended sandbox
record.connGate The start of the kept connection of one sandbox. It is a channel with one place, so that a request can stop its wait. keptFor
m.volMu The creation and the deletion of volumes CreateVolume, DeleteVolume, ensureDefaultVolumes
  1. Do not call the engine while you hold m.mu. An engine call can take minutes, and each API request needs the lock.
  2. Do not call the GPU allocator while you hold m.mu. The allocator has its own lock, and Allocate starts a program to read the GPUs.
  3. Do not wait for opMu, connGate or volMu while you hold m.mu. Take those locks first.
  4. Do not take m.mu two times. It is not a lock that one goroutine can take again.
  5. Call save only while you hold m.mu. This is the one slow operation that the lock permits.
  6. After you release m.mu and take it again, examine the record again.
  7. Change the saved fields of a record and call save in the same hold of the lock.

For rule 6, the code uses this pattern after each engine call:

m.mu.Lock()
if cur, ok := m.boxes[id]; !ok || cur != rec || rec.hidden() {
m.mu.Unlock()
return ErrNotFound
}

The lookup finds a record that forget deleted during the engine call. The check on hidden or dying finds a kill that started during the engine call.

A comment on each function says if the caller holds m.mu. This table gives the most important functions.

The caller must hold m.mu The function takes m.mu itself
save, owned, handOut, hasOrphan, idle forget, remove, discard, engineErr
mark, markPaused, markResumed, dropConn unrefSnapshot, forgetLostSnapshot, emptyTrash
holdVolumes, releaseVolumes, volumeUsers use, wake, wakeLocked, suspend
refSnapshot, poolLike, poolView, waiting, take, sizeAllowed, resize, poolOn retryOrphans, reap, syncPaused, drainPools

fromPool is special. The caller holds m.mu, fromPool releases it for Engine.Inspect, and it holds the lock again when it returns. New calls save, markPaused and markResumed with no lock, because no other goroutine exists then.

  • A call from a client waits for opMu: setPaused, wake, snapshot, and Kill of a suspended sandbox.
  • A background loop only tries opMu: suspend, reap, syncPaused, and Sweep for a suspended sandbox. A loop must not block.
  • wakeLocked and snapshot with held set are for a caller that holds opMu.
  • Kill of a sandbox that is not suspended does not take opMu. A commit in progress can then get “not found” from the engine.

The reason for opMu is the commit of a snapshot. The engine freezes the container during a commit. Without opMu, syncPaused reads that freeze as a pause, or a resume cancels it.

This table gives each limit of the manager. A limit with no constant name is a literal in the code.

Limit Constant or field Value
Default timeout of a sandbox Config.DefaultTimeout 5 minutes
Maximum timeout Config.MaxTimeout No maximum
Default CPU limit Config.DefaultCPUs 2
Default memory limit Config.DefaultMemoryMB 1024 MiB
Minimum default memory of a GPU sandbox literal in Create 8192 MiB
Shared memory of a container literal in boot Half of the memory limit
Processes in a container Config.PidsLimit 4096
Sandboxes Config.MaxSandboxes No maximum
Kept snapshots Config.MaxSnapshots No maximum
Volumes Config.MaxVolumes No maximum
Waiting sandboxes in all pools DefaultMaxPooled 64
Mounts of one sandbox MaxMounts 16
Length of a volume name volumeName 63 characters
Minimum idle time before a suspension MinSuspendAfter 10 seconds
Layers below a container that the daemon can suspend MaxLayers 100
Copies of one fork MaxFork 64
Creates of one fork at the same time forkParallel 8
Starts for pools at the same time poolParallel 4
Starts for pools in one pass poolBatch 8
Wait after a failed start for a pool poolRetry 30 seconds
Time that a failed snapshot stays in trash trashGrace 1 hour
Idle time of a kept connection DefaultConnectionIdle 1 minute
Standard input of a command on the kept connection keptStdin 1 MiB
Wait for the hello of the helper keptHello 15 seconds
Wait for the helper to take a frame keptStall 10 seconds
Answer line of a file operation maxAnswer 32 MiB
Answer line of a helper question (ask) literal in askAs 16 KiB
Wait for guest version, dns, own, procs literal 30 seconds each
Wait for guest gpus literal in checkGPUs 45 seconds
Removal of a container in discard literal 30 seconds
Pause or resume literal in setPaused 1 minute
A wake literal in wakeLocked 5 minutes
The commit of a snapshot literal in snapshot 15 minutes
Sweep period literal in Watch 1 second
Reclaim period literal in Watch 2 seconds
Pool period literal in WatchPools 10 seconds
Reconcile period literal in Watch 20 seconds
  1. One sandbox has a maximum of one container. The name of the container is boxfork-<sandbox ID>.
  2. The manager releases a GPU only after the engine removed the container that held it.
  3. No function calls the engine or the GPU allocator while it holds m.mu.
  4. A client cannot see a sandbox before its record is in the state file.
  5. A create that fails leaves no container, no held GPU, no user count and no record. The one exception is an entry in orphans.
  6. A function examines its record again after each time that it takes m.mu again.
  7. A hidden record refuses each call from a client.
  8. The manager removes only a container that has the label boxfork.managed=true and a name that starts with boxfork-.
  9. The state file contains no environment variable.
  10. Cleanup uses context.WithoutCancel and a time limit. A client that goes away must not stop a cleanup.
  11. The manager writes the ID of a snapshot to discarded before it asks the engine for the commit.
  12. A background loop does not wait for opMu.
  13. forget is the only place that deletes the record of a sandbox that a client can see.
Failure What the manager does
The engine cannot pull the image boot returns an error. “Not found” becomes an InvalidError.
The engine makes a container and loses the answer fail removes the container by its name.
The engine cannot remove a container after a failed create The container goes to orphans. Its GPUs stay held until retryOrphans removes it.
The helper does not answer guest version in 30 seconds boot fails and removes the container.
The engine uses a different runtime than Config.Runtime boot fails and removes the container.
The helper cannot set the name servers The create succeeds. The daemon writes a warning.
A GPU sandbox sees the wrong GPUs boot fails. The allocator distrusts the GPUs.
save fails at the end of a create Create removes the container and returns “recording the sandbox”.
The engine cannot remove a container at a kill Kill returns the error. The sandbox stays and is not dying.
The engine cannot remove a container at a timeout Sweep writes an error and tries again each second.
A container stops by itself, for example from a lack of memory The next Reconcile removes it and forgets the sandbox. The log line gives oom_killed.
A command finds that the container is gone engineErr forgets the sandbox immediately and returns ErrNotFound.
The engine loses the answer of a pause setPaused inspects the container and believes the engine.
A person pauses a container with the engine tools syncPaused corrects the record on the next Reconcile.
The engine cannot list the containers Reconcile writes an error and stops this pass. It forgets nothing.
The state file is damaged at a start The daemon does not start.
The daemon stops during a create The container has no record. The next New removes it.
The daemon stops during a fork The copies have Fork set. The first Sweep removes them.
A second daemon with its own state file starts on the same engine Its New removes the containers of the first daemon as containers without a record.
  1. Decide if the field must stay after a restart.
  2. If it must stay, add an exported field with a JSON tag and omitempty to record.
  3. If it must not stay, add a private field.
  4. If the client must see the field, add it to Sandbox and not to record.
  5. Write to the field only while you hold m.mu.
  6. Call save in the same hold of the lock, if the field is in the state file.
  7. Decide what New does with an old state file in which the field is absent.
  8. If a hand-out changes the field, add it to handedFields, snapshotOfFields and restoreFields.
  9. Add a test that restarts the manager and reads the field. Use TestRestartRecovery as the example.
  10. Do not put a secret in an exported field.
  1. If the step is a check of the request, put it in Create before the lock. Return invalid(...).
  2. If the step talks to the engine or the helper, put it in boot.
  3. Put the step after createTried = true only if it needs the container.
  4. Return each error of the step through fail. Do not return directly after the GPU allocation.
  5. Decide if a failure of the step must fail the create. setDNS and giveVolumes only write a warning.
  6. Remember that a wake and a fork also run boot. Make sure that the step is correct for them.
  7. If the step changes what a waiting sandbox is, add its input to setupOf.
  8. Add a case to TestFailedCreateLeavesNothing that makes the engine operation of the step fail.
  9. Make sure that the test finds no container and no held GPU after the failure.
  1. Add the field to Config with a comment that gives the meaning of zero.
  2. If the field has a default, set it in Config.defaults.
  3. Add the flag to serve in cmd/boxfork/main.go and pass the value to sandbox.New.
  4. Return a LimitError when the host is at the limit and an InvalidError when the request is wrong.
  5. If a create in progress must count, add a counter such as pending.
  6. Add the limit to the table in this page.
  7. Add a test such as TestMaxSandboxes.
  1. Decide which loop does the work. Use the table of the background loops.
  2. If the work can take a long time, give it its own goroutine in Watch.
  3. Make the list of the work under m.mu. Then release the lock.
  4. Examine each record again under the lock before you act on it.
  5. Use opMu.TryLock, not opMu.Lock.
  6. Write a failure to the log and let the next pass try again.
  7. Call the function directly in the test. Use e.clock.Advance to move the time.

The unit tests use the test engine in internal/engine/enginetest/fake.go. The test engine runs the real helper code in the test process, thus the tests use the real protocol. Its containers have no isolation. The function setup in manager_test.go makes a manager, a test engine and a clock that the test controls. It also makes the number of GPUs that the test asks for. These GPUs are not real.

Run the Go tests with make test-go. The target runs go vet and go test -race.

File Topic
internal/sandbox/manager_test.go Create, kill, timeouts, pause, restart, reconcile, detection
internal/sandbox/faults_test.go Failures of the engine and of GPUs
internal/sandbox/gpucheck_test.go The GPU check in boot
internal/sandbox/dns_test.go setDNS
internal/sandbox/review5_test.go giveVolumes, NetworkReady, mounts of a copy
internal/api/server_test.go The same paths through the HTTP API

The most important tests for this page:

Test What it proves
TestCreateRunKill The full life of one sandbox.
TestCreateValidation The checks in Create.
TestFailedCreateLeavesNothing Six engine operations fail in turn. Each time, no container, no record and no held GPU stay.
TestACreateWhoseAnswerIsLostLeavesNoContainer fail removes a container by name when the engine lost the answer.
TestGPUsAreExclusive Two sandboxes never hold one GPU.
TestAGPUStaysHeldWhileItsContainerCannotBeRemoved orphans and retryOrphans.
TestTimeoutSweep, TestSweepRetriesAFailedKill Sweep kills at the timeout and tries again after an engine failure.
TestSweepHonoursWhatChangedSinceItLooked remove with onlyExpired reads the timeout again under the lock.
TestPauseStopsTheClock, TestSetTimeout RemainingNS, markPaused, markResumed, SetTimeout.
TestPauseAndResumeSurviveALostAnswer setPaused inspects the container after an engine error.
TestMaxSandboxes atLimit and pending.
TestRestartRecovery The reconciliation in New.
TestOnlyOwnContainersAreEverRemoved The label check and the name check in New.
TestDamagedStateFile, TestStateFileHoldsNoEnvironment, TestConfigAndStateEdges The state file.
TestReconcile, TestVanishedContainer, TestReconcileCorrectsThePausedState Reconcile, engineErr, syncPaused.
TestReconcileLooksAgainBeforeItForgets reap examines the record again after it gets opMu.
TestDetect, TestCheckNetwork Detect and CheckNetwork.
TestARestartWhileASandboxsGPUIsGone New keeps a sandbox whose GPU the driver does not list.
  • Nobody ran the GPU path on NVIDIA GPU hardware. The tests use GPUs that are not real, and the test engine answers guest gpus itself. This applies to Allocator.Allocate, the nvidia and cdi device names, NVIDIA_VISIBLE_DEVICES, checkGPUs and the release after a kill.
  • Nobody ran the daemon on x86_64.
  • Nobody ran the daemon on a real AWS account or a real Google Cloud project.
  • The runs on a real engine were on Docker with gVisor on arm64, in a nested virtual machine, and on Podman.
  • The time of 139 ms for a create is from that test machine. Nobody measured it on a server that is not a nested virtual machine.
  • The unit tests do not cut the power during save. The atomic write depends on Sync and rename of the file system, and no test proves it.
  • loadState does not examine version. No test reads a state file from a different version of the format.
  • No test runs two daemons on one engine. The code does not refuse the second daemon.
  • No test measures how long Sweep waits when Reconcile is slow.