Skip to content

The engine layer

This page describes the package internal/engine: the interface between the daemon and the engine. It is for a contributor who changes the Docker driver, the test engine, or who adds a new backend. After you read this page, you know what each method must guarantee and where the tests are.

This page uses one more name. An exec is one process that the engine starts in a container for the daemon, with its standard streams attached.

File Contents
internal/engine/engine.go The interface Engine, its data types, and the errors ErrNotFound, ErrExists, ErrInUse.
internal/engine/docker.go The type Docker: the driver for the Docker Engine API.
internal/engine/enginetest/fake.go The type Fake: the test engine.
internal/sandbox/manager.go Detect and tryRuntime: the selection and the check of the isolation. Manager.boot: the user of most methods.
cmd/boxfork/main.go serve makes the driver with engine.NewDocker and gives it to sandbox.Config.Engine.

The rest of the daemon uses only the interface. The package internal/sandbox does not import the Docker driver. The reason for this layer is in decision 2 and decision 4 of decisions.md.

The table gives each method and what the callers depend on. A driver that does not keep a guarantee causes a defect in the daemon, not only in the driver.

Method What it does What it must guarantee
Info It describes the engine. Runtimes contains each runtime name that the engine offers. Detect looks for runsc there.
EnsureImage It gives a local image. It pulls the image first if it is not local. It fills Arch, OS, Volumes and Layers. For an image that does not exist, the error matches ErrNotFound.
LocalImage It gives an image that is on the machine. It never pulls. For an image that is not there, the error matches ErrNotFound.
EnsureNetwork It creates the network if it is not there. The result isolated comes from a read of the network, not from the request. A second call for the same name is not an error.
NetworkSubnets It gives the address ranges of a network. Each item is a prefix such as 172.18.0.0/16.
Create It creates a container and gives its ID. It does not start the container. It applies each field of CreateSpec.
CopyIn It puts files in a container. It works before the start of the container. It creates the parent directories.
Start It starts the first process. The process is the Entrypoint of the spec, with no other arguments.
Remove It kills and deletes a container. It accepts an ID or a name. A container that is not there is not an error.
Pause, Unpause They freeze and continue all processes. After an error, Inspect gives the true state.
Inspect It gives the state of one container. It fills Runtime with the runtime that the engine really used. A container that is not there gives ErrNotFound.
List It gives each container that has a label. It includes containers that do not run. It gives only containers that really have the label.
Exec It starts an exec and gives its streams. See “What Exec must guarantee” below.
Commit It saves the files of a container as a local image. The container is frozen during the read of its files. The image has the name ref.
RemoveImage It deletes a local image. An image that is not there is not an error. An image that a container uses gives ErrInUse.
CreateVolume It makes an empty volume. A name that exists gives ErrExists.
Volume It gives one volume. A name that is not there gives ErrNotFound.
Volumes It gives each volume that has a label. It gives only volumes that really have the label.
RemoveVolume It deletes a volume and its contents. A name that is not there gives ErrNotFound. A mounted volume gives ErrInUse.

The callers compare errors with errors.Is. A driver can wrap the three error values in its own error type.

The helper protocol depends on these rules. See helper.md.

  • The context limits only the start of the exec. After the start, the stream lives until the caller closes it.
  • ExecStream.Stdin and ExecStream.Stdout move bytes in order and do not change them.
  • ExecStream.Stderr gives the error text that the process wrote up to now.
  • When the caller closes the stream, the process sees the end of its input. The helper then kills its command.
  • ExecSpec.User set to 0 runs the process as root. An empty value runs it as the user of the image.
  • A container that is not there gives an error that matches ErrNotFound. The daemon then drops the record.
