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
145 keepstoreLogger io.WriteCloser
146 keepstoreLogbuf *bufThenWrite
147 statLogger io.WriteCloser
148 statReporter *crunchstat.Reporter
149 hoststatLogger io.WriteCloser
150 hoststatReporter *crunchstat.Reporter
151 statInterval time.Duration
153 // What we expect the container's cgroup parent to be.
154 expectCgroupParent string
155 // What we tell docker to use as the container's cgroup
156 // parent. Note: Ideally we would use the same field for both
157 // expectCgroupParent and setCgroupParent, and just make it
158 // default to "docker". However, when using docker < 1.10 with
159 // systemd, specifying a non-empty cgroup parent (even the
160 // default value "docker") hits a docker bug
161 // (https://github.com/docker/docker/issues/17126). Using two
162 // separate fields makes it possible to use the "expect cgroup
163 // parent to be X" feature even on sites where the "specify
164 // cgroup parent" feature breaks.
165 setCgroupParent string
167 cStateLock sync.Mutex
168 cCancelled bool // StopContainer() invoked
170 enableMemoryLimit bool
171 enableNetwork string // one of "default" or "always"
172 networkMode string // "none", "host", or "" -- passed through to executor
173 brokenNodeHook string // script to run if node appears to be broken
174 arvMountLog *ThrottledLogger
176 containerWatchdogInterval time.Duration
181 // setupSignals sets up signal handling to gracefully terminate the
182 // underlying container and update state when receiving a TERM, INT or
184 func (runner *ContainerRunner) setupSignals() {
185 runner.SigChan = make(chan os.Signal, 1)
186 signal.Notify(runner.SigChan, syscall.SIGTERM)
187 signal.Notify(runner.SigChan, syscall.SIGINT)
188 signal.Notify(runner.SigChan, syscall.SIGQUIT)
190 go func(sig chan os.Signal) {
197 // stop the underlying container.
198 func (runner *ContainerRunner) stop(sig os.Signal) {
199 runner.cStateLock.Lock()
200 defer runner.cStateLock.Unlock()
202 runner.CrunchLog.Printf("caught signal: %v", sig)
204 runner.cCancelled = true
205 runner.CrunchLog.Printf("stopping container")
206 err := runner.executor.Stop()
208 runner.CrunchLog.Printf("error stopping container: %s", err)
212 var errorBlacklist = []string{
213 "(?ms).*[Cc]annot connect to the Docker daemon.*",
214 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
215 "(?ms).*grpc: the connection is unavailable.*",
218 func (runner *ContainerRunner) runBrokenNodeHook() {
219 if runner.brokenNodeHook == "" {
220 path := filepath.Join(lockdir, brokenfile)
221 runner.CrunchLog.Printf("Writing %s to mark node as broken", path)
222 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0700)
224 runner.CrunchLog.Printf("Error writing %s: %s", path, err)
229 runner.CrunchLog.Printf("Running broken node hook %q", runner.brokenNodeHook)
231 c := exec.Command(runner.brokenNodeHook)
232 c.Stdout = runner.CrunchLog
233 c.Stderr = runner.CrunchLog
236 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
241 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
242 for _, d := range errorBlacklist {
243 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
244 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
245 runner.runBrokenNodeHook()
252 // LoadImage determines the docker image id from the container record and
253 // checks if it is available in the local Docker image store. If not, it loads
254 // the image from Keep.
255 func (runner *ContainerRunner) LoadImage() (string, error) {
256 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
258 d, err := os.Open(runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage)
263 allfiles, err := d.Readdirnames(-1)
267 var tarfiles []string
268 for _, fnm := range allfiles {
269 if strings.HasSuffix(fnm, ".tar") {
270 tarfiles = append(tarfiles, fnm)
273 if len(tarfiles) == 0 {
274 return "", fmt.Errorf("image collection does not include a .tar image file")
276 if len(tarfiles) > 1 {
277 return "", fmt.Errorf("cannot choose from multiple tar files in image collection: %v", tarfiles)
279 imageID := tarfiles[0][:len(tarfiles[0])-4]
280 imageTarballPath := runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage + "/" + imageID + ".tar"
281 runner.CrunchLog.Printf("Using Docker image id %q", imageID)
283 runner.CrunchLog.Print("Loading Docker image from keep")
284 err = runner.executor.LoadImage(imageID, imageTarballPath, runner.Container, runner.ArvMountPoint,
285 runner.containerClient)
293 func (runner *ContainerRunner) ArvMountCmd(cmdline []string, token string) (c *exec.Cmd, err error) {
294 c = exec.Command(cmdline[0], cmdline[1:]...)
296 // Copy our environment, but override ARVADOS_API_TOKEN with
297 // the container auth token.
299 for _, s := range os.Environ() {
300 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
301 c.Env = append(c.Env, s)
304 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
306 w, err := runner.NewLogWriter("arv-mount")
310 runner.arvMountLog = NewThrottledLogger(w)
311 scanner := logScanner{
314 "Block not found error",
315 "Unhandled exception during FUSE operation",
317 ReportFunc: runner.reportArvMountWarning,
319 c.Stdout = runner.arvMountLog
320 c.Stderr = io.MultiWriter(runner.arvMountLog, os.Stderr, &scanner)
322 runner.CrunchLog.Printf("Running %v", c.Args)
329 statReadme := make(chan bool)
330 runner.ArvMountExit = make(chan error)
335 time.Sleep(100 * time.Millisecond)
336 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
348 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
350 runner.ArvMountExit <- mnterr
351 close(runner.ArvMountExit)
357 case err := <-runner.ArvMountExit:
358 runner.ArvMount = nil
366 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
367 if runner.ArvMountPoint == "" {
368 runner.ArvMountPoint, err = runner.MkTempDir(runner.parentTemp, prefix)
373 func copyfile(src string, dst string) (err error) {
374 srcfile, err := os.Open(src)
379 os.MkdirAll(path.Dir(dst), 0777)
381 dstfile, err := os.Create(dst)
385 _, err = io.Copy(dstfile, srcfile)
390 err = srcfile.Close()
391 err2 := dstfile.Close()
404 func (runner *ContainerRunner) SetupMounts() (map[string]bindmount, error) {
405 bindmounts := map[string]bindmount{}
406 err := runner.SetupArvMountPoint("keep")
408 return nil, fmt.Errorf("While creating keep mount temp dir: %v", err)
411 token, err := runner.ContainerToken()
413 return nil, fmt.Errorf("could not get container token: %s", err)
415 runner.CrunchLog.Printf("container token %q", token)
419 arvMountCmd := []string{
423 "--storage-classes", strings.Join(runner.Container.OutputStorageClasses, ","),
424 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
426 if _, isdocker := runner.executor.(*dockerExecutor); isdocker {
427 arvMountCmd = append(arvMountCmd, "--allow-other")
430 if runner.Container.RuntimeConstraints.KeepCacheDisk > 0 {
431 keepcachedir, err := runner.MkTempDir(runner.parentTemp, "keepcache")
433 return nil, fmt.Errorf("while creating keep cache temp dir: %v", err)
435 arvMountCmd = append(arvMountCmd, "--disk-cache", "--disk-cache-dir", keepcachedir, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheDisk))
436 } else if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
437 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
440 collectionPaths := []string{}
441 needCertMount := true
442 type copyFile struct {
446 var copyFiles []copyFile
449 for bind := range runner.Container.Mounts {
450 binds = append(binds, bind)
452 for bind := range runner.SecretMounts {
453 if _, ok := runner.Container.Mounts[bind]; ok {
454 return nil, fmt.Errorf("secret mount %q conflicts with regular mount", bind)
456 if runner.SecretMounts[bind].Kind != "json" &&
457 runner.SecretMounts[bind].Kind != "text" {
458 return nil, fmt.Errorf("secret mount %q type is %q but only 'json' and 'text' are permitted",
459 bind, runner.SecretMounts[bind].Kind)
461 binds = append(binds, bind)
465 for _, bind := range binds {
466 mnt, notSecret := runner.Container.Mounts[bind]
468 mnt = runner.SecretMounts[bind]
470 if bind == "stdout" || bind == "stderr" {
471 // Is it a "file" mount kind?
472 if mnt.Kind != "file" {
473 return nil, fmt.Errorf("unsupported mount kind '%s' for %s: only 'file' is supported", mnt.Kind, bind)
476 // Does path start with OutputPath?
477 prefix := runner.Container.OutputPath
478 if !strings.HasSuffix(prefix, "/") {
481 if !strings.HasPrefix(mnt.Path, prefix) {
482 return nil, fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
487 // Is it a "collection" mount kind?
488 if mnt.Kind != "collection" && mnt.Kind != "json" {
489 return nil, fmt.Errorf("unsupported mount kind '%s' for stdin: only 'collection' and 'json' are supported", mnt.Kind)
493 if bind == "/etc/arvados/ca-certificates.crt" {
494 needCertMount = false
497 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
498 if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
499 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)
504 case mnt.Kind == "collection" && bind != "stdin":
506 if mnt.UUID != "" && mnt.PortableDataHash != "" {
507 return nil, fmt.Errorf("cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
511 return nil, fmt.Errorf("writing to existing collections currently not permitted")
514 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
515 } else if mnt.PortableDataHash != "" {
516 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
517 return nil, fmt.Errorf("can never write to a collection specified by portable data hash")
519 idx := strings.Index(mnt.PortableDataHash, "/")
521 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
522 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
523 runner.Container.Mounts[bind] = mnt
525 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
526 if mnt.Path != "" && mnt.Path != "." {
527 if strings.HasPrefix(mnt.Path, "./") {
528 mnt.Path = mnt.Path[2:]
529 } else if strings.HasPrefix(mnt.Path, "/") {
530 mnt.Path = mnt.Path[1:]
532 src += "/" + mnt.Path
535 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
536 arvMountCmd = append(arvMountCmd, "--mount-tmp", fmt.Sprintf("tmp%d", tmpcount))
540 if bind == runner.Container.OutputPath {
541 runner.HostOutputDir = src
542 bindmounts[bind] = bindmount{HostPath: src}
543 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
544 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
546 bindmounts[bind] = bindmount{HostPath: src}
549 bindmounts[bind] = bindmount{HostPath: src, ReadOnly: true}
551 collectionPaths = append(collectionPaths, src)
553 case mnt.Kind == "tmp":
555 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
557 return nil, fmt.Errorf("while creating mount temp dir: %v", err)
559 st, staterr := os.Stat(tmpdir)
561 return nil, fmt.Errorf("while Stat on temp dir: %v", staterr)
563 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
565 return nil, fmt.Errorf("while Chmod temp dir: %v", err)
567 bindmounts[bind] = bindmount{HostPath: tmpdir}
568 if bind == runner.Container.OutputPath {
569 runner.HostOutputDir = tmpdir
572 case mnt.Kind == "json" || mnt.Kind == "text":
574 if mnt.Kind == "json" {
575 filedata, err = json.Marshal(mnt.Content)
577 return nil, fmt.Errorf("encoding json data: %v", err)
580 text, ok := mnt.Content.(string)
582 return nil, fmt.Errorf("content for mount %q must be a string", bind)
584 filedata = []byte(text)
587 tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
589 return nil, fmt.Errorf("creating temp dir: %v", err)
591 tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
592 err = ioutil.WriteFile(tmpfn, filedata, 0444)
594 return nil, fmt.Errorf("writing temp file: %v", err)
596 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && (notSecret || runner.Container.Mounts[runner.Container.OutputPath].Kind != "collection") {
597 // In most cases, if the container
598 // specifies a literal file inside the
599 // output path, we copy it into the
600 // output directory (either a mounted
601 // collection or a staging area on the
602 // host fs). If it's a secret, it will
603 // be skipped when copying output from
604 // staging to Keep later.
605 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
607 // If a secret is outside OutputPath,
608 // we bind mount the secret file
609 // directly just like other mounts. We
610 // also use this strategy when a
611 // secret is inside OutputPath but
612 // OutputPath is a live collection, to
613 // avoid writing the secret to
614 // Keep. Attempting to remove a
615 // bind-mounted secret file from
616 // inside the container will return a
617 // "Device or resource busy" error
618 // that might not be handled well by
619 // the container, which is why we
620 // don't use this strategy when
621 // OutputPath is a staging directory.
622 bindmounts[bind] = bindmount{HostPath: tmpfn, ReadOnly: true}
625 case mnt.Kind == "git_tree":
626 tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
628 return nil, fmt.Errorf("creating temp dir: %v", err)
630 err = gitMount(mnt).extractTree(runner.ContainerArvClient, tmpdir, token)
634 bindmounts[bind] = bindmount{HostPath: tmpdir, ReadOnly: true}
638 if runner.HostOutputDir == "" {
639 return nil, fmt.Errorf("output path does not correspond to a writable mount point")
642 if needCertMount && runner.Container.RuntimeConstraints.API {
643 for _, certfile := range arvadosclient.CertFiles {
644 _, err := os.Stat(certfile)
646 bindmounts["/etc/arvados/ca-certificates.crt"] = bindmount{HostPath: certfile, ReadOnly: true}
653 // If we are only mounting collections by pdh, make
654 // sure we don't subscribe to websocket events to
655 // avoid putting undesired load on the API server
656 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id", "--disable-event-listening")
658 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
660 // the by_uuid mount point is used by singularity when writing
661 // out docker images converted to SIF
662 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_uuid")
663 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
665 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
667 return nil, fmt.Errorf("while trying to start arv-mount: %v", err)
670 for _, p := range collectionPaths {
673 return nil, fmt.Errorf("while checking that input files exist: %v", err)
677 for _, cp := range copyFiles {
678 st, err := os.Stat(cp.src)
680 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
683 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
687 target := path.Join(cp.bind, walkpath[len(cp.src):])
688 if walkinfo.Mode().IsRegular() {
689 copyerr := copyfile(walkpath, target)
693 return os.Chmod(target, walkinfo.Mode()|0777)
694 } else if walkinfo.Mode().IsDir() {
695 mkerr := os.MkdirAll(target, 0777)
699 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
701 return fmt.Errorf("source %q is not a regular file or directory", cp.src)
704 } else if st.Mode().IsRegular() {
705 err = copyfile(cp.src, cp.bind)
707 err = os.Chmod(cp.bind, st.Mode()|0777)
711 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
715 return bindmounts, nil
718 func (runner *ContainerRunner) stopHoststat() error {
719 if runner.hoststatReporter == nil {
722 runner.hoststatReporter.Stop()
723 err := runner.hoststatLogger.Close()
725 return fmt.Errorf("error closing hoststat logs: %v", err)
730 func (runner *ContainerRunner) startHoststat() error {
731 w, err := runner.NewLogWriter("hoststat")
735 runner.hoststatLogger = NewThrottledLogger(w)
736 runner.hoststatReporter = &crunchstat.Reporter{
737 Logger: log.New(runner.hoststatLogger, "", 0),
738 CgroupRoot: runner.cgroupRoot,
739 PollPeriod: runner.statInterval,
741 runner.hoststatReporter.Start()
745 func (runner *ContainerRunner) startCrunchstat() error {
746 w, err := runner.NewLogWriter("crunchstat")
750 runner.statLogger = NewThrottledLogger(w)
751 runner.statReporter = &crunchstat.Reporter{
752 CID: runner.executor.CgroupID(),
753 Logger: log.New(runner.statLogger, "", 0),
754 CgroupParent: runner.expectCgroupParent,
755 CgroupRoot: runner.cgroupRoot,
756 PollPeriod: runner.statInterval,
757 TempDir: runner.parentTemp,
759 runner.statReporter.Start()
763 type infoCommand struct {
768 // LogHostInfo logs info about the current host, for debugging and
769 // accounting purposes. Although it's logged as "node-info", this is
770 // about the environment where crunch-run is actually running, which
771 // might differ from what's described in the node record (see
773 func (runner *ContainerRunner) LogHostInfo() (err error) {
774 w, err := runner.NewLogWriter("node-info")
779 commands := []infoCommand{
781 label: "Host Information",
782 cmd: []string{"uname", "-a"},
785 label: "CPU Information",
786 cmd: []string{"cat", "/proc/cpuinfo"},
789 label: "Memory Information",
790 cmd: []string{"cat", "/proc/meminfo"},
794 cmd: []string{"df", "-m", "/", os.TempDir()},
797 label: "Disk INodes",
798 cmd: []string{"df", "-i", "/", os.TempDir()},
802 // Run commands with informational output to be logged.
803 for _, command := range commands {
804 fmt.Fprintln(w, command.label)
805 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
808 if err := cmd.Run(); err != nil {
809 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
818 return fmt.Errorf("While closing node-info logs: %v", err)
823 // LogContainerRecord gets and saves the raw JSON container record from the API server
824 func (runner *ContainerRunner) LogContainerRecord() error {
825 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
826 if !logged && err == nil {
827 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
832 // LogNodeRecord logs the current host's InstanceType config entry (or
833 // the arvados#node record, if running via crunch-dispatch-slurm).
834 func (runner *ContainerRunner) LogNodeRecord() error {
835 if it := os.Getenv("InstanceType"); it != "" {
836 // Dispatched via arvados-dispatch-cloud. Save
837 // InstanceType config fragment received from
838 // dispatcher on stdin.
839 w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
844 _, err = io.WriteString(w, it)
850 // Dispatched via crunch-dispatch-slurm. Look up
851 // apiserver's node record corresponding to
853 hostname := os.Getenv("SLURMD_NODENAME")
855 hostname, _ = os.Hostname()
857 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
858 // The "info" field has admin-only info when
859 // obtained with a privileged token, and
860 // should not be logged.
861 node, ok := resp.(map[string]interface{})
869 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
870 writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
875 ArvClient: runner.DispatcherArvClient,
876 UUID: runner.Container.UUID,
877 loggingStream: label,
881 reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
883 return false, fmt.Errorf("error getting %s record: %v", label, err)
887 dec := json.NewDecoder(reader)
889 var resp map[string]interface{}
890 if err = dec.Decode(&resp); err != nil {
891 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
893 items, ok := resp["items"].([]interface{})
895 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
896 } else if len(items) < 1 {
902 // Re-encode it using indentation to improve readability
903 enc := json.NewEncoder(w)
904 enc.SetIndent("", " ")
905 if err = enc.Encode(items[0]); err != nil {
906 return false, fmt.Errorf("error logging %s record: %v", label, err)
910 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
915 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
916 stdoutPath := mntPath[len(runner.Container.OutputPath):]
917 index := strings.LastIndex(stdoutPath, "/")
919 subdirs := stdoutPath[:index]
921 st, err := os.Stat(runner.HostOutputDir)
923 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
925 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
926 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
928 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
932 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
934 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
937 return stdoutFile, nil
940 // CreateContainer creates the docker container.
941 func (runner *ContainerRunner) CreateContainer(imageID string, bindmounts map[string]bindmount) error {
942 var stdin io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
943 if mnt, ok := runner.Container.Mounts["stdin"]; ok {
950 collID = mnt.PortableDataHash
952 path := runner.ArvMountPoint + "/by_id/" + collID + "/" + mnt.Path
953 f, err := os.Open(path)
959 j, err := json.Marshal(mnt.Content)
961 return fmt.Errorf("error encoding stdin json data: %v", err)
963 stdin = ioutil.NopCloser(bytes.NewReader(j))
965 return fmt.Errorf("stdin mount has unsupported kind %q", mnt.Kind)
969 var stdout, stderr io.WriteCloser
970 if mnt, ok := runner.Container.Mounts["stdout"]; ok {
971 f, err := runner.getStdoutFile(mnt.Path)
976 } else if w, err := runner.NewLogWriter("stdout"); err != nil {
979 stdout = NewThrottledLogger(w)
982 if mnt, ok := runner.Container.Mounts["stderr"]; ok {
983 f, err := runner.getStdoutFile(mnt.Path)
988 } else if w, err := runner.NewLogWriter("stderr"); err != nil {
991 stderr = NewThrottledLogger(w)
994 env := runner.Container.Environment
995 enableNetwork := runner.enableNetwork == "always"
996 if runner.Container.RuntimeConstraints.API {
998 tok, err := runner.ContainerToken()
1002 env = map[string]string{}
1003 for k, v := range runner.Container.Environment {
1006 env["ARVADOS_API_TOKEN"] = tok
1007 env["ARVADOS_API_HOST"] = os.Getenv("ARVADOS_API_HOST")
1008 env["ARVADOS_API_HOST_INSECURE"] = os.Getenv("ARVADOS_API_HOST_INSECURE")
1009 env["ARVADOS_KEEP_SERVICES"] = os.Getenv("ARVADOS_KEEP_SERVICES")
1011 workdir := runner.Container.Cwd
1013 // both "" and "." mean default
1016 ram := runner.Container.RuntimeConstraints.RAM
1017 if !runner.enableMemoryLimit {
1020 runner.executorStdin = stdin
1021 runner.executorStdout = stdout
1022 runner.executorStderr = stderr
1024 if runner.Container.RuntimeConstraints.CUDA.DeviceCount > 0 {
1025 nvidiaModprobe(runner.CrunchLog)
1028 return runner.executor.Create(containerSpec{
1030 VCPUs: runner.Container.RuntimeConstraints.VCPUs,
1032 WorkingDir: workdir,
1034 BindMounts: bindmounts,
1035 Command: runner.Container.Command,
1036 EnableNetwork: enableNetwork,
1037 CUDADeviceCount: runner.Container.RuntimeConstraints.CUDA.DeviceCount,
1038 NetworkMode: runner.networkMode,
1039 CgroupParent: runner.setCgroupParent,
1046 // StartContainer starts the docker container created by CreateContainer.
1047 func (runner *ContainerRunner) StartContainer() error {
1048 runner.CrunchLog.Printf("Starting container")
1049 runner.cStateLock.Lock()
1050 defer runner.cStateLock.Unlock()
1051 if runner.cCancelled {
1054 err := runner.executor.Start()
1057 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1058 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])
1060 return fmt.Errorf("could not start container: %v%s", err, advice)
1065 // WaitFinish waits for the container to terminate, capture the exit code, and
1066 // close the stdout/stderr logging.
1067 func (runner *ContainerRunner) WaitFinish() error {
1068 runner.CrunchLog.Print("Waiting for container to finish")
1069 var timeout <-chan time.Time
1070 if s := runner.Container.SchedulingParameters.MaxRunTime; s > 0 {
1071 timeout = time.After(time.Duration(s) * time.Second)
1073 ctx, cancel := context.WithCancel(context.Background())
1078 runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1080 case <-runner.ArvMountExit:
1081 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1086 exitcode, err := runner.executor.Wait(ctx)
1088 runner.checkBrokenNode(err)
1091 runner.ExitCode = &exitcode
1094 if exitcode&0x80 != 0 {
1095 // Convert raw exit status (0x80 + signal number) to a
1096 // string to log after the code, like " (signal 101)"
1097 // or " (signal 9, killed)"
1098 sig := syscall.WaitStatus(exitcode).Signal()
1099 if name := unix.SignalName(sig); name != "" {
1100 extra = fmt.Sprintf(" (signal %d, %s)", sig, name)
1102 extra = fmt.Sprintf(" (signal %d)", sig)
1105 runner.CrunchLog.Printf("Container exited with status code %d%s", exitcode, extra)
1106 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1107 "container": arvadosclient.Dict{"exit_code": exitcode},
1110 runner.CrunchLog.Printf("ignoring error updating exit_code: %s", err)
1114 if err = runner.executorStdin.Close(); err != nil {
1115 err = fmt.Errorf("error closing container stdin: %s", err)
1116 runner.CrunchLog.Printf("%s", err)
1119 if err = runner.executorStdout.Close(); err != nil {
1120 err = fmt.Errorf("error closing container stdout: %s", err)
1121 runner.CrunchLog.Printf("%s", err)
1122 if returnErr == nil {
1126 if err = runner.executorStderr.Close(); err != nil {
1127 err = fmt.Errorf("error closing container stderr: %s", err)
1128 runner.CrunchLog.Printf("%s", err)
1129 if returnErr == nil {
1134 if runner.statReporter != nil {
1135 runner.statReporter.Stop()
1136 err = runner.statLogger.Close()
1138 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
1144 func (runner *ContainerRunner) updateLogs() {
1145 ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1148 sigusr1 := make(chan os.Signal, 1)
1149 signal.Notify(sigusr1, syscall.SIGUSR1)
1150 defer signal.Stop(sigusr1)
1152 saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1153 saveAtSize := crunchLogUpdateSize
1159 saveAtTime = time.Now()
1161 runner.logMtx.Lock()
1162 done := runner.LogsPDH != nil
1163 runner.logMtx.Unlock()
1167 size := runner.LogCollection.Size()
1168 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1171 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1172 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1173 saved, err := runner.saveLogCollection(false)
1175 runner.CrunchLog.Printf("error updating log collection: %s", err)
1179 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1180 "container": arvadosclient.Dict{"log": saved.PortableDataHash},
1183 runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1191 func (runner *ContainerRunner) reportArvMountWarning(pattern, text string) {
1192 var updated arvados.Container
1193 err := runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1194 "container": arvadosclient.Dict{
1195 "runtime_status": arvadosclient.Dict{
1196 "warning": "arv-mount: " + pattern,
1197 "warningDetail": text,
1202 runner.CrunchLog.Printf("error updating container runtime_status: %s", err)
1206 // CaptureOutput saves data from the container's output directory if
1207 // needed, and updates the container output accordingly.
1208 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1209 if runner.Container.RuntimeConstraints.API {
1210 // Output may have been set directly by the container, so
1211 // refresh the container record to check.
1212 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1213 nil, &runner.Container)
1217 if runner.Container.Output != "" {
1218 // Container output is already set.
1219 runner.OutputPDH = &runner.Container.Output
1224 txt, err := (&copier{
1225 client: runner.containerClient,
1226 arvClient: runner.ContainerArvClient,
1227 keepClient: runner.ContainerKeepClient,
1228 hostOutputDir: runner.HostOutputDir,
1229 ctrOutputDir: runner.Container.OutputPath,
1230 bindmounts: bindmounts,
1231 mounts: runner.Container.Mounts,
1232 secretMounts: runner.SecretMounts,
1233 logger: runner.CrunchLog,
1238 if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1239 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1240 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1244 txt, err = fs.MarshalManifest(".")
1249 var resp arvados.Collection
1250 err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1251 "ensure_unique_name": true,
1252 "collection": arvadosclient.Dict{
1254 "name": "output for " + runner.Container.UUID,
1255 "manifest_text": txt,
1259 return fmt.Errorf("error creating output collection: %v", err)
1261 runner.OutputPDH = &resp.PortableDataHash
1265 func (runner *ContainerRunner) CleanupDirs() {
1266 if runner.ArvMount != nil {
1268 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1269 umount.Stdout = runner.CrunchLog
1270 umount.Stderr = runner.CrunchLog
1271 runner.CrunchLog.Printf("Running %v", umount.Args)
1272 umnterr := umount.Start()
1275 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1276 runner.ArvMount.Process.Kill()
1278 // If arv-mount --unmount gets stuck for any reason, we
1279 // don't want to wait for it forever. Do Wait() in a goroutine
1280 // so it doesn't block crunch-run.
1281 umountExit := make(chan error)
1283 mnterr := umount.Wait()
1285 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1287 umountExit <- mnterr
1290 for again := true; again; {
1296 case <-runner.ArvMountExit:
1298 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1299 runner.CrunchLog.Printf("Timed out waiting for unmount")
1301 umount.Process.Kill()
1303 runner.ArvMount.Process.Kill()
1307 runner.ArvMount = nil
1310 if runner.ArvMountPoint != "" {
1311 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1312 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1314 runner.ArvMountPoint = ""
1317 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1318 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1322 // CommitLogs posts the collection containing the final container logs.
1323 func (runner *ContainerRunner) CommitLogs() error {
1325 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1326 runner.cStateLock.Lock()
1327 defer runner.cStateLock.Unlock()
1329 runner.CrunchLog.Print(runner.finalState)
1331 if runner.arvMountLog != nil {
1332 runner.arvMountLog.Close()
1334 runner.CrunchLog.Close()
1336 // Closing CrunchLog above allows them to be committed to Keep at this
1337 // point, but re-open crunch log with ArvClient in case there are any
1338 // other further errors (such as failing to write the log to Keep!)
1339 // while shutting down
1340 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1341 ArvClient: runner.DispatcherArvClient,
1342 UUID: runner.Container.UUID,
1343 loggingStream: "crunch-run",
1346 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1349 if runner.keepstoreLogger != nil {
1350 // Flush any buffered logs from our local keepstore
1351 // process. Discard anything logged after this point
1352 // -- it won't end up in the log collection, so
1353 // there's no point writing it to the collectionfs.
1354 runner.keepstoreLogbuf.SetWriter(io.Discard)
1355 runner.keepstoreLogger.Close()
1356 runner.keepstoreLogger = nil
1359 if runner.LogsPDH != nil {
1360 // If we have already assigned something to LogsPDH,
1361 // we must be closing the re-opened log, which won't
1362 // end up getting attached to the container record and
1363 // therefore doesn't need to be saved as a collection
1364 // -- it exists only to send logs to other channels.
1368 saved, err := runner.saveLogCollection(true)
1370 return fmt.Errorf("error saving log collection: %s", err)
1372 runner.logMtx.Lock()
1373 defer runner.logMtx.Unlock()
1374 runner.LogsPDH = &saved.PortableDataHash
1378 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1379 runner.logMtx.Lock()
1380 defer runner.logMtx.Unlock()
1381 if runner.LogsPDH != nil {
1382 // Already finalized.
1385 updates := arvadosclient.Dict{
1386 "name": "logs for " + runner.Container.UUID,
1388 mt, err1 := runner.LogCollection.MarshalManifest(".")
1390 // Only send updated manifest text if there was no
1392 updates["manifest_text"] = mt
1395 // Even if flushing the manifest had an error, we still want
1396 // to update the log record, if possible, to push the trash_at
1397 // and delete_at times into the future. Details on bug
1400 updates["is_trashed"] = true
1402 exp := time.Now().Add(crunchLogUpdatePeriod * 24)
1403 updates["trash_at"] = exp
1404 updates["delete_at"] = exp
1406 reqBody := arvadosclient.Dict{"collection": updates}
1408 if runner.logUUID == "" {
1409 reqBody["ensure_unique_name"] = true
1410 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1412 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1415 runner.logUUID = response.UUID
1418 if err1 != nil || err2 != nil {
1419 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1424 // UpdateContainerRunning updates the container state to "Running"
1425 func (runner *ContainerRunner) UpdateContainerRunning() error {
1426 runner.cStateLock.Lock()
1427 defer runner.cStateLock.Unlock()
1428 if runner.cCancelled {
1431 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID,
1432 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running", "gateway_address": runner.gateway.Address}}, nil)
1435 // ContainerToken returns the api_token the container (and any
1436 // arv-mount processes) are allowed to use.
1437 func (runner *ContainerRunner) ContainerToken() (string, error) {
1438 if runner.token != "" {
1439 return runner.token, nil
1442 var auth arvados.APIClientAuthorization
1443 err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1447 runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1448 return runner.token, nil
1451 // UpdateContainerFinal updates the container record state on API
1452 // server to "Complete" or "Cancelled"
1453 func (runner *ContainerRunner) UpdateContainerFinal() error {
1454 update := arvadosclient.Dict{}
1455 update["state"] = runner.finalState
1456 if runner.LogsPDH != nil {
1457 update["log"] = *runner.LogsPDH
1459 if runner.ExitCode != nil {
1460 update["exit_code"] = *runner.ExitCode
1462 update["exit_code"] = nil
1464 if runner.finalState == "Complete" && runner.OutputPDH != nil {
1465 update["output"] = *runner.OutputPDH
1467 var it arvados.InstanceType
1468 if j := os.Getenv("InstanceType"); j != "" && json.Unmarshal([]byte(j), &it) == nil && it.Price > 0 {
1469 update["cost"] = it.Price * time.Now().Sub(runner.costStartTime).Seconds() / time.Hour.Seconds()
1471 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1474 // IsCancelled returns the value of Cancelled, with goroutine safety.
1475 func (runner *ContainerRunner) IsCancelled() bool {
1476 runner.cStateLock.Lock()
1477 defer runner.cStateLock.Unlock()
1478 return runner.cCancelled
1481 // NewArvLogWriter creates an ArvLogWriter
1482 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1483 writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1487 return &ArvLogWriter{
1488 ArvClient: runner.DispatcherArvClient,
1489 UUID: runner.Container.UUID,
1490 loggingStream: name,
1491 writeCloser: writer,
1495 // Run the full container lifecycle.
1496 func (runner *ContainerRunner) Run() (err error) {
1497 runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1498 runner.CrunchLog.Printf("%s", currentUserAndGroups())
1499 v, _ := exec.Command("arv-mount", "--version").CombinedOutput()
1500 runner.CrunchLog.Printf("Using FUSE mount: %s", v)
1501 runner.CrunchLog.Printf("Using container runtime: %s", runner.executor.Runtime())
1502 runner.CrunchLog.Printf("Executing container: %s", runner.Container.UUID)
1503 runner.costStartTime = time.Now()
1505 hostname, hosterr := os.Hostname()
1507 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1509 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1512 runner.finalState = "Queued"
1515 runner.CleanupDirs()
1517 runner.CrunchLog.Printf("crunch-run finished")
1518 runner.CrunchLog.Close()
1521 err = runner.fetchContainerRecord()
1525 if runner.Container.State != "Locked" {
1526 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1529 var bindmounts map[string]bindmount
1531 // checkErr prints e (unless it's nil) and sets err to
1532 // e (unless err is already non-nil). Thus, if err
1533 // hasn't already been assigned when Run() returns,
1534 // this cleanup func will cause Run() to return the
1535 // first non-nil error that is passed to checkErr().
1536 checkErr := func(errorIn string, e error) {
1540 runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1544 if runner.finalState == "Complete" {
1545 // There was an error in the finalization.
1546 runner.finalState = "Cancelled"
1550 // Log the error encountered in Run(), if any
1551 checkErr("Run", err)
1553 if runner.finalState == "Queued" {
1554 runner.UpdateContainerFinal()
1558 if runner.IsCancelled() {
1559 runner.finalState = "Cancelled"
1560 // but don't return yet -- we still want to
1561 // capture partial output and write logs
1564 if bindmounts != nil {
1565 checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1567 checkErr("stopHoststat", runner.stopHoststat())
1568 checkErr("CommitLogs", runner.CommitLogs())
1569 runner.CleanupDirs()
1570 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1573 runner.setupSignals()
1574 err = runner.startHoststat()
1579 // set up FUSE mount and binds
1580 bindmounts, err = runner.SetupMounts()
1582 runner.finalState = "Cancelled"
1583 err = fmt.Errorf("While setting up mounts: %v", err)
1587 // check for and/or load image
1588 imageID, err := runner.LoadImage()
1590 if !runner.checkBrokenNode(err) {
1591 // Failed to load image but not due to a "broken node"
1592 // condition, probably user error.
1593 runner.finalState = "Cancelled"
1595 err = fmt.Errorf("While loading container image: %v", err)
1599 err = runner.CreateContainer(imageID, bindmounts)
1603 err = runner.LogHostInfo()
1607 err = runner.LogNodeRecord()
1611 err = runner.LogContainerRecord()
1616 if runner.IsCancelled() {
1620 err = runner.UpdateContainerRunning()
1624 runner.finalState = "Cancelled"
1626 err = runner.startCrunchstat()
1631 err = runner.StartContainer()
1633 runner.checkBrokenNode(err)
1637 err = runner.WaitFinish()
1638 if err == nil && !runner.IsCancelled() {
1639 runner.finalState = "Complete"
1644 // Fetch the current container record (uuid = runner.Container.UUID)
1645 // into runner.Container.
1646 func (runner *ContainerRunner) fetchContainerRecord() error {
1647 reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1649 return fmt.Errorf("error fetching container record: %v", err)
1651 defer reader.Close()
1653 dec := json.NewDecoder(reader)
1655 err = dec.Decode(&runner.Container)
1657 return fmt.Errorf("error decoding container record: %v", err)
1661 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1664 containerToken, err := runner.ContainerToken()
1666 return fmt.Errorf("error getting container token: %v", err)
1669 runner.ContainerArvClient, runner.ContainerKeepClient,
1670 runner.containerClient, err = runner.MkArvClient(containerToken)
1672 return fmt.Errorf("error creating container API client: %v", err)
1675 runner.ContainerKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1676 runner.DispatcherKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1678 err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1680 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1681 return fmt.Errorf("error fetching secret_mounts: %v", err)
1683 // ok && apierr.HttpStatusCode == 404, which means
1684 // secret_mounts isn't supported by this API server.
1686 runner.SecretMounts = sm.SecretMounts
1691 // NewContainerRunner creates a new container runner.
1692 func NewContainerRunner(dispatcherClient *arvados.Client,
1693 dispatcherArvClient IArvadosClient,
1694 dispatcherKeepClient IKeepClient,
1695 containerUUID string) (*ContainerRunner, error) {
1697 cr := &ContainerRunner{
1698 dispatcherClient: dispatcherClient,
1699 DispatcherArvClient: dispatcherArvClient,
1700 DispatcherKeepClient: dispatcherKeepClient,
1702 cr.NewLogWriter = cr.NewArvLogWriter
1703 cr.RunArvMount = cr.ArvMountCmd
1704 cr.MkTempDir = ioutil.TempDir
1705 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1706 cl, err := arvadosclient.MakeArvadosClient()
1708 return nil, nil, nil, err
1711 kc, err := keepclient.MakeKeepClient(cl)
1713 return nil, nil, nil, err
1715 c2 := arvados.NewClientFromEnv()
1716 c2.AuthToken = token
1717 return cl, kc, c2, nil
1720 cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1724 cr.Container.UUID = containerUUID
1725 w, err := cr.NewLogWriter("crunch-run")
1729 cr.CrunchLog = NewThrottledLogger(w)
1730 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1732 loadLogThrottleParams(dispatcherArvClient)
1738 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1739 log := log.New(stderr, "", 0)
1740 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1741 statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1742 cgroupRoot := flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1743 cgroupParent := flags.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1744 cgroupParentSubsystem := flags.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1745 caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1746 detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1747 stdinConfig := flags.Bool("stdin-config", false, "Load config and environment variables from JSON message on stdin")
1748 configFile := flags.String("config", arvados.DefaultConfigFile, "filename of cluster config file to try loading if -stdin-config=false (default is $ARVADOS_CONFIG)")
1749 sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1750 kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1751 list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes")
1752 enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1753 enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1754 networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1755 memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1756 runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1757 brokenNodeHook := flags.String("broken-node-hook", "", "script to run if node is detected to be broken (for example, Docker daemon is not running)")
1758 flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1759 version := flags.Bool("version", false, "Write version information to stdout and exit 0.")
1761 ignoreDetachFlag := false
1762 if len(args) > 0 && args[0] == "-no-detach" {
1763 // This process was invoked by a parent process, which
1764 // has passed along its own arguments, including
1765 // -detach, after the leading -no-detach flag. Strip
1766 // the leading -no-detach flag (it's not recognized by
1767 // flags.Parse()) and ignore the -detach flag that
1770 ignoreDetachFlag = true
1773 if ok, code := cmd.ParseFlags(flags, prog, args, "container-uuid", stderr); !ok {
1775 } else if *version {
1776 fmt.Fprintln(stdout, prog, cmd.Version.String())
1778 } else if !*list && flags.NArg() != 1 {
1779 fmt.Fprintf(stderr, "missing required argument: container-uuid (try -help)\n")
1783 containerUUID := flags.Arg(0)
1786 case *detach && !ignoreDetachFlag:
1787 return Detach(containerUUID, prog, args, os.Stdin, os.Stdout, os.Stderr)
1789 return KillProcess(containerUUID, syscall.Signal(*kill), os.Stdout, os.Stderr)
1791 return ListProcesses(os.Stdout, os.Stderr)
1794 if len(containerUUID) != 27 {
1795 log.Printf("usage: %s [options] UUID", prog)
1799 var keepstoreLogbuf bufThenWrite
1802 err := json.NewDecoder(stdin).Decode(&conf)
1804 log.Printf("decode stdin: %s", err)
1807 for k, v := range conf.Env {
1808 err = os.Setenv(k, v)
1810 log.Printf("setenv(%q): %s", k, err)
1814 if conf.Cluster != nil {
1815 // ClusterID is missing from the JSON
1816 // representation, but we need it to generate
1817 // a valid config file for keepstore, so we
1818 // fill it using the container UUID prefix.
1819 conf.Cluster.ClusterID = containerUUID[:5]
1822 conf = hpcConfData(containerUUID, *configFile, io.MultiWriter(&keepstoreLogbuf, stderr))
1825 log.Printf("crunch-run %s started", cmd.Version.String())
1828 if *caCertsPath != "" {
1829 arvadosclient.CertFiles = []string{*caCertsPath}
1832 keepstore, err := startLocalKeepstore(conf, io.MultiWriter(&keepstoreLogbuf, stderr))
1837 if keepstore != nil {
1838 defer keepstore.Process.Kill()
1841 api, err := arvadosclient.MakeArvadosClient()
1843 log.Printf("%s: %v", containerUUID, err)
1848 kc, err := keepclient.MakeKeepClient(api)
1850 log.Printf("%s: %v", containerUUID, err)
1853 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1856 cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
1862 if keepstore == nil {
1863 // Log explanation (if any) for why we're not running
1864 // a local keepstore.
1865 var buf bytes.Buffer
1866 keepstoreLogbuf.SetWriter(&buf)
1868 cr.CrunchLog.Printf("%s", strings.TrimSpace(buf.String()))
1870 } else if logWhat := conf.Cluster.Containers.LocalKeepLogsToContainerLog; logWhat == "none" {
1871 cr.CrunchLog.Printf("using local keepstore process (pid %d) at %s", keepstore.Process.Pid, os.Getenv("ARVADOS_KEEP_SERVICES"))
1872 keepstoreLogbuf.SetWriter(io.Discard)
1874 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"))
1875 logwriter, err := cr.NewLogWriter("keepstore")
1880 cr.keepstoreLogger = NewThrottledLogger(logwriter)
1882 var writer io.WriteCloser = cr.keepstoreLogger
1883 if logWhat == "errors" {
1884 writer = &filterKeepstoreErrorsOnly{WriteCloser: writer}
1885 } else if logWhat != "all" {
1886 // should have been caught earlier by
1887 // dispatcher's config loader
1888 log.Printf("invalid value for Containers.LocalKeepLogsToContainerLog: %q", logWhat)
1891 err = keepstoreLogbuf.SetWriter(writer)
1896 cr.keepstoreLogbuf = &keepstoreLogbuf
1899 switch *runtimeEngine {
1901 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
1903 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
1905 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
1906 cr.CrunchLog.Close()
1910 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
1911 cr.checkBrokenNode(err)
1912 cr.CrunchLog.Close()
1915 defer cr.executor.Close()
1917 cr.brokenNodeHook = *brokenNodeHook
1919 gwAuthSecret := os.Getenv("GatewayAuthSecret")
1920 os.Unsetenv("GatewayAuthSecret")
1921 if gwAuthSecret == "" {
1922 // not safe to run a gateway service without an auth
1924 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAuthSecret was not provided by dispatcher)")
1926 gwListen := os.Getenv("GatewayAddress")
1927 cr.gateway = Gateway{
1929 AuthSecret: gwAuthSecret,
1930 ContainerUUID: containerUUID,
1931 Target: cr.executor,
1935 // Direct connection won't work, so we use the
1936 // gateway_address field to indicate the
1937 // internalURL of the controller process that
1938 // has the current tunnel connection.
1939 cr.gateway.ArvadosClient = cr.dispatcherClient
1940 cr.gateway.UpdateTunnelURL = func(url string) {
1941 cr.gateway.Address = "tunnel " + url
1942 cr.DispatcherArvClient.Update("containers", containerUUID,
1943 arvadosclient.Dict{"container": arvadosclient.Dict{"gateway_address": cr.gateway.Address}}, nil)
1946 err = cr.gateway.Start()
1948 log.Printf("error starting gateway server: %s", err)
1953 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
1955 log.Printf("%s: %v", containerUUID, tmperr)
1959 cr.parentTemp = parentTemp
1960 cr.statInterval = *statInterval
1961 cr.cgroupRoot = *cgroupRoot
1962 cr.expectCgroupParent = *cgroupParent
1963 cr.enableMemoryLimit = *enableMemoryLimit
1964 cr.enableNetwork = *enableNetwork
1965 cr.networkMode = *networkMode
1966 if *cgroupParentSubsystem != "" {
1967 p, err := findCgroup(*cgroupParentSubsystem)
1969 log.Printf("fatal: cgroup parent subsystem: %s", err)
1972 cr.setCgroupParent = p
1973 cr.expectCgroupParent = p
1978 if *memprofile != "" {
1979 f, err := os.Create(*memprofile)
1981 log.Printf("could not create memory profile: %s", err)
1983 runtime.GC() // get up-to-date statistics
1984 if err := pprof.WriteHeapProfile(f); err != nil {
1985 log.Printf("could not write memory profile: %s", err)
1987 closeerr := f.Close()
1988 if closeerr != nil {
1989 log.Printf("closing memprofile file: %s", err)
1994 log.Printf("%s: %v", containerUUID, runerr)
2000 // Try to load ConfigData in hpc (slurm/lsf) environment. This means
2001 // loading the cluster config from the specified file and (if that
2002 // works) getting the runtime_constraints container field from
2003 // controller to determine # VCPUs so we can calculate KeepBuffers.
2004 func hpcConfData(uuid string, configFile string, stderr io.Writer) ConfigData {
2006 conf.Cluster = loadClusterConfigFile(configFile, stderr)
2007 if conf.Cluster == nil {
2008 // skip loading the container record -- we won't be
2009 // able to start local keepstore anyway.
2012 arv, err := arvadosclient.MakeArvadosClient()
2014 fmt.Fprintf(stderr, "error setting up arvadosclient: %s\n", err)
2018 var ctr arvados.Container
2019 err = arv.Call("GET", "containers", uuid, "", arvadosclient.Dict{"select": []string{"runtime_constraints"}}, &ctr)
2021 fmt.Fprintf(stderr, "error getting container record: %s\n", err)
2024 if ctr.RuntimeConstraints.VCPUs > 0 {
2025 conf.KeepBuffers = ctr.RuntimeConstraints.VCPUs * conf.Cluster.Containers.LocalKeepBlobBuffersPerVCPU
2030 // Load cluster config file from given path. If an error occurs, log
2031 // the error to stderr and return nil.
2032 func loadClusterConfigFile(path string, stderr io.Writer) *arvados.Cluster {
2033 ldr := config.NewLoader(&bytes.Buffer{}, ctxlog.New(stderr, "plain", "info"))
2035 cfg, err := ldr.Load()
2037 fmt.Fprintf(stderr, "could not load config file %s: %s\n", path, err)
2040 cluster, err := cfg.GetCluster("")
2042 fmt.Fprintf(stderr, "could not use config file %s: %s\n", path, err)
2045 fmt.Fprintf(stderr, "loaded config file %s\n", path)
2049 func startLocalKeepstore(configData ConfigData, logbuf io.Writer) (*exec.Cmd, error) {
2050 if configData.KeepBuffers < 1 {
2051 fmt.Fprintf(logbuf, "not starting a local keepstore process because KeepBuffers=%v in config\n", configData.KeepBuffers)
2054 if configData.Cluster == nil {
2055 fmt.Fprint(logbuf, "not starting a local keepstore process because cluster config file was not loaded\n")
2058 for uuid, vol := range configData.Cluster.Volumes {
2059 if len(vol.AccessViaHosts) > 0 {
2060 fmt.Fprintf(logbuf, "not starting a local keepstore process because a volume (%s) uses AccessViaHosts\n", uuid)
2063 if !vol.ReadOnly && vol.Replication < configData.Cluster.Collections.DefaultReplication {
2064 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)
2069 // Rather than have an alternate way to tell keepstore how
2070 // many buffers to use when starting it this way, we just
2071 // modify the cluster configuration that we feed it on stdin.
2072 configData.Cluster.API.MaxKeepBlobBuffers = configData.KeepBuffers
2074 localaddr := localKeepstoreAddr()
2075 ln, err := net.Listen("tcp", net.JoinHostPort(localaddr, "0"))
2079 _, port, err := net.SplitHostPort(ln.Addr().String())
2085 url := "http://" + net.JoinHostPort(localaddr, port)
2087 fmt.Fprintf(logbuf, "starting keepstore on %s\n", url)
2089 var confJSON bytes.Buffer
2090 err = json.NewEncoder(&confJSON).Encode(arvados.Config{
2091 Clusters: map[string]arvados.Cluster{
2092 configData.Cluster.ClusterID: *configData.Cluster,
2098 cmd := exec.Command("/proc/self/exe", "keepstore", "-config=-")
2099 if target, err := os.Readlink(cmd.Path); err == nil && strings.HasSuffix(target, ".test") {
2100 // If we're a 'go test' process, running
2101 // /proc/self/exe would start the test suite in a
2102 // child process, which is not what we want.
2103 cmd.Path, _ = exec.LookPath("go")
2104 cmd.Args = append([]string{"go", "run", "../../cmd/arvados-server"}, cmd.Args[1:]...)
2105 cmd.Env = os.Environ()
2107 cmd.Stdin = &confJSON
2110 cmd.Env = append(cmd.Env,
2112 "ARVADOS_SERVICE_INTERNAL_URL="+url)
2115 return nil, fmt.Errorf("error starting keepstore process: %w", err)
2122 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10))
2124 poll := time.NewTicker(time.Second / 10)
2126 client := http.Client{}
2128 testReq, err := http.NewRequestWithContext(ctx, "GET", url+"/_health/ping", nil)
2129 testReq.Header.Set("Authorization", "Bearer "+configData.Cluster.ManagementToken)
2133 resp, err := client.Do(testReq)
2136 if resp.StatusCode == http.StatusOK {
2141 return nil, fmt.Errorf("keepstore child process exited")
2143 if ctx.Err() != nil {
2144 return nil, fmt.Errorf("timed out waiting for new keepstore process to report healthy")
2147 os.Setenv("ARVADOS_KEEP_SERVICES", url)
2151 // return current uid, gid, groups in a format suitable for logging:
2152 // "crunch-run process has uid=1234(arvados) gid=1234(arvados)
2153 // groups=1234(arvados),114(fuse)"
2154 func currentUserAndGroups() string {
2155 u, err := user.Current()
2157 return fmt.Sprintf("error getting current user ID: %s", err)
2159 s := fmt.Sprintf("crunch-run process has uid=%s(%s) gid=%s", u.Uid, u.Username, u.Gid)
2160 if g, err := user.LookupGroupId(u.Gid); err == nil {
2161 s += fmt.Sprintf("(%s)", g.Name)
2164 if gids, err := u.GroupIds(); err == nil {
2165 for i, gid := range gids {
2170 if g, err := user.LookupGroupId(gid); err == nil {
2171 s += fmt.Sprintf("(%s)", g.Name)
2178 // Return a suitable local interface address for a local keepstore
2179 // service. Currently this is the numerically lowest non-loopback ipv4
2180 // address assigned to a local interface that is not in any of the
2181 // link-local/vpn/loopback ranges 169.254/16, 100.64/10, or 127/8.
2182 func localKeepstoreAddr() string {
2184 // Ignore error (proceed with zero IPs)
2185 addrs, _ := processIPs(os.Getpid())
2186 for addr := range addrs {
2187 ip := net.ParseIP(addr)
2192 if ip.Mask(net.CIDRMask(8, 32)).Equal(net.IPv4(127, 0, 0, 0)) ||
2193 ip.Mask(net.CIDRMask(10, 32)).Equal(net.IPv4(100, 64, 0, 0)) ||
2194 ip.Mask(net.CIDRMask(16, 32)).Equal(net.IPv4(169, 254, 0, 0)) {
2198 ips = append(ips, ip)
2203 sort.Slice(ips, func(ii, jj int) bool {
2204 i, j := ips[ii], ips[jj]
2205 if len(i) != len(j) {
2206 return len(i) < len(j)
2215 return ips[0].String()