1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
34 "git.arvados.org/arvados.git/lib/cmd"
35 "git.arvados.org/arvados.git/lib/config"
36 "git.arvados.org/arvados.git/lib/crunchstat"
37 "git.arvados.org/arvados.git/sdk/go/arvados"
38 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
39 "git.arvados.org/arvados.git/sdk/go/ctxlog"
40 "git.arvados.org/arvados.git/sdk/go/keepclient"
41 "git.arvados.org/arvados.git/sdk/go/manifest"
42 "golang.org/x/sys/unix"
47 var Command = command{}
49 // ConfigData contains environment variables and (when needed) cluster
50 // configuration, passed from dispatchcloud to crunch-run on stdin.
51 type ConfigData struct {
54 Cluster *arvados.Cluster
57 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
58 type IArvadosClient interface {
59 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
60 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
61 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
62 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
63 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
64 Discovery(key string) (interface{}, error)
67 // ErrCancelled is the error returned when the container is cancelled.
68 var ErrCancelled = errors.New("Cancelled")
70 // IKeepClient is the minimal Keep API methods used by crunch-run.
71 type IKeepClient interface {
72 BlockWrite(context.Context, arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error)
73 ReadAt(locator string, p []byte, off int) (int, error)
74 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
75 LocalLocator(locator string) (string, error)
77 SetStorageClasses(sc []string)
80 // NewLogWriter is a factory function to create a new log writer.
81 type NewLogWriter func(name string) (io.WriteCloser, error)
83 type RunArvMount func(cmdline []string, tok string) (*exec.Cmd, error)
85 type MkTempDir func(string, string) (string, error)
87 type PsProcess interface {
88 CmdlineSlice() ([]string, error)
91 // ContainerRunner is the main stateful struct used for a single execution of a
93 type ContainerRunner struct {
94 executor containerExecutor
95 executorStdin io.Closer
96 executorStdout io.Closer
97 executorStderr io.Closer
99 // Dispatcher client is initialized with the Dispatcher token.
100 // This is a privileged token used to manage container status
103 // We have both dispatcherClient and DispatcherArvClient
104 // because there are two different incompatible Arvados Go
105 // SDKs and we have to use both (hopefully this gets fixed in
107 dispatcherClient *arvados.Client
108 DispatcherArvClient IArvadosClient
109 DispatcherKeepClient IKeepClient
111 // Container client is initialized with the Container token
112 // This token controls the permissions of the container, and
113 // must be used for operations such as reading collections.
115 // Same comment as above applies to
116 // containerClient/ContainerArvClient.
117 containerClient *arvados.Client
118 ContainerArvClient IArvadosClient
119 ContainerKeepClient IKeepClient
121 Container arvados.Container
124 NewLogWriter NewLogWriter
125 CrunchLog *ThrottledLogger
128 LogCollection arvados.CollectionFileSystem
130 RunArvMount RunArvMount
135 Volumes map[string]struct{}
137 SigChan chan os.Signal
138 ArvMountExit chan error
139 SecretMounts map[string]arvados.Mount
140 MkArvClient func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error)
143 costStartTime time.Time
146 keepstoreLogger io.WriteCloser
147 keepstoreLogbuf *bufThenWrite
148 statLogger io.WriteCloser
149 statReporter *crunchstat.Reporter
150 hoststatLogger io.WriteCloser
151 hoststatReporter *crunchstat.Reporter
152 statInterval time.Duration
154 // What we expect the container's cgroup parent to be.
155 expectCgroupParent string
156 // What we tell docker to use as the container's cgroup
157 // parent. Note: Ideally we would use the same field for both
158 // expectCgroupParent and setCgroupParent, and just make it
159 // default to "docker". However, when using docker < 1.10 with
160 // systemd, specifying a non-empty cgroup parent (even the
161 // default value "docker") hits a docker bug
162 // (https://github.com/docker/docker/issues/17126). Using two
163 // separate fields makes it possible to use the "expect cgroup
164 // parent to be X" feature even on sites where the "specify
165 // cgroup parent" feature breaks.
166 setCgroupParent string
168 cStateLock sync.Mutex
169 cCancelled bool // StopContainer() invoked
171 enableMemoryLimit bool
172 enableNetwork string // one of "default" or "always"
173 networkMode string // "none", "host", or "" -- passed through to executor
174 brokenNodeHook string // script to run if node appears to be broken
175 arvMountLog *ThrottledLogger
177 containerWatchdogInterval time.Duration
182 // setupSignals sets up signal handling to gracefully terminate the
183 // underlying container and update state when receiving a TERM, INT or
185 func (runner *ContainerRunner) setupSignals() {
186 runner.SigChan = make(chan os.Signal, 1)
187 signal.Notify(runner.SigChan, syscall.SIGTERM)
188 signal.Notify(runner.SigChan, syscall.SIGINT)
189 signal.Notify(runner.SigChan, syscall.SIGQUIT)
191 go func(sig chan os.Signal) {
198 // stop the underlying container.
199 func (runner *ContainerRunner) stop(sig os.Signal) {
200 runner.cStateLock.Lock()
201 defer runner.cStateLock.Unlock()
203 runner.CrunchLog.Printf("caught signal: %v", sig)
205 runner.cCancelled = true
206 runner.CrunchLog.Printf("stopping container")
207 err := runner.executor.Stop()
209 runner.CrunchLog.Printf("error stopping container: %s", err)
213 var errorBlacklist = []string{
214 "(?ms).*[Cc]annot connect to the Docker daemon.*",
215 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
216 "(?ms).*grpc: the connection is unavailable.*",
219 func (runner *ContainerRunner) runBrokenNodeHook() {
220 if runner.brokenNodeHook == "" {
221 path := filepath.Join(lockdir, brokenfile)
222 runner.CrunchLog.Printf("Writing %s to mark node as broken", path)
223 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0700)
225 runner.CrunchLog.Printf("Error writing %s: %s", path, err)
230 runner.CrunchLog.Printf("Running broken node hook %q", runner.brokenNodeHook)
232 c := exec.Command(runner.brokenNodeHook)
233 c.Stdout = runner.CrunchLog
234 c.Stderr = runner.CrunchLog
237 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
242 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
243 for _, d := range errorBlacklist {
244 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
245 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
246 runner.runBrokenNodeHook()
253 // LoadImage determines the docker image id from the container record and
254 // checks if it is available in the local Docker image store. If not, it loads
255 // the image from Keep.
256 func (runner *ContainerRunner) LoadImage() (string, error) {
257 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
259 d, err := os.Open(runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage)
264 allfiles, err := d.Readdirnames(-1)
268 var tarfiles []string
269 for _, fnm := range allfiles {
270 if strings.HasSuffix(fnm, ".tar") {
271 tarfiles = append(tarfiles, fnm)
274 if len(tarfiles) == 0 {
275 return "", fmt.Errorf("image collection does not include a .tar image file")
277 if len(tarfiles) > 1 {
278 return "", fmt.Errorf("cannot choose from multiple tar files in image collection: %v", tarfiles)
280 imageID := tarfiles[0][:len(tarfiles[0])-4]
281 imageTarballPath := runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage + "/" + imageID + ".tar"
282 runner.CrunchLog.Printf("Using Docker image id %q", imageID)
284 runner.CrunchLog.Print("Loading Docker image from keep")
285 err = runner.executor.LoadImage(imageID, imageTarballPath, runner.Container, runner.ArvMountPoint,
286 runner.containerClient)
294 func (runner *ContainerRunner) ArvMountCmd(cmdline []string, token string) (c *exec.Cmd, err error) {
295 c = exec.Command(cmdline[0], cmdline[1:]...)
297 // Copy our environment, but override ARVADOS_API_TOKEN with
298 // the container auth token.
300 for _, s := range os.Environ() {
301 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
302 c.Env = append(c.Env, s)
305 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
307 w, err := runner.NewLogWriter("arv-mount")
311 runner.arvMountLog = NewThrottledLogger(w)
312 scanner := logScanner{
315 "Block not found error",
316 "Unhandled exception during FUSE operation",
318 ReportFunc: runner.reportArvMountWarning,
320 c.Stdout = runner.arvMountLog
321 c.Stderr = io.MultiWriter(runner.arvMountLog, os.Stderr, &scanner)
323 runner.CrunchLog.Printf("Running %v", c.Args)
330 statReadme := make(chan bool)
331 runner.ArvMountExit = make(chan error)
336 time.Sleep(100 * time.Millisecond)
337 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
349 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
351 runner.ArvMountExit <- mnterr
352 close(runner.ArvMountExit)
358 case err := <-runner.ArvMountExit:
359 runner.ArvMount = nil
367 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
368 if runner.ArvMountPoint == "" {
369 runner.ArvMountPoint, err = runner.MkTempDir(runner.parentTemp, prefix)
374 func copyfile(src string, dst string) (err error) {
375 srcfile, err := os.Open(src)
380 os.MkdirAll(path.Dir(dst), 0777)
382 dstfile, err := os.Create(dst)
386 _, err = io.Copy(dstfile, srcfile)
391 err = srcfile.Close()
392 err2 := dstfile.Close()
405 func (runner *ContainerRunner) SetupMounts() (map[string]bindmount, error) {
406 bindmounts := map[string]bindmount{}
407 err := runner.SetupArvMountPoint("keep")
409 return nil, fmt.Errorf("While creating keep mount temp dir: %v", err)
412 token, err := runner.ContainerToken()
414 return nil, fmt.Errorf("could not get container token: %s", err)
416 runner.CrunchLog.Printf("container token %q", token)
420 arvMountCmd := []string{
424 "--storage-classes", strings.Join(runner.Container.OutputStorageClasses, ","),
425 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
427 if _, isdocker := runner.executor.(*dockerExecutor); isdocker {
428 arvMountCmd = append(arvMountCmd, "--allow-other")
431 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
432 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
435 collectionPaths := []string{}
436 needCertMount := true
437 type copyFile struct {
441 var copyFiles []copyFile
444 for bind := range runner.Container.Mounts {
445 binds = append(binds, bind)
447 for bind := range runner.SecretMounts {
448 if _, ok := runner.Container.Mounts[bind]; ok {
449 return nil, fmt.Errorf("secret mount %q conflicts with regular mount", bind)
451 if runner.SecretMounts[bind].Kind != "json" &&
452 runner.SecretMounts[bind].Kind != "text" {
453 return nil, fmt.Errorf("secret mount %q type is %q but only 'json' and 'text' are permitted",
454 bind, runner.SecretMounts[bind].Kind)
456 binds = append(binds, bind)
460 for _, bind := range binds {
461 mnt, notSecret := runner.Container.Mounts[bind]
463 mnt = runner.SecretMounts[bind]
465 if bind == "stdout" || bind == "stderr" {
466 // Is it a "file" mount kind?
467 if mnt.Kind != "file" {
468 return nil, fmt.Errorf("unsupported mount kind '%s' for %s: only 'file' is supported", mnt.Kind, bind)
471 // Does path start with OutputPath?
472 prefix := runner.Container.OutputPath
473 if !strings.HasSuffix(prefix, "/") {
476 if !strings.HasPrefix(mnt.Path, prefix) {
477 return nil, fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
482 // Is it a "collection" mount kind?
483 if mnt.Kind != "collection" && mnt.Kind != "json" {
484 return nil, fmt.Errorf("unsupported mount kind '%s' for stdin: only 'collection' and 'json' are supported", mnt.Kind)
488 if bind == "/etc/arvados/ca-certificates.crt" {
489 needCertMount = false
492 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
493 if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
494 return nil, fmt.Errorf("only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path for %q, was %q", bind, mnt.Kind)
499 case mnt.Kind == "collection" && bind != "stdin":
501 if mnt.UUID != "" && mnt.PortableDataHash != "" {
502 return nil, fmt.Errorf("cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
506 return nil, fmt.Errorf("writing to existing collections currently not permitted")
509 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
510 } else if mnt.PortableDataHash != "" {
511 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
512 return nil, fmt.Errorf("can never write to a collection specified by portable data hash")
514 idx := strings.Index(mnt.PortableDataHash, "/")
516 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
517 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
518 runner.Container.Mounts[bind] = mnt
520 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
521 if mnt.Path != "" && mnt.Path != "." {
522 if strings.HasPrefix(mnt.Path, "./") {
523 mnt.Path = mnt.Path[2:]
524 } else if strings.HasPrefix(mnt.Path, "/") {
525 mnt.Path = mnt.Path[1:]
527 src += "/" + mnt.Path
530 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
531 arvMountCmd = append(arvMountCmd, "--mount-tmp", fmt.Sprintf("tmp%d", tmpcount))
535 if bind == runner.Container.OutputPath {
536 runner.HostOutputDir = src
537 bindmounts[bind] = bindmount{HostPath: src}
538 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
539 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
541 bindmounts[bind] = bindmount{HostPath: src}
544 bindmounts[bind] = bindmount{HostPath: src, ReadOnly: true}
546 collectionPaths = append(collectionPaths, src)
548 case mnt.Kind == "tmp":
550 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
552 return nil, fmt.Errorf("while creating mount temp dir: %v", err)
554 st, staterr := os.Stat(tmpdir)
556 return nil, fmt.Errorf("while Stat on temp dir: %v", staterr)
558 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
560 return nil, fmt.Errorf("while Chmod temp dir: %v", err)
562 bindmounts[bind] = bindmount{HostPath: tmpdir}
563 if bind == runner.Container.OutputPath {
564 runner.HostOutputDir = tmpdir
567 case mnt.Kind == "json" || mnt.Kind == "text":
569 if mnt.Kind == "json" {
570 filedata, err = json.Marshal(mnt.Content)
572 return nil, fmt.Errorf("encoding json data: %v", err)
575 text, ok := mnt.Content.(string)
577 return nil, fmt.Errorf("content for mount %q must be a string", bind)
579 filedata = []byte(text)
582 tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
584 return nil, fmt.Errorf("creating temp dir: %v", err)
586 tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
587 err = ioutil.WriteFile(tmpfn, filedata, 0444)
589 return nil, fmt.Errorf("writing temp file: %v", err)
591 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && (notSecret || runner.Container.Mounts[runner.Container.OutputPath].Kind != "collection") {
592 // In most cases, if the container
593 // specifies a literal file inside the
594 // output path, we copy it into the
595 // output directory (either a mounted
596 // collection or a staging area on the
597 // host fs). If it's a secret, it will
598 // be skipped when copying output from
599 // staging to Keep later.
600 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
602 // If a secret is outside OutputPath,
603 // we bind mount the secret file
604 // directly just like other mounts. We
605 // also use this strategy when a
606 // secret is inside OutputPath but
607 // OutputPath is a live collection, to
608 // avoid writing the secret to
609 // Keep. Attempting to remove a
610 // bind-mounted secret file from
611 // inside the container will return a
612 // "Device or resource busy" error
613 // that might not be handled well by
614 // the container, which is why we
615 // don't use this strategy when
616 // OutputPath is a staging directory.
617 bindmounts[bind] = bindmount{HostPath: tmpfn, ReadOnly: true}
620 case mnt.Kind == "git_tree":
621 tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
623 return nil, fmt.Errorf("creating temp dir: %v", err)
625 err = gitMount(mnt).extractTree(runner.ContainerArvClient, tmpdir, token)
629 bindmounts[bind] = bindmount{HostPath: tmpdir, ReadOnly: true}
633 if runner.HostOutputDir == "" {
634 return nil, fmt.Errorf("output path does not correspond to a writable mount point")
637 if needCertMount && runner.Container.RuntimeConstraints.API {
638 for _, certfile := range arvadosclient.CertFiles {
639 _, err := os.Stat(certfile)
641 bindmounts["/etc/arvados/ca-certificates.crt"] = bindmount{HostPath: certfile, ReadOnly: true}
648 // If we are only mounting collections by pdh, make
649 // sure we don't subscribe to websocket events to
650 // avoid putting undesired load on the API server
651 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id", "--disable-event-listening")
653 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
655 // the by_uuid mount point is used by singularity when writing
656 // out docker images converted to SIF
657 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_uuid")
658 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
660 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
662 return nil, fmt.Errorf("while trying to start arv-mount: %v", err)
664 if runner.hoststatReporter != nil && runner.ArvMount != nil {
665 runner.hoststatReporter.ReportPID("arv-mount", runner.ArvMount.Process.Pid)
668 for _, p := range collectionPaths {
671 return nil, fmt.Errorf("while checking that input files exist: %v", err)
675 for _, cp := range copyFiles {
676 st, err := os.Stat(cp.src)
678 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
681 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
685 target := path.Join(cp.bind, walkpath[len(cp.src):])
686 if walkinfo.Mode().IsRegular() {
687 copyerr := copyfile(walkpath, target)
691 return os.Chmod(target, walkinfo.Mode()|0777)
692 } else if walkinfo.Mode().IsDir() {
693 mkerr := os.MkdirAll(target, 0777)
697 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
699 return fmt.Errorf("source %q is not a regular file or directory", cp.src)
702 } else if st.Mode().IsRegular() {
703 err = copyfile(cp.src, cp.bind)
705 err = os.Chmod(cp.bind, st.Mode()|0777)
709 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
713 return bindmounts, nil
716 func (runner *ContainerRunner) stopHoststat() error {
717 if runner.hoststatReporter == nil {
720 runner.hoststatReporter.Stop()
721 err := runner.hoststatLogger.Close()
723 return fmt.Errorf("error closing hoststat logs: %v", err)
728 func (runner *ContainerRunner) startHoststat() error {
729 w, err := runner.NewLogWriter("hoststat")
733 runner.hoststatLogger = NewThrottledLogger(w)
734 runner.hoststatReporter = &crunchstat.Reporter{
735 Logger: log.New(runner.hoststatLogger, "", 0),
736 CgroupRoot: runner.cgroupRoot,
737 PollPeriod: runner.statInterval,
739 runner.hoststatReporter.Start()
740 runner.hoststatReporter.ReportPID("crunch-run", os.Getpid())
744 func (runner *ContainerRunner) startCrunchstat() error {
745 w, err := runner.NewLogWriter("crunchstat")
749 runner.statLogger = NewThrottledLogger(w)
750 runner.statReporter = &crunchstat.Reporter{
751 CID: runner.executor.CgroupID(),
752 Logger: log.New(runner.statLogger, "", 0),
753 CgroupParent: runner.expectCgroupParent,
754 CgroupRoot: runner.cgroupRoot,
755 PollPeriod: runner.statInterval,
756 TempDir: runner.parentTemp,
758 runner.statReporter.Start()
762 type infoCommand struct {
767 // LogHostInfo logs info about the current host, for debugging and
768 // accounting purposes. Although it's logged as "node-info", this is
769 // about the environment where crunch-run is actually running, which
770 // might differ from what's described in the node record (see
772 func (runner *ContainerRunner) LogHostInfo() (err error) {
773 w, err := runner.NewLogWriter("node-info")
778 commands := []infoCommand{
780 label: "Host Information",
781 cmd: []string{"uname", "-a"},
784 label: "CPU Information",
785 cmd: []string{"cat", "/proc/cpuinfo"},
788 label: "Memory Information",
789 cmd: []string{"cat", "/proc/meminfo"},
793 cmd: []string{"df", "-m", "/", os.TempDir()},
796 label: "Disk INodes",
797 cmd: []string{"df", "-i", "/", os.TempDir()},
801 // Run commands with informational output to be logged.
802 for _, command := range commands {
803 fmt.Fprintln(w, command.label)
804 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
807 if err := cmd.Run(); err != nil {
808 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
817 return fmt.Errorf("While closing node-info logs: %v", err)
822 // LogContainerRecord gets and saves the raw JSON container record from the API server
823 func (runner *ContainerRunner) LogContainerRecord() error {
824 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
825 if !logged && err == nil {
826 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
831 // LogNodeRecord logs the current host's InstanceType config entry (or
832 // the arvados#node record, if running via crunch-dispatch-slurm).
833 func (runner *ContainerRunner) LogNodeRecord() error {
834 if it := os.Getenv("InstanceType"); it != "" {
835 // Dispatched via arvados-dispatch-cloud. Save
836 // InstanceType config fragment received from
837 // dispatcher on stdin.
838 w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
843 _, err = io.WriteString(w, it)
849 // Dispatched via crunch-dispatch-slurm. Look up
850 // apiserver's node record corresponding to
852 hostname := os.Getenv("SLURMD_NODENAME")
854 hostname, _ = os.Hostname()
856 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
857 // The "info" field has admin-only info when
858 // obtained with a privileged token, and
859 // should not be logged.
860 node, ok := resp.(map[string]interface{})
868 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
869 writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
874 ArvClient: runner.DispatcherArvClient,
875 UUID: runner.Container.UUID,
876 loggingStream: label,
880 reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
882 return false, fmt.Errorf("error getting %s record: %v", label, err)
886 dec := json.NewDecoder(reader)
888 var resp map[string]interface{}
889 if err = dec.Decode(&resp); err != nil {
890 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
892 items, ok := resp["items"].([]interface{})
894 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
895 } else if len(items) < 1 {
901 // Re-encode it using indentation to improve readability
902 enc := json.NewEncoder(w)
903 enc.SetIndent("", " ")
904 if err = enc.Encode(items[0]); err != nil {
905 return false, fmt.Errorf("error logging %s record: %v", label, err)
909 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
914 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
915 stdoutPath := mntPath[len(runner.Container.OutputPath):]
916 index := strings.LastIndex(stdoutPath, "/")
918 subdirs := stdoutPath[:index]
920 st, err := os.Stat(runner.HostOutputDir)
922 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
924 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
925 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
927 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
931 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
933 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
936 return stdoutFile, nil
939 // CreateContainer creates the docker container.
940 func (runner *ContainerRunner) CreateContainer(imageID string, bindmounts map[string]bindmount) error {
941 var stdin io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
942 if mnt, ok := runner.Container.Mounts["stdin"]; ok {
949 collID = mnt.PortableDataHash
951 path := runner.ArvMountPoint + "/by_id/" + collID + "/" + mnt.Path
952 f, err := os.Open(path)
958 j, err := json.Marshal(mnt.Content)
960 return fmt.Errorf("error encoding stdin json data: %v", err)
962 stdin = ioutil.NopCloser(bytes.NewReader(j))
964 return fmt.Errorf("stdin mount has unsupported kind %q", mnt.Kind)
968 var stdout, stderr io.WriteCloser
969 if mnt, ok := runner.Container.Mounts["stdout"]; ok {
970 f, err := runner.getStdoutFile(mnt.Path)
975 } else if w, err := runner.NewLogWriter("stdout"); err != nil {
978 stdout = NewThrottledLogger(w)
981 if mnt, ok := runner.Container.Mounts["stderr"]; ok {
982 f, err := runner.getStdoutFile(mnt.Path)
987 } else if w, err := runner.NewLogWriter("stderr"); err != nil {
990 stderr = NewThrottledLogger(w)
993 env := runner.Container.Environment
994 enableNetwork := runner.enableNetwork == "always"
995 if runner.Container.RuntimeConstraints.API {
997 tok, err := runner.ContainerToken()
1001 env = map[string]string{}
1002 for k, v := range runner.Container.Environment {
1005 env["ARVADOS_API_TOKEN"] = tok
1006 env["ARVADOS_API_HOST"] = os.Getenv("ARVADOS_API_HOST")
1007 env["ARVADOS_API_HOST_INSECURE"] = os.Getenv("ARVADOS_API_HOST_INSECURE")
1008 env["ARVADOS_KEEP_SERVICES"] = os.Getenv("ARVADOS_KEEP_SERVICES")
1010 workdir := runner.Container.Cwd
1012 // both "" and "." mean default
1015 ram := runner.Container.RuntimeConstraints.RAM
1016 if !runner.enableMemoryLimit {
1019 runner.executorStdin = stdin
1020 runner.executorStdout = stdout
1021 runner.executorStderr = stderr
1023 if runner.Container.RuntimeConstraints.CUDA.DeviceCount > 0 {
1024 nvidiaModprobe(runner.CrunchLog)
1027 return runner.executor.Create(containerSpec{
1029 VCPUs: runner.Container.RuntimeConstraints.VCPUs,
1031 WorkingDir: workdir,
1033 BindMounts: bindmounts,
1034 Command: runner.Container.Command,
1035 EnableNetwork: enableNetwork,
1036 CUDADeviceCount: runner.Container.RuntimeConstraints.CUDA.DeviceCount,
1037 NetworkMode: runner.networkMode,
1038 CgroupParent: runner.setCgroupParent,
1045 // StartContainer starts the docker container created by CreateContainer.
1046 func (runner *ContainerRunner) StartContainer() error {
1047 runner.CrunchLog.Printf("Starting container")
1048 runner.cStateLock.Lock()
1049 defer runner.cStateLock.Unlock()
1050 if runner.cCancelled {
1053 err := runner.executor.Start()
1056 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1057 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])
1059 return fmt.Errorf("could not start container: %v%s", err, advice)
1064 // WaitFinish waits for the container to terminate, capture the exit code, and
1065 // close the stdout/stderr logging.
1066 func (runner *ContainerRunner) WaitFinish() error {
1067 runner.CrunchLog.Print("Waiting for container to finish")
1068 var timeout <-chan time.Time
1069 if s := runner.Container.SchedulingParameters.MaxRunTime; s > 0 {
1070 timeout = time.After(time.Duration(s) * time.Second)
1072 ctx, cancel := context.WithCancel(context.Background())
1077 runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1079 case <-runner.ArvMountExit:
1080 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1085 exitcode, err := runner.executor.Wait(ctx)
1087 runner.checkBrokenNode(err)
1090 runner.ExitCode = &exitcode
1093 if exitcode&0x80 != 0 {
1094 // Convert raw exit status (0x80 + signal number) to a
1095 // string to log after the code, like " (signal 101)"
1096 // or " (signal 9, killed)"
1097 sig := syscall.WaitStatus(exitcode).Signal()
1098 if name := unix.SignalName(sig); name != "" {
1099 extra = fmt.Sprintf(" (signal %d, %s)", sig, name)
1101 extra = fmt.Sprintf(" (signal %d)", sig)
1104 runner.CrunchLog.Printf("Container exited with status code %d%s", exitcode, extra)
1105 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1106 "container": arvadosclient.Dict{"exit_code": exitcode},
1109 runner.CrunchLog.Printf("ignoring error updating exit_code: %s", err)
1113 if err = runner.executorStdin.Close(); err != nil {
1114 err = fmt.Errorf("error closing container stdin: %s", err)
1115 runner.CrunchLog.Printf("%s", err)
1118 if err = runner.executorStdout.Close(); err != nil {
1119 err = fmt.Errorf("error closing container stdout: %s", err)
1120 runner.CrunchLog.Printf("%s", err)
1121 if returnErr == nil {
1125 if err = runner.executorStderr.Close(); err != nil {
1126 err = fmt.Errorf("error closing container stderr: %s", err)
1127 runner.CrunchLog.Printf("%s", err)
1128 if returnErr == nil {
1133 if runner.statReporter != nil {
1134 runner.statReporter.Stop()
1135 err = runner.statLogger.Close()
1137 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
1143 func (runner *ContainerRunner) updateLogs() {
1144 ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1147 sigusr1 := make(chan os.Signal, 1)
1148 signal.Notify(sigusr1, syscall.SIGUSR1)
1149 defer signal.Stop(sigusr1)
1151 saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1152 saveAtSize := crunchLogUpdateSize
1158 saveAtTime = time.Now()
1160 runner.logMtx.Lock()
1161 done := runner.LogsPDH != nil
1162 runner.logMtx.Unlock()
1166 size := runner.LogCollection.Size()
1167 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1170 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1171 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1172 saved, err := runner.saveLogCollection(false)
1174 runner.CrunchLog.Printf("error updating log collection: %s", err)
1178 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1179 "container": arvadosclient.Dict{"log": saved.PortableDataHash},
1182 runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1190 func (runner *ContainerRunner) reportArvMountWarning(pattern, text string) {
1191 var updated arvados.Container
1192 err := runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1193 "container": arvadosclient.Dict{
1194 "runtime_status": arvadosclient.Dict{
1195 "warning": "arv-mount: " + pattern,
1196 "warningDetail": text,
1201 runner.CrunchLog.Printf("error updating container runtime_status: %s", err)
1205 // CaptureOutput saves data from the container's output directory if
1206 // needed, and updates the container output accordingly.
1207 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1208 if runner.Container.RuntimeConstraints.API {
1209 // Output may have been set directly by the container, so
1210 // refresh the container record to check.
1211 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1212 nil, &runner.Container)
1216 if runner.Container.Output != "" {
1217 // Container output is already set.
1218 runner.OutputPDH = &runner.Container.Output
1223 txt, err := (&copier{
1224 client: runner.containerClient,
1225 arvClient: runner.ContainerArvClient,
1226 keepClient: runner.ContainerKeepClient,
1227 hostOutputDir: runner.HostOutputDir,
1228 ctrOutputDir: runner.Container.OutputPath,
1229 bindmounts: bindmounts,
1230 mounts: runner.Container.Mounts,
1231 secretMounts: runner.SecretMounts,
1232 logger: runner.CrunchLog,
1237 if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1238 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1239 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1243 txt, err = fs.MarshalManifest(".")
1248 var resp arvados.Collection
1249 err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1250 "ensure_unique_name": true,
1251 "collection": arvadosclient.Dict{
1253 "name": "output for " + runner.Container.UUID,
1254 "manifest_text": txt,
1258 return fmt.Errorf("error creating output collection: %v", err)
1260 runner.OutputPDH = &resp.PortableDataHash
1264 func (runner *ContainerRunner) CleanupDirs() {
1265 if runner.ArvMount != nil {
1267 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1268 umount.Stdout = runner.CrunchLog
1269 umount.Stderr = runner.CrunchLog
1270 runner.CrunchLog.Printf("Running %v", umount.Args)
1271 umnterr := umount.Start()
1274 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1275 runner.ArvMount.Process.Kill()
1277 // If arv-mount --unmount gets stuck for any reason, we
1278 // don't want to wait for it forever. Do Wait() in a goroutine
1279 // so it doesn't block crunch-run.
1280 umountExit := make(chan error)
1282 mnterr := umount.Wait()
1284 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1286 umountExit <- mnterr
1289 for again := true; again; {
1295 case <-runner.ArvMountExit:
1297 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1298 runner.CrunchLog.Printf("Timed out waiting for unmount")
1300 umount.Process.Kill()
1302 runner.ArvMount.Process.Kill()
1306 runner.ArvMount = nil
1309 if runner.ArvMountPoint != "" {
1310 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1311 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1313 runner.ArvMountPoint = ""
1316 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1317 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1321 // CommitLogs posts the collection containing the final container logs.
1322 func (runner *ContainerRunner) CommitLogs() error {
1324 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1325 runner.cStateLock.Lock()
1326 defer runner.cStateLock.Unlock()
1328 runner.CrunchLog.Print(runner.finalState)
1330 if runner.arvMountLog != nil {
1331 runner.arvMountLog.Close()
1333 runner.CrunchLog.Close()
1335 // Closing CrunchLog above allows them to be committed to Keep at this
1336 // point, but re-open crunch log with ArvClient in case there are any
1337 // other further errors (such as failing to write the log to Keep!)
1338 // while shutting down
1339 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1340 ArvClient: runner.DispatcherArvClient,
1341 UUID: runner.Container.UUID,
1342 loggingStream: "crunch-run",
1345 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1348 if runner.keepstoreLogger != nil {
1349 // Flush any buffered logs from our local keepstore
1350 // process. Discard anything logged after this point
1351 // -- it won't end up in the log collection, so
1352 // there's no point writing it to the collectionfs.
1353 runner.keepstoreLogbuf.SetWriter(io.Discard)
1354 runner.keepstoreLogger.Close()
1355 runner.keepstoreLogger = nil
1358 if runner.LogsPDH != nil {
1359 // If we have already assigned something to LogsPDH,
1360 // we must be closing the re-opened log, which won't
1361 // end up getting attached to the container record and
1362 // therefore doesn't need to be saved as a collection
1363 // -- it exists only to send logs to other channels.
1367 saved, err := runner.saveLogCollection(true)
1369 return fmt.Errorf("error saving log collection: %s", err)
1371 runner.logMtx.Lock()
1372 defer runner.logMtx.Unlock()
1373 runner.LogsPDH = &saved.PortableDataHash
1377 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1378 runner.logMtx.Lock()
1379 defer runner.logMtx.Unlock()
1380 if runner.LogsPDH != nil {
1381 // Already finalized.
1384 updates := arvadosclient.Dict{
1385 "name": "logs for " + runner.Container.UUID,
1387 mt, err1 := runner.LogCollection.MarshalManifest(".")
1389 // Only send updated manifest text if there was no
1391 updates["manifest_text"] = mt
1394 // Even if flushing the manifest had an error, we still want
1395 // to update the log record, if possible, to push the trash_at
1396 // and delete_at times into the future. Details on bug
1399 updates["is_trashed"] = true
1401 exp := time.Now().Add(crunchLogUpdatePeriod * 24)
1402 updates["trash_at"] = exp
1403 updates["delete_at"] = exp
1405 reqBody := arvadosclient.Dict{"collection": updates}
1407 if runner.logUUID == "" {
1408 reqBody["ensure_unique_name"] = true
1409 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1411 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1414 runner.logUUID = response.UUID
1417 if err1 != nil || err2 != nil {
1418 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1423 // UpdateContainerRunning updates the container state to "Running"
1424 func (runner *ContainerRunner) UpdateContainerRunning() error {
1425 runner.cStateLock.Lock()
1426 defer runner.cStateLock.Unlock()
1427 if runner.cCancelled {
1430 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID,
1431 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running", "gateway_address": runner.gateway.Address}}, nil)
1434 // ContainerToken returns the api_token the container (and any
1435 // arv-mount processes) are allowed to use.
1436 func (runner *ContainerRunner) ContainerToken() (string, error) {
1437 if runner.token != "" {
1438 return runner.token, nil
1441 var auth arvados.APIClientAuthorization
1442 err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1446 runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1447 return runner.token, nil
1450 // UpdateContainerFinal updates the container record state on API
1451 // server to "Complete" or "Cancelled"
1452 func (runner *ContainerRunner) UpdateContainerFinal() error {
1453 update := arvadosclient.Dict{}
1454 update["state"] = runner.finalState
1455 if runner.LogsPDH != nil {
1456 update["log"] = *runner.LogsPDH
1458 if runner.ExitCode != nil {
1459 update["exit_code"] = *runner.ExitCode
1461 update["exit_code"] = nil
1463 if runner.finalState == "Complete" && runner.OutputPDH != nil {
1464 update["output"] = *runner.OutputPDH
1466 var it arvados.InstanceType
1467 if j := os.Getenv("InstanceType"); j != "" && json.Unmarshal([]byte(j), &it) == nil && it.Price > 0 {
1468 update["cost"] = it.Price * time.Now().Sub(runner.costStartTime).Seconds() / time.Hour.Seconds()
1470 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1473 // IsCancelled returns the value of Cancelled, with goroutine safety.
1474 func (runner *ContainerRunner) IsCancelled() bool {
1475 runner.cStateLock.Lock()
1476 defer runner.cStateLock.Unlock()
1477 return runner.cCancelled
1480 // NewArvLogWriter creates an ArvLogWriter
1481 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1482 writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1486 return &ArvLogWriter{
1487 ArvClient: runner.DispatcherArvClient,
1488 UUID: runner.Container.UUID,
1489 loggingStream: name,
1490 writeCloser: writer,
1494 // Run the full container lifecycle.
1495 func (runner *ContainerRunner) Run() (err error) {
1496 runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1497 runner.CrunchLog.Printf("%s", currentUserAndGroups())
1498 v, _ := exec.Command("arv-mount", "--version").CombinedOutput()
1499 runner.CrunchLog.Printf("Using FUSE mount: %s", v)
1500 runner.CrunchLog.Printf("Using container runtime: %s", runner.executor.Runtime())
1501 runner.CrunchLog.Printf("Executing container: %s", runner.Container.UUID)
1502 runner.costStartTime = time.Now()
1504 hostname, hosterr := os.Hostname()
1506 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1508 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1511 runner.finalState = "Queued"
1514 runner.CleanupDirs()
1516 runner.CrunchLog.Printf("crunch-run finished")
1517 runner.CrunchLog.Close()
1520 err = runner.fetchContainerRecord()
1524 if runner.Container.State != "Locked" {
1525 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1528 var bindmounts map[string]bindmount
1530 // checkErr prints e (unless it's nil) and sets err to
1531 // e (unless err is already non-nil). Thus, if err
1532 // hasn't already been assigned when Run() returns,
1533 // this cleanup func will cause Run() to return the
1534 // first non-nil error that is passed to checkErr().
1535 checkErr := func(errorIn string, e error) {
1539 runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1543 if runner.finalState == "Complete" {
1544 // There was an error in the finalization.
1545 runner.finalState = "Cancelled"
1549 // Log the error encountered in Run(), if any
1550 checkErr("Run", err)
1552 if runner.finalState == "Queued" {
1553 runner.UpdateContainerFinal()
1557 if runner.IsCancelled() {
1558 runner.finalState = "Cancelled"
1559 // but don't return yet -- we still want to
1560 // capture partial output and write logs
1563 if bindmounts != nil {
1564 checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1566 checkErr("stopHoststat", runner.stopHoststat())
1567 checkErr("CommitLogs", runner.CommitLogs())
1568 runner.CleanupDirs()
1569 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1572 runner.setupSignals()
1573 err = runner.startHoststat()
1577 if runner.keepstore != nil {
1578 runner.hoststatReporter.ReportPID("keepstore", runner.keepstore.Process.Pid)
1581 // set up FUSE mount and binds
1582 bindmounts, err = runner.SetupMounts()
1584 runner.finalState = "Cancelled"
1585 err = fmt.Errorf("While setting up mounts: %v", err)
1589 // check for and/or load image
1590 imageID, err := runner.LoadImage()
1592 if !runner.checkBrokenNode(err) {
1593 // Failed to load image but not due to a "broken node"
1594 // condition, probably user error.
1595 runner.finalState = "Cancelled"
1597 err = fmt.Errorf("While loading container image: %v", err)
1601 err = runner.CreateContainer(imageID, bindmounts)
1605 err = runner.LogHostInfo()
1609 err = runner.LogNodeRecord()
1613 err = runner.LogContainerRecord()
1618 if runner.IsCancelled() {
1622 err = runner.UpdateContainerRunning()
1626 runner.finalState = "Cancelled"
1628 err = 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.DispatcherArvClient.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)
1663 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1666 containerToken, err := runner.ContainerToken()
1668 return fmt.Errorf("error getting container token: %v", err)
1671 runner.ContainerArvClient, runner.ContainerKeepClient,
1672 runner.containerClient, err = runner.MkArvClient(containerToken)
1674 return fmt.Errorf("error creating container API client: %v", err)
1677 runner.ContainerKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1678 runner.DispatcherKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1680 err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1682 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1683 return fmt.Errorf("error fetching secret_mounts: %v", err)
1685 // ok && apierr.HttpStatusCode == 404, which means
1686 // secret_mounts isn't supported by this API server.
1688 runner.SecretMounts = sm.SecretMounts
1693 // NewContainerRunner creates a new container runner.
1694 func NewContainerRunner(dispatcherClient *arvados.Client,
1695 dispatcherArvClient IArvadosClient,
1696 dispatcherKeepClient IKeepClient,
1697 containerUUID string) (*ContainerRunner, error) {
1699 cr := &ContainerRunner{
1700 dispatcherClient: dispatcherClient,
1701 DispatcherArvClient: dispatcherArvClient,
1702 DispatcherKeepClient: dispatcherKeepClient,
1704 cr.NewLogWriter = cr.NewArvLogWriter
1705 cr.RunArvMount = cr.ArvMountCmd
1706 cr.MkTempDir = ioutil.TempDir
1707 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1708 cl, err := arvadosclient.MakeArvadosClient()
1710 return nil, nil, nil, err
1713 kc, err := keepclient.MakeKeepClient(cl)
1715 return nil, nil, nil, err
1717 c2 := arvados.NewClientFromEnv()
1718 c2.AuthToken = token
1719 return cl, kc, c2, nil
1722 cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1726 cr.Container.UUID = containerUUID
1727 w, err := cr.NewLogWriter("crunch-run")
1731 cr.CrunchLog = NewThrottledLogger(w)
1732 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1734 loadLogThrottleParams(dispatcherArvClient)
1740 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1741 log := log.New(stderr, "", 0)
1742 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1743 statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1744 cgroupRoot := flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1745 cgroupParent := flags.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1746 cgroupParentSubsystem := flags.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1747 caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1748 detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1749 stdinConfig := flags.Bool("stdin-config", false, "Load config and environment variables from JSON message on stdin")
1750 configFile := flags.String("config", arvados.DefaultConfigFile, "filename of cluster config file to try loading if -stdin-config=false (default is $ARVADOS_CONFIG)")
1751 sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1752 kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1753 list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes")
1754 enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1755 enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1756 networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1757 memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1758 runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1759 brokenNodeHook := flags.String("broken-node-hook", "", "script to run if node is detected to be broken (for example, Docker daemon is not running)")
1760 flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1761 version := flags.Bool("version", false, "Write version information to stdout and exit 0.")
1763 ignoreDetachFlag := false
1764 if len(args) > 0 && args[0] == "-no-detach" {
1765 // This process was invoked by a parent process, which
1766 // has passed along its own arguments, including
1767 // -detach, after the leading -no-detach flag. Strip
1768 // the leading -no-detach flag (it's not recognized by
1769 // flags.Parse()) and ignore the -detach flag that
1772 ignoreDetachFlag = true
1775 if ok, code := cmd.ParseFlags(flags, prog, args, "container-uuid", stderr); !ok {
1777 } else if *version {
1778 fmt.Fprintln(stdout, prog, cmd.Version.String())
1780 } else if !*list && flags.NArg() != 1 {
1781 fmt.Fprintf(stderr, "missing required argument: container-uuid (try -help)\n")
1785 containerUUID := flags.Arg(0)
1788 case *detach && !ignoreDetachFlag:
1789 return Detach(containerUUID, prog, args, os.Stdin, os.Stdout, os.Stderr)
1791 return KillProcess(containerUUID, syscall.Signal(*kill), os.Stdout, os.Stderr)
1793 return ListProcesses(os.Stdout, os.Stderr)
1796 if len(containerUUID) != 27 {
1797 log.Printf("usage: %s [options] UUID", prog)
1801 var keepstoreLogbuf bufThenWrite
1804 err := json.NewDecoder(stdin).Decode(&conf)
1806 log.Printf("decode stdin: %s", err)
1809 for k, v := range conf.Env {
1810 err = os.Setenv(k, v)
1812 log.Printf("setenv(%q): %s", k, err)
1816 if conf.Cluster != nil {
1817 // ClusterID is missing from the JSON
1818 // representation, but we need it to generate
1819 // a valid config file for keepstore, so we
1820 // fill it using the container UUID prefix.
1821 conf.Cluster.ClusterID = containerUUID[:5]
1824 conf = hpcConfData(containerUUID, *configFile, io.MultiWriter(&keepstoreLogbuf, stderr))
1827 log.Printf("crunch-run %s started", cmd.Version.String())
1830 if *caCertsPath != "" {
1831 arvadosclient.CertFiles = []string{*caCertsPath}
1834 keepstore, err := startLocalKeepstore(conf, io.MultiWriter(&keepstoreLogbuf, stderr))
1839 if keepstore != nil {
1840 defer keepstore.Process.Kill()
1843 api, err := arvadosclient.MakeArvadosClient()
1845 log.Printf("%s: %v", containerUUID, err)
1850 kc, err := keepclient.MakeKeepClient(api)
1852 log.Printf("%s: %v", containerUUID, err)
1855 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1858 cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
1864 cr.keepstore = keepstore
1865 if keepstore == nil {
1866 // Log explanation (if any) for why we're not running
1867 // a local keepstore.
1868 var buf bytes.Buffer
1869 keepstoreLogbuf.SetWriter(&buf)
1871 cr.CrunchLog.Printf("%s", strings.TrimSpace(buf.String()))
1873 } else if logWhat := conf.Cluster.Containers.LocalKeepLogsToContainerLog; logWhat == "none" {
1874 cr.CrunchLog.Printf("using local keepstore process (pid %d) at %s", keepstore.Process.Pid, os.Getenv("ARVADOS_KEEP_SERVICES"))
1875 keepstoreLogbuf.SetWriter(io.Discard)
1877 cr.CrunchLog.Printf("using local keepstore process (pid %d) at %s, writing logs to keepstore.txt in log collection", keepstore.Process.Pid, os.Getenv("ARVADOS_KEEP_SERVICES"))
1878 logwriter, err := cr.NewLogWriter("keepstore")
1883 cr.keepstoreLogger = NewThrottledLogger(logwriter)
1885 var writer io.WriteCloser = cr.keepstoreLogger
1886 if logWhat == "errors" {
1887 writer = &filterKeepstoreErrorsOnly{WriteCloser: writer}
1888 } else if logWhat != "all" {
1889 // should have been caught earlier by
1890 // dispatcher's config loader
1891 log.Printf("invalid value for Containers.LocalKeepLogsToContainerLog: %q", logWhat)
1894 err = keepstoreLogbuf.SetWriter(writer)
1899 cr.keepstoreLogbuf = &keepstoreLogbuf
1902 switch *runtimeEngine {
1904 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
1906 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
1908 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
1909 cr.CrunchLog.Close()
1913 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
1914 cr.checkBrokenNode(err)
1915 cr.CrunchLog.Close()
1918 defer cr.executor.Close()
1920 cr.brokenNodeHook = *brokenNodeHook
1922 gwAuthSecret := os.Getenv("GatewayAuthSecret")
1923 os.Unsetenv("GatewayAuthSecret")
1924 if gwAuthSecret == "" {
1925 // not safe to run a gateway service without an auth
1927 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAuthSecret was not provided by dispatcher)")
1929 gwListen := os.Getenv("GatewayAddress")
1930 cr.gateway = Gateway{
1932 AuthSecret: gwAuthSecret,
1933 ContainerUUID: containerUUID,
1934 Target: cr.executor,
1938 // Direct connection won't work, so we use the
1939 // gateway_address field to indicate the
1940 // internalURL of the controller process that
1941 // has the current tunnel connection.
1942 cr.gateway.ArvadosClient = cr.dispatcherClient
1943 cr.gateway.UpdateTunnelURL = func(url string) {
1944 cr.gateway.Address = "tunnel " + url
1945 cr.DispatcherArvClient.Update("containers", containerUUID,
1946 arvadosclient.Dict{"container": arvadosclient.Dict{"gateway_address": cr.gateway.Address}}, nil)
1949 err = cr.gateway.Start()
1951 log.Printf("error starting gateway server: %s", err)
1956 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
1958 log.Printf("%s: %v", containerUUID, tmperr)
1962 cr.parentTemp = parentTemp
1963 cr.statInterval = *statInterval
1964 cr.cgroupRoot = *cgroupRoot
1965 cr.expectCgroupParent = *cgroupParent
1966 cr.enableMemoryLimit = *enableMemoryLimit
1967 cr.enableNetwork = *enableNetwork
1968 cr.networkMode = *networkMode
1969 if *cgroupParentSubsystem != "" {
1970 p, err := findCgroup(*cgroupParentSubsystem)
1972 log.Printf("fatal: cgroup parent subsystem: %s", err)
1975 cr.setCgroupParent = p
1976 cr.expectCgroupParent = p
1981 if *memprofile != "" {
1982 f, err := os.Create(*memprofile)
1984 log.Printf("could not create memory profile: %s", err)
1986 runtime.GC() // get up-to-date statistics
1987 if err := pprof.WriteHeapProfile(f); err != nil {
1988 log.Printf("could not write memory profile: %s", err)
1990 closeerr := f.Close()
1991 if closeerr != nil {
1992 log.Printf("closing memprofile file: %s", err)
1997 log.Printf("%s: %v", containerUUID, runerr)
2003 // Try to load ConfigData in hpc (slurm/lsf) environment. This means
2004 // loading the cluster config from the specified file and (if that
2005 // works) getting the runtime_constraints container field from
2006 // controller to determine # VCPUs so we can calculate KeepBuffers.
2007 func hpcConfData(uuid string, configFile string, stderr io.Writer) ConfigData {
2009 conf.Cluster = loadClusterConfigFile(configFile, stderr)
2010 if conf.Cluster == nil {
2011 // skip loading the container record -- we won't be
2012 // able to start local keepstore anyway.
2015 arv, err := arvadosclient.MakeArvadosClient()
2017 fmt.Fprintf(stderr, "error setting up arvadosclient: %s\n", err)
2021 var ctr arvados.Container
2022 err = arv.Call("GET", "containers", uuid, "", arvadosclient.Dict{"select": []string{"runtime_constraints"}}, &ctr)
2024 fmt.Fprintf(stderr, "error getting container record: %s\n", err)
2027 if ctr.RuntimeConstraints.VCPUs > 0 {
2028 conf.KeepBuffers = ctr.RuntimeConstraints.VCPUs * conf.Cluster.Containers.LocalKeepBlobBuffersPerVCPU
2033 // Load cluster config file from given path. If an error occurs, log
2034 // the error to stderr and return nil.
2035 func loadClusterConfigFile(path string, stderr io.Writer) *arvados.Cluster {
2036 ldr := config.NewLoader(&bytes.Buffer{}, ctxlog.New(stderr, "plain", "info"))
2038 cfg, err := ldr.Load()
2040 fmt.Fprintf(stderr, "could not load config file %s: %s\n", path, err)
2043 cluster, err := cfg.GetCluster("")
2045 fmt.Fprintf(stderr, "could not use config file %s: %s\n", path, err)
2048 fmt.Fprintf(stderr, "loaded config file %s\n", path)
2052 func startLocalKeepstore(configData ConfigData, logbuf io.Writer) (*exec.Cmd, error) {
2053 if configData.KeepBuffers < 1 {
2054 fmt.Fprintf(logbuf, "not starting a local keepstore process because KeepBuffers=%v in config\n", configData.KeepBuffers)
2057 if configData.Cluster == nil {
2058 fmt.Fprint(logbuf, "not starting a local keepstore process because cluster config file was not loaded\n")
2061 for uuid, vol := range configData.Cluster.Volumes {
2062 if len(vol.AccessViaHosts) > 0 {
2063 fmt.Fprintf(logbuf, "not starting a local keepstore process because a volume (%s) uses AccessViaHosts\n", uuid)
2066 if !vol.ReadOnly && vol.Replication < configData.Cluster.Collections.DefaultReplication {
2067 fmt.Fprintf(logbuf, "not starting a local keepstore process because a writable volume (%s) has replication less than Collections.DefaultReplication (%d < %d)\n", uuid, vol.Replication, configData.Cluster.Collections.DefaultReplication)
2072 // Rather than have an alternate way to tell keepstore how
2073 // many buffers to use when starting it this way, we just
2074 // modify the cluster configuration that we feed it on stdin.
2075 configData.Cluster.API.MaxKeepBlobBuffers = configData.KeepBuffers
2077 localaddr := localKeepstoreAddr()
2078 ln, err := net.Listen("tcp", net.JoinHostPort(localaddr, "0"))
2082 _, port, err := net.SplitHostPort(ln.Addr().String())
2088 url := "http://" + net.JoinHostPort(localaddr, port)
2090 fmt.Fprintf(logbuf, "starting keepstore on %s\n", url)
2092 var confJSON bytes.Buffer
2093 err = json.NewEncoder(&confJSON).Encode(arvados.Config{
2094 Clusters: map[string]arvados.Cluster{
2095 configData.Cluster.ClusterID: *configData.Cluster,
2101 cmd := exec.Command("/proc/self/exe", "keepstore", "-config=-")
2102 if target, err := os.Readlink(cmd.Path); err == nil && strings.HasSuffix(target, ".test") {
2103 // If we're a 'go test' process, running
2104 // /proc/self/exe would start the test suite in a
2105 // child process, which is not what we want.
2106 cmd.Path, _ = exec.LookPath("go")
2107 cmd.Args = append([]string{"go", "run", "../../cmd/arvados-server"}, cmd.Args[1:]...)
2108 cmd.Env = os.Environ()
2110 cmd.Stdin = &confJSON
2113 cmd.Env = append(cmd.Env,
2115 "ARVADOS_SERVICE_INTERNAL_URL="+url)
2118 return nil, fmt.Errorf("error starting keepstore process: %w", err)
2125 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10))
2127 poll := time.NewTicker(time.Second / 10)
2129 client := http.Client{}
2131 testReq, err := http.NewRequestWithContext(ctx, "GET", url+"/_health/ping", nil)
2132 testReq.Header.Set("Authorization", "Bearer "+configData.Cluster.ManagementToken)
2136 resp, err := client.Do(testReq)
2139 if resp.StatusCode == http.StatusOK {
2144 return nil, fmt.Errorf("keepstore child process exited")
2146 if ctx.Err() != nil {
2147 return nil, fmt.Errorf("timed out waiting for new keepstore process to report healthy")
2150 os.Setenv("ARVADOS_KEEP_SERVICES", url)
2154 // return current uid, gid, groups in a format suitable for logging:
2155 // "crunch-run process has uid=1234(arvados) gid=1234(arvados)
2156 // groups=1234(arvados),114(fuse)"
2157 func currentUserAndGroups() string {
2158 u, err := user.Current()
2160 return fmt.Sprintf("error getting current user ID: %s", err)
2162 s := fmt.Sprintf("crunch-run process has uid=%s(%s) gid=%s", u.Uid, u.Username, u.Gid)
2163 if g, err := user.LookupGroupId(u.Gid); err == nil {
2164 s += fmt.Sprintf("(%s)", g.Name)
2167 if gids, err := u.GroupIds(); err == nil {
2168 for i, gid := range gids {
2173 if g, err := user.LookupGroupId(gid); err == nil {
2174 s += fmt.Sprintf("(%s)", g.Name)
2181 // Return a suitable local interface address for a local keepstore
2182 // service. Currently this is the numerically lowest non-loopback ipv4
2183 // address assigned to a local interface that is not in any of the
2184 // link-local/vpn/loopback ranges 169.254/16, 100.64/10, or 127/8.
2185 func localKeepstoreAddr() string {
2187 // Ignore error (proceed with zero IPs)
2188 addrs, _ := processIPs(os.Getpid())
2189 for addr := range addrs {
2190 ip := net.ParseIP(addr)
2195 if ip.Mask(net.CIDRMask(8, 32)).Equal(net.IPv4(127, 0, 0, 0)) ||
2196 ip.Mask(net.CIDRMask(10, 32)).Equal(net.IPv4(100, 64, 0, 0)) ||
2197 ip.Mask(net.CIDRMask(16, 32)).Equal(net.IPv4(169, 254, 0, 0)) {
2201 ips = append(ips, ip)
2206 sort.Slice(ips, func(ii, jj int) bool {
2207 i, j := ips[ii], ips[jj]
2208 if len(i) != len(j) {
2209 return len(i) < len(j)
2218 return ips[0].String()