Type Purpose Important fields
Info The engine Product (docker or podman), Version, Runtimes, DefaultRuntime, CDIDevices
Image A local image Arch selects the helper. Volumes are paths that a commit does not save. Layers limits the number of suspensions.
CreateSpec A container to create Name, Image, Entrypoint, Env, Labels, CPUs, MemoryMB, ShmMB, PidsLimit, Runtime, Network, GPU, Mounts
GPURequest GPUs for a container Driver (nvidia or cdi), DeviceIDs
Mount A volume at a path Volume is a volume name, never a host path. Path, ReadOnly
File A file for CopyIn Path, Mode, Data
ExecSpec An exec to start Argv, Env, User, WorkingDir
ExecStream The streams of an exec Stdin, Stdout, Stderr, Close
Container The state of a container ID, Name, Labels, Running, Paused, OOMKilled, ExitCode, Runtime
Volume A volume Name, Labels, CreatedAt

CreateSpec.Network has three values: none, a network name, or empty for the default of the engine. The daemon sets none or the name boxfork. See network.md.

The type Docker uses only the standard library of Go. The reason is the size of the daemon: one small program with no dependencies. The cost is that we write each request and each answer type by hand.

NewDocker accepts unix:///path or tcp://host:port. With an empty address it uses the variable DOCKER_HOST, then DefaultDockerHost, unix:///var/run/docker.sock. The HTTP client has a DialContext that always connects to that one address. The request URL starts with http://engine and has no API version in the path.

Three functions make the requests:

  • Docker.do sends one request and changes a status of 400 or more to an APIError.
  • Docker.call sends a JSON body and decodes a JSON answer.
  • apiError reads a maximum of 64 KiB of the answer and uses its message field.

APIError.Is maps the HTTP status to the error values:

HTTP status Matches
404 ErrNotFound
409 ErrInUse
Method HTTP request
Info GET /info, then GET /version for the product name
LocalImage GET /images/{ref}/json
EnsureImage GET /images/{ref}/json, then POST /images/create?fromImage=&tag= if it is not local
EnsureNetwork GET /networks/{name}, then POST /networks/create if it is not there
NetworkSubnets GET /networks/{name}
Create POST /containers/create?name=
CopyIn PUT /containers/{id}/archive?path=/ with a tar body
Start POST /containers/{id}/start
Remove DELETE /containers/{id}?force=true&v=true
Pause, Unpause POST /containers/{id}/pause, POST /containers/{id}/unpause
Inspect GET /containers/{id}/json
List GET /containers/json?all=true&filters=
Exec POST /containers/{id}/exec, then POST /exec/{id}/start with an upgrade
Commit POST /commit?container=&repo=&tag=&pause=true
RemoveImage DELETE /images/{ref}
CreateVolume GET /volumes/{name}, then POST /volumes/create
Volume GET /volumes/{name}
Volumes GET /volumes?filters=
RemoveVolume DELETE /volumes/{name}

EnsureImage looks for the image first. If the image is local, the driver uses it and does not ask a registry. If it is not local, splitRef divides the reference into a name and a tag or a digest. The driver always sends the tag: with no tag, the engine pulls all tags. A reference with no tag gets the tag latest.

The engine reports the progress of a pull as a sequence of JSON objects, after the status 200. A failure in the middle of the pull is one of these objects, with an error field. The driver reads each object and gives the first error as the error of the pull. The driver sends no registry credentials.

Docker.Create writes these fields of HostConfig:

CreateSpec HostConfig Value
always SecurityOpt no-new-privileges
always CapDrop NET_RAW, MKNOD, AUDIT_WRITE
CPUs NanoCpus CPUs multiplied by 1e9
MemoryMB Memory The value in bytes
MemoryMB MemorySwap The same value, thus the container gets no swap
ShmMB ShmSize The value in bytes
PidsLimit PidsLimit The value
Runtime Runtime The name, for example runsc
Network NetworkMode none or the network name
Mounts Mounts Type volume, NoCopy true
GPU DeviceRequests Driver, DeviceIDs, and Capabilities [["gpu"]] if the driver is not cdi

The driver omits a limit when its value is 0. The reasons for the security options:

  • no-new-privileges: a process in the sandbox cannot get privileges that it did not start with.
  • NET_RAW: raw sockets let a container send packets with a false address on the shared bridge.
  • MKNOD and AUDIT_WRITE: a sandbox does not need to make device nodes or audit records.

