1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
30 "git.curoverse.com/arvados.git/lib/crunchstat"
31 "git.curoverse.com/arvados.git/sdk/go/arvados"
32 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
33 "git.curoverse.com/arvados.git/sdk/go/keepclient"
34 "git.curoverse.com/arvados.git/sdk/go/manifest"
36 dockertypes "github.com/docker/docker/api/types"
37 dockercontainer "github.com/docker/docker/api/types/container"
38 dockernetwork "github.com/docker/docker/api/types/network"
39 dockerclient "github.com/docker/docker/client"
42 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
43 type IArvadosClient interface {
44 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
45 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
46 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
47 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
48 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
49 Discovery(key string) (interface{}, error)
52 // ErrCancelled is the error returned when the container is cancelled.
53 var ErrCancelled = errors.New("Cancelled")
55 // IKeepClient is the minimal Keep API methods used by crunch-run.
56 type IKeepClient interface {
57 PutHB(hash string, buf []byte) (string, int, error)
58 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
62 // NewLogWriter is a factory function to create a new log writer.
63 type NewLogWriter func(name string) io.WriteCloser
65 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
67 type MkTempDir func(string, string) (string, error)
69 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
70 type ThinDockerClient interface {
71 ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
72 ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
73 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
74 ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
75 ContainerStop(ctx context.Context, container string, timeout *time.Duration) error
76 ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error)
77 ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
78 ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
79 ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
82 // ThinDockerClientProxy is a proxy implementation of ThinDockerClient
83 // that executes the docker requests on dockerclient.Client
84 type ThinDockerClientProxy struct {
85 Docker *dockerclient.Client
88 // ContainerAttach invokes dockerclient.Client.ContainerAttach
89 func (proxy ThinDockerClientProxy) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
90 return proxy.Docker.ContainerAttach(ctx, container, options)
93 // ContainerCreate invokes dockerclient.Client.ContainerCreate
94 func (proxy ThinDockerClientProxy) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
95 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
96 return proxy.Docker.ContainerCreate(ctx, config, hostConfig, networkingConfig, containerName)
99 // ContainerStart invokes dockerclient.Client.ContainerStart
100 func (proxy ThinDockerClientProxy) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
101 return proxy.Docker.ContainerStart(ctx, container, options)
104 // ContainerStop invokes dockerclient.Client.ContainerStop
105 func (proxy ThinDockerClientProxy) ContainerStop(ctx context.Context, container string, timeout *time.Duration) error {
106 return proxy.Docker.ContainerStop(ctx, container, timeout)
109 // ContainerWait invokes dockerclient.Client.ContainerWait
110 func (proxy ThinDockerClientProxy) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
111 return proxy.Docker.ContainerWait(ctx, container, condition)
114 // ImageInspectWithRaw invokes dockerclient.Client.ImageInspectWithRaw
115 func (proxy ThinDockerClientProxy) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
116 return proxy.Docker.ImageInspectWithRaw(ctx, image)
119 // ImageLoad invokes dockerclient.Client.ImageLoad
120 func (proxy ThinDockerClientProxy) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
121 return proxy.Docker.ImageLoad(ctx, input, quiet)
124 // ImageRemove invokes dockerclient.Client.ImageRemove
125 func (proxy ThinDockerClientProxy) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
126 return proxy.Docker.ImageRemove(ctx, image, options)
129 // ContainerRunner is the main stateful struct used for a single execution of a
131 type ContainerRunner struct {
132 Docker ThinDockerClient
133 ArvClient IArvadosClient
136 ContainerConfig dockercontainer.Config
137 dockercontainer.HostConfig
142 loggingDone chan bool
143 CrunchLog *ThrottledLogger
144 Stdout io.WriteCloser
145 Stderr io.WriteCloser
146 LogCollection *CollectionWriter
153 CleanupTempDir []string
155 Volumes map[string]struct{}
157 SigChan chan os.Signal
158 ArvMountExit chan error
161 statLogger io.WriteCloser
162 statReporter *crunchstat.Reporter
163 statInterval time.Duration
165 // What we expect the container's cgroup parent to be.
166 expectCgroupParent string
167 // What we tell docker to use as the container's cgroup
168 // parent. Note: Ideally we would use the same field for both
169 // expectCgroupParent and setCgroupParent, and just make it
170 // default to "docker". However, when using docker < 1.10 with
171 // systemd, specifying a non-empty cgroup parent (even the
172 // default value "docker") hits a docker bug
173 // (https://github.com/docker/docker/issues/17126). Using two
174 // separate fields makes it possible to use the "expect cgroup
175 // parent to be X" feature even on sites where the "specify
176 // cgroup parent" feature breaks.
177 setCgroupParent string
179 cStateLock sync.Mutex
180 cStarted bool // StartContainer() succeeded
181 cCancelled bool // StopContainer() invoked
183 enableNetwork string // one of "default" or "always"
184 networkMode string // passed through to HostConfig.NetworkMode
187 // setupSignals sets up signal handling to gracefully terminate the underlying
188 // Docker container and update state when receiving a TERM, INT or QUIT signal.
189 func (runner *ContainerRunner) setupSignals() {
190 runner.SigChan = make(chan os.Signal, 1)
191 signal.Notify(runner.SigChan, syscall.SIGTERM)
192 signal.Notify(runner.SigChan, syscall.SIGINT)
193 signal.Notify(runner.SigChan, syscall.SIGQUIT)
195 go func(sig chan os.Signal) {
201 // stop the underlying Docker container.
202 func (runner *ContainerRunner) stop() {
203 runner.cStateLock.Lock()
204 defer runner.cStateLock.Unlock()
205 if runner.cCancelled {
208 runner.cCancelled = true
210 timeout := time.Duration(10)
211 err := runner.Docker.ContainerStop(context.TODO(), runner.ContainerID, &(timeout))
213 log.Printf("StopContainer failed: %s", err)
218 func (runner *ContainerRunner) teardown() {
219 if runner.SigChan != nil {
220 signal.Stop(runner.SigChan)
221 close(runner.SigChan)
225 // LoadImage determines the docker image id from the container record and
226 // checks if it is available in the local Docker image store. If not, it loads
227 // the image from Keep.
228 func (runner *ContainerRunner) LoadImage() (err error) {
230 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
232 var collection arvados.Collection
233 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
235 return fmt.Errorf("While getting container image collection: %v", err)
237 manifest := manifest.Manifest{Text: collection.ManifestText}
238 var img, imageID string
239 for ms := range manifest.StreamIter() {
240 img = ms.FileStreamSegments[0].Name
241 if !strings.HasSuffix(img, ".tar") {
242 return fmt.Errorf("First file in the container image collection does not end in .tar")
244 imageID = img[:len(img)-4]
247 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
249 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
251 runner.CrunchLog.Print("Loading Docker image from keep")
253 var readCloser io.ReadCloser
254 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
256 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
259 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, false)
261 return fmt.Errorf("While loading container image into Docker: %v", err)
263 response.Body.Close()
265 runner.CrunchLog.Print("Docker image is available")
268 runner.ContainerConfig.Image = imageID
270 runner.Kc.ClearBlockCache()
275 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
276 c = exec.Command("arv-mount", arvMountCmd...)
278 // Copy our environment, but override ARVADOS_API_TOKEN with
279 // the container auth token.
281 for _, s := range os.Environ() {
282 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
283 c.Env = append(c.Env, s)
286 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
288 nt := NewThrottledLogger(runner.NewLogWriter("arv-mount"))
297 statReadme := make(chan bool)
298 runner.ArvMountExit = make(chan error)
303 time.Sleep(100 * time.Millisecond)
304 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
314 runner.ArvMountExit <- c.Wait()
315 close(runner.ArvMountExit)
321 case err := <-runner.ArvMountExit:
322 runner.ArvMount = nil
330 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
331 if runner.ArvMountPoint == "" {
332 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
337 func (runner *ContainerRunner) SetupMounts() (err error) {
338 err = runner.SetupArvMountPoint("keep")
340 return fmt.Errorf("While creating keep mount temp dir: %v", err)
343 runner.CleanupTempDir = append(runner.CleanupTempDir, runner.ArvMountPoint)
347 arvMountCmd := []string{"--foreground", "--allow-other", "--read-write"}
349 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
350 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
353 collectionPaths := []string{}
355 runner.Volumes = make(map[string]struct{})
356 needCertMount := true
359 for bind := range runner.Container.Mounts {
360 binds = append(binds, bind)
364 for _, bind := range binds {
365 mnt := runner.Container.Mounts[bind]
366 if bind == "stdout" || bind == "stderr" {
367 // Is it a "file" mount kind?
368 if mnt.Kind != "file" {
369 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
372 // Does path start with OutputPath?
373 prefix := runner.Container.OutputPath
374 if !strings.HasSuffix(prefix, "/") {
377 if !strings.HasPrefix(mnt.Path, prefix) {
378 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
383 // Is it a "collection" mount kind?
384 if mnt.Kind != "collection" && mnt.Kind != "json" {
385 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
389 if bind == "/etc/arvados/ca-certificates.crt" {
390 needCertMount = false
393 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
394 if mnt.Kind != "collection" {
395 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
400 case mnt.Kind == "collection" && bind != "stdin":
402 if mnt.UUID != "" && mnt.PortableDataHash != "" {
403 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
407 return fmt.Errorf("Writing to existing collections currently not permitted.")
410 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
411 } else if mnt.PortableDataHash != "" {
413 return fmt.Errorf("Can never write to a collection specified by portable data hash")
415 idx := strings.Index(mnt.PortableDataHash, "/")
417 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
418 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
419 runner.Container.Mounts[bind] = mnt
421 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
422 if mnt.Path != "" && mnt.Path != "." {
423 if strings.HasPrefix(mnt.Path, "./") {
424 mnt.Path = mnt.Path[2:]
425 } else if strings.HasPrefix(mnt.Path, "/") {
426 mnt.Path = mnt.Path[1:]
428 src += "/" + mnt.Path
431 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
432 arvMountCmd = append(arvMountCmd, "--mount-tmp")
433 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
437 if bind == runner.Container.OutputPath {
438 runner.HostOutputDir = src
439 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
440 return fmt.Errorf("Writable mount points are not permitted underneath the output_path: %v", bind)
442 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
444 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
446 collectionPaths = append(collectionPaths, src)
448 case mnt.Kind == "tmp":
450 tmpdir, err = runner.MkTempDir("", "")
452 return fmt.Errorf("While creating mount temp dir: %v", err)
454 st, staterr := os.Stat(tmpdir)
456 return fmt.Errorf("While Stat on temp dir: %v", staterr)
458 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
460 return fmt.Errorf("While Chmod temp dir: %v", err)
462 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
463 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
464 if bind == runner.Container.OutputPath {
465 runner.HostOutputDir = tmpdir
468 case mnt.Kind == "json":
469 jsondata, err := json.Marshal(mnt.Content)
471 return fmt.Errorf("encoding json data: %v", err)
473 // Create a tempdir with a single file
474 // (instead of just a tempfile): this way we
475 // can ensure the file is world-readable
476 // inside the container, without having to
477 // make it world-readable on the docker host.
478 tmpdir, err := runner.MkTempDir("", "")
480 return fmt.Errorf("creating temp dir: %v", err)
482 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
483 tmpfn := filepath.Join(tmpdir, "mountdata.json")
484 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
486 return fmt.Errorf("writing temp file: %v", err)
488 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
492 if runner.HostOutputDir == "" {
493 return fmt.Errorf("Output path does not correspond to a writable mount point")
496 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
497 for _, certfile := range arvadosclient.CertFiles {
498 _, err := os.Stat(certfile)
500 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
507 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
509 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
511 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
513 token, err := runner.ContainerToken()
515 return fmt.Errorf("could not get container token: %s", err)
518 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
520 return fmt.Errorf("While trying to start arv-mount: %v", err)
523 for _, p := range collectionPaths {
526 return fmt.Errorf("While checking that input files exist: %v", err)
533 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
534 // Handle docker log protocol
535 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
537 header := make([]byte, 8)
539 _, readerr := io.ReadAtLeast(containerReader, header, 8)
542 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
545 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
548 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
553 if readerr != io.EOF {
554 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
557 closeerr := runner.Stdout.Close()
559 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
562 closeerr = runner.Stderr.Close()
564 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
567 if runner.statReporter != nil {
568 runner.statReporter.Stop()
569 closeerr = runner.statLogger.Close()
571 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
575 runner.loggingDone <- true
576 close(runner.loggingDone)
582 func (runner *ContainerRunner) StartCrunchstat() {
583 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
584 runner.statReporter = &crunchstat.Reporter{
585 CID: runner.ContainerID,
586 Logger: log.New(runner.statLogger, "", 0),
587 CgroupParent: runner.expectCgroupParent,
588 CgroupRoot: runner.cgroupRoot,
589 PollPeriod: runner.statInterval,
591 runner.statReporter.Start()
594 type infoCommand struct {
599 // Gather node information and store it on the log for debugging
601 func (runner *ContainerRunner) LogNodeInfo() (err error) {
602 w := runner.NewLogWriter("node-info")
603 logger := log.New(w, "node-info", 0)
605 commands := []infoCommand{
607 label: "Host Information",
608 cmd: []string{"uname", "-a"},
611 label: "CPU Information",
612 cmd: []string{"cat", "/proc/cpuinfo"},
615 label: "Memory Information",
616 cmd: []string{"cat", "/proc/meminfo"},
620 cmd: []string{"df", "-m", "/", os.TempDir()},
623 label: "Disk INodes",
624 cmd: []string{"df", "-i", "/", os.TempDir()},
628 // Run commands with informational output to be logged.
630 for _, command := range commands {
631 out, err = exec.Command(command.cmd[0], command.cmd[1:]...).CombinedOutput()
633 return fmt.Errorf("While running command %q: %v",
636 logger.Println(command.label)
637 for _, line := range strings.Split(string(out), "\n") {
638 logger.Println(" ", line)
644 return fmt.Errorf("While closing node-info logs: %v", err)
649 // Get and save the raw JSON container record from the API server
650 func (runner *ContainerRunner) LogContainerRecord() (err error) {
652 ArvClient: runner.ArvClient,
653 UUID: runner.Container.UUID,
654 loggingStream: "container",
655 writeCloser: runner.LogCollection.Open("container.json"),
658 // Get Container record JSON from the API Server
659 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
661 return fmt.Errorf("While retrieving container record from the API server: %v", err)
665 dec := json.NewDecoder(reader)
667 var cr map[string]interface{}
668 if err = dec.Decode(&cr); err != nil {
669 return fmt.Errorf("While decoding the container record JSON response: %v", err)
671 // Re-encode it using indentation to improve readability
672 enc := json.NewEncoder(w)
673 enc.SetIndent("", " ")
674 if err = enc.Encode(cr); err != nil {
675 return fmt.Errorf("While logging the JSON container record: %v", err)
679 return fmt.Errorf("While closing container.json log: %v", err)
684 // AttachStreams connects the docker container stdin, stdout and stderr logs
685 // to the Arvados logger which logs to Keep and the API server logs table.
686 func (runner *ContainerRunner) AttachStreams() (err error) {
688 runner.CrunchLog.Print("Attaching container streams")
690 // If stdin mount is provided, attach it to the docker container
691 var stdinRdr arvados.File
693 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
694 if stdinMnt.Kind == "collection" {
695 var stdinColl arvados.Collection
696 collId := stdinMnt.UUID
698 collId = stdinMnt.PortableDataHash
700 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
702 return fmt.Errorf("While getting stding collection: %v", err)
705 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
706 if os.IsNotExist(err) {
707 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
708 } else if err != nil {
709 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
711 } else if stdinMnt.Kind == "json" {
712 stdinJson, err = json.Marshal(stdinMnt.Content)
714 return fmt.Errorf("While encoding stdin json data: %v", err)
719 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
720 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
721 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
723 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
726 runner.loggingDone = make(chan bool)
728 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
729 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
733 runner.Stdout = stdoutFile
735 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
738 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
739 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
743 runner.Stderr = stderrFile
745 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
750 _, err := io.Copy(response.Conn, stdinRdr)
752 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
756 response.CloseWrite()
758 } else if len(stdinJson) != 0 {
760 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
762 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
765 response.CloseWrite()
769 go runner.ProcessDockerAttach(response.Reader)
774 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
775 stdoutPath := mntPath[len(runner.Container.OutputPath):]
776 index := strings.LastIndex(stdoutPath, "/")
778 subdirs := stdoutPath[:index]
780 st, err := os.Stat(runner.HostOutputDir)
782 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
784 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
785 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
787 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
791 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
793 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
796 return stdoutFile, nil
799 // CreateContainer creates the docker container.
800 func (runner *ContainerRunner) CreateContainer() error {
801 runner.CrunchLog.Print("Creating Docker container")
803 runner.ContainerConfig.Cmd = runner.Container.Command
804 if runner.Container.Cwd != "." {
805 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
808 for k, v := range runner.Container.Environment {
809 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
812 runner.ContainerConfig.Volumes = runner.Volumes
814 runner.HostConfig = dockercontainer.HostConfig{
816 LogConfig: dockercontainer.LogConfig{
819 Resources: dockercontainer.Resources{
820 CgroupParent: runner.setCgroupParent,
824 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
825 tok, err := runner.ContainerToken()
829 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
830 "ARVADOS_API_TOKEN="+tok,
831 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
832 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
834 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
836 if runner.enableNetwork == "always" {
837 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
839 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
843 _, stdinUsed := runner.Container.Mounts["stdin"]
844 runner.ContainerConfig.OpenStdin = stdinUsed
845 runner.ContainerConfig.StdinOnce = stdinUsed
846 runner.ContainerConfig.AttachStdin = stdinUsed
847 runner.ContainerConfig.AttachStdout = true
848 runner.ContainerConfig.AttachStderr = true
850 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
852 return fmt.Errorf("While creating container: %v", err)
855 runner.ContainerID = createdBody.ID
857 return runner.AttachStreams()
860 // StartContainer starts the docker container created by CreateContainer.
861 func (runner *ContainerRunner) StartContainer() error {
862 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
863 runner.cStateLock.Lock()
864 defer runner.cStateLock.Unlock()
865 if runner.cCancelled {
868 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
869 dockertypes.ContainerStartOptions{})
872 if strings.Contains(err.Error(), "no such file or directory") {
873 advice = fmt.Sprintf("\nPossible causes: command %q is missing, the interpreter given in #! is missing, or script has Windows line endings.", runner.Container.Command[0])
875 return fmt.Errorf("could not start container: %v%s", err, advice)
877 runner.cStarted = true
881 // WaitFinish waits for the container to terminate, capture the exit code, and
882 // close the stdout/stderr logging.
883 func (runner *ContainerRunner) WaitFinish() (err error) {
884 runner.CrunchLog.Print("Waiting for container to finish")
886 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, "not-running")
888 var waitBody dockercontainer.ContainerWaitOKBody
890 case waitBody = <-waitOk:
891 case err = <-waitErr:
895 return fmt.Errorf("container wait: %v", err)
898 runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
899 code := int(waitBody.StatusCode)
900 runner.ExitCode = &code
902 waitMount := runner.ArvMountExit
904 case err = <-waitMount:
905 runner.CrunchLog.Printf("arv-mount exited before container finished: %v", err)
911 // wait for stdout/stderr to complete
917 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
918 func (runner *ContainerRunner) CaptureOutput() error {
919 if runner.finalState != "Complete" {
923 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
924 // Output may have been set directly by the container, so
925 // refresh the container record to check.
926 err := runner.ArvClient.Get("containers", runner.Container.UUID,
927 nil, &runner.Container)
931 if runner.Container.Output != "" {
932 // Container output is already set.
933 runner.OutputPDH = &runner.Container.Output
938 if runner.HostOutputDir == "" {
942 _, err := os.Stat(runner.HostOutputDir)
944 return fmt.Errorf("While checking host output path: %v", err)
947 // Pre-populate output from the configured mount points
949 for bind, mnt := range runner.Container.Mounts {
950 if mnt.Kind == "collection" {
951 binds = append(binds, bind)
956 var manifestText string
958 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
959 _, err = os.Stat(collectionMetafile)
963 // Find symlinks to arv-mounted files & dirs.
964 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
968 if info.Mode()&os.ModeSymlink == 0 {
971 // read link to get container internal path
972 // only support 1 level of symlinking here.
974 tgt, err = os.Readlink(path)
979 // get path relative to output dir
980 outputSuffix := path[len(runner.HostOutputDir):]
982 if strings.HasPrefix(tgt, "/") {
983 // go through mounts and try reverse map to collection reference
984 for _, bind := range binds {
985 mnt := runner.Container.Mounts[bind]
986 if tgt == bind || strings.HasPrefix(tgt, bind+"/") {
987 // get path relative to bind
988 targetSuffix := tgt[len(bind):]
990 // Copy mount and adjust the path to add path relative to the bind
992 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
996 m, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
1000 manifestText = manifestText + m
1001 // delete symlink so WriteTree won't try to to dereference it.
1008 // Not a link to a mount. Must be dereferencible and
1009 // point into the output directory.
1010 tgt, err = filepath.EvalSymlinks(path)
1016 // Symlink target must be within the output directory otherwise it's an error.
1017 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1019 return fmt.Errorf("Output directory symlink %q points to invalid location %q, must point to mount or output directory.",
1025 return fmt.Errorf("While checking output symlinks: %v", err)
1028 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1030 m, err = cw.WriteTree(runner.HostOutputDir, runner.CrunchLog.Logger)
1031 manifestText = manifestText + m
1033 return fmt.Errorf("While uploading output files: %v", err)
1036 // FUSE mount directory
1037 file, openerr := os.Open(collectionMetafile)
1039 return fmt.Errorf("While opening FUSE metafile: %v", err)
1043 var rec arvados.Collection
1044 err = json.NewDecoder(file).Decode(&rec)
1046 return fmt.Errorf("While reading FUSE metafile: %v", err)
1048 manifestText = rec.ManifestText
1051 for _, bind := range binds {
1052 mnt := runner.Container.Mounts[bind]
1054 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1056 if bindSuffix == bind || len(bindSuffix) <= 0 {
1057 // either does not start with OutputPath or is OutputPath itself
1061 if mnt.ExcludeFromOutput == true {
1065 // append to manifest_text
1066 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1071 manifestText = manifestText + m
1075 var response arvados.Collection
1076 manifest := manifest.Manifest{Text: manifestText}
1077 manifestText = manifest.Extract(".", ".").Text
1078 err = runner.ArvClient.Create("collections",
1080 "ensure_unique_name": true,
1081 "collection": arvadosclient.Dict{
1083 "name": "output for " + runner.Container.UUID,
1084 "manifest_text": manifestText}},
1087 return fmt.Errorf("While creating output collection: %v", err)
1089 runner.OutputPDH = &response.PortableDataHash
1093 var outputCollections = make(map[string]arvados.Collection)
1095 // Fetch the collection for the mnt.PortableDataHash
1096 // Return the manifest_text fragment corresponding to the specified mnt.Path
1097 // after making any required updates.
1099 // If mnt.Path is not specified,
1100 // return the entire manifest_text after replacing any "." with bindSuffix
1101 // If mnt.Path corresponds to one stream,
1102 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1103 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1104 // for that stream after replacing stream name with bindSuffix minus the last word
1105 // and the file name with last word of the bindSuffix
1106 // Allowed path examples:
1108 // "path":"/subdir1"
1109 // "path":"/subdir1/subdir2"
1110 // "path":"/subdir/filename" etc
1111 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1112 collection := outputCollections[mnt.PortableDataHash]
1113 if collection.PortableDataHash == "" {
1114 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1116 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1118 outputCollections[mnt.PortableDataHash] = collection
1121 if collection.ManifestText == "" {
1122 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1126 mft := manifest.Manifest{Text: collection.ManifestText}
1127 extracted := mft.Extract(mnt.Path, bindSuffix)
1128 if extracted.Err != nil {
1129 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1131 return extracted.Text, nil
1134 func (runner *ContainerRunner) CleanupDirs() {
1135 if runner.ArvMount != nil {
1136 umount := exec.Command("fusermount", "-z", "-u", runner.ArvMountPoint)
1137 umnterr := umount.Run()
1139 runner.CrunchLog.Printf("While running fusermount: %v", umnterr)
1142 mnterr := <-runner.ArvMountExit
1144 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
1148 for _, tmpdir := range runner.CleanupTempDir {
1149 rmerr := os.RemoveAll(tmpdir)
1151 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1156 // CommitLogs posts the collection containing the final container logs.
1157 func (runner *ContainerRunner) CommitLogs() error {
1158 runner.CrunchLog.Print(runner.finalState)
1159 runner.CrunchLog.Close()
1161 // Closing CrunchLog above allows it to be committed to Keep at this
1162 // point, but re-open crunch log with ArvClient in case there are any
1163 // other further (such as failing to write the log to Keep!) while
1165 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1166 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1168 if runner.LogsPDH != nil {
1169 // If we have already assigned something to LogsPDH,
1170 // we must be closing the re-opened log, which won't
1171 // end up getting attached to the container record and
1172 // therefore doesn't need to be saved as a collection
1173 // -- it exists only to send logs to other channels.
1177 mt, err := runner.LogCollection.ManifestText()
1179 return fmt.Errorf("While creating log manifest: %v", err)
1182 var response arvados.Collection
1183 err = runner.ArvClient.Create("collections",
1185 "ensure_unique_name": true,
1186 "collection": arvadosclient.Dict{
1188 "name": "logs for " + runner.Container.UUID,
1189 "manifest_text": mt}},
1192 return fmt.Errorf("While creating log collection: %v", err)
1194 runner.LogsPDH = &response.PortableDataHash
1198 // UpdateContainerRunning updates the container state to "Running"
1199 func (runner *ContainerRunner) UpdateContainerRunning() error {
1200 runner.cStateLock.Lock()
1201 defer runner.cStateLock.Unlock()
1202 if runner.cCancelled {
1205 return runner.ArvClient.Update("containers", runner.Container.UUID,
1206 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1209 // ContainerToken returns the api_token the container (and any
1210 // arv-mount processes) are allowed to use.
1211 func (runner *ContainerRunner) ContainerToken() (string, error) {
1212 if runner.token != "" {
1213 return runner.token, nil
1216 var auth arvados.APIClientAuthorization
1217 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1221 runner.token = auth.APIToken
1222 return runner.token, nil
1225 // UpdateContainerComplete updates the container record state on API
1226 // server to "Complete" or "Cancelled"
1227 func (runner *ContainerRunner) UpdateContainerFinal() error {
1228 update := arvadosclient.Dict{}
1229 update["state"] = runner.finalState
1230 if runner.LogsPDH != nil {
1231 update["log"] = *runner.LogsPDH
1233 if runner.finalState == "Complete" {
1234 if runner.ExitCode != nil {
1235 update["exit_code"] = *runner.ExitCode
1237 if runner.OutputPDH != nil {
1238 update["output"] = *runner.OutputPDH
1241 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1244 // IsCancelled returns the value of Cancelled, with goroutine safety.
1245 func (runner *ContainerRunner) IsCancelled() bool {
1246 runner.cStateLock.Lock()
1247 defer runner.cStateLock.Unlock()
1248 return runner.cCancelled
1251 // NewArvLogWriter creates an ArvLogWriter
1252 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1253 return &ArvLogWriter{ArvClient: runner.ArvClient, UUID: runner.Container.UUID, loggingStream: name,
1254 writeCloser: runner.LogCollection.Open(name + ".txt")}
1257 // Run the full container lifecycle.
1258 func (runner *ContainerRunner) Run() (err error) {
1259 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1261 hostname, hosterr := os.Hostname()
1263 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1265 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1268 // Clean up temporary directories _after_ finalizing
1269 // everything (if we've made any by then)
1270 defer runner.CleanupDirs()
1272 runner.finalState = "Queued"
1275 // checkErr prints e (unless it's nil) and sets err to
1276 // e (unless err is already non-nil). Thus, if err
1277 // hasn't already been assigned when Run() returns,
1278 // this cleanup func will cause Run() to return the
1279 // first non-nil error that is passed to checkErr().
1280 checkErr := func(e error) {
1284 runner.CrunchLog.Print(e)
1288 if runner.finalState == "Complete" {
1289 // There was an error in the finalization.
1290 runner.finalState = "Cancelled"
1294 // Log the error encountered in Run(), if any
1297 if runner.finalState == "Queued" {
1298 runner.CrunchLog.Close()
1299 runner.UpdateContainerFinal()
1303 if runner.IsCancelled() {
1304 runner.finalState = "Cancelled"
1305 // but don't return yet -- we still want to
1306 // capture partial output and write logs
1309 checkErr(runner.CaptureOutput())
1310 checkErr(runner.CommitLogs())
1311 checkErr(runner.UpdateContainerFinal())
1313 // The real log is already closed, but then we opened
1314 // a new one in case we needed to log anything while
1316 runner.CrunchLog.Close()
1321 err = runner.fetchContainerRecord()
1326 // setup signal handling
1327 runner.setupSignals()
1329 // check for and/or load image
1330 err = runner.LoadImage()
1332 runner.finalState = "Cancelled"
1333 err = fmt.Errorf("While loading container image: %v", err)
1337 // set up FUSE mount and binds
1338 err = runner.SetupMounts()
1340 runner.finalState = "Cancelled"
1341 err = fmt.Errorf("While setting up mounts: %v", err)
1345 err = runner.CreateContainer()
1350 // Gather and record node information
1351 err = runner.LogNodeInfo()
1355 // Save container.json record on log collection
1356 err = runner.LogContainerRecord()
1361 runner.StartCrunchstat()
1363 if runner.IsCancelled() {
1367 err = runner.UpdateContainerRunning()
1371 runner.finalState = "Cancelled"
1373 err = runner.StartContainer()
1378 err = runner.WaitFinish()
1380 runner.finalState = "Complete"
1385 // Fetch the current container record (uuid = runner.Container.UUID)
1386 // into runner.Container.
1387 func (runner *ContainerRunner) fetchContainerRecord() error {
1388 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1390 return fmt.Errorf("error fetching container record: %v", err)
1392 defer reader.Close()
1394 dec := json.NewDecoder(reader)
1396 err = dec.Decode(&runner.Container)
1398 return fmt.Errorf("error decoding container record: %v", err)
1403 // NewContainerRunner creates a new container runner.
1404 func NewContainerRunner(api IArvadosClient,
1406 docker ThinDockerClient,
1407 containerUUID string) *ContainerRunner {
1409 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1410 cr.NewLogWriter = cr.NewArvLogWriter
1411 cr.RunArvMount = cr.ArvMountCmd
1412 cr.MkTempDir = ioutil.TempDir
1413 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1414 cr.Container.UUID = containerUUID
1415 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1416 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1418 loadLogThrottleParams(api)
1424 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1425 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1426 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1427 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1428 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1429 enableNetwork := flag.String("container-enable-networking", "default",
1430 `Specify if networking should be enabled for container. One of 'default', 'always':
1431 default: only enable networking if container requests it.
1432 always: containers always have networking enabled
1434 networkMode := flag.String("container-network-mode", "default",
1435 `Set networking mode for container. Corresponds to Docker network mode (--net).
1437 memprofile := flag.String("memprofile", "", "write memory profile to `file` after running container")
1440 containerId := flag.Arg(0)
1442 if *caCertsPath != "" {
1443 arvadosclient.CertFiles = []string{*caCertsPath}
1446 api, err := arvadosclient.MakeArvadosClient()
1448 log.Fatalf("%s: %v", containerId, err)
1452 var kc *keepclient.KeepClient
1453 kc, err = keepclient.MakeKeepClient(api)
1455 log.Fatalf("%s: %v", containerId, err)
1457 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1460 var docker *dockerclient.Client
1461 // API version 1.21 corresponds to Docker 1.9, which is currently the
1462 // minimum version we want to support.
1463 docker, err = dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1465 log.Fatalf("%s: %v", containerId, err)
1468 dockerClientProxy := ThinDockerClientProxy{Docker: docker}
1470 cr := NewContainerRunner(api, kc, dockerClientProxy, containerId)
1471 cr.statInterval = *statInterval
1472 cr.cgroupRoot = *cgroupRoot
1473 cr.expectCgroupParent = *cgroupParent
1474 cr.enableNetwork = *enableNetwork
1475 cr.networkMode = *networkMode
1476 if *cgroupParentSubsystem != "" {
1477 p := findCgroup(*cgroupParentSubsystem)
1478 cr.setCgroupParent = p
1479 cr.expectCgroupParent = p
1484 if *memprofile != "" {
1485 f, err := os.Create(*memprofile)
1487 log.Printf("could not create memory profile: ", err)
1489 runtime.GC() // get up-to-date statistics
1490 if err := pprof.WriteHeapProfile(f); err != nil {
1491 log.Printf("could not write memory profile: ", err)
1493 closeerr := f.Close()
1494 if closeerr != nil {
1495 log.Printf("closing memprofile file: ", err)
1500 log.Fatalf("%s: %v", containerId, runerr)