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
114 SecretMounts map[string]arvados.Mount
115 MkArvClient func(token string) (IArvadosClient, error)
119 statLogger io.WriteCloser
120 statReporter *crunchstat.Reporter
121 hoststatLogger io.WriteCloser
122 hoststatReporter *crunchstat.Reporter
123 statInterval time.Duration
125 // What we expect the container's cgroup parent to be.
126 expectCgroupParent string
127 // What we tell docker to use as the container's cgroup
128 // parent. Note: Ideally we would use the same field for both
129 // expectCgroupParent and setCgroupParent, and just make it
130 // default to "docker". However, when using docker < 1.10 with
131 // systemd, specifying a non-empty cgroup parent (even the
132 // default value "docker") hits a docker bug
133 // (https://github.com/docker/docker/issues/17126). Using two
134 // separate fields makes it possible to use the "expect cgroup
135 // parent to be X" feature even on sites where the "specify
136 // cgroup parent" feature breaks.
137 setCgroupParent string
139 cStateLock sync.Mutex
140 cCancelled bool // StopContainer() invoked
142 enableNetwork string // one of "default" or "always"
143 networkMode string // passed through to HostConfig.NetworkMode
144 arvMountLog *ThrottledLogger
147 // setupSignals sets up signal handling to gracefully terminate the underlying
148 // Docker container and update state when receiving a TERM, INT or QUIT signal.
149 func (runner *ContainerRunner) setupSignals() {
150 runner.SigChan = make(chan os.Signal, 1)
151 signal.Notify(runner.SigChan, syscall.SIGTERM)
152 signal.Notify(runner.SigChan, syscall.SIGINT)
153 signal.Notify(runner.SigChan, syscall.SIGQUIT)
155 go func(sig chan os.Signal) {
162 // stop the underlying Docker container.
163 func (runner *ContainerRunner) stop(sig os.Signal) {
164 runner.cStateLock.Lock()
165 defer runner.cStateLock.Unlock()
167 runner.CrunchLog.Printf("caught signal: %v", sig)
169 if runner.ContainerID == "" {
172 runner.cCancelled = true
173 runner.CrunchLog.Printf("removing container")
174 err := runner.Docker.ContainerRemove(context.TODO(), runner.ContainerID, dockertypes.ContainerRemoveOptions{Force: true})
176 runner.CrunchLog.Printf("error removing container: %s", err)
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(runner.parentTemp, prefix)
333 func copyfile(src string, dst string) (err error) {
334 srcfile, err := os.Open(src)
339 os.MkdirAll(path.Dir(dst), 0777)
341 dstfile, err := os.Create(dst)
345 _, err = io.Copy(dstfile, srcfile)
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)
401 for bind := range runner.SecretMounts {
402 if _, ok := runner.Container.Mounts[bind]; ok {
403 return fmt.Errorf("Secret mount %q conflicts with regular mount", bind)
405 if runner.SecretMounts[bind].Kind != "json" &&
406 runner.SecretMounts[bind].Kind != "text" {
407 return fmt.Errorf("Secret mount %q type is %q but only 'json' and 'text' are permitted.",
408 bind, runner.SecretMounts[bind].Kind)
410 binds = append(binds, bind)
414 for _, bind := range binds {
415 mnt, ok := runner.Container.Mounts[bind]
417 mnt = runner.SecretMounts[bind]
419 if bind == "stdout" || bind == "stderr" {
420 // Is it a "file" mount kind?
421 if mnt.Kind != "file" {
422 return fmt.Errorf("Unsupported mount kind '%s' for %s. Only 'file' is supported.", mnt.Kind, bind)
425 // Does path start with OutputPath?
426 prefix := runner.Container.OutputPath
427 if !strings.HasSuffix(prefix, "/") {
430 if !strings.HasPrefix(mnt.Path, prefix) {
431 return fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
436 // Is it a "collection" mount kind?
437 if mnt.Kind != "collection" && mnt.Kind != "json" {
438 return fmt.Errorf("Unsupported mount kind '%s' for stdin. Only 'collection' or 'json' are supported.", mnt.Kind)
442 if bind == "/etc/arvados/ca-certificates.crt" {
443 needCertMount = false
446 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
447 if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
448 return fmt.Errorf("Only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path for %q, was %q", bind, mnt.Kind)
453 case mnt.Kind == "collection" && bind != "stdin":
455 if mnt.UUID != "" && mnt.PortableDataHash != "" {
456 return fmt.Errorf("Cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
460 return fmt.Errorf("Writing to existing collections currently not permitted.")
463 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
464 } else if mnt.PortableDataHash != "" {
465 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
466 return fmt.Errorf("Can never write to a collection specified by portable data hash")
468 idx := strings.Index(mnt.PortableDataHash, "/")
470 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
471 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
472 runner.Container.Mounts[bind] = mnt
474 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
475 if mnt.Path != "" && mnt.Path != "." {
476 if strings.HasPrefix(mnt.Path, "./") {
477 mnt.Path = mnt.Path[2:]
478 } else if strings.HasPrefix(mnt.Path, "/") {
479 mnt.Path = mnt.Path[1:]
481 src += "/" + mnt.Path
484 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
485 arvMountCmd = append(arvMountCmd, "--mount-tmp")
486 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
490 if bind == runner.Container.OutputPath {
491 runner.HostOutputDir = src
492 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
493 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
494 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
496 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", src, bind))
499 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", src, bind))
501 collectionPaths = append(collectionPaths, src)
503 case mnt.Kind == "tmp":
505 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
507 return fmt.Errorf("While creating mount temp dir: %v", err)
509 st, staterr := os.Stat(tmpdir)
511 return fmt.Errorf("While Stat on temp dir: %v", staterr)
513 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
515 return fmt.Errorf("While Chmod temp dir: %v", err)
517 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s", tmpdir, bind))
518 if bind == runner.Container.OutputPath {
519 runner.HostOutputDir = tmpdir
522 case mnt.Kind == "json" || mnt.Kind == "text":
524 if mnt.Kind == "json" {
525 filedata, err = json.Marshal(mnt.Content)
527 return fmt.Errorf("encoding json data: %v", err)
530 text, ok := mnt.Content.(string)
532 return fmt.Errorf("content for mount %q must be a string", bind)
534 filedata = []byte(text)
537 tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
539 return fmt.Errorf("creating temp dir: %v", err)
541 tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
542 err = ioutil.WriteFile(tmpfn, filedata, 0444)
544 return fmt.Errorf("writing temp file: %v", err)
546 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
547 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
549 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:%s:ro", tmpfn, bind))
552 case mnt.Kind == "git_tree":
553 tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
555 return fmt.Errorf("creating temp dir: %v", err)
557 err = gitMount(mnt).extractTree(runner.ArvClient, tmpdir, token)
561 runner.Binds = append(runner.Binds, tmpdir+":"+bind+":ro")
565 if runner.HostOutputDir == "" {
566 return fmt.Errorf("Output path does not correspond to a writable mount point")
569 if wantAPI := runner.Container.RuntimeConstraints.API; needCertMount && wantAPI != nil && *wantAPI {
570 for _, certfile := range arvadosclient.CertFiles {
571 _, err := os.Stat(certfile)
573 runner.Binds = append(runner.Binds, fmt.Sprintf("%s:/etc/arvados/ca-certificates.crt:ro", certfile))
580 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
582 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
584 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
586 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
588 return fmt.Errorf("While trying to start arv-mount: %v", err)
591 for _, p := range collectionPaths {
594 return fmt.Errorf("While checking that input files exist: %v", err)
598 for _, cp := range copyFiles {
599 st, err := os.Stat(cp.src)
601 return fmt.Errorf("While staging writable file from %q to %q: %v", cp.src, cp.bind, err)
604 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
608 target := path.Join(cp.bind, walkpath[len(cp.src):])
609 if walkinfo.Mode().IsRegular() {
610 copyerr := copyfile(walkpath, target)
614 return os.Chmod(target, walkinfo.Mode()|0777)
615 } else if walkinfo.Mode().IsDir() {
616 mkerr := os.MkdirAll(target, 0777)
620 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
622 return fmt.Errorf("Source %q is not a regular file or directory", cp.src)
625 } else if st.Mode().IsRegular() {
626 err = copyfile(cp.src, cp.bind)
628 err = os.Chmod(cp.bind, st.Mode()|0777)
632 return fmt.Errorf("While staging writable file from %q to %q: %v", cp.src, cp.bind, err)
639 func (runner *ContainerRunner) ProcessDockerAttach(containerReader io.Reader) {
640 // Handle docker log protocol
641 // https://docs.docker.com/engine/reference/api/docker_remote_api_v1.15/#attach-to-a-container
642 defer close(runner.loggingDone)
644 header := make([]byte, 8)
647 _, err = io.ReadAtLeast(containerReader, header, 8)
654 readsize := int64(header[7]) | (int64(header[6]) << 8) | (int64(header[5]) << 16) | (int64(header[4]) << 24)
657 _, err = io.CopyN(runner.Stdout, containerReader, readsize)
660 _, err = io.CopyN(runner.Stderr, containerReader, readsize)
665 runner.CrunchLog.Printf("error reading docker logs: %v", err)
668 err = runner.Stdout.Close()
670 runner.CrunchLog.Printf("error closing stdout logs: %v", err)
673 err = runner.Stderr.Close()
675 runner.CrunchLog.Printf("error closing stderr logs: %v", err)
678 if runner.statReporter != nil {
679 runner.statReporter.Stop()
680 err = runner.statLogger.Close()
682 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
687 func (runner *ContainerRunner) stopHoststat() error {
688 if runner.hoststatReporter == nil {
691 runner.hoststatReporter.Stop()
692 err := runner.hoststatLogger.Close()
694 return fmt.Errorf("error closing hoststat logs: %v", err)
699 func (runner *ContainerRunner) startHoststat() {
700 runner.hoststatLogger = NewThrottledLogger(runner.NewLogWriter("hoststat"))
701 runner.hoststatReporter = &crunchstat.Reporter{
702 Logger: log.New(runner.hoststatLogger, "", 0),
703 CgroupRoot: runner.cgroupRoot,
704 PollPeriod: runner.statInterval,
706 runner.hoststatReporter.Start()
709 func (runner *ContainerRunner) startCrunchstat() {
710 runner.statLogger = NewThrottledLogger(runner.NewLogWriter("crunchstat"))
711 runner.statReporter = &crunchstat.Reporter{
712 CID: runner.ContainerID,
713 Logger: log.New(runner.statLogger, "", 0),
714 CgroupParent: runner.expectCgroupParent,
715 CgroupRoot: runner.cgroupRoot,
716 PollPeriod: runner.statInterval,
718 runner.statReporter.Start()
721 type infoCommand struct {
726 // LogHostInfo logs info about the current host, for debugging and
727 // accounting purposes. Although it's logged as "node-info", this is
728 // about the environment where crunch-run is actually running, which
729 // might differ from what's described in the node record (see
731 func (runner *ContainerRunner) LogHostInfo() (err error) {
732 w := runner.NewLogWriter("node-info")
734 commands := []infoCommand{
736 label: "Host Information",
737 cmd: []string{"uname", "-a"},
740 label: "CPU Information",
741 cmd: []string{"cat", "/proc/cpuinfo"},
744 label: "Memory Information",
745 cmd: []string{"cat", "/proc/meminfo"},
749 cmd: []string{"df", "-m", "/", os.TempDir()},
752 label: "Disk INodes",
753 cmd: []string{"df", "-i", "/", os.TempDir()},
757 // Run commands with informational output to be logged.
758 for _, command := range commands {
759 fmt.Fprintln(w, command.label)
760 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
763 if err := cmd.Run(); err != nil {
764 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
773 return fmt.Errorf("While closing node-info logs: %v", err)
778 // LogContainerRecord gets and saves the raw JSON container record from the API server
779 func (runner *ContainerRunner) LogContainerRecord() error {
780 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
781 if !logged && err == nil {
782 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
787 // LogNodeRecord logs arvados#node record corresponding to the current host.
788 func (runner *ContainerRunner) LogNodeRecord() error {
789 hostname := os.Getenv("SLURMD_NODENAME")
791 hostname, _ = os.Hostname()
793 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
794 // The "info" field has admin-only info when obtained
795 // with a privileged token, and should not be logged.
796 node, ok := resp.(map[string]interface{})
804 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
806 ArvClient: runner.ArvClient,
807 UUID: runner.Container.UUID,
808 loggingStream: label,
809 writeCloser: runner.LogCollection.Open(label + ".json"),
812 reader, err := runner.ArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
814 return false, fmt.Errorf("error getting %s record: %v", label, err)
818 dec := json.NewDecoder(reader)
820 var resp map[string]interface{}
821 if err = dec.Decode(&resp); err != nil {
822 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
824 items, ok := resp["items"].([]interface{})
826 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
827 } else if len(items) < 1 {
833 // Re-encode it using indentation to improve readability
834 enc := json.NewEncoder(w)
835 enc.SetIndent("", " ")
836 if err = enc.Encode(items[0]); err != nil {
837 return false, fmt.Errorf("error logging %s record: %v", label, err)
841 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
846 // AttachStreams connects the docker container stdin, stdout and stderr logs
847 // to the Arvados logger which logs to Keep and the API server logs table.
848 func (runner *ContainerRunner) AttachStreams() (err error) {
850 runner.CrunchLog.Print("Attaching container streams")
852 // If stdin mount is provided, attach it to the docker container
853 var stdinRdr arvados.File
855 if stdinMnt, ok := runner.Container.Mounts["stdin"]; ok {
856 if stdinMnt.Kind == "collection" {
857 var stdinColl arvados.Collection
858 collId := stdinMnt.UUID
860 collId = stdinMnt.PortableDataHash
862 err = runner.ArvClient.Get("collections", collId, nil, &stdinColl)
864 return fmt.Errorf("While getting stding collection: %v", err)
867 stdinRdr, err = runner.Kc.ManifestFileReader(manifest.Manifest{Text: stdinColl.ManifestText}, stdinMnt.Path)
868 if os.IsNotExist(err) {
869 return fmt.Errorf("stdin collection path not found: %v", stdinMnt.Path)
870 } else if err != nil {
871 return fmt.Errorf("While getting stdin collection path %v: %v", stdinMnt.Path, err)
873 } else if stdinMnt.Kind == "json" {
874 stdinJson, err = json.Marshal(stdinMnt.Content)
876 return fmt.Errorf("While encoding stdin json data: %v", err)
881 stdinUsed := stdinRdr != nil || len(stdinJson) != 0
882 response, err := runner.Docker.ContainerAttach(context.TODO(), runner.ContainerID,
883 dockertypes.ContainerAttachOptions{Stream: true, Stdin: stdinUsed, Stdout: true, Stderr: true})
885 return fmt.Errorf("While attaching container stdout/stderr streams: %v", err)
888 runner.loggingDone = make(chan bool)
890 if stdoutMnt, ok := runner.Container.Mounts["stdout"]; ok {
891 stdoutFile, err := runner.getStdoutFile(stdoutMnt.Path)
895 runner.Stdout = stdoutFile
897 runner.Stdout = NewThrottledLogger(runner.NewLogWriter("stdout"))
900 if stderrMnt, ok := runner.Container.Mounts["stderr"]; ok {
901 stderrFile, err := runner.getStdoutFile(stderrMnt.Path)
905 runner.Stderr = stderrFile
907 runner.Stderr = NewThrottledLogger(runner.NewLogWriter("stderr"))
912 _, err := io.Copy(response.Conn, stdinRdr)
914 runner.CrunchLog.Print("While writing stdin collection to docker container %q", err)
918 response.CloseWrite()
920 } else if len(stdinJson) != 0 {
922 _, err := io.Copy(response.Conn, bytes.NewReader(stdinJson))
924 runner.CrunchLog.Print("While writing stdin json to docker container %q", err)
927 response.CloseWrite()
931 go runner.ProcessDockerAttach(response.Reader)
936 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
937 stdoutPath := mntPath[len(runner.Container.OutputPath):]
938 index := strings.LastIndex(stdoutPath, "/")
940 subdirs := stdoutPath[:index]
942 st, err := os.Stat(runner.HostOutputDir)
944 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
946 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
947 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
949 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
953 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
955 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
958 return stdoutFile, nil
961 // CreateContainer creates the docker container.
962 func (runner *ContainerRunner) CreateContainer() error {
963 runner.CrunchLog.Print("Creating Docker container")
965 runner.ContainerConfig.Cmd = runner.Container.Command
966 if runner.Container.Cwd != "." {
967 runner.ContainerConfig.WorkingDir = runner.Container.Cwd
970 for k, v := range runner.Container.Environment {
971 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env, k+"="+v)
974 runner.ContainerConfig.Volumes = runner.Volumes
976 maxRAM := int64(runner.Container.RuntimeConstraints.RAM)
977 runner.HostConfig = dockercontainer.HostConfig{
979 LogConfig: dockercontainer.LogConfig{
982 Resources: dockercontainer.Resources{
983 CgroupParent: runner.setCgroupParent,
984 NanoCPUs: int64(runner.Container.RuntimeConstraints.VCPUs) * 1000000000,
985 Memory: maxRAM, // RAM
986 MemorySwap: maxRAM, // RAM+swap
987 KernelMemory: maxRAM, // kernel portion
991 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
992 tok, err := runner.ContainerToken()
996 runner.ContainerConfig.Env = append(runner.ContainerConfig.Env,
997 "ARVADOS_API_TOKEN="+tok,
998 "ARVADOS_API_HOST="+os.Getenv("ARVADOS_API_HOST"),
999 "ARVADOS_API_HOST_INSECURE="+os.Getenv("ARVADOS_API_HOST_INSECURE"),
1001 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
1003 if runner.enableNetwork == "always" {
1004 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode(runner.networkMode)
1006 runner.HostConfig.NetworkMode = dockercontainer.NetworkMode("none")
1010 _, stdinUsed := runner.Container.Mounts["stdin"]
1011 runner.ContainerConfig.OpenStdin = stdinUsed
1012 runner.ContainerConfig.StdinOnce = stdinUsed
1013 runner.ContainerConfig.AttachStdin = stdinUsed
1014 runner.ContainerConfig.AttachStdout = true
1015 runner.ContainerConfig.AttachStderr = true
1017 createdBody, err := runner.Docker.ContainerCreate(context.TODO(), &runner.ContainerConfig, &runner.HostConfig, nil, runner.Container.UUID)
1019 return fmt.Errorf("While creating container: %v", err)
1022 runner.ContainerID = createdBody.ID
1024 return runner.AttachStreams()
1027 // StartContainer starts the docker container created by CreateContainer.
1028 func (runner *ContainerRunner) StartContainer() error {
1029 runner.CrunchLog.Printf("Starting Docker container id '%s'", runner.ContainerID)
1030 runner.cStateLock.Lock()
1031 defer runner.cStateLock.Unlock()
1032 if runner.cCancelled {
1035 err := runner.Docker.ContainerStart(context.TODO(), runner.ContainerID,
1036 dockertypes.ContainerStartOptions{})
1039 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1040 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])
1042 return fmt.Errorf("could not start container: %v%s", err, advice)
1047 // WaitFinish waits for the container to terminate, capture the exit code, and
1048 // close the stdout/stderr logging.
1049 func (runner *ContainerRunner) WaitFinish() error {
1050 runner.CrunchLog.Print("Waiting for container to finish")
1052 waitOk, waitErr := runner.Docker.ContainerWait(context.TODO(), runner.ContainerID, dockercontainer.WaitConditionNotRunning)
1053 arvMountExit := runner.ArvMountExit
1056 case waitBody := <-waitOk:
1057 runner.CrunchLog.Printf("Container exited with code: %v", waitBody.StatusCode)
1058 code := int(waitBody.StatusCode)
1059 runner.ExitCode = &code
1061 // wait for stdout/stderr to complete
1062 <-runner.loggingDone
1065 case err := <-waitErr:
1066 return fmt.Errorf("container wait: %v", err)
1068 case <-arvMountExit:
1069 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1071 // arvMountExit will always be ready now that
1072 // it's closed, but that doesn't interest us.
1078 var ErrNotInOutputDir = fmt.Errorf("Must point to path within the output directory")
1080 func (runner *ContainerRunner) derefOutputSymlink(path string, startinfo os.FileInfo) (tgt string, readlinktgt string, info os.FileInfo, err error) {
1081 // Follow symlinks if necessary
1086 for followed := 0; info.Mode()&os.ModeSymlink != 0; followed++ {
1087 if followed >= limitFollowSymlinks {
1088 // Got stuck in a loop or just a pathological number of links, give up.
1089 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1093 readlinktgt, err = os.Readlink(nextlink)
1099 if !strings.HasPrefix(tgt, "/") {
1100 // Relative symlink, resolve it to host path
1101 tgt = filepath.Join(filepath.Dir(path), tgt)
1103 if strings.HasPrefix(tgt, runner.Container.OutputPath+"/") && !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1104 // Absolute symlink to container output path, adjust it to host output path.
1105 tgt = filepath.Join(runner.HostOutputDir, tgt[len(runner.Container.OutputPath):])
1107 if !strings.HasPrefix(tgt, runner.HostOutputDir+"/") {
1108 // After dereferencing, symlink target must either be
1109 // within output directory, or must point to a
1110 // collection mount.
1111 err = ErrNotInOutputDir
1115 info, err = os.Lstat(tgt)
1118 err = fmt.Errorf("Symlink in output %q points to invalid location %q: %v",
1119 path[len(runner.HostOutputDir):], readlinktgt, err)
1129 var limitFollowSymlinks = 10
1131 // UploadFile uploads files within the output directory, with special handling
1132 // for symlinks. If the symlink leads to a keep mount, copy the manifest text
1133 // from the keep mount into the output manifestText. Ensure that whether
1134 // symlinks are relative or absolute, every symlink target (even targets that
1135 // are symlinks themselves) must point to a path in either the output directory
1136 // or a collection mount.
1138 // Assumes initial value of "path" is absolute, and located within runner.HostOutputDir.
1139 func (runner *ContainerRunner) UploadOutputFile(
1144 walkUpload *WalkUpload,
1145 relocateFrom string,
1147 followed int) (manifestText string, err error) {
1153 if info.Mode().IsDir() {
1154 // if empty, need to create a .keep file
1155 dir, direrr := os.Open(path)
1160 names, eof := dir.Readdirnames(1)
1161 if len(names) == 0 && eof == io.EOF && path != runner.HostOutputDir {
1162 containerPath := runner.OutputPath + path[len(runner.HostOutputDir):]
1163 for _, bind := range binds {
1164 mnt := runner.Container.Mounts[bind]
1165 // Check if there is a bind for this
1166 // directory, in which case assume we don't need .keep
1167 if (containerPath == bind || strings.HasPrefix(containerPath, bind+"/")) && mnt.PortableDataHash != "d41d8cd98f00b204e9800998ecf8427e+0" {
1171 outputSuffix := path[len(runner.HostOutputDir)+1:]
1172 return fmt.Sprintf("./%v d41d8cd98f00b204e9800998ecf8427e+0 0:0:.keep\n", outputSuffix), nil
1177 if followed >= limitFollowSymlinks {
1178 // Got stuck in a loop or just a pathological number of
1179 // directory links, give up.
1180 err = fmt.Errorf("Followed more than %v symlinks from path %q", limitFollowSymlinks, path)
1184 // "path" is the actual path we are visiting
1185 // "tgt" is the target of "path" (a non-symlink) after following symlinks
1186 // "relocated" is the path in the output manifest where the file should be placed,
1187 // but has HostOutputDir as a prefix.
1189 // The destination path in the output manifest may need to be
1190 // logically relocated to some other path in order to appear
1191 // in the correct location as a result of following a symlink.
1192 // Remove the relocateFrom prefix and replace it with
1194 relocated := relocateTo + path[len(relocateFrom):]
1196 tgt, readlinktgt, info, derefErr := runner.derefOutputSymlink(path, info)
1197 if derefErr != nil && derefErr != ErrNotInOutputDir {
1201 // go through mounts and try reverse map to collection reference
1202 for _, bind := range binds {
1203 mnt := runner.Container.Mounts[bind]
1204 if (tgt == bind || strings.HasPrefix(tgt, bind+"/")) && !mnt.Writable {
1205 // get path relative to bind
1206 targetSuffix := tgt[len(bind):]
1208 // Copy mount and adjust the path to add path relative to the bind
1209 adjustedMount := mnt
1210 adjustedMount.Path = filepath.Join(adjustedMount.Path, targetSuffix)
1212 // Terminates in this keep mount, so add the
1213 // manifest text at appropriate location.
1214 outputSuffix := relocated[len(runner.HostOutputDir):]
1215 manifestText, err = runner.getCollectionManifestForPath(adjustedMount, outputSuffix)
1220 // If target is not a collection mount, it must be located within the
1221 // output directory, otherwise it is an error.
1222 if derefErr == ErrNotInOutputDir {
1223 err = fmt.Errorf("Symlink in output %q points to invalid location %q, must point to path within the output directory.",
1224 path[len(runner.HostOutputDir):], readlinktgt)
1228 if info.Mode().IsRegular() {
1229 return "", walkUpload.UploadFile(relocated, tgt)
1232 if info.Mode().IsDir() {
1233 // Symlink leads to directory. Walk() doesn't follow
1234 // directory symlinks, so we walk the target directory
1235 // instead. Within the walk, file paths are relocated
1236 // so they appear under the original symlink path.
1237 err = filepath.Walk(tgt, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
1239 m, walkerr = runner.UploadOutputFile(walkpath, walkinfo, walkerr,
1240 binds, walkUpload, tgt, relocated, followed+1)
1242 manifestText = manifestText + m
1252 // HandleOutput sets the output, unmounts the FUSE mount, and deletes temporary directories
1253 func (runner *ContainerRunner) CaptureOutput() error {
1254 if wantAPI := runner.Container.RuntimeConstraints.API; wantAPI != nil && *wantAPI {
1255 // Output may have been set directly by the container, so
1256 // refresh the container record to check.
1257 err := runner.ArvClient.Get("containers", runner.Container.UUID,
1258 nil, &runner.Container)
1262 if runner.Container.Output != "" {
1263 // Container output is already set.
1264 runner.OutputPDH = &runner.Container.Output
1269 if runner.HostOutputDir == "" {
1273 _, err := os.Stat(runner.HostOutputDir)
1275 return fmt.Errorf("While checking host output path: %v", err)
1278 // Pre-populate output from the configured mount points
1280 for bind, mnt := range runner.Container.Mounts {
1281 if mnt.Kind == "collection" {
1282 binds = append(binds, bind)
1287 // Delete secret mounts so they don't get saved to the output collection.
1288 for bind := range runner.SecretMounts {
1289 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
1290 err = os.Remove(runner.HostOutputDir + bind[len(runner.Container.OutputPath):])
1292 return fmt.Errorf("Unable to remove secret mount: %v", err)
1297 var manifestText string
1299 collectionMetafile := fmt.Sprintf("%s/.arvados#collection", runner.HostOutputDir)
1300 _, err = os.Stat(collectionMetafile)
1302 // Regular directory
1304 cw := CollectionWriter{0, runner.Kc, nil, nil, sync.Mutex{}}
1305 walkUpload := cw.BeginUpload(runner.HostOutputDir, runner.CrunchLog.Logger)
1308 err = filepath.Walk(runner.HostOutputDir, func(path string, info os.FileInfo, err error) error {
1309 m, err = runner.UploadOutputFile(path, info, err, binds, walkUpload, "", "", 0)
1311 manifestText = manifestText + m
1316 cw.EndUpload(walkUpload)
1319 return fmt.Errorf("While uploading output files: %v", err)
1322 m, err = cw.ManifestText()
1323 manifestText = manifestText + m
1325 return fmt.Errorf("While uploading output files: %v", err)
1328 // FUSE mount directory
1329 file, openerr := os.Open(collectionMetafile)
1331 return fmt.Errorf("While opening FUSE metafile: %v", err)
1335 var rec arvados.Collection
1336 err = json.NewDecoder(file).Decode(&rec)
1338 return fmt.Errorf("While reading FUSE metafile: %v", err)
1340 manifestText = rec.ManifestText
1343 for _, bind := range binds {
1344 mnt := runner.Container.Mounts[bind]
1346 bindSuffix := strings.TrimPrefix(bind, runner.Container.OutputPath)
1348 if bindSuffix == bind || len(bindSuffix) <= 0 {
1349 // either does not start with OutputPath or is OutputPath itself
1353 if mnt.ExcludeFromOutput == true || mnt.Writable {
1357 // append to manifest_text
1358 m, err := runner.getCollectionManifestForPath(mnt, bindSuffix)
1363 manifestText = manifestText + m
1367 var response arvados.Collection
1368 manifest := manifest.Manifest{Text: manifestText}
1369 manifestText = manifest.Extract(".", ".").Text
1370 err = runner.ArvClient.Create("collections",
1372 "ensure_unique_name": true,
1373 "collection": arvadosclient.Dict{
1375 "name": "output for " + runner.Container.UUID,
1376 "manifest_text": manifestText}},
1379 return fmt.Errorf("While creating output collection: %v", err)
1381 runner.OutputPDH = &response.PortableDataHash
1385 var outputCollections = make(map[string]arvados.Collection)
1387 // Fetch the collection for the mnt.PortableDataHash
1388 // Return the manifest_text fragment corresponding to the specified mnt.Path
1389 // after making any required updates.
1391 // If mnt.Path is not specified,
1392 // return the entire manifest_text after replacing any "." with bindSuffix
1393 // If mnt.Path corresponds to one stream,
1394 // return the manifest_text for that stream after replacing that stream name with bindSuffix
1395 // Otherwise, check if a filename in any one stream is being sought. Return the manifest_text
1396 // for that stream after replacing stream name with bindSuffix minus the last word
1397 // and the file name with last word of the bindSuffix
1398 // Allowed path examples:
1400 // "path":"/subdir1"
1401 // "path":"/subdir1/subdir2"
1402 // "path":"/subdir/filename" etc
1403 func (runner *ContainerRunner) getCollectionManifestForPath(mnt arvados.Mount, bindSuffix string) (string, error) {
1404 collection := outputCollections[mnt.PortableDataHash]
1405 if collection.PortableDataHash == "" {
1406 err := runner.ArvClient.Get("collections", mnt.PortableDataHash, nil, &collection)
1408 return "", fmt.Errorf("While getting collection for %v: %v", mnt.PortableDataHash, err)
1410 outputCollections[mnt.PortableDataHash] = collection
1413 if collection.ManifestText == "" {
1414 runner.CrunchLog.Printf("No manifest text for collection %v", collection.PortableDataHash)
1418 mft := manifest.Manifest{Text: collection.ManifestText}
1419 extracted := mft.Extract(mnt.Path, bindSuffix)
1420 if extracted.Err != nil {
1421 return "", fmt.Errorf("Error parsing manifest for %v: %v", mnt.PortableDataHash, extracted.Err.Error())
1423 return extracted.Text, nil
1426 func (runner *ContainerRunner) CleanupDirs() {
1427 if runner.ArvMount != nil {
1429 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1430 umount.Stdout = runner.CrunchLog
1431 umount.Stderr = runner.CrunchLog
1432 runner.CrunchLog.Printf("Running %v", umount.Args)
1433 umnterr := umount.Start()
1436 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1438 // If arv-mount --unmount gets stuck for any reason, we
1439 // don't want to wait for it forever. Do Wait() in a goroutine
1440 // so it doesn't block crunch-run.
1441 umountExit := make(chan error)
1443 mnterr := umount.Wait()
1445 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1447 umountExit <- mnterr
1450 for again := true; again; {
1456 case <-runner.ArvMountExit:
1458 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1459 runner.CrunchLog.Printf("Timed out waiting for unmount")
1461 umount.Process.Kill()
1463 runner.ArvMount.Process.Kill()
1469 if runner.ArvMountPoint != "" {
1470 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1471 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1475 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1476 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1480 // CommitLogs posts the collection containing the final container logs.
1481 func (runner *ContainerRunner) CommitLogs() error {
1483 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1484 runner.cStateLock.Lock()
1485 defer runner.cStateLock.Unlock()
1487 runner.CrunchLog.Print(runner.finalState)
1489 if runner.arvMountLog != nil {
1490 runner.arvMountLog.Close()
1492 runner.CrunchLog.Close()
1494 // Closing CrunchLog above allows them to be committed to Keep at this
1495 // point, but re-open crunch log with ArvClient in case there are any
1496 // other further errors (such as failing to write the log to Keep!)
1497 // while shutting down
1498 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{ArvClient: runner.ArvClient,
1499 UUID: runner.Container.UUID, loggingStream: "crunch-run", writeCloser: nil})
1500 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1503 if runner.LogsPDH != nil {
1504 // If we have already assigned something to LogsPDH,
1505 // we must be closing the re-opened log, which won't
1506 // end up getting attached to the container record and
1507 // therefore doesn't need to be saved as a collection
1508 // -- it exists only to send logs to other channels.
1512 mt, err := runner.LogCollection.ManifestText()
1514 return fmt.Errorf("While creating log manifest: %v", err)
1517 var response arvados.Collection
1518 err = runner.ArvClient.Create("collections",
1520 "ensure_unique_name": true,
1521 "collection": arvadosclient.Dict{
1523 "name": "logs for " + runner.Container.UUID,
1524 "manifest_text": mt}},
1527 return fmt.Errorf("While creating log collection: %v", err)
1529 runner.LogsPDH = &response.PortableDataHash
1533 // UpdateContainerRunning updates the container state to "Running"
1534 func (runner *ContainerRunner) UpdateContainerRunning() error {
1535 runner.cStateLock.Lock()
1536 defer runner.cStateLock.Unlock()
1537 if runner.cCancelled {
1540 return runner.ArvClient.Update("containers", runner.Container.UUID,
1541 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running"}}, nil)
1544 // ContainerToken returns the api_token the container (and any
1545 // arv-mount processes) are allowed to use.
1546 func (runner *ContainerRunner) ContainerToken() (string, error) {
1547 if runner.token != "" {
1548 return runner.token, nil
1551 var auth arvados.APIClientAuthorization
1552 err := runner.ArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1556 runner.token = auth.APIToken
1557 return runner.token, nil
1560 // UpdateContainerComplete updates the container record state on API
1561 // server to "Complete" or "Cancelled"
1562 func (runner *ContainerRunner) UpdateContainerFinal() error {
1563 update := arvadosclient.Dict{}
1564 update["state"] = runner.finalState
1565 if runner.LogsPDH != nil {
1566 update["log"] = *runner.LogsPDH
1568 if runner.finalState == "Complete" {
1569 if runner.ExitCode != nil {
1570 update["exit_code"] = *runner.ExitCode
1572 if runner.OutputPDH != nil {
1573 update["output"] = *runner.OutputPDH
1576 return runner.ArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1579 // IsCancelled returns the value of Cancelled, with goroutine safety.
1580 func (runner *ContainerRunner) IsCancelled() bool {
1581 runner.cStateLock.Lock()
1582 defer runner.cStateLock.Unlock()
1583 return runner.cCancelled
1586 // NewArvLogWriter creates an ArvLogWriter
1587 func (runner *ContainerRunner) NewArvLogWriter(name string) io.WriteCloser {
1588 return &ArvLogWriter{
1589 ArvClient: runner.ArvClient,
1590 UUID: runner.Container.UUID,
1591 loggingStream: name,
1592 writeCloser: runner.LogCollection.Open(name + ".txt")}
1595 // Run the full container lifecycle.
1596 func (runner *ContainerRunner) Run() (err error) {
1597 runner.CrunchLog.Printf("crunch-run %s started", version)
1598 runner.CrunchLog.Printf("Executing container '%s'", runner.Container.UUID)
1600 hostname, hosterr := os.Hostname()
1602 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1604 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1607 runner.finalState = "Queued"
1610 runner.CleanupDirs()
1612 runner.CrunchLog.Printf("crunch-run finished")
1613 runner.CrunchLog.Close()
1617 // checkErr prints e (unless it's nil) and sets err to
1618 // e (unless err is already non-nil). Thus, if err
1619 // hasn't already been assigned when Run() returns,
1620 // this cleanup func will cause Run() to return the
1621 // first non-nil error that is passed to checkErr().
1622 checkErr := func(e error) {
1626 runner.CrunchLog.Print(e)
1630 if runner.finalState == "Complete" {
1631 // There was an error in the finalization.
1632 runner.finalState = "Cancelled"
1636 // Log the error encountered in Run(), if any
1639 if runner.finalState == "Queued" {
1640 runner.UpdateContainerFinal()
1644 if runner.IsCancelled() {
1645 runner.finalState = "Cancelled"
1646 // but don't return yet -- we still want to
1647 // capture partial output and write logs
1650 checkErr(runner.CaptureOutput())
1651 checkErr(runner.stopHoststat())
1652 checkErr(runner.CommitLogs())
1653 checkErr(runner.UpdateContainerFinal())
1656 err = runner.fetchContainerRecord()
1660 runner.setupSignals()
1661 runner.startHoststat()
1663 // check for and/or load image
1664 err = runner.LoadImage()
1666 if !runner.checkBrokenNode(err) {
1667 // Failed to load image but not due to a "broken node"
1668 // condition, probably user error.
1669 runner.finalState = "Cancelled"
1671 err = fmt.Errorf("While loading container image: %v", err)
1675 // set up FUSE mount and binds
1676 err = runner.SetupMounts()
1678 runner.finalState = "Cancelled"
1679 err = fmt.Errorf("While setting up mounts: %v", err)
1683 err = runner.CreateContainer()
1687 err = runner.LogHostInfo()
1691 err = runner.LogNodeRecord()
1695 err = runner.LogContainerRecord()
1700 if runner.IsCancelled() {
1704 err = runner.UpdateContainerRunning()
1708 runner.finalState = "Cancelled"
1710 runner.startCrunchstat()
1712 err = runner.StartContainer()
1714 runner.checkBrokenNode(err)
1718 err = runner.WaitFinish()
1719 if err == nil && !runner.IsCancelled() {
1720 runner.finalState = "Complete"
1725 // Fetch the current container record (uuid = runner.Container.UUID)
1726 // into runner.Container.
1727 func (runner *ContainerRunner) fetchContainerRecord() error {
1728 reader, err := runner.ArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1730 return fmt.Errorf("error fetching container record: %v", err)
1732 defer reader.Close()
1734 dec := json.NewDecoder(reader)
1736 err = dec.Decode(&runner.Container)
1738 return fmt.Errorf("error decoding container record: %v", err)
1742 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1745 containerToken, err := runner.ContainerToken()
1747 return fmt.Errorf("error getting container token: %v", err)
1750 containerClient, err := runner.MkArvClient(containerToken)
1752 return fmt.Errorf("error creating container API client: %v", err)
1755 err = containerClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1757 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1758 return fmt.Errorf("error fetching secret_mounts: %v", err)
1760 // ok && apierr.HttpStatusCode == 404, which means
1761 // secret_mounts isn't supported by this API server.
1763 runner.SecretMounts = sm.SecretMounts
1768 // NewContainerRunner creates a new container runner.
1769 func NewContainerRunner(api IArvadosClient,
1771 docker ThinDockerClient,
1772 containerUUID string) *ContainerRunner {
1774 cr := &ContainerRunner{ArvClient: api, Kc: kc, Docker: docker}
1775 cr.NewLogWriter = cr.NewArvLogWriter
1776 cr.RunArvMount = cr.ArvMountCmd
1777 cr.MkTempDir = ioutil.TempDir
1778 cr.MkArvClient = func(token string) (IArvadosClient, error) {
1779 cl, err := arvadosclient.MakeArvadosClient()
1786 cr.LogCollection = &CollectionWriter{0, kc, nil, nil, sync.Mutex{}}
1787 cr.Container.UUID = containerUUID
1788 cr.CrunchLog = NewThrottledLogger(cr.NewLogWriter("crunch-run"))
1789 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1791 loadLogThrottleParams(api)
1797 statInterval := flag.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1798 cgroupRoot := flag.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1799 cgroupParent := flag.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1800 cgroupParentSubsystem := flag.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1801 caCertsPath := flag.String("ca-certs", "", "Path to TLS root certificates")
1802 enableNetwork := flag.String("container-enable-networking", "default",
1803 `Specify if networking should be enabled for container. One of 'default', 'always':
1804 default: only enable networking if container requests it.
1805 always: containers always have networking enabled
1807 networkMode := flag.String("container-network-mode", "default",
1808 `Set networking mode for container. Corresponds to Docker network mode (--net).
1810 memprofile := flag.String("memprofile", "", "write memory profile to `file` after running container")
1811 getVersion := flag.Bool("version", false, "Print version information and exit.")
1814 // Print version information if requested
1816 fmt.Printf("crunch-run %s\n", version)
1820 log.Printf("crunch-run %s started", version)
1822 containerId := flag.Arg(0)
1824 if *caCertsPath != "" {
1825 arvadosclient.CertFiles = []string{*caCertsPath}
1828 api, err := arvadosclient.MakeArvadosClient()
1830 log.Fatalf("%s: %v", containerId, err)
1834 kc, kcerr := keepclient.MakeKeepClient(api)
1836 log.Fatalf("%s: %v", containerId, kcerr)
1838 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1841 // API version 1.21 corresponds to Docker 1.9, which is currently the
1842 // minimum version we want to support.
1843 docker, dockererr := dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
1845 cr := NewContainerRunner(api, kc, docker, containerId)
1846 if dockererr != nil {
1847 cr.CrunchLog.Printf("%s: %v", containerId, dockererr)
1848 cr.checkBrokenNode(dockererr)
1849 cr.CrunchLog.Close()
1853 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerId+".")
1855 log.Fatalf("%s: %v", containerId, tmperr)
1858 cr.parentTemp = parentTemp
1859 cr.statInterval = *statInterval
1860 cr.cgroupRoot = *cgroupRoot
1861 cr.expectCgroupParent = *cgroupParent
1862 cr.enableNetwork = *enableNetwork
1863 cr.networkMode = *networkMode
1864 if *cgroupParentSubsystem != "" {
1865 p := findCgroup(*cgroupParentSubsystem)
1866 cr.setCgroupParent = p
1867 cr.expectCgroupParent = p
1872 if *memprofile != "" {
1873 f, err := os.Create(*memprofile)
1875 log.Printf("could not create memory profile: ", err)
1877 runtime.GC() // get up-to-date statistics
1878 if err := pprof.WriteHeapProfile(f); err != nil {
1879 log.Printf("could not write memory profile: ", err)
1881 closeerr := f.Close()
1882 if closeerr != nil {
1883 log.Printf("closing memprofile file: ", err)
1888 log.Fatalf("%s: %v", containerId, runerr)