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")
432 arvMountCmd = append(arvMountCmd, "--disk-cache", "--disk-cache-dir", keepcachedir, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheDisk))
434 else if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
435 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
438 collectionPaths := []string{}
439 needCertMount := true
440 type copyFile struct {
444 var copyFiles []copyFile
447 for bind := range runner.Container.Mounts {
448 binds = append(binds, bind)
450 for bind := range runner.SecretMounts {
451 if _, ok := runner.Container.Mounts[bind]; ok {
452 return nil, fmt.Errorf("secret mount %q conflicts with regular mount", bind)
454 if runner.SecretMounts[bind].Kind != "json" &&
455 runner.SecretMounts[bind].Kind != "text" {
456 return nil, fmt.Errorf("secret mount %q type is %q but only 'json' and 'text' are permitted",
457 bind, runner.SecretMounts[bind].Kind)
459 binds = append(binds, bind)
463 for _, bind := range binds {
464 mnt, notSecret := runner.Container.Mounts[bind]
466 mnt = runner.SecretMounts[bind]
468 if bind == "stdout" || bind == "stderr" {
469 // Is it a "file" mount kind?
470 if mnt.Kind != "file" {
471 return nil, fmt.Errorf("unsupported mount kind '%s' for %s: only 'file' is supported", mnt.Kind, bind)
474 // Does path start with OutputPath?
475 prefix := runner.Container.OutputPath
476 if !strings.HasSuffix(prefix, "/") {
479 if !strings.HasPrefix(mnt.Path, prefix) {
480 return nil, fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
485 // Is it a "collection" mount kind?
486 if mnt.Kind != "collection" && mnt.Kind != "json" {
487 return nil, fmt.Errorf("unsupported mount kind '%s' for stdin: only 'collection' and 'json' are supported", mnt.Kind)
491 if bind == "/etc/arvados/ca-certificates.crt" {
492 needCertMount = false
495 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
496 if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
497 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)
502 case mnt.Kind == "collection" && bind != "stdin":
504 if mnt.UUID != "" && mnt.PortableDataHash != "" {
505 return nil, fmt.Errorf("cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
509 return nil, fmt.Errorf("writing to existing collections currently not permitted")
512 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
513 } else if mnt.PortableDataHash != "" {
514 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
515 return nil, fmt.Errorf("can never write to a collection specified by portable data hash")
517 idx := strings.Index(mnt.PortableDataHash, "/")
519 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
520 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
521 runner.Container.Mounts[bind] = mnt
523 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
524 if mnt.Path != "" && mnt.Path != "." {
525 if strings.HasPrefix(mnt.Path, "./") {
526 mnt.Path = mnt.Path[2:]
527 } else if strings.HasPrefix(mnt.Path, "/") {
528 mnt.Path = mnt.Path[1:]
530 src += "/" + mnt.Path
533 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
534 arvMountCmd = append(arvMountCmd, "--mount-tmp", fmt.Sprintf("tmp%d", tmpcount))
538 if bind == runner.Container.OutputPath {
539 runner.HostOutputDir = src
540 bindmounts[bind] = bindmount{HostPath: src}
541 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
542 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
544 bindmounts[bind] = bindmount{HostPath: src}
547 bindmounts[bind] = bindmount{HostPath: src, ReadOnly: true}
549 collectionPaths = append(collectionPaths, src)
551 case mnt.Kind == "tmp":
553 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
555 return nil, fmt.Errorf("while creating mount temp dir: %v", err)
557 st, staterr := os.Stat(tmpdir)
559 return nil, fmt.Errorf("while Stat on temp dir: %v", staterr)
561 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
563 return nil, fmt.Errorf("while Chmod temp dir: %v", err)
565 bindmounts[bind] = bindmount{HostPath: tmpdir}
566 if bind == runner.Container.OutputPath {
567 runner.HostOutputDir = tmpdir
570 case mnt.Kind == "json" || mnt.Kind == "text":
572 if mnt.Kind == "json" {
573 filedata, err = json.Marshal(mnt.Content)
575 return nil, fmt.Errorf("encoding json data: %v", err)
578 text, ok := mnt.Content.(string)
580 return nil, fmt.Errorf("content for mount %q must be a string", bind)
582 filedata = []byte(text)
585 tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
587 return nil, fmt.Errorf("creating temp dir: %v", err)
589 tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
590 err = ioutil.WriteFile(tmpfn, filedata, 0444)
592 return nil, fmt.Errorf("writing temp file: %v", err)
594 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && (notSecret || runner.Container.Mounts[runner.Container.OutputPath].Kind != "collection") {
595 // In most cases, if the container
596 // specifies a literal file inside the
597 // output path, we copy it into the
598 // output directory (either a mounted
599 // collection or a staging area on the
600 // host fs). If it's a secret, it will
601 // be skipped when copying output from
602 // staging to Keep later.
603 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
605 // If a secret is outside OutputPath,
606 // we bind mount the secret file
607 // directly just like other mounts. We
608 // also use this strategy when a
609 // secret is inside OutputPath but
610 // OutputPath is a live collection, to
611 // avoid writing the secret to
612 // Keep. Attempting to remove a
613 // bind-mounted secret file from
614 // inside the container will return a
615 // "Device or resource busy" error
616 // that might not be handled well by
617 // the container, which is why we
618 // don't use this strategy when
619 // OutputPath is a staging directory.
620 bindmounts[bind] = bindmount{HostPath: tmpfn, ReadOnly: true}
623 case mnt.Kind == "git_tree":
624 tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
626 return nil, fmt.Errorf("creating temp dir: %v", err)
628 err = gitMount(mnt).extractTree(runner.ContainerArvClient, tmpdir, token)
632 bindmounts[bind] = bindmount{HostPath: tmpdir, ReadOnly: true}
636 if runner.HostOutputDir == "" {
637 return nil, fmt.Errorf("output path does not correspond to a writable mount point")
640 if needCertMount && runner.Container.RuntimeConstraints.API {
641 for _, certfile := range arvadosclient.CertFiles {
642 _, err := os.Stat(certfile)
644 bindmounts["/etc/arvados/ca-certificates.crt"] = bindmount{HostPath: certfile, ReadOnly: true}
651 // If we are only mounting collections by pdh, make
652 // sure we don't subscribe to websocket events to
653 // avoid putting undesired load on the API server
654 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id", "--disable-event-listening")
656 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
658 // the by_uuid mount point is used by singularity when writing
659 // out docker images converted to SIF
660 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_uuid")
661 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
663 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
665 return nil, fmt.Errorf("while trying to start arv-mount: %v", err)
668 for _, p := range collectionPaths {
671 return nil, fmt.Errorf("while checking that input files exist: %v", err)
675 for _, cp := range copyFiles {
676 st, err := os.Stat(cp.src)
678 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
681 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
685 target := path.Join(cp.bind, walkpath[len(cp.src):])
686 if walkinfo.Mode().IsRegular() {
687 copyerr := copyfile(walkpath, target)
691 return os.Chmod(target, walkinfo.Mode()|0777)
692 } else if walkinfo.Mode().IsDir() {
693 mkerr := os.MkdirAll(target, 0777)
697 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
699 return fmt.Errorf("source %q is not a regular file or directory", cp.src)
702 } else if st.Mode().IsRegular() {
703 err = copyfile(cp.src, cp.bind)
705 err = os.Chmod(cp.bind, st.Mode()|0777)
709 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
713 return bindmounts, nil
716 func (runner *ContainerRunner) stopHoststat() error {
717 if runner.hoststatReporter == nil {
720 runner.hoststatReporter.Stop()
721 err := runner.hoststatLogger.Close()
723 return fmt.Errorf("error closing hoststat logs: %v", err)
728 func (runner *ContainerRunner) startHoststat() error {
729 w, err := runner.NewLogWriter("hoststat")
733 runner.hoststatLogger = NewThrottledLogger(w)
734 runner.hoststatReporter = &crunchstat.Reporter{
735 Logger: log.New(runner.hoststatLogger, "", 0),
736 CgroupRoot: runner.cgroupRoot,
737 PollPeriod: runner.statInterval,
739 runner.hoststatReporter.Start()
743 func (runner *ContainerRunner) startCrunchstat() error {
744 w, err := runner.NewLogWriter("crunchstat")
748 runner.statLogger = NewThrottledLogger(w)
749 runner.statReporter = &crunchstat.Reporter{
750 CID: runner.executor.CgroupID(),
751 Logger: log.New(runner.statLogger, "", 0),
752 CgroupParent: runner.expectCgroupParent,
753 CgroupRoot: runner.cgroupRoot,
754 PollPeriod: runner.statInterval,
755 TempDir: runner.parentTemp,
757 runner.statReporter.Start()
761 type infoCommand struct {
766 // LogHostInfo logs info about the current host, for debugging and
767 // accounting purposes. Although it's logged as "node-info", this is
768 // about the environment where crunch-run is actually running, which
769 // might differ from what's described in the node record (see
771 func (runner *ContainerRunner) LogHostInfo() (err error) {
772 w, err := runner.NewLogWriter("node-info")
777 commands := []infoCommand{
779 label: "Host Information",
780 cmd: []string{"uname", "-a"},
783 label: "CPU Information",
784 cmd: []string{"cat", "/proc/cpuinfo"},
787 label: "Memory Information",
788 cmd: []string{"cat", "/proc/meminfo"},
792 cmd: []string{"df", "-m", "/", os.TempDir()},
795 label: "Disk INodes",
796 cmd: []string{"df", "-i", "/", os.TempDir()},
800 // Run commands with informational output to be logged.
801 for _, command := range commands {
802 fmt.Fprintln(w, command.label)
803 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
806 if err := cmd.Run(); err != nil {
807 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
816 return fmt.Errorf("While closing node-info logs: %v", err)
821 // LogContainerRecord gets and saves the raw JSON container record from the API server
822 func (runner *ContainerRunner) LogContainerRecord() error {
823 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
824 if !logged && err == nil {
825 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
830 // LogNodeRecord logs the current host's InstanceType config entry (or
831 // the arvados#node record, if running via crunch-dispatch-slurm).
832 func (runner *ContainerRunner) LogNodeRecord() error {
833 if it := os.Getenv("InstanceType"); it != "" {
834 // Dispatched via arvados-dispatch-cloud. Save
835 // InstanceType config fragment received from
836 // dispatcher on stdin.
837 w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
842 _, err = io.WriteString(w, it)
848 // Dispatched via crunch-dispatch-slurm. Look up
849 // apiserver's node record corresponding to
851 hostname := os.Getenv("SLURMD_NODENAME")
853 hostname, _ = os.Hostname()
855 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
856 // The "info" field has admin-only info when
857 // obtained with a privileged token, and
858 // should not be logged.
859 node, ok := resp.(map[string]interface{})
867 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
868 writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
873 ArvClient: runner.DispatcherArvClient,
874 UUID: runner.Container.UUID,
875 loggingStream: label,
879 reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
881 return false, fmt.Errorf("error getting %s record: %v", label, err)
885 dec := json.NewDecoder(reader)
887 var resp map[string]interface{}
888 if err = dec.Decode(&resp); err != nil {
889 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
891 items, ok := resp["items"].([]interface{})
893 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
894 } else if len(items) < 1 {
900 // Re-encode it using indentation to improve readability
901 enc := json.NewEncoder(w)
902 enc.SetIndent("", " ")
903 if err = enc.Encode(items[0]); err != nil {
904 return false, fmt.Errorf("error logging %s record: %v", label, err)
908 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
913 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
914 stdoutPath := mntPath[len(runner.Container.OutputPath):]
915 index := strings.LastIndex(stdoutPath, "/")
917 subdirs := stdoutPath[:index]
919 st, err := os.Stat(runner.HostOutputDir)
921 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
923 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
924 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
926 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
930 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
932 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
935 return stdoutFile, nil
938 // CreateContainer creates the docker container.
939 func (runner *ContainerRunner) CreateContainer(imageID string, bindmounts map[string]bindmount) error {
940 var stdin io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
941 if mnt, ok := runner.Container.Mounts["stdin"]; ok {
948 collID = mnt.PortableDataHash
950 path := runner.ArvMountPoint + "/by_id/" + collID + "/" + mnt.Path
951 f, err := os.Open(path)
957 j, err := json.Marshal(mnt.Content)
959 return fmt.Errorf("error encoding stdin json data: %v", err)
961 stdin = ioutil.NopCloser(bytes.NewReader(j))
963 return fmt.Errorf("stdin mount has unsupported kind %q", mnt.Kind)
967 var stdout, stderr io.WriteCloser
968 if mnt, ok := runner.Container.Mounts["stdout"]; ok {
969 f, err := runner.getStdoutFile(mnt.Path)
974 } else if w, err := runner.NewLogWriter("stdout"); err != nil {
977 stdout = NewThrottledLogger(w)
980 if mnt, ok := runner.Container.Mounts["stderr"]; ok {
981 f, err := runner.getStdoutFile(mnt.Path)
986 } else if w, err := runner.NewLogWriter("stderr"); err != nil {
989 stderr = NewThrottledLogger(w)
992 env := runner.Container.Environment
993 enableNetwork := runner.enableNetwork == "always"
994 if runner.Container.RuntimeConstraints.API {
996 tok, err := runner.ContainerToken()
1000 env = map[string]string{}
1001 for k, v := range runner.Container.Environment {
1004 env["ARVADOS_API_TOKEN"] = tok
1005 env["ARVADOS_API_HOST"] = os.Getenv("ARVADOS_API_HOST")
1006 env["ARVADOS_API_HOST_INSECURE"] = os.Getenv("ARVADOS_API_HOST_INSECURE")
1007 env["ARVADOS_KEEP_SERVICES"] = os.Getenv("ARVADOS_KEEP_SERVICES")
1009 workdir := runner.Container.Cwd
1011 // both "" and "." mean default
1014 ram := runner.Container.RuntimeConstraints.RAM
1015 if !runner.enableMemoryLimit {
1018 runner.executorStdin = stdin
1019 runner.executorStdout = stdout
1020 runner.executorStderr = stderr
1022 if runner.Container.RuntimeConstraints.CUDA.DeviceCount > 0 {
1023 nvidiaModprobe(runner.CrunchLog)
1026 return runner.executor.Create(containerSpec{
1028 VCPUs: runner.Container.RuntimeConstraints.VCPUs,
1030 WorkingDir: workdir,
1032 BindMounts: bindmounts,
1033 Command: runner.Container.Command,
1034 EnableNetwork: enableNetwork,
1035 CUDADeviceCount: runner.Container.RuntimeConstraints.CUDA.DeviceCount,
1036 NetworkMode: runner.networkMode,
1037 CgroupParent: runner.setCgroupParent,
1044 // StartContainer starts the docker container created by CreateContainer.
1045 func (runner *ContainerRunner) StartContainer() error {
1046 runner.CrunchLog.Printf("Starting container")
1047 runner.cStateLock.Lock()
1048 defer runner.cStateLock.Unlock()
1049 if runner.cCancelled {
1052 err := runner.executor.Start()
1055 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1056 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])
1058 return fmt.Errorf("could not start container: %v%s", err, advice)
1063 // WaitFinish waits for the container to terminate, capture the exit code, and
1064 // close the stdout/stderr logging.
1065 func (runner *ContainerRunner) WaitFinish() error {
1066 runner.CrunchLog.Print("Waiting for container to finish")
1067 var timeout <-chan time.Time
1068 if s := runner.Container.SchedulingParameters.MaxRunTime; s > 0 {
1069 timeout = time.After(time.Duration(s) * time.Second)
1071 ctx, cancel := context.WithCancel(context.Background())
1076 runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1078 case <-runner.ArvMountExit:
1079 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1084 exitcode, err := runner.executor.Wait(ctx)
1086 runner.checkBrokenNode(err)
1089 runner.ExitCode = &exitcode
1092 if exitcode&0x80 != 0 {
1093 // Convert raw exit status (0x80 + signal number) to a
1094 // string to log after the code, like " (signal 101)"
1095 // or " (signal 9, killed)"
1096 sig := syscall.WaitStatus(exitcode).Signal()
1097 if name := unix.SignalName(sig); name != "" {
1098 extra = fmt.Sprintf(" (signal %d, %s)", sig, name)
1100 extra = fmt.Sprintf(" (signal %d)", sig)
1103 runner.CrunchLog.Printf("Container exited with status code %d%s", exitcode, extra)
1104 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1105 "container": arvadosclient.Dict{"exit_code": exitcode},
1108 runner.CrunchLog.Printf("ignoring error updating exit_code: %s", err)
1112 if err = runner.executorStdin.Close(); err != nil {
1113 err = fmt.Errorf("error closing container stdin: %s", err)
1114 runner.CrunchLog.Printf("%s", err)
1117 if err = runner.executorStdout.Close(); err != nil {
1118 err = fmt.Errorf("error closing container stdout: %s", err)
1119 runner.CrunchLog.Printf("%s", err)
1120 if returnErr == nil {
1124 if err = runner.executorStderr.Close(); err != nil {
1125 err = fmt.Errorf("error closing container stderr: %s", err)
1126 runner.CrunchLog.Printf("%s", err)
1127 if returnErr == nil {
1132 if runner.statReporter != nil {
1133 runner.statReporter.Stop()
1134 err = runner.statLogger.Close()
1136 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
1142 func (runner *ContainerRunner) updateLogs() {
1143 ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1146 sigusr1 := make(chan os.Signal, 1)
1147 signal.Notify(sigusr1, syscall.SIGUSR1)
1148 defer signal.Stop(sigusr1)
1150 saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1151 saveAtSize := crunchLogUpdateSize
1157 saveAtTime = time.Now()
1159 runner.logMtx.Lock()
1160 done := runner.LogsPDH != nil
1161 runner.logMtx.Unlock()
1165 size := runner.LogCollection.Size()
1166 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1169 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1170 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1171 saved, err := runner.saveLogCollection(false)
1173 runner.CrunchLog.Printf("error updating log collection: %s", err)
1177 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1178 "container": arvadosclient.Dict{"log": saved.PortableDataHash},
1181 runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1189 func (runner *ContainerRunner) reportArvMountWarning(pattern, text string) {
1190 var updated arvados.Container
1191 err := runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1192 "container": arvadosclient.Dict{
1193 "runtime_status": arvadosclient.Dict{
1194 "warning": "arv-mount: " + pattern,
1195 "warningDetail": text,
1200 runner.CrunchLog.Printf("error updating container runtime_status: %s", err)
1204 // CaptureOutput saves data from the container's output directory if
1205 // needed, and updates the container output accordingly.
1206 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1207 if runner.Container.RuntimeConstraints.API {
1208 // Output may have been set directly by the container, so
1209 // refresh the container record to check.
1210 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1211 nil, &runner.Container)
1215 if runner.Container.Output != "" {
1216 // Container output is already set.
1217 runner.OutputPDH = &runner.Container.Output
1222 txt, err := (&copier{
1223 client: runner.containerClient,
1224 arvClient: runner.ContainerArvClient,
1225 keepClient: runner.ContainerKeepClient,
1226 hostOutputDir: runner.HostOutputDir,
1227 ctrOutputDir: runner.Container.OutputPath,
1228 bindmounts: bindmounts,
1229 mounts: runner.Container.Mounts,
1230 secretMounts: runner.SecretMounts,
1231 logger: runner.CrunchLog,
1236 if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1237 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1238 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1242 txt, err = fs.MarshalManifest(".")
1247 var resp arvados.Collection
1248 err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1249 "ensure_unique_name": true,
1250 "collection": arvadosclient.Dict{
1252 "name": "output for " + runner.Container.UUID,
1253 "manifest_text": txt,
1257 return fmt.Errorf("error creating output collection: %v", err)
1259 runner.OutputPDH = &resp.PortableDataHash
1263 func (runner *ContainerRunner) CleanupDirs() {
1264 if runner.ArvMount != nil {
1266 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1267 umount.Stdout = runner.CrunchLog
1268 umount.Stderr = runner.CrunchLog
1269 runner.CrunchLog.Printf("Running %v", umount.Args)
1270 umnterr := umount.Start()
1273 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1274 runner.ArvMount.Process.Kill()
1276 // If arv-mount --unmount gets stuck for any reason, we
1277 // don't want to wait for it forever. Do Wait() in a goroutine
1278 // so it doesn't block crunch-run.
1279 umountExit := make(chan error)
1281 mnterr := umount.Wait()
1283 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1285 umountExit <- mnterr
1288 for again := true; again; {
1294 case <-runner.ArvMountExit:
1296 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1297 runner.CrunchLog.Printf("Timed out waiting for unmount")
1299 umount.Process.Kill()
1301 runner.ArvMount.Process.Kill()
1305 runner.ArvMount = nil
1308 if runner.ArvMountPoint != "" {
1309 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1310 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1312 runner.ArvMountPoint = ""
1315 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1316 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1320 // CommitLogs posts the collection containing the final container logs.
1321 func (runner *ContainerRunner) CommitLogs() error {
1323 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1324 runner.cStateLock.Lock()
1325 defer runner.cStateLock.Unlock()
1327 runner.CrunchLog.Print(runner.finalState)
1329 if runner.arvMountLog != nil {
1330 runner.arvMountLog.Close()
1332 runner.CrunchLog.Close()
1334 // Closing CrunchLog above allows them to be committed to Keep at this
1335 // point, but re-open crunch log with ArvClient in case there are any
1336 // other further errors (such as failing to write the log to Keep!)
1337 // while shutting down
1338 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1339 ArvClient: runner.DispatcherArvClient,
1340 UUID: runner.Container.UUID,
1341 loggingStream: "crunch-run",
1344 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1347 if runner.keepstoreLogger != nil {
1348 // Flush any buffered logs from our local keepstore
1349 // process. Discard anything logged after this point
1350 // -- it won't end up in the log collection, so
1351 // there's no point writing it to the collectionfs.
1352 runner.keepstoreLogbuf.SetWriter(io.Discard)
1353 runner.keepstoreLogger.Close()
1354 runner.keepstoreLogger = nil
1357 if runner.LogsPDH != nil {
1358 // If we have already assigned something to LogsPDH,
1359 // we must be closing the re-opened log, which won't
1360 // end up getting attached to the container record and
1361 // therefore doesn't need to be saved as a collection
1362 // -- it exists only to send logs to other channels.
1366 saved, err := runner.saveLogCollection(true)
1368 return fmt.Errorf("error saving log collection: %s", err)
1370 runner.logMtx.Lock()
1371 defer runner.logMtx.Unlock()
1372 runner.LogsPDH = &saved.PortableDataHash
1376 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1377 runner.logMtx.Lock()
1378 defer runner.logMtx.Unlock()
1379 if runner.LogsPDH != nil {
1380 // Already finalized.
1383 updates := arvadosclient.Dict{
1384 "name": "logs for " + runner.Container.UUID,
1386 mt, err1 := runner.LogCollection.MarshalManifest(".")
1388 // Only send updated manifest text if there was no
1390 updates["manifest_text"] = mt
1393 // Even if flushing the manifest had an error, we still want
1394 // to update the log record, if possible, to push the trash_at
1395 // and delete_at times into the future. Details on bug
1398 updates["is_trashed"] = true
1400 exp := time.Now().Add(crunchLogUpdatePeriod * 24)
1401 updates["trash_at"] = exp
1402 updates["delete_at"] = exp
1404 reqBody := arvadosclient.Dict{"collection": updates}
1406 if runner.logUUID == "" {
1407 reqBody["ensure_unique_name"] = true
1408 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1410 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1413 runner.logUUID = response.UUID
1416 if err1 != nil || err2 != nil {
1417 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1422 // UpdateContainerRunning updates the container state to "Running"
1423 func (runner *ContainerRunner) UpdateContainerRunning() error {
1424 runner.cStateLock.Lock()
1425 defer runner.cStateLock.Unlock()
1426 if runner.cCancelled {
1429 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID,
1430 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running", "gateway_address": runner.gateway.Address}}, nil)
1433 // ContainerToken returns the api_token the container (and any
1434 // arv-mount processes) are allowed to use.
1435 func (runner *ContainerRunner) ContainerToken() (string, error) {
1436 if runner.token != "" {
1437 return runner.token, nil
1440 var auth arvados.APIClientAuthorization
1441 err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1445 runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1446 return runner.token, nil
1449 // UpdateContainerFinal updates the container record state on API
1450 // server to "Complete" or "Cancelled"
1451 func (runner *ContainerRunner) UpdateContainerFinal() error {
1452 update := arvadosclient.Dict{}
1453 update["state"] = runner.finalState
1454 if runner.LogsPDH != nil {
1455 update["log"] = *runner.LogsPDH
1457 if runner.ExitCode != nil {
1458 update["exit_code"] = *runner.ExitCode
1460 update["exit_code"] = nil
1462 if runner.finalState == "Complete" && runner.OutputPDH != nil {
1463 update["output"] = *runner.OutputPDH
1465 var it arvados.InstanceType
1466 if j := os.Getenv("InstanceType"); j != "" && json.Unmarshal([]byte(j), &it) == nil && it.Price > 0 {
1467 update["cost"] = it.Price * time.Now().Sub(runner.costStartTime).Seconds() / time.Hour.Seconds()
1469 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1472 // IsCancelled returns the value of Cancelled, with goroutine safety.
1473 func (runner *ContainerRunner) IsCancelled() bool {
1474 runner.cStateLock.Lock()
1475 defer runner.cStateLock.Unlock()
1476 return runner.cCancelled
1479 // NewArvLogWriter creates an ArvLogWriter
1480 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1481 writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1485 return &ArvLogWriter{
1486 ArvClient: runner.DispatcherArvClient,
1487 UUID: runner.Container.UUID,
1488 loggingStream: name,
1489 writeCloser: writer,
1493 // Run the full container lifecycle.
1494 func (runner *ContainerRunner) Run() (err error) {
1495 runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1496 runner.CrunchLog.Printf("%s", currentUserAndGroups())
1497 v, _ := exec.Command("arv-mount", "--version").CombinedOutput()
1498 runner.CrunchLog.Printf("Using FUSE mount: %s", v)
1499 runner.CrunchLog.Printf("Using container runtime: %s", runner.executor.Runtime())
1500 runner.CrunchLog.Printf("Executing container: %s", runner.Container.UUID)
1501 runner.costStartTime = time.Now()
1503 hostname, hosterr := os.Hostname()
1505 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1507 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1510 runner.finalState = "Queued"
1513 runner.CleanupDirs()
1515 runner.CrunchLog.Printf("crunch-run finished")
1516 runner.CrunchLog.Close()
1519 err = runner.fetchContainerRecord()
1523 if runner.Container.State != "Locked" {
1524 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1527 var bindmounts map[string]bindmount
1529 // checkErr prints e (unless it's nil) and sets err to
1530 // e (unless err is already non-nil). Thus, if err
1531 // hasn't already been assigned when Run() returns,
1532 // this cleanup func will cause Run() to return the
1533 // first non-nil error that is passed to checkErr().
1534 checkErr := func(errorIn string, e error) {
1538 runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1542 if runner.finalState == "Complete" {
1543 // There was an error in the finalization.
1544 runner.finalState = "Cancelled"
1548 // Log the error encountered in Run(), if any
1549 checkErr("Run", err)
1551 if runner.finalState == "Queued" {
1552 runner.UpdateContainerFinal()
1556 if runner.IsCancelled() {
1557 runner.finalState = "Cancelled"
1558 // but don't return yet -- we still want to
1559 // capture partial output and write logs
1562 if bindmounts != nil {
1563 checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1565 checkErr("stopHoststat", runner.stopHoststat())
1566 checkErr("CommitLogs", runner.CommitLogs())
1567 runner.CleanupDirs()
1568 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1571 runner.setupSignals()
1572 err = runner.startHoststat()
1577 // set up FUSE mount and binds
1578 bindmounts, err = runner.SetupMounts()
1580 runner.finalState = "Cancelled"
1581 err = fmt.Errorf("While setting up mounts: %v", err)
1585 // check for and/or load image
1586 imageID, err := runner.LoadImage()
1588 if !runner.checkBrokenNode(err) {
1589 // Failed to load image but not due to a "broken node"
1590 // condition, probably user error.
1591 runner.finalState = "Cancelled"
1593 err = fmt.Errorf("While loading container image: %v", err)
1597 err = runner.CreateContainer(imageID, bindmounts)
1601 err = runner.LogHostInfo()
1605 err = runner.LogNodeRecord()
1609 err = runner.LogContainerRecord()
1614 if runner.IsCancelled() {
1618 err = runner.UpdateContainerRunning()
1622 runner.finalState = "Cancelled"
1624 err = runner.startCrunchstat()
1629 err = runner.StartContainer()
1631 runner.checkBrokenNode(err)
1635 err = runner.WaitFinish()
1636 if err == nil && !runner.IsCancelled() {
1637 runner.finalState = "Complete"
1642 // Fetch the current container record (uuid = runner.Container.UUID)
1643 // into runner.Container.
1644 func (runner *ContainerRunner) fetchContainerRecord() error {
1645 reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1647 return fmt.Errorf("error fetching container record: %v", err)
1649 defer reader.Close()
1651 dec := json.NewDecoder(reader)
1653 err = dec.Decode(&runner.Container)
1655 return fmt.Errorf("error decoding container record: %v", err)
1659 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1662 containerToken, err := runner.ContainerToken()
1664 return fmt.Errorf("error getting container token: %v", err)
1667 runner.ContainerArvClient, runner.ContainerKeepClient,
1668 runner.containerClient, err = runner.MkArvClient(containerToken)
1670 return fmt.Errorf("error creating container API client: %v", err)
1673 runner.ContainerKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1674 runner.DispatcherKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1676 err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1678 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1679 return fmt.Errorf("error fetching secret_mounts: %v", err)
1681 // ok && apierr.HttpStatusCode == 404, which means
1682 // secret_mounts isn't supported by this API server.
1684 runner.SecretMounts = sm.SecretMounts
1689 // NewContainerRunner creates a new container runner.
1690 func NewContainerRunner(dispatcherClient *arvados.Client,
1691 dispatcherArvClient IArvadosClient,
1692 dispatcherKeepClient IKeepClient,
1693 containerUUID string) (*ContainerRunner, error) {
1695 cr := &ContainerRunner{
1696 dispatcherClient: dispatcherClient,
1697 DispatcherArvClient: dispatcherArvClient,
1698 DispatcherKeepClient: dispatcherKeepClient,
1700 cr.NewLogWriter = cr.NewArvLogWriter
1701 cr.RunArvMount = cr.ArvMountCmd
1702 cr.MkTempDir = ioutil.TempDir
1703 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1704 cl, err := arvadosclient.MakeArvadosClient()
1706 return nil, nil, nil, err
1709 kc, err := keepclient.MakeKeepClient(cl)
1711 return nil, nil, nil, err
1713 c2 := arvados.NewClientFromEnv()
1714 c2.AuthToken = token
1715 return cl, kc, c2, nil
1718 cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1722 cr.Container.UUID = containerUUID
1723 w, err := cr.NewLogWriter("crunch-run")
1727 cr.CrunchLog = NewThrottledLogger(w)
1728 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1730 loadLogThrottleParams(dispatcherArvClient)
1736 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1737 log := log.New(stderr, "", 0)
1738 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1739 statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1740 cgroupRoot := flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1741 cgroupParent := flags.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1742 cgroupParentSubsystem := flags.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1743 caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1744 detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1745 stdinConfig := flags.Bool("stdin-config", false, "Load config and environment variables from JSON message on stdin")
1746 configFile := flags.String("config", arvados.DefaultConfigFile, "filename of cluster config file to try loading if -stdin-config=false (default is $ARVADOS_CONFIG)")
1747 sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1748 kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1749 list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes")
1750 enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1751 enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1752 networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1753 memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1754 runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1755 brokenNodeHook := flags.String("broken-node-hook", "", "script to run if node is detected to be broken (for example, Docker daemon is not running)")
1756 flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1757 version := flags.Bool("version", false, "Write version information to stdout and exit 0.")
1759 ignoreDetachFlag := false
1760 if len(args) > 0 && args[0] == "-no-detach" {
1761 // This process was invoked by a parent process, which
1762 // has passed along its own arguments, including
1763 // -detach, after the leading -no-detach flag. Strip
1764 // the leading -no-detach flag (it's not recognized by
1765 // flags.Parse()) and ignore the -detach flag that
1768 ignoreDetachFlag = true
1771 if ok, code := cmd.ParseFlags(flags, prog, args, "container-uuid", stderr); !ok {
1773 } else if *version {
1774 fmt.Fprintln(stdout, prog, cmd.Version.String())
1776 } else if !*list && flags.NArg() != 1 {
1777 fmt.Fprintf(stderr, "missing required argument: container-uuid (try -help)\n")
1781 containerUUID := flags.Arg(0)
1784 case *detach && !ignoreDetachFlag:
1785 return Detach(containerUUID, prog, args, os.Stdin, os.Stdout, os.Stderr)
1787 return KillProcess(containerUUID, syscall.Signal(*kill), os.Stdout, os.Stderr)
1789 return ListProcesses(os.Stdout, os.Stderr)
1792 if len(containerUUID) != 27 {
1793 log.Printf("usage: %s [options] UUID", prog)
1797 var keepstoreLogbuf bufThenWrite
1800 err := json.NewDecoder(stdin).Decode(&conf)
1802 log.Printf("decode stdin: %s", err)
1805 for k, v := range conf.Env {
1806 err = os.Setenv(k, v)
1808 log.Printf("setenv(%q): %s", k, err)
1812 if conf.Cluster != nil {
1813 // ClusterID is missing from the JSON
1814 // representation, but we need it to generate
1815 // a valid config file for keepstore, so we
1816 // fill it using the container UUID prefix.
1817 conf.Cluster.ClusterID = containerUUID[:5]
1820 conf = hpcConfData(containerUUID, *configFile, io.MultiWriter(&keepstoreLogbuf, stderr))
1823 log.Printf("crunch-run %s started", cmd.Version.String())
1826 if *caCertsPath != "" {
1827 arvadosclient.CertFiles = []string{*caCertsPath}
1830 keepstore, err := startLocalKeepstore(conf, io.MultiWriter(&keepstoreLogbuf, stderr))
1835 if keepstore != nil {
1836 defer keepstore.Process.Kill()
1839 api, err := arvadosclient.MakeArvadosClient()
1841 log.Printf("%s: %v", containerUUID, err)
1846 kc, err := keepclient.MakeKeepClient(api)
1848 log.Printf("%s: %v", containerUUID, err)
1851 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1854 cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
1860 if keepstore == nil {
1861 // Log explanation (if any) for why we're not running
1862 // a local keepstore.
1863 var buf bytes.Buffer
1864 keepstoreLogbuf.SetWriter(&buf)
1866 cr.CrunchLog.Printf("%s", strings.TrimSpace(buf.String()))
1868 } else if logWhat := conf.Cluster.Containers.LocalKeepLogsToContainerLog; logWhat == "none" {
1869 cr.CrunchLog.Printf("using local keepstore process (pid %d) at %s", keepstore.Process.Pid, os.Getenv("ARVADOS_KEEP_SERVICES"))
1870 keepstoreLogbuf.SetWriter(io.Discard)
1872 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"))
1873 logwriter, err := cr.NewLogWriter("keepstore")
1878 cr.keepstoreLogger = NewThrottledLogger(logwriter)
1880 var writer io.WriteCloser = cr.keepstoreLogger
1881 if logWhat == "errors" {
1882 writer = &filterKeepstoreErrorsOnly{WriteCloser: writer}
1883 } else if logWhat != "all" {
1884 // should have been caught earlier by
1885 // dispatcher's config loader
1886 log.Printf("invalid value for Containers.LocalKeepLogsToContainerLog: %q", logWhat)
1889 err = keepstoreLogbuf.SetWriter(writer)
1894 cr.keepstoreLogbuf = &keepstoreLogbuf
1897 switch *runtimeEngine {
1899 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
1901 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
1903 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
1904 cr.CrunchLog.Close()
1908 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
1909 cr.checkBrokenNode(err)
1910 cr.CrunchLog.Close()
1913 defer cr.executor.Close()
1915 cr.brokenNodeHook = *brokenNodeHook
1917 gwAuthSecret := os.Getenv("GatewayAuthSecret")
1918 os.Unsetenv("GatewayAuthSecret")
1919 if gwAuthSecret == "" {
1920 // not safe to run a gateway service without an auth
1922 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAuthSecret was not provided by dispatcher)")
1924 gwListen := os.Getenv("GatewayAddress")
1925 cr.gateway = Gateway{
1927 AuthSecret: gwAuthSecret,
1928 ContainerUUID: containerUUID,
1929 Target: cr.executor,
1933 // Direct connection won't work, so we use the
1934 // gateway_address field to indicate the
1935 // internalURL of the controller process that
1936 // has the current tunnel connection.
1937 cr.gateway.ArvadosClient = cr.dispatcherClient
1938 cr.gateway.UpdateTunnelURL = func(url string) {
1939 cr.gateway.Address = "tunnel " + url
1940 cr.DispatcherArvClient.Update("containers", containerUUID,
1941 arvadosclient.Dict{"container": arvadosclient.Dict{"gateway_address": cr.gateway.Address}}, nil)
1944 err = cr.gateway.Start()
1946 log.Printf("error starting gateway server: %s", err)
1951 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
1953 log.Printf("%s: %v", containerUUID, tmperr)
1957 cr.parentTemp = parentTemp
1958 cr.statInterval = *statInterval
1959 cr.cgroupRoot = *cgroupRoot
1960 cr.expectCgroupParent = *cgroupParent
1961 cr.enableMemoryLimit = *enableMemoryLimit
1962 cr.enableNetwork = *enableNetwork
1963 cr.networkMode = *networkMode
1964 if *cgroupParentSubsystem != "" {
1965 p, err := findCgroup(*cgroupParentSubsystem)
1967 log.Printf("fatal: cgroup parent subsystem: %s", err)
1970 cr.setCgroupParent = p
1971 cr.expectCgroupParent = p
1976 if *memprofile != "" {
1977 f, err := os.Create(*memprofile)
1979 log.Printf("could not create memory profile: %s", err)
1981 runtime.GC() // get up-to-date statistics
1982 if err := pprof.WriteHeapProfile(f); err != nil {
1983 log.Printf("could not write memory profile: %s", err)
1985 closeerr := f.Close()
1986 if closeerr != nil {
1987 log.Printf("closing memprofile file: %s", err)
1992 log.Printf("%s: %v", containerUUID, runerr)
1998 // Try to load ConfigData in hpc (slurm/lsf) environment. This means
1999 // loading the cluster config from the specified file and (if that
2000 // works) getting the runtime_constraints container field from
2001 // controller to determine # VCPUs so we can calculate KeepBuffers.
2002 func hpcConfData(uuid string, configFile string, stderr io.Writer) ConfigData {
2004 conf.Cluster = loadClusterConfigFile(configFile, stderr)
2005 if conf.Cluster == nil {
2006 // skip loading the container record -- we won't be
2007 // able to start local keepstore anyway.
2010 arv, err := arvadosclient.MakeArvadosClient()
2012 fmt.Fprintf(stderr, "error setting up arvadosclient: %s\n", err)
2016 var ctr arvados.Container
2017 err = arv.Call("GET", "containers", uuid, "", arvadosclient.Dict{"select": []string{"runtime_constraints"}}, &ctr)
2019 fmt.Fprintf(stderr, "error getting container record: %s\n", err)
2022 if ctr.RuntimeConstraints.VCPUs > 0 {
2023 conf.KeepBuffers = ctr.RuntimeConstraints.VCPUs * conf.Cluster.Containers.LocalKeepBlobBuffersPerVCPU
2028 // Load cluster config file from given path. If an error occurs, log
2029 // the error to stderr and return nil.
2030 func loadClusterConfigFile(path string, stderr io.Writer) *arvados.Cluster {
2031 ldr := config.NewLoader(&bytes.Buffer{}, ctxlog.New(stderr, "plain", "info"))
2033 cfg, err := ldr.Load()
2035 fmt.Fprintf(stderr, "could not load config file %s: %s\n", path, err)
2038 cluster, err := cfg.GetCluster("")
2040 fmt.Fprintf(stderr, "could not use config file %s: %s\n", path, err)
2043 fmt.Fprintf(stderr, "loaded config file %s\n", path)
2047 func startLocalKeepstore(configData ConfigData, logbuf io.Writer) (*exec.Cmd, error) {
2048 if configData.KeepBuffers < 1 {
2049 fmt.Fprintf(logbuf, "not starting a local keepstore process because KeepBuffers=%v in config\n", configData.KeepBuffers)
2052 if configData.Cluster == nil {
2053 fmt.Fprint(logbuf, "not starting a local keepstore process because cluster config file was not loaded\n")
2056 for uuid, vol := range configData.Cluster.Volumes {
2057 if len(vol.AccessViaHosts) > 0 {
2058 fmt.Fprintf(logbuf, "not starting a local keepstore process because a volume (%s) uses AccessViaHosts\n", uuid)
2061 if !vol.ReadOnly && vol.Replication < configData.Cluster.Collections.DefaultReplication {
2062 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)
2067 // Rather than have an alternate way to tell keepstore how
2068 // many buffers to use when starting it this way, we just
2069 // modify the cluster configuration that we feed it on stdin.
2070 configData.Cluster.API.MaxKeepBlobBuffers = configData.KeepBuffers
2072 localaddr := localKeepstoreAddr()
2073 ln, err := net.Listen("tcp", net.JoinHostPort(localaddr, "0"))
2077 _, port, err := net.SplitHostPort(ln.Addr().String())
2083 url := "http://" + net.JoinHostPort(localaddr, port)
2085 fmt.Fprintf(logbuf, "starting keepstore on %s\n", url)
2087 var confJSON bytes.Buffer
2088 err = json.NewEncoder(&confJSON).Encode(arvados.Config{
2089 Clusters: map[string]arvados.Cluster{
2090 configData.Cluster.ClusterID: *configData.Cluster,
2096 cmd := exec.Command("/proc/self/exe", "keepstore", "-config=-")
2097 if target, err := os.Readlink(cmd.Path); err == nil && strings.HasSuffix(target, ".test") {
2098 // If we're a 'go test' process, running
2099 // /proc/self/exe would start the test suite in a
2100 // child process, which is not what we want.
2101 cmd.Path, _ = exec.LookPath("go")
2102 cmd.Args = append([]string{"go", "run", "../../cmd/arvados-server"}, cmd.Args[1:]...)
2103 cmd.Env = os.Environ()
2105 cmd.Stdin = &confJSON
2108 cmd.Env = append(cmd.Env,
2110 "ARVADOS_SERVICE_INTERNAL_URL="+url)
2113 return nil, fmt.Errorf("error starting keepstore process: %w", err)
2120 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10))
2122 poll := time.NewTicker(time.Second / 10)
2124 client := http.Client{}
2126 testReq, err := http.NewRequestWithContext(ctx, "GET", url+"/_health/ping", nil)
2127 testReq.Header.Set("Authorization", "Bearer "+configData.Cluster.ManagementToken)
2131 resp, err := client.Do(testReq)
2134 if resp.StatusCode == http.StatusOK {
2139 return nil, fmt.Errorf("keepstore child process exited")
2141 if ctx.Err() != nil {
2142 return nil, fmt.Errorf("timed out waiting for new keepstore process to report healthy")
2145 os.Setenv("ARVADOS_KEEP_SERVICES", url)
2149 // return current uid, gid, groups in a format suitable for logging:
2150 // "crunch-run process has uid=1234(arvados) gid=1234(arvados)
2151 // groups=1234(arvados),114(fuse)"
2152 func currentUserAndGroups() string {
2153 u, err := user.Current()
2155 return fmt.Sprintf("error getting current user ID: %s", err)
2157 s := fmt.Sprintf("crunch-run process has uid=%s(%s) gid=%s", u.Uid, u.Username, u.Gid)
2158 if g, err := user.LookupGroupId(u.Gid); err == nil {
2159 s += fmt.Sprintf("(%s)", g.Name)
2162 if gids, err := u.GroupIds(); err == nil {
2163 for i, gid := range gids {
2168 if g, err := user.LookupGroupId(gid); err == nil {
2169 s += fmt.Sprintf("(%s)", g.Name)
2176 // Return a suitable local interface address for a local keepstore
2177 // service. Currently this is the numerically lowest non-loopback ipv4
2178 // address assigned to a local interface that is not in any of the
2179 // link-local/vpn/loopback ranges 169.254/16, 100.64/10, or 127/8.
2180 func localKeepstoreAddr() string {
2182 // Ignore error (proceed with zero IPs)
2183 addrs, _ := processIPs(os.Getpid())
2184 for addr := range addrs {
2185 ip := net.ParseIP(addr)
2190 if ip.Mask(net.CIDRMask(8, 32)).Equal(net.IPv4(127, 0, 0, 0)) ||
2191 ip.Mask(net.CIDRMask(10, 32)).Equal(net.IPv4(100, 64, 0, 0)) ||
2192 ip.Mask(net.CIDRMask(16, 32)).Equal(net.IPv4(169, 254, 0, 0)) {
2196 ips = append(ips, ip)
2201 sort.Slice(ips, func(ii, jj int) bool {
2202 i, j := ips[ii], ips[jj]
2203 if len(i) != len(j) {
2204 return len(i) < len(j)
2213 return ips[0].String()