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.KeepCacheDisk > 0 {
432 keepcachedir, err := runner.MkTempDir(runner.parentTemp, "keepcache")
434 return nil, fmt.Errorf("while creating keep cache temp dir: %v", err)
436 arvMountCmd = append(arvMountCmd, "--disk-cache", "--disk-cache-dir", keepcachedir, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheDisk))
437 } else if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
438 arvMountCmd = append(arvMountCmd, "--ram-cache", "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
441 collectionPaths := []string{}
442 needCertMount := true
443 type copyFile struct {
447 var copyFiles []copyFile
450 for bind := range runner.Container.Mounts {
451 binds = append(binds, bind)
453 for bind := range runner.SecretMounts {
454 if _, ok := runner.Container.Mounts[bind]; ok {
455 return nil, fmt.Errorf("secret mount %q conflicts with regular mount", bind)
457 if runner.SecretMounts[bind].Kind != "json" &&
458 runner.SecretMounts[bind].Kind != "text" {
459 return nil, fmt.Errorf("secret mount %q type is %q but only 'json' and 'text' are permitted",
460 bind, runner.SecretMounts[bind].Kind)
462 binds = append(binds, bind)
466 for _, bind := range binds {
467 mnt, notSecret := runner.Container.Mounts[bind]
469 mnt = runner.SecretMounts[bind]
471 if bind == "stdout" || bind == "stderr" {
472 // Is it a "file" mount kind?
473 if mnt.Kind != "file" {
474 return nil, fmt.Errorf("unsupported mount kind '%s' for %s: only 'file' is supported", mnt.Kind, bind)
477 // Does path start with OutputPath?
478 prefix := runner.Container.OutputPath
479 if !strings.HasSuffix(prefix, "/") {
482 if !strings.HasPrefix(mnt.Path, prefix) {
483 return nil, fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
488 // Is it a "collection" mount kind?
489 if mnt.Kind != "collection" && mnt.Kind != "json" {
490 return nil, fmt.Errorf("unsupported mount kind '%s' for stdin: only 'collection' and 'json' are supported", mnt.Kind)
494 if bind == "/etc/arvados/ca-certificates.crt" {
495 needCertMount = false
498 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
499 if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
500 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)
505 case mnt.Kind == "collection" && bind != "stdin":
507 if mnt.UUID != "" && mnt.PortableDataHash != "" {
508 return nil, fmt.Errorf("cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
512 return nil, fmt.Errorf("writing to existing collections currently not permitted")
515 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
516 } else if mnt.PortableDataHash != "" {
517 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
518 return nil, fmt.Errorf("can never write to a collection specified by portable data hash")
520 idx := strings.Index(mnt.PortableDataHash, "/")
522 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
523 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
524 runner.Container.Mounts[bind] = mnt
526 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
527 if mnt.Path != "" && mnt.Path != "." {
528 if strings.HasPrefix(mnt.Path, "./") {
529 mnt.Path = mnt.Path[2:]
530 } else if strings.HasPrefix(mnt.Path, "/") {
531 mnt.Path = mnt.Path[1:]
533 src += "/" + mnt.Path
536 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
537 arvMountCmd = append(arvMountCmd, "--mount-tmp", fmt.Sprintf("tmp%d", tmpcount))
541 if bind == runner.Container.OutputPath {
542 runner.HostOutputDir = src
543 bindmounts[bind] = bindmount{HostPath: src}
544 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
545 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
547 bindmounts[bind] = bindmount{HostPath: src}
550 bindmounts[bind] = bindmount{HostPath: src, ReadOnly: true}
552 collectionPaths = append(collectionPaths, src)
554 case mnt.Kind == "tmp":
556 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
558 return nil, fmt.Errorf("while creating mount temp dir: %v", err)
560 st, staterr := os.Stat(tmpdir)
562 return nil, fmt.Errorf("while Stat on temp dir: %v", staterr)
564 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
566 return nil, fmt.Errorf("while Chmod temp dir: %v", err)
568 bindmounts[bind] = bindmount{HostPath: tmpdir}
569 if bind == runner.Container.OutputPath {
570 runner.HostOutputDir = tmpdir
573 case mnt.Kind == "json" || mnt.Kind == "text":
575 if mnt.Kind == "json" {
576 filedata, err = json.Marshal(mnt.Content)
578 return nil, fmt.Errorf("encoding json data: %v", err)
581 text, ok := mnt.Content.(string)
583 return nil, fmt.Errorf("content for mount %q must be a string", bind)
585 filedata = []byte(text)
588 tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
590 return nil, fmt.Errorf("creating temp dir: %v", err)
592 tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
593 err = ioutil.WriteFile(tmpfn, filedata, 0444)
595 return nil, fmt.Errorf("writing temp file: %v", err)
597 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && (notSecret || runner.Container.Mounts[runner.Container.OutputPath].Kind != "collection") {
598 // In most cases, if the container
599 // specifies a literal file inside the
600 // output path, we copy it into the
601 // output directory (either a mounted
602 // collection or a staging area on the
603 // host fs). If it's a secret, it will
604 // be skipped when copying output from
605 // staging to Keep later.
606 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
608 // If a secret is outside OutputPath,
609 // we bind mount the secret file
610 // directly just like other mounts. We
611 // also use this strategy when a
612 // secret is inside OutputPath but
613 // OutputPath is a live collection, to
614 // avoid writing the secret to
615 // Keep. Attempting to remove a
616 // bind-mounted secret file from
617 // inside the container will return a
618 // "Device or resource busy" error
619 // that might not be handled well by
620 // the container, which is why we
621 // don't use this strategy when
622 // OutputPath is a staging directory.
623 bindmounts[bind] = bindmount{HostPath: tmpfn, ReadOnly: true}
626 case mnt.Kind == "git_tree":
627 tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
629 return nil, fmt.Errorf("creating temp dir: %v", err)
631 err = gitMount(mnt).extractTree(runner.ContainerArvClient, tmpdir, token)
635 bindmounts[bind] = bindmount{HostPath: tmpdir, ReadOnly: true}
639 if runner.HostOutputDir == "" {
640 return nil, fmt.Errorf("output path does not correspond to a writable mount point")
643 if needCertMount && runner.Container.RuntimeConstraints.API {
644 for _, certfile := range arvadosclient.CertFiles {
645 _, err := os.Stat(certfile)
647 bindmounts["/etc/arvados/ca-certificates.crt"] = bindmount{HostPath: certfile, ReadOnly: true}
654 // If we are only mounting collections by pdh, make
655 // sure we don't subscribe to websocket events to
656 // avoid putting undesired load on the API server
657 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id", "--disable-event-listening")
659 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
661 // the by_uuid mount point is used by singularity when writing
662 // out docker images converted to SIF
663 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_uuid")
664 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
666 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
668 return nil, fmt.Errorf("while trying to start arv-mount: %v", err)
670 if runner.hoststatReporter != nil && runner.ArvMount != nil {
671 runner.hoststatReporter.ReportPID("arv-mount", runner.ArvMount.Process.Pid)
674 for _, p := range collectionPaths {
677 return nil, fmt.Errorf("while checking that input files exist: %v", err)
681 for _, cp := range copyFiles {
682 st, err := os.Stat(cp.src)
684 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
687 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
691 target := path.Join(cp.bind, walkpath[len(cp.src):])
692 if walkinfo.Mode().IsRegular() {
693 copyerr := copyfile(walkpath, target)
697 return os.Chmod(target, walkinfo.Mode()|0777)
698 } else if walkinfo.Mode().IsDir() {
699 mkerr := os.MkdirAll(target, 0777)
703 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
705 return fmt.Errorf("source %q is not a regular file or directory", cp.src)
708 } else if st.Mode().IsRegular() {
709 err = copyfile(cp.src, cp.bind)
711 err = os.Chmod(cp.bind, st.Mode()|0777)
715 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
719 return bindmounts, nil
722 func (runner *ContainerRunner) stopHoststat() error {
723 if runner.hoststatReporter == nil {
726 runner.hoststatReporter.Stop()
727 err := runner.hoststatLogger.Close()
729 return fmt.Errorf("error closing hoststat logs: %v", err)
734 func (runner *ContainerRunner) startHoststat() error {
735 w, err := runner.NewLogWriter("hoststat")
739 runner.hoststatLogger = NewThrottledLogger(w)
740 runner.hoststatReporter = &crunchstat.Reporter{
741 Logger: log.New(runner.hoststatLogger, "", 0),
742 CgroupRoot: runner.cgroupRoot,
743 PollPeriod: runner.statInterval,
745 runner.hoststatReporter.Start()
746 runner.hoststatReporter.ReportPID("crunch-run", os.Getpid())
750 func (runner *ContainerRunner) startCrunchstat() error {
751 w, err := runner.NewLogWriter("crunchstat")
755 runner.statLogger = NewThrottledLogger(w)
756 runner.statReporter = &crunchstat.Reporter{
757 CID: runner.executor.CgroupID(),
758 Logger: log.New(runner.statLogger, "", 0),
759 CgroupParent: runner.expectCgroupParent,
760 CgroupRoot: runner.cgroupRoot,
761 PollPeriod: runner.statInterval,
762 TempDir: runner.parentTemp,
764 runner.statReporter.Start()
768 type infoCommand struct {
773 // LogHostInfo logs info about the current host, for debugging and
774 // accounting purposes. Although it's logged as "node-info", this is
775 // about the environment where crunch-run is actually running, which
776 // might differ from what's described in the node record (see
778 func (runner *ContainerRunner) LogHostInfo() (err error) {
779 w, err := runner.NewLogWriter("node-info")
784 commands := []infoCommand{
786 label: "Host Information",
787 cmd: []string{"uname", "-a"},
790 label: "CPU Information",
791 cmd: []string{"cat", "/proc/cpuinfo"},
794 label: "Memory Information",
795 cmd: []string{"cat", "/proc/meminfo"},
799 cmd: []string{"df", "-m", "/", os.TempDir()},
802 label: "Disk INodes",
803 cmd: []string{"df", "-i", "/", os.TempDir()},
807 // Run commands with informational output to be logged.
808 for _, command := range commands {
809 fmt.Fprintln(w, command.label)
810 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
813 if err := cmd.Run(); err != nil {
814 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
823 return fmt.Errorf("While closing node-info logs: %v", err)
828 // LogContainerRecord gets and saves the raw JSON container record from the API server
829 func (runner *ContainerRunner) LogContainerRecord() error {
830 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
831 if !logged && err == nil {
832 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
837 // LogNodeRecord logs the current host's InstanceType config entry (or
838 // the arvados#node record, if running via crunch-dispatch-slurm).
839 func (runner *ContainerRunner) LogNodeRecord() error {
840 if it := os.Getenv("InstanceType"); it != "" {
841 // Dispatched via arvados-dispatch-cloud. Save
842 // InstanceType config fragment received from
843 // dispatcher on stdin.
844 w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
849 _, err = io.WriteString(w, it)
855 // Dispatched via crunch-dispatch-slurm. Look up
856 // apiserver's node record corresponding to
858 hostname := os.Getenv("SLURMD_NODENAME")
860 hostname, _ = os.Hostname()
862 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
863 // The "info" field has admin-only info when
864 // obtained with a privileged token, and
865 // should not be logged.
866 node, ok := resp.(map[string]interface{})
874 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
875 writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
880 ArvClient: runner.DispatcherArvClient,
881 UUID: runner.Container.UUID,
882 loggingStream: label,
886 reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
888 return false, fmt.Errorf("error getting %s record: %v", label, err)
892 dec := json.NewDecoder(reader)
894 var resp map[string]interface{}
895 if err = dec.Decode(&resp); err != nil {
896 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
898 items, ok := resp["items"].([]interface{})
900 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
901 } else if len(items) < 1 {
907 // Re-encode it using indentation to improve readability
908 enc := json.NewEncoder(w)
909 enc.SetIndent("", " ")
910 if err = enc.Encode(items[0]); err != nil {
911 return false, fmt.Errorf("error logging %s record: %v", label, err)
915 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
920 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
921 stdoutPath := mntPath[len(runner.Container.OutputPath):]
922 index := strings.LastIndex(stdoutPath, "/")
924 subdirs := stdoutPath[:index]
926 st, err := os.Stat(runner.HostOutputDir)
928 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
930 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
931 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
933 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
937 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
939 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
942 return stdoutFile, nil
945 // CreateContainer creates the docker container.
946 func (runner *ContainerRunner) CreateContainer(imageID string, bindmounts map[string]bindmount) error {
947 var stdin io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
948 if mnt, ok := runner.Container.Mounts["stdin"]; ok {
955 collID = mnt.PortableDataHash
957 path := runner.ArvMountPoint + "/by_id/" + collID + "/" + mnt.Path
958 f, err := os.Open(path)
964 j, err := json.Marshal(mnt.Content)
966 return fmt.Errorf("error encoding stdin json data: %v", err)
968 stdin = ioutil.NopCloser(bytes.NewReader(j))
970 return fmt.Errorf("stdin mount has unsupported kind %q", mnt.Kind)
974 var stdout, stderr io.WriteCloser
975 if mnt, ok := runner.Container.Mounts["stdout"]; ok {
976 f, err := runner.getStdoutFile(mnt.Path)
981 } else if w, err := runner.NewLogWriter("stdout"); err != nil {
984 stdout = NewThrottledLogger(w)
987 if mnt, ok := runner.Container.Mounts["stderr"]; ok {
988 f, err := runner.getStdoutFile(mnt.Path)
993 } else if w, err := runner.NewLogWriter("stderr"); err != nil {
996 stderr = NewThrottledLogger(w)
999 env := runner.Container.Environment
1000 enableNetwork := runner.enableNetwork == "always"
1001 if runner.Container.RuntimeConstraints.API {
1002 enableNetwork = true
1003 tok, err := runner.ContainerToken()
1007 env = map[string]string{}
1008 for k, v := range runner.Container.Environment {
1011 env["ARVADOS_API_TOKEN"] = tok
1012 env["ARVADOS_API_HOST"] = os.Getenv("ARVADOS_API_HOST")
1013 env["ARVADOS_API_HOST_INSECURE"] = os.Getenv("ARVADOS_API_HOST_INSECURE")
1014 env["ARVADOS_KEEP_SERVICES"] = os.Getenv("ARVADOS_KEEP_SERVICES")
1016 workdir := runner.Container.Cwd
1018 // both "" and "." mean default
1021 ram := runner.Container.RuntimeConstraints.RAM
1022 if !runner.enableMemoryLimit {
1025 runner.executorStdin = stdin
1026 runner.executorStdout = stdout
1027 runner.executorStderr = stderr
1029 if runner.Container.RuntimeConstraints.CUDA.DeviceCount > 0 {
1030 nvidiaModprobe(runner.CrunchLog)
1033 return runner.executor.Create(containerSpec{
1035 VCPUs: runner.Container.RuntimeConstraints.VCPUs,
1037 WorkingDir: workdir,
1039 BindMounts: bindmounts,
1040 Command: runner.Container.Command,
1041 EnableNetwork: enableNetwork,
1042 CUDADeviceCount: runner.Container.RuntimeConstraints.CUDA.DeviceCount,
1043 NetworkMode: runner.networkMode,
1044 CgroupParent: runner.setCgroupParent,
1051 // StartContainer starts the docker container created by CreateContainer.
1052 func (runner *ContainerRunner) StartContainer() error {
1053 runner.CrunchLog.Printf("Starting container")
1054 runner.cStateLock.Lock()
1055 defer runner.cStateLock.Unlock()
1056 if runner.cCancelled {
1059 err := runner.executor.Start()
1062 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1063 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])
1065 return fmt.Errorf("could not start container: %v%s", err, advice)
1070 // WaitFinish waits for the container to terminate, capture the exit code, and
1071 // close the stdout/stderr logging.
1072 func (runner *ContainerRunner) WaitFinish() error {
1073 runner.CrunchLog.Print("Waiting for container to finish")
1074 var timeout <-chan time.Time
1075 if s := runner.Container.SchedulingParameters.MaxRunTime; s > 0 {
1076 timeout = time.After(time.Duration(s) * time.Second)
1078 ctx, cancel := context.WithCancel(context.Background())
1083 runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1085 case <-runner.ArvMountExit:
1086 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1091 exitcode, err := runner.executor.Wait(ctx)
1093 runner.checkBrokenNode(err)
1096 runner.ExitCode = &exitcode
1099 if exitcode&0x80 != 0 {
1100 // Convert raw exit status (0x80 + signal number) to a
1101 // string to log after the code, like " (signal 101)"
1102 // or " (signal 9, killed)"
1103 sig := syscall.WaitStatus(exitcode).Signal()
1104 if name := unix.SignalName(sig); name != "" {
1105 extra = fmt.Sprintf(" (signal %d, %s)", sig, name)
1107 extra = fmt.Sprintf(" (signal %d)", sig)
1110 runner.CrunchLog.Printf("Container exited with status code %d%s", exitcode, extra)
1111 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1112 "container": arvadosclient.Dict{"exit_code": exitcode},
1115 runner.CrunchLog.Printf("ignoring error updating exit_code: %s", err)
1119 if err = runner.executorStdin.Close(); err != nil {
1120 err = fmt.Errorf("error closing container stdin: %s", err)
1121 runner.CrunchLog.Printf("%s", err)
1124 if err = runner.executorStdout.Close(); err != nil {
1125 err = fmt.Errorf("error closing container stdout: %s", err)
1126 runner.CrunchLog.Printf("%s", err)
1127 if returnErr == nil {
1131 if err = runner.executorStderr.Close(); err != nil {
1132 err = fmt.Errorf("error closing container stderr: %s", err)
1133 runner.CrunchLog.Printf("%s", err)
1134 if returnErr == nil {
1139 if runner.statReporter != nil {
1140 runner.statReporter.Stop()
1141 err = runner.statLogger.Close()
1143 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
1149 func (runner *ContainerRunner) updateLogs() {
1150 ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1153 sigusr1 := make(chan os.Signal, 1)
1154 signal.Notify(sigusr1, syscall.SIGUSR1)
1155 defer signal.Stop(sigusr1)
1157 saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1158 saveAtSize := crunchLogUpdateSize
1164 saveAtTime = time.Now()
1166 runner.logMtx.Lock()
1167 done := runner.LogsPDH != nil
1168 runner.logMtx.Unlock()
1172 size := runner.LogCollection.Size()
1173 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1176 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1177 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1178 saved, err := runner.saveLogCollection(false)
1180 runner.CrunchLog.Printf("error updating log collection: %s", err)
1184 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1185 "container": arvadosclient.Dict{"log": saved.PortableDataHash},
1188 runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1196 func (runner *ContainerRunner) reportArvMountWarning(pattern, text string) {
1197 var updated arvados.Container
1198 err := runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1199 "container": arvadosclient.Dict{
1200 "runtime_status": arvadosclient.Dict{
1201 "warning": "arv-mount: " + pattern,
1202 "warningDetail": text,
1207 runner.CrunchLog.Printf("error updating container runtime_status: %s", err)
1211 // CaptureOutput saves data from the container's output directory if
1212 // needed, and updates the container output accordingly.
1213 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1214 if runner.Container.RuntimeConstraints.API {
1215 // Output may have been set directly by the container, so
1216 // refresh the container record to check.
1217 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1218 nil, &runner.Container)
1222 if runner.Container.Output != "" {
1223 // Container output is already set.
1224 runner.OutputPDH = &runner.Container.Output
1229 txt, err := (&copier{
1230 client: runner.containerClient,
1231 arvClient: runner.ContainerArvClient,
1232 keepClient: runner.ContainerKeepClient,
1233 hostOutputDir: runner.HostOutputDir,
1234 ctrOutputDir: runner.Container.OutputPath,
1235 bindmounts: bindmounts,
1236 mounts: runner.Container.Mounts,
1237 secretMounts: runner.SecretMounts,
1238 logger: runner.CrunchLog,
1243 if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1244 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1245 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1249 txt, err = fs.MarshalManifest(".")
1254 var resp arvados.Collection
1255 err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1256 "ensure_unique_name": true,
1257 "collection": arvadosclient.Dict{
1259 "name": "output for " + runner.Container.UUID,
1260 "manifest_text": txt,
1264 return fmt.Errorf("error creating output collection: %v", err)
1266 runner.OutputPDH = &resp.PortableDataHash
1270 func (runner *ContainerRunner) CleanupDirs() {
1271 if runner.ArvMount != nil {
1273 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1274 umount.Stdout = runner.CrunchLog
1275 umount.Stderr = runner.CrunchLog
1276 runner.CrunchLog.Printf("Running %v", umount.Args)
1277 umnterr := umount.Start()
1280 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1281 runner.ArvMount.Process.Kill()
1283 // If arv-mount --unmount gets stuck for any reason, we
1284 // don't want to wait for it forever. Do Wait() in a goroutine
1285 // so it doesn't block crunch-run.
1286 umountExit := make(chan error)
1288 mnterr := umount.Wait()
1290 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1292 umountExit <- mnterr
1295 for again := true; again; {
1301 case <-runner.ArvMountExit:
1303 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1304 runner.CrunchLog.Printf("Timed out waiting for unmount")
1306 umount.Process.Kill()
1308 runner.ArvMount.Process.Kill()
1312 runner.ArvMount = nil
1315 if runner.ArvMountPoint != "" {
1316 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1317 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1319 runner.ArvMountPoint = ""
1322 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1323 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1327 // CommitLogs posts the collection containing the final container logs.
1328 func (runner *ContainerRunner) CommitLogs() error {
1330 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1331 runner.cStateLock.Lock()
1332 defer runner.cStateLock.Unlock()
1334 runner.CrunchLog.Print(runner.finalState)
1336 if runner.arvMountLog != nil {
1337 runner.arvMountLog.Close()
1339 runner.CrunchLog.Close()
1341 // Closing CrunchLog above allows them to be committed to Keep at this
1342 // point, but re-open crunch log with ArvClient in case there are any
1343 // other further errors (such as failing to write the log to Keep!)
1344 // while shutting down
1345 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1346 ArvClient: runner.DispatcherArvClient,
1347 UUID: runner.Container.UUID,
1348 loggingStream: "crunch-run",
1351 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1354 if runner.keepstoreLogger != nil {
1355 // Flush any buffered logs from our local keepstore
1356 // process. Discard anything logged after this point
1357 // -- it won't end up in the log collection, so
1358 // there's no point writing it to the collectionfs.
1359 runner.keepstoreLogbuf.SetWriter(io.Discard)
1360 runner.keepstoreLogger.Close()
1361 runner.keepstoreLogger = nil
1364 if runner.LogsPDH != nil {
1365 // If we have already assigned something to LogsPDH,
1366 // we must be closing the re-opened log, which won't
1367 // end up getting attached to the container record and
1368 // therefore doesn't need to be saved as a collection
1369 // -- it exists only to send logs to other channels.
1373 saved, err := runner.saveLogCollection(true)
1375 return fmt.Errorf("error saving log collection: %s", err)
1377 runner.logMtx.Lock()
1378 defer runner.logMtx.Unlock()
1379 runner.LogsPDH = &saved.PortableDataHash
1383 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1384 runner.logMtx.Lock()
1385 defer runner.logMtx.Unlock()
1386 if runner.LogsPDH != nil {
1387 // Already finalized.
1390 updates := arvadosclient.Dict{
1391 "name": "logs for " + runner.Container.UUID,
1393 mt, err1 := runner.LogCollection.MarshalManifest(".")
1395 // Only send updated manifest text if there was no
1397 updates["manifest_text"] = mt
1400 // Even if flushing the manifest had an error, we still want
1401 // to update the log record, if possible, to push the trash_at
1402 // and delete_at times into the future. Details on bug
1405 updates["is_trashed"] = true
1407 exp := time.Now().Add(crunchLogUpdatePeriod * 24)
1408 updates["trash_at"] = exp
1409 updates["delete_at"] = exp
1411 reqBody := arvadosclient.Dict{"collection": updates}
1413 if runner.logUUID == "" {
1414 reqBody["ensure_unique_name"] = true
1415 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1417 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1420 runner.logUUID = response.UUID
1423 if err1 != nil || err2 != nil {
1424 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1429 // UpdateContainerRunning updates the container state to "Running"
1430 func (runner *ContainerRunner) UpdateContainerRunning() error {
1431 runner.cStateLock.Lock()
1432 defer runner.cStateLock.Unlock()
1433 if runner.cCancelled {
1436 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID,
1437 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running", "gateway_address": runner.gateway.Address}}, nil)
1440 // ContainerToken returns the api_token the container (and any
1441 // arv-mount processes) are allowed to use.
1442 func (runner *ContainerRunner) ContainerToken() (string, error) {
1443 if runner.token != "" {
1444 return runner.token, nil
1447 var auth arvados.APIClientAuthorization
1448 err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1452 runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1453 return runner.token, nil
1456 // UpdateContainerFinal updates the container record state on API
1457 // server to "Complete" or "Cancelled"
1458 func (runner *ContainerRunner) UpdateContainerFinal() error {
1459 update := arvadosclient.Dict{}
1460 update["state"] = runner.finalState
1461 if runner.LogsPDH != nil {
1462 update["log"] = *runner.LogsPDH
1464 if runner.ExitCode != nil {
1465 update["exit_code"] = *runner.ExitCode
1467 update["exit_code"] = nil
1469 if runner.finalState == "Complete" && runner.OutputPDH != nil {
1470 update["output"] = *runner.OutputPDH
1472 var it arvados.InstanceType
1473 if j := os.Getenv("InstanceType"); j != "" && json.Unmarshal([]byte(j), &it) == nil && it.Price > 0 {
1474 update["cost"] = it.Price * time.Now().Sub(runner.costStartTime).Seconds() / time.Hour.Seconds()
1476 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1479 // IsCancelled returns the value of Cancelled, with goroutine safety.
1480 func (runner *ContainerRunner) IsCancelled() bool {
1481 runner.cStateLock.Lock()
1482 defer runner.cStateLock.Unlock()
1483 return runner.cCancelled
1486 // NewArvLogWriter creates an ArvLogWriter
1487 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1488 writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1492 return &ArvLogWriter{
1493 ArvClient: runner.DispatcherArvClient,
1494 UUID: runner.Container.UUID,
1495 loggingStream: name,
1496 writeCloser: writer,
1500 // Run the full container lifecycle.
1501 func (runner *ContainerRunner) Run() (err error) {
1502 runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1503 runner.CrunchLog.Printf("%s", currentUserAndGroups())
1504 v, _ := exec.Command("arv-mount", "--version").CombinedOutput()
1505 runner.CrunchLog.Printf("Using FUSE mount: %s", v)
1506 runner.CrunchLog.Printf("Using container runtime: %s", runner.executor.Runtime())
1507 runner.CrunchLog.Printf("Executing container: %s", runner.Container.UUID)
1508 runner.costStartTime = time.Now()
1510 hostname, hosterr := os.Hostname()
1512 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1514 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1517 runner.finalState = "Queued"
1520 runner.CleanupDirs()
1522 runner.CrunchLog.Printf("crunch-run finished")
1523 runner.CrunchLog.Close()
1526 err = runner.fetchContainerRecord()
1530 if runner.Container.State != "Locked" {
1531 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1534 var bindmounts map[string]bindmount
1536 // checkErr prints e (unless it's nil) and sets err to
1537 // e (unless err is already non-nil). Thus, if err
1538 // hasn't already been assigned when Run() returns,
1539 // this cleanup func will cause Run() to return the
1540 // first non-nil error that is passed to checkErr().
1541 checkErr := func(errorIn string, e error) {
1545 runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1549 if runner.finalState == "Complete" {
1550 // There was an error in the finalization.
1551 runner.finalState = "Cancelled"
1555 // Log the error encountered in Run(), if any
1556 checkErr("Run", err)
1558 if runner.finalState == "Queued" {
1559 runner.UpdateContainerFinal()
1563 if runner.IsCancelled() {
1564 runner.finalState = "Cancelled"
1565 // but don't return yet -- we still want to
1566 // capture partial output and write logs
1569 if bindmounts != nil {
1570 checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1572 checkErr("stopHoststat", runner.stopHoststat())
1573 checkErr("CommitLogs", runner.CommitLogs())
1574 runner.CleanupDirs()
1575 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1578 runner.setupSignals()
1579 err = runner.startHoststat()
1583 if runner.keepstore != nil {
1584 runner.hoststatReporter.ReportPID("keepstore", runner.keepstore.Process.Pid)
1587 // set up FUSE mount and binds
1588 bindmounts, err = runner.SetupMounts()
1590 runner.finalState = "Cancelled"
1591 err = fmt.Errorf("While setting up mounts: %v", err)
1595 // check for and/or load image
1596 imageID, err := runner.LoadImage()
1598 if !runner.checkBrokenNode(err) {
1599 // Failed to load image but not due to a "broken node"
1600 // condition, probably user error.
1601 runner.finalState = "Cancelled"
1603 err = fmt.Errorf("While loading container image: %v", err)
1607 err = runner.CreateContainer(imageID, bindmounts)
1611 err = runner.LogHostInfo()
1615 err = runner.LogNodeRecord()
1619 err = runner.LogContainerRecord()
1624 if runner.IsCancelled() {
1628 err = runner.UpdateContainerRunning()
1632 runner.finalState = "Cancelled"
1634 err = runner.startCrunchstat()
1639 err = runner.StartContainer()
1641 runner.checkBrokenNode(err)
1645 err = runner.WaitFinish()
1646 if err == nil && !runner.IsCancelled() {
1647 runner.finalState = "Complete"
1652 // Fetch the current container record (uuid = runner.Container.UUID)
1653 // into runner.Container.
1654 func (runner *ContainerRunner) fetchContainerRecord() error {
1655 reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1657 return fmt.Errorf("error fetching container record: %v", err)
1659 defer reader.Close()
1661 dec := json.NewDecoder(reader)
1663 err = dec.Decode(&runner.Container)
1665 return fmt.Errorf("error decoding container record: %v", err)
1669 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1672 containerToken, err := runner.ContainerToken()
1674 return fmt.Errorf("error getting container token: %v", err)
1677 runner.ContainerArvClient, runner.ContainerKeepClient,
1678 runner.containerClient, err = runner.MkArvClient(containerToken)
1680 return fmt.Errorf("error creating container API client: %v", err)
1683 runner.ContainerKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1684 runner.DispatcherKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1686 err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1688 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1689 return fmt.Errorf("error fetching secret_mounts: %v", err)
1691 // ok && apierr.HttpStatusCode == 404, which means
1692 // secret_mounts isn't supported by this API server.
1694 runner.SecretMounts = sm.SecretMounts
1699 // NewContainerRunner creates a new container runner.
1700 func NewContainerRunner(dispatcherClient *arvados.Client,
1701 dispatcherArvClient IArvadosClient,
1702 dispatcherKeepClient IKeepClient,
1703 containerUUID string) (*ContainerRunner, error) {
1705 cr := &ContainerRunner{
1706 dispatcherClient: dispatcherClient,
1707 DispatcherArvClient: dispatcherArvClient,
1708 DispatcherKeepClient: dispatcherKeepClient,
1710 cr.NewLogWriter = cr.NewArvLogWriter
1711 cr.RunArvMount = cr.ArvMountCmd
1712 cr.MkTempDir = ioutil.TempDir
1713 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1714 cl, err := arvadosclient.MakeArvadosClient()
1716 return nil, nil, nil, err
1719 kc, err := keepclient.MakeKeepClient(cl)
1721 return nil, nil, nil, err
1723 c2 := arvados.NewClientFromEnv()
1724 c2.AuthToken = token
1725 return cl, kc, c2, nil
1728 cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1732 cr.Container.UUID = containerUUID
1733 w, err := cr.NewLogWriter("crunch-run")
1737 cr.CrunchLog = NewThrottledLogger(w)
1738 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1740 loadLogThrottleParams(dispatcherArvClient)
1746 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1747 log := log.New(stderr, "", 0)
1748 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1749 statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1750 cgroupRoot := flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1751 cgroupParent := flags.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1752 cgroupParentSubsystem := flags.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1753 caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1754 detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1755 stdinConfig := flags.Bool("stdin-config", false, "Load config and environment variables from JSON message on stdin")
1756 configFile := flags.String("config", arvados.DefaultConfigFile, "filename of cluster config file to try loading if -stdin-config=false (default is $ARVADOS_CONFIG)")
1757 sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1758 kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1759 list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes")
1760 enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1761 enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1762 networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1763 memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1764 runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1765 brokenNodeHook := flags.String("broken-node-hook", "", "script to run if node is detected to be broken (for example, Docker daemon is not running)")
1766 flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1767 version := flags.Bool("version", false, "Write version information to stdout and exit 0.")
1769 ignoreDetachFlag := false
1770 if len(args) > 0 && args[0] == "-no-detach" {
1771 // This process was invoked by a parent process, which
1772 // has passed along its own arguments, including
1773 // -detach, after the leading -no-detach flag. Strip
1774 // the leading -no-detach flag (it's not recognized by
1775 // flags.Parse()) and ignore the -detach flag that
1778 ignoreDetachFlag = true
1781 if ok, code := cmd.ParseFlags(flags, prog, args, "container-uuid", stderr); !ok {
1783 } else if *version {
1784 fmt.Fprintln(stdout, prog, cmd.Version.String())
1786 } else if !*list && flags.NArg() != 1 {
1787 fmt.Fprintf(stderr, "missing required argument: container-uuid (try -help)\n")
1791 containerUUID := flags.Arg(0)
1794 case *detach && !ignoreDetachFlag:
1795 return Detach(containerUUID, prog, args, os.Stdin, os.Stdout, os.Stderr)
1797 return KillProcess(containerUUID, syscall.Signal(*kill), os.Stdout, os.Stderr)
1799 return ListProcesses(os.Stdout, os.Stderr)
1802 if len(containerUUID) != 27 {
1803 log.Printf("usage: %s [options] UUID", prog)
1807 var keepstoreLogbuf bufThenWrite
1810 err := json.NewDecoder(stdin).Decode(&conf)
1812 log.Printf("decode stdin: %s", err)
1815 for k, v := range conf.Env {
1816 err = os.Setenv(k, v)
1818 log.Printf("setenv(%q): %s", k, err)
1822 if conf.Cluster != nil {
1823 // ClusterID is missing from the JSON
1824 // representation, but we need it to generate
1825 // a valid config file for keepstore, so we
1826 // fill it using the container UUID prefix.
1827 conf.Cluster.ClusterID = containerUUID[:5]
1830 conf = hpcConfData(containerUUID, *configFile, io.MultiWriter(&keepstoreLogbuf, stderr))
1833 log.Printf("crunch-run %s started", cmd.Version.String())
1836 if *caCertsPath != "" {
1837 arvadosclient.CertFiles = []string{*caCertsPath}
1840 keepstore, err := startLocalKeepstore(conf, io.MultiWriter(&keepstoreLogbuf, stderr))
1845 if keepstore != nil {
1846 defer keepstore.Process.Kill()
1849 api, err := arvadosclient.MakeArvadosClient()
1851 log.Printf("%s: %v", containerUUID, err)
1856 kc, err := keepclient.MakeKeepClient(api)
1858 log.Printf("%s: %v", containerUUID, err)
1861 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1864 cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
1870 cr.keepstore = keepstore
1871 if keepstore == nil {
1872 // Log explanation (if any) for why we're not running
1873 // a local keepstore.
1874 var buf bytes.Buffer
1875 keepstoreLogbuf.SetWriter(&buf)
1877 cr.CrunchLog.Printf("%s", strings.TrimSpace(buf.String()))
1879 } else if logWhat := conf.Cluster.Containers.LocalKeepLogsToContainerLog; logWhat == "none" {
1880 cr.CrunchLog.Printf("using local keepstore process (pid %d) at %s", keepstore.Process.Pid, os.Getenv("ARVADOS_KEEP_SERVICES"))
1881 keepstoreLogbuf.SetWriter(io.Discard)
1883 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"))
1884 logwriter, err := cr.NewLogWriter("keepstore")
1889 cr.keepstoreLogger = NewThrottledLogger(logwriter)
1891 var writer io.WriteCloser = cr.keepstoreLogger
1892 if logWhat == "errors" {
1893 writer = &filterKeepstoreErrorsOnly{WriteCloser: writer}
1894 } else if logWhat != "all" {
1895 // should have been caught earlier by
1896 // dispatcher's config loader
1897 log.Printf("invalid value for Containers.LocalKeepLogsToContainerLog: %q", logWhat)
1900 err = keepstoreLogbuf.SetWriter(writer)
1905 cr.keepstoreLogbuf = &keepstoreLogbuf
1908 switch *runtimeEngine {
1910 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
1912 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
1914 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
1915 cr.CrunchLog.Close()
1919 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
1920 cr.checkBrokenNode(err)
1921 cr.CrunchLog.Close()
1924 defer cr.executor.Close()
1926 cr.brokenNodeHook = *brokenNodeHook
1928 gwAuthSecret := os.Getenv("GatewayAuthSecret")
1929 os.Unsetenv("GatewayAuthSecret")
1930 if gwAuthSecret == "" {
1931 // not safe to run a gateway service without an auth
1933 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAuthSecret was not provided by dispatcher)")
1935 gwListen := os.Getenv("GatewayAddress")
1936 cr.gateway = Gateway{
1938 AuthSecret: gwAuthSecret,
1939 ContainerUUID: containerUUID,
1940 Target: cr.executor,
1944 // Direct connection won't work, so we use the
1945 // gateway_address field to indicate the
1946 // internalURL of the controller process that
1947 // has the current tunnel connection.
1948 cr.gateway.ArvadosClient = cr.dispatcherClient
1949 cr.gateway.UpdateTunnelURL = func(url string) {
1950 cr.gateway.Address = "tunnel " + url
1951 cr.DispatcherArvClient.Update("containers", containerUUID,
1952 arvadosclient.Dict{"container": arvadosclient.Dict{"gateway_address": cr.gateway.Address}}, nil)
1955 err = cr.gateway.Start()
1957 log.Printf("error starting gateway server: %s", err)
1962 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
1964 log.Printf("%s: %v", containerUUID, tmperr)
1968 cr.parentTemp = parentTemp
1969 cr.statInterval = *statInterval
1970 cr.cgroupRoot = *cgroupRoot
1971 cr.expectCgroupParent = *cgroupParent
1972 cr.enableMemoryLimit = *enableMemoryLimit
1973 cr.enableNetwork = *enableNetwork
1974 cr.networkMode = *networkMode
1975 if *cgroupParentSubsystem != "" {
1976 p, err := findCgroup(*cgroupParentSubsystem)
1978 log.Printf("fatal: cgroup parent subsystem: %s", err)
1981 cr.setCgroupParent = p
1982 cr.expectCgroupParent = p
1987 if *memprofile != "" {
1988 f, err := os.Create(*memprofile)
1990 log.Printf("could not create memory profile: %s", err)
1992 runtime.GC() // get up-to-date statistics
1993 if err := pprof.WriteHeapProfile(f); err != nil {
1994 log.Printf("could not write memory profile: %s", err)
1996 closeerr := f.Close()
1997 if closeerr != nil {
1998 log.Printf("closing memprofile file: %s", err)
2003 log.Printf("%s: %v", containerUUID, runerr)
2009 // Try to load ConfigData in hpc (slurm/lsf) environment. This means
2010 // loading the cluster config from the specified file and (if that
2011 // works) getting the runtime_constraints container field from
2012 // controller to determine # VCPUs so we can calculate KeepBuffers.
2013 func hpcConfData(uuid string, configFile string, stderr io.Writer) ConfigData {
2015 conf.Cluster = loadClusterConfigFile(configFile, stderr)
2016 if conf.Cluster == nil {
2017 // skip loading the container record -- we won't be
2018 // able to start local keepstore anyway.
2021 arv, err := arvadosclient.MakeArvadosClient()
2023 fmt.Fprintf(stderr, "error setting up arvadosclient: %s\n", err)
2027 var ctr arvados.Container
2028 err = arv.Call("GET", "containers", uuid, "", arvadosclient.Dict{"select": []string{"runtime_constraints"}}, &ctr)
2030 fmt.Fprintf(stderr, "error getting container record: %s\n", err)
2033 if ctr.RuntimeConstraints.VCPUs > 0 {
2034 conf.KeepBuffers = ctr.RuntimeConstraints.VCPUs * conf.Cluster.Containers.LocalKeepBlobBuffersPerVCPU
2039 // Load cluster config file from given path. If an error occurs, log
2040 // the error to stderr and return nil.
2041 func loadClusterConfigFile(path string, stderr io.Writer) *arvados.Cluster {
2042 ldr := config.NewLoader(&bytes.Buffer{}, ctxlog.New(stderr, "plain", "info"))
2044 cfg, err := ldr.Load()
2046 fmt.Fprintf(stderr, "could not load config file %s: %s\n", path, err)
2049 cluster, err := cfg.GetCluster("")
2051 fmt.Fprintf(stderr, "could not use config file %s: %s\n", path, err)
2054 fmt.Fprintf(stderr, "loaded config file %s\n", path)
2058 func startLocalKeepstore(configData ConfigData, logbuf io.Writer) (*exec.Cmd, error) {
2059 if configData.KeepBuffers < 1 {
2060 fmt.Fprintf(logbuf, "not starting a local keepstore process because KeepBuffers=%v in config\n", configData.KeepBuffers)
2063 if configData.Cluster == nil {
2064 fmt.Fprint(logbuf, "not starting a local keepstore process because cluster config file was not loaded\n")
2067 for uuid, vol := range configData.Cluster.Volumes {
2068 if len(vol.AccessViaHosts) > 0 {
2069 fmt.Fprintf(logbuf, "not starting a local keepstore process because a volume (%s) uses AccessViaHosts\n", uuid)
2072 if !vol.ReadOnly && vol.Replication < configData.Cluster.Collections.DefaultReplication {
2073 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)
2078 // Rather than have an alternate way to tell keepstore how
2079 // many buffers to use when starting it this way, we just
2080 // modify the cluster configuration that we feed it on stdin.
2081 configData.Cluster.API.MaxKeepBlobBuffers = configData.KeepBuffers
2083 localaddr := localKeepstoreAddr()
2084 ln, err := net.Listen("tcp", net.JoinHostPort(localaddr, "0"))
2088 _, port, err := net.SplitHostPort(ln.Addr().String())
2094 url := "http://" + net.JoinHostPort(localaddr, port)
2096 fmt.Fprintf(logbuf, "starting keepstore on %s\n", url)
2098 var confJSON bytes.Buffer
2099 err = json.NewEncoder(&confJSON).Encode(arvados.Config{
2100 Clusters: map[string]arvados.Cluster{
2101 configData.Cluster.ClusterID: *configData.Cluster,
2107 cmd := exec.Command("/proc/self/exe", "keepstore", "-config=-")
2108 if target, err := os.Readlink(cmd.Path); err == nil && strings.HasSuffix(target, ".test") {
2109 // If we're a 'go test' process, running
2110 // /proc/self/exe would start the test suite in a
2111 // child process, which is not what we want.
2112 cmd.Path, _ = exec.LookPath("go")
2113 cmd.Args = append([]string{"go", "run", "../../cmd/arvados-server"}, cmd.Args[1:]...)
2114 cmd.Env = os.Environ()
2116 cmd.Stdin = &confJSON
2119 cmd.Env = append(cmd.Env,
2121 "ARVADOS_SERVICE_INTERNAL_URL="+url)
2124 return nil, fmt.Errorf("error starting keepstore process: %w", err)
2131 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10))
2133 poll := time.NewTicker(time.Second / 10)
2135 client := http.Client{}
2137 testReq, err := http.NewRequestWithContext(ctx, "GET", url+"/_health/ping", nil)
2138 testReq.Header.Set("Authorization", "Bearer "+configData.Cluster.ManagementToken)
2142 resp, err := client.Do(testReq)
2145 if resp.StatusCode == http.StatusOK {
2150 return nil, fmt.Errorf("keepstore child process exited")
2152 if ctx.Err() != nil {
2153 return nil, fmt.Errorf("timed out waiting for new keepstore process to report healthy")
2156 os.Setenv("ARVADOS_KEEP_SERVICES", url)
2160 // return current uid, gid, groups in a format suitable for logging:
2161 // "crunch-run process has uid=1234(arvados) gid=1234(arvados)
2162 // groups=1234(arvados),114(fuse)"
2163 func currentUserAndGroups() string {
2164 u, err := user.Current()
2166 return fmt.Sprintf("error getting current user ID: %s", err)
2168 s := fmt.Sprintf("crunch-run process has uid=%s(%s) gid=%s", u.Uid, u.Username, u.Gid)
2169 if g, err := user.LookupGroupId(u.Gid); err == nil {
2170 s += fmt.Sprintf("(%s)", g.Name)
2173 if gids, err := u.GroupIds(); err == nil {
2174 for i, gid := range gids {
2179 if g, err := user.LookupGroupId(gid); err == nil {
2180 s += fmt.Sprintf("(%s)", g.Name)
2187 // Return a suitable local interface address for a local keepstore
2188 // service. Currently this is the numerically lowest non-loopback ipv4
2189 // address assigned to a local interface that is not in any of the
2190 // link-local/vpn/loopback ranges 169.254/16, 100.64/10, or 127/8.
2191 func localKeepstoreAddr() string {
2193 // Ignore error (proceed with zero IPs)
2194 addrs, _ := processIPs(os.Getpid())
2195 for addr := range addrs {
2196 ip := net.ParseIP(addr)
2201 if ip.Mask(net.CIDRMask(8, 32)).Equal(net.IPv4(127, 0, 0, 0)) ||
2202 ip.Mask(net.CIDRMask(10, 32)).Equal(net.IPv4(100, 64, 0, 0)) ||
2203 ip.Mask(net.CIDRMask(16, 32)).Equal(net.IPv4(169, 254, 0, 0)) {
2207 ips = append(ips, ip)
2212 sort.Slice(ips, func(ii, jj int) bool {
2213 i, j := ips[ii], ips[jj]
2214 if len(i) != len(j) {
2215 return len(i) < len(j)
2224 return ips[0].String()