1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
28 "git.curoverse.com/arvados.git/lib/crunchstat"
29 "git.curoverse.com/arvados.git/sdk/go/arvados"
30 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
31 "git.curoverse.com/arvados.git/sdk/go/keepclient"
32 "git.curoverse.com/arvados.git/sdk/go/manifest"
34 dockertypes "github.com/docker/docker/api/types"
35 dockercontainer "github.com/docker/docker/api/types/container"
36 dockernetwork "github.com/docker/docker/api/types/network"
37 dockerclient "github.com/docker/docker/client"
40 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
41 type IArvadosClient interface {
42 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
43 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
44 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
45 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
46 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
47 Discovery(key string) (interface{}, error)
50 // ErrCancelled is the error returned when the container is cancelled.
51 var ErrCancelled = errors.New("Cancelled")
53 // IKeepClient is the minimal Keep API methods used by crunch-run.
54 type IKeepClient interface {
55 PutHB(hash string, buf []byte) (string, int, error)
56 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
59 // NewLogWriter is a factory function to create a new log writer.
60 type NewLogWriter func(name string) io.WriteCloser
62 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
64 type MkTempDir func(string, string) (string, error)
66 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
67 type ThinDockerClient interface {
68 ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
69 ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
70 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
71 ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
72 ContainerStop(ctx context.Context, container string, timeout *time.Duration) error
73 ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error)
74 ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
75 ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
76 ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
79 // ThinDockerClientProxy is a proxy implementation of ThinDockerClient
80 // that executes the docker requests on dockerclient.Client
81 type ThinDockerClientProxy struct {
82 Docker *dockerclient.Client
85 // ContainerAttach invokes dockerclient.Client.ContainerAttach
86 func (proxy ThinDockerClientProxy) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
87 return proxy.Docker.ContainerAttach(ctx, container, options)
90 // ContainerCreate invokes dockerclient.Client.ContainerCreate
91 func (proxy ThinDockerClientProxy) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
92 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
93 return proxy.Docker.ContainerCreate(ctx, config, hostConfig, networkingConfig, containerName)
96 // ContainerStart invokes dockerclient.Client.ContainerStart
97 func (proxy ThinDockerClientProxy) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
98 return proxy.Docker.ContainerStart(ctx, container, options)
101 // ContainerStop invokes dockerclient.Client.ContainerStop
102 func (proxy ThinDockerClientProxy) ContainerStop(ctx context.Context, container string, timeout *time.Duration) error {
103 return proxy.Docker.ContainerStop(ctx, container, timeout)
106 // ContainerWait invokes dockerclient.Client.ContainerWait
107 func (proxy ThinDockerClientProxy) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
108 return proxy.Docker.ContainerWait(ctx, container, condition)
111 // ImageInspectWithRaw invokes dockerclient.Client.ImageInspectWithRaw
112 func (proxy ThinDockerClientProxy) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
113 return proxy.Docker.ImageInspectWithRaw(ctx, image)
116 // ImageLoad invokes dockerclient.Client.ImageLoad
117 func (proxy ThinDockerClientProxy) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
118 return proxy.Docker.ImageLoad(ctx, input, quiet)
121 // ImageRemove invokes dockerclient.Client.ImageRemove
122 func (proxy ThinDockerClientProxy) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
123 return proxy.Docker.ImageRemove(ctx, image, options)
126 // ContainerRunner is the main stateful struct used for a single execution of a
128 type ContainerRunner struct {
129 Docker ThinDockerClient
130 ArvClient IArvadosClient
133 ContainerConfig dockercontainer.Config
134 dockercontainer.HostConfig
139 loggingDone chan bool
140 CrunchLog *ThrottledLogger
141 Stdout io.WriteCloser
142 Stderr io.WriteCloser
143 LogCollection *CollectionWriter
150 CleanupTempDir []string
152 Volumes map[string]struct{}
154 SigChan chan os.Signal
155 ArvMountExit chan error
158 statLogger io.WriteCloser
159 statReporter *crunchstat.Reporter
160 statInterval time.Duration
162 // What we expect the container's cgroup parent to be.
163 expectCgroupParent string
164 // What we tell docker to use as the container's cgroup
165 // parent. Note: Ideally we would use the same field for both
166 // expectCgroupParent and setCgroupParent, and just make it
167 // default to "docker". However, when using docker < 1.10 with
168 // systemd, specifying a non-empty cgroup parent (even the
169 // default value "docker") hits a docker bug
170 // (https://github.com/docker/docker/issues/17126). Using two
171 // separate fields makes it possible to use the "expect cgroup
172 // parent to be X" feature even on sites where the "specify
173 // cgroup parent" feature breaks.
174 setCgroupParent string
176 cStateLock sync.Mutex
177 cStarted bool // StartContainer() succeeded
178 cCancelled bool // StopContainer() invoked
180 enableNetwork string // one of "default" or "always"
181 networkMode string // passed through to HostConfig.NetworkMode
184 // SetupSignals sets up signal handling to gracefully terminate the underlying
185 // Docker container and update state when receiving a TERM, INT or QUIT signal.
186 func (runner *ContainerRunner) SetupSignals() {
187 runner.SigChan = make(chan os.Signal, 1)
188 signal.Notify(runner.SigChan, syscall.SIGTERM)
189 signal.Notify(runner.SigChan, syscall.SIGINT)
190 signal.Notify(runner.SigChan, syscall.SIGQUIT)
192 go func(sig chan os.Signal) {
199 // stop the underlying Docker container.
200 func (runner *ContainerRunner) stop() {
201 runner.cStateLock.Lock()
202 defer runner.cStateLock.Unlock()
203 if runner.cCancelled {
206 runner.cCancelled = true
208 timeout := time.Duration(10)
209 err := runner.Docker.ContainerStop(context.TODO(), runner.ContainerID, &(timeout))
211 log.Printf("StopContainer failed: %s", err)
216 // LoadImage determines the docker image id from the container record and
217 // checks if it is available in the local Docker image store. If not, it loads
218 // the image from Keep.
219 func (runner *ContainerRunner) LoadImage() (err error) {
221 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
223 var collection arvados.Collection
224 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
226 return fmt.Errorf("While getting container image collection: %v", err)
228 manifest := manifest.Manifest{Text: collection.ManifestText}
229 var img, imageID string
230 for ms := range manifest.StreamIter() {
231 img = ms.FileStreamSegments[0].Name
232 if !strings.HasSuffix(img, ".tar") {
233 return fmt.Errorf("First file in the container image collection does not end in .tar")
235 imageID = img[:len(img)-4]
238 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
240 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
242 runner.CrunchLog.Print("Loading Docker image from keep")
244 var readCloser io.ReadCloser
245 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
247 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
250 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, false)
252 return fmt.Errorf("While loading container image into Docker: %v", err)
254 response.Body.Close()
256 runner.CrunchLog.Print("Docker image is available")
259 runner.ContainerConfig.Image = imageID
264 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
265 c = exec.Command("arv-mount", arvMountCmd...)
267 // Copy our environment, but override ARVADOS_API_TOKEN with
268 // the container auth token.
270 for _, s := range os.Environ() {
271 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
272 c.Env = append(c.Env, s)
275 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
277 nt := NewThrottledLogger(runner.NewLogWriter("arv-mount"))
286 statReadme := make(chan bool)
287 runner.ArvMountExit = make(chan error)
292 time.Sleep(100 * time.Millisecond)
293 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
303 runner.ArvMountExit <- c.Wait()
304 close(runner.ArvMountExit)
310 case err := <-runner.ArvMountExit:
311 runner.ArvMount = nil
319 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
320 if runner.ArvMountPoint == "" {
321 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
326 func (runner *ContainerRunner) SetupMounts() (err error) {
327 err = runner.SetupArvMountPoint("keep")
329 return fmt.Errorf("While creating keep mount temp dir: %v", err)
332 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.ArvMountPoint)
336 arvMountCmd := []string{"--foreground", "--allow-other", "--read-write"}
338 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
339 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
342 collectionPaths := []string{}
344 runner.Volumes = make(map[string]struct{})
345 needCertMount := true
348 for bind := range runner.Container.Mounts {
349 binds = append(binds, bind)
353 for _, bind := range binds {
354 mnt := runner.Container.Mounts[bind]
355 if bind == "stdout" || bind == "stderr" {
356 // Is it a "file" mount kind?
357 if mnt.Kind != "file" {
358 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
361 // Does path start with OutputPath?
362 prefix := runner.Container.OutputPath
363 if !strings.HasSuffix(prefix, "/") {
366 if !strings.HasPrefix(mnt.Path, prefix) {
367 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
372 // Is it a "collection" mount kind?
373 if mnt.Kind != "collection" && mnt.Kind != "json" {
374 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
378 if bind == "/etc/arvados/ca-certificates.crt" {
379 needCertMount = false
382 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
383 if mnt.Kind != "collection" {
384 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
389 case mnt.Kind == "collection" && bind != "stdin":
391 if mnt.UUID != "" && mnt.PortableDataHash != "" {
392 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
396 return fmt.Errorf("Writing to existing collections currently not permitted.")
399 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
400 } else if mnt.PortableDataHash != "" {
402 return fmt.Errorf("Can never write to a collection specified by portable data hash")
404 idx := strings.Index(mnt.PortableDataHash, "/")
406 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
407 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
408 runner.Container.Mounts[bind] = mnt
410 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
411 if mnt.Path != "" && mnt.Path != "." {
412 if strings.HasPrefix(mnt.Path, "./") {
413 mnt.Path = mnt.Path[2:]
414 } else if strings.HasPrefix(mnt.Path, "/") {
415 mnt.Path = mnt.Path[1:]
417 src += "/" + mnt.Path
420 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
421 arvMountCmd = append(arvMountCmd, "--mount-tmp")
422 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
426 if bind == runner.Container.OutputPath {
427 runner.HostOutputDir = src
428 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
429 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
431 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
433 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
435 collectionPaths = append(collectionPaths, src)
437 case mnt.Kind == "tmp":
439 tmpdir, err = runner.MkTempDir("", "")
441 return fmt.Errorf("While creating mount temp dir: %v", err)
443 st, staterr := os.Stat(tmpdir)
445 return fmt.Errorf("While Stat on temp dir: %v", staterr)
447 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
449 return fmt.Errorf("While Chmod temp dir: %v", err)
451 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
452 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
453 if bind == runner.Container.OutputPath {
454 runner.HostOutputDir = tmpdir
457 case mnt.Kind == "json":
458 jsondata, err := json.Marshal(mnt.Content)
460 return fmt.Errorf("encoding json data: %v", err)
462 // Create a tempdir with a single file
463 // (instead of just a tempfile): this way we
464 // can ensure the file is world-readable
465 // inside the container, without having to
466 // make it world-readable on the docker host.
467 tmpdir, err := runner.MkTempDir("", "")
469 return fmt.Errorf("creating temp dir: %v", err)
471 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
472 tmpfn := filepath.Join(tmpdir, "mountdata.json")
473 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
475 return fmt.Errorf("writing temp file: %v", err)
477 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
481 if runner.HostOutputDir == "" {
482 return fmt.Errorf("Output path does not correspond to a writable mount point")
485 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
486 for _, certfile := range arvadosclient.CertFiles {
487 _, err := os.Stat(certfile)
489 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
496 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
498 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
500 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
502 token, err := runner.ContainerToken()
504 return fmt.Errorf("could not get container token: %s", err)
507 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
509 return fmt.Errorf("While trying to start arv-mount: %v", err)
512 for _, p := range collectionPaths {
515 return fmt.Errorf("While checking that input files exist: %v", err)
522 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
523 // Handle docker log protocol
524 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
526 header := make([]byte, 8)
528 _, readerr := io.ReadAtLeast(containerReader, header, 8)
531 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
534 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
537 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
542 if readerr != io.EOF {
543 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
546 closeerr := runner.Stdout.Close()
548 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
551 closeerr = runner.Stderr.Close()
553 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
556 if runner.statReporter != nil {
557 runner.statReporter.Stop()
558 closeerr = runner.statLogger.Close()
560 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
564 runner.loggingDone <- true
565 close(runner.loggingDone)
571 func (runner *ContainerRunner) StartCrunchstat() {
572 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
573 runner.statReporter = &crunchstat.Reporter{
574 CID: runner.ContainerID,
575 Logger: log.New(runner.statLogger, "", 0),
576 CgroupParent: runner.expectCgroupParent,
577 CgroupRoot: runner.cgroupRoot,
578 PollPeriod: runner.statInterval,
580 runner.statReporter.Start()
583 type infoCommand struct {
588 // Gather node information and store it on the log for debugging
590 func (runner *ContainerRunner) LogNodeInfo() (err error) {
591 w := runner.NewLogWriter("node-info")
592 logger := log.New(w, "node-info", 0)
594 commands := []infoCommand{
596 label: "Host Information",
597 cmd: []string{"uname", "-a"},
600 label: "CPU Information",
601 cmd: []string{"cat", "/proc/cpuinfo"},
604 label: "Memory Information",
605 cmd: []string{"cat", "/proc/meminfo"},
609 cmd: []string{"df", "-m", "/", os.TempDir()},
612 label: "Disk INodes",
613 cmd: []string{"df", "-i", "/", os.TempDir()},
617 // Run commands with informational output to be logged.
619 for _, command := range commands {
620 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
622 return fmt.Errorf("While running command %q: %v",
625 logger.Println(command.label)
626 for _, line := range strings.Split(string(out), "\n") {
627 logger.Println(" ", line)
633 return fmt.Errorf("While closing node-info logs: %v", err)
638 // Get and save the raw JSON container record from the API server
639 func (runner *ContainerRunner) LogContainerRecord() (err error) {
641 ArvClient: runner.ArvClient,
642 UUID: runner.Container.UUID,
643 loggingStream: "container",
644 writeCloser: runner.LogCollection.Open("container.json"),
647 // Get Container record JSON from the API Server
648 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
650 return fmt.Errorf("While retrieving container record from the API server: %v", err)
654 dec := json.NewDecoder(reader)
656 var cr map[string]interface{}
657 if err = dec.Decode(&cr); err != nil {
658 return fmt.Errorf("While decoding the container record JSON response: %v", err)
660 // Re-encode it using indentation to improve readability
661 enc := json.NewEncoder(w)
662 enc.SetIndent("", " ")
663 if err = enc.Encode(cr); err != nil {
664 return fmt.Errorf("While logging the JSON container record: %v", err)
668 return fmt.Errorf("While closing container.json log: %v", err)
673 // AttachStreams connects the docker container stdin, stdout and stderr logs
674 // to the Arvados logger which logs to Keep and the API server logs table.
675 func (runner *ContainerRunner) AttachStreams() (err error) {
677 runner.CrunchLog.Print("Attaching container streams")
679 // If stdin mount is provided, attach it to the docker container
680 var stdinRdr arvados.File
682 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
683 if stdinMnt.Kind == "collection" {
684 var stdinColl arvados.Collection
685 collId := stdinMnt.UUID
687 collId = stdinMnt.PortableDataHash
689 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
691 return fmt.Errorf("While getting stding collection: %v", err)
694 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
695 if os.IsNotExist(err) {
696 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
697 } else if err != nil {
698 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
700 } else if stdinMnt.Kind == "json" {
701 stdinJson, err = json.Marshal(stdinMnt.Content)
703 return fmt.Errorf("While encoding stdin json data: %v", err)
708 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
709 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
710 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
712 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
715 runner.loggingDone = make(chan bool)
717 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
718 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
722 runner.Stdout = stdoutFile
724 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
727 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
728 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
732 runner.Stderr = stderrFile
734 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
739 _, err := io.Copy(response.Conn, stdinRdr)
741 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
745 response.CloseWrite()
747 } else if len(stdinJson) != 0 {
749 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
751 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
754 response.CloseWrite()
758 go runner.ProcessDockerAttach(response.Reader)
763 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
764 stdoutPath := mntPath[len(runner.Container.OutputPath):]
765 index := strings.LastIndex(stdoutPath, "/")
767 subdirs := stdoutPath[:index]
769 st, err := os.Stat(runner.HostOutputDir)
771 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
773 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
774 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
776 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
780 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
782 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
785 return stdoutFile, nil
788 // CreateContainer creates the docker container.
789 func (runner *ContainerRunner) CreateContainer() error {
790 runner.CrunchLog.Print("Creating Docker container")
792 runner.ContainerConfig.Cmd = runner.Container.Command
793 if runner.Container.Cwd != "." {
794 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
797 for k, v := range runner.Container.Environment {
798 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
801 runner.ContainerConfig.Volumes = runner.Volumes
803 runner.HostConfig = dockercontainer.HostConfig{
805 LogConfig: dockercontainer.LogConfig{
808 Resources: dockercontainer.Resources{
809 CgroupParent: runner.setCgroupParent,
813 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
814 tok, err := runner.ContainerToken()
818 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
819 "ARVADOS_API_TOKEN="+tok,
820 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
821 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
823 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
825 if runner.enableNetwork == "always" {
826 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
828 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
832 _, stdinUsed := runner.Container.Mounts["stdin"]
833 runner.ContainerConfig.OpenStdin = stdinUsed
834 runner.ContainerConfig.StdinOnce = stdinUsed
835 runner.ContainerConfig.AttachStdin = stdinUsed
836 runner.ContainerConfig.AttachStdout = true
837 runner.ContainerConfig.AttachStderr = true
839 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
841 return fmt.Errorf("While creating container: %v", err)
844 runner.ContainerID = createdBody.ID
846 return runner.AttachStreams()
849 // StartContainer starts the docker container created by CreateContainer.
850 func (runner *ContainerRunner) StartContainer() error {
851 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
852 runner.cStateLock.Lock()
853 defer runner.cStateLock.Unlock()
854 if runner.cCancelled {
857 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
858 dockertypes.ContainerStartOptions{})
860 return fmt.Errorf("could not start container: %v", err)
862 runner.cStarted = true
866 // WaitFinish waits for the container to terminate, capture the exit code, and
867 // close the stdout/stderr logging.
868 func (runner *ContainerRunner) WaitFinish() (err error) {
869 runner.CrunchLog.Print("Waiting for container to finish")
871 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, "not-running")
873 var waitBody dockercontainer.ContainerWaitOKBody
875 case waitBody = <-waitOk:
876 case err = <-waitErr:
880 return fmt.Errorf("container wait: %v", err)
883 runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
884 code := int(waitBody.StatusCode)
885 runner.ExitCode = &code
887 waitMount := runner.ArvMountExit
889 case err = <-waitMount:
890 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
896 // wait for stdout/stderr to complete
902 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
903 func (runner *ContainerRunner) CaptureOutput() error {
904 if runner.finalState != "Complete" {
908 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
909 // Output may have been set directly by the container, so
910 // refresh the container record to check.
911 err := runner.ArvClient.Get("containers", runner.Container.UUID,
912 nil, &runner.Container)
916 if runner.Container.Output != "" {
917 // Container output is already set.
918 runner.OutputPDH = &runner.Container.Output
923 if runner.HostOutputDir == "" {
927 _, err := os.Stat(runner.HostOutputDir)
929 return fmt.Errorf("While checking host output path: %v", err)
932 // Pre-populate output from the configured mount points
934 for bind, mnt := range runner.Container.Mounts {
935 if mnt.Kind == "collection" {
936 binds = append(binds, bind)
941 var manifestText string
943 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
944 _, err = os.Stat(collectionMetafile)
948 // Find symlinks to arv-mounted files & dirs.
949 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
953 if info.Mode()&os.ModeSymlink == 0 {
956 // read link to get container internal path
957 // only support 1 level of symlinking here.
959 tgt, err = os.Readlink(path)
964 // get path relative to output dir
965 outputSuffix := path[len(runner.HostOutputDir):]
967 if strings.HasPrefix(tgt, "/") {
968 // go through mounts and try reverse map to collection reference
969 for _, bind := range binds {
970 mnt := runner.Container.Mounts[bind]
971 if tgt == bind || strings.HasPrefix(tgt, bind+"/") {
972 // get path relative to bind
973 targetSuffix := tgt[len(bind):]
975 // Copy mount and adjust the path to add path relative to the bind
977 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
981 m, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
985 manifestText = manifestText + m
986 // delete symlink so WriteTree won't try to to dereference it.
993 // Not a link to a mount. Must be dereferencible and
994 // point into the output directory.
995 tgt, err = filepath.EvalSymlinks(path)
1001 // Symlink target must be within the output directory otherwise it's an error.
1002 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1004 return fmt.Errorf("Output directory symlink %q points to invalid location %q, must point to mount or output directory.",
1010 return fmt.Errorf("While checking output symlinks: %v", err)
1013 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1015 m, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
1016 manifestText = manifestText + m
1018 return fmt.Errorf("While uploading output files: %v", err)
1021 // FUSE mount directory
1022 file, openerr := os.Open(collectionMetafile)
1024 return fmt.Errorf("While opening FUSE metafile: %v", err)
1028 var rec arvados.Collection
1029 err = json.NewDecoder(file).Decode(&rec)
1031 return fmt.Errorf("While reading FUSE metafile: %v", err)
1033 manifestText = rec.ManifestText
1036 for _, bind := range binds {
1037 mnt := runner.Container.Mounts[bind]
1039 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1041 if bindSuffix == bind || len(bindSuffix) <= 0 {
1042 // either does not start with OutputPath or is OutputPath itself
1046 if mnt.ExcludeFromOutput == true {
1050 // append to manifest_text
1051 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1056 manifestText = manifestText + m
1060 var response arvados.Collection
1061 manifest := manifest.Manifest{Text: manifestText}
1062 manifestText = manifest.Extract(".", ".").Text
1063 err = runner.ArvClient.Create("collections",
1065 "ensure_unique_name": true,
1066 "collection": arvadosclient.Dict{
1068 "name": "output for " + runner.Container.UUID,
1069 "manifest_text": manifestText}},
1072 return fmt.Errorf("While creating output collection: %v", err)
1074 runner.OutputPDH = &response.PortableDataHash
1078 var outputCollections = make(map[string]arvados.Collection)
1080 // Fetch the collection for the mnt.PortableDataHash
1081 // Return the manifest_text fragment corresponding to the specified mnt.Path
1082 // after making any required updates.
1084 // If mnt.Path is not specified,
1085 // return the entire manifest_text after replacing any "." with bindSuffix
1086 // If mnt.Path corresponds to one stream,
1087 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1088 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1089 // for that stream after replacing stream name with bindSuffix minus the last word
1090 // and the file name with last word of the bindSuffix
1091 // Allowed path examples:
1093 // "path":"/subdir1"
1094 // "path":"/subdir1/subdir2"
1095 // "path":"/subdir/filename" etc
1096 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1097 collection := outputCollections[mnt.PortableDataHash]
1098 if collection.PortableDataHash == "" {
1099 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1101 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1103 outputCollections[mnt.PortableDataHash] = collection
1106 if collection.ManifestText == "" {
1107 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1111 mft := manifest.Manifest{Text: collection.ManifestText}
1112 extracted := mft.Extract(mnt.Path, bindSuffix)
1113 if extracted.Err != nil {
1114 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1116 return extracted.Text, nil
1119 func (runner *ContainerRunner) CleanupDirs() {
1120 if runner.ArvMount != nil {
1121 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
1122 umnterr := umount.Run()
1124 runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
1127 mnterr := <-runner.ArvMountExit
1129 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
1133 for _, tmpdir := range runner.CleanupTempDir {
1134 rmerr := os.RemoveAll(tmpdir)
1136 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1141 // CommitLogs posts the collection containing the final container logs.
1142 func (runner *ContainerRunner) CommitLogs() error {
1143 runner.CrunchLog.Print(runner.finalState)
1144 runner.CrunchLog.Close()
1146 // Closing CrunchLog above allows it to be committed to Keep at this
1147 // point, but re-open crunch log with ArvClient in case there are any
1148 // other further (such as failing to write the log to Keep!) while
1150 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1151 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1153 if runner.LogsPDH != nil {
1154 // If we have already assigned something to LogsPDH,
1155 // we must be closing the re-opened log, which won't
1156 // end up getting attached to the container record and
1157 // therefore doesn't need to be saved as a collection
1158 // -- it exists only to send logs to other channels.
1162 mt, err := runner.LogCollection.ManifestText()
1164 return fmt.Errorf("While creating log manifest: %v", err)
1167 var response arvados.Collection
1168 err = runner.ArvClient.Create("collections",
1170 "ensure_unique_name": true,
1171 "collection": arvadosclient.Dict{
1173 "name": "logs for " + runner.Container.UUID,
1174 "manifest_text": mt}},
1177 return fmt.Errorf("While creating log collection: %v", err)
1179 runner.LogsPDH = &response.PortableDataHash
1183 // UpdateContainerRunning updates the container state to "Running"
1184 func (runner *ContainerRunner) UpdateContainerRunning() error {
1185 runner.cStateLock.Lock()
1186 defer runner.cStateLock.Unlock()
1187 if runner.cCancelled {
1190 return runner.ArvClient.Update("containers", runner.Container.UUID,
1191 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1194 // ContainerToken returns the api_token the container (and any
1195 // arv-mount processes) are allowed to use.
1196 func (runner *ContainerRunner) ContainerToken() (string, error) {
1197 if runner.token != "" {
1198 return runner.token, nil
1201 var auth arvados.APIClientAuthorization
1202 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1206 runner.token = auth.APIToken
1207 return runner.token, nil
1210 // UpdateContainerComplete updates the container record state on API
1211 // server to "Complete" or "Cancelled"
1212 func (runner *ContainerRunner) UpdateContainerFinal() error {
1213 update := arvadosclient.Dict{}
1214 update["state"] = runner.finalState
1215 if runner.LogsPDH != nil {
1216 update["log"] = *runner.LogsPDH
1218 if runner.finalState == "Complete" {
1219 if runner.ExitCode != nil {
1220 update["exit_code"] = *runner.ExitCode
1222 if runner.OutputPDH != nil {
1223 update["output"] = *runner.OutputPDH
1226 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1229 // IsCancelled returns the value of Cancelled, with goroutine safety.
1230 func (runner *ContainerRunner) IsCancelled() bool {
1231 runner.cStateLock.Lock()
1232 defer runner.cStateLock.Unlock()
1233 return runner.cCancelled
1236 // NewArvLogWriter creates an ArvLogWriter
1237 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1238 return &ArvLogWriter{ArvClient: runner.ArvClient, UUID: runner.Container.UUID, loggingStream: name,
1239 writeCloser: runner.LogCollection.Open(name + ".txt")}
1242 // Run the full container lifecycle.
1243 func (runner *ContainerRunner) Run() (err error) {
1244 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1246 hostname, hosterr := os.Hostname()
1248 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1250 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1253 // Clean up temporary directories _after_ finalizing
1254 // everything (if we've made any by then)
1255 defer runner.CleanupDirs()
1257 runner.finalState = "Queued"
1260 // checkErr prints e (unless it's nil) and sets err to
1261 // e (unless err is already non-nil). Thus, if err
1262 // hasn't already been assigned when Run() returns,
1263 // this cleanup func will cause Run() to return the
1264 // first non-nil error that is passed to checkErr().
1265 checkErr := func(e error) {
1269 runner.CrunchLog.Print(e)
1273 if runner.finalState == "Complete" {
1274 // There was an error in the finalization.
1275 runner.finalState = "Cancelled"
1279 // Log the error encountered in Run(), if any
1282 if runner.finalState == "Queued" {
1283 runner.CrunchLog.Close()
1284 runner.UpdateContainerFinal()
1288 if runner.IsCancelled() {
1289 runner.finalState = "Cancelled"
1290 // but don't return yet -- we still want to
1291 // capture partial output and write logs
1294 checkErr(runner.CaptureOutput())
1295 checkErr(runner.CommitLogs())
1296 checkErr(runner.UpdateContainerFinal())
1298 // The real log is already closed, but then we opened
1299 // a new one in case we needed to log anything while
1301 runner.CrunchLog.Close()
1304 err = runner.fetchContainerRecord()
1309 // setup signal handling
1310 runner.SetupSignals()
1312 // check for and/or load image
1313 err = runner.LoadImage()
1315 runner.finalState = "Cancelled"
1316 err = fmt.Errorf("While loading container image: %v", err)
1320 // set up FUSE mount and binds
1321 err = runner.SetupMounts()
1323 runner.finalState = "Cancelled"
1324 err = fmt.Errorf("While setting up mounts: %v", err)
1328 err = runner.CreateContainer()
1333 // Gather and record node information
1334 err = runner.LogNodeInfo()
1338 // Save container.json record on log collection
1339 err = runner.LogContainerRecord()
1344 runner.StartCrunchstat()
1346 if runner.IsCancelled() {
1350 err = runner.UpdateContainerRunning()
1354 runner.finalState = "Cancelled"
1356 err = runner.StartContainer()
1361 err = runner.WaitFinish()
1363 runner.finalState = "Complete"
1368 // Fetch the current container record (uuid = runner.Container.UUID)
1369 // into runner.Container.
1370 func (runner *ContainerRunner) fetchContainerRecord() error {
1371 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1373 return fmt.Errorf("error fetching container record: %v", err)
1375 defer reader.Close()
1377 dec := json.NewDecoder(reader)
1379 err = dec.Decode(&runner.Container)
1381 return fmt.Errorf("error decoding container record: %v", err)
1386 // NewContainerRunner creates a new container runner.
1387 func NewContainerRunner(api IArvadosClient,
1389 docker ThinDockerClient,
1390 containerUUID string) *ContainerRunner {
1392 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1393 cr.NewLogWriter = cr.NewArvLogWriter
1394 cr.RunArvMount = cr.ArvMountCmd
1395 cr.MkTempDir = ioutil.TempDir
1396 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1397 cr.Container.UUID = containerUUID
1398 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1399 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1401 loadLogThrottleParams(api)
1407 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1408 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1409 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1410 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1411 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1412 enableNetwork := flag.String("container-enable-networking", "default",
1413 `Specify if networking should be enabled for container. One of 'default', 'always':
1414 default: only enable networking if container requests it.
1415 always: containers always have networking enabled
1417 networkMode := flag.String("container-network-mode", "default",
1418 `Set networking mode for container. Corresponds to Docker network mode (--net).
1422 containerId := flag.Arg(0)
1424 if *caCertsPath != "" {
1425 arvadosclient.CertFiles = []string{*caCertsPath}
1428 api, err := arvadosclient.MakeArvadosClient()
1430 log.Fatalf("%s: %v", containerId, err)
1434 var kc *keepclient.KeepClient
1435 kc, err = keepclient.MakeKeepClient(api)
1437 log.Fatalf("%s: %v", containerId, err)
1441 var docker *dockerclient.Client
1442 // API version 1.21 corresponds to Docker 1.9, which is currently the
1443 // minimum version we want to support.
1444 docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1446 log.Fatalf("%s: %v", containerId, err)
1449 dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1451 cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1452 cr.statInterval = *statInterval
1453 cr.cgroupRoot = *cgroupRoot
1454 cr.expectCgroupParent = *cgroupParent
1455 cr.enableNetwork = *enableNetwork
1456 cr.networkMode = *networkMode
1457 if *cgroupParentSubsystem != "" {
1458 p := findCgroup(*cgroupParentSubsystem)
1459 cr.setCgroupParent = p
1460 cr.expectCgroupParent = p
1465 log.Fatalf("%s: %v", containerId, err)