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)
144 keepstoreLogger io.WriteCloser
145 keepstoreLogbuf *bufThenWrite
146 statLogger io.WriteCloser
147 statReporter *crunchstat.Reporter
148 hoststatLogger io.WriteCloser
149 hoststatReporter *crunchstat.Reporter
150 statInterval time.Duration
152 // What we expect the container's cgroup parent to be.
153 expectCgroupParent string
154 // What we tell docker to use as the container's cgroup
155 // parent. Note: Ideally we would use the same field for both
156 // expectCgroupParent and setCgroupParent, and just make it
157 // default to "docker". However, when using docker < 1.10 with
158 // systemd, specifying a non-empty cgroup parent (even the
159 // default value "docker") hits a docker bug
160 // (https://github.com/docker/docker/issues/17126). Using two
161 // separate fields makes it possible to use the "expect cgroup
162 // parent to be X" feature even on sites where the "specify
163 // cgroup parent" feature breaks.
164 setCgroupParent string
166 cStateLock sync.Mutex
167 cCancelled bool // StopContainer() invoked
169 enableMemoryLimit bool
170 enableNetwork string // one of "default" or "always"
171 networkMode string // "none", "host", or "" -- passed through to executor
172 brokenNodeHook string // script to run if node appears to be broken
173 arvMountLog *ThrottledLogger
175 containerWatchdogInterval time.Duration
180 // setupSignals sets up signal handling to gracefully terminate the
181 // underlying container and update state when receiving a TERM, INT or
183 func (runner *ContainerRunner) setupSignals() {
184 runner.SigChan = make(chan os.Signal, 1)
185 signal.Notify(runner.SigChan, syscall.SIGTERM)
186 signal.Notify(runner.SigChan, syscall.SIGINT)
187 signal.Notify(runner.SigChan, syscall.SIGQUIT)
189 go func(sig chan os.Signal) {
196 // stop the underlying container.
197 func (runner *ContainerRunner) stop(sig os.Signal) {
198 runner.cStateLock.Lock()
199 defer runner.cStateLock.Unlock()
201 runner.CrunchLog.Printf("caught signal: %v", sig)
203 runner.cCancelled = true
204 runner.CrunchLog.Printf("stopping container")
205 err := runner.executor.Stop()
207 runner.CrunchLog.Printf("error stopping container: %s", err)
211 var errorBlacklist = []string{
212 "(?ms).*[Cc]annot connect to the Docker daemon.*",
213 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
214 "(?ms).*grpc: the connection is unavailable.*",
217 func (runner *ContainerRunner) runBrokenNodeHook() {
218 if runner.brokenNodeHook == "" {
219 path := filepath.Join(lockdir, brokenfile)
220 runner.CrunchLog.Printf("Writing %s to mark node as broken", path)
221 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0700)
223 runner.CrunchLog.Printf("Error writing %s: %s", path, err)
228 runner.CrunchLog.Printf("Running broken node hook %q", runner.brokenNodeHook)
230 c := exec.Command(runner.brokenNodeHook)
231 c.Stdout = runner.CrunchLog
232 c.Stderr = runner.CrunchLog
235 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
240 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
241 for _, d := range errorBlacklist {
242 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
243 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
244 runner.runBrokenNodeHook()
251 // LoadImage determines the docker image id from the container record and
252 // checks if it is available in the local Docker image store. If not, it loads
253 // the image from Keep.
254 func (runner *ContainerRunner) LoadImage() (string, error) {
255 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
257 d, err := os.Open(runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage)
262 allfiles, err := d.Readdirnames(-1)
266 var tarfiles []string
267 for _, fnm := range allfiles {
268 if strings.HasSuffix(fnm, ".tar") {
269 tarfiles = append(tarfiles, fnm)
272 if len(tarfiles) == 0 {
273 return "", fmt.Errorf("image collection does not include a .tar image file")
275 if len(tarfiles) > 1 {
276 return "", fmt.Errorf("cannot choose from multiple tar files in image collection: %v", tarfiles)
278 imageID := tarfiles[0][:len(tarfiles[0])-4]
279 imageTarballPath := runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage + "/" + imageID + ".tar"
280 runner.CrunchLog.Printf("Using Docker image id %q", imageID)
282 runner.CrunchLog.Print("Loading Docker image from keep")
283 err = runner.executor.LoadImage(imageID, imageTarballPath, runner.Container, runner.ArvMountPoint,
284 runner.containerClient)
292 func (runner *ContainerRunner) ArvMountCmd(cmdline []string, token string) (c *exec.Cmd, err error) {
293 c = exec.Command(cmdline[0], cmdline[1:]...)
295 // Copy our environment, but override ARVADOS_API_TOKEN with
296 // the container auth token.
298 for _, s := range os.Environ() {
299 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
300 c.Env = append(c.Env, s)
303 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
305 w, err := runner.NewLogWriter("arv-mount")
309 runner.arvMountLog = NewThrottledLogger(w)
310 scanner := logScanner{
313 "Block not found error",
314 "Unhandled exception during FUSE operation",
316 ReportFunc: runner.reportArvMountWarning,
318 c.Stdout = runner.arvMountLog
319 c.Stderr = io.MultiWriter(runner.arvMountLog, os.Stderr, &scanner)
321 runner.CrunchLog.Printf("Running %v", c.Args)
328 statReadme := make(chan bool)
329 runner.ArvMountExit = make(chan error)
334 time.Sleep(100 * time.Millisecond)
335 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
347 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
349 runner.ArvMountExit <- mnterr
350 close(runner.ArvMountExit)
356 case err := <-runner.ArvMountExit:
357 runner.ArvMount = nil
365 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
366 if runner.ArvMountPoint == "" {
367 runner.ArvMountPoint, err = runner.MkTempDir(runner.parentTemp, prefix)
372 func copyfile(src string, dst string) (err error) {
373 srcfile, err := os.Open(src)
378 os.MkdirAll(path.Dir(dst), 0777)
380 dstfile, err := os.Create(dst)
384 _, err = io.Copy(dstfile, srcfile)
389 err = srcfile.Close()
390 err2 := dstfile.Close()
403 func (runner *ContainerRunner) SetupMounts() (map[string]bindmount, error) {
404 bindmounts := map[string]bindmount{}
405 err := runner.SetupArvMountPoint("keep")
407 return nil, fmt.Errorf("While creating keep mount temp dir: %v", err)
410 token, err := runner.ContainerToken()
412 return nil, fmt.Errorf("could not get container token: %s", err)
414 runner.CrunchLog.Printf("container token %q", token)
418 arvMountCmd := []string{
422 "--storage-classes", strings.Join(runner.Container.OutputStorageClasses, ","),
423 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
425 if _, isdocker := runner.executor.(*dockerExecutor); isdocker {
426 arvMountCmd = append(arvMountCmd, "--allow-other")
429 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
430 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
433 collectionPaths := []string{}
434 needCertMount := true
435 type copyFile struct {
439 var copyFiles []copyFile
442 for bind := range runner.Container.Mounts {
443 binds = append(binds, bind)
445 for bind := range runner.SecretMounts {
446 if _, ok := runner.Container.Mounts[bind]; ok {
447 return nil, fmt.Errorf("secret mount %q conflicts with regular mount", bind)
449 if runner.SecretMounts[bind].Kind != "json" &&
450 runner.SecretMounts[bind].Kind != "text" {
451 return nil, fmt.Errorf("secret mount %q type is %q but only 'json' and 'text' are permitted",
452 bind, runner.SecretMounts[bind].Kind)
454 binds = append(binds, bind)
458 for _, bind := range binds {
459 mnt, notSecret := runner.Container.Mounts[bind]
461 mnt = runner.SecretMounts[bind]
463 if bind == "stdout" || bind == "stderr" {
464 // Is it a "file" mount kind?
465 if mnt.Kind != "file" {
466 return nil, fmt.Errorf("unsupported mount kind '%s' for %s: only 'file' is supported", mnt.Kind, bind)
469 // Does path start with OutputPath?
470 prefix := runner.Container.OutputPath
471 if !strings.HasSuffix(prefix, "/") {
474 if !strings.HasPrefix(mnt.Path, prefix) {
475 return nil, fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
480 // Is it a "collection" mount kind?
481 if mnt.Kind != "collection" && mnt.Kind != "json" {
482 return nil, fmt.Errorf("unsupported mount kind '%s' for stdin: only 'collection' and 'json' are supported", mnt.Kind)
486 if bind == "/etc/arvados/ca-certificates.crt" {
487 needCertMount = false
490 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
491 if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
492 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)
497 case mnt.Kind == "collection" && bind != "stdin":
499 if mnt.UUID != "" && mnt.PortableDataHash != "" {
500 return nil, fmt.Errorf("cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
504 return nil, fmt.Errorf("writing to existing collections currently not permitted")
507 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
508 } else if mnt.PortableDataHash != "" {
509 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
510 return nil, fmt.Errorf("can never write to a collection specified by portable data hash")
512 idx := strings.Index(mnt.PortableDataHash, "/")
514 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
515 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
516 runner.Container.Mounts[bind] = mnt
518 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
519 if mnt.Path != "" && mnt.Path != "." {
520 if strings.HasPrefix(mnt.Path, "./") {
521 mnt.Path = mnt.Path[2:]
522 } else if strings.HasPrefix(mnt.Path, "/") {
523 mnt.Path = mnt.Path[1:]
525 src += "/" + mnt.Path
528 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
529 arvMountCmd = append(arvMountCmd, "--mount-tmp", fmt.Sprintf("tmp%d", tmpcount))
533 if bind == runner.Container.OutputPath {
534 runner.HostOutputDir = src
535 bindmounts[bind] = bindmount{HostPath: src}
536 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
537 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
539 bindmounts[bind] = bindmount{HostPath: src}
542 bindmounts[bind] = bindmount{HostPath: src, ReadOnly: true}
544 collectionPaths = append(collectionPaths, src)
546 case mnt.Kind == "tmp":
548 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
550 return nil, fmt.Errorf("while creating mount temp dir: %v", err)
552 st, staterr := os.Stat(tmpdir)
554 return nil, fmt.Errorf("while Stat on temp dir: %v", staterr)
556 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
558 return nil, fmt.Errorf("while Chmod temp dir: %v", err)
560 bindmounts[bind] = bindmount{HostPath: tmpdir}
561 if bind == runner.Container.OutputPath {
562 runner.HostOutputDir = tmpdir
565 case mnt.Kind == "json" || mnt.Kind == "text":
567 if mnt.Kind == "json" {
568 filedata, err = json.Marshal(mnt.Content)
570 return nil, fmt.Errorf("encoding json data: %v", err)
573 text, ok := mnt.Content.(string)
575 return nil, fmt.Errorf("content for mount %q must be a string", bind)
577 filedata = []byte(text)
580 tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
582 return nil, fmt.Errorf("creating temp dir: %v", err)
584 tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
585 err = ioutil.WriteFile(tmpfn, filedata, 0444)
587 return nil, fmt.Errorf("writing temp file: %v", err)
589 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && (notSecret || runner.Container.Mounts[runner.Container.OutputPath].Kind != "collection") {
590 // In most cases, if the container
591 // specifies a literal file inside the
592 // output path, we copy it into the
593 // output directory (either a mounted
594 // collection or a staging area on the
595 // host fs). If it's a secret, it will
596 // be skipped when copying output from
597 // staging to Keep later.
598 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
600 // If a secret is outside OutputPath,
601 // we bind mount the secret file
602 // directly just like other mounts. We
603 // also use this strategy when a
604 // secret is inside OutputPath but
605 // OutputPath is a live collection, to
606 // avoid writing the secret to
607 // Keep. Attempting to remove a
608 // bind-mounted secret file from
609 // inside the container will return a
610 // "Device or resource busy" error
611 // that might not be handled well by
612 // the container, which is why we
613 // don't use this strategy when
614 // OutputPath is a staging directory.
615 bindmounts[bind] = bindmount{HostPath: tmpfn, ReadOnly: true}
618 case mnt.Kind == "git_tree":
619 tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
621 return nil, fmt.Errorf("creating temp dir: %v", err)
623 err = gitMount(mnt).extractTree(runner.ContainerArvClient, tmpdir, token)
627 bindmounts[bind] = bindmount{HostPath: tmpdir, ReadOnly: true}
631 if runner.HostOutputDir == "" {
632 return nil, fmt.Errorf("output path does not correspond to a writable mount point")
635 if needCertMount && runner.Container.RuntimeConstraints.API {
636 for _, certfile := range arvadosclient.CertFiles {
637 _, err := os.Stat(certfile)
639 bindmounts["/etc/arvados/ca-certificates.crt"] = bindmount{HostPath: certfile, ReadOnly: true}
646 // If we are only mounting collections by pdh, make
647 // sure we don't subscribe to websocket events to
648 // avoid putting undesired load on the API server
649 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id", "--disable-event-listening")
651 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
653 // the by_uuid mount point is used by singularity when writing
654 // out docker images converted to SIF
655 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_uuid")
656 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
658 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
660 return nil, fmt.Errorf("while trying to start arv-mount: %v", err)
663 for _, p := range collectionPaths {
666 return nil, fmt.Errorf("while checking that input files exist: %v", err)
670 for _, cp := range copyFiles {
671 st, err := os.Stat(cp.src)
673 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
676 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
680 target := path.Join(cp.bind, walkpath[len(cp.src):])
681 if walkinfo.Mode().IsRegular() {
682 copyerr := copyfile(walkpath, target)
686 return os.Chmod(target, walkinfo.Mode()|0777)
687 } else if walkinfo.Mode().IsDir() {
688 mkerr := os.MkdirAll(target, 0777)
692 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
694 return fmt.Errorf("source %q is not a regular file or directory", cp.src)
697 } else if st.Mode().IsRegular() {
698 err = copyfile(cp.src, cp.bind)
700 err = os.Chmod(cp.bind, st.Mode()|0777)
704 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
708 return bindmounts, nil
711 func (runner *ContainerRunner) stopHoststat() error {
712 if runner.hoststatReporter == nil {
715 runner.hoststatReporter.Stop()
716 err := runner.hoststatLogger.Close()
718 return fmt.Errorf("error closing hoststat logs: %v", err)
723 func (runner *ContainerRunner) startHoststat() error {
724 w, err := runner.NewLogWriter("hoststat")
728 runner.hoststatLogger = NewThrottledLogger(w)
729 runner.hoststatReporter = &crunchstat.Reporter{
730 Logger: log.New(runner.hoststatLogger, "", 0),
731 CgroupRoot: runner.cgroupRoot,
732 PollPeriod: runner.statInterval,
734 runner.hoststatReporter.Start()
738 func (runner *ContainerRunner) startCrunchstat() error {
739 w, err := runner.NewLogWriter("crunchstat")
743 runner.statLogger = NewThrottledLogger(w)
744 runner.statReporter = &crunchstat.Reporter{
745 CID: runner.executor.CgroupID(),
746 Logger: log.New(runner.statLogger, "", 0),
747 CgroupParent: runner.expectCgroupParent,
748 CgroupRoot: runner.cgroupRoot,
749 PollPeriod: runner.statInterval,
750 TempDir: runner.parentTemp,
752 runner.statReporter.Start()
756 type infoCommand struct {
761 // LogHostInfo logs info about the current host, for debugging and
762 // accounting purposes. Although it's logged as "node-info", this is
763 // about the environment where crunch-run is actually running, which
764 // might differ from what's described in the node record (see
766 func (runner *ContainerRunner) LogHostInfo() (err error) {
767 w, err := runner.NewLogWriter("node-info")
772 commands := []infoCommand{
774 label: "Host Information",
775 cmd: []string{"uname", "-a"},
778 label: "CPU Information",
779 cmd: []string{"cat", "/proc/cpuinfo"},
782 label: "Memory Information",
783 cmd: []string{"cat", "/proc/meminfo"},
787 cmd: []string{"df", "-m", "/", os.TempDir()},
790 label: "Disk INodes",
791 cmd: []string{"df", "-i", "/", os.TempDir()},
795 // Run commands with informational output to be logged.
796 for _, command := range commands {
797 fmt.Fprintln(w, command.label)
798 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
801 if err := cmd.Run(); err != nil {
802 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
811 return fmt.Errorf("While closing node-info logs: %v", err)
816 // LogContainerRecord gets and saves the raw JSON container record from the API server
817 func (runner *ContainerRunner) LogContainerRecord() error {
818 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
819 if !logged && err == nil {
820 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
825 // LogNodeRecord logs the current host's InstanceType config entry (or
826 // the arvados#node record, if running via crunch-dispatch-slurm).
827 func (runner *ContainerRunner) LogNodeRecord() error {
828 if it := os.Getenv("InstanceType"); it != "" {
829 // Dispatched via arvados-dispatch-cloud. Save
830 // InstanceType config fragment received from
831 // dispatcher on stdin.
832 w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
837 _, err = io.WriteString(w, it)
843 // Dispatched via crunch-dispatch-slurm. Look up
844 // apiserver's node record corresponding to
846 hostname := os.Getenv("SLURMD_NODENAME")
848 hostname, _ = os.Hostname()
850 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
851 // The "info" field has admin-only info when
852 // obtained with a privileged token, and
853 // should not be logged.
854 node, ok := resp.(map[string]interface{})
862 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
863 writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
868 ArvClient: runner.DispatcherArvClient,
869 UUID: runner.Container.UUID,
870 loggingStream: label,
874 reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
876 return false, fmt.Errorf("error getting %s record: %v", label, err)
880 dec := json.NewDecoder(reader)
882 var resp map[string]interface{}
883 if err = dec.Decode(&resp); err != nil {
884 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
886 items, ok := resp["items"].([]interface{})
888 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
889 } else if len(items) < 1 {
895 // Re-encode it using indentation to improve readability
896 enc := json.NewEncoder(w)
897 enc.SetIndent("", " ")
898 if err = enc.Encode(items[0]); err != nil {
899 return false, fmt.Errorf("error logging %s record: %v", label, err)
903 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
908 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
909 stdoutPath := mntPath[len(runner.Container.OutputPath):]
910 index := strings.LastIndex(stdoutPath, "/")
912 subdirs := stdoutPath[:index]
914 st, err := os.Stat(runner.HostOutputDir)
916 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
918 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
919 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
921 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
925 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
927 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
930 return stdoutFile, nil
933 // CreateContainer creates the docker container.
934 func (runner *ContainerRunner) CreateContainer(imageID string, bindmounts map[string]bindmount) error {
935 var stdin io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
936 if mnt, ok := runner.Container.Mounts["stdin"]; ok {
943 collID = mnt.PortableDataHash
945 path := runner.ArvMountPoint + "/by_id/" + collID + "/" + mnt.Path
946 f, err := os.Open(path)
952 j, err := json.Marshal(mnt.Content)
954 return fmt.Errorf("error encoding stdin json data: %v", err)
956 stdin = ioutil.NopCloser(bytes.NewReader(j))
958 return fmt.Errorf("stdin mount has unsupported kind %q", mnt.Kind)
962 var stdout, stderr io.WriteCloser
963 if mnt, ok := runner.Container.Mounts["stdout"]; ok {
964 f, err := runner.getStdoutFile(mnt.Path)
969 } else if w, err := runner.NewLogWriter("stdout"); err != nil {
972 stdout = NewThrottledLogger(w)
975 if mnt, ok := runner.Container.Mounts["stderr"]; ok {
976 f, err := runner.getStdoutFile(mnt.Path)
981 } else if w, err := runner.NewLogWriter("stderr"); err != nil {
984 stderr = NewThrottledLogger(w)
987 env := runner.Container.Environment
988 enableNetwork := runner.enableNetwork == "always"
989 if runner.Container.RuntimeConstraints.API {
991 tok, err := runner.ContainerToken()
995 env = map[string]string{}
996 for k, v := range runner.Container.Environment {
999 env["ARVADOS_API_TOKEN"] = tok
1000 env["ARVADOS_API_HOST"] = os.Getenv("ARVADOS_API_HOST")
1001 env["ARVADOS_API_HOST_INSECURE"] = os.Getenv("ARVADOS_API_HOST_INSECURE")
1003 workdir := runner.Container.Cwd
1005 // both "" and "." mean default
1008 ram := runner.Container.RuntimeConstraints.RAM
1009 if !runner.enableMemoryLimit {
1012 runner.executorStdin = stdin
1013 runner.executorStdout = stdout
1014 runner.executorStderr = stderr
1016 if runner.Container.RuntimeConstraints.CUDA.DeviceCount > 0 {
1017 nvidiaModprobe(runner.CrunchLog)
1020 return runner.executor.Create(containerSpec{
1022 VCPUs: runner.Container.RuntimeConstraints.VCPUs,
1024 WorkingDir: workdir,
1026 BindMounts: bindmounts,
1027 Command: runner.Container.Command,
1028 EnableNetwork: enableNetwork,
1029 CUDADeviceCount: runner.Container.RuntimeConstraints.CUDA.DeviceCount,
1030 NetworkMode: runner.networkMode,
1031 CgroupParent: runner.setCgroupParent,
1038 // StartContainer starts the docker container created by CreateContainer.
1039 func (runner *ContainerRunner) StartContainer() error {
1040 runner.CrunchLog.Printf("Starting container")
1041 runner.cStateLock.Lock()
1042 defer runner.cStateLock.Unlock()
1043 if runner.cCancelled {
1046 err := runner.executor.Start()
1049 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
1050 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])
1052 return fmt.Errorf("could not start container: %v%s", err, advice)
1057 // WaitFinish waits for the container to terminate, capture the exit code, and
1058 // close the stdout/stderr logging.
1059 func (runner *ContainerRunner) WaitFinish() error {
1060 runner.CrunchLog.Print("Waiting for container to finish")
1061 var timeout <-chan time.Time
1062 if s := runner.Container.SchedulingParameters.MaxRunTime; s > 0 {
1063 timeout = time.After(time.Duration(s) * time.Second)
1065 ctx, cancel := context.WithCancel(context.Background())
1070 runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1072 case <-runner.ArvMountExit:
1073 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1078 exitcode, err := runner.executor.Wait(ctx)
1080 runner.checkBrokenNode(err)
1083 runner.ExitCode = &exitcode
1086 if exitcode&0x80 != 0 {
1087 // Convert raw exit status (0x80 + signal number) to a
1088 // string to log after the code, like " (signal 101)"
1089 // or " (signal 9, killed)"
1090 sig := syscall.WaitStatus(exitcode).Signal()
1091 if name := unix.SignalName(sig); name != "" {
1092 extra = fmt.Sprintf(" (signal %d, %s)", sig, name)
1094 extra = fmt.Sprintf(" (signal %d)", sig)
1097 runner.CrunchLog.Printf("Container exited with status code %d%s", exitcode, extra)
1098 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1099 "container": arvadosclient.Dict{"exit_code": exitcode},
1102 runner.CrunchLog.Printf("ignoring error updating exit_code: %s", err)
1106 if err = runner.executorStdin.Close(); err != nil {
1107 err = fmt.Errorf("error closing container stdin: %s", err)
1108 runner.CrunchLog.Printf("%s", err)
1111 if err = runner.executorStdout.Close(); err != nil {
1112 err = fmt.Errorf("error closing container stdout: %s", err)
1113 runner.CrunchLog.Printf("%s", err)
1114 if returnErr == nil {
1118 if err = runner.executorStderr.Close(); err != nil {
1119 err = fmt.Errorf("error closing container stderr: %s", err)
1120 runner.CrunchLog.Printf("%s", err)
1121 if returnErr == nil {
1126 if runner.statReporter != nil {
1127 runner.statReporter.Stop()
1128 err = runner.statLogger.Close()
1130 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
1136 func (runner *ContainerRunner) updateLogs() {
1137 ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1140 sigusr1 := make(chan os.Signal, 1)
1141 signal.Notify(sigusr1, syscall.SIGUSR1)
1142 defer signal.Stop(sigusr1)
1144 saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1145 saveAtSize := crunchLogUpdateSize
1151 saveAtTime = time.Now()
1153 runner.logMtx.Lock()
1154 done := runner.LogsPDH != nil
1155 runner.logMtx.Unlock()
1159 size := runner.LogCollection.Size()
1160 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1163 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1164 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1165 saved, err := runner.saveLogCollection(false)
1167 runner.CrunchLog.Printf("error updating log collection: %s", err)
1171 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1172 "container": arvadosclient.Dict{"log": saved.PortableDataHash},
1175 runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1183 func (runner *ContainerRunner) reportArvMountWarning(pattern, text string) {
1184 var updated arvados.Container
1185 err := runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1186 "container": arvadosclient.Dict{
1187 "runtime_status": arvadosclient.Dict{
1188 "warning": "arv-mount: " + pattern,
1189 "warningDetail": text,
1194 runner.CrunchLog.Printf("error updating container runtime_status: %s", err)
1198 // CaptureOutput saves data from the container's output directory if
1199 // needed, and updates the container output accordingly.
1200 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1201 if runner.Container.RuntimeConstraints.API {
1202 // Output may have been set directly by the container, so
1203 // refresh the container record to check.
1204 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1205 nil, &runner.Container)
1209 if runner.Container.Output != "" {
1210 // Container output is already set.
1211 runner.OutputPDH = &runner.Container.Output
1216 txt, err := (&copier{
1217 client: runner.containerClient,
1218 arvClient: runner.ContainerArvClient,
1219 keepClient: runner.ContainerKeepClient,
1220 hostOutputDir: runner.HostOutputDir,
1221 ctrOutputDir: runner.Container.OutputPath,
1222 bindmounts: bindmounts,
1223 mounts: runner.Container.Mounts,
1224 secretMounts: runner.SecretMounts,
1225 logger: runner.CrunchLog,
1230 if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1231 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1232 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1236 txt, err = fs.MarshalManifest(".")
1241 var resp arvados.Collection
1242 err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1243 "ensure_unique_name": true,
1244 "collection": arvadosclient.Dict{
1246 "name": "output for " + runner.Container.UUID,
1247 "manifest_text": txt,
1251 return fmt.Errorf("error creating output collection: %v", err)
1253 runner.OutputPDH = &resp.PortableDataHash
1257 func (runner *ContainerRunner) CleanupDirs() {
1258 if runner.ArvMount != nil {
1260 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1261 umount.Stdout = runner.CrunchLog
1262 umount.Stderr = runner.CrunchLog
1263 runner.CrunchLog.Printf("Running %v", umount.Args)
1264 umnterr := umount.Start()
1267 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1268 runner.ArvMount.Process.Kill()
1270 // If arv-mount --unmount gets stuck for any reason, we
1271 // don't want to wait for it forever. Do Wait() in a goroutine
1272 // so it doesn't block crunch-run.
1273 umountExit := make(chan error)
1275 mnterr := umount.Wait()
1277 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1279 umountExit <- mnterr
1282 for again := true; again; {
1288 case <-runner.ArvMountExit:
1290 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1291 runner.CrunchLog.Printf("Timed out waiting for unmount")
1293 umount.Process.Kill()
1295 runner.ArvMount.Process.Kill()
1299 runner.ArvMount = nil
1302 if runner.ArvMountPoint != "" {
1303 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1304 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1306 runner.ArvMountPoint = ""
1309 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1310 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1314 // CommitLogs posts the collection containing the final container logs.
1315 func (runner *ContainerRunner) CommitLogs() error {
1317 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1318 runner.cStateLock.Lock()
1319 defer runner.cStateLock.Unlock()
1321 runner.CrunchLog.Print(runner.finalState)
1323 if runner.arvMountLog != nil {
1324 runner.arvMountLog.Close()
1326 runner.CrunchLog.Close()
1328 // Closing CrunchLog above allows them to be committed to Keep at this
1329 // point, but re-open crunch log with ArvClient in case there are any
1330 // other further errors (such as failing to write the log to Keep!)
1331 // while shutting down
1332 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1333 ArvClient: runner.DispatcherArvClient,
1334 UUID: runner.Container.UUID,
1335 loggingStream: "crunch-run",
1338 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1341 if runner.keepstoreLogger != nil {
1342 // Flush any buffered logs from our local keepstore
1343 // process. Discard anything logged after this point
1344 // -- it won't end up in the log collection, so
1345 // there's no point writing it to the collectionfs.
1346 runner.keepstoreLogbuf.SetWriter(io.Discard)
1347 runner.keepstoreLogger.Close()
1348 runner.keepstoreLogger = nil
1351 if runner.LogsPDH != nil {
1352 // If we have already assigned something to LogsPDH,
1353 // we must be closing the re-opened log, which won't
1354 // end up getting attached to the container record and
1355 // therefore doesn't need to be saved as a collection
1356 // -- it exists only to send logs to other channels.
1360 saved, err := runner.saveLogCollection(true)
1362 return fmt.Errorf("error saving log collection: %s", err)
1364 runner.logMtx.Lock()
1365 defer runner.logMtx.Unlock()
1366 runner.LogsPDH = &saved.PortableDataHash
1370 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1371 runner.logMtx.Lock()
1372 defer runner.logMtx.Unlock()
1373 if runner.LogsPDH != nil {
1374 // Already finalized.
1377 updates := arvadosclient.Dict{
1378 "name": "logs for " + runner.Container.UUID,
1380 mt, err1 := runner.LogCollection.MarshalManifest(".")
1382 // Only send updated manifest text if there was no
1384 updates["manifest_text"] = mt
1387 // Even if flushing the manifest had an error, we still want
1388 // to update the log record, if possible, to push the trash_at
1389 // and delete_at times into the future. Details on bug
1392 updates["is_trashed"] = true
1394 exp := time.Now().Add(crunchLogUpdatePeriod * 24)
1395 updates["trash_at"] = exp
1396 updates["delete_at"] = exp
1398 reqBody := arvadosclient.Dict{"collection": updates}
1400 if runner.logUUID == "" {
1401 reqBody["ensure_unique_name"] = true
1402 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1404 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1407 runner.logUUID = response.UUID
1410 if err1 != nil || err2 != nil {
1411 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1416 // UpdateContainerRunning updates the container state to "Running"
1417 func (runner *ContainerRunner) UpdateContainerRunning() error {
1418 runner.cStateLock.Lock()
1419 defer runner.cStateLock.Unlock()
1420 if runner.cCancelled {
1423 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID,
1424 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running", "gateway_address": runner.gateway.Address}}, nil)
1427 // ContainerToken returns the api_token the container (and any
1428 // arv-mount processes) are allowed to use.
1429 func (runner *ContainerRunner) ContainerToken() (string, error) {
1430 if runner.token != "" {
1431 return runner.token, nil
1434 var auth arvados.APIClientAuthorization
1435 err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1439 runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1440 return runner.token, nil
1443 // UpdateContainerFinal updates the container record state on API
1444 // server to "Complete" or "Cancelled"
1445 func (runner *ContainerRunner) UpdateContainerFinal() error {
1446 update := arvadosclient.Dict{}
1447 update["state"] = runner.finalState
1448 if runner.LogsPDH != nil {
1449 update["log"] = *runner.LogsPDH
1451 if runner.ExitCode != nil {
1452 update["exit_code"] = *runner.ExitCode
1454 update["exit_code"] = nil
1456 if runner.finalState == "Complete" && runner.OutputPDH != nil {
1457 update["output"] = *runner.OutputPDH
1459 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1462 // IsCancelled returns the value of Cancelled, with goroutine safety.
1463 func (runner *ContainerRunner) IsCancelled() bool {
1464 runner.cStateLock.Lock()
1465 defer runner.cStateLock.Unlock()
1466 return runner.cCancelled
1469 // NewArvLogWriter creates an ArvLogWriter
1470 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1471 writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1475 return &ArvLogWriter{
1476 ArvClient: runner.DispatcherArvClient,
1477 UUID: runner.Container.UUID,
1478 loggingStream: name,
1479 writeCloser: writer,
1483 // Run the full container lifecycle.
1484 func (runner *ContainerRunner) Run() (err error) {
1485 runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1486 runner.CrunchLog.Printf("%s", currentUserAndGroups())
1487 v, _ := exec.Command("arv-mount", "--version").CombinedOutput()
1488 runner.CrunchLog.Printf("Using FUSE mount: %s", v)
1489 runner.CrunchLog.Printf("Using container runtime: %s", runner.executor.Runtime())
1490 runner.CrunchLog.Printf("Executing container: %s", runner.Container.UUID)
1492 hostname, hosterr := os.Hostname()
1494 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1496 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1499 runner.finalState = "Queued"
1502 runner.CleanupDirs()
1504 runner.CrunchLog.Printf("crunch-run finished")
1505 runner.CrunchLog.Close()
1508 err = runner.fetchContainerRecord()
1512 if runner.Container.State != "Locked" {
1513 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1516 var bindmounts map[string]bindmount
1518 // checkErr prints e (unless it's nil) and sets err to
1519 // e (unless err is already non-nil). Thus, if err
1520 // hasn't already been assigned when Run() returns,
1521 // this cleanup func will cause Run() to return the
1522 // first non-nil error that is passed to checkErr().
1523 checkErr := func(errorIn string, e error) {
1527 runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1531 if runner.finalState == "Complete" {
1532 // There was an error in the finalization.
1533 runner.finalState = "Cancelled"
1537 // Log the error encountered in Run(), if any
1538 checkErr("Run", err)
1540 if runner.finalState == "Queued" {
1541 runner.UpdateContainerFinal()
1545 if runner.IsCancelled() {
1546 runner.finalState = "Cancelled"
1547 // but don't return yet -- we still want to
1548 // capture partial output and write logs
1551 if bindmounts != nil {
1552 checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1554 checkErr("stopHoststat", runner.stopHoststat())
1555 checkErr("CommitLogs", runner.CommitLogs())
1556 runner.CleanupDirs()
1557 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1560 runner.setupSignals()
1561 err = runner.startHoststat()
1566 // set up FUSE mount and binds
1567 bindmounts, err = runner.SetupMounts()
1569 runner.finalState = "Cancelled"
1570 err = fmt.Errorf("While setting up mounts: %v", err)
1574 // check for and/or load image
1575 imageID, err := runner.LoadImage()
1577 if !runner.checkBrokenNode(err) {
1578 // Failed to load image but not due to a "broken node"
1579 // condition, probably user error.
1580 runner.finalState = "Cancelled"
1582 err = fmt.Errorf("While loading container image: %v", err)
1586 err = runner.CreateContainer(imageID, bindmounts)
1590 err = runner.LogHostInfo()
1594 err = runner.LogNodeRecord()
1598 err = runner.LogContainerRecord()
1603 if runner.IsCancelled() {
1607 err = runner.UpdateContainerRunning()
1611 runner.finalState = "Cancelled"
1613 err = runner.startCrunchstat()
1618 err = runner.StartContainer()
1620 runner.checkBrokenNode(err)
1624 err = runner.WaitFinish()
1625 if err == nil && !runner.IsCancelled() {
1626 runner.finalState = "Complete"
1631 // Fetch the current container record (uuid = runner.Container.UUID)
1632 // into runner.Container.
1633 func (runner *ContainerRunner) fetchContainerRecord() error {
1634 reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1636 return fmt.Errorf("error fetching container record: %v", err)
1638 defer reader.Close()
1640 dec := json.NewDecoder(reader)
1642 err = dec.Decode(&runner.Container)
1644 return fmt.Errorf("error decoding container record: %v", err)
1648 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1651 containerToken, err := runner.ContainerToken()
1653 return fmt.Errorf("error getting container token: %v", err)
1656 runner.ContainerArvClient, runner.ContainerKeepClient,
1657 runner.containerClient, err = runner.MkArvClient(containerToken)
1659 return fmt.Errorf("error creating container API client: %v", err)
1662 runner.ContainerKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1663 runner.DispatcherKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1665 err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1667 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1668 return fmt.Errorf("error fetching secret_mounts: %v", err)
1670 // ok && apierr.HttpStatusCode == 404, which means
1671 // secret_mounts isn't supported by this API server.
1673 runner.SecretMounts = sm.SecretMounts
1678 // NewContainerRunner creates a new container runner.
1679 func NewContainerRunner(dispatcherClient *arvados.Client,
1680 dispatcherArvClient IArvadosClient,
1681 dispatcherKeepClient IKeepClient,
1682 containerUUID string) (*ContainerRunner, error) {
1684 cr := &ContainerRunner{
1685 dispatcherClient: dispatcherClient,
1686 DispatcherArvClient: dispatcherArvClient,
1687 DispatcherKeepClient: dispatcherKeepClient,
1689 cr.NewLogWriter = cr.NewArvLogWriter
1690 cr.RunArvMount = cr.ArvMountCmd
1691 cr.MkTempDir = ioutil.TempDir
1692 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1693 cl, err := arvadosclient.MakeArvadosClient()
1695 return nil, nil, nil, err
1698 kc, err := keepclient.MakeKeepClient(cl)
1700 return nil, nil, nil, err
1702 c2 := arvados.NewClientFromEnv()
1703 c2.AuthToken = token
1704 return cl, kc, c2, nil
1707 cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1711 cr.Container.UUID = containerUUID
1712 w, err := cr.NewLogWriter("crunch-run")
1716 cr.CrunchLog = NewThrottledLogger(w)
1717 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1719 loadLogThrottleParams(dispatcherArvClient)
1725 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1726 log := log.New(stderr, "", 0)
1727 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1728 statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1729 cgroupRoot := flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1730 cgroupParent := flags.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1731 cgroupParentSubsystem := flags.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1732 caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1733 detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1734 stdinConfig := flags.Bool("stdin-config", false, "Load config and environment variables from JSON message on stdin")
1735 configFile := flags.String("config", arvados.DefaultConfigFile, "filename of cluster config file to try loading if -stdin-config=false (default is $ARVADOS_CONFIG)")
1736 sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1737 kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1738 list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes")
1739 enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1740 enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1741 networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1742 memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1743 runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1744 brokenNodeHook := flags.String("broken-node-hook", "", "script to run if node is detected to be broken (for example, Docker daemon is not running)")
1745 flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1747 ignoreDetachFlag := false
1748 if len(args) > 0 && args[0] == "-no-detach" {
1749 // This process was invoked by a parent process, which
1750 // has passed along its own arguments, including
1751 // -detach, after the leading -no-detach flag. Strip
1752 // the leading -no-detach flag (it's not recognized by
1753 // flags.Parse()) and ignore the -detach flag that
1756 ignoreDetachFlag = true
1759 if ok, code := cmd.ParseFlags(flags, prog, args, "container-uuid", stderr); !ok {
1761 } else if !*list && flags.NArg() != 1 {
1762 fmt.Fprintf(stderr, "missing required argument: container-uuid (try -help)\n")
1766 containerUUID := flags.Arg(0)
1769 case *detach && !ignoreDetachFlag:
1770 return Detach(containerUUID, prog, args, os.Stdin, os.Stdout, os.Stderr)
1772 return KillProcess(containerUUID, syscall.Signal(*kill), os.Stdout, os.Stderr)
1774 return ListProcesses(os.Stdout, os.Stderr)
1777 if len(containerUUID) != 27 {
1778 log.Printf("usage: %s [options] UUID", prog)
1782 var keepstoreLogbuf bufThenWrite
1785 err := json.NewDecoder(stdin).Decode(&conf)
1787 log.Printf("decode stdin: %s", err)
1790 for k, v := range conf.Env {
1791 err = os.Setenv(k, v)
1793 log.Printf("setenv(%q): %s", k, err)
1797 if conf.Cluster != nil {
1798 // ClusterID is missing from the JSON
1799 // representation, but we need it to generate
1800 // a valid config file for keepstore, so we
1801 // fill it using the container UUID prefix.
1802 conf.Cluster.ClusterID = containerUUID[:5]
1805 conf = hpcConfData(containerUUID, *configFile, io.MultiWriter(&keepstoreLogbuf, stderr))
1808 log.Printf("crunch-run %s started", cmd.Version.String())
1811 if *caCertsPath != "" {
1812 arvadosclient.CertFiles = []string{*caCertsPath}
1815 keepstore, err := startLocalKeepstore(conf, io.MultiWriter(&keepstoreLogbuf, stderr))
1820 if keepstore != nil {
1821 defer keepstore.Process.Kill()
1824 api, err := arvadosclient.MakeArvadosClient()
1826 log.Printf("%s: %v", containerUUID, err)
1831 kc, err := keepclient.MakeKeepClient(api)
1833 log.Printf("%s: %v", containerUUID, err)
1836 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1839 cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
1845 if keepstore == nil {
1846 // Log explanation (if any) for why we're not running
1847 // a local keepstore.
1848 var buf bytes.Buffer
1849 keepstoreLogbuf.SetWriter(&buf)
1851 cr.CrunchLog.Printf("%s", strings.TrimSpace(buf.String()))
1853 } else if logWhat := conf.Cluster.Containers.LocalKeepLogsToContainerLog; logWhat == "none" {
1854 cr.CrunchLog.Printf("using local keepstore process (pid %d) at %s", keepstore.Process.Pid, os.Getenv("ARVADOS_KEEP_SERVICES"))
1855 keepstoreLogbuf.SetWriter(io.Discard)
1857 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"))
1858 logwriter, err := cr.NewLogWriter("keepstore")
1863 cr.keepstoreLogger = NewThrottledLogger(logwriter)
1865 var writer io.WriteCloser = cr.keepstoreLogger
1866 if logWhat == "errors" {
1867 writer = &filterKeepstoreErrorsOnly{WriteCloser: writer}
1868 } else if logWhat != "all" {
1869 // should have been caught earlier by
1870 // dispatcher's config loader
1871 log.Printf("invalid value for Containers.LocalKeepLogsToContainerLog: %q", logWhat)
1874 err = keepstoreLogbuf.SetWriter(writer)
1879 cr.keepstoreLogbuf = &keepstoreLogbuf
1882 switch *runtimeEngine {
1884 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
1886 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
1888 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
1889 cr.CrunchLog.Close()
1893 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
1894 cr.checkBrokenNode(err)
1895 cr.CrunchLog.Close()
1898 defer cr.executor.Close()
1900 cr.brokenNodeHook = *brokenNodeHook
1902 gwAuthSecret := os.Getenv("GatewayAuthSecret")
1903 os.Unsetenv("GatewayAuthSecret")
1904 if gwAuthSecret == "" {
1905 // not safe to run a gateway service without an auth
1907 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAuthSecret was not provided by dispatcher)")
1909 gwListen := os.Getenv("GatewayAddress")
1910 cr.gateway = Gateway{
1912 AuthSecret: gwAuthSecret,
1913 ContainerUUID: containerUUID,
1914 Target: cr.executor,
1918 // Direct connection won't work, so we use the
1919 // gateway_address field to indicate the
1920 // internalURL of the controller process that
1921 // has the current tunnel connection.
1922 cr.gateway.ArvadosClient = cr.dispatcherClient
1923 cr.gateway.UpdateTunnelURL = func(url string) {
1924 cr.gateway.Address = "tunnel " + url
1925 cr.DispatcherArvClient.Update("containers", containerUUID,
1926 arvadosclient.Dict{"container": arvadosclient.Dict{"gateway_address": cr.gateway.Address}}, nil)
1929 err = cr.gateway.Start()
1931 log.Printf("error starting gateway server: %s", err)
1936 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
1938 log.Printf("%s: %v", containerUUID, tmperr)
1942 cr.parentTemp = parentTemp
1943 cr.statInterval = *statInterval
1944 cr.cgroupRoot = *cgroupRoot
1945 cr.expectCgroupParent = *cgroupParent
1946 cr.enableMemoryLimit = *enableMemoryLimit
1947 cr.enableNetwork = *enableNetwork
1948 cr.networkMode = *networkMode
1949 if *cgroupParentSubsystem != "" {
1950 p, err := findCgroup(*cgroupParentSubsystem)
1952 log.Printf("fatal: cgroup parent subsystem: %s", err)
1955 cr.setCgroupParent = p
1956 cr.expectCgroupParent = p
1961 if *memprofile != "" {
1962 f, err := os.Create(*memprofile)
1964 log.Printf("could not create memory profile: %s", err)
1966 runtime.GC() // get up-to-date statistics
1967 if err := pprof.WriteHeapProfile(f); err != nil {
1968 log.Printf("could not write memory profile: %s", err)
1970 closeerr := f.Close()
1971 if closeerr != nil {
1972 log.Printf("closing memprofile file: %s", err)
1977 log.Printf("%s: %v", containerUUID, runerr)
1983 // Try to load ConfigData in hpc (slurm/lsf) environment. This means
1984 // loading the cluster config from the specified file and (if that
1985 // works) getting the runtime_constraints container field from
1986 // controller to determine # VCPUs so we can calculate KeepBuffers.
1987 func hpcConfData(uuid string, configFile string, stderr io.Writer) ConfigData {
1989 conf.Cluster = loadClusterConfigFile(configFile, stderr)
1990 if conf.Cluster == nil {
1991 // skip loading the container record -- we won't be
1992 // able to start local keepstore anyway.
1995 arv, err := arvadosclient.MakeArvadosClient()
1997 fmt.Fprintf(stderr, "error setting up arvadosclient: %s\n", err)
2001 var ctr arvados.Container
2002 err = arv.Call("GET", "containers", uuid, "", arvadosclient.Dict{"select": []string{"runtime_constraints"}}, &ctr)
2004 fmt.Fprintf(stderr, "error getting container record: %s\n", err)
2007 if ctr.RuntimeConstraints.VCPUs > 0 {
2008 conf.KeepBuffers = ctr.RuntimeConstraints.VCPUs * conf.Cluster.Containers.LocalKeepBlobBuffersPerVCPU
2013 // Load cluster config file from given path. If an error occurs, log
2014 // the error to stderr and return nil.
2015 func loadClusterConfigFile(path string, stderr io.Writer) *arvados.Cluster {
2016 ldr := config.NewLoader(&bytes.Buffer{}, ctxlog.New(stderr, "plain", "info"))
2018 cfg, err := ldr.Load()
2020 fmt.Fprintf(stderr, "could not load config file %s: %s\n", path, err)
2023 cluster, err := cfg.GetCluster("")
2025 fmt.Fprintf(stderr, "could not use config file %s: %s\n", path, err)
2028 fmt.Fprintf(stderr, "loaded config file %s\n", path)
2032 func startLocalKeepstore(configData ConfigData, logbuf io.Writer) (*exec.Cmd, error) {
2033 if configData.KeepBuffers < 1 {
2034 fmt.Fprintf(logbuf, "not starting a local keepstore process because KeepBuffers=%v in config\n", configData.KeepBuffers)
2037 if configData.Cluster == nil {
2038 fmt.Fprint(logbuf, "not starting a local keepstore process because cluster config file was not loaded\n")
2041 for uuid, vol := range configData.Cluster.Volumes {
2042 if len(vol.AccessViaHosts) > 0 {
2043 fmt.Fprintf(logbuf, "not starting a local keepstore process because a volume (%s) uses AccessViaHosts\n", uuid)
2046 if !vol.ReadOnly && vol.Replication < configData.Cluster.Collections.DefaultReplication {
2047 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)
2052 // Rather than have an alternate way to tell keepstore how
2053 // many buffers to use when starting it this way, we just
2054 // modify the cluster configuration that we feed it on stdin.
2055 configData.Cluster.API.MaxKeepBlobBuffers = configData.KeepBuffers
2057 ln, err := net.Listen("tcp", "localhost:0")
2061 _, port, err := net.SplitHostPort(ln.Addr().String())
2067 url := "http://localhost:" + port
2069 fmt.Fprintf(logbuf, "starting keepstore on %s\n", url)
2071 var confJSON bytes.Buffer
2072 err = json.NewEncoder(&confJSON).Encode(arvados.Config{
2073 Clusters: map[string]arvados.Cluster{
2074 configData.Cluster.ClusterID: *configData.Cluster,
2080 cmd := exec.Command("/proc/self/exe", "keepstore", "-config=-")
2081 if target, err := os.Readlink(cmd.Path); err == nil && strings.HasSuffix(target, ".test") {
2082 // If we're a 'go test' process, running
2083 // /proc/self/exe would start the test suite in a
2084 // child process, which is not what we want.
2085 cmd.Path, _ = exec.LookPath("go")
2086 cmd.Args = append([]string{"go", "run", "../../cmd/arvados-server"}, cmd.Args[1:]...)
2087 cmd.Env = os.Environ()
2089 cmd.Stdin = &confJSON
2092 cmd.Env = append(cmd.Env,
2094 "ARVADOS_SERVICE_INTERNAL_URL="+url)
2097 return nil, fmt.Errorf("error starting keepstore process: %w", err)
2104 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10))
2106 poll := time.NewTicker(time.Second / 10)
2108 client := http.Client{}
2110 testReq, err := http.NewRequestWithContext(ctx, "GET", url+"/_health/ping", nil)
2111 testReq.Header.Set("Authorization", "Bearer "+configData.Cluster.ManagementToken)
2115 resp, err := client.Do(testReq)
2118 if resp.StatusCode == http.StatusOK {
2123 return nil, fmt.Errorf("keepstore child process exited")
2125 if ctx.Err() != nil {
2126 return nil, fmt.Errorf("timed out waiting for new keepstore process to report healthy")
2129 os.Setenv("ARVADOS_KEEP_SERVICES", url)
2133 // return current uid, gid, groups in a format suitable for logging:
2134 // "crunch-run process has uid=1234(arvados) gid=1234(arvados)
2135 // groups=1234(arvados),114(fuse)"
2136 func currentUserAndGroups() string {
2137 u, err := user.Current()
2139 return fmt.Sprintf("error getting current user ID: %s", err)
2141 s := fmt.Sprintf("crunch-run process has uid=%s(%s) gid=%s", u.Uid, u.Username, u.Gid)
2142 if g, err := user.LookupGroupId(u.Gid); err == nil {
2143 s += fmt.Sprintf("(%s)", g.Name)
2146 if gids, err := u.GroupIds(); err == nil {
2147 for i, gid := range gids {
2152 if g, err := user.LookupGroupId(gid); err == nil {
2153 s += fmt.Sprintf("(%s)", g.Name)