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/crunchstat"
36 "git.arvados.org/arvados.git/sdk/go/arvados"
37 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
38 "git.arvados.org/arvados.git/sdk/go/keepclient"
39 "git.arvados.org/arvados.git/sdk/go/manifest"
40 "golang.org/x/sys/unix"
45 var Command = command{}
47 // ConfigData contains environment variables and (when needed) cluster
48 // configuration, passed from dispatchcloud to crunch-run on stdin.
49 type ConfigData struct {
52 Cluster *arvados.Cluster
55 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
56 type IArvadosClient interface {
57 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
58 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
59 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
60 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
61 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
62 Discovery(key string) (interface{}, error)
65 // ErrCancelled is the error returned when the container is cancelled.
66 var ErrCancelled = errors.New("Cancelled")
68 // IKeepClient is the minimal Keep API methods used by crunch-run.
69 type IKeepClient interface {
70 BlockWrite(context.Context, arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error)
71 ReadAt(locator string, p []byte, off int) (int, error)
72 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
73 LocalLocator(locator string) (string, error)
75 SetStorageClasses(sc []string)
78 // NewLogWriter is a factory function to create a new log writer.
79 type NewLogWriter func(name string) (io.WriteCloser, error)
81 type RunArvMount func(cmdline []string, tok string) (*exec.Cmd, error)
83 type MkTempDir func(string, string) (string, error)
85 type PsProcess interface {
86 CmdlineSlice() ([]string, error)
89 // ContainerRunner is the main stateful struct used for a single execution of a
91 type ContainerRunner struct {
92 executor containerExecutor
93 executorStdin io.Closer
94 executorStdout io.Closer
95 executorStderr io.Closer
97 // Dispatcher client is initialized with the Dispatcher token.
98 // This is a privileged token used to manage container status
101 // We have both dispatcherClient and DispatcherArvClient
102 // because there are two different incompatible Arvados Go
103 // SDKs and we have to use both (hopefully this gets fixed in
105 dispatcherClient *arvados.Client
106 DispatcherArvClient IArvadosClient
107 DispatcherKeepClient IKeepClient
109 // Container client is initialized with the Container token
110 // This token controls the permissions of the container, and
111 // must be used for operations such as reading collections.
113 // Same comment as above applies to
114 // containerClient/ContainerArvClient.
115 containerClient *arvados.Client
116 ContainerArvClient IArvadosClient
117 ContainerKeepClient IKeepClient
119 Container arvados.Container
122 NewLogWriter NewLogWriter
123 CrunchLog *ThrottledLogger
126 LogCollection arvados.CollectionFileSystem
128 RunArvMount RunArvMount
133 Volumes map[string]struct{}
135 SigChan chan os.Signal
136 ArvMountExit chan error
137 SecretMounts map[string]arvados.Mount
138 MkArvClient func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error)
142 keepstoreLogger io.WriteCloser
143 keepstoreLogbuf *bufThenWrite
144 statLogger io.WriteCloser
145 statReporter *crunchstat.Reporter
146 hoststatLogger io.WriteCloser
147 hoststatReporter *crunchstat.Reporter
148 statInterval time.Duration
150 // What we expect the container's cgroup parent to be.
151 expectCgroupParent string
152 // What we tell docker to use as the container's cgroup
153 // parent. Note: Ideally we would use the same field for both
154 // expectCgroupParent and setCgroupParent, and just make it
155 // default to "docker". However, when using docker < 1.10 with
156 // systemd, specifying a non-empty cgroup parent (even the
157 // default value "docker") hits a docker bug
158 // (https://github.com/docker/docker/issues/17126). Using two
159 // separate fields makes it possible to use the "expect cgroup
160 // parent to be X" feature even on sites where the "specify
161 // cgroup parent" feature breaks.
162 setCgroupParent string
164 cStateLock sync.Mutex
165 cCancelled bool // StopContainer() invoked
167 enableMemoryLimit bool
168 enableNetwork string // one of "default" or "always"
169 networkMode string // "none", "host", or "" -- passed through to executor
170 arvMountLog *ThrottledLogger
172 containerWatchdogInterval time.Duration
177 // setupSignals sets up signal handling to gracefully terminate the
178 // underlying container and update state when receiving a TERM, INT or
180 func (runner *ContainerRunner) setupSignals() {
181 runner.SigChan = make(chan os.Signal, 1)
182 signal.Notify(runner.SigChan, syscall.SIGTERM)
183 signal.Notify(runner.SigChan, syscall.SIGINT)
184 signal.Notify(runner.SigChan, syscall.SIGQUIT)
186 go func(sig chan os.Signal) {
193 // stop the underlying container.
194 func (runner *ContainerRunner) stop(sig os.Signal) {
195 runner.cStateLock.Lock()
196 defer runner.cStateLock.Unlock()
198 runner.CrunchLog.Printf("caught signal: %v", sig)
200 runner.cCancelled = true
201 runner.CrunchLog.Printf("stopping container")
202 err := runner.executor.Stop()
204 runner.CrunchLog.Printf("error stopping container: %s", err)
208 var errorBlacklist = []string{
209 "(?ms).*[Cc]annot connect to the Docker daemon.*",
210 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
211 "(?ms).*grpc: the connection is unavailable.*",
213 var brokenNodeHook *string = flag.String("broken-node-hook", "", "Script to run if node is detected to be broken (for example, Docker daemon is not running)")
215 func (runner *ContainerRunner) runBrokenNodeHook() {
216 if *brokenNodeHook == "" {
217 path := filepath.Join(lockdir, brokenfile)
218 runner.CrunchLog.Printf("Writing %s to mark node as broken", path)
219 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0700)
221 runner.CrunchLog.Printf("Error writing %s: %s", path, err)
226 runner.CrunchLog.Printf("Running broken node hook %q", *brokenNodeHook)
228 c := exec.Command(*brokenNodeHook)
229 c.Stdout = runner.CrunchLog
230 c.Stderr = runner.CrunchLog
233 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
238 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
239 for _, d := range errorBlacklist {
240 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
241 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
242 runner.runBrokenNodeHook()
249 // LoadImage determines the docker image id from the container record and
250 // checks if it is available in the local Docker image store. If not, it loads
251 // the image from Keep.
252 func (runner *ContainerRunner) LoadImage() (string, error) {
253 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
255 d, err := os.Open(runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage)
260 allfiles, err := d.Readdirnames(-1)
264 var tarfiles []string
265 for _, fnm := range allfiles {
266 if strings.HasSuffix(fnm, ".tar") {
267 tarfiles = append(tarfiles, fnm)
270 if len(tarfiles) == 0 {
271 return "", fmt.Errorf("image collection does not include a .tar image file")
273 if len(tarfiles) > 1 {
274 return "", fmt.Errorf("cannot choose from multiple tar files in image collection: %v", tarfiles)
276 imageID := tarfiles[0][:len(tarfiles[0])-4]
277 imageTarballPath := runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage + "/" + imageID + ".tar"
278 runner.CrunchLog.Printf("Using Docker image id %q", imageID)
280 runner.CrunchLog.Print("Loading Docker image from keep")
281 err = runner.executor.LoadImage(imageID, imageTarballPath, runner.Container, runner.ArvMountPoint,
282 runner.containerClient)
290 func (runner *ContainerRunner) ArvMountCmd(cmdline []string, token string) (c *exec.Cmd, err error) {
291 c = exec.Command(cmdline[0], cmdline[1:]...)
293 // Copy our environment, but override ARVADOS_API_TOKEN with
294 // the container auth token.
296 for _, s := range os.Environ() {
297 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
298 c.Env = append(c.Env, s)
301 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
303 w, err := runner.NewLogWriter("arv-mount")
307 runner.arvMountLog = NewThrottledLogger(w)
308 scanner := logScanner{
311 "Block not found error",
312 "Unhandled exception during FUSE operation",
314 ReportFunc: runner.reportArvMountWarning,
316 c.Stdout = runner.arvMountLog
317 c.Stderr = io.MultiWriter(runner.arvMountLog, os.Stderr, &scanner)
319 runner.CrunchLog.Printf("Running %v", c.Args)
326 statReadme := make(chan bool)
327 runner.ArvMountExit = make(chan error)
332 time.Sleep(100 * time.Millisecond)
333 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
345 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
347 runner.ArvMountExit <- mnterr
348 close(runner.ArvMountExit)
354 case err := <-runner.ArvMountExit:
355 runner.ArvMount = nil
363 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
364 if runner.ArvMountPoint == "" {
365 runner.ArvMountPoint, err = runner.MkTempDir(runner.parentTemp, prefix)
370 func copyfile(src string, dst string) (err error) {
371 srcfile, err := os.Open(src)
376 os.MkdirAll(path.Dir(dst), 0777)
378 dstfile, err := os.Create(dst)
382 _, err = io.Copy(dstfile, srcfile)
387 err = srcfile.Close()
388 err2 := dstfile.Close()
401 func (runner *ContainerRunner) SetupMounts() (map[string]bindmount, error) {
402 bindmounts := map[string]bindmount{}
403 err := runner.SetupArvMountPoint("keep")
405 return nil, fmt.Errorf("While creating keep mount temp dir: %v", err)
408 token, err := runner.ContainerToken()
410 return nil, fmt.Errorf("could not get container token: %s", err)
412 runner.CrunchLog.Printf("container token %q", token)
416 arvMountCmd := []string{
420 "--storage-classes", strings.Join(runner.Container.OutputStorageClasses, ","),
421 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
423 if runner.executor.Runtime() == "docker" {
424 arvMountCmd = append(arvMountCmd, "--allow-other")
427 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
428 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
431 collectionPaths := []string{}
432 needCertMount := true
433 type copyFile struct {
437 var copyFiles []copyFile
440 for bind := range runner.Container.Mounts {
441 binds = append(binds, bind)
443 for bind := range runner.SecretMounts {
444 if _, ok := runner.Container.Mounts[bind]; ok {
445 return nil, fmt.Errorf("secret mount %q conflicts with regular mount", bind)
447 if runner.SecretMounts[bind].Kind != "json" &&
448 runner.SecretMounts[bind].Kind != "text" {
449 return nil, fmt.Errorf("secret mount %q type is %q but only 'json' and 'text' are permitted",
450 bind, runner.SecretMounts[bind].Kind)
452 binds = append(binds, bind)
456 for _, bind := range binds {
457 mnt, notSecret := runner.Container.Mounts[bind]
459 mnt = runner.SecretMounts[bind]
461 if bind == "stdout" || bind == "stderr" {
462 // Is it a "file" mount kind?
463 if mnt.Kind != "file" {
464 return nil, fmt.Errorf("unsupported mount kind '%s' for %s: only 'file' is supported", mnt.Kind, bind)
467 // Does path start with OutputPath?
468 prefix := runner.Container.OutputPath
469 if !strings.HasSuffix(prefix, "/") {
472 if !strings.HasPrefix(mnt.Path, prefix) {
473 return nil, fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
478 // Is it a "collection" mount kind?
479 if mnt.Kind != "collection" && mnt.Kind != "json" {
480 return nil, fmt.Errorf("unsupported mount kind '%s' for stdin: only 'collection' and 'json' are supported", mnt.Kind)
484 if bind == "/etc/arvados/ca-certificates.crt" {
485 needCertMount = false
488 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
489 if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
490 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)
495 case mnt.Kind == "collection" && bind != "stdin":
497 if mnt.UUID != "" && mnt.PortableDataHash != "" {
498 return nil, fmt.Errorf("cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
502 return nil, fmt.Errorf("writing to existing collections currently not permitted")
505 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
506 } else if mnt.PortableDataHash != "" {
507 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
508 return nil, fmt.Errorf("can never write to a collection specified by portable data hash")
510 idx := strings.Index(mnt.PortableDataHash, "/")
512 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
513 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
514 runner.Container.Mounts[bind] = mnt
516 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
517 if mnt.Path != "" && mnt.Path != "." {
518 if strings.HasPrefix(mnt.Path, "./") {
519 mnt.Path = mnt.Path[2:]
520 } else if strings.HasPrefix(mnt.Path, "/") {
521 mnt.Path = mnt.Path[1:]
523 src += "/" + mnt.Path
526 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
527 arvMountCmd = append(arvMountCmd, "--mount-tmp", fmt.Sprintf("tmp%d", tmpcount))
531 if bind == runner.Container.OutputPath {
532 runner.HostOutputDir = src
533 bindmounts[bind] = bindmount{HostPath: src}
534 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
535 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
537 bindmounts[bind] = bindmount{HostPath: src}
540 bindmounts[bind] = bindmount{HostPath: src, ReadOnly: true}
542 collectionPaths = append(collectionPaths, src)
544 case mnt.Kind == "tmp":
546 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
548 return nil, fmt.Errorf("while creating mount temp dir: %v", err)
550 st, staterr := os.Stat(tmpdir)
552 return nil, fmt.Errorf("while Stat on temp dir: %v", staterr)
554 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
556 return nil, fmt.Errorf("while Chmod temp dir: %v", err)
558 bindmounts[bind] = bindmount{HostPath: tmpdir}
559 if bind == runner.Container.OutputPath {
560 runner.HostOutputDir = tmpdir
563 case mnt.Kind == "json" || mnt.Kind == "text":
565 if mnt.Kind == "json" {
566 filedata, err = json.Marshal(mnt.Content)
568 return nil, fmt.Errorf("encoding json data: %v", err)
571 text, ok := mnt.Content.(string)
573 return nil, fmt.Errorf("content for mount %q must be a string", bind)
575 filedata = []byte(text)
578 tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
580 return nil, fmt.Errorf("creating temp dir: %v", err)
582 tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
583 err = ioutil.WriteFile(tmpfn, filedata, 0444)
585 return nil, fmt.Errorf("writing temp file: %v", err)
587 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && (notSecret || runner.Container.Mounts[runner.Container.OutputPath].Kind != "collection") {
588 // In most cases, if the container
589 // specifies a literal file inside the
590 // output path, we copy it into the
591 // output directory (either a mounted
592 // collection or a staging area on the
593 // host fs). If it's a secret, it will
594 // be skipped when copying output from
595 // staging to Keep later.
596 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
598 // If a secret is outside OutputPath,
599 // we bind mount the secret file
600 // directly just like other mounts. We
601 // also use this strategy when a
602 // secret is inside OutputPath but
603 // OutputPath is a live collection, to
604 // avoid writing the secret to
605 // Keep. Attempting to remove a
606 // bind-mounted secret file from
607 // inside the container will return a
608 // "Device or resource busy" error
609 // that might not be handled well by
610 // the container, which is why we
611 // don't use this strategy when
612 // OutputPath is a staging directory.
613 bindmounts[bind] = bindmount{HostPath: tmpfn, ReadOnly: true}
616 case mnt.Kind == "git_tree":
617 tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
619 return nil, fmt.Errorf("creating temp dir: %v", err)
621 err = gitMount(mnt).extractTree(runner.ContainerArvClient, tmpdir, token)
625 bindmounts[bind] = bindmount{HostPath: tmpdir, ReadOnly: true}
629 if runner.HostOutputDir == "" {
630 return nil, fmt.Errorf("output path does not correspond to a writable mount point")
633 if needCertMount && runner.Container.RuntimeConstraints.API {
634 for _, certfile := range arvadosclient.CertFiles {
635 _, err := os.Stat(certfile)
637 bindmounts["/etc/arvados/ca-certificates.crt"] = bindmount{HostPath: certfile, ReadOnly: true}
644 // If we are only mounting collections by pdh, make
645 // sure we don't subscribe to websocket events to
646 // avoid putting undesired load on the API server
647 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id", "--disable-event-listening")
649 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
651 // the by_uuid mount point is used by singularity when writing
652 // out docker images converted to SIF
653 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_uuid")
654 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
656 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
658 return nil, fmt.Errorf("while trying to start arv-mount: %v", err)
661 for _, p := range collectionPaths {
664 return nil, fmt.Errorf("while checking that input files exist: %v", err)
668 for _, cp := range copyFiles {
669 st, err := os.Stat(cp.src)
671 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
674 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
678 target := path.Join(cp.bind, walkpath[len(cp.src):])
679 if walkinfo.Mode().IsRegular() {
680 copyerr := copyfile(walkpath, target)
684 return os.Chmod(target, walkinfo.Mode()|0777)
685 } else if walkinfo.Mode().IsDir() {
686 mkerr := os.MkdirAll(target, 0777)
690 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
692 return fmt.Errorf("source %q is not a regular file or directory", cp.src)
695 } else if st.Mode().IsRegular() {
696 err = copyfile(cp.src, cp.bind)
698 err = os.Chmod(cp.bind, st.Mode()|0777)
702 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
706 return bindmounts, nil
709 func (runner *ContainerRunner) stopHoststat() error {
710 if runner.hoststatReporter == nil {
713 runner.hoststatReporter.Stop()
714 err := runner.hoststatLogger.Close()
716 return fmt.Errorf("error closing hoststat logs: %v", err)
721 func (runner *ContainerRunner) startHoststat() error {
722 w, err := runner.NewLogWriter("hoststat")
726 runner.hoststatLogger = NewThrottledLogger(w)
727 runner.hoststatReporter = &crunchstat.Reporter{
728 Logger: log.New(runner.hoststatLogger, "", 0),
729 CgroupRoot: runner.cgroupRoot,
730 PollPeriod: runner.statInterval,
732 runner.hoststatReporter.Start()
736 func (runner *ContainerRunner) startCrunchstat() error {
737 w, err := runner.NewLogWriter("crunchstat")
741 runner.statLogger = NewThrottledLogger(w)
742 runner.statReporter = &crunchstat.Reporter{
743 CID: runner.executor.CgroupID(),
744 Logger: log.New(runner.statLogger, "", 0),
745 CgroupParent: runner.expectCgroupParent,
746 CgroupRoot: runner.cgroupRoot,
747 PollPeriod: runner.statInterval,
748 TempDir: runner.parentTemp,
750 runner.statReporter.Start()
754 type infoCommand struct {
759 // LogHostInfo logs info about the current host, for debugging and
760 // accounting purposes. Although it's logged as "node-info", this is
761 // about the environment where crunch-run is actually running, which
762 // might differ from what's described in the node record (see
764 func (runner *ContainerRunner) LogHostInfo() (err error) {
765 w, err := runner.NewLogWriter("node-info")
770 commands := []infoCommand{
772 label: "Host Information",
773 cmd: []string{"uname", "-a"},
776 label: "CPU Information",
777 cmd: []string{"cat", "/proc/cpuinfo"},
780 label: "Memory Information",
781 cmd: []string{"cat", "/proc/meminfo"},
785 cmd: []string{"df", "-m", "/", os.TempDir()},
788 label: "Disk INodes",
789 cmd: []string{"df", "-i", "/", os.TempDir()},
793 // Run commands with informational output to be logged.
794 for _, command := range commands {
795 fmt.Fprintln(w, command.label)
796 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
799 if err := cmd.Run(); err != nil {
800 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
809 return fmt.Errorf("While closing node-info logs: %v", err)
814 // LogContainerRecord gets and saves the raw JSON container record from the API server
815 func (runner *ContainerRunner) LogContainerRecord() error {
816 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
817 if !logged && err == nil {
818 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
823 // LogNodeRecord logs the current host's InstanceType config entry (or
824 // the arvados#node record, if running via crunch-dispatch-slurm).
825 func (runner *ContainerRunner) LogNodeRecord() error {
826 if it := os.Getenv("InstanceType"); it != "" {
827 // Dispatched via arvados-dispatch-cloud. Save
828 // InstanceType config fragment received from
829 // dispatcher on stdin.
830 w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
835 _, err = io.WriteString(w, it)
841 // Dispatched via crunch-dispatch-slurm. Look up
842 // apiserver's node record corresponding to
844 hostname := os.Getenv("SLURMD_NODENAME")
846 hostname, _ = os.Hostname()
848 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
849 // The "info" field has admin-only info when
850 // obtained with a privileged token, and
851 // should not be logged.
852 node, ok := resp.(map[string]interface{})
860 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
861 writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
866 ArvClient: runner.DispatcherArvClient,
867 UUID: runner.Container.UUID,
868 loggingStream: label,
872 reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
874 return false, fmt.Errorf("error getting %s record: %v", label, err)
878 dec := json.NewDecoder(reader)
880 var resp map[string]interface{}
881 if err = dec.Decode(&resp); err != nil {
882 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
884 items, ok := resp["items"].([]interface{})
886 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
887 } else if len(items) < 1 {
893 // Re-encode it using indentation to improve readability
894 enc := json.NewEncoder(w)
895 enc.SetIndent("", " ")
896 if err = enc.Encode(items[0]); err != nil {
897 return false, fmt.Errorf("error logging %s record: %v", label, err)
901 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
906 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
907 stdoutPath := mntPath[len(runner.Container.OutputPath):]
908 index := strings.LastIndex(stdoutPath, "/")
910 subdirs := stdoutPath[:index]
912 st, err := os.Stat(runner.HostOutputDir)
914 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
916 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
917 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
919 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
923 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
925 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
928 return stdoutFile, nil
931 // CreateContainer creates the docker container.
932 func (runner *ContainerRunner) CreateContainer(imageID string, bindmounts map[string]bindmount) error {
933 var stdin io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
934 if mnt, ok := runner.Container.Mounts["stdin"]; ok {
941 collID = mnt.PortableDataHash
943 path := runner.ArvMountPoint + "/by_id/" + collID + "/" + mnt.Path
944 f, err := os.Open(path)
950 j, err := json.Marshal(mnt.Content)
952 return fmt.Errorf("error encoding stdin json data: %v", err)
954 stdin = ioutil.NopCloser(bytes.NewReader(j))
956 return fmt.Errorf("stdin mount has unsupported kind %q", mnt.Kind)
960 var stdout, stderr io.WriteCloser
961 if mnt, ok := runner.Container.Mounts["stdout"]; ok {
962 f, err := runner.getStdoutFile(mnt.Path)
967 } else if w, err := runner.NewLogWriter("stdout"); err != nil {
970 stdout = NewThrottledLogger(w)
973 if mnt, ok := runner.Container.Mounts["stderr"]; ok {
974 f, err := runner.getStdoutFile(mnt.Path)
979 } else if w, err := runner.NewLogWriter("stderr"); err != nil {
982 stderr = NewThrottledLogger(w)
985 env := runner.Container.Environment
986 enableNetwork := runner.enableNetwork == "always"
987 if runner.Container.RuntimeConstraints.API {
989 tok, err := runner.ContainerToken()
993 env = map[string]string{}
994 for k, v := range runner.Container.Environment {
997 env["ARVADOS_API_TOKEN"] = tok
998 env["ARVADOS_API_HOST"] = os.Getenv("ARVADOS_API_HOST")
999 env["ARVADOS_API_HOST_INSECURE"] = os.Getenv("ARVADOS_API_HOST_INSECURE")
1001 workdir := runner.Container.Cwd
1003 // both "" and "." mean default
1006 ram := runner.Container.RuntimeConstraints.RAM
1007 if !runner.enableMemoryLimit {
1010 runner.executorStdin = stdin
1011 runner.executorStdout = stdout
1012 runner.executorStderr = stderr
1014 if runner.Container.RuntimeConstraints.CUDA.DeviceCount > 0 {
1015 nvidiaModprobe(runner.CrunchLog)
1018 return runner.executor.Create(containerSpec{
1020 VCPUs: runner.Container.RuntimeConstraints.VCPUs,
1022 WorkingDir: workdir,
1024 BindMounts: bindmounts,
1025 Command: runner.Container.Command,
1026 EnableNetwork: enableNetwork,
1027 CUDADeviceCount: runner.Container.RuntimeConstraints.CUDA.DeviceCount,
1028 NetworkMode: runner.networkMode,
1029 CgroupParent: runner.setCgroupParent,
1036 // StartContainer starts the docker container created by CreateContainer.
1037 func (runner *ContainerRunner) StartContainer() error {
1038 runner.CrunchLog.Printf("Starting container")
1039 runner.cStateLock.Lock()
1040 defer runner.cStateLock.Unlock()
1041 if runner.cCancelled {
1044 err := runner.executor.Start()
1047 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1048 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])
1050 return fmt.Errorf("could not start container: %v%s", err, advice)
1055 // WaitFinish waits for the container to terminate, capture the exit code, and
1056 // close the stdout/stderr logging.
1057 func (runner *ContainerRunner) WaitFinish() error {
1058 runner.CrunchLog.Print("Waiting for container to finish")
1059 var timeout <-chan time.Time
1060 if s := runner.Container.SchedulingParameters.MaxRunTime; s > 0 {
1061 timeout = time.After(time.Duration(s) * time.Second)
1063 ctx, cancel := context.WithCancel(context.Background())
1068 runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1070 case <-runner.ArvMountExit:
1071 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1076 exitcode, err := runner.executor.Wait(ctx)
1078 runner.checkBrokenNode(err)
1081 runner.ExitCode = &exitcode
1084 if exitcode&0x80 != 0 {
1085 // Convert raw exit status (0x80 + signal number) to a
1086 // string to log after the code, like " (signal 101)"
1087 // or " (signal 9, killed)"
1088 sig := syscall.WaitStatus(exitcode).Signal()
1089 if name := unix.SignalName(sig); name != "" {
1090 extra = fmt.Sprintf(" (signal %d, %s)", sig, name)
1092 extra = fmt.Sprintf(" (signal %d)", sig)
1095 runner.CrunchLog.Printf("Container exited with status code %d%s", exitcode, extra)
1098 if err = runner.executorStdin.Close(); err != nil {
1099 err = fmt.Errorf("error closing container stdin: %s", err)
1100 runner.CrunchLog.Printf("%s", err)
1103 if err = runner.executorStdout.Close(); err != nil {
1104 err = fmt.Errorf("error closing container stdout: %s", err)
1105 runner.CrunchLog.Printf("%s", err)
1106 if returnErr == nil {
1110 if err = runner.executorStderr.Close(); err != nil {
1111 err = fmt.Errorf("error closing container stderr: %s", err)
1112 runner.CrunchLog.Printf("%s", err)
1113 if returnErr == nil {
1118 if runner.statReporter != nil {
1119 runner.statReporter.Stop()
1120 err = runner.statLogger.Close()
1122 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
1128 func (runner *ContainerRunner) updateLogs() {
1129 ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1132 sigusr1 := make(chan os.Signal, 1)
1133 signal.Notify(sigusr1, syscall.SIGUSR1)
1134 defer signal.Stop(sigusr1)
1136 saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1137 saveAtSize := crunchLogUpdateSize
1143 saveAtTime = time.Now()
1145 runner.logMtx.Lock()
1146 done := runner.LogsPDH != nil
1147 runner.logMtx.Unlock()
1151 size := runner.LogCollection.Size()
1152 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1155 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1156 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1157 saved, err := runner.saveLogCollection(false)
1159 runner.CrunchLog.Printf("error updating log collection: %s", err)
1163 var updated arvados.Container
1164 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1165 "container": arvadosclient.Dict{"log": saved.PortableDataHash},
1168 runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1176 func (runner *ContainerRunner) reportArvMountWarning(pattern, text string) {
1177 var updated arvados.Container
1178 err := runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1179 "container": arvadosclient.Dict{
1180 "runtime_status": arvadosclient.Dict{
1181 "warning": "arv-mount: " + pattern,
1182 "warningDetail": text,
1187 runner.CrunchLog.Printf("error updating container runtime_status: %s", err)
1191 // CaptureOutput saves data from the container's output directory if
1192 // needed, and updates the container output accordingly.
1193 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1194 if runner.Container.RuntimeConstraints.API {
1195 // Output may have been set directly by the container, so
1196 // refresh the container record to check.
1197 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1198 nil, &runner.Container)
1202 if runner.Container.Output != "" {
1203 // Container output is already set.
1204 runner.OutputPDH = &runner.Container.Output
1209 txt, err := (&copier{
1210 client: runner.containerClient,
1211 arvClient: runner.ContainerArvClient,
1212 keepClient: runner.ContainerKeepClient,
1213 hostOutputDir: runner.HostOutputDir,
1214 ctrOutputDir: runner.Container.OutputPath,
1215 bindmounts: bindmounts,
1216 mounts: runner.Container.Mounts,
1217 secretMounts: runner.SecretMounts,
1218 logger: runner.CrunchLog,
1223 if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1224 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1225 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1229 txt, err = fs.MarshalManifest(".")
1234 var resp arvados.Collection
1235 err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1236 "ensure_unique_name": true,
1237 "collection": arvadosclient.Dict{
1239 "name": "output for " + runner.Container.UUID,
1240 "manifest_text": txt,
1244 return fmt.Errorf("error creating output collection: %v", err)
1246 runner.OutputPDH = &resp.PortableDataHash
1250 func (runner *ContainerRunner) CleanupDirs() {
1251 if runner.ArvMount != nil {
1253 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1254 umount.Stdout = runner.CrunchLog
1255 umount.Stderr = runner.CrunchLog
1256 runner.CrunchLog.Printf("Running %v", umount.Args)
1257 umnterr := umount.Start()
1260 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1261 runner.ArvMount.Process.Kill()
1263 // If arv-mount --unmount gets stuck for any reason, we
1264 // don't want to wait for it forever. Do Wait() in a goroutine
1265 // so it doesn't block crunch-run.
1266 umountExit := make(chan error)
1268 mnterr := umount.Wait()
1270 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1272 umountExit <- mnterr
1275 for again := true; again; {
1281 case <-runner.ArvMountExit:
1283 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1284 runner.CrunchLog.Printf("Timed out waiting for unmount")
1286 umount.Process.Kill()
1288 runner.ArvMount.Process.Kill()
1292 runner.ArvMount = nil
1295 if runner.ArvMountPoint != "" {
1296 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1297 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1299 runner.ArvMountPoint = ""
1302 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1303 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1307 // CommitLogs posts the collection containing the final container logs.
1308 func (runner *ContainerRunner) CommitLogs() error {
1310 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1311 runner.cStateLock.Lock()
1312 defer runner.cStateLock.Unlock()
1314 runner.CrunchLog.Print(runner.finalState)
1316 if runner.arvMountLog != nil {
1317 runner.arvMountLog.Close()
1319 runner.CrunchLog.Close()
1321 // Closing CrunchLog above allows them to be committed to Keep at this
1322 // point, but re-open crunch log with ArvClient in case there are any
1323 // other further errors (such as failing to write the log to Keep!)
1324 // while shutting down
1325 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1326 ArvClient: runner.DispatcherArvClient,
1327 UUID: runner.Container.UUID,
1328 loggingStream: "crunch-run",
1331 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1334 if runner.keepstoreLogger != nil {
1335 // Flush any buffered logs from our local keepstore
1336 // process. Discard anything logged after this point
1337 // -- it won't end up in the log collection, so
1338 // there's no point writing it to the collectionfs.
1339 runner.keepstoreLogbuf.SetWriter(io.Discard)
1340 runner.keepstoreLogger.Close()
1341 runner.keepstoreLogger = nil
1344 if runner.LogsPDH != nil {
1345 // If we have already assigned something to LogsPDH,
1346 // we must be closing the re-opened log, which won't
1347 // end up getting attached to the container record and
1348 // therefore doesn't need to be saved as a collection
1349 // -- it exists only to send logs to other channels.
1353 saved, err := runner.saveLogCollection(true)
1355 return fmt.Errorf("error saving log collection: %s", err)
1357 runner.logMtx.Lock()
1358 defer runner.logMtx.Unlock()
1359 runner.LogsPDH = &saved.PortableDataHash
1363 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1364 runner.logMtx.Lock()
1365 defer runner.logMtx.Unlock()
1366 if runner.LogsPDH != nil {
1367 // Already finalized.
1370 updates := arvadosclient.Dict{
1371 "name": "logs for " + runner.Container.UUID,
1373 mt, err1 := runner.LogCollection.MarshalManifest(".")
1375 // Only send updated manifest text if there was no
1377 updates["manifest_text"] = mt
1380 // Even if flushing the manifest had an error, we still want
1381 // to update the log record, if possible, to push the trash_at
1382 // and delete_at times into the future. Details on bug
1385 updates["is_trashed"] = true
1387 exp := time.Now().Add(crunchLogUpdatePeriod * 24)
1388 updates["trash_at"] = exp
1389 updates["delete_at"] = exp
1391 reqBody := arvadosclient.Dict{"collection": updates}
1393 if runner.logUUID == "" {
1394 reqBody["ensure_unique_name"] = true
1395 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1397 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1400 runner.logUUID = response.UUID
1403 if err1 != nil || err2 != nil {
1404 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1409 // UpdateContainerRunning updates the container state to "Running"
1410 func (runner *ContainerRunner) UpdateContainerRunning() error {
1411 runner.cStateLock.Lock()
1412 defer runner.cStateLock.Unlock()
1413 if runner.cCancelled {
1416 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID,
1417 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running", "gateway_address": runner.gateway.Address}}, nil)
1420 // ContainerToken returns the api_token the container (and any
1421 // arv-mount processes) are allowed to use.
1422 func (runner *ContainerRunner) ContainerToken() (string, error) {
1423 if runner.token != "" {
1424 return runner.token, nil
1427 var auth arvados.APIClientAuthorization
1428 err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1432 runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1433 return runner.token, nil
1436 // UpdateContainerFinal updates the container record state on API
1437 // server to "Complete" or "Cancelled"
1438 func (runner *ContainerRunner) UpdateContainerFinal() error {
1439 update := arvadosclient.Dict{}
1440 update["state"] = runner.finalState
1441 if runner.LogsPDH != nil {
1442 update["log"] = *runner.LogsPDH
1444 if runner.finalState == "Complete" {
1445 if runner.ExitCode != nil {
1446 update["exit_code"] = *runner.ExitCode
1448 if runner.OutputPDH != nil {
1449 update["output"] = *runner.OutputPDH
1452 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1455 // IsCancelled returns the value of Cancelled, with goroutine safety.
1456 func (runner *ContainerRunner) IsCancelled() bool {
1457 runner.cStateLock.Lock()
1458 defer runner.cStateLock.Unlock()
1459 return runner.cCancelled
1462 // NewArvLogWriter creates an ArvLogWriter
1463 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1464 writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1468 return &ArvLogWriter{
1469 ArvClient: runner.DispatcherArvClient,
1470 UUID: runner.Container.UUID,
1471 loggingStream: name,
1472 writeCloser: writer,
1476 // Run the full container lifecycle.
1477 func (runner *ContainerRunner) Run() (err error) {
1478 runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1479 runner.CrunchLog.Printf("%s", currentUserAndGroups())
1480 runner.CrunchLog.Printf("Executing container '%s' using %s runtime", runner.Container.UUID, runner.executor.Runtime())
1482 hostname, hosterr := os.Hostname()
1484 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1486 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1489 runner.finalState = "Queued"
1492 runner.CleanupDirs()
1494 runner.CrunchLog.Printf("crunch-run finished")
1495 runner.CrunchLog.Close()
1498 err = runner.fetchContainerRecord()
1502 if runner.Container.State != "Locked" {
1503 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1506 var bindmounts map[string]bindmount
1508 // checkErr prints e (unless it's nil) and sets err to
1509 // e (unless err is already non-nil). Thus, if err
1510 // hasn't already been assigned when Run() returns,
1511 // this cleanup func will cause Run() to return the
1512 // first non-nil error that is passed to checkErr().
1513 checkErr := func(errorIn string, e error) {
1517 runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1521 if runner.finalState == "Complete" {
1522 // There was an error in the finalization.
1523 runner.finalState = "Cancelled"
1527 // Log the error encountered in Run(), if any
1528 checkErr("Run", err)
1530 if runner.finalState == "Queued" {
1531 runner.UpdateContainerFinal()
1535 if runner.IsCancelled() {
1536 runner.finalState = "Cancelled"
1537 // but don't return yet -- we still want to
1538 // capture partial output and write logs
1541 if bindmounts != nil {
1542 checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1544 checkErr("stopHoststat", runner.stopHoststat())
1545 checkErr("CommitLogs", runner.CommitLogs())
1546 runner.CleanupDirs()
1547 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1550 runner.setupSignals()
1551 err = runner.startHoststat()
1556 // set up FUSE mount and binds
1557 bindmounts, err = runner.SetupMounts()
1559 runner.finalState = "Cancelled"
1560 err = fmt.Errorf("While setting up mounts: %v", err)
1564 // check for and/or load image
1565 imageID, err := runner.LoadImage()
1567 if !runner.checkBrokenNode(err) {
1568 // Failed to load image but not due to a "broken node"
1569 // condition, probably user error.
1570 runner.finalState = "Cancelled"
1572 err = fmt.Errorf("While loading container image: %v", err)
1576 err = runner.CreateContainer(imageID, bindmounts)
1580 err = runner.LogHostInfo()
1584 err = runner.LogNodeRecord()
1588 err = runner.LogContainerRecord()
1593 if runner.IsCancelled() {
1597 err = runner.UpdateContainerRunning()
1601 runner.finalState = "Cancelled"
1603 err = runner.startCrunchstat()
1608 err = runner.StartContainer()
1610 runner.checkBrokenNode(err)
1614 err = runner.WaitFinish()
1615 if err == nil && !runner.IsCancelled() {
1616 runner.finalState = "Complete"
1621 // Fetch the current container record (uuid = runner.Container.UUID)
1622 // into runner.Container.
1623 func (runner *ContainerRunner) fetchContainerRecord() error {
1624 reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1626 return fmt.Errorf("error fetching container record: %v", err)
1628 defer reader.Close()
1630 dec := json.NewDecoder(reader)
1632 err = dec.Decode(&runner.Container)
1634 return fmt.Errorf("error decoding container record: %v", err)
1638 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1641 containerToken, err := runner.ContainerToken()
1643 return fmt.Errorf("error getting container token: %v", err)
1646 runner.ContainerArvClient, runner.ContainerKeepClient,
1647 runner.containerClient, err = runner.MkArvClient(containerToken)
1649 return fmt.Errorf("error creating container API client: %v", err)
1652 runner.ContainerKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1653 runner.DispatcherKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1655 err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1657 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1658 return fmt.Errorf("error fetching secret_mounts: %v", err)
1660 // ok && apierr.HttpStatusCode == 404, which means
1661 // secret_mounts isn't supported by this API server.
1663 runner.SecretMounts = sm.SecretMounts
1668 // NewContainerRunner creates a new container runner.
1669 func NewContainerRunner(dispatcherClient *arvados.Client,
1670 dispatcherArvClient IArvadosClient,
1671 dispatcherKeepClient IKeepClient,
1672 containerUUID string) (*ContainerRunner, error) {
1674 cr := &ContainerRunner{
1675 dispatcherClient: dispatcherClient,
1676 DispatcherArvClient: dispatcherArvClient,
1677 DispatcherKeepClient: dispatcherKeepClient,
1679 cr.NewLogWriter = cr.NewArvLogWriter
1680 cr.RunArvMount = cr.ArvMountCmd
1681 cr.MkTempDir = ioutil.TempDir
1682 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1683 cl, err := arvadosclient.MakeArvadosClient()
1685 return nil, nil, nil, err
1688 kc, err := keepclient.MakeKeepClient(cl)
1690 return nil, nil, nil, err
1692 c2 := arvados.NewClientFromEnv()
1693 c2.AuthToken = token
1694 return cl, kc, c2, nil
1697 cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1701 cr.Container.UUID = containerUUID
1702 w, err := cr.NewLogWriter("crunch-run")
1706 cr.CrunchLog = NewThrottledLogger(w)
1707 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1709 loadLogThrottleParams(dispatcherArvClient)
1715 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1716 log := log.New(stderr, "", 0)
1717 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1718 statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1719 cgroupRoot := flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1720 cgroupParent := flags.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1721 cgroupParentSubsystem := flags.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1722 caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1723 detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1724 stdinConfig := flags.Bool("stdin-config", false, "Load config and environment variables from JSON message on stdin")
1725 sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1726 kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1727 list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes")
1728 enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1729 enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1730 networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1731 memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1732 runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1733 flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1735 ignoreDetachFlag := false
1736 if len(args) > 0 && args[0] == "-no-detach" {
1737 // This process was invoked by a parent process, which
1738 // has passed along its own arguments, including
1739 // -detach, after the leading -no-detach flag. Strip
1740 // the leading -no-detach flag (it's not recognized by
1741 // flags.Parse()) and ignore the -detach flag that
1744 ignoreDetachFlag = true
1747 if ok, code := cmd.ParseFlags(flags, prog, args, "container-uuid", stderr); !ok {
1749 } else if !*list && flags.NArg() != 1 {
1750 fmt.Fprintf(stderr, "missing required argument: container-uuid (try -help)\n")
1754 containerUUID := flags.Arg(0)
1757 case *detach && !ignoreDetachFlag:
1758 return Detach(containerUUID, prog, args, os.Stdin, os.Stdout, os.Stderr)
1760 return KillProcess(containerUUID, syscall.Signal(*kill), os.Stdout, os.Stderr)
1762 return ListProcesses(os.Stdout, os.Stderr)
1765 if len(containerUUID) != 27 {
1766 log.Printf("usage: %s [options] UUID", prog)
1772 err := json.NewDecoder(stdin).Decode(&conf)
1774 log.Printf("decode stdin: %s", err)
1777 for k, v := range conf.Env {
1778 err = os.Setenv(k, v)
1780 log.Printf("setenv(%q): %s", k, err)
1784 if conf.Cluster != nil {
1785 // ClusterID is missing from the JSON
1786 // representation, but we need it to generate
1787 // a valid config file for keepstore, so we
1788 // fill it using the container UUID prefix.
1789 conf.Cluster.ClusterID = containerUUID[:5]
1793 log.Printf("crunch-run %s started", cmd.Version.String())
1796 if *caCertsPath != "" {
1797 arvadosclient.CertFiles = []string{*caCertsPath}
1800 var keepstoreLogbuf bufThenWrite
1801 keepstore, err := startLocalKeepstore(conf, io.MultiWriter(&keepstoreLogbuf, stderr))
1806 if keepstore != nil {
1807 defer keepstore.Process.Kill()
1810 api, err := arvadosclient.MakeArvadosClient()
1812 log.Printf("%s: %v", containerUUID, err)
1817 kc, err := keepclient.MakeKeepClient(api)
1819 log.Printf("%s: %v", containerUUID, err)
1822 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1825 cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
1831 if keepstore == nil {
1832 // Log explanation (if any) for why we're not running
1833 // a local keepstore.
1834 var buf bytes.Buffer
1835 keepstoreLogbuf.SetWriter(&buf)
1837 cr.CrunchLog.Printf("%s", strings.TrimSpace(buf.String()))
1839 } else if logWhat := conf.Cluster.Containers.LocalKeepLogsToContainerLog; logWhat == "none" {
1840 cr.CrunchLog.Printf("using local keepstore process (pid %d) at %s", keepstore.Process.Pid, os.Getenv("ARVADOS_KEEP_SERVICES"))
1841 keepstoreLogbuf.SetWriter(io.Discard)
1843 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"))
1844 logwriter, err := cr.NewLogWriter("keepstore")
1849 cr.keepstoreLogger = NewThrottledLogger(logwriter)
1851 var writer io.WriteCloser = cr.keepstoreLogger
1852 if logWhat == "errors" {
1853 writer = &filterKeepstoreErrorsOnly{WriteCloser: writer}
1854 } else if logWhat != "all" {
1855 // should have been caught earlier by
1856 // dispatcher's config loader
1857 log.Printf("invalid value for Containers.LocalKeepLogsToContainerLog: %q", logWhat)
1860 err = keepstoreLogbuf.SetWriter(writer)
1865 cr.keepstoreLogbuf = &keepstoreLogbuf
1868 switch *runtimeEngine {
1870 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
1872 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
1874 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
1875 cr.CrunchLog.Close()
1879 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
1880 cr.checkBrokenNode(err)
1881 cr.CrunchLog.Close()
1884 defer cr.executor.Close()
1886 gwAuthSecret := os.Getenv("GatewayAuthSecret")
1887 os.Unsetenv("GatewayAuthSecret")
1888 if gwAuthSecret == "" {
1889 // not safe to run a gateway service without an auth
1891 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAuthSecret was not provided by dispatcher)")
1892 } else if gwListen := os.Getenv("GatewayAddress"); gwListen == "" {
1893 // dispatcher did not tell us which external IP
1894 // address to advertise --> no gateway service
1895 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAddress was not provided by dispatcher)")
1896 } else if de, ok := cr.executor.(*dockerExecutor); ok {
1897 cr.gateway = Gateway{
1899 AuthSecret: gwAuthSecret,
1900 ContainerUUID: containerUUID,
1901 DockerContainerID: &de.containerID,
1903 ContainerIPAddress: dockerContainerIPAddress(&de.containerID),
1905 err = cr.gateway.Start()
1907 log.Printf("error starting gateway server: %s", err)
1912 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
1914 log.Printf("%s: %v", containerUUID, tmperr)
1918 cr.parentTemp = parentTemp
1919 cr.statInterval = *statInterval
1920 cr.cgroupRoot = *cgroupRoot
1921 cr.expectCgroupParent = *cgroupParent
1922 cr.enableMemoryLimit = *enableMemoryLimit
1923 cr.enableNetwork = *enableNetwork
1924 cr.networkMode = *networkMode
1925 if *cgroupParentSubsystem != "" {
1926 p := findCgroup(*cgroupParentSubsystem)
1927 cr.setCgroupParent = p
1928 cr.expectCgroupParent = p
1933 if *memprofile != "" {
1934 f, err := os.Create(*memprofile)
1936 log.Printf("could not create memory profile: %s", err)
1938 runtime.GC() // get up-to-date statistics
1939 if err := pprof.WriteHeapProfile(f); err != nil {
1940 log.Printf("could not write memory profile: %s", err)
1942 closeerr := f.Close()
1943 if closeerr != nil {
1944 log.Printf("closing memprofile file: %s", err)
1949 log.Printf("%s: %v", containerUUID, runerr)
1955 func startLocalKeepstore(configData ConfigData, logbuf io.Writer) (*exec.Cmd, error) {
1956 if configData.Cluster == nil || configData.KeepBuffers < 1 {
1959 for uuid, vol := range configData.Cluster.Volumes {
1960 if len(vol.AccessViaHosts) > 0 {
1961 fmt.Fprintf(logbuf, "not starting a local keepstore process because a volume (%s) uses AccessViaHosts\n", uuid)
1964 if !vol.ReadOnly && vol.Replication < configData.Cluster.Collections.DefaultReplication {
1965 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)
1970 // Rather than have an alternate way to tell keepstore how
1971 // many buffers to use when starting it this way, we just
1972 // modify the cluster configuration that we feed it on stdin.
1973 configData.Cluster.API.MaxKeepBlobBuffers = configData.KeepBuffers
1975 ln, err := net.Listen("tcp", "localhost:0")
1979 _, port, err := net.SplitHostPort(ln.Addr().String())
1985 url := "http://localhost:" + port
1987 fmt.Fprintf(logbuf, "starting keepstore on %s\n", url)
1989 var confJSON bytes.Buffer
1990 err = json.NewEncoder(&confJSON).Encode(arvados.Config{
1991 Clusters: map[string]arvados.Cluster{
1992 configData.Cluster.ClusterID: *configData.Cluster,
1998 cmd := exec.Command("/proc/self/exe", "keepstore", "-config=-")
1999 if target, err := os.Readlink(cmd.Path); err == nil && strings.HasSuffix(target, ".test") {
2000 // If we're a 'go test' process, running
2001 // /proc/self/exe would start the test suite in a
2002 // child process, which is not what we want.
2003 cmd.Path, _ = exec.LookPath("go")
2004 cmd.Args = append([]string{"go", "run", "../../cmd/arvados-server"}, cmd.Args[1:]...)
2005 cmd.Env = os.Environ()
2007 cmd.Stdin = &confJSON
2010 cmd.Env = append(cmd.Env,
2012 "ARVADOS_SERVICE_INTERNAL_URL="+url)
2015 return nil, fmt.Errorf("error starting keepstore process: %w", err)
2022 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10))
2024 poll := time.NewTicker(time.Second / 10)
2026 client := http.Client{}
2028 testReq, err := http.NewRequestWithContext(ctx, "GET", url+"/_health/ping", nil)
2029 testReq.Header.Set("Authorization", "Bearer "+configData.Cluster.ManagementToken)
2033 resp, err := client.Do(testReq)
2036 if resp.StatusCode == http.StatusOK {
2041 return nil, fmt.Errorf("keepstore child process exited")
2043 if ctx.Err() != nil {
2044 return nil, fmt.Errorf("timed out waiting for new keepstore process to report healthy")
2047 os.Setenv("ARVADOS_KEEP_SERVICES", url)
2051 // return current uid, gid, groups in a format suitable for logging:
2052 // "crunch-run process has uid=1234(arvados) gid=1234(arvados)
2053 // groups=1234(arvados),114(fuse)"
2054 func currentUserAndGroups() string {
2055 u, err := user.Current()
2057 return fmt.Sprintf("error getting current user ID: %s", err)
2059 s := fmt.Sprintf("crunch-run process has uid=%s(%s) gid=%s", u.Uid, u.Username, u.Gid)
2060 if g, err := user.LookupGroupId(u.Gid); err == nil {
2061 s += fmt.Sprintf("(%s)", g.Name)
2064 if gids, err := u.GroupIds(); err == nil {
2065 for i, gid := range gids {
2070 if g, err := user.LookupGroupId(gid); err == nil {
2071 s += fmt.Sprintf("(%s)", g.Name)