A mount always has the type volume and never bind. Thus the source is a volume name and cannot be a path on the host. NoCopy stops the engine from a copy of image files into a new volume.

The body sets Entrypoint from the spec and Cmd to an empty list. The driver sorts the environment variables, thus the request is the same for the same spec.

The values of the limits come from Manager.boot and Config.defaults in internal/sandbox/manager.go:

Limit Default Source
CPUs 2 Config.DefaultCPUs
Memory 1024 MB. 8192 MB for a sandbox with a GPU that gives no value Config.DefaultMemoryMB
Shared memory Half of the memory ShmMB: rec.MemoryMB / 2
Processes 4096 Config.PidsLimit

Docker.CopyIn makes a tar archive in memory. For each file it writes the parent directories first, each one time, with mode 0755. Then it sends the archive to the path / of the container. The daemon uses this method only for the helper.

An exec needs a connection with two directions. The Engine API gives it through an HTTP upgrade: after the answer, the TCP or Unix connection becomes a raw stream. The driver writes this request by hand in Docker.Exec.

sequenceDiagram
participant D as Docker.Exec
participant E as Engine
D->>E: POST /containers/{id}/exec (Cmd, Env, User, WorkingDir, attach all streams, no TTY)
E-->>D: the ID of the exec
D->>E: new connection, POST /exec/{execID}/start, Connection: Upgrade, Upgrade: tcp
E-->>D: status 101, or status 200 from an older engine
Note over D,E: The connection is now a raw stream
D->>E: bytes for the standard input
E-->>D: blocks, each with a header of 8 bytes

The steps in the code:

  1. Docker.call creates the exec and reads its ID.
  2. Docker.dial opens a new connection that the HTTP client does not own.
  3. The driver sets a deadline: the deadline of the context, or 30 seconds.
  4. The driver writes the start request as text and reads the answer with http.ReadResponse.
  5. The driver accepts the status 101 or 200. Other statuses become an APIError.
  6. The driver removes the deadline.
  7. The driver gives an ExecStream: the connection is Stdin and Close, a demux is Stdout.

The engine sends the output of the process in blocks. Each block has a header of 8 bytes.

Byte Contents
0 The stream: 1 is the standard output
1 to 3 Not used
4 to 7 The length of the block, big-endian

demux.Read gives the blocks of stream 1 to the reader. It keeps the blocks of all other streams as error text, to a maximum of maxStderr, 16 KiB. It drops error text above that limit. The driver reads the error text only while the caller reads Stdout.

The driver does not close one direction of the connection. Thus the helper protocol has its own frame for the end of the standard input. A close of the stream closes the full connection.

Docker.Commit divides ref with splitRef and sends pause=true. The engine thus freezes the container during the read of its files. The daemon gives a snapshot the image name boxfork-snapshot:<id>: see snapshotRef in internal/sandbox/snapshot.go.

An image from a commit keeps the labels of its container. For this reason Manager.boot sets all three labels on each container, also the empty ones. A commit does not save a path that the image keeps in a volume, and it does not save a mounted volume.

The package internal/sandbox selects the labels and the names. The driver only sends them and reads them.

Item Value Constant
Label on each container, each volume and the network boxfork.managed=true LabelManaged
Label with the sandbox ID boxfork.id LabelID
Label with the GPU identifiers, or empty boxfork.gpus LabelGPUs
Label on each volume boxfork.volume LabelVolume
Container name boxfork-<sandbox ID> in Manager.boot
Volume name boxfork-vol-<name> volumePrefix
Network name boxfork NetworkName

Docker.List and Docker.Volumes send a label filter to the engine. Then they examine each result and drop an item that does not have the label. The reason: the callers remove what these methods give. With no such check, an engine that ignores the filter gives each container on the host to the callers.

When the daemon starts, sandbox.New removes each labeled container that no record knows. It removes only a container with a name that starts with boxfork-. A container that a person starts by hand from a snapshot image has the labels but not the name.

Docker.EnsureNetwork creates a bridge network with the option com.docker.network.bridge.enable_icc set to false. It then reads the network again and reports what the engine kept. A status 409 from the create request means that the network came to exist in the meantime. See network.md.

