1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
30 "git.arvados.org/arvados.git/lib/cmd"
31 "git.arvados.org/arvados.git/lib/crunchstat"
32 "git.arvados.org/arvados.git/sdk/go/arvados"
33 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
34 "git.arvados.org/arvados.git/sdk/go/keepclient"
35 "git.arvados.org/arvados.git/sdk/go/manifest"
36 "golang.org/x/net/context"
41 var Command = command{}
43 // IArvadosClient is the minimal Arvados API methods used by crunch-run.
44 type IArvadosClient interface {
45 Create(resourceType string, parameters arvadosclient.Dict, output interface{}) error
46 Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
47 Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error
48 Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error
49 CallRaw(method string, resourceType string, uuid string, action string, parameters arvadosclient.Dict) (reader io.ReadCloser, err error)
50 Discovery(key string) (interface{}, error)
53 // ErrCancelled is the error returned when the container is cancelled.
54 var ErrCancelled = errors.New("Cancelled")
56 // IKeepClient is the minimal Keep API methods used by crunch-run.
57 type IKeepClient interface {
58 BlockWrite(context.Context, arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error)
59 ReadAt(locator string, p []byte, off int) (int, error)
60 ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error)
61 LocalLocator(locator string) (string, error)
63 SetStorageClasses(sc []string)
66 // NewLogWriter is a factory function to create a new log writer.
67 type NewLogWriter func(name string) (io.WriteCloser, error)
69 type RunArvMount func(cmdline []string, tok string) (*exec.Cmd, error)
71 type MkTempDir func(string, string) (string, error)
73 type PsProcess interface {
74 CmdlineSlice() ([]string, error)
77 // ContainerRunner is the main stateful struct used for a single execution of a
79 type ContainerRunner struct {
80 executor containerExecutor
81 executorStdin io.Closer
82 executorStdout io.Closer
83 executorStderr io.Closer
85 // Dispatcher client is initialized with the Dispatcher token.
86 // This is a privileged token used to manage container status
89 // We have both dispatcherClient and DispatcherArvClient
90 // because there are two different incompatible Arvados Go
91 // SDKs and we have to use both (hopefully this gets fixed in
93 dispatcherClient *arvados.Client
94 DispatcherArvClient IArvadosClient
95 DispatcherKeepClient IKeepClient
97 // Container client is initialized with the Container token
98 // This token controls the permissions of the container, and
99 // must be used for operations such as reading collections.
101 // Same comment as above applies to
102 // containerClient/ContainerArvClient.
103 containerClient *arvados.Client
104 ContainerArvClient IArvadosClient
105 ContainerKeepClient IKeepClient
107 Container arvados.Container
110 NewLogWriter NewLogWriter
111 CrunchLog *ThrottledLogger
114 LogCollection arvados.CollectionFileSystem
116 RunArvMount RunArvMount
121 Volumes map[string]struct{}
123 SigChan chan os.Signal
124 ArvMountExit chan error
125 SecretMounts map[string]arvados.Mount
126 MkArvClient func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error)
130 statLogger io.WriteCloser
131 statReporter *crunchstat.Reporter
132 hoststatLogger io.WriteCloser
133 hoststatReporter *crunchstat.Reporter
134 statInterval time.Duration
136 // What we expect the container's cgroup parent to be.
137 expectCgroupParent string
138 // What we tell docker to use as the container's cgroup
139 // parent. Note: Ideally we would use the same field for both
140 // expectCgroupParent and setCgroupParent, and just make it
141 // default to "docker". However, when using docker < 1.10 with
142 // systemd, specifying a non-empty cgroup parent (even the
143 // default value "docker") hits a docker bug
144 // (https://github.com/docker/docker/issues/17126). Using two
145 // separate fields makes it possible to use the "expect cgroup
146 // parent to be X" feature even on sites where the "specify
147 // cgroup parent" feature breaks.
148 setCgroupParent string
150 cStateLock sync.Mutex
151 cCancelled bool // StopContainer() invoked
153 enableMemoryLimit bool
154 enableNetwork string // one of "default" or "always"
155 networkMode string // "none", "host", or "" -- passed through to executor
156 arvMountLog *ThrottledLogger
158 containerWatchdogInterval time.Duration
163 // setupSignals sets up signal handling to gracefully terminate the
164 // underlying container and update state when receiving a TERM, INT or
166 func (runner *ContainerRunner) setupSignals() {
167 runner.SigChan = make(chan os.Signal, 1)
168 signal.Notify(runner.SigChan, syscall.SIGTERM)
169 signal.Notify(runner.SigChan, syscall.SIGINT)
170 signal.Notify(runner.SigChan, syscall.SIGQUIT)
172 go func(sig chan os.Signal) {
179 // stop the underlying container.
180 func (runner *ContainerRunner) stop(sig os.Signal) {
181 runner.cStateLock.Lock()
182 defer runner.cStateLock.Unlock()
184 runner.CrunchLog.Printf("caught signal: %v", sig)
186 runner.cCancelled = true
187 runner.CrunchLog.Printf("stopping container")
188 err := runner.executor.Stop()
190 runner.CrunchLog.Printf("error stopping container: %s", err)
194 var errorBlacklist = []string{
195 "(?ms).*[Cc]annot connect to the Docker daemon.*",
196 "(?ms).*oci runtime error.*starting container process.*container init.*mounting.*to rootfs.*no such file or directory.*",
197 "(?ms).*grpc: the connection is unavailable.*",
199 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)")
201 func (runner *ContainerRunner) runBrokenNodeHook() {
202 if *brokenNodeHook == "" {
203 path := filepath.Join(lockdir, brokenfile)
204 runner.CrunchLog.Printf("Writing %s to mark node as broken", path)
205 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0700)
207 runner.CrunchLog.Printf("Error writing %s: %s", path, err)
212 runner.CrunchLog.Printf("Running broken node hook %q", *brokenNodeHook)
214 c := exec.Command(*brokenNodeHook)
215 c.Stdout = runner.CrunchLog
216 c.Stderr = runner.CrunchLog
219 runner.CrunchLog.Printf("Error running broken node hook: %v", err)
224 func (runner *ContainerRunner) checkBrokenNode(goterr error) bool {
225 for _, d := range errorBlacklist {
226 if m, e := regexp.MatchString(d, goterr.Error()); m && e == nil {
227 runner.CrunchLog.Printf("Error suggests node is unable to run containers: %v", goterr)
228 runner.runBrokenNodeHook()
235 // LoadImage determines the docker image id from the container record and
236 // checks if it is available in the local Docker image store. If not, it loads
237 // the image from Keep.
238 func (runner *ContainerRunner) LoadImage() (string, error) {
239 runner.CrunchLog.Printf("Fetching Docker image from collection '%s'", runner.Container.ContainerImage)
241 d, err := os.Open(runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage)
246 allfiles, err := d.Readdirnames(-1)
250 var tarfiles []string
251 for _, fnm := range allfiles {
252 if strings.HasSuffix(fnm, ".tar") {
253 tarfiles = append(tarfiles, fnm)
256 if len(tarfiles) == 0 {
257 return "", fmt.Errorf("image collection does not include a .tar image file")
259 if len(tarfiles) > 1 {
260 return "", fmt.Errorf("cannot choose from multiple tar files in image collection: %v", tarfiles)
262 imageID := tarfiles[0][:len(tarfiles[0])-4]
263 imageTarballPath := runner.ArvMountPoint + "/by_id/" + runner.Container.ContainerImage + "/" + imageID + ".tar"
264 runner.CrunchLog.Printf("Using Docker image id %q", imageID)
266 runner.CrunchLog.Print("Loading Docker image from keep")
267 err = runner.executor.LoadImage(imageID, imageTarballPath, runner.Container, runner.ArvMountPoint,
268 runner.containerClient)
276 func (runner *ContainerRunner) ArvMountCmd(cmdline []string, token string) (c *exec.Cmd, err error) {
277 c = exec.Command(cmdline[0], cmdline[1:]...)
279 // Copy our environment, but override ARVADOS_API_TOKEN with
280 // the container auth token.
282 for _, s := range os.Environ() {
283 if !strings.HasPrefix(s, "ARVADOS_API_TOKEN=") {
284 c.Env = append(c.Env, s)
287 c.Env = append(c.Env, "ARVADOS_API_TOKEN="+token)
289 w, err := runner.NewLogWriter("arv-mount")
293 runner.arvMountLog = NewThrottledLogger(w)
294 scanner := logScanner{
297 "Block not found error",
298 "Unhandled exception during FUSE operation",
300 ReportFunc: runner.reportArvMountWarning,
302 c.Stdout = runner.arvMountLog
303 c.Stderr = io.MultiWriter(runner.arvMountLog, os.Stderr, &scanner)
305 runner.CrunchLog.Printf("Running %v", c.Args)
312 statReadme := make(chan bool)
313 runner.ArvMountExit = make(chan error)
318 time.Sleep(100 * time.Millisecond)
319 _, err = os.Stat(fmt.Sprintf("%s/by_id/README", runner.ArvMountPoint))
331 runner.CrunchLog.Printf("Arv-mount exit error: %v", mnterr)
333 runner.ArvMountExit <- mnterr
334 close(runner.ArvMountExit)
340 case err := <-runner.ArvMountExit:
341 runner.ArvMount = nil
349 func (runner *ContainerRunner) SetupArvMountPoint(prefix string) (err error) {
350 if runner.ArvMountPoint == "" {
351 runner.ArvMountPoint, err = runner.MkTempDir(runner.parentTemp, prefix)
356 func copyfile(src string, dst string) (err error) {
357 srcfile, err := os.Open(src)
362 os.MkdirAll(path.Dir(dst), 0777)
364 dstfile, err := os.Create(dst)
368 _, err = io.Copy(dstfile, srcfile)
373 err = srcfile.Close()
374 err2 := dstfile.Close()
387 func (runner *ContainerRunner) SetupMounts() (map[string]bindmount, error) {
388 bindmounts := map[string]bindmount{}
389 err := runner.SetupArvMountPoint("keep")
391 return nil, fmt.Errorf("While creating keep mount temp dir: %v", err)
394 token, err := runner.ContainerToken()
396 return nil, fmt.Errorf("could not get container token: %s", err)
398 runner.CrunchLog.Printf("container token %q", token)
402 arvMountCmd := []string{
407 "--storage-classes", strings.Join(runner.Container.OutputStorageClasses, ","),
408 fmt.Sprintf("--crunchstat-interval=%v", runner.statInterval.Seconds())}
410 if runner.Container.RuntimeConstraints.KeepCacheRAM > 0 {
411 arvMountCmd = append(arvMountCmd, "--file-cache", fmt.Sprintf("%d", runner.Container.RuntimeConstraints.KeepCacheRAM))
414 collectionPaths := []string{}
415 needCertMount := true
416 type copyFile struct {
420 var copyFiles []copyFile
423 for bind := range runner.Container.Mounts {
424 binds = append(binds, bind)
426 for bind := range runner.SecretMounts {
427 if _, ok := runner.Container.Mounts[bind]; ok {
428 return nil, fmt.Errorf("secret mount %q conflicts with regular mount", bind)
430 if runner.SecretMounts[bind].Kind != "json" &&
431 runner.SecretMounts[bind].Kind != "text" {
432 return nil, fmt.Errorf("secret mount %q type is %q but only 'json' and 'text' are permitted",
433 bind, runner.SecretMounts[bind].Kind)
435 binds = append(binds, bind)
439 for _, bind := range binds {
440 mnt, ok := runner.Container.Mounts[bind]
442 mnt = runner.SecretMounts[bind]
444 if bind == "stdout" || bind == "stderr" {
445 // Is it a "file" mount kind?
446 if mnt.Kind != "file" {
447 return nil, fmt.Errorf("unsupported mount kind '%s' for %s: only 'file' is supported", mnt.Kind, bind)
450 // Does path start with OutputPath?
451 prefix := runner.Container.OutputPath
452 if !strings.HasSuffix(prefix, "/") {
455 if !strings.HasPrefix(mnt.Path, prefix) {
456 return nil, fmt.Errorf("%s path does not start with OutputPath: %s, %s", strings.Title(bind), mnt.Path, prefix)
461 // Is it a "collection" mount kind?
462 if mnt.Kind != "collection" && mnt.Kind != "json" {
463 return nil, fmt.Errorf("unsupported mount kind '%s' for stdin: only 'collection' and 'json' are supported", mnt.Kind)
467 if bind == "/etc/arvados/ca-certificates.crt" {
468 needCertMount = false
471 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") && bind != runner.Container.OutputPath+"/" {
472 if mnt.Kind != "collection" && mnt.Kind != "text" && mnt.Kind != "json" {
473 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)
478 case mnt.Kind == "collection" && bind != "stdin":
480 if mnt.UUID != "" && mnt.PortableDataHash != "" {
481 return nil, fmt.Errorf("cannot specify both 'uuid' and 'portable_data_hash' for a collection mount")
485 return nil, fmt.Errorf("writing to existing collections currently not permitted")
488 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.UUID)
489 } else if mnt.PortableDataHash != "" {
490 if mnt.Writable && !strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
491 return nil, fmt.Errorf("can never write to a collection specified by portable data hash")
493 idx := strings.Index(mnt.PortableDataHash, "/")
495 mnt.Path = path.Clean(mnt.PortableDataHash[idx:])
496 mnt.PortableDataHash = mnt.PortableDataHash[0:idx]
497 runner.Container.Mounts[bind] = mnt
499 src = fmt.Sprintf("%s/by_id/%s", runner.ArvMountPoint, mnt.PortableDataHash)
500 if mnt.Path != "" && mnt.Path != "." {
501 if strings.HasPrefix(mnt.Path, "./") {
502 mnt.Path = mnt.Path[2:]
503 } else if strings.HasPrefix(mnt.Path, "/") {
504 mnt.Path = mnt.Path[1:]
506 src += "/" + mnt.Path
509 src = fmt.Sprintf("%s/tmp%d", runner.ArvMountPoint, tmpcount)
510 arvMountCmd = append(arvMountCmd, "--mount-tmp")
511 arvMountCmd = append(arvMountCmd, fmt.Sprintf("tmp%d", tmpcount))
515 if bind == runner.Container.OutputPath {
516 runner.HostOutputDir = src
517 bindmounts[bind] = bindmount{HostPath: src}
518 } else if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
519 copyFiles = append(copyFiles, copyFile{src, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
521 bindmounts[bind] = bindmount{HostPath: src}
524 bindmounts[bind] = bindmount{HostPath: src, ReadOnly: true}
526 collectionPaths = append(collectionPaths, src)
528 case mnt.Kind == "tmp":
530 tmpdir, err = runner.MkTempDir(runner.parentTemp, "tmp")
532 return nil, fmt.Errorf("while creating mount temp dir: %v", err)
534 st, staterr := os.Stat(tmpdir)
536 return nil, fmt.Errorf("while Stat on temp dir: %v", staterr)
538 err = os.Chmod(tmpdir, st.Mode()|os.ModeSetgid|0777)
540 return nil, fmt.Errorf("while Chmod temp dir: %v", err)
542 bindmounts[bind] = bindmount{HostPath: tmpdir}
543 if bind == runner.Container.OutputPath {
544 runner.HostOutputDir = tmpdir
547 case mnt.Kind == "json" || mnt.Kind == "text":
549 if mnt.Kind == "json" {
550 filedata, err = json.Marshal(mnt.Content)
552 return nil, fmt.Errorf("encoding json data: %v", err)
555 text, ok := mnt.Content.(string)
557 return nil, fmt.Errorf("content for mount %q must be a string", bind)
559 filedata = []byte(text)
562 tmpdir, err := runner.MkTempDir(runner.parentTemp, mnt.Kind)
564 return nil, fmt.Errorf("creating temp dir: %v", err)
566 tmpfn := filepath.Join(tmpdir, "mountdata."+mnt.Kind)
567 err = ioutil.WriteFile(tmpfn, filedata, 0444)
569 return nil, fmt.Errorf("writing temp file: %v", err)
571 if strings.HasPrefix(bind, runner.Container.OutputPath+"/") {
572 copyFiles = append(copyFiles, copyFile{tmpfn, runner.HostOutputDir + bind[len(runner.Container.OutputPath):]})
574 bindmounts[bind] = bindmount{HostPath: tmpfn, ReadOnly: true}
577 case mnt.Kind == "git_tree":
578 tmpdir, err := runner.MkTempDir(runner.parentTemp, "git_tree")
580 return nil, fmt.Errorf("creating temp dir: %v", err)
582 err = gitMount(mnt).extractTree(runner.ContainerArvClient, tmpdir, token)
586 bindmounts[bind] = bindmount{HostPath: tmpdir, ReadOnly: true}
590 if runner.HostOutputDir == "" {
591 return nil, fmt.Errorf("output path does not correspond to a writable mount point")
594 if needCertMount && runner.Container.RuntimeConstraints.API {
595 for _, certfile := range arvadosclient.CertFiles {
596 _, err := os.Stat(certfile)
598 bindmounts["/etc/arvados/ca-certificates.crt"] = bindmount{HostPath: certfile, ReadOnly: true}
605 arvMountCmd = append(arvMountCmd, "--mount-by-pdh", "by_id")
607 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_id")
609 arvMountCmd = append(arvMountCmd, "--mount-by-id", "by_uuid")
610 arvMountCmd = append(arvMountCmd, runner.ArvMountPoint)
612 runner.ArvMount, err = runner.RunArvMount(arvMountCmd, token)
614 return nil, fmt.Errorf("while trying to start arv-mount: %v", err)
617 for _, p := range collectionPaths {
620 return nil, fmt.Errorf("while checking that input files exist: %v", err)
624 for _, cp := range copyFiles {
625 st, err := os.Stat(cp.src)
627 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
630 err = filepath.Walk(cp.src, func(walkpath string, walkinfo os.FileInfo, walkerr error) error {
634 target := path.Join(cp.bind, walkpath[len(cp.src):])
635 if walkinfo.Mode().IsRegular() {
636 copyerr := copyfile(walkpath, target)
640 return os.Chmod(target, walkinfo.Mode()|0777)
641 } else if walkinfo.Mode().IsDir() {
642 mkerr := os.MkdirAll(target, 0777)
646 return os.Chmod(target, walkinfo.Mode()|os.ModeSetgid|0777)
648 return fmt.Errorf("source %q is not a regular file or directory", cp.src)
651 } else if st.Mode().IsRegular() {
652 err = copyfile(cp.src, cp.bind)
654 err = os.Chmod(cp.bind, st.Mode()|0777)
658 return nil, fmt.Errorf("while staging writable file from %q to %q: %v", cp.src, cp.bind, err)
662 return bindmounts, nil
665 func (runner *ContainerRunner) stopHoststat() error {
666 if runner.hoststatReporter == nil {
669 runner.hoststatReporter.Stop()
670 err := runner.hoststatLogger.Close()
672 return fmt.Errorf("error closing hoststat logs: %v", err)
677 func (runner *ContainerRunner) startHoststat() error {
678 w, err := runner.NewLogWriter("hoststat")
682 runner.hoststatLogger = NewThrottledLogger(w)
683 runner.hoststatReporter = &crunchstat.Reporter{
684 Logger: log.New(runner.hoststatLogger, "", 0),
685 CgroupRoot: runner.cgroupRoot,
686 PollPeriod: runner.statInterval,
688 runner.hoststatReporter.Start()
692 func (runner *ContainerRunner) startCrunchstat() error {
693 w, err := runner.NewLogWriter("crunchstat")
697 runner.statLogger = NewThrottledLogger(w)
698 runner.statReporter = &crunchstat.Reporter{
699 CID: runner.executor.CgroupID(),
700 Logger: log.New(runner.statLogger, "", 0),
701 CgroupParent: runner.expectCgroupParent,
702 CgroupRoot: runner.cgroupRoot,
703 PollPeriod: runner.statInterval,
704 TempDir: runner.parentTemp,
706 runner.statReporter.Start()
710 type infoCommand struct {
715 // LogHostInfo logs info about the current host, for debugging and
716 // accounting purposes. Although it's logged as "node-info", this is
717 // about the environment where crunch-run is actually running, which
718 // might differ from what's described in the node record (see
720 func (runner *ContainerRunner) LogHostInfo() (err error) {
721 w, err := runner.NewLogWriter("node-info")
726 commands := []infoCommand{
728 label: "Host Information",
729 cmd: []string{"uname", "-a"},
732 label: "CPU Information",
733 cmd: []string{"cat", "/proc/cpuinfo"},
736 label: "Memory Information",
737 cmd: []string{"cat", "/proc/meminfo"},
741 cmd: []string{"df", "-m", "/", os.TempDir()},
744 label: "Disk INodes",
745 cmd: []string{"df", "-i", "/", os.TempDir()},
749 // Run commands with informational output to be logged.
750 for _, command := range commands {
751 fmt.Fprintln(w, command.label)
752 cmd := exec.Command(command.cmd[0], command.cmd[1:]...)
755 if err := cmd.Run(); err != nil {
756 err = fmt.Errorf("While running command %q: %v", command.cmd, err)
765 return fmt.Errorf("While closing node-info logs: %v", err)
770 // LogContainerRecord gets and saves the raw JSON container record from the API server
771 func (runner *ContainerRunner) LogContainerRecord() error {
772 logged, err := runner.logAPIResponse("container", "containers", map[string]interface{}{"filters": [][]string{{"uuid", "=", runner.Container.UUID}}}, nil)
773 if !logged && err == nil {
774 err = fmt.Errorf("error: no container record found for %s", runner.Container.UUID)
779 // LogNodeRecord logs the current host's InstanceType config entry (or
780 // the arvados#node record, if running via crunch-dispatch-slurm).
781 func (runner *ContainerRunner) LogNodeRecord() error {
782 if it := os.Getenv("InstanceType"); it != "" {
783 // Dispatched via arvados-dispatch-cloud. Save
784 // InstanceType config fragment received from
785 // dispatcher on stdin.
786 w, err := runner.LogCollection.OpenFile("node.json", os.O_CREATE|os.O_WRONLY, 0666)
791 _, err = io.WriteString(w, it)
797 // Dispatched via crunch-dispatch-slurm. Look up
798 // apiserver's node record corresponding to
800 hostname := os.Getenv("SLURMD_NODENAME")
802 hostname, _ = os.Hostname()
804 _, err := runner.logAPIResponse("node", "nodes", map[string]interface{}{"filters": [][]string{{"hostname", "=", hostname}}}, func(resp interface{}) {
805 // The "info" field has admin-only info when
806 // obtained with a privileged token, and
807 // should not be logged.
808 node, ok := resp.(map[string]interface{})
816 func (runner *ContainerRunner) logAPIResponse(label, path string, params map[string]interface{}, munge func(interface{})) (logged bool, err error) {
817 writer, err := runner.LogCollection.OpenFile(label+".json", os.O_CREATE|os.O_WRONLY, 0666)
822 ArvClient: runner.DispatcherArvClient,
823 UUID: runner.Container.UUID,
824 loggingStream: label,
828 reader, err := runner.DispatcherArvClient.CallRaw("GET", path, "", "", arvadosclient.Dict(params))
830 return false, fmt.Errorf("error getting %s record: %v", label, err)
834 dec := json.NewDecoder(reader)
836 var resp map[string]interface{}
837 if err = dec.Decode(&resp); err != nil {
838 return false, fmt.Errorf("error decoding %s list response: %v", label, err)
840 items, ok := resp["items"].([]interface{})
842 return false, fmt.Errorf("error decoding %s list response: no \"items\" key in API list response", label)
843 } else if len(items) < 1 {
849 // Re-encode it using indentation to improve readability
850 enc := json.NewEncoder(w)
851 enc.SetIndent("", " ")
852 if err = enc.Encode(items[0]); err != nil {
853 return false, fmt.Errorf("error logging %s record: %v", label, err)
857 return false, fmt.Errorf("error closing %s.json in log collection: %v", label, err)
862 func (runner *ContainerRunner) getStdoutFile(mntPath string) (*os.File, error) {
863 stdoutPath := mntPath[len(runner.Container.OutputPath):]
864 index := strings.LastIndex(stdoutPath, "/")
866 subdirs := stdoutPath[:index]
868 st, err := os.Stat(runner.HostOutputDir)
870 return nil, fmt.Errorf("While Stat on temp dir: %v", err)
872 stdoutPath := filepath.Join(runner.HostOutputDir, subdirs)
873 err = os.MkdirAll(stdoutPath, st.Mode()|os.ModeSetgid|0777)
875 return nil, fmt.Errorf("While MkdirAll %q: %v", stdoutPath, err)
879 stdoutFile, err := os.Create(filepath.Join(runner.HostOutputDir, stdoutPath))
881 return nil, fmt.Errorf("While creating file %q: %v", stdoutPath, err)
884 return stdoutFile, nil
887 // CreateContainer creates the docker container.
888 func (runner *ContainerRunner) CreateContainer(imageID string, bindmounts map[string]bindmount) error {
889 var stdin io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
890 if mnt, ok := runner.Container.Mounts["stdin"]; ok {
897 collID = mnt.PortableDataHash
899 path := runner.ArvMountPoint + "/by_id/" + collID + "/" + mnt.Path
900 f, err := os.Open(path)
906 j, err := json.Marshal(mnt.Content)
908 return fmt.Errorf("error encoding stdin json data: %v", err)
910 stdin = ioutil.NopCloser(bytes.NewReader(j))
912 return fmt.Errorf("stdin mount has unsupported kind %q", mnt.Kind)
916 var stdout, stderr io.WriteCloser
917 if mnt, ok := runner.Container.Mounts["stdout"]; ok {
918 f, err := runner.getStdoutFile(mnt.Path)
923 } else if w, err := runner.NewLogWriter("stdout"); err != nil {
926 stdout = NewThrottledLogger(w)
929 if mnt, ok := runner.Container.Mounts["stderr"]; ok {
930 f, err := runner.getStdoutFile(mnt.Path)
935 } else if w, err := runner.NewLogWriter("stderr"); err != nil {
938 stderr = NewThrottledLogger(w)
941 env := runner.Container.Environment
942 enableNetwork := runner.enableNetwork == "always"
943 if runner.Container.RuntimeConstraints.API {
945 tok, err := runner.ContainerToken()
949 env = map[string]string{}
950 for k, v := range runner.Container.Environment {
953 env["ARVADOS_API_TOKEN"] = tok
954 env["ARVADOS_API_HOST"] = os.Getenv("ARVADOS_API_HOST")
955 env["ARVADOS_API_HOST_INSECURE"] = os.Getenv("ARVADOS_API_HOST_INSECURE")
957 workdir := runner.Container.Cwd
959 // both "" and "." mean default
962 ram := runner.Container.RuntimeConstraints.RAM
963 if !runner.enableMemoryLimit {
966 runner.executorStdin = stdin
967 runner.executorStdout = stdout
968 runner.executorStderr = stderr
969 return runner.executor.Create(containerSpec{
971 VCPUs: runner.Container.RuntimeConstraints.VCPUs,
975 BindMounts: bindmounts,
976 Command: runner.Container.Command,
977 EnableNetwork: enableNetwork,
978 NetworkMode: runner.networkMode,
979 CgroupParent: runner.setCgroupParent,
986 // StartContainer starts the docker container created by CreateContainer.
987 func (runner *ContainerRunner) StartContainer() error {
988 runner.CrunchLog.Printf("Starting container")
989 runner.cStateLock.Lock()
990 defer runner.cStateLock.Unlock()
991 if runner.cCancelled {
994 err := runner.executor.Start()
997 if m, e := regexp.MatchString("(?ms).*(exec|System error).*(no such file or directory|file not found).*", err.Error()); m && e == nil {
998 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])
1000 return fmt.Errorf("could not start container: %v%s", err, advice)
1005 // WaitFinish waits for the container to terminate, capture the exit code, and
1006 // close the stdout/stderr logging.
1007 func (runner *ContainerRunner) WaitFinish() error {
1008 runner.CrunchLog.Print("Waiting for container to finish")
1009 var timeout <-chan time.Time
1010 if s := runner.Container.SchedulingParameters.MaxRunTime; s > 0 {
1011 timeout = time.After(time.Duration(s) * time.Second)
1013 ctx, cancel := context.WithCancel(context.Background())
1018 runner.CrunchLog.Printf("maximum run time exceeded. Stopping container.")
1020 case <-runner.ArvMountExit:
1021 runner.CrunchLog.Printf("arv-mount exited while container is still running. Stopping container.")
1026 exitcode, err := runner.executor.Wait(ctx)
1028 runner.checkBrokenNode(err)
1031 runner.ExitCode = &exitcode
1034 if err = runner.executorStdin.Close(); err != nil {
1035 err = fmt.Errorf("error closing container stdin: %s", err)
1036 runner.CrunchLog.Printf("%s", err)
1039 if err = runner.executorStdout.Close(); err != nil {
1040 err = fmt.Errorf("error closing container stdout: %s", err)
1041 runner.CrunchLog.Printf("%s", err)
1042 if returnErr == nil {
1046 if err = runner.executorStderr.Close(); err != nil {
1047 err = fmt.Errorf("error closing container stderr: %s", err)
1048 runner.CrunchLog.Printf("%s", err)
1049 if returnErr == nil {
1054 if runner.statReporter != nil {
1055 runner.statReporter.Stop()
1056 err = runner.statLogger.Close()
1058 runner.CrunchLog.Printf("error closing crunchstat logs: %v", err)
1064 func (runner *ContainerRunner) updateLogs() {
1065 ticker := time.NewTicker(crunchLogUpdatePeriod / 360)
1068 sigusr1 := make(chan os.Signal, 1)
1069 signal.Notify(sigusr1, syscall.SIGUSR1)
1070 defer signal.Stop(sigusr1)
1072 saveAtTime := time.Now().Add(crunchLogUpdatePeriod)
1073 saveAtSize := crunchLogUpdateSize
1079 saveAtTime = time.Now()
1081 runner.logMtx.Lock()
1082 done := runner.LogsPDH != nil
1083 runner.logMtx.Unlock()
1087 size := runner.LogCollection.Size()
1088 if size == savedSize || (time.Now().Before(saveAtTime) && size < saveAtSize) {
1091 saveAtTime = time.Now().Add(crunchLogUpdatePeriod)
1092 saveAtSize = runner.LogCollection.Size() + crunchLogUpdateSize
1093 saved, err := runner.saveLogCollection(false)
1095 runner.CrunchLog.Printf("error updating log collection: %s", err)
1099 var updated arvados.Container
1100 err = runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1101 "container": arvadosclient.Dict{"log": saved.PortableDataHash},
1104 runner.CrunchLog.Printf("error updating container log to %s: %s", saved.PortableDataHash, err)
1112 func (runner *ContainerRunner) reportArvMountWarning(pattern, text string) {
1113 var updated arvados.Container
1114 err := runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{
1115 "container": arvadosclient.Dict{
1116 "runtime_status": arvadosclient.Dict{
1117 "warning": "arv-mount: " + pattern,
1118 "warningDetail": text,
1123 runner.CrunchLog.Printf("error updating container runtime_status: %s", err)
1127 // CaptureOutput saves data from the container's output directory if
1128 // needed, and updates the container output accordingly.
1129 func (runner *ContainerRunner) CaptureOutput(bindmounts map[string]bindmount) error {
1130 if runner.Container.RuntimeConstraints.API {
1131 // Output may have been set directly by the container, so
1132 // refresh the container record to check.
1133 err := runner.DispatcherArvClient.Get("containers", runner.Container.UUID,
1134 nil, &runner.Container)
1138 if runner.Container.Output != "" {
1139 // Container output is already set.
1140 runner.OutputPDH = &runner.Container.Output
1145 txt, err := (&copier{
1146 client: runner.containerClient,
1147 arvClient: runner.ContainerArvClient,
1148 keepClient: runner.ContainerKeepClient,
1149 hostOutputDir: runner.HostOutputDir,
1150 ctrOutputDir: runner.Container.OutputPath,
1151 bindmounts: bindmounts,
1152 mounts: runner.Container.Mounts,
1153 secretMounts: runner.SecretMounts,
1154 logger: runner.CrunchLog,
1159 if n := len(regexp.MustCompile(` [0-9a-f]+\+\S*\+R`).FindAllStringIndex(txt, -1)); n > 0 {
1160 runner.CrunchLog.Printf("Copying %d data blocks from remote input collections...", n)
1161 fs, err := (&arvados.Collection{ManifestText: txt}).FileSystem(runner.containerClient, runner.ContainerKeepClient)
1165 txt, err = fs.MarshalManifest(".")
1170 var resp arvados.Collection
1171 err = runner.ContainerArvClient.Create("collections", arvadosclient.Dict{
1172 "ensure_unique_name": true,
1173 "collection": arvadosclient.Dict{
1175 "name": "output for " + runner.Container.UUID,
1176 "manifest_text": txt,
1180 return fmt.Errorf("error creating output collection: %v", err)
1182 runner.OutputPDH = &resp.PortableDataHash
1186 func (runner *ContainerRunner) CleanupDirs() {
1187 if runner.ArvMount != nil {
1189 umount := exec.Command("arv-mount", fmt.Sprintf("--unmount-timeout=%d", delay), "--unmount", runner.ArvMountPoint)
1190 umount.Stdout = runner.CrunchLog
1191 umount.Stderr = runner.CrunchLog
1192 runner.CrunchLog.Printf("Running %v", umount.Args)
1193 umnterr := umount.Start()
1196 runner.CrunchLog.Printf("Error unmounting: %v", umnterr)
1197 runner.ArvMount.Process.Kill()
1199 // If arv-mount --unmount gets stuck for any reason, we
1200 // don't want to wait for it forever. Do Wait() in a goroutine
1201 // so it doesn't block crunch-run.
1202 umountExit := make(chan error)
1204 mnterr := umount.Wait()
1206 runner.CrunchLog.Printf("Error unmounting: %v", mnterr)
1208 umountExit <- mnterr
1211 for again := true; again; {
1217 case <-runner.ArvMountExit:
1219 case <-time.After(time.Duration((delay + 1) * int64(time.Second))):
1220 runner.CrunchLog.Printf("Timed out waiting for unmount")
1222 umount.Process.Kill()
1224 runner.ArvMount.Process.Kill()
1228 runner.ArvMount = nil
1231 if runner.ArvMountPoint != "" {
1232 if rmerr := os.Remove(runner.ArvMountPoint); rmerr != nil {
1233 runner.CrunchLog.Printf("While cleaning up arv-mount directory %s: %v", runner.ArvMountPoint, rmerr)
1235 runner.ArvMountPoint = ""
1238 if rmerr := os.RemoveAll(runner.parentTemp); rmerr != nil {
1239 runner.CrunchLog.Printf("While cleaning up temporary directory %s: %v", runner.parentTemp, rmerr)
1243 // CommitLogs posts the collection containing the final container logs.
1244 func (runner *ContainerRunner) CommitLogs() error {
1246 // Hold cStateLock to prevent races on CrunchLog (e.g., stop()).
1247 runner.cStateLock.Lock()
1248 defer runner.cStateLock.Unlock()
1250 runner.CrunchLog.Print(runner.finalState)
1252 if runner.arvMountLog != nil {
1253 runner.arvMountLog.Close()
1255 runner.CrunchLog.Close()
1257 // Closing CrunchLog above allows them to be committed to Keep at this
1258 // point, but re-open crunch log with ArvClient in case there are any
1259 // other further errors (such as failing to write the log to Keep!)
1260 // while shutting down
1261 runner.CrunchLog = NewThrottledLogger(&ArvLogWriter{
1262 ArvClient: runner.DispatcherArvClient,
1263 UUID: runner.Container.UUID,
1264 loggingStream: "crunch-run",
1267 runner.CrunchLog.Immediate = log.New(os.Stderr, runner.Container.UUID+" ", 0)
1270 if runner.LogsPDH != nil {
1271 // If we have already assigned something to LogsPDH,
1272 // we must be closing the re-opened log, which won't
1273 // end up getting attached to the container record and
1274 // therefore doesn't need to be saved as a collection
1275 // -- it exists only to send logs to other channels.
1278 saved, err := runner.saveLogCollection(true)
1280 return fmt.Errorf("error saving log collection: %s", err)
1282 runner.logMtx.Lock()
1283 defer runner.logMtx.Unlock()
1284 runner.LogsPDH = &saved.PortableDataHash
1288 func (runner *ContainerRunner) saveLogCollection(final bool) (response arvados.Collection, err error) {
1289 runner.logMtx.Lock()
1290 defer runner.logMtx.Unlock()
1291 if runner.LogsPDH != nil {
1292 // Already finalized.
1295 updates := arvadosclient.Dict{
1296 "name": "logs for " + runner.Container.UUID,
1298 mt, err1 := runner.LogCollection.MarshalManifest(".")
1300 // Only send updated manifest text if there was no
1302 updates["manifest_text"] = mt
1305 // Even if flushing the manifest had an error, we still want
1306 // to update the log record, if possible, to push the trash_at
1307 // and delete_at times into the future. Details on bug
1310 updates["is_trashed"] = true
1312 exp := time.Now().Add(crunchLogUpdatePeriod * 24)
1313 updates["trash_at"] = exp
1314 updates["delete_at"] = exp
1316 reqBody := arvadosclient.Dict{"collection": updates}
1318 if runner.logUUID == "" {
1319 reqBody["ensure_unique_name"] = true
1320 err2 = runner.DispatcherArvClient.Create("collections", reqBody, &response)
1322 err2 = runner.DispatcherArvClient.Update("collections", runner.logUUID, reqBody, &response)
1325 runner.logUUID = response.UUID
1328 if err1 != nil || err2 != nil {
1329 err = fmt.Errorf("error recording logs: %q, %q", err1, err2)
1334 // UpdateContainerRunning updates the container state to "Running"
1335 func (runner *ContainerRunner) UpdateContainerRunning() error {
1336 runner.cStateLock.Lock()
1337 defer runner.cStateLock.Unlock()
1338 if runner.cCancelled {
1341 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID,
1342 arvadosclient.Dict{"container": arvadosclient.Dict{"state": "Running", "gateway_address": runner.gateway.Address}}, nil)
1345 // ContainerToken returns the api_token the container (and any
1346 // arv-mount processes) are allowed to use.
1347 func (runner *ContainerRunner) ContainerToken() (string, error) {
1348 if runner.token != "" {
1349 return runner.token, nil
1352 var auth arvados.APIClientAuthorization
1353 err := runner.DispatcherArvClient.Call("GET", "containers", runner.Container.UUID, "auth", nil, &auth)
1357 runner.token = fmt.Sprintf("v2/%s/%s/%s", auth.UUID, auth.APIToken, runner.Container.UUID)
1358 return runner.token, nil
1361 // UpdateContainerFinal updates the container record state on API
1362 // server to "Complete" or "Cancelled"
1363 func (runner *ContainerRunner) UpdateContainerFinal() error {
1364 update := arvadosclient.Dict{}
1365 update["state"] = runner.finalState
1366 if runner.LogsPDH != nil {
1367 update["log"] = *runner.LogsPDH
1369 if runner.finalState == "Complete" {
1370 if runner.ExitCode != nil {
1371 update["exit_code"] = *runner.ExitCode
1373 if runner.OutputPDH != nil {
1374 update["output"] = *runner.OutputPDH
1377 return runner.DispatcherArvClient.Update("containers", runner.Container.UUID, arvadosclient.Dict{"container": update}, nil)
1380 // IsCancelled returns the value of Cancelled, with goroutine safety.
1381 func (runner *ContainerRunner) IsCancelled() bool {
1382 runner.cStateLock.Lock()
1383 defer runner.cStateLock.Unlock()
1384 return runner.cCancelled
1387 // NewArvLogWriter creates an ArvLogWriter
1388 func (runner *ContainerRunner) NewArvLogWriter(name string) (io.WriteCloser, error) {
1389 writer, err := runner.LogCollection.OpenFile(name+".txt", os.O_CREATE|os.O_WRONLY, 0666)
1393 return &ArvLogWriter{
1394 ArvClient: runner.DispatcherArvClient,
1395 UUID: runner.Container.UUID,
1396 loggingStream: name,
1397 writeCloser: writer,
1401 // Run the full container lifecycle.
1402 func (runner *ContainerRunner) Run() (err error) {
1403 runner.CrunchLog.Printf("crunch-run %s started", cmd.Version.String())
1404 runner.CrunchLog.Printf("Executing container '%s' using %s runtime", runner.Container.UUID, runner.executor.Runtime())
1406 hostname, hosterr := os.Hostname()
1408 runner.CrunchLog.Printf("Error getting hostname '%v'", hosterr)
1410 runner.CrunchLog.Printf("Executing on host '%s'", hostname)
1413 runner.finalState = "Queued"
1416 runner.CleanupDirs()
1418 runner.CrunchLog.Printf("crunch-run finished")
1419 runner.CrunchLog.Close()
1422 err = runner.fetchContainerRecord()
1426 if runner.Container.State != "Locked" {
1427 return fmt.Errorf("dispatch error detected: container %q has state %q", runner.Container.UUID, runner.Container.State)
1430 var bindmounts map[string]bindmount
1432 // checkErr prints e (unless it's nil) and sets err to
1433 // e (unless err is already non-nil). Thus, if err
1434 // hasn't already been assigned when Run() returns,
1435 // this cleanup func will cause Run() to return the
1436 // first non-nil error that is passed to checkErr().
1437 checkErr := func(errorIn string, e error) {
1441 runner.CrunchLog.Printf("error in %s: %v", errorIn, e)
1445 if runner.finalState == "Complete" {
1446 // There was an error in the finalization.
1447 runner.finalState = "Cancelled"
1451 // Log the error encountered in Run(), if any
1452 checkErr("Run", err)
1454 if runner.finalState == "Queued" {
1455 runner.UpdateContainerFinal()
1459 if runner.IsCancelled() {
1460 runner.finalState = "Cancelled"
1461 // but don't return yet -- we still want to
1462 // capture partial output and write logs
1465 if bindmounts != nil {
1466 checkErr("CaptureOutput", runner.CaptureOutput(bindmounts))
1468 checkErr("stopHoststat", runner.stopHoststat())
1469 checkErr("CommitLogs", runner.CommitLogs())
1470 runner.CleanupDirs()
1471 checkErr("UpdateContainerFinal", runner.UpdateContainerFinal())
1474 runner.setupSignals()
1475 err = runner.startHoststat()
1480 // set up FUSE mount and binds
1481 bindmounts, err = runner.SetupMounts()
1483 runner.finalState = "Cancelled"
1484 err = fmt.Errorf("While setting up mounts: %v", err)
1488 // check for and/or load image
1489 imageID, err := runner.LoadImage()
1491 if !runner.checkBrokenNode(err) {
1492 // Failed to load image but not due to a "broken node"
1493 // condition, probably user error.
1494 runner.finalState = "Cancelled"
1496 err = fmt.Errorf("While loading container image: %v", err)
1500 err = runner.CreateContainer(imageID, bindmounts)
1504 err = runner.LogHostInfo()
1508 err = runner.LogNodeRecord()
1512 err = runner.LogContainerRecord()
1517 if runner.IsCancelled() {
1521 err = runner.UpdateContainerRunning()
1525 runner.finalState = "Cancelled"
1527 err = runner.startCrunchstat()
1532 err = runner.StartContainer()
1534 runner.checkBrokenNode(err)
1538 err = runner.WaitFinish()
1539 if err == nil && !runner.IsCancelled() {
1540 runner.finalState = "Complete"
1545 // Fetch the current container record (uuid = runner.Container.UUID)
1546 // into runner.Container.
1547 func (runner *ContainerRunner) fetchContainerRecord() error {
1548 reader, err := runner.DispatcherArvClient.CallRaw("GET", "containers", runner.Container.UUID, "", nil)
1550 return fmt.Errorf("error fetching container record: %v", err)
1552 defer reader.Close()
1554 dec := json.NewDecoder(reader)
1556 err = dec.Decode(&runner.Container)
1558 return fmt.Errorf("error decoding container record: %v", err)
1562 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
1565 containerToken, err := runner.ContainerToken()
1567 return fmt.Errorf("error getting container token: %v", err)
1570 runner.ContainerArvClient, runner.ContainerKeepClient,
1571 runner.containerClient, err = runner.MkArvClient(containerToken)
1573 return fmt.Errorf("error creating container API client: %v", err)
1576 runner.ContainerKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1577 runner.DispatcherKeepClient.SetStorageClasses(runner.Container.OutputStorageClasses)
1579 err = runner.ContainerArvClient.Call("GET", "containers", runner.Container.UUID, "secret_mounts", nil, &sm)
1581 if apierr, ok := err.(arvadosclient.APIServerError); !ok || apierr.HttpStatusCode != 404 {
1582 return fmt.Errorf("error fetching secret_mounts: %v", err)
1584 // ok && apierr.HttpStatusCode == 404, which means
1585 // secret_mounts isn't supported by this API server.
1587 runner.SecretMounts = sm.SecretMounts
1592 // NewContainerRunner creates a new container runner.
1593 func NewContainerRunner(dispatcherClient *arvados.Client,
1594 dispatcherArvClient IArvadosClient,
1595 dispatcherKeepClient IKeepClient,
1596 containerUUID string) (*ContainerRunner, error) {
1598 cr := &ContainerRunner{
1599 dispatcherClient: dispatcherClient,
1600 DispatcherArvClient: dispatcherArvClient,
1601 DispatcherKeepClient: dispatcherKeepClient,
1603 cr.NewLogWriter = cr.NewArvLogWriter
1604 cr.RunArvMount = cr.ArvMountCmd
1605 cr.MkTempDir = ioutil.TempDir
1606 cr.MkArvClient = func(token string) (IArvadosClient, IKeepClient, *arvados.Client, error) {
1607 cl, err := arvadosclient.MakeArvadosClient()
1609 return nil, nil, nil, err
1612 kc, err := keepclient.MakeKeepClient(cl)
1614 return nil, nil, nil, err
1616 c2 := arvados.NewClientFromEnv()
1617 c2.AuthToken = token
1618 return cl, kc, c2, nil
1621 cr.LogCollection, err = (&arvados.Collection{}).FileSystem(cr.dispatcherClient, cr.DispatcherKeepClient)
1625 cr.Container.UUID = containerUUID
1626 w, err := cr.NewLogWriter("crunch-run")
1630 cr.CrunchLog = NewThrottledLogger(w)
1631 cr.CrunchLog.Immediate = log.New(os.Stderr, containerUUID+" ", 0)
1633 loadLogThrottleParams(dispatcherArvClient)
1639 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
1640 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
1641 statInterval := flags.Duration("crunchstat-interval", 10*time.Second, "sampling period for periodic resource usage reporting")
1642 cgroupRoot := flags.String("cgroup-root", "/sys/fs/cgroup", "path to sysfs cgroup tree")
1643 cgroupParent := flags.String("cgroup-parent", "docker", "name of container's parent cgroup (ignored if -cgroup-parent-subsystem is used)")
1644 cgroupParentSubsystem := flags.String("cgroup-parent-subsystem", "", "use current cgroup for given subsystem as parent cgroup for container")
1645 caCertsPath := flags.String("ca-certs", "", "Path to TLS root certificates")
1646 detach := flags.Bool("detach", false, "Detach from parent process and run in the background")
1647 stdinEnv := flags.Bool("stdin-env", false, "Load environment variables from JSON message on stdin")
1648 sleep := flags.Duration("sleep", 0, "Delay before starting (testing use only)")
1649 kill := flags.Int("kill", -1, "Send signal to an existing crunch-run process for given UUID")
1650 list := flags.Bool("list", false, "List UUIDs of existing crunch-run processes")
1651 enableMemoryLimit := flags.Bool("enable-memory-limit", true, "tell container runtime to limit container's memory usage")
1652 enableNetwork := flags.String("container-enable-networking", "default", "enable networking \"always\" (for all containers) or \"default\" (for containers that request it)")
1653 networkMode := flags.String("container-network-mode", "default", `Docker network mode for container (use any argument valid for docker --net)`)
1654 memprofile := flags.String("memprofile", "", "write memory profile to `file` after running container")
1655 runtimeEngine := flags.String("runtime-engine", "docker", "container runtime: docker or singularity")
1656 flags.Duration("check-containerd", 0, "Ignored. Exists for compatibility with older versions.")
1658 ignoreDetachFlag := false
1659 if len(args) > 0 && args[0] == "-no-detach" {
1660 // This process was invoked by a parent process, which
1661 // has passed along its own arguments, including
1662 // -detach, after the leading -no-detach flag. Strip
1663 // the leading -no-detach flag (it's not recognized by
1664 // flags.Parse()) and ignore the -detach flag that
1667 ignoreDetachFlag = true
1670 if err := flags.Parse(args); err == flag.ErrHelp {
1672 } else if err != nil {
1677 if *stdinEnv && !ignoreDetachFlag {
1678 // Load env vars on stdin if asked (but not in a
1679 // detached child process, in which case stdin is
1681 err := loadEnv(os.Stdin)
1688 containerUUID := flags.Arg(0)
1691 case *detach && !ignoreDetachFlag:
1692 return Detach(containerUUID, prog, args, os.Stdout, os.Stderr)
1694 return KillProcess(containerUUID, syscall.Signal(*kill), os.Stdout, os.Stderr)
1696 return ListProcesses(os.Stdout, os.Stderr)
1699 if containerUUID == "" {
1700 log.Printf("usage: %s [options] UUID", prog)
1704 log.Printf("crunch-run %s started", cmd.Version.String())
1707 if *caCertsPath != "" {
1708 arvadosclient.CertFiles = []string{*caCertsPath}
1711 api, err := arvadosclient.MakeArvadosClient()
1713 log.Printf("%s: %v", containerUUID, err)
1718 kc, kcerr := keepclient.MakeKeepClient(api)
1720 log.Printf("%s: %v", containerUUID, kcerr)
1723 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 2}
1726 cr, err := NewContainerRunner(arvados.NewClientFromEnv(), api, kc, containerUUID)
1732 switch *runtimeEngine {
1734 cr.executor, err = newDockerExecutor(containerUUID, cr.CrunchLog.Printf, cr.containerWatchdogInterval)
1736 cr.executor, err = newSingularityExecutor(cr.CrunchLog.Printf)
1738 cr.CrunchLog.Printf("%s: unsupported RuntimeEngine %q", containerUUID, *runtimeEngine)
1739 cr.CrunchLog.Close()
1743 cr.CrunchLog.Printf("%s: %v", containerUUID, err)
1744 cr.checkBrokenNode(err)
1745 cr.CrunchLog.Close()
1748 defer cr.executor.Close()
1750 gwAuthSecret := os.Getenv("GatewayAuthSecret")
1751 os.Unsetenv("GatewayAuthSecret")
1752 if gwAuthSecret == "" {
1753 // not safe to run a gateway service without an auth
1755 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAuthSecret was not provided by dispatcher)")
1756 } else if gwListen := os.Getenv("GatewayAddress"); gwListen == "" {
1757 // dispatcher did not tell us which external IP
1758 // address to advertise --> no gateway service
1759 cr.CrunchLog.Printf("Not starting a gateway server (GatewayAddress was not provided by dispatcher)")
1760 } else if de, ok := cr.executor.(*dockerExecutor); ok {
1761 cr.gateway = Gateway{
1763 AuthSecret: gwAuthSecret,
1764 ContainerUUID: containerUUID,
1765 DockerContainerID: &de.containerID,
1767 ContainerIPAddress: dockerContainerIPAddress(&de.containerID),
1769 err = cr.gateway.Start()
1771 log.Printf("error starting gateway server: %s", err)
1776 parentTemp, tmperr := cr.MkTempDir("", "crunch-run."+containerUUID+".")
1778 log.Printf("%s: %v", containerUUID, tmperr)
1782 cr.parentTemp = parentTemp
1783 cr.statInterval = *statInterval
1784 cr.cgroupRoot = *cgroupRoot
1785 cr.expectCgroupParent = *cgroupParent
1786 cr.enableMemoryLimit = *enableMemoryLimit
1787 cr.enableNetwork = *enableNetwork
1788 cr.networkMode = *networkMode
1789 if *cgroupParentSubsystem != "" {
1790 p := findCgroup(*cgroupParentSubsystem)
1791 cr.setCgroupParent = p
1792 cr.expectCgroupParent = p
1797 if *memprofile != "" {
1798 f, err := os.Create(*memprofile)
1800 log.Printf("could not create memory profile: %s", err)
1802 runtime.GC() // get up-to-date statistics
1803 if err := pprof.WriteHeapProfile(f); err != nil {
1804 log.Printf("could not write memory profile: %s", err)
1806 closeerr := f.Close()
1807 if closeerr != nil {
1808 log.Printf("closing memprofile file: %s", err)
1813 log.Printf("%s: %v", containerUUID, runerr)
1819 func loadEnv(rdr io.Reader) error {
1820 buf, err := ioutil.ReadAll(rdr)
1822 return fmt.Errorf("read stdin: %s", err)
1824 var env map[string]string
1825 err = json.Unmarshal(buf, &env)
1827 return fmt.Errorf("decode stdin: %s", err)
1829 for k, v := range env {
1830 err = os.Setenv(k, v)
1832 return fmt.Errorf("setenv(%q): %s", k, err)