1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
16 "git.arvados.org/arvados.git/sdk/go/arvados"
17 dockertypes "github.com/docker/docker/api/types"
18 dockercontainer "github.com/docker/docker/api/types/container"
19 dockerclient "github.com/docker/docker/client"
20 "golang.org/x/net/context"
23 // Docker daemon won't let you set a limit less than ~10 MiB
24 const minDockerRAM = int64(16 * 1024 * 1024)
26 // DockerAPIVersion is the API version we use to communicate with the
27 // docker service. The oldest OS we support is Ubuntu 18.04 (bionic)
28 // which originally shipped docker 1.17.12 / API 1.35 so there is no
29 // reason to use an older API version. See
30 // https://dev.arvados.org/issues/15370#note-38 and
31 // https://docs.docker.com/engine/api/.
32 const DockerAPIVersion = "1.35"
34 type dockerExecutor struct {
36 logf func(string, ...interface{})
37 watchdogInterval time.Duration
38 dockerclient *dockerclient.Client
40 savedIPAddress atomic.Value
45 func newDockerExecutor(containerUUID string, logf func(string, ...interface{}), watchdogInterval time.Duration) (*dockerExecutor, error) {
46 // API version 1.21 corresponds to Docker 1.9, which is
47 // currently the minimum version we want to support.
48 client, err := dockerclient.NewClient(dockerclient.DefaultDockerHost, DockerAPIVersion, nil, nil)
49 if watchdogInterval < 1 {
50 watchdogInterval = time.Minute
52 return &dockerExecutor{
53 containerUUID: containerUUID,
55 watchdogInterval: watchdogInterval,
60 func (e *dockerExecutor) Runtime() string {
61 v, _ := e.dockerclient.ServerVersion(context.Background())
63 for _, cv := range v.Components {
67 info += cv.Name + " " + cv.Version
70 info = "(unknown version)"
72 return "docker " + info
75 func (e *dockerExecutor) LoadImage(imageID string, imageTarballPath string, container arvados.Container, arvMountPoint string,
76 containerClient *arvados.Client) error {
77 _, _, err := e.dockerclient.ImageInspectWithRaw(context.TODO(), imageID)
83 f, err := os.Open(imageTarballPath)
88 resp, err := e.dockerclient.ImageLoad(context.TODO(), f, true)
90 return fmt.Errorf("While loading container image into Docker: %v", err)
92 defer resp.Body.Close()
93 buf, _ := ioutil.ReadAll(resp.Body)
94 e.logf("loaded image: response %s", buf)
98 func (e *dockerExecutor) config(spec containerSpec) (dockercontainer.Config, dockercontainer.HostConfig) {
99 e.logf("Creating Docker container")
100 cfg := dockercontainer.Config{
103 WorkingDir: spec.WorkingDir,
104 Volumes: map[string]struct{}{},
105 OpenStdin: spec.Stdin != nil,
106 StdinOnce: spec.Stdin != nil,
107 AttachStdin: spec.Stdin != nil,
111 if cfg.WorkingDir == "." {
114 for k, v := range spec.Env {
115 cfg.Env = append(cfg.Env, k+"="+v)
117 if spec.RAM > 0 && spec.RAM < minDockerRAM {
118 spec.RAM = minDockerRAM
120 hostCfg := dockercontainer.HostConfig{
121 LogConfig: dockercontainer.LogConfig{
124 NetworkMode: dockercontainer.NetworkMode("none"),
125 Resources: dockercontainer.Resources{
126 CgroupParent: spec.CgroupParent,
127 NanoCPUs: int64(spec.VCPUs) * 1000000000,
128 Memory: spec.RAM, // RAM
129 MemorySwap: spec.RAM, // RAM+swap
130 KernelMemory: spec.RAM, // kernel portion
133 if spec.CUDADeviceCount != 0 {
134 var deviceIds []string
135 if cudaVisibleDevices := os.Getenv("CUDA_VISIBLE_DEVICES"); cudaVisibleDevices != "" {
136 // If a resource manager such as slurm or LSF told
137 // us to select specific devices we need to propagate that.
138 deviceIds = strings.Split(cudaVisibleDevices, ",")
141 deviceCount := spec.CUDADeviceCount
142 if len(deviceIds) > 0 {
143 // Docker won't accept both non-empty
144 // DeviceIDs and a non-zero Count
146 // (it turns out "Count" is a dumb fallback
147 // that just allocates device 0, 1, 2, ...,
152 // Capabilities are confusing. The driver has generic
153 // capabilities "gpu" and "nvidia" but then there's
154 // additional capabilities "compute" and "utility"
155 // that are passed to nvidia-container-cli.
157 // "compute" means include the CUDA libraries and
158 // "utility" means include the CUDA utility programs
159 // (like nvidia-smi).
161 // https://github.com/moby/moby/blob/7b9275c0da707b030e62c96b679a976f31f929d3/daemon/nvidia_linux.go#L37
162 // https://github.com/containerd/containerd/blob/main/contrib/nvidia/nvidia.go
163 hostCfg.Resources.DeviceRequests = append(hostCfg.Resources.DeviceRequests, dockercontainer.DeviceRequest{
166 DeviceIDs: deviceIds,
167 Capabilities: [][]string{[]string{"gpu", "nvidia", "compute", "utility"}},
170 for path, mount := range spec.BindMounts {
171 bind := mount.HostPath + ":" + path
175 hostCfg.Binds = append(hostCfg.Binds, bind)
177 if spec.EnableNetwork {
178 hostCfg.NetworkMode = dockercontainer.NetworkMode(spec.NetworkMode)
183 func (e *dockerExecutor) Create(spec containerSpec) error {
184 cfg, hostCfg := e.config(spec)
185 created, err := e.dockerclient.ContainerCreate(context.TODO(), &cfg, &hostCfg, nil, e.containerUUID)
187 return fmt.Errorf("While creating container: %v", err)
189 e.containerID = created.ID
190 return e.startIO(spec.Stdin, spec.Stdout, spec.Stderr)
193 func (e *dockerExecutor) CgroupID() string {
197 func (e *dockerExecutor) Start() error {
198 return e.dockerclient.ContainerStart(context.TODO(), e.containerID, dockertypes.ContainerStartOptions{})
201 func (e *dockerExecutor) Stop() error {
202 err := e.dockerclient.ContainerRemove(context.TODO(), e.containerID, dockertypes.ContainerRemoveOptions{Force: true})
203 if err != nil && strings.Contains(err.Error(), "No such container: "+e.containerID) {
209 // Wait for the container to terminate, capture the exit code, and
210 // wait for stdout/stderr logging to finish.
211 func (e *dockerExecutor) Wait(ctx context.Context) (int, error) {
212 ctx, cancel := context.WithCancel(ctx)
214 watchdogErr := make(chan error, 1)
216 ticker := time.NewTicker(e.watchdogInterval)
219 dctx, dcancel := context.WithDeadline(ctx, time.Now().Add(e.watchdogInterval))
220 ctr, err := e.dockerclient.ContainerInspect(dctx, e.containerID)
222 if ctx.Err() != nil {
223 // Either the container already
224 // exited, or our caller is trying to
227 } else if err != nil {
228 e.logf("Error inspecting container: %s", err)
231 } else if ctr.State == nil || !(ctr.State.Running || ctr.State.Status == "created") {
232 watchdogErr <- fmt.Errorf("Container is not running: State=%v", ctr.State)
238 waitOk, waitErr := e.dockerclient.ContainerWait(ctx, e.containerID, dockercontainer.WaitConditionNotRunning)
241 case waitBody := <-waitOk:
242 // wait for stdout/stderr to complete
244 return int(waitBody.StatusCode), nil
246 case err := <-waitErr:
247 return -1, fmt.Errorf("container wait: %v", err)
252 case err := <-watchdogErr:
258 func (e *dockerExecutor) startIO(stdin io.Reader, stdout, stderr io.Writer) error {
259 resp, err := e.dockerclient.ContainerAttach(context.TODO(), e.containerID, dockertypes.ContainerAttachOptions{
266 return fmt.Errorf("error attaching container stdin/stdout/stderr streams: %v", err)
271 errStdin = e.handleStdin(stdin, resp.Conn, resp.CloseWrite)
274 e.doneIO = make(chan struct{})
276 e.errIO = e.handleStdoutStderr(stdout, stderr, resp.Reader)
277 if e.errIO == nil && errStdin != nil {
285 func (e *dockerExecutor) handleStdin(stdin io.Reader, conn io.Writer, closeConn func() error) error {
287 _, err := io.Copy(conn, stdin)
289 return fmt.Errorf("While writing to docker container on stdin: %v", err)
294 // Handle docker log protocol; see
295 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
296 func (e *dockerExecutor) handleStdoutStderr(stdout, stderr io.Writer, reader io.Reader) error {
297 header := make([]byte, 8)
300 _, err = io.ReadAtLeast(reader, header, 8)
307 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
309 _, err = io.CopyN(stdout, reader, readsize)
312 _, err = io.CopyN(stderr, reader, readsize)
316 return fmt.Errorf("error copying stdout/stderr from docker: %v", err)
321 func (e *dockerExecutor) Close() {
322 e.dockerclient.ContainerRemove(context.TODO(), e.containerID, dockertypes.ContainerRemoveOptions{Force: true})
325 func (e *dockerExecutor) InjectCommand(ctx context.Context, detachKeys, username string, usingTTY bool, injectcmd []string) (*exec.Cmd, error) {
326 cmd := exec.CommandContext(ctx, "docker", "exec", "-i", "--detach-keys="+detachKeys, "--user="+username)
328 cmd.Args = append(cmd.Args, "-t")
330 cmd.Args = append(cmd.Args, e.containerID)
331 cmd.Args = append(cmd.Args, injectcmd...)
335 func (e *dockerExecutor) IPAddress() (string, error) {
336 if ip, ok := e.savedIPAddress.Load().(*string); ok {
339 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
341 ctr, err := e.dockerclient.ContainerInspect(ctx, e.containerID)
343 return "", fmt.Errorf("cannot get docker container info: %s", err)
345 ip := ctr.NetworkSettings.IPAddress
347 // TODO: try to enable networking if it wasn't
348 // already enabled when the container was
350 return "", fmt.Errorf("container has no IP address")
352 e.savedIPAddress.Store(&ip)