Docker.CreateVolume looks for the name first. The reason: the engine answers a create request for a name that exists with the volume that is there. The caller prevents two create requests at the same time.

Docker.Remote is a method of the driver and not of the interface. It reports that the engine is on a different machine: a tcp address that is not localhost and not a loopback address. serve uses it for the block of the metadata service.

How the daemon selects and verifies the isolation

Section titled “How the daemon selects and verifies the isolation”

The isolation is gVisor (gvisor) or a plain container (container). The flag --isolation of boxfork serve has the values auto, gvisor and container. sandbox.Detect makes the decision when the daemon starts.

An engine can show the runtime name runsc when gVisor is not installed. Thus Detect does not trust the list of runtimes. tryRuntime starts one real container with the runtime and reads the result.

flowchart TD
A["--isolation"] -->|container| P["plain container"]
A -->|"auto or gvisor"| B{"Info shows runsc?"}
B -->|"no, auto"| P
B -->|"no, gvisor"| X["the daemon does not start"]
B -->|yes| C["tryRuntime: a trial container with Runtime runsc"]
C --> D{"It runs, and Inspect gives Runtime runsc?"}
D -->|yes| G["gVisor"]
D -->|"no, auto"| N["plain container, and a note in the log"]
D -->|"no, gvisor"| X
C -->|"the trial itself fails"| X

The trial container has these properties:

  • The name boxfork-probe-<random> and the labels boxfork.managed=true and boxfork.id=probe.
  • 1 CPU, 256 MB of memory, a limit of 64 processes, and the network none.
  • The helper as its first process.

If the daemon stops during the trial, the next start removes the container as one that no record knows.

tryRuntime gives two different results for a failure:

What fails Result
The pull of the image, the helper for the architecture, Inspect, the removal of the trial container An error. The daemon knows nothing about the runtime, and it does not start.
Create, CopyIn, Start A reason. The runtime is not usable.
The container does not run after the start A reason.
Inspect gives a different runtime name A reason.

The daemon does the same check for each sandbox. When Config.Runtime is not empty, Manager.boot calls Inspect after Start. If Container.Runtime is not equal to Config.Runtime, boot removes the container and the create operation fails. Thus the field isolation of a sandbox is gvisor only for a container that the engine reports with runsc.

When the isolation is container, the daemon writes a warning: sandboxes share the kernel of the host.

One more check depends on the runtime. Manager.CheckSnapshots in internal/sandbox/snapshot.go makes sure that a commit contains the files of a sandbox. With runsc, a commit can be empty if the runtime does not have the argument --overlay2=none. In that case the daemon switches off snapshot, fork and suspension, and says why.

Podman serves the same API, and the driver has no separate code path for it. The code and the tests record these differences:

Topic On Podman Where the daemon handles it
Product name A component name of GET /version contains podman. Docker.Info sets Info.Product. boxfork info shows it.
Runtime The API accepts a runtime name and runs the container with its default runtime. tryRuntime compares Container.Runtime. The result is isolation container.
Sandbox-to-sandbox block Podman drops the bridge option that it does not know. EnsureNetwork reads the option again and gives isolated false. serve writes a warning.
Metadata-service block The daemon cannot set the rule. hostfw.Block needs the DOCKER-USER chain of Docker and gives ErrUnavailable. See network.md.

enginetest.Fake is an engine in memory. The unit tests of internal/sandbox and internal/api use it, and so does the program cmd/boxfork-testserver for the SDK tests.

  • Containers. Create, CopyIn, Start, Remove by ID or name, Pause, Inspect and List keep a map of containers with their spec.
  • The helper. Fake.Exec runs guest.Main in the test process and connects it with pipes. Thus the tests use the real protocol.
  • A helper that is not there. Exec fails if CopyIn did not put the helper at guest.Path.
  • The end of a container. Remove and Stop close the input of each helper of the container.
  • Images. EnsureImage knows only the images that the test gives. Other names give ErrNotFound.
  • Commits. Commit makes an image with one more layer and the volumes of the source image.
  • Images in use. RemoveImage gives ErrInUse while a container uses the image.
  • Volumes. Create fails for a mount of a volume that does not exist. RemoveVolume gives ErrInUse for a mounted volume.
  • Runtimes. Runtimes, BrokenRuntimes and IgnoreRuntime imitate an engine with gVisor, with a defective runtime, and Podman.
  • A network that does not isolate. OpenNetwork makes EnsureNetwork give false.

