1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
14 "git.arvados.org/arvados.git/sdk/go/arvados"
15 dockertypes "github.com/docker/docker/api/types"
16 dockercontainer "github.com/docker/docker/api/types/container"
17 dockerclient "github.com/docker/docker/client"
18 "golang.org/x/net/context"
21 // Docker daemon won't let you set a limit less than ~10 MiB
22 const minDockerRAM = int64(16 * 1024 * 1024)
24 type dockerExecutor struct {
26 logf func(string, ...interface{})
27 watchdogInterval time.Duration
28 dockerclient *dockerclient.Client
34 func newDockerExecutor(containerUUID string, logf func(string, ...interface{}), watchdogInterval time.Duration) (*dockerExecutor, error) {
35 // API version 1.21 corresponds to Docker 1.9, which is
36 // currently the minimum version we want to support.
37 client, err := dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
38 if watchdogInterval < 1 {
39 watchdogInterval = time.Minute
41 return &dockerExecutor{
42 containerUUID: containerUUID,
44 watchdogInterval: watchdogInterval,
49 func (e *dockerExecutor) LoadImage(imageID string, imageTarballPath string, container arvados.Container, arvMountPoint string,
50 containerClient *arvados.Client) error {
51 _, _, err := e.dockerclient.ImageInspectWithRaw(context.TODO(), imageID)
57 f, err := os.Open(imageTarballPath)
62 resp, err := e.dockerclient.ImageLoad(context.TODO(), f, true)
64 return fmt.Errorf("While loading container image into Docker: %v", err)
66 defer resp.Body.Close()
67 buf, _ := ioutil.ReadAll(resp.Body)
68 e.logf("loaded image: response %s", buf)
72 func (e *dockerExecutor) Create(spec containerSpec) error {
73 e.logf("Creating Docker container")
74 cfg := dockercontainer.Config{
77 WorkingDir: spec.WorkingDir,
78 Volumes: map[string]struct{}{},
79 OpenStdin: spec.Stdin != nil,
80 StdinOnce: spec.Stdin != nil,
81 AttachStdin: spec.Stdin != nil,
85 if cfg.WorkingDir == "." {
88 for k, v := range spec.Env {
89 cfg.Env = append(cfg.Env, k+"="+v)
91 if spec.RAM > 0 && spec.RAM < minDockerRAM {
92 spec.RAM = minDockerRAM
94 hostCfg := dockercontainer.HostConfig{
95 LogConfig: dockercontainer.LogConfig{
98 NetworkMode: dockercontainer.NetworkMode("none"),
99 Resources: dockercontainer.Resources{
100 CgroupParent: spec.CgroupParent,
101 NanoCPUs: int64(spec.VCPUs) * 1000000000,
102 Memory: spec.RAM, // RAM
103 MemorySwap: spec.RAM, // RAM+swap
104 KernelMemory: spec.RAM, // kernel portion
107 for path, mount := range spec.BindMounts {
108 bind := mount.HostPath + ":" + path
112 hostCfg.Binds = append(hostCfg.Binds, bind)
114 if spec.EnableNetwork {
115 hostCfg.NetworkMode = dockercontainer.NetworkMode(spec.NetworkMode)
118 created, err := e.dockerclient.ContainerCreate(context.TODO(), &cfg, &hostCfg, nil, e.containerUUID)
120 return fmt.Errorf("While creating container: %v", err)
122 e.containerID = created.ID
123 return e.startIO(spec.Stdin, spec.Stdout, spec.Stderr)
126 func (e *dockerExecutor) CgroupID() string {
130 func (e *dockerExecutor) Start() error {
131 return e.dockerclient.ContainerStart(context.TODO(), e.containerID, dockertypes.ContainerStartOptions{})
134 func (e *dockerExecutor) Stop() error {
135 err := e.dockerclient.ContainerRemove(context.TODO(), e.containerID, dockertypes.ContainerRemoveOptions{Force: true})
136 if err != nil && strings.Contains(err.Error(), "No such container: "+e.containerID) {
142 // Wait for the container to terminate, capture the exit code, and
143 // wait for stdout/stderr logging to finish.
144 func (e *dockerExecutor) Wait(ctx context.Context) (int, error) {
145 ctx, cancel := context.WithCancel(ctx)
147 watchdogErr := make(chan error, 1)
149 ticker := time.NewTicker(e.watchdogInterval)
152 dctx, dcancel := context.WithDeadline(ctx, time.Now().Add(e.watchdogInterval))
153 ctr, err := e.dockerclient.ContainerInspect(dctx, e.containerID)
155 if ctx.Err() != nil {
156 // Either the container already
157 // exited, or our caller is trying to
160 } else if err != nil {
161 e.logf("Error inspecting container: %s", err)
164 } else if ctr.State == nil || !(ctr.State.Running || ctr.State.Status == "created") {
165 watchdogErr <- fmt.Errorf("Container is not running: State=%v", ctr.State)
171 waitOk, waitErr := e.dockerclient.ContainerWait(ctx, e.containerID, dockercontainer.WaitConditionNotRunning)
174 case waitBody := <-waitOk:
175 e.logf("Container exited with code: %v", waitBody.StatusCode)
176 // wait for stdout/stderr to complete
178 return int(waitBody.StatusCode), nil
180 case err := <-waitErr:
181 return -1, fmt.Errorf("container wait: %v", err)
186 case err := <-watchdogErr:
192 func (e *dockerExecutor) startIO(stdin io.Reader, stdout, stderr io.Writer) error {
193 resp, err := e.dockerclient.ContainerAttach(context.TODO(), e.containerID, dockertypes.ContainerAttachOptions{
200 return fmt.Errorf("error attaching container stdin/stdout/stderr streams: %v", err)
205 errStdin = e.handleStdin(stdin, resp.Conn, resp.CloseWrite)
208 e.doneIO = make(chan struct{})
210 e.errIO = e.handleStdoutStderr(stdout, stderr, resp.Reader)
211 if e.errIO == nil && errStdin != nil {
219 func (e *dockerExecutor) handleStdin(stdin io.Reader, conn io.Writer, closeConn func() error) error {
221 _, err := io.Copy(conn, stdin)
223 return fmt.Errorf("While writing to docker container on stdin: %v", err)
228 // Handle docker log protocol; see
229 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
230 func (e *dockerExecutor) handleStdoutStderr(stdout, stderr io.Writer, reader io.Reader) error {
231 header := make([]byte, 8)
234 _, err = io.ReadAtLeast(reader, header, 8)
241 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
243 _, err = io.CopyN(stdout, reader, readsize)
246 _, err = io.CopyN(stderr, reader, readsize)
250 return fmt.Errorf("error copying stdout/stderr from docker: %v", err)
255 func (e *dockerExecutor) Close() {
256 e.dockerclient.ContainerRemove(context.TODO(), e.containerID, dockertypes.ContainerRemoveOptions{Force: true})