17813: Upload .sif file to cache project & read it from keep
[arvados.git] / lib / crunchrun / docker.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4 package crunchrun
5
6 import (
7         "fmt"
8         "io"
9         "io/ioutil"
10         "os"
11         "strings"
12         "time"
13
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"
19 )
20
21 // Docker daemon won't let you set a limit less than ~10 MiB
22 const minDockerRAM = int64(16 * 1024 * 1024)
23
24 type dockerExecutor struct {
25         containerUUID    string
26         logf             func(string, ...interface{})
27         watchdogInterval time.Duration
28         dockerclient     *dockerclient.Client
29         containerID      string
30         doneIO           chan struct{}
31         errIO            error
32 }
33
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
40         }
41         return &dockerExecutor{
42                 containerUUID:    containerUUID,
43                 logf:             logf,
44                 watchdogInterval: watchdogInterval,
45                 dockerclient:     client,
46         }, err
47 }
48
49 func (e *dockerExecutor) ImageLoaded(imageID string) bool {
50         _, _, err := e.dockerclient.ImageInspectWithRaw(context.TODO(), imageID)
51         return err == nil
52 }
53
54 func (e *dockerExecutor) LoadImage(filename string) error {
55         f, err := os.Open(filename)
56         if err != nil {
57                 return err
58         }
59         defer f.Close()
60         resp, err := e.dockerclient.ImageLoad(context.TODO(), f, true)
61         if err != nil {
62                 return fmt.Errorf("While loading container image into Docker: %v", err)
63         }
64         defer resp.Body.Close()
65         buf, _ := ioutil.ReadAll(resp.Body)
66         e.logf("loaded image: response %s", buf)
67         return nil
68 }
69
70 func (e *dockerExecutor) Create(spec containerSpec) error {
71         e.logf("Creating Docker container")
72         cfg := dockercontainer.Config{
73                 Image:        spec.Image,
74                 Cmd:          spec.Command,
75                 WorkingDir:   spec.WorkingDir,
76                 Volumes:      map[string]struct{}{},
77                 OpenStdin:    spec.Stdin != nil,
78                 StdinOnce:    spec.Stdin != nil,
79                 AttachStdin:  spec.Stdin != nil,
80                 AttachStdout: true,
81                 AttachStderr: true,
82         }
83         if cfg.WorkingDir == "." {
84                 cfg.WorkingDir = ""
85         }
86         for k, v := range spec.Env {
87                 cfg.Env = append(cfg.Env, k+"="+v)
88         }
89         if spec.RAM > 0 && spec.RAM < minDockerRAM {
90                 spec.RAM = minDockerRAM
91         }
92         hostCfg := dockercontainer.HostConfig{
93                 LogConfig: dockercontainer.LogConfig{
94                         Type: "none",
95                 },
96                 NetworkMode: dockercontainer.NetworkMode("none"),
97                 Resources: dockercontainer.Resources{
98                         CgroupParent: spec.CgroupParent,
99                         NanoCPUs:     int64(spec.VCPUs) * 1000000000,
100                         Memory:       spec.RAM, // RAM
101                         MemorySwap:   spec.RAM, // RAM+swap
102                         KernelMemory: spec.RAM, // kernel portion
103                 },
104         }
105         for path, mount := range spec.BindMounts {
106                 bind := mount.HostPath + ":" + path
107                 if mount.ReadOnly {
108                         bind += ":ro"
109                 }
110                 hostCfg.Binds = append(hostCfg.Binds, bind)
111         }
112         if spec.EnableNetwork {
113                 hostCfg.NetworkMode = dockercontainer.NetworkMode(spec.NetworkMode)
114         }
115
116         created, err := e.dockerclient.ContainerCreate(context.TODO(), &cfg, &hostCfg, nil, e.containerUUID)
117         if err != nil {
118                 return fmt.Errorf("While creating container: %v", err)
119         }
120         e.containerID = created.ID
121         return e.startIO(spec.Stdin, spec.Stdout, spec.Stderr)
122 }
123
124 func (e *dockerExecutor) CgroupID() string {
125         return e.containerID
126 }
127
128 func (e *dockerExecutor) Start() error {
129         return e.dockerclient.ContainerStart(context.TODO(), e.containerID, dockertypes.ContainerStartOptions{})
130 }
131
132 func (e *dockerExecutor) Stop() error {
133         err := e.dockerclient.ContainerRemove(context.TODO(), e.containerID, dockertypes.ContainerRemoveOptions{Force: true})
134         if err != nil && strings.Contains(err.Error(), "No such container: "+e.containerID) {
135                 err = nil
136         }
137         return err
138 }
139
140 // Wait for the container to terminate, capture the exit code, and
141 // wait for stdout/stderr logging to finish.
142 func (e *dockerExecutor) Wait(ctx context.Context) (int, error) {
143         ctx, cancel := context.WithCancel(ctx)
144         defer cancel()
145         watchdogErr := make(chan error, 1)
146         go func() {
147                 ticker := time.NewTicker(e.watchdogInterval)
148                 defer ticker.Stop()
149                 for range ticker.C {
150                         dctx, dcancel := context.WithDeadline(ctx, time.Now().Add(e.watchdogInterval))
151                         ctr, err := e.dockerclient.ContainerInspect(dctx, e.containerID)
152                         dcancel()
153                         if ctx.Err() != nil {
154                                 // Either the container already
155                                 // exited, or our caller is trying to
156                                 // kill it.
157                                 return
158                         } else if err != nil {
159                                 e.logf("Error inspecting container: %s", err)
160                                 watchdogErr <- err
161                                 return
162                         } else if ctr.State == nil || !(ctr.State.Running || ctr.State.Status == "created") {
163                                 watchdogErr <- fmt.Errorf("Container is not running: State=%v", ctr.State)
164                                 return
165                         }
166                 }
167         }()
168
169         waitOk, waitErr := e.dockerclient.ContainerWait(ctx, e.containerID, dockercontainer.WaitConditionNotRunning)
170         for {
171                 select {
172                 case waitBody := <-waitOk:
173                         e.logf("Container exited with code: %v", waitBody.StatusCode)
174                         // wait for stdout/stderr to complete
175                         <-e.doneIO
176                         return int(waitBody.StatusCode), nil
177
178                 case err := <-waitErr:
179                         return -1, fmt.Errorf("container wait: %v", err)
180
181                 case <-ctx.Done():
182                         return -1, ctx.Err()
183
184                 case err := <-watchdogErr:
185                         return -1, err
186                 }
187         }
188 }
189
190 func (e *dockerExecutor) startIO(stdin io.Reader, stdout, stderr io.Writer) error {
191         resp, err := e.dockerclient.ContainerAttach(context.TODO(), e.containerID, dockertypes.ContainerAttachOptions{
192                 Stream: true,
193                 Stdin:  stdin != nil,
194                 Stdout: true,
195                 Stderr: true,
196         })
197         if err != nil {
198                 return fmt.Errorf("error attaching container stdin/stdout/stderr streams: %v", err)
199         }
200         var errStdin error
201         if stdin != nil {
202                 go func() {
203                         errStdin = e.handleStdin(stdin, resp.Conn, resp.CloseWrite)
204                 }()
205         }
206         e.doneIO = make(chan struct{})
207         go func() {
208                 e.errIO = e.handleStdoutStderr(stdout, stderr, resp.Reader)
209                 if e.errIO == nil && errStdin != nil {
210                         e.errIO = errStdin
211                 }
212                 close(e.doneIO)
213         }()
214         return nil
215 }
216
217 func (e *dockerExecutor) handleStdin(stdin io.Reader, conn io.Writer, closeConn func() error) error {
218         defer closeConn()
219         _, err := io.Copy(conn, stdin)
220         if err != nil {
221                 return fmt.Errorf("While writing to docker container on stdin: %v", err)
222         }
223         return nil
224 }
225
226 // Handle docker log protocol; see
227 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
228 func (e *dockerExecutor) handleStdoutStderr(stdout, stderr io.Writer, reader io.Reader) error {
229         header := make([]byte, 8)
230         var err error
231         for err == nil {
232                 _, err = io.ReadAtLeast(reader, header, 8)
233                 if err != nil {
234                         if err == io.EOF {
235                                 err = nil
236                         }
237                         break
238                 }
239                 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
240                 if header[0] == 1 {
241                         _, err = io.CopyN(stdout, reader, readsize)
242                 } else {
243                         // stderr
244                         _, err = io.CopyN(stderr, reader, readsize)
245                 }
246         }
247         if err != nil {
248                 return fmt.Errorf("error copying stdout/stderr from docker: %v", err)
249         }
250         return nil
251 }
252
253 func (e *dockerExecutor) Close() {
254         e.dockerclient.ContainerRemove(context.TODO(), e.containerID, dockertypes.ContainerRemoveOptions{Force: true})
255 }
256
257 func (e *dockerExecutor) SetArvadoClient(containerClient *arvados.Client, keepClient IKeepClient, container arvados.Container, keepMount string) {
258 }