A test injects failures with these fields:

Field Effect
Fail and SetFail The named operation gives an error and does nothing.
Lose The named operation does its work and then gives an error, as when the answer does not arrive.
IgnoreFilter List and Volumes give all items, as an engine that ignores the label filter.
OnCommit, OnRemove A function of the test runs in the middle of the operation.
ExecHook, ExecIn A function of the test gives the stream in the place of the helper.
GPUsSeen, Procs, DNSAnswer, OwnAnswer The answer line of the modes gpus, procs, dns and own.
  • Isolation. A command runs as a process of the test, on your machine, with your user and your files.
  • A container filesystem. CopyIn only records the file. A file operation changes files of your machine.
  • Saved files. A commit records a name. It contains no files.
  • Limits. CPU, memory and process limits have no effect.
  • A network. There are no addresses and no packets. NetworkSubnets gives the list Subnets.
  • A frozen container. Pause sets a flag. Exec refuses a paused container, but processes that run continue.
  • The HTTP API. The hijack, the block headers and the conversion of errors of the Docker driver do not run.
  • GPUs. With no GPUsSeen function, a container sees the identifiers of its spec.
  • Four modes of the helper. The test engine answers gpus, procs, dns and own itself.

The test engine answers those four modes because the real code reads or changes the machine. For example, the real dns mode writes the resolver file of the machine on which it runs.

A change must keep these rules.

  • The package internal/sandbox uses only the interface. Do not put Docker types in it.
  • A mount is always a named volume. Do not add a host path to Mount.
  • List and Volumes give only items that have the label. The callers remove what they get.
  • Remove gives no error for a container that is not there, and it accepts a name.
  • Inspect reports the runtime that the engine used, not the runtime of the request.
  • EnsureNetwork reports what the engine kept, not what the driver sent.
  • A close of an ExecStream ends the input of the process.
  • The context of Exec limits only the start.
  • Each container gets the security options of Docker.Create. Do not make them optional.
  • The driver uses only the standard library.
  • When you add a method to Engine, add it to Docker and to Fake.
Failure What the driver gives What the daemon does
The engine does not answer at the address “cannot reach the container engine at …” serve stops at the start with a text that names Docker.
The image is not in the registry An error that matches ErrNotFound The create request fails with “image was not found”.
The pull fails in the middle An error with the text of the engine The create request fails.
Create did its work but the answer did not arrive An error Manager.boot removes the container by its name.
Remove fails An error For a kill request, the sandbox stays and the client gets the error. In other cases the daemon tries again later. See gpu.md.
The container is gone at Exec An error that matches ErrNotFound Manager.engineErr drops the record and answers “sandbox not found”.
The engine starts the container with a different runtime Inspect gives the real runtime Manager.boot removes the container.
Pause fails An error Manager.setPaused calls Inspect and uses the real state.
The helper writes much error text It drops the text above 16 KiB The error text of the command is short.
Commit fails or saves no files An error, or an empty image Manager.CheckSnapshots switches off snapshot, fork and suspension.

