1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
20 "git.arvados.org/arvados.git/sdk/go/arvados"
21 dockercontainer "github.com/docker/docker/api/types/container"
22 dockerclient "github.com/docker/docker/client"
25 // Docker daemon won't let you set a limit less than ~10 MiB
26 const minDockerRAM = int64(16 * 1024 * 1024)
28 // DockerAPIVersion is the API version we use to communicate with the
29 // docker service. The oldest OS we support is Ubuntu 18.04 (bionic)
30 // which originally shipped docker 1.17.12 / API 1.35 so there is no
31 // reason to use an older API version. See
32 // https://dev.arvados.org/issues/15370#note-38 and
33 // https://docs.docker.com/engine/api/.
34 const DockerAPIVersion = "1.35"
36 // Number of consecutive "inspect container" failures before
37 // concluding Docker is unresponsive, giving up, and cancelling the
39 const dockerWatchdogThreshold = 5
41 type dockerExecutor struct {
43 logf func(string, ...interface{})
44 watchdogInterval time.Duration
45 dockerclient *dockerclient.Client
47 savedIPAddress atomic.Value
52 func newDockerExecutor(containerUUID string, logf func(string, ...interface{}), watchdogInterval time.Duration) (*dockerExecutor, error) {
53 // API version 1.21 corresponds to Docker 1.9, which is
54 // currently the minimum version we want to support.
55 client, err := dockerclient.NewClient(dockerclient.DefaultDockerHost, DockerAPIVersion, nil, nil)
56 if watchdogInterval < 1 {
57 watchdogInterval = time.Minute * 2
59 return &dockerExecutor{
60 containerUUID: containerUUID,
62 watchdogInterval: watchdogInterval,
67 func (e *dockerExecutor) Runtime() string {
68 v, _ := e.dockerclient.ServerVersion(context.Background())
70 for _, cv := range v.Components {
74 info += cv.Name + " " + cv.Version
77 info = "(unknown version)"
79 return "docker " + info
82 func (e *dockerExecutor) LoadImage(imageID string, imageTarballPath string, container arvados.Container, arvMountPoint string,
83 containerClient *arvados.Client) error {
84 _, _, err := e.dockerclient.ImageInspectWithRaw(context.TODO(), imageID)
90 f, err := os.Open(imageTarballPath)
95 resp, err := e.dockerclient.ImageLoad(context.TODO(), f, true)
97 return fmt.Errorf("While loading container image into Docker: %v", err)
99 defer resp.Body.Close()
100 buf, _ := ioutil.ReadAll(resp.Body)
101 e.logf("loaded image: response %s", buf)
105 func (e *dockerExecutor) config(spec containerSpec) (dockercontainer.Config, dockercontainer.HostConfig) {
106 e.logf("Creating Docker container")
107 cfg := dockercontainer.Config{
110 WorkingDir: spec.WorkingDir,
111 Volumes: map[string]struct{}{},
112 OpenStdin: spec.Stdin != nil,
113 StdinOnce: spec.Stdin != nil,
114 AttachStdin: spec.Stdin != nil,
118 if cfg.WorkingDir == "." {
121 for k, v := range spec.Env {
122 cfg.Env = append(cfg.Env, k+"="+v)
124 if spec.RAM > 0 && spec.RAM < minDockerRAM {
125 spec.RAM = minDockerRAM
127 hostCfg := dockercontainer.HostConfig{
128 LogConfig: dockercontainer.LogConfig{
131 NetworkMode: dockercontainer.NetworkMode("none"),
132 Resources: dockercontainer.Resources{
133 CgroupParent: spec.CgroupParent,
134 NanoCPUs: int64(spec.VCPUs) * 1000000000,
135 Memory: spec.RAM, // RAM
136 MemorySwap: spec.RAM, // RAM+swap
137 KernelMemory: spec.RAM, // kernel portion
140 if spec.GPUStack == "cuda" && spec.GPUDeviceCount > 0 {
141 var deviceIds []string
142 if cudaVisibleDevices := os.Getenv("CUDA_VISIBLE_DEVICES"); cudaVisibleDevices != "" {
143 // If a resource manager such as slurm or LSF told
144 // us to select specific devices we need to propagate that.
145 deviceIds = strings.Split(cudaVisibleDevices, ",")
148 deviceCount := spec.GPUDeviceCount
149 if len(deviceIds) > 0 {
150 // Docker won't accept both non-empty
151 // DeviceIDs and a non-zero Count
153 // (it turns out "Count" is a dumb fallback
154 // that just allocates device 0, 1, 2, ...,
159 // Capabilities are confusing. The driver has generic
160 // capabilities "gpu" and "nvidia" but then there's
161 // additional capabilities "compute" and "utility"
162 // that are passed to nvidia-container-cli.
164 // "compute" means include the CUDA libraries and
165 // "utility" means include the CUDA utility programs
166 // (like nvidia-smi).
168 // https://github.com/moby/moby/blob/7b9275c0da707b030e62c96b679a976f31f929d3/daemon/nvidia_linux.go#L37
169 // https://github.com/containerd/containerd/blob/main/contrib/nvidia/nvidia.go
170 hostCfg.Resources.DeviceRequests = append(hostCfg.Resources.DeviceRequests, dockercontainer.DeviceRequest{
173 DeviceIDs: deviceIds,
174 Capabilities: [][]string{[]string{"gpu", "nvidia", "compute", "utility"}},
177 if spec.GPUStack == "rocm" && spec.GPUDeviceCount > 0 {
178 // there's no container toolkit or builtin Docker
179 // support for ROCm so we just provide the devices to
180 // the container ourselves.
182 // fortunately, the minimum version of this seems to be this:
183 // rendergroup=$(getent group render | cut -d: -f3)
184 // videogroup=$(getent group video | cut -d: -f3)
185 // docker run -it --device=/dev/kfd --device=/dev/dri/renderD128 --user $(id -u) --group-add $videogroup --group-add $rendergroup "$@"
187 hostCfg.Devices = append(hostCfg.Devices, dockercontainer.DeviceMapping{
188 PathInContainer: "/dev/kfd",
189 PathOnHost: "/dev/kfd",
190 CgroupPermissions: "rwm",
192 info, _ := os.Stat("/dev/kfd")
193 if stat, ok := info.Sys().(*syscall.Stat_t); ok {
194 // Make sure the container has access
195 // to the group id that allow it to
196 // access the device.
197 hostCfg.GroupAdd = append(hostCfg.GroupAdd, fmt.Sprintf("%v", stat.Gid))
200 var deviceIndexes []int
201 if amdVisibleDevices := os.Getenv("AMD_VISIBLE_DEVICES"); amdVisibleDevices != "" {
202 // If a resource manager/dispatcher told us to
203 // select specific devices, so we need to
205 for _, dev := range strings.Split(amdVisibleDevices, ",") {
206 intDev, err := strconv.Atoi(dev)
210 deviceIndexes = append(deviceIndexes, intDev)
213 // Try every device, we'll check below to see
214 // which ones actually exists.
215 for i := 0; i < 128; i++ {
216 deviceIndexes = append(deviceIndexes, i)
219 for _, intDev := range deviceIndexes {
220 devPath := fmt.Sprintf("/dev/dri/renderD%v", 128+intDev)
221 info, err := os.Stat(devPath)
225 hostCfg.Devices = append(hostCfg.Devices, dockercontainer.DeviceMapping{
226 PathInContainer: devPath,
228 CgroupPermissions: "rwm",
230 if stat, ok := info.Sys().(*syscall.Stat_t); ok {
231 // Make sure the container has access
232 // to the group id that allow it to
233 // access the device.
234 if !slices.Contains(hostCfg.GroupAdd, fmt.Sprintf("%v", stat.Gid)) {
235 hostCfg.GroupAdd = append(hostCfg.GroupAdd, fmt.Sprintf("%v", stat.Gid))
241 for path, mount := range spec.BindMounts {
242 bind := mount.HostPath + ":" + path
246 hostCfg.Binds = append(hostCfg.Binds, bind)
248 if spec.EnableNetwork {
249 hostCfg.NetworkMode = dockercontainer.NetworkMode(spec.NetworkMode)
254 func (e *dockerExecutor) Create(spec containerSpec) error {
255 cfg, hostCfg := e.config(spec)
256 created, err := e.dockerclient.ContainerCreate(context.TODO(), &cfg, &hostCfg, nil, nil, e.containerUUID)
258 return fmt.Errorf("While creating container: %v", err)
260 e.containerID = created.ID
261 return e.startIO(spec.Stdin, spec.Stdout, spec.Stderr)
264 func (e *dockerExecutor) Pid() int {
265 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Second))
267 ctr, err := e.dockerclient.ContainerInspect(ctx, e.containerID)
268 if err == nil && ctr.State != nil {
275 func (e *dockerExecutor) Start() error {
276 return e.dockerclient.ContainerStart(context.TODO(), e.containerID, dockercontainer.StartOptions{})
279 func (e *dockerExecutor) Stop() error {
280 err := e.dockerclient.ContainerRemove(context.TODO(), e.containerID, dockercontainer.RemoveOptions{Force: true})
281 if err != nil && strings.Contains(err.Error(), "No such container: "+e.containerID) {
287 // Wait for the container to terminate, capture the exit code, and
288 // wait for stdout/stderr logging to finish.
289 func (e *dockerExecutor) Wait(ctx context.Context) (int, error) {
290 ctx, cancel := context.WithCancel(ctx)
292 watchdogErr := make(chan error, 1)
294 ticker := time.NewTicker(e.watchdogInterval)
297 dctx, dcancel := context.WithDeadline(ctx, time.Now().Add(e.watchdogInterval))
298 ctr, err := e.dockerclient.ContainerInspect(dctx, e.containerID)
300 if ctx.Err() != nil {
301 // Either the container already
302 // exited, or our caller is trying to
305 } else if err != nil {
306 watchdogErr <- fmt.Errorf("error inspecting container: %s", err)
307 } else if ctr.State == nil || !(ctr.State.Running || ctr.State.Status == "created") {
308 watchdogErr <- fmt.Errorf("container is not running: State=%v", ctr.State)
315 waitOk, waitErr := e.dockerclient.ContainerWait(ctx, e.containerID, dockercontainer.WaitConditionNotRunning)
319 case waitBody := <-waitOk:
320 // wait for stdout/stderr to complete
322 return int(waitBody.StatusCode), nil
324 case err := <-waitErr:
325 return -1, fmt.Errorf("container wait: %v", err)
330 case err := <-watchdogErr:
334 e.logf("docker watchdog: %s", err)
336 if errors >= dockerWatchdogThreshold {
337 e.logf("docker watchdog: giving up")
345 func (e *dockerExecutor) startIO(stdin io.Reader, stdout, stderr io.Writer) error {
346 resp, err := e.dockerclient.ContainerAttach(context.TODO(), e.containerID, dockercontainer.AttachOptions{
353 return fmt.Errorf("error attaching container stdin/stdout/stderr streams: %v", err)
358 errStdin = e.handleStdin(stdin, resp.Conn, resp.CloseWrite)
361 e.doneIO = make(chan struct{})
363 e.errIO = e.handleStdoutStderr(stdout, stderr, resp.Reader)
364 if e.errIO == nil && errStdin != nil {
372 func (e *dockerExecutor) handleStdin(stdin io.Reader, conn io.Writer, closeConn func() error) error {
374 _, err := io.Copy(conn, stdin)
376 return fmt.Errorf("While writing to docker container on stdin: %v", err)
381 // Handle docker log protocol; see
382 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
383 func (e *dockerExecutor) handleStdoutStderr(stdout, stderr io.Writer, reader io.Reader) error {
384 header := make([]byte, 8)
387 _, err = io.ReadAtLeast(reader, header, 8)
394 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
396 _, err = io.CopyN(stdout, reader, readsize)
399 _, err = io.CopyN(stderr, reader, readsize)
403 return fmt.Errorf("error copying stdout/stderr from docker: %v", err)
408 func (e *dockerExecutor) Close() {
409 e.dockerclient.ContainerRemove(context.TODO(), e.containerID, dockercontainer.RemoveOptions{Force: true})
412 func (e *dockerExecutor) InjectCommand(ctx context.Context, detachKeys, username string, usingTTY bool, injectcmd []string) (*exec.Cmd, error) {
413 cmd := exec.CommandContext(ctx, "docker", "exec", "-i", "--detach-keys="+detachKeys, "--user="+username)
415 cmd.Args = append(cmd.Args, "-t")
417 cmd.Args = append(cmd.Args, e.containerID)
418 cmd.Args = append(cmd.Args, injectcmd...)
422 func (e *dockerExecutor) IPAddress() (string, error) {
423 if ip, ok := e.savedIPAddress.Load().(*string); ok {
426 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
428 ctr, err := e.dockerclient.ContainerInspect(ctx, e.containerID)
430 return "", fmt.Errorf("cannot get docker container info: %s", err)
432 ip := ctr.NetworkSettings.IPAddress
434 // TODO: try to enable networking if it wasn't
435 // already enabled when the container was
437 return "", fmt.Errorf("container has no IP address")
439 e.savedIPAddress.Store(&ip)