20259: Add documentation for banner and tooltip features
[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         "os/exec"
12         "strings"
13         "sync/atomic"
14         "time"
15
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"
21 )
22
23 // Docker daemon won't let you set a limit less than ~10 MiB
24 const minDockerRAM = int64(16 * 1024 * 1024)
25
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"
33
34 // Number of consecutive "inspect container" failures before
35 // concluding Docker is unresponsive, giving up, and cancelling the
36 // container.
37 const dockerWatchdogThreshold = 3
38
39 type dockerExecutor struct {
40         containerUUID    string
41         logf             func(string, ...interface{})
42         watchdogInterval time.Duration
43         dockerclient     *dockerclient.Client
44         containerID      string
45         savedIPAddress   atomic.Value
46         doneIO           chan struct{}
47         errIO            error
48 }
49
50 func newDockerExecutor(containerUUID string, logf func(string, ...interface{}), watchdogInterval time.Duration) (*dockerExecutor, error) {
51         // API version 1.21 corresponds to Docker 1.9, which is
52         // currently the minimum version we want to support.
53         client, err := dockerclient.NewClient(dockerclient.DefaultDockerHost, DockerAPIVersion, nil, nil)
54         if watchdogInterval < 1 {
55                 watchdogInterval = time.Minute
56         }
57         return &dockerExecutor{
58                 containerUUID:    containerUUID,
59                 logf:             logf,
60                 watchdogInterval: watchdogInterval,
61                 dockerclient:     client,
62         }, err
63 }
64
65 func (e *dockerExecutor) Runtime() string {
66         v, _ := e.dockerclient.ServerVersion(context.Background())
67         info := ""
68         for _, cv := range v.Components {
69                 if info != "" {
70                         info += ", "
71                 }
72                 info += cv.Name + " " + cv.Version
73         }
74         if info == "" {
75                 info = "(unknown version)"
76         }
77         return "docker " + info
78 }
79
80 func (e *dockerExecutor) LoadImage(imageID string, imageTarballPath string, container arvados.Container, arvMountPoint string,
81         containerClient *arvados.Client) error {
82         _, _, err := e.dockerclient.ImageInspectWithRaw(context.TODO(), imageID)
83         if err == nil {
84                 // already loaded
85                 return nil
86         }
87
88         f, err := os.Open(imageTarballPath)
89         if err != nil {
90                 return err
91         }
92         defer f.Close()
93         resp, err := e.dockerclient.ImageLoad(context.TODO(), f, true)
94         if err != nil {
95                 return fmt.Errorf("While loading container image into Docker: %v", err)
96         }
97         defer resp.Body.Close()
98         buf, _ := ioutil.ReadAll(resp.Body)
99         e.logf("loaded image: response %s", buf)
100         return nil
101 }
102
103 func (e *dockerExecutor) config(spec containerSpec) (dockercontainer.Config, dockercontainer.HostConfig) {
104         e.logf("Creating Docker container")
105         cfg := dockercontainer.Config{
106                 Image:        spec.Image,
107                 Cmd:          spec.Command,
108                 WorkingDir:   spec.WorkingDir,
109                 Volumes:      map[string]struct{}{},
110                 OpenStdin:    spec.Stdin != nil,
111                 StdinOnce:    spec.Stdin != nil,
112                 AttachStdin:  spec.Stdin != nil,
113                 AttachStdout: true,
114                 AttachStderr: true,
115         }
116         if cfg.WorkingDir == "." {
117                 cfg.WorkingDir = ""
118         }
119         for k, v := range spec.Env {
120                 cfg.Env = append(cfg.Env, k+"="+v)
121         }
122         if spec.RAM > 0 && spec.RAM < minDockerRAM {
123                 spec.RAM = minDockerRAM
124         }
125         hostCfg := dockercontainer.HostConfig{
126                 LogConfig: dockercontainer.LogConfig{
127                         Type: "none",
128                 },
129                 NetworkMode: dockercontainer.NetworkMode("none"),
130                 Resources: dockercontainer.Resources{
131                         CgroupParent: spec.CgroupParent,
132                         NanoCPUs:     int64(spec.VCPUs) * 1000000000,
133                         Memory:       spec.RAM, // RAM
134                         MemorySwap:   spec.RAM, // RAM+swap
135                         KernelMemory: spec.RAM, // kernel portion
136                 },
137         }
138         if spec.CUDADeviceCount != 0 {
139                 var deviceIds []string
140                 if cudaVisibleDevices := os.Getenv("CUDA_VISIBLE_DEVICES"); cudaVisibleDevices != "" {
141                         // If a resource manager such as slurm or LSF told
142                         // us to select specific devices we need to propagate that.
143                         deviceIds = strings.Split(cudaVisibleDevices, ",")
144                 }
145
146                 deviceCount := spec.CUDADeviceCount
147                 if len(deviceIds) > 0 {
148                         // Docker won't accept both non-empty
149                         // DeviceIDs and a non-zero Count
150                         //
151                         // (it turns out "Count" is a dumb fallback
152                         // that just allocates device 0, 1, 2, ...,
153                         // Count-1)
154                         deviceCount = 0
155                 }
156
157                 // Capabilities are confusing.  The driver has generic
158                 // capabilities "gpu" and "nvidia" but then there's
159                 // additional capabilities "compute" and "utility"
160                 // that are passed to nvidia-container-cli.
161                 //
162                 // "compute" means include the CUDA libraries and
163                 // "utility" means include the CUDA utility programs
164                 // (like nvidia-smi).
165                 //
166                 // https://github.com/moby/moby/blob/7b9275c0da707b030e62c96b679a976f31f929d3/daemon/nvidia_linux.go#L37
167                 // https://github.com/containerd/containerd/blob/main/contrib/nvidia/nvidia.go
168                 hostCfg.Resources.DeviceRequests = append(hostCfg.Resources.DeviceRequests, dockercontainer.DeviceRequest{
169                         Driver:       "nvidia",
170                         Count:        deviceCount,
171                         DeviceIDs:    deviceIds,
172                         Capabilities: [][]string{[]string{"gpu", "nvidia", "compute", "utility"}},
173                 })
174         }
175         for path, mount := range spec.BindMounts {
176                 bind := mount.HostPath + ":" + path
177                 if mount.ReadOnly {
178                         bind += ":ro"
179                 }
180                 hostCfg.Binds = append(hostCfg.Binds, bind)
181         }
182         if spec.EnableNetwork {
183                 hostCfg.NetworkMode = dockercontainer.NetworkMode(spec.NetworkMode)
184         }
185         return cfg, hostCfg
186 }
187
188 func (e *dockerExecutor) Create(spec containerSpec) error {
189         cfg, hostCfg := e.config(spec)
190         created, err := e.dockerclient.ContainerCreate(context.TODO(), &cfg, &hostCfg, nil, e.containerUUID)
191         if err != nil {
192                 return fmt.Errorf("While creating container: %v", err)
193         }
194         e.containerID = created.ID
195         return e.startIO(spec.Stdin, spec.Stdout, spec.Stderr)
196 }
197
198 func (e *dockerExecutor) CgroupID() string {
199         return e.containerID
200 }
201
202 func (e *dockerExecutor) Start() error {
203         return e.dockerclient.ContainerStart(context.TODO(), e.containerID, dockertypes.ContainerStartOptions{})
204 }
205
206 func (e *dockerExecutor) Stop() error {
207         err := e.dockerclient.ContainerRemove(context.TODO(), e.containerID, dockertypes.ContainerRemoveOptions{Force: true})
208         if err != nil && strings.Contains(err.Error(), "No such container: "+e.containerID) {
209                 err = nil
210         }
211         return err
212 }
213
214 // Wait for the container to terminate, capture the exit code, and
215 // wait for stdout/stderr logging to finish.
216 func (e *dockerExecutor) Wait(ctx context.Context) (int, error) {
217         ctx, cancel := context.WithCancel(ctx)
218         defer cancel()
219         watchdogErr := make(chan error, 1)
220         go func() {
221                 ticker := time.NewTicker(e.watchdogInterval)
222                 defer ticker.Stop()
223                 for range ticker.C {
224                         dctx, dcancel := context.WithDeadline(ctx, time.Now().Add(e.watchdogInterval))
225                         ctr, err := e.dockerclient.ContainerInspect(dctx, e.containerID)
226                         dcancel()
227                         if ctx.Err() != nil {
228                                 // Either the container already
229                                 // exited, or our caller is trying to
230                                 // kill it.
231                                 return
232                         } else if err != nil {
233                                 watchdogErr <- fmt.Errorf("error inspecting container: %s", err)
234                         } else if ctr.State == nil || !(ctr.State.Running || ctr.State.Status == "created") {
235                                 watchdogErr <- fmt.Errorf("container is not running: State=%v", ctr.State)
236                         } else {
237                                 watchdogErr <- nil
238                         }
239                 }
240         }()
241
242         waitOk, waitErr := e.dockerclient.ContainerWait(ctx, e.containerID, dockercontainer.WaitConditionNotRunning)
243         errors := 0
244         for {
245                 select {
246                 case waitBody := <-waitOk:
247                         // wait for stdout/stderr to complete
248                         <-e.doneIO
249                         return int(waitBody.StatusCode), nil
250
251                 case err := <-waitErr:
252                         return -1, fmt.Errorf("container wait: %v", err)
253
254                 case <-ctx.Done():
255                         return -1, ctx.Err()
256
257                 case err := <-watchdogErr:
258                         if err == nil {
259                                 errors = 0
260                         } else {
261                                 e.logf("docker watchdog: %s", err)
262                                 errors++
263                                 if errors >= dockerWatchdogThreshold {
264                                         e.logf("docker watchdog: giving up")
265                                         return -1, err
266                                 }
267                         }
268                 }
269         }
270 }
271
272 func (e *dockerExecutor) startIO(stdin io.Reader, stdout, stderr io.Writer) error {
273         resp, err := e.dockerclient.ContainerAttach(context.TODO(), e.containerID, dockertypes.ContainerAttachOptions{
274                 Stream: true,
275                 Stdin:  stdin != nil,
276                 Stdout: true,
277                 Stderr: true,
278         })
279         if err != nil {
280                 return fmt.Errorf("error attaching container stdin/stdout/stderr streams: %v", err)
281         }
282         var errStdin error
283         if stdin != nil {
284                 go func() {
285                         errStdin = e.handleStdin(stdin, resp.Conn, resp.CloseWrite)
286                 }()
287         }
288         e.doneIO = make(chan struct{})
289         go func() {
290                 e.errIO = e.handleStdoutStderr(stdout, stderr, resp.Reader)
291                 if e.errIO == nil && errStdin != nil {
292                         e.errIO = errStdin
293                 }
294                 close(e.doneIO)
295         }()
296         return nil
297 }
298
299 func (e *dockerExecutor) handleStdin(stdin io.Reader, conn io.Writer, closeConn func() error) error {
300         defer closeConn()
301         _, err := io.Copy(conn, stdin)
302         if err != nil {
303                 return fmt.Errorf("While writing to docker container on stdin: %v", err)
304         }
305         return nil
306 }
307
308 // Handle docker log protocol; see
309 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
310 func (e *dockerExecutor) handleStdoutStderr(stdout, stderr io.Writer, reader io.Reader) error {
311         header := make([]byte, 8)
312         var err error
313         for err == nil {
314                 _, err = io.ReadAtLeast(reader, header, 8)
315                 if err != nil {
316                         if err == io.EOF {
317                                 err = nil
318                         }
319                         break
320                 }
321                 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
322                 if header[0] == 1 {
323                         _, err = io.CopyN(stdout, reader, readsize)
324                 } else {
325                         // stderr
326                         _, err = io.CopyN(stderr, reader, readsize)
327                 }
328         }
329         if err != nil {
330                 return fmt.Errorf("error copying stdout/stderr from docker: %v", err)
331         }
332         return nil
333 }
334
335 func (e *dockerExecutor) Close() {
336         e.dockerclient.ContainerRemove(context.TODO(), e.containerID, dockertypes.ContainerRemoveOptions{Force: true})
337 }
338
339 func (e *dockerExecutor) InjectCommand(ctx context.Context, detachKeys, username string, usingTTY bool, injectcmd []string) (*exec.Cmd, error) {
340         cmd := exec.CommandContext(ctx, "docker", "exec", "-i", "--detach-keys="+detachKeys, "--user="+username)
341         if usingTTY {
342                 cmd.Args = append(cmd.Args, "-t")
343         }
344         cmd.Args = append(cmd.Args, e.containerID)
345         cmd.Args = append(cmd.Args, injectcmd...)
346         return cmd, nil
347 }
348
349 func (e *dockerExecutor) IPAddress() (string, error) {
350         if ip, ok := e.savedIPAddress.Load().(*string); ok {
351                 return *ip, nil
352         }
353         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
354         defer cancel()
355         ctr, err := e.dockerclient.ContainerInspect(ctx, e.containerID)
356         if err != nil {
357                 return "", fmt.Errorf("cannot get docker container info: %s", err)
358         }
359         ip := ctr.NetworkSettings.IPAddress
360         if ip == "" {
361                 // TODO: try to enable networking if it wasn't
362                 // already enabled when the container was
363                 // created.
364                 return "", fmt.Errorf("container has no IP address")
365         }
366         e.savedIPAddress.Store(&ip)
367         return ip, nil
368 }