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
109 CleanupTempDir []string
111 Volumes map[string]struct{}
113 SigChan chan os.Signal
114 ArvMountExit chan error
117 statLogger io.WriteCloser
118 statReporter *crunchstat.Reporter
119 statInterval time.Duration
121 // What we expect the container's cgroup parent to be.
122 expectCgroupParent string
123 // What we tell docker to use as the container's cgroup
124 // parent. Note: Ideally we would use the same field for both
125 // expectCgroupParent and setCgroupParent, and just make it
126 // default to "docker". However, when using docker < 1.10 with
127 // systemd, specifying a non-empty cgroup parent (even the
128 // default value "docker") hits a docker bug
129 // (https://github.com/docker/docker/issues/17126). Using two
130 // separate fields makes it possible to use the "expect cgroup
131 // parent to be X" feature even on sites where the "specify
132 // cgroup parent" feature breaks.
133 setCgroupParent string
135 cStateLock sync.Mutex
136 cCancelled bool // StopContainer() invoked
138 enableNetwork string // one of "default" or "always"
139 networkMode string // passed through to HostConfig.NetworkMode
140 arvMountLog *ThrottledLogger
143 // setupSignals sets up signal handling to gracefully terminate the underlying
144 // Docker container and update state when receiving a TERM, INT or QUIT signal.
145 func (runner *ContainerRunner) setupSignals() {
146 runner.SigChan = make(chan os.Signal, 1)
147 signal.Notify(runner.SigChan, syscall.SIGTERM)
148 signal.Notify(runner.SigChan, syscall.SIGINT)
149 signal.Notify(runner.SigChan, syscall.SIGQUIT)
151 go func(sig chan os.Signal) {
153 runner.CrunchLog.Printf("caught signal: %v", s)
159 // stop the underlying Docker container.
160 func (runner *ContainerRunner) stop() {
161 runner.cStateLock.Lock()
162 defer runner.cStateLock.Unlock()
163 if runner.ContainerID == "" {
166 runner.cCancelled = true
167 runner.CrunchLog.Printf("removing container")
168 err := runner.Docker.ContainerRemove(context.TODO(), runner.ContainerID, dockertypes.ContainerRemoveOptions{Force: true})
170 runner.CrunchLog.Printf("error removing container: %s", err)
174 func (runner *ContainerRunner) stopSignals() {
175 if runner.SigChan != nil {
176 signal.Stop(runner.SigChan)
180 var errorBlacklist = []string{
181 "(?ms).*[Cc]annot connect to the Docker daemon.*",
182 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
184 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)")
186 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
187 for _, d := range errorBlacklist {
188 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
189 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
190 if *brokenNodeHook == "" {
191 runner.CrunchLog.Printf("No broken node hook provided, cannot mark node as broken.")
193 runner.CrunchLog.Printf("Running broken node hook %q", *brokenNodeHook)
195 c := exec.Command(*brokenNodeHook)
196 c.Stdout = runner.CrunchLog
197 c.Stderr = runner.CrunchLog
200 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
209 // LoadImage determines the docker image id from the container record and
210 // checks if it is available in the local Docker image store. If not, it loads
211 // the image from Keep.
212 func (runner *ContainerRunner) LoadImage() (err error) {
214 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
216 var collection arvados.Collection
217 err = runner.ArvClient.Get("collections", runner.Container.ContainerImage, nil, &collection)
219 return fmt.Errorf("While getting container image collection: %v", err)
221 manifest := manifest.Manifest{Text: collection.ManifestText}
222 var img, imageID string
223 for ms := range manifest.StreamIter() {
224 img = ms.FileStreamSegments[0].Name
225 if !strings.HasSuffix(img, ".tar") {
226 return fmt.Errorf("First file in the container image collection does not end in .tar")
228 imageID = img[:len(img)-4]
231 runner.CrunchLog.Printf("Using Docker image id '%s'", imageID)
233 _, _, err = runner.Docker.ImageInspectWithRaw(context.TODO(), imageID)
235 runner.CrunchLog.Print("Loading Docker image from keep")
237 var readCloser io.ReadCloser
238 readCloser, err = runner.Kc.ManifestFileReader(manifest, img)
240 return fmt.Errorf("While creating ManifestFileReader for container image: %v", err)
243 response, err := runner.Docker.ImageLoad(context.TODO(), readCloser, true)
245 return fmt.Errorf("While loading container image into Docker: %v", err)
248 defer response.Body.Close()
249 rbody, err := ioutil.ReadAll(response.Body)
251 return fmt.Errorf("Reading response to image load: %v", err)
253 runner.CrunchLog.Printf("Docker response: %s", rbody)
255 runner.CrunchLog.Print("Docker image is available")
258 runner.ContainerConfig.Image = imageID
260 runner.Kc.ClearBlockCache()
265 func (runner *ContainerRunner) ArvMountCmd(arvMountCmd []string, token string) (c *exec.Cmd, err error) {
266 c = exec.Command("arv-mount", arvMountCmd...)
268 // Copy our environment, but override ARVADOS_API_TOKEN with
269 // the container auth token.
271 for _, s := range os.Environ() {
272 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
273 c.Env = append(c.Env, s)
276 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
278 runner.arvMountLog = NewThrottledLogger(runner.NewLogWriter("arv-mount"))
279 c.Stdout = runner.arvMountLog
280 c.Stderr = runner.arvMountLog
282 runner.CrunchLog.Printf("Running %v", c.Args)
289 statReadme := make(chan bool)
290 runner.ArvMountExit = make(chan error)
295 time.Sleep(100 * time.Millisecond)
296 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
308 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
310 runner.ArvMountExit <- mnterr
311 close(runner.ArvMountExit)
317 case err := <-runner.ArvMountExit:
318 runner.ArvMount = nil
326 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
327 if runner.ArvMountPoint == "" {
328 runner.ArvMountPoint, err = runner.MkTempDir("", prefix)
333 func copyfile(src string, dst string) (err error) {
334 srcfile, err := os.Open(src)
339 os.MkdirAll(path.Dir(dst), 0770)
341 dstfile, err := os.Create(dst)
345 _, err = io.Copy(srcfile, dstfile)
350 err = srcfile.Close()
351 err2 := dstfile.Close()
364 func (runner *ContainerRunner) SetupMounts() (err error) {
365 err = runner.SetupArvMountPoint("keep")
367 return fmt.Errorf("While creating keep mount temp dir: %v", err)
370 token, err := runner.ContainerToken()
372 return fmt.Errorf("could not get container token: %s", err)
377 arvMountCmd := []string{
381 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
383 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
384 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
387 collectionPaths := []string{}
389 runner.Volumes = make(map[string]struct{})
390 needCertMount := true
391 type copyFile struct {
395 var copyFiles []copyFile
398 for bind := range runner.Container.Mounts {
399 binds = append(binds, bind)
403 for _, bind := range binds {
404 mnt := runner.Container.Mounts[bind]
405 if bind == "stdout" || bind == "stderr" {
406 // Is it a "file" mount kind?
407 if mnt.Kind != "file" {
408 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
411 // Does path start with OutputPath?
412 prefix := runner.Container.OutputPath
413 if !strings.HasSuffix(prefix, "/") {
416 if !strings.HasPrefix(mnt.Path, prefix) {
417 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
422 // Is it a "collection" mount kind?
423 if mnt.Kind != "collection" && mnt.Kind != "json" {
424 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
428 if bind == "/etc/arvados/ca-certificates.crt" {
429 needCertMount = false
432 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
433 if mnt.Kind != "collection" {
434 return fmt.Errorf("Only mount points of kind 'collection' are supported underneath the output_path: %v", bind)
439 case mnt.Kind == "collection" && bind != "stdin":
441 if mnt.UUID != "" && mnt.PortableDataHash != "" {
442 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
446 return fmt.Errorf("Writing to existing collections currently not permitted.")
449 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
450 } else if mnt.PortableDataHash != "" {
451 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
452 return fmt.Errorf("Can never write to a collection specified by portable data hash")
454 idx := strings.Index(mnt.PortableDataHash, "/")
456 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
457 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
458 runner.Container.Mounts[bind] = mnt
460 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
461 if mnt.Path != "" && mnt.Path != "." {
462 if strings.HasPrefix(mnt.Path, "./") {
463 mnt.Path = mnt.Path[2:]
464 } else if strings.HasPrefix(mnt.Path, "/") {
465 mnt.Path = mnt.Path[1:]
467 src += "/" + mnt.Path
470 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
471 arvMountCmd = append(arvMountCmd, "--mount-tmp")
472 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
476 if bind == runner.Container.OutputPath {
477 runner.HostOutputDir = src
478 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
479 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
480 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
482 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
485 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
487 collectionPaths = append(collectionPaths, src)
489 case mnt.Kind == "tmp":
491 tmpdir, err = runner.MkTempDir("", "")
493 return fmt.Errorf("While creating mount temp dir: %v", err)
495 st, staterr := os.Stat(tmpdir)
497 return fmt.Errorf("While Stat on temp dir: %v", staterr)
499 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
501 return fmt.Errorf("While Chmod temp dir: %v", err)
503 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
504 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
505 if bind == runner.Container.OutputPath {
506 runner.HostOutputDir = tmpdir
509 case mnt.Kind == "json":
510 jsondata, err := json.Marshal(mnt.Content)
512 return fmt.Errorf("encoding json data: %v", err)
514 // Create a tempdir with a single file
515 // (instead of just a tempfile): this way we
516 // can ensure the file is world-readable
517 // inside the container, without having to
518 // make it world-readable on the docker host.
519 tmpdir, err := runner.MkTempDir("", "")
521 return fmt.Errorf("creating temp dir: %v", err)
523 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
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("", "")
534 return fmt.Errorf("creating temp dir: %v", err)
536 runner.CleanupTempDir = append(runner.CleanupTempDir, tmpdir)
537 err = gitMount(mnt).extractTree(runner.ArvClient, tmpdir, token)
541 runner.Binds = append(runner.Binds, tmpdir+":"+bind+":ro")
545 if runner.HostOutputDir == "" {
546 return fmt.Errorf("Output path does not correspond to a writable mount point")
549 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
550 for _, certfile := range arvadosclient.CertFiles {
551 _, err := os.Stat(certfile)
553 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
560 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
562 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
564 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
566 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
568 return fmt.Errorf("While trying to start arv-mount: %v", err)
571 for _, p := range collectionPaths {
574 return fmt.Errorf("While checking that input files exist: %v", err)
578 for _, cp := range copyFiles {
579 dir, err := os.Stat(cp.src)
582 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
583 if walkinfo.Mode().IsRegular() {
584 return copyfile(walkpath, path.Join(cp.bind, walkpath[len(cp.src):]))
589 err = copyfile(cp.src, cp.bind)
593 return fmt.Errorf("While staging writable files: %v", err)
600 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
601 // Handle docker log protocol
602 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
604 header := make([]byte, 8)
606 _, readerr := io.ReadAtLeast(containerReader, header, 8)
609 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
612 _, readerr = io.CopyN(runner.Stdout, containerReader, readsize)
615 _, readerr = io.CopyN(runner.Stderr, containerReader, readsize)
620 if readerr != io.EOF {
621 runner.CrunchLog.Printf("While reading docker logs: %v", readerr)
624 closeerr := runner.Stdout.Close()
626 runner.CrunchLog.Printf("While closing stdout logs: %v", closeerr)
629 closeerr = runner.Stderr.Close()
631 runner.CrunchLog.Printf("While closing stderr logs: %v", closeerr)
634 if runner.statReporter != nil {
635 runner.statReporter.Stop()
636 closeerr = runner.statLogger.Close()
638 runner.CrunchLog.Printf("While closing crunchstat logs: %v", closeerr)
642 close(runner.loggingDone)
648 func (runner *ContainerRunner) StartCrunchstat() {
649 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
650 runner.statReporter = &crunchstat.Reporter{
651 CID: runner.ContainerID,
652 Logger: log.New(runner.statLogger, "", 0),
653 CgroupParent: runner.expectCgroupParent,
654 CgroupRoot: runner.cgroupRoot,
655 PollPeriod: runner.statInterval,
657 runner.statReporter.Start()
660 type infoCommand struct {
665 // LogHostInfo logs info about the current host, for debugging and
666 // accounting purposes. Although it's logged as "node-info", this is
667 // about the environment where crunch-run is actually running, which
668 // might differ from what's described in the node record (see
670 func (runner *ContainerRunner) LogHostInfo() (err error) {
671 w := runner.NewLogWriter("node-info")
673 commands := []infoCommand{
675 label: "Host Information",
676 cmd: []string{"uname", "-a"},
679 label: "CPU Information",
680 cmd: []string{"cat", "/proc/cpuinfo"},
683 label: "Memory Information",
684 cmd: []string{"cat", "/proc/meminfo"},
688 cmd: []string{"df", "-m", "/", os.TempDir()},
691 label: "Disk INodes",
692 cmd: []string{"df", "-i", "/", os.TempDir()},
696 // Run commands with informational output to be logged.
697 for _, command := range commands {
698 fmt.Fprintln(w, command.label)
699 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
702 if err := cmd.Run(); err != nil {
703 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
712 return fmt.Errorf("While closing node-info logs: %v", err)
717 // LogContainerRecord gets and saves the raw JSON container record from the API server
718 func (runner *ContainerRunner) LogContainerRecord() error {
719 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
720 if !logged && err == nil {
721 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
726 // LogNodeRecord logs arvados#node record corresponding to the current host.
727 func (runner *ContainerRunner) LogNodeRecord() error {
728 hostname := os.Getenv("SLURMD_NODENAME")
730 hostname, _ = os.Hostname()
732 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
733 // The "info" field has admin-only info when obtained
734 // with a privileged token, and should not be logged.
735 node, ok := resp.(map[string]interface{})
743 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
745 ArvClient: runner.ArvClient,
746 UUID: runner.Container.UUID,
747 loggingStream: label,
748 writeCloser: runner.LogCollection.Open(label + ".json"),
751 reader, err := runner.ArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
753 return false, fmt.Errorf("error getting %s record: %v", label, err)
757 dec := json.NewDecoder(reader)
759 var resp map[string]interface{}
760 if err = dec.Decode(&resp); err != nil {
761 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
763 items, ok := resp["items"].([]interface{})
765 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
766 } else if len(items) < 1 {
772 // Re-encode it using indentation to improve readability
773 enc := json.NewEncoder(w)
774 enc.SetIndent("", " ")
775 if err = enc.Encode(items[0]); err != nil {
776 return false, fmt.Errorf("error logging %s record: %v", label, err)
780 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
785 // AttachStreams connects the docker container stdin, stdout and stderr logs
786 // to the Arvados logger which logs to Keep and the API server logs table.
787 func (runner *ContainerRunner) AttachStreams() (err error) {
789 runner.CrunchLog.Print("Attaching container streams")
791 // If stdin mount is provided, attach it to the docker container
792 var stdinRdr arvados.File
794 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
795 if stdinMnt.Kind == "collection" {
796 var stdinColl arvados.Collection
797 collId := stdinMnt.UUID
799 collId = stdinMnt.PortableDataHash
801 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
803 return fmt.Errorf("While getting stding collection: %v", err)
806 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
807 if os.IsNotExist(err) {
808 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
809 } else if err != nil {
810 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
812 } else if stdinMnt.Kind == "json" {
813 stdinJson, err = json.Marshal(stdinMnt.Content)
815 return fmt.Errorf("While encoding stdin json data: %v", err)
820 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
821 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
822 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
824 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
827 runner.loggingDone = make(chan bool)
829 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
830 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
834 runner.Stdout = stdoutFile
836 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
839 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
840 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
844 runner.Stderr = stderrFile
846 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
851 _, err := io.Copy(response.Conn, stdinRdr)
853 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
857 response.CloseWrite()
859 } else if len(stdinJson) != 0 {
861 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
863 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
866 response.CloseWrite()
870 go runner.ProcessDockerAttach(response.Reader)
875 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
876 stdoutPath := mntPath[len(runner.Container.OutputPath):]
877 index := strings.LastIndex(stdoutPath, "/")
879 subdirs := stdoutPath[:index]
881 st, err := os.Stat(runner.HostOutputDir)
883 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
885 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
886 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
888 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
892 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
894 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
897 return stdoutFile, nil
900 // CreateContainer creates the docker container.
901 func (runner *ContainerRunner) CreateContainer() error {
902 runner.CrunchLog.Print("Creating Docker container")
904 runner.ContainerConfig.Cmd = runner.Container.Command
905 if runner.Container.Cwd != "." {
906 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
909 for k, v := range runner.Container.Environment {
910 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
913 runner.ContainerConfig.Volumes = runner.Volumes
915 runner.HostConfig = dockercontainer.HostConfig{
917 LogConfig: dockercontainer.LogConfig{
920 Resources: dockercontainer.Resources{
921 CgroupParent: runner.setCgroupParent,
925 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
926 tok, err := runner.ContainerToken()
930 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
931 "ARVADOS_API_TOKEN="+tok,
932 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
933 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
935 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
937 if runner.enableNetwork == "always" {
938 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
940 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
944 _, stdinUsed := runner.Container.Mounts["stdin"]
945 runner.ContainerConfig.OpenStdin = stdinUsed
946 runner.ContainerConfig.StdinOnce = stdinUsed
947 runner.ContainerConfig.AttachStdin = stdinUsed
948 runner.ContainerConfig.AttachStdout = true
949 runner.ContainerConfig.AttachStderr = true
951 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
953 return fmt.Errorf("While creating container: %v", err)
956 runner.ContainerID = createdBody.ID
958 return runner.AttachStreams()
961 // StartContainer starts the docker container created by CreateContainer.
962 func (runner *ContainerRunner) StartContainer() error {
963 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
964 runner.cStateLock.Lock()
965 defer runner.cStateLock.Unlock()
966 if runner.cCancelled {
969 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
970 dockertypes.ContainerStartOptions{})
973 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
974 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])
976 return fmt.Errorf("could not start container: %v%s", err, advice)
981 // WaitFinish waits for the container to terminate, capture the exit code, and
982 // close the stdout/stderr logging.
983 func (runner *ContainerRunner) WaitFinish() error {
984 runner.CrunchLog.Print("Waiting for container to finish")
986 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, dockercontainer.WaitConditionNotRunning)
987 arvMountExit := runner.ArvMountExit
990 case waitBody := <-waitOk:
991 runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
992 code := int(waitBody.StatusCode)
993 runner.ExitCode = &code
995 // wait for stdout/stderr to complete
999 case err := <-waitErr:
1000 return fmt.Errorf("container wait: %v", err)
1002 case <-arvMountExit:
1003 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1005 // arvMountExit will always be ready now that
1006 // it's closed, but that doesn't interest us.
1012 var ErrNotInOutputDir = fmt.Errorf("Must point to path within the output directory")
1014 func (runner *ContainerRunner) derefOutputSymlink(path string, startinfo os.FileInfo) (tgt string, readlinktgt string, info os.FileInfo, err error) {
1015 // Follow symlinks if necessary
1020 for followed := 0; info.Mode()&os.ModeSymlink != 0; followed++ {
1021 if followed >= limitFollowSymlinks {
1022 // Got stuck in a loop or just a pathological number of links, give up.
1023 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1027 readlinktgt, err = os.Readlink(nextlink)
1033 if !strings.HasPrefix(tgt, "/") {
1034 // Relative symlink, resolve it to host path
1035 tgt = filepath.Join(filepath.Dir(path), tgt)
1037 if strings.HasPrefix(tgt, runner.Container.OutputPath+"/") && !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1038 // Absolute symlink to container output path, adjust it to host output path.
1039 tgt = filepath.Join(runner.HostOutputDir, tgt[len(runner.Container.OutputPath):])
1041 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1042 // After dereferencing, symlink target must either be
1043 // within output directory, or must point to a
1044 // collection mount.
1045 err = ErrNotInOutputDir
1049 info, err = os.Lstat(tgt)
1052 err = fmt.Errorf("Symlink in output %q points to invalid location %q: %v",
1053 path[len(runner.HostOutputDir):], readlinktgt, err)
1063 var limitFollowSymlinks = 10
1065 // UploadFile uploads files within the output directory, with special handling
1066 // for symlinks. If the symlink leads to a keep mount, copy the manifest text
1067 // from the keep mount into the output manifestText. Ensure that whether
1068 // symlinks are relative or absolute, every symlink target (even targets that
1069 // are symlinks themselves) must point to a path in either the output directory
1070 // or a collection mount.
1072 // Assumes initial value of "path" is absolute, and located within runner.HostOutputDir.
1073 func (runner *ContainerRunner) UploadOutputFile(
1078 walkUpload *WalkUpload,
1079 relocateFrom string,
1081 followed int) (manifestText string, err error) {
1087 if info.Mode().IsDir() {
1088 // if empty, need to create a .keep file
1089 dir, direrr := os.Open(path)
1094 names, eof := dir.Readdirnames(1)
1095 if len(names) == 0 && eof == io.EOF && path != runner.HostOutputDir {
1096 containerPath := runner.OutputPath + path[len(runner.HostOutputDir):]
1097 for _, bind := range binds {
1098 mnt := runner.Container.Mounts[bind]
1099 // Check if there is a bind for this
1100 // directory, in which case assume we don't need .keep
1101 if (containerPath == bind || strings.HasPrefix(containerPath, bind+"/")) && mnt.PortableDataHash != "d41d8cd98f00b204e9800998ecf8427e+0" {
1105 outputSuffix := path[len(runner.HostOutputDir)+1:]
1106 return fmt.Sprintf("./%v d41d8cd98f00b204e9800998ecf8427e+0 0:0:.keep\n", outputSuffix), nil
1111 if followed >= limitFollowSymlinks {
1112 // Got stuck in a loop or just a pathological number of
1113 // directory links, give up.
1114 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1118 // "path" is the actual path we are visiting
1119 // "tgt" is the target of "path" (a non-symlink) after following symlinks
1120 // "relocated" is the path in the output manifest where the file should be placed,
1121 // but has HostOutputDir as a prefix.
1123 // The destination path in the output manifest may need to be
1124 // logically relocated to some other path in order to appear
1125 // in the correct location as a result of following a symlink.
1126 // Remove the relocateFrom prefix and replace it with
1128 relocated := relocateTo + path[len(relocateFrom):]
1130 tgt, readlinktgt, info, derefErr := runner.derefOutputSymlink(path, info)
1131 if derefErr != nil && derefErr != ErrNotInOutputDir {
1135 // go through mounts and try reverse map to collection reference
1136 for _, bind := range binds {
1137 mnt := runner.Container.Mounts[bind]
1138 if tgt == bind || strings.HasPrefix(tgt, bind+"/") {
1139 // get path relative to bind
1140 targetSuffix := tgt[len(bind):]
1142 // Copy mount and adjust the path to add path relative to the bind
1143 adjustedMount := mnt
1144 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
1146 // Terminates in this keep mount, so add the
1147 // manifest text at appropriate location.
1148 outputSuffix := relocated[len(runner.HostOutputDir):]
1149 manifestText, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
1154 // If target is not a collection mount, it must be located within the
1155 // output directory, otherwise it is an error.
1156 if derefErr == ErrNotInOutputDir {
1157 err = fmt.Errorf("Symlink in output %q points to invalid location %q, must point to path within the output directory.",
1158 path[len(runner.HostOutputDir):], readlinktgt)
1162 if info.Mode().IsRegular() {
1163 return "", walkUpload.UploadFile(relocated, tgt)
1166 if info.Mode().IsDir() {
1167 // Symlink leads to directory. Walk() doesn't follow
1168 // directory symlinks, so we walk the target directory
1169 // instead. Within the walk, file paths are relocated
1170 // so they appear under the original symlink path.
1171 err = filepath.Walk(tgt, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
1173 m, walkerr = runner.UploadOutputFile(walkpath, walkinfo, walkerr,
1174 binds, walkUpload, tgt, relocated, followed+1)
1176 manifestText = manifestText + m
1186 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
1187 func (runner *ContainerRunner) CaptureOutput() error {
1188 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1189 // Output may have been set directly by the container, so
1190 // refresh the container record to check.
1191 err := runner.ArvClient.Get("containers", runner.Container.UUID,
1192 nil, &runner.Container)
1196 if runner.Container.Output != "" {
1197 // Container output is already set.
1198 runner.OutputPDH = &runner.Container.Output
1203 if runner.HostOutputDir == "" {
1207 _, err := os.Stat(runner.HostOutputDir)
1209 return fmt.Errorf("While checking host output path: %v", err)
1212 // Pre-populate output from the configured mount points
1214 for bind, mnt := range runner.Container.Mounts {
1215 if mnt.Kind == "collection" {
1216 binds = append(binds, bind)
1221 var manifestText string
1223 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
1224 _, err = os.Stat(collectionMetafile)
1226 // Regular directory
1228 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1229 walkUpload := cw.BeginUpload(runner.HostOutputDir, runner.CrunchLog.Logger)
1232 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
1233 m, err = runner.UploadOutputFile(path, info, err, binds, walkUpload, "", "", 0)
1235 manifestText = manifestText + m
1240 cw.EndUpload(walkUpload)
1243 return fmt.Errorf("While uploading output files: %v", err)
1246 m, err = cw.ManifestText()
1247 manifestText = manifestText + m
1249 return fmt.Errorf("While uploading output files: %v", err)
1252 // FUSE mount directory
1253 file, openerr := os.Open(collectionMetafile)
1255 return fmt.Errorf("While opening FUSE metafile: %v", err)
1259 var rec arvados.Collection
1260 err = json.NewDecoder(file).Decode(&rec)
1262 return fmt.Errorf("While reading FUSE metafile: %v", err)
1264 manifestText = rec.ManifestText
1267 for _, bind := range binds {
1268 mnt := runner.Container.Mounts[bind]
1270 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1272 if bindSuffix == bind || len(bindSuffix) <= 0 {
1273 // either does not start with OutputPath or is OutputPath itself
1277 if mnt.ExcludeFromOutput == true {
1281 // append to manifest_text
1282 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1287 manifestText = manifestText + m
1291 var response arvados.Collection
1292 manifest := manifest.Manifest{Text: manifestText}
1293 manifestText = manifest.Extract(".", ".").Text
1294 err = runner.ArvClient.Create("collections",
1296 "ensure_unique_name": true,
1297 "collection": arvadosclient.Dict{
1299 "name": "output for " + runner.Container.UUID,
1300 "manifest_text": manifestText}},
1303 return fmt.Errorf("While creating output collection: %v", err)
1305 runner.OutputPDH = &response.PortableDataHash
1309 var outputCollections = make(map[string]arvados.Collection)
1311 // Fetch the collection for the mnt.PortableDataHash
1312 // Return the manifest_text fragment corresponding to the specified mnt.Path
1313 // after making any required updates.
1315 // If mnt.Path is not specified,
1316 // return the entire manifest_text after replacing any "." with bindSuffix
1317 // If mnt.Path corresponds to one stream,
1318 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1319 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1320 // for that stream after replacing stream name with bindSuffix minus the last word
1321 // and the file name with last word of the bindSuffix
1322 // Allowed path examples:
1324 // "path":"/subdir1"
1325 // "path":"/subdir1/subdir2"
1326 // "path":"/subdir/filename" etc
1327 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1328 collection := outputCollections[mnt.PortableDataHash]
1329 if collection.PortableDataHash == "" {
1330 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1332 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1334 outputCollections[mnt.PortableDataHash] = collection
1337 if collection.ManifestText == "" {
1338 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1342 mft := manifest.Manifest{Text: collection.ManifestText}
1343 extracted := mft.Extract(mnt.Path, bindSuffix)
1344 if extracted.Err != nil {
1345 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1347 return extracted.Text, nil
1350 func (runner *ContainerRunner) CleanupDirs() {
1351 if runner.ArvMount != nil {
1353 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1354 umount.Stdout = runner.CrunchLog
1355 umount.Stderr = runner.CrunchLog
1356 runner.CrunchLog.Printf("Running %v", umount.Args)
1357 umnterr := umount.Start()
1360 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1362 // If arv-mount --unmount gets stuck for any reason, we
1363 // don't want to wait for it forever. Do Wait() in a goroutine
1364 // so it doesn't block crunch-run.
1365 umountExit := make(chan error)
1367 mnterr := umount.Wait()
1369 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1371 umountExit <- mnterr
1374 for again := true; again; {
1380 case <-runner.ArvMountExit:
1382 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1383 runner.CrunchLog.Printf("Timed out waiting for unmount")
1385 umount.Process.Kill()
1387 runner.ArvMount.Process.Kill()
1393 if runner.ArvMountPoint != "" {
1394 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1395 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1399 for _, tmpdir := range runner.CleanupTempDir {
1400 if rmerr := os.RemoveAll(tmpdir); rmerr != nil {
1401 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", tmpdir, rmerr)
1406 // CommitLogs posts the collection containing the final container logs.
1407 func (runner *ContainerRunner) CommitLogs() error {
1408 runner.CrunchLog.Print(runner.finalState)
1410 if runner.arvMountLog != nil {
1411 runner.arvMountLog.Close()
1413 runner.CrunchLog.Close()
1415 // Closing CrunchLog above allows them to be committed to Keep at this
1416 // point, but re-open crunch log with ArvClient in case there are any
1417 // other further errors (such as failing to write the log to Keep!)
1418 // while shutting down
1419 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1420 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1421 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1423 if runner.LogsPDH != nil {
1424 // If we have already assigned something to LogsPDH,
1425 // we must be closing the re-opened log, which won't
1426 // end up getting attached to the container record and
1427 // therefore doesn't need to be saved as a collection
1428 // -- it exists only to send logs to other channels.
1432 mt, err := runner.LogCollection.ManifestText()
1434 return fmt.Errorf("While creating log manifest: %v", err)
1437 var response arvados.Collection
1438 err = runner.ArvClient.Create("collections",
1440 "ensure_unique_name": true,
1441 "collection": arvadosclient.Dict{
1443 "name": "logs for " + runner.Container.UUID,
1444 "manifest_text": mt}},
1447 return fmt.Errorf("While creating log collection: %v", err)
1449 runner.LogsPDH = &response.PortableDataHash
1453 // UpdateContainerRunning updates the container state to "Running"
1454 func (runner *ContainerRunner) UpdateContainerRunning() error {
1455 runner.cStateLock.Lock()
1456 defer runner.cStateLock.Unlock()
1457 if runner.cCancelled {
1460 return runner.ArvClient.Update("containers", runner.Container.UUID,
1461 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1464 // ContainerToken returns the api_token the container (and any
1465 // arv-mount processes) are allowed to use.
1466 func (runner *ContainerRunner) ContainerToken() (string, error) {
1467 if runner.token != "" {
1468 return runner.token, nil
1471 var auth arvados.APIClientAuthorization
1472 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1476 runner.token = auth.APIToken
1477 return runner.token, nil
1480 // UpdateContainerComplete updates the container record state on API
1481 // server to "Complete" or "Cancelled"
1482 func (runner *ContainerRunner) UpdateContainerFinal() error {
1483 update := arvadosclient.Dict{}
1484 update["state"] = runner.finalState
1485 if runner.LogsPDH != nil {
1486 update["log"] = *runner.LogsPDH
1488 if runner.finalState == "Complete" {
1489 if runner.ExitCode != nil {
1490 update["exit_code"] = *runner.ExitCode
1492 if runner.OutputPDH != nil {
1493 update["output"] = *runner.OutputPDH
1496 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1499 // IsCancelled returns the value of Cancelled, with goroutine safety.
1500 func (runner *ContainerRunner) IsCancelled() bool {
1501 runner.cStateLock.Lock()
1502 defer runner.cStateLock.Unlock()
1503 return runner.cCancelled
1506 // NewArvLogWriter creates an ArvLogWriter
1507 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1508 return &ArvLogWriter{
1509 ArvClient: runner.ArvClient,
1510 UUID: runner.Container.UUID,
1511 loggingStream: name,
1512 writeCloser: runner.LogCollection.Open(name + ".txt")}
1515 // Run the full container lifecycle.
1516 func (runner *ContainerRunner) Run() (err error) {
1517 runner.CrunchLog.Printf("crunch-run %s started", version)
1518 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1520 hostname, hosterr := os.Hostname()
1522 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1524 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1527 runner.finalState = "Queued"
1530 runner.stopSignals()
1531 runner.CleanupDirs()
1533 runner.CrunchLog.Printf("crunch-run finished")
1534 runner.CrunchLog.Close()
1538 // checkErr prints e (unless it's nil) and sets err to
1539 // e (unless err is already non-nil). Thus, if err
1540 // hasn't already been assigned when Run() returns,
1541 // this cleanup func will cause Run() to return the
1542 // first non-nil error that is passed to checkErr().
1543 checkErr := func(e error) {
1547 runner.CrunchLog.Print(e)
1551 if runner.finalState == "Complete" {
1552 // There was an error in the finalization.
1553 runner.finalState = "Cancelled"
1557 // Log the error encountered in Run(), if any
1560 if runner.finalState == "Queued" {
1561 runner.UpdateContainerFinal()
1565 if runner.IsCancelled() {
1566 runner.finalState = "Cancelled"
1567 // but don't return yet -- we still want to
1568 // capture partial output and write logs
1571 checkErr(runner.CaptureOutput())
1572 checkErr(runner.CommitLogs())
1573 checkErr(runner.UpdateContainerFinal())
1576 err = runner.fetchContainerRecord()
1581 // setup signal handling
1582 runner.setupSignals()
1584 // check for and/or load image
1585 err = runner.LoadImage()
1587 if !runner.checkBrokenNode(err) {
1588 // Failed to load image but not due to a "broken node"
1589 // condition, probably user error.
1590 runner.finalState = "Cancelled"
1592 err = fmt.Errorf("While loading container image: %v", err)
1596 // set up FUSE mount and binds
1597 err = runner.SetupMounts()
1599 runner.finalState = "Cancelled"
1600 err = fmt.Errorf("While setting up mounts: %v", err)
1604 err = runner.CreateContainer()
1608 err = runner.LogHostInfo()
1612 err = runner.LogNodeRecord()
1616 err = runner.LogContainerRecord()
1621 if runner.IsCancelled() {
1625 err = runner.UpdateContainerRunning()
1629 runner.finalState = "Cancelled"
1631 runner.StartCrunchstat()
1633 err = runner.StartContainer()
1635 runner.checkBrokenNode(err)
1639 err = runner.WaitFinish()
1640 if err == nil && !runner.IsCancelled() {
1641 runner.finalState = "Complete"
1646 // Fetch the current container record (uuid = runner.Container.UUID)
1647 // into runner.Container.
1648 func (runner *ContainerRunner) fetchContainerRecord() error {
1649 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1651 return fmt.Errorf("error fetching container record: %v", err)
1653 defer reader.Close()
1655 dec := json.NewDecoder(reader)
1657 err = dec.Decode(&runner.Container)
1659 return fmt.Errorf("error decoding container record: %v", err)
1664 // NewContainerRunner creates a new container runner.
1665 func NewContainerRunner(api IArvadosClient,
1667 docker ThinDockerClient,
1668 containerUUID string) *ContainerRunner {
1670 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1671 cr.NewLogWriter = cr.NewArvLogWriter
1672 cr.RunArvMount = cr.ArvMountCmd
1673 cr.MkTempDir = ioutil.TempDir
1674 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1675 cr.Container.UUID = containerUUID
1676 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1677 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1679 loadLogThrottleParams(api)
1685 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1686 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1687 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1688 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1689 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1690 enableNetwork := flag.String("container-enable-networking", "default",
1691 `Specify if networking should be enabled for container. One of 'default', 'always':
1692 default: only enable networking if container requests it.
1693 always: containers always have networking enabled
1695 networkMode := flag.String("container-network-mode", "default",
1696 `Set networking mode for container. Corresponds to Docker network mode (--net).
1698 memprofile := flag.String("memprofile", "", "write memory profile to `file` after running container")
1699 getVersion := flag.Bool("version", false, "Print version information and exit.")
1702 // Print version information if requested
1704 fmt.Printf("crunch-run %s\n", version)
1708 log.Printf("crunch-run %s started", version)
1710 containerId := flag.Arg(0)
1712 if *caCertsPath != "" {
1713 arvadosclient.CertFiles = []string{*caCertsPath}
1716 api, err := arvadosclient.MakeArvadosClient()
1718 log.Fatalf("%s: %v", containerId, err)
1722 kc, kcerr := keepclient.MakeKeepClient(api)
1724 log.Fatalf("%s: %v", containerId, kcerr)
1726 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1729 // API version 1.21 corresponds to Docker 1.9, which is currently the
1730 // minimum version we want to support.
1731 docker, dockererr := dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1733 cr := NewContainerRunner(api, kc, docker, containerId)
1734 if dockererr != nil {
1735 cr.CrunchLog.Printf("%s: %v", containerId, dockererr)
1736 cr.checkBrokenNode(dockererr)
1737 cr.CrunchLog.Close()
1741 cr.statInterval = *statInterval
1742 cr.cgroupRoot = *cgroupRoot
1743 cr.expectCgroupParent = *cgroupParent
1744 cr.enableNetwork = *enableNetwork
1745 cr.networkMode = *networkMode
1746 if *cgroupParentSubsystem != "" {
1747 p := findCgroup(*cgroupParentSubsystem)
1748 cr.setCgroupParent = p
1749 cr.expectCgroupParent = p
1754 if *memprofile != "" {
1755 f, err := os.Create(*memprofile)
1757 log.Printf("could not create memory profile: ", err)
1759 runtime.GC() // get up-to-date statistics
1760 if err := pprof.WriteHeapProfile(f); err != nil {
1761 log.Printf("could not write memory profile: ", err)
1763 closeerr := f.Close()
1764 if closeerr != nil {
1765 log.Printf("closing memprofile file: ", err)
1770 log.Fatalf("%s: %v", containerId, runerr)