A new backend is a type that has all methods of Engine. An example is a microVM backend. The roadmap lists it and the tree does not contain it.

  1. A sandbox whose first process is the helper, with the helper file in place before the start.
  2. An exec in a sandbox that runs, with input, output and error text.
  3. The end of the input of an exec when the daemon closes the stream.
  4. An exec as root for User set to 0, and as the user of the image for an empty value.
  5. Names, labels and a list by label. The daemon finds its containers with them after a restart.
  6. A removal by ID or by name that gives no error for a container that is not there.
  7. Pause and unpause of all processes.
  8. Saved files under a local name: Commit, LocalImage, RemoveImage, with Image.Layers and Image.Volumes.
  9. A network with a report on the sandbox-to-sandbox block, its address ranges, and the value none.
  10. Limits for CPU, memory, shared memory and the number of processes.
  11. Its own security options that are equal to those of Docker.Create.
  12. Named volumes with labels, read-only mounts, and ErrExists, ErrNotFound, ErrInUse.
  13. GPUs from a GPURequest, if the backend supports GPUs.
  14. A value of Container.Runtime that the daemon can compare with Config.Runtime.
  15. An Image.Arch that guestbin.For knows: amd64, x86_64, arm64 or aarch64.

If the backend cannot save files, Commit must give an error. Manager.CheckSnapshots then switches off snapshot, fork and suspension for the host.

  1. Read internal/engine/engine.go and the table of guarantees on this page.
  2. Create a new file in internal/engine with a type for the backend.
  3. Write each method of Engine for the type.
  4. Make each error match ErrNotFound, ErrExists or ErrInUse where the table says so.
  5. Write Exec first, and make sure that a close of the stream ends the input of the process.
  6. Run the helper modes version, run, serve and fs through your Exec by hand.
  7. Add a constant for the isolation next to IsolationGVisor in internal/sandbox/manager.go.
  8. Change sandbox.Detect, which knows only runsc, to select and verify the new isolation.
  9. Add a flag to serve in cmd/boxfork/main.go that selects the backend.
  10. Give the metadataGuard a value for remote, which now comes from Docker.Remote.
  11. Decide how the backend blocks the metadata service, because hostfw uses a chain of Docker.
  12. Decide if Manager.setDNS is necessary, because it runs only for the runtime runsc.
  13. Write unit tests for the backend, as internal/engine/docker_test.go does for Docker.
  14. Run make test.
  15. Change the proof scripts in scripts/proof, which call the docker command, and run them on a real machine.
  16. Add the backend to this page, to network.md and to gpu.md.

The tree has no set of tests that runs against a given Engine. The tests of internal/sandbox create the test engine directly. Thus they do not prove a new backend.

  1. Find the method in internal/engine/docker.go.
  2. Change the stand-in API in fakeAPI.ServeHTTP in docker_test.go to accept the new request.
  3. Add a test that examines the request that the driver sends.
  4. If the behavior of the method changes, make the same change in Fake.
  5. Run go test ./internal/engine/....
  6. Run the proof scripts on a real engine, because the stand-in API is not Docker.
File What it tests
internal/engine/docker_test.go The Docker driver against fakeAPI, a stand-in for the Engine API on a Unix socket: addresses, splitRef, Info, pulls, the create body, the tar archive, the exec stream, the conversion of errors, networks, volumes.
internal/sandbox/manager_test.go TestDetect: the selection of the isolation. TestCheckNetwork. The use of the interface by Manager.
internal/sandbox/faults_test.go Failures of the engine with Fail and Lose.
scripts/proof/conn.sh, scripts/proof/pool.sh Proof scripts for a real engine. They call the HTTP API of the daemon and the docker command.

enginetest.Fake has no tests of its own.

  • The Docker driver ran on Docker with gVisor on arm64, in a nested virtual machine, and on Podman. It did not run on x86_64.
  • DeviceRequests did not run on a machine with an NVIDIA GPU. The tests only examine the request body.
  • No test in the tree connects to an engine at a tcp address on a different machine.
  • The answer status 200 for the exec upgrade comes from the code. No test uses an engine that sends it.
  • No backend other than the Docker driver exists. The procedure “How to add a new backend” comes from the code and nobody did it.
  • The driver sends no registry credentials. Pull a private image to the machine with the tools of the engine first.
  • Info.CDIDevices and Info.DefaultRuntime have values, but no code of the daemon reads them.
  • The driver keeps a maximum of 16 KiB of error text for each exec.
  • Docker.CopyIn holds the full archive in memory. It is made for the helper, not for large files.
  • One daemon for one engine: a second daemon removes the containers of the first when it starts.