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"
35 "golang.org/x/net/context"
37 dockertypes "github.com/docker/docker/api/types"
38 dockercontainer "github.com/docker/docker/api/types/container"
39 dockernetwork "github.com/docker/docker/api/types/network"
40 dockerclient "github.com/docker/docker/client"
45 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
46 type IArvadosClient interface {
47 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
48 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
49 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
50 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
51 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
52 Discovery(key string) (interface{}, error)
55 // ErrCancelled is the error returned when the container is cancelled.
56 var ErrCancelled = errors.New("Cancelled")
58 // IKeepClient is the minimal Keep API methods used by crunch-run.
59 type IKeepClient interface {
60 PutHB(hash string, buf []byte) (string, int, error)
61 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
65 // NewLogWriter is a factory function to create a new log writer.
66 type NewLogWriter func(name string) io.WriteCloser
68 type RunArvMount func(args []string, tok string) (*exec.Cmd, error)
70 type MkTempDir func(string, string) (string, error)
72 // ThinDockerClient is the minimal Docker client interface used by crunch-run.
73 type ThinDockerClient interface {
74 ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
75 ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig,
76 networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
77 ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
78 ContainerRemove(ctx context.Context, container string, options dockertypes.ContainerRemoveOptions) error
79 ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error)
80 ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
81 ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error)
82 ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
85 // ContainerRunner is the main stateful struct used for a single execution of a
87 type ContainerRunner struct {
88 Docker ThinDockerClient
89 ArvClient IArvadosClient
92 ContainerConfig dockercontainer.Config
93 dockercontainer.HostConfig
99 CrunchLog *ThrottledLogger
100 Stdout io.WriteCloser
101 Stderr io.WriteCloser
102 LogCollection *CollectionWriter
110 Volumes map[string]struct{}
112 SigChan chan os.Signal
113 ArvMountExit chan error
117 statLogger io.WriteCloser
118 statReporter *crunchstat.Reporter
119 hoststatLogger io.WriteCloser
120 hoststatReporter *crunchstat.Reporter
121 statInterval time.Duration
123 // What we expect the container's cgroup parent to be.
124 expectCgroupParent string
125 // What we tell docker to use as the container's cgroup
126 // parent. Note: Ideally we would use the same field for both
127 // expectCgroupParent and setCgroupParent, and just make it
128 // default to "docker". However, when using docker < 1.10 with
129 // systemd, specifying a non-empty cgroup parent (even the
130 // default value "docker") hits a docker bug
131 // (https://github.com/docker/docker/issues/17126). Using two
132 // separate fields makes it possible to use the "expect cgroup
133 // parent to be X" feature even on sites where the "specify
134 // cgroup parent" feature breaks.
135 setCgroupParent string
137 cStateLock sync.Mutex
138 cCancelled bool // StopContainer() invoked
140 enableNetwork string // one of "default" or "always"
141 networkMode string // passed through to HostConfig.NetworkMode
142 arvMountLog *ThrottledLogger
145 // setupSignals sets up signal handling to gracefully terminate the underlying
146 // Docker container and update state when receiving a TERM, INT or QUIT signal.
147 func (runner *ContainerRunner) setupSignals() {
148 runner.SigChan = make(chan os.Signal, 1)
149 signal.Notify(runner.SigChan, syscall.SIGTERM)
150 signal.Notify(runner.SigChan, syscall.SIGINT)
151 signal.Notify(runner.SigChan, syscall.SIGQUIT)
153 go func(sig chan os.Signal) {
155 runner.CrunchLog.Printf("caught signal: %v", s)
161 // stop the underlying Docker container.
162 func (runner *ContainerRunner) stop() {
163 runner.cStateLock.Lock()
164 defer runner.cStateLock.Unlock()
165 if runner.ContainerID == "" {
168 runner.cCancelled = true
169 runner.CrunchLog.Printf("removing container")
170 err := runner.Docker.ContainerRemove(context.TODO(), runner.ContainerID, dockertypes.ContainerRemoveOptions{Force: true})
172 runner.CrunchLog.Printf("error removing container: %s", err)
176 func (runner *ContainerRunner) stopSignals() {
177 if runner.SigChan != nil {
178 signal.Stop(runner.SigChan)
182 var errorBlacklist = []string{
183 "(?ms).*[Cc]annot connect to the Docker daemon.*",
184 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
186 var brokenNodeHook *string = flag.String("broken-node-hook", "", "Script to run if node is detected to be broken (for example, Docker daemon is not running)")
188 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
189 for _, d := range errorBlacklist {
190 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
191 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
192 if *brokenNodeHook == "" {
193 runner.CrunchLog.Printf("No broken node hook provided, cannot mark node as broken.")
195 runner.CrunchLog.Printf("Running broken node hook %q", *brokenNodeHook)
197 c := exec.Command(*brokenNodeHook)
198 c.Stdout = runner.CrunchLog
199 c.Stderr = runner.CrunchLog
202 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
211 // LoadImage determines the docker image id from the container record and
212 // checks if it is available in the local Docker image store. If not, it loads
213 // the image from Keep.
214 func (runner *ContainerRunner) LoadImage() (err error) {
216 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
218 var collection arvados.Collection
219 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
221 return fmt.Errorf("While getting container image collection: %v", err)
223 manifest := manifest.Manifest{Text: collection.ManifestText}
224 var img, imageID string
225 for ms := range manifest.StreamIter() {
226 img = ms.FileStreamSegments[0].Name
227 if !strings.HasSuffix(img, ".tar") {
228 return fmt.Errorf("First file in the container image collection does not end in .tar")
230 imageID = img[:len(img)-4]
233 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
235 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
237 runner.CrunchLog.Print("Loading Docker image from keep")
239 var readCloser io.ReadCloser
240 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
242 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
245 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, true)
247 return fmt.Errorf("While loading container image into Docker: %v", err)
250 defer response.Body.Close()
251 rbody, err := ioutil.ReadAll(response.Body)
253 return fmt.Errorf("Reading response to image load: %v", err)
255 runner.CrunchLog.Printf("Docker response: %s", rbody)
257 runner.CrunchLog.Print("Docker image is available")
260 runner.ContainerConfig.Image = imageID
262 runner.Kc.ClearBlockCache()
267 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
268 c = exec.Command("arv-mount", arvMountCmd...)
270 // Copy our environment, but override ARVADOS_API_TOKEN with
271 // the container auth token.
273 for _, s := range os.Environ() {
274 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
275 c.Env = append(c.Env, s)
278 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
280 runner.arvMountLog = NewThrottledLogger(runner.NewLogWriter("arv-mount"))
281 c.Stdout = runner.arvMountLog
282 c.Stderr = runner.arvMountLog
284 runner.CrunchLog.Printf("Running %v", c.Args)
291 statReadme := make(chan bool)
292 runner.ArvMountExit = make(chan error)
297 time.Sleep(100 * time.Millisecond)
298 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
310 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
312 runner.ArvMountExit <- mnterr
313 close(runner.ArvMountExit)
319 case err := <-runner.ArvMountExit:
320 runner.ArvMount = nil
328 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
329 if runner.ArvMountPoint == "" {
330 runner.ArvMountPoint, err = runner.MkTempDir(runner.parentTemp, prefix)
335 func copyfile(src string, dst string) (err error) {
336 srcfile, err := os.Open(src)
341 os.MkdirAll(path.Dir(dst), 0777)
343 dstfile, err := os.Create(dst)
347 _, err = io.Copy(dstfile, srcfile)
352 err = srcfile.Close()
353 err2 := dstfile.Close()
366 func (runner *ContainerRunner) SetupMounts() (err error) {
367 err = runner.SetupArvMountPoint("keep")
369 return fmt.Errorf("While creating keep mount temp dir: %v", err)
372 token, err := runner.ContainerToken()
374 return fmt.Errorf("could not get container token: %s", err)
379 arvMountCmd := []string{
383 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
385 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
386 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
389 collectionPaths := []string{}
391 runner.Volumes = make(map[string]struct{})
392 needCertMount := true
393 type copyFile struct {
397 var copyFiles []copyFile
400 for bind := range runner.Container.Mounts {
401 binds = append(binds, bind)
405 for _, bind := range binds {
406 mnt := runner.Container.Mounts[bind]
407 if bind == "stdout" || bind == "stderr" {
408 // Is it a "file" mount kind?
409 if mnt.Kind != "file" {
410 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
413 // Does path start with OutputPath?
414 prefix := runner.Container.OutputPath
415 if !strings.HasSuffix(prefix, "/") {
418 if !strings.HasPrefix(mnt.Path, prefix) {
419 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
424 // Is it a "collection" mount kind?
425 if mnt.Kind != "collection" && mnt.Kind != "json" {
426 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
430 if bind == "/etc/arvados/ca-certificates.crt" {
431 needCertMount = false
434 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
435 if mnt.Kind != "collection" {
436 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
441 case mnt.Kind == "collection" && bind != "stdin":
443 if mnt.UUID != "" && mnt.PortableDataHash != "" {
444 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
448 return fmt.Errorf("Writing to existing collections currently not permitted.")
451 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
452 } else if mnt.PortableDataHash != "" {
453 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
454 return fmt.Errorf("Can never write to a collection specified by portable data hash")
456 idx := strings.Index(mnt.PortableDataHash, "/")
458 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
459 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
460 runner.Container.Mounts[bind] = mnt
462 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
463 if mnt.Path != "" && mnt.Path != "." {
464 if strings.HasPrefix(mnt.Path, "./") {
465 mnt.Path = mnt.Path[2:]
466 } else if strings.HasPrefix(mnt.Path, "/") {
467 mnt.Path = mnt.Path[1:]
469 src += "/" + mnt.Path
472 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
473 arvMountCmd = append(arvMountCmd, "--mount-tmp")
474 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
478 if bind == runner.Container.OutputPath {
479 runner.HostOutputDir = src
480 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
481 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
482 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
484 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
487 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
489 collectionPaths = append(collectionPaths, src)
491 case mnt.Kind == "tmp":
493 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
495 return fmt.Errorf("While creating mount temp dir: %v", err)
497 st, staterr := os.Stat(tmpdir)
499 return fmt.Errorf("While Stat on temp dir: %v", staterr)
501 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
503 return fmt.Errorf("While Chmod temp dir: %v", err)
505 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
506 if bind == runner.Container.OutputPath {
507 runner.HostOutputDir = tmpdir
510 case mnt.Kind == "json":
511 jsondata, err := json.Marshal(mnt.Content)
513 return fmt.Errorf("encoding json data: %v", err)
515 // Create a tempdir with a single file
516 // (instead of just a tempfile): this way we
517 // can ensure the file is world-readable
518 // inside the container, without having to
519 // make it world-readable on the docker host.
520 tmpdir, err := runner.MkTempDir(runner.parentTemp, "json")
522 return fmt.Errorf("creating temp dir: %v", err)
524 tmpfn := filepath.Join(tmpdir, "mountdata.json")
525 err = ioutil.WriteFile(tmpfn, jsondata, 0644)
527 return fmt.Errorf("writing temp file: %v", err)
529 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
531 case mnt.Kind == "git_tree":
532 tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
534 return fmt.Errorf("creating temp dir: %v", err)
536 err = gitMount(mnt).extractTree(runner.ArvClient, tmpdir, token)
540 runner.Binds = append(runner.Binds, tmpdir+":"+bind+":ro")
544 if runner.HostOutputDir == "" {
545 return fmt.Errorf("Output path does not correspond to a writable mount point")
548 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
549 for _, certfile := range arvadosclient.CertFiles {
550 _, err := os.Stat(certfile)
552 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
559 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
561 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
563 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
565 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
567 return fmt.Errorf("While trying to start arv-mount: %v", err)
570 for _, p := range collectionPaths {
573 return fmt.Errorf("While checking that input files exist: %v", err)
577 for _, cp := range copyFiles {
578 st, err := os.Stat(cp.src)
580 return fmt.Errorf("While staging writable file from %q to %q: %v", cp.src, cp.bind, err)
583 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
587 target := path.Join(cp.bind, walkpath[len(cp.src):])
588 if walkinfo.Mode().IsRegular() {
589 copyerr := copyfile(walkpath, target)
593 return os.Chmod(target, walkinfo.Mode()|0777)
594 } else if walkinfo.Mode().IsDir() {
595 mkerr := os.MkdirAll(target, 0777)
599 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
601 return fmt.Errorf("Source %q is not a regular file or directory", cp.src)
604 } else if st.Mode().IsRegular() {
605 err = copyfile(cp.src, cp.bind)
607 err = os.Chmod(cp.bind, st.Mode()|0777)
611 return fmt.Errorf("While staging writable file from %q to %q: %v", cp.src, cp.bind, err)
618 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
619 // Handle docker log protocol
620 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
621 defer close(runner.loggingDone)
623 header := make([]byte, 8)
626 _, err = io.ReadAtLeast(containerReader, header, 8)
633 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
636 _, err = io.CopyN(runner.Stdout, containerReader, readsize)
639 _, err = io.CopyN(runner.Stderr, containerReader, readsize)
644 runner.CrunchLog.Printf("error reading docker logs: %v", err)
647 err = runner.Stdout.Close()
649 runner.CrunchLog.Printf("error closing stdout logs: %v", err)
652 err = runner.Stderr.Close()
654 runner.CrunchLog.Printf("error closing stderr logs: %v", err)
657 if runner.statReporter != nil {
658 runner.statReporter.Stop()
659 err = runner.statLogger.Close()
661 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
666 func (runner *ContainerRunner) stopHoststat() error {
667 if runner.hoststatReporter == nil {
670 runner.hoststatReporter.Stop()
671 err := runner.hoststatLogger.Close()
673 return fmt.Errorf("error closing hoststat logs: %v", err)
678 func (runner *ContainerRunner) startHoststat() {
679 runner.hoststatLogger = NewThrottledLogger(runner.NewLogWriter("hoststat"))
680 runner.hoststatReporter = &crunchstat.Reporter{
681 Logger: log.New(runner.hoststatLogger, "", 0),
682 CgroupRoot: runner.cgroupRoot,
683 PollPeriod: runner.statInterval,
685 runner.hoststatReporter.Start()
688 func (runner *ContainerRunner) startCrunchstat() {
689 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
690 runner.statReporter = &crunchstat.Reporter{
691 CID: runner.ContainerID,
692 Logger: log.New(runner.statLogger, "", 0),
693 CgroupParent: runner.expectCgroupParent,
694 CgroupRoot: runner.cgroupRoot,
695 PollPeriod: runner.statInterval,
697 runner.statReporter.Start()
700 type infoCommand struct {
705 // LogHostInfo logs info about the current host, for debugging and
706 // accounting purposes. Although it's logged as "node-info", this is
707 // about the environment where crunch-run is actually running, which
708 // might differ from what's described in the node record (see
710 func (runner *ContainerRunner) LogHostInfo() (err error) {
711 w := runner.NewLogWriter("node-info")
713 commands := []infoCommand{
715 label: "Host Information",
716 cmd: []string{"uname", "-a"},
719 label: "CPU Information",
720 cmd: []string{"cat", "/proc/cpuinfo"},
723 label: "Memory Information",
724 cmd: []string{"cat", "/proc/meminfo"},
728 cmd: []string{"df", "-m", "/", os.TempDir()},
731 label: "Disk INodes",
732 cmd: []string{"df", "-i", "/", os.TempDir()},
736 // Run commands with informational output to be logged.
737 for _, command := range commands {
738 fmt.Fprintln(w, command.label)
739 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
742 if err := cmd.Run(); err != nil {
743 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
752 return fmt.Errorf("While closing node-info logs: %v", err)
757 // LogContainerRecord gets and saves the raw JSON container record from the API server
758 func (runner *ContainerRunner) LogContainerRecord() error {
759 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
760 if !logged && err == nil {
761 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
766 // LogNodeRecord logs arvados#node record corresponding to the current host.
767 func (runner *ContainerRunner) LogNodeRecord() error {
768 hostname := os.Getenv("SLURMD_NODENAME")
770 hostname, _ = os.Hostname()
772 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
773 // The "info" field has admin-only info when obtained
774 // with a privileged token, and should not be logged.
775 node, ok := resp.(map[string]interface{})
783 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
785 ArvClient: runner.ArvClient,
786 UUID: runner.Container.UUID,
787 loggingStream: label,
788 writeCloser: runner.LogCollection.Open(label + ".json"),
791 reader, err := runner.ArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
793 return false, fmt.Errorf("error getting %s record: %v", label, err)
797 dec := json.NewDecoder(reader)
799 var resp map[string]interface{}
800 if err = dec.Decode(&resp); err != nil {
801 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
803 items, ok := resp["items"].([]interface{})
805 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
806 } else if len(items) < 1 {
812 // Re-encode it using indentation to improve readability
813 enc := json.NewEncoder(w)
814 enc.SetIndent("", " ")
815 if err = enc.Encode(items[0]); err != nil {
816 return false, fmt.Errorf("error logging %s record: %v", label, err)
820 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
825 // AttachStreams connects the docker container stdin, stdout and stderr logs
826 // to the Arvados logger which logs to Keep and the API server logs table.
827 func (runner *ContainerRunner) AttachStreams() (err error) {
829 runner.CrunchLog.Print("Attaching container streams")
831 // If stdin mount is provided, attach it to the docker container
832 var stdinRdr arvados.File
834 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
835 if stdinMnt.Kind == "collection" {
836 var stdinColl arvados.Collection
837 collId := stdinMnt.UUID
839 collId = stdinMnt.PortableDataHash
841 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
843 return fmt.Errorf("While getting stding collection: %v", err)
846 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
847 if os.IsNotExist(err) {
848 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
849 } else if err != nil {
850 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
852 } else if stdinMnt.Kind == "json" {
853 stdinJson, err = json.Marshal(stdinMnt.Content)
855 return fmt.Errorf("While encoding stdin json data: %v", err)
860 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
861 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
862 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
864 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
867 runner.loggingDone = make(chan bool)
869 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
870 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
874 runner.Stdout = stdoutFile
876 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
879 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
880 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
884 runner.Stderr = stderrFile
886 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
891 _, err := io.Copy(response.Conn, stdinRdr)
893 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
897 response.CloseWrite()
899 } else if len(stdinJson) != 0 {
901 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
903 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
906 response.CloseWrite()
910 go runner.ProcessDockerAttach(response.Reader)
915 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
916 stdoutPath := mntPath[len(runner.Container.OutputPath):]
917 index := strings.LastIndex(stdoutPath, "/")
919 subdirs := stdoutPath[:index]
921 st, err := os.Stat(runner.HostOutputDir)
923 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
925 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
926 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
928 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
932 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
934 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
937 return stdoutFile, nil
940 // CreateContainer creates the docker container.
941 func (runner *ContainerRunner) CreateContainer() error {
942 runner.CrunchLog.Print("Creating Docker container")
944 runner.ContainerConfig.Cmd = runner.Container.Command
945 if runner.Container.Cwd != "." {
946 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
949 for k, v := range runner.Container.Environment {
950 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
953 runner.ContainerConfig.Volumes = runner.Volumes
955 runner.HostConfig = dockercontainer.HostConfig{
957 LogConfig: dockercontainer.LogConfig{
960 Resources: dockercontainer.Resources{
961 CgroupParent: runner.setCgroupParent,
965 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
966 tok, err := runner.ContainerToken()
970 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
971 "ARVADOS_API_TOKEN="+tok,
972 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
973 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
975 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
977 if runner.enableNetwork == "always" {
978 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
980 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
984 _, stdinUsed := runner.Container.Mounts["stdin"]
985 runner.ContainerConfig.OpenStdin = stdinUsed
986 runner.ContainerConfig.StdinOnce = stdinUsed
987 runner.ContainerConfig.AttachStdin = stdinUsed
988 runner.ContainerConfig.AttachStdout = true
989 runner.ContainerConfig.AttachStderr = true
991 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
993 return fmt.Errorf("While creating container: %v", err)
996 runner.ContainerID = createdBody.ID
998 return runner.AttachStreams()
1001 // StartContainer starts the docker container created by CreateContainer.
1002 func (runner *ContainerRunner) StartContainer() error {
1003 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
1004 runner.cStateLock.Lock()
1005 defer runner.cStateLock.Unlock()
1006 if runner.cCancelled {
1009 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
1010 dockertypes.ContainerStartOptions{})
1013 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1014 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])
1016 return fmt.Errorf("could not start container: %v%s", err, advice)
1021 // WaitFinish waits for the container to terminate, capture the exit code, and
1022 // close the stdout/stderr logging.
1023 func (runner *ContainerRunner) WaitFinish() error {
1024 runner.CrunchLog.Print("Waiting for container to finish")
1026 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, dockercontainer.WaitConditionNotRunning)
1027 arvMountExit := runner.ArvMountExit
1030 case waitBody := <-waitOk:
1031 runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
1032 code := int(waitBody.StatusCode)
1033 runner.ExitCode = &code
1035 // wait for stdout/stderr to complete
1036 <-runner.loggingDone
1039 case err := <-waitErr:
1040 return fmt.Errorf("container wait: %v", err)
1042 case <-arvMountExit:
1043 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1045 // arvMountExit will always be ready now that
1046 // it's closed, but that doesn't interest us.
1052 var ErrNotInOutputDir = fmt.Errorf("Must point to path within the output directory")
1054 func (runner *ContainerRunner) derefOutputSymlink(path string, startinfo os.FileInfo) (tgt string, readlinktgt string, info os.FileInfo, err error) {
1055 // Follow symlinks if necessary
1060 for followed := 0; info.Mode()&os.ModeSymlink != 0; followed++ {
1061 if followed >= limitFollowSymlinks {
1062 // Got stuck in a loop or just a pathological number of links, give up.
1063 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1067 readlinktgt, err = os.Readlink(nextlink)
1073 if !strings.HasPrefix(tgt, "/") {
1074 // Relative symlink, resolve it to host path
1075 tgt = filepath.Join(filepath.Dir(path), tgt)
1077 if strings.HasPrefix(tgt, runner.Container.OutputPath+"/") && !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1078 // Absolute symlink to container output path, adjust it to host output path.
1079 tgt = filepath.Join(runner.HostOutputDir, tgt[len(runner.Container.OutputPath):])
1081 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1082 // After dereferencing, symlink target must either be
1083 // within output directory, or must point to a
1084 // collection mount.
1085 err = ErrNotInOutputDir
1089 info, err = os.Lstat(tgt)
1092 err = fmt.Errorf("Symlink in output %q points to invalid location %q: %v",
1093 path[len(runner.HostOutputDir):], readlinktgt, err)
1103 var limitFollowSymlinks = 10
1105 // UploadFile uploads files within the output directory, with special handling
1106 // for symlinks. If the symlink leads to a keep mount, copy the manifest text
1107 // from the keep mount into the output manifestText. Ensure that whether
1108 // symlinks are relative or absolute, every symlink target (even targets that
1109 // are symlinks themselves) must point to a path in either the output directory
1110 // or a collection mount.
1112 // Assumes initial value of "path" is absolute, and located within runner.HostOutputDir.
1113 func (runner *ContainerRunner) UploadOutputFile(
1118 walkUpload *WalkUpload,
1119 relocateFrom string,
1121 followed int) (manifestText string, err error) {
1127 if info.Mode().IsDir() {
1128 // if empty, need to create a .keep file
1129 dir, direrr := os.Open(path)
1134 names, eof := dir.Readdirnames(1)
1135 if len(names) == 0 && eof == io.EOF && path != runner.HostOutputDir {
1136 containerPath := runner.OutputPath + path[len(runner.HostOutputDir):]
1137 for _, bind := range binds {
1138 mnt := runner.Container.Mounts[bind]
1139 // Check if there is a bind for this
1140 // directory, in which case assume we don't need .keep
1141 if (containerPath == bind || strings.HasPrefix(containerPath, bind+"/")) && mnt.PortableDataHash != "d41d8cd98f00b204e9800998ecf8427e+0" {
1145 outputSuffix := path[len(runner.HostOutputDir)+1:]
1146 return fmt.Sprintf("./%v d41d8cd98f00b204e9800998ecf8427e+0 0:0:.keep\n", outputSuffix), nil
1151 if followed >= limitFollowSymlinks {
1152 // Got stuck in a loop or just a pathological number of
1153 // directory links, give up.
1154 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1158 // "path" is the actual path we are visiting
1159 // "tgt" is the target of "path" (a non-symlink) after following symlinks
1160 // "relocated" is the path in the output manifest where the file should be placed,
1161 // but has HostOutputDir as a prefix.
1163 // The destination path in the output manifest may need to be
1164 // logically relocated to some other path in order to appear
1165 // in the correct location as a result of following a symlink.
1166 // Remove the relocateFrom prefix and replace it with
1168 relocated := relocateTo + path[len(relocateFrom):]
1170 tgt, readlinktgt, info, derefErr := runner.derefOutputSymlink(path, info)
1171 if derefErr != nil && derefErr != ErrNotInOutputDir {
1175 // go through mounts and try reverse map to collection reference
1176 for _, bind := range binds {
1177 mnt := runner.Container.Mounts[bind]
1178 if (tgt == bind || strings.HasPrefix(tgt, bind+"/")) && !mnt.Writable {
1179 // get path relative to bind
1180 targetSuffix := tgt[len(bind):]
1182 // Copy mount and adjust the path to add path relative to the bind
1183 adjustedMount := mnt
1184 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
1186 // Terminates in this keep mount, so add the
1187 // manifest text at appropriate location.
1188 outputSuffix := relocated[len(runner.HostOutputDir):]
1189 manifestText, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
1194 // If target is not a collection mount, it must be located within the
1195 // output directory, otherwise it is an error.
1196 if derefErr == ErrNotInOutputDir {
1197 err = fmt.Errorf("Symlink in output %q points to invalid location %q, must point to path within the output directory.",
1198 path[len(runner.HostOutputDir):], readlinktgt)
1202 if info.Mode().IsRegular() {
1203 return "", walkUpload.UploadFile(relocated, tgt)
1206 if info.Mode().IsDir() {
1207 // Symlink leads to directory. Walk() doesn't follow
1208 // directory symlinks, so we walk the target directory
1209 // instead. Within the walk, file paths are relocated
1210 // so they appear under the original symlink path.
1211 err = filepath.Walk(tgt, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
1213 m, walkerr = runner.UploadOutputFile(walkpath, walkinfo, walkerr,
1214 binds, walkUpload, tgt, relocated, followed+1)
1216 manifestText = manifestText + m
1226 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
1227 func (runner *ContainerRunner) CaptureOutput() error {
1228 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1229 // Output may have been set directly by the container, so
1230 // refresh the container record to check.
1231 err := runner.ArvClient.Get("containers", runner.Container.UUID,
1232 nil, &runner.Container)
1236 if runner.Container.Output != "" {
1237 // Container output is already set.
1238 runner.OutputPDH = &runner.Container.Output
1243 if runner.HostOutputDir == "" {
1247 _, err := os.Stat(runner.HostOutputDir)
1249 return fmt.Errorf("While checking host output path: %v", err)
1252 // Pre-populate output from the configured mount points
1254 for bind, mnt := range runner.Container.Mounts {
1255 if mnt.Kind == "collection" {
1256 binds = append(binds, bind)
1261 var manifestText string
1263 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
1264 _, err = os.Stat(collectionMetafile)
1266 // Regular directory
1268 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1269 walkUpload := cw.BeginUpload(runner.HostOutputDir, runner.CrunchLog.Logger)
1272 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
1273 m, err = runner.UploadOutputFile(path, info, err, binds, walkUpload, "", "", 0)
1275 manifestText = manifestText + m
1280 cw.EndUpload(walkUpload)
1283 return fmt.Errorf("While uploading output files: %v", err)
1286 m, err = cw.ManifestText()
1287 manifestText = manifestText + m
1289 return fmt.Errorf("While uploading output files: %v", err)
1292 // FUSE mount directory
1293 file, openerr := os.Open(collectionMetafile)
1295 return fmt.Errorf("While opening FUSE metafile: %v", err)
1299 var rec arvados.Collection
1300 err = json.NewDecoder(file).Decode(&rec)
1302 return fmt.Errorf("While reading FUSE metafile: %v", err)
1304 manifestText = rec.ManifestText
1307 for _, bind := range binds {
1308 mnt := runner.Container.Mounts[bind]
1310 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1312 if bindSuffix == bind || len(bindSuffix) <= 0 {
1313 // either does not start with OutputPath or is OutputPath itself
1317 if mnt.ExcludeFromOutput == true || mnt.Writable {
1321 // append to manifest_text
1322 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1327 manifestText = manifestText + m
1331 var response arvados.Collection
1332 manifest := manifest.Manifest{Text: manifestText}
1333 manifestText = manifest.Extract(".", ".").Text
1334 err = runner.ArvClient.Create("collections",
1336 "ensure_unique_name": true,
1337 "collection": arvadosclient.Dict{
1339 "name": "output for " + runner.Container.UUID,
1340 "manifest_text": manifestText}},
1343 return fmt.Errorf("While creating output collection: %v", err)
1345 runner.OutputPDH = &response.PortableDataHash
1349 var outputCollections = make(map[string]arvados.Collection)
1351 // Fetch the collection for the mnt.PortableDataHash
1352 // Return the manifest_text fragment corresponding to the specified mnt.Path
1353 // after making any required updates.
1355 // If mnt.Path is not specified,
1356 // return the entire manifest_text after replacing any "." with bindSuffix
1357 // If mnt.Path corresponds to one stream,
1358 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1359 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1360 // for that stream after replacing stream name with bindSuffix minus the last word
1361 // and the file name with last word of the bindSuffix
1362 // Allowed path examples:
1364 // "path":"/subdir1"
1365 // "path":"/subdir1/subdir2"
1366 // "path":"/subdir/filename" etc
1367 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1368 collection := outputCollections[mnt.PortableDataHash]
1369 if collection.PortableDataHash == "" {
1370 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1372 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1374 outputCollections[mnt.PortableDataHash] = collection
1377 if collection.ManifestText == "" {
1378 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1382 mft := manifest.Manifest{Text: collection.ManifestText}
1383 extracted := mft.Extract(mnt.Path, bindSuffix)
1384 if extracted.Err != nil {
1385 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1387 return extracted.Text, nil
1390 func (runner *ContainerRunner) CleanupDirs() {
1391 if runner.ArvMount != nil {
1393 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1394 umount.Stdout = runner.CrunchLog
1395 umount.Stderr = runner.CrunchLog
1396 runner.CrunchLog.Printf("Running %v", umount.Args)
1397 umnterr := umount.Start()
1400 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1402 // If arv-mount --unmount gets stuck for any reason, we
1403 // don't want to wait for it forever. Do Wait() in a goroutine
1404 // so it doesn't block crunch-run.
1405 umountExit := make(chan error)
1407 mnterr := umount.Wait()
1409 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1411 umountExit <- mnterr
1414 for again := true; again; {
1420 case <-runner.ArvMountExit:
1422 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1423 runner.CrunchLog.Printf("Timed out waiting for unmount")
1425 umount.Process.Kill()
1427 runner.ArvMount.Process.Kill()
1433 if runner.ArvMountPoint != "" {
1434 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1435 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1439 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1440 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1444 // CommitLogs posts the collection containing the final container logs.
1445 func (runner *ContainerRunner) CommitLogs() error {
1446 runner.CrunchLog.Print(runner.finalState)
1448 if runner.arvMountLog != nil {
1449 runner.arvMountLog.Close()
1451 runner.CrunchLog.Close()
1453 // Closing CrunchLog above allows them to be committed to Keep at this
1454 // point, but re-open crunch log with ArvClient in case there are any
1455 // other further errors (such as failing to write the log to Keep!)
1456 // while shutting down
1457 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1458 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1459 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1461 if runner.LogsPDH != nil {
1462 // If we have already assigned something to LogsPDH,
1463 // we must be closing the re-opened log, which won't
1464 // end up getting attached to the container record and
1465 // therefore doesn't need to be saved as a collection
1466 // -- it exists only to send logs to other channels.
1470 mt, err := runner.LogCollection.ManifestText()
1472 return fmt.Errorf("While creating log manifest: %v", err)
1475 var response arvados.Collection
1476 err = runner.ArvClient.Create("collections",
1478 "ensure_unique_name": true,
1479 "collection": arvadosclient.Dict{
1481 "name": "logs for " + runner.Container.UUID,
1482 "manifest_text": mt}},
1485 return fmt.Errorf("While creating log collection: %v", err)
1487 runner.LogsPDH = &response.PortableDataHash
1491 // UpdateContainerRunning updates the container state to "Running"
1492 func (runner *ContainerRunner) UpdateContainerRunning() error {
1493 runner.cStateLock.Lock()
1494 defer runner.cStateLock.Unlock()
1495 if runner.cCancelled {
1498 return runner.ArvClient.Update("containers", runner.Container.UUID,
1499 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1502 // ContainerToken returns the api_token the container (and any
1503 // arv-mount processes) are allowed to use.
1504 func (runner *ContainerRunner) ContainerToken() (string, error) {
1505 if runner.token != "" {
1506 return runner.token, nil
1509 var auth arvados.APIClientAuthorization
1510 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1514 runner.token = auth.APIToken
1515 return runner.token, nil
1518 // UpdateContainerComplete updates the container record state on API
1519 // server to "Complete" or "Cancelled"
1520 func (runner *ContainerRunner) UpdateContainerFinal() error {
1521 update := arvadosclient.Dict{}
1522 update["state"] = runner.finalState
1523 if runner.LogsPDH != nil {
1524 update["log"] = *runner.LogsPDH
1526 if runner.finalState == "Complete" {
1527 if runner.ExitCode != nil {
1528 update["exit_code"] = *runner.ExitCode
1530 if runner.OutputPDH != nil {
1531 update["output"] = *runner.OutputPDH
1534 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1537 // IsCancelled returns the value of Cancelled, with goroutine safety.
1538 func (runner *ContainerRunner) IsCancelled() bool {
1539 runner.cStateLock.Lock()
1540 defer runner.cStateLock.Unlock()
1541 return runner.cCancelled
1544 // NewArvLogWriter creates an ArvLogWriter
1545 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1546 return &ArvLogWriter{
1547 ArvClient: runner.ArvClient,
1548 UUID: runner.Container.UUID,
1549 loggingStream: name,
1550 writeCloser: runner.LogCollection.Open(name + ".txt")}
1553 // Run the full container lifecycle.
1554 func (runner *ContainerRunner) Run() (err error) {
1555 runner.CrunchLog.Printf("crunch-run %s started", version)
1556 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1558 hostname, hosterr := os.Hostname()
1560 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1562 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1565 runner.finalState = "Queued"
1568 runner.stopSignals()
1569 runner.CleanupDirs()
1571 runner.CrunchLog.Printf("crunch-run finished")
1572 runner.CrunchLog.Close()
1576 // checkErr prints e (unless it's nil) and sets err to
1577 // e (unless err is already non-nil). Thus, if err
1578 // hasn't already been assigned when Run() returns,
1579 // this cleanup func will cause Run() to return the
1580 // first non-nil error that is passed to checkErr().
1581 checkErr := func(e error) {
1585 runner.CrunchLog.Print(e)
1589 if runner.finalState == "Complete" {
1590 // There was an error in the finalization.
1591 runner.finalState = "Cancelled"
1595 // Log the error encountered in Run(), if any
1598 if runner.finalState == "Queued" {
1599 runner.UpdateContainerFinal()
1603 if runner.IsCancelled() {
1604 runner.finalState = "Cancelled"
1605 // but don't return yet -- we still want to
1606 // capture partial output and write logs
1609 checkErr(runner.CaptureOutput())
1610 checkErr(runner.stopHoststat())
1611 checkErr(runner.CommitLogs())
1612 checkErr(runner.UpdateContainerFinal())
1615 err = runner.fetchContainerRecord()
1619 runner.setupSignals()
1620 runner.startHoststat()
1622 // check for and/or load image
1623 err = runner.LoadImage()
1625 if !runner.checkBrokenNode(err) {
1626 // Failed to load image but not due to a "broken node"
1627 // condition, probably user error.
1628 runner.finalState = "Cancelled"
1630 err = fmt.Errorf("While loading container image: %v", err)
1634 // set up FUSE mount and binds
1635 err = runner.SetupMounts()
1637 runner.finalState = "Cancelled"
1638 err = fmt.Errorf("While setting up mounts: %v", err)
1642 err = runner.CreateContainer()
1646 err = runner.LogHostInfo()
1650 err = runner.LogNodeRecord()
1654 err = runner.LogContainerRecord()
1659 if runner.IsCancelled() {
1663 err = runner.UpdateContainerRunning()
1667 runner.finalState = "Cancelled"
1669 runner.startCrunchstat()
1671 err = runner.StartContainer()
1673 runner.checkBrokenNode(err)
1677 err = runner.WaitFinish()
1678 if err == nil && !runner.IsCancelled() {
1679 runner.finalState = "Complete"
1684 // Fetch the current container record (uuid = runner.Container.UUID)
1685 // into runner.Container.
1686 func (runner *ContainerRunner) fetchContainerRecord() error {
1687 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1689 return fmt.Errorf("error fetching container record: %v", err)
1691 defer reader.Close()
1693 dec := json.NewDecoder(reader)
1695 err = dec.Decode(&runner.Container)
1697 return fmt.Errorf("error decoding container record: %v", err)
1702 // NewContainerRunner creates a new container runner.
1703 func NewContainerRunner(api IArvadosClient,
1705 docker ThinDockerClient,
1706 containerUUID string) *ContainerRunner {
1708 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1709 cr.NewLogWriter = cr.NewArvLogWriter
1710 cr.RunArvMount = cr.ArvMountCmd
1711 cr.MkTempDir = ioutil.TempDir
1712 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1713 cr.Container.UUID = containerUUID
1714 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1715 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1717 loadLogThrottleParams(api)
1723 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1724 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1725 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1726 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1727 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1728 enableNetwork := flag.String("container-enable-networking", "default",
1729 `Specify if networking should be enabled for container. One of 'default', 'always':
1730 default: only enable networking if container requests it.
1731 always: containers always have networking enabled
1733 networkMode := flag.String("container-network-mode", "default",
1734 `Set networking mode for container. Corresponds to Docker network mode (--net).
1736 memprofile := flag.String("memprofile", "", "write memory profile to `file` after running container")
1737 getVersion := flag.Bool("version", false, "Print version information and exit.")
1740 // Print version information if requested
1742 fmt.Printf("crunch-run %s\n", version)
1746 log.Printf("crunch-run %s started", version)
1748 containerId := flag.Arg(0)
1750 if *caCertsPath != "" {
1751 arvadosclient.CertFiles = []string{*caCertsPath}
1754 api, err := arvadosclient.MakeArvadosClient()
1756 log.Fatalf("%s: %v", containerId, err)
1760 kc, kcerr := keepclient.MakeKeepClient(api)
1762 log.Fatalf("%s: %v", containerId, kcerr)
1764 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1767 // API version 1.21 corresponds to Docker 1.9, which is currently the
1768 // minimum version we want to support.
1769 docker, dockererr := dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1771 cr := NewContainerRunner(api, kc, docker, containerId)
1772 if dockererr != nil {
1773 cr.CrunchLog.Printf("%s: %v", containerId, dockererr)
1774 cr.checkBrokenNode(dockererr)
1775 cr.CrunchLog.Close()
1779 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerId+".")
1781 log.Fatalf("%s: %v", containerId, tmperr)
1784 cr.parentTemp = parentTemp
1785 cr.statInterval = *statInterval
1786 cr.cgroupRoot = *cgroupRoot
1787 cr.expectCgroupParent = *cgroupParent
1788 cr.enableNetwork = *enableNetwork
1789 cr.networkMode = *networkMode
1790 if *cgroupParentSubsystem != "" {
1791 p := findCgroup(*cgroupParentSubsystem)
1792 cr.setCgroupParent = p
1793 cr.expectCgroupParent = p
1798 if *memprofile != "" {
1799 f, err := os.Create(*memprofile)
1801 log.Printf("could not create memory profile: ", err)
1803 runtime.GC() // get up-to-date statistics
1804 if err := pprof.WriteHeapProfile(f); err != nil {
1805 log.Printf("could not write memory profile: ", err)
1807 closeerr := f.Close()
1808 if closeerr != nil {
1809 log.Printf("closing memprofile file: ", err)
1814 log.Fatalf("%s: %v", containerId, runerr)