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 type dockerExecutor struct {
28 logf func(string, ...interface{})
29 watchdogInterval time.Duration
30 dockerclient *dockerclient.Client
32 savedIPAddress atomic.Value
37 func newDockerExecutor(containerUUID string, logf func(string, ...interface{}), watchdogInterval time.Duration) (*dockerExecutor, error) {
38 // API version 1.21 corresponds to Docker 1.9, which is
39 // currently the minimum version we want to support.
40 client, err := dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
41 if watchdogInterval < 1 {
42 watchdogInterval = time.Minute
44 return &dockerExecutor{
45 containerUUID: containerUUID,
47 watchdogInterval: watchdogInterval,
52 func (e *dockerExecutor) Runtime() string {
53 v, _ := e.dockerclient.ServerVersion(context.Background())
55 for _, cv := range v.Components {
59 info += cv.Name + " " + cv.Version
62 info = "(unknown version)"
64 return "docker " + info
67 func (e *dockerExecutor) LoadImage(imageID string, imageTarballPath string, container arvados.Container, arvMountPoint string,
68 containerClient *arvados.Client) error {
69 _, _, err := e.dockerclient.ImageInspectWithRaw(context.TODO(), imageID)
75 f, err := os.Open(imageTarballPath)
80 resp, err := e.dockerclient.ImageLoad(context.TODO(), f, true)
82 return fmt.Errorf("While loading container image into Docker: %v", err)
84 defer resp.Body.Close()
85 buf, _ := ioutil.ReadAll(resp.Body)
86 e.logf("loaded image: response %s", buf)
90 func (e *dockerExecutor) config(spec containerSpec) (dockercontainer.Config, dockercontainer.HostConfig) {
91 e.logf("Creating Docker container")
92 cfg := dockercontainer.Config{
95 WorkingDir: spec.WorkingDir,
96 Volumes: map[string]struct{}{},
97 OpenStdin: spec.Stdin != nil,
98 StdinOnce: spec.Stdin != nil,
99 AttachStdin: spec.Stdin != nil,
103 if cfg.WorkingDir == "." {
106 for k, v := range spec.Env {
107 cfg.Env = append(cfg.Env, k+"="+v)
109 if spec.RAM > 0 && spec.RAM < minDockerRAM {
110 spec.RAM = minDockerRAM
112 hostCfg := dockercontainer.HostConfig{
113 LogConfig: dockercontainer.LogConfig{
116 NetworkMode: dockercontainer.NetworkMode("none"),
117 Resources: dockercontainer.Resources{
118 CgroupParent: spec.CgroupParent,
119 NanoCPUs: int64(spec.VCPUs) * 1000000000,
120 Memory: spec.RAM, // RAM
121 MemorySwap: spec.RAM, // RAM+swap
122 KernelMemory: spec.RAM, // kernel portion
125 if spec.CUDADeviceCount != 0 {
126 var deviceIds []string
127 if cudaVisibleDevices := os.Getenv("CUDA_VISIBLE_DEVICES"); cudaVisibleDevices != "" {
128 // If a resource manager such as slurm or LSF told
129 // us to select specific devices we need to propagate that.
130 deviceIds = strings.Split(cudaVisibleDevices, ",")
133 deviceCount := spec.CUDADeviceCount
134 if len(deviceIds) > 0 {
135 // Docker won't accept both non-empty
136 // DeviceIDs and a non-zero Count
138 // (it turns out "Count" is a dumb fallback
139 // that just allocates device 0, 1, 2, ...,
144 // Capabilities are confusing. The driver has generic
145 // capabilities "gpu" and "nvidia" but then there's
146 // additional capabilities "compute" and "utility"
147 // that are passed to nvidia-container-cli.
149 // "compute" means include the CUDA libraries and
150 // "utility" means include the CUDA utility programs
151 // (like nvidia-smi).
153 // https://github.com/moby/moby/blob/7b9275c0da707b030e62c96b679a976f31f929d3/daemon/nvidia_linux.go#L37
154 // https://github.com/containerd/containerd/blob/main/contrib/nvidia/nvidia.go
155 hostCfg.Resources.DeviceRequests = append(hostCfg.Resources.DeviceRequests, dockercontainer.DeviceRequest{
158 DeviceIDs: deviceIds,
159 Capabilities: [][]string{[]string{"gpu", "nvidia", "compute", "utility"}},
162 for path, mount := range spec.BindMounts {
163 bind := mount.HostPath + ":" + path
167 hostCfg.Binds = append(hostCfg.Binds, bind)
169 if spec.EnableNetwork {
170 hostCfg.NetworkMode = dockercontainer.NetworkMode(spec.NetworkMode)
175 func (e *dockerExecutor) Create(spec containerSpec) error {
176 cfg, hostCfg := e.config(spec)
177 created, err := e.dockerclient.ContainerCreate(context.TODO(), &cfg, &hostCfg, nil, e.containerUUID)
179 return fmt.Errorf("While creating container: %v", err)
181 e.containerID = created.ID
182 return e.startIO(spec.Stdin, spec.Stdout, spec.Stderr)
185 func (e *dockerExecutor) CgroupID() string {
189 func (e *dockerExecutor) Start() error {
190 return e.dockerclient.ContainerStart(context.TODO(), e.containerID, dockertypes.ContainerStartOptions{})
193 func (e *dockerExecutor) Stop() error {
194 err := e.dockerclient.ContainerRemove(context.TODO(), e.containerID, dockertypes.ContainerRemoveOptions{Force: true})
195 if err != nil && strings.Contains(err.Error(), "No such container: "+e.containerID) {
201 // Wait for the container to terminate, capture the exit code, and
202 // wait for stdout/stderr logging to finish.
203 func (e *dockerExecutor) Wait(ctx context.Context) (int, error) {
204 ctx, cancel := context.WithCancel(ctx)
206 watchdogErr := make(chan error, 1)
208 ticker := time.NewTicker(e.watchdogInterval)
211 dctx, dcancel := context.WithDeadline(ctx, time.Now().Add(e.watchdogInterval))
212 ctr, err := e.dockerclient.ContainerInspect(dctx, e.containerID)
214 if ctx.Err() != nil {
215 // Either the container already
216 // exited, or our caller is trying to
219 } else if err != nil {
220 e.logf("Error inspecting container: %s", err)
223 } else if ctr.State == nil || !(ctr.State.Running || ctr.State.Status == "created") {
224 watchdogErr <- fmt.Errorf("Container is not running: State=%v", ctr.State)
230 waitOk, waitErr := e.dockerclient.ContainerWait(ctx, e.containerID, dockercontainer.WaitConditionNotRunning)
233 case waitBody := <-waitOk:
234 // wait for stdout/stderr to complete
236 return int(waitBody.StatusCode), nil
238 case err := <-waitErr:
239 return -1, fmt.Errorf("container wait: %v", err)
244 case err := <-watchdogErr:
250 func (e *dockerExecutor) startIO(stdin io.Reader, stdout, stderr io.Writer) error {
251 resp, err := e.dockerclient.ContainerAttach(context.TODO(), e.containerID, dockertypes.ContainerAttachOptions{
258 return fmt.Errorf("error attaching container stdin/stdout/stderr streams: %v", err)
263 errStdin = e.handleStdin(stdin, resp.Conn, resp.CloseWrite)
266 e.doneIO = make(chan struct{})
268 e.errIO = e.handleStdoutStderr(stdout, stderr, resp.Reader)
269 if e.errIO == nil && errStdin != nil {
277 func (e *dockerExecutor) handleStdin(stdin io.Reader, conn io.Writer, closeConn func() error) error {
279 _, err := io.Copy(conn, stdin)
281 return fmt.Errorf("While writing to docker container on stdin: %v", err)
286 // Handle docker log protocol; see
287 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
288 func (e *dockerExecutor) handleStdoutStderr(stdout, stderr io.Writer, reader io.Reader) error {
289 header := make([]byte, 8)
292 _, err = io.ReadAtLeast(reader, header, 8)
299 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
301 _, err = io.CopyN(stdout, reader, readsize)
304 _, err = io.CopyN(stderr, reader, readsize)
308 return fmt.Errorf("error copying stdout/stderr from docker: %v", err)
313 func (e *dockerExecutor) Close() {
314 e.dockerclient.ContainerRemove(context.TODO(), e.containerID, dockertypes.ContainerRemoveOptions{Force: true})
317 func (e *dockerExecutor) InjectCommand(ctx context.Context, detachKeys, username string, usingTTY bool, injectcmd []string) (*exec.Cmd, error) {
318 cmd := exec.CommandContext(ctx, "docker", "exec", "-i", "--detach-keys="+detachKeys, "--user="+username)
320 cmd.Args = append(cmd.Args, "-t")
322 cmd.Args = append(cmd.Args, e.containerID)
323 cmd.Args = append(cmd.Args, injectcmd...)
327 func (e *dockerExecutor) IPAddress() (string, error) {
328 if ip, ok := e.savedIPAddress.Load().(*string); ok {
331 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
333 ctr, err := e.dockerclient.ContainerInspect(ctx, e.containerID)
335 return "", fmt.Errorf("cannot get docker container info: %s", err)
337 ip := ctr.NetworkSettings.IPAddress
339 // TODO: try to enable networking if it wasn't
340 // already enabled when the container was
342 return "", fmt.Errorf("container has no IP address")
344 e.savedIPAddress.Store